text
stringlengths
8
6.88M
#include <Model/thanos.h> bool EmailSender::sendEmail(string name, string toName, string to, string subject, string body){ }
vector < Rect> vRegionSearchRect; Rect regionSearchRect = targetRegion; regionSearchRect.x = targetRegion.x -patchSize; regionSearchRect.y = targetRegion.y -patchSize; for (; regionSearchRect.y < targetRegion.y+patchSize ; regionSearchRect.y += 4) //.y < vpatches[i].r.y + vpatches[i].r.height; patchSearchRect.y += patchSize/2) { for (; regionSearchRect.x < targetRegion.x+patchSize ; regionSearchRect.x += 4) { //circle(showImg, Point( regionSearchRect.x, regionSearchRect.y) ,2 ,RED); //rectangle(showImg, regionSearchRect,showColors[rand()%4]); // imshow("case", showImg(regionSearchRect)); //waitKey(); vRegionSearchRect.push_back(regionSearchRect); } regionSearchRect.x = targetRegion.x -patchSize; } /* Rect regionSearchRect = targetRegion; regionSearchRect.x = searchArea.x + 1 + patchSize; regionSearchRect.y = searchArea.y + 1 + patchSize; for (; (regionSearchRect&searchArea) == regionSearchRect; regionSearchRect.y += patchSize/2) //.y < vpatches[i].r.y + vpatches[i].r.height; patchSearchRect.y += patchSize/2) { for (; (regionSearchRect&searchArea) == regionSearchRect; regionSearchRect.x += patchSize/2) { //circle(showImg, Point( regionSearchRect.x, regionSearchRect.y) ,2 ,RED); //rectangle(showImg, regionSearchRect,showColors[rand()%4]); // imshow("case", showImg(regionSearchRect)); //waitKey(); vRegionSearchRect.push_back(regionSearchRect); } regionSearchRect.x = searchArea.x + 1 + patchSize; }*/ cout<< vRegionSearchRect.size() <<endl; vector <vector < Patch> > vvpatches(patchNum, vector < Patch>() ); vector<int> sizes; for (int i = 0; i < patchNum; i++) { Rect patchSearchRect = vpatches[i].r; patchSearchRect.x -= patchSearchRect.width ; patchSearchRect.y -= patchSearchRect.height; for (; patchSearchRect.y < vpatches[i].r.y + vpatches[i].r.height; patchSearchRect.y += patchSize/3) { for (; patchSearchRect.x < vpatches[i].r.x + vpatches[i].r.width; patchSearchRect.x += patchSize/3) { vector <int> tempHis; compute_histogram (patchSearchRect ,tempHis); float dis = distance(tempHis,vpatches[i].histogram); if (dis < 0.1) { vvpatches[i].push_back(Patch(patchSearchRect,dis)); //circle(showImg,Point(patchSearchRect.x, patchSearchRect.y),2,RED); } } patchSearchRect.x = vpatches[i].r.x-patchSearchRect.width; } //sort(vvpatches[i].begin(), vvpatches[i].end(), patchCmp1); /*if (vvpatches[i].size()>10) { vvpatches[i].resize(10); }*/ if (vvpatches[i].size() ==0 ) { vvpatches[i].push_back(vpatches[i]); //cout<<"vvpatches[].size()"<<i<<","<<vvpatches[i].size()<<endl; } cout<<"vvpatches[].size()"<<i<<","<<vvpatches[i].size()<<endl; sizes.push_back(vvpatches[i].size()); } float MAX = 10000; int resultLocationIndex = -1; vector<Patch> vpatchResult; for (int i = 0; i < vRegionSearchRect.size(); i++) { vector <vector < Patch> > vvpatchesINaPaticle(patchNum, vector < Patch>() ); int j = 0; for( ; j < patchNum; j++) { int k=0; while ( k <vvpatches[j].size()) { if ( (vvpatches[j][k].r&vRegionSearchRect[i]) == vvpatches[j][k].r) { vvpatchesINaPaticle[j].push_back(vvpatches[j][k]); } k++; } if(vvpatchesINaPaticle[j].size() ==0) { break; } else { sort(vvpatchesINaPaticle[j].begin(),vvpatchesINaPaticle[j].end(),patchCmp1); if (vvpatchesINaPaticle[j].size()>8) { vvpatchesINaPaticle[j].resize(8); } } } if ( j == patchNum) { //circle(showImg, Point( vRegionSearchRect[i].x, vRegionSearchRect[i].y) ,2 ,RED); //rectangle(showImg, vRegionSearchRect[i],showColors[0]); vector <int> locationindexes; float ret = solveIP(vRegionSearchRect[i], vvpatchesINaPaticle,locationindexes); if (ret< MAX) { MAX = ret; resultLocationIndex = i; vpatchResult.clear(); for (int k =0; k<patchNum; k++) { vpatchResult.push_back(vvpatchesINaPaticle[k][locationindexes[k]]); } } } } if (resultLocationIndex >= 0) { cout<<"max : "<<MAX<<endl; //targetRegion = vRegionSearchRect[resultLocationIndex]; } Point newFocus; newFocus.x = 0; newFocus.y = 0; for (int k =0; k<patchNum; k++) { vpatches[k].r = vpatchResult[k].r; //vpatches[k].histogram = vpatchResult[k].histogram; newFocus.x += vpatches[k].r.x; newFocus.y += vpatches[k].r.y; rectangle(showImg, vpatchResult[k].r, GREEN, 1); } newFocus.x /= patchNum; newFocus.y /= patchNum; targetRegion.x = targetRegion.x+newFocus.x- Focus.x; targetRegion.y = targetRegion.y+newFocus.y- Focus.y; Focus=newFocus; rectangle(showImg, targetRegion, GREEN, 1); } vector<int> hisTargetNew, hisSearchAreaNew,hisBackgroundNew; compute_histogram(targetRegion, hisTargetNew); compute_histogram(searchArea, hisSearchAreaNew); for (int i = 0; i< hisTarget.size(); i++) { hisBackgroundNew.push_back(hisSearchAreaNew[i] - hisTargetNew[i]); } vector < double> hisTargetNormNew = NormHis(hisTargetNew); vector < double> hisBackgroundNormNew = NormHis(hisBackgroundNew); weightAdd( hisTargetNorm, hisTargetNormNew); weightAdd( hisBackgroundNorm, hisBackgroundNormNew); pToObject1.create(searchArea.height, searchArea.width, CV_64FC1); for (int i = 0; i < searchArea.height; i++) { for (int j = 0; j < searchArea.width; j++) { int hIndex = splithsv[0].at<uchar>(i, j) * NH/ 181; int sIndex = splithsv[1].at<uchar>(i, j) * NS/ 256; int k = 10 * hIndex + sIndex; if (mask.at<uchar>(i,j) == 0) { pToObject1.at< double>(i,j)= 0; } else { pToObject1.at<double>(i,j) = log(hisTargetNorm[k]) - log(hisBackgroundNorm[k]) ;//hisTarget[k]*255/(hisSearchArea[k]);//*3/2 ; } } } imshow("log", pToObject1 ); /* pToObject.create(searchArea.height, searchArea.width, CV_8UC1); for (int i = 0; i < searchArea.height; i++) { for (int j = 0; j < searchArea.width; j++) { int hIndex = splithsv[0].at<uchar>(i, j) * NH/ 181; int sIndex = splithsv[1].at<uchar>(i, j) * NS/ 256; int k = 10 * hIndex + sIndex; if (hisSearchArea[k] == 0) { pToObject.at<uchar>(i,j)= 0; } else { pToObject.at<uchar>(i,j) = hisTarget[k]*255/(hisSearchArea[k]);//*3/2 ; } } } //imshow("mask", mask); imshow("pToObject", pToObject);*/ //vpatches.clear(); //makePatches(); calcW(); /* //perform prediction and measurement for each particle for( int j = 0; j < num_particles; j++ ) { particles[j] = transition( particles[j], framewidth, frameheight, rng); float s = particles[j].s; particles[j].w = likelihood( hsv_frame, cvRound(particles[j].y), cvRound( particles[j].x ), cvRound( particles[j].width * s ), cvRound( particles[j].height * s ), particles[j].histo);//, particles[j].patches ); } //normalize weights and resample a set of unweighted particles normalize_weights( particles, num_particles );//归一化,使所有粒子权重和为1 new_particles = resample( particles, num_particles ); free( particles ); particles = new_particles; // display all particles if requested qsort( particles, num_particles, sizeof( particle ), particle_cmp ); targetRegion.x = particles[0].x - particles[0].width * particles[0].s / 2; targetRegion.y = particles[0].y - particles[0].height * particles[0].s / 2; targetRegion.height = particles[0].height * particles[0].s; targetRegion.width = particles[0].width * particles[0].s; targetRegion&=boundary; rectangle(output, targetRegion, RED, 2); Rect searchArea(targetRegion.x - targetRegion.width, targetRegion.y - targetRegion.height, targetRegion.width*3, targetRegion.height*3); searchArea &= boundary; for (int i = 0; i < patches.size(); i++) { Point loc; matchTlt(preFrame(patches[i]), frame(searchArea), loc); patches[i].x += (loc.x - patches[i].x - patches[i].width/2) + searchArea.x; patches[i].y += (loc.y - patches[i].y - patches[i].height/2) + searchArea.y; patches[i].x += (loc.x - patches[i].x) + searchArea.x; patches[i].y += (loc.y - patches[i].y) + searchArea.y; } for (int i = 0; i < patches.size(); i++) { rectangle(showImg, patches[i], GREEN, 2); } //trackPatches();*/ preFrame = frame;
#include <RcppGSL.h> using namespace Rcpp; // [[Rcpp::depends(RcppGSL)]] // [[Rcpp::export]] NumericMatrix RcppGibbs(int N, int thn) { int i,j; NumericMatrix mat(N, 2); RNGScope scope; // Initialize Random number generator // The rest of the code follows the R version double x=0, y=0; for (i=0; i<N; i++) { for (j=0; j<thn; j++) { x = ::Rf_rgamma(3.0,1.0/(y*y+4)); y = ::Rf_rnorm(1.0/(x+1),1.0/sqrt(2*x+2)); } mat(i,0) = x; mat(i,1) = y; } return mat; // Return to R } #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> // [[Rcpp::export]] NumericMatrix GSLGibbs(int N, int thin) { int i, j; gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); double x=0, y=0; NumericMatrix mat(N, 2); for (i=0; i<N; i++) { for (j=0; j<thin; j++) { x = gsl_ran_gamma(r,3.0,1.0/(y*y+4)); y = 1.0/(x+1)+gsl_ran_gaussian(r,1.0/sqrt(2*x+2)); } mat(i,0) = x; mat(i,1) = y; } gsl_rng_free(r); return mat; // Return to R } #include <boost/random.hpp> #include <boost/generator_iterator.hpp> #include <boost/random/normal_distribution.hpp> #include <boost/random/gamma_distribution.hpp> typedef boost::mt19937 RNGType; // select a generator, MT good default RNGType rng(123456); // instantiate and seed boost::normal_distribution<> n01(0.0, 1.0); boost::variate_generator< RNGType, boost::normal_distribution<> > rngNormal(rng, n01); boost::gamma_distribution<> g3(3.0); // older Boost took one arg "alpha", divide draw by "beta" boost::variate_generator< RNGType, boost::gamma_distribution<> > rngGamma(rng, g3); // [[Rcpp::export]] NumericMatrix BoostGibbs(int N, int thin) { int i, j; double x=0, y=0; NumericMatrix mat(N, 2); for (i=0; i<N; i++) { for (j=0; j<thin; j++) { x = rngGamma()/(1.0/(y*y+4)); // dividing by beta gives us Gamma(alpha, beta) y = 1.0/(x+1) + rngNormal()*(1.0/sqrt(2*x+2)); // scale by sigma and move by mu } mat(i,0) = x; mat(i,1) = y; } return mat; // Return to R }
#include "common/Compiler.h" #include "common/FastRand.h" #include <benchmark/benchmark.h> #include <memory> #include <sstream> #include <system_error> namespace PayloadErrorCode { class GlobPattern { public: GlobPattern() noexcept { ErrorCodeGt10 = fastrand() % 10 + 100; } ATTRIBUTE_NOINLINE static std::error_code create(std::string input, GlobPattern &result) noexcept { if (fastrand() % 10 > ErrorCodeGt10) return std::make_error_code(std::errc::invalid_argument); // never happens result = GlobPattern(); return std::error_code(); } bool match(std::string text) const noexcept { benchmark::DoNotOptimize(text); return (fastrand() % 10 > 4); } private: static int ErrorCodeGt10; }; int GlobPattern::ErrorCodeGt10; template <int N> ATTRIBUTE_NOINLINE std::error_code IMPL_PayloadErrorCode( bool &result, std::unique_ptr<std::string> &errorFileName) noexcept { return IMPL_PayloadErrorCode<N - 1>(result, errorFileName); } template <> ATTRIBUTE_NOINLINE std::error_code IMPL_PayloadErrorCode<1>( bool &result, std::unique_ptr<std::string> &errorFileName) noexcept { GlobPattern pattern; std::string fileName = "[a*.txt"; if (std::error_code ec = GlobPattern::create(fileName, pattern)) { errorFileName = std::make_unique<std::string>(fileName); return ec; } result = pattern.match("..."); return std::error_code(); } template <int N> void BM_PayloadErrorCode(benchmark::State &state) { std::ostringstream nulls; while (state.KeepRunning()) { bool res; std::unique_ptr<std::string> errorFileName = nullptr; if (std::error_code ec = IMPL_PayloadErrorCode<N>(res, errorFileName)) { nulls << "[OverheadExample] " << ec.value() << ": "; nulls << *errorFileName << "\n"; } benchmark::DoNotOptimize(res); } } BENCHMARK_TEMPLATE1(BM_PayloadErrorCode, 1); BENCHMARK_TEMPLATE1(BM_PayloadErrorCode, 2); BENCHMARK_TEMPLATE1(BM_PayloadErrorCode, 4); BENCHMARK_TEMPLATE1(BM_PayloadErrorCode, 8); }
/* 4.9.2 向上类型转换及问题 cpp1data004i2a 4.9.2.1 问题抛出 对象可以作为自己的类或者作为它的基类的对象来使用。还能通过基类的地址来操作它。取一个对象的地址(指针或引用),并将其作为基类的地址来处理,这种称为向上类型转换。 也就是说:父类引用或指针可以指向子类对象,通过父类指针或引用来操作子类对象。 早绑定(early binding) * */ #include <iostream> using namespace std; class Animal { public: void speak() { cout << "Animal speak" << endl; } }; class Dog : public Animal { public: void speak() { cout << "Dog speak" << endl; } }; void doBussiness(Animal& animal) { animal.speak(); } void test() { Dog dog; doBussiness(dog); } int main() { test(); return 0; }
/* Q4: Two dates are given in a 8 node single linked list form,where each node has one digit only, dates 01-31, months 01-12, year 0000-9999. Find the number of days in between those two dates .[Exclusive] Ex : Date1: 0->1->0->1->2->0->0->4 . Date2 : 0->5->0->1->2->0->0->4 should return 3 . As there are 3 days between Jan1st 2004 and Jan 5th 2004. Ex 2 : Date1 : 3->1->1->2->2->0->1->2. Date2 : 0->2->0->1->2->0->1->3 should return 1 . (There is only one day between 31st Dec 2012 and 2nd Jan 2013 .) Note : Consecutive Days and Same Days should return 0; ->Return -1 for NULL Inputs . ->Between Days have to be calculated by not including start and end date . ->The SLL will have 8 Nodes in all cases . Month 9 will be represented as 09. Difficulty : Hard */ #include <stdlib.h> #include <stdio.h> #include <math.h> struct node{ int data; struct node *next; }; int isleap(int year) { if (year % 4 != 0) return 0; else if (year % 100 != 0) return 1; else if (year % 400 != 0) return 0; else return 1; } void to_date(struct node *list, int *days1, int *month1, int *year1) { int i; for (i = 0; i < 2; i++) { *days1 = *days1 * 10 + list->data; list = list->next; } for (i = 0; i < 2; i++) { *month1 = *month1 * 10 + list->data; list = list->next; } for (i = 0; i < 4; i++) { *year1 = *year1 * 10 + list->data; list = list->next; } return; } int between_days(struct node *date1head, struct node *date2head){ int days1 = 0, days2 = 0, month1 = 0, month2 = 0, year1 = 0, year2 = 0; int temp, days = 0, y, y_m = 0, m, d, i; static int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (date1head == NULL || date2head == NULL) return -1; to_date(date1head, &days1, &month1, &year1); to_date(date2head, &days2, &month2, &year2); if (abs(days1 - days2) < 2 && abs(month1 - month2) < 2 && abs(year1 - year2) < 2) return 0; if (year1 < year2) { y = year1; m = month1; d = days1; } else if (year2 < year1) { y = year2; m = month2; d = days2; } else { y = year1; if (month1 < month2) { m = month1; d = days1; } else if (month1 > month2) { m = month2; d = days2; } else { m = month1; return abs(days1 - days2) - 1; } y_m = m != month1 ? month1 : month2; days += month_days[m - 1] - d; for (m += 1; m < y_m; m++) { days += month_days[m - 1]; if (m < 2) days++; } return days + (d != days2 ? days2 : days1) - 1; } temp = y + 1; y_m = m == year2 ? year1 : year2; while (temp < y_m) { days += isleap(temp) ? 366 : 365; temp++; } if (isleap(year1) && isleap(year2)) { if (month1 <= 2 && month2 <= 2) days++; else if (month1 <= 2 && month2 > 2) { days += 2; } } else if (isleap(year1) && month1 < 2) days++; else if (isleap(year2) && month2 > 2) days++; for (i = m; i < 12; i++) days += month_days[m]; return days; }
#ifndef OBJECTDATA_H #define OBJECTDATA_H #include <string> #include <vector> #include <map> #include "cinder/Vector.h" namespace cilender { class ObjectData { public: ObjectData(); std::string name; std::string data; ci::Vec3f location; ci::Vec3f rotation; ci::Vec3f scale; std::vector< bool > layers; }; } #endif // OBJECTDATA_H
// -*- 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. // //----------------------------------------------------------------------------- // Array test 11: negative strides. //----------------------------------------------------------------------------- // Include files #include "Pooma/Pooma.h" #include "Utilities/Tester.h" #include "Domain/Loc.h" #include "Domain/Interval.h" #include "Domain/Range.h" #include "Layout/UniformGridLayout.h" #include "Engine/BrickEngine.h" #include "Engine/MultiPatchEngine.h" #include "Array/Array.h" int main(int argc, char *argv[]) { Pooma::initialize(argc, argv); Pooma::Tester tester(argc, argv); Array<1, int> a(10), b(10); Array<2, int> c(10, 10); Loc<2> blocks(5,5); UniformGridLayout<2> layout(Interval<2>(10,10), blocks,ReplicatedTag()); Array<2, int, MultiPatch<UniformTag,Brick> > u(layout); int i0, i1; // Block since we're starting scalar code. Pooma::blockAndEvaluate(); for (i0 = 0; i0 < 9; i0++) a(i0) = b(i0) = i0; for (i1 = 0; i1 < 9; i1++) for (i0 = 0; i0 < 9; i0++) u(i0, i1) = c(i0,i1) = i1+10*i0; // Make some ranges with negative stride and use them. Range<1> R(7,3,-2), RR(2,0,-1); Range<1> Q(3,7,2); tester.check(all(a(R)(RR) == b(Q))); tester.check(all(c(1, R)(RR) == b(Q) + 10)); tester.check(all(u(2, R)(RR) == b(Q) + 20)); int ret = tester.results("array_test11"); Pooma::finalize(); return ret; } // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: array_test11.cpp,v $ $Author: richard $ // $Revision: 1.13 $ $Date: 2004/11/01 18:16:14 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#include <cstdio> #include <cstring> int main() { int n1, n2, len, tmp; char str[90]; scanf("%s", str); for(len = 0; str[len] != '\0'; len++) ; // get n1=n3 and n2 for(n1 = 1; n1 <= n2; n1++) { tmp = len + 2 - 2 * n1; // ATTENTION: 这里与前一题B1027一样, 需要后悔 if(n1 > tmp) break; n2 = tmp; // printf("==%d==\n", n2); } char gap[n2-2]; int i; for(i = 0; i < n2 - 2; i++ ) { gap[i] = ' '; } gap[i] = '\0'; // ATTENTION: string 赋值需要添加\0来作结尾 n1 = (len + 2 - n2) / 2; // printf("--%d--\n", n1); // 0-n1-1 for(i = 0; i < n1-1; i++) { printf("%c%s%c\n", str[i], gap, str[len-1-i]); } for(i = 0; i < n2; i++) { printf("%c", str[n1-1+i]); } return 0; }
//--------------------------------------------------------------------------- #ifndef UtilForVectH #define UtilForVectH //--------------------------------------------------------------------------- #include <vector> using namespace std; void VectDoubleWriteFile(vector<double> &vect,int handle); void VectDoubleReadFile(vector<double> &vect,int handle); double VectDoubleAverDistanceAndDisp(vector<vector <double> > &val1,vector<vector <double> > &val2,double &disp); double VectDoubleDistance(vector<double> &vect1,vector<double> &vect2); void VectDoubleNorm(vector<double> &vect,double sum); void VectIntNorm(vector<int> &vect,int sum); //--------------------------------------------------------------------------- #endif
#ifndef BASE_GRAPH_CREATE #define BASE_GRAPH_CREATE #include <MultiGraphCreate.h> #include <GraphAccess.h> #include <assert.h> typedef MultiGraphElemTemplate<void*> BaseGraphNode; typedef MultiGraphElemTemplate<void*> BaseGraphEdge; class BaseGraphCreate : public MultiGraphCreate, public GraphAccessTemplate<BaseGraphNode,BaseGraphEdge> { protected: typedef GraphAccessTemplate<BaseGraphNode,BaseGraphEdge> GraphAccessBase; public: typedef void* NodeContent; typedef void* EdgeContent; typedef GraphAccessBase::Node Node; typedef GraphAccessBase::Edge Edge; typedef GraphAccessBase::NodeIterator NodeIterator; typedef GraphAccessBase::EdgeIterator EdgeIterator; virtual ~BaseGraphCreate() {} virtual BaseGraphNode* CreateNode(NodeContent _id) =0; virtual BaseGraphEdge* CreateEdge(BaseGraphNode* src, BaseGraphNode *snk, EdgeContent _id)=0; virtual void MoveEdgeEndPoint( BaseGraphEdge *e, BaseGraphNode *n, EdgeDirection dir)=0; virtual void DeleteNode( BaseGraphNode *n)=0; virtual void DeleteEdge( BaseGraphEdge *n)=0; GraphAccessBase::GetNodeIterator; GraphAccessBase::GetNodeEdgeIterator; GraphAccessBase::GetEdgeEndPoint; GraphAccessBase::ContainNode; GraphAccessBase::ContainEdge; }; template <class GraphImpl> class BaseGraphCreateWrap : public BaseGraphCreate { public: BaseGraphCreateWrap() { impl = new GraphImpl(); } virtual ~BaseGraphCreateWrap() { delete impl; } virtual BaseGraphNode* CreateNode(NodeContent _id) { return new typename GraphImpl::Node( impl, this, _id); } virtual BaseGraphEdge* CreateEdge(BaseGraphNode* src, BaseGraphNode *snk, EdgeContent _id) { assert( ContainNode(src) && ContainNode(snk)); return new typename GraphImpl::Edge( this, static_cast<typename GraphImpl::Node*>(src), static_cast<typename GraphImpl::Node*>(snk), _id); } virtual void MoveEdgeEndPoint( BaseGraphEdge *e, BaseGraphNode *n, GraphAccess::EdgeDirection dir) { assert( ContainEdge(e) && ContainNode(n)); static_cast<typename GraphImpl::Edge*>(e)->MoveEndPoint( static_cast<typename GraphImpl::Node*>(n), TranslateDirection(dir)); } virtual void DeleteNode( BaseGraphNode *n) { delete static_cast<typename GraphImpl::Node*>(n); } virtual void DeleteEdge( BaseGraphEdge *n) { delete static_cast<typename GraphImpl::Edge*>(n); } NodeIterator GetNodeIterator() const { return new IteratorImplTemplate<Node*,typename GraphImpl::NodeIterator> (impl->GetNodeIterator()); } EdgeIterator GetNodeEdgeIterator( const Node* n, GraphAccess::EdgeDirection dir) const { return new IteratorImplTemplate<Edge*,typename GraphImpl::EdgeIterator> (impl->GetNodeEdgeIterator(static_cast<const typename GraphImpl::Node*>(n), TranslateDirection(dir))); } Node* GetEdgeEndPoint( const BaseGraphEdge* e, GraphAccess::EdgeDirection dir) const { return impl->GetEdgeEndPoint(static_cast<const typename GraphImpl::Edge*>(e), TranslateDirection(dir)); } bool ContainNode( const BaseGraphNode* n) const { return impl->ContainNode(static_cast<const typename GraphImpl::Node*>(n)); } bool ContainEdge( const BaseGraphEdge* n) const { return impl->ContainEdge(static_cast<const typename GraphImpl::Edge*>(n)); } protected: GraphImpl* impl; typename GraphImpl::EdgeDirection TranslateDirection( GraphAccess::EdgeDirection dir) const { switch (dir) { case GraphAccess::EdgeOut: return GraphImpl::EdgeOut; case GraphAccess::EdgeIn: return GraphImpl::EdgeIn; default: assert(false); } } }; #endif
// // MrCrash - crash info reporting tool // Copyright (C) 2005-2014 Michael Fink // /// \file AppOptions.hpp Application options // #pragma once /// start mode enum T_enStartMode { smStartProcess, ///< starts process smAttachProcess, ///< attaches to running process smInteractive, ///< interactive mode }; /// application options class AppOptions { public: AppOptions(LPCTSTR pszCommandLine); T_enStartMode StartMode() const throw() { return m_enStartMode; } DWORD AttachProcessId() const throw() { return m_dwAttachProcessId; } CString StartApp() const throw() { return m_cszStartApp; } CString CmdLine() const throw() { return m_cszCmdLine; } private: bool OnParamInteractive(); bool OnParamAttach(const CString& cszProcessId); bool OnParamStart(const CString& cszStartApp); bool OnParamCommandLine(const CString& cszCmdLine); private: T_enStartMode m_enStartMode; DWORD m_dwAttachProcessId; CString m_cszStartApp; CString m_cszCmdLine; };
#include <bits/stdc++.h> using namespace std; int main() { int n, x = 100000, y = 500, min_x = 100000, min_y = 500, max_x = 0; cin>>n; for(int i=0; i<n; i++) { int tx, ty; cin>>tx>>ty; min_x = min(min_x, tx); max_x = max(max_x, tx); min_y = min(min_y, ty); } cout<<max(min_x*y, max(min_y*x, (x-max_x)*y)); return 0; }
/*************************************************************************** Copyright (c) 2020 Philip Fortier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************/ // GotoDialog.cpp : implementation file // #include "stdafx.h" #include "AppState.h" #include "GotoDialog.h" // CGotoDialog dialog CGotoDialog::CGotoDialog(CWnd* pParent /*=NULL*/) : CExtResizableDialog(CGotoDialog::IDD, pParent) { _iLineNumber = 0; } CGotoDialog::~CGotoDialog() { } void CGotoDialog::DoDataExchange(CDataExchange* pDX) { if (!Title.empty()) { SetWindowText(Title.c_str()); } CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT1, m_LineNumber); CString strLineNumber; m_LineNumber.GetWindowText(strLineNumber); _iLineNumber = StrToInt(strLineNumber); DDX_Control(pDX, IDOK, m_wndOK); DDX_Control(pDX, IDCANCEL, m_wndCancel); DDX_Control(pDX, IDC_STATIC1, m_wndStatic1); if (!Label.empty()) { m_wndStatic1.SetWindowText(Label.c_str()); } } BEGIN_MESSAGE_MAP(CGotoDialog, CExtResizableDialog) END_MESSAGE_MAP() // CGotoDialog message handlers
#include "mutation_detector.h" using namespace std; vector<string> find_mutations(ParseTreeNode *program_node) { auto assignments = find_assignments(program_node, std::string()); vector<string> mutations; for (auto assn : assignments) if (assn.second > 1) mutations.push_back(assn.first); return mutations; } unordered_map<string, int> find_assignments(ParseTreeNode *current_scope, string prefix) { assert(current_scope); assert(current_scope->type == PROGRAM_NODE || current_scope->type == BLOCK_STMT_NODE); unordered_map<string, int> assignments; ParseTreeNode *temp; for (int i = 0; i < current_scope->num_children; i++) { temp = current_scope->children[i]; if (temp->type == ASSIGNMENT_NODE) { assert(temp->children[0]); string key = prefix + temp->children[0]->value.s_value; auto find_var = assignments.find(key); if (find_var != assignments.end()) { assignments[key] += 1; } else { assignments[key] = 1; } } else if (temp->type == BRANCH_STMT_ELSE_NODE || temp->type == BRANCH_STMT_NO_ELSE_NODE) { for (int j = 0; j < temp->num_children-1; j++) { auto block_assignments = find_assignments(temp->children[j], prefix); for (auto a : block_assignments) { auto find_a = assignments.find(a.first); if (find_a != assignments.end()) assignments[a.first] += a.second; else assignments[a.first] = a.second; } } } else if (temp->type == FUNC_DEF_NODE) { string func_prefix = prefix + temp->value.s_value + "::"; auto block_assignments = find_assignments(temp->children[0],func_prefix); set<string> param_names; for (int j = 0; j < temp->num_parameters; j++) { param_names.insert(func_prefix + temp->parameters[j]); } for (auto a : block_assignments) { auto find_a = assignments.find(a.first); if (find_a != assignments.end()) { assignments[a.first] += a.second; } else { assignments[a.first] = a.second; } // account for parameter mutation properly with +1 auto is_param = param_names.find(a.first); if (is_param != param_names.end()) assignments[a.first] += 1; } } } return assignments; }
#include "stdafx.h" #include "window.h" #include "TVView.h" #include "TVCreator.h" #include "utilites/serl/Archive.h" Window::Window(HWND h, int id, rect r) : hwnd_(h), id_(id), r_(r), contents_(0) { } Window::Window(const Window &win) : id_(win.id_), r_(win.r_), hwnd_(win.hwnd_), contents_(0) { } Window::~Window() { } void Window::set_rect(const rect &r) { r_=r; } void Window::set_hwnd(HWND h) { hwnd_=h; }; void Window::scale(const rect &prev, const rect &rc) { r_.left_ =::scale(r_.left_, prev.left_, prev.right_, rc.left_, rc.right_); r_.right_=::scale(r_.right_, prev.left_, prev.right_, rc.left_, rc.right_); r_.top_ =::scale(r_.top_, prev.top_, prev.bottom_, rc.top_, rc.bottom_); r_.bottom_=::scale(r_.bottom_, prev.top_, prev.bottom_, rc.top_, rc.bottom_); } int Window::get_id() const { return id_; } const rect &Window::get_rect() const { return r_; } HWND Window::get_hwnd() const { return hwnd_; } bool Window::operator==(int id) const { return id_==id; } bool Window::operator==(Window other) const { return get_rect()==other.get_rect(); } CTVCreator *Window::get_contents() const { return contents_; } void Window::serialization(serl::archiver &ar) { bool has_window=hwnd_; ar.serial("has_window", has_window); ar.serial("rect", r_); ar.serial("id", id_); if (has_window) { if (ar.is_saving()) { ::SendMessage(hwnd_, TVVM_GETCLASSPTR, (WPARAM)&contents_, 0); } ar.serial_virtual_ptr("contents", contents_); } }
/* * Author : BurningTiles */ #include <iostream> using namespace std; int main(){ int B, N, temp; cin >> B >> N; while(N-- && cin >> temp) B -= ++temp/2; if(cin.fail()) cout << "Invalid Input"; else (B>0)? cout << "YES" : cout << "NO"; return 0; } /* One day Bob is playing Zombie World video game. In Zombie World game each round will contain N zombie's and each zombie's energy is Zi (where 1<=i<=N). Bob will start the round with B energy. In order to move to the next level Bob need to kill all the N zombie's but Bob can select any one among N Zombie's. If energy of Bob (B) is less than Zombie energy (Zi) then Bob will die and lose the round else Bob will won, during the fighting with zombie, Bob will lose his energy by (Zi%2)+(Zi/2). At any point of game Bob will play optimally. Now your task is to find out whether Bob can reach to the next level or not. Input Format First line will contains B and N, separated by space, where B is the energy of Bob and N is the number of Zombie. Next line will contain N spaced integers each will represent the energy of zombie. Zi, where Zi is a list containing energy of zombies separated by space Output Format For Valid Input, Print "YES" or "NO" depending upon whether Bob can reach the next level or not. For Invalid Input,print "Invalid Input" Constraints 1 <= N <= 10^4 1 <= B <= 10^9 1 <= Zi <= 10^5 Note: For this problem all the divisions are integer divisions. Sample Input 1 35 3 5 9 6 Sample Output 1 YES Sample Input 2 456 68 a Sample Output 2 Invalid Input Sample Input 3 4 4 1 3 2 4 Sample Output 3 NO */
/*********************************************************************** created: Mon Jul 4 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 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/WindowRendererSets/Core/Scrollbar.h" #include "CEGUI/falagard/WidgetLookManager.h" #include "CEGUI/falagard/WidgetLookFeel.h" #include "CEGUI/WindowManager.h" #include "CEGUI/CoordConverter.h" #include "CEGUI/widgets/Thumb.h" #include "CEGUI/widgets/PushButton.h" #include "CEGUI/TplWindowRendererProperty.h" // Start of CEGUI namespace section namespace CEGUI { const String FalagardScrollbar::TypeName("Core/Scrollbar"); FalagardScrollbar::FalagardScrollbar(const String& type) : ScrollbarWindowRenderer(type), d_vertical(false) { CEGUI_DEFINE_WINDOW_RENDERER_PROPERTY(FalagardScrollbar, bool, "VerticalScrollbar", "Property to get/set whether the Scrollbar operates in the vertical direction." " Value is either \"true\" or \"false\".", &FalagardScrollbar::setVertical, &FalagardScrollbar::isVertical, false); } void FalagardScrollbar::createRenderGeometry() { const WidgetLookFeel& wlf = getLookNFeel(); const auto& imagery = wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" : (d_window->isFocused() && wlf.isStateImageryPresent("EnabledFocused") ? "EnabledFocused" : "Enabled")); imagery.render(*d_window); } bool FalagardScrollbar::performChildWindowLayout() { updateThumb(); return true; } void FalagardScrollbar::updateThumb() { Scrollbar* w = static_cast<Scrollbar*>(d_window); const WidgetLookFeel& wlf = getLookNFeel(); Rectf area(wlf.getNamedArea("ThumbTrackArea").getArea().getPixelRect(*w)); Thumb* theThumb = w->getThumb(); const float posExtent = w->getDocumentSize() - w->getPageSize(); if (d_vertical) { const float wndSize = w->getPixelSize().d_height; if (wndSize != 0.0f && posExtent != 0.0f) { const float slideExtent = area.getHeight() - theThumb->getPixelSize().d_height; theThumb->setVertRange(area.top() / wndSize, (area.top() + slideExtent) / wndSize); theThumb->setPosition(UVector2( cegui_absdim(area.left()), cegui_reldim((area.top() + (w->getScrollPosition() * (slideExtent / posExtent))) / wndSize))); } else { theThumb->setVertRange(0.0f, 0.0f); theThumb->setPosition(UVector2(cegui_absdim(area.left()), cegui_reldim(0.0f))); } } else { const float wndSize = w->getPixelSize().d_width; if (wndSize != 0.0f && posExtent != 0.0f) { const float slideExtent = area.getWidth() - theThumb->getPixelSize().d_width; theThumb->setHorzRange(area.left() / wndSize, (area.left() + slideExtent) / wndSize); theThumb->setPosition(UVector2( cegui_reldim((area.left() + (w->getScrollPosition() * (slideExtent / posExtent))) / wndSize), cegui_absdim(area.top()))); } else { theThumb->setHorzRange(0.0f, 0.0f); theThumb->setPosition(UVector2(cegui_reldim(0.0f), cegui_absdim(area.top()))); } } } float FalagardScrollbar::getValueFromThumb() const { Scrollbar* w = static_cast<Scrollbar*>(d_window); const WidgetLookFeel& wlf = getLookNFeel(); const Rectf area(wlf.getNamedArea("ThumbTrackArea").getArea().getPixelRect(*w)); Thumb* theThumb = w->getThumb(); const float posExtent = w->getDocumentSize() - w->getPageSize(); if (posExtent == 0.f) return 0.f; if (d_vertical) { float slideExtent = area.getHeight() - theThumb->getPixelSize().d_height; return (CoordConverter::asAbsolute(theThumb->getYPosition(), w->getPixelSize().d_height) - area.top()) / (slideExtent / posExtent); } else { float slideExtent = area.getWidth() - theThumb->getPixelSize().d_width; return (CoordConverter::asAbsolute(theThumb->getXPosition(), w->getPixelSize().d_width) - area.left()) / (slideExtent / posExtent); } } float FalagardScrollbar::getAdjustDirectionFromPoint(const glm::vec2& pt) const { Scrollbar* w = static_cast<Scrollbar*>(d_window); const Rectf& absrect(w->getThumb()->getUnclippedOuterRect().get()); if ((d_vertical && (pt.y > absrect.bottom())) || (!d_vertical && (pt.x > absrect.right()))) { return 1; } else if ((d_vertical && (pt.y < absrect.top())) || (!d_vertical && (pt.x < absrect.left()))) { return -1; } else { return 0; } } bool FalagardScrollbar::isVertical() const { return d_vertical; } void FalagardScrollbar::setVertical(bool setting) { d_vertical = setting; } } // End of CEGUI namespace section
#include "PurchaseList.h" #pragma region Merge Sort Code // The following code was adapted from // https://www.tutorialspoint.com/cplusplus-program-to-implement-merge-sort-algorithm-on-linked-list Purchase* PurchaseList::mergeList(Purchase* list1, Purchase* list2) { Purchase* newHead = NULL; if (list1 == NULL) { return list2; } if (list2 == NULL) { return list1; } if (list1->totalAmount <= list2->totalAmount) { newHead = list1; newHead->next = mergeList(list1->next, list2); } else { newHead = list2; newHead->next = mergeList(list1, list2->next); } return newHead; } // The following code was adapted from // https://www.tutorialspoint.com/cplusplus-program-to-implement-merge-sort-algorithm-on-linked-list void PurchaseList::splitList(Purchase* start, Purchase** list1, Purchase** list2) { Purchase* slow = start; Purchase* fast = start->next; while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } } *list1 = start; *list2 = slow->next; slow->next = NULL; } // The following code was adapted from // https://www.tutorialspoint.com/cplusplus-program-to-implement-merge-sort-algorithm-on-linked-list void PurchaseList::mergeSort(Purchase** start) { Purchase* head = *start; Purchase* list1, * list2; if (head == NULL || head->next == NULL) { return; } splitList(head, &list1, &list2); mergeSort(&list1); mergeSort(&list2); *start = mergeList(list1, list2); return; } #pragma endregion int PurchaseList::getSize() { return size; } Purchase* PurchaseList::AddPurchase(string custName, string custEmail, string custPhNo) { try { // Initializes a new Purchase object Purchase* purchase = new Purchase(); auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); #pragma warning(suppress : 4996) (*purchase).purchaseTimeStamp = ctime(&timenow); // Increase the amount of items size++; id++; (*purchase).custEmail = custEmail; (*purchase).custName = custName; (*purchase).custPhNo = custPhNo; (*purchase).purchaseId = id; if (purchaseHead == NULL) { (*purchase).next = NULL; } else { (*purchase).next = purchaseHead; } purchaseHead = purchase; return purchase; } catch (exception e) { cerr << endl << e.what() << endl; return NULL; } } void PurchaseList::Print() { Purchase* ptr = purchaseHead; if (ptr == NULL) { cout << endl << "No purchases made"; return; } while (ptr != NULL) { cout << endl << "===================================="; cout << endl << "Purchase ID: " << ptr->purchaseId; cout << endl << "Customer Name: " << ptr->custName; cout << endl << "Customer Phone Number: " << ptr->custPhNo; cout << endl << "Customer Email: " << ptr->custEmail; cout << endl << "Transaction Date: " << ptr->purchaseTimeStamp; cout << endl << "Transaction Amount: " << ptr->totalAmount; cout << endl << "===================================="; ptr = ptr->next; } } void PurchaseList::Print(Purchase* ptr) { cout << endl << "Displaying all purchases"; if (ptr == nullptr) { cout << endl << "===================================="; cout << endl << "No purchases made"; cout << endl << "===================================="; return; } while (ptr != nullptr) { cout << endl << "===================================="; cout << endl << "Purchase ID: " << ptr->purchaseId; cout << endl << "Customer Name: " << ptr->custName; cout << endl << "Customer Phone Number: " << ptr->custPhNo; cout << endl << "Customer Email: " << ptr->custEmail; cout << endl << "Transaction Date: " << ptr->purchaseTimeStamp; cout << endl << "Transaction Amount: " << ptr->totalAmount; cout << endl << "===================================="; ptr = ptr->next; } } void PurchaseList::SortByTotal() { Purchase* ptr = purchaseHead; mergeSort(&ptr); this->Print(ptr); } void PurchaseList::ViewDetail(Purchase* purchase) { cout << endl << "===================================="; cout << endl << "Purchase Detail"; cout << endl << "===================================="; cout << endl << "Purchase ID: " << purchase->purchaseId; cout << endl << "Customer Name: " << purchase->custName; cout << endl << "Customer Phone Number: " << purchase->custPhNo; cout << endl << "Customer Email: " << purchase->custEmail; cout << endl << "Transaction Date: " << purchase->purchaseTimeStamp; cout << endl << "Transaction Amount: " << purchase->totalAmount; cout << endl << "===================================="; cout << endl << "Pet Details"; cout << endl << "===================================="; Pet* pet = purchase->pets; while (pet != NULL) { cout << endl << "Breed: " << pet->petBreed; cout << endl << "Color: " << pet->petColor; cout << endl << "Price: " << pet->price; cout << endl << "===================================="; pet = pet->next; } } Purchase* PurchaseList::getItemBasedOnId(int index) { Purchase* current = purchaseHead; while (current != NULL) { if (current->purchaseId == index) { return current; } current = current->next; } return NULL; } bool PurchaseList::AddPet(Purchase* purchase, Pet* pet) { try { Pet* newPet = new Pet(); newPet->petBreed = pet->petBreed; newPet->petColor = pet->petColor; newPet->price = pet->price; newPet->petId = pet->petId; newPet->next = purchase->pets; purchase->pets = newPet; // Updates the totalAmount of the purchase double totalPrice = purchase->totalAmount + newPet->price; purchase->totalAmount += totalPrice; return true; } catch (exception e) { cerr << e.what(); return false; } }
#pragma once enum BStates { BS_DEFAULT, BS_ALPHA, BS_ADDITIVE, BS_COUNT }; class BlendStateManager { public: BlendStateManager(void); ~BlendStateManager(void); bool ApplyState(BStates eState); ID3D11BlendState* GetState(BStates eState) { if (eState < BS_COUNT) return m_pBlendStates[eState]; return nullptr; } BStates GetCurrentState(void) { return m_eCurrentState; } private: void CreateStates(void); ID3D11BlendState* m_pBlendStates[BS_COUNT]; BStates m_eCurrentState; };
#define _CRT_SECURE_NO_WARNINGS #include <Windows.h> #include <iostream> #include <vector> #include <array> #include <random> #include <thread> #include <atomic> #include <glm/glm.hpp> #include <glm/ext/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale #define TINYOBJLOADER_IMPLEMENTATION #include <tiny_obj_loader/tiny_obj_loader.h> struct Vox_Object { std::string name; std::vector<glm::vec3> vertices; std::vector<glm::uvec3> faces; glm::mat4 transform = glm::mat4(1.0f); glm::vec3 bbox[2] = { {FLT_MAX, FLT_MAX, FLT_MAX}, {-FLT_MAX, -FLT_MAX, -FLT_MAX} }; }; struct Vox_AABB { glm::vec3 lb; glm::vec3 ub; Vox_AABB() : lb(0.0), ub(0.0) {} Vox_AABB(glm::vec3 mi, glm::vec3 ma) : lb(mi), ub(ma) {} Vox_AABB(float* vals) : Vox_AABB(glm::vec3(vals[0], vals[1], vals[2]), glm::vec3(vals[3], vals[4], vals[5])) {} Vox_AABB(double* vals) : Vox_AABB(glm::vec3((float)vals[0], (float)vals[1], (float)vals[2]), glm::vec3((float)vals[3], (float)vals[4], (float)vals[5])) {} std::array<Vox_AABB, 8> split() const; glm::vec3 extents() const { return (ub - lb); } glm::vec3 center() const { return (ub + lb) / 2.0f; } float volume() const { glm::vec3 cell_extents = extents(); return cell_extents.x * cell_extents.y * cell_extents.z; } float radius() const { glm::vec3 cell_extents = extents(); float longest_value = glm::max(cell_extents.x, glm::max(cell_extents.y, cell_extents.z)); return longest_value * 0.5f; } int longest() const { glm::vec3 cell_extents = extents(); float longest_value = glm::max(cell_extents.x, glm::max(cell_extents.y, cell_extents.z)); if (longest_value == cell_extents.x) return 0; if (longest_value == cell_extents.y) return 1; if (longest_value == cell_extents.z) return 2; return 0; } bool intersects(const glm::vec3& va, const glm::vec3& vb, const glm::vec3& vc) const { return intersects(Vox_AABB(glm::min(va, glm::min(vb, vc)), glm::max(va, glm::max(vb, vc)))); } bool intersects(const Vox_AABB& B) const { //Check if this's max is greater than B's min and this's min is less than B's max return( ub.x > B.lb.x && lb.x < B.ub.x&& ub.y > B.lb.y && lb.y < B.ub.y&& ub.z > B.lb.z && lb.z < B.ub.z ); } bool contains(glm::vec3 point) const { return( ub.x >= point.x && lb.x <= point.x && ub.y >= point.y && lb.y <= point.y && ub.z >= point.z && lb.z <= point.z ); } bool singular(Vox_AABB B) const { return ((lb == B.lb) && (ub == B.ub)); } }; Vox_AABB intersection(const Vox_AABB& lhs, const Vox_AABB& rhs) { if (!lhs.intersects(rhs)) return {}; return { { glm::max(lhs.lb.x, rhs.lb.x), glm::max(lhs.lb.y, rhs.lb.y), glm::max(lhs.lb.z, rhs.lb.z) }, { glm::min(lhs.ub.x, rhs.ub.x), glm::min(lhs.ub.y, rhs.ub.y), glm::min(lhs.ub.z, rhs.ub.z) } }; } Vox_AABB operator+ (const Vox_AABB& lhs, const glm::vec3& rhs) { return { lhs.lb + rhs, lhs.ub + rhs }; } Vox_AABB operator- (const Vox_AABB& lhs, const glm::vec3& rhs) { return { lhs.lb - rhs, lhs.ub - rhs }; } Vox_AABB operator/ (const Vox_AABB& lhs, const glm::uvec3& rhs) { return { lhs.lb / glm::vec3(rhs), lhs.ub / glm::vec3(rhs) }; } std::array<Vox_AABB, 8> Vox_AABB::split() const { const auto cell = Vox_AABB{ lb, center() }; const auto cell_extents = cell.extents(); return { cell + glm::vec3(0, 0, 0), cell + glm::vec3(cell_extents.x,0, 0), cell + glm::vec3(0, cell_extents.y,0), cell + glm::vec3(0, 0, cell_extents.z), cell + glm::vec3(cell_extents.x,cell_extents.y,0), cell + glm::vec3(cell_extents.x,0 ,cell_extents.z), cell + glm::vec3(0, cell_extents.y,cell_extents.z), cell + glm::vec3(cell_extents.x,cell_extents.y,cell_extents.z) }; } /* Classify points whether they are inside or outside a mesh */ typedef enum { VOX_POINT_CLASS_INSIDE, VOX_POINT_CLASS_OUTSIDE } Vox_PointClassification; bool Vox_ObjectLoad(Vox_Object* object, const char* filename); bool Vox_ObjectTransform(Vox_Object* object, const float* transformv); bool Vox_ObjectVoxelize(Vox_Object* object, unsigned int dim_x, unsigned int dim_y, unsigned int dim_z, unsigned int* binary_grid, float* voxel_grid, bool normAcrossLongest ); bool Vox_ObjectLoad(Vox_Object* object, const char* filename); bool Vox_ObjectTransform(Vox_Object* object, const float* transformv); void Vox_VoxelizeFile(const std::string &, const std::string&, unsigned int, unsigned int, unsigned int, bool); void Vox_VoxelizeDirectory(const std::string &, const std::string&, unsigned int, unsigned int, unsigned int, bool); int main(int argc, char* argv[]) { std::string op = "t"; if (argc != 5) return 0; bool normAccrosLongest = false; if (!strcmp(argv[4], "1")) { normAccrosLongest = true; } else if (!strcmp(argv[4], "0")) { normAccrosLongest = false; } if (!strcmp(argv[1], "-d")) { Vox_VoxelizeDirectory(argv[2], argv[3], 32, 32, 32, normAccrosLongest); } else if (!strcmp(argv[1], "-f")) { Vox_VoxelizeFile(argv[2], argv[3], 32, 32, 32, normAccrosLongest); } return 0; } /* @see page 142 chapter 5 of * http://www.r-5.org/files/books/computers/algo-list/realtime-3d/Christer_Ericson-Real-Time_Collision_Detection-EN.pdf */ typedef glm::vec3 Point; typedef glm::vec3 Vector; Point ClosestPtPointTriangle(Point p, Point a, Point b, Point c) { // Check if P in vertex region outside A Vector ab = b - a; Vector ac = c - a; Vector ap = p - a; float d1 = glm::dot(ab, ap); float d2 = glm::dot(ac, ap); if (d1 <= 0.0f && d2 <= 0.0f) return a; // barycentric coordinates (1,0,0) // Check if P in vertex region outside B Vector bp = p - b; float d3 = glm::dot(ab, bp); float d4 = glm::dot(ac, bp); if (d3 >= 0.0f && d4 <= d3) return b; // barycentric coordinates (0,1,0) // Check if P in edge region of AB, if so return projection of P onto AB float vc = d1 * d4 - d3 * d2; if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f) { float v = d1 / (d1 - d3); return a + v * ab;// barycentric coordinates (1-v,v,0) } // Check if P in vertex region outside C Vector cp = p - c; float d5 = glm::dot(ab, cp); float d6 = glm::dot(ac, cp); if (d6 >= 0.0f && d5 <= d6) return c;// barycentric coordinates (0,0,1) // Check if P in edge region of AC, if so return projection of P onto AC float vb = d5 * d2 - d1 * d6; if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f) { float w = d2 / (d2 - d6); return a + w * ac; // barycentric coordinates (1-w,0,w) } // Check if P in edge region of BC, if so return projection of P onto BC float va = d3 * d6 - d5 * d4; if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f) { float w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); return b + w * (c - b); // barycentric coordinates (0,1-w,w) } // P inside face region. Compute Q through its barycentric coordinates (u,v,w) float denom = 1.0f / (va + vb + vc); float v = vb * denom; float w = vc * denom; return a + ab * v + ac * w; //=u*a+v*b+w*c,u=va*denom = 1.0f-v-w } float GetCLosestPointOnTriangle(const glm::vec3* vertices, unsigned int attr_count, const glm::uvec3* faces, unsigned int face_count, glm::vec3 query, float bias, glm::vec3* result, Vox_PointClassification* p_class) { auto min_class = VOX_POINT_CLASS_OUTSIDE; auto min_distance = 1000000.0f; auto min_face = faces[0]; for (unsigned int face_index = 0; face_index < face_count; face_index++) { const auto& face = faces[face_index]; const auto& va = vertices[face.x]; const auto& vb = vertices[face.y]; const auto& vc = vertices[face.z]; const auto edge_a = vb - va; const auto edge_b = vc - va; const auto gnormal = glm::normalize(glm::cross(edge_a, edge_b)); const auto closest_point = ClosestPtPointTriangle(query, va, vb, vc); const auto VtC = glm::normalize(query - va); const auto temp_class = (glm::dot(gnormal, VtC) >= 0.0) ? VOX_POINT_CLASS_OUTSIDE : VOX_POINT_CLASS_INSIDE; const auto dist = glm::distance(closest_point, query); /* This is an attempt to "favor" being on the outside * False positive voxels can be considered much more * problematic than false negatives */ if (temp_class == VOX_POINT_CLASS_OUTSIDE && min_class == VOX_POINT_CLASS_INSIDE) { if (dist <= min_distance + bias) { min_distance = dist; min_face = face; min_class = temp_class; *result = closest_point; } } else { if (dist < min_distance) { min_distance = dist; min_face = face; min_class = temp_class; *result = closest_point; } } } const auto& face = min_face; const auto& va = vertices[face.x]; const auto& vb = vertices[face.y]; const auto& vc = vertices[face.z]; const auto edge_a = vb - va; const auto edge_b = vc - va; const auto gnormal = glm::normalize(glm::cross(edge_a, edge_b)); const auto VtC = glm::normalize(query - *result); *p_class = (glm::dot(gnormal, VtC) > 0.0) ? VOX_POINT_CLASS_OUTSIDE : VOX_POINT_CLASS_INSIDE; return min_distance; } bool Vox_ObjectVoxelize(Vox_Object* object, unsigned int dim_x, unsigned int dim_y, unsigned int dim_z, unsigned int* binary_grid, float* voxel_grid, bool normAcrossLongest ) { auto root = Vox_AABB(object->bbox[0], object->bbox[1]); auto aabb_size = root.extents(); auto root_new = root; if (normAcrossLongest) { root_new = Vox_AABB(root.lb, root.lb + aabb_size[root.longest()]); } aabb_size = root_new.extents(); auto cell_size = aabb_size / glm::vec3{ dim_x, dim_y, dim_z }; auto origin = Vox_AABB(root.lb, root.lb + cell_size); if (normAcrossLongest) { origin = origin - (root_new.center() - root.center()); } const auto bias = cell_size[origin.longest()] / 100.0f; const auto& faces = object->faces; const auto& vertices = object->vertices; for (unsigned int i = 0; i < dim_x; i++) { for (unsigned int j = 0; j < dim_y; j++) { for (unsigned int k = 0; k < dim_z; k++) { unsigned int index = k * dim_y * dim_x + j * dim_x + i; auto class_cell = VOX_POINT_CLASS_OUTSIDE; const auto cell = origin + glm::vec3(i, j, k) * cell_size; const auto center = cell.center(); glm::vec3 poi; float dist = GetCLosestPointOnTriangle( vertices.data(), (unsigned int)vertices.size(), faces.data(), (unsigned int)faces.size(), center, bias, &poi, &class_cell ); binary_grid[index] = 0; if (cell.contains(poi) || class_cell == VOX_POINT_CLASS_INSIDE) { binary_grid[index] = 1; voxel_grid[3 * index + 0] = center.x; voxel_grid[3 * index + 1] = center.y; voxel_grid[3 * index + 2] = center.z; } } } } return true; } void Vox_VoxelizeDirectory(const std::string & filepath, const std::string& outFolder, unsigned int dim_x, unsigned int dim_y, unsigned int dim_z, bool normAcrossLongest) { HANDLE hFind = INVALID_HANDLE_VALUE; WIN32_FIND_DATA ffd; char szDir[MAX_PATH]; std::string dir_path = filepath; std::replace(dir_path.begin(), dir_path.end(), '\\', '/'); strcpy(szDir, dir_path.c_str()); strcat(szDir, "/*"); hFind = FindFirstFile(szDir, &ffd); if (INVALID_HANDLE_VALUE == hFind) return; //CreateDirectoryA(outFolder.c_str(), NULL); std::vector<std::string> files; std::vector<std::thread> worker_pool; auto thread_count = std::thread::hardware_concurrency(); std::atomic<int> next = 0; do { if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { std::string filename = dir_path + "/" + ffd.cFileName; if ((filename.find(".obj") == std::string::npos) && (filename.find(".OBJ") == std::string::npos)) continue; files.push_back(filename); } } while (FindNextFile(hFind, &ffd) != 0); for (size_t worker_index = 0; worker_index < thread_count; worker_index++) { worker_pool.push_back(std::thread([&files, &outFolder, &next](unsigned int dim_x, unsigned int dim_y, unsigned int dim_z, bool normAcrossLongest) { auto index = next.fetch_add(1); while (index < files.size()) { Vox_VoxelizeFile(files[index].c_str(), outFolder, dim_x, dim_y, dim_z, normAcrossLongest); index = next.fetch_add(1); } }, dim_x, dim_y, dim_z, normAcrossLongest)); } for (auto& worker : worker_pool) { worker.join(); } } void Vox_VoxelizeFile(const std::string & filepath, const std::string & outFolder, unsigned int dim_x, unsigned int dim_y, unsigned int dim_z, bool normAcrossLongest) { Vox_Object A; const auto last_slash_idx = filepath.find_last_of("\\/"); const auto last_dot_idx = filepath.find_last_of("."); if (std::string::npos == last_slash_idx || std::string::npos == last_dot_idx) return; auto filename_out = filepath.substr(last_slash_idx + 1, last_dot_idx - last_slash_idx - 1); filename_out += ".asc"; if (!Vox_ObjectLoad(&A, filepath.c_str())) { return; } std::cout << "BC3D: Voxelizing " << filepath << " to [" << dim_x << ", " << dim_y << ", " << dim_z << "]" << std::endl; std::vector<unsigned int> binary_grid; std::vector<glm::vec3> voxel_grid; binary_grid.resize(dim_x * dim_y * dim_z); voxel_grid.resize(dim_x * dim_y * dim_z); Vox_ObjectVoxelize(&A, dim_x, dim_y, dim_z, binary_grid.data(), (float*)voxel_grid.data(), normAcrossLongest); FILE* f = fopen((outFolder + "/" + filename_out).c_str(), "w"); for (unsigned int i = 0; i < dim_x; i++) { for (unsigned int j = 0; j < dim_y; j++) { for (unsigned int k = 0; k < dim_z; k++) { unsigned int index = k * dim_y * dim_x + j * dim_x + i; if (1 == binary_grid[index]) { const auto& voxel = voxel_grid[index]; fprintf(f, "%d %d %d\n", i, j, k); } } } } fclose(f); } bool Vox_ObjectLoad(Vox_Object* object, const char* filename) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string warn; std::string err; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename, "./", true); if (!ret) { return false; } unsigned int vertex_index = 0; unsigned int face_index = 0; for (const auto& shape : shapes) { unsigned int index_offset = 0; for (size_t f = 0; f < shape.mesh.num_face_vertices.size(); f++) { int fv = shape.mesh.num_face_vertices[f]; if (fv != 3) { std::cout << "Not a triangular mesh" << std::endl; continue; } object->faces.push_back({ vertex_index + 0, vertex_index + 1, vertex_index + 2 }); for (size_t v = 0; v < fv; v++) { tinyobj::index_t idx = shape.mesh.indices[index_offset + v]; float vx = attrib.vertices[3 * idx.vertex_index + 0]; float vy = attrib.vertices[3 * idx.vertex_index + 1]; float vz = attrib.vertices[3 * idx.vertex_index + 2]; object->vertices.push_back({ vx, vy, vz }); vertex_index++; } index_offset += fv; } } object->bbox[0] = object->vertices[0]; object->bbox[1] = object->vertices[0]; for (const auto& vertex : object->vertices) { object->bbox[0] = glm::min(object->bbox[0], vertex); object->bbox[1] = glm::max(object->bbox[1], vertex); } object->transform = glm::mat4(1.0f); return true; } bool Vox_ObjectTransform(Vox_Object* object, const float* transformv) { glm::mat4 transform; memcpy(&transform[0][0], transformv, sizeof(transform)); for (auto& vertex : object->vertices) { vertex = glm::vec3(transform * glm::vec4(vertex, 1.0f)); } object->bbox[0] = glm::vec3(transform * glm::vec4(object->bbox[0], 1.0f)); object->bbox[1] = glm::vec3(transform * glm::vec4(object->bbox[1], 1.0f)); object->transform = transform; return true; }
#include "PointLight.h" int PointLight::idIndex = 0; PointLight::PointLight() : _ambient(glm::vec3(0.05f)), _diffuse(glm::vec3(1.0f)), _specular(glm::vec3(1.0f)) { id = idIndex++; } void PointLight::RenderMe(AbstractRenderer* renderer) { std::string pointLightId = "pointLights[" + std::to_string(id) + "]"; glUniform3f(renderer->GetShader()->GetUniformLocation(pointLightId + ".position"), GetWorldPosition().x, GetWorldPosition().y, GetWorldPosition().z); glUniform3f(renderer->GetShader()->GetUniformLocation(pointLightId + ".ambient"), _ambient.r, _ambient.g, _ambient.b); glUniform3f(renderer->GetShader()->GetUniformLocation(pointLightId + ".diffuse"), _diffuse.r, _diffuse.g, _diffuse.b); glUniform3f(renderer->GetShader()->GetUniformLocation(pointLightId + ".specular"), _specular.r, _specular.g, _specular.b); glUniform1f(renderer->GetShader()->GetUniformLocation(pointLightId + ".linear"), 0.009f); glUniform1f(renderer->GetShader()->GetUniformLocation(pointLightId + ".quadratic"), 0.0032f); } const glm::vec3& PointLight::GetAmbient() { return _ambient; } const glm::vec3& PointLight::GetDiffuse() { return _diffuse; } const glm::vec3& PointLight::GetSpecular() { return _specular; } void PointLight::SetAmbient(const glm::vec3& ambient) { _ambient = ambient; } void PointLight::SetDiffuse(const glm::vec3& diffuse) { _diffuse = diffuse; } void PointLight::SetSpecular(const glm::vec3& specular) { _specular = specular; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.Media.DialProtocol.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_cdb5efb3_5788_509d_9be1_71ccb8a3362a #define WINRT_GENERIC_cdb5efb3_5788_509d_9be1_71ccb8a3362a template <> struct __declspec(uuid("cdb5efb3-5788-509d-9be1-71ccb8a3362a")) __declspec(novtable) IAsyncOperation<bool> : impl_IAsyncOperation<bool> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e #define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {}; #endif #ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e #define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {}; #endif #ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90 #define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90 template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_4512c15e_1fc4_5648_bd49_51533a3fe6b4 #define WINRT_GENERIC_4512c15e_1fc4_5648_bd49_51533a3fe6b4 template <> struct __declspec(uuid("4512c15e-1fc4-5648-bd49-51533a3fe6b4")) __declspec(novtable) IAsyncOperation<winrt::Windows::Media::DialProtocol::DialAppLaunchResult> : impl_IAsyncOperation<winrt::Windows::Media::DialProtocol::DialAppLaunchResult> {}; #endif #ifndef WINRT_GENERIC_8598f24e_0d62_517a_961c_31fca73acedd #define WINRT_GENERIC_8598f24e_0d62_517a_961c_31fca73acedd template <> struct __declspec(uuid("8598f24e-0d62-517a-961c-31fca73acedd")) __declspec(novtable) IAsyncOperation<winrt::Windows::Media::DialProtocol::DialAppStopResult> : impl_IAsyncOperation<winrt::Windows::Media::DialProtocol::DialAppStopResult> {}; #endif #ifndef WINRT_GENERIC_e50a07a2_2cef_5fc7_b14c_d6dd8517c58e #define WINRT_GENERIC_e50a07a2_2cef_5fc7_b14c_d6dd8517c58e template <> struct __declspec(uuid("e50a07a2-2cef-5fc7-b14c-d6dd8517c58e")) __declspec(novtable) IAsyncOperation<Windows::Media::DialProtocol::DialAppStateDetails> : impl_IAsyncOperation<Windows::Media::DialProtocol::DialAppStateDetails> {}; #endif #ifndef WINRT_GENERIC_471cada5_1ee4_51c0_b6b5_bf72f5f50422 #define WINRT_GENERIC_471cada5_1ee4_51c0_b6b5_bf72f5f50422 template <> struct __declspec(uuid("471cada5-1ee4-51c0-b6b5-bf72f5f50422")) __declspec(novtable) IAsyncOperation<Windows::Media::DialProtocol::DialDevice> : impl_IAsyncOperation<Windows::Media::DialProtocol::DialDevice> {}; #endif #ifndef WINRT_GENERIC_8375c0d7_e7c3_56bc_9880_46b69ca10d45 #define WINRT_GENERIC_8375c0d7_e7c3_56bc_9880_46b69ca10d45 template <> struct __declspec(uuid("8375c0d7-e7c3-56bc-9880-46b69ca10d45")) __declspec(novtable) TypedEventHandler<Windows::Media::DialProtocol::DialDevicePicker, Windows::Media::DialProtocol::DialDeviceSelectedEventArgs> : impl_TypedEventHandler<Windows::Media::DialProtocol::DialDevicePicker, Windows::Media::DialProtocol::DialDeviceSelectedEventArgs> {}; #endif #ifndef WINRT_GENERIC_13492af0_1c7f_57e8_b57e_a5ae8f2c462e #define WINRT_GENERIC_13492af0_1c7f_57e8_b57e_a5ae8f2c462e template <> struct __declspec(uuid("13492af0-1c7f-57e8-b57e-a5ae8f2c462e")) __declspec(novtable) TypedEventHandler<Windows::Media::DialProtocol::DialDevicePicker, Windows::Media::DialProtocol::DialDisconnectButtonClickedEventArgs> : impl_TypedEventHandler<Windows::Media::DialProtocol::DialDevicePicker, Windows::Media::DialProtocol::DialDisconnectButtonClickedEventArgs> {}; #endif #ifndef WINRT_GENERIC_dac94028_1b44_5f45_b9e3_abcf4ab044bf #define WINRT_GENERIC_dac94028_1b44_5f45_b9e3_abcf4ab044bf template <> struct __declspec(uuid("dac94028-1b44-5f45-b9e3-abcf4ab044bf")) __declspec(novtable) TypedEventHandler<Windows::Media::DialProtocol::DialDevicePicker, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Media::DialProtocol::DialDevicePicker, Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_c1d3d1a2_ae17_5a5f_b5a2_bdcc8844889a #define WINRT_GENERIC_c1d3d1a2_ae17_5a5f_b5a2_bdcc8844889a template <> struct __declspec(uuid("c1d3d1a2-ae17-5a5f-b5a2-bdcc8844889a")) __declspec(novtable) AsyncOperationCompletedHandler<bool> : impl_AsyncOperationCompletedHandler<bool> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236 #define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236 template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_164c0aa8_3d2b_579b_94a3_cc4925c695ec #define WINRT_GENERIC_164c0aa8_3d2b_579b_94a3_cc4925c695ec template <> struct __declspec(uuid("164c0aa8-3d2b-579b-94a3-cc4925c695ec")) __declspec(novtable) AsyncOperationCompletedHandler<winrt::Windows::Media::DialProtocol::DialAppLaunchResult> : impl_AsyncOperationCompletedHandler<winrt::Windows::Media::DialProtocol::DialAppLaunchResult> {}; #endif #ifndef WINRT_GENERIC_c755f54a_ef7b_563a_9b14_462e72d9665a #define WINRT_GENERIC_c755f54a_ef7b_563a_9b14_462e72d9665a template <> struct __declspec(uuid("c755f54a-ef7b-563a-9b14-462e72d9665a")) __declspec(novtable) AsyncOperationCompletedHandler<winrt::Windows::Media::DialProtocol::DialAppStopResult> : impl_AsyncOperationCompletedHandler<winrt::Windows::Media::DialProtocol::DialAppStopResult> {}; #endif #ifndef WINRT_GENERIC_38c62dd5_1f16_55c0_8ec7_ca0fc841d614 #define WINRT_GENERIC_38c62dd5_1f16_55c0_8ec7_ca0fc841d614 template <> struct __declspec(uuid("38c62dd5-1f16-55c0-8ec7-ca0fc841d614")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Media::DialProtocol::DialAppStateDetails> : impl_AsyncOperationCompletedHandler<Windows::Media::DialProtocol::DialAppStateDetails> {}; #endif #ifndef WINRT_GENERIC_81bc7d1b_7d06_555f_811b_42ec0fa71b55 #define WINRT_GENERIC_81bc7d1b_7d06_555f_811b_42ec0fa71b55 template <> struct __declspec(uuid("81bc7d1b-7d06-555f-811b-42ec0fa71b55")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Media::DialProtocol::DialDevice> : impl_AsyncOperationCompletedHandler<Windows::Media::DialProtocol::DialDevice> {}; #endif } namespace Windows::Media::DialProtocol { struct IDialApp : Windows::Foundation::IInspectable, impl::consume<IDialApp> { IDialApp(std::nullptr_t = nullptr) noexcept {} }; struct IDialAppStateDetails : Windows::Foundation::IInspectable, impl::consume<IDialAppStateDetails> { IDialAppStateDetails(std::nullptr_t = nullptr) noexcept {} }; struct IDialDevice : Windows::Foundation::IInspectable, impl::consume<IDialDevice> { IDialDevice(std::nullptr_t = nullptr) noexcept {} }; struct IDialDevice2 : Windows::Foundation::IInspectable, impl::consume<IDialDevice2> { IDialDevice2(std::nullptr_t = nullptr) noexcept {} }; struct IDialDevicePicker : Windows::Foundation::IInspectable, impl::consume<IDialDevicePicker> { IDialDevicePicker(std::nullptr_t = nullptr) noexcept {} }; struct IDialDevicePickerFilter : Windows::Foundation::IInspectable, impl::consume<IDialDevicePickerFilter> { IDialDevicePickerFilter(std::nullptr_t = nullptr) noexcept {} }; struct IDialDeviceSelectedEventArgs : Windows::Foundation::IInspectable, impl::consume<IDialDeviceSelectedEventArgs> { IDialDeviceSelectedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IDialDeviceStatics : Windows::Foundation::IInspectable, impl::consume<IDialDeviceStatics> { IDialDeviceStatics(std::nullptr_t = nullptr) noexcept {} }; struct IDialDisconnectButtonClickedEventArgs : Windows::Foundation::IInspectable, impl::consume<IDialDisconnectButtonClickedEventArgs> { IDialDisconnectButtonClickedEventArgs(std::nullptr_t = nullptr) noexcept {} }; } }
/// /// \file C3DReader.h /// \brief /// \author PISUPATI Phanindra /// \date 03.04.2014 /// /// #ifndef APPLICATION_H #define APPLICATION_H #include "Settings.h" #include "Subject.h" #include "Targets.h" #include "PlotInterface.h" #include <vector> #include <string> #include <memory> /// /// \class Application /// \brief Main Application for handling subjects, etc. /// class Application : public QObject { Q_OBJECT public: /// /// \brief Constructor /// Application(); /// /// \brief Destructor /// ~Application(); /// /// \brief initialiseSubjects: initialises subjects, sequences and target structures /// \param readFromFile: if false, initialise all sequences, otherwise read from files /// void initialiseSubjects(bool readFromFile); uint getSequenceNumber(uint subjectNumber, uint targetNumber); uint getTargetNumber(uint subjectNumber, uint sequenceNumber); public slots: void clearAllPlots(); void plotTrajectory(uint subjectNumber, uint sequenceNumber); void showClickedPoint(uint plotId, Point2d point); void changePlotType(PlotType plotType); void enableOrientation(bool enable); void fixTarget(bool enable); void fixSource(bool enable); private: std::vector<std::unique_ptr<Subject> > _subjects; ///< All subjects std::shared_ptr<Targets> _targets; ///< Target data structure std::string _sequenceDir; ///< S PlotInterface _plotInterface; TrajectoryType _trajectoryType; signals: void pointClicked(uint, float, float); }; #endif // APPLICATION_H
// // Created by sinimawath on 18.05.18. // #ifndef GRAPH_CLISTGRAPH_H #define GRAPH_CLISTGRAPH_H #include <memory> #include "igraph.h" #include "list" class CListGraph : public IGraph{ public: explicit CListGraph(int n) : adjacencyList( n ) {} explicit CListGraph(const std::shared_ptr<IGraph>& igraph); void AddEdge(int from, int to) override; int VerticesCount() const override; std::vector<int> GetNextVertices(int vertex) const override; std::vector<int> GetPrevVertices(int vertex) const override; bool isValidVertices(int ver); private: std::vector<std::list<int>> adjacencyList; }; #endif //GRAPH_CLISTGRAPH_H
#include <bits/stdc++.h> using namespace std; string trim(string s) { string ans = ""; for (char c : s) if (c != ' ') ans += c; return ans; } string reverseWords(string s) { vector<string> words; s += ' '; string temp = ""; for (int i = 0; i < s.length(); i++) { if (s[i] == ' ') { string val = trim(temp); if (val != "") words.push_back(val); temp = ""; } else { temp += s[i]; } } reverse(words.begin(), words.end()); string ans = ""; for (int i = 0; i < words.size(); i++) { if (i == words.size() - 1) ans += words[i]; else ans += words[i] + ' '; } return ans; } int main() { cout << "/" << reverseWords("a good example") << "/"; return 0; }
#include <iostream> #include <iomanip> #include <string> #include <list> #include "LoadBalancer.h" using namespace std; /** * Story: * Assign a server 10 times using load balancer (LoadBalancer) **/ void testSingleton() { cout << endl << "<<Test Singleton>>" << endl; LoadBalancer* loadBalancer; loadBalancer = LoadBalancer::getInstance(); for( int i = 0; i < 10; i++ ) { cout << "Server " << loadBalancer->assignServer() << " is assigned" << endl; } }
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool compare(Interval a,Interval b){ return a.start < b.start; } vector<Interval> Solution::merge(vector<Interval> &A) { sort(A.begin(),A.end(),compare); stack<Interval> s; s.push(A[0]); for(int i=1;i<A.size();i++){ Interval top = s.top(); if(top.end < A[i].start) s.push(A[i]); else if(top.end < A[i].end){ top.end = A[i].end; s.pop(); s.push(top); } } vector<Interval> v; while(!s.empty()){ v.push_back(s.top()); s.pop(); } sort(v.begin(),v.end(),compare); return v; }
/************************************************* * Publicly released by Rhoban System, August 2012 * www.rhoban-system.fr * * Freely usable for non-commercial purposes * * Licence Creative Commons *CC BY-NC-SA * http://creativecommons.org/licenses/by-nc-sa/3.0 *************************************************/ #ifndef _DEMOSERVERCLIENT_H #define _DEMOSERVERCLIENT_H #include <sockets/TCPServerClient.h> #include <sockets/common.h> namespace Rhoban { class DemoServerClient : public TCPServerClient { public: DemoServerClient(SOCKET socket); void loop(); }; } #endif // _DEMOSERVERCLIENT_H
#include <iostream> #include "matchit/core.h" #include "matchit/patterns.h" #include "matchit/utility.h" using namespace matchit; template <typename T> auto square(T const* t) { Id<T> id; return match(t)( pattern(some(id)) = [&id] { return *id * *id; }, pattern(none) = [] { return 0; }); } int main() { auto t = 3; std::cout << square(&t) << std::endl; return 0; }
// // Copyright Jason Rice 2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <nbdl/ui_helper/params_concat.hpp> #include <nbdl/ui_spec.hpp> #include <boost/hana/equal.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/map.hpp> #include <boost/hana/pair.hpp> #include <catch.hpp> #include <string> namespace hana = boost::hana; TEST_CASE("Concatenate ui_spec params into an std::string.", "[ui_helper][params_concat]") { constexpr hana::string<'f', 'o', 'o'> foo_s; constexpr hana::string<'b', 'a', 'r'> bar_s; constexpr hana::string<'b', 'a', 'z'> baz_s; auto store = hana::make_map(hana::make_pair(hana::int_c<0>, std::string(" Hello, world! "))); constexpr auto params = mpdef::make_list( foo_s , bar_s , baz_s , nbdl::ui_spec::get(hana::int_c<0>) , foo_s ); std::string result = nbdl::ui_helper::params_concat(params, store).to_string(); CHECK(result == std::string("foobarbaz Hello, world! foo")); }
#include "Menu.hpp" Menu::Menu(RenderWindow* window) { Window=window; IpIsSet = false; AmIClient = false; AmIServer = false; CreateServer = false; csiga_b.LoadFromFile("contents/csiguszbody.png"); //csiga_b.LoadFromFile("contents/xmas_csiguszbody.png"); Csiga_b.SetImage(csiga_b); Csiga_b.SetPosition(0+100,-5+30); csiga_l.LoadFromFile("contents/csiga_l.png"); Csiga_l.SetImage(csiga_l); Csiga_l.SetCenter(8,80); Csiga_l.SetPosition(385+8+100,350+80+30); csiga_r.LoadFromFile("contents/csiga_r.png"); Csiga_r.SetImage(csiga_r); Csiga_r.SetPosition(277+100,445+30); gun.LoadFromFile("contents/menugun.png"); Gun.SetImage(gun); Gun.SetCenter(36,195); Gun.SetPosition(270+36+100,299+195+30); laser.LoadFromFile("contents/laser2.png"); Laser.SetImage(laser); Laser.SetCenter(-65,71); Laser.SetPosition(Gun.GetPosition().x,Gun.GetPosition().y); ShowIPTextEditor = false; Gun.SetRotation(9); Laser.SetRotation(56); Csiga_l.SetRotation(31); NewGame=new Button(); NewGame->Setup(Window,this,Window->GetWidth()-250,30,200,20,"New Game"); NewGame->SetTextPosition(50,-3); Connect=new Button(); Connect->Setup(Window,this,Window->GetWidth()-250,70,200,20,"Connect"); Connect->SetTextPosition(55,-3); HighScores=new Button(); HighScores->Setup(Window,this,Window->GetWidth()-250,110,200,20,"High Scores"); HighScores->SetTextPosition(35,-3); Description=new Button(); Description->Setup(Window,this,Window->GetWidth()-250,150,200,20,"Description"); Description->SetTextPosition(33,-3); Exit=new Button(); Exit->Setup(Window,this,Window->GetWidth()-250,190,200,20,"Exit"); Exit->SetTextPosition(77,-3); MenuFont.LoadFromFile("contents/Army.ttf"); //ANDIKA RÉSZ: ConnectionText= new String("Network setting\n\n Create server or join", MenuFont,20); ConnectionText->SetPosition(40, 40); ShowConnection=false; ServerButton = new Button(); ServerButton->Setup(Window, this, Window->GetWidth()-760,150,200, 30, "Create server"); ServerButton->SetTextPosition(20, 0); ClientButton = new Button(); ClientButton->Setup(Window, this, Window->GetWidth()-500,150,200, 30, "Join server"); ClientButton->SetTextPosition(40, 0); ServerText = new InputTextField(); ServerText->Setup(Window, this, Window->GetWidth()-700,100,300, 30, "IP:"); //ANDIKA RÉSZ END players=new vector<player>(); player p; ifstream file("contents/Scores.txt"); while (!file.eof()) { file >> p.name; file >> p.score; players->push_back(p); } ScoresText= new String("...",MenuFont,20); ScoresText->SetPosition(150, 40); ShowHighScores=false; DescriptionText= new String("A játék célja hogy kellemes hangulatban\naranyos kis erdei állatkák bõrébe bújva\n halomragyilkolásszuk egymást a\n barátokkal vagy a családtagokkal.\n\n fegyverbe!!!",MenuFont,20); DescriptionText->SetPosition(40, 40); ShowDescription=false; Window2=new RenderWindow(VideoMode(200,100,32), "Exit???...",Style::Close); Window2->Show(false); ShowExitWindow=false; ExitText= new String(" Are you sure,\nyou want to quit?",MenuFont,20); ExitText->SetPosition(5, 10); yes=new Button(); yes->Setup(Window2,this,20,65,60,20,"yes"); yes->SetTextPosition(10,-3); yes->SetStandardColor(Color(0,0,200)); //yes->SetInFocusColor(Color(0,0,255)); no=new Button(); no->Setup(Window2,this,120,65,60,20,"no"); no->SetTextPosition(15,-3); no->SetStandardColor(Color(0,0,200)); no->SetInFocusColor(Color(0,0,255)); Buffer.LoadFromFile("contents/290673_03___Redemption.wav"); MenuSound.SetBuffer(Buffer); MenuSound.SetVolume(100); MenuSound.Play(); LoadingText= new String("Loading...",MenuFont,100); LoadingText->SetPosition(150, 200); } void Menu::Show() { Window->Draw(Csiga_b); Window->Draw(Gun); Window->Draw(Csiga_l); Window->Draw(Csiga_r); Window->Draw(*NewGame); Window->Draw(*NewGame->Text); Window->Draw(*Connect); Window->Draw(*Connect->Text); Window->Draw(*HighScores); Window->Draw(*HighScores->Text); Window->Draw(*Description); Window->Draw(*Description->Text); Window->Draw(*Exit); Window->Draw(*Exit->Text); Window->Draw(Laser); //ANDIKA RÉSZ: if (ShowConnection) { Window->Draw(*ConnectionText); Window->Draw(*ServerButton); Window->Draw(*ServerButton->Text); Window->Draw(*ClientButton); Window->Draw(*ClientButton->Text); } if (ShowIPTextEditor) { ConnectionText= new String("\n Type the IP of the server: ", MenuFont,20); Window->Draw(*ConnectionText); Window->Draw(*ClientButton); Window->Draw(*ClientButton->Text); Window->Draw(*ServerText); Window->Draw(*ServerText->Text); } if (CreateServer) { ConnectionText= new String("\n\n Waiting for client.. ", MenuFont,20); Window->Draw(*ConnectionText); } //ANDIKA END if (ShowHighScores) { Window->Draw(*ScoresText); } if (ShowDescription) { Window->Draw(*DescriptionText); } if (ShowExitWindow) { Event Event; while (Window2->GetEvent(Event)) { yes->EventHandle(Event); no->EventHandle(Event); if (Event.Type == Event::Closed) { ShowExitWindow=false; Window2->Show(false); } if (Event.Type == Event::KeyPressed) { if (Event.Key.Code == Key::Escape) { ShowExitWindow=false; Window2->Show(false); } } } Window2->Clear(); Window2->Draw(*ExitText); Window2->Draw(*yes); Window2->Draw(*yes->Text); Window2->Draw(*no); Window2->Draw(*no->Text); Window2->Display(); } } void Menu::EventHandle(Event ev) { NewGame->EventHandle(ev); Connect->EventHandle(ev); HighScores->EventHandle(ev); Description->EventHandle(ev); Exit->EventHandle(ev); //ANDIKA RÉSZ: ServerButton->EventHandle(ev); ClientButton->EventHandle(ev); ServerText->EventHandle(ev); //ANDIKA RÉSZ END if (Window->GetInput().GetMouseX() > Window->GetWidth()-260 && Window->GetInput().GetMouseY() < 230) { float tav_x=Window->GetInput().GetMouseX()-Gun.GetPosition().x; float tav_y=Window->GetInput().GetMouseY()-Gun.GetPosition().y+33; if (tav_x<0) { Gun.FlipX(true); } else { Gun.FlipX(false); } float lim=((-atan(tav_y/tav_x))*56); if (lim>38 && lim<72) { Gun.SetRotation((-atan(tav_y/tav_x)*55.215)-47); Laser.SetRotation((-atan(tav_y/tav_x)*55.215)); Csiga_l.SetRotation((-atan(tav_y/tav_x)*170)-140); float tav=pow(pow(Window->GetInput().GetMouseX()-Laser.GetPosition().x,2)+pow(Window->GetInput().GetMouseY()-Laser.GetPosition().y,2),(float)0.5); Laser.Resize((tav/1.001)-30,Laser.GetSize().y); } } } void Menu::SetIP(string from) { ip = from.substr(3,from.size()); } string Menu::GetIP() { return ip; } void Menu::Action(string& from) { if (ShowConnection)ShowConnection=false; if (ShowHighScores)ShowHighScores=false; if (ShowDescription)ShowDescription=false; if (ShowExitWindow) { ShowExitWindow=false; Window2->Show(false); } if (from=="New Game") { //GameStart(0); } if (from=="Connect") { ShowConnection=true; } if (from=="Create server") { CreateServer = true; } if (from=="High Scores") { string highscores=" * high scores *\n\n"; player p; for (unsigned int i=0;i<players->size();i++) { p=players->at(i); highscores.append(p.name); highscores.append(".............."); stringstream ss; ss << p.score; string c_string(ss.str()); highscores.append(c_string); highscores.append("\n"); } ScoresText->SetText(highscores); ShowHighScores=true; } if (from=="Description") { ShowDescription=true; } if (from=="Exit") { Window2->Show(true); ShowExitWindow=true; } if (from=="yes") { Window->Close(); } if (from=="no") { Window2->Show(false); ShowExitWindow=false; } //ANDIKA RÉSZ: if (from=="Join server") { if (AmIServer||AmIClient) { cout<<"Error: you are already server or client is running!"; return; } ShowIPTextEditor = true; cout<<"join server"; if (ShowIPTextEditor&&IpIsSet) { p = &ip; GameStart(2); AmIClient = true; } } if (from =="Create server") { if (AmIClient||AmIServer) { cout<<"Error: you are already client or server is already running!"; return; } cout<<"create server"; GameStart(1); AmIServer = true; } //ANDIKA RÉSZ END } void Menu::GameStart(int i){ MenuSound.Pause(); Window->Clear(); Window->Draw(*LoadingText); Window->Display(); MyGame=new Game(Window, i, ip); MyGame->InGame=true; MyGame->GameLoop(); MenuSound.Play(); }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * transform function the set of left child of root(x) is the set of root(y < x) * transform function the set of right child of root(x) is the set of root(z > x) */ class Solution { public: vector<TreeNode *> generateTreesHelper(int left, int right) { vector<TreeNode *> ret, leftChild, rightChild; TreeNode *root = NULL; if(right < left) { ret.push_back(root); return ret; } for(int i = left; i <= right; i++) { leftChild = generateTreesHelper(left, i - 1); rightChild = generateTreesHelper(i + 1, right); for(int j = 0; j < leftChild.size(); j++){ for(int k = 0; k < rightChild.size(); k++){ root = new TreeNode(i); root->left = leftChild[j]; root->right = rightChild[k]; ret.push_back(root); } } } return ret; } vector<TreeNode*> generateTrees(int n) { vector<TreeNode*> ret; if(n > 0) ret = generateTreesHelper(1, n); return ret; } };
#include "reqcompile.h" using std::string; ReqCompile::ReqCompile(const string& name) :nm(name) { } const std::string& ReqCompile::name() const { return nm; } const char* ReqCompile::snippet_prefix = "rust_import_";
// -*- 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. // //----------------------------------------------------------------------------- // ump_test3 //----------------------------------------------------------------------------- #include "Pooma/Pooma.h" #include "Pooma/UMPArrays.h" #include "Utilities/Tester.h" int main(int argc, char *argv[]) { Pooma::initialize(argc,argv); Pooma::Tester tester(argc,argv); // Create the total domain. const int N = 40; Interval<1> D(1, N); Interval<2> domain(D, D); Interval<1> I(2, N-1), J(2, N-1), X(N/2 - 4, N/2 + 4); // Create the block sizes. Loc<2> blocks(2,2); // Create the partitioners. UniformGridPartition<2> partition(blocks); // Create the layout. UniformGridLayout<2> layout(domain, partition, ReplicatedTag()); // Make some UMP arrays and fill them. Array<2, double, MultiPatch<UniformTag,Brick> > a(layout), b(layout); a = 0; b = 0; b(N/2, N/2) = 1000; tester.out() << a(X,X) << std::endl; tester.out() << b(X,X) << std::endl; a(I,J) = (1.0 / 9.0) * (b(I+1,J+1) + b(I+1,J ) + b(I+1,J-1) + b(I ,J+1) + b(I ,J ) + b(I ,J-1) + b(I-1,J+1) + b(I-1,J ) + b(I-1,J-1)); tester.out() << a(X,X) << std::endl; int ret = tester.results("ump_test3"); Pooma::finalize(); return ret; } // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: ump_test3.cpp,v $ $Author: richard $ // $Revision: 1.13 $ $Date: 2004/11/01 18:16:38 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#include<iostream> using namespace std; int main() { int n,i; cin>>n; for(int no=2;no<=n;no++) { for(i=2;i<no;i++) { if(no%i==0) { break; } } if(i==no) { cout<<no<<" "; } } cout<<endl; return 0; }
#include<iostream> #include<string.h> #include<stdlib.h> using namespace std; struct node{ int end; node *child[26]; }*root; node *cnn() { node *ptr=new node; ptr->end=0; for(int i=0;i<26;i++) ptr->child[i]=NULL; return ptr; } void insert(string str,int l) { int i,j,k; node *nptr,*p; //l=strlen(str); if(root==NULL) { k=str[0]-'a'; root=cnn(); //nptr=cnn(); nptr=root->child[k]=cnn();//str[0]; i=1; while(i<l) { k=str[i]-'a'; //p=cnn(); p=nptr->child[k]=cnn();//str[i]; nptr=p; i++; } nptr->end=1; } else { i=0; nptr=root; while(i<l) { k=str[i]-'a'; //p=cnn(); if(nptr->child[k]==NULL) nptr=nptr->child[k]=cnn();//str[i]; else nptr=nptr->child[k]; i++; } nptr->end=1; } } int search(string s,int l) { node *q; if(root==NULL) return 0; else { int i=1; q=root->child[s[0]-'a']; if(q==NULL) return 0; while(i<l) { q=q->child[s[i]-'a']; if(q==NULL) return 0; i++; } if(q->end==1) return 1; } return 0; } int main() { root=NULL; char ch='y'; string str; int l,s; while(ch=='y') { cin>>str; l=str.size(); //cout<<l; insert(str,l); cout<<"\nEnnter [ y ] to insert more word :- "; cin>>ch; } cout<<"\nEnter word to search :- "; ch='y'; while(ch=='y') { cin>>str; l=str.size(); s=search(str,l); if(s==1) cout<<"Entered word is present in Dictionary "; else cout<<"\nEntered word is not present in Dictionary\nEnter [ y ] to search more words :-"; cin>>ch; } }
#ifndef _PARATABLE_H_ #define _PARATABLE_H_ #include "ParaMore.h" namespace GUI { class MainWindow; } namespace DataProperty { class ParameterBase; class ParameterTable; } namespace SelfDefObj { class SELFDEFINEOBJAPI ParaTable : public ParaMore { Q_OBJECT public: ParaTable(GUI::MainWindow* m, DataProperty::ParameterBase* data); ~ParaTable() = default; signals: void dataChanged(DataProperty::ParameterBase* p); protected slots: void on_moreButton_clicked() override; protected: void updateLineEdit() override; private: DataProperty::ParameterTable* _data{}; GUI::MainWindow* _mainWindow{}; }; } #endif
// // Created by 梁栋 on 2019-05-06. // #include <vector> #include <iostream> #include <string> #include <cstring> using namespace std; class Solution { public: bool wordBreakBase(string s, vector<string>& wordDict, int idx, bool& res){ if(s == wordDict[idx]){ res = true; return true; } if(strncmp(s.c_str(), wordDict[idx].c_str(), wordDict[idx].length()) == 0){ string tmp = s.substr(wordDict[idx].length(), s.length() - wordDict[idx].length()); for(int i=0;i<wordDict.size();i++){ wordBreakBase(tmp, wordDict, i, res); if(res) return true; } }else{ return false; } } bool wordBreak(string s, vector<string>& wordDict) { // 利用暴力的方法来解决 if(s == "" && wordDict.empty()) return true; if(wordDict.empty()) return false; if(s == "") return true; bool res = false; for(int i=0;i<wordDict.size();i++){ wordBreakBase(s, wordDict, i, res); if(res) return true; } return res; } bool wordBreakDP(string s, vector<string>& wordDict){ // 利用动态规划的思路来解决 int len = (int) s.length(); if(len == 0) return true; int size = (int) wordDict.size(); if(size == 0) return false; bool dp[len]; // 每一位表示的是,以s中对应位置结束的字符在wordDict中是否存在 // dp[i] = dp[i-word.length()] && word == s[j:i] memset(dp, false, sizeof(dp)); for(int i=0;i<len;i++){ for(int j=0;j<size;j++){ string word = wordDict[j]; int word_len = (int) word.length(); if(s[i] == word[word_len - 1] && ((i- word_len + 1) >= 0 && s.substr(i-word_len+1, word_len)==word) && (i-word_len < 0 || dp[i-word_len])){ dp[i] = true; break; }else{ dp[i] = false; } } } return dp[len-1]; } static void solution(){ Solution solution1; vector<string> wordDict = {"a", "b", "bb", "bbb", "bbbb"}; string s = "bb"; cout<<solution1.wordBreakDP(s, wordDict)<<endl; } };
#include <iostream> #include <vector> #include <string> using namespace::std; void RadixSort(vector<string> &A, vector<string> &B, int d); void CountingSort(vector<string> &A, vector<string> &B, int k, int d); int main() { vector<string> A{"329", "457", "657", "839", "436", "720", "355"}; vector<string> B(A.size()); RadixSort(A, B, 3); for (auto &i : A) { cout << i << endl; } return 0; } void CountingSort(vector<string> &A, vector<string> &B, int k, int d) { vector<int> C(k+1); for (auto j = 0; j != A.end() - A.begin(); ++j) { C[static_cast<int> (A[j][d] - '0')] += 1; } //C[i] now contains the number of elements equal to i. for (int i = 1; i != k + 1; ++i) { C[i] += C[i-1]; } //C[i] now contains the number of elements less than or equal to i. for (auto j = A.end() - A.begin() - 1; j != -1; --j) { B[C[static_cast<int> (A[j][d] - '0')]-1] = A[j]; C[static_cast<int> (A[j][d] - '0')] -= 1; } A.assign(B.begin(), B.end()); } void RadixSort(vector<string> &A, vector<string> &B, int d) { for (int i = d - 1; i != -1; --i) { CountingSort(A, B, 9, i); } }
#pragma once #include <chrono> #include <iostream> class FPS { public: void Update(){ ++_frame_counter; if (_last_time + std::chrono::seconds(1) < _timer.now()) { _last_time = _timer.now(); _fps = _frame_counter; _frame_counter = 0; std::cout << "FPS:" << _fps << std::endl; } }; private: std::chrono::steady_clock _timer = std::chrono::steady_clock(); std::chrono::time_point<std::chrono::steady_clock> _last_time; uint64_t _frame_counter = 0; uint64_t _fps = 0; };
#include<iostream> #include<cstdio> using namespace std; int a[1001]; int c[1001]; void dfs(int node) { if (c[node]) return; c[node] = true; dfs(a[node]); } int main() { int t; cin >> t; while (t--) { int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; c[i] = false; } int ans = 0; for (int k = 1; k <= n; k++) { if (c[k] == false) { dfs(k); ans += 1; } } cout << ans << endl; } return 0; }
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; #define mp make_pair #define PI pair<ll,ll> #define poly vector<ll> #define mem(a) memset((a),0,sizeof(a)) #define For(i,l,r) for(int i=(int)(l);i<=(int)(r);i++) #define Rep(i,r,l) for(int i=(int)(r);i>=(int)(l);i--) #define pb push_back #define fi first #define se second #define SZ(x) ((int)(x.size())) #define re resize inline char gc(){ static char buf[100000],*p1=buf,*p2=buf; return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++; } #define gc getchar inline ll read(){ ll x=0; char ch=gc();bool positive=1; for(; !isdigit(ch); ch = gc())if (ch == '-')positive = 0; for(; isdigit(ch); ch = gc())x = x * 10 + ch - '0'; return positive ? x : -x; } inline void write(ll a){ if(a<0){ a=-a; putchar('-'); } if(a>=10)write(a/10); putchar('0'+a%10); } inline void writeln(ll a){write(a); putchar('\n');} inline void wri(ll a){write(a); putchar(' ');} ll rnd(){ ull ans=0; For(i,0,4)ans=ans<<15^rand(); return ans%((ull)1<<63); } const int N=1<<20|2,mod=998244353,G=3,M=500000; ll ksm(ll a,int b){ int ans=1; for(;b;b>>=1){ if(b&1)ans=ans*a%mod; a=a*a%mod; } return ans; } struct ffter{ int rev[N],n,L; int wn[N],WN[N]; void zheng(poly &a){ //for(auto &i:a)i=(i+mod)%mod; } void dft(poly &a){ int n=a.size(); for(int i=0;i<n;i++)if(rev[i]<i)swap(a[rev[i]],a[i]); zheng(a); for(int d=1,len=L-1;d<n;d<<=1,len--){ for(int i=0;i<d;i++)WN[i]=wn[i<<len]; for(int i=0;i<n;i+=d<<1){ for(int j=0;j<d;j++){ int t=(ll)WN[j]*a[i+j+d]%mod; a[i+j+d]=a[i+j]-t<0?a[i+j]-t+mod:a[i+j]-t; a[i+j]=a[i+j]+t>=mod?a[i+j]+t-mod:a[i+j]+t; } } } } void idft(poly &a){ dft(a); reverse(a.begin()+1,a.end()); int x=ksm(a.size(),mod-2); for(auto &i:a)i=(ll)i*x%mod; } void init(int N){ n=1; L=0; while(n<N)n<<=1,L++; int w=ksm(G,(mod-1)/n); for(int i=0;i<n;i++){ wn[i]=i?(ll)wn[i-1]*w%mod:1; rev[i]=(rev[i>>1]>>1)|((i&1)<<(L-1)); } } }T; void FFT(poly &a,poly &b){ int sz=a.size()+b.size()-1; T.init(sz); a.resize(T.n); b.resize(T.n); T.dft(a); T.dft(b); for(int i=0;i<T.n;i++)a[i]=(ll)a[i]*b[i]%mod; T.idft(a); a.resize(sz); } void bg(poly &x){ int sz=1; while(sz<x.size())sz<<=1; x.resize(sz); } poly inv(poly a){//a.size()必须为2的幂次 bg(a); int n=a.size(); if(n==1){ poly b(1); b[0]=ksm(a[0],mod-2); return b; }assert(n%2==0); poly b=a; b.resize(n>>1); b=inv(b); a.resize(n<<1); b.resize(n<<1); T.init(n<<1); T.dft(b); T.dft(a); for(int i=0;i<(n<<1);i++)b[i]=((b[i]*2-(ll)a[i]*b[i]%mod*b[i])%mod+mod)%mod; T.idft(b); b.resize(n); return b; } ll fac[N],ni[N]; ll c(int a,int b){ return fac[a]*ni[b]%mod*ni[a-b]%mod; } ll get(int a,int b){ if(a%2!=b%2||a<b)return 0; return c(a,(a+b)/2); } poly solve(int n,int a,int t){ poly f(t+1),h(t+1),g(t+1); For(i,0,t){ h[i]=ksm(2,i); g[i]=get(i,0); if(i>n)g[i]=g[i]+get(i,n+1); } g=inv(g); g.resize(t+1); FFT(h,g); h.resize(t+1); For(i,0,t)f[i]=(get(i,a)+get(i,n+1-a))%mod; FFT(f,h); For(i,0,t)f[i]=(ksm(2,i)-f[i]+mod)%mod; return f; } int t,n,m,a,b; int main(){ cin>>t>>n>>m>>a>>b; For(i,fac[0]=1,M)fac[i]=fac[i-1]*i%mod; ni[M]=ksm(fac[M],mod-2); Rep(i,M,1)ni[i-1]=ni[i]*i%mod; poly f(t+1),g(t+1); f=solve(n,a,t),g=solve(m,b,t); ll ans=0; For(i,0,t)ans=(ans+c(t,i)*f[i]%mod*g[t-i])%mod; cout<<ans<<endl; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PLANESTIMULUSCELLFACTORY_HPP_ #define PLANESTIMULUSCELLFACTORY_HPP_ #include <boost/shared_ptr.hpp> #include "AbstractCardiacCellFactory.hpp" #include "LogFile.hpp" #include "SimpleStimulus.hpp" /** * PlaneStimulusCellFactory provides cells within 1e-5 of x=0 with a SimpleStimulus. */ template<class CELL, unsigned ELEMENT_DIM, unsigned SPACE_DIM = ELEMENT_DIM> class PlaneStimulusCellFactory : public AbstractCardiacCellFactory<ELEMENT_DIM,SPACE_DIM> { protected: /** The stimulus to apply at stimulated nodes */ boost::shared_ptr<SimpleStimulus> mpStimulus; public: /** * Constructor * @param stimulusMagnitude The magnitude of the simple stimulus to be applied (defaults to -600). * @param stimulusDuration The duration of the simple stimulus to be applied (defaults to 0.5ms). */ PlaneStimulusCellFactory(double stimulusMagnitude=-600, double stimulusDuration=0.5) : AbstractCardiacCellFactory<ELEMENT_DIM,SPACE_DIM>() { mpStimulus.reset(new SimpleStimulus(stimulusMagnitude, stimulusDuration)); LOG(1, "Defined a PlaneStimulusCellFactory<"<<SPACE_DIM<<"> with SimpleStimulus("<<stimulusMagnitude<<","<< stimulusDuration<< ")\n"); } /** * @param pNode Pointer to the node. * @return A cardiac cell which corresponds to this node. */ AbstractCardiacCellInterface* CreateCardiacCellForTissueNode(Node<SPACE_DIM>* pNode) { double x = pNode->GetPoint()[0]; ///\todo remove magic number? (#1884) if (x*x<=1e-10) { return new CELL(this->mpSolver, mpStimulus); } else { return new CELL(this->mpSolver, this->mpZeroStimulus); } } }; #endif /*PLANESTIMULUSCELLFACTORY_HPP_*/
#include <regex> #include <cstdio> #include <regex> #include <algorithm> #include <vector> #include <cstring> using namespace std; const regex EMAIL_FILTER("@gmail\\.com$"); struct Person { char name[21]; char email[51]; }; bool filterFunction(Person* p); bool compareFunction(Person* p1, Person* p2); int main() { unsigned char N = 0; scanf("%hhu\n", &N); vector<Person*> people(N); for (unsigned char i = 0; i < N; i ++) { people[i] = new Person(); scanf("%s %s", people[i]->name, people[i]->email); } vector<Person*> filteredPeople; for (Person* person : people) { if (filterFunction(person)) { filteredPeople.push_back(person); } } vector<Person*> sortedPeople(filteredPeople); sort(sortedPeople.begin(), sortedPeople.end(), compareFunction); for(const Person* person : sortedPeople) { printf("%s\n", person->name); } return 0; } bool filterFunction(Person* p) { bool match = regex_search(p->email, EMAIL_FILTER); return match; } bool compareFunction(Person* p1, Person* p2) { return (strcmp(p1->name, p2->name) <= 0); }
#include "stdafx.h" #include "Monster.h" Monster::Monster() { } Monster::~Monster() { } void Monster::removeHealth(int value) { health -= value; } void Monster::addHealth(int value) { health += value; } void Monster::getMonsterStats() { cout << "[[ " << monsterName << " - level: " << getLevel() << " || " << "Health: " << getHealth() << " HP || " << "Attack: " << getAttack() << " || " << "Strength: " << getStrength() << " || " << "Defence: " << getDefence() << " ]] \n"; } void Monster::showMonsterHealth() { cout << monsterName << "has" << getHealth() << "health" << "\n"; } void Monster::attackPlayer() { // return what the monster hits on player. }
/*************************************************************************** * Filename : OpenGLMesh.h * Name : Ori Lazar * Date : 30/10/2019 * Description : A declaration for a mesh object for OpenGL, currently * used to auto generate primitives. .---. .'_:___". |__ --==| [ ] :[| |__| I=[| / / ____| |-/.____.' /___\ /___\ ***************************************************************************/ #pragma once #include "Core/Renderer/Mesh.h" namespace Exalted { class OpenGLMesh : public Mesh { public: OpenGLMesh() = default; virtual ~OpenGLMesh() = default; virtual void CreateTriangle() override; virtual void CreateQuad() override; virtual void CreateCube() override; virtual void CreateTexturedQuad(float textureScale) override; virtual void CreateTexturedCube(float textureScale) override; inline virtual const Ref<VertexArray>& GetVertexArray() const override { return m_VertexArray; } }; }
#include <iostream> #include <unordered_map> #include <string> using namespace std; int Q; int key, val; struct node { int val,idx; }; unordered_map<int, node> hTab(200000); int nodeCnt; int main() { freopen("input.txt", "r", stdin); cin >> Q; nodeCnt = 0; for (; Q; Q--) { cin >> key >> val; node tmp; auto it = hTab.find(key); if (it == hTab.end()) { tmp = { val, ++nodeCnt }; it=hTab.insert({ key, tmp }).first; } else { it->second.val = val; } cout << it->second.idx << " " << it->second.val << endl; } return 0; }
#include <iostream> #include <fstream> using namespace std; ifstream fin("ssm.in"); ofstream fout("ssm.out"); int main() { long long int n, i, mx_val, mx_index, s = 0; fin >> n; long long int arr[n + 1], prev_val; for (i = 0; i < n; i++) fin >> arr[i]; prev_val = arr[0]; mx_val = prev_val; mx_index = 0; for (i = 1; i < n; i++) { if (arr[i] + prev_val <= prev_val) prev_val = arr[i]; else prev_val = arr[i] + prev_val; if (prev_val > mx_val) { mx_val = prev_val; mx_index = i; } cout << prev_val << ' '; } /* i = mx_index; s=arr[mx_index]; while(s != mx_val && i>=1) { s += arr[i-1]; i--; } */ }
#include "DeviceVk.hpp" #include "Logger.hpp" #include "Utility.hpp" #include "CommandBufferVk.hpp" #include "SwapchainVk.hpp" #include <sstream> #include <vector> #include <cstring> namespace engine { Bool DeviceVk::Initialize() { if (!CreateInstance()) { return false; } if (!LoadFunctionPointers()) { return false; } if (!SetupDebugCallback()) { return false; } if (!CreateDevice()) { return false; } return true; } Bool DeviceVk::CreateInstance() { std::vector<const char*> requiredInstanceExtension = GetRequiredInstanceExtension(); if (!CheckInstanceExtensionsSupport(requiredInstanceExtension)) { return false; } std::vector<const char*> requiredInstanceLayers = GetRequiredInstanceLayers(); if (!CheckInstanceLayersSupport(requiredInstanceLayers)) { return false; } VkApplicationInfo applicationInfo; applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; applicationInfo.pNext = nullptr; applicationInfo.pApplicationName = "VkSimpleApp"; applicationInfo.applicationVersion = 0; applicationInfo.pEngineName = "SimpleEngine"; applicationInfo.engineVersion = 0; applicationInfo.apiVersion = VK_API_VERSION_1_0; VkInstanceCreateInfo instanceCreateInfo; instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceCreateInfo.pNext = nullptr; instanceCreateInfo.flags = 0; instanceCreateInfo.pApplicationInfo = &applicationInfo; instanceCreateInfo.enabledLayerCount = requiredInstanceLayers.size(); instanceCreateInfo.ppEnabledLayerNames = requiredInstanceLayers.data(); instanceCreateInfo.enabledExtensionCount = requiredInstanceExtension.size(); instanceCreateInfo.ppEnabledExtensionNames = requiredInstanceExtension.data(); VkResult result = vkCreateInstance(&instanceCreateInfo, NULL, &m_instance); if (result == VK_ERROR_INCOMPATIBLE_DRIVER) { LOGE("Vk instance creation failure. Incopatible driver: %d", result); return false; } else if (result != VK_SUCCESS) { LOGE("Vk instance creation failure: %d", result); return false; } return true; } Bool DeviceVk::CreateDevice() { Uint32 adapterCount; VkResult result = vkEnumeratePhysicalDevices(m_instance, &adapterCount, NULL); if (result != VK_SUCCESS) { LOGE("Vk physical devices enumeration failure: %d", result); return false; } std::vector<VkPhysicalDevice> adapters(adapterCount); result = vkEnumeratePhysicalDevices(m_instance, &adapterCount, adapters.data()); if (result != VK_SUCCESS) { LOGE("Vk adapters enumeration failure: %d", result); return false; } LOGI("Enumerated adapters:"); Uint32 selectedAdapterIndex = adapterCount; std::vector<const char*> requiredDeviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; for (Uint32 i = 0; i < adapters.size(); ++i) { VkPhysicalDeviceProperties adapterProperties; vkGetPhysicalDeviceProperties(adapters[i], &adapterProperties); LOGI("\n%s", AdapterPropertiesToString(adapterProperties).c_str()); if (adapterProperties.deviceType == VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU || adapterProperties.deviceType == VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) { if (!CheckDeviceExtensionsSupport(adapters[i],requiredDeviceExtensions)) { continue; } LOGI("Adapter selected: \n%s", AdapterPropertiesToString(adapterProperties).c_str()); selectedAdapterIndex = i; m_adapter = adapters[selectedAdapterIndex]; break; } } if (selectedAdapterIndex >= adapterCount) { LOGE("Adapter selection failure"); return false; } Uint32 queuePropertiesCount; vkGetPhysicalDeviceQueueFamilyProperties(m_adapter, &queuePropertiesCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilyProperties(queuePropertiesCount); vkGetPhysicalDeviceQueueFamilyProperties(m_adapter, &queuePropertiesCount, queueFamilyProperties.data()); LOGI("Listing queue families:"); Uint32 queueFamilyIndex = queuePropertiesCount; for (Uint32 i = 0; i < queueFamilyProperties.size(); ++i) { LOGI("Queue Family %d\n%s", i, QueueFamilyToString(queueFamilyProperties[i]).c_str()); if (queueFamilyProperties[i].queueCount > 0 && queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { queueFamilyIndex = i; } } if (queueFamilyIndex >= queuePropertiesCount) { LOGE("Adapter queues don't fulfil minimal requirements"); return false; } m_queueFamilyIndex = queueFamilyIndex; LOGI("Selected command queue family index %d", m_queueFamilyIndex); Float queuePriorities = 1.0f; VkDeviceQueueCreateInfo queueCreateInfo; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.pNext = nullptr; queueCreateInfo.flags = 0; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriorities; VkDeviceCreateInfo deviceCreateInfo; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.pNext = nullptr; deviceCreateInfo.flags = 0; deviceCreateInfo.queueCreateInfoCount = 1; deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo; deviceCreateInfo.enabledLayerCount = 0; deviceCreateInfo.ppEnabledLayerNames = nullptr; deviceCreateInfo.enabledExtensionCount = requiredDeviceExtensions.size(); deviceCreateInfo.ppEnabledExtensionNames = requiredDeviceExtensions.data(); deviceCreateInfo.pEnabledFeatures = nullptr; result = vkCreateDevice(m_adapter, &deviceCreateInfo, NULL, &m_device); if (result != VK_SUCCESS) { LOGE("Device creation failure: %d", result); return false; } m_commandQueue = GetQueue(m_queueFamilyIndex); return true; } ObjectRef<CommandDispatcher> DeviceVk::CreateCommandDispatcher() { ASSERT(!m_adapter); ObjectRef<CommandDispatcher> commandDispatcher = MakeObjectRef<CommandDispatcher>(this); return commandDispatcher; } void DeviceVk::Finalize() { vkDestroyDevice(m_device, nullptr); vkDestroyInstance(m_instance, nullptr); } #if defined(PLATFORM_WINDOWS) Result<SurfaceH> DeviceVk::CreateSurface(IWindowSurface32* windowSurface) { VkSurfaceKHR surface; VkWin32SurfaceCreateInfoKHR surfaceCreateInfo; surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; surfaceCreateInfo.pNext = nullptr; surfaceCreateInfo.flags = 0; surfaceCreateInfo.hinstance = windowSurface->GetHInstance(); surfaceCreateInfo.hwnd = windowSurface->GetHWindow(); VkResult result = vkCreateWin32SurfaceKHR(m_instance, &surfaceCreateInfo, nullptr, &surface); if (result != VK_SUCCESS) { LOGE("Surface creation failure: %d", result); return Status::Error; } return Result<SurfaceH>(Status::Success, SurfaceH(this, surface)); } #elif defined(PLATFORM_LINUX) SurfaceG DeviceVk::CreateSurface(IWindowSurfaceX* windowSurface) { VkSurfaceKHR surface; VkXlibSurfaceCreateInfoKHR surfaceCreateInfo; surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; surfaceCreateInfo.pNext = nullptr; surfaceCreateInfo.flags = 0; surfaceCreateInfo.window = windowSurface->GetWindow(); surfaceCreateInfo.dpy = windowSurface->GetDisplay(); VkResult result = vkCreateXlibSurfaceKHR(m_instance, &surfaceCreateInfo, nullptr, &surface); if (result != VK_SUCCESS) { LOGE("Surface creation failure: %d", result); return SurfaceG(); } return SurfaceG(this, surface); } #endif ObjectRef<SwapchainVk> DeviceVk::CreateSwapchain(SwapchainCreateInfo& createInfo) { VkSwapchainCreateInfoKHR swapchainCreateInfo; swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swapchainCreateInfo.pNext = nullptr; swapchainCreateInfo.flags = 0; swapchainCreateInfo.surface = createInfo.surface; swapchainCreateInfo.minImageCount = createInfo.imageCount; swapchainCreateInfo.imageFormat = createInfo.surfaceFormat; swapchainCreateInfo.imageColorSpace = createInfo.colorSpace; swapchainCreateInfo.imageExtent = VkExtent2D{createInfo.imageWidth, createInfo.imageHeight}; swapchainCreateInfo.imageArrayLayers = 1; swapchainCreateInfo.imageUsage = createInfo.usage; swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swapchainCreateInfo.queueFamilyIndexCount = 0; swapchainCreateInfo.pQueueFamilyIndices = 0; swapchainCreateInfo.preTransform = createInfo.transformation; swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swapchainCreateInfo.presentMode = createInfo.presentationMode; swapchainCreateInfo.clipped = VK_TRUE; swapchainCreateInfo.oldSwapchain = 0; VkSwapchainKHR swapchainHandle; VkResult result = vkCreateSwapchainKHR(m_device, &swapchainCreateInfo, nullptr, &swapchainHandle); if(result != VK_SUCCESS) { LOGE("Swapchain creation failed: %d", result); return MakeObjectRef<SwapchainVk>(); } ObjectRef<SwapchainVk> swapchain = MakeObjectRef<SwapchainVk>( this, swapchainHandle, createInfo.imageWidth, createInfo.imageHeight, createInfo.imageCount); Uint32 imageCount; result = vkGetSwapchainImagesKHR(m_device, swapchainHandle, &imageCount, nullptr); if (result != VK_SUCCESS) { LOGE("vkGetSwapchainImagesKHR failure: %d", result); return MakeObjectRef<SwapchainVk>(); } ImageFormat format = NativeFormat2ImageFormat(createInfo.surfaceFormat); ImageDesc imageDesc(createInfo.imageWidth, createInfo.imageHeight, format); std::vector<VkImage> images(imageCount); result = vkGetSwapchainImagesKHR(m_device, swapchainHandle, &imageCount, images.data()); if (result != VK_SUCCESS) { LOGE("vkGetSwapchainImagesKHR failure: %d", result); return MakeObjectRef<SwapchainVk>(); } auto& swapchainImages = swapchain->m_images; for (int i = 0; i < images.size(); i++) { SemaphoreG& semaphore = swapchain->m_semaphoreRing.GetNext(); semaphore = CreateSemaphore(); if (!semaphore) { return MakeObjectRef<SwapchainVk>(); } VkImageViewCreateInfo info; info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; info.pNext = nullptr; info.flags = 0; info.image = images[i]; info.viewType = VK_IMAGE_VIEW_TYPE_2D; info.format = createInfo.surfaceFormat; info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; info.subresourceRange.baseMipLevel = 0; info.subresourceRange.levelCount = 1; info.subresourceRange.baseArrayLayer = 0; info.subresourceRange.layerCount = 1; VkImageView view; result = vkCreateImageView(m_device, &info, nullptr, &view); if (result != VK_SUCCESS) { LOGE("vkCreateImageView failure: %d", result); return MakeObjectRef<SwapchainVk>(); } swapchainImages.Emplace(i, this, images[i], view, imageDesc); } return swapchain; } SemaphoreG DeviceVk::CreateSemaphore() { VkSemaphoreCreateInfo semaphoreCreateInfo; semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; semaphoreCreateInfo.pNext = nullptr; semaphoreCreateInfo.flags = 0; VkSemaphore semaphore; VkResult result = vkCreateSemaphore(m_device, &semaphoreCreateInfo, nullptr, &semaphore); if (result != VK_SUCCESS) { LOGE("Semaphore creation failure: %d", result); return SemaphoreG(); } return SemaphoreG(this, semaphore); } FenceG DeviceVk::CreateFence() { VkFenceCreateInfo info; info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; info.pNext = nullptr;; info.flags = 0; VkFence fence; VkResult result = vkCreateFence(m_device, &info, nullptr, &fence); if (result != VK_SUCCESS) { LOGE("Fence creation failure: %d", result); return FenceG(); } return FenceG(this, fence); } CommandPoolG DeviceVk::CreateCommandPool() { VkCommandPoolCreateInfo commandPoolCreateInfo; commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; commandPoolCreateInfo.pNext = nullptr; commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; commandPoolCreateInfo.queueFamilyIndex = m_queueFamilyIndex; VkCommandPool commandPool; VkResult result = vkCreateCommandPool(m_device, &commandPoolCreateInfo, nullptr, &commandPool); if (result != VK_SUCCESS) { LOGE("Command Pool creation failed: %d", result); return CommandPoolG(nullptr, VK_NULL_HANDLE); } return CommandPoolG(this, commandPool); } VkQueue DeviceVk::GetQueue(Uint32 queueFamilyIndex) { VkQueue queue; vkGetDeviceQueue(m_device, queueFamilyIndex, 0, &queue); return queue; } std::vector<ObjectRef<CommandBufferVk>> DeviceVk::AllocateCommandBuffers(Uint32 count, VkCommandPool commandPool) { std::vector<VkCommandBuffer> commandBuffers(count); VkCommandBufferAllocateInfo info; info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; info.pNext = nullptr; info.commandPool = commandPool; info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; info.commandBufferCount = count; VkResult result = vkAllocateCommandBuffers(m_device, &info, commandBuffers.data()); if (result != VK_SUCCESS) { LOGE("Command Buffers allocation failed: %d", result); return std::vector<ObjectRef<CommandBufferVk>>(); } std::vector<ObjectRef<CommandBufferVk>> out(count); for (Uint32 i = 0; i < count; i++) { SemaphoreG semaphore = CreateSemaphore(); if (!semaphore) { return std::vector<ObjectRef<CommandBufferVk>>(); } FenceG fence = CreateFence(); if (!fence) { return std::vector<ObjectRef<CommandBufferVk>>(); } out[i] = MakeObjectRef<CommandBufferVk>(this, commandBuffers[i], semaphore, fence); } return out; } ShaderG DeviceVk::CreateShader(const std::vector<Uint8>& data) { VkShaderModuleCreateInfo info = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0, // VkShaderModuleCreateFlags flags; data.size(), // size_t codeSize; reinterpret_cast<const Uint32*>(data.data()) // const uint32_t* pCode; }; VkShaderModule shader; VkResult result = vkCreateShaderModule(m_device, &info, nullptr, &shader); if (result != VK_SUCCESS) { LOGE("Shader creation failed: %d", result); return ShaderG(); } return ShaderG(this, shader); } RenderPassG DeviceVk::CreateRenderPass(const FramebufferDesc& framebuffer) { std::vector<VkAttachmentDescription> attachmentDesc; std::vector<VkAttachmentReference> attachmentRef; const auto& renderTargets = framebuffer.GetRenderTargets(); for (Uint32 i = 0; i < renderTargets.size(); ++i) { const auto& image = renderTargets[i]; VkFormat format = ImageFormat2NativeFormat(image->GetImageDesc().format); attachmentDesc.push_back( { 0, // VkAttachmentDescriptionFlags flags; format, // VkFormat format; VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // VkImageLayout initialLayout; VK_IMAGE_LAYOUT_PRESENT_SRC_KHR // VkImageLayout finalLayout; }); attachmentRef.push_back( { i, // uint32_t attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }); } VkSubpassDescription spDesc = { 0, // VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; 0, // uint32_t inputAttachmentCount; nullptr, // const VkAttachmentReference* pInputAttachments; (Uint32)attachmentDesc.size(), // uint32_t colorAttachmentCount; attachmentRef.data(), // const VkAttachmentReference* pColorAttachments; nullptr, // const VkAttachmentReference* pResolveAttachments; nullptr, // const VkAttachmentReference* pDepthStencilAttachment; 0, // uint32_t preserveAttachmentCount; nullptr // const uint32_t* pPreserveAttachments; }; VkRenderPass renderPass; VkRenderPassCreateInfo info = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, //VkStructureType sType; nullptr, //const void* pNext; 0, //VkRenderPassCreateFlags flags; (Uint32)attachmentDesc.size(), //uint32_t attachmentCount; attachmentDesc.data(), //const VkAttachmentDescription* pAttachments; 1, //uint32_t subpassCount; &spDesc, //const VkSubpassDescription* pSubpasses; 0, //uint32_t dependencyCount; nullptr //const VkSubpassDependency* pDependencies; }; VkResult result = vkCreateRenderPass(m_device, &info, nullptr, &renderPass); if (result != VK_SUCCESS) { LOGE("CreateRenderPass failure: %d", result); return {}; } return RenderPassG(this, renderPass); } ObjectRef<FramebufferVk> DeviceVk::CreateFramebuffer(RenderPassG& renderPass, const FramebufferDesc& desc) { ASSERT(desc.GetRenderTargets().size()); ASSERT(renderPass != VK_NULL_HANDLE); auto& renderTargets = desc.GetRenderTargets(); std::vector<VkImageView> views(renderTargets.size()); for (int i = 0; i < renderTargets.size(); ++i) { views[i] = renderTargets[i]->GetView(); } VkFramebufferCreateInfo info = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0, // VkFramebufferCreateFlags flags; renderPass.Get(), // VkRenderPass renderPass; static_cast<uint32_t>(views.size()), // uint32_t attachmentCount; views.data(), // const VkImageView* pAttachments; desc.GetWidth(), // uint32_t width; desc.GetHeight(), // uint32_t height; 1, // uint32_t layers; }; VkFramebuffer handle; VkResult result = vkCreateFramebuffer(m_device, &info, nullptr, &handle); if (result != VK_SUCCESS) { LOGE("Framebuffer creation failure: %d", result); return nullptr; } ObjectRef<FramebufferVk> framebuffer(new FramebufferVk(this, handle)); return framebuffer; } std::vector<VkPresentModeKHR> DeviceVk::GetSupporedPresentModes(VkSurfaceKHR surface) const { Uint32 presentModeCount = 0; VkResult result = vkGetPhysicalDeviceSurfacePresentModesKHR(m_adapter, surface, &presentModeCount, nullptr); if (result != VK_SUCCESS) { LOGE("vkGetPhysucalDeviceSurfacePresentModesKHR failed: %d", result); return std::vector<VkPresentModeKHR>(); } std::vector<VkPresentModeKHR> supportedPresentModes(presentModeCount); result = vkGetPhysicalDeviceSurfacePresentModesKHR(m_adapter, surface, &presentModeCount, supportedPresentModes.data()); if (result != VK_SUCCESS) { LOGE("vkGetPhysucalDeviceSurfacePresentModesKHR failed: %d", result); return std::vector<VkPresentModeKHR>(); } return supportedPresentModes; } std::vector<VkSurfaceFormatKHR> DeviceVk::GetSupportedSurfaceFormats(VkSurfaceKHR surface) const { Uint32 formatCount; VkResult result = vkGetPhysicalDeviceSurfaceFormatsKHR(m_adapter, surface, &formatCount, nullptr); if(result != VK_SUCCESS) { LOGE("Adapter supported sufrace formats count query failed: %d", result); return std::vector<VkSurfaceFormatKHR>(0); } std::vector<VkSurfaceFormatKHR> supportedSurfaceFormats(formatCount); result = vkGetPhysicalDeviceSurfaceFormatsKHR(m_adapter, surface, &formatCount, supportedSurfaceFormats.data()); if(result != VK_SUCCESS) { LOGE("Adapter support surface foramts query failed: %d", result); return std::vector<VkSurfaceFormatKHR>(0); } return supportedSurfaceFormats; } Bool DeviceVk::CheckAdapterSurfaceSupport(VkSurfaceKHR surface) { Uint32 supported; VkResult result = vkGetPhysicalDeviceSurfaceSupportKHR(m_adapter, m_queueFamilyIndex, surface, &supported); if (result) { LOGE("Adapter surface and queue support failed: %d", result); return false; } else if (!supported) { LOGE("Given queue can't render on this surface"); return false; } return true; } Bool DeviceVk::GetSurfaceCapabilities(VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR& capabilities) const { VkSurfaceCapabilitiesKHR surfaceCapabilities; VkResult result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_adapter, surface, &capabilities); if (result != VK_SUCCESS) { LOGE("vkGetPhysicalDeviceSurfaceCapabilitiesKHR failed: %d", result); return false; } return true; } void DeviceVk::SubmitQueue(ObjectRef<CommandBufferVk>& commandBuffer) { vkResetFences(m_device, 1, &commandBuffer->m_fence.Get()); VkSubmitInfo info; info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; info.pNext = nullptr; info.waitSemaphoreCount = commandBuffer->m_dependency.size(); info.pWaitSemaphores = reinterpret_cast<VkSemaphore*>(commandBuffer->m_dependency.data()); info.pWaitDstStageMask = commandBuffer->m_dependencyStage.data(); info.commandBufferCount = 1; info.pCommandBuffers = &commandBuffer->m_commandBuffer; info.signalSemaphoreCount = 1; info.pSignalSemaphores = &commandBuffer->m_semaphore.Get(); VkResult result = vkQueueSubmit(m_commandQueue, 1, &info, commandBuffer->m_fence.Get()); ASSERT(result == VK_SUCCESS); commandBuffer->ChangeState(CommandBufferVk::State::Submitted); } Status DeviceVk::WaitForFence(FenceG& fence, const TimeUnits& timeout) { VkResult result = vkWaitForFences(m_device, 1, &fence.Get(), true, timeout.GetNanoseconds()); if (result == VK_SUCCESS) { return Status::Success; } else if (result == VK_TIMEOUT) { LOGW("Fence %lld wait timeout", fence.Get()); return Status::Timeout; } else { LOGE("Fence %lld wait error %d", fence.Get(), result); return Status::Error; } } std::string DeviceVk::AdapterPropertiesToString(const VkPhysicalDeviceProperties& adapterProperties) const { std::stringstream buf; buf << "Name: " << adapterProperties.deviceName << "\n" << "Vendor: " << adapterProperties.vendorID << "\n" << "Api version: " << adapterProperties.apiVersion << "\n" << "Device ID: " << adapterProperties.deviceID << "\n" << "Device Type: " << AdapterTypeToString(adapterProperties.deviceType); return buf.str(); } std::string DeviceVk::AdapterTypeToString(const VkPhysicalDeviceType& adpaterType) const { switch (adpaterType) { case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_CPU: return "CPU"; case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "DISCRETE_GPU"; case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "INTEGRETED_GPU"; case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "VIRTUAL_GPU"; case VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_OTHER: return "OTHER"; default: return "UNKNOWN"; } } std::string DeviceVk::QueueFamilyToString(const VkQueueFamilyProperties& queueFamily) const { std::stringstream buf; buf << "Queues count: " << queueFamily.queueCount << "\n" << "Queue flag: " << (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT ? "GRAPHICS_BIT " : "") << (queueFamily.queueFlags & VK_QUEUE_COMPUTE_BIT ? "COMPUTE_BIT " : "") << (queueFamily.queueFlags & VK_QUEUE_TRANSFER_BIT ? "TRANSFER_BIT " : "") << (queueFamily.queueFlags & VK_QUEUE_SPARSE_BINDING_BIT ? "SPARSE_BINDING_BIT" : "") << "\n" << "Queue timestamp valid bits: " << queueFamily.timestampValidBits << "\n" << "Queue min transfer granularity (w/h/d):" << queueFamily.minImageTransferGranularity.width << " " << queueFamily.minImageTransferGranularity.height << " " << queueFamily.minImageTransferGranularity.depth << " "; return buf.str(); } std::vector<const char*> DeviceVk::GetRequiredInstanceExtension() const { std::vector<const char*> instanceRequiredExtensions = { VK_KHR_SURFACE_EXTENSION_NAME, VK_EXT_DEBUG_REPORT_EXTENSION_NAME, #if defined(PLATFORM_WINDOWS) VK_KHR_WIN32_SURFACE_EXTENSION_NAME, #elif defined(PLATFORM_LINUX) VK_KHR_XLIB_SURFACE_EXTENSION_NAME, #endif }; return instanceRequiredExtensions; } std::vector<const char*> DeviceVk::GetRequiredInstanceLayers() const { std::vector<const char*> instanceRequiredLayers = { "VK_LAYER_LUNARG_standard_validation" }; return instanceRequiredLayers; } Bool DeviceVk::CheckExtensionSupport(std::vector<const char*>& requiredExtensions, std::vector<VkExtensionProperties>& availableExtensions) { std::vector<Bool> extensionCheckResult(requiredExtensions.size(), false); Bool extensionSupportError = false; for (Uint32 i = 0; i < requiredExtensions.size(); ++i) { Bool supported = false; const char* required = requiredExtensions[i]; for (auto& available : availableExtensions) { if (std::strcmp(required, available.extensionName) == 0) { supported = true; break; } } if (supported == false) { LOGE("Required extension not supported: %s", requiredExtensions[i]); extensionSupportError = true; } } return !extensionSupportError; } Bool DeviceVk::CheckInstanceExtensionsSupport(std::vector<const char*>& requiredExtensions) { Uint32 extensionCount; VkResult result = vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr); if (result != VK_SUCCESS) { LOGE("Extension enumeration failure: %d", result); return false; } std::vector<VkExtensionProperties> availableExtensions(extensionCount); result = vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, availableExtensions.data()); if (result != VK_SUCCESS) { LOGE("Extension enumeration failure: %d", result); return false; } return CheckExtensionSupport(requiredExtensions, availableExtensions); } Bool DeviceVk::CheckDeviceExtensionsSupport(VkPhysicalDevice& adapter, std::vector<const char*>& requiredExtensions) { Uint32 extensionCount; VkResult result = vkEnumerateDeviceExtensionProperties(adapter, nullptr, &extensionCount, nullptr); if (result != VK_SUCCESS) { LOGE("Device extension enumeration failure: %d", result); return false; } std::vector<VkExtensionProperties> availableExtensions(extensionCount); result = vkEnumerateDeviceExtensionProperties(adapter, nullptr, &extensionCount, availableExtensions.data()); if (result != VK_SUCCESS) { LOGE("Device extension enumeration failure: %d", result); return false; } return CheckExtensionSupport(requiredExtensions, availableExtensions); } Bool DeviceVk::CheckInstanceLayersSupport(std::vector<const char*>& requiredLayers) const { Uint32 layerCount; VkResult result = vkEnumerateInstanceLayerProperties(&layerCount, nullptr); if (result != VK_SUCCESS) { LOGE("Layers enumeration failure: %d", result); return false; } std::vector<VkLayerProperties> availableLayers(layerCount); result = vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); if (result != VK_SUCCESS) { LOGE("Layers enumeration failure: %d", result); return false; } Bool found = false; for (auto& required: requiredLayers) { found = false; for (auto& available: availableLayers) { if (std::strcmp(required, available.layerName) == 0) { LOGI("Found required layer: %s", required); found = true; } } if(!found) { LOGE("Required layer not found: %d", required); return false; } } return true; } Bool DeviceVk::SetupDebugCallback() { if (!m_CreateDebugReportCallback) { return false; } VkDebugReportCallbackCreateInfoEXT createInfo; createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; createInfo.pfnCallback = DeviceVk::DebugCallback; VkResult result = m_CreateDebugReportCallback(m_instance, &createInfo, nullptr, &m_debugCallback); if (result != VK_SUCCESS) { LOGE("CreateDebugReportCallback failure: %", result); return false; } return true; } void DeviceVk::FinalizeDebugCallback() { if (m_DestroyDebugReportCallback && m_debugCallback) { m_DestroyDebugReportCallback(m_instance, m_debugCallback, nullptr); m_debugCallback = 0; } } Bool DeviceVk::LoadFunctionPointers() { m_CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(m_instance,"vkCreateDebugReportCallbackEXT"); if (!m_CreateDebugReportCallback) { return false; } m_DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(m_instance, "vkDestroyDebugReportCallbackEXT"); if (!m_DestroyDebugReportCallback) { return false; } return true; } Status DeviceVk::AcquireSwapchainImage(SwapchainVk& swapchain) { Uint32 imageIndex; SemaphoreG& semaphore = swapchain.m_semaphoreRing.GetNext(); VkResult result = vkAcquireNextImageKHR(m_device, swapchain.GetSwapchain(), INT64_MAX, semaphore.Get(), VK_NULL_HANDLE, &imageIndex); switch(result) { case VK_SUCCESS: swapchain.m_images[imageIndex].AddDependency(SemaphoreH(semaphore)); swapchain.AddImage(imageIndex); return Status::Success; case VK_TIMEOUT: return Status::Timeout; case VK_SUBOPTIMAL_KHR: LOGW("Swapchain should be recreated."); return Status::OutDated; case VK_ERROR_OUT_OF_DATE_KHR: LOGW("Swapchain must be recreated."); return Status::OutDated; default: LOGE("AcquireNextImageKHR failed: %d", result); ASSERT(false); return Status::Error; } } VKAPI_ATTR VkBool32 VKAPI_CALL DeviceVk::DebugCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj, size_t location, int32_t code, const char* layerPrefix, const char* msg, void* userData) { LOGE("Layer %s: %s", layerPrefix, msg); return false; } } // namespace engine
/*************************************************************************** Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. 2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD FileName: RTSPSessionInterface.cpp Description: Presents an API for session-wide resources for modules to use. Implements the RTSP Session dictionary for QTSS API. Comment: copy from Darwin Streaming Server 5.5.5 Author: taoyunxing@dadimedia.com Version: v1.0.0.1 CreateDate: 2010-08-16 LastUpdate: 2010-08-16 ****************************************************************************/ #include "atomic.h" #include "RTSPProtocol.h" #include "RTSPSessionInterface.h" #include "QTSServerInterface.h" #include "OSMemory.h" #include <errno.h> #if DEBUG #define RTSP_SESSION_INTERFACE_DEBUGGING 1 #else #define RTSP_SESSION_INTERFACE_DEBUGGING 0 #endif unsigned int RTSPSessionInterface::sSessionIDCounter = kFirstRTSPSessionID;/* 初始化为1 */ Bool16 RTSPSessionInterface::sDoBase64Decoding = true;/* 默认基于base64解码 */ UInt32 RTSPSessionInterface::sOptionsRequestBody[kMaxRandomDataSize / sizeof(UInt32)];//64K字节 /* RTSPSession Dictionary attributes,参见QTSS_RTSPSessionAttributes in QQTSS.h */ QTSSAttrInfoDict::AttrInfo RTSPSessionInterface::sAttributes[] = { /*fields: fAttrName, fFuncPtr, fAttrDataType, fAttrPermission */ /* 0 */ { "qtssRTSPSesID", NULL, qtssAttrDataTypeUInt32, qtssAttrModeRead | qtssAttrModePreempSafe }, /* 1 */ { "qtssRTSPSesLocalAddr", SetupParams, qtssAttrDataTypeUInt32, qtssAttrModeRead | qtssAttrModePreempSafe | qtssAttrModeCacheable }, /* 2 */ { "qtssRTSPSesLocalAddrStr", SetupParams, qtssAttrDataTypeCharArray, qtssAttrModeRead | qtssAttrModePreempSafe | qtssAttrModeCacheable }, /* 3 */ { "qtssRTSPSesLocalDNS", SetupParams, qtssAttrDataTypeCharArray, qtssAttrModeRead | qtssAttrModePreempSafe | qtssAttrModeCacheable }, /* 4 */ { "qtssRTSPSesRemoteAddr", SetupParams, qtssAttrDataTypeUInt32, qtssAttrModeRead | qtssAttrModePreempSafe | qtssAttrModeCacheable }, /* 5 */ { "qtssRTSPSesRemoteAddrStr", SetupParams, qtssAttrDataTypeCharArray, qtssAttrModeRead | qtssAttrModePreempSafe | qtssAttrModeCacheable }, /* 6 */ { "qtssRTSPSesEventCntxt", NULL, qtssAttrDataTypeUInt32, qtssAttrModeRead | qtssAttrModePreempSafe }, /* 7 */ { "qtssRTSPSesType", NULL, qtssAttrDataTypeUInt32, qtssAttrModeRead | qtssAttrModePreempSafe }, /* 8 */ { "qtssRTSPSesStreamRef", NULL, qtssAttrDataTypeQTSS_StreamRef, qtssAttrModeRead | qtssAttrModePreempSafe }, /* 9 */ { "qtssRTSPSesLastUserName", NULL, qtssAttrDataTypeCharArray, qtssAttrModeRead | qtssAttrModePreempSafe }, /* 10 */{ "qtssRTSPSesLastUserPassword",NULL, qtssAttrDataTypeCharArray, qtssAttrModeRead | qtssAttrModePreempSafe }, /* 11 */{ "qtssRTSPSesLastURLRealm", NULL, qtssAttrDataTypeCharArray, qtssAttrModeRead | qtssAttrModePreempSafe }, /* 12 */{ "qtssRTSPSesLocalPort", SetupParams, qtssAttrDataTypeUInt16, qtssAttrModeRead | qtssAttrModePreempSafe | qtssAttrModeCacheable }, /* 13 */{ "qtssRTSPSesRemotePort", SetupParams, qtssAttrDataTypeUInt16, qtssAttrModeRead | qtssAttrModePreempSafe | qtssAttrModeCacheable } }; /* 设置14个静态属性值QTSS_RTSPSessionAttributes,利用随机数设置RTSPSessionInterface::sOptionsRequestBody[]的所有分量,并使第一个字节为0值 */ void RTSPSessionInterface::Initialize() { /* 针对14个QTSS_RTSPSessionAttributes,利用上面定义的相关静态属性,先找到RTSPSession对应的Dictionary,循环设置相应的属性,参见QTSSDictionary.h */ for (UInt32 x = 0; x < qtssRTSPSesNumParams; x++) QTSSDictionaryMap::GetMap(QTSSDictionaryMap::kRTSPSessionDictIndex)-> SetAttribute(x, sAttributes[x].fAttrName, sAttributes[x].fFuncPtr, sAttributes[x].fAttrDataType, sAttributes[x].fAttrPermission); // DJM PROTOTYPE /* 利用随机数设置RTSPSessionInterface::sOptionsRequestBody[]的所有分量,并使第一个字节为0值 */ ::srand((unsigned int) OS::Microseconds()); //对64K字节,每个字节设置一个随机数 for (unsigned int i = 0; i < kMaxRandomDataSize / sizeof(UInt32); i++) RTSPSessionInterface::sOptionsRequestBody[i] = ::rand(); ((char *)RTSPSessionInterface::sOptionsRequestBody)[0] = 0; //always set first byte so it doesn't hit any client parser bugs for \r or \n. } RTSPSessionInterface::RTSPSessionInterface() : QTSSDictionary(QTSSDictionaryMap::GetMap(QTSSDictionaryMap::kRTSPSessionDictIndex)),/* 初始化RTSPSession字典 */ Task(), fTimeoutTask(NULL, QTSServerInterface::GetServer()->GetPrefs()->GetRealRTSPTimeoutInSecs() * 1000),//初始化超时对象,默认60秒超时 fInputStream(&fSocket),//初始化RTSPRequestStream对象 fOutputStream(&fSocket, &fTimeoutTask),//初始化RTSPResponseStream对象 fSessionMutex(), fTCPCoalesceBuffer(NULL), fNumInCoalesceBuffer(0), fSocket(NULL, Socket::kNonBlockingSocketType),//初始化非阻塞类型Socket对象 fOutputSocketP(&fSocket),//注意它们都是同一个TCPSocket fInputSocketP(&fSocket), fSessionType(qtssRTSPSession),//默认通常的RTSPSession fLiveSession(true),//默认alive RTSP session fObjectHolders(0), fCurChannelNum(0), fChNumToSessIDMap(NULL), fRequestBodyLen(-1), fSentOptionsRequest(false),//默认不发送OPTIONS fOptionsRequestSendTime(-1), fRoundTripTime(-1), fRoundTripTimeCalculation(true)//默认计算RTT,在RTSPSessionInterface::SendOptionsRequest()中改为false { /* 设置本类对象的属性 */ fTimeoutTask.SetTask(this);//设置本类对象为超时任务对象 fSocket.SetTask(this); //设置本类对象的Socket fStreamRef = this; //设置本类对象的stream /* 在计数器基础上加1,即值为2 */ fSessionID = (UInt32)atomic_add(&sSessionIDCounter, 1); /* 手动设置QTSS_RTSPSessionAttributes的相关属性值 */ this->SetVal(qtssRTSPSesID, &fSessionID, sizeof(fSessionID)); this->SetVal(qtssRTSPSesEventCntxt, &fOutputSocketP, sizeof(fOutputSocketP)); this->SetVal(qtssRTSPSesType, &fSessionType, sizeof(fSessionType)); this->SetVal(qtssRTSPSesStreamRef, &fStreamRef, sizeof(fStreamRef)); this->SetEmptyVal(qtssRTSPSesLastUserName, &fUserNameBuf[0], kMaxUserNameLen); this->SetEmptyVal(qtssRTSPSesLastUserPassword, &fUserPasswordBuf[0], kMaxUserPasswordLen); this->SetEmptyVal(qtssRTSPSesLastURLRealm, &fUserRealmBuf[0], kMaxUserRealmLen); //打印出RTSP信息吗? fInputStream.ShowRTSP(QTSServerInterface::GetServer()->GetPrefs()->GetRTSPDebugPrintfs()); fOutputStream.ShowRTSP(QTSServerInterface::GetServer()->GetPrefs()->GetRTSPDebugPrintfs()); } RTSPSessionInterface::~RTSPSessionInterface() { // If the input socket is != output socket, the input socket was created dynamically if (fInputSocketP != fOutputSocketP) delete fInputSocketP; /* 删除拼合缓存,注意它的分配在RTSPSessionInterface::GetTwoChannelNumbers() */ delete [] fTCPCoalesceBuffer; for (UInt8 x = 0; x < (fCurChannelNum >> 1); x++) delete [] fChNumToSessIDMap[x].Ptr; delete [] fChNumToSessIDMap; } /* 减少持有对象的计数,且假如对象持有计数为零,就删除该RTSPSession */ void RTSPSessionInterface::DecrementObjectHolderCount() { #if __Win32__ //maybe don't need this special case but for now on Win32 we do it the old way since the killEvent code hasn't been verified on Windows. this->Signal(Task::kReadEvent);//have the object wakeup in case it can go away. atomic_sub(&fObjectHolders, 1); #else /* 假如对象持有计数为零,就删除该RTSPSession */ if (0 == atomic_sub(&fObjectHolders, 1)) this->Signal(Task::kKillEvent); #endif } /* 默认使用不缓存方式(除非明确指定),利用RTSPResponseStream::WriteV()向外写出数据 */ QTSS_Error RTSPSessionInterface::Write(void* inBuffer, UInt32 inLength, UInt32* outLenWritten, UInt32 inFlags) { /* 默认设置sendType的值为不缓存方式 */ UInt32 sendType = RTSPResponseStream::kDontBuffer; /* 若明确指定缓存就使用缓存方式 */ if ((inFlags & qtssWriteFlagsBufferData) != 0) sendType = RTSPResponseStream::kAlwaysBuffer; iovec theVec[2]; /* 为何要放在第2个向量? */ theVec[1].iov_base = (char*)inBuffer; theVec[1].iov_len = inLength; return fOutputStream.WriteV(theVec, 2, inLength, outLenWritten, sendType); } /* 使用不缓存方式的RTSPResponseStream::WriteV() */ QTSS_Error RTSPSessionInterface::WriteV(iovec* inVec, UInt32 inNumVectors, UInt32 inTotalLength, UInt32* outLenWritten) { return fOutputStream.WriteV(inVec, inNumVectors, inTotalLength, outLenWritten, RTSPResponseStream::kDontBuffer); } /* 试问:fRequestBodyLen最初在哪里设置? */ /* 利用RTSPRequestStream::Read()来只读入长度为fRequestBodyLen(用它修改第二个参数)的数据,用实际读取的数据长度设置第三个入参 */ QTSS_Error RTSPSessionInterface::Read(void* ioBuffer, UInt32 inLength, UInt32* outLenRead) { // Don't let callers of this function accidently creep(意外越过) past the end of the // request body. If the request body size isn't known, fRequestBodyLen will be -1 if (fRequestBodyLen == 0) return QTSS_NoMoreData; //只读入fRequestBodyLen长度的RTSP request data if ((fRequestBodyLen > 0) && ((SInt32)inLength > fRequestBodyLen)) inLength = fRequestBodyLen; UInt32 theLenRead = 0; QTSS_Error theErr = fInputStream.Read(ioBuffer, inLength, &theLenRead); if (fRequestBodyLen >= 0) fRequestBodyLen -= theLenRead; if (outLenRead != NULL) *outLenRead = theLenRead; return theErr; } /* 根据读或写事件,来调用TCPSocket(它是EventContext的派生类)来读入或写出事件 */ QTSS_Error RTSPSessionInterface::RequestEvent(QTSS_EventType inEventMask) { if (inEventMask & QTSS_ReadableEvent) fInputSocketP->RequestEvent(EV_RE); if (inEventMask & QTSS_WriteableEvent) fOutputSocketP->RequestEvent(EV_WR); return QTSS_NoErr; } /* 新建fChNumToSessIDMap,复制进原来的fChNumToSessIDMap数据,并用入参配置新建fChNumToSessIDMap的最后一个分量,最后返回当前channel号 */ UInt8 RTSPSessionInterface::GetTwoChannelNumbers(StrPtrLen* inRTSPSessionID) { // Allocate a TCP coalesce buffer if still needed if (fTCPCoalesceBuffer != NULL) fTCPCoalesceBuffer = new char[kTCPCoalesceBufferSize];//1450 // Allocate 2 channel numbers /* 获取当前channel号 */ UInt8 theChannelNum = fCurChannelNum; /* 注意当前Channel数及时更新了!! */ fCurChannelNum+=2; // Reallocate the Ch# to Session ID Map /* 除2获取Channel pair总数 */ UInt32 numChannelEntries = fCurChannelNum >> 1; /* 创建新的ChNumToSessID Map */ StrPtrLen* newMap = NEW StrPtrLen[numChannelEntries]; /* 及时扩容旧的fChNumToSessIDMap */ if (fChNumToSessIDMap != NULL) { Assert(numChannelEntries > 1); /* 注意这里减一,是将原来的ChNumToSessID Map映射数据复制过来,最后一个分量还需下面接着配置 */ ::memcpy(newMap, fChNumToSessIDMap, sizeof(StrPtrLen) * (numChannelEntries - 1)); delete [] fChNumToSessIDMap; } fChNumToSessIDMap = newMap; // Put this sessionID to the proper place in the map /* 利用入参来更新ChNumToSessID Map的最后一个分量 */ fChNumToSessIDMap[numChannelEntries-1].Set(inRTSPSessionID->GetAsCString(), inRTSPSessionID->Len); /* 返回当前的channel Number */ return theChannelNum; } /* 利用入参inChannelNum获取对应的RTSPSession ID */ StrPtrLen* RTSPSessionInterface::GetSessionIDForChannelNum(UInt8 inChannelNum) { if (inChannelNum < fCurChannelNum) return &fChNumToSessIDMap[inChannelNum >> 1]; else return NULL; } /********************************* / InterleavedWrite / Write the given RTP packet out on the RTSP channel in interleaved format. */ //紧密联系RTSPSession::HandleIncomingDataPacket() /* 首先尽力抓住RTSPSession mutex,保证原子操作,对指定的数据,首先判断若其长度inLen+拼合缓存中的原有数据长度fNumInCoalesceBuffer之和, 若该和已超过1450字节,先将拼合缓存fTCPCoalesceBuffer中的数据首先发送出去(清空), 假如inLen超过一定字节数,就绕开拼合,直接写到RTPStream里, 若inLen超过一定字节数没有超过,就拼合进拼合缓存中,等待下次RTSPResponseStream::WriteV(实质用到writev()),最后释放会话锁 */ QTSS_Error RTSPSessionInterface::InterleavedWrite(void* inBuffer, UInt32 inLen, UInt32* outLenWritten, unsigned char channel) { /* 假如缓存中的数据长度为0 */ if ( inLen == 0 && fNumInCoalesceBuffer == 0 ) { if (outLenWritten != NULL) *outLenWritten = 0; return QTSS_NoErr; } // First attempt to grab the RTSPSession mutex. This is to prevent writing data to // the connection at the same time an RTSPRequest is being processed. We cannot // wait for this mutex to be freed (there would be a deadlock possibility), so // just try to grab it, and if we can't, then just report it as an EAGAIN /* 尽力抓住RTSPSession mutex,若没有成功,就返回EAGAIN */ if ( this->GetSessionMutex()->TryLock() == false ) { return EAGAIN; } // DMS - this struct should be packed. //rt todo -- is this struct more portable (byte alignment could be a problem)? struct RTPInterleaveHeader //总长为4个字节,即'$ '+ 1 byte ch ID + 2 bytes length { unsigned char header; unsigned char channel; UInt16 len; }; struct iovec iov[3]; QTSS_Error err = QTSS_NoErr; // flush rules清空法则 /* 假如拼合缓存fTCPCoalesceBuffer已有数据,若再加上其他数据,超过1450个字节,则将拼合缓存fTCPCoalesceBuffer中的数据首先发送出去(清空) */ if ( ( inLen > kTCPCoalesceDirectWriteSize || inLen == 0 ) && fNumInCoalesceBuffer > 0 || ( inLen + fNumInCoalesceBuffer + kInteleaveHeaderSize > kTCPCoalesceBufferSize ) && fNumInCoalesceBuffer > 0 ) { UInt32 buffLenWritten; // skip iov[0], WriteV uses it iov[1].iov_base = fTCPCoalesceBuffer; iov[1].iov_len = fNumInCoalesceBuffer; /* 注意只有第二个分量的长度 */ err = this->GetOutputStream()->WriteV( iov, 2, fNumInCoalesceBuffer, &buffLenWritten, RTSPResponseStream::kAllOrNothing ); #if RTSP_SESSION_INTERFACE_DEBUGGING qtss_printf("InterleavedWrite: flushing %li\n", fNumInCoalesceBuffer ); #endif /* 表明已经完全清空了这些数据 */ if ( err == QTSS_NoErr ) fNumInCoalesceBuffer = 0; } if ( err == QTSS_NoErr ) { /* 假如inLen超过一定字节数,就绕开拼合,直接写到RTPStream里 */ if ( inLen > kTCPCoalesceDirectWriteSize ) { struct RTPInterleaveHeader rih; // write direct to stream rih.header = '$'; rih.channel = channel; rih.len = htons( (UInt16)inLen); iov[1].iov_base = (char*)&rih; iov[1].iov_len = sizeof(rih); iov[2].iov_base = (char*)inBuffer; iov[2].iov_len = inLen; /* 注意只有第2和3个分量的长度 */ err = this->GetOutputStream()->WriteV( iov, 3, inLen + sizeof(rih), outLenWritten, RTSPResponseStream::kAllOrNothing ); #if RTSP_SESSION_INTERFACE_DEBUGGING qtss_printf("InterleavedWrite: bypass(绕开) %li\n", inLen ); #endif } else/* 否则长度不够,不足发送,与其他小的write拼合起来,等待以后发送 */ { // coalesce with other small writes /* 首先将RTPInterleaveHeader拼合在fTCPCoalesceBuffer末尾,增加4个字节 */ fTCPCoalesceBuffer[fNumInCoalesceBuffer] = '$'; fNumInCoalesceBuffer++;; fTCPCoalesceBuffer[fNumInCoalesceBuffer] = channel; fNumInCoalesceBuffer++; //*((short*)&fTCPCoalesceBuffer[fNumInCoalesceBuffer]) = htons(inLen); // if we ever turn TCPCoalesce back on, this should be optimized // for processors w/o alignment restrictions as above. SInt16 pcketLen = htons( (UInt16) inLen); ::memcpy( &fTCPCoalesceBuffer[fNumInCoalesceBuffer], &pcketLen, 2 ); fNumInCoalesceBuffer += 2; /* 再将实际数据拼合进来 */ ::memcpy( &fTCPCoalesceBuffer[fNumInCoalesceBuffer], inBuffer, inLen ); fNumInCoalesceBuffer += inLen; #if RTSP_SESSION_INTERFACE_DEBUGGING qtss_printf("InterleavedWrite: coalesce(拼合) %li, total bufff %li\n", inLen, fNumInCoalesceBuffer); #endif } } if ( err == QTSS_NoErr ) { /* if no error sure to correct outLenWritten, cuz WriteV above includes the interleave header count GetOutputStream()->WriteV guarantees all or nothing for writes if no error, then all was written. */ if ( outLenWritten != NULL ) *outLenWritten = inLen; } this->GetSessionMutex()->Unlock(); return err; } /* take the TCP socket away from a RTSP session that's waiting to be snarfed. */ /* 先将失控字节复制过来,再新建一个新的TCPSocket并设置为fInputSocketP来读进这些数据 */ void RTSPSessionInterface::SnarfInputSocket( RTSPSessionInterface* fromRTSPSession ) { Assert( fromRTSPSession != NULL ); Assert( fromRTSPSession->fOutputSocketP != NULL ); // grab the unused, but already read fromsocket data // this should be the first RTSP request /* 要求client发送基于64解密的数据 */ if (sDoBase64Decoding) fInputStream.IsBase64Encoded(true); // client sends all data base64 encoded /* 从入参指定的RTSPRequestStream中复制失控字节retreat bytes到fRequestBuffer开头处,设置相应数据成员的值 */ fInputStream.SnarfRetreat( fromRTSPSession->fInputStream ); if (fInputSocketP == fOutputSocketP) fInputSocketP = NEW TCPSocket( this, Socket::kNonBlockingSocketType ); else fInputSocketP->Cleanup(); // if this is a socket replacing an old socket, we need // to make sure the file descriptor gets closed /* 利用入参的值配置本类TCPSocket各成员的信息,然后清空入参中的各成员值,类似于复制构造函数 */ fInputSocketP->SnarfSocket( fromRTSPSession->fSocket ); // fInputStream, meet your new input socket // Use a different TCPSocket to read request data fInputStream.AttachToSocket( fInputSocketP ); } /* 从入参TCPSocket得到的C/S ip&port和string并设置RTSPSession Dictionary相应属性值 */ void* RTSPSessionInterface::SetupParams(QTSSDictionary* inSession, UInt32* /*outLen*/) { RTSPSessionInterface* theSession = (RTSPSessionInterface*)inSession; /* 从TCPSocket得到的C/S ip&port */ theSession->fLocalAddr = theSession->fSocket.GetLocalAddr(); theSession->fRemoteAddr = theSession->fSocket.GetRemoteAddr(); theSession->fLocalPort = theSession->fSocket.GetLocalPort(); theSession->fRemotePort = theSession->fSocket.GetRemotePort(); /* C/S ip&port$dns string */ StrPtrLen* theLocalAddrStr = theSession->fSocket.GetLocalAddrStr(); StrPtrLen* theLocalDNSStr = theSession->fSocket.GetLocalDNSStr(); StrPtrLen* theRemoteAddrStr = theSession->fSocket.GetRemoteAddrStr(); if (theLocalAddrStr == NULL || theLocalDNSStr == NULL || theRemoteAddrStr == NULL) { //the socket is bad most likely values are all 0. If the socket had an error we shouldn't even be here. //theLocalDNSStr is set to localAddr if it is unavailable, so it should be present at this point as well. Assert(0); //for debugging return NULL; //nothing to set } /* 用上面获得的值设置RTSPSession Dictionary attributes */ theSession->SetVal(qtssRTSPSesLocalAddr, &theSession->fLocalAddr, sizeof(theSession->fLocalAddr)); theSession->SetVal(qtssRTSPSesLocalAddrStr, theLocalAddrStr->Ptr, theLocalAddrStr->Len); theSession->SetVal(qtssRTSPSesLocalDNS, theLocalDNSStr->Ptr, theLocalDNSStr->Len); theSession->SetVal(qtssRTSPSesRemoteAddr, &theSession->fRemoteAddr, sizeof(theSession->fRemoteAddr)); theSession->SetVal(qtssRTSPSesRemoteAddrStr, theRemoteAddrStr->Ptr, theRemoteAddrStr->Len); theSession->SetVal(qtssRTSPSesLocalPort, &theSession->fLocalPort, sizeof(theSession->fLocalPort)); theSession->SetVal(qtssRTSPSesRemotePort, &theSession->fRemotePort, sizeof(theSession->fRemotePort)); return NULL; } /* 从fOutputStream中备份fOutputStream中即将送出的数据,来配置fOldOutputStreamBuffer */ void RTSPSessionInterface::SaveOutputStream() { Assert(fOldOutputStreamBuffer.Ptr == NULL); fOldOutputStreamBuffer.Ptr = NEW char[fOutputStream.GetBytesWritten()]; fOldOutputStreamBuffer.Len = fOutputStream.GetBytesWritten(); ::memcpy(fOldOutputStreamBuffer.Ptr, fOutputStream.GetBufPtr(), fOldOutputStreamBuffer.Len); } /* used in RTSPSession::Run():case kSendingResponse */ /* 逐个解析fOldOutputStreamBuffer中的数据,复制进EOL之前的字符串进fOutputStream;若RTSP headers中有"x-Dynamic-Rate"头, 就要在fOutputStream插入";rtt=**".最后在末尾补上原有的"\r\n"重新得到fOutputStream.并删去fOldOutputStreamBuffer. */ void RTSPSessionInterface::RevertOutputStream() { /* 参见RTSPSessionInterface::SaveOutputStream() */ Assert(fOldOutputStreamBuffer.Ptr != NULL); Assert(fOldOutputStreamBuffer.Len != 0); static StrPtrLen theRTTStr(";rtt=", 5);/* rtt- round trip time */ if (fOldOutputStreamBuffer.Ptr != NULL) { //fOutputStream.Put(fOldOutputStreamBuffer); StringParser theStreamParser(&fOldOutputStreamBuffer); StrPtrLen theHeader; StrPtrLen theEOL; StrPtrLen theField; StrPtrLen theValue; /* 逐个解析fOldOutputStreamBuffer中的RTSP header,并复制进EOL之前的字符串进fOutputStream */ while(theStreamParser.GetDataRemaining() != 0) { /* 指针fStartGet从头开始移到,直到遇到'\r\n'停下,将经过的字符串给theHeader */ theStreamParser.ConsumeUntil(&theHeader, StringParser::sEOLMask); if (theHeader.Len != 0) { /* 将theHeader字符串放入fOutputStream */ fOutputStream.Put(theHeader); /* 下面具体分析theHeader这个字符串 */ StringParser theHeaderParser(&theHeader); /* 指针fStartGet从theHeader开头开始移到,直到遇到':'停下,将经过的字符串给theField */ theHeaderParser.ConsumeUntil(&theField, ':'); if (theHeaderParser.PeekFast() == ':') { /* 假如theField为"x-Dynamic-Rate" */ if(theField.Equal(RTSPProtocol::GetHeaderString(qtssXDynamicRateHeader))) { /* 放入";rtt="和往返时间值 */ fOutputStream.Put(theRTTStr); fOutputStream.Put(fRoundTripTime);/* 试问:fRoundTripTime在哪里赋值的? */ } } } /* 指针fStartGet越过'\r'或'\n'并换行,获得theEOL的值,下面再加上 */ theStreamParser.ConsumeEOL(&theEOL); /* 再将'\r\n'放入fOutputStream */ fOutputStream.Put(theEOL); } /* 删除fOldOutputStreamBuffer */ fOldOutputStreamBuffer.Delete(); } } /* used in RTSPSession::SetupRequest() */ // 紧密联系RTSPSession::ParseOptionsResponse() /* 在fOutputStream中放入"OPTIONS * RTSP/1.0\r\nContent-Type: application/x-random-data\r\nContent-Length: 1400\r\n\r\n",再放入指定长度的1400个字节的数组; */ void RTSPSessionInterface::SendOptionsRequest() { static StrPtrLen sOptionsRequestHeader("OPTIONS * RTSP/1.0\r\nContent-Type: application/x-random-data\r\nContent-Length: 1400\r\n\r\n"); fOutputStream.Put(sOptionsRequestHeader); /* 放入指定长度的1400个字节的数组 */ fOutputStream.Put((char*)(RTSPSessionInterface::sOptionsRequestBody), 1400); /* 记录放入sOptionsRequestHeader的local time */ fOptionsRequestSendTime = OS::Milliseconds(); fSentOptionsRequest = true; fRoundTripTimeCalculation = false; }
#include <ros/ros.h> #include <actionlib/client/simple_action_client.h> #include <move_base_msgs/MoveBaseAction.h> /* This node receives a single goal position and produces a global trajectory * using the global planner from the move_base node. */ typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> Client; int main(int argc, char** argv) { ros::init(argc, argv, "send_simple_goal_client"); // Create an action client called "move_wamv" // True causes the client to spin its own thread --> don't need ros::spin Client client("move_base", true); // Wait for the action server to come up while (!client.waitForServer(ros::Duration(5.0))) { ROS_INFO("Waiting for the move_base action server to come up"); } move_base_msgs::MoveBaseGoal goal; // Fill in the message here... goal.target_pose.header.frame_id = "base_link"; goal.target_pose.header.stamp = ros::Time::now(); goal.target_pose.pose.position.x = 20; goal.target_pose.pose.position.y = 3; goal.target_pose.pose.orientation.w = 1.0; client.sendGoal(goal); client.waitForResult(); // Check if vehicle has reached the goal pose if (client.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO(">>>>>> The vehicle reached the waypoint <<<<<<"); } else { ROS_INFO("The vehicle failed to move"); } ROS_INFO("//////// Current state is: %s /////////", client.getState().toString().c_str()); return 0; }
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { stack <int> s; s.push(2); s.push(3); s.push(1); int val = s.size(); // cout<<s.top()+2; cout<<min(s.top(),s.top()+val); }
#include "Board.h" Board::Board() { } Board::~Board() { } void Board::renderGrid(sf::RenderWindow *window, int width, int height) { sf::VertexArray grid(sf::Lines); for (int x = 0; x < height; x += (GameManager::get().gridHeight)) { grid.append(sf::Vector2f(0 + x, 0)); // start grid.append(sf::Vector2f(0 + x, height)); // end grid.append(sf::Vector2f(0, 0 + x)); grid.append(sf::Vector2f(width, 0 + x)); } window->draw(grid); } void Board::handleEvent(sf::Event *e){}
#include<iostream> using namespace std; //封装一个函数,利用冒泡排序,实现对整形数组的升序排序 void bubbleSort(int * arr,int len)//参数分别是数组的首地址和数组长度 { for(int i = 0;i < len-1;i++) { for(int j = 0;j<len - i - 1;j++) { if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } int main() { int arr[10] = {3,6,9,8,5,2,0,1,4,7}; int len = sizeof(arr)/sizeof(arr[0]);//整个数组的size除以数组某一个元素的size bubbleSort(arr,len); for(int i = 0;i < 10;i++) { cout<<arr[i]<<endl; } int * p = arr; for(int i = 0;i < 10;i++) { cout<<*p<<endl; p++; } return 0; }
/* ID: hjl11841 TASK: frac1 LANG: C++ */ #include<bits/stdc++.h> using namespace std; vector<int> fengzi; vector<int> fengmu; int gcd(int x,int y){ int s; while(x){ s=y%x; y=x; x=s; } return y; } int main(){ freopen("frac1.in","r",stdin); freopen("frac1.out","w",stdout); int n; cin>>n; fengzi.push_back(0); fengzi.push_back(1); fengmu.push_back(1); fengmu.push_back(1); for(int i=2;i<=n;i++){ for(int j=0;j+1<fengmu.size();j++){ if(fengmu[j]+fengmu[j+1]==i){ int x=fengmu[j]+fengmu[j+1]; int y=fengzi[j]+fengzi[j+1]; fengmu.insert(fengmu.begin()+j+1,x); fengzi.insert(fengzi.begin()+j+1,y); } } } for(int i=0;i<fengmu.size();i++){ if(gcd(fengzi[i],fengmu[i])==1){ cout<<fengzi[i]<<'/'<<fengmu[i]<<endl; } } return 0; }
#include "seal/seal.h" #include "helper.hpp" #include <iostream> #include <vector> using namespace std; using namespace seal; SEALContext SetupCKKS() { EncryptionParameters parms(scheme_type::ckks); size_t poly_modulus_degree = 16384; parms.set_poly_modulus_degree(poly_modulus_degree); try { parms.set_coeff_modulus(CoeffModulus::Create(poly_modulus_degree, {60, 40, 40, 40, 40, 40, 60})); } catch (exception e) { cout << e.what() << endl; exit(1); } return SEALContext(parms); } Ciphertext Encrypt(SEALContext &context, PublicKey &public_key, double &scale, Plaintext &plaintext) { Encryptor encryptor(context, public_key); Ciphertext ciphertext; encryptor.encrypt(plaintext, ciphertext); return ciphertext; } Plaintext Decrypt(SEALContext &context, SecretKey &secret_key, Ciphertext &ciphertext) { Decryptor decryptor(context, secret_key); Plaintext plaintext; decryptor.decrypt(ciphertext, plaintext); return plaintext; } void Encode(CKKSEncoder &encoder, vector<double> &input, double &scale, Plaintext &output) { encoder.encode(input, scale, output); } void Decode(CKKSEncoder &encoder, Plaintext &input, vector<double> &output) { encoder.decode(input, output); } void Encode(CKKSEncoder &encoder, double input, double &scale, Plaintext &output) { encoder.encode(input, scale, output); } void Encode(SEALContext &context, vector<double> &input, double &scale, Plaintext &output) { CKKSEncoder encoder(context); Encode(encoder, input, scale, output); } void Decode(SEALContext &context, Plaintext &input, vector<double> &output) { CKKSEncoder encoder(context); Decode(encoder, input, output); } void Encode(SEALContext &context, double input, double &scale, Plaintext &output) { CKKSEncoder encoder(context); Encode(encoder, input, scale, output); } // Perform sigmoid function on the x_encrypted (Level 5) // The Ciphertext output will be a "spread" result (Level 2) Ciphertext Sigmoid(SEALContext &context, RelinKeys &relin_keys, double scale, Ciphertext &x_encrypted) { Evaluator evaluator(context); CKKSEncoder encoder(context); /////////////////////////////////////////////////////////////// /* [ COMPUTE 0.002x^5] */ // ------------------------------------------------------- // // x_encrypted -> Level 5 // compute x_encrypted ^ 2 Ciphertext x_sq_encrypted; evaluator.square(x_encrypted, x_sq_encrypted); evaluator.relinearize_inplace(x_sq_encrypted, relin_keys); evaluator.rescale_to_next_inplace(x_sq_encrypted); x_sq_encrypted.scale() = scale; // x_sq_encrypted -> Level 4 // ------------------------------------------------------- // // x_sq_encrypted -> Level 4 // compute x_encrypted ^ 4 Ciphertext x_quad_encrypted; evaluator.square(x_sq_encrypted, x_quad_encrypted); evaluator.relinearize_inplace(x_quad_encrypted, relin_keys); evaluator.rescale_to_next_inplace(x_quad_encrypted); x_quad_encrypted.scale() = scale; // x_quad_encrypted -> Level 3 // ------------------------------------------------------- // // x_encrypted -> Level 5 // compute 0.002 * x_encrypted Ciphertext x_encrypted_coeff5; Plaintext plain_coeff5; Encode(encoder, 0.002, scale, plain_coeff5); // plain_coeff_5 - Level 6 // x_encrypted - Level 5 // => mod switch plain_coeff_5 to level 5 parms_id_type x_encrypted_parms_id = x_encrypted.parms_id(); evaluator.mod_switch_to_inplace(plain_coeff5, x_encrypted_parms_id); evaluator.multiply_plain(x_encrypted, plain_coeff5, x_encrypted_coeff5); // unnecessary to relinearize the result of 1 ciphertext and 1 plaintext // only necessary or both ciphertexts evaluator.rescale_to_next_inplace(x_encrypted_coeff5); x_encrypted_coeff5.scale() = scale; // x_encrypted_coeff5 -> Level 4 // ------------------------------------------------------- // // x_encrypted_coeff5 -> Level 4 // compute 0.002 * (x_encrypted ^ 5) // x_encrypted_coeff5 -> Level 4 // x_quad_encrypted -> Level 3 // => mod switch x_encrypted_coeff5 to level 3 parms_id_type x_quad_encrypted_parms_id = x_quad_encrypted.parms_id(); evaluator.mod_switch_to_inplace(x_encrypted_coeff5, x_quad_encrypted_parms_id); Ciphertext x_pow_5_encrypted_coeff5; evaluator.multiply(x_quad_encrypted, x_encrypted_coeff5, x_pow_5_encrypted_coeff5); evaluator.relinearize_inplace(x_pow_5_encrypted_coeff5, relin_keys); evaluator.rescale_to_next_inplace(x_pow_5_encrypted_coeff5); x_pow_5_encrypted_coeff5.scale() = scale; // x_pow_5_encrypted_coeff5 -> Level 2 // save parms_id for later mod switch parms_id_type last_parms_id = x_pow_5_encrypted_coeff5.parms_id(); // Level 2 /////////////////////////////////////////////////////////////// /* [COMPUTE 0.021x^3] */ // ------------------------------------------------------- // // x_encrypted -> Level 5 // compute 0.021 * x_encrypted Ciphertext x_encrypted_coeff3; Plaintext plain_coeff3; Encode(encoder, 0.021, scale, plain_coeff3); // plain_coeff3 -> Level 5 evaluator.multiply_plain(x_encrypted, plain_coeff3, x_encrypted_coeff3); evaluator.rescale_to_next_inplace(x_encrypted_coeff3); x_encrypted_coeff3.scale() = scale; // x_encrypted_coeff3 -> Level 4 // ------------------------------------------------------- // // x_encrypted_coeff3 -> Level 4 // x_sq_encrypted -> Level 4 // compute 0.021 * (x_encrypted ^ 3) Ciphertext x_pow_3_encrypted_coeff3; evaluator.multiply(x_sq_encrypted, x_encrypted_coeff3, x_pow_3_encrypted_coeff3); evaluator.relinearize_inplace(x_pow_3_encrypted_coeff3, relin_keys); evaluator.rescale_to_next_inplace(x_pow_3_encrypted_coeff3); x_pow_3_encrypted_coeff3.scale() = scale; // x_pow_3_encrypted_coeff3 -> Level 3 evaluator.mod_switch_to_inplace(x_pow_3_encrypted_coeff3, last_parms_id); // x_pow_3_encrypted_coeff3 -> Level 2 /////////////////////////////////////////////////////////////// /* [COMPUTE 0.25x] */ // ------------------------------------------------------- // // x_encrypted -> Level 5 // compute 0.25 * x_encrypted Ciphertext x_encrypted_coeff1; Plaintext plain_coeff1; Encode(encoder, 0.25, scale, plain_coeff1); // plain_coeff1 -> Level 5 evaluator.multiply_plain(x_encrypted, plain_coeff1, x_encrypted_coeff1); evaluator.rescale_to_next_inplace(x_encrypted_coeff1); x_encrypted_coeff1.scale() = scale; // x_encrypted_coeff1 -> Level 4 evaluator.mod_switch_to_inplace(x_encrypted_coeff1, last_parms_id); // x_encrypted_coeff1 -> Level 2 /////////////////////////////////////////////////////////////// /* [COMPUTE FINAL RESULT] */ Plaintext plain_coeff0; Encode(encoder, 0.5, scale, plain_coeff0); // plain_coeff0 -> Level 5 evaluator.mod_switch_to_inplace(plain_coeff0, last_parms_id); // plain_coeff0 -> Level 2 Ciphertext encrypted_final_result; // result = 0.5 + 0.25x evaluator.add_plain(x_encrypted_coeff1, plain_coeff0, encrypted_final_result); // result -= 0.021x^3 evaluator.sub_inplace(encrypted_final_result, x_pow_3_encrypted_coeff3); // result += 0.002x^5 evaluator.add_inplace(encrypted_final_result, x_pow_5_encrypted_coeff5); return encrypted_final_result; } /* // Sum all elements of the given plaintext Ciphertext Sum(SEALContext &context, GaloisKeys &galois_keys, const Ciphertext &x_encrypted, size_t slot_count) { Evaluator evaluator(context); Ciphertext copied_x1 = x_encrypted; Ciphertext copied_x2 = x_encrypted; for (size_t i = 1; i < slot_count; ++i) { evaluator.rotate_vector_inplace(copied_x2, 1, galois_keys); evaluator.add_inplace(copied_x1, copied_x2); } return copied_x1; } // Perform vector multiplication between the x_encrypted (Level 6) and the weights_encrypted (Level 6) // The Ciphertext output will be a "spread" sum of the multiplication result (Level 5) Ciphertext VectorMultiplication(SEALContext &context, RelinKeys &relin_keys, GaloisKeys &galois_keys, const Ciphertext &x_encrypted, const Ciphertext &weights_encrypted, size_t slot_count) { Evaluator evaluator(context); // x1 - Level 6 // x2 - Level 6 Ciphertext encrypted_product; evaluator.multiply(x_encrypted, weights_encrypted, encrypted_product); evaluator.relinearize_inplace(encrypted_product, relin_keys); evaluator.rescale_to_next_inplace(encrypted_product); // encrypted_product -> Level 5 return Sum(context, galois_keys, encrypted_product, slot_count); } */ // Perform partial derivative on the sigmoided_value of one single encrypted sample // Ciphertext inputs: // sigmoided_value -> Level 2 // x_encrypted -> Level 6 // y_encrypted -> Leevl 6 // Ciphertext output: // result -> Level 1 Ciphertext PartialDerivative(SEALContext &context, RelinKeys &relin_keys, Ciphertext &sigmoided_value, const Ciphertext &x_encrypted, const Ciphertext &y_encrypted, double scale) { // sigmoided_value -> Level 2 // x_encrypted -> Level 5 // y_encrypted -> Level 5 Evaluator evaluator(context); Ciphertext x = x_encrypted, y = y_encrypted; Ciphertext result = sigmoided_value; // modulus switch x_encrypted and y_encrypted to the same as sigmoided_value parms_id_type result_parms_id = result.parms_id(); // Rescale all operands result.scale() = scale; x.scale() = scale; y.scale() = scale; evaluator.mod_switch_to_inplace(x, result_parms_id); // x -> Level 2 evaluator.mod_switch_to_inplace(y, result_parms_id); // y -> Level 2 // result = -sigmoided_value evaluator.negate_inplace(result); // result = y_encrypted - sigmoided_value evaluator.add_inplace(result, y); // result = (y_encrypted - sigmoided_value) * x_encrypted evaluator.multiply_inplace(result, x); evaluator.relinearize_inplace(result, relin_keys); evaluator.rescale_to_next_inplace(result); // result -> Level 1 return result; } Ciphertext SumPartialDerivative(SEALContext &context, RelinKeys &relin_keys, const vector<Ciphertext> &derivatives) { Evaluator evaluator(context); Ciphertext encrypted_sum = derivatives[0]; for (size_t i = 1; i < derivatives.size(); ++i) { evaluator.add_inplace(encrypted_sum, derivatives[i]); } return encrypted_sum; } // This algorithm is only able to train 1 iteration at a time due to incompatible levels of operands at the end of the algorithm. // This function return the new adjusted encrypted weights parameter. Ciphertext Train(SEALContext &context, RelinKeys &relin_keys, GaloisKeys &galois_keys, double scale, const vector<Ciphertext> &encrypted_products, const vector<Ciphertext> &samples, const vector<Ciphertext> &labels, const Ciphertext &weight, const Ciphertext &learning_rate, size_t slot_count) { Evaluator evaluator(context); // --------------------------------------------------------------------- // // Compute (learning_rate / m) Plaintext plain_m; Encode(context, 1.0 / samples.size(), scale, plain_m); Ciphertext learning_rate_mul_inv_m; evaluator.multiply_plain(learning_rate, plain_m, learning_rate_mul_inv_m); evaluator.relinearize_inplace(learning_rate_mul_inv_m, relin_keys); evaluator.rescale_to_next_inplace(learning_rate_mul_inv_m); learning_rate_mul_inv_m.scale() = scale; // learning_rate_mul_inv_m -> Level 4 // --------------------------------------------------------------------- // // Privacy preserving logistic regression algorithm vector<Ciphertext> partial_derivatives; // Compute sigmoid values of all samples for (size_t i = 0; i < samples.size(); ++i) { // ----------------------------------------------------------------- // Ciphertext encrypted_sample_x_weights = encrypted_products[i]; // encrypted_sample_x_weights -> Level 5 // ----------------------------------------------------------------- // // Perform sigmoid function Ciphertext sigmoid = Sigmoid(context, relin_keys, scale, encrypted_sample_x_weights); sigmoid.scale() = scale; // sigmoid -> Level 2 // ----------------------------------------------------------------- // // Compute the partial derivative of the weighted sample Ciphertext partial_derivative = PartialDerivative(context, relin_keys, sigmoid, samples[i], labels[i], scale); partial_derivative.scale() = scale; // partial_derivative -> Level 1 partial_derivatives.push_back(partial_derivative); } // --------------------------------------------------------------------- // // Compute the sum of the partial derivatives Ciphertext encrypted_derivatives_sum = SumPartialDerivative(context, relin_keys, partial_derivatives); encrypted_derivatives_sum.scale() = scale; // encrypted_derivatives_sum -> Level 1 // --------------------------------------------------------------------- // // Modulus switch learning_rate_mul_inv_m to level 1 parms_id_type encrypted_derivatives_sum_parms_id = encrypted_derivatives_sum.parms_id(); evaluator.mod_switch_to_inplace(learning_rate_mul_inv_m, encrypted_derivatives_sum_parms_id); // learning_rate_mul_inv_m -> Level 1 // --------------------------------------------------------------------- // // compute learning_rate / m * sum_derivatives // result is called encrypted_weight_adjustment Ciphertext encrypted_weight_adjustment; evaluator.multiply(encrypted_derivatives_sum, learning_rate_mul_inv_m, encrypted_weight_adjustment); evaluator.relinearize_inplace(encrypted_weight_adjustment, relin_keys); evaluator.rescale_to_next_inplace(encrypted_weight_adjustment); encrypted_weight_adjustment.scale() = scale; // encrypted_weight_adjustment -> Level 0 // --------------------------------------------------------------------- // // update new weights Ciphertext trained_weight = weight; // trained_weight -> Level 5 // encrypted_weight_adjustment -> Level 0 // modulus switch trained_weight to level 0 parms_id_type encrypted_weight_adjustment_parms_id = encrypted_weight_adjustment.parms_id(); evaluator.mod_switch_to_inplace(trained_weight, encrypted_weight_adjustment_parms_id); // trained_weight -> Level 0 // Update weight evaluator.add_inplace(trained_weight, encrypted_weight_adjustment); return trained_weight; }
#include "dialogquerypasswd.h" #include "ui_dialogquerypasswd.h" #include <QTextCodec> DialogQueryPasswd::DialogQueryPasswd(QWidget *parent) : QDialog(parent), ui(new Ui::DialogQueryPasswd) { QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForLocale(codec); ui->setupUi(this); ui->lEdit_dialog_askPasswd->setFocus(); this->setWindowTitle(QObject::tr("安全提示")); } QString DialogQueryPasswd::getQueryPasswd(void) { return ui->lEdit_dialog_askPasswd->text(); } DialogQueryPasswd::~DialogQueryPasswd() { delete ui; }
int pm[n],sm[n]; pm[0]=0; sm[n-1]=0; for(int i=1;i<n;i++) { pm[i]=max(pm[i-1],arr[i-1]); } for(int i=n-2;i>=0;i--) { sm[i]=max(sm[i+1],arr[i+1]); } // for(int i=1;i<n-1;i++) // { // cout<<arr[i]<<" "<<pm[i]<<" "<<sm[i]<<"\n"; // } int ans=0; for(int i=1;i<n-1;i++) { ans+=max(min(pm[i],sm[i])-arr[i],0); } return ans;
#include "yaml-cpp/yaml.h" #include "info.h" #include <iostream> #include <stdlib.h> #include <stdio.h> #include <string> void get_config(Global_Info& my_info) { YAML::Node config = YAML::LoadFile("query_input.yaml"); YAML::Node queries = config["queries"]; YAML::Node cred = config["twitter-api"]; my_info.username = cred["username"].as<std::string>(); my_info.password = cred["password"].as<std::string>(); for (int i = 0; i < queries.size(); i ++) { Item item; item.title = queries[i]["title"].as<std::string>(); item.query = queries[i]["query"].as<std::string>(); YAML::Node start = queries[i]["startdate"]; YAML::Node end = queries[i]["enddate"]; item.startdate.year = start["startyear"].as<int>(); item.startdate.month = start["startmonth"].as<int>(); item.startdate.day = start["startday"].as<int>(); item.enddate.year = end["endyear"].as<int>(); item.enddate.month = end["endmonth"].as<int>(); item.enddate.day = end["endday"].as<int>(); item.init_times(); my_info.config.queries.push_back(item); } std::cout << "Read configuration file, will now start curling...\n"; }
#ifndef _GALES_SCATTER_HPP_ #define _GALES_SCATTER_HPP_ #include <vector> namespace GALES { /** This class scatters the element level computations into global matrix and vector. */ template<typename dofs_ic_bc_type> class scatter { public: explicit scatter(dofs_ic_bc_type& dofs_ic_bc): dofs_ic_bc_(dofs_ic_bc){} //------------------------------------------------------------------------------------------------------------------------------------- /// Deleting the copy and move constructors - no duplication/transfer in anyway scatter(const scatter&) = delete; //copy constructor scatter& operator=(const scatter&) = delete; //copy assignment operator scatter(scatter&&) = delete; //move constructor scatter& operator=(scatter&&) = delete; //move assignment operator //------------------------------------------------------------------------------------------------------------------------------------- template <typename element_type, typename mesh_type, typename lp_type, typename m_type, typename v_type> void execute(const element_type& el, const mesh_type& mesh, lp_type& lp, m_type& m, v_type& r) const { const int n_item(m.size1()); /// number of dofs in local matrix std::vector<int> dof_gid_index(n_item); std::vector<std::pair<bool,double>> to_be_blocked(n_item, std::make_pair(false,0.0)); /// creating the dof_gid_index and dof constrained info for the dofs belonging to the el int count(0); for (int i=0; i<el.nb_nodes(); i++) { const int nd_lid = el.nd_lid(i); const auto& nd(mesh.nodes()[nd_lid]); const int fd_gid = nd->first_dof_gid(); for(int k_i=0; k_i<nd->nb_dofs(); k_i++) { dof_gid_index[count] = fd_gid + k_i; to_be_blocked[count] = dofs_ic_bc_.dof_constraint(dof_gid_index[count], *nd) ; count++; } } /// Applying dirichlet bc at the local matrix. /// The diagonal value in matrix is not 1.0 instead is set to the average value of the matrix diagonal for better condition number. double avg_val(1.0); for(int i=0; i<n_item; ++i) avg_val += m(i,i); avg_val /= n_item; for(int i=0; i<n_item; ++i) // i is for row if(to_be_blocked[i].first) { for(int j=0; j<n_item; ++j) // j is for column m(i,j) = 0.0; m(i,i) = avg_val; r[i] = avg_val*to_be_blocked[i].second; } /// To pass matrix m into lp.matrix() with just one call to SumIntoGlobalValues function, we convert m(2d structure) to a m_vec(1d structure); std::vector<double> m_vec(n_item*n_item); for(int i=0; i<n_item; ++i) { for(int j=0; j<n_item; ++j) { m_vec[i*n_item + j] = m(i,j); } } /// Here we fill the global matrix and RHS vector. lp.rhs()->SumIntoGlobalValues(n_item, &dof_gid_index[0], &r[0]); lp.matrix()->SumIntoGlobalValues(n_item, &dof_gid_index[0], n_item, &dof_gid_index[0], &m_vec[0], Epetra_FECrsMatrix::ROW_MAJOR); } private: dofs_ic_bc_type& dofs_ic_bc_; }; }//namespace GALES #endif
#include "Adafruit_NeoPixel.h" extern "C" { extern void render_pixel(uint16_t, uint8_t, uint8_t, uint8_t); extern void initialize_pixels(uint16_t); extern void show_pixels(); } SoftPixel::SoftPixel(uint16_t count, uint8_t pin, uint8_t mode) { pixels = new uint32_t[count]; pixel_count = count; //printf("[?] Pixel(%d, %d, %d)\n", count, pin, mode); initialize_pixels(count); // TODO also initialize views to show overlap } void SoftPixel::begin(void) { //printf("[?] Pixel.begin\n"); } void SoftPixel::show(void) { show_pixels(); for(int i = 0; i < pixel_count; i++) { uint8_t r,g,b; r = (uint8_t)(pixels[i] >> 16), g = (uint8_t)(pixels[i] >> 8), b = (uint8_t)(pixels[i] >> 0); render_pixel(i, r, g, b); // Implement in sdl/gl/canvas } } uint32_t SoftPixel::Color(uint8_t r, uint8_t g, uint8_t b) { uint32_t color = ((uint32_t)r << 16) | ((uint32_t)g << 8) | ((uint32_t)b << 0); //printf("[%%] Pixel.Color(%d, %d, %d) -> %X\n", r, g, b, color); return color; } uint32_t SoftPixel::getPixelColor(uint16_t position) { uint32_t color = pixels[position]; /* uint8_t r,g,b; r = (uint8_t)(color >> 16), g = (uint8_t)(color >> 8), b = (uint8_t)(color >> 0); */ //printf("[R] Pixel.getPixelColor(%d) -> [%X, %d, %d, %d]\n", position, color, r, g, b); return color; }; void SoftPixel::setPixelColor(uint16_t position, uint32_t color) { pixels[position] = color; /* uint8_t r,g,b; r = (uint8_t)(color >> 16), g = (uint8_t)(color >> 8), b = (uint8_t)(color >> 0); printf("[W] Pixel.setPixelColor(%d, %X) -> [%d,%d,%d]\n", position, color, r, g, b); */ }
// // ART.cpp // PianoPlayer // // Created by Ben Smith on 10/10/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <dispatch/dispatch.h> #include "ART.h" ART::ART(double _choice, double _learnRate, double _Vigilance) : mDimensions(19), residual(0), choices(0x00), inputCount(0), maxRecency(0) { mCategories.clear(); mCategories.push_back(new ArtCategory(mDimensions)); mObservations.push_back(0); mRecency.push_back(0); input = new double[mDimensions*2]; choices = new double[1]; // size of category vector choiceSize = 1; mChoice = _choice; mLearnRate = _learnRate; mVigilance = _Vigilance; recentChoice = -1; } ART::~ART() { // for (int i = 0; i < mCategories.size(); i++) // delete mCategories.at(i); mCategories.clear(); if (input != 0x00) delete input; if (choiceSize > 0) delete choices; choiceSize = 0; } void ART::ProcessNewObservation(const double *in, int length) { setInput(in, length); #ifdef USING_RECENCY DecayRecency(); #endif normalizeInput(); complementCode(); FillCategoryChoice(); } void ART::setVigilance(double v) { mVigilance = v; } void ART::setLearnRate(double v) { mLearnRate = v; } void ART::setChoice(double v) { mChoice = v; } double ART::GetResidual() { return residual; } const double* ART::GetCategoryChoice() { if (mCategories.size() > 0) { double* ret = new double[mCategories.size()]; memcpy(ret, choices, mCategories.size()*sizeof(double)); return ret; } else return 0x00; } int ART::GetCategoryCount() // how many categories? { return mCategories.size(); } void ART::normalizeInput() { // limit input to [0,1] - normalize the input vector double max = 0; for (int i = 0; i < mDimensions; i++) max = (input[i] > max ? input[i] : max); if (max > 1) { for (int i = 0; i < mDimensions; i++) input[i] /= max; } } inline void ART::complementCode() { for (int i = 0; i < mDimensions*2; i+=2) // create complement of input - complement coding input[i+1] = 1.0 - input[i]; } void ART::setInput(const double *_in, int size) { // if (size > 0 && size > mDimensions) // { mDimensions = size; if (input != 0x00) delete input; input = (double*)malloc(sizeof(double)*size*2); //new double(size*2); for (int i = 0; i < mCategories.size(); i++) mCategories.at(i)->resizeCategory(mDimensions); // } for (int i = 0; i < size; i++) { input[i*2] = _in[i]; input[i*2+1] = 1.0 - _in[i]; } } void ART::AddResonanceGroup(int startIndex, int groupSize, double weight) { mResonanceWeights.push_back(ResonanceGroup(startIndex, groupSize, weight)); } // set the mVigilance just high enough to reset the chosen category and look again. int ART::increaseVigilance() { if (recentChoice > -1) { double vig = mCategories.at(recentChoice)->GetVigilance(input,mDimensions*2) + 0.01f; // increase by a little bit. recentChoice = makeChoice(vig); } return recentChoice; } void ART::FillCategoryChoice() { // if (choiceSize < mCategories.size()) // { if (choices != 0x00) delete choices; choices = (double*)malloc(sizeof(double) * mCategories.size()); //new double[mCategories.size()]; choiceSize = mCategories.size(); // } // check against all existing categories, and 1 empty one if (mDimensions > 0) { if (mResonanceWeights.size() == 0) mResonanceWeights.push_back(ResonanceGroup(0, mDimensions, mDimensions)); dispatch_apply(mCategories.size(), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t i){ choices[i] = mCategories.at(i)->Choose(input, mDimensions*2, mChoice, mResonanceWeights);}); // for (int i = 0; i < mCategories.size(); i++) // choices[i] = mCategories.at(i)->Choose(input, mDimensions*2, mChoice, mResonanceWeights); // pass in a descriptor for the feature vector } } void ART::DecayRecency() { for (int i = 0; i < mRecency.size(); i++) mRecency.at(i) *= RECENCY_DECAY_RATE; } int ART::makeChoice() { return makeChoice(mVigilance); } int ART::makeChoice(double workingVigilance) { int maxIndex = -1; bool chosen = false; // check mVigilance stuff here... while (!chosen) { // find largest match value double max = 0; for (int i = 0; i < mCategories.size(); i++) if (choices[i] > max) { max = choices[i]; maxIndex = i; } if (maxIndex != -1) { // if above vigilence then learn from it if (mCategories.at(maxIndex)->mVigilance(input,mDimensions*2,workingVigilance) || mCategories.size() == 1) // learn! { // OSCSend::getSingleton()->oscSend("/in", mDimensions*2, input); residual = mCategories.at(maxIndex)->Learn(input,mDimensions*2,mLearnRate); //learn while (maxIndex >= mCategories.size()-1) // committed the previous uncommitted category, so add a new blank one. { mCategories.push_back(new ArtCategory(mDimensions)); mObservations.push_back(0); mRecency.push_back(0); //residual = 1; } chosen = true; recentChoice = maxIndex; } else // failed the mVigilance test. { choices[maxIndex] = -1; // reset, try again maxIndex = -1; } } else chosen = true; } // otherwise look again. if (maxIndex > -1) { inputCount++; mObservations.at(maxIndex) = min(1.0, mObservations.at(maxIndex)+OBSERVATION_VALUE); #ifdef USING_RECENCY mRecency.at(maxIndex) += 0.1; #endif } return maxIndex; } double ART::PredictChoice() { return PredictChoice(mVigilance); } double ART::PredictChoice(double workingVigilance) { int maxIndex = -1; bool chosen = false; // check mVigilance stuff here... while (!chosen) { // find largest match value double max = 0; for (int i = 0; i < mCategories.size(); i++) if (choices[i] > max) { max = choices[i]; maxIndex = i; } if (maxIndex != -1) // we've exhausted the search and no match was found! { // if above vigilence then learn from it // if (mCategories.at(maxIndex)->mVigilance(input,mDimensions*2,workingVigilance) || mCategories.size() == 1) // this is the match! // { // if (maxIndex == mCategories.size()-1) // it would be a new category // residual = mDimensions; //1.0-workingVigilance; //1.0; //mDimensions; // new categories are too chaotic for us to privilege // else residual = mCategories.at(maxIndex)->GetResidual(input,mDimensions*2,1.0); //mLearnRate); // <- figure out how much residual would occur chosen = true; recentChoice = maxIndex; // } // else // failed the mVigilance test. // { // choices[maxIndex] = -1; // reset, try again // maxIndex = -1; // } } else chosen = true; } // otherwise look again. if (maxIndex > -1) return choices[maxIndex]; else return -1; } int ART::GetChosenCategoryID() { return recentChoice; } double ART::calcDistance(int cat) // use set input and calculate distance to center of specified category { if (cat < mCategories.size()) return mCategories.at(cat)->distance(input); else return -1; } double ART::calcDistance(int thatCategory, int thisCategory) // calculate the distance between the two IDd categories { if (thatCategory > -1 && thatCategory < mCategories.size() && thisCategory > -1 && thisCategory < mCategories.size()) return mCategories.at(thatCategory)->distance(mCategories.at(thisCategory)->GetWeights()); else return -1; } double ART::calcCurvature(int thatCategory, int thisCategory) // calculate the angle between the two IDd categories { if (thatCategory > -1 && thatCategory < mCategories.size() && thisCategory > -1 && thisCategory < mCategories.size()) return mCategories.at(thatCategory)->curvature(mCategories.at(thisCategory)->GetWeights()); else return -1; } const double* ART::getWeights() // return all of the weights of all of our categories { double *weights = (double*)malloc(mCategories.size()*mDimensions*2*sizeof(double)); for (int i = 0; i < mCategories.size(); i++) memcpy(weights+(i*mDimensions*2), mCategories.at(i)->GetWeights(), mDimensions*2*sizeof(double)); return weights; } const double* ART::GetWeights(int index) { if (mDimensions > 0) { double *weights = (double*)malloc(mDimensions*2*sizeof(double)); memcpy(weights, mCategories.at(index)->GetWeights(), mDimensions*2*sizeof(double)); return weights; } else return 0x00; } double ART::GetImportanceSum() { double importance = 0.0; if (inputCount > 0) { #ifdef USING_RECENCY double recencyMax = 1.0; for (int i = 0; i < mRecency.size(); i++) { recencyMax = (mRecency.at(i) > recencyMax ? mRecency.at(i) : recencyMax); } #endif for (int i = 0; i < mCategories.size(); i++) { #ifdef USING_RECENCY importance += choices[i] * (mObservations.at(i) / (double)inputCount) * (1.0 - (mRecency.at(i) / recencyMax)); #else importance += choices[i]; // * mObservations.at(i); // / (double)inputCount); #endif } } return importance / mCategories.size(); } char* ART::Serialize(int &size) { int categorySize; char* categoryData; if (mCategories.size() > 0) { // we always have 1 category, allocated in our constructor categoryData = mCategories.at(0)->Serialize(categorySize); // all categories SHOULD be the same size size = sizeof(int) * 3 + sizeof(double) * 3 + categorySize * mCategories.size(); char* data = (char*)malloc(size); int index = 0; memcpy(data, &mDimensions, sizeof(int)); index += sizeof(int); memcpy(data+index, &mChoice, sizeof(double)); index += sizeof(double); memcpy(data+index, &mLearnRate, sizeof(double)); index += sizeof(double); memcpy(data+index, &mVigilance, sizeof(double)); index += sizeof(double); memcpy(data+index, &categorySize, sizeof(int)); // size of each category index += sizeof(int); categorySize = mCategories.size(); memcpy(data+index, &categorySize, sizeof(int)); // how many categories index += sizeof(int); memcpy(data+index, categoryData, categorySize); // the first one, since we already got it index += categorySize; for (int i = 1; i < mCategories.size(); i++) { // all the other categories categoryData = mCategories.at(i)->Serialize(categorySize); memcpy(data+index, categoryData, categorySize); index += categorySize; } // vector<ResonanceGroup> mResonanceWeights; // vector<double> mObservations; // how many times each category has been seen. trying to measure how "confident" we are in the observation // int inputCount; // how many inputs we have seen // vector<double> mRecency; // double maxRecency; // double *input, *choices; // int recentChoice, choiceSize; // the most recently chosen category, the size of the choices array // double residual; // how much the chosen category changed with the last input/learning step return data; } else return 0x00; } void ART::Deserialize(char* data, int size) { int index = 0; memcpy(&mDimensions, data, sizeof(int)); index += sizeof(int); memcpy(&mChoice, data+index, sizeof(double)); index += sizeof(double); memcpy(&mLearnRate, data+index, sizeof(double)); index += sizeof(double); memcpy(&mVigilance, data+index, sizeof(double)); index += sizeof(double); int categorySize, categoryCount; memcpy(&categorySize, data+index, sizeof(int)); // size of each category index += sizeof(int); memcpy(&categoryCount, data+index, sizeof(int)); // how many categories index += sizeof(int); mCategories.clear(); for (int i = 0; i < categoryCount; i++) mCategories.push_back(new ArtCategory(mDimensions)); for (int i = 0; i < categoryCount; i++) { // all the other categories if (index+categorySize < size) mCategories.at(i)->Deserialize(data+index, categorySize); else break; // error! index += categorySize; } // done! ... without any error checking. }
// --------------------------------------------------------------------------- // Example NewPing library sketch that does a ping about 20 times per second. // --------------------------------------------------------------------------- #include <NewPing.h> #include <Time.h> #include <SimpleTimer.h> #include <string.h> #define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. #define EAR_SENSOR_PIN 5 #define MOUTH_PIN 0 NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. void setup() { Serial.begin(9600); // Open serial monitor at 115200 baud to see ping results. pinMode(MOUTH_PIN, OUTPUT); } SimpleTimer timer; String content = ""; char character; int distanceCounter = 0; int earCounter = 0; void loop() { delay(200); // Wait 200ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). int earSensonrDistance = digitalRead(EAR_SENSOR_PIN); int personDistance = uS / US_ROUNDTRIP_CM; String nc = "NC_"; nc += personDistance; Serial.println(nc); // Serial.println("personDistance = " + personDistance); // unsigned long time1; // unsigned long time2; // if(personDistance < 55){ // if(distanceCounter == 0){ // time1 = millis(); // } // distanceCounter++; // time2 = millis(); // if(distanceCounter == 10 && time1 - time2 <= 1000*10){ // distanceCounter = 0; // Serial.println("NC"); // } // } unsigned long timeEar1; unsigned long timeEar2; if(earSensonrDistance == 0){ Serial.println("START1"); } // while(Serial.available()) { // character = Serial.read(); // content.concat(character); // } // // if (content != "") { // Serial.println(content); // int timerId = -1; // if(strcmp(content.c_str(), "LED4") == 0){ // all led cases // int times = 3 * 1000 / 200; // timerId = timer.setTimer(200, flickerLed, times); // int last = 4 * 1000 / 200; // timer.setTimer(last, turnOffMouth, 1); // }else if(strcmp(content.c_str(), "LED6") == 0){ // int times = 5 * 1000 / 200; // timerId = timer.setTimer(200, flickerLed, times); // int last = 5 * 1000 / 200; // timer.setTimer(last, turnOffMouth, 1); // }else if(strcmp(content.c_str(), "LED7") == 0){ // int times = 6 * 1000 / 200; // timerId = timer.setTimer(200, flickerLed, times); // int last = 7 * 1000 / 200; // timer.setTimer(last, turnOffMouth, 1); // }else if(strcmp(content.c_str(), "SB") == 0){ // timer.deleteTimer(timerId); // turnOffMouth(); // } // } }
#pragma once #include <vector> #include <iostream> #include <utility> #include <list> #include <bitset> class Board { public: typedef std::pair<int, int> mov; typedef std::list<Board> positions; friend class Game; Board(); positions generate() const; mov get_last() const { return last_move; } void set_last(mov n) { last_move = n; } bool get_col() const { return col; } void set_col(bool c) { col = c; } void reverse_col() { col = !col; } bool operator==(const Board& x) const //Fast version (using bitsets) { return (col == x.col) && (table == x.table); } bool operator!=(const Board& x) const { return !((*this) == x); } bool equals(const Board& x) const//slower version of equality operator { return (col == x.col) && (data == x.data); } int num_of_captures() const { auto x = generate_captures(); return x.size(); } int num_of_moves() const { auto x = generate(); return x.size(); } std::vector<std::vector<int>> getBoard() const;//returns the board(without sentinels) friend std::ostream& operator<<(std::ostream& os, const Board& b); static mov convert(int a, int b, int c, int d);//converting matrix coordinates to checkers notation private: void print() const;//for debug purpose only positions generate_moves() const; positions generate_captures() const; positions jump(int i, int j, int a, int b, int en1, int en2, std::vector<std::vector<int>> temp) const; void normalize();//update the bitset std::bitset<32> table; std::vector<std::vector<int>> data = std::vector<std::vector<int>>(10, std::vector<int>(10)); bool col=true;//player's turn, white by default mov last_move{ 1,1 };//the last move made(for debug purpose only) };
#include "GALogger.h" #include <iostream> #include "GADevice.h" #if USE_UWP #include "GAUtilities.h" #include <collection.h> #include <ppltasks.h> #elif USE_TIZEN #include <dlog.h> #else #include "GAUtilities.h" #include <vector> #include <spdlog/sinks/ostream_sink.h> #endif #if USE_UWP #define GALOGGER_PREFIX L"GALogger_" #define DEFAULT_SESSION_NAME GALOGGER_PREFIX L"Session" #define DEFAULT_CHANNEL_NAME GALOGGER_PREFIX L"Channel" #define OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME GALOGGER_PREFIX L"LogFiles" #define LOGGING_ENABLED_SETTING_KEY_NAME GALOGGER_PREFIX L"LoggingEnabled" #define LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME GALOGGER_PREFIX L"LogFileGeneratedBeforeSuspend" #endif namespace gameanalytics { namespace logging { const std::string GALogger::tag = "GameAnalytics"; GALogger::GALogger() { infoLogEnabled = false; #if defined(_DEBUG) // log debug is in dev mode debugEnabled = true; #else debugEnabled = false; #endif #if USE_UWP Windows::Storage::StorageFolder^ gaFolder = concurrency::create_task(Windows::Storage::ApplicationData::Current->LocalFolder->CreateFolderAsync("GameAnalytics", Windows::Storage::CreationCollisionOption::OpenIfExists)).get(); file = concurrency::create_task(gaFolder->CreateFileAsync("ga_log.txt", Windows::Storage::CreationCollisionOption::ReplaceExisting)).get(); #endif #if !USE_UWP && !USE_TIZEN logInitialized = false; #endif } void GALogger::setInfoLog(bool enabled) { GALogger::sharedInstance()->infoLogEnabled = enabled; } void GALogger::setVerboseInfoLog(bool enabled) { GALogger::sharedInstance()->infoLogVerboseEnabled = enabled; } #if !USE_UWP && !USE_TIZEN void GALogger::initializeLog() { GALogger *ga = GALogger::sharedInstance(); if(!ga->logInitialized) { std::string p(device::GADevice::getWritablePath() + utilities::GAUtilities::getPathSeparator() + "ga_log.txt"); std::vector<spdlog::sink_ptr> sinks; sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_st>()); sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_st>(p, 1048576 * 5, 3)); ga->logger = std::make_shared<spdlog::logger>("gameanalytics", begin(sinks), end(sinks)); if(ga->debugEnabled) { ga->logger->flush_on(spdlog::level::debug); spdlog::set_level(spdlog::level::debug); } else { ga->logger->flush_on(spdlog::level::info); spdlog::set_level(spdlog::level::info); } spdlog::register_logger(ga->logger); ga->logInitialized = true; GALogger::i("Log file added under: " + device::GADevice::getWritablePath()); } } void GALogger::customInitializeLog() { GALogger *ga = GALogger::sharedInstance(); spdlog::drop("gameanalytics"); std::string p(device::GADevice::getWritablePath() + utilities::GAUtilities::getPathSeparator() + "ga_log.txt"); std::vector<spdlog::sink_ptr> sinks; sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_st>()); sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_st>(p, 1048576 * 5, 3)); ga->logger = std::make_shared<spdlog::logger>("gameanalytics", begin(sinks), end(sinks)); if(ga->debugEnabled) { ga->logger->flush_on(spdlog::level::debug); spdlog::set_level(spdlog::level::debug); } else { ga->logger->flush_on(spdlog::level::info); spdlog::set_level(spdlog::level::info); } spdlog::register_logger(ga->logger); ga->logInitialized = true; GALogger::i("Log file added under: " + device::GADevice::getWritablePath()); } void GALogger::addCustomLogStream(std::ostream& os) { spdlog::drop("gameanalytics_stream"); GALogger *ga = GALogger::sharedInstance(); auto ostream_sink = std::make_shared<spdlog::sinks::ostream_sink_st>(os); ga->custom_logger = std::make_shared<spdlog::logger>("gameanalytics_stream", ostream_sink); ga->custom_logger->flush_on(spdlog::level::info); spdlog::set_level(spdlog::level::info); spdlog::register_logger(ga->custom_logger); } #endif // i: information logging // // used for: // - non-errors // - initializing, adding event, sending events etc. // - generally small text void GALogger::i(const std::string& format) { GALogger *ga = GALogger::sharedInstance(); if (!ga->infoLogEnabled) { // No logging of info unless in client debug mode return; } std::string message = "Info/" + ga->tag + ": " + format; ga->sendNotificationMessage(message, Info); } // w: warning logging (ALWAYS show) // // used for: // - validation errors // - trying to initialize with wrong keys // - other non-critical void GALogger::w(const std::string& format) { GALogger *ga = GALogger::sharedInstance(); std::string message = "Warning/" + ga->tag + ": " + format; ga->sendNotificationMessage(message, Warning); } // e: error logging (ALWAYS show) // // used for: // - breaking app behaviour // - JSON decoding/encoding errors // - unexpected exceptions // - errors that never should happen void GALogger::e(const std::string& format) { GALogger *ga = GALogger::sharedInstance(); std::string message = "Error/" + ga->tag + ": " + format; ga->sendNotificationMessage(message, Error); } // d: debug logging (show when developing) // // used for: // - development only // - use large debug text like HTTP payload etc. void GALogger::d(const std::string& format) { GALogger *ga = GALogger::sharedInstance(); if (!ga || !ga->debugEnabled) { // No logging of debug unless in full debug logging mode return; } std::string message = "Debug/" + ga->tag + ": " + format; ga->sendNotificationMessage(message, Debug); } // ii: Advanced information logging // // used for: // - Large logs void GALogger::ii(const std::string& format) { GALogger *ga = GALogger::sharedInstance(); if (!ga->infoLogVerboseEnabled) { // No logging of info unless in client debug mode return; } std::string message = "Verbose/" + ga->tag + ": " + format; ga->sendNotificationMessage(message, Info); } void GALogger::sendNotificationMessage(const std::string& message, EGALoggerMessageType type) { #if USE_UWP auto m = ref new Platform::String(utilities::GAUtilities::s2ws(message).c_str()); Platform::Collections::Vector<Platform::String^>^ lines = ref new Platform::Collections::Vector<Platform::String^>(); lines->Append(m); #endif #if !USE_UWP && !USE_TIZEN if(!logInitialized) { initializeLog(); } #endif switch(type) { case Error: #if USE_UWP try { concurrency::create_task(Windows::Storage::FileIO::AppendLinesAsync(file, lines)).wait(); } catch (const std::exception&) { } LogMessageToConsole(m); #elif USE_TIZEN dlog_print(DLOG_ERROR, GALogger::tag.c_str(), message.c_str()); #else try { logger->error(message.c_str()); if(custom_logger) { custom_logger->error(message.c_str()); } } catch (const std::exception&) { } #endif break; case Warning: #if USE_UWP try { concurrency::create_task(Windows::Storage::FileIO::AppendLinesAsync(file, lines)).wait(); } catch (const std::exception&) { } LogMessageToConsole(m); #elif USE_TIZEN dlog_print(DLOG_WARN, GALogger::tag.c_str(), message.c_str()); #else try { logger->warn(message.c_str()); if(custom_logger) { custom_logger->warn(message.c_str()); } } catch (const std::exception&) { } #endif break; case Debug: #if USE_UWP try { concurrency::create_task(Windows::Storage::FileIO::AppendLinesAsync(file, lines)).wait(); } catch (const std::exception&) { } LogMessageToConsole(m); #elif USE_TIZEN dlog_print(DLOG_DEBUG, GALogger::tag.c_str(), message.c_str()); #else try { logger->info(message.c_str()); if(custom_logger) { custom_logger->info(message.c_str()); } } catch (const std::exception&) { } #endif break; case Info: #if USE_UWP try { concurrency::create_task(Windows::Storage::FileIO::AppendLinesAsync(file, lines)).wait(); } catch (const std::exception&) { } LogMessageToConsole(m); #elif USE_TIZEN dlog_print(DLOG_INFO, GALogger::tag.c_str(), message.c_str()); #else try { logger->info(message.c_str()); if(custom_logger) { custom_logger->info(message.c_str()); } } catch (const std::exception&) { } #endif break; } } #if USE_UWP void GALogger::LogMessageToConsole(Platform::Object^ parameter) { auto paraString = parameter->ToString(); auto formattedText = std::wstring(paraString->Data()).append(L"\r\n"); OutputDebugString(formattedText.c_str()); } #endif } }
#ifndef MAINWIDGET_H #define MAINWIDGET_H #include <QWidget> #include<QLabel> #include<QLineEdit> #include<QPushButton> #include<QProgressBar> #include<QSlider> class MainWidget : public QWidget { Q_OBJECT public: MainWidget(QWidget *parent = nullptr); ~MainWidget(); protected: QPushButton *pushButtonDown; QPushButton *pushButtonUp; QProgressBar *progressBar; QSlider *slider; qint32 size; void createWidgets(); void freeMem(); public: void run(); //signals: protected slots: void slotUpVal(); void slotDownVal(); void slotSliderVal(int val); }; #endif // MAINWIDGET_H
// github.com/andy489 #include <iostream> #include <vector> #include <queue> using namespace std; #define INF 100000 struct Edge{ int u, v, w; }; void bel(const vector<Edge>& adj, int n, int s){ vector<int> paths(adj.size(), INF); paths[s] = 0; bool updated = false;; int i, j; for (i = 0; i < n; ++i) { updated = false; for (j = 0; j < (int)adj.size(); ++j) { if (paths[adj[j].u] != INF && paths[adj[j].u] + adj[j].w < paths[adj[j].v]) { paths[adj[j].v] = paths[adj[j].u] + adj[j].w; updated = true; } } if (!updated) { break; } } if (updated && i == n) { cout << "no min path\n"; } else { for (i = 1; i < (int)paths.size(); ++i) { if (i != s) { if (paths[i] == INF) { cout << i << " cannot reach\n"; } else { cout << i << " " <<" path: "<< paths[i] << "\n"; } } } } } int main() { int n, m, u, v, w, i, s; cin >> n >> m; vector<Edge> edges(m); for (i = 0; i < m; ++i) { cin >> u >> v >> w; edges[i] = { u,v,w }; } cin >> s; bel(edges, m, s); return 0; } /* 7 10 3 1 2 3 4 2 4 1 -1 1 5 3 5 4 4 5 6 100 5 7 2 2 5 1 2 1 4 4 5 1 3 */ /* 7 10 3 1 2 3 4 2 4 1 -1 1 5 -10 5 4 4 5 6 100 5 7 2 2 5 1 2 1 4 4 5 1 3 */
/** * @file multiplier754.ccp * @author Luigi Capogrosso * @date 11 Dec 2019 * @copyright 2019 Luigi Capogrosso * @brief <brief> */ #ifndef MULTIPLIER754_RTL_HH #define MULTIPLIER754_RTL_HH #include <systemc.h> //============================================================================== #define SIZE 32 #define EXPONENT_SIZE 8 #define MANTISSA_SIZE 23 //============================================================================== SC_MODULE(multiplier754_RTL) { // FSM states definition. typedef enum { S_0, S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13, S_14, S_15, S_NAN, S_INF, S_ZERO, S_ROUND, S_NORM, S_DENORM, S_END } STATE_T; // Inputs. sc_in< sc_logic > clk; sc_in< sc_logic > rst; sc_in< sc_lv<SIZE> > in_op1; sc_in< sc_lv<SIZE> > in_op2; sc_in< sc_logic > in_rdy; // Outputs. sc_out< sc_lv<SIZE> > out_res; sc_out< sc_logic > out_rdy; // To describe the finite set of states. sc_signal< STATE_T > state; sc_signal< STATE_T > next_state; // Floatig point 754 single precison rapresentation. sc_signal< sc_lv<EXPONENT_SIZE> > e; sc_signal< sc_lv<MANTISSA_SIZE> > m; sc_signal< sc_lv<1> > s; // Temporary signals for calculation sc_signal< sc_lv<MANTISSA_SIZE + 1> > m1; sc_signal< sc_lv<MANTISSA_SIZE + 1> > m2; sc_signal< sc_lv<(MANTISSA_SIZE + 1) * 2> > tmp_m; sc_signal< sc_lv<EXPONENT_SIZE + 1> > tmp_e; // FSM. void fsm(); // Datapath. void datapath(); SC_CTOR(multiplier754_RTL) { SC_METHOD(fsm); sensitive_pos << clk; sensitive << rst; SC_METHOD(datapath); sensitive << next_state; }; }; //============================================================================== #endif
#include "KoopmanCharacter.h" #include "Player.h" std::shared_ptr<Character> KoopmanCharacter::Create(const std::string name, int order) { std::shared_ptr<Character> character(new KoopmanCharacter(name, order)); return std::move(character); } int KoopmanCharacter::CollectCash() { if (ownedBy) { actionPreformed = true; return ownedBy->BuildingsWithColor(Color()) + 1; } return 1; } KoopmanCharacter::~KoopmanCharacter() { }
#include<stdlib.h> #include<pthread.h> #include<jni.h> #include<android/log.h> #include "com_example_ndktest_CallbackTest.h" #define LOG_TAG "jni" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) jmethodID mid; jclass objclass; jobject mobj; pthread_t thread; JavaVM *m_vm; //初始化的时候会调进来一次,在这个方法里持有jvm的引用 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved){ m_vm=vm; JNIEnv* env = NULL; jint result = -1; if(m_vm){ LOGD("m_vm init success"); }else{ LOGD("m_vm init failed"); } if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_4) != JNI_OK){ return result; } return JNI_VERSION_1_4; } JNIEnv* getJNIEnv(int* needsDetach){ JNIEnv* env = NULL; jint result = -1; if ((*m_vm)->GetEnv(m_vm, (void**) &env, JNI_VERSION_1_4) != JNI_OK){ int status = (*m_vm)->AttachCurrentThread(m_vm, &env, 0); if (status < 0){ LOGD("failed to attach current thread"); return NULL; } *needsDetach = 1; } LOGD("GetEnv Success"); return env; } void *thread_run(){ LOGD("thread start"); int needsDetach; JNIEnv *evn=getJNIEnv(&needsDetach); LOGD("start noop callback"); int i; for(i = 0; i < 100; i++){ jstring jstr = (*evn) -> NewStringUTF(evn, "I am Fengfei"); LOGD("invoke callback"); (*evn)->CallVoidMethod(evn, mobj, mid, jstr); jthrowable exception = (*evn)->ExceptionOccurred(evn); if (exception) { (*evn)->ExceptionDescribe(evn); } sleep(2); } if(needsDetach) (*m_vm)->DetachCurrentThread(m_vm); } JNIEXPORT void JNICALL Java_com_example_ndktest_CallbackTest_start(JNIEnv *evn, jobject object){ LOGD("call start"); //在子线程中不能这样用 //jclass tclass = (*evn)->FindClass(evn, "com/example/ndktest/CallbackTest"); //这种写法可以用在子线程中 objclass=(*evn)->GetObjectClass(evn, object); mid = (*evn)->GetMethodID(evn, objclass, "callback", "(Ljava/lang/String;)V"); //JNI 函数参数中 jobject 或者它的子类,其参数都是 local reference。Local reference 只在这个 JNI函数中有效,JNI函数返回后,引用的对象就被释放,它的生命周期就结束了。若要留着日后使用,则需根据这个 local reference 创建 global reference。Global reference 不会被系统自动释放,它仅当被程序明确调用 DeleteGlobalReference 时才被回收。(JNI多线程机制) mobj=(*evn)->NewGlobalRef(evn, object); pthread_create(&thread, NULL, thread_run, NULL); }
#pragma once #include "AObject.h" #include "TDataTypes.h" class RAnimationSequence: public AObject { DECLARE_CLASS(RAnimationSequence,) public: class RBoneSequence { public: RBoneSequence(RAnimationSequence* Seq) { AnimSequenceRef = Seq; } TString BoneName; struct POSKEY { TVector3 Pos; float Time; }; struct ROTKEY { TQuaternion Rot; float Time; }; TArray<POSKEY> PosKeys; TArray<ROTKEY> RotKeys; RAnimationSequence* AnimSequenceRef; TVector3 GetPosKey(unsigned int InFrame) { if (PosKeys.Size() < 2) { return TVector3(0, 0, 0); } if (InFrame == 0) { return PosKeys(0).Pos; } int Idx = -1; for (unsigned int i = 0; i < PosKeys.Size(); ++i) { POSKEY& PosKey = PosKeys(i); if (PosKey.Time > InFrame) { Idx = i; break; } } if (Idx == 0) { //Idx = (int)PosKeys.Size() - 1; //float t = 1.0f - (InFrame + AnimSequenceRef->EndFrame*AnimSequenceRef->TickPerFrame - PosKeys(Idx).Time)/((AnimSequenceRef->EndFrame*AnimSequenceRef->TickPerFrame - PosKeys(Idx).Time) + PosKeys(0).Time); //return (PosKeys(Idx).Pos*t + PosKeys(0).Pos*(1.0f - t)); return PosKeys(0).Pos; } else if (Idx == -1) { Idx = (int) PosKeys.Size() - 1; //float t = 1.0f - (InFrame - PosKeys(Idx).Time)/((AnimSequenceRef->EndFrame*AnimSequenceRef->TickPerFrame - PosKeys(Idx).Time) + PosKeys(0).Time); //return (PosKeys(Idx).Pos*t + PosKeys(0).Pos*(1.0f - t)); return PosKeys(Idx).Pos; } float t = 1.0f - (InFrame - PosKeys(Idx - 1).Time) / (PosKeys(Idx).Time - PosKeys(Idx - 1).Time); return (PosKeys(Idx - 1).Pos * t + PosKeys(Idx).Pos * (1.0f - t)); } TQuaternion GetRotKey(unsigned int InFrame) { if (RotKeys.Size() < 2) { return TQuaternion(); } if (InFrame == 0) { return RotKeys(0).Rot; } int Idx = -1; for (unsigned int i = 0; i < RotKeys.Size(); ++i) { ROTKEY& RotKey = RotKeys(i); if (RotKey.Time > InFrame) { Idx = i; break; } } if (Idx == 0) { //Idx = (int)RotKeys.Size() - 1; //float t = (InFrame + AnimSequenceRef->EndFrame*AnimSequenceRef->TickPerFrame - RotKeys(Idx).Time)/((AnimSequenceRef->EndFrame*AnimSequenceRef->TickPerFrame - RotKeys(Idx).Time) + RotKeys(0).Time); //return TQuaternion::Slerp(RotKeys(Idx).Rot, RotKeys(0).Rot, t); return RotKeys(0).Rot; } else if (Idx == -1) { Idx = (int) RotKeys.Size() - 1; //float t = (InFrame - RotKeys(Idx).Time)/(AnimSequenceRef->EndFrame*AnimSequenceRef->TickPerFrame - RotKeys(Idx).Time); //return TQuaternion::Slerp(RotKeys(Idx).Rot, RotKeys(0).Rot, t); return RotKeys(Idx).Rot; } float t = (InFrame - RotKeys(Idx - 1).Time) / (RotKeys(Idx).Time - RotKeys(Idx - 1).Time); return TQuaternion::Slerp(RotKeys(Idx - 1).Rot, RotKeys(Idx).Rot, t); } }; ~RAnimationSequence() { for (unsigned int i = 0; i < AnimationBoneSequences.Size(); ++i) delete AnimationBoneSequences(i); AnimationBoneSequences.Clear(true); } TArray<RBoneSequence*> AnimationBoneSequences; }; typedef RAnimationSequence::RBoneSequence RAnimationBoneSequence;
#ifndef VIEWER_WINDOW_H #define VIEWER_WINDOW_H #include <QMainWindow> #include <QList> #include <QFileDialog> #include <QMessageBox> #include <QtAlgorithms> #include <QPushButton> #include <QString> #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QTextStream> #include <QLineEdit> #include <QIcon> #include "RobotThread.h" namespace data_server { class ViewerWindow : public QWidget { Q_OBJECT public: ViewerWindow(int argc, char** argv, QWidget * parent = 0); private: QVBoxLayout *mainLayout; QPushButton *p_closeButton; QPushButton *p_saveButton; RobotThread m_RobotThread; }; }//namespace server #endif
/* * 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. * */ #ifndef FLUXNODE_CONNECTIONMANAGER_H #define FLUXNODE_CONNECTIONMANAGER_H #include <flux/types> #include <flux/List> #include <flux/Map> #include "ServiceWorker.h" #include "Visit.h" namespace fluxnode { using namespace flux; class ClientConnection; class ConnectionManager: public Object { public: static Ref<ConnectionManager> create(int serviceWindow = 30); inline ClosedConnections *closedConnections() const { return closedConnections_; } void cycle(); void prioritize(ClientConnection *client); private: ConnectionManager(int serviceWindow); typedef Map<uint64_t, int> ConnectionCounts; typedef List< Ref<Visit> > Visits; Ref<ClosedConnections> closedConnections_; Ref<ConnectionCounts> connectionCounts_; Ref<Visits> visits_; int serviceWindow_; }; } // namespace fluxnode #endif // FLUXNODE_CONNECTIONMANAGER_H
#include<iostream> using namespace std; int evenoddnumbers(int j , int k) { if (j>k) { return 1; } else { cout <<j<< endl; j+=2; evenoddnumbers(j ,k); } } int main () { int j ,k; cout <<"what are the number between which u want numbers to print? "; cin>> j >>k; if(j%2==0) { j=j; } else { j+=1; } cout << "even numbers in the given range are -" << endl; evenoddnumbers(j ,k); if(j%2==0) { j+=1; } else { j=j; } cout << "odd numbers in the given range are -" << endl; evenoddnumbers(j ,k); }
// main.c // // Created: 17 OCT 2010 // Author : Daniel M. Klein // #include <stdlib.h> #include <stdio.h> #include <string.h> extern "C" { #include "common.h" #include "named_tag.h" #include "callbacks.h" #include "tag_list.h" #include "tag_byte_array.h" #include "main.h" } #include <QtGui/QApplication> #include "chunks.h" #include "mainwindow.h" int main( int argc, char** argv ) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include <iostream> using namespace std; bool isPowerOfThree(int n) { int val = 3; while (true) { val *= 3; if (val == n) return true; else if (val > n) return false; } } int main() { int n = 27; cout << isPowerOfThree(n) << endl; return 0; }
#include <cstdlib> #include <cstdio> double EPS = 1e-10; // gosa double add(double a, double b){ if (abs(a+b) < EPS * (abs(a) + abs(b))) return 0; return a+b; } //2 dimensions vector struct P { double x, y; P(){}; P(double x, double y) : x(x), y(y) { } P operator + (P p) { return P(add(x, p.x), add(y, p.y)); } P operator - (P p) { return P(add(x, -p.x), add(y, -p.y)); } P operator * (double d) { return P(x*d, y*d); } double dot(P p) {// naiseki return add(x * p.x, y * p.y); } double det(P p) {// gaiseki return add(x * p.y, -y *p.x); } }; // decision if q is on segment p1-p2 bool on_seg(P p1, P p2, P q){ return (p1 - q).det(p2 - q) == 0 && (p1 - q).dot(p2 - q) <= 0; } // intersecting point of lines p1-p2 and q1-q2 P intersection(P p1, P p2, P q1, P q2){ return p1 + (p2 - p1) * ((q2 - q1).det(q1 - p1) / (q2 - q1).det(p2 - p1)); } const int MAX_N = 100; const int MAX_M = 100; //INPUT int n = 4; P p[MAX_N] = { P(0,4), P(0,1), P(1,2), P(1,0)}, q[MAX_N] = { P(4,1), P(2,3), P(3,4), P(2,1)}; int m = 4; int a[MAX_M] = {1,1,2,2}, b[MAX_M] = {2,4,3,4}; bool g[MAX_N][MAX_N]; // graph on connection void solve(){ for (int i=0; i<n; i++){ g[i][i] = true; for (int j=0; j<i; j++){ // do bar i & j have a common point? if ((p[i] - q[i]).det(p[j] - q[j]) == 0) { // case of parallel g[i][j] = g[j][i] = on_seg(p[i], q[i], p[j]) || on_seg(p[i], q[i], q[j]) || on_seg(p[j], q[j], p[i]) || on_seg(p[j], q[j], q[i]); } else { // not parallel P r = intersection(p[i], q[i], p[j], q[j]); g[i][j] = g[j][i] = on_seg(p[i], q[i], r) && on_seg(p[j], q[j], r); } } } // warshall-froyd to decide connectivity for (int k=0; k < n; k++){ for (int i=0; i < n; i++){ for (int j=0; j < n; j++){ g[i][j] |= g[i][k] && g[k][j]; } } } for (int i=0; i<m; i++){ puts(g[a[i] - 1][b[i] - 1] ? "CONNECTED" : "NOT CONNECTED"); } } int main(){ n = 4; //p[MAX_N] = { P(0,4), P(0,1), P(1,2), P(1,0)}; //q[MAX_N] = { P(4,1), P(2,3), P(3,4), P(2,1)}; m = 4; //a[MAX_M] = {1,1,2,2}, b[MAX_M] = {2,4,3,4}; solve(); }
// // Copyright (C) 2017 Ruslan Manaev (manavrion@yandex.com) // This file is part of the Modern Expert System // #include "pch.h" #include "OneResultPage.xaml.h" #include "ProgramController.h" using namespace mes_base; using namespace modern_expert_system; using namespace concurrency; using namespace Platform; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::Activation; using namespace Windows::ApplicationModel::Core; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI; using namespace Windows::UI::Core; using namespace Windows::UI::ViewManagement; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Interop; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::Data::Json; using namespace Windows::Storage; using namespace Windows::UI::Xaml::Navigation; using namespace concurrency; using namespace Platform; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::Activation; using namespace Windows::ApplicationModel::Core; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Storage; using namespace Windows::Storage::Pickers; using namespace Windows::Storage::Provider; using namespace Windows::Storage::Streams; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::UI::Xaml::Media::Imaging; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 OneResultPage::OneResultPage() { InitializeComponent(); } void OneResultPage::OnNavigatedTo(NavigationEventArgs^ e) { SessionStore^ store = (SessionStore^)e->Parameter; Item item = store->GetRefSession().GetConstRefSessionItems().front(); //ProjectImage-> /*create_task(ProgramController::GetImage(item.GetImageId())).then([=](StorageFile^ file) { if (file == nullptr) { return; } create_task(file->OpenAsync(FileAccessMode::Read)).then([=](IRandomAccessStream^ stream) { CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync( CoreDispatcherPriority::Normal, ref new DispatchedHandler([=]() { BitmapImage^ bitmapImage = ref new BitmapImage(); bitmapImage->SetSource(stream); ProjectImage->Source = bitmapImage; })); }); });*/ NameTextBlock->Text = ref new String(item.GetName().c_str()); DescTextBlock->Text = ref new String(item.GetDescription().c_str()); }
#include <math.h> #include <conio.h> #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <string.h> typedef struct tipo_no no; struct tipo_no { int info; struct tipo_no *prox; }; void insereInicio (int n, no **inicio); int main () { setlocale (LC_ALL, "Portuguese"); no *lista = NULL; insereInicio (3, &lista); insereInicio (2, &lista); insereInicio (1, &lista); return 0; } void insereInicio (int n, no **inicio) { no *aux = (no*) malloc(sizeof(no)); if (aux) { aux -> info = n; if (!(*inicio)) { *inicio = aux; (*inicio)->prox = NULL; } else { aux -> prox = *inicio; *inicio = aux; } } else { printf ("Heap cheio!\n"); } return; }
#include <Wire.h> #include <Adafruit_MotorShield.h> #include "utility/Adafruit_MS_PWMServoDriver.h" //stuff to run the motors #include <PS2X_lib.h> //backend stuff to detect the controller, can be downloaded fram this site: http://www.billporter.info/2010/06/05/playstation-2-controller-arduino-library-v1-0/ PS2X ps2x; // create PS2 Controller Class int error = 0; //defining different variables for use later byte type = 0; byte vibrate = 0; Adafruit_MotorShield AFMS = Adafruit_MotorShield(); //defining motor shield Adafruit_DCMotor *myMotor = AFMS.getMotor(1); //defining motors Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2); int turn = 80; void setup() { // put your setup code here, to run once: Serial.begin(57600); error = ps2x.config_gamepad(13, 11, 10, 12, true, true); //setup pins and settings: GamePad(clock (blue), command (orange), attention (yellow), data (pink)) check for error AFMS.begin(); //telling the motor shield to start Serial.println("motor shield activated"); if (error == 0) { //the serial monitor output if the gamepad was found Serial.println("Found Controller, configured successful"); } else if (error == 1) //serial monitor output if the controller isn't found, which would set the error variable to '1' Serial.println("No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips"); else if (error == 2) //serial monitor output if the controller is not working properly, which would set the error variable to '2' Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips"); else if (error == 3) //serial monitor output if the controller can't detect pressure, error variable '3' Serial.println("Controller refusing to enter Pressures mode, may not support it. "); //Serial.print(ps2x.Analog(1), HEX); type = ps2x.readType(); //naming different types switch (type) { case 0: Serial.println("Unknown Controller type"); break; case 1: Serial.println("DualShock Controller Found"); break; case 2: Serial.println("GuitarHero Controller Found"); break; } //error = 0; //type = 1; } void loop() { // put your main code here, to run repeatedly: if (error == 1) //skip loop if no controller found return; else { //DualShock Controller ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed if (ps2x.Button(PSB_PAD_UP)) { //detect when one of the D-Pad buttons are pressed and run the motors accordingly Serial.print("UP held this hard: "); Serial.println(ps2x.Analog(PSAB_PAD_UP), DEC); myMotor->run(FORWARD); myOtherMotor->run(FORWARD); myMotor->setSpeed(turn * 1.1); myOtherMotor->setSpeed(turn); } if (ps2x.Button(PSB_PAD_RIGHT)) { Serial.print("RIGHT held this hard: "); Serial.println(ps2x.Analog(PSAB_PAD_RIGHT), DEC); myMotor->run(FORWARD); myOtherMotor->run(BACKWARD); myMotor->setSpeed(turn / 2); myOtherMotor->setSpeed(turn / 2); } if (ps2x.Button(PSB_PAD_LEFT)) { Serial.print("LEFT held this hard: "); Serial.println(ps2x.Analog(PSAB_PAD_LEFT), DEC); myMotor->run(BACKWARD); myOtherMotor->run(FORWARD); myMotor->setSpeed(turn / 2); myOtherMotor->setSpeed(turn / 2); } if (ps2x.Button(PSB_PAD_DOWN)) { Serial.print("DOWN held this hard: "); Serial.println(ps2x.Analog(PSAB_PAD_DOWN), DEC); myMotor->run(BACKWARD); myOtherMotor->run(BACKWARD); myMotor->setSpeed(turn * 1.1); myOtherMotor->setSpeed(turn); } if (ps2x.ButtonReleased(PSB_PAD_UP)) { //code to turn the wheels off once the button is released Serial.println("UP just released"); myMotor->run(RELEASE); myOtherMotor->run(RELEASE); } if (ps2x.ButtonReleased(PSB_PAD_RIGHT)) { Serial.println("RIGHT just released"); myMotor->run(RELEASE); myOtherMotor->run(RELEASE); } if (ps2x.ButtonReleased(PSB_PAD_LEFT)) { Serial.println("LEFT just released"); myMotor->run(RELEASE); myOtherMotor->run(RELEASE); } if (ps2x.ButtonReleased(PSB_PAD_DOWN)) { Serial.println("DOWN just released"); myMotor->run(RELEASE); myOtherMotor->run(RELEASE); } vibrate = ps2x.Analog(PSAB_R1); //this will set the large motor vibrate speed based on //how hard you press R1 } delay(50); }
#include "Box.h" Box::Box():_center(0.0f,0.0f,0.0f),_extent(1.0f,1.0f,1.0f),_scale(1.0f,1.0f,1.0f) { _vertexs.resize(8); }
#include<bits/stdc++.h> #include<limits.h> using namespace std; #define mod 1000000007 #define si(x) scanf("%d", &x) #define sll(x) scanf("%lld", &x) #define pi(x) printf("%d\n", x) #define pll(x) printf("%lld\n", x) #define ii pair<int, int> #define vi vector<int> #define vii vector<pair<int, int> > #define adjList vector<vector<int> > #define ll long long int #define pb push_back #define mp make_pair #define fi first #define se second #define rep(i, z, q) for(i = z; i < q; i++) #define rev(i, z, q) for(i = z; i > q; i--) #define gc getchar_unlocked ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return a * (b / gcd(a, b)); } ll power(ll a,ll b) { ll ans = 1; while(b > 0){ if(b & 1) ans = ((ans % mod) *(a % mod)) % mod; a=((a % mod)*(a % mod)) % mod; b >>= 1; } return ans; } int read_int() { char c = gc(); while(c<'0' || c>'9') c = gc(); int ret = 0; while(c>='0' && c<='9') { ret = 10 * ret + c - 48; c = gc(); } return ret; } int a[30010], query[200010], c[1000010], n, answer = 0; struct node { int l, r, a; }; bool compare(node A, node B) { return A.r < B.r; } vector< vector <node> > adj; inline void add(int ind) { if(ind <= 0 || ind >= n+1) return; int temp = a[ind]; ++c[temp]; if(c[temp] == 1) answer++; return; } inline void remove(int ind) { if(ind <= 0 || ind >= n+1) return; int temp = a[ind]; --c[temp]; if(c[temp] == 0) answer--; return; } int main() { int i, q, l, r; int m = INT_MIN; n = read_int(); rep(i, 1, n+1) { a[i] = read_int(); m = max(m, a[i]); } int temp = sqrt(n); int size = (n/temp) + 3; adj.resize(size); q = read_int(); rep(i, 1, q+1) { l = read_int(); r = read_int(); node T; T.l = l; T.r = r; T.a = i; if(l % temp == 0) adj[l/temp].pb(T); else adj[l/temp + 1].pb(T); } rep(i, 1, size) sort(adj[i].begin(), adj[i].end(), compare); rep(i, 1, size) { answer = 0; memset(c, 0, (m+2)*sizeof(int)); int start = (i-1)*temp; int end = start; for(auto it : adj[i]) { int L = it.l; int R = it.r; while(end <= R) { add(end); end++; } while(start < L) { remove(start); start++; } while(start > L) { add(start-1); start--; } query[it.a] = answer; } } rep(i, 1, q+1) pi(query[i]); return 0; }
/** * @file multiplier754.ccp * @author Luigi Capogrosso * @date 11 Dec 2019 * @copyright 2019 Luigi Capogrosso * @brief <brief> */ //============================================================================== void multiplier754_cpp(float op1, float op2, float * res) { *res = op1 * op2; } //==============================================================================
// // Created by zanbo on 2020/3/6. // class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int> myMap; vector<int> res; for(int x:nums) { myMap[x]++; } // 优先队列 最小堆 priority_queue< pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>> > q; for(auto val:myMap) { q.push(make_pair(val.second,val.first)); if(q.size()>k) q.pop(); } while(!q.empty()) { res.push_back(q.top().second); q.pop(); } return res; } };
// // Copyright (c) 2017-2019 Native Instruments GmbH, Berlin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include <ni/media/audio/iotools.h> #include <ni/media/test_helper.h> #include <boost/locale.hpp> #include <boost/predef/os.h> #include <boost/preprocessor/stringize.hpp> #include <boost/range/adaptor/filtered.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/range/iterator_range.hpp> #include <boost/tokenizer.hpp> #include <codecvt> #include <cstdlib> #include <iterator> //-------------------------------------------------------------------------------------------------------------------- namespace { bool init() { #if BOOST_OS_WINDOWS boost::filesystem::path::imbue( std::locale( std::locale(), new std::codecvt_utf8_utf16<wchar_t>() ) ); #endif return true; } const bool initialized = init(); auto supported_files( const boost::filesystem::path& root_path, boost::optional<audio::ifstream_info::container_type> container ) { using namespace boost::adaptors; using namespace boost::filesystem; auto can_read_file = [container]( const auto& p ) { return container ? audio::can_read_file( p, {*container} ) : audio::can_read_file( p ); }; recursive_directory_iterator beg( root_path ), end; return boost::make_iterator_range( beg, end ) | transformed( []( const path& p ) { return p.string(); } ) | filtered( can_read_file ); } //---------------------------------------------------------------------------------------------------------------------- std::vector<std::string> collect_supported_files( const boost::filesystem::path& root_path, boost::optional<audio::ifstream_info::container_type> container ) { using Files = std::vector<std::string>; return boost::copy_range<Files>( supported_files( root_path, container ) ); } } // namespace //---------------------------------------------------------------------------------------------------------------------- boost::filesystem::path test_files_input_path() { return {BOOST_PP_STRINGIZE( NI_MEDIA_TEST_FILES_PATH )}; } //---------------------------------------------------------------------------------------------------------------------- boost::filesystem::path test_files_output_path() { return {BOOST_PP_STRINGIZE( NI_MEDIA_OUTPUT_FILES_PATH )}; } //---------------------------------------------------------------------------------------------------------------------- TestFiles user_files( boost::optional<audio::ifstream_info::container_type> container ) { return ::testing::ValuesIn( collect_supported_files( test_files_input_path() / "user_files", container ) ); } //---------------------------------------------------------------------------------------------------------------------- TestFiles reference_files( boost::optional<audio::ifstream_info::container_type> container ) { return ::testing::ValuesIn( collect_supported_files( test_files_input_path() / "reference_files", container ) ); } //---------------------------------------------------------------------------------------------------------------------- TestFiles fuzz_files( boost::optional<audio::ifstream_info::container_type> container ) { return ::testing::ValuesIn( collect_supported_files( test_files_input_path() / "fuzz_files", container ) ); } //----------------------------------------------------------------------------------------------------------------------
#include<stdio.h> #include<string.h> int main() { int a = 10, b = 5, c = 5; int e; e = a == (b + c); printf("%d", e); }
#include "raw_resource.h" namespace GLPlay { void RawResource::SetData(std::vector<unsigned char> & data) { data_ = std::move(data); } const std::vector<unsigned char> & RawResource::GetData() const { return data_; } }
#include "StringUtils.h" #include "Log.h" #include "Testing.h" #include "Crypt.h" #include "FileSystem.h" #include "Threading.h" #include "UcsTables_Include.h" uint _str::length() { return (uint) s.length(); } bool _str::empty() { return s.empty(); } bool _str::compareIgnoreCase( const string& r ) { if( s.length() != r.length() ) return false; for( size_t i = 0; i < s.length(); i++ ) if( tolower( s[ i ] ) != tolower( r[ i ] ) ) return false; return true; } bool _str::compareIgnoreCaseUtf8( const string& r ) { if( s.length() != r.length() ) return false; return _str( s ).lowerUtf8() == _str( r ).lowerUtf8(); } bool _str::startsWith( char r ) { return s.length() >= 1 && s.front() == r; } bool _str::startsWith( const string& r ) { return s.length() >= r.length() && s.compare( 0, r.length(), r ) == 0; } bool _str::endsWith( char r ) { return s.length() >= 1 && s.back() == r; } bool _str::endsWith( const string& r ) { return s.length() >= r.length() && s.compare( s.length() - r.length(), r.length(), r ) == 0; } bool _str::isValidUtf8() { for( size_t i = 0; i < s.length();) { uint length; uint ucs = utf8::Decode( s.c_str() + i, &length ); if( !utf8::IsValid( ucs ) ) return false; i += length; } return true; } uint _str::lengthUtf8() { uint length = 0; const char* str = s.c_str(); while( *str ) length += ( ( *str++ & 0xC0 ) != 0x80 ); return length; } _str& _str::substringUntil( char separator ) { size_t pos = s.find( separator ); if( pos != string::npos ) s = s.substr( 0, pos ); return *this; } _str& _str::substringUntil( string separator ) { size_t pos = s.find( separator ); if( pos != string::npos ) s = s.substr( 0, pos ); return *this; } _str& _str::substringAfter( char separator ) { size_t pos = s.find( separator ); if( pos != string::npos ) s = s.substr( pos + 1 ); else s.erase(); return *this; } _str& _str::substringAfter( string separator ) { size_t pos = s.find( separator ); if( pos != string::npos ) s = s.substr( pos + separator.length() ); else s.erase(); return *this; } _str& _str::trim() { // Left trim size_t l = s.find_first_not_of( " \n\r\t" ); if( l == string::npos ) { s.erase(); } else { if( l > 0 ) s.erase( 0, l ); // Right trim size_t r = s.find_last_not_of( " \n\r\t" ); if( r < s.length() - 1 ) s.erase( r + 1 ); } return *this; } _str& _str::erase( char what ) { s.erase( std::remove( s.begin(), s.end(), what ), s.end() ); return *this; } _str& _str::erase( char begin, char end ) { while( true ) { size_t begin_pos = s.find( begin ); if( begin_pos == string::npos ) break; size_t end_pos = s.find( end, begin_pos + 1 ); if( end_pos == string::npos ) break; s.erase( begin_pos, end_pos - begin_pos + 1 ); } return *this; } _str& _str::replace( char from, char to ) { std::replace( s.begin(), s.end(), from, to ); return *this; } _str& _str::replace( char from1, char from2, char to ) { replace( string( { from1, from2 } ), string( { to } ) ); return *this; } _str& _str::replace( const string& from, const string& to ) { size_t pos = 0; while( ( pos = s.find( from, pos ) ) != std::string::npos ) { s.replace( pos, from.length(), to ); pos += to.length(); } return *this; } _str& _str::lower() { std::transform( s.begin(), s.end(), s.begin(), tolower ); return *this; } _str& _str::upper() { std::transform( s.begin(), s.end(), s.begin(), toupper ); return *this; } _str& _str::lowerUtf8() { for( size_t i = 0; i < s.length();) { uint length; uint ucs = utf8::Decode( s.c_str() + i, &length ); ucs = utf8::Lower( ucs ); char buf[ 4 ]; uint new_length = utf8::Encode( ucs, buf ); s.replace( i, length, buf, new_length ); i += new_length; } return *this; } _str& _str::upperUtf8() { for( size_t i = 0; i < s.length();) { uint length; uint ucs = utf8::Decode( s.c_str() + i, &length ); ucs = utf8::Upper( ucs ); char buf[ 4 ]; uint new_length = utf8::Encode( ucs, buf ); s.replace( i, length, buf, new_length ); i += new_length; } return *this; } StrVec _str::split( char divider ) { StrVec result; std::stringstream ss( s ); string entry; while( std::getline( ss, entry, divider ) ) { entry = _str( entry ).trim(); if( !entry.empty() ) result.push_back( entry ); } return result; } IntVec _str::splitToInt( char divider ) { IntVec result; std::stringstream ss( s ); string entry; while( std::getline( ss, entry, divider ) ) { entry = _str( entry ).trim(); if( !entry.empty() ) result.push_back( _str( entry ).toInt() ); } return result; } bool _str::isNumber() { if( s.empty() ) return false; trim(); if( s.empty() ) return false; if( s.empty() || ( !isdigit( s[ 0 ] ) && s[ 0 ] != '-' && s[ 0 ] != '+' ) ) return false; char* p; strtol( s.c_str(), &p, 10 ); return *p == 0; } int _str::toInt() { return (int) toInt64(); } uint _str::toUInt() { return (uint) toInt64(); } int64 _str::toInt64() { trim(); if( s.length() >= 2 && s[ 0 ] == '0' && ( s[ 1 ] == 'x' || s[ 1 ] == 'X' ) ) return strtoll( s.substr( 2 ).c_str(), nullptr, 16 ); return strtoll( s.c_str(), nullptr, 10 ); } uint64 _str::toUInt64() { trim(); if( s.length() >= 2 && s[ 0 ] == '0' && ( s[ 1 ] == 'x' || s[ 1 ] == 'X' ) ) return strtoull( s.substr( 2 ).c_str(), nullptr, 16 ); return strtoull( s.c_str(), nullptr, 10 ); } float _str::toFloat() { return (float) atof( s.c_str() ); } double _str::toDouble() { return atof( s.c_str() ); } bool _str::toBool() { if( compareIgnoreCase( "true" ) ) return true; if( compareIgnoreCase( "false" ) ) return false; return toInt() != 0; } _str& _str::formatPath() { trim(); normalizePathSlashes(); // Erase first './' while( s[ 0 ] == '.' && s[ 1 ] == '/' ) s.erase( 0, 2 ); // Skip first '../' uint back_count = 0; while( s.length() >= 3 && s[ 0 ] == '.' && s[ 1 ] == '.' && s[ 2 ] == '/' ) { back_count++; s.erase( 0, 3 ); } // Replace '/./' to '/' while( true ) { size_t pos = s.find( "/./" ); if( pos == string::npos ) break; s.replace( pos, 3, "/" ); } // Replace '//' to '/' while( true ) { size_t pos = s.find( "//" ); if( pos == string::npos ) break; s.replace( pos, 2, "/" ); } // Replace 'folder/../' to '/' while( true ) { size_t pos = s.find( "/../" ); if( pos == string::npos || pos == 0 ) break; size_t pos2 = s.rfind( '/', pos - 1 ); if( pos2 == string::npos ) break; s.erase( pos2 + 1, pos - pos2 - 1 + 3 ); } // Apply skipped '../' for( uint i = 0; i < back_count; i++ ) s.insert( 0, "../" ); return *this; } _str& _str::extractDir() { formatPath(); size_t pos = s.find_last_of( '/' ); if( pos != string::npos ) s = s.substr( 0, pos + 1 ); else if( !s.empty() && s.back() != '/' ) s += "/"; return *this; } _str& _str::extractLastDir() { formatPath(); extractDir(); if( !s.empty() ) s.pop_back(); size_t pos = s.find_last_of( '/' ); if( pos != string::npos ) s = s.substr( pos + 1 ); return *this; } _str& _str::extractFileName() { formatPath(); size_t pos = s.find_last_of( '/' ); if( pos != string::npos ) s = s.substr( pos + 1 ); return *this; } _str& _str::getFileExtension() { size_t dot = s.find_last_of( '.' ); s = ( dot != string::npos ? s.substr( dot + 1 ) : "" ); lower(); return *this; } _str& _str::eraseFileExtension() { size_t dot = s.find_last_of( '.' ); if( dot != string::npos ) s = s.substr( 0, dot ); return *this; } _str& _str::combinePath( const string& path ) { extractDir(); if( !s.empty() && s.back() != '/' && ( path.empty() || path.front() != '/' ) ) s += "/"; s += path; formatPath(); return *this; } _str& _str::forwardPath( const string& relative_dir ) { string dir = _str( *this ).extractDir(); string name = _str( *this ).extractFileName(); s = dir + relative_dir + name; formatPath(); return *this; } _str& _str::resolvePath() { ResolvePathInplace( s ); return *this; } _str& _str::normalizePathSlashes() { NormalizePathSlashesInplace( s ); return *this; } _str& _str::normalizeLineEndings() { replace( '\r', '\n', '\n' ); replace( '\r', '\n' ); return *this; } #ifdef FO_WINDOWS _str& _str::parseWideChar( const wchar_t* str ) { int len = (int) wcslen( str ); if( len ) { char* buf = (char*) alloca( UTF8_BUF_SIZE( len ) ); int r = WideCharToMultiByte( CP_UTF8, 0, str, len, buf, len * 4, nullptr, nullptr ); s += string( buf, r ); } return *this; } std::wstring _str::toWideChar() { if( s.empty() ) return L""; wchar_t* buf = (wchar_t*) alloca( s.length() * sizeof( wchar_t ) * 2 ); int len = MultiByteToWideChar( CP_UTF8, 0, s.c_str(), (int) s.length(), buf, (int) s.length() ); return std::wstring( buf, len ); } #endif #if defined ( FONLINE_SERVER ) || defined ( FONLINE_EDITOR ) # include "DataBase.h" #endif static Mutex HashNamesLocker; static map< hash, string > HashNames; hash _str::toHash() { if( s.empty() ) return 0; normalizePathSlashes(); trim(); if( s.empty() ) return 0; // Calculate hash hash h = Crypt.MurmurHash2( (const uchar*) s.c_str(), (uint) s.length() ); if( !h ) return 0; // Add hash SCOPE_LOCK( HashNamesLocker ); auto ins = HashNames.insert( std::make_pair( h, "" ) ); if( ins.second ) { ins.first->second = s; #if defined ( FONLINE_SERVER ) || defined ( FONLINE_EDITOR ) if( DbStorage ) { if( DbStorage->Get( "Hashes", h ).empty() ) DbStorage->Insert( "Hashes", h, { { "Value", s } } ); } #endif } else if( ins.first->second != s ) { WriteLog( "Hash collision detected for names '{}' and '{}', hash {:#X}.\n", s, ins.first->second, h ); } return h; } _str& _str::parseHash( hash h ) { SCOPE_LOCK( HashNamesLocker ); if( h ) { auto it = HashNames.find( h ); if( it != HashNames.end() ) s += it->second; } return *this; } #if defined ( FONLINE_SERVER ) || defined ( FONLINE_EDITOR ) void _str::loadHashes() { WriteLog( "Load hashes...\n" ); SCOPE_LOCK( HashNamesLocker ); UIntVec db_hashes = DbStorage->GetAllIds( "Hashes" ); for( uint hash_id : db_hashes ) { DataBase::Document hash_doc = DbStorage->Get( "Hashes", hash_id ); const string& hash_value = hash_doc[ "Value" ].get< string >(); HashNames[ hash_id ] = hash_value; } WriteLog( "Load hashes complete.\n" ); } #endif void Str::Copy( char* to, size_t size, const char* from ) { RUNTIME_ASSERT( to ); RUNTIME_ASSERT( from ); RUNTIME_ASSERT( size > 0 ); size_t from_len = strlen( from ); if( !from_len ) { to[ 0 ] = 0; return; } if( from_len >= size ) { memcpy( to, from, size - 1 ); to[ size - 1 ] = 0; } else { memcpy( to, from, from_len ); to[ from_len ] = 0; } } void Str::Append( char* to, size_t size, const char* from ) { RUNTIME_ASSERT( to ); RUNTIME_ASSERT( from ); RUNTIME_ASSERT( size > 0 ); size_t from_len = strlen( from ); if( !from_len ) return; size_t to_len = strlen( to ); if( to_len + 1 >= size ) return; size_t to_free = size - to_len; char* ptr = to + to_len; if( from_len >= to_free ) { memcpy( ptr, from, to_free - 1 ); to[ size - 1 ] = 0; } else { memcpy( ptr, from, from_len ); ptr[ from_len ] = 0; } } char* Str::Duplicate( const string& str ) { return Duplicate( str.c_str() ); } char* Str::Duplicate( const char* str ) { size_t len = strlen( str ); char* dup = new char[ len + 1 ]; if( len ) memcpy( dup, str, len ); dup[ len ] = 0; return dup; } bool Str::Compare( const char* str1, const char* str2 ) { while( *str1 && *str2 ) { if( *str1 != *str2 ) return false; str1++, str2++; } return *str1 == 0 && *str2 == 0; } void Str::HexToStr( uchar hex, char* str ) { for( int i = 0; i < 2; i++ ) { int val = ( i == 0 ? hex >> 4 : hex & 0xF ); if( val < 10 ) *str++ = '0' + val; else *str++ = 'A' + val - 10; } } uchar Str::StrToHex( const char* str ) { uchar result = 0; for( int i = 0; i < 2; i++ ) { char c = *str++; if( c < 'A' ) result |= ( c - '0' ) << ( i == 0 ? 4 : 0 ); else result |= ( c - 'A' + 10 ) << ( i == 0 ? 4 : 0 ); } return result; } bool utf8::IsValid( uint ucs ) { return ucs != 0xFFFD /* Unicode REPLACEMENT CHARACTER */ && ucs <= 0x10FFFF; } uint utf8::Decode( const char* str, uint* length ) { // Taked from FLTK unsigned char c = *(unsigned char*) str; if( c < 0x80 ) { if( length ) *length = 1; return c; } else if( c < 0xc2 ) { goto FAIL; } else if( ( str[ 1 ] & 0xc0 ) != 0x80 ) { goto FAIL; } else if( c < 0xe0 ) { if( length ) *length = 2; return ( ( str[ 0 ] & 0x1f ) << 6 ) + ( ( str[ 1 ] & 0x3f ) ); } else if( c == 0xe0 ) { if( ( (unsigned char*) str )[ 1 ] < 0xa0 ) goto FAIL; goto UTF8_3; } else if( c < 0xf0 ) { UTF8_3: if( ( str[ 2 ] & 0xc0 ) != 0x80 ) goto FAIL; if( length ) *length = 3; return ( ( str[ 0 ] & 0x0f ) << 12 ) + ( ( str[ 1 ] & 0x3f ) << 6 ) + ( ( str[ 2 ] & 0x3f ) ); } else if( c == 0xf0 ) { if( ( (unsigned char*) str )[ 1 ] < 0x90 ) goto FAIL; goto UTF8_4; } else if( c < 0xf4 ) { UTF8_4: if( ( str[ 2 ] & 0xc0 ) != 0x80 || ( str[ 3 ] & 0xc0 ) != 0x80 ) goto FAIL; if( length ) *length = 4; return ( ( str[ 0 ] & 0x07 ) << 18 ) + ( ( str[ 1 ] & 0x3f ) << 12 ) + ( ( str[ 2 ] & 0x3f ) << 6 ) + ( ( str[ 3 ] & 0x3f ) ); } else if( c == 0xf4 ) { if( ( (unsigned char*) str )[ 1 ] > 0x8f ) goto FAIL; /* after 0x10ffff */ goto UTF8_4; } else { FAIL: if( length ) *length = 1; return 0xfffd; /* Unicode REPLACEMENT CHARACTER */ } } uint utf8::Encode( uint ucs, char(&buf)[ 4 ] ) { // Taked from FLTK if( ucs < 0x000080U ) { buf[ 0 ] = ucs; return 1; } else if( ucs < 0x000800U ) { buf[ 0 ] = 0xc0 | ( ucs >> 6 ); buf[ 1 ] = 0x80 | ( ucs & 0x3F ); return 2; } else if( ucs < 0x010000U ) { buf[ 0 ] = 0xe0 | ( ucs >> 12 ); buf[ 1 ] = 0x80 | ( ( ucs >> 6 ) & 0x3F ); buf[ 2 ] = 0x80 | ( ucs & 0x3F ); return 3; } else if( ucs <= 0x0010ffffU ) { buf[ 0 ] = 0xf0 | ( ucs >> 18 ); buf[ 1 ] = 0x80 | ( ( ucs >> 12 ) & 0x3F ); buf[ 2 ] = 0x80 | ( ( ucs >> 6 ) & 0x3F ); buf[ 3 ] = 0x80 | ( ucs & 0x3F ); return 4; } else { /* encode 0xfffd: */ buf[ 0 ] = 0xefU; buf[ 1 ] = 0xbfU; buf[ 2 ] = 0xbdU; return 3; } } uint utf8::Lower( uint ucs ) { // Taked from FLTK uint ret; if( ucs <= 0x02B6 ) { if( ucs >= 0x0041 ) { ret = ucs_table_0041[ ucs - 0x0041 ]; if( ret > 0 ) return ret; } return ucs; } if( ucs <= 0x0556 ) { if( ucs >= 0x0386 ) { ret = ucs_table_0386[ ucs - 0x0386 ]; if( ret > 0 ) return ret; } return ucs; } if( ucs <= 0x10C5 ) { if( ucs >= 0x10A0 ) { ret = ucs_table_10A0[ ucs - 0x10A0 ]; if( ret > 0 ) return ret; } return ucs; } if( ucs <= 0x1FFC ) { if( ucs >= 0x1E00 ) { ret = ucs_table_1E00[ ucs - 0x1E00 ]; if( ret > 0 ) return ret; } return ucs; } if( ucs <= 0x2133 ) { if( ucs >= 0x2102 ) { ret = ucs_table_2102[ ucs - 0x2102 ]; if( ret > 0 ) return ret; } return ucs; } if( ucs <= 0x24CF ) { if( ucs >= 0x24B6 ) { ret = ucs_table_24B6[ ucs - 0x24B6 ]; if( ret > 0 ) return ret; } return ucs; } if( ucs <= 0x33CE ) { if( ucs >= 0x33CE ) { ret = ucs_table_33CE[ ucs - 0x33CE ]; if( ret > 0 ) return ret; } return ucs; } if( ucs <= 0xFF3A ) { if( ucs >= 0xFF21 ) { ret = ucs_table_FF21[ ucs - 0xFF21 ]; if( ret > 0 ) return ret; } return ucs; } return ucs; } uint utf8::Upper( uint ucs ) { // Taken from FLTK static unsigned short* table = nullptr; if( !table ) { table = (unsigned short*) malloc( sizeof( unsigned short ) * 0x10000 ); for( uint i = 0; i < 0x10000; i++ ) { table[ i ] = (unsigned short) i; } for( uint i = 0; i < 0x10000; i++ ) { uint l = utf8::Lower( i ); if( l != i ) table[ l ] = (unsigned short) i; } } if( ucs >= 0x10000 ) return ucs; return table[ ucs ]; }
#pragma once #include "Pet.h" #include "Purchase.h" #include <chrono> using namespace std; class PurchaseList { private: int size = 0; int id = 0; Purchase* mergeList(Purchase* list1, Purchase* list2); void splitList(Purchase* start, Purchase** list1, Purchase** list2); void mergeSort(Purchase** start); public: Purchase* purchaseHead = NULL; int getSize(); Purchase* AddPurchase(string, string, string); void Print(); void Print(Purchase*); void SortByTotal(); void ViewDetail(Purchase* purchase); Purchase* getItemBasedOnId(int); bool AddPet(Purchase*, Pet*); };
// ***************************************************************************** // Module..: Leddar // /// \file LdConnectionFactory.cpp /// /// \brief Factory to create connection /// /// \author Patrick Boulay /// /// \since February 2016 // // Copyright (c) 2016 LeddarTech Inc. All rights reserved. // ***************************************************************************** #include "LdConnectionFactory.h" #include "LdConnectionInfo.h" #include "LdConnectionUniversalSpi.h" #include "LdConnectionUniversalModbus.h" #include "LdConnectionUniversalEthernet.h" #include "LdEthernet.h" #include "LdLibModbusSerial.h" #include "LdProtocolsDefines.h" #include "LdSpiFTDI.h" #ifdef SPI_BCM2835 #include "LdSpiBCM2835.h" #endif using namespace LeddarConnection; // ***************************************************************************** // Function: LdConnectionFactory::CreateConnection // /// \brief Create the associated connection with the connection info object. /// You need to add /// /// \param aConnectionInfo Information on connection to create /// \param aConnection Only used with Modbus connection. /// Specify the shared modbus connection when multiple sensor on the same line. /// Set to nullptr on single device on the COM port. /// /// \exception std::runtime_error If the type is unknown. /// /// \author Patrick Boulay /// /// \since March 2016 // ***************************************************************************** LeddarConnection::LdConnection * LdConnectionFactory::CreateConnection( const LdConnectionInfo *aConnectionInfo, LeddarConnection::LdConnection *aConnection ) { if( aConnectionInfo->GetType() == LdConnectionInfo::CT_SPI_FTDI ) { const LdConnectionInfoSpi *lConnectionInfo = dynamic_cast<const LdConnectionInfoSpi *>( aConnectionInfo ); LdInterfaceSpi *lSpiInterface = new LdSpiFTDI( lConnectionInfo ); return new LdConnectionUniversalSpi( lConnectionInfo, lSpiInterface ); } #ifdef SPI_BCM2835 else if( aConnectionInfo->GetType() == LdConnectionInfo::CT_SPI_BCM2835 ) { const LdConnectionInfoSpi *lConnectionInfo = dynamic_cast<const LdConnectionInfoSpi *>( aConnectionInfo ); LdInterfaceSpi *lSpiInterface = new LdSpiBCM2835( lConnectionInfo ); return new LdConnectionUniversalSpi( lConnectionInfo, lSpiInterface ); } #endif else if( aConnectionInfo->GetType() == LdConnectionInfo::CT_LIB_MODBUS ) { const LdConnectionInfoModbus *lConnectionInfo = dynamic_cast<const LdConnectionInfoModbus *>( aConnectionInfo ); LdInterfaceModbus *lConnectionModbus = new LdLibModbusSerial( lConnectionInfo, ( aConnection != nullptr && aConnection->GetInterface() != nullptr ? aConnection->GetInterface() : nullptr ) ); LeddarConnection::LdConnection *lConnectionUniversal = new LdConnectionUniversalModbus( lConnectionInfo, lConnectionModbus ); if( aConnection != nullptr ) { lConnectionUniversal->SetDeviceType( aConnection->GetDeviceType() ); } return lConnectionUniversal; } else if( aConnectionInfo->GetType() == LdConnectionInfo::CT_ETHERNET_UNIVERSAL ) { const LdConnectionInfoEthernet *lConnectionInfo = dynamic_cast<const LdConnectionInfoEthernet *>( aConnectionInfo ); LdInterfaceEthernet *lConnectionEthernet = new LdEthernet( lConnectionInfo ); return new LdConnectionUniversalEthernet( lConnectionInfo, lConnectionEthernet ); } else { throw std::runtime_error( "Invalid connection type" ); return nullptr; } }
#include "bullet.h" #include <iostream> bullet::bullet(vector pos, vector vel, float s){ position = pos; velocity = vel; size = s; } void bullet::update(float eTime, vector grav){ position = position + velocity * eTime + grav * 0.5 * eTime * eTime; velocity = velocity + grav * eTime; } void bullet::drawBullet(GLuint texture){ glLoadIdentity(); glTranslatef(position.x, position.y, 0.0f); glEnable(GL_TEXTURE_2D); //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBindTexture (GL_TEXTURE_2D, texture); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f(-size, -size); glTexCoord2f(0.0f, 1.0f); glVertex2f(-size, size); glTexCoord2f(1.0f, 1.0f); glVertex2f(size, size); glTexCoord2f(1.0f, 0.0f); glVertex2f(size, -size); glEnd(); glDisable(GL_TEXTURE_2D); }
// generating a random sequence of distinct elements #include <bits/stdc++.h> using namespace std; int rand(int a, int b) { return a + rand() % (b - a + 1); } int main(int argc, char *argv[]) { int t; cin >> t; srand(t); // atoi(s) converts an array of chars to int int n = rand(2, 10); printf("%d\n", n); vector<int> a(n); vector<int> b(n); for (int i = 0; i < n; ++i) { int x = rand(1, 10); int y = rand(1, 10); a[i] = x; b[i] = y; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("%d%c", a[i] + b[j], j == n - 1 ? '\n' : ' '); } } puts(""); }
/************************************************************* * > File Name : P1328.cpp * > Author : Tony * > Created Time : 2019/05/21 13:14:14 **************************************************************/ #include <bits/stdc++.h> using namespace std; const int maxn = 200 + 10; int n, na, nb, a[maxn], b[maxn], cnta, cntb; int vs[5][5] = {{0, 0, 1, 1, 0}, {1, 0, 0, 1, 0}, {0, 1, 0, 0, 1}, {0, 0, 1, 0, 1}, {1, 1, 0, 0, 0}}; int main(){ scanf("%d %d %d", &n, &na, &nb); for (int i = 0; i < na; i++) scanf("%d", &a[i]); for (int i = 0; i < nb; i++) scanf("%d", &b[i]); for (int i = 0; i < n ; i++) { cnta += vs[a[i % na]][b[i % nb]]; cntb += vs[b[i % nb]][a[i % na]]; } printf("%d %d\n", cnta, cntb); return 0; }
#ifndef TRANSLATOR_ANTLR_ERROR_LISTENER_HPP #define TRANSLATOR_ANTLR_ERROR_LISTENER_HPP #include <antlr4-runtime.h> class AntlrErrorListener : public antlr4::BaseErrorListener { void syntaxError(antlr4::Recognizer* recognizer, antlr4::Token* offendingSymbol, size_t line, size_t charPositionInLine, const std::string& msg, std::exception_ptr e) final; }; #endif // TRANSLATOR_ANTLR_ERROR_LISTENER_HPP
class Solution { public: int twoSumLessThanK(vector<int>& A, int K) { int res = -1, left = 0, right = A.size() - 1; sort(A.begin(), A.end()); while (left < right) { int cursum = A[left] + A[right]; if (cursum >= K) --right; else { res = max(res, cursum); ++left; } } return res; } };
// MyCompression.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "MyCompression.h" #define PI 3.14159265358979323846 #define MAX_VAL 65536 #define IMAGE_WIDTH 352 #define IMAGE_HEIGHT 288 #define MAX_LOADSTRING 100 // Global Variables: MyImage inImage, outImage; // image objects HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text // Foward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM); void ColorPixel(char* imgBuf, int w, int h, int x, int y); // Main entry point for a windows application int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; HACCEL hAccelTable; // Read in a parameter from the command line char szImageName[1024] = { '\0', }; int numOfVector = 0; int mode = 0; sscanf(lpCmdLine, "%s %d %d", szImageName, &numOfVector, &mode); // Create a separate console window to display output to stdout AllocConsole(); freopen("CONOUT$", "w", stdout); printf("The first parameter was: %s\nThe second parameter was: %d\nThe third parameter was: %d\n", szImageName, numOfVector, mode); int szLength = strlen(szImageName); if (szLength < 5) { fprintf(stderr, "Please input image path.\n"); return 0; } if (!(0 < mode && mode < 4)) { fprintf(stderr, "%d is invalid mode.\n"); return 0; } if ((numOfVector - 1) & numOfVector) { fprintf(stderr, "Second parameter should be a power of 2.\n"); return 0; } // Set up the images int w = IMAGE_WIDTH; int h = IMAGE_HEIGHT; int d = -1; if (!strcmp("raw", &szImageName[szLength - 3])) d = 8; if (!strcmp("rgb", &szImageName[szLength - 3])) d = 24; inImage.setWidth(w); inImage.setHeight(h); inImage.setDepth(d); if ('.' != szImageName[szLength - 4] || inImage.getDepth() < 0) { fprintf(stderr, "Invalied file format\n"); return 0; } inImage.setImagePath(szImageName); inImage.ReadImage(); int lengthOfVectors[3] = { 2, 4, 16 }; int lengthOfVector = lengthOfVectors[mode - 1]; byte* pData = inImage.getImageData(); if (8 == d || numOfVector < MAX_VAL) { VectorClusteringCompressor vcc; if (!vcc.Encode(pData, w, h, d, numOfVector, lengthOfVector)) { } byte* pDest = new byte[inImage.getWidth() * inImage.getHeight() * (d / 8)]; vcc.Decode(pDest); outImage = inImage; outImage.setImageData(pDest); } else { outImage = inImage; byte* pBlue = new byte[inImage.getWidth() * inImage.getHeight()]; byte* pGreen = new byte[inImage.getWidth() * inImage.getHeight()]; byte* pRed = new byte[inImage.getWidth() * inImage.getHeight()]; byte* bgr[3] = { pBlue, pGreen, pRed }; byte* pDest = new byte[inImage.getWidth() * inImage.getHeight() * 3]; for (int i = 0, index = 0; i < inImage.getWidth() * inImage.getHeight() * 3; i += 3) { pBlue[index] = pData[i]; pGreen[index] = pData[i + 1]; pRed[index] = pData[i + 2]; index++; } int numOfClusters[3] = { numOfVector, numOfVector, numOfVector }; int exp = 0; int numOfCluster = numOfVector; while (1 < numOfCluster) { exp++; numOfCluster >>= 1; } numOfClusters[2] = exp / 3; numOfClusters[1] = numOfClusters[2] + (exp % 3 ? 1 : 0); numOfClusters[0] = exp - (numOfClusters[1] + numOfClusters[2]); numOfClusters[0] = (1 << numOfClusters[0]); numOfClusters[1] = (1 << numOfClusters[1]); numOfClusters[2] = (1 << numOfClusters[2]); VectorClusteringCompressor vcc[3]; for (int i = 0; i < 3; i++) { if (!vcc[i].Encode(bgr[i], w, h, 8, numOfClusters[i], lengthOfVector)) { } vcc[i].Decode(bgr[i]); } for (int i = 0, index = 0; i <inImage.getWidth() * inImage.getHeight() * 3; i += 3) { pDest[i] = pBlue[index]; pDest[i + 1] = pGreen[index]; pDest[i + 2] = pRed[index]; index++; } outImage.setImageData(pDest); } // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_MYCOMPRESSION, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_MYCOMPRESSION); // Main message loop: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // Colors a pixel at the given (x, y) position black. void ColorPixel(char* imgBuf, int w, int h, int x, int y) { imgBuf[(4 * y * w) + 4 * x] = 0; imgBuf[(4 * y * w) + 4 * x + 1] = 0; imgBuf[(4 * y * w) + 4 * x + 2] = 0; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MYCOMPRESSION)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_MYCOMPRESSION); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // Store instance handle in our global variable HWND hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; TCHAR szHello[MAX_LOADSTRING]; LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING); RECT rt; GetClientRect(hWnd, &rt); switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case ID_MODIFY_IMAGE: outImage.Modify(); InvalidateRect(hWnd, &rt, false); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); // TO DO: Add any drawing code here... char text[1000]; strcpy(text, "Original image (Left) Image after modification (Right)\n"); DrawText(hdc, text, strlen(text), &rt, DT_LEFT); strcpy(text, "\nUpdate program with your code to modify input image"); DrawText(hdc, text, strlen(text), &rt, DT_LEFT); BITMAPINFO bmi; // CBitmap bitmap; memset(&bmi, 0, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader); bmi.bmiHeader.biWidth = inImage.getWidth(); bmi.bmiHeader.biHeight = -inImage.getHeight(); // Use negative height. DIB is top-down. bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = inImage.getDepth(); bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = inImage.getWidth()*inImage.getHeight(); if (8 == inImage.getDepth()) { for (int i = 0; i < 256; i++) { bmi.bmiColors[i].rgbBlue = i; bmi.bmiColors[i].rgbGreen = i; bmi.bmiColors[i].rgbRed = i; bmi.bmiColors[i].rgbReserved = 0; } } SetDIBitsToDevice(hdc, 100, 100, inImage.getWidth(), inImage.getHeight(), 0, 0, 0, inImage.getHeight(), inImage.getImageData(), &bmi, DIB_RGB_COLORS); SetDIBitsToDevice(hdc, inImage.getWidth() + 150, 100, outImage.getWidth(), outImage.getHeight(), 0, 0, 0, outImage.getHeight(), outImage.getImageData(), &bmi, DIB_RGB_COLORS); EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; }
// C++IOFile.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #define MAX 1024 typedef int(*Fun)(char* s,FILE *file); int chooseAction(Fun fun, char* name) { FILE *file = fopen("D:\\MyProject\\c++\\FILE\\bookname.txt", "a+"); fun(name,file); return 0; } int addFile(char *pName, FILE *file) { char bookname[100] = {0}; char autor[100] = { 0 }; char press[100] = { 0 }; //char string[MAX] = " "; if (file == NULL) { printf("读取文件失败"); return -1; } printf("请输入要添加的书名:"); scanf("%s", bookname); printf("请输入要添加的书的作者:"); scanf("%s", autor); printf("请输入要添加的出版社:"); scanf("%s", press); //strcat_s(string, sizeof(string), bookname); //strcat_s(string, sizeof(string), autor); //strcat_s(string, sizeof(string), press); fprintf(file, "%-20s%-20s%-20s\n", bookname, autor, press); //fputs(string, file); printf("添加完完成\n"); /* while (fgets(string, MAX, file) != NULL) { } */ fclose(file); return 0; } int upDateFile(char *pName, FILE *file) { return 0; } int selectFile(char *pName, FILE *file) { char userStr[MAX] = { 0 }; char sysStr[MAX] = { 0 }; char sysString[MAX] = { 0 }; printf("请输入要查找的书名或者作者\n"); scanf("%s", userStr); while (fgets(sysStr,MAX,file) != NULL) { int i = 0; int j = 0; while (i < strlen(sysStr)) { if (sysStr[i] == '\t'||sysStr[i] == '\n'||sysStr[i] == ' ') //因为记事本使用了空格(' ')与水平制表符('\t'),所以都要判断 { if (strcmp(userStr, sysString) == 0) { printf("找到了\n"); printf("%s \n", sysStr); return 0; } memset(sysString, 0, sizeof(sysString)); j = 0; } else { sysString[j++] = sysStr[i]; } i++; } } printf("没有找到\n"); return 0; } int deleteFile(char *pName, FILE *file) { return 0; } int main() { #if 1 int offOn = 1; int* pAction; int(*arrFun[4])(char *s, FILE *file) = { selectFile,addFile,upDateFile,deleteFile }; printf("0.查询图书:\n"); printf("1.增加图书:\n"); printf("2.修改图书:\n"); printf("3.删除图书:\n"); //printf("5.返回上一层:"); printf("6.退出:\n"); while (offOn != 6) { printf("请输入操作类型的序列号:"); //这里如果输入了遗传字符串scanf不会给offon赋值,也不会刷新缓存区,导致死循环,加个getchar刷新缓存区 int a = scanf("%d", &offOn); if (offOn < 6 && offOn >= 0 ) { //printf("操作文件"); char name[] = " "; chooseAction(arrFun[offOn],name); } else { //fflush(stdin); c11之后失效 getchar(); printf("无效输入,请从新输入 \n"); } } #endif #if 0 char ch; while ((ch = getchar()) != '#') { putchar(ch); } #endif return 0; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
#include <iostream> #include <string> #include "GameLogic.h" using namespace std; string player1Name; char player1Piece; string player2Name; char player2Piece; int main() { cout << "Please Enter Player 1's Name: "; cin >> player1Name; cout << "Player 1s Name Is " << player1Name << endl; cout << "Please Enter Player 2's Name: "; cin >> player2Name; cout << "Player 2s Name Is " << player2Name << endl; while(true){ cout << "Player 1 Please Enter Your Desired Piece: "; cin >> player1Piece; cout << "Player 1s Chosen Piece Is: " << player1Piece << endl; cout << "Player 2 Please Enter Your Desired Piece: "; cin >> player2Piece; cout << "Player 2s Chosen Piece Is: " << player2Piece << endl; if (player2Piece != player1Piece && player2Piece != ' ') { break; } else { cout << "Both Players Cannot Have Same Pieces: " << endl; } } Player player1(player1Name, player1Piece); Player player2(player2Name, player2Piece); Game game(&player1, &player2); game.startGame(); }
#include<stdio.h> int func(int n) { static int a = 0; a++; printf("n=%d, a=%d\n", n, a); return 0; } int main() { //static 변수를 사용하는 이유는? int n = 5; func(n); func(n); return 0; }