text
stringlengths 8
6.88M
|
|---|
#include <chrono>
#include <cstring>
#include <iostream>
extern void calc(int, const int *, const int *, int *);
int main()
{
std::ios_base::sync_with_stdio(false);
int n;
std::cin >> n;
int *a = new int[n];
int *b = new int[n];
int *c = new int[n];
// Initialize the arrays
std::memset(c, 0, sizeof(int) * n);
for (int i = 0; i < n; ++i)
std::cin >> a[i] >> b[i];
// Start the calculation
auto start = std::chrono::high_resolution_clock::now();
calc(n, a, b, c);
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = stop - start;
std::clog << "Time elapsed: " << diff.count() << '\n';
// Print the result
for (int i = 0; i < n; i++)
std::cout << c[i] << '\n';
delete[] a;
delete[] b;
delete[] c;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node *next;
Node() : val(0), next(NULL){};
Node(int val) : val(val), next(NULL){};
};
Node *insert(vector<int> nums)
{
Node *head = new Node(nums[0]), *temp = head;
int i = 1;
while (temp && i < nums.size())
{
Node *node = new Node(nums[i++]);
temp->next = node;
temp = temp->next;
}
return head;
}
void print(const Node *head)
{
if(!head) return;
print(head->next);
cout << head->val << " ";
}
int kth_element(Node *head, int k)
{
if(!head) return 0;
int temp = kth_element(head->next, k)+1;
if(temp == k) cout << head->val << endl;
return temp;
}
int main()
{
Node* head = insert({1,2,3,4,5,6,7,8});
// print(head);
kth_element(head,3);
return 0;
}
|
//
// Calendar.cpp
// IMKSupply
//
// Created by KimSteve on 2017. 9. 7..
//
//
#include "Calendar.h"
Calendar::Calendar() : _gapX(0), _gapY(0), _year(0), _month(0), _listener(nullptr)
{
_gridCellList.clear();
}
Calendar::~Calendar()
{
_gridCellList.clear();
}
Calendar * Calendar::create(unsigned int year, unsigned int month, unsigned int day)
{
Calendar * calendar = new (std::nothrow)Calendar;
calendar->_year = year;
calendar->_month = month;
calendar->_day = day;
calendar->setAnchorPoint(cocos2d::Vec2::ZERO);
calendar->setContentSize(cocos2d::Size(CELL_SIZE*7, CELL_SIZE*5));
if ( calendar && calendar->init()) {
calendar->autorelease();
} else {
CC_SAFE_DELETE(calendar);
}
return calendar;
}
void Calendar::reset(unsigned int year, unsigned int month, unsigned int day)
{
for (int i=0; i<_gridCellList.size(); i++) {
CalendarDayCell * cell = _gridCellList[i];
cell->removeFromParent();
}
_gridCellList.clear();
_year = year;
_month = month;
_day = day;
makeCellbutton();
}
void Calendar::makeCellbutton()
{
if (_year==0 && _month==0) {
time_t now;
struct tm *fmt;
time(&now);
fmt = localtime(&now);
_year = fmt->tm_year + 1900;
_month = fmt->tm_mon;
}
struct tm *fmt = new tm;
fmt->tm_year = _year - 1900;
fmt->tm_mon = _month;
fmt->tm_mday = 1;
fmt->tm_hour = 1;
fmt->tm_min = 1;
fmt->tm_sec = 1;
mktime(fmt);
_firstDayOfTheWeekThisMonth = fmt->tm_wday;
delete fmt;
int daysInMonth = getMonthDays();
for (int i = 1; i <= daysInMonth; i ++)
{
CalendarDayCell * cell = CalendarDayCell::create(_year, _month, i);
cell->setAnchorPoint(cocos2d::Vec2::ZERO);
cell->setContentSize(cocos2d::Size(CELL_SIZE, CELL_SIZE));
cell->setCalendarDayCellListener(this);
cell->setToday(_day==i);
addGridCell(cell);
}
}
bool Calendar::init()
{
if (!SMView::init()) {
return false;
}
setBackgroundColor4F(cocos2d::Color4F(0, 1, 0, 0.6f));
_gapX = CELL_SIZE;
_gapY = CELL_SIZE;
makeCellbutton();
return true;
}
void Calendar::addGridCell(CalendarDayCell *cell)
{
// cell->retain();
cocos2d::Vec2 pos = cocos2d::Vec2::ZERO;
if (_gridCellList.size()<=0) {
// first cell
pos = cocos2d::Vec2(cell->getContentSize().width*_firstDayOfTheWeekThisMonth, getContentSize().height-(cell->getContentSize().height));
} else {
pos = getLastAvailableCellPosition();
}
cell->setPosition(pos);
_gridCellList.push_back(cell);
addChild(cell);
}
int Calendar::getColumnCount()
{
return 7;
}
int Calendar::getRowCount()
{
return 5;
}
cocos2d::Vec2 Calendar::getLastAvailableCellPosition()
{
if (_gridCellList.size()<=0) {
return cocos2d::Vec2::ZERO;
}
CalendarDayCell * lastCell = _gridCellList[_gridCellList.size()-1];
if (lastCell->getWeekDays()==6) {
return cocos2d::Vec2(0, lastCell->getPosition().y-lastCell->getContentSize().height);
} else {
return cocos2d::Vec2(lastCell->getPosition().x+lastCell->getContentSize().width, lastCell->getPosition().y);
}
}
int Calendar::getMonthDays()
{
switch (_month) {
case 0:
case 2:
case 4:
case 6:
case 7:
case 9:
case 11:
return 31;
break;
case 1:
{
// 2월
if ((_year % 4 == 0 && _year % 100 != 0)|| _year % 400 == 0)
{
return 29;
}
else
{
return 28;
}
break;
}
case 3:
case 5:
case 8:
case 10:
return 30;
break;
default:
return 0;
break;
}
}
void Calendar::onCalenderCellClick(int year, int month, int day)
{
if (_listener) {
_listener->onSelectDay(year, month, day);
}
}
|
//
// EchoServer.h
// NetTest
//
// Created by uistrong on 13-3-20.
// Copyright (c) 2013年 uistrong. All rights reserved.
//
#ifndef __NetTest__EchoServer__
#define __NetTest__EchoServer__
#include <vector>
class EchoServer{
public:
EchoServer();
~EchoServer();
int StartServer(unsigned short port);
void StopServer();
private:
static void* ListenThread(void *arg);
int ListenThreadEntity();
int ReadWriteThreadEntity();
int CreateSocket();
private:
bool _started;
int _acceptSocket;
unsigned short _listenPort;
std::vector<int> _clients;
};
#endif /* defined(__NetTest__EchoServer__) */
|
#include <iostream>
#include <fstream>
#include "LexTokenStream.hpp"
#include "JavaRecognizer.hpp"
#include "JavaTreeParser.hpp"
ANTLR_USING_NAMESPACE(std)
ANTLR_USING_NAMESPACE(antlr)
static void parseFile(const string& f);
static void doTreeAction(const string& f, RefAST t);
int main(int argc,char* argv[])
{
// Use a try/catch block for parser exceptions
try {
// if we have at least one command-line argument
if (argc > 1 ) {
cerr << "Parsing..." << endl;
// for each file specified on the command line
for(int i=1; i< argc;i++) {
cerr << " " << argv[i] << endl;
parseFile(argv[i]);
} }
else
cerr << "Usage: " << argv[0]
<< " <file name(s)>" << endl;
}
catch(exception& e) {
cerr << "exception: " << e.what() << endl;
// e.printStackTrace(System.err); // so we can get stack trace
}
}
// Here's where we do the real work...
static void parseFile(const string& f)
{
try {
// ifstream s(f.c_str());
FILE* fp=fopen(f.c_str(),"r");
// Create a scanner that reads from the input stream
LexTokenStream lexer(fp);
// Create a parser that reads from the scanner
JavaRecognizer parser(lexer);
// start parsing at the compilationUnit rule
parser.compilationUnit();
fclose(fp);
// do something with the tree
doTreeAction(f, parser.getAST());
}
catch (exception& e) {
cerr << "parser exception: " << e.what() << endl;
// e.printStackTrace(); // so we can get stack trace
}
}
static void doTreeAction(const string& f, RefAST t)
{
if ( t==nullAST ) return;
JavaTreeParser tparse;
try {
tparse.compilationUnit(t);
// System.out.println("successful walk of result AST for "+f);
}
catch (RecognitionException& e) {
cerr << e.getMessage() << endl;
// e.printStackTrace();
}
}
|
//
//
//
#include "HelloTest.h"
#include "LiquidCrystal.h"
#include "HIC.h"
#include "Mode.h"
extern LiquidCrystal lcd;
static void PrintHello ()
{
hic.print (F ("Hello\n"));
}
void HelloTest::Activate ()
{
lcd.clear ();
lcd.print (F ("Print Hello"));
Mode::Show ();
}
void HelloTest::Select ()
{
Mode::Next ();
}
void HelloTest::Execute ()
{
Mode::Execute (PrintHello);
}
|
#include<iostream>
#include<vector>
#include<stack>
#include<climits>
#define FOR(i,n) for(int i = 0; i < n; i++)
using namespace std;
int gMaxAreaOfHistogram(int xArray[], int n)
{
int lMaxArea = INT_MIN;
stack<int> lStack;
FOR(i, n)
{
if (lStack.empty())
{
lStack.push(i);
}
else
{
int lCurrTopIndex = lStack.top();
int lCurrTop = xArray[lCurrTopIndex];
if (lCurrTop <= xArray[i])
lStack.push(i);
else
{
while(!lStack.empty() && lCurrTop > xArray[i])
{
int lArea = 0;
lStack.pop();
if (lStack.empty())
{
lArea = i * lCurrTop;
}
else
{
lCurrTopIndex = lStack.top();
while(xArray[lCurrTopIndex] == lCurrTop && !lStack.empty())
{
lCurrTopIndex = lStack.top();
}
lArea = (i - lCurrTopIndex - 1) * lCurrTop;
lCurrTop = xArray[lCurrTopIndex];
}
lMaxArea = lArea > lMaxArea ? lArea : lMaxArea;
}
lStack.push(i);
}
}
}
while (!lStack.empty())
{
int lCurrTopIndex = lStack.top();
int lCurrTop = xArray[lCurrTopIndex];
lStack.pop();
int lArea = 0;
if (lStack.empty())
{
lArea = n*lCurrTop;
}
else
{
lArea = (n - lCurrTopIndex) * lCurrTop;
}
lMaxArea = lArea > lMaxArea ? lArea : lMaxArea;
}
return lMaxArea;
}
int main()
{
std::ios_base::sync_with_stdio(false);
int lTests;
cin>>lTests;
FOR(i, lTests)
{
int lSize;
cin>>lSize;
//vector<int> lVec(lSize, -1);
int lVec[lSize];
FOR(j, lSize)
cin>>lVec[j];
cout<<gMaxAreaOfHistogram(lVec, lSize)<<"\n";
}
}
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "generators/include/python_CEGUI.h"
#include "RenderTargetEventArgs.pypp.hpp"
namespace bp = boost::python;
struct RenderTargetEventArgs_wrapper : CEGUI::RenderTargetEventArgs, bp::wrapper< CEGUI::RenderTargetEventArgs > {
RenderTargetEventArgs_wrapper(CEGUI::RenderTargetEventArgs const & arg )
: CEGUI::RenderTargetEventArgs( arg )
, bp::wrapper< CEGUI::RenderTargetEventArgs >(){
// copy constructor
}
RenderTargetEventArgs_wrapper(::CEGUI::RenderTarget * target )
: CEGUI::RenderTargetEventArgs( boost::python::ptr(target) )
, bp::wrapper< CEGUI::RenderTargetEventArgs >(){
// constructor
}
static ::CEGUI::RenderTarget * get_target(CEGUI::RenderTargetEventArgs const & inst ){
return inst.target;
}
static void set_target( CEGUI::RenderTargetEventArgs & inst, ::CEGUI::RenderTarget * new_value ){
inst.target = new_value;
}
};
void register_RenderTargetEventArgs_class(){
{ //::CEGUI::RenderTargetEventArgs
typedef bp::class_< RenderTargetEventArgs_wrapper, bp::bases< CEGUI::EventArgs > > RenderTargetEventArgs_exposer_t;
RenderTargetEventArgs_exposer_t RenderTargetEventArgs_exposer = RenderTargetEventArgs_exposer_t( "RenderTargetEventArgs", "! EventArgs class passed to subscribers of RenderTarget events.\n", bp::init< CEGUI::RenderTarget * >(( bp::arg("target") )) );
bp::scope RenderTargetEventArgs_scope( RenderTargetEventArgs_exposer );
bp::implicitly_convertible< CEGUI::RenderTarget *, CEGUI::RenderTargetEventArgs >();
RenderTargetEventArgs_exposer.add_property( "target"
, bp::make_function( (::CEGUI::RenderTarget * (*)( ::CEGUI::RenderTargetEventArgs const & ))(&RenderTargetEventArgs_wrapper::get_target), bp::return_internal_reference< >() )
, bp::make_function( (void (*)( ::CEGUI::RenderTargetEventArgs &,::CEGUI::RenderTarget * ))(&RenderTargetEventArgs_wrapper::set_target), bp::with_custodian_and_ward_postcall< 1, 2 >() )
, "! pointer to the RenderTarget that triggered the event.\n" );
}
}
|
#include <bits/stdc++.h>
using namespace std;
int dp[20002];
int main()
{
int t;scanf("%d",&t);
while(t--)
{
int total,n;scanf("%d %d",&total,&n);
int ara[n+3];
for(int i=0;i<=20000;i++)dp[i]=100000000;
for(int i=1;i<=n;i++)scanf("%d",&ara[i]);
dp[0]=0;
for(int i=1;i<=n;i++)
{
for(int j=20000;j>=1;j--){
if(j>=ara[i])
dp[j]=min(dp[j],dp[j-ara[i]]+1);
}
}
int take;
for(int i=total;i<=20000;i++){
if(dp[i]!=100000000){
take=i;break;
}
}
printf("%d %d\n",take,dp[take]);
}
return 0;
}
|
// Clang includes
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Tooling/ArgumentsAdjusters.h"
#include <iostream>
#include <iomanip>
#include "clang/Rewrite/Frontend/Rewriters.h"
#include "clang/Rewrite/Core/RewriteBuffer.h"
#include "clang/Rewrite/Core/Rewriter.h"
/*
#include "function_definition_lister.h"
#include "llvm/Support/CommandLine.h"
/home/balaji/clang-llvm/llvm/include/llvm/Support/CommandLine.h
using namespace clang::tooling;
using namespace llvm;
using namespace clang::ast_matchers;
#include <home/balaji/mutation/airlib/b747cl_grt_rtw>
#include "home/balaji/mutation/airlib"
#include "usr/local/MATLAB/R2016a/extern/include"
#include "usr/local/MATLAB/R2016a/simulink/include"
#include "usr/local/MATLAB/R2016a/rtw/c/src"
#include "usr/local/MATLAB/R2016a/rtw/c/src/ext_mode/common"
#include "extern/include"
#include "simulink/include"
#include "src"
#include "src/ext_mode/common"
*/
// LLVM includes
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
// Standard includes
#include <memory>
#include <string>
#include <vector>
using namespace llvm;
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
static llvm::cl::OptionCategory flt_cat("func-decl-list-am options");
static llvm::cl::opt<bool> verbose_compiler(
"vc",
llvm::cl::desc("pass -v to compiler instance (default false)"),
llvm::cl::cat(flt_cat),
llvm::cl::init(false)
);
namespace Mutator {
/// Callback class for clang-variable matches.
class MatchHandler : public clang::ast_matchers::MatchFinder::MatchCallback {
public:
using MatchResult = clang::ast_matchers::MatchFinder::MatchResult;
/// Handles the matched variable.
///
/// Checks if the name of the matched variable is either empty or prefixed
/// with `clang_` else emits a diagnostic and FixItHint.
void run(const MatchResult& Result) {
clang::SourceManager &srcMgr = Result.Context->getSourceManager();
if(const clang::VarDecl* var = Result.Nodes.getNodeAs<clang::VarDecl>("clang")) {
if(var->isFunctionOrMethodVarDecl()) {
std::cout << std::setw(20) << std::left << "Local Variable: " << var->getName().str() << "\t\t";
std::cout << ((clang::CXXMethodDecl*)(var->getParentFunctionOrMethod()))->getQualifiedNameAsString() << "\t";
std::cout << "--" << srcMgr.getFilename(var->getLocation()).str();
std::cout << "\n";
}
if(var->hasExternalStorage()) {
std::cout << std::setw(20) << std::left << "External Variable: " << var->getName().str() << "\t\t";
std::cout << "--" << srcMgr.getFilename(var->getLocation()).str();
std::cout << "\n";
}
else if(var->hasGlobalStorage()) {
std::cout << std::setw(20) << std::left << "Global Variable: " << var->getName().str() << "\t\t";
std::cout << "--" << srcMgr.getFilename(var->getLocation()).str();
std::cout << "\n";
}
}
const clang::VarDecl* Variable =
Result.Nodes.getNodeAs<clang::VarDecl>("clang");
//clang::SourceManager &srcMgr = Result.Context->getSourceManager();
clang::SourceRange loc = Variable->getSourceRange();
clang::PresumedLoc locStart = srcMgr.getPresumedLoc(loc.getBegin());
clang::PresumedLoc locEnd = srcMgr.getPresumedLoc(loc.getEnd());
//std::string r = "hihi";
std::cout << "\n\n *** Start print *** \n\n" << std::endl;
std::cout << Variable->getName().str() << std::endl;
//std::cout << loc.str() << std::endl;
std::cout << locStart.getLine() << std::endl;
std::cout << locStart.getColumn() << std::endl;
std::cout << locEnd.getLine() << std::endl;
std::cout << locEnd.getColumn() << std::endl;
/// The `Rewriter` used to insert the `override` keyword.
clang::Rewriter rewriter;
rewriter.setSourceMgr(Result.Context->getSourceManager(),Result.Context->getLangOpts());
//rewriter.InsertText(loc.getBegin(),"float_Balaji", true, true); //not working
//rewriter.ReplaceText(loc, "float_Balaji");
rewriter.ReplaceText(loc.getBegin(),5,"real_Tmutated");
// Now emit the rewritten buffer.
// Rewriter.getEditBuffer(SM.getMainFileID()).write(llvm::outs()); --> this will output to screen as what you got.
std::error_code error_code;
llvm::raw_fd_ostream outFile("output.txt", error_code, llvm::sys::fs::F_None);
rewriter.getEditBuffer(rewriter.getSourceMgr().getMainFileID()).write(outFile); // --> this will write the result to outFile
outFile.close();
//errs() << "\n Found " << "";
//rewriter.getEditBuffer(rewriter.getSourceMgr().getMainFileID()).write(errs());
//rewriter.ReplaceText(loc, "float_Balaji");
//rewriter.ReplaceText(sloc,5,"float_Balaji");
//std::cout << Variable->getLocation().str() << std::endl;
std::cout << "\n\n *** End print *** \n\n" << std::endl;
//printf("%s\n",r.c_str());
const llvm::StringRef Name = Variable->getName();
if (Name.empty() || Name.startswith("clang_")) return;
clang::DiagnosticsEngine& Engine = Result.Context->getDiagnostics();
const unsigned ID =
Engine.getCustomDiagID(clang::DiagnosticsEngine::Warning,
"found mutating variable");
/// Hint to the user to prefix the variable with 'clang_'.
const clang::FixItHint FixIt =
clang::FixItHint::CreateInsertion(Variable->getLocation(), "precision & accuracy mutation");
Engine.Report(Variable->getLocation(), ID).AddFixItHint(FixIt);
}
}; // namespace Mutator
/// Dispatches the ASTMatcher.
class Consumer : public clang::ASTConsumer {
public:
/// Creates the matcher for clang variables and dispatches it on the TU.
void HandleTranslationUnit(clang::ASTContext& Context) override {
using namespace clang::ast_matchers; // NOLINT(build/namespaces)
const auto Matcher = declaratorDecl(
isExpansionInMainFile(),
hasType(asString("int_T"))
).bind("clang");
/*
// clang-format off
const auto Matcher = varDecl(
isExpansionInMainFile(),
hasType(isConstQualified()), // const
hasInitializer(
hasType(cxxRecordDecl(
isLambda(), // lambda
has(functionTemplateDecl( // auto
has(cxxMethodDecl(
isNoThrow(), // noexcept
hasBody(compoundStmt(hasDescendant(gotoStmt()))) // goto
)))))))).bind("clang");
// clang-format on
*/
MatchHandler Handler;
MatchFinder MatchFinder;
MatchFinder.addMatcher(Matcher, &Handler);
MatchFinder.matchAST(Context);
}
};
/// Creates an `ASTConsumer` and logs begin and end of file processing.
class Action : public clang::ASTFrontendAction {
public:
using ASTConsumerPointer = std::unique_ptr<clang::ASTConsumer>;
ASTConsumerPointer CreateASTConsumer(clang::CompilerInstance& Compiler,
llvm::StringRef) override {
return std::make_unique<Consumer>();
}
bool BeginSourceFileAction(clang::CompilerInstance& Compiler,
llvm::StringRef Filename) override {
llvm::errs() << "Processing " << Filename << "\n\n";
return true;
}
void EndSourceFileAction() override {
if (!RewriteOption) return;
const auto File = Rewriter.getSourceMgr().getMainFileID();
Rewriter.getEditBuffer(File).write(llvm::outs());
llvm::errs() << "\nFinished processing file ...\n";
}
private:
/// Whether to rewrite the source code. Forwarded to the `Consumer`.
bool RewriteOption;
/// A `clang::Rewriter` to rewrite source code. Forwarded to the `Consumer`.
clang::Rewriter Rewriter;
};
} // namespace Mutator
namespace {
llvm::cl::OptionCategory ToolCategory("clang-variables options");
llvm::cl::extrahelp MoreHelp(R"(
Finds all Const Lambdas, that take an Auto parameter, are declared Noexcept
and have a Goto statement inside, e.g.:
const auto lambda = [] (auto) noexcept {
bool done = true;
flip: done = !done;
if (!done) goto flip;
}
)");
llvm::cl::extrahelp
CommonHelp(clang::tooling::CommonOptionsParser::HelpMessage);
} // namespace
auto main(int argc, const char* argv[]) -> int {
using namespace clang::tooling;
CommonOptionsParser OptionsParser(argc, argv, ToolCategory);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
//MATLAB_ROOT := /usr/local/MATLAB/R2016a
//START_DIR := /home/balaji/clang-llvm/cppdocker/code/mutator
//#-c -ansi -pedantic -Wno-long-long -fwrapv -fPIC -O0 -DMAT_FILE=1 -DINTEGER_CODE=0 -DMT=0 -DCLASSIC_INTERFACE=1 -DALLOCATIONFCN=0 -DONESTEPFCN=0 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DTID01EQ=1 -DMODEL=b747cl -DNUMST=2 -DNCSTATES=0 -DHAVESTDIO -DRT -DUSE_RTMODEL -DUNIX -I$(START_DIR)/b747cl_grt_rtw -I$(START_DIR) -I$(MATLAB_ROOT)/extern/include -I$(MATLAB_ROOT)/simulink/include -I$(MATLAB_ROOT)/rtw/c/src -I$(MATLAB_ROOT)/rtw/c/src/ext_mode/common -Iextern/include -Isimulink/include -Isrc -Isrc/ext_mode/common
// add header search paths to compiler
std::string clang_inc_dir1("-c");
std::string clang_inc_dir2("-ansi");
std::string clang_inc_dir3("-pedantic");
std::string clang_inc_dir4("-Wno-long-long");
std::string clang_inc_dir5("-Wgnu-include-next");
std::string clang_inc_dir6("-fwrapv");
std::string clang_inc_dir7("-fPIC");
std::string clang_inc_dir8("-O0");
std::string clang_inc_dir9("-DMAT_FILE=1");
std::string clang_inc_dir10("-DINTEGER_CODE=0");
std::string clang_inc_dir11("-DMT=0");
std::string clang_inc_dir12("-DCLASSIC_INTERFACE=1");
std::string clang_inc_dir13("-DALLOCATIONFCN=0");
std::string clang_inc_dir14("-DONESTEPFCN=0");
std::string clang_inc_dir15("-DTERMFCN=1");
std::string clang_inc_dir16("-DMULTI_INSTANCE_CODE=0");
std::string clang_inc_dir17("-DTID01EQ=1");
std::string clang_inc_dir18("-DMODEL=b747cl");
std::string clang_inc_dir19("-DNUMST=2");
std::string clang_inc_dir20("-DNCSTATES=0");
std::string clang_inc_dir21("-DHAVESTDIO");
std::string clang_inc_dir22("-DRT");
std::string clang_inc_dir23("-DUSE_RTMODEL");
std::string clang_inc_dir24("-DUNIX");
std::string clang_inc_dir25("-I/usr/lib/clang/3.8.0/include");
std::string clang_inc_dir26("-I/home/balaji/clang-llvm/cppdocker/code/mutator");
std::string clang_inc_dir27("-I/home/balaji/clang-llvm/cppdocker/code");
std::string clang_inc_dir28("-I/usr/local/MATLAB/R2016a/extern/include");
std::string clang_inc_dir29("-I/usr/local/MATLAB/R2016a/simulink/include");
std::string clang_inc_dir30("-I/usr/local/MATLAB/R2016a/rtw/c/src");
std::string clang_inc_dir31("-I/usr/local/MATLAB/R2016a/rtw/c/src/ext_mode/common");
//-I$(START_DIR)/b747cl_grt_rtw -I$(START_DIR) -I$(MATLAB_ROOT)/extern/include -I$(MATLAB_ROOT)/simulink/include -I$(MATLAB_ROOT)/rtw/c/src -I$(MATLAB_ROOT)/rtw/c/src/ext_mode/common
//std::string clang_inc_dir1("-I/src/ext_mode/common"); //clang_inc_dir1="-I/path1/to/headers"
//std::string clang_inc_dir2("-I/simulink/include");
//std::string clang_inc_dir3("-I/extern/include");
ArgumentsAdjuster ardj1 = getInsertArgumentAdjuster(clang_inc_dir1.c_str());
ArgumentsAdjuster ardj2 = getInsertArgumentAdjuster(clang_inc_dir2.c_str());
ArgumentsAdjuster ardj3 = getInsertArgumentAdjuster(clang_inc_dir3.c_str());
ArgumentsAdjuster ardj4 = getInsertArgumentAdjuster(clang_inc_dir4.c_str());
ArgumentsAdjuster ardj5 = getInsertArgumentAdjuster(clang_inc_dir5.c_str());
ArgumentsAdjuster ardj6 = getInsertArgumentAdjuster(clang_inc_dir6.c_str());
ArgumentsAdjuster ardj7 = getInsertArgumentAdjuster(clang_inc_dir7.c_str());
ArgumentsAdjuster ardj8 = getInsertArgumentAdjuster(clang_inc_dir8.c_str());
ArgumentsAdjuster ardj9 = getInsertArgumentAdjuster(clang_inc_dir9.c_str());
ArgumentsAdjuster ardj10 = getInsertArgumentAdjuster(clang_inc_dir10.c_str());
ArgumentsAdjuster ardj11 = getInsertArgumentAdjuster(clang_inc_dir11.c_str());
ArgumentsAdjuster ardj12 = getInsertArgumentAdjuster(clang_inc_dir12.c_str());
ArgumentsAdjuster ardj13 = getInsertArgumentAdjuster(clang_inc_dir13.c_str());
ArgumentsAdjuster ardj14 = getInsertArgumentAdjuster(clang_inc_dir14.c_str());
ArgumentsAdjuster ardj15 = getInsertArgumentAdjuster(clang_inc_dir15.c_str());
ArgumentsAdjuster ardj16 = getInsertArgumentAdjuster(clang_inc_dir16.c_str());
ArgumentsAdjuster ardj17 = getInsertArgumentAdjuster(clang_inc_dir17.c_str());
ArgumentsAdjuster ardj18 = getInsertArgumentAdjuster(clang_inc_dir18.c_str());
ArgumentsAdjuster ardj19 = getInsertArgumentAdjuster(clang_inc_dir19.c_str());
ArgumentsAdjuster ardj20 = getInsertArgumentAdjuster(clang_inc_dir20.c_str());
ArgumentsAdjuster ardj21 = getInsertArgumentAdjuster(clang_inc_dir21.c_str());
ArgumentsAdjuster ardj22 = getInsertArgumentAdjuster(clang_inc_dir22.c_str());
ArgumentsAdjuster ardj23 = getInsertArgumentAdjuster(clang_inc_dir23.c_str());
ArgumentsAdjuster ardj24 = getInsertArgumentAdjuster(clang_inc_dir24.c_str());
ArgumentsAdjuster ardj25 = getInsertArgumentAdjuster(clang_inc_dir25.c_str());
ArgumentsAdjuster ardj26 = getInsertArgumentAdjuster(clang_inc_dir26.c_str());
ArgumentsAdjuster ardj27 = getInsertArgumentAdjuster(clang_inc_dir27.c_str());
ArgumentsAdjuster ardj28 = getInsertArgumentAdjuster(clang_inc_dir28.c_str());
ArgumentsAdjuster ardj29 = getInsertArgumentAdjuster(clang_inc_dir29.c_str());
ArgumentsAdjuster ardj30 = getInsertArgumentAdjuster(clang_inc_dir30.c_str());
ArgumentsAdjuster ardj31 = getInsertArgumentAdjuster(clang_inc_dir31.c_str());
Tool.appendArgumentsAdjuster(ardj1);
Tool.appendArgumentsAdjuster(ardj2);
Tool.appendArgumentsAdjuster(ardj3);
Tool.appendArgumentsAdjuster(ardj4);
Tool.appendArgumentsAdjuster(ardj5);
Tool.appendArgumentsAdjuster(ardj6);
Tool.appendArgumentsAdjuster(ardj7);
Tool.appendArgumentsAdjuster(ardj8);
Tool.appendArgumentsAdjuster(ardj9);
Tool.appendArgumentsAdjuster(ardj10);
Tool.appendArgumentsAdjuster(ardj11);
Tool.appendArgumentsAdjuster(ardj12);
Tool.appendArgumentsAdjuster(ardj13);
Tool.appendArgumentsAdjuster(ardj14);
Tool.appendArgumentsAdjuster(ardj15);
Tool.appendArgumentsAdjuster(ardj16);
Tool.appendArgumentsAdjuster(ardj17);
Tool.appendArgumentsAdjuster(ardj18);
Tool.appendArgumentsAdjuster(ardj19);
Tool.appendArgumentsAdjuster(ardj20);
Tool.appendArgumentsAdjuster(ardj21);
Tool.appendArgumentsAdjuster(ardj22);
Tool.appendArgumentsAdjuster(ardj23);
Tool.appendArgumentsAdjuster(ardj24);
Tool.appendArgumentsAdjuster(ardj25);
Tool.appendArgumentsAdjuster(ardj26);
Tool.appendArgumentsAdjuster(ardj27);
Tool.appendArgumentsAdjuster(ardj28);
Tool.appendArgumentsAdjuster(ardj29);
Tool.appendArgumentsAdjuster(ardj30);
Tool.appendArgumentsAdjuster(ardj31);
if(verbose_compiler){
ArgumentsAdjuster ardj32 = getInsertArgumentAdjuster("-v");
Tool.appendArgumentsAdjuster(ardj32);
}
const auto Action = newFrontendActionFactory<Mutator::Action>();
return Tool.run(Action.get());
}
|
#include<stdio.h>
#include<stdlib.h>
typedef char TElemType;
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
/****************************************************/
bool InitTree(BiTree *T)
{
*T = NULL;
}
void DestoryTree(BiTree *T)
{
if(*T==NULL)
return;
else
{
DestoryTree(&((*T)->lchild));
DestoryTree(&((*T)->rchild));
free(*T);
*T=NULL;
}
}
void PreVisit(BiTree T)
{
if(T!=NULL)
{
PreVisit(T->lchild);
printf("%d",&T->data);
PreVisit(T->rchild);
}
}
void InVisit(BiTree T)
{
if(T!=NULL)
{
printf("%d",&T->data);
PreVisit(T->lchild);
PreVisit(T->rchild);
}
}
void PostVisit(BiTree T)
{
if(T!=NULL)
{
PreVisit(T->lchild);
PreVisit(T->rchild);
printf("%d",&T->data);
}
}
/*统计树的深度*/
int Length(BiTree T)
{
int deep;
int leftdeep,rightdeep;
if(T!=NULL)
{
Length(T->lchild);
Length(T->rchild);
deep = leftdeep>rightdeep?leftdeep:rightdeep;
}
return deep;
}
int count = 0;
/*统计叶子节点的个数*/
void Count(BiTree T)
{
if(T!=NULL)
{
if((!T->lchild)&&(!T->rchild))
count++;
Count(T->lchild);
Count(T->rchild);
}
}
/*统计所有的结点*/
int CountNode(BiTree T)
{
if(T!=NULL)
{
return 1+CountNode(T->lchild)+CountNode(T->rchild);
}
return 0;
}
|
#include <algorithm>
#include "ControlPoint.h"
ControlPoint::ControlPoint(unsigned long workers) : workers(workers) {}
unsigned long clamp(unsigned long x, unsigned long min, unsigned long max) {
if (x < min) x = min;
if (x > max) x = max;
return x;
}
void ControlPoint::occupyWorker() {
busyWorkers = clamp(busyWorkers + 1, 0, workers);
}
void ControlPoint::releaseWorker() {
busyWorkers = clamp(busyWorkers - 1, 0, workers);
}
bool ControlPoint::isBusy() const {
return busyWorkers == workers;
}
std::ostream& operator<<(std::ostream& os, const ControlPoint& point) {
os << "busyWorkers: " << point.busyWorkers << " workers: " << point.workers;
return os;
}
|
// github.com/andy489
/// Counting inversions using merge sort
#include <iostream>
using namespace std;
size_t mergeSort(size_t *arr, size_t *temp, int left, int right);
size_t merge(size_t *arr, size_t *temp, int left, int mid, int right);
/* sorts the array and returns count of inversions */
size_t mergeSort(size_t *arr, size_t array_size) {
size_t *temp = new size_t[array_size];
size_t inversions = mergeSort(arr, temp, 0, array_size - 1);
delete[] temp;
return inversions;
}
size_t mergeSort(size_t *arr, size_t *temp, int left, int right) {
int mid, invCount(0);
if (right > left) {
mid = (right + left) / 2;
/* Inversion count will be sum of inversions in left part,
right part and number of inversions in merging */
invCount = mergeSort(arr, temp, left, mid);
invCount += mergeSort(arr, temp, mid + 1, right);
// merging the two parts
invCount += merge(arr, temp, left, mid + 1, right);
}
return invCount;
}
// Merges two sorted arrays and returning inversion count in the arrays
size_t merge(size_t *arr, size_t *temp, int left, int mid, int right) {
int i, j, k;
size_t invCount(0);
i = left; // i is index for left subarray
j = mid; // j is index for right subarray
k = left; // k is index for resultant merged subarray
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) temp[k++] = arr[i++];
else {
temp[k++] = arr[j++];
invCount = invCount + (mid - i);
}
}
// copy remaining elements
while (i <= mid - 1) temp[k++] = arr[i++];
while (j <= right) temp[k++] = arr[j++];
// copy back the merged elements to original array
for (i = left; i <= right; ++i) arr[i] = temp[i];
return invCount;
}
int main() {
int Q;
cin >> Q;
while (Q--) {
size_t n;
cin >> n;
size_t *soldiers = new size_t[n];
for (size_t i = 0; i < n; ++i)
cin >> soldiers[i];
cout << mergeSort(soldiers, n) << '\n';
delete[] soldiers;
}
return 0;
}
|
#include <vector>
#include <iostream>
using namespace std;
class FriendScore
{
public:
int highestScore(vector<string> friends) {
int N = friends.size();
int ans = 0;
for (int i = 0; i < N; i++) {
int match = 0;
for (int j = 0; j < N; j++) {
if (i == j) continue;
if (friends[i][j] == 'Y') {
match++;
} else {
for (int k = 0; k < N; k++) {
if (friends[j][k] == 'Y' && friends[i][k] == 'Y') {
match++;
break;
}
}
}
}
ans = max(ans, match);
}
return ans;
}
};
int main(int argc, char *argv[]) {
vector<string> friends(5);
friends[0] = "NYNNN";
friends[1] = "YNYNN";
friends[2] = "NYNYN";
friends[3] = "NNYNY";
friends[4] = "NNNYN";
FriendScore *friendScore = new FriendScore();
int ans = friendScore->highestScore(friends);
cout << ans << endl;
}
|
#ifndef PIECE_H_
#define PIECE_H_
class piece {
private:
bool is_white;
char shape;
int x_coord;
int y_coord;
public:
virtual piece(void){}
virtual ~piece(void){}
virtual void move(void) = 0;
virtual void set_color(void) = 0;
};
#endif
|
#ifndef CSOLIDSPHERE_H
#define CSOLIDSPHERE_H
#include "../header/Angel.h"
#include "CShape.h"
typedef Angel::vec4 color4;
typedef Angel::vec4 point4;
#define SOLIDCUBE_NUM 36 // 6 faces, 2 triangles/face , 3 vertices/triangle
class CSolidSphere : public CShape
{
private:
GLfloat m_fRadius;
GLint m_iSlices, m_iStacks;
vec4 m_Points[SOLIDCUBE_NUM];
vec3 m_Normals[SOLIDCUBE_NUM];
vec4 m_vertices[8];
int m_iIndex;
public:
CSolidSphere(const GLfloat fRadius=1.0f, const int iSlices=12,const int iStacks = 6);
~CSolidSphere();
void Update(float dt, point4 vLightPos, color4 vLightI);
void Update(float dt, const LightSource &Lights, const LightSource &Lights2);
void Update(float dt, const LightSource &Lights);
void Update(float dt); // 不計算光源的照明
// Sphere 的繪製方始使用多組的 GL_TRIANGLE_STRIP 來繪製, 因此沒有辦法提供 Flat Shading,
// 只有以 vertex 為基礎的計算顏色的 Ground Shading
void RenderWithFlatShading(point4 vLightPos, color4 vLightI);
void RenderWithGouraudShading(point4 vLightPos, color4 vLightI);
void RenderWithFlatShading(const LightSource &Lights);
void RenderWithGouraudShading(const LightSource &Lights);
void Draw();
void DrawW(); // 呼叫不再次設定 Shader 的描繪方式
};
#endif
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "BallBoy.h"
#include "PlasmaBarrel.h"
#include "CoreMinimal.h"
#include "UObject/Class.h"
#include "GameFramework/Controller.h"
#include "GameFramework/GameMode.h"
#include "BBGameMode.generated.h"
/**
*
*/
UCLASS()
class BALLBRAWL_API ABBGameMode : public AGameMode
{
GENERATED_BODY()
public:
ABBGameMode(const FObjectInitializer& ObjectInitializer);
virtual void PostLogin(APlayerController* NewPlayer) override;
UClass* GetDefaultPawnClassForController_Implementation(AController* InController) override;
virtual void BeginPlay() override;
int GetHealthPerTeam() const;
private:
void SpawnBalls();
public:
static const int BACKGROUND_RADIUS = 242;
private:
UPROPERTY(EditAnywhere)
int HealthPerTeam;
private:
//UPROPERTY(EditDefaultsOnly)
int PlayersSpawned;
TArray<ABrawlBall*> SceneBrawlBalls;
TArray<ABallBoy*> SceneBallBoys;
TArray<APlasmaBarrel*> ScenePlasmaBarrels;
};
|
#ifndef _HS_SFM_SFM_PIPELINE_SCENE_EXPANDOR_HPP_
#define _HS_SFM_SFM_PIPELINE_SCENE_EXPANDOR_HPP_
#include <vector>
#include <map>
#include "hs_progress/progress_utility/progress_manager.hpp"
#include "hs_sfm/sfm_utility/key_type.hpp"
#include "hs_sfm/sfm_utility/camera_type.hpp"
#include "hs_sfm/sfm_utility/match_type.hpp"
#include "hs_sfm/sfm_pipeline/image_expandor.hpp"
#include "hs_sfm/sfm_pipeline/point_expandor.hpp"
#include "hs_sfm/sfm_pipeline/bundle_adjustment_optimizor.hpp"
namespace hs
{
namespace sfm
{
namespace pipeline
{
template <typename _Scalar>
class SceneExpandor
{
public:
typedef _Scalar Scalar;
typedef int Err;
typedef CameraExtrinsicParams<Scalar> ExtrinsicParams;
typedef CameraIntrinsicParams<Scalar> IntrinsicParams;
typedef EIGEN_STD_VECTOR(ExtrinsicParams) ExtrinsicParamsContainer;
typedef EIGEN_STD_VECTOR(IntrinsicParams) IntrinsicParamsContainer;
typedef ImageKeys<Scalar> ImageKeyset;
typedef EIGEN_STD_VECTOR(ImageKeyset) ImageKeysetContainer;
typedef EIGEN_VECTOR(Scalar, 3) Point;
typedef EIGEN_STD_VECTOR(Point) PointContainer;
typedef ObjectIndexMap TrackPointMap;
typedef ObjectIndexMap ImageIntrinsicMap;
typedef ObjectIndexMap ImageExtrinsicMap;
protected:
typedef hs::sfm::pipeline::ImageExpandor<Scalar> ImageExpandor;
typedef typename ImageExpandor::ImageViewTracks ImageViewTracks;
typedef typename ImageExpandor::ImageViewTracksContainer
ImageViewTracksContainer;
typedef hs::sfm::pipeline::PointExpandor<Scalar> PointExpandor;
typedef hs::sfm::pipeline::BundleAdjustmentOptimizor<Scalar>
BundleAdjustmentOptimizor;
public:
SceneExpandor(
size_t add_new_image_matches_threshold = 8,
Scalar pmatrix_ransac_threshold = 4.0,
size_t min_triangulate_views = 2,
Scalar triangulate_error_threshold = 4.0,
size_t number_of_threads = 1)
: image_expandor_(add_new_image_matches_threshold,
pmatrix_ransac_threshold),
min_triangulate_views_(min_triangulate_views),
triangulate_error_threshold_(triangulate_error_threshold),
number_of_threads_(number_of_threads) {}
Err operator() (const ImageKeysetContainer& image_keysets,
const ImageIntrinsicMap& image_intrinsic_map,
const TrackContainer& tracks,
IntrinsicParamsContainer& intrinsic_params_set,
ExtrinsicParamsContainer& extrinsic_params_set,
ImageExtrinsicMap& image_extrinsic_map,
PointContainer& points,
TrackPointMap& track_point_map,
ViewInfoIndexer& view_info_indexer,
hs::progress::ProgressManager* progress_manager = NULL
) const
{
return Run(image_keysets,
image_intrinsic_map,
tracks,
intrinsic_params_set,
extrinsic_params_set,
image_extrinsic_map,
points,
track_point_map,
view_info_indexer,
progress_manager
);
}
Err Run(const ImageKeysetContainer& image_keysets,
const ImageIntrinsicMap& image_intrinsic_map,
const TrackContainer& tracks,
IntrinsicParamsContainer& intrinsic_params_set,
ExtrinsicParamsContainer& extrinsic_params_set,
ImageExtrinsicMap& image_extrinsic_map,
PointContainer& points,
TrackPointMap& track_point_map,
ViewInfoIndexer& view_info_indexer,
hs::progress::ProgressManager* progress_manager = NULL
) const
{
size_t number_of_images = image_keysets.size();
if (image_intrinsic_map.Size() != number_of_images) return -1;
ImageViewTracksContainer image_view_tracks_set;
if (Initialize(number_of_images,
tracks,
image_view_tracks_set,
view_info_indexer) != 0)
{
return -1;
}
while (1)
{
if (progress_manager) //若指定了ProgressManager
{
if (!progress_manager->CheckKeepWorking())
{
break;
}
}
BundleAdjustmentOptimizor bundle_adjustment_optimizor(
number_of_threads_); //光束法平差校准
if (bundle_adjustment_optimizor(image_keysets,
image_intrinsic_map,
tracks,
image_extrinsic_map,
track_point_map,
view_info_indexer,
intrinsic_params_set,
extrinsic_params_set,
points) != 0)
{
break;
}
ExtrinsicParamsContainer new_extrinsic_params_set;
std::vector<size_t> new_image_ids;
if (image_expandor_(image_keysets,
intrinsic_params_set,
image_intrinsic_map,
points,
track_point_map,
image_view_tracks_set,
image_extrinsic_map,
view_info_indexer,
new_extrinsic_params_set,
new_image_ids) != 0) //调用ImageExpandor处理新照片的加入, 若无新照片则跳出
{
break;
}
for (size_t i = 0; i < new_extrinsic_params_set.size(); i++)
{
extrinsic_params_set.push_back(new_extrinsic_params_set[i]);
image_extrinsic_map[new_image_ids[i]] = extrinsic_params_set.size() - 1;
}
//if (bundle_adjustment_optimizor(image_keysets,
// image_intrinsic_map,
// tracks,
// image_extrinsic_map,
// track_point_map,
// view_info_indexer,
// intrinsic_params_set,
// extrinsic_params_set,
// points) != 0)
//{
// break;
//}
PointExpandor point_expandor; //处理空间三维点的加入, 类似ImageExpandor
if (point_expandor(image_keysets,
intrinsic_params_set,
image_intrinsic_map,
tracks,
extrinsic_params_set,
image_extrinsic_map,
min_triangulate_views_,
triangulate_error_threshold_,
points,
track_point_map,
view_info_indexer) != 0)
{
break;
}
if (progress_manager)
{
progress_manager->SetCurrentSubProgressCompleteRatio(
float(extrinsic_params_set.size() / float(image_keysets.size())));
}
}
return 0;
}
protected:
Err Initialize(size_t number_of_images,
const TrackContainer& tracks,
ImageViewTracksContainer& image_view_tracks_set, //这个container是ImageViewTracks的向量, 而ImageViewTracks是vector<size_t>
ViewInfoIndexer& view_info_indexer) const
{
//计算每张影像拍到的track
image_view_tracks_set.resize(number_of_images);
size_t number_of_tracks = tracks.size();
for (size_t i = 0; i < number_of_tracks; i++)
{
size_t number_of_views = tracks[i].size(); //获取每个track的size
for (size_t j = 0; j < number_of_views; j++)
{
image_view_tracks_set[tracks[i][j].first].push_back(i);
}
}
return 0;
}
protected:
ImageExpandor image_expandor_;
size_t min_triangulate_views_;
Scalar triangulate_error_threshold_;
size_t number_of_threads_;
};
}
}
}
#endif
|
/*
Copyright (C) 2011 by Ladislav Hrabcak
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 __ASYNC_VBO_TRANSFERS_APP_SCENARIO2_H__
#define __ASYNC_VBO_TRANSFERS_APP_SCENARIO2_H__
#include "base/app.h"
#include "base/thread.h"
#include <memory>
#include <assert.h>
#include <glm/glm.hpp>
class renderer;
class app_scenario3
: public base::app
{
protected:
std::auto_ptr<scene> _scene;
std::auto_ptr<renderer> _renderer;
public:
app_scenario3();
virtual ~app_scenario3();
virtual const char* get_app_name() const { return "scenario 3"; }
virtual void start(const bool);
virtual void renderer_side_start();
virtual void stop();
virtual void draw_frame();
private:
app_scenario3(const app_scenario3&);
void operator =(const app_scenario3&);
};
#endif // __ASYNC_VBO_TRANSFERS_APP_SCENARIO2_H__
|
#include <iostream>
#include <string>
#define MAX 1000
using namespace std;
struct Person
{
string m_Name;
int m_Sex; //1 male 2 female
int m_Age;
string m_Phone;
string m_Addr;
};
struct Addressbooks
{
// array to put contacts
struct Person personArray[MAX];
// number of contacts now
int m_Size;
};
// add infomation of the perosn
void addInfo(Addressbooks *abs, int n)
{
//add name
string name;
cout << "Please input the name: " <<endl;
cin>> name;
abs->personArray[n].m_Name = name;
// add sex
cout << "Please input the sex: " <<endl;
cout <<"1 -- male" << endl;
cout <<"2 -- female" << endl;
int sex = 0;
while(1){
cin >> sex;
if(sex == 1 || sex == 2)
{
abs->personArray[n].m_Sex = sex;
break;
}
cout << "Please input sex again, 1--male; 2--female " <<endl;
}
// add age
cout << "Please input the age: " << endl;
int age = 0;
cin >> age;
abs->personArray[abs->m_Size].m_Age = age;
//add phone number
cout << "Please input the phone mumber: " << endl;
string phone;
cin >> phone;
abs->personArray[abs->m_Size].m_Phone = phone;
// add address
cout << "Please input the addree: " << endl;
string address;
cin >> address;
abs->personArray[abs->m_Size].m_Addr = address;
}
// add contacts
void addPerson(Addressbooks *abs)
{
if(abs->m_Size == MAX)
{
cout << " Addressbook is full,you can add any more" <<endl;
return;
}
else
{
addInfo(abs, abs->m_Size);
}
//update the number of contacts
abs->m_Size++;
cout << " add contact successfully"<< endl;
system("pause"); // press any key to continue
system("cls"); // claer the screen
}
// display contacts
void showPerson(Addressbooks *abs)
{
if(abs->m_Size == 0)
{
cout << "The contacts are empty" <<endl;
}
else
{
for(int i = 0; i < abs->m_Size ;i++ )
{
cout << " Name: " <<abs->personArray[i].m_Name <<"\t"
" Age: " <<abs->personArray[i].m_Age <<"\t"
" Sex: " <<(abs->personArray[i].m_Sex == 1 ? "male" : "female") <<"\t"
" Phone: " <<abs->personArray[i].m_Phone<<"\t"
" address: " <<abs->personArray[i].m_Addr <<endl;
}
}
system("pause"); // press any key to continue
system("cls"); // claer the screen
}
// check if the person is in the contacts. if yes, return the index of the person, otherwise, return -1
int isExist(Addressbooks *abs, string name)
{
for(int i = 0; i < abs->m_Size ;i++ )
{
if(abs->personArray[i].m_Name == name)
{
return i;
}
}
return -1;
}
//delete contact
void deletePerosn(Addressbooks *abs)
{
string name;
cout << "Please input the name which is going to be deleted" <<endl;
cin >> name;
int ret = isExist(abs,name);
if(ret != -1)
{
for(int i = ret; i < abs->m_Size; i++ )
{
abs->personArray[i] = abs->personArray[i + 1];
}
abs->m_Size--;
cout << "delete successfully" << endl;
}
else
{
cout << "No that person" <<endl;
}
system("pause"); // press any key to continue
system("cls"); // claer the screen
}
// search contact
void findPerson(Addressbooks *abs)
{
cout << "Please input the name to search " << endl;
string name;
cin >> name;
int ret = isExist(abs,name);
if(ret != -1)
{
cout << " Name: " <<abs->personArray[ret].m_Name <<"\t"
" Age: " <<abs->personArray[ret].m_Age <<"\t"
" Sex: " <<(abs->personArray[ret].m_Sex == 1 ? "male" : "female") <<"\t"
" Phone: " <<abs->personArray[ret].m_Phone<<"\t"
" address: " <<abs->personArray[ret].m_Addr <<endl;
cout << "search successfully" << endl;
}
else
{
cout << "No that person" <<endl;
}
system("pause"); // press any key to continue
system("cls"); // claer the screen
}
//modify the contact
void modifyPerson(Addressbooks *abs)
{
cout << "Please input the name to modify " << endl;
string name;
cin >> name;
int ret = isExist(abs,name);
if(ret != -1)
{
addInfo(abs, ret);
}
else
{
cout << "No that person" <<endl;
}
system("pause"); // press any key to continue
system("cls"); // claer the screen
}
//clear all contacts
void clearPerson(Addressbooks *abs)
{
abs->m_Size = 0;
cout << "Clear all the contacts" <<endl;
system("pause");
system("cls");
}
// menu display
void showMenu()
{
cout << "*******************************" << endl;
cout << "***** 1. add contacts *****" << endl;
cout << "***** 2. display contacts *****" << endl;
cout << "***** 3. delete contacts *****" << endl;
cout << "***** 4. search contacts *****" << endl;
cout << "***** 5. modify contacts *****" << endl;
cout << "***** 6. clear contacts *****" << endl;
cout << "***** 0. exit contacts *****" << endl;
cout << "*******************************" << endl;
}
int main(){
// create contact struct
Addressbooks abs;
abs.m_Size = 0;
int select = 0;
while(true){
showMenu();
cout << "Please choose the mune number:" << endl;
cin >> select;
switch(select)
{
case 1: // add contacts
addPerson(&abs);
break;
case 2:
showPerson(&abs);
break; // display contacts
case 3: // delete contacts
deletePerosn(&abs);
break;
case 4: // search contacts
findPerson(&abs);
break;
case 5: // modify contacts
modifyPerson(&abs);
break;
case 6: // clear contacts
clearPerson(&abs);
break;
case 0: //exit contacts
cout << " welcome to use it again" << endl;
system("pause");
return 0;
break;
default:
break;
}
}
system("pause");
return 0;
}
|
#pragma once
#include <stdlib.h>
#include "cocos2d.h"
using namespace cocos2d;
//#define LITE_VER // LITE version
//#define TEST_MODE
#define IPAD_VER // IPAD version
#define MAX_SIZE_OF_CHARACTER_POOL 128
#define FRAME_HEIGHT 960.0f
#define FRAME_WIDTH 640.0f
#ifdef IPAD_VER
#define BUY_AT_STORE_URL "https://itunes.apple.com/app/id504138737?mt=8"
#define ckConsumableBaseFeatureId "com.ozzywow.kw4ipadlite"
#define ckProductIdStep2 "com.ozzywow.kw4ipadlite.step2"
#define ckProductIdStep3 "com.ozzywow.kw4ipadlite.step3"
#define ckProductIdStep4 "com.ozzywow.kw4ipadlite.step4"
#define ckProductIdStep5 "com.ozzywow.kw4ipadlite.step5"
#define ckProductIdTotal "com.ozzywow.kw4ipadlite.total"
#else //IPAD_VER
#define BUY_AT_STORE_URL "http://itunes.apple.com/app/id509909625?mt=8"
#define ckConsumableBaseFeatureId "com.ozzywow.kw4iphonelite"
#define ckProductIdStep2 "com.ozzywow.kw4iphonelite.step2"
#define ckProductIdStep3 "com.ozzywow.kw4iphonelite.step3"
#define ckProductIdStep4 "com.ozzywow.kw4iphonelite.step4"
#define ckProductIdStep5 "com.ozzywow.kw4iphonelite.step5"
#define ckProductIdTotal "com.ozzywow.kw4iphonelite.total"
#endif //IPAD_VER
enum
{
kGameSceneTagImg,
kGameSceneTagBackground,
kGameSceneTagTouchHandlingLayer,
kGameSceneTagTextBtn,
kGameSecceTagHintLayer,
kGameSceneTagFuncBtn = kGameSecceTagHintLayer + 10,
kGameSceneTagAnswerShadow,
kGameSceneTagAnswerText,
kGameSceneTagAnswerFrame,
kGameSceneTagAvatar,
kGameSceneTagStar,
kGameSceneTagAppleSpecial,
kGameSceneTagApplePoint,
kGameSceneTagTouchedBtn = kGameSceneTagApplePoint + 10,
kGameSceneTagPopup,
kGameSceneTagEffect,
kGameSceneTagGoodjob,
kGameSceneTagWatch,
};
//static int MAX_WORD_NUM = 8;
static bool arrRandFlag[8];
static void InitRandNum()
{
memset(arrRandFlag, 0, sizeof(arrRandFlag));
}
static int GetRandNum(int max = 8)
{
for (int i = 0; i< 100; ++i) {
int ran = rand() % max;
if (arrRandFlag[ran] == false)
{
arrRandFlag[ran] = true;
return ran;
}
}
return -1;
}
static void PrintStyle(Node* parent, std::string& str, int fontSize, Point pos)
{
auto label0 = Label::createWithSystemFont(str, "Arial", fontSize);
label0->setPosition(pos.x - 1, pos.y);
label0->setColor(Color3B::BLACK);
parent->addChild(label0, kGameSceneTagAnswerText);
auto label1 = Label::createWithSystemFont(str, "Arial", fontSize);
label1->setPosition(pos.x + 1, pos.y);
label1->setColor(Color3B::BLACK);
parent->addChild(label1, kGameSceneTagAnswerText);
auto label2 = Label::createWithSystemFont(str, "Arial", fontSize);
label2->setPosition(pos.x, pos.y - 1);
label2->setColor(Color3B::BLACK);
parent->addChild(label2, kGameSceneTagAnswerText);
auto label3 = Label::createWithSystemFont(str, "Arial", fontSize);
label3->setPosition(pos.x, pos.y + 1);
label3->setColor(Color3B::BLACK);
parent->addChild(label3, kGameSceneTagAnswerText);
auto label = Label::createWithSystemFont(str, "Arial", fontSize);
label->setPosition(pos.x, pos.y + 1);
label->setColor(Color3B::WHITE);
parent->addChild(label, kGameSceneTagAnswerText);
}
static std::string replace_all(
const std::string &message,
const std::string &pattern,
const std::string &replace
) {
std::string result = message;
std::string::size_type pos = 0;
std::string::size_type offset = 0;
while ((pos = result.find(pattern, offset)) != std::string::npos)
{
result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
offset = pos + replace.size();
}
return result;
}
static inline unsigned long timeGetTimeEx()
{
struct timeval tv;
gettimeofday(&tv, 0);
return ((tv.tv_sec * 1000) + (tv.tv_usec / 1000));
}
|
#pragma once
#include <opencv2/opencv.hpp>
using pii = std::pair<size_t, size_t>;
namespace Kruskal
{
class Drawer
{
public:
Drawer(const size_t height, const size_t width);
void drawLine(const pii a, const pii b);
cv::Mat& getMat();
private:
size_t m_height;
size_t m_width;
cv::Mat m_mat;
};
}
|
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
int n, m, arr[maxn];
int dp[maxn][25];
inline int read() {
int x = 0, sign = 1;
char c = getchar();
// 符号
for (; c < '0' || '9' < c; c = getchar())
if (c == '-')
sign = -1;
// 多位数字
for (; '0' <= c && c <= '9'; c = getchar())
x = x * 10 + c - '0';
return x * sign;
}
// 这里dp存储的是最小的元素,也可以按实际要求存储最小值的下标
void init() {
for (int i = 1; i <= n; ++i)
dp[i][0] = arr[i];
for (int j = 1; (1 << j) <= n; ++j)
for (int i = 1; i + (1 << j) <= n + 1; ++i)
dp[i][j] = max(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
}
int rmq(int l, int r) {
int k = 0;
while ((1 << (k + 1)) <= r - l + 1)
++k;
return max(dp[l][k], dp[r - (1 << k) + 1][k]);
}
// #define DEBUG
int main() {
#ifdef DEBUG
freopen("d:\\.in", "r", stdin);
freopen("d:\\.out", "w", stdout);
#endif
cin >> n >> m;
for (int i = 1; i <= n; ++i)
arr[i] = read();
init();
int l, r;
for (int i = 0; i < m; ++i) {
l = read(), r = read();
printf("%d\n", rmq(l, r));
}
return 0;
}
|
/*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2020, Savely Pototsky (SavaLione)
* 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 REGENTS 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 REGENTS 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
* @brief sbc-client
* @author SavaLione
* @date 15 Nov 2020
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <string>
using boost::asio::ip::tcp;
enum
{
max_length = 1024
};
int main(int argc, char *argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: sbc-client <host> <port>\n";
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
tcp::resolver::iterator iterator = resolver.resolve(query);
tcp::socket s(io_service);
boost::asio::connect(s, iterator);
std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = std::strlen(request);
boost::asio::write(s, boost::asio::buffer(request, request_length));
char reply[max_length];
size_t reply_length = boost::asio::read(s, boost::asio::buffer(reply, request_length));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception &e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
#include "movil.h"
using namespace App_Interfaces;
Movil::Movil()
:vector(0.0, 0.0)
{
}
Movil::~Movil()
{
}
float Movil::integrar_vector(float delta, float &vec, float factor)
{
float copia_vector=vec;
vec+=factor * delta;
float val=copia_vector + vec;
return val * 0.5 * delta;
}
void Movil::sumar_vector(float c, t_vector t)
{
switch(t)
{
case t_vector::V_X: vector.x+=c; break;
case t_vector::V_Y: vector.y+=c; break;
}
}
void Movil::establecer_vector(float c, t_vector t)
{
switch(t)
{
case t_vector::V_X: vector.x=c; break;
case t_vector::V_Y: vector.y=c; break;
}
}
void Movil::accion_gravedad(float delta, float valor_gravedad)
{
integrar_vector(delta, vector.y, obtener_peso()*valor_gravedad);
float max_v_c=obtener_max_velocidad_caida();
if(vector.y > max_v_c) vector.y=max_v_c;
}
|
#include "StdAfx.h"
Q_PGW_ELF Qest_PGW_ELF;
void Q_PGW_ELF::Config()
{
int EnableExQuest = GetPrivateProfileInt("Quest", "Ativar", 1, CFG_QUEST_ELF);
if (EnableExQuest < 1) {
return;
}
}
bool Q_PGW_ELF::IsBadFileLine(char *FileLine, int &Flag)
{
Qest_PGW.Config();
if (Flag == 0)
{
if (isdigit(FileLine[0]))
{
Flag = FileLine[0] - 48;
return true;
}
}
else if (Flag < 0 || Flag > 9)
{
Flag = 0;
}
if (!strncmp(FileLine, "end", 3))
{
Flag = 0;
return true;
}
if (FileLine[0] == '/' || FileLine[0] == '\n')
return true;
for (UINT i = 0; i < strlen(FileLine); i++)
{
if (isalnum(FileLine[i]))
return false;
}
return true;
}
void Q_PGW_ELF::Q_Num()
{
for (int i(0); i<1000; i++)
{
Number[i].Mob = 0;
Number[i].Coun = 0;
Number[i].proc = 0;
Number[i].rew = 0;
Number[i].gift = 0;
Number[i].Zen = 0;
Number[i].exp = 0;
Number[i].lvl =0;
Number[i].resets = 0;
Number[i].teleport = 0;
Number[i].map = 0;
Number[i].x = 0;
Number[i].y = 0;
Number[i].reqmap = 0;
Number[i].msg[0] = NULL;
Number[i].msg2[0] = NULL;
Number[i].msg3[0] = NULL;
}
}
void Q_PGW_ELF::Q_Load()
{
Qest_PGW.Config();
Q_Num();
FILE *file;
file = fopen(CFG_QUEST_ELF, "r");
if (file == NULL)
{
MessageBoxA(0, CFG_QUEST_ELF, "CRITICAL ERROR", 0);
ExitProcess(1);
return;
}
char Buff[256];
int Flag = 0;
Count = 0;
while (!feof(file))
{
fgets(Buff, 256, file);
if (IsBadFileLine(Buff, Flag)) continue;
if (Flag == 1)
{
int n[10];
char mes[100];
char mes2[100];
char mes3[100];
//gets(mes);
sscanf(Buff, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d \"%[^\"]\" \"%[^\"]\" \"%[^\"]\"", &n[0], &n[1], &n[2], &n[3], &n[4], &n[5], &n[6], &n[7], &n[8], &n[9], &n[10], &n[11], &n[12], &n[13], &mes, &mes2, &mes3);
Number[Count].Mob = n[0];
Number[Count].Coun = n[1];
Number[Count].proc = n[2];
Number[Count].rew = n[3];
Number[Count].gift = n[4];
Number[Count].Zen = n[5];
Number[Count].exp = n[6];
Number[Count].lvl = n[7];
Number[Count].resets = n[8];
Number[Count].teleport = n[9];
Number[Count].map = n[10];
Number[Count].x = n[11];
Number[Count].y = n[12];
Number[Count].reqmap = n[13];
sprintf(Number[Count].msg, "%s", mes);
sprintf(Number[Count].msg2, "%s", mes2);
sprintf(Number[Count].msg3, "%s", mes3);
Count++;
}
}
fclose(file);
}
void Q_PGW_ELF::Q_NPC(int aIndex, int aNPC)
{
Qest_PGW.Config();
OBJECTSTRUCT * lpObj = (OBJECTSTRUCT*)OBJECT_POINTER(aIndex);
OBJECTSTRUCT *gObjNPC = (OBJECTSTRUCT*)OBJECT_POINTER(aNPC);
if ((gObjNPC->Class == NPC_Quest_Elf))
{
bool classe = gObj[aIndex].DbClass == DB_FAIRY_ELF || gObj[aIndex].DbClass == DB_MUSE_ELF;
if (!classe) {
ChatTargetSend(gObjNPC, "Começe por lorencia!", aIndex);
MsgOutput(aIndex, "Sua classe incia em lorencia.");
return;
}
if(QuestUser[aIndex].Quest_Num < Count)
{
if(QuestUser[aIndex].Quest_Start == 0)
{
if(QuestUser[aIndex].Quest_Num == 0 && lpObj->Level >= Number[QuestUser[aIndex].Quest_Num].lvl && Custom[aIndex].Resets >= Number[QuestUser[aIndex].Quest_Num].resets && lpObj->MapNumber == Number[QuestUser[aIndex].Quest_Num].reqmap)
{
ChatTargetSend(gObjNPC,"[Quest] Aceita!",aIndex);
QuestUser[aIndex].Quest_Start = 1;
//Manager.ExecFormat("UPDATE [MuOnline].[dbo].[Character] SET Quest_Start = 1 WHERE Name='%s'", lpObj->Name);
MsgOutput(aIndex,"[Quest] Quest N: %d",QuestUser[aIndex].Quest_Num+1);
MsgOutput(aIndex,"[Quest] %s",Number[QuestUser[aIndex].Quest_Num].msg);
MsgOutput(aIndex,"[Quest] Mate %s [%d/%d]",Number[QuestUser[aIndex].Quest_Num].msg2,QuestUser[aIndex].Quest_kill,Number[QuestUser[aIndex].Quest_Num].Coun);
if (Number[QuestUser[aIndex].Quest_Num].teleport > 0) {
gObjTeleport(gObj[aIndex].m_Index, Number[QuestUser[aIndex].Quest_Num].map, Number[QuestUser[aIndex].Quest_Num].x, Number[QuestUser[aIndex].Quest_Num].y);
}
return;
}
else if(QuestUser[aIndex].Quest_Num > 0 && lpObj->Level >= Number[QuestUser[aIndex].Quest_Num].lvl && Custom[aIndex].Resets >= Number[QuestUser[aIndex].Quest_Num].resets && lpObj->MapNumber == Number[QuestUser[aIndex].Quest_Num].reqmap)
{
QuestUser[aIndex].Quest_Start = 1;
//Manager.ExecFormat("UPDATE [MuOnline].[dbo].[Character] SET Quest_Start = 1 WHERE Name='%s'", lpObj->Name);
MsgOutput(aIndex,"[Quest] Quest N: %d",QuestUser[aIndex].Quest_Num+1);
MsgOutput(aIndex,"[Quest] %s",Number[QuestUser[aIndex].Quest_Num].msg);
MsgOutput(aIndex,"[Quest] Mate %s [%d/%d]",Number[QuestUser[aIndex].Quest_Num].msg2,QuestUser[aIndex].Quest_kill,Number[QuestUser[aIndex].Quest_Num].Coun);
ChatTargetSend(gObjNPC,"Complete essa nova Quest!",aIndex);
if (Number[QuestUser[aIndex].Quest_Num].teleport > 0) {
gObjTeleport(gObj[aIndex].m_Index, Number[QuestUser[aIndex].Quest_Num].map, Number[QuestUser[aIndex].Quest_Num].x, Number[QuestUser[aIndex].Quest_Num].y);
}
return;
}
else if (lpObj->Level < Number[QuestUser[aIndex].Quest_Num].lvl && Custom[aIndex].Resets < Number[QuestUser[aIndex].Quest_Num].resets) {
MsgOutput(aIndex, "[Quest]Volte no level: %d", Number[QuestUser[aIndex].Quest_Num].lvl);
MsgOutput(aIndex, "[Quest]Volte com %d resets", Number[QuestUser[aIndex].Quest_Num].resets);
}
else if (lpObj->Level < Number[QuestUser[aIndex].Quest_Num].lvl) {
MsgOutput(aIndex, "[Quest]Volte no level: %d", Number[QuestUser[aIndex].Quest_Num].lvl);
}
else if (Custom[aIndex].Resets < Number[QuestUser[aIndex].Quest_Num].resets) {
MsgOutput(aIndex, "[Quest]Volte com %d resets", Number[QuestUser[aIndex].Quest_Num].resets);
}
else if (lpObj->MapNumber != Number[QuestUser[aIndex].Quest_Num].reqmap) {
MsgOutput(aIndex, "[Quest] %s", Number[QuestUser[aIndex].Quest_Num].msg3);
}
else {
MsgOutput(aIndex, "Verifica esse erro...");
}
}
else if(QuestUser[aIndex].Quest_Start == 1)
{
if(QuestUser[aIndex].Quest_kill == Number[QuestUser[aIndex].Quest_Num].Coun)
{
int ExQuest_gift = Qest_PGW.Presents(aIndex,Number[QuestUser[aIndex].Quest_Num].rew,Number[QuestUser[aIndex].Quest_Num].gift);
if(ExQuest_gift == false)
{
ChatTargetSend(gObjNPC,"Premiação desativada!",aIndex);
return;
}
if(QuestUser[aIndex].Quest_Num == Count)
{
MsgOutput(aIndex,"[Quest] Finalzada");
return;
}
QuestUser[aIndex].Quest_Start = 0;
QuestUser[aIndex].Quest_Num++;
QuestUser[aIndex].Quest_kill = 0;
ChatTargetSend(gObjNPC,"Parabéns!",aIndex);
//Manager.ExecFormat("UPDATE [MuOnline].[dbo].[Character] SET Quest_Start = 0 WHERE Name='%s'", lpObj->Name);
//Manager.ExecFormat("UPDATE [MuOnline].[dbo].[Character] SET Quest_Kill = 0 WHERE Name='%s'", lpObj->Name);
//Manager.ExecFormat("UPDATE [MuOnline].[dbo].[Character] SET Quest_Num = Quest_Num + 1 WHERE Name='%s'", lpObj->Name);
return;
}
else
{
ChatTargetSend(gObjNPC,"Volte quando tiver terminado!",aIndex);
MsgOutput(aIndex,"[Quest] %s",Number[QuestUser[aIndex].Quest_Num].msg);
MsgOutput(aIndex,"[Quest] %s [%d/%d]",Number[QuestUser[aIndex].Quest_Num].msg2,QuestUser[aIndex].Quest_kill,Number[QuestUser[aIndex].Quest_Num].Coun);
return;
}
}
}
else
{
ChatTargetSend(gObjNPC,"Você completou todas as Quest!",aIndex);
MsgOutput(aIndex,"Você completou todas as Quest");
return;
}
}
}
void Q_PGW_ELF::KilledMob(int aIndex)
{
Qest_PGW.Config();
OBJECTSTRUCT * lpObj = (OBJECTSTRUCT*)OBJECT_POINTER(aIndex);
if (QuestUser[aIndex].Quest_kill < Number[QuestUser[aIndex].Quest_Num].Coun)
{
QuestUser[aIndex].Quest_kill++;
if (QuestUser[aIndex].Quest_kill == Number[QuestUser[aIndex].Quest_Num].Coun)
{
MsgOutput(aIndex, "[Quest] Retorne ao NPC!");
func.MsgUser(aIndex, 0, "[Quest] Retorne ao NPC!");
}
}
}
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <flux/stdio>
#include <flux/DirWalker>
#include "pack.h"
namespace fluxtar {
void pack(String path, ArchiveWriter *archive, bool verbose)
{
if (verbose) ferr() << path << nl;
archive->writeFile(path);
Ref<DirWalker> walker = DirWalker::tryOpen(path);
if (!walker) return;
walker->setFollowSymlink(true);
String sourcePath;
while (walker->read(&sourcePath)) {
if (verbose) ferr() << sourcePath << nl;
archive->writeFile(sourcePath);
}
}
} // namespace fluxtar
|
#include "mobilefacenet.hpp"
#include "face_align.hpp"
using namespace std;
using namespace cv;
MobileFacenet::MobileFacenet(const std::string&dir){
int dims[8];
std::string proto=dir+"/MobileFaceNet.prototxt";
std::string model=dir+"/MobileFaceNet.caffemodel";
graph=create_graph(nullptr,"caffe",proto.c_str(),model.c_str());
input_tensor =get_graph_input_tensor(graph, 0, 0);
get_tensor_shape(input_tensor,dims,4);
cout<<"==== MobileFacenet.dims="<<dims[0]<<","<<dims[1]<<","<<dims[2]<<","<<dims[3]<<endl;
input_data = (float *)malloc(sizeof(float) * dims[1]*dims[2]*dims[3]);
set_tensor_shape(input_tensor, dims, 4);
int rc=infer_shape(graph);
std::cout<<" MobileFacenet.InferShape()="<<rc<<std::endl;
rc=prerun_graph(graph);
out_tensor=get_graph_output_tensor(graph,0,0);
get_tensor_shape(out_tensor,dims,4);
feature_len=dims[1];
cout<<"Mobilefacenet.prerun="<<rc<<" graph="<<graph<<endl<<endl;
}
MobileFacenet::~MobileFacenet(){
release_graph_tensor(input_tensor);
release_graph_tensor(out_tensor);
destroy_graph(graph);
}
static void get_data(float* input_data, Mat &gray, int img_h, int img_w)
{
cv::Mat sample;
std::vector<cv::Mat>channels;
if(gray.channels()>1){
gray.convertTo(sample, CV_32FC3);
for(int i=0;i<gray.channels();i++){
cv::Mat channel(img_w,img_h, CV_32FC1, input_data);
input_data+=img_w*img_h;
channels.push_back(channel);
}
//sample/=256.f;//For model Lightened_CNN
cv::split(sample,channels);
return;
}else{
cv::Mat channel(img_w,img_h,CV_32FC1,input_data);
gray.convertTo(channel,CV_32FC1);
//channel/=256.f;//For model Lightened_CNN
}
}
int MobileFacenet::GetFeature(const cv::Mat&frame,FaceBox&box,float*feature)
{
cv::Mat aligned;
int alignflag,outsize=0,dims[4];
get_tensor_shape(input_tensor,dims,4);
alignflag = get_aligned_face(frame, (float *)&box.landmark, 5, dims[2],dims[3], aligned);
if(!alignflag){
std::cout<<"MobileFacenet::GetFeature aligned failed"<<std::endl;
return 0;
}
//get face feature
get_data(input_data,aligned,dims[3]/*img_h*/,dims[2]/*img_w*/);
set_tensor_buffer(input_tensor,input_data,dims[1]*dims[2]*dims[3]*sizeof(float));
run_graph(graph, 1);
float *data = (float *)get_tensor_buffer(out_tensor);
outsize=get_tensor_buffer_size(out_tensor)/sizeof(float);
for(int i=0;i<outsize;i++)
feature[i]=data[i];
return outsize;
}
|
#include "ViewerWindow.h"
#include <QPalette>
#define PI 3.1415926535898
namespace data_server{
ViewerWindow::ViewerWindow(int argc, char **argv, QWidget *parent)
: QWidget(parent),
m_RobotThread(argc, argv),
m_MathThread()
{
/** Set up the Controls **/
p_closeButton = new QPushButton(tr("&Quit"));
/** Set up the Position Display **/
leftLayout = new QVBoxLayout();
p_topLayout = new QHBoxLayout();
p_pointLayout = new QHBoxLayout();
p_circleLayout = new QHBoxLayout();
p_segmentLayout = new QHBoxLayout();
p_bezierLayout = new QHBoxLayout();
p_shapeLayout = new QHBoxLayout();
p_timeLayout = new QHBoxLayout();
p_segErrorLayout = new QHBoxLayout();
p_dataLayout = new QHBoxLayout();
p_typeLabel = new QLabel();
p_typeLabel->setText("Type");
p_maxLabel = new QLabel();
p_maxLabel->setText("Maximum");
p_minLabel = new QLabel();
p_minLabel->setText("Minimum");
p_averageLabel = new QLabel();
p_averageLabel->setText("Mean");
p_topLayout->addWidget(p_typeLabel);
p_topLayout->addWidget(p_minLabel);
p_topLayout->addWidget(p_averageLabel);
p_topLayout->addWidget(p_maxLabel);
p_shapeLabel = new QLabel();
p_shapeLabel->setText("Shapes: ");
p_shapeDisplay = new QLineEdit();
p_shapeDisplay->setText("0.0");
p_minShapes = new QLineEdit();
p_minShapes->setText("0.0");
p_maxShapes = new QLineEdit();
p_maxShapes->setText("0.0");
p_pointLabel = new QLabel();
p_pointLabel->setText("Points: ");
p_pointDisplay = new QLineEdit();
p_pointDisplay->setText("0.0");
p_minPoints = new QLineEdit();
p_minPoints->setText("0.0");
p_maxPoints = new QLineEdit();
p_maxPoints->setText("0.0");
p_circleLabel = new QLabel();
p_circleLabel->setText("Circles:");
p_circleDisplay = new QLineEdit();
p_circleDisplay->setText("0.0");
p_minCircle = new QLineEdit();
p_minCircle->setText("0.0");
p_maxCircle = new QLineEdit();
p_maxCircle->setText("0.0");
p_segmentLabel = new QLabel();
p_segmentLabel->setText("Segments:");
p_segmentDisplay = new QLineEdit();
p_segmentDisplay->setText("0.0");
p_minSeg = new QLineEdit();
p_minSeg->setText("0.0");
p_maxSeg = new QLineEdit();
p_maxSeg->setText("0.0");
p_bezierLabel = new QLabel();
p_bezierLabel->setText("Bezier: ");
p_bezierDisplay = new QLineEdit();
p_bezierDisplay->setText("0.0");
p_minBezier = new QLineEdit();
p_minBezier->setText("0.0");
p_maxBezier = new QLineEdit();
p_maxBezier->setText("0.0");
p_timeLabel = new QLabel();
p_timeLabel->setText("Time: ");
p_timeDisplay = new QLineEdit();
p_timeDisplay->setText("0.0");
p_maxTime = new QLineEdit();
p_minTime = new QLineEdit();
p_maxTime->setText("0.0");
p_minTime->setText("0.0");
p_segErrorLabel = new QLabel();
p_segErrorLabel->setText("Segment Error: ");
p_segErrorDisplay = new QLineEdit();
p_segErrorDisplay->setText("0.0");
p_minError = new QLineEdit();
p_minError->setText("0.0");
p_maxError = new QLineEdit();
p_maxError->setText("0.0");
p_dataLabel = new QLabel();
p_dataLabel->setText("Number Of Data Points: ");
p_dataSize = new QLineEdit();
p_dataSize->setText("0");
p_dataLayout->addWidget(p_dataLabel);
p_dataLayout->addWidget(p_dataSize);
p_circleLayout->addWidget(p_circleLabel);
p_circleLayout->addWidget(p_minCircle);
p_circleLayout->addWidget(p_circleDisplay);
p_circleLayout->addWidget(p_maxCircle);
p_segmentLayout->addWidget(p_segmentLabel);
p_segmentLayout->addWidget(p_minSeg);
p_segmentLayout->addWidget(p_segmentDisplay);
p_segmentLayout->addWidget(p_maxSeg);
p_bezierLayout->addWidget(p_bezierLabel);
p_bezierLayout->addWidget(p_minBezier);
p_bezierLayout->addWidget(p_bezierDisplay);
p_bezierLayout->addWidget(p_maxBezier);
p_shapeLayout->addWidget(p_shapeLabel);
p_shapeLayout->addWidget(p_minShapes);
p_shapeLayout->addWidget(p_shapeDisplay);
p_shapeLayout->addWidget(p_maxShapes);
p_pointLayout->addWidget(p_pointLabel);
p_pointLayout->addWidget(p_minPoints);
p_pointLayout->addWidget(p_pointDisplay);
p_pointLayout->addWidget(p_maxPoints);
p_timeLayout->addWidget(p_timeLabel);
p_timeLayout->addWidget(p_minTime);
p_timeLayout->addWidget(p_timeDisplay);
p_timeLayout->addWidget(p_maxTime);
p_segErrorLayout->addWidget(p_segErrorLabel);
p_segErrorLayout->addWidget(p_segErrorDisplay);
p_segErrorLayout->addWidget(p_maxError);
leftLayout->addLayout(p_topLayout);
leftLayout->addLayout(p_shapeLayout);
leftLayout->addLayout(p_pointLayout);
leftLayout->addLayout(p_circleLayout);
leftLayout->addLayout(p_segmentLayout);
leftLayout->addLayout(p_segErrorLayout);
leftLayout->addLayout(p_bezierLayout);
leftLayout->addLayout(p_timeLayout);
leftLayout->addLayout(p_dataLayout);
mainLayout = new QVBoxLayout();
mainLayout->addLayout(leftLayout);
mainLayout->addWidget(p_closeButton);
setLayout(mainLayout);
setWindowTitle(tr("Data Window"));
connect(p_closeButton, SIGNAL(clicked()), this, SLOT(close()));
connect(&m_MathThread, SIGNAL(newCircle(double,double,double)), this, SLOT(updateCircleDisplay(double,double,double)));
connect(&m_MathThread, SIGNAL(newPoint(double,double,double)), this, SLOT(updatePointDisplay(double,double,double)));
connect(&m_MathThread, SIGNAL(newShapeCount(double, double, double,double)), this, SLOT(updateShapeDisplay(double,double,double,double)));
connect(&m_MathThread, SIGNAL(newSegment(double, double, double)), this, SLOT(updateSegmentDisplay(double,double,double)));
connect(&m_MathThread, SIGNAL(newCurve(double,double,double)), this, SLOT(updateCurveDisplay(double,double,double)));
connect(&m_MathThread, SIGNAL(newMaxSegError(double,double)), this, SLOT(updateMaxSegErrorDisplay(double,double)));
connect(&m_MathThread, SIGNAL(newTimeDiff(double,double,double)), this, SLOT(updateTimeDisplay(double,double,double)));
connect(&m_RobotThread, SIGNAL(CircleInformation(double)), &m_MathThread, SLOT(pushCircle(double)));
connect(&m_RobotThread, SIGNAL(SegmentInformation(double)), &m_MathThread, SLOT(pushSegment(double)));
connect(&m_RobotThread, SIGNAL(PointInformation(double)), &m_MathThread, SLOT(pushPoint(double)));
connect(&m_RobotThread, SIGNAL(BezierInformation(double)), &m_MathThread, SLOT(pushCurve(double)));
connect(&m_RobotThread, SIGNAL(ShapeInformation(double)), &m_MathThread, SLOT(pushShape(double)));
connect(&m_RobotThread, SIGNAL(TimeInformation(double)), &m_MathThread, SLOT(pushTime(double)));
connect(&m_RobotThread, SIGNAL(SegmentErrorInformation(double)), &m_MathThread, SLOT(pushSegError(double)));
m_RobotThread.init();
m_RobotThread.start();
m_MathThread.start();
}//end constructor
void ViewerWindow::updateShapeDisplay(double min, double num, double max, double dataSize)
{
QString shapeNum, minNum, maxNum, dataNum;
minNum.setNum(min);
dataNum.setNum(dataSize);
maxNum.setNum(max);
shapeNum.setNum(num);
p_minShapes->setText(minNum);
p_shapeDisplay->setText(shapeNum);
p_maxShapes->setText(maxNum);
p_dataSize->setText(dataNum);
}
void ViewerWindow::updatePointDisplay(double min, double num, double max)
{
QString pointNum, minNum, maxNum;
minNum.setNum(min);
pointNum.setNum(num);
maxNum.setNum(max);
p_minPoints->setText(minNum);
p_pointDisplay->setText(pointNum);
p_maxPoints->setText(maxNum);
}
void ViewerWindow::updateCircleDisplay(double min, double num, double max)
{
QString circleNum, minNum, maxNum;
circleNum.setNum(num);
minNum.setNum(min);
maxNum.setNum(max);
p_circleDisplay->setText(circleNum);
p_minCircle->setText(minNum);
p_maxCircle->setText(maxNum);
}
void ViewerWindow::updateSegmentDisplay(double min, double num, double max)
{
QString segmentNum, minNum, maxNum;
segmentNum.setNum(num);
minNum.setNum(min);
maxNum.setNum(max);
p_segmentDisplay->setText(segmentNum);
p_minSeg->setText(minNum);
p_maxSeg->setText(maxNum);
}
void ViewerWindow::updateCurveDisplay(double min, double num, double max)
{
QString curveNum, minNum, maxNum;
double curveNumber = num;
minNum.setNum(min);
maxNum.setNum(max);
curveNum.setNum(curveNumber);
p_bezierDisplay->setText(curveNum);
p_minBezier->setText(minNum);
p_maxBezier->setText(maxNum);
}
void ViewerWindow::updateTimeDisplay(double min, double num, double max)
{
QString timeNum, minNum, maxNum;
double timeNumber = num;
timeNum.setNum(timeNumber, 'g', 15);
minNum.setNum(min);
maxNum.setNum(max);
p_timeDisplay->setText(timeNum);
p_minTime->setText(minNum);
p_maxTime->setText(maxNum);
}
void ViewerWindow::updateMaxSegErrorDisplay(double min, double max)
{
QString minError, maxError;
minError.setNum(min);
maxError.setNum(max);
p_maxError->setText(maxError);
p_minError->setText(minError);
}
}//namespace server
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Foundation.Metadata.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Foundation::Metadata {
struct ApiInformation
{
ApiInformation() = delete;
static bool IsTypePresent(hstring_view typeName);
static bool IsMethodPresent(hstring_view typeName, hstring_view methodName);
static bool IsMethodPresent(hstring_view typeName, hstring_view methodName, uint32_t inputParameterCount);
static bool IsEventPresent(hstring_view typeName, hstring_view eventName);
static bool IsPropertyPresent(hstring_view typeName, hstring_view propertyName);
static bool IsReadOnlyPropertyPresent(hstring_view typeName, hstring_view propertyName);
static bool IsWriteablePropertyPresent(hstring_view typeName, hstring_view propertyName);
static bool IsEnumNamedValuePresent(hstring_view enumTypeName, hstring_view valueName);
static bool IsApiContractPresent(hstring_view contractName, uint16_t majorVersion);
static bool IsApiContractPresent(hstring_view contractName, uint16_t majorVersion, uint16_t minorVersion);
};
}
}
|
// bfs
// N*N행렬로 계산
// 큐 사용
// visit표시 중요
// 배열에서 1부터 시작하는거 유의
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void bfs(vector<vector <int> >&llist, int start, vector<int> &visit){
queue<int> q;
visit[start]=1;
cout<<start<<" ";
q.push(start);
while(!q.empty()){
int tmp = q.front();
q.pop();
// tmp해주는거 잊지말자
for(int i=1; i<=llist[tmp].size(); ++i){
if (llist[tmp][i]==1 && !visit[i]){
visit[i]=1;
cout << i << " ";
q.push(i);
}
}
}
cout<<""<<endl;
}
int main(){
int tcase;
cin>>tcase;
for (int i=0 ; i<tcase; ++i){
int v, start;
cin>>v>>start;
vector<vector<int> > llist(v+1, vector<int> (v+1,0));
vector<int> visit(v+1,0);
while(1){
int x,y;
cin>>x>>y;
if (x==-1 && y==-1) break;
llist[x][y] = llist[y][x] = 1;
}
bfs(llist, start, visit);
}
}
|
#include <cstdio>
const int MAX_N = 2000;
int N;
char S[MAX_N+1];
void read();
void solve();
int main(){
read();
solve();
return 0;
}
void read(){
scanf("%d\n", &N);
for (int i=0; i<N; i++){
scanf("%c", &S[i]);
}
}
void solve(){
int a=0, b=N-1;
while(a<=b){
bool left = false;
for (int i=0; a+i <= b; i++){
if (S[a+i] < S[b-i]){
left = true;
break;
}
else if (S[a+i] > S[b-i]){
left = false;
break;
}
}
if (left) putchar (S[a++]);
else putchar (S[b--]);
}
putchar ('\n');
}
|
/* @brief Process.cpp
* Este programa obtiene todas las variables
* que son necesarias, asi como sus transformaciones
*/
#include <bits/stdc++.h>
using namespace std;
extern map<int, int> tablePermutation;
void inversePermutation( string *valueofPhi ){
string previous = "";
register int auxCont = 1;
for( register int i = 0; i < (*valueofPhi).size(); i++ ){
previous = previous + (*valueofPhi)[i];
if( (*valueofPhi)[i] == ' ' ){
tablePermutation.insert( pair<int, int>( stoi( previous, nullptr, 10 ), auxCont ) );
auxCont++;
previous = "";
}
}
}
vector<int> randomPermutation( int n ){
vector<int> randomNumbers;
for( register int i = 0; i < n; i++ )
randomNumbers.push_back( i+1 );
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
shuffle ( randomNumbers.begin(), randomNumbers.end(), default_random_engine( seed ) );
return randomNumbers;
}
void mappingValues( string *valueofPhi ){
string previous = "";
register int j = 0, auxCont = 1;
// Usamos una String auxiliar en caso de que el numero tenga dos digitos
for( register int i = 0; i < (*valueofPhi).size(); i++ ){
previous = previous + (*valueofPhi)[i];
if( (*valueofPhi)[i] == ' ' ){
tablePermutation.insert( pair<int, int>( auxCont, stoi( previous, nullptr, 10 ) ) );
auxCont++;
previous = "";
}
}
}
void verifytoMod( string *messagetoVerify ){
int mod = (*messagetoVerify).size() % tablePermutation.size();
int missing = tablePermutation.size() - mod;
char specialCharacters[ missing ];
if( mod != 0 ){
cout<< " Special characters added: " << missing << endl;
for( register int i = 0; i < missing; i++ )
specialCharacters[i] = char( 40+i );
specialCharacters[ missing ] = '\0';
*messagetoVerify = *messagetoVerify + specialCharacters;
}
}
void reviewMod( string *messagetoVerify ){
int tamBloque = tablePermutation.size() / 8;
int mod = (*messagetoVerify).size() % tamBloque;
int missing = tamBloque - mod;
char specialCharacters[ missing ];
if( mod != 0 ){
cout<< " Special characters added: " << missing << endl;
for( register int i = 0; i < missing; i++ )
specialCharacters[i] = char( 40+i );
specialCharacters[ missing ] = '\0';
*messagetoVerify = *messagetoVerify + specialCharacters;
}
}
string askforType( void ){
string answer;
cout<< " Do you want encrypt/decrypt at the bit level? ";
cin>> answer;
return answer;
}
|
// Copyright 2020 JD.com, Inc. Galileo Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ==============================================================================
#include "client/dgraph_global.h"
#include "glog/logging.h"
namespace galileo {
namespace client {
DGraph *gDGraph = nullptr;
bool CreateDGraph(const DGraphConfig &config) {
if (nullptr == gDGraph) {
gDGraph = new DGraph();
if (!gDGraph->Initialize(config)) {
LOG(ERROR) << "Initialize graph without candidate failed.";
delete gDGraph;
gDGraph = nullptr;
return false;
}
LOG(INFO) << "Create dgraph instance success.";
}
return true;
}
void DestroyDGraph() {
if (gDGraph != nullptr) {
delete gDGraph;
gDGraph = nullptr;
}
}
GraphMeta CollectGraphMeta() {
GraphMeta meta_info{0, 0};
if (nullptr == gDGraph) {
LOG(ERROR) << "The gDGraph is nullptr!";
return meta_info;
}
if (!gDGraph->CollectGraphMeta(&meta_info)) {
LOG(ERROR) << "Get meta info fail!";
}
return meta_info;
}
} // namespace client
} // namespace galileo
|
#include <iostream>
#include <string>
int main ()
{
std::string str, preStr, maxStr;
unsigned cnt = 0, tmpCnt = 0;
std::cout << "Please input some words:";
while (std::cin >> str)
{
if (str == preStr)
{
tmpCnt++;
} else
{
if (tmpCnt > cnt) {
cnt = tmpCnt;
maxStr = preStr;
}
tmpCnt = 0;
preStr = str;
}
}
std::cout << "\n" << maxStr << " has " << cnt + 1 << " times!\n";
std::cout << "Bye!\n";
}
|
#ifndef __PlaneRippleObject_H__
#define __PlaneRippleObject_H__
const Vector4 PLANE_DEFAULT_COLOR = Vector4(0, 0, 20, 255);
const float PLANE_RIPPLE_DEFAULT_DURATION = 6;
const float DEFAULT_COLLISION_RADIUS_MODIFIER = 5.0f;
class PlaneRippleObject : public GameObject
{
protected:
std::vector<Vector4> m_collisionPointsPositionAndRadius;
std::vector<float> m_collisionPointsTimer;
std::vector<float>m_timersPercentageLeft;
int m_numberActiveCollisionPoints;
Sound* m_impactSound;
public:
PlaneRippleObject(Scene* pScene, std::string name, Vector3 pos, Vector3 rot, Vector3 scale, Mesh* pMesh, ShaderProgram* pShader, GLuint texture, vec2 UVScale = vec2(1, 1), vec2 UVOffset = vec2(0, 0));
virtual ~PlaneRippleObject();
virtual void Update(double TimePassed);
virtual void Draw(int renderorder);
virtual void BeginCollision(b2Fixture* fixtureCollided, b2Fixture* fixtureCollidedAgainst, GameObject* objectCollidedagainst, b2Vec2 collisionNormal, b2Vec2 contactPoint, bool touching);
virtual void Reset();
};
#endif //__PlayerObject_H__
|
//C++ INCLUDES
#include <vector>
#include <fstream>
#include <iostream>
#include <math.h>
//ROOT INCLUDES
//#include <TSYSTEM.h>
#include <TSystem.h>
#include <TTree.h>
#include <TLatex.h>
#include <TString.h>
#include <TFile.h>
#include <TH1D.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TF1.h>
#include <TBox.h>
#include <TCanvas.h>
#include <TGraph.h>
#include <TColor.h>
#include <TGraphErrors.h>
#include <TRandom3.h>
#include <TLegend.h>
#include <TMath.h>
#include <TROOT.h>
#include <Math/GaussIntegrator.h>
#include <Math/IntegratorOptions.h>
#include <TFractionFitter.h>
#include <TRandom3.h>
//LOCAL INCLUDES
#include "Aux.hh"
//Axis
const float axisTitleSize = 0.06;
const float axisTitleOffset = 0.9;
const float axisTitleSizeRatioX = 0.18;
const float axisLabelSizeRatioX = 0.12;
const float axisTitleOffsetRatioX = 0.84;
const float axisTitleSizeRatioY = 0.15;
const float axisLabelSizeRatioY = 0.108;
const float axisTitleOffsetRatioY = 0.52;
//Margins
const float leftMargin = 0.13;
const float rightMargin = 0.05;
const float topMargin = 0.07;
const float bottomMargin = 0.12;
using namespace std;
float getXsecBR(std::string sigModelName)
{
float fxsecBR = 1.0;
ifstream is("data/XsecBR.dat");
while(!is.eof())
{
std::string name;
std::string xsec;
std::string exsec;
std::string BR;
std::string xsecBR;
std::string exsecBR;
is>>name;
is>>xsec;
is>>exsec;
is>>BR;
is>>xsecBR;
is>>exsecBR;
if(name.compare(sigModelName)==0)
{
fxsecBR = strtof(xsecBR.c_str(), 0);
return fxsecBR;
}
}
return fxsecBR;
}
;
void DrawDataBkgSig(TH1F *h1Data, TH1F *h1QCDGJets, TH1F *h1EWK, TH1F *h1Sig, TH1F *h1all, float lumi, std::string sigModelTitle, std::string sigModelName, std::string suffix, TString outPlotsDir)
{
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetLogy(1);
h1Data->SetLineWidth(2);
h1Data->SetLineColor(kBlack);
h1Data->SetMarkerStyle(8);
h1Data->GetYaxis()->SetTitleSize(axisTitleSize);
h1Data->GetXaxis()->SetTitleSize(axisTitleSize);
h1Data->GetYaxis()->SetTitleOffset(axisTitleOffset);
h1Data->GetXaxis()->SetTitleOffset(axisTitleOffset);
h1Data->Draw("E");
h1Data->GetYaxis()->SetRangeUser(1e-3, 1000.0*h1Data->GetMaximum());
h1QCDGJets->SetLineColor(kBlue);
h1QCDGJets->SetLineWidth(2);
h1EWK->SetLineColor(kOrange);
h1EWK->SetLineWidth(2);
h1Sig->SetLineColor(kGreen);
h1Sig->SetLineWidth(2);
h1all->SetLineColor(kRed);
h1all->SetLineWidth(2);
h1QCDGJets->Draw("samehisto");
h1EWK->Draw("samehisto");
h1Sig->Draw("samehisto");
h1all->Draw("samehisto");
TLegend * leg = new TLegend(0.18, 0.7, 0.93, 0.89);
leg->SetNColumns(2);
leg->SetBorderSize(0);
leg->SetTextSize(0.03);
leg->SetLineColor(1);
leg->SetLineStyle(1);
leg->SetLineWidth(1);
leg->SetFillColor(0);
leg->SetFillStyle(1001);
leg->AddEntry(h1Data,"data","lep");
leg->AddEntry(h1QCDGJets,"#gamma + jets/QCD bkg","l");
leg->AddEntry(h1EWK,"EWK bkg","l");
leg->AddEntry(h1Sig, sigModelTitle.c_str(),"l");
leg->AddEntry(h1all,"combined fit","l");
leg->Draw();
DrawCMS(myC, 13, lumi);
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+("/"+sigModelName+"_postfit_bkgsig_"+suffix+".pdf").c_str());
myC->SaveAs("fit_results/2016/"+outPlotsDir+("/"+sigModelName+"_postfit_bkgsig_"+suffix+".png").c_str());
myC->SaveAs("fit_results/2016/"+outPlotsDir+("/"+sigModelName+"_postfit_bkgsig_"+suffix+".C").c_str());
}
;
void DrawDataBkgSig(TH1F *h1Data, TH1F *h1Bkg, TH1F *h1Sig, TH1F *h1all, float lumi, std::string sigModelTitle, std::string sigModelName, std::string suffix, TString outPlotsDir)
{
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetLogy(1);
h1Data->SetLineWidth(2);
h1Data->SetLineColor(kBlack);
h1Data->SetMarkerStyle(8);
h1Data->GetYaxis()->SetTitleSize(axisTitleSize);
h1Data->GetXaxis()->SetTitleSize(axisTitleSize);
h1Data->GetYaxis()->SetTitleOffset(axisTitleOffset);
h1Data->GetXaxis()->SetTitleOffset(axisTitleOffset);
h1Data->Draw("E");
//h1Data->GetYaxis()->SetRangeUser(1e-3, 1000.0*std::max(h1Data->GetMaximum(), h1Bkg->GetMaximum(), h1Sig->GetMaximum()));
h1Data->GetYaxis()->SetRangeUser(1e-3, 1000.0*h1Data->GetMaximum());
h1Bkg->SetLineColor(kBlue);
h1Bkg->SetLineWidth(2);
h1Sig->SetLineColor(kGreen);
h1Sig->SetLineWidth(2);
h1all->SetLineColor(kRed);
h1all->SetLineWidth(2);
h1Bkg->Draw("samehisto");
h1Sig->Draw("samehisto");
h1all->Draw("samehisto");
TLegend * leg = new TLegend(0.18, 0.7, 0.93, 0.89);
leg->SetNColumns(2);
leg->SetBorderSize(0);
leg->SetTextSize(0.03);
leg->SetLineColor(1);
leg->SetLineStyle(1);
leg->SetLineWidth(1);
leg->SetFillColor(0);
leg->SetFillStyle(1001);
leg->AddEntry(h1Data,"data","lep");
leg->AddEntry(h1Bkg,"#gamma + jets/QCD bkg","l");
leg->AddEntry(h1Sig, sigModelTitle.c_str(),"l");
leg->AddEntry(h1all,"combined fit","l");
leg->Draw();
DrawCMS(myC, 13, lumi);
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+("/"+sigModelName+"_fit_bkgsig_"+suffix+".pdf").c_str());
myC->SaveAs("fit_results/2016/"+outPlotsDir+("/"+sigModelName+"_fit_bkgsig_"+suffix+".png").c_str());
myC->SaveAs("fit_results/2016/"+outPlotsDir+("/"+sigModelName+"_fit_bkgsig_"+suffix+".C").c_str());
}
;
void DrawCMS(TCanvas *myC, int energy, float lumi)
{
myC->cd();
TLatex *tlatex = new TLatex();
tlatex->SetNDC();
tlatex->SetTextAngle(0);
tlatex->SetTextColor(kBlack);
tlatex->SetTextFont(63);
tlatex->SetTextAlign(11);
tlatex->SetTextSize(25);
tlatex->DrawLatex(0.16, 0.95, "CMS");
tlatex->SetTextFont(53);
tlatex->DrawLatex(0.23, 0.95, "Preliminary");
tlatex->SetTextFont(43);
tlatex->SetTextSize(23);
TString lumiString = Form("%.2f pb^{-1} (%d TeV)", lumi, energy);
if (lumi > 1000.0)
{
lumiString = Form("%.2f fb^{-1} (%d TeV)", lumi/1000.0, energy);
}
std::string Lumi ((const char*) lumiString);
tlatex->SetTextAlign(31);
tlatex->DrawLatex(0.9, 0.95, Lumi.c_str());
tlatex->SetTextAlign(11);
};
void properScale(TH1F * hist, float norm)
{
for(int i=0; i<hist->GetNbinsX()+1; i++)
{
float v0 = hist->GetBinContent(i);
hist->SetBinContent(i,norm*v0);
if(v0>0.0000001) hist->SetBinError(i, norm*v0/sqrt(v0));
else hist->SetBinError(i, 0);
}
}
|
#ifndef _CGNSFAMILY_H_
#define _CGNSFAMILY_H_
#include "meshDataAPI.h"
#include "meshSet.h"
namespace MeshData
{
class MESHDATAAPI CgnsFamily : public MeshSet
{
public:
CgnsFamily(QString name);
CgnsFamily();
~CgnsFamily();
///添加子set
void appendDataSet(vtkDataSet* set);
void generateDisplayDataSet() override;
virtual QDomElement& writeToProjectFile(QDomDocument* doc, QDomElement* parent) override;
//从XML文件读取数据
virtual void readDataFromProjectFile(QDomElement* e) override;
//写入二进制文件
virtual void writeBinaryFile(QDataStream* dataStream) override;
//读入二进制文件
virtual void readBinaryFile(QDataStream* dataStream) override;
private:
QList<vtkDataSet*> _setList{};
};
}
#endif
|
/***********************************************************************
created: 16/7/2013
author: Lukas E Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CustomShapesDrawing.h"
#include "CEGUI/System.h"
#include "CEGUI/Renderer.h"
#include "CEGUI/SchemeManager.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/Window.h"
#include "CEGUI/widgets/DefaultWindow.h"
#include "CEGUI/widgets/ToggleButton.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/svg/SVGDataManager.h"
#include "CEGUI/svg/SVGImage.h"
#include "CEGUI/svg/SVGData.h"
#include "CEGUI/svg/SVGBasicShape.h"
#include <glm/glm.hpp>
#include <sstream>
#include <ctime>
#include <stddef.h>
using namespace CEGUI;
using namespace glm;
/*************************************************************************
Constructor.
*************************************************************************/
CustomShapesDrawingSample::CustomShapesDrawingSample() :
d_root(nullptr),
d_customSVGImageFrameWindow(nullptr),
d_customPolyline(nullptr),
d_FPSGraphGeometryBuffer(nullptr),
d_FPSGraphSamplesCount(30),
d_FPSFrames(),
d_FPSElapsed(0.0f),
d_FPSMaxGraphValue(1),
d_useRealFPS(false),
d_customSVGImageWidth(300.0f),
d_customSVGImageHeight(100.0f),
d_customGeometryGraphWidth(300.0f),
d_customGeometryGraphHeight(100.0f),
d_lastFPSLabel(nullptr),
d_customGeometryFPSLabel1(nullptr),
d_customGeometryFPSLabel2(nullptr),
d_customGeometryFPSLabel3(nullptr),
d_customSVGImageFPSLabel1(nullptr),
d_customSVGImageFPSLabel2(nullptr),
d_customSVGImageFPSLabel3(nullptr),
d_customSVGImage(nullptr),
d_customSVGData(nullptr)
{
Sample::d_name = "CustomShapesDrawingSample";
Sample::d_credits = "Lukas \"Ident\" Meindl";
Sample::d_description =
"In CEGUI the GeometryBuffer can be used to render vertices directly on the screen. However, this comes with limitations, "
"since CEGUI is not a Rendering Engine.For example only textured and coloured vertices are available out of the box.The vertices for all lines and "
"the quad of the background of the graph had to be calculated with extra code.The other possibility to render a graph, as display in this sample, "
"is by using an SVGImage.Each SVGImage points to a(possibly shared) SVGData object that contains its data.This data can be modified by adding shapes based "
"on the SVG BasicShapes.The vertices do not have to be calculated in this case and the rendering specifics like colours and line widths can be specified "
"more conveniently.Additionally, with SVGImages it is possible to switch on anti - aliasing, which is implemented by adding additional blending geometry to all shapes. "
"Also, it is easily possible to add the SVGImage to a window, by referring to it via a property, which is not possible with the GeometryBuffer method.This is "
"displayed in the sample with a WindowsLook / FrameWindow that contains an Generic / Image window.The FrameWindow is sizeable and will also scale its child window when "
"sized.The Generic / Image window has an 'Image' property that is pointing to our SVGImage.When the FrameWindow is sized it can thus be seen that the image is "
"being scaled too.";
Sample::d_summary =
"This sample displays rendering possibilities provided with CEGUI's GeometryBuffer and SVGImage/SVGData class. "
"The goal is to render an FPS graph that displays the last recorded FPS values.SVGImage provides optional anti - aliasing and the possibility to "
"use the Image as part of a window.";
// Initialising the FPS values
for(unsigned int i = 0; i < d_FPSGraphSamplesCount; ++i)
d_lastFPSValues.push_front(0);
}
/*************************************************************************
Sample specific initialisation goes here.
*************************************************************************/
bool CustomShapesDrawingSample::initialise(CEGUI::GUIContext* guiContext)
{
d_usedFiles = CEGUI::String(__FILE__);
// CEGUI setup
SchemeManager::getSingleton().createFromFile("WindowsLook.scheme");
SchemeManager::getSingleton().createFromFile("Generic.scheme");
guiContext->setDefaultCursorImage("WindowsLook/MouseArrow");
WindowManager& winMgr = WindowManager::getSingleton();
// Create a Generic/image called 'Root' with a white image as Image property.
d_root = static_cast<DefaultWindow*>(winMgr.createWindow("Generic/Image", "Root"));
d_root->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f)));
d_root->setProperty("Image", "WindowsLook/Background");
// load font and setup default if not loaded via scheme
FontManager::FontList loadedFonts = FontManager::getSingleton().createFromFile("DejaVuSans-12.font");
Font* defaultFont = loadedFonts.empty() ? 0 : loadedFonts.front();
FontManager::getSingleton().createFromFile("DejaVuSans-10.font");
// Set default font for the gui context
guiContext->setDefaultFont(defaultFont);
// Set the root window as root of our GUI Context
guiContext->setRootWindow(d_root);
// Initialise random-seed
srand(static_cast<unsigned int>(time(nullptr)));
// We create a checkbox to switch between showing randomly generated FPS and real FPS
createCheckboxShowRealFPS();
// Create a label displaying the last FPS value
createLastFPSLabel();
// Create a label with description of the Sample
createDescriptionLabel();
/* We will render custom geometry in two different ways. The first uses an SVGImage with attached customly defined
SVGData. The SVGImage will be part of a window inside a Framewindow which can be moved around. The second directly
modifies a Geometrybuffer to render user-defined vertices directly on the screen. */
/* Our first method uses the SVGImage class of CEGUI. The SVGImage references an SVGData object that we will create.
This SVGData object commonly contains what is parsed from an SVG file. In our case we will manually create SVG BasicShape
objects, such as a polyline, which connects several points with lines, and add them to the SVGData. The SVGImage can be used
in the same way as a regular raster graphics Image (BitmapImage) in CEGUI and can therefore be set as a property of a window
that will then render the Image automatically, with appropriate scaling etc.
*/
setupCustomSVGImage();
// We create a drag- and sizable FrameWindow and add a child-window to it that will render our SVGImage
createCustomSVGImageWindows();
// We add labels to our graph using windows
createCustomSVGImageFPSLabels();
/* Our second method directly modifies a GeometryBuffer of CEGUI. This has the disadvantage that we will have to calculate all
vertex positions of all triangles forming the geometry ourselves before filling them in. Compared to using SVGData and creating
and modifying SVG BasicShapes this can be inconvenient. Additionally, we cannot make our geometry be used in connection with a window, so that it could be moved around etc. wever this can be of great
use for overlays or backgrounds that use custom geometry that is calculated by the user. */
setupCustomGeometryGraph(guiContext);
// We add labels to our graph using windows
createCustomGeometryFPSLabels();
// Subscribe handler to reposition our labels when the window size is changed
CEGUI::System::getSingleton().subscribeEvent(
CEGUI::System::EventDisplaySizeChanged,
CEGUI::Event::Subscriber(&CustomShapesDrawingSample::handleDisplaySizeChange,
this));
// return true so that the samples framework knows that initialisation was a
// success, and that it should now run the sample.
return true;
}
/*************************************************************************
Positions the GeometryBuffer based graph
*************************************************************************/
void CustomShapesDrawingSample::positionCustomGeometryFPSGraph()
{
CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();
const CEGUI::Rectf scrn(glm::vec2(0, 0), renderer->getDisplaySize());
d_FPSGraphGeometryBuffer->setClippingRegion(scrn);
d_FPSGraphGeometryBuffer->setTranslation(glm::vec3(250.0f, 250.0f, 0.0f));
}
/*************************************************************************
Triggers the drawing of our FPS graph after everything else was rendered
*************************************************************************/
bool CustomShapesDrawingSample::drawFPSGraphOverlay(const CEGUI::EventArgs& args)
{
if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RenderQueueID::Overlay)
return false;
// draw FPS value
d_FPSGraphGeometryBuffer->draw();
return true;
}
/*************************************************************************
Update the FPS graph geometry when necessary
*************************************************************************/
void CustomShapesDrawingSample::update(float timeSinceLastUpdate)
{
updateFPS(timeSinceLastUpdate);
positionCustomGeometryFPSGraph();
}
/*************************************************************************
Update the FPS value
*************************************************************************/
void CustomShapesDrawingSample::updateFPS(const float elapsed)
{
// another frame
++d_FPSFrames;
// Add FPS count if a second has passed
if ((d_FPSElapsed += elapsed) >= 1.0f)
{
if(d_useRealFPS)
updateFPSData(d_FPSFrames);
else
{
int randomFPS = 50 + rand() % 60;
updateFPSData(randomFPS);
}
// reset counter state
d_FPSFrames = 0;
float modValue = 1.0f;
d_FPSElapsed = std::modf(d_FPSElapsed, &modValue);
}
}
/*************************************************************************
Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void CustomShapesDrawingSample::deinitialise()
{
// Destroy the GeometryBuffer created for this sample
CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();
renderer->destroyGeometryBuffer(*d_FPSGraphGeometryBuffer);
// Destroy the SVGImage created for this sample
CEGUI::ImageManager& imageManager = CEGUI::ImageManager::getSingleton();
imageManager.destroy("FPSGraphSVG");
// Destroy the created custom SVGData
CEGUI::SVGDataManager& svgDataManager = CEGUI::SVGDataManager::getSingleton();
svgDataManager.destroy(*d_customSVGData);
// This destroys the window and its child windows
WindowManager& winMgr = WindowManager::getSingleton();
winMgr.destroyWindow(d_root);
}
/*************************************************************************
Update the geometry used for the FPS graph
*************************************************************************/
void CustomShapesDrawingSample::updateFPSGraphs()
{
d_FPSGraphGeometryBuffer->reset();
std::vector<glm::vec2> linePositions;
for(unsigned int i = 0; i < d_FPSGraphSamplesCount; ++i)
{
float currentOffset = i / static_cast<float>(d_FPSGraphSamplesCount - 1);
float relative_height = d_lastFPSValues.at(i) / static_cast<float>(d_FPSMaxGraphValue);
glm::vec2 currentPosition(currentOffset, relative_height);
linePositions.push_back(currentPosition);
}
// We will update the SVG Polyline object by simply passing the linepoints to it and triggering
// a re-draw of the Image.
updateCustomSVGImagePolyline(linePositions);
// Update the FPS labels for the SVGImage
updateCustomSVGImageFPSLabels();
// We will update the GeometryBuffer which contains our line vertices. We will need to calculate
// the vertices of a line with a width of 1.0 and which will be rendered in green colour.
updateCustomGeometryGraph(linePositions);
// Update the FPS Labels for the GeometryBuffer
updateCustomGeometryFPSLabels();
}
/*************************************************************************
Update the FPS graph geometry
*************************************************************************/
void CustomShapesDrawingSample::updateCustomGeometryGraph(std::vector<glm::vec2> linePositions)
{
// Reset all geometry data
d_FPSGraphGeometryBuffer->reset();
// Add the background vertices
d_FPSGraphGeometryBuffer->appendGeometry(d_customGeometryGraphBackgroundVertices.data(), d_customGeometryGraphBackgroundVertices.size());
//Precalculate y and y coordinate of first point
linePositions.at(0).x = 0.0f;
linePositions.at(0).y = d_customGeometryGraphHeight - linePositions.at(0).y * d_customGeometryGraphHeight;
//We will draw a simple quad for each line segment
size_t linePositionsCount = linePositions.size();
for (size_t j = 1; j < linePositionsCount; ++j)
{
const glm::vec2& prevPos = linePositions.at(j - 1);
glm::vec2& currentPos = linePositions.at(j);
currentPos.x = currentPos.x * d_customGeometryGraphWidth * 0.95f;
currentPos.y = d_customGeometryGraphHeight - currentPos.y * d_customGeometryGraphHeight;
// Normalize and tilt the 2D direction vector by 90� to get the vector pointing in the offset direction
glm::vec2 offsetVector = currentPos - prevPos;
offsetVector = glm::normalize(offsetVector);
offsetVector = glm::vec2(offsetVector.y, -offsetVector.x) * 1.0f;
CEGUI::ColouredVertex linePositionVertex;
static const CEGUI::Colour lineColour(0.0f, 1.0f, 0.0f, 1.0f);
linePositionVertex.setColour(lineColour);
linePositionVertex.d_position = glm::vec3(prevPos - offsetVector, 0.0f);
d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex);
linePositionVertex.d_position = glm::vec3(currentPos - offsetVector, 0.0f);
d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex);
linePositionVertex.d_position = glm::vec3(currentPos + offsetVector, 0.0f);
d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex);
linePositionVertex.d_position = glm::vec3(currentPos + offsetVector, 0.0f);
d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex);
linePositionVertex.d_position = glm::vec3(prevPos - offsetVector, 0.0f);
d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex);
linePositionVertex.d_position = glm::vec3(prevPos + offsetVector, 0.0f);
d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex);
}
}
/*************************************************************************
Update the FPS graph SVGImage's Polyline
*************************************************************************/
void CustomShapesDrawingSample::updateCustomSVGImagePolyline(std::vector<glm::vec2> linePositions)
{
//! We need to scale and offset our linepoints to match the chosen SVGImage size
size_t linePosCount = linePositions.size();
for(size_t i = 0; i < linePosCount; ++i)
{
// Calculating the position with 95% horizontal scale
linePositions[i].x = linePositions[i].x * d_customSVGImageWidth * 0.95f;
// Calculating the position with 90% vertical scale and 5% vertical offset
linePositions[i].y = d_customSVGImageHeight * 0.975f - linePositions[i].y * d_customSVGImageHeight * 0.95f;
}
d_customPolyline->d_points = linePositions;
d_customSVGImageWindow->invalidate();
}
/*************************************************************************
Sets up everything we need to draw our graph into the GeometryBuffer
*************************************************************************/
void CustomShapesDrawingSample::setupCustomGeometryGraph(CEGUI::GUIContext* guiContext)
{
CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();
// GeometryBuffer used for drawing in this Sample
d_FPSGraphGeometryBuffer = &renderer->createGeometryBufferColoured();
// Calculate and save our custom graph background
setupCustomGeometryGraphBackground();
// Clearing this queue actually makes sure it's created(!)
guiContext->clearGeometry(CEGUI::RenderQueueID::Overlay);
// Subscribe handler to render overlay items
guiContext->subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
CEGUI::Event::Subscriber(&CustomShapesDrawingSample::drawFPSGraphOverlay,
this));
}
/*************************************************************************
Sets up everything we need to draw our graph using an SVGImage object
*************************************************************************/
void CustomShapesDrawingSample::setupCustomSVGImage()
{
// Create an SVGImage using the ImageManager
CEGUI::ImageManager& imageManager = CEGUI::ImageManager::getSingleton();
d_customSVGImage = static_cast<SVGImage*>(&imageManager.create("SVGImage", "FPSGraphSVG"));
// Create an SVGData object
CEGUI::SVGDataManager& svgDataManager = CEGUI::SVGDataManager::getSingleton();
d_customSVGData = &svgDataManager.create(CEGUI::String("FPSGraphCustomShape"));
// Set the desired size of the SVGData
d_customSVGData->setWidth(d_customSVGImageWidth);
d_customSVGData->setHeight(d_customSVGImageHeight);
// Set the pointer to the SVGData for the SVGImage
d_customSVGImage->setSVGData(d_customSVGData);
// We make our SVGImage the same size as the SVGData
const Rectf imageArea(glm::vec2(0, 0), CEGUI::Sizef(d_customSVGData->getWidth(), d_customSVGData->getHeight()));
d_customSVGImage->setImageArea(imageArea);
// We create a graph background consisting of a grey background and some lines for better readability
setupCustomSVGImageGraphBackground(*d_customSVGData);
// We create polyline object for the visualisation of the last FPS values. It contains no points yet.
std::vector<glm::vec2> pointsList;
d_customPolyline = new SVGPolyline(SVGPaintStyle(), glm::mat3x3(1.0f), pointsList);
d_customPolyline->d_paintStyle.d_stroke.d_colour = glm::vec3(0.0f, 1.0f, 0.0f);
d_customPolyline->d_paintStyle.d_strokeLinejoin = SVGPaintStyle::SVGLinejoin::Round;
d_customPolyline->d_paintStyle.d_strokeWidth = 2.0f;
//By default the SVG standard has the default fill set to black. We do not want any fill so we switch it to "none".
d_customPolyline->d_paintStyle.d_fill.d_none = true;
//We add the created shape to the SVGData object
d_customSVGData->addShape(d_customPolyline);
}
/*************************************************************************
Refreshes the maximum value that will be visualised in the graph
*************************************************************************/
void CustomShapesDrawingSample::refreshFPSMaxGraphValue()
{
d_FPSMaxGraphValue = 0;
size_t lastFPSValuesCount = d_lastFPSValues.size();
for(size_t i = 0; i < lastFPSValuesCount; ++i)
d_FPSMaxGraphValue = std::max(d_FPSMaxGraphValue, d_lastFPSValues[i]);
}
/*************************************************************************
Creates a checkbox to let the user choose to display randomised or real FPS value
*************************************************************************/
void CustomShapesDrawingSample::createCheckboxShowRealFPS()
{
WindowManager& winMgr = WindowManager::getSingleton();
// We create a button and subscribe to its click events
ToggleButton* checkboxShowRealFPS = static_cast<CEGUI::ToggleButton*>(winMgr.createWindow("WindowsLook/Checkbox"));
checkboxShowRealFPS->setArea(
CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.13f)),
CEGUI::USize(cegui_reldim(0.25f), cegui_reldim(0.035f)));
checkboxShowRealFPS->setHorizontalAlignment(HorizontalAlignment::Centre);
checkboxShowRealFPS->setText("Show randomly generated FPS values");
checkboxShowRealFPS->subscribeEvent(ToggleButton::EventSelectStateChanged, Event::Subscriber(&CustomShapesDrawingSample::handleToggleButtonShowRandomisedFpsSelectionChanged, this));
checkboxShowRealFPS->setSelected(true);
d_root->addChild(checkboxShowRealFPS);
}
/*************************************************************************
Creates a label that will display our last FPS value
*************************************************************************/
void CustomShapesDrawingSample::createLastFPSLabel()
{
WindowManager& winMgr = WindowManager::getSingleton();
// We create a button and subscribe to its click events
d_lastFPSLabel = winMgr.createWindow("Generic/Label");
d_lastFPSLabel->setArea(
CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.18f)),
CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(0.035f)));
d_lastFPSLabel->setHorizontalAlignment(HorizontalAlignment::Centre);
d_root->addChild(d_lastFPSLabel);
}
/*************************************************************************
Creates a label that contains a description of what is seen in the sample
*************************************************************************/
void CustomShapesDrawingSample::createDescriptionLabel()
{
WindowManager& winMgr = WindowManager::getSingleton();
// We create a button and subscribe to its click events
CEGUI::Window* descriptionLabel = winMgr.createWindow("Generic/Label");
descriptionLabel->setArea(
CEGUI::UVector2(cegui_reldim(0.0f), cegui_absdim(400.0f)),
CEGUI::USize(cegui_reldim(0.8f), cegui_reldim(0.25f)));
descriptionLabel->setHorizontalAlignment(HorizontalAlignment::Centre);
descriptionLabel->setProperty("HorzFormatting", "CentreAligned");
if (descriptionLabel->isPropertyPresent("WordWrap"))
descriptionLabel->setProperty("WordWrap", "true");
d_root->addChild(descriptionLabel);
descriptionLabel->setText("The left graph is rendered directly into a GeometryBuffer and rendered as overlay."
"The right graph is created using an SVGImage with modified SVGData and is then used in the same way as a regular CEGUI image"
" - it is set as a property for a window that renders the image. \n\n"
"The benefit of creating custom geometry by using an SVGImage and its SVGData is that it can be conveniently added to a CEGUI Window "
"and that defining primitive objects, such as lines, rectangles etc., is easier. Additionally, the internal CEGUI SVG classes which "
"create the geometry offer an anti-aliasing option that delivers anti-aliasing at almost no extra performance cost for the GPU.");
}
/*************************************************************************
Event handler for the FPS value checkbox selection change
*************************************************************************/
bool CustomShapesDrawingSample::handleToggleButtonShowRandomisedFpsSelectionChanged(const CEGUI::EventArgs& args)
{
const CEGUI::WindowEventArgs& winArgs = static_cast<const CEGUI::WindowEventArgs&>(args);
CEGUI::ToggleButton* checkbox = static_cast<CEGUI::ToggleButton*>(winArgs.window);
d_useRealFPS = !checkbox->isSelected();
return true;
}
/*************************************************************************
Updates everything needed for the graphs and then the graphs themselves
*************************************************************************/
void CustomShapesDrawingSample::updateFPSData(int newFPSValue)
{
//Update the window displaying the current FPS as text
std::stringstream sstream;
sstream << newFPSValue;
d_lastFPSLabel->setText(CEGUI::String("Currently recorded FPS: " + sstream.str()));
d_lastFPSValues.pop_front();
d_lastFPSValues.push_back(newFPSValue);
refreshFPSMaxGraphValue();
//Update the graphs
updateFPSGraphs();
}
/*************************************************************************
Sets up the background of the GeometryBuffer-based graph
*************************************************************************/
void CustomShapesDrawingSample::setupCustomGeometryGraphBackground()
{
// Add a grey background quad
static const glm::vec2 topLeft(0.0f, 0.0f);
static const glm::vec2 bottomLeft(0.0f, d_customGeometryGraphHeight);
static const glm::vec2 topRight(d_customGeometryGraphWidth * 0.9f + d_customGeometryGraphWidth * 0.05f, 0.0f);
static const glm::vec2 bottomRight(d_customGeometryGraphWidth * 0.9f + d_customGeometryGraphWidth * 0.05f, d_customGeometryGraphHeight);
// Defining some colours we will use
static const CEGUI::Colour backgroundQuadColour(0.3f, 0.3f, 0.3f, 1.0f);
static const CEGUI::Colour lineColour(0.5f, 0.5f, 0.5f, 1.0f);
CEGUI::ColouredVertex backgroundQuadVertex;
backgroundQuadVertex.setColour(backgroundQuadColour);
backgroundQuadVertex.d_position = glm::vec3(topLeft, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex);
backgroundQuadVertex.d_position = glm::vec3(bottomLeft, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex);
backgroundQuadVertex.d_position = glm::vec3(topRight, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex);
backgroundQuadVertex.d_position = glm::vec3(topRight, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex);
backgroundQuadVertex.d_position = glm::vec3(bottomLeft, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex);
backgroundQuadVertex.d_position = glm::vec3(bottomRight, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex);
// We save some horizontical line vertices that we will use for our graph's background.
CEGUI::ColouredVertex linePositionVertex;
linePositionVertex.setColour(lineColour);
size_t lineCount = 7;
for (size_t i = 0; i < lineCount; ++i)
{
const float currentHeight = d_customGeometryGraphHeight * i / (lineCount - 1);
const glm::vec2 linePointBegin(0.0f, currentHeight);
const glm::vec2 linePointEnd(d_customGeometryGraphWidth, currentHeight);
glm::vec2 offsetVector(0.0f, 0.5f);
linePositionVertex.d_position = glm::vec3(linePointBegin - offsetVector, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex);
linePositionVertex.d_position = glm::vec3(linePointEnd - offsetVector, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex);
linePositionVertex.d_position = glm::vec3(linePointEnd + offsetVector, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex);
linePositionVertex.d_position = glm::vec3(linePointEnd + offsetVector, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex);
linePositionVertex.d_position = glm::vec3(linePointBegin - offsetVector, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex);
linePositionVertex.d_position = glm::vec3(linePointBegin + offsetVector, 0.0f);
d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex);
}
}
/*************************************************************************
Creates the labels that we will use to display the FPS values next to the GeometryBuffer-based graph
*************************************************************************/
void CustomShapesDrawingSample::createCustomGeometryFPSLabels()
{
WindowManager& winMgr = WindowManager::getSingleton();
// We create a button and subscribe to its click events
d_customGeometryFPSLabel1 = winMgr.createWindow("Generic/Label");
d_customGeometryFPSLabel1->setSize(CEGUI::USize(cegui_absdim(100.0f), cegui_reldim(0.035f)));
d_customGeometryFPSLabel1->setProperty("HorzFormatting", "LeftAligned");
d_root->addChild(d_customGeometryFPSLabel1);
d_customGeometryFPSLabel1->setFont("DejaVuSans-10");
// We create a button and subscribe to its click events
d_customGeometryFPSLabel2 = winMgr.createWindow("Generic/Label");
d_customGeometryFPSLabel2->setSize(CEGUI::USize(cegui_absdim(100.0f), cegui_reldim(0.035f)));
d_customGeometryFPSLabel2->setProperty("HorzFormatting", "LeftAligned");
d_root->addChild(d_customGeometryFPSLabel2);
d_customGeometryFPSLabel2->setFont("DejaVuSans-10");
// We create a button and subscribe to its click events
d_customGeometryFPSLabel3 = winMgr.createWindow("Generic/Label");
d_customGeometryFPSLabel3->setSize(CEGUI::USize(cegui_absdim(100.0f), cegui_reldim(0.035f)));
d_customGeometryFPSLabel3->setProperty("HorzFormatting", "LeftAligned");
d_root->addChild(d_customGeometryFPSLabel3);
d_customGeometryFPSLabel3->setFont("DejaVuSans-10");
}
/*************************************************************************
Updates the labels we will display next to the graph made with the GeometryBuffer
*************************************************************************/
void CustomShapesDrawingSample::updateCustomGeometryFPSLabels()
{
//Calculate our top position with the half of the window's height as offset for centering
float absoluteHeight = d_customGeometryFPSLabel1->getUnclippedOuterRect().get().getHeight();
float centeredPositionTop = 250.0f - absoluteHeight * 0.5f;
std::stringstream sstream;
d_customGeometryFPSLabel1->setPosition(CEGUI::UVector2(cegui_absdim(550.0f + 2.0f), cegui_absdim(centeredPositionTop + 100.0f)));
d_customGeometryFPSLabel1->setText(CEGUI::String("0"));
d_customGeometryFPSLabel2->setPosition(CEGUI::UVector2(cegui_absdim(550.0f + 2.0f), cegui_absdim(centeredPositionTop + 100.f * 0.5f)));
unsigned int halfMaxValue = d_FPSMaxGraphValue / 2;
sstream << halfMaxValue;
d_customGeometryFPSLabel2->setText(sstream.str());
sstream.str("");
d_customGeometryFPSLabel3->setPosition(CEGUI::UVector2(cegui_absdim(550.0f + 2.0f), cegui_absdim(centeredPositionTop)));
sstream << d_FPSMaxGraphValue;
d_customGeometryFPSLabel3->setText(sstream.str());
}
/*************************************************************************
Creates the labels we will display next to the graph using the SVGImage
*************************************************************************/
void CustomShapesDrawingSample::createCustomSVGImageFPSLabels()
{
WindowManager& winMgr = WindowManager::getSingleton();
// We create a button and subscribe to its click events
d_customSVGImageFPSLabel1 = winMgr.createWindow("Generic/Label");
d_customSVGImageFPSLabel1->setSize(CEGUI::USize(cegui_reldim(0.3f), cegui_reldim(0.15f)));
d_customSVGImageFPSLabel1->setProperty("HorzFormatting", "LeftAligned");
d_customSVGImageFrameWindow->addChild(d_customSVGImageFPSLabel1);
d_customSVGImageFPSLabel1->setFont("DejaVuSans-10");
// We create a button and subscribe to its click events
d_customSVGImageFPSLabel2 = winMgr.createWindow("Generic/Label");
d_customSVGImageFPSLabel2->setSize(CEGUI::USize(cegui_reldim(0.3f), cegui_reldim(0.15f)));
d_customSVGImageFPSLabel2->setProperty("HorzFormatting", "LeftAligned");
d_customSVGImageFrameWindow->addChild(d_customSVGImageFPSLabel2);
d_customSVGImageFPSLabel2->setFont("DejaVuSans-10");
// We create a button and subscribe to its click events
d_customSVGImageFPSLabel3 = winMgr.createWindow("Generic/Label");
d_customSVGImageFPSLabel3->setSize(CEGUI::USize(cegui_reldim(0.3f), cegui_reldim(0.15f)));
d_customSVGImageFPSLabel3->setProperty("HorzFormatting", "LeftAligned");
d_customSVGImageFrameWindow->addChild(d_customSVGImageFPSLabel3);
d_customSVGImageFPSLabel3->setFont("DejaVuSans-10");
}
/*************************************************************************
Updates the labels we will display next to the graph using the SVGImage
*************************************************************************/
void CustomShapesDrawingSample::updateCustomSVGImageFPSLabels()
{
//Calculate our top position with the half of the window's height as offset for centering
float absoluteHeight = d_customSVGImageFPSLabel1->getUnclippedOuterRect().get().getHeight();
float centeredPositionOffset = -absoluteHeight * 0.5f;
std::stringstream sstream;
//We horizontically position the windows after the graph SVGImage window
CEGUI::UDim labelPosX = CEGUI::UDim(0.75f, 2.0f);
//The vertical position is calculated from the image and window heights and results in a fixed value for the relative dimension.
d_customSVGImageFPSLabel1->setPosition(CEGUI::UVector2(labelPosX, CEGUI::UDim(0.9275f, centeredPositionOffset)));
d_customSVGImageFPSLabel1->setText(CEGUI::String("0"));
d_customSVGImageFPSLabel2->setPosition(CEGUI::UVector2(labelPosX, CEGUI::UDim(0.5f, centeredPositionOffset)));
unsigned int halfMaxValue = d_FPSMaxGraphValue / 2;
sstream << halfMaxValue;
d_customSVGImageFPSLabel2->setText(sstream.str());
sstream.str("");
d_customSVGImageFPSLabel3->setPosition(CEGUI::UVector2(labelPosX, CEGUI::UDim(0.0725f, centeredPositionOffset)));
sstream << d_FPSMaxGraphValue;
d_customSVGImageFPSLabel3->setText(sstream.str());
}
/*************************************************************************
Sets up the background of the SVGImage-based graph
*************************************************************************/
void CustomShapesDrawingSample::setupCustomSVGImageGraphBackground(CEGUI::SVGData &fpsSVGData)
{
// We make a grey quad background for the graph. We offset its position by 2.5% of the height and
// make the total height of the rect 95% of the image height. We will later do the same with our lines
// so that their strokes won't be clipped by the image's area.
SVGRect* svg_rect = new SVGRect(SVGPaintStyle(), glm::mat3x3(1.0f),
0.0f, d_customSVGImageHeight * 0.025f,
d_customSVGImageWidth * 0.95f, d_customSVGImageHeight * 0.95f);
svg_rect->d_paintStyle.d_fill.d_colour = glm::vec3(0.3f, 0.3f, 0.3f);
// We don't want a stroke to be rendered. SVG offers a black stroke with 1 width by default.
svg_rect->d_paintStyle.d_stroke.d_none = true;
fpsSVGData.addShape(svg_rect);
//We create our background line's style
SVGPaintStyle graphBGLineStyle;
graphBGLineStyle.d_stroke.d_colour = glm::vec3(0.5f, 0.5f, 0.5f);
graphBGLineStyle.d_strokeWidth = 0.35f;
// We don't fill the full height because the strokes need some extra space
float adjustedHeight = d_customSVGImageHeight * 0.95f;
// We save some horizontical line vertices that we will use for our graph's background.
size_t lineCount = 7;
for (size_t i = 0; i < lineCount; ++i)
{
// We calculate the current height of the line vertex using an offset from the top and the modified height, so that the stroke won't get clipped by the image
const float currentHeight = d_customSVGImageHeight * 0.025f + adjustedHeight * i / static_cast<float>(lineCount - 1);
const glm::vec2 linePointBegin(0.0f, currentHeight);
const glm::vec2 linePointEnd(d_customSVGImageWidth, currentHeight);
SVGLine* currentLine = new SVGLine(graphBGLineStyle, glm::mat3x3(1.0f), linePointBegin, linePointEnd);
fpsSVGData.addShape(currentLine);
}
}
/*************************************************************************
Creates the windows which will be used to display the SVGImage graph
*************************************************************************/
void CustomShapesDrawingSample::createCustomSVGImageWindows()
{
WindowManager& winMgr = WindowManager::getSingleton();
//We create a draggable and resizable frame window that will contain our Image window.
d_customSVGImageFrameWindow = winMgr.createWindow("WindowsLook/FrameWindow");
d_customSVGImageFrameWindow->setArea(
CEGUI::UVector2(cegui_reldim(0.5f), cegui_reldim(0.29f)),
CEGUI::USize(cegui_absdim(490.0f), cegui_absdim(160.0f)));
d_root->addChild(d_customSVGImageFrameWindow);
d_customSVGImageFrameWindow->subscribeEvent(CEGUI::Window::EventSized,
CEGUI::Event::Subscriber(&CustomShapesDrawingSample::handleSVGImageFrameWindowSizeChanged,
this));
//We create the image window through which our custom SVGImage will be rendered.
d_customSVGImageWindow = winMgr.createWindow("Generic/Image");
d_customSVGImageWindow->setArea(
CEGUI::UVector2(cegui_reldim(0.05f), cegui_reldim(0.05f)),
CEGUI::USize(cegui_reldim(0.7f), cegui_reldim(0.9f)));
d_customSVGImageFrameWindow->addChild(d_customSVGImageWindow);
d_customSVGImageWindow->setProperty("Image", "FPSGraphSVG");
}
/*************************************************************************
Display size change handler
*************************************************************************/
bool CustomShapesDrawingSample::handleDisplaySizeChange(const CEGUI::EventArgs&)
{
updateCustomGeometryFPSLabels();
updateCustomSVGImageFPSLabels();
return false;
}
/*************************************************************************
Handler for size changes of the custom-SVGImage FrameWindow
*************************************************************************/
bool CustomShapesDrawingSample::handleSVGImageFrameWindowSizeChanged
(const CEGUI::EventArgs&)
{
updateCustomSVGImageFPSLabels();
return false;
}
|
#include <iostream>
#include <string>
#include "Card.h"
using namespace std;
// BlackJack::BlackJack () {
// card_deck = new string [52];
// }
Card::Card(){
}
Card::~Card(){
}
void Card::assignValues(char suit, char value){
_suit = suit;
_value = value;
switch (_value) {
case 11:
_weight = 1; // Ace = 1;
break;
case 12:
case 13:
case 14:
_weight = 10; // Jack, Queen, King = 10;
break;
default:
_weight = value; // КАК ЭТО? - char - это число от −128 до 127 , символом он становится только при печати.
// Поэтому, char преобразуется в int без вопросов, вот обратно с вопросами,
// потому что int может не уместиться в char (но тоже не ошибка, если знаешь, что делаешь)
break;
}
}
void Card::print(){
// если и suit и value - это оба char - как это они в switch могут быть переменными - числами?
// см. пояснения line 35 : _weight = value;
switch (_value) {
case 11:
cout << "Ace";
break;
case 12:
cout << "Jack";
break;
case 13:
cout << "Queen";
break;
case 14:
cout << "King";
break;
default:
// cout<< выводит символ, если аргумент char, а нам надо число чтобы напечатал - надо для этого аргумент сделать int.
// вот это - (int)_value - из char (или другого какого типа) делает int. это объяснение лженаучное, но самое простое ))
cout << ((int)_value);
break;
}
switch (_suit) {
case 0:
cout << " of Spades";
break;
case 1:
cout << " of Clubs";
break;
case 2:
cout << " of Diamonds";
break;
case 3:
cout << " of Hearts";
break;
}
}
int Card::weight(){
return _weight;
}
/*
int print_card_value(int card){
using namespace std;
switch(card){
case 1:
cout << "You got an Ace" << endl;
return 1;
break;
case 11:
cout << "You got a Jack" << endl;
return 10;
break;
case 12:
cout << "You got a Queen" << endl;
return 10;
break;
case 13:
cout << "You got a King" << endl;
return 10;
break;
default:
cout << "You got a " << card << endl;
return card;
break;
}
}
*/
|
#ifndef _HS_SFM_BUNDLE_ADJUSTMENT_CAMERA_SHARED_GRADIENT_DELTA_X_DOT_PRODUCT_CALCULATOR_HPP_
#define _HS_SFM_BUNDLE_ADJUSTMENT_CAMERA_SHARED_GRADIENT_DELTA_X_DOT_PRODUCT_CALCULATOR_HPP_
#include "hs_math/linear_algebra/eigen_macro.hpp"
#include "hs_sfm/bundle_adjustment/camera_shared_vector_function.hpp"
#include "hs_sfm/bundle_adjustment/camera_shared_gradient.hpp"
namespace hs
{
namespace sfm
{
namespace ba
{
template <typename _Scalar>
class CameraSharedGradientDeltaXDotProductCalculator
{
public:
typedef _Scalar Scalar;
typedef CameraSharedVectorFunction<Scalar> VectorFunction;
typedef typename VectorFunction::Index Index;
typedef typename VectorFunction::XVector DeltaXVector;
typedef CameraSharedGradient<Scalar> Gradient;
Scalar operator() (const Gradient& gradient,
const DeltaXVector& delta_x) const
{
Index x_size = gradient.GetXSize();
Scalar dot_product = Scalar(0);
for (Index i = 0; i < x_size; i++)
{
dot_product += gradient[i] * delta_x[i];
}
return dot_product;
}
};
}
}
}
#endif
|
/*
* Copyright (c) 2019 Eric Lange
*
* Distributed under the MIT License. See LICENSE.md at
* https://github.com/LiquidPlayer/caraml-core for terms and conditions.
*/
#include "node.h"
#include "caraml-core.h"
using namespace v8;
void Init(Local<Object> target)
{
}
NODE_MODULE_CONTEXT_AWARE(caramlcore,Init)
void register_caramlcore()
{
_register_caramlcore();
}
|
/*
* support.h
*
* Created on: Sep 6, 2016
* Author: nigel
*/
#ifndef SUPPORT_H_
#define SUPPORT_H_
#include <stdlib.h>
#include <string>
#include <ctime>
using namespace std;
//////////////////My functions/////////////////////
int getCalendarDate(void);
int string2int(string);
int pow(int, int);
///////////////////////////////////////////////////
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#include <sys/time.h>
#include <sys/resource.h>
#elif defined(_WIN32)
#include <time.h>
#endif
double getCPUTime(void);
int randomInRange(const int start, const int end);
#endif /* SUPPORT_H_ */
|
class Solution {
public:
bool isValid(string s) {
if(s.size()==0)return true;
stack<char>stk;
for(char ch:s)
{
if(ch=='('||ch=='{'||ch=='[')
stk.push(ch);
else
{
if(stk.empty())return false;
if(ch==')'&&stk.top()!='(' )return false;
else if(ch=='}'&&stk.top()!='{')return false;
else if(ch==']'&&stk.top()!='[')return false;
else
stk.pop();
}
}
if(stk.size()==0)
return true;
else
return false;
}
}
|
/*
编译运行
g++ xx.cpp
./xx.out
*/
// 导入包
#include <iostream>
// 命名空间
using namespace std;
// 自定义函数
int example(char s){
return s+"ok";
}
// 内联函数: 编译时,编译器会把该函数的代码副本放置在每个调用该函数的地方(类中函数默认inline)
inline char bb(){
return "bb";
}
// 主函数
int main(){
example("001");
}
|
#include "content\Singularity.Content.h"
namespace Singularity
{
namespace Content
{
class IModelImporter : public Singularity::Content::IContentImporter
{
protected:
#pragma region Properties
virtual const int Get_ModelCount() = 0;
#pragma endregion
#pragma region Methods
virtual Singularity::Components::GameObject* LoadModel(unsigned index) = 0;
virtual Singularity::Graphics::Mesh* LoadMesh(unsigned index) = 0;
virtual Singularity::Graphics::Material* LoadMaterial(unsigned index) = 0;
#pragma endregion
friend class ModelLoader;
};
}
}
|
#ifndef BOT_H
#define BOT_H
#include <QMutex>
#include "cell.h"
#include "collider.h"
#include "customscene.h"
#include "config.h"
class Bot : public QThread, public Cell
{
public:
Bot(CustomScene* map);
void run();
char getDirection() const;
Collider *getBotCollider() const;
private:
Cell* botCell;
Cell* target;
Cell* fetch;
Collider* botCollider;
CustomScene* map;
char direction;
bool targetTargeted;
QMutex mutex_direction;
void calcDirection();
};
#endif // BOT_H
|
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
int findSpecialInteger(vector<int>& arr) {
unordered_map<int, int> m;
for (auto elem : arr) {
if (m.count(elem)) {
++m[elem];
} else {
m[elem] = 1;
}
if (m[elem] * 4 > arr.size()) return elem;
}
return 0;
}
};
|
#include "lab/dialogs/class_variables.h"
#include "lab/labv2_internal.h"
#include "ship/ship.h"
#include "ship/shipfx.h"
#include "weapon/weapon.h"
void Variables::open(Button* /*caller*/) {
if (dialogWindow == nullptr) {
dialogWindow = (DialogWindow*)getLabManager()->Screen->Add(new DialogWindow("Class Variables", gr_screen.center_offset_x + gr_screen.center_w - 285,
gr_screen.center_offset_y + 200));
Assert(Opener != nullptr);
dialogWindow->SetOwner(Opener->getDialog());
}
update(getLabManager()->CurrentMode, getLabManager()->CurrentClass);
}
void Variables::update(LabMode newLabMode, int classIndex) {
if (dialogWindow == nullptr)
return;
int y = 0;
dialogWindow->DeleteChildren();
ship_info* sip = nullptr;
weapon_info* wip = nullptr;
if (classIndex > -1) {
switch (newLabMode) {
case LabMode::Ship:
sip = &Ship_info[classIndex];
addVariable(&y, "Name", sip->name);
addVariable(&y, "Species", sip->species);
addVariable(&y, "Type", sip->class_type);
addVariable(&y, "Default Team Color", sip->default_team_name);
addHeader(y, "Physics");
addVariable(&y, "Density", sip->density);
addVariable(&y, "Damp", sip->damp);
addVariable(&y, "Rotdamp", sip->rotdamp);
addVariable(&y, "Max vel (x)", sip->max_vel.xyz.x);
addVariable(&y, "Max vel (y)", sip->max_vel.xyz.y);
addVariable(&y, "Max vel (z)", sip->max_vel.xyz.z);
addVariable(&y, "Warp in speed", Warp_params[sip->warpin_params_index].speed);
addVariable(&y, "Warp out speed", Warp_params[sip->warpout_params_index].speed);
addHeader(y, "Stats");
addVariable(&y, "Shields", sip->max_shield_strength);
addVariable(&y, "Hull", sip->max_hull_strength);
addVariable(&y, "Subsys repair rate", sip->subsys_repair_rate);
addVariable(&y, "Subsys repair max", sip->subsys_repair_max);
addVariable(&y, "Hull repair rate", sip->hull_repair_rate);
addVariable(&y, "Hull repair max", sip->hull_repair_max);
addVariable(&y, "Countermeasures", sip->cmeasure_max);
addVariable(&y, "HUD Icon", sip->shield_icon_index);
addHeader(y, "Power");
addVariable(&y, "Power output", sip->power_output);
addVariable(&y, "Max oclk speed", sip->max_overclocked_speed);
addVariable(&y, "Max weapon reserve", sip->max_weapon_reserve);
addHeader(y, "Afterburner");
addVariable(&y, "Fuel", sip->afterburner_fuel_capacity);
addVariable(&y, "Burn rate", sip->afterburner_burn_rate);
addVariable(&y, "Recharge rate", sip->afterburner_recover_rate);
addHeader(y, "Explosion");
addVariable(&y, "Inner radius", sip->shockwave.inner_rad);
addVariable(&y, "Outer radius", sip->shockwave.outer_rad);
addVariable(&y, "Damage", sip->shockwave.damage);
addVariable(&y, "Blast", sip->shockwave.blast);
addVariable(&y, "Propagates", sip->explosion_propagates);
addVariable(&y, "Shockwave speed", sip->shockwave.speed);
addVariable(&y, "Shockwave count", sip->shockwave_count);
// techroom
addHeader(y, "Techroom");
addVariable(&y, "Closeup zoom", sip->closeup_zoom);
addVariable(&y, "Closeup pos (x)", sip->closeup_pos.xyz.x);
addVariable(&y, "Closeup pos (y)", sip->closeup_pos.xyz.y);
addVariable(&y, "Closeup pos (z)", sip->closeup_pos.xyz.z);
break;
case LabMode::Weapon:
wip = &Weapon_info[classIndex];
addVariable(&y, "Name", wip->name);
addVariable(&y, "Subtype", wip->subtype);
// physics
addHeader(y, "Physics");
addVariable(&y, "Mass", wip->mass);
addVariable(&y, "Max speed", wip->max_speed);
addVariable(&y, "Lifetime", wip->lifetime);
addVariable(&y, "Range", wip->weapon_range);
addVariable(&y, "Min Range", wip->weapon_min_range);
addHeader(y, "Damage");
addVariable(&y, "Fire wait", wip->fire_wait);
addVariable(&y, "Damage", wip->damage);
addVariable(&y, "Armor factor", wip->armor_factor);
addVariable(&y, "Shield factor", wip->shield_factor);
addVariable(&y, "Subsys factor", wip->subsystem_factor);
addHeader(y, "Armor");
addVariable(&y, "Damage type", wip->damage_type_idx);
addHeader(y, "Shockwave");
addVariable(&y, "Speed", wip->shockwave.speed);
addHeader(y, "Missiles");
addVariable(&y, "Turn time", wip->turn_time);
addVariable(&y, "FOV", wip->fov);
addVariable(&y, "Min locktime", wip->min_lock_time);
addVariable(&y, "Pixels/sec", wip->lock_pixels_per_sec);
addVariable(&y, "Catchup pixels/sec", wip->catchup_pixels_per_sec);
addVariable(&y, "Catchup pixel pen.", wip->catchup_pixel_penalty);
addVariable(&y, "Swarm count", wip->swarm_count);
addVariable(&y, "Swarm wait", wip->SwarmWait);
break;
default:
return;
}
}
}
template<typename T>
void Variables::addVariable(int* Y, const char* var_name, T &value) {
int y = 0;
Text* new_text;
if (Y) {
y = *Y;
}
// variable
dialogWindow->AddChild(new Text((var_name), (var_name), 0, y, 150));
// edit box
SCP_stringstream value_str;
value_str << value;
new_text = (Text*)dialogWindow->AddChild(new Text(SCP_string((var_name)) + SCP_string("Editbox"), value_str.str(),
160, y, 100, gr_get_font_height() + 2));
if (Y) {
*Y += new_text->GetHeight() + 2;
}
}
Text* Variables::addHeader(int& y, const SCP_string& text) {
auto retval = (Text*)dialogWindow->AddChild(new Text(text, text, 80, y + 8, 100));
y += retval->GetHeight() + 10;
return retval;
}
|
struct Verticies;
struct Inventory;
meta() struct Player
{
//u32 id = 0, weapon = 1;
float health = 100.0f;
float speed;
Verticies *mesh, *model;
Inventory *inventory;
};
meta()
int result;
meta()
void proc0() { puts("proc0"); }
meta()
int sum(int x, int y) { return x + y; }
meta()
void proc1(int *ptr0, float* *ptr1, double* ptr2) { }
|
#pragma once
#include "Logger.hpp"
#include "LogSpace.hpp"
class StringSumSquareBrackets
{
public:
StringSumSquareBrackets() = default;
~StringSumSquareBrackets() = default;
StringSumSquareBrackets(StringSumSquareBrackets &&) = default;
StringSumSquareBrackets& operator=(StringSumSquareBrackets &&) = default;
StringSumSquareBrackets(const StringSumSquareBrackets &) = default;
StringSumSquareBrackets& operator=(const StringSumSquareBrackets &) = default;
void sum(const std::string& s);
std::string getSumedString() const;
private:
std::string _sumedString;
Logger _log {LogSpace::MessageFramework};
};
|
/////////////////////////////////////////////////////////////////////////////
// Name: wx/statusbr.h
// Purpose: wxStatusBar class interface
// Author: Vadim Zeitlin
// Modified by:
// Created: 05.02.00
// RCS-ID: $Id: statusbr.h 59568 2009-03-15 19:45:34Z FM $
// Copyright: (c) Vadim Zeitlin
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_STATUSBR_H_BASE_
#define _WX_STATUSBR_H_BASE_
#include "wx/defs.h"
#if wxUSE_STATUSBAR
#include "wx/window.h"
#include "wx/list.h"
#include "wx/dynarray.h"
extern WXDLLIMPEXP_DATA_CORE(const char) wxStatusBarNameStr[];
// ----------------------------------------------------------------------------
// wxStatusBar constants
// ----------------------------------------------------------------------------
// style flags for fields
#define wxSB_NORMAL 0x0000
#define wxSB_FLAT 0x0001
#define wxSB_RAISED 0x0002
// ----------------------------------------------------------------------------
// wxStatusBarPane: an helper for wxStatusBar
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxStatusBarPane
{
// only wxStatusBarBase can access our internal members and modify them:
friend class WXDLLIMPEXP_FWD_CORE wxStatusBarBase;
public:
wxStatusBarPane(int style = wxSB_NORMAL, size_t width = 0)
: m_nStyle(style), m_nWidth(width) { m_arrStack.Add(wxEmptyString); }
int GetWidth() const
{ return m_nWidth; }
int GetStyle() const
{ return m_nStyle; }
const wxArrayString& GetStack() const
{ return m_arrStack; }
// use wxStatusBar setter functions to modify a wxStatusBarPane
protected:
int m_nStyle;
int m_nWidth; // the width maybe negative, indicating a variable-width field
// this is the array of the stacked strings of this pane; note that this
// stack does include also the string currently displayed in this pane
// as the version stored in the native status bar control is possibly
// ellipsized; note that arrStack.Last() is the top of the stack
// (i.e. the string shown in the status bar)
wxArrayString m_arrStack;
};
WX_DECLARE_OBJARRAY(wxStatusBarPane, wxStatusBarPaneArray);
// ----------------------------------------------------------------------------
// wxStatusBar: a window near the bottom of the frame used for status info
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxStatusBarBase : public wxWindow
{
public:
wxStatusBarBase();
virtual ~wxStatusBarBase();
// field count
// -----------
// set the number of fields and call SetStatusWidths(widths) if widths are
// given
virtual void SetFieldsCount(int number = 1, const int *widths = NULL);
int GetFieldsCount() const { return m_panes.GetCount(); }
// field text
// ----------
virtual void SetStatusText(const wxString& text, int number = 0)
{ m_panes[number].GetStack().Last() = text; }
virtual wxString GetStatusText(int number = 0) const
{ return m_panes[number].GetStack().Last(); }
const wxArrayString& GetStatusStack(int n) const
{ return m_panes[n].GetStack(); }
void PushStatusText(const wxString& text, int number = 0);
void PopStatusText(int number = 0);
// fields widths
// -------------
// set status field widths as absolute numbers: positive widths mean that
// the field has the specified absolute width, negative widths are
// interpreted as the sizer options, i.e. the extra space (total space
// minus the sum of fixed width fields) is divided between the fields with
// negative width according to the abs value of the width (field with width
// -2 grows twice as much as one with width -1 &c)
virtual void SetStatusWidths(int n, const int widths[]);
int GetStatusWidth(int n) const
{ return m_panes[n].GetWidth(); }
// field styles
// ------------
// Set the field style. Use either wxSB_NORMAL (default) for a standard 3D
// border around a field, wxSB_FLAT for no border around a field, so that it
// appears flat or wxSB_POPOUT to make the field appear raised.
// Setting field styles only works on wxMSW
virtual void SetStatusStyles(int n, const int styles[]);
int GetStatusStyle(int n) const
{ return m_panes[n].GetStyle(); }
// geometry
// --------
// Get the position and size of the field's internal bounding rectangle
virtual bool GetFieldRect(int i, wxRect& rect) const = 0;
// sets the minimal vertical size of the status bar
virtual void SetMinHeight(int height) = 0;
// get the dimensions of the horizontal and vertical borders
virtual int GetBorderX() const = 0;
virtual int GetBorderY() const = 0;
// miscellaneous
// -------------
const wxStatusBarPane& GetField(int n) const
{ return m_panes[n]; }
// wxWindow overrides:
// don't want status bars to accept the focus at all
virtual bool AcceptsFocus() const { return false; }
// the client size of a toplevel window doesn't include the status bar
virtual bool CanBeOutsideClientArea() const { return true; }
protected:
virtual wxBorder GetDefaultBorder() const { return wxBORDER_NONE; }
// calculate the real field widths for the given total available size
wxArrayInt CalculateAbsWidths(wxCoord widthTotal) const;
// the array with the pane infos:
wxStatusBarPaneArray m_panes;
// if true overrides the width info of the wxStatusBarPanes
bool m_bSameWidthForAllPanes;
wxDECLARE_NO_COPY_CLASS(wxStatusBarBase);
};
// ----------------------------------------------------------------------------
// include the actual wxStatusBar class declaration
// ----------------------------------------------------------------------------
#if defined(__WXUNIVERSAL__)
#define wxStatusBarUniv wxStatusBar
#include "wx/univ/statusbr.h"
#elif defined(__WXPALMOS__)
#define wxStatusBarPalm wxStatusBar
#include "wx/palmos/statusbr.h"
#elif defined(__WIN32__) && wxUSE_NATIVE_STATUSBAR
#include "wx/msw/statusbar.h"
#elif defined(__WXMAC__)
#define wxStatusBarMac wxStatusBar
#include "wx/generic/statusbr.h"
#include "wx/osx/statusbr.h"
#else
#define wxStatusBarGeneric wxStatusBar
#include "wx/generic/statusbr.h"
#endif
#endif // wxUSE_STATUSBAR
#endif
// _WX_STATUSBR_H_BASE_
|
#include "gui.h"
#include "file.h"
#include <iostream>
#include <QString>
#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QIcon>
using namespace std;
GUI::GUI(int argc, char** argv) {
qDebug() << "Application started" << endl;
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("cpp", &this->workerThread);
engine.load(QUrl("qrc:/qml/main.qml"));
QObject* qml = engine.rootObjects().first();
QObject::connect(qml, SIGNAL(signalRemoveCurrentTask(QString, QString)),
&this->workerThread, SLOT(onRemoveCurrentTask(QString, QString)));
QObject::connect(qml, SIGNAL(signalMoveNewTasksToCurrent()),
&this->workerThread, SLOT(onMoveNewTasksToCurrent()));
QObject::connect(qml, SIGNAL(signalAddNewTasks(QVariant, QString)),
&this->workerThread, SLOT(onAddNewTasks(QVariant, QString)));
QObject::connect(qml, SIGNAL(signalStartCurrentTasks()),
&this->workerThread, SLOT(onStartCurrentTasks()));
QObject::connect(qml, SIGNAL(signalStopCurrentTasks()),
&this->workerThread, SLOT(onStopCurrentTasks()));
QObject::connect(qml, SIGNAL(signalWorkerInvoke(QString, QVariant)),
&this->workerThread, SLOT(onWorkerInvoke(QString, QVariant)));
this->workerThread.signalStartWorker();
QObject::connect(&app, SIGNAL(aboutToQuit()), this, SLOT(onAboutToQuit()));
app.setWindowIcon(QIcon("main.png"));
app.exec();
// emit this->workerThread.signalStopWorker();
// this->workerThread.wait();
}
GUI::~GUI() {}
void GUI::onAboutToQuit() {
emit this->workerThread.signalStopWorker();
// this->workerThread.wait();
}
//void GUI::setMouseCursor(int type) {
// this->app->setOverrideCursor(QCursor(static_cast<Qt::CursorShape>(type)));
//}
|
/// @file LedDisp.cc
/// @brief LedDisp の実装ファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2006, 2013 Yusuke Matsunaga
/// All rights reserved.
#include "LedDisp.h"
BEGIN_NAMESPACE_LED
// @brief コンストラクタ
// @param[in] parent 親のウィジェット
// @param[in] flags ウィンドウフラグ
LedDisp::LedDisp(QWidget* parent,
Qt::WindowFlags flags) :
QWidget(parent, flags)
{
}
// @brief デストラクタ
LedDisp::~LedDisp()
{
}
#if 0
// @brief 初期化
// @note on_realize() 中で呼ばれる.
// @note gl_begin() と gl_end() で挟まれている.
void
GlvScene::initialize()
{
}
// @brief ウィンドウのサイズが変わったときの処理
// @note on_configure_event() 中で呼ばれる.
// @note gl_begin() と gl_end() で挟まれている.
void
GlvScene::resize()
{
}
// @brief 描画を行う.
// @note on_expose_event() 中で呼ばれる.
// @note gl_begin() と gl_end() で挟まれている.
// @note ただし gl_end() の前に swap_buffers() か glFlush()
// を行う.
void
GlvScene::draw()
{
}
// "realize" イベントハンドラ
void
GlvScene::on_realize()
{
// We need to call the base on_realize()
Gtk::DrawingArea::on_realize();
// Get GL::Drawable.
Glib::RefPtr<Gdk::GL::Drawable> gldrawable = get_gl_drawable();
// GL calls.
// *** OpenGL BEGIN ***
if ( !gldrawable->gl_begin(get_gl_context()) ) {
return;
}
initialize();
gldrawable->gl_end();
// *** OpenGL END ***
}
// "configure" イベントハンドラ
bool
GlvScene::on_configure_event(GdkEventConfigure* event)
{
// Get GL::Drawable.
Glib::RefPtr<Gdk::GL::Drawable> gldrawable = get_gl_drawable();
// GL calls.
// *** OpenGL BEGIN ***
if ( !gldrawable->gl_begin(get_gl_context()) ) {
return false;
}
resize();
gldrawable->gl_end();
// *** OpenGL END ***
return true;
}
// "expose" イベントハンドラ
bool
GlvScene::on_expose_event(GdkEventExpose* event)
{
// Get GL::Drawable.
Glib::RefPtr<Gdk::GL::Drawable> gldrawable = get_gl_drawable();
// GL calls.
// *** OpenGL BEGIN ***
if ( !gldrawable->gl_begin(get_gl_context()) ) {
return false;
}
draw();
// Swap buffers.
if ( gldrawable->is_double_buffered() ) {
gldrawable->swap_buffers();
}
else {
glFlush();
}
gldrawable->gl_end();
// *** OpenGL END ***
return true;
}
/// @brief "map" イベントハンドラ
bool
GlvScene::on_map_event(GdkEventAny* event)
{
return true;
}
/// @brief "unmap" イベントハンドラ
bool
GlvScene::on_unmap_event(GdkEventAny* event)
{
return true;
}
/// @brief "visibility notify" イベントハンドラ
bool
GlvScene::on_visibility_notify_event(GdkEventVisibility* event)
{
return true;
}
#endif
//////////////////////////////////////////////////////////////////////
// QWidget のイベントコールバック関数の再定義
//////////////////////////////////////////////////////////////////////
// paint イベント
void
LedDisp::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
QRect rect = event->rect();
#if 0
// 盤面の背景
mDispMgr->draw_ban(painter, rect);
// 駒
for (const Pos* ppos = Pos::all_list(); *ppos != kPos_NO; ++ ppos) {
Pos pos(*ppos);
ymuint8 pat_id = koma(pos).cur_pat();
mDispMgr->draw_koma(painter, pos, pat_id, rect);
if ( koma(pos).marker() ) {
// マーカーの描画
mDispMgr->draw_marker(painter, pos, rect);
}
}
Pos cpos = cursor_pos();
if ( check_cursor_disp() && cpos != kPos_NO ) {
// カーソルの描画
mDispMgr->draw_cursor(painter, cpos, rect);
}
#endif
}
// Motion notify イベント
void
LedDisp::mouseMoveEvent(QMouseEvent* event)
{
ymuint x = event->x();
ymuint y = event->y();
#if 0
Pos pos = search(x, y, mCursorPos);
if ( pos != mCursorPos ) {
// 位置が変わった.
if ( !loose_cursor() || pos != kPos_NO ) {
set_cursor_pos(pos);
}
}
#endif
}
// Leave notify イベント
void
LedDisp::leaveEvent(QEvent* event)
{
#if 0
if ( !loose_cursor() ) {
set_cursor_pos(kPos_NO);
}
#endif
}
// Button Press イベント
void
LedDisp::mousePressEvent(QMouseEvent* event)
{
ymuint x = event->x();
ymuint y = event->y();
#if 0
Pos pos = search(x, y, mCursorPos);
if ( pos != kPos_NO ) {
emit button_pressed(pos, event);
}
#endif
}
// @brief Key Press イベント
void
LedDisp::keyPressEvent(QKeyEvent* event)
{
#if 0
ymuint x;
ymuint y;
if ( mCursorPos.is_pass() ) {
x = 1;
y = 1;
}
else {
x = mCursorPos.x();
y = mCursorPos.y();
}
switch ( event->key() ) {
case Qt::Key_Left: if ( x > 1 ) -- x; break;
case Qt::Key_Up: if ( y > 1 ) -- y; break;
case Qt::Key_Right: if ( x < 8 ) ++ x; break;
case Qt::Key_Down: if ( y < 8 ) ++ y; break;
case Qt::Key_A: x = 1; break;
case Qt::Key_B: x = 2; break;
case Qt::Key_C: x = 3; break;
case Qt::Key_D: x = 4; break;
case Qt::Key_E: x = 5; break;
case Qt::Key_F: x = 6; break;
case Qt::Key_G: x = 7; break;
case Qt::Key_H: x = 8; break;
case Qt::Key_1: y = 1; break;
case Qt::Key_2: y = 2; break;
case Qt::Key_3: y = 3; break;
case Qt::Key_4: y = 4; break;
case Qt::Key_5: y = 5; break;
case Qt::Key_6: y = 6; break;
case Qt::Key_7: y = 7; break;
case Qt::Key_8: y = 8; break;
default: QWidget::keyPressEvent(event); return;
}
set_cursor_pos(Pos(x, y));
#endif
}
END_NAMESPACE_LED
|
/***********************************************************************
* created: 21/4/2013
* author: Martin Preisler
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/Animation.h"
#include "CEGUI/AnimationInstance.h"
#include "CEGUI/AnimationManager.h"
#include "CEGUI/Affector.h"
#include <boost/test/unit_test.hpp>
struct SampleAnimationSetupFixture
{
SampleAnimationSetupFixture()
{
{
d_zeroToOne = CEGUI::AnimationManager::getSingleton().createAnimation("ZeroToOne");
d_zeroToOne->setDuration(1.0f);
CEGUI::Affector* affector = d_zeroToOne->createAffector("Alpha", "float");
affector->createKeyFrame(0.0f, "0");
affector->createKeyFrame(1.0f, "1");
}
{
d_zeroDuration = CEGUI::AnimationManager::getSingleton().createAnimation("ZeroLength");
d_zeroDuration->setDuration(0.0f);
d_zeroDuration->createAffector("Alpha", "float");
}
}
~SampleAnimationSetupFixture()
{
CEGUI::AnimationManager::getSingleton().destroyAnimation(d_zeroToOne);
CEGUI::AnimationManager::getSingleton().destroyAnimation(d_zeroDuration);
}
CEGUI::Animation* d_zeroToOne;
CEGUI::Animation* d_zeroDuration;
};
BOOST_FIXTURE_TEST_SUITE(AnimationSystem, SampleAnimationSetupFixture)
BOOST_AUTO_TEST_CASE(SkipFirstStep)
{
CEGUI::AnimationInstance* instance = CEGUI::AnimationManager::getSingleton().instantiateAnimation(d_zeroToOne);
d_zeroToOne->setReplayMode(CEGUI::Animation::ReplayMode::PlayOnce);
instance->start(true);
BOOST_CHECK_CLOSE(instance->getPosition(), 0.0f, 0.0001f);
instance->step(123.0f);
BOOST_CHECK_CLOSE(instance->getPosition(), 0.0f, 0.0001f);
CEGUI::AnimationManager::getSingleton().destroyAnimationInstance(instance);
}
BOOST_AUTO_TEST_CASE(PlayOnceReplayMode)
{
CEGUI::AnimationInstance* instance = CEGUI::AnimationManager::getSingleton().instantiateAnimation(d_zeroToOne);
d_zeroToOne->setReplayMode(CEGUI::Animation::ReplayMode::PlayOnce);
instance->start(false);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.0f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.5f);
BOOST_CHECK_CLOSE(instance->getPosition(), 0.5f, 0.0001f);
instance->step(0.5f);
BOOST_CHECK_CLOSE(instance->getPosition(), 1.0f, 0.0001f);
instance->step(1.0f);
BOOST_CHECK_CLOSE(instance->getPosition(), 1.0f, 0.0001f);
CEGUI::AnimationManager::getSingleton().destroyAnimationInstance(instance);
}
BOOST_AUTO_TEST_CASE(PlayLoopReplayMode)
{
CEGUI::AnimationInstance* instance = CEGUI::AnimationManager::getSingleton().instantiateAnimation(d_zeroToOne);
d_zeroToOne->setReplayMode(CEGUI::Animation::ReplayMode::Loop);
instance->start(false);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.0f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.5f);
BOOST_CHECK_CLOSE(instance->getPosition(), 0.5f, 0.0001f);
instance->step(0.5f);
BOOST_CHECK_CLOSE(instance->getPosition(), 1.0f, 0.0001f);
instance->step(0.3f);
BOOST_CHECK_CLOSE(instance->getPosition(), 0.3f, 0.0001f);
instance->step(0.7f);
BOOST_CHECK_CLOSE(instance->getPosition(), 1.0f, 0.0001f);
CEGUI::AnimationManager::getSingleton().destroyAnimationInstance(instance);
}
BOOST_AUTO_TEST_CASE(PlayBounceReplayMode)
{
CEGUI::AnimationInstance* instance = CEGUI::AnimationManager::getSingleton().instantiateAnimation(d_zeroToOne);
d_zeroToOne->setReplayMode(CEGUI::Animation::ReplayMode::Bounce);
instance->start(false);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.0f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.5f);
BOOST_CHECK_CLOSE(instance->getPosition(), 0.5f, 0.0001f);
instance->step(0.5f);
BOOST_CHECK_CLOSE(instance->getPosition(), 1.0f, 0.0001f);
instance->step(0.3f);
BOOST_CHECK_CLOSE(instance->getPosition(), 0.7f, 0.0001f);
instance->step(0.7f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
CEGUI::AnimationManager::getSingleton().destroyAnimationInstance(instance);
}
BOOST_AUTO_TEST_CASE(ZeroDurationReplayModes)
{
{
CEGUI::AnimationInstance* instance = CEGUI::AnimationManager::getSingleton().instantiateAnimation(d_zeroDuration);
d_zeroDuration->setReplayMode(CEGUI::Animation::ReplayMode::PlayOnce);
instance->start(false);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.0f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.5f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
CEGUI::AnimationManager::getSingleton().destroyAnimationInstance(instance);
}
{
CEGUI::AnimationInstance* instance = CEGUI::AnimationManager::getSingleton().instantiateAnimation(d_zeroDuration);
d_zeroDuration->setReplayMode(CEGUI::Animation::ReplayMode::Loop);
instance->start(false);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.0f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.5f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
CEGUI::AnimationManager::getSingleton().destroyAnimationInstance(instance);
}
{
CEGUI::AnimationInstance* instance = CEGUI::AnimationManager::getSingleton().instantiateAnimation(d_zeroDuration);
d_zeroDuration->setReplayMode(CEGUI::Animation::ReplayMode::Bounce);
instance->start(false);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.0f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
instance->step(0.5f);
BOOST_CHECK_SMALL(instance->getPosition(), 0.0001f);
CEGUI::AnimationManager::getSingleton().destroyAnimationInstance(instance);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <omp.h>
#define REAL double
void calc_aux_cy(REAL *q , int qSize,
REAL *xq0 , int xq0Size,
REAL *xq1 , int xq1Size,
REAL *xq2 , int xq2Size,
REAL *xi , int xiSize,
REAL *yi , int yiSize,
REAL *zi , int ziSize,
REAL *normal0 , int normal0Size,
REAL *normal1 , int normal1Size,
REAL *normal2 , int normal2Size,
int stype,
REAL *aux , int auxSize,
REAL E);
void calc_aux_cy(REAL *q , int qSize,
REAL *xq0 , int xq0Size,
REAL *xq1 , int xq1Size,
REAL *xq2 , int xq2Size,
REAL *xi , int xiSize,
REAL *yi , int yiSize,
REAL *zi , int ziSize,
REAL *normal0 , int normal0Size,
REAL *normal1 , int normal1Size,
REAL *normal2 , int normal2Size,
int stype,
REAL *aux , int auxSize,
REAL E)
{
REAL dx_pq[xiSize], dy_pq[yiSize], dz_pq[ziSize], R_pq[xiSize];
for(int i=0; i<qSize; i++)
{
for (int j = 0; j < xiSize; j++)
{
dx_pq[j] = xi[j] - xq0[i];
dy_pq[j] = yi[j] - xq1[i];
dz_pq[j] = zi[j] - xq2[i];
}
for (int j = 0; j < xiSize; j++)
{
R_pq[j] = sqrt(dx_pq[j] * dx_pq[j] + dy_pq[j] * dy_pq[j] + dz_pq[j] * dz_pq[j]);
}
if (stype == 1)
{
for (int j = 0; j < auxSize; j++)
{
aux[j] = aux[j] - ( q[i] / ( R_pq[j] * R_pq[j] * R_pq[j] ) * (dx_pq[j] * normal0[j] + dy_pq[j] * normal1[j] + dz_pq[j] * normal2[j]) );
}
} else
{
for (int j = 0; j < auxSize; j++)
{
aux[j] = aux[j] + q[i] / (E * R_pq[j]) ;
}
}
}
};
|
//
// SMImageEditorScene.cpp
// ePubCheck
//
// Created by KimSteve on 2017. 4. 18..
// Copyright © 2017년 KimSteve. All rights reserved.
//
#include "SMImageEditorScene.h"
#include "../../SMFrameWork/Base/SMView.h"
#include "../../SMFrameWork/Base/SMImageView.h"
#include "../../SMFrameWork/Base/SMZoomView.h"
#include "../../SMFrameWork/Base/SMButton.h"
#include "../../SMFrameWork/Base/SMTableView.h"
#include "../../SMFrameWork/Base/SMPageView.h"
#include "../../SMFrameWork/Base/SMCircularListView.h"
#include "../../SMFrameWork/Base/SMSlider.h"
#include "../../SMFrameWork/Base/MeshSprite.h"
#include "../../SMFrameWork/Const/SMFontColor.h"
#include "../../SMFrameWork/Base/ShaderNode.h"
#include "../../SMFrameWork/Base/ViewAction.h"
#include "../../SMFrameWork/Util/ViewUtil.h"
#include "../../SMFrameWork/Util/cvImageUtil.h"
#include "SMImageEditorListener.h"
#include "SMImageEditorCropScene.h"
#include "SMImageEditorRotateScene.h"
#include "SMImageEditorStraightenScene.h"
#include "SMImageEditorColorScene.h"
#include "SMImageEditorStickerScene.h"
#include "SMImageEditorFilterScene.h"
#include "SMImageEditorDrawScene.h"
#include "../../SMFrameWork/Const/SMViewConstValue.h"
#define TOP_MENU_HEIGHT (SMViewConstValue::Size::TOP_MENU_HEIGHT+SMViewConstValue::Size::getStatusHeight())
#define PHOTO_MARGIN 20.0f
#define BOTTOM_MENU_HEIGHT 160.0f
#define MAX_PHOTO_SIZE 1080.0f
SMImageEditorScene::SMImageEditorScene() :
_contentView(nullptr)
, _topMenuView(nullptr)
, _bottomMenuTableView(nullptr)
, _mainMeshSprite(nullptr)
, _mainImageSprite(nullptr)
, _mainImageView(nullptr)
, _zoomView(nullptr)
, _editMenuView(nullptr)
, _adjustMenuView(nullptr)
, _magicMenuView(nullptr)
, _bEditMenuVisible(false)
, _bAdjustMenuVisible(false)
, _bMagicMenuVisible(false)
, _resultSprite(nullptr)
, _bAlreadyCrop(false)
, _tmpImageview(nullptr)
, _mainccImage(nullptr)
, _originccImage(nullptr)
, _resultccImage(nullptr)
{
}
SMImageEditorScene::~SMImageEditorScene()
{
CC_SAFE_RELEASE_NULL(_mainccImage);
CC_SAFE_RELEASE_NULL(_originccImage);
/*
CC_SAFE_RELEASE_NULL(_resultSprite);
CC_SAFE_RELEASE_NULL(_resultccImage);
CC_SAFE_RELEASE_NULL(_editMenuTableView);
CC_SAFE_RELEASE_NULL(_adjustMenuTableView);
CC_SAFE_RELEASE_NULL(_magicMenuTableView);
CC_SAFE_RELEASE_NULL(_mainImageView);
CC_SAFE_RELEASE_NULL(_zoomView);
CC_SAFE_RELEASE_NULL(_mainImageSprite);
CC_SAFE_RELEASE_NULL(_mainMeshSprite);
*/
}
bool SMImageEditorScene::init()
{
if (!SMScene::init()) {
return false;
}
cocos2d::Size s = cocos2d::Director::getInstance()->getWinSize();
_contentView = SMView::create(0, 0, 0, s.width, s.height);
_contentView->setBackgroundColor4F(cocos2d::Color4F::WHITE);
addChild(_contentView);
_topMenuView = SMView::create(0, 0, s.height-TOP_MENU_HEIGHT, s.width, TOP_MENU_HEIGHT);
_topMenuView->setBackgroundColor4F(cocos2d::Color4F::WHITE);
_contentView->addChild(_topMenuView);
SMView * topMenuBottomLine = SMView::create(0, 0, 0, s.width, 1);
topMenuBottomLine->setBackgroundColor4F(MAKE_COLOR4F(0xadafb3, 1.0f));
_topMenuView->addChild(topMenuBottomLine);
_topMenuView->setLocalZOrder(10);
auto programBundle = this->getSceneParam();
if (programBundle && programBundle->getBool("FROM_PICKER", false)) {
SMButton * backButton = SMButton::create(0, SMButton::Style::DEFAULT, 0, 0, TOP_MENU_HEIGHT, TOP_MENU_HEIGHT);
backButton->setIcon(SMButton::State::NORMAL, "images/ic_titlebar_back.png");
backButton->setIconColor(SMButton::State::NORMAL, cocos2d::Color4F(0x22/255.0f, 0x22/255.0f, 0x22/255.0f, 1.0f));
backButton->setIconColor(SMButton::State::PRESSED, cocos2d::Color4F(0x99/255.0f, 0x99/255.0f, 0x99/255.0f, 1.0f));
backButton->setPushDownScale(0.9f);
_topMenuView->addChild(backButton);
backButton->setOnClickCallback([&](SMView * view){
auto pScene = SceneTransition::SlideOutToRight::create(SceneTransition::Time::NORMAL, cocos2d::Director::getInstance()->getPreviousScene());
_director->popSceneWithTransition(pScene);
});
} else {
SMButton * closeButton = SMButton::create(0, SMButton::Style::DEFAULT, 0, 0, TOP_MENU_HEIGHT, TOP_MENU_HEIGHT);
closeButton->setIcon(SMButton::State::NORMAL, "images/popup_close.png");
closeButton->setIconColor(SMButton::State::NORMAL, cocos2d::Color4F(0x22/255.0f, 0x22/255.0f, 0x22/255.0f, 1.0f));
closeButton->setIconColor(SMButton::State::PRESSED, cocos2d::Color4F(0x99/255.0f, 0x99/255.0f, 0x99/255.0f, 1.0f));
closeButton->setPushDownScale(0.9f);
_topMenuView->addChild(closeButton);
closeButton->setOnClickCallback([&](SMView * view){
cocos2d::Director::getInstance()->getScheduler()->performFunctionInCocosThread([&]{
});
});
}
auto applyButton = SMButton::create(0, SMButton::Style::DEFAULT, s.width-110, 0, 110, 110);
applyButton->setIcon(SMButton::State::NORMAL, "images/ic_titlebar_check.png");
applyButton->setIconColor(SMButton::State::NORMAL, cocos2d::Color4F(0x22/255.0f, 0x22/255.0f, 0x22/255.0f, 1.0f));
applyButton->setIconColor(SMButton::State::PRESSED, cocos2d::Color4F(0x99/255.0f, 0x99/255.0f, 0x99/255.0f, 1.0f));
applyButton->setPushDownScale(0.9f);
_topMenuView->addChild(applyButton);
applyButton->setOnClickCallback([&](SMView * view){
_director->getScheduler()->performFunctionInCocosThread([&]{
finishEditImage();
});
});
// intent로 sprite를 받으려 했으나
// RenderTexture에서 capture를 하면 화질 손실이 있다.
// 처음 부터 받을때 Data로 받고 OpenCV에서 Resize & Rotate & Crop 등을 진행한다.
if (programBundle) {
cocos2d::Image * receiveImage = (cocos2d::Image*)programBundle->getRef("INTENT_IMAGE");
if ((float)receiveImage->getWidth()>MAX_PHOTO_SIZE || (float)receiveImage->getHeight()>MAX_PHOTO_SIZE) {
// resize image
float widhtRatio = MAX_PHOTO_SIZE/(float)receiveImage->getWidth();
float heightRatio = MAX_PHOTO_SIZE/(float)receiveImage->getHeight();
float ratio = MIN(widhtRatio, heightRatio);
cv::Mat src = cvImageUtil::ccImage2cvMat(receiveImage);
cv::Size scaleSize(receiveImage->getWidth()*ratio, receiveImage->getHeight()*ratio);
cv::Mat dst;
cv::resize(src, dst, scaleSize);
_originccImage = cvImageUtil::cvMat2ccImage(dst);
src.release();
dst.release();
} else {
_originccImage = new cocos2d::Image();
_originccImage->initWithRawData(receiveImage->getData(), receiveImage->getDataLen(), receiveImage->getWidth(), receiveImage->getHeight(), receiveImage->getBitPerPixel());
_originccImage->autorelease();
}
_originccImage->retain();
} else {
_originccImage = new cocos2d::Image();
_originccImage->initWithImageFile("images/defaults.jpg");
_originccImage->retain();
}
_mainccImage = new cocos2d::Image;
_mainccImage->initWithRawData(_originccImage->getData(), _originccImage->getDataLen(), _originccImage->getWidth(), _originccImage->getHeight(), _originccImage->getBitPerPixel());
_mainccImage->retain();
auto texture = new cocos2d::Texture2D;
texture->initWithImage(_mainccImage);
_mainccImage->release();
auto tmp = cocos2d::Sprite::createWithTexture(texture);
texture->release();
// auto tmp = (cocos2d::Sprite *)programBundle->getRef("INTENT_IMAGE");
if (tmp) {
_mainImageSprite = cocos2d::Sprite::createWithTexture(tmp->getTexture());
}
if (_mainImageSprite==nullptr) {
cocos2d::Label * noti = cocos2d::Label::createWithSystemFont("이미지가 없습니다.", SMFontConst::SystemFontRegular, 36.0f);
noti->setTextColor(cocos2d::Color4B::BLACK);
noti->setPosition(s/2);
_contentView->addChild(noti);
return true;
}
SMView * bottomMenuContainer = SMView::create(0, 0, 0, s.width, BOTTOM_MENU_HEIGHT);
bottomMenuContainer->setBackgroundColor4F(cocos2d::Color4F::WHITE);
_contentView->addChild(bottomMenuContainer);
SMView * bottomMenuTopLine = SMView::create(0, 0, 159, s.width, 1);
bottomMenuTopLine->setBackgroundColor4F(MAKE_COLOR4F(0xadafb3, 1.0f));
bottomMenuContainer->addChild(bottomMenuTopLine);
bottomMenuTopLine->setLocalZOrder(10);
_zoomView = SMZoomView::create(0, 0, BOTTOM_MENU_HEIGHT, s.width, s.height-290);
_zoomView->setBackgroundColor4F(SMColorConst::COLOR_F_DBDCDF);
// _mainMeshSprite = MeshSprite::create(_mainImageSprite);
_mainImageView = SMImageView::create(_mainImageSprite);
_mainImageView->setContentSize(_mainImageSprite->getContentSize());
// setPadding must call before setContentNode()
_zoomView->setPadding(PHOTO_MARGIN);
_zoomView->setContentNode(_mainImageView);
_contentView->addChild(_zoomView);
_zoomView->setScissorEnable(true);
_bottomMenuTableView = SMTableView::createMultiColumn(SMTableView::Orientation::HORIZONTAL, 1, 0, 0, s.width, BOTTOM_MENU_HEIGHT);
_bottomMenuTableView->numberOfRowsInSection = [&](int section)->int {
return 3;
};
_bottomMenuTableView->cellForRowAtIndexPath = [&] (const IndexPath &indexPath)->cocos2d::Node * {
cocos2d::Node * converView = _bottomMenuTableView->dequeueReusableCellWithIdentifier("MENU_CELL");
MenuCell * cell = nullptr;
int index = indexPath.getIndex();
if (converView) {
cell = (MenuCell*)converView;
} else {
cell = MenuCell::create(0, 0, 0, 160, 160);
cell->menuButton = SMButton::create(0, SMButton::Style::SOLID_ROUNDEDRECT, 10, 10, 140, 140);
cell->addChild(cell->menuButton);
cell->menuButton->setShapeCornerRadius(10);
cell->menuButton->setOutlineWidth(2.0f);
cell->menuButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0xadafb3, 1.0f));
cell->menuButton->setButtonColor(SMButton::State::NORMAL, cocos2d::Color4F::WHITE);
cell->menuButton->setOutlineColor(SMButton::State::PRESSED, MAKE_COLOR4F(0xdbdcdf, 1.0f));
cell->menuButton->setButtonColor(SMButton::State::PRESSED, MAKE_COLOR4F(0xeeeff1, 1.0f));
cell->menuButton->setTextColor(SMButton::State::NORMAL, cocos2d::Color4F::BLACK);
cell->menuButton->setTextColor(SMButton::State::PRESSED, MAKE_COLOR4F(0x666666, 1.0f));
cell->menuButton->setPushDownScale(0.9f);
}
cell->setTag(index);
cell->menuButton->setTag(index);
cell->menuButton->setOnClickListener(this);
switch (index) {
case 0:
{
cell->menuButton->setTextSystemFont("편집", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 1:
{
cell->menuButton->setTextSystemFont("보정", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 2:
{
cell->menuButton->setTextSystemFont("꾸미기", SMFontConst::SystemFontRegular, 24.0f);
}
break;
}
return cell;
};
bottomMenuContainer->addChild(_bottomMenuTableView);
bottomMenuContainer->setLocalZOrder(10);
_editMenuView = SMView::create(0, 0, 0, s.width, BOTTOM_MENU_HEIGHT);
_editMenuView->setBackgroundColor4F(cocos2d::Color4F(1, 1, 1, 0.8f));
auto border = ShapeRect::create();
border->setContentSize(_editMenuView->getContentSize());
border->setColor4F(MAKE_COLOR4F(0xadafb3, 1.0f));
border->setLineWidth(2.0f);
_editMenuView->addChild(border);
// auto tmpEditLabel = cocos2d::Label::createWithSystemFont("편집 메뉴", SMFontConst::SystemFontRegular, 22.0f);
// tmpEditLabel->setTextColor(cocos2d::Color4B::BLACK);
// tmpEditLabel->setPosition(_editMenuView->getContentSize()/2);
// _editMenuView->addChild(tmpEditLabel);
_editMenuView->setVisible(false);
_contentView->addChild(_editMenuView);
_adjustMenuView = SMView::create(0, 0, 0, s.width, BOTTOM_MENU_HEIGHT);
_adjustMenuView->setBackgroundColor4F(cocos2d::Color4F(1, 1, 1, 0.8f));
auto border2 = ShapeRect::create();
border2->setContentSize(_adjustMenuView->getContentSize());
border2->setColor4F(MAKE_COLOR4F(0xadafb3, 1.0f));
border2->setLineWidth(2.0f);
_adjustMenuView->addChild(border2);
// auto tmpAdjustLabel = cocos2d::Label::createWithSystemFont("보정 메뉴", SMFontConst::SystemFontRegular, 22.0f);
// tmpAdjustLabel->setTextColor(cocos2d::Color4B::BLACK);
// tmpAdjustLabel->setPosition(_adjustMenuView->getContentSize()/2);
// _adjustMenuView->addChild(tmpAdjustLabel);
_adjustMenuView->setVisible(false);
_contentView->addChild(_adjustMenuView);
_magicMenuView = SMView::create(0, 0, 0, s.width, BOTTOM_MENU_HEIGHT);
_magicMenuView->setBackgroundColor4F(cocos2d::Color4F(1, 1, 1, 0.8f));
auto border3 = ShapeRect::create();
border3->setContentSize(_magicMenuView->getContentSize());
border3->setColor4F(MAKE_COLOR4F(0xadafb3, 1.0f));
border3->setLineWidth(2.0f);
_magicMenuView->addChild(border3);
// auto tmpMagicLabel = cocos2d::Label::createWithSystemFont("꾸미기 메뉴", SMFontConst::SystemFontRegular, 22.0f);
// tmpMagicLabel->setTextColor(cocos2d::Color4B::BLACK);
// tmpMagicLabel->setPosition(_magicMenuView->getContentSize()/2);
// _magicMenuView->addChild(tmpMagicLabel);
_magicMenuView->setVisible(false);
_contentView->addChild(_magicMenuView);
// edit menu button list
_editMenuTableView = SMTableView::createMultiColumn(SMTableView::Orientation::HORIZONTAL, 1, 0, 0, s.width, BOTTOM_MENU_HEIGHT);
_editMenuTableView->setLocalZOrder(10);
_editMenuView->addChild(_editMenuTableView);
_adjustMenuTableView = SMTableView::createMultiColumn(SMTableView::Orientation::HORIZONTAL, 1, 0, 0, s.width, BOTTOM_MENU_HEIGHT);
_adjustMenuTableView->setLocalZOrder(10);
_adjustMenuView->addChild(_adjustMenuTableView);
_magicMenuTableView = SMTableView::createMultiColumn(SMTableView::Orientation::HORIZONTAL, 1, 0, 0, s.width, BOTTOM_MENU_HEIGHT);
_magicMenuTableView->setLocalZOrder(10);
_magicMenuView->addChild(_magicMenuTableView);
// 자르기, 회전, 수평
_editMenuTableView->numberOfRowsInSection = [&] (int section) {
return 3;
};
// brightness, contrast, saturation, temperature
_adjustMenuTableView->numberOfRowsInSection = [&] (int section) {
return 4;
};
// sticker, text, draw, filter
_magicMenuTableView->numberOfRowsInSection = [&] (int section) {
return 4;
};
_editMenuTableView->cellForRowAtIndexPath = [&] (const IndexPath & indexPath)->cocos2d::Node* {
cocos2d::Node * converView = _editMenuTableView->dequeueReusableCellWithIdentifier("EDIT_CELL");
MenuCell * cell = nullptr;
int index = indexPath.getIndex();
if (converView) {
cell = (MenuCell*)converView;
} else {
cell = MenuCell::create(0, 0, 0, 160, 160);
cell->menuButton = SMButton::create(0, SMButton::Style::SOLID_ROUNDEDRECT, 10, 10, 140, 140);
cell->addChild(cell->menuButton);
cell->menuButton->setShapeCornerRadius(10);
cell->menuButton->setOutlineWidth(2.0f);
cell->menuButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0xadafb3, 1.0f));
cell->menuButton->setButtonColor(SMButton::State::NORMAL, cocos2d::Color4F::WHITE);
cell->menuButton->setOutlineColor(SMButton::State::PRESSED, MAKE_COLOR4F(0xdbdcdf, 1.0f));
cell->menuButton->setButtonColor(SMButton::State::PRESSED, MAKE_COLOR4F(0xeeeff1, 1.0f));
cell->menuButton->setTextColor(SMButton::State::NORMAL, cocos2d::Color4F::BLACK);
cell->menuButton->setTextColor(SMButton::State::PRESSED, MAKE_COLOR4F(0x666666, 1.0f));
cell->menuButton->setPushDownScale(0.9f);
cell->menuButton->setOnClickListener(this);
}
switch (index) {
case 0:
{
cell->menuButton->setTextSystemFont("자르기", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 1:
{
cell->menuButton->setTextSystemFont("회전", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 2:
{
cell->menuButton->setTextSystemFont("수평", SMFontConst::SystemFontRegular, 24.0f);
}
break;
}
cell->setTag(index+10);
cell->menuButton->setTag(index+10);
return cell;
};
_adjustMenuTableView->cellForRowAtIndexPath = [&] (const IndexPath & indexPath)->cocos2d::Node* {
cocos2d::Node * converView = _adjustMenuTableView->dequeueReusableCellWithIdentifier("ADJUST_CELL");
MenuCell * cell = nullptr;
int index = indexPath.getIndex();
if (converView) {
cell = (MenuCell*)converView;
} else {
cell = MenuCell::create(0, 0, 0, 160, 160);
cell->menuButton = SMButton::create(0, SMButton::Style::SOLID_ROUNDEDRECT, 10, 10, 140, 140);
cell->addChild(cell->menuButton);
cell->menuButton->setShapeCornerRadius(10);
cell->menuButton->setOutlineWidth(2.0f);
cell->menuButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0xadafb3, 1.0f));
cell->menuButton->setButtonColor(SMButton::State::NORMAL, cocos2d::Color4F::WHITE);
cell->menuButton->setOutlineColor(SMButton::State::PRESSED, MAKE_COLOR4F(0xdbdcdf, 1.0f));
cell->menuButton->setButtonColor(SMButton::State::PRESSED, MAKE_COLOR4F(0xeeeff1, 1.0f));
cell->menuButton->setTextColor(SMButton::State::NORMAL, cocos2d::Color4F::BLACK);
cell->menuButton->setTextColor(SMButton::State::PRESSED, MAKE_COLOR4F(0x666666, 1.0f));
cell->menuButton->setPushDownScale(0.9f);
cell->menuButton->setOnClickListener(this);
}
switch (index) {
case 0:
{
cell->menuButton->setTextSystemFont("밝기", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 1:
{
cell->menuButton->setTextSystemFont("명도", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 2:
{
cell->menuButton->setTextSystemFont("채도", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 3:
{
cell->menuButton->setTextSystemFont("색조", SMFontConst::SystemFontRegular, 24.0f);
}
break;
}
cell->setTag(index+20);
cell->menuButton->setTag(index+20);
return cell;
};
_magicMenuTableView->cellForRowAtIndexPath = [&] (const IndexPath & indexPath)->cocos2d::Node* {
cocos2d::Node * converView = _magicMenuTableView->dequeueReusableCellWithIdentifier("MAGIC_CELL");
MenuCell * cell = nullptr;
int index = indexPath.getIndex();
if (converView) {
cell = (MenuCell*)converView;
} else {
cell = MenuCell::create(0, 0, 0, 160, 160);
cell->menuButton = SMButton::create(0, SMButton::Style::SOLID_ROUNDEDRECT, 10, 10, 140, 140);
cell->addChild(cell->menuButton);
cell->menuButton->setShapeCornerRadius(10);
cell->menuButton->setOutlineWidth(2.0f);
cell->menuButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0xadafb3, 1.0f));
cell->menuButton->setButtonColor(SMButton::State::NORMAL, cocos2d::Color4F::WHITE);
cell->menuButton->setOutlineColor(SMButton::State::PRESSED, MAKE_COLOR4F(0xdbdcdf, 1.0f));
cell->menuButton->setButtonColor(SMButton::State::PRESSED, MAKE_COLOR4F(0xeeeff1, 1.0f));
cell->menuButton->setTextColor(SMButton::State::NORMAL, cocos2d::Color4F::BLACK);
cell->menuButton->setTextColor(SMButton::State::PRESSED, MAKE_COLOR4F(0x666666, 1.0f));
cell->menuButton->setPushDownScale(0.9f);
cell->menuButton->setOnClickListener(this);
}
switch (index) {
case 0:
{
cell->menuButton->setTextSystemFont("스티커", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 1:
{
cell->menuButton->setTextSystemFont("텍스트", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 2:
{
cell->menuButton->setTextSystemFont("그리기", SMFontConst::SystemFontRegular, 24.0f);
}
break;
case 3:
{
cell->menuButton->setTextSystemFont("필터", SMFontConst::SystemFontRegular, 24.0f);
}
break;
}
cell->setTag(index+30);
cell->menuButton->setTag(index+30);
return cell;
};
return true;
}
void SMImageEditorScene::setMainImage(cocos2d::Sprite *sprite)
{
_mainImageView->setSprite(nullptr);
_zoomView->setContentNode(nullptr);
// CC_SAFE_RELEASE_NULL(_mainImageSprite);
_mainImageSprite = cocos2d::Sprite::createWithTexture(sprite->getTexture());
// _mainImageSprite = cocos2d::Sprite::createWithSpriteFrame(sprite->getSpriteFrame());
_mainImageView = SMImageView::create(_mainImageSprite);
_mainImageView->setContentSize(_mainImageSprite->getContentSize());
_zoomView->setContentNode(_mainImageView);
_zoomView->refreshContentNode();
}
void SMImageEditorScene::setMenu(float dt)
{
unschedule(schedule_selector(SMImageEditorScene::setMenu));
// 현재 메뉴 체크
switch (currentMenuType) {
case kMenuTypeEdit:
{
showHideEditMenu(!_bEditMenuVisible);
showHideAdjustMenu(false);
showHideMagicMenu(false);
CCLOG("[[[[[ 편집 눌렀음.");
}
break;
case kMenuTypeAdjust:
{
showHideAdjustMenu(!_bAdjustMenuVisible);
showHideEditMenu(false);
showHideMagicMenu(false);
CCLOG("[[[[[ 보정 눌렀음.");
}
break;
case kMenuTypeMagic:
{
showHideMagicMenu(!_bMagicMenuVisible);
showHideEditMenu(false);
showHideAdjustMenu(false);
CCLOG("[[[[[ 꾸미기 눌렀음.");
}
break;
default:
break;
}
}
void SMImageEditorScene::showHideEditMenu(bool bShow)
{
if (_bEditMenuVisible==bShow) {
return;
}
_bEditMenuVisible = bShow;
cocos2d::Vec2 pos = cocos2d::Point::ZERO;
if (_bEditMenuVisible) {
pos = cocos2d::Vec2(0, BOTTOM_MENU_HEIGHT);
_editMenuView->setVisible(_bEditMenuVisible);
} else {
pos = cocos2d::Vec2::ZERO;
}
auto moveTo = cocos2d::MoveTo::create(0.15f, pos);
auto action = cocos2d::Sequence::create(moveTo, cocos2d::CallFunc::create([&]{
if (_bEditMenuVisible) {
CCLOG("[[[[[ 편집 메뉴 보임");
} else {
CCLOG("[[[[[ 편집 메뉴 사라짐");
_editMenuView->setVisible(_bEditMenuVisible);
}
}), NULL);
_editMenuView->runAction(action);
float op = 0;
if (_bEditMenuVisible) {
op = 255.0f;
}
auto fadeTo = cocos2d::FadeTo::create(0.15f, op);
_editMenuView->runAction(fadeTo);
}
void SMImageEditorScene::showHideAdjustMenu(bool bShow)
{
if (_bAdjustMenuVisible==bShow) {
return;
}
_bAdjustMenuVisible = bShow;
cocos2d::Vec2 pos = cocos2d::Point::ZERO;
if (_bAdjustMenuVisible) {
pos = cocos2d::Vec2(0, BOTTOM_MENU_HEIGHT);
_adjustMenuView->setVisible(_bAdjustMenuVisible);
} else {
pos = cocos2d::Vec2::ZERO;
}
auto moveTo = cocos2d::MoveTo::create(0.15f, pos);
auto action = cocos2d::Sequence::create(moveTo, cocos2d::CallFunc::create([&]{
if (_bAdjustMenuVisible) {
CCLOG("[[[[[ 보정 메뉴 보임");
} else {
CCLOG("[[[[[ 보정 메뉴 사라짐");
_adjustMenuView->setVisible(_bAdjustMenuVisible);
}
}), NULL);
_adjustMenuView->runAction(action);
float op = 0;
if (_bAdjustMenuVisible) {
op = 255.0f;
}
auto fadeTo = cocos2d::FadeTo::create(0.15f, op);
_adjustMenuView->runAction(fadeTo);
}
void SMImageEditorScene::showHideMagicMenu(bool bShow)
{
if (_bMagicMenuVisible==bShow) {
return;
}
_bMagicMenuVisible = bShow;
cocos2d::Vec2 pos = cocos2d::Point::ZERO;
if (_bMagicMenuVisible) {
pos = cocos2d::Vec2(0, BOTTOM_MENU_HEIGHT);
_magicMenuView->setVisible(_bMagicMenuVisible);
} else {
pos = cocos2d::Vec2::ZERO;
}
auto moveTo = cocos2d::MoveTo::create(0.15f, pos);
auto action = cocos2d::Sequence::create(moveTo, cocos2d::CallFunc::create([&]{
if (_bMagicMenuVisible) {
CCLOG("[[[[[ 꾸미기 메뉴 보임");
} else {
CCLOG("[[[[[ 꾸미기 메뉴 사라짐");
_magicMenuView->setVisible(_bMagicMenuVisible);
}
}), NULL);
_magicMenuView->runAction(action);
float op = 0;
if (_bMagicMenuVisible) {
op = 255.0f;
}
auto fadeTo = cocos2d::FadeTo::create(0.15f, op);
_magicMenuView->runAction(fadeTo);
}
void SMImageEditorScene::onClick(SMView *view)
{
int tag = view->getTag();
if (tag<10) {
if (isScheduled(schedule_selector(SMImageEditorScene::setMenu))) {
unschedule(schedule_selector(SMImageEditorScene::setMenu));
}
currentMenuType = (kMenuType)tag;
schedule(schedule_selector(SMImageEditorScene::setMenu), 0.1f);
} else if (tag<20) {
// edit menu
switch (tag) {
case kEditMenuCrop:
{
// cv::Mat src = cvImageUtil::ccImage2cvMat(_mainccImage);
//
// cv::Mat dst;
//
// cv::cvtColor(src, dst, cv::COLOR_RGBA2YUV_I420);
//
// cv::cvtColor(dst, src, cv::COLOR_YUV2RGBA_IYUV);
//
// auto ccImage = cvImageUtil::cvMat2ccImage(src);
//
// auto texture = new cocos2d::Texture2D;
// texture->initWithImage(ccImage);
// texture->autorelease();
//
// auto sprite = cocos2d::Sprite::createWithTexture(texture);
//
// auto layer = (SMView*)_director->getSharedLayer(cocos2d::Director::SharedLayer::POPUP);
//
// auto imgView = SMImageView::create(sprite);
// imgView->setBackgroundColor4F(MAKE_COLOR4F(0xffffff, 0.6f));
// auto s = _director->getWinSize();
// imgView->setContentSize(s);
// layer->addChild(imgView);
//
// imgView->setOnClickCallback([this](SMView * view){
// _director->getScheduler()->performFunctionInCocosThread([this]{
// auto layer = (SMView*)_director->getSharedLayer(cocos2d::Director::SharedLayer::POPUP);
// layer->removeAllChildren();
// });
// });
//
// return;
CCLOG("[[[[[ 자르기");
Intent * intent = Intent::create();
intent->putRef("EDIT_IMAGE", _mainccImage);
auto scene = SMImageEditorCropScene::create(intent, SMScene::SwipeType::NONE);
auto pScene = SceneTransition::FadeIn::create(SceneTransition::Time::NORMAL, scene);
_director->pushScene(pScene);
}
break;
case kEditMenuRotate:
{
CCLOG("[[[[[ 회전");
Intent * intent = Intent::create();
intent->putRef("EDIT_IMAGE", _mainccImage);
auto scene = SMImageEditorRotateScene::create(intent, SMScene::SwipeType::NONE);
auto pScene = SceneTransition::FadeIn::create(SceneTransition::Time::NORMAL, scene);
_director->pushScene(pScene);
}
break;
case kEditMenuHorizon:
{
CCLOG("[[[[[ 수평");
Intent * intent = Intent::create();
intent->putRef("EDIT_IMAGE", _mainccImage);
auto scene = SMImageEditorStraightenScene::create(intent, SMScene::SwipeType::NONE);
auto pScene = SceneTransition::FadeIn::create(SceneTransition::Time::NORMAL, scene);
_director->pushScene(pScene);
}
break;
default:
{
CCLOG("[[[[[ WTF???");
}
break;
}
} else if (tag<30) {
// adjust menu
kColorType type;
switch (tag) {
case kAdjustMenuBrightness:
{
CCLOG("[[[[[ 밝기");
type = kColorTypeBrightness;
}
break;
case kAdjustMenuContrast:
{
CCLOG("[[[[[ 명도");
type = kColorTypeContrast;
}
break;
case kAdjustMenuSaturation:
{
CCLOG("[[[[[ 채도");
type = kColorTypeSaturation;
}
break;
case kAdjustMenuTemperature:
{
CCLOG("[[[[[ 색조");
type = kColorTypeTemperature;
}
break;
default:
{
CCLOG("[[[[[ WTF???");
}
break;
}
Intent * intent = Intent::create();
intent->putRef("EDIT_IMAGE", _mainccImage);
intent->putInt("COLOR_TYPE", type);
auto scene = SMImageEditorColorScene::create(intent, SMScene::SwipeType::NONE);
auto pScene = SceneTransition::FadeIn::create(SceneTransition::Time::NORMAL, scene);
_director->pushScene(pScene);
} else if (tag<40) {
// magic menu
switch (tag) {
case kMagicMenuSticker:
{
CCLOG("[[[[[ 스티커");
Intent * intent = Intent::create();
intent->putRef("EDIT_IMAGE", _mainccImage);
auto scene = SMImageEditorStickerScene::create(intent, SMScene::SwipeType::NONE);
auto pScene = SceneTransition::FadeIn::create(SceneTransition::Time::NORMAL, scene);
_director->pushScene(pScene);
}
break;
case kMagicMenuText:
{
CCLOG("[[[[[ 텍스트");
}
break;
case kMagicMenuDraw:
{
CCLOG("[[[[[ 그리기");
Intent * intent = Intent::create();
intent->putRef("EDIT_IMAGE", _mainccImage);
auto scene = SMImageEditorDrawScene::create(intent, SMScene::SwipeType::NONE);
auto pScene = SceneTransition::FadeIn::create(SceneTransition::Time::NORMAL, scene);
_director->pushScene(pScene);
}
break;
case kMagicMenuFilter:
{
CCLOG("[[[[[ 필터");
Intent * intent = Intent::create();
intent->putRef("EDIT_IMAGE", _mainccImage);
auto scene = SMImageEditorFilterScene::create(intent, SMScene::SwipeType::NONE);
auto pScene = SceneTransition::FadeIn::create(SceneTransition::Time::NORMAL, scene);
_director->pushScene(pScene);
}
break;
default:
{
CCLOG("[[[[[ WTF???");
}
break;
}
} else {
CCLOG("[[[[[ WTF???");
}
}
void SMImageEditorScene::onSceneResult(SMScene *fromScene, Intent *result)
{
CCLOG("[[[[[ editor scene on scene result");
if (result!=nullptr) {
auto ccImage = static_cast<cocos2d::Image*>(result->getRef("EDIT_IMAGE"));
if (ccImage) {
_mainccImage->release();
_mainccImage = new cocos2d::Image;
_mainccImage->initWithRawData(ccImage->getData(), ccImage->getDataLen(), ccImage->getWidth(), ccImage->getHeight(), ccImage->getBitPerPixel());
_mainccImage->retain();
auto texture = new cocos2d::Texture2D;
texture->initWithImage(_mainccImage);
_mainccImage->release();
auto tmp = cocos2d::Sprite::createWithTexture(texture);
texture->release();
setMainImage(tmp);
} else {
// else는 나중에 지우자
auto sprite = static_cast<cocos2d::Sprite*>(result->getRef("CROP_SPRITE"));
if (sprite) {
setMainImage(sprite);
}
}
}
}
void SMImageEditorScene::finishEditImage()
{
}
|
#include "BoyerMoore.h"
#include "Zalgorithm.h"
#include "gtest/gtest.h"
#include "BoyerMoorePreprocessing.h"
using testing::Test;
#include <algorithm>
#include <random>
#include <string>
#define NUM_TEST_CASES 10000
#define RANDOM_STRING_SIZE 100
#define RANDOM_SUBSTRING_SIZE 4
// Sanity check for BoyerMoore & ZalgorithmBasedMatching
// Does NUM_TEST_CASES times:
// 1) Generate random string T of size RANDOM_STRING_SIZE
// 2) Generate a random substring P of T
// 3) Runs BoyerMoore and ZalgorithmBasedMatching and checks results are identical
// Use <random> & uniform_int_distribution for your random number generation
TEST(TwoAlgorithmVerificationSanityCheck, SubstringMatchesInRandomString) {
const std::string Sigma = "abcdefghijklmnopqrstuvwxyz";
// TODO: implement this.
std::default_random_engine generator;
std::uniform_int_distribution<int> letterDistribution(0, 25);
std::uniform_int_distribution<int> substringDistribution(1, RANDOM_STRING_SIZE);
for (int i = 0; i < NUM_TEST_CASES; i++) {
std::string T = " ";
for (int j = 0; j < RANDOM_STRING_SIZE; j++) {
T.push_back('a' + letterDistribution(generator));
}
int start = substringDistribution(generator), end = substringDistribution(generator);
if (start > end) {
std::swap(start, end);
}
std::string P = " " + T.substr(start, end);
std::list<int> Z_matches, BM_matches;
ZalgorithmBasedMatching(P, T, &Z_matches);
BoyerMoore(P, T, Sigma, &BM_matches);
std::list<int>::iterator itr1 = Z_matches.begin();
std::list<int>::iterator itr2 = BM_matches.begin();
for (; itr1 != Z_matches.end() && itr2 != BM_matches.end(); ++itr1, ++itr2)
{
EXPECT_EQ(*itr1, *itr2);
}
}
}
// Sanity check for BoyerMoore & ZalgorithmBasedMatching
// Does NUM_TEST_CASES times:
// 1) Generate random string T of size RANDOM_STRING_SIZE
// 2) Generate a random substring P of size RANDOM_SUBSTRING_SIZE (no relationship to T)
// 3) Runs BoyerMoore and ZalgorithmBasedMatching and checks results are identical
// Use <random> & uniform_int_distribution for your random number generation
TEST(TwoAlgorithmVerificationSanityCheck, RandomSubstringVsRandomString) {
const std::string Sigma = "abcdefghijklmnopqrstuvwxyz";
// TODO: implement this.
std::default_random_engine generator;
std::uniform_int_distribution<int> letterDistribution(0, 25);
std::uniform_int_distribution<int> substringDistribution(1, RANDOM_STRING_SIZE);
for (int i = 0; i < NUM_TEST_CASES; i++) {
std::string T = " ";
for (int j = 0; j < RANDOM_STRING_SIZE; j++) {
T.push_back('a' + letterDistribution(generator));
}
std::string P = " ";
for (int k = 0; k < RANDOM_SUBSTRING_SIZE; k++) {
P.push_back('a' + letterDistribution(generator));
}
std::list<int> Z_matches, BM_matches;
ZalgorithmBasedMatching(P, T, &Z_matches);
BoyerMoore(P, T, Sigma, &BM_matches);
std::list<int>::iterator itr1 = Z_matches.begin();
std::list<int>::iterator itr2 = BM_matches.begin();
for (; itr1 != Z_matches.end() && itr2 != BM_matches.end(); ++itr1, ++itr2)
{
EXPECT_EQ(*itr1, *itr2);
}
}
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
//
// Created by crabman on 11.01.16.
//
#include "parsing_error_exception.h"
parsing_error_exception::parsing_error_exception():
std::logic_error{"Parsing error!"} { }
|
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head==NULL)return NULL;
Node* prev=NULL;
Node* temp3 = NULL;
Node* head1=head;
vector<Node*> v1,v2;
while(head!=NULL)
{
Node* temp2= new Node(head->val);
Node* temp5 = head1;
Node* temp4 = temp3;
while(temp4!=NULL)
{
if(temp5->random==head)
{
temp4->random=temp2;
}
temp5 = temp5->next;
temp4 = temp4->next;
}
v2.push_back(temp2);
v1.push_back(head);
for(int i=0;i<v1.size();i++)
{
if(v1[i]==head->random)
{
temp2->random=v2[i];
break;
}
}
if(prev!=NULL)
prev->next=temp2;
else
temp3=temp2;
prev=temp2;
head = head->next;
}
return temp3;
}
};
|
#include "animemodel.h"
#include <QColor>
#include <QFont>
#include <QLocale>
AnimeModel::AnimeModel(QtDataSync::DataStoreModel *srcModel, QObject *parent) :
QObjectProxyModel({tr("Id"), tr("Name"), tr("Season Count"), tr("Last updated"), tr("Season Overview")}, parent)
{
setSourceModel(srcModel);
addMapping(0, Qt::DisplayRole, "id");
addMapping(0, Qt::ToolTipRole, "id");
addMapping(1, Qt::DisplayRole, "title");
addMapping(1, Qt::ToolTipRole, "title");
addMapping(2, Qt::DisplayRole, "totalSeasonCount");
addMapping(2, Qt::ToolTipRole, "totalSeasonCount");
addMapping(3, Qt::DisplayRole, "lastUpdateCheck");
addMapping(3, Qt::ToolTipRole, "lastUpdateCheck");
addMapping(4, Qt::DisplayRole, "relationsUrl");
addMapping(4, Qt::ToolTipRole, "relationsUrl");
}
QVariant AnimeModel::data(const QModelIndex &index, int role) const
{
auto src = mapToSource(index);
if(!src.isValid())
return {};
auto info = static_cast<QtDataSync::DataStoreModel*>(sourceModel())->object<AnimeInfo>(src);
switch (role) {
case Qt::DisplayRole:
case Qt::ToolTipRole:
switch(index.column()) {
case 2:
return QLocale().toString(info.totalSeasonCount());
case 3:
return info.lastUpdateCheck().toString(Qt::DefaultLocaleShortDate);
default:
break;
}
break;
case Qt::FontRole:
if(info.hasNewSeasons()) {
QFont font;
font.setBold(true);
return font;
} else
break;
case Qt::ForegroundRole:
if(info.hasNewSeasons())
return QColor(0x8A, 0x0E, 0x0E);
else
break;
default:
break;
}
return QObjectProxyModel::data(index, role);
}
|
/*************************************************************
* > File Name : UVa12304.cpp
* > Author : Tony
* > Created Time : 2019/04/21 22:22:17
**************************************************************/
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<iostream>
#include<vector>
using namespace std;
const double eps = 1e-6;
const double PI = acos(-1);
struct Point {
double x, y;
Point(double x = 0, double y = 0): x(x), y(y) {}
};
typedef Point Vector;
Vector operator + (const Vector& a, const Vector& b) { return Vector(a.x + b.x, a.y + b.y); }
Vector operator - (const Vector& a, const Vector& b) { return Vector(a.x - b.x, a.y - b.y); }
Vector operator * (const Vector& a, double p) { return Vector(a.x * p, a.y * p); }
Vector operator / (const Vector& a, double p) { return Vector(a.x / p, a.y / p); }
bool operator < (const Point& a, const Point& b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
int dcmp(double x) {
if (fabs(x) < eps) return 0;
else return x < 0 ? -1 : 1;
}
bool operator == (const Point& a, const Point& b) {
return dcmp(a.x - b.x) == 0 && dcmp(a.y - b.y) == 0;
}
double Dot(const Vector& a, const Vector& b) { return a.x * b.x + a.y * b.y; }
double Length(const Vector& a) { return sqrt(Dot(a, a)); }
double Angle(const Vector& a, const Vector& b) { return acos(Dot(a, b) / Length(a) / Length(b)); }
double Cross(const Vector& a, const Vector& b) { return a.x * b.y - a.y * b.x; }
double Area2(const Point& a, const Point& b, const Point& c) { return Cross(b - a, c - a); }
Vector Rotate(const Vector& a, double rad) {
return Vector(a.x * cos(rad) - a.y * sin(rad), a.x * sin(rad) + a.y * cos(rad));
}
Vector Normal(const Vector& a) {
double L = Length(a);
return Vector(-a.y / L, a.x / L);
}
Point GetLineIntersection(const Point& p, const Vector& v, const Point& q, const Vector& w) {
Vector u = p - q;
double t = Cross(w, u) / Cross(v, w);
return p + v * t;
}
double angle(const Vector& v) {
return atan2(v.y, v.x);
}
double DistanceToLine(const Point& p, const Point& a, const Point& b) {
Vector v1 = b - a, v2 = p - a;
return fabs(Cross(v1, v2)) / Length(v1);
}
double DistanceToSegment(const Point& p, const Point& a, const Point& b) {
if (a == b) return Length(p - a);
Vector v1 = b - a, v2 = p - a, v3 = p - b;
if (dcmp(Dot(v1, v2)) < 0) return Length(v2);
else if (dcmp(Dot(v1, v3)) > 0) return Length(v3);
else return fabs(Cross(v1, v2)) / Length(v1);
}
Point GetLineProjection(Point p, Point a, Point b) {
Vector v = b - a;
return a + v * (Dot(v, p - a) / Dot(v, v));
}
bool SegmentProperIntersection(Point a1, Point a2, Point b1, Point b2) {
double c1 = Cross(a2 - a1, b1 - a1), c2 = Cross(a2 - a1, b2 - a1),
c3 = Cross(b2 - b1, a1 - b1), c4 = Cross(b2 - b1, a2 - b1);
return dcmp(c1) * dcmp(c2) < 0 && dcmp(c3) * dcmp(c4) < 0;
}
bool OnSegment(Point p, Point a1, Point a2) {
return dcmp(Cross(a1 - p, a2 - p)) == 0 && dcmp(Dot(a1 - p, a2 - p)) < 0;
}
double ConvexPolygonArea(Point* p, int n) {
double area = 0;
for (int i = 1; i < n - 1; ++i) {
area += Cross(p[i] - p[0], p[i + 1] - p[0]);
}
return area / 2;
}
double PolygonArea(Point* p, int n) {
double area = 0;
for (int i = 1; i < n - 1; ++i) {
area += Cross(p[i] - p[0], p[i + 1] - p[0]);
}
return area / 2;
}
struct Line {
Point p;
Vector v;
Line(Point p, Vector v): p(p), v(v) {}
Point point(double t) {
return p + v * t;
}
Line move(double d) {
return Line(p + Normal(v) * d, v);
}
};
Line GetLine(double x1, double Y1, double x2, double y2) {
Point p1(x1, Y1);
Point p2(x2, y2);
return Line(p1, p2 - p1);
}
struct Circle {
Point c;
double r;
Circle(Point c, double r): c(c), r(r) {}
Point point(double a) {
return Point(c.x + cos(a) * r, c.y + sin(a) * r);
}
};
Point GetLineIntersection(Line a, Line b) {
return GetLineIntersection(a.p, a.v, b.p, b.v);
}
int GetLineCircleIntersection(Line L, Circle C, double& t1, double& t2, vector<Point>& sol) {
double a = L.v.x, b = L.p.x - C.c.x, c = L.v.y, d = L.p.y - C.c.y;
double e = a * a + c * c, f = 2 * (a * b + c * d), g = b * b + d * d - C.r * C.r;
double delta = f * f - 4 * e * g;
if (dcmp(delta) < 0 ) return 0;
if (dcmp(delta) == 0) {
t1 = t2 = -f / (2 * e);
sol.push_back(L.point(t1));
return 1;
}
t1 = (-f - sqrt(delta)) / (2 * e); sol.push_back(L.point(t1));
t2 = (-f + sqrt(delta)) / (2 * e); sol.push_back(L.point(t2));
return 2;
}
int GetCircleCircleIntersection(Circle C1, Circle C2, vector<Point>& sol) {
double d = Length(C1.c - C2.c);
if (dcmp(d) == 0) {
if (dcmp(C1.r - C2.r) == 0) return -1;
return 0;
}
if (dcmp(C1.r + C2.r - d) < 0) return 0;
if (dcmp(fabs(C1.r - C2.r) - d) > 0) return 0;
double a = angle(C2.c - C1.c);
double da = acos((C1.r * C1.r + d * d - C2.r * C2.r) / (2 * C1.r * d));
Point p1 = C1.point(a - da), p2 = C1.point(a + da);
sol.push_back(p1);
if (p1 == p2) return 1;
sol.push_back(p2);
return 2;
}
/*** Solve ***/
// Problem 1
Circle CircumscribedCircle(Point p1, Point p2, Point p3) {
double Bx = p2.x - p1.x, By = p2.y - p1.y;
double Cx = p3.x - p1.x, Cy = p3.y - p1.y;
double D = 2 * (Bx * Cy - By * Cx);
double cx = (Cy * (Bx * Bx + By * By) - By * (Cx * Cx + Cy * Cy)) / D + p1.x;
double cy = (Bx * (Cx * Cx + Cy * Cy) - Cx * (Bx * Bx + By * By)) / D + p1.y;
Point p = Point(cx, cy);
return Circle(p, Length(p1 - p));
}
// Problem 2
Circle InscribedCircle(Point p1, Point p2, Point p3) {
double a = Length(p2 - p3);
double b = Length(p3 - p1);
double c = Length(p1 - p2);
Point p = (p1 * a + p2 * b + p3 * c) / (a + b + c);
return Circle(p, DistanceToLine(p, p1, p2));
}
// Problem 3
int TangentLineThroughPoint(Point p, Circle C, Vector* v) {
Vector u = C.c - p;
double dist = Length(u);
if (dist < C.r) return 0;
else if (dcmp(dist - C.r) == 0) {
v[0] = Rotate(u, PI / 2);
return 1;
} else {
double ang = asin(C.r / dist);
v[0] = Rotate(u, -ang);
v[1] = Rotate(u, +ang);
return 2;
}
}
double LineAngleDegree(Vector v) {
double ang = angle(v) * 180.0 / PI;
while (dcmp(ang) < 0) ang += 360.0;
while (dcmp(ang - 180) >= 0) ang -= 180.0;
return ang;
}
// Problem 4
vector<Point> CircleThroughPointTangentToLineGivenRadius(Point p, Line L, double r) {
vector<Point> ans;
double t1, t2;
GetLineCircleIntersection(L.move(-r), Circle(p, r), t1, t2, ans);
GetLineCircleIntersection(L.move(r) , Circle(p, r), t1, t2, ans);
return ans;
}
// Problem 5
vector<Point> CircleTangentToLinesGivenRadius(Line a, Line b, double r) {
vector<Point> ans;
Line L1 = a.move(-r), L2 = a.move(r);
Line L3 = b.move(-r), L4 = b.move(r);
ans.push_back(GetLineIntersection(L1, L3));
ans.push_back(GetLineIntersection(L1, L4));
ans.push_back(GetLineIntersection(L2, L3));
ans.push_back(GetLineIntersection(L2, L4));
return ans;
}
// Problem 6
vector<Point> CircleTangentToTwoDisjointCirclesWithRadius(Circle c1, Circle c2, double r) {
vector<Point> ans;
Vector v = c2.c - c1.c;
double dist = Length(v);
int d = dcmp(dist - c1.r - c2.r - r * 2);
if (d > 0) return ans;
GetCircleCircleIntersection(Circle(c1.c, c1.r + r), Circle(c2.c, c2.r + r), ans);
return ans;
}
/*** Output ***/
// Problem 1 2
void print(Circle c) {
printf("(%.6lf,%.6lf,%.6lf)\n", c.c.x, c.c.y, c.r);
}
// Problem 3
void print(vector<double> ans) {
int n = ans.size();
sort(ans.begin(), ans.end());
printf("[");
if (n) {
printf("%.6lf", ans[0]);
for (int i = 1; i < n; ++i) {
printf(",%.6lf", ans[i]);
}
}
printf("]\n");
}
// Problem 4 5 6
void print(vector<Point> ans) {
int n = ans.size();
sort(ans.begin(), ans.end());
printf("[");
if (n) {
printf("(%.6lf,%.6lf)", ans[0].x, ans[0].y);
for (int i = 1; i < n; ++i) {
printf(",(%.6lf,%.6lf)", ans[i].x, ans[i].y);
}
}
printf("]\n");
}
/*** main ***/
double x1, Y1, x2, y2, x3, y3, x4, y4, xp, yp, xc, yc, r1, r2, r;
int main() {
string opt;
while (cin >> opt) {
if (opt == "CircumscribedCircle") {
cin >> x1 >> Y1 >> x2 >> y2 >> x3 >> y3;
print(CircumscribedCircle(Point(x1, Y1), Point(x2, y2), Point(x3, y3)));
}
if (opt == "InscribedCircle") {
cin >> x1 >> Y1 >> x2 >> y2 >> x3 >> y3;
print(InscribedCircle(Point(x1, Y1), Point(x2, y2), Point(x3, y3)));
}
if (opt == "TangentLineThroughPoint") {
cin >> xc >> yc >> r >> xp >> yp;
Vector v[2];
vector<double> ans;
int cnt = TangentLineThroughPoint(Point(xp, yp), Circle(Point(xc, yc), r), v);
for (int i = 0; i < cnt; i++) ans.push_back(LineAngleDegree(v[i]));
print(ans);
}
if (opt == "CircleThroughAPointAndTangentToALineWithRadius") {
cin >> xp >> yp >> x1 >> Y1 >> x2 >> y2 >> r;
print(CircleThroughPointTangentToLineGivenRadius(Point(xp, yp), GetLine(x1, Y1, x2, y2), r));
}
if (opt == "CircleTangentToTwoLinesWithRadius") {
cin >> x1 >> Y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4 >> r;
print(CircleTangentToLinesGivenRadius(GetLine(x1, Y1, x2, y2), GetLine(x3, y3, x4, y4), r));
}
if (opt == "CircleTangentToTwoDisjointCirclesWithRadius") {
cin >> x1 >> Y1 >> r1 >> x2 >> y2 >> r2 >> r;
print(CircleTangentToTwoDisjointCirclesWithRadius(Circle(Point(x1, Y1), r1), Circle(Point(x2, y2), r2), r));
}
}
return 0;
}
|
#include "texture.h"
Texture::Texture(WCHAR* textureFilePath, ID3D11Device* device):
textureFilePath(textureFilePath),
device(device)
{
textureResource = 0;
}
Texture::Texture(const Texture& other)
{
}
Texture::~Texture()
{
}
bool Texture::Initialize()
{
HRESULT result;
// Load the texture in.
result = D3DX11CreateShaderResourceViewFromFile(device, textureFilePath, NULL, NULL, &textureResource, NULL);
if (FAILED(result))
{
return false;
}
return true;
}
void Texture::Shutdown()
{
// Release the texture resource.
if (textureResource)
{
textureResource->Release();
textureResource = 0;
}
return;
}
ID3D11ShaderResourceView* Texture::GetTexture()
{
return textureResource;
}
|
#include "renderable.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <fmt/format.h>
namespace GLPlay {
EventSource<Renderable::RenderableEvent> Renderable::event_source_;
Renderable::Renderable(std::string frag_shader, std::string vert_shader) {
gl_texture_ = 0;
glGenBuffers(3, gl_buffers_);
glGenVertexArrays(1, gl_objects_);
shader_ = new Shader(frag_shader, vert_shader);
glBindBuffer(GL_UNIFORM_BUFFER, gl_buffers_[UNIFORM_BUFFER]);
glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(glm::mat4), nullptr, GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glBindBufferRange(GL_UNIFORM_BUFFER, 0, gl_buffers_[UNIFORM_BUFFER], 0, 2 * sizeof(glm::mat4));
rotation_theta_ = 0.0f;
rotation_vector_ = glm::vec3(1.0f, 0.0f, 0.0f);
translation_ = glm::vec3(0.0f, 0.0f, 0.0f);
scale_ = glm::vec3(1.0f, 1.0f, 1.0f);
CalculateModelMatrix();
}
Renderable::~Renderable() {
glDeleteVertexArrays(1, gl_objects_);
glDeleteBuffers(2, gl_buffers_);
event_source_.GenerateEvent(VERTEX_EVENT, VertexEventData(-vertices_.size(), -indices_.size()));
}
void Renderable::Bind() {
glBindVertexArray(gl_objects_[ARRAY_OBJECT]); {
glBindBuffer(GL_ARRAY_BUFFER, gl_buffers_[ARRAY_BUFFER]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*vertices_.size(), vertices_.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gl_buffers_[ELEMENT_ARRAY_BUFFER]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*indices_.size(), indices_.data(), GL_STATIC_DRAW);
// Position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(offsetof(Vertex, pos)));
glEnableVertexAttribArray(0);
// Normal
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(offsetof(Vertex, nor)));
glEnableVertexAttribArray(1);
// Color
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(offsetof(Vertex, col)));
glEnableVertexAttribArray(2);
// Texture 0
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(offsetof(Vertex, tx0)));
glEnableVertexAttribArray(3);
// Texture 1
glVertexAttribPointer(4, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(offsetof(Vertex, tx1)));
glEnableVertexAttribArray(4);
glBindVertexArray(0);
}
}
void Renderable::AddMesh(std::vector<Vertex> & vertices, std::vector<GLuint> & indices) {
size_t i = vertices_.size();
for (auto & vertex : vertices) {
vertices_.emplace_back(vertex);
}
for (auto & index : indices) {
indices_.emplace_back(i+index);
}
Bind();
event_source_.GenerateEvent(VERTEX_EVENT, VertexEventData(vertices.size(), indices.size()));
}
void Renderable::ClearMesh() {
event_source_.GenerateEvent(VERTEX_EVENT, VertexEventData(-vertices_.size(), -indices_.size()));
vertices_.clear();
indices_.clear();
}
void Renderable::Render(glm::mat4 view_matrix, glm::mat4 proj_matrix) {
// FIXME: matricies should not be passed in here. Maybe observer on the shader object which monitors matrix changes?
glBindBuffer(GL_UNIFORM_BUFFER, gl_buffers_[UNIFORM_BUFFER]);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), glm::value_ptr(view_matrix));
glBufferSubData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(proj_matrix));
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glBindBufferBase(GL_UNIFORM_BUFFER, 0, gl_buffers_[UNIFORM_BUFFER]);
glBindVertexArray(gl_objects_[ARRAY_OBJECT]); {
glUseProgram((*shader_).gl_shader_);
glUniform1i(glGetUniformLocation((*shader_).gl_shader_, "tex0"), 0);
glUniformMatrix4fv(glGetUniformLocation((*shader_).gl_shader_, "model_matrix"), 1, GL_FALSE, glm::value_ptr(model_matrix_));
if (gl_texture_) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, gl_texture_);
}
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indices_.size()), GL_UNSIGNED_INT, 0);
if (gl_texture_) {
glBindTexture(GL_TEXTURE_2D, 0);
}
glBindVertexArray(0);
}
}
void Renderable::SetTextureFromBitmap(unsigned char *bitmap, int width, int height) {
glGenTextures(1, &gl_texture_);
glBindTexture(GL_TEXTURE_2D, gl_texture_); {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, bitmap);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
void Renderable::CalculateModelMatrix() {
model_matrix_ = glm::mat4(1.0f);
model_matrix_ = glm::rotate(model_matrix_, rotation_theta_, rotation_vector_);
model_matrix_ = glm::translate(model_matrix_, translation_);
model_matrix_ = glm::scale(model_matrix_, scale_);
}
void Renderable::SetTranslation(const glm::vec3 & translation) {
translation_ = translation;
CalculateModelMatrix();
}
void Renderable::SetRotation(const float rotation_theta, const glm::vec3 & rotation_vector) {
rotation_theta_ = rotation_theta;
rotation_vector_ = rotation_vector;
CalculateModelMatrix();
}
void Renderable::SetScale(const glm::vec3 & scale) {
scale_ = scale;
CalculateModelMatrix();
}
glm::mat4 & Renderable::model_matrix() {
return model_matrix_;
}
}
|
/*
* EE 205 Lab 2
*
* File: task1.cpp
* Name: Paulo Lemus
* Date: 1/18/2017
*
* Learn the size of various data types.
*/
#include <iostream>
using namespace std;
struct Empty{
};
struct Base{
int a;
};
struct Derived : public Base{
int b;
};
struct Bit{
unsigned bit : 1;
};
int main(){
Empty e;
Derived d;
Bit bit;
Base& b = d;
int i1 = 0x12345678;
int i2 = -1;
char c = 'a';
float f = 22.625;
double db = 1.2;
const int N = 10;
int a[N];
// TODO: CODE TO INITIALIZE a[]
for(int i = 0; i < N; i++){
a[i] = i1;
}
int* p1 = &i1;
int* p2 = &i2;
float* p3 = &f;
double* p4 = &db;
char* p5 = &c;
cout << "Datatype \t size in bytes\n";
cout << "___________________________\n";
cout << "integer \t\t\t" << sizeof(int) << endl;
// FILL CODE TO FIND SIZE OF ALL OTHER PRIMITIVE DATA TYPES
cout << "float \t\t\t\t" << sizeof(float) << endl;
cout << "double \t\t\t\t" << sizeof(double) << endl;
cout << "char \t\t\t\t" << sizeof(char) << endl;
cout << "array of 10 int\t\t\t" << sizeof(int[10]) << endl;
cout << "array of 10 int(2)\t\t" << sizeof(a) << endl;
cout << "length of array of 10 int\t" << (sizeof(a) / sizeof(*a)) << endl;
cout << "length of array of 10 int (2)\t" << (sizeof(a) / sizeof(a[0])) << endl;
cout << "pointer \t\t\t" << sizeof(&e) << endl;
cout << "Empty class \t\t\t" << sizeof(e) << endl;
cout << "Derived \t\t\t" << sizeof(d) << endl;
cout << "Derived through Base \t\t" << sizeof(b) << endl;
return 0;
}
|
#include "graph.hpp"
#include <stdexcept>
#include <fstream>
// format: 1 line = 1 node
// first line followed by it's neighbours.
// separator is an empty new line
// std::string vertexSerializer(const V& v) converts V into std::string
// V vertexCreator(const std::string&s) converts std::string to V
template <typename V, typename F>
Graph<V> readGraphFromPlainText(const std::string& filename, F vertexCreator)
{
std::ifstream file(filename);
if (!file.good())
throw std::runtime_error("Failed to open " + filename + " to read.");
Graph<V> g;
std::string line;
while (std::getline(file, line))
if (!line.empty())
break;
bool new_entry = true;
V current_vertex;
while (std::getline(file, line)) {
if (line.empty()) {
new_entry = true;
} else {
if (new_entry) {
current_vertex = vertexCreator(line);
g.addVertex(current_vertex);
new_entry = false;
} else {
g.addEdge(current_vertex, vertexCreator(line));
}
}
}
return g;
}
template <typename V, typename F>
void writeGraphToPlainText(const Graph<V>& g, const std::string& filename, F vertexSerializer)
{
std::ofstream file;
file.open (filename);
if (!file.is_open())
throw std::runtime_error("Failed to open " + filename + " to write.");
for (const auto cit : g) {
file << vertexSerializer(cit) << std::endl;
for (const auto cit2 : g.neighboursOf(cit))
file << vertexSerializer(cit2) << std::endl;
file << std::endl;
}
file.close();
}
|
#include "natives.hpp"
#include "CLogManager.hpp"
#include <fmt/format.h>
// native Logger:CreateLog(const name[], E_LOGLEVEL:level = INFO | WARNING | ERROR, bool:debuginfo = true);
AMX_DECLARE_NATIVE(Native::CreateLog)
{
const char *name = nullptr;
amx_StrParam(amx, params[1], name);
return CLogManager::Get()->Create(
name, static_cast<LogLevel>(params[2]), params[3] != 0);
}
// native DestroyLog(Logger:logger);
AMX_DECLARE_NATIVE(Native::DestroyLog)
{
const LoggerId_t logid = params[1];
if (CLogManager::Get()->IsValid(logid) == false)
return 0;
return CLogManager::Get()->Destroy(logid) ? 1 : 0;
}
// native SetLogLevel(Logger:logger, E_LOGLEVEL:level);
AMX_DECLARE_NATIVE(Native::SetLogLevel)
{
const LoggerId_t logid = params[1];
if (CLogManager::Get()->IsValid(logid) == false)
return 0;
CLogManager::Get()->GetLogger(logid).
SetLogLevel(static_cast<samplog::LogLevel>(params[2]));
return 1;
}
// native bool:IsLogLevel(Logger:logger, E_LOGLEVEL:level);
AMX_DECLARE_NATIVE(Native::IsLogLevel)
{
const LoggerId_t logid = params[1];
if (CLogManager::Get()->IsValid(logid) == false)
return 0;
return CLogManager::Get()->GetLogger(logid).
IsLogLevel(static_cast<samplog::LogLevel>(params[2]));
}
// native Log(Logger:logger, E_LOGLEVEL:level, const msg[], {Float,_}:...);
AMX_DECLARE_NATIVE(Native::Log)
{
const LoggerId_t logid = params[1];
if (CLogManager::Get()->IsValid(logid) == false)
return 0;
auto &logger = CLogManager::Get()->GetLogger(logid);
const samplog::LogLevel loglevel = static_cast<decltype(loglevel)>(params[2]);
if (!logger.IsLogLevel(loglevel))
return 0;
std::string format_str = amx_GetCppString(amx, params[3]);
const unsigned int
first_param_idx = 4,
num_args = (params[0] / sizeof(cell)),
num_dyn_args = num_args - (first_param_idx - 1);
unsigned int param_counter = 0;
fmt::MemoryWriter str_writer;
size_t
spec_pos = std::string::npos,
spec_offset = 0;
while ((spec_pos = format_str.find('%', spec_offset)) != std::string::npos)
{
if (param_counter >= num_dyn_args)
return false; // too many args given
if (spec_pos == (format_str.length() - 1))
return false;
str_writer << format_str.substr(spec_offset, spec_pos - spec_offset);
spec_offset = spec_pos + 2; // 2 = '%' + char specifier (like 'd' or 's')
cell *param_addr = nullptr;
switch (format_str.at(spec_pos + 1))
{
case '%': // '%' escape
str_writer << '%';
break;
case 's': // string
str_writer << amx_GetCppString(amx, params[first_param_idx + param_counter]);
break;
case 'd': // decimal
case 'i': // integer
amx_GetAddr(amx, params[first_param_idx + param_counter], ¶m_addr);
str_writer << static_cast<int>(*param_addr);
break;
case 'f': // float
amx_GetAddr(amx, params[first_param_idx + param_counter], ¶m_addr);
str_writer << amx_ctof(*param_addr);
break;
default:
return false;
}
param_counter++;
}
// copy rest of format string
str_writer << format_str.substr(spec_offset);
return logger.Log(loglevel, str_writer.c_str(), amx) ? 1 : 0;
}
|
#include <iostream>
#include <time.h>
using namespace std;
void main(void) {
//반복문
//1. for문
// 초기화 범위 연산
for (int i = 0; i < 12; i++) {
cout << "haha" << endl;
}
//2중 for문
for (int i = 1; i < 10; i++) {
for (int j = 1; j < 10; j++) {
cout << i << " X " << j << " = " << i * j << endl;
}
}
//2. while문
//참일 때만 동작한다
//기본적으로 무한루프를 돈다
//제어문이 필수적
/*
while (true) {
cout << "꺼내줘!!" << endl;
}
*/
srand(NULL);
int OrcHP = 50000;
int OrcAtk = 0;
int ElfHP = 50000;
int ElfAtk = 0;
while (OrcHP >= 0 && ElfHP >= 0) {
OrcAtk = rand() % 1000;
ElfAtk = rand() % 1000;
OrcHP -= ElfAtk;
ElfHP -= OrcAtk;
cout << "엘프 공격 : " << ElfAtk << endl;
cout << "오크 HP : " << OrcHP << endl;
cout << "오크 반격 : " << OrcAtk << endl;
cout << "엘프 HP : " << ElfHP << endl;
}
//제어문
//1. break : 연산을 중지하고 빠져나간다
//2. continue : 연산을 건너뛴다(처음으로 가는 것처럼 보임)
//3. return : 값을 반환하고 종료
//4. go to : go to home
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
if (i > 5) break;
cout << i << endl;
}
//1. 컴퓨터틑 0 ~ 999 까지의 수 중에 랜덤하게 하나를 갖는다
//2. 플레이어는 10번의 기회가 있다.
//3. 플레이어가 수를 넣으면 컴퓨터는 그 수가 큰지, 작은지, 정답인지 알려준다.
//4. 물론, 잘못 넣으면 예외처리를 해준다
srand(NULL);
int comNum = rand() % 1000;
int inputNum;
int roundCount = 10;
cout << "하하, 내가 무슨 숫자를 생각하고 있는지 10번만에 맞춰보아라." << endl;
while (true) {
cout << "입력 : ";
cin >> inputNum;
if (inputNum == comNum) {
cout << "하하, 정답이다." << endl;
break;
}
if (inputNum < comNum && inputNum >= 0) {
cout << "그 숫자는 내가 생각한 것보다 작다." << endl;
roundCount--;
}
if (inputNum > comNum && inputNum < 1000) {
cout << "그 숫자는 내가 생각한 것보다 크다." << endl;
roundCount--;
}
if (inputNum < 0 || inputNum >= 1000) {
cout << "그 숫자는 정해진 범위의 숫자가 아니다" << endl;
continue;
}
cout << roundCount << "회 남았다" << endl;
if (roundCount <= 0) {
cout << "틀렸다 요놈아!" << endl;
break;
}
}
// Homework
// 0 ~ 9 중에 서로 다른 숫자 3개
// 1. 숫자만 일치하면 Ball
// 2. 위치까지 일치하면 Strike
// 3. 전혀 일치하지 않으면 Out
}
|
#include <iostream>
using namespace std;
int MyFun(int *p, int s)
{
int min = p[0];
for (int i = 0; i < s; i++)
{
if (min > p[i])
min = p[i];
}
int x=min;
for(int i=0;i<s;i++)
{
if(p[i]>=x)
{
cout<<p[i]<<" ";
x=p[i];
}
}
cout<<endl;
return 0;
}
int main()
{
int n;
cout<<"Enter Array size: ";
cin >> n;
int *array = new int[n];
cout<<"Enter Values: "<<endl;
for(int i=0;i<n;i++)
{
cin>>array[i];
}
MyFun(array,n);
return 0;
}
//time Complexity= O(N)
|
# include <Attributes.hpp>
Attributes::Attributes(short unsigned health)
: m_health(health)
{
// empty
}
const short unsigned & Attributes::get_health() const
{
return m_health;
}
void Attributes::healted()
{
if(m_health < 3)
++m_health;
}
void Attributes::attacked()
{
if(m_health > 0)
--m_health;
m_attackable = false;
m_attacked = true;
}
bool Attributes::recentlyAttacked()
{
if(m_attacked)
{
m_attacked = false; // restore it's condition
return true;
}
return false;
}
void Attributes::restoreAttackable()
{
m_attackable = true;
}
void Attributes::inmortal()
{
m_attackable = false;
}
bool Attributes::attackable() const
{
return m_attackable;
}
bool Attributes::dead() const
{
return m_health == 0;
}
|
#pragma once
#include "ofMain.h"
#include "rectangle.hpp"
#include "Mover.hpp"
#include "machina.hpp"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
int Number;
rectangle wave;
ofSoundPlayer Lent;
ofImage boat;
ofImage petal;
ofImage bird;
vector <ofPoint> pos;
vector <ofPoint> vel;
vector <ofPoint> wForce;
vector <ofPoint> gForce;
vector <Mover> movers;
vector <machina> machinas;
int machinasAlpha;
bool display2 = true;
bool display1 = true;
};
|
#ifndef ANIREMSETTINGSVIEWMODEL_H
#define ANIREMSETTINGSVIEWMODEL_H
#include "datasyncsettingsviewmodel.h"
#include "imageloader.h"
class AniremSettingsViewModel : public DataSyncSettingsViewModel
{
Q_OBJECT
QTMVVM_INJECT_PROP(ImageLoader*, imageLoader, _loader)
public:
Q_INVOKABLE explicit AniremSettingsViewModel(QObject *parent = nullptr);
void saveValue(const QString &key, const QVariant &value) override;
void resetValue(const QString &key) override;
public slots:
void callAction(const QString &key, const QVariantMap ¶meters) override;
private:
ImageLoader *_loader;
};
#endif // ANIREMSETTINGSVIEWMODEL_H
|
#ifndef Automovil_h
#define Automovil_h
#include "Nave.h"
class Automovil: public Nave
{
private:
std::string color;
public:
// Constructores
Automovil();
Automovil(std::string, std::string, double, Piloto); // string color, string fabricante, double precio, Piloto piloto;
// Getters y Setters
std::string getColor() const;
void setColor(std::string);
// Métodos
void imprime() override;
};
Automovil::Automovil(){
color = "-";
}
Automovil::Automovil(std::string c, std::string fab, double pr, Piloto pl):Nave(fab, pr, pl){
color = c;
}
std::string Automovil::getColor() const {
return color;
}
void Automovil::setColor(std::string c){
color = c;
}
void Automovil::imprime(){
Nave::imprime();
std::cout << "-.-ATRIBUTOS AUTOMOVIL-.-" << std::endl;
std::cout << "Color: " << getColor() << std::endl;
std:: cout << "-.-.-.-.-.-.-.-.-.-.-.-" << std::endl << std::endl;
}
#endif
|
#include "Application.hpp"
int main(){
Application* App = new Application (800,600);
App->EventHandle();
return EXIT_SUCCESS;
}
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* error1 = NULL;
TreeNode* error2 = NULL;
TreeNode* pre = NULL;
while(root != NULL || !s.empty())
{
while(root != NULL)
{
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
if(pre == NULL) pre = root;
else
{
if(pre->val >= root->val)
{
error2 = root;
if(error1 == NULL) error1 = pre;
else break;
}
}
pre = root;
root = root->right;
}
swap(error1->val,error2->val);
}
};
|
/*
Name: Mohit Kishorbhai Sheladiya
Student ID: 117979203
Student Email: mksheladiya@myseneca.ca
Date: 21/01/27
*/
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include "File.h"
#include "Employee.h"
namespace sdds {
FILE* fptr;
bool openFile(const char filename[]) {
fptr = fopen(filename, "r");
return fptr != NULL;
}
int noOfRecords() {
int noOfRecs = 0;
char ch;
while (fscanf(fptr, "%c", &ch) == 1) {
noOfRecs += (ch == '\n');
}
rewind(fptr);
return noOfRecs;
}
void closeFile() {
if (fptr) fclose(fptr);
}
bool read(int& number) { // This function is defined to get employee number of the employee from the file
if (fscanf(fptr, "%d,", &number) == 1) {
return true;
} else {
return false;
}
}
bool read(double& salary) { // This function is defined to get employee salary of the employee from the file
if (fscanf(fptr, "%lf,", &salary) == 1) {
return true;
} else {
return false;
}
}
bool read(char* name) { // This function is defined to get name of the employee from the file
if (fscanf(fptr, "%[^\n]\n", name) == 1) {
return true;
} else {
return false;
}
}
}
|
/*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
type sets;
libs ("libsampling.so");
setFormat csv;
interpolationScheme cellPoint;
fields
(
UMean
);
sets
(
nacelle
{{
type points;
axis xyz;
ordered false;
points
(
{points}
);
}}
);
// ************************************************************************* //
|
/* Copyright (C) 2015 Willi Menapace <willi.menapace@gmail.com>, Simone Lorengo <simone@lorengo.org> - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Simone Lorengo <simone@lorengo.org>
*/
#ifndef CURRENT_SENSOR_INCLUDED
#define CURRENT_SENSOR_INCLUDED
#include "GlobalDefines.h"
#ifdef ONBOARD
#include "EmonLib.h"
#include "Sensor.h"
/**
* Rappresenta un sensore di corrente elettrica alternata
* Modello di riferimento: ACS712 20A
*/
class CurrentSensor : public Sensor {
private:
SensorType type;
int sensorPin;
long offset;
EnergyMonitor sensor;
/**
* @return valore non elaborato
*/
long getRaw();
public:
SensorType getType();
/**
* @return valore elaborato del sensore in Amper RMS (Irms)
*/
long readValue();
/**
* Imposta un offset per la calibrazione del sensore
*/
void setOffset(long calibOffset);
/**
* Crea un sensore di tipo CURRENT
*/
CurrentSensor(int sensorAnalogPin);
};
#endif //ONBOARD
#endif // CURRENT_SENSOR_INCLUDED
|
#include <cstdio>
int get_id(int pa);
int main() {
typedef struct {
// char no[16];
long long no;
int pa;
int pb;
} List;
int n = 0, // provide N infos
i = 0,
m = 0, // get M infos
tmp = 0;
scanf("%d", &n);
List list[n];
for(i = 0; i < n; i++) {
// scanf("%s %d %d", list[i].no, &list[i].pa, &list[i].pb);
scanf("%lld %d %d", &list[i].no, &list[i].pa, &list[i].pb);
}
scanf("%d", &m);
for(i = 0; i < m; i++) {
scanf("%d", &tmp);
for(int j = 0; j < n; j++) {
if(list[j].pa == tmp)
printf("%lld %d\n", list[j].no, list[j].pb);
}
}
return 0;
}
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
#ifndef POOMA_POOMA_GMPARRAYS_H
#define POOMA_POOMA_GMPARRAYS_H
/** @file
* @ingroup Pooma
* @brief
* A one-stop-shopping header file that sets up everything one needs to use
* GMP-based arrays.
*/
// Include files
#include "Pooma/BrickArrays.h"
#include "Layout/GridLayout.h"
#include "Engine/MultiPatchEngine.h"
#endif // POOMA_POOMA_GMPARRAYS_H
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: GMPArrays.h,v $ $Author: richard $
// $Revision: 1.5 $ $Date: 2004/11/01 18:17:04 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
#include "MinimumHeap.hpp"
#include <stdio.h>
#include <assert.h>
#include <iostream>
using namespace std;
void MinimumHeap::SiftDown(int index) {
int length = _Groups_in_fact;
int leftChildIndex = 2 * index;
int rightChildIndex = 2 * index + 1;
if (leftChildIndex > length){
if(_Groups_in_fact==1){
_heap[1]->SetIndex(1);
}
return; //index is a leaf
}
int minIndex = index;
if (*(_heap[index]) > *(_heap[leftChildIndex])) {
minIndex = leftChildIndex;
}
if ((rightChildIndex <= length)
&& (*(_heap[minIndex]) > *(_heap[rightChildIndex]))) {
minIndex = rightChildIndex;
}
if (minIndex != index) {
_heap[index]->SetIndex(minIndex);
_heap[minIndex]->SetIndex(index);
//need to swap
Group* temp = _heap[index];
_heap[index] = _heap[minIndex];
_heap[minIndex] = temp;
SiftDown(minIndex);
}
}
void MinimumHeap::SiftUp(int index) {
if (index == 1)
return;
int parentIndex = (index ) / 2;
if (*(_heap[parentIndex]) > *(_heap[index])) {
_heap[index]->SetIndex(parentIndex);
_heap[parentIndex]->SetIndex(index);
//need to swap
Group* temp = _heap[parentIndex];
_heap[parentIndex] = _heap[index];
_heap[index] = temp;
SiftUp(parentIndex);
}
}
MinimumHeap::MinimumHeap(int* array, int n) {
_Groups_in_fact = n;
_Groups_in_memory = 2 * n;
_heap = (Group**) new Group*[2 * n+1];
_heap[0]= NULL;
for (int i = 0; i < n; i++) {
_heap[i + 1] = new Group(array[i], i+1);
}
for (int j = n / 2; j > 0; j--) {
SiftDown(j);
}
}
/*MinimumHeap::MinimumHeap() {
_Groups_in_fact = 0;
_Groups_in_memory =0;
}*/
Group* MinimumHeap::Insert(int newValue) {
if (_Groups_in_fact < _Groups_in_memory) {
_Groups_in_fact++;
Group* gr= new Group(newValue,_Groups_in_fact);
_heap[_Groups_in_fact] =gr;
SiftUp (_Groups_in_fact);
return gr;
}else {
assert(_Groups_in_fact==_Groups_in_memory);
Group** arr = (Group**) new Group*[2 * _Groups_in_memory+1];
arr[0]= NULL;
for(int i=1; i<=_Groups_in_memory; i++){
arr[i]=_heap[i];
}
delete [] _heap;
_Groups_in_fact++;
_Groups_in_memory=2* _Groups_in_memory;
_heap=arr;
Group* gr=new Group(newValue,_Groups_in_fact);
_heap[_Groups_in_fact] =gr;
SiftUp (_Groups_in_fact);
return gr;
}
}
int MinimumHeap::FindMin() {
return _heap[1]->GetId();
}
HeapStatus MinimumHeap::DelKey(int index){
delete _heap[index];
if(index== _Groups_in_fact){
_Groups_in_fact--;
return HEAP_SUCCESS; }
_heap[index]=_heap[_Groups_in_fact];
_heap[index]->SetIndex(index);
if(_heap[index]== NULL){
assert(1);
}
//_heap[index]->SetIndex(index);
//_heap[_Groups_in_fact]=NULL;
_Groups_in_fact--;
SiftDown(index);
return HEAP_SUCCESS;
}
Group** MinimumHeap::get_heap(){
return _heap;
}
MinimumHeap::~MinimumHeap(){
/*for (int i=1; i<= _Groups_in_fact; i++){
std::cout<< "i="<< i << std::endl;
delete(_heap[i]);
}*/
delete[] _heap;
}
std::ostream& operator<<(std::ostream& output, const MinimumHeap& heap){
output << "\nHeap:\n";
for(int i=1; i< heap._Groups_in_fact+1 ; i++){
output<<" ID, index : "<< heap._heap[i]->GetId()<<","<< heap._heap[i]->GetIndex()<<" ";
}
return output;
}
|
#include <bits/stdc++.h>
using namespace std;
#define ar array
#define ll long long
const int MAX_N = 1e5 + 1;
const ll MOD = 1e9 + 7;
const ll INF = 1e9;
// CF Contest Global Round # 14 (1515) ProgB
void solve() {
ll n;
cin>>n;
if(n == 0 || (n & 1)){
cout<<"NO\n";
return;
}
if((!(n%2) && ((ll)(sqrt((ll)(n/2))) * (ll)(sqrt( (ll)(n/2))) == (ll)(n/2))) || (!(n%4) && ((ll)(sqrt((ll)(n/4)))) * (ll)(sqrt((ll)(n/4))) == (ll)(n/4)))
cout<<"YES";
else
cout<<"NO";
cout<<"\n";
}
//for(int i = 0; i < n; i++)
//cout<<"\n";
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t=1;
cin>>t;
while(t--)
{
//cout << "Case #" << t << ": ";
solve();
}
//cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
}
|
#include "Item.h"
#include <iostream>
Item::Item() : name("Unknown"), price(0), purpose("Unknown") { //Constructors
}
Item::Item(std::string name, int price, std::string purpose) : name(name), price(price), purpose(purpose) {
}
std::string Item::GetName() { //Getter for the name of the item
return name;
}
void Item::SetName(std::string name) { //Setter for item's name
this->name = name;
}
void Item::SetPrice(int price) { //Setter for item's price
this->price = price;
}
void Item::SetPurpose(std::string purpose) { //Setter for item's purpose
this->purpose = purpose;
}
void Item::PrintInfo() { //Function to print info about the item
std::cout << std::endl;
std::cout << "Item's name is: " << name << ".\nIt costs " << price << " gold." << "\nIt's purpose is " << purpose << "." << std::endl;
}
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 12036 - Stable Grid */
#include <iostream>
#include <vector>
int main() {
int nNoTestCases;
std::cin >> nNoTestCases;
for (int nCaseLoop = 1; nCaseLoop <= nNoTestCases; nCaseLoop++) {
int nN;
std::cin >> nN;
int nNPow2 = nN * nN;
std::vector<int> oVecFreq(101);
bool bSol = true;
for (int nLoop = 0; nLoop < nNPow2; nLoop++) {
int nNumber;
std::cin >> nNumber;
if (++oVecFreq[nNumber] > nN) {
bSol = false;
}
}
std::cout << "Case " << nCaseLoop << ": " << (bSol ? "yes" : "no") << std::endl;
}
return 0;
}
|
#ifndef STICKUINO_COMPONENTS_ACTIVATOR_H
#define STICKUINO_COMPONENTS_ACTIVATOR_H
#include "Component.h"
namespace Stickuino {
namespace Components {
/// <summary>
/// A component which can be active (HIGH) or inactive (LOW).
/// </summary>
class Activator : public Component {
public:
/// <summary>
/// Creates a new Activator.
/// </summary>
/// <param name="pin">The pin this Activator is hooked up to.</param>
/// <param name="debounceDelay">The amount of time to debounce. Set to 0 to disable debouncing.</param>
Activator(const int& pin, const unsigned long& debounceDelay = 0);
/// <summary>
/// Loops the Activator.
/// </summary>
/// <param name="interrupt">The latest interrupt.</param>
void preLoop(volatile int& interrupt) override;
/// <summary>
/// Loops the Activator and switches states.
/// </summary>
/// <param name="interrupt">The latest interrupt.</param>
void postLoop(volatile int& interrupt) override;
/// <summary>
/// Checks whether the Activator has just been activated.
/// </summary>
/// <returns>Whether the Activator has been activated.</returns>
bool isActivated() const;
/// <summary>
/// Checks whether the Activator has just been deactivated.
/// </summary>
/// <returns>Whether the Activator has been deactivated.</returns>
bool isDeactivated() const;
/// <summary>
/// Checks whether the Activator is active.
/// </summary>
/// <returns>Whether the activator is active.</returns>
bool isActive() const;
/// <summary>
/// Checks whether the Activator is inactive.
/// </summary>
/// <returns>Whether the activator is inactive.</returns>
bool isInactive() const;
private:
/// <summary>
/// The amount of time to debounce.
/// </summary>
unsigned long debounceDelay_;
/// <summary>
/// The last time debouncing was performed.
/// </summary>
unsigned long lastDebounceTime_ = 0;
/// <summary>
/// The state of the Activator in the last frame.
/// </summary>
bool lastState_ = false;
/// <summary>
/// The last state before the current one, when including debouncing.
/// </summary>
bool lastDebouncedState_ = false;
/// <summary>
/// The debounced state.
/// </summary>
bool debouncedState_ = false;
};
}
}
#endif
|
#include "cybModel.h"
#include "cybUpdateModel.h"
CybUpdateModel::~CybUpdateModel(){}
|
#pragma once
#include "Common.h"
#include "SDL.h"
#include "SDL_syswm.h"
#include "GluStuff.h"
#ifndef FO_OGL_ES
# include "GL/glew.h"
# include "SDL_opengl.h"
#else
# include "SDL_opengles2.h"
#endif
#include "SDL_vulkan.h"
#ifdef FO_MSVC
# pragma comment( lib, "opengl32.lib" )
# pragma comment( lib, "glu32.lib" )
# pragma comment( lib, "Version.lib" )
# pragma comment( lib, "Winmm.lib" )
# pragma comment( lib, "Imm32.lib" )
#endif
#ifdef FO_HAVE_DX
# include <d3d9.h>
# ifdef FO_MSVC
# pragma comment(lib, "d3d9")
# pragma comment(lib, "gdi32")
# endif
#endif
#ifndef FO_OGL_ES
# ifdef FO_MAC
# undef glGenVertexArrays
# undef glBindVertexArray
# undef glDeleteVertexArrays
# define glGenVertexArrays glGenVertexArraysAPPLE
# define glBindVertexArray glBindVertexArrayAPPLE
# define glDeleteVertexArrays glDeleteVertexArraysAPPLE
# endif
#else
# define glGenVertexArrays glGenVertexArraysOES
# define glBindVertexArray glBindVertexArrayOES
# define glDeleteVertexArrays glDeleteVertexArraysOES
# define glGenFramebuffersEXT glGenFramebuffers
# define glBindFramebufferEXT glBindFramebuffer
# define glFramebufferTexture2DEXT glFramebufferTexture2D
# define glRenderbufferStorageEXT glRenderbufferStorage
# define glGenRenderbuffersEXT glGenRenderbuffers
# define glBindRenderbufferEXT glBindRenderbuffer
# define glFramebufferRenderbufferEXT glFramebufferRenderbuffer
# define glCheckFramebufferStatusEXT glCheckFramebufferStatus
# define glDeleteRenderbuffersEXT glDeleteRenderbuffers
# define glDeleteFramebuffersEXT glDeleteFramebuffers
# define glProgramBinary( a, b, c, d )
# define glGetProgramBinary( a, b, c, d, e )
# define glProgramParameteri glProgramParameteriEXT
# define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0
# define GL_PROGRAM_BINARY_LENGTH 0
# define GL_FRAMEBUFFER_COMPLETE_EXT GL_FRAMEBUFFER_COMPLETE
# define GL_FRAMEBUFFER_EXT GL_FRAMEBUFFER
# ifndef GL_COLOR_ATTACHMENT0_EXT
# define GL_COLOR_ATTACHMENT0_EXT GL_COLOR_ATTACHMENT0
# endif
# define GL_RENDERBUFFER_EXT GL_RENDERBUFFER
# define GL_DEPTH_ATTACHMENT_EXT GL_DEPTH_ATTACHMENT
# define GL_RENDERBUFFER_BINDING_EXT GL_RENDERBUFFER_BINDING
# define GL_CLAMP GL_CLAMP_TO_EDGE
# define GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES
# define GL_DEPTH24_STENCIL8_EXT GL_DEPTH24_STENCIL8_OES
# define GL_STENCIL_ATTACHMENT_EXT GL_STENCIL_ATTACHMENT
# define glGetTexImage( a, b, c, d, e )
# define glDrawBuffer( a )
# ifndef GL_MAX_COLOR_TEXTURE_SAMPLES
# define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E
# endif
# ifndef GL_TEXTURE_2D_MULTISAMPLE
# define GL_TEXTURE_2D_MULTISAMPLE 0x9100
# endif
# ifndef GL_MAX
# define GL_MAX GL_MAX_EXT
# define GL_MIN GL_MIN_EXT
# endif
# if defined ( FO_IOS )
# define glTexImage2DMultisample( a, b, c, d, e, f )
# define glRenderbufferStorageMultisample glRenderbufferStorageMultisampleAPPLE
# define glRenderbufferStorageMultisampleEXT glRenderbufferStorageMultisampleAPPLE
# elif defined ( FO_ANDROID )
# define glGenVertexArraysOES glGenVertexArraysOES_
# define glBindVertexArrayOES glBindVertexArrayOES_
# define glDeleteVertexArraysOES glDeleteVertexArraysOES_
# define glTexImage2DMultisample glFramebufferTexture2DMultisampleIMG_
# define glRenderbufferStorageMultisample glRenderbufferStorageMultisampleIMG_
# define glRenderbufferStorageMultisampleEXT glRenderbufferStorageMultisampleIMG_
extern PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES_;
extern PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES_;
extern PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES_;
extern PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC glFramebufferTexture2DMultisampleIMG_;
extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC glRenderbufferStorageMultisampleIMG_;
# elif defined ( FO_WEB )
# define glTexImage2DMultisample( a, b, c, d, e, f )
# define glRenderbufferStorageMultisample( a, b, c, d, e )
# define glRenderbufferStorageMultisampleEXT( a, b, c, d, e )
# endif
#endif
#define GL( expr ) { expr; if( GameOpt.OpenGLDebug ) { GLenum err__ = glGetError(); RUNTIME_ASSERT_STR( err__ == GL_NO_ERROR, _str( # expr " error {:#X}", err__ ) ); } }
extern bool OGL_version_2_0;
extern bool OGL_vertex_buffer_object;
extern bool OGL_framebuffer_object;
extern bool OGL_framebuffer_object_ext;
extern bool OGL_framebuffer_multisample;
extern bool OGL_packed_depth_stencil;
extern bool OGL_texture_multisample;
extern bool OGL_vertex_array_object;
extern bool OGL_get_program_binary;
#define GL_HAS( extension ) ( OGL_ ## extension )
namespace GraphicApi
{
bool Init();
}
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <Transformation.h>
#include <CompositeTransformation.h>
#include <ID.h>
namespace test {
using namespace std;
using ::testing::Contains;
using ::testing::Return;
using ::testing::AllOf;
using ::testing::Pointee;
using ::testing::UnorderedElementsAre;
using ::testing::Each;
using ::testing::SizeIs;
using ::testing::_;
struct BufferingTestSuite : public ::testing::Test {
using Events = Transformer::Events;
using EventTypes = Transformer::EventTypes;
struct TestTransformer : public BufferedTransformer {
using EventPtrs = BufferedTransformer::EventPtrs;
string name;
TestTransformer(const string& name, const EventType& out, const EventTypes& in)
: BufferedTransformer(out, in, AbstractPolicy()), name(name) {}
MOCK_CONST_METHOD1(check, bool(const MetaEvent&));
MOCK_CONST_METHOD1(execute, Events(const EventPtrs&));
virtual void print(ostream& o) const { o << name; }
};
struct TestTransformation : public Transformation {
string name;
TestTransformation(const string& name, size_t arity)
: Transformation(Type::attribute, arity, EventID::any), name(name) { }
MOCK_CONST_METHOD3(in, EventTypes(const EventType& goal, const EventType& provided, const MetaFilter& filter));
MOCK_CONST_METHOD2(in, EventIDs(EventID goal, const MetaFilter& filter));
MOCK_CONST_METHOD4(create, TransPtr(const EventType& out, const EventTypes& in, const AbstractPolicy& policy, const MetaFilter& filter));
virtual void print(ostream& o) const { o << name; }
};
Events gen(const EventTypes& eTs) const {
Events e;
for(const EventType& eT: eTs)
e.emplace_back(eT);
return e;
}
Events execute(Transformer& t, const Events& in) const {
Events result;
for(const MetaEvent& e : in) {
Events temp = t(e);
move(temp.begin(), temp.end(), back_inserter(result));
}
return result;
}
EventType outET, inET0, inET1, inET2, tET0, tET1;
const id::attribute::ID outID=250, inID0=251, inID1=252, inID2=253, tID0=254, tID1=255;
BufferingTestSuite() {
ValueType v(id::type::Float::value(), 1, 1, false);
AttributeType outAT (outID, v, Scale<>(), Dimensionless());
AttributeType inAT0 (inID0, v, Scale<>(), Dimensionless());
AttributeType inAT1 (inID1, v, Scale<>(), Dimensionless());
AttributeType inAT2 (inID2, v, Scale<>(), Dimensionless());
AttributeType tAT0 (tID0, v, Scale<>(), Dimensionless());
AttributeType tAT1 (tID1, v, Scale<>(), Dimensionless());
outET.add(outAT);
inET0.add(inAT0);
inET1.add(inAT1);
inET2.add(inAT2);
tET0.add(tAT0);
tET1.add(tAT1);
}
};
TEST_F(BufferingTestSuite, singleHetTest) {
MetaEvent out(outET);
Events in = gen({inET0, inET1, inET0, inET1});
out.attribute(outID)->value().set(0,0,3);
in[0].attribute(inID0)->value().set(0,0,1);
in[1].attribute(inID1)->value().set(0,0,2);
in[2].attribute(inID0)->value().set(0,0,10);
in[3].attribute(inID1)->value().set(0,0,20);
EXPECT_NE(in[0], in[2]);
EXPECT_NE(in[1], in[3]);
TestTransformer t("SingleHet", outET, {inET0, inET1});
EXPECT_CALL(t, check(_)).WillRepeatedly(Return(false));
EXPECT_CALL(t, check(in[0])).Times(1).WillOnce(Return(true));
EXPECT_CALL(t, check(in[1])).Times(1).WillOnce(Return(true));
EXPECT_CALL(t, execute( AllOf(
Contains(Pointee(in[0])),
Contains(Pointee(in[1]))
))).Times(1).WillOnce(Return(Events({out})));
EXPECT_THAT(execute(t, in), Events({out}));
}
TEST_F(BufferingTestSuite, singleHomTest) {
MetaEvent out(outET);
Events in = gen({inET0, inET0, inET0, inET0});
out.attribute(outID)->value().set(0,0,3);
in[0].attribute(inID0)->value().set(0,0,1);
in[1].attribute(inID0)->value().set(0,0,2);
in[2].attribute(inID0)->value().set(0,0,10);
in[3].attribute(inID0)->value().set(0,0,20);
EXPECT_NE(in[0], in[2]);
EXPECT_NE(in[1], in[3]);
TestTransformer t("SingleHom", outET, {inET0, inET0});
EXPECT_CALL(t, check(_)).WillRepeatedly(Return(false));
EXPECT_CALL(t, check(in[0])).Times(1).WillOnce(Return(true));
EXPECT_CALL(t, check(in[1])).Times(1).WillOnce(Return(true));
EXPECT_CALL(t, execute( UnorderedElementsAre(
Pointee(in[0]),
Pointee(in[1])
))).Times(2).WillRepeatedly(Return(Events({out})));
EXPECT_THAT(execute(t, in), Events({out, out}));
}
TEST_F(BufferingTestSuite, multiHetTest) {
MetaEvent out(outET);
Events in = gen({inET0, inET1, inET2});
MetaEvent temp0(tET0), temp1(tET1);
out.attribute(outID)->value().set(0,0,3);
in[0].attribute(inID0)->value().set(0,0,1);
in[1].attribute(inID1)->value().set(0,0,2);
in[2].attribute(inID2)->value().set(0,0,10);
temp0.attribute(tID0)->value().set(0,0,5);
temp1.attribute(tID1)->value().set(0,0,6);
auto nothing = [](void *){};
TestTransformer a("a", tET0, {inET0, inET1}), b("b", tET1, {inET1, inET2}), c("c", outET, {tET0, tET1});
TestTransformation aT("aT", 2), bT("bT", 2), cT("cT", 2);
EXPECT_CALL(aT, in(tET0, _, _)).Times(1).WillOnce(Return(EventTypes({inET0, inET1})));
EXPECT_CALL(bT, in(tET1, _, _)).Times(1).WillOnce(Return(EventTypes({inET1, inET2})));
EXPECT_CALL(cT, in(outET, _, _)).Times(1).WillOnce(Return(EventTypes({tET0, tET1})));
CompositeTransformation compTrans(TransformationPtr(&cT), outET, EventType());
compTrans.add(TransformationPtr(&aT), compTrans.root(), tET0, EventType());
compTrans.add(TransformationPtr(&bT), compTrans.root(), tET1, EventType());
using TransPtr = Transformation::TransPtr;
EXPECT_CALL(aT, create(tET0,EventTypes({inET0, inET1}),_, _))
.Times(1).WillOnce(Return(TransPtr(&a, nothing)));
EXPECT_CALL(bT, create(tET1,EventTypes({inET1, inET2}),_, _))
.Times(1).WillOnce(Return(TransPtr(&b, nothing)));
EXPECT_CALL(cT, create(outET,EventTypes({tET0, tET1}),_, _))
.Times(1).WillOnce(Return(TransPtr(&c, nothing)));
TransPtr tPtr = compTrans.create(AbstractPolicy());
ASSERT_NE(tPtr, nullptr);
EXPECT_CALL(a, check(_)).WillRepeatedly(Return(false));
EXPECT_CALL(a, check(in[0])).Times(1).WillOnce(Return(true));
EXPECT_CALL(a, check(in[1])).Times(1).WillOnce(Return(true));
EXPECT_CALL(b, check(_)).WillRepeatedly(Return(false));
EXPECT_CALL(b, check(in[1])).Times(1).WillOnce(Return(true));
EXPECT_CALL(b, check(in[2])).Times(1).WillOnce(Return(true));
EXPECT_CALL(c, check(_)).WillRepeatedly(Return(false));
EXPECT_CALL(c, check(temp0)).Times(1).WillOnce(Return(true));
EXPECT_CALL(c, check(temp1)).Times(1).WillOnce(Return(true));
EXPECT_CALL(a, execute( UnorderedElementsAre(
Pointee(in[0]),
Pointee(in[1])
))).Times(1).WillRepeatedly(Return(Events({temp0})));
EXPECT_CALL(b, execute( UnorderedElementsAre(
Pointee(in[1]),
Pointee(in[2])
))).Times(1).WillRepeatedly(Return(Events({temp1})));
EXPECT_CALL(c, execute( UnorderedElementsAre(
Pointee(temp0),
Pointee(temp1)
))).Times(1).WillRepeatedly(Return(Events({out})));
EXPECT_THAT(execute(*tPtr, in), Events({out}));
}
TEST_F(BufferingTestSuite, complexTest) {
MetaEvent out(outET);
Events in = gen({inET0, inET0, inET1, inET1});
MetaEvent temp0(tET0), temp1(tET1);
out.attribute(outID)->value().set(0,0,3);
in[0].attribute(inID0)->value().set(0,0,1);
in[1].attribute(inID0)->value().set(0,0,2);
in[2].attribute(inID1)->value().set(0,0,10);
in[3].attribute(inID1)->value().set(0,0,9);
temp0.attribute(tID0)->value().set(0,0,5);
temp1.attribute(tID1)->value().set(0,0,6);
auto nothing = [](void *){};
TestTransformer a("a", tET0, {inET0, inET0}), b("b", tET1, {inET1, inET1}), c("c", outET, {tET0, tET1});
TestTransformation aT("aT", 2), bT("bT", 2), cT("cT", 2);
EXPECT_CALL(aT, in(tET0, _, _)).Times(1).WillOnce(Return(EventTypes({inET0, inET0})));
EXPECT_CALL(bT, in(tET1, _, _)).Times(1).WillOnce(Return(EventTypes({inET1, inET1})));
EXPECT_CALL(cT, in(outET, _, _)).Times(1).WillOnce(Return(EventTypes({tET0, tET1})));
CompositeTransformation compTrans(TransformationPtr(&cT), outET, EventType());
compTrans.add(TransformationPtr(&aT), compTrans.root(), tET0, EventType());
compTrans.add(TransformationPtr(&bT), compTrans.root(), tET1, EventType());
using TransPtr = Transformation::TransPtr;
EXPECT_CALL(aT, create(tET0,EventTypes({inET0, inET0}),_, _))
.Times(1).WillOnce(Return(TransPtr(&a, nothing)));
EXPECT_CALL(bT, create(tET1,EventTypes({inET1, inET1}),_, _))
.Times(1).WillOnce(Return(TransPtr(&b, nothing)));
EXPECT_CALL(cT, create(outET,EventTypes({tET0, tET1}),_, _))
.Times(1).WillOnce(Return(TransPtr(&c, nothing)));
TransPtr tPtr = compTrans.create(AbstractPolicy());
ASSERT_NE(tPtr, nullptr);
EXPECT_CALL(a, check(_)).WillRepeatedly(Return(false));
EXPECT_CALL(a, check(in[0])).Times(1).WillOnce(Return(true));
EXPECT_CALL(a, check(in[1])).Times(1).WillOnce(Return(true));
EXPECT_CALL(b, check(_)).WillRepeatedly(Return(false));
EXPECT_CALL(b, check(in[2])).Times(1).WillOnce(Return(true));
EXPECT_CALL(b, check(in[3])).Times(1).WillOnce(Return(true));
EXPECT_CALL(c, check(_)).WillRepeatedly(Return(false));
EXPECT_CALL(c, check(temp0)).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(c, check(temp1)).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(a, execute( UnorderedElementsAre(
Pointee(in[0]),
Pointee(in[1])
))).Times(2).WillRepeatedly(Return(Events({temp0})));
EXPECT_CALL(b, execute( UnorderedElementsAre(
Pointee(in[2]),
Pointee(in[3])
))).Times(2).WillRepeatedly(Return(Events({temp1})));
EXPECT_CALL(c, execute( UnorderedElementsAre(
Pointee(temp0),
Pointee(temp1)
))).Times(4).WillRepeatedly(Return(Events({out})));
EXPECT_THAT(execute(*tPtr, in), AllOf(SizeIs(4), Each(out)));
}
}
|
#ifndef Included_MontonCartas_H
#define Included_MontonCartas_H
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "Carta.h"
using namespace std;
class MontonCartas
{
Carta *p; // this is our stack, a simple pointer. Yeah, amazing xD
Carta *deleted;
void intercambiar(int pos1, int pos2);
void eliminarCarta(int pos);
void recursiveDelete (Carta* &pointer);
public:
MontonCartas(); // constructor that builds an empty Spanish card stack
MontonCartas(int todas); // constructor that builds a complete Spanish card stack
~MontonCartas();
MontonCartas& operator= (const MontonCartas& orig);
void mezclar ();
void insertarCarta (int n, char tipo);
void printMonton ();
int sizeMonton ();
int getNumeroCarta (int pos) const;
char getPaloCarta (int pos) const;
Carta* getCarta (int pos) ;
Carta* sacarCarta (int pos) ;
};
#endif
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006-2010 MStar Semiconductor, Inc.
// All rights reserved.
//
// Unless otherwise stipulated in writing, any and all information contained
// herein regardless in any format shall remain the sole proprietary of
// MStar Semiconductor Inc. and be kept in strict confidence
// (''MStar Confidential Information'') by the recipient.
// Any unauthorized act including without limitation unauthorized disclosure,
// copying, use, reproduction, sale, distribution, modification, disassembling,
// reverse engineering and compiling of the contents of MStar Confidential
// Information is unlawful and strictly prohibited. MStar hereby reserves the
// rights to any and all damages, losses, costs and expenses resulting therefrom.
//
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// This file is automatically generated by SkinTool [Version:0.2.3][Build:Dec 18 2014 17:25:00]
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// Window List (Position)
WINDOWPOSDATA _MP_TBLSEG _GUI_WindowPositionList_Zui_Install_Guide_Atsc[] =
{
// HWND_MAINFRAME
{
HWND_MAINFRAME, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_PROGRESSBAR,
{ 0, 0, 334, 264 },
},
// HWND_INSTALL_BACKGROUND_ATSC
{
HWND_MAINFRAME, HWND_INSTALL_BACKGROUND_OK,
{ 0, 0, 334, 264 },
},
// HWND_INSTALL_BACKGROUND_BG_L
{
HWND_INSTALL_BACKGROUND_ATSC, HWND_INSTALL_BACKGROUND_BG_L,
{ 0, 0, 2, 232 },
},
// HWND_INSTALL_BACKGROUND_BG_C
{
HWND_INSTALL_BACKGROUND_ATSC, HWND_INSTALL_BACKGROUND_BG_C,
{ 3, 0, 329, 232 },
},
// HWND_INSTALL_BACKGROUND_BG_R
{
HWND_INSTALL_BACKGROUND_ATSC, HWND_INSTALL_BACKGROUND_BG_R,
{ 332, 0, 2, 232 },
},
// HWND_INSTALL_BACKGROUND_MENU
{
HWND_INSTALL_BACKGROUND_ATSC, HWND_INSTALL_BACKGROUND_MENU,
{ 13, 210, 47, 16 },
},
// HWND_INSTALL_BACKGROUND_OK
{
HWND_INSTALL_BACKGROUND_ATSC, HWND_INSTALL_BACKGROUND_OK,
{ 288, 210, 34, 16 },
},
// HWND_INSTALL_MAIN_PAGE_ATSC
{
HWND_MAINFRAME, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_PROGRESSBAR,
{ 12, 5, 6, 3 },
},
// HWND_INSTALL_MAIN_TITLE_ATSC
{
HWND_INSTALL_MAIN_PAGE_ATSC, HWND_INSTALL_MAIN_TITLE_ATSC,
{ 31, 0, 274, 38 },
},
// HWND_INSTALL_MAIN_PAGE_LANGUAGE
{
HWND_INSTALL_MAIN_PAGE_ATSC, HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT_TEXT,
{ 33, 46, 6, 4 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_TITLE
{
HWND_INSTALL_MAIN_PAGE_LANGUAGE, HWND_INSTALL_MAIN_OSD_LANGUAGE_TITLE_TEXT,
{ 0, 175, 334, 24 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_TITLE_TEXT
{
HWND_INSTALL_MAIN_OSD_LANGUAGE_TITLE, HWND_INSTALL_MAIN_OSD_LANGUAGE_TITLE_TEXT,
{ 0, 175, 334, 24 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE
{
HWND_INSTALL_MAIN_PAGE_LANGUAGE, HWND_INSTALL_MAIN_OSD_LANGUAGE_RIGHT_ARROW,
{ 0, 43, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_FOCUS_BG
{
HWND_INSTALL_MAIN_OSD_LANGUAGE, HWND_INSTALL_MAIN_OSD_LANGUAGE_FOCUS_BG,
{ 0, 43, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_TEXT
{
HWND_INSTALL_MAIN_OSD_LANGUAGE, HWND_INSTALL_MAIN_OSD_LANGUAGE_TEXT,
{ 44, 43, 180, 29 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_OPTION
{
HWND_INSTALL_MAIN_OSD_LANGUAGE, HWND_INSTALL_MAIN_OSD_LANGUAGE_OPTION,
{ 210, 43, 93, 30 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_LEFT_ARROW
{
HWND_INSTALL_MAIN_OSD_LANGUAGE, HWND_INSTALL_MAIN_OSD_LANGUAGE_LEFT_ARROW,
{ 4, 52, 10, 10 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_RIGHT_ARROW
{
HWND_INSTALL_MAIN_OSD_LANGUAGE, HWND_INSTALL_MAIN_OSD_LANGUAGE_RIGHT_ARROW,
{ 322, 52, 10, 10 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT
{
HWND_INSTALL_MAIN_PAGE_LANGUAGE, HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT_TEXT,
{ 0, 75, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT_RIGHT_ARROW
{
HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT, HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT_RIGHT_ARROW,
{ 0, 75, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT_TEXT
{
HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT, HWND_INSTALL_MAIN_OSD_LANGUAGE_NEXT_TEXT,
{ 0, 75, 334, 29 },
},
// HWND_INSTALL_MAIN_PAGE_TIME
{
HWND_INSTALL_MAIN_PAGE_ATSC, HWND_INSTALL_MAIN_OSD_TIME_FORMAT_RIGHT_ARROW,
{ 33, 46, 6, 4 },
},
// HWND_INSTALL_MAIN_OSD_TIME_TITLE
{
HWND_INSTALL_MAIN_PAGE_TIME, HWND_INSTALL_MAIN_OSD_TIME_TITLE_TEXT,
{ 0, 175, 334, 24 },
},
// HWND_INSTALL_MAIN_OSD_TIME_TITLE_TEXT
{
HWND_INSTALL_MAIN_OSD_TIME_TITLE, HWND_INSTALL_MAIN_OSD_TIME_TITLE_TEXT,
{ 0, 175, 334, 24 },
},
// HWND_INSTALL_MAIN_OSD_TIME
{
HWND_INSTALL_MAIN_PAGE_TIME, HWND_INSTALL_MAIN_OSD_TIME_RIGHT_ARROW,
{ 0, 43, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_FOCUS_BG
{
HWND_INSTALL_MAIN_OSD_TIME, HWND_INSTALL_MAIN_OSD_TIME_FOCUS_BG,
{ 0, 43, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_TEXT
{
HWND_INSTALL_MAIN_OSD_TIME, HWND_INSTALL_MAIN_OSD_TIME_TEXT,
{ 44, 43, 180, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_OPTION
{
HWND_INSTALL_MAIN_OSD_TIME, HWND_INSTALL_MAIN_OSD_TIME_OPTION,
{ 210, 43, 93, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_LEFT_ARROW
{
HWND_INSTALL_MAIN_OSD_TIME, HWND_INSTALL_MAIN_OSD_TIME_LEFT_ARROW,
{ 4, 52, 10, 10 },
},
// HWND_INSTALL_MAIN_OSD_TIME_RIGHT_ARROW
{
HWND_INSTALL_MAIN_OSD_TIME, HWND_INSTALL_MAIN_OSD_TIME_RIGHT_ARROW,
{ 322, 52, 10, 10 },
},
// HWND_INSTALL_MAIN_OSD_TIME_NEXT
{
HWND_INSTALL_MAIN_PAGE_TIME, HWND_INSTALL_MAIN_OSD_TIME_NEXT_TEXT,
{ 0, 137, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_NEXT_RIGHT_ARROW
{
HWND_INSTALL_MAIN_OSD_TIME_NEXT, HWND_INSTALL_MAIN_OSD_TIME_NEXT_RIGHT_ARROW,
{ 0, 137, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_NEXT_TEXT
{
HWND_INSTALL_MAIN_OSD_TIME_NEXT, HWND_INSTALL_MAIN_OSD_TIME_NEXT_TEXT,
{ 0, 137, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT
{
HWND_INSTALL_MAIN_PAGE_TIME, HWND_INSTALL_MAIN_OSD_TIME_FORMAT_RIGHT_ARROW,
{ 0, 72, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_FOCUS_BG
{
HWND_INSTALL_MAIN_OSD_TIME_FORMAT, HWND_INSTALL_MAIN_OSD_TIME_FORMAT_FOCUS_BG,
{ 0, 72, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_TEXT
{
HWND_INSTALL_MAIN_OSD_TIME_FORMAT, HWND_INSTALL_MAIN_OSD_TIME_FORMAT_TEXT,
{ 44, 72, 180, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_OPTION
{
HWND_INSTALL_MAIN_OSD_TIME_FORMAT, HWND_INSTALL_MAIN_OSD_TIME_FORMAT_OPTION,
{ 210, 72, 93, 29 },
},
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_LEFT_ARROW
{
HWND_INSTALL_MAIN_OSD_TIME_FORMAT, HWND_INSTALL_MAIN_OSD_TIME_FORMAT_LEFT_ARROW,
{ 4, 81, 10, 10 },
},
// HWND_INSTALL_MAIN_OSD_TIME_FORMAT_RIGHT_ARROW
{
HWND_INSTALL_MAIN_OSD_TIME_FORMAT, HWND_INSTALL_MAIN_OSD_TIME_FORMAT_RIGHT_ARROW,
{ 319, 81, 10, 10 },
},
// HWND_INSTALL_MAIN_PAGE_ANT
{
HWND_INSTALL_MAIN_PAGE_ATSC, HWND_INSTALL_MAIN_OSD_ANT_NEXT_TEXT,
{ 33, 46, 6, 4 },
},
// HWND_INSTALL_MAIN_OSD_ANT_TITLE
{
HWND_INSTALL_MAIN_PAGE_ANT, HWND_INSTALL_MAIN_OSD_ANT_TITLE_TEXT,
{ 0, 175, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_ANT_TITLE_TEXT
{
HWND_INSTALL_MAIN_OSD_ANT_TITLE, HWND_INSTALL_MAIN_OSD_ANT_TITLE_TEXT,
{ 0, 175, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_ANT
{
HWND_INSTALL_MAIN_PAGE_ANT, HWND_INSTALL_MAIN_OSD_ANT_RIGHT_ARROW,
{ 0, 43, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_ANT_FOCUS_BG
{
HWND_INSTALL_MAIN_OSD_ANT, HWND_INSTALL_MAIN_OSD_ANT_FOCUS_BG,
{ 0, 43, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_ANT_TEXT
{
HWND_INSTALL_MAIN_OSD_ANT, HWND_INSTALL_MAIN_OSD_ANT_TEXT,
{ 44, 43, 180, 29 },
},
// HWND_INSTALL_MAIN_OSD_ANT_OPTION
{
HWND_INSTALL_MAIN_OSD_ANT, HWND_INSTALL_MAIN_OSD_ANT_OPTION,
{ 210, 43, 93, 29 },
},
// HWND_INSTALL_MAIN_OSD_ANT_LEFT_ARROW
{
HWND_INSTALL_MAIN_OSD_ANT, HWND_INSTALL_MAIN_OSD_ANT_LEFT_ARROW,
{ 4, 52, 10, 10 },
},
// HWND_INSTALL_MAIN_OSD_ANT_RIGHT_ARROW
{
HWND_INSTALL_MAIN_OSD_ANT, HWND_INSTALL_MAIN_OSD_ANT_RIGHT_ARROW,
{ 319, 52, 10, 10 },
},
// HWND_INSTALL_MAIN_OSD_ANT_NEXT
{
HWND_INSTALL_MAIN_PAGE_ANT, HWND_INSTALL_MAIN_OSD_ANT_NEXT_TEXT,
{ 0, 75, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_ANT_NEXT_RIGHT_ARROW
{
HWND_INSTALL_MAIN_OSD_ANT_NEXT, HWND_INSTALL_MAIN_OSD_ANT_NEXT_RIGHT_ARROW,
{ 0, 75, 334, 29 },
},
// HWND_INSTALL_MAIN_OSD_ANT_NEXT_TEXT
{
HWND_INSTALL_MAIN_OSD_ANT_NEXT, HWND_INSTALL_MAIN_OSD_ANT_NEXT_TEXT,
{ 0, 75, 334, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE
{
HWND_INSTALL_MAIN_PAGE_ATSC, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_PROGRESSBAR,
{ 88, 96, 233, 83 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_PROGRAM,
{ 0, 43, 334, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_TEXT
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_TEXT,
{ 44, 43, 93, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_VALUE
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_VALUE,
{ 147, 43, 93, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_PROGRAM
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_FOUND_PROGRAM,
{ 210, 43, 124, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_PROGRAM,
{ 0, 75, 334, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_TEXT
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_TEXT,
{ 44, 75, 93, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_VALUE
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_VALUE,
{ 147, 75, 93, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_PROGRAM
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_ANALOG_PROGRAM,
{ 210, 75, 124, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_PROGRAM,
{ 0, 104, 334, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_TEXT
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_TEXT,
{ 44, 106, 93, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_VALUE
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_VALUE,
{ 147, 106, 93, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_PROGRAM
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_DIGITAL_PROGRAM,
{ 210, 106, 124, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_CH_TYPE,
{ 0, 168, 334, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_PERCENT
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_PERCENT,
{ 66, 168, 37, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_PERCENT_TEXT
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_PERCENT_TEXT,
{ 104, 168, 37, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH_TEXT
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH_TEXT,
{ 141, 168, 49, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH_VALUE
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH_VALUE,
{ 192, 168, 37, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_CH_TYPE
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_RFCH, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_ITEM_CH_TYPE,
{ 229, 168, 80, 29 },
},
// HWND_INSTALL_SCAN_RESULT_SUB_PAGE_PROGRESSBAR
{
HWND_INSTALL_SCAN_RESULT_SUB_PAGE, HWND_INSTALL_SCAN_RESULT_SUB_PAGE_PROGRESSBAR,
{ 67, 197, 199, 12 },
},
};
|
#include <iostream>
#include <string.h>
#include <math.h>
void RomToAr();
using namespace std;
void ArToRom() {
int num;
cout << "Enter arabic number: ";
cin >> num;
if ( 1 <= num && num <= 3999) {
cout << "Roman number: " << endl;
for (; num >= 1000; num -= 1000) cout << "M";
if (num >= 900) {
num -= 900;
cout << "CM";
}
if (num >= 500) {
num -= 500;
cout << "D";
}
if (num >= 400) {
num -= 400;
cout << "CD";
}
else {
for (; num >= 100; num -= 100) cout << "C";
}
if (num >= 90) {
num -= 90;
cout << "XC";
}
if (num >= 50) {
num -= 50;
cout << "L";
}
if (num >= 40) {
num -= 40;
cout << "XL";
}
else {
for (; num >= 10; num -= 10) cout << "X";
}
if (num >= 9) {
num -= 9;
cout << "IX";
}
if (num >= 5) {
num -= 5;
cout << "V";
}
if (num >= 4) {
num -= 4;
cout << "IV";
}
else {
for (; num >= 1; num -= 1) cout << "I";
}
} cout << endl;
}
void RomToAr() {
string num;
int res = 0;
cout << "Enter roman number: ";
cin >> num;
for (int i = 0; i < num.length(); i++) {
if (num[i] == 'M') {
res += 1000;
}
else if (num[i] == 'C' && num[i+1] == 'M') {
res +=900;
i += 1;
}
else if (num[i] == 'D') {
res += 500;
}
else if (num[i] == 'C' && num[i+1] == 'D') {
res +=400;
i += 1;
}
else if (num[i] == 'C') {
res += 100;
}
else if (num[i] == 'X' && num[i+1] == 'C') {
res += 90;
i += 1;
}
else if (num[i] == 'L') {
res += 50;
}
else if (num[i] == 'X' && num[i+1] == 'L') {
res += 40;
i += 1;
}
else if (num[i] == 'X') {
res += 10;
}
else if (num[i] == 'I' && num[i+1] == 'X') {
res += 9;
i += 1;
}
else if (num[i] == 'V') {
res += 5;
}
else if (num[i] == 'I' && num[i+1] == 'V') {
res += 4;
i += 1;
}
else if (num[i] == 'I') {
res += 1;
}
else {
cout << "error" << endl;
}
}
cout << "Arabic number: " << res << endl;
}
int main() {
int menu;
cout << " 0 - Exit from program \n 1 - Convert from Arabic to Roman \n 2 - Convert from Roman to Arabic \n";
do {
cout << ">>>>";
cin >> menu;
switch (menu) {
case 0:
return 0;
case 1:
ArToRom();
break;
case 2:
RomToAr();
break;
}
} while (menu != 0);
return 0;
}
|
#ifndef H_TRANSLATING_GAME_OBJECT
#define H_TRANSLATING_GAME_OBJECT
#include "GameObject.h"
class TranslatingGameObject : public GameObject {
public:
TranslatingGameObject::TranslatingGameObject();
TranslatingGameObject::TranslatingGameObject(AllKit::Sprite sprite, int x = 0, int y = 0, double movementAngle = 0, float movementSpeed = 0);
TranslatingGameObject::TranslatingGameObject(const TranslatingGameObject& other);
//Update translatie beweging
virtual void Update();
/* Eigen functies */
void setMovement(float speed, double angle);
double getMovementAngle() { return movementAngle; }
float getMovementSpeed() { return movementSpeed; }
protected:
//De snelheid op de x - as
float velX;
//De snelheid op de y - as
float velY;
//De snelheid van bewegen
float movementSpeed;
//De hoek waarheen bewogen wordt
double movementAngle;
};
#endif
|
//
// Created by glumes on 2021/3/7.
//
#include "FilterUtil.h"
#include <VulkanFilter.h>
#include <MirrorFilter.h>
#include <RGBFilter.h>
#include <ColorInvertFilter.h>
#include <FilterType.h>
#include <ExposureFilter.h>
#include <GammFilter.h>
#include <ContrastFilter.h>
#include <HazeFilter.h>
VulkanFilter* FilterUtil::getFilterByType(int type) {
switch (type){
case SHOW_TYPE:
return new VulkanFilter();
case RBG_FILTER_TYPE:
return new RGBFilter();
case MIRROR_FILTER_TYPE:
return new MirrorFilter();
case REVERT_FILTER_TYPE:
return new ColorInvertFilter();
case EXPOSURE_FILTER_TYPE:
return new ExposureFilter();
case GAMMA_FILTER_TYPE:
return new GammFilter();
case CONTRAST_FILTER_TYPE:
return new ContrastFilter();
case HAZE_FILTER_TYPE:
return new HazeFilter();
default:
break;
}
return new VulkanFilter();
}
float FilterUtil::getProcess(int progress, float start, float end) {
return (end - start) * progress / 100.0f + start;
}
|
#include <cmath>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <set>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/* Solution */
// https://leetcode.com/problems/construct-k-palindrome-strings/
const int MOD = 1000000007;
class Solution {
public:
bool canConstruct(string s, int k) {
vector<int> count(26, 0);
for (char c : s)
{
count[c - 'a']++;
}
int pairs = 0, odds = 0;
for (int x : count)
{
if (x & 1)
{
odds++;
}
pairs += x / 2;
}
if (odds > k) return false;
if (2 * pairs < k - odds) return false;
return true;
}
};
int main()
{
Solution sol;
string s;
int k;
s = "qlkzenwmmnpkopu";
k = 15;
cout << "(" << s << ", " << k << "): " << sol.canConstruct(s, k) << endl;
s = "annabelle";
k = 2;
cout << "(" << s << ", " << k << "): " << sol.canConstruct(s, k) << endl;
s = "leetcode";
k = 3;
cout << "(" << s << ", " << k << "): " << sol.canConstruct(s, k) << endl;
s = "true";
k = 4;
cout << "(" << s << ", " << k << "): " << sol.canConstruct(s, k) << endl;
s = "yzyzyzyzyzyzyzy";
k = 2;
cout << "(" << s << ", " << k << "): " << sol.canConstruct(s, k) << endl;
s = "cr";
k = 7;
cout << "(" << s << ", " << k << "): " << sol.canConstruct(s, k) << endl;
}
|
#include<iostream>
#include<cmath>
using namespace std;
class Time{
private:
int Hour;
int Min;
int Sec;
public:
Time(){
Hour = 00;
Min = 00;
Sec = 00;
}
Time(int Hour, int Min, int Sec){
(*this).Hour = Hour;
this->Min = Min;
this->Sec = Sec;
}
~Time(){
Hour = 00;
Min = 00;
Sec = 00;
}
void Accept(){
cout<<"Enter Time in Hour & Minute & Second:\n";
cin>>this->Hour>>this->Min>>this->Sec;
}
void Display(){
cout<<"\n\nTime : "<<this->Hour<<" : "<<this->Min<<" : "<<this->Sec<<endl;
}
void operator>(Time t2){
if(this->Hour > t2.Hour){
cout<<"\nYour Greater Time is ";
this->Display();
}else if(this->Hour < t2.Hour){
cout<<"\nYour Greater Time is ";
t2.Display();
}else if(this->Min > t2.Min){
cout<<"\nYour Greater Time is ";
this->Display();
}else if(this->Min < t2.Min){
cout<<"\nYour Greater Time is ";
t2.Display();
}else if(this->Sec > t2.Sec){
cout<<"\nYour Greater Time is ";
this->Display();
}else if(this->Sec < t2.Sec){
cout<<"\nYour Greater Time is ";
t2.Display();
}else{
cout<<"\nYour Both Time are Equal";
}
}
Time operator-(Time t2){
Time temp;
int time1,time2;
time1 = (t2.Hour * 3600) + (t2.Min * 60) + t2.Sec;
time2 = (this->Hour * 3600) + (this->Min * 60) + this->Sec;
time1 = abs(time1 - time2);
temp.Hour = time1/3600;
temp.Min = (time1%3600)/60;
temp.Sec = ((time1%3600)%60);
return temp;
}
};
int main(){
Time t1 , t2, t3;
Time t4(12,00,00);
cout<<"\nYour Midnight Time is : \n";
t4.Display();
cout<<"\nYour First Time : \n";
t1.Accept();
t1.Display();
cout<<"\nYour Second Time : \n";
t2.Accept();
t2.Display();
t1>t2;
t3 = t1 - t2; // t3 = t1.operator-(t2); // t3 = operator-(&t1, t2);
cout<<"\nYour Time Difference is : \n";
t3.Display();
}
|
/* Priority queue:
* Thuộc tính:
+ Priority queue là một hàng đợi
+ Hàng đợi có ưu tiên (Priority queue)
+ Cấp phát động (Allocator-aware)
* Template parameters <T, Container>:
+ T: Kiểu dữ liệu cần chứa (Type of ele contained)
+ Container: Kiểu dữ liệu sử dụng bên trong (Underlying container type)
* Function member:
- Constructor:
+ priority_queue(): khởi tạo với 0 element
+ priority_queue(Container<T>): khởi tạo mà copy toàn bộ dữ liệu từ container<T>
- Capacity:
+ size(): => size
+ empty(): => priority_queue có rỗng? (true or false)
- Element access:
+ font(): => reference ele[0]
+ back(): => reference ele[n - 1]
- Modifiers:
+ push(value): chèn sao chép phần tử vào cuối
+ pop(value): xóa phần tử đầu
+ emplace(value): chèn trực tiếp phần tử vào cuối
+ swap(priority_queue): hoán đổi dữ liệu 2 swap
- Non-member function overloads:
+ swap(priority_queue): hoán đổi dữ liệu 2 priority_queue.
+ relational operators(dque): dùng để biểu thị toán tử quan hệ
_ ____ __ _ _ __
(_/_(_(_(_)(__ / (_(_/_(_(_(_/__(/_/ (_
/( .-/ .-/
(_) (_/ (_/
*/
#include <iostream>
#include <queue>
using namespace std;
int main() {
}
|
#include "StdAfx.h"
#include "frmPCHistory.h"
|
// Copyright 2020 JD.com, Inc. Galileo Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ==============================================================================
#pragma once
#include <mutex>
#include "common/macro.h"
#include "common/schema.h"
#include "common/types.h"
#include "utils/buffer.h"
#include "utils/task_thread_pool.h"
#include "edge_worker.h"
#include "file_manager.h"
#include "vertex_worker.h"
namespace galileo {
namespace convertor {
using Buffer = galileo::utils::Buffer;
struct SliceBuffer {
Buffer buffer;
std::mutex locker;
};
class Converter {
friend class Worker;
friend class VertexWorker;
friend class EdgeWorker;
public:
Converter();
~Converter();
public:
bool Initialize(int slice_count, const char* shcema_path);
bool Start(int worker_count, const char* vertex_source_path,
const char* vertex_binary_path, const char* edge_source_path,
const char* edge_binary_path);
private:
bool _StartVertexWorkerProcess(const char* v_source_path,
const char* v_binary_path, int worker_count);
bool _StartEdgeWorkerProcess(const char* e_source_path,
const char* e_binary_path, int worker_count);
private:
galileo::schema::Schema schema_;
SliceBuffer* slices_;
int slice_count_;
FileManager file_manager_;
galileo::utils::TaskThreadPool task_thread_pool_;
};
} // namespace convertor
} // namespace galileo
|
#ifndef _PAINTTOOLS_H_
#define _PAINTTOOLS_H_
#include <QRect>
#include <QObject>
#include <QStringList>
#include <QPainterPath>
#include <QImage>
#include "interfaces.h"
class PaintTools : public QObject, public BrushInterface
{
Q_OBJECT
Q_INTERFACES( BrushInterface );
public:
QStringList brushes() const;
QRect mousePress( const QString &brush, QPainter &painter, const QPoint &pos);
QRect mouseMove( const QString &brush, QPainter &painter, const QPoint &oldPos, const QPoint &newPos );
QRect mouseRelease( const QString &brush, QPainter &painter, const QPoint &pos );
};
#endif
|
#ifndef _HS_SFM_SFM_PIPELINE_POINT_CLOUD_NORM_CALCULATOR_HPP_
#define _HS_SFM_SFM_PIPELINE_POINT_CLOUD_NORM_CALCULATOR_HPP_
#include <utility>
#include <limits>
#include <flann/flann.hpp>
#include "hs_sfm/sfm_utility/camera_type.hpp"
#include "hs_sfm/sfm_utility/projective_functions.hpp"
namespace hs
{
namespace sfm
{
namespace pipeline
{
template <typename _Scalar>
class PointCloudNormCalculator
{
public:
typedef _Scalar Scalar;
typedef CameraIntrinsicParams<Scalar> IntrinsicParams;
typedef CameraExtrinsicParams<Scalar> ExtrinsicParams;
typedef EIGEN_VECTOR(Scalar, 3) Point;
struct CameraParams
{
IntrinsicParams intrinsic_params;
ExtrinsicParams extrinsic_params;
size_t image_width;
size_t image_height;
};
typedef EIGEN_STD_VECTOR(CameraParams) CameraParamsContainer;
typedef EIGEN_STD_VECTOR(Point) PointContainer;
private:
typedef flann::L2<Scalar> Distance;
typedef flann::Index<Distance> Index;
typedef EIGEN_VECTOR(Scalar, 2) Key;
public:
PointCloudNormCalculator(int knn = 64)
: knn_(knn) {}
int operator() (const CameraParamsContainer& cameras,
const PointContainer& points,
PointContainer& norms) const
{
Index index = BuildQueryTree(points);
norms.resize(points.size());
for (size_t i = 0; i < points.size(); i++)
{
Point norm = PCANearestNeighborNorm(points, i, index);
//计算所有与该点关联的相机中,相机拍摄方向与法向量的夹角
Scalar max_angle = -std::numeric_limits<Scalar>::max();
Scalar max_angle_signed = Scalar(0);
for (size_t j = 0; j < cameras.size(); j++)
{
Key key =
ProjectiveFunctions<Scalar>::WorldPointProjectToImageKey(
cameras[j].intrinsic_params,
cameras[j].extrinsic_params,
points[i]);
if (key[0] >= Scalar(0) && key[0] < Scalar(cameras[j].image_width) &&
key[1] >= Scalar(0) && key[1] < Scalar(cameras[j].image_height))
{
EIGEN_MATRIX(Scalar, 3, 3) r_matrix =
cameras[j].extrinsic_params.rotation();
Point camera_direction = r_matrix.row(2).transpose();
Scalar angle = camera_direction.dot(norm);
if (max_angle < std::abs(angle))
{
max_angle = std::abs(angle);
max_angle_signed = angle;
}
}
}
if (max_angle_signed > Scalar(0))
{
norm *= Scalar(-1);
}
norms[i] = norm;
}
return 0;
}
int operator() (const PointContainer& points,
const Point& up_vector,
PointContainer& norms) const
{
Index index = BuildQueryTree(points);
norms.resize(points.size());
for (size_t i = 0; i < points.size(); i++)
{
Point norm = PCANearestNeighborNorm(points, i, index);
if (norm.dot(up_vector) < Scalar(0))
{
norm *= Scalar(-1);
}
norms[i] = norm;
}
return 0;
}
private:
Index BuildQueryTree(const PointContainer& points) const
{
std::vector<Scalar> data(points.size() * 3);
for (size_t i = 0; i < points.size(); i++)
{
data[i * 3 + 0] = points[i][0];
data[i * 3 + 1] = points[i][1];
data[i * 3 + 2] = points[i][2];
}
flann::Matrix<Scalar> index_matrix(data.data(), points.size(), 3);
Index index(index_matrix, flann::KDTreeSingleIndexParams());
index.buildIndex();
return index;
}
Point PCANearestNeighborNorm(const PointContainer& points,
size_t id,
const Index& index) const
{
typedef typename Distance::ResultType DistanceResultType;
typedef EIGEN_MATRIX(Scalar, 3, Eigen::Dynamic) Matrix3X;
typedef EIGEN_MATRIX(Scalar, 3, 3) Matrix33;
Point norm;
Scalar search_data[3] = { points[id][0], points[id][1], points[id][2] };
std::vector<size_t> indices_data(knn_);
std::vector<DistanceResultType> distances_data(knn_);
flann::Matrix<Scalar> serach_matrix(search_data, 1, 3);
flann::Matrix<size_t> indices_matrix(indices_data.data(), 1, knn_);
flann::Matrix<DistanceResultType> distances_matrix(
distances_data.data(), 1, knn_);
index.knnSearch(serach_matrix, indices_matrix, distances_matrix, knn_,
flann::SearchParams(flann::FLANN_CHECKS_UNLIMITED));
Point mean = Point::Zero();
for (size_t j = 0; j < knn_; j++)
{
mean[0] += points[indices_matrix[0][j]][0];
mean[1] += points[indices_matrix[0][j]][1];
mean[2] += points[indices_matrix[0][j]][2];
}
mean /= Scalar(knn_);
Matrix3X A(3, knn_);
for (size_t j = 0; j < knn_; j++)
{
Point point_neighbor = points[indices_matrix[0][j]];
A.col(j) = point_neighbor - mean;
}
Matrix33 cov = A * A.transpose();
Eigen::EigenSolver<Matrix33> eigen_solver(cov);
Scalar min_eigen_value = std::numeric_limits<Scalar>::max();
int min_idx = -1;
for (int j = 0; j < 3; j++)
{
Scalar eigen_value = eigen_solver.eigenvalues()[j].real();
if (min_eigen_value > eigen_value)
{
min_eigen_value = eigen_value;
min_idx = j;
}
}
norm = eigen_solver.eigenvectors().col(min_idx).real();
norm /= norm.norm();
return norm;
}
private:
int knn_;
};
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.