text
stringlengths
8
6.88M
/* 1.先求原图的最小生成树T,并记录树边和最小值small1 2.然后求dis[i][j],表示在T中x到y的唯一路径上的最大边 3.枚举所有非树边(u,v),设其值为w,那么small2=min{small1-dis[u][v]+w},最后看small1和 small2是否一样就可以了。 */ #include<cstdio> #include<cstring> #include<vector> #include<queue> #include<algorithm> #define maxn 110 #define maxm 10000 using namespace std; struct edge{ int u,v,w,next,inv; bool inTree; }; vector<edge> e; int id[maxm]; int beg[maxn]; int fa[maxn]; int dis[maxn][maxn]; int n,m; int small1,small2; int nE; void add(int x,int y ,int z,int invFlag) { e.push_back(edge()); int last=e.size()-1; e[last].u=x; e[last].v=y; e[last].next=beg[x]; e[last].w=z; e[last].inTree=false; beg[x]=last; if(!invFlag) e[last].inv=last+1; else e[last].inv=last-1; } bool cmp(int x,int y) { return e[x].w<e[y].w; } void input() { int x,y,z; e.resize(1); memset(beg,0,sizeof(beg)); scanf("%d%d",&n,&m); for(int i=1;i<=m;++i) { scanf("%d%d%d",&x,&y,&z); add(x,y,z,0); add(y,x,z,1); } //label nE=e.size()-1; for(int i=1;i<=nE;++i) id[i]=i; sort(id+1,id+nE+1,cmp); } int find(int x) { int fx,tm; fx=x; while(fa[fx]!=fx) fx=fa[fx]; while(fa[x]!=fx) { tm=fa[x]; fa[x]=fx; x=tm; } return fx; } void kruskal() { small1=0; for(int i=1;i<=n;++i) fa[i]=i; for(int i=1;i<=nE;++i) { int x=e[id[i]].u; int y=e[id[i]].v; x=find(x); y=find(y); if(x!=y) { e[id[i]].inTree=true; e[e[id[i]].inv].inTree=true; small1+=e[id[i]].w; fa[x]=y; } } } void dfs(int x,int father,int now,int best[]) { best[x]=now; for(int i=beg[x];i;i=e[i].next) if(e[i].inTree && e[i].v!=father) { if(e[i].w>now) dfs(e[i].v,x,e[i].w,best); else dfs(e[i].v,x,now,best); } } void find_dis() { memset(dis,0,sizeof(dis)); for(int i=1;i<=n;++i) dfs(i,0,0,dis[i]); } void cal_second() { small2=2000000000; for(int i=1;i<=nE;++i) if(!e[i].inTree){ int sub=dis[e[i].u][e[i].v]; if(small1-sub+e[i].w<small2) small2=small1-sub+e[i].w; } } void output() { if(small1==small2) printf("Not Unique!\n"); else printf("%d\n",small1); } int main() { freopen("pku1679.in","r",stdin); int cs; scanf("%d",&cs); while(cs--) { input(); kruskal(); find_dis(); cal_second(); output(); } return 0; }
#ifndef DTFECHA_H #define DTFECHA_H class DtFecha { private: int dia; int mes; int anio; public: DtFecha(); DtFecha(int dia, int mes, int anio); int getD(); int getM(); int getA(); }; #endif
//Declaration header #include"text_renderer.h" //shady_engine headers #include"smath/math.h" #include"resources.h" #include"shader.h" #include"texture2D.h" namespace shady_engine { text_renderer::text_renderer() { } text_renderer::~text_renderer() { glDeleteBuffers(1,&mVBO); glDeleteVertexArrays(1,&mVAO); } text_renderer::text_renderer( const std::shared_ptr<texture2D> pTextureAtlas, const std::string& pPath ) : mTextureAtlas(pTextureAtlas) { FILE *file = nullptr; file = fopen(pPath.c_str(), "r"); if (!file) { throw std::runtime_error("failed to load to read font!"); } while (true) { character c; int id; char result = fscanf(file, "%d,%d,%d,%d,%d,%d,%d,%d,", &id, &c.position.x, &c.position.y, &c.size.x, &c.size.y, &c.offsets.x, &c.offsets.y, &c.advanceX ); mCharacters.insert(std::pair<char, character>(static_cast<char>(id), c)); if (result == EOF) break; } fclose(file); mShader = resources::getInstance()->load_shader("shader for text rendering", "shadyengine/shaders/text_renderer_vs.glsl", "shadyengine/shaders/text_renderer_fs.glsl" ); //Setting up quad float points[] = { 0.0f,0.0f, 1.0f,0.0f, 0.0f,1.0f, 1.0f,1.0f }; glGenVertexArrays(1, &mVAO); glGenBuffers(1, &mVBO); glBindVertexArray(mVAO); glBindBuffer(GL_ARRAY_BUFFER, mVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW); //Position glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(0)); glBindVertexArray(0); } void text_renderer::init( const std::shared_ptr<texture2D> pTextureAtlas, const std::string& pPath ) { mTextureAtlas = pTextureAtlas; FILE *file = nullptr; file = fopen(pPath.c_str(), "r"); if (!file) { std::cout << "failed to open font file"; return; } while (true) { character c; int id; char result = fscanf(file, "%d,%d,%d,%d,%d,%d,%d,%d,", &id, &c.position.x, &c.position.y, &c.size.x, &c.size.y, &c.offsets.x, &c.offsets.y, &c.advanceX ); mCharacters.insert(std::pair<char, character>(static_cast<char>(id), c)); if (result == EOF) break; } fclose(file); resources::getInstance()->load_shader("shader for text rendering", "shadyengine/shaders/text_renderer_vs.glsl", "shadyengine/shaders/text_renderer_fs.glsl" ); mShader = resources::getInstance()->get_shader("shader for text rendering"); //Setting up quad float points[] = { 0.0f,0.0f, 1.0f,0.0f, 0.0f,1.0f, 1.0f,1.0f }; glGenVertexArrays(1, &mVAO); glGenBuffers(1, &mVBO); glBindVertexArray(mVAO); glBindBuffer(GL_ARRAY_BUFFER, mVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW); //Position glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(0)); glBindVertexArray(0); } void text_renderer::text( const glm::mat4& pProjection, const glm::mat4& pView, const glm::vec2& pPosition, float pSize, const glm::vec3& pColor, const char* pFormat, ... ) { float width = smath::map_to_range(1.0f, 300.0f, .43f, .6f,pSize); float edge = 0.2f - smath::map_to_range(1.0f, 300.0f, 0.1f, 0.2f,pSize); pSize = smath::map_to_range(1.0,300.0f, 0.2f, 5.0,pSize); glm::vec2 tempPos = pPosition; //Initializing variable argument list va_list lst; va_start(lst, pFormat); std::string text; //Extracting data from variable argument list for (const char* traverse = pFormat; *traverse != '\0'; traverse++) { while (true) { if (*traverse == '%' || *traverse == '\0') break; text += *traverse; traverse++; } if (*traverse == '\0') break; traverse++; switch (*traverse) { case 'd': text += std::to_string(va_arg(lst, int)); break; case 'f': text += std::to_string(va_arg(lst, double)); break; } } va_end(lst); int primCounter = 0; //counts the number of text //Iterating through the string and calculating attributes of each character for (auto iter = text.begin(); iter != text.end(); iter++) { character c = mCharacters[*iter]; if (*iter == '\n') { tempPos.y +=pSize*70.0f; tempPos.x = pPosition.x; continue; } float dx = float(c.position.x) / mTextureAtlas->get_size().x; float dy = float(c.position.y) / mTextureAtlas->get_size().y; float dw = float(c.size.x) / mTextureAtlas->get_size().x; float dh = float(c.size.y) / mTextureAtlas->get_size().y; mTexCoords.push_back(glm::vec4(dx,dy,dw,dh)); mOffsets.push_back(tempPos + (glm::vec2(c.offsets)*pSize)); mScalers.push_back(glm::vec2(c.size)*pSize); tempPos.x += (c.advanceX-8)*pSize; primCounter++; } //Generating some needed buffers for offsets,scales and texture coordinates glGenBuffers(1, &mVBOTexCoords); glGenBuffers(1,&mVBOOffsets); glGenBuffers(1, &mVBOScalers); glBindVertexArray(mVAO); //TEXTURE COORDS glBindBuffer(GL_ARRAY_BUFFER, mVBOTexCoords); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4)*mTexCoords.size(), mTexCoords.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribDivisor(1, 1); //OFFSETS glBindBuffer(GL_ARRAY_BUFFER,mVBOOffsets); glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec2)*mOffsets.size(),mOffsets.data(),GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2,2,GL_FLOAT,GL_FALSE,0,0); glVertexAttribDivisor(2, 1); //SCALERS glBindBuffer(GL_ARRAY_BUFFER, mVBOScalers); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2)*mScalers.size(), mScalers.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribDivisor(3, 1); glBindVertexArray(0); mShader->use(); mShader->setMat4("projection",pProjection); mShader->setMat4("view",pView); mShader->set3fv("font_color", pColor); mShader->set1f("width", width); mShader->set1f("edge", edge); mShader->set1i("use_color", 1); //Binding the font texture at GL_TEXTURE0 mShader->set1i("texture_atlas", 0); glActiveTexture(GL_TEXTURE0); mTextureAtlas->bind(); glBindVertexArray(mVAO); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4,primCounter); glBindVertexArray(0); glDeleteBuffers(1, &mVBOOffsets); glDeleteBuffers(1, &mVBOScalers); glDeleteBuffers(1, &mVBOTexCoords); mOffsets.clear(); mScalers.clear(); mTexCoords.clear(); } void text_renderer::textured_text( const glm::mat4& pProjection, const glm::mat4& pView, const glm::vec2& pPosition, float pSize, std::shared_ptr<texture2D> pFontTexture, const char* pFormat, ... ) { float width = smath::map_to_range(1.0f, 300.0f, .43f, .6f, pSize); float edge = 0.2f - smath::map_to_range(1.0f, 300.0f, 0.1f, 0.2f, pSize); pSize = smath::map_to_range(1.0, 300.0f, 0.2f, 5.0, pSize); glm::vec2 tempPos = pPosition; //Initializing variable argument list va_list lst; va_start(lst, pFormat); std::string text; //Extracting data from variable argument list for (const char* traverse = pFormat; *traverse != '\0'; traverse++) { while (true) { if (*traverse == '%' || *traverse == '\0') break; text += *traverse; traverse++; } if (*traverse == '\0') break; traverse++; switch (*traverse) { case 'd': text += std::to_string(va_arg(lst, int)); break; case 'f': text += std::to_string(va_arg(lst, double)); break; } } va_end(lst); unsigned int primCounter = 0; //counts the number of text //Iterating through the string and calculating attributes of each character for (auto iter = text.begin(); iter != text.end(); iter++) { character c = mCharacters[*iter]; if (*iter == '\n') { tempPos.y += pSize*70.0f; tempPos.x = pPosition.x; continue; } //Mapping texture coordinates from [0,texture dimenstions] to [0,1] float dx = float(c.position.x) / mTextureAtlas->get_size().x; float dy = float(c.position.y) / mTextureAtlas->get_size().y; float dw = float(c.size.x) / mTextureAtlas->get_size().x; float dh = float(c.size.y) / mTextureAtlas->get_size().y; mTexCoords.push_back(glm::vec4(dx, dy, dw, dh)); mOffsets.push_back(tempPos + (glm::vec2(c.offsets)*pSize)); mScalers.push_back(glm::vec2(c.size)*pSize); tempPos.x += (c.advanceX - 8)*pSize; primCounter++; } //Generating some needed buffers for offsets,scales and texture coordinates glGenBuffers(1, &mVBOTexCoords); glGenBuffers(1, &mVBOOffsets); glGenBuffers(1, &mVBOScalers); glBindVertexArray(mVAO); //TEXTURE COORDS glBindBuffer(GL_ARRAY_BUFFER, mVBOTexCoords); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4)*mTexCoords.size(), mTexCoords.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribDivisor(1, 1); //OFFSETS glBindBuffer(GL_ARRAY_BUFFER, mVBOOffsets); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2)*mOffsets.size(), mOffsets.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribDivisor(2, 1); //SCALERS glBindBuffer(GL_ARRAY_BUFFER, mVBOScalers); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2)*mScalers.size(), mScalers.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribDivisor(3, 1); mShader->use(); mShader->setMat4("projection", pProjection); mShader->setMat4("view", pView); mShader->set1f("width", width); mShader->set1f("edge", edge); mShader->set1i("use_color", 0); //Binding the font texture at GL_TEXTURE0 mShader->set1i("texture_atlas", 0); glActiveTexture(GL_TEXTURE0); mTextureAtlas->bind(); mShader->set1i("font_texture", 1); glActiveTexture(GL_TEXTURE1); pFontTexture->bind(); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, primCounter); glBindVertexArray(0); glDeleteBuffers(1, &mVBOOffsets); glDeleteBuffers(1, &mVBOScalers); glDeleteBuffers(1, &mVBOTexCoords); mOffsets.clear(); mScalers.clear(); mTexCoords.clear(); } }//End of namespace
/* -*- mode: c++; c-file-style: "gnu" -*- */ group "XMLUtils.XMLFragment.treeaccessor"; require init; require XMLUTILS_XMLFRAGMENT_XMLTREEACCESSOR_SUPPORT; include "modules/xmlutils/xmlfragment.h"; include "modules/xmlutils/xmltreeaccessor.h"; include "modules/xmlutils/xmlnames.h"; test("XMLFragment tree accessor #1") { XMLFragment fragment; XMLTreeAccessor *tree = 0; verify(OpStatus::IsSuccess(fragment.Parse(UNI_L("<root><element1/>text1<element2/>text2<element3/>text3</root>")))); verify(OpStatus::IsSuccess(fragment.CreateXMLTreeAccessor(tree))); XMLTreeAccessor::Node *node, *other; const uni_char *value; verify(node = tree->GetRoot()); verify(tree->GetNodeType(node) == XMLTreeAccessor::TYPE_ROOT); /* <root/> */ verify(node = tree->GetFirstChild(node)); verify(!tree->GetPreviousSibling(node)); verify(!tree->GetNextSibling(node)); verify(tree->GetNodeType(node) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(node) == XMLCompleteName(UNI_L("root"))); other = node; /* <element1/> */ verify(node = tree->GetFirstChild(node)); verify(other == tree->GetParent(node)); verify(!tree->GetPreviousSibling(node)); verify(tree->GetNodeType(node) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(node) == XMLCompleteName(UNI_L("element1"))); other = node; /* text1 */ verify(node = tree->GetNextSibling(node)); verify(other == tree->GetPreviousSibling(node)); verify(tree->GetNodeType(node) == XMLTreeAccessor::TYPE_TEXT); verify(OpStatus::IsSuccess(tree->GetData(value, node, NULL))); verify(value); verify(uni_strcmp(value, UNI_L("text1")) == 0); other = node; /* <element2/> */ verify(node = tree->GetNextSibling(node)); verify(other == tree->GetPreviousSibling(node)); verify(tree->GetNodeType(node) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(node) == XMLCompleteName(UNI_L("element2"))); other = node; /* text2 */ verify(node = tree->GetNextSibling(node)); verify(other == tree->GetPreviousSibling(node)); verify(tree->GetNodeType(node) == XMLTreeAccessor::TYPE_TEXT); verify(OpStatus::IsSuccess(tree->GetData(value, node, NULL))); verify(value); verify(uni_strcmp(value, UNI_L("text2")) == 0); other = node; /* <element3/> */ verify(node = tree->GetNextSibling(node)); verify(other == tree->GetPreviousSibling(node)); verify(tree->GetNodeType(node) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(node) == XMLCompleteName(UNI_L("element3"))); other = node; /* text3 */ verify(node = tree->GetNextSibling(node)); verify(other == tree->GetPreviousSibling(node)); verify(tree->GetNodeType(node) == XMLTreeAccessor::TYPE_TEXT); verify(OpStatus::IsSuccess(tree->GetData(value, node, NULL))); verify(value); verify(uni_strcmp(value, UNI_L("text3")) == 0); verify(node == tree->GetLastChild(tree->GetFirstChild(tree->GetRoot()))); verify(!tree->GetNextSibling(node)); } finally { XMLFragment::FreeXMLTreeAccessor(tree); } test("XMLFragment tree accessor #2") { XMLFragment fragment; XMLTreeAccessor *tree = 0; verify(OpStatus::IsSuccess(fragment.Parse(UNI_L("<root><parent1><child1><grandchild1/><grandchild2/><grandchild3/></child1><child2><grandchild1/><grandchild2/><grandchild3/></child2></parent1><parent2><child1><grandchild1/><grandchild2/><grandchild3/></child1><child2><grandchild1/><grandchild2/><grandchild3/></child2></parent2></root>")))); verify(OpStatus::IsSuccess(fragment.CreateXMLTreeAccessor(tree))); XMLTreeAccessor::Node *rootnode, *rootelement, *parent1, *parent2, *child1, *child2, *grandchild1, *grandchild2, *grandchild3; verify(rootnode = tree->GetRoot()); verify(tree->GetNodeType(rootnode) == XMLTreeAccessor::TYPE_ROOT); verify(tree->GetParent(rootnode) == NULL); verify(tree->GetPreviousSibling(rootnode) == NULL); verify(tree->GetNextSibling(rootnode) == NULL); verify(rootelement = tree->GetFirstChild(rootnode)); verify(rootelement == tree->GetLastChild(rootnode)); verify(tree->GetNodeType(rootelement) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(rootelement) == XMLCompleteName(UNI_L("root"))); verify(tree->GetParent(rootelement) == rootnode); verify(tree->GetPreviousSibling(rootelement) == NULL); verify(tree->GetNextSibling(rootelement) == NULL); verify(parent1 = tree->GetFirstChild(rootelement)); verify(parent2 = tree->GetLastChild(rootelement)); verify(tree->GetNodeType(parent1) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(parent1) == XMLCompleteName(UNI_L("parent1"))); verify(tree->GetParent(parent1) == rootelement); verify(tree->GetPreviousSibling(parent1) == NULL); verify(tree->GetNextSibling(parent1) == parent2); verify(tree->GetNodeType(parent2) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(parent2) == XMLCompleteName(UNI_L("parent2"))); verify(tree->GetParent(parent2) == rootelement); verify(tree->GetPreviousSibling(parent2) == parent1); verify(tree->GetNextSibling(parent2) == NULL); verify(child1 = tree->GetFirstChild(parent1)); verify(child2 = tree->GetLastChild(parent1)); verify(tree->GetNodeType(child1) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(child1) == XMLCompleteName(UNI_L("child1"))); verify(tree->GetParent(child1) == parent1); verify(tree->GetPreviousSibling(child1) == NULL); verify(tree->GetNextSibling(child1) == child2); verify(tree->GetNodeType(child2) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(child2) == XMLCompleteName(UNI_L("child2"))); verify(tree->GetParent(child2) == parent1); verify(tree->GetPreviousSibling(child2) == child1); verify(tree->GetNextSibling(child2) == NULL); verify(grandchild1 = tree->GetFirstChild(child1)); verify(grandchild2 = tree->GetNextSibling(grandchild1)); verify(grandchild3 = tree->GetLastChild(child1)); verify(tree->GetNodeType(grandchild1) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild1) == XMLCompleteName(UNI_L("grandchild1"))); verify(tree->GetParent(grandchild1) == child1); verify(tree->GetFirstChild(grandchild1) == NULL); verify(tree->GetLastChild(grandchild1) == NULL); verify(tree->GetPreviousSibling(grandchild1) == NULL); verify(tree->GetNextSibling(grandchild1) == grandchild2); verify(tree->GetNodeType(grandchild2) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild2) == XMLCompleteName(UNI_L("grandchild2"))); verify(tree->GetParent(grandchild2) == child1); verify(tree->GetFirstChild(grandchild2) == NULL); verify(tree->GetLastChild(grandchild2) == NULL); verify(tree->GetPreviousSibling(grandchild2) == grandchild1); verify(tree->GetNextSibling(grandchild2) == grandchild3); verify(tree->GetNodeType(grandchild3) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild3) == XMLCompleteName(UNI_L("grandchild3"))); verify(tree->GetParent(grandchild3) == child1); verify(tree->GetFirstChild(grandchild3) == NULL); verify(tree->GetLastChild(grandchild3) == NULL); verify(tree->GetPreviousSibling(grandchild3) == grandchild2); verify(tree->GetNextSibling(grandchild3) == NULL); verify(grandchild1 = tree->GetFirstChild(child2)); verify(grandchild2 = tree->GetNextSibling(grandchild1)); verify(grandchild3 = tree->GetLastChild(child2)); verify(tree->GetNodeType(grandchild1) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild1) == XMLCompleteName(UNI_L("grandchild1"))); verify(tree->GetParent(grandchild1) == child2); verify(tree->GetFirstChild(grandchild1) == NULL); verify(tree->GetLastChild(grandchild1) == NULL); verify(tree->GetPreviousSibling(grandchild1) == NULL); verify(tree->GetNextSibling(grandchild1) == grandchild2); verify(tree->GetNodeType(grandchild2) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild2) == XMLCompleteName(UNI_L("grandchild2"))); verify(tree->GetParent(grandchild2) == child2); verify(tree->GetFirstChild(grandchild2) == NULL); verify(tree->GetLastChild(grandchild2) == NULL); verify(tree->GetPreviousSibling(grandchild2) == grandchild1); verify(tree->GetNextSibling(grandchild2) == grandchild3); verify(tree->GetNodeType(grandchild3) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild3) == XMLCompleteName(UNI_L("grandchild3"))); verify(tree->GetParent(grandchild3) == child2); verify(tree->GetFirstChild(grandchild3) == NULL); verify(tree->GetLastChild(grandchild3) == NULL); verify(tree->GetPreviousSibling(grandchild3) == grandchild2); verify(tree->GetNextSibling(grandchild3) == NULL); verify(child1 = tree->GetFirstChild(parent2)); verify(child2 = tree->GetLastChild(parent2)); verify(tree->GetNodeType(child1) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(child1) == XMLCompleteName(UNI_L("child1"))); verify(tree->GetParent(child1) == parent2); verify(tree->GetPreviousSibling(child1) == NULL); verify(tree->GetNextSibling(child1) == child2); verify(tree->GetNodeType(child2) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(child2) == XMLCompleteName(UNI_L("child2"))); verify(tree->GetParent(child2) == parent2); verify(tree->GetPreviousSibling(child2) == child1); verify(tree->GetNextSibling(child2) == NULL); verify(grandchild1 = tree->GetFirstChild(child1)); verify(grandchild2 = tree->GetNextSibling(grandchild1)); verify(grandchild3 = tree->GetLastChild(child1)); verify(tree->GetNodeType(grandchild1) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild1) == XMLCompleteName(UNI_L("grandchild1"))); verify(tree->GetParent(grandchild1) == child1); verify(tree->GetFirstChild(grandchild1) == NULL); verify(tree->GetLastChild(grandchild1) == NULL); verify(tree->GetPreviousSibling(grandchild1) == NULL); verify(tree->GetNextSibling(grandchild1) == grandchild2); verify(tree->GetNodeType(grandchild2) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild2) == XMLCompleteName(UNI_L("grandchild2"))); verify(tree->GetParent(grandchild2) == child1); verify(tree->GetFirstChild(grandchild2) == NULL); verify(tree->GetLastChild(grandchild2) == NULL); verify(tree->GetPreviousSibling(grandchild2) == grandchild1); verify(tree->GetNextSibling(grandchild2) == grandchild3); verify(tree->GetNodeType(grandchild3) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild3) == XMLCompleteName(UNI_L("grandchild3"))); verify(tree->GetParent(grandchild3) == child1); verify(tree->GetFirstChild(grandchild3) == NULL); verify(tree->GetLastChild(grandchild3) == NULL); verify(tree->GetPreviousSibling(grandchild3) == grandchild2); verify(tree->GetNextSibling(grandchild3) == NULL); verify(grandchild1 = tree->GetFirstChild(child2)); verify(grandchild2 = tree->GetNextSibling(grandchild1)); verify(grandchild3 = tree->GetLastChild(child2)); verify(tree->GetNodeType(grandchild1) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild1) == XMLCompleteName(UNI_L("grandchild1"))); verify(tree->GetParent(grandchild1) == child2); verify(tree->GetFirstChild(grandchild1) == NULL); verify(tree->GetLastChild(grandchild1) == NULL); verify(tree->GetPreviousSibling(grandchild1) == NULL); verify(tree->GetNextSibling(grandchild1) == grandchild2); verify(tree->GetNodeType(grandchild2) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild2) == XMLCompleteName(UNI_L("grandchild2"))); verify(tree->GetParent(grandchild2) == child2); verify(tree->GetFirstChild(grandchild2) == NULL); verify(tree->GetLastChild(grandchild2) == NULL); verify(tree->GetPreviousSibling(grandchild2) == grandchild1); verify(tree->GetNextSibling(grandchild2) == grandchild3); verify(tree->GetNodeType(grandchild3) == XMLTreeAccessor::TYPE_ELEMENT); verify(tree->GetName(grandchild3) == XMLCompleteName(UNI_L("grandchild3"))); verify(tree->GetParent(grandchild3) == child2); verify(tree->GetFirstChild(grandchild3) == NULL); verify(tree->GetLastChild(grandchild3) == NULL); verify(tree->GetPreviousSibling(grandchild3) == grandchild2); verify(tree->GetNextSibling(grandchild3) == NULL); } finally { XMLFragment::FreeXMLTreeAccessor(tree); }
#include "FreedomLanguage.h" std::tuple<std::string, std::string> __GET_OVERPARSER_FUNCS__(std::string input, Core* core, std::deque < Order >* orders); void run(std::string fn, std::string text, Core* core) { auto lexer = Lexer(text, fn); for (auto const& x : core->GetVarables()) { lexer.Variables[x.first] = true; } //to avoid deleting at the first run if (core->GetOpSymbls().size() > 0 && core->GetKeyWords().size() > 0) { lexer.SetOpSymbls(core->GetOpSymbls()); lexer.SetKeyWords(core->GetKeyWords()); } auto tokens = lexer.make_tokens(); core->SetOpSymbls(lexer.GetOpSymb()); core->SetKeyWords(lexer.GetKeyWords()); core->SetTokens(tokens); } int main() { Core core; auto parser = Parser(&core.GetTokens()); std::deque < Order > orders; std::string text; std::string cinName = ""; do { text = ""; std::cout << "freedom >>"; std::getline(std::cin, text); auto __over_funcs_result__ = __GET_OVERPARSER_FUNCS__(text, &core, &orders); cinName = std::get<0>(__over_funcs_result__); text = std::get<1>(__over_funcs_result__); run("<" + cinName + ">", text, &core); parser.SetVariables(core.GetVarables()); orders = parser.parse(core.GetTokens()); core.SetVarables(parser.GetVariables()); } while (text != "q"); } std::tuple<std::string, std::string> __GET_OVERPARSER_FUNCS__(std::string input, Core* core, std::deque < Order >* orders) { //special functions: if (input == "actvars") { for (auto const& x : core->GetVarables()) { std::cout << x.first // string (key) << ':' << x.second.Type << " = " << x.second.Value << std::endl; } } else if (input == "toks") { for (auto const& x : core->GetTokens()) { std::cout << x.Type // string (key) << ':' << x.Value << std::endl; } } else if (input == "ordrs") { for (auto x : *orders) { std::cout << x.GetTypeSTR()// string (key) << std::endl; } } else if (input == "clrvars") { std::unordered_map<std::string, Token> emptyMap; core->SetVarables(emptyMap); } else if (input == "rstrt") { Core newCore; *core = newCore; } else if (input.substr(0, 4) == "opnf") { std::string parameters[16]; short flagsSmount = 0; int flagsIreator = 5; for (; flagsIreator < input.size(); flagsIreator++) { if (input[flagsIreator] != ' ') parameters[flagsSmount] += input[flagsIreator]; else flagsSmount++; } //properties: std::string fileName = ""; bool runFromFIle = false; short paramCounter = 0; int flagsfinINX = -1; //going to the end of flags while (parameters[++flagsfinINX][0] == '-') {} for (int i = 0; i <= flagsSmount; i++) { if (parameters[i] == "-n") { fileName = parameters[flagsfinINX + paramCounter]; paramCounter++; } else if (parameters[i] == "-rn") { runFromFIle = true; } } if (runFromFIle) { Lexer lexer("", ""); std::ifstream programFile(fileName); std::string programInpuitFromFile = ""; std::string line = ""; while (std::getline(programFile, line)) { programInpuitFromFile += line; for (auto const& x : lexer.GetKeyWords()) { if (x.second == lexer.TT_NEWLN) { programInpuitFromFile += " " + x.first + " "; break; } } } return std::make_tuple(fileName, programInpuitFromFile); } } else return std::make_tuple("frdm", input); return std::make_tuple("", ""); }
#pragma once #include <iberbar/RHI/Types.h> namespace iberbar { namespace RHI { class IShader; class IVertexBuffer; class IIndexBuffer; class IUniformBuffer; class ITexture; class IShaderState; class IShaderVariableTable; class IBlendState; class IDepthStencilState; class ISamplerState; class __iberbarRHIApi__ ICommandContext abstract { public: virtual ~ICommandContext() {} public: virtual void SetVertexBuffer( uint32 nStreamIndex, IVertexBuffer* pVertexBuffer, uint32 nOffset ) = 0; virtual void SetIndexBuffer( IIndexBuffer* pIndexBuffer, uint32 nOffset ) = 0; virtual void SetShaderState( IShaderState* pShaderState ) = 0; //virtual void SetShaderVariableTable( EShaderType eShaderType, IShaderVariableTable* pShaderVariableTable ) = 0; virtual void SetTexture( EShaderType nShaderType, uint32 nTextureIndex, ITexture* pTexture ) = 0; virtual void SetSamplerState( EShaderType nShaderType, uint32 nSamplerIndex, ISamplerState* pSamplerState ) = 0; virtual void SetUniformBuffer( EShaderType nShaderType, uint32 nBufferIndex, IUniformBuffer* pUniformBuffer ) = 0; virtual void SetBlendFactor( const CColor4F& Factor ) = 0; virtual void SetBlendState( IBlendState* pBlendState, const CColor4F& Factor ) = 0; virtual void SetDepthStencilState( IDepthStencilState* pDepthStencilState, uint32 nStencilRef ) = 0; virtual void SetPrimitiveTopology( UPrimitiveType nPrimitiveType ) = 0; //virtual void DrawElements( UPrimitiveType nPrimitiveType, UIndexFormat nIndexFormat, uint32 nCount, uint32 nOffset ) = 0; virtual void DrawPrimitive( uint32 nBaseVertexIndex, uint32 nNumPrimitives ) = 0; virtual void DrawIndexed( uint32 nIndexStart, uint32 nIndexCount, uint32 nBaseVertexStart ) = 0; }; } }
#include "hf2_shared_ptr.hpp" namespace HF2 { // Scalar template<class T> SharedPointer<T>& SharedPointer<T>::operator=(SharedPointer<T>&& sp) { if (this->ctrl_ != nullptr) this->ctrl_->decrementRefCount(); this->ctrl_ = sp.ctrl_; sp.ctrl_ = nullptr; return *this; } template<class T> SharedPointer<T>& SharedPointer<T>::operator=(const SharedPointer<T>& sp) { if (this->ctrl_ != nullptr) this->ctrl_->decrementRefCount(); this->ctrl_ = sp.ctrl_; this->ctrl_->incrementRefCount(); return *this; } // Vector template<class T> SharedPointer<T[]>::SharedPointer(SharedPointer<T[]>&& sp) noexcept : Abstract_SmartPointer<T[]>{ sp.ctrl_ } { this->offset_ = sp.offset_; sp.ctrl_ = nullptr; sp.offset_ = 0U; } template<class T> SharedPointer<T[]>& SharedPointer<T[]>::operator=(SharedPointer<T[]>&& sp) noexcept { if (this->ctrl_ != nullptr) this->ctrl_->decrementRefCount(); this->ctrl_ = sp.ctrl_; sp.ctrl_ = nullptr; this->offset_ = sp.offset_; sp.offset_ = 0U; return *this; } template<class T> SharedPointer<T[]>& SharedPointer<T[]>::operator=(const SharedPointer<T[]>& sp) { if (this->ctrl_ != nullptr) this->ctrl_->decrementRefCount(); this->ctrl_ = sp.ctrl_; this->ctrl_->incrementRefCount(); this->offset_ = sp.offset_; return *this; } }
#include<iostream> #include<cstdio> using namespace std; const double NI = 1e-6; double a,b,c,d; double f(double x) { return a*x*x*x+b*x*x+c*x-d; } double ft(double x) { return 3*a*x*x+2*b*x+c; } int main() {double x0 = 0,x = 0; cin >> a >> b >> c >> d; do {double t1,t2; x0 = x; t1 = f(x0); t2 = ft(x0); x = x0 - t1/t2; //cout << x0 << " " << x << endl; }while ((x - x0) > NI || (x0 - x) > NI); printf("%.4lf",x); return 0; }
#pragma once #include <unordered_map> #include <unordered_set> #include "actor.h" #include "types.h" #include "vm.h" namespace sim::infra { enum class VMStorageEventType { kNone, kVMCreated, kVMProvisionRequested, kVMScheduled, kVMHosted, kVMStopped, kVMDeleted }; enum class VMStatus { kCreated, // VM created by no provision request received yet kHostedVM, // VMs that are currently hosted on some server kStoppedVM, // VMs that were stopped but not deleted kPending, // VMs that pending when scheduler decides where to place them kProvisioning // VMs that are set to the server by scheduler bt not hosted // yet }; struct VMStorageEvent : events::Event { VMStorageEventType type{VMStorageEventType::kNone}; UUID vm_uuid{}; }; /** * A class for VMStorage --- virtual component of the Cloud, which is * responsible for holding VM images (esp. when VM is stopped) * */ class VMStorage : public events::IActor { public: VMStorage() : events::IActor("VM-Storage") {} void HandleEvent(const events::Event* event) override; // For scheduler const auto& GetVMs() const { return vms_; } private: std::unordered_map<UUID, VMStatus> vms_; enum class VMStorageState { kOk, kFailure, }; VMStorageState state_{VMStorageState::kOk}; // event handlers void AddVM(const VMStorageEvent* event); void MoveToPending(const VMStorageEvent* event); void MoveToProvisioning(const VMStorageEvent* event); void MoveToStopped(const VMStorageEvent* event); void MoveToHosted(const VMStorageEvent* event); void DeleteVM(const VMStorageEvent* event); }; } // namespace sim::infra
#include <iostream> #include <sstream> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <climits> #include <ctime> #include <complex> #include <cmath> #include <string> #include <cctype> #include <cstring> #include <algorithm> using namespace std; typedef pair<int,int> pii; typedef long long ll; char old[10005]; char ans[10005]; int index[10005]; int m; int l,r,k; int main(){ cin>>old; cin>>m; int sz=strlen(old); while(m--){ cin>>l>>r>>k; l--; r--; for(int i=0;i<sz;i++){ index[i]=i; } k=k%(r-l+1); for(int i=l;i<=r;i++){ int t=i-l+k; t=t%(r-l+1); index[t+l]=i; } // for(int i=0;i<sz;i++){ // cout<<index[i]<<" "; // } // cout<<"\n"; for(int i=0;i<sz;i++){ ans[i]=old[index[i]]; } ans[sz]='\0'; strcpy(old,ans); // cout<<old<<"\n"; } cout<<ans<<"\n"; return 0; }
#include "TestShadows.h" #include "VertexBufferLayout.h" #include <random> namespace test { TestShadows::TestShadows() : camera(&m_Proj, &m_View, m_ScreenWidth, m_ScreenHeight) { glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); //triangle 1 glm::vec3 edge1 = m_Point2 - m_Point1; glm::vec3 edge2 = m_Point3 - m_Point1; glm::vec2 deltaUV1 = m_UV2 - m_UV1; glm::vec2 deltaUV2 = m_UV3 - m_UV1; float det = (1.0f) / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y); m_Tangent1.x = (det * deltaUV2.y * edge1.x) - (det * deltaUV1.y * edge2.x); m_Tangent1.y = (det * deltaUV2.y * edge1.y) - (det * deltaUV1.y * edge2.y); m_Tangent1.z = (det * deltaUV2.y * edge1.z) - (det * deltaUV1.y * edge2.z); m_Bitangent1.x = -(det * deltaUV2.x * edge1.x) + (det * deltaUV1.x * edge2.x); m_Bitangent1.y = -(det * deltaUV2.x * edge1.y) + (det * deltaUV1.x * edge2.y); m_Bitangent1.z = -(det * deltaUV2.x * edge1.z) + (det * deltaUV1.x * edge2.z); //triangle 2 edge1 = m_Point3 - m_Point1; edge2 = m_Point4 - m_Point1; deltaUV1 = m_UV3 - m_UV1; deltaUV2 = m_UV4 - m_UV1; det = (1.0f) / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y); m_Tangent2.x = (det * deltaUV2.y * edge1.x) - (det * deltaUV1.y * edge2.x); m_Tangent2.y = (det * deltaUV2.y * edge1.y) - (det * deltaUV1.y * edge2.y); m_Tangent2.z = (det * deltaUV2.y * edge1.z) - (det * deltaUV1.y * edge2.z); m_Bitangent2.x = -(det * deltaUV2.x * edge1.x) + (det * deltaUV1.x * edge2.x); m_Bitangent2.y = -(det * deltaUV2.x * edge1.y) + (det * deltaUV1.x * edge2.y); m_Bitangent2.z = -(det * deltaUV2.x * edge1.z) + (det * deltaUV1.x * edge2.z); float vertexBuffer[] = { m_Point1.x, m_Point1.y, m_Point1.z, m_Normal.x, m_Normal.y, m_Normal.z, m_UV1.x, m_UV1.y, m_Tangent1.x, m_Tangent1.y, m_Tangent1.z, m_Bitangent1.x, m_Bitangent1.y, m_Bitangent1.z, m_Point2.x, m_Point2.y, m_Point2.z, m_Normal.x, m_Normal.y, m_Normal.z, m_UV2.x, m_UV2.y, m_Tangent1.x, m_Tangent1.y, m_Tangent1.z, m_Bitangent1.x, m_Bitangent1.y, m_Bitangent1.z, m_Point3.x, m_Point3.y, m_Point3.z, m_Normal.x, m_Normal.y, m_Normal.z, m_UV3.x, m_UV3.y, m_Tangent1.x, m_Tangent1.y, m_Tangent1.z, m_Bitangent1.x, m_Bitangent1.y, m_Bitangent1.z, m_Point1.x, m_Point1.y, m_Point1.z, m_Normal.x, m_Normal.y, m_Normal.z, m_UV1.x, m_UV1.y, m_Tangent2.x, m_Tangent2.y, m_Tangent2.z, m_Bitangent2.x, m_Bitangent2.y, m_Bitangent2.z, m_Point3.x, m_Point3.y, m_Point3.z, m_Normal.x, m_Normal.y, m_Normal.z, m_UV3.x, m_UV3.y, m_Tangent2.x, m_Tangent2.y, m_Tangent2.z, m_Bitangent2.x, m_Bitangent2.y, m_Bitangent2.z, m_Point4.x, m_Point4.y, m_Point4.z, m_Normal.x, m_Normal.y, m_Normal.z, m_UV4.x, m_UV4.y, m_Tangent2.x, m_Tangent2.y, m_Tangent2.z, m_Bitangent2.x, m_Bitangent2.y, m_Bitangent2.z, }; float cubeVertices[] = { // back face -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, // top-left // front face -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, // top-left -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left // left face -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-left -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-right -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right // right face 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-left // bottom face -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // top-left 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-right -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right // top face -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left 1.0f, 1.0f , 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f // bottom-left }; float quadVertices[] = { // positions // texture Coords -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, }; m_PlaneVAO = std::make_unique<VertexArray>(); m_PlaneVAO->Bind(); m_PlaneVBO = std::make_unique<VertexBuffer>(vertexBuffer, sizeof(vertexBuffer)); m_PlaneVBO->Bind(); VertexBufferLayout layout; layout.Push<float>(3); layout.Push<float>(3); layout.Push<float>(2); layout.Push<float>(3); layout.Push<float>(3); m_PlaneVAO->AddBuffer(*m_PlaneVBO, layout); m_PlaneVAO->Unbind(); m_CubeVAO = std::make_unique<VertexArray>(); m_CubeVAO->Bind(); m_CubeVBO = std::make_unique<VertexBuffer>(cubeVertices, sizeof(cubeVertices)); m_CubeVBO->Bind(); VertexBufferLayout layoutCube; layoutCube.Push<float>(3); layoutCube.Push<float>(3); layoutCube.Push<float>(2); m_CubeVAO->AddBuffer(*m_CubeVBO, layoutCube); m_CubeVAO->Unbind(); m_QuadVAO = std::make_unique<VertexArray>(); m_QuadVAO->Bind(); m_QuadVBO = std::make_unique<VertexBuffer>(quadVertices, sizeof(quadVertices)); m_QuadVBO->Bind(); VertexBufferLayout quadLayout; quadLayout.Push<float>(3); quadLayout.Push<float>(2); m_QuadVAO->AddBuffer(*m_QuadVBO, quadLayout); m_QuadVAO->Unbind(); objectPositions.push_back(glm::vec3(-3.0, -0.5, -3.0)); objectPositions.push_back(glm::vec3(0.0, -0.5, -3.0)); objectPositions.push_back(glm::vec3(3.0, -0.5, -3.0)); objectPositions.push_back(glm::vec3(-3.0, -0.5, 0.0)); objectPositions.push_back(glm::vec3(0.0, -0.5, 0.0)); objectPositions.push_back(glm::vec3(3.0, -0.5, 0.0)); objectPositions.push_back(glm::vec3(-3.0, -0.5, 3.0)); objectPositions.push_back(glm::vec3(0.0, -0.5, 3.0)); objectPositions.push_back(glm::vec3(3.0, -0.5, 3.0)); m_Shader = std::make_unique<Shader>("res/shaders/NormalMap.shader"); m_DenemeShader = std::make_unique<Shader>("res/shaders/Deneme.shader"); m_HDRShader = std::make_unique<Shader>("res/shaders/HDR.shader"); m_NormalShader = std::make_unique<Shader>("res/shaders/Normal.shader", 1); m_LightShader = std::make_unique<Shader>("res/shaders/Light.shader"); m_FinalShader = std::make_unique<Shader>("res/shaders/final.shader"); m_BlurShader = std::make_unique<Shader>("res/shaders/blur.shader"); m_DiffShader = std::make_unique<Shader>("res/shaders/Diff.shader"); m_DeferredShader = std::make_unique<Shader>("res/shaders/Deferred.shader"); m_ModelShader = std::make_unique<Shader>("res/shaders/Model.shader"); m_SceneShader = std::make_unique<Shader>("res/shaders/Scene.shader"); m_LightCubeShader = std::make_unique<Shader>("res/shaders/LightCube.shader"); m_DeferringShader = std::make_unique<Shader>("res/shaders/DeferringShader.shader"); m_SSAOShader = std::make_unique<Shader>("res/shaders/SSAO.shader"); m_SSAOBlurShader = std::make_unique<Shader>("res/shaders/ssaoBlur.shader"); m_SSAOFinalShader = std::make_unique<Shader>("res/shaders/ssaoFinal.shader"); m_Textures.emplace("Diffuse", new Texture("res/textures/brick/bricks2.jpg")); m_Textures.emplace("Normal", new Texture("res/textures/brick/bricks2_normal.jpg")); m_Textures.emplace("Height", new Texture("res/textures/brick/bricks2_disp.jpg")); m_Textures.emplace("Wood", new Texture("res/textures/container_diffuse.png")); m_Textures.emplace("ToyDiffuse", new Texture("res/textures/toy/wood.png")); m_Textures.emplace("ToyNormal", new Texture("res/textures/toy/toy_box_normal.png")); m_Textures.emplace("ToyHeight", new Texture("res/textures/toy/toy_box_disp.png")); //loadModel = new obj::Model("res/obj/nanosuit/source/scene.fbx"); lightPositions.emplace_back(glm::vec3(2.0, 4.0, -2.0)); lightColors.emplace_back(glm::vec3(0.2, 0.2, 0.7)); GLCall(glGenRenderbuffers(1, &hdrRenderBuffer)); GLCall(glBindRenderbuffer(GL_RENDERBUFFER, hdrRenderBuffer)); GLCall(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_ScreenWidth, m_ScreenHeight)); glGenBuffers(1, &uniformBlock); glBindBuffer(GL_UNIFORM_BUFFER, uniformBlock); glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(glm::mat4), nullptr, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glBindBufferRange(GL_UNIFORM_BUFFER, 0, uniformBlock, 0, 2 * sizeof(glm::mat4)); glUniformBlockBinding(m_DenemeShader->GetId(), glGetUniformBlockIndex(m_DenemeShader->GetId(), "matrices"), 0); glUniformBlockBinding(m_LightShader->GetId(), glGetUniformBlockIndex(m_LightShader->GetId(), "matrices"), 0); //model = new obj::Model("res/obj/backpack/backpack.obj"); GLCall(glGenFramebuffers(1, &gBuffer)); GLCall(glBindFramebuffer(GL_FRAMEBUFFER, gBuffer)); GLCall(glGenTextures(1, &gPosition)); GLCall(glBindTexture(GL_TEXTURE_2D, gPosition)); GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, m_ScreenWidth, m_ScreenHeight, 0, GL_RGBA, GL_FLOAT, NULL)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); GLCall(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gPosition, 0)); GLCall(glGenTextures(1, &gNormal)); GLCall(glBindTexture(GL_TEXTURE_2D, gNormal)); GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, m_ScreenWidth, m_ScreenHeight, 0, GL_RGBA, GL_FLOAT, NULL)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); GLCall(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0)); unsigned int colorBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; GLCall(glGenTextures(1, &gAlbedoSpec)); GLCall(glBindTexture(GL_TEXTURE_2D, gAlbedoSpec)); GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_ScreenWidth, m_ScreenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); GLCall(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gAlbedoSpec, 0)); GLCall(glDrawBuffers(3, colorBuffers)); glGenRenderbuffers(1, &bloomRBO); GLCall(glBindRenderbuffer(GL_RENDERBUFFER, bloomRBO)); GLCall(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_ScreenWidth, m_ScreenHeight)); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, bloomRBO); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer not complete!" << std::endl; GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0)); glGenFramebuffers(1, &ssaoFBO); glBindFramebuffer(GL_FRAMEBUFFER, ssaoFBO); glGenTextures(1, &ssaoTexture); glBindTexture(GL_TEXTURE_2D, ssaoTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, m_ScreenWidth, m_ScreenHeight, 0, GL_RED, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssaoTexture, 0); glGenFramebuffers(1, &ssaoBlurFBO); glBindFramebuffer(GL_FRAMEBUFFER, ssaoBlurFBO); glGenTextures(1, &ssaoBlurTexture); glBindTexture(GL_TEXTURE_2D, ssaoBlurTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, m_ScreenWidth, m_ScreenHeight, 0, GL_RED, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssaoBlurTexture, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); std::uniform_real_distribution<float> randomFloat(0.0f, 1.0f); std::default_random_engine engine; for (int i = 0; i < 64; i++) { glm::vec3 sample = glm::vec3( randomFloat(engine) * 2.0f - 1.0f, randomFloat(engine) * 2.0f - 1.0f, randomFloat(engine)); sample = glm::normalize(sample); sample *= randomFloat(engine); float scale = (float)i / 64.0f; scale = lerp(0.1f, 1.0f, scale * scale); sample *= scale; ssaoKernel.emplace_back(sample); } for (int i = 0; i < 16; i++) { ssaoRotate.emplace_back( glm::vec3( randomFloat(engine) * 2.0f - 1.0f, randomFloat(engine) * 2.0f - 1.0f, 0.0f )); } glGenTextures(1, &noiseTexture); glBindTexture(GL_TEXTURE_2D, noiseTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 4, 4, 0, GL_RGBA, GL_FLOAT, &ssaoRotate[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); model = new obj::Model("res/obj/backpack/backpack.obj"); glViewport(0, 0, m_ScreenWidth, m_ScreenHeight); } TestShadows::~TestShadows() { } void TestShadows::OnUpdate(float deltaTime) { camera.OnUpdate(); } void TestShadows::OnRender() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); camera.OnRender(); { glBindFramebuffer(GL_FRAMEBUFFER, gBuffer); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_CubeVAO->Bind(); m_DeferringShader->Bind(); m_DeferringShader->SetUniformMat4f("u_Proj", m_Proj); m_DeferringShader->SetUniformMat4f("u_View", m_View); m_Model = glm::mat4(1.0f); m_Model = glm::translate(m_Model, glm::vec3(0.0, 7.0f, 0.0f)); m_Model = glm::scale(m_Model, glm::vec3(7.5f, 7.5f, 7.5f)); m_DeferringShader->SetUniformMat4f("u_Model", m_Model); m_DeferringShader->SetUniform1i("isInverseNormal", m_IsInverse); glDrawArrays(GL_TRIANGLES, 0, 36); m_CubeVAO->Unbind(); m_Model = glm::mat4(1.0f); m_Model = glm::translate(m_Model, glm::vec3(0.0f, 0.5f, 0.0)); m_Model = glm::rotate(m_Model, glm::radians(-90.0f), glm::vec3(1.0, 0.0, 0.0)); m_Model = glm::scale(m_Model, glm::vec3(1.0f)); m_DeferringShader->SetUniformMat4f("u_Model", m_Model); model->Draw(*m_DeferringShader); glBindFramebuffer(GL_FRAMEBUFFER, 0); } { glBindFramebuffer(GL_FRAMEBUFFER, ssaoFBO); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_QuadVAO->Bind(); m_SSAOShader->Bind(); m_SSAOShader->SetUniformMat4f("u_Proj", m_Proj); for (int i = 0; i < 64; i++) m_SSAOShader->SetUniformVec3f("samplers[" + std::to_string(i) + "]", ssaoKernel.at(i)); m_SSAOShader->SetUniform1f("bias", bias); m_SSAOShader->SetUniform1f("radius", radius); m_SSAOShader->SetUniform1f("str", str); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, gPosition); m_SSAOShader->SetUniform1i("gPosition", 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, gNormal); m_SSAOShader->SetUniform1i("gNormal", 1); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, noiseTexture); m_SSAOShader->SetUniform1i("ssaoNoise", 2); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); m_QuadVAO->Unbind(); m_SSAOShader->Unbind(); glBindFramebuffer(GL_FRAMEBUFFER, 0); } { glBindFramebuffer(GL_FRAMEBUFFER, ssaoBlurFBO); glClear(GL_COLOR_BUFFER_BIT); m_QuadVAO->Bind(); m_SSAOBlurShader->Bind(); m_SSAOBlurShader->SetUniform1i("ssaoTexture", 0); glBindTexture(GL_TEXTURE_2D, ssaoTexture); glActiveTexture(GL_TEXTURE0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); m_QuadVAO->Unbind(); m_SSAOBlurShader->Unbind(); glBindFramebuffer(GL_FRAMEBUFFER, 0); } { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_QuadVAO->Bind(); m_SSAOFinalShader->Bind(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, gPosition); m_SSAOFinalShader->SetUniform1i("gPosition", 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, gNormal); m_SSAOFinalShader->SetUniform1i("gNormal", 1); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, gAlbedoSpec); m_SSAOFinalShader->SetUniform1i("gAlbedo", 2); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, ssaoBlurTexture); m_SSAOFinalShader->SetUniform1i("SSAO", 3); glm::vec3 viewLight = glm::vec3(m_View * glm::vec4(lightPositions.at(0), 1.0f)); m_SSAOFinalShader->SetUniformVec3f("u_Light.Position", viewLight); m_SSAOFinalShader->SetUniformVec3f("u_Light.Color", lightColors.at(0)); m_SSAOFinalShader->SetUniform1f("u_Light.Linear", linear); m_SSAOFinalShader->SetUniform1f("u_Light.Quadratic", quadratic); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); m_QuadVAO->Unbind(); m_SSAOFinalShader->Unbind(); } } void TestShadows::OnImGuiRender() { ImGui::Begin("Translations"); ImGui::SliderFloat3("Light0 Translation", &lightPositions.at(0).x, -50.0f, 50.0f); ImGui::ColorEdit3("Color", &lightColors.at(0).x); ImGui::SliderFloat("Bias", &bias, 0.01f, 0.1f); ImGui::SliderFloat("Radius", &radius, 0, 1.0f); ImGui::SliderFloat("Str", &str, 0, 16.0f); ImGui::SliderFloat("Linear", &linear, 0.01f, 0.1f); ImGui::SliderFloat("Quadratic", &quadratic, 0.01f, 0.1f); ImGui::Checkbox("Is Inverse Normal", &m_IsInverse); ImGui::End(); camera.OnImGuiRender(); } }
/**** * PSEUDOCODE: MinWordLength loop array and compare each length if the length is smaller that the curent smallest set it as the smallest return shortest MaxWordLength loop array and compare each length if the length is larger that the last set it as the longest length return longest WordLegthRange return max - min word length MostCommonWordLength loop through array loop through rest of array starting at current spot count how many times the length is repeated if it is repeated the most return that * */ #include <string> int MinWordLength(std::string words[], int length) { // TODO implement this function int min = words[0].length(); for ( int word = 1; word < length; word++){ if ( min > words[word].length() ) min = words[word].length(); } return min; throw "Unsupported Operation"; } int MaxWordLength(std::string words[], int length) { // TODO implement this function int max = words[0].length(); for ( int word = 1; word < length; word++){ if ( max < words[word].length() ) max = words[word].length(); } return max; throw "Unsupported Operation"; } int WordLengthRange(std::string words[], int length) { // TODO implement this function return MaxWordLength(words, length) - MinWordLength(words, length); throw "Unsupported Operation"; } int AverageWordLength(std::string words[], int length) { // TODO implement this function int total_length = 0; for( int word = 0; word < length; word++ ){ total_length += words[word].length(); } return total_length / length; throw "Unsupported Operation"; } int MostCommonWordLength(std::string words[], int length) { // TODO implement this function int common_length = 0; int number_repeated = 0; int compare_repeated = 0; for ( int word = 0; word < length; word++){ compare_repeated = 0; for (int k = word; k < length; k++ ){ if ( words[word].length() == words[k].length()) compare_repeated++; } if (number_repeated < compare_repeated){ common_length = words[word].length(); number_repeated = compare_repeated; } } return common_length; throw "Unsupported Operation"; }
// // Created by biega on 10.03.2018. // #ifndef TANKSMAPGENERATOR_MENU_H #define TANKSMAPGENERATOR_MENU_H #include "map.h" #include "objectmap.h" #include "inputvalidator.h" #include "mapreader.h" #include "mapconverter.h" #include "mapmodificator.h" class Menu{ public: void run(); private: Map* map= nullptr; //pointer to map using in program InputValidator iv; //used to validating MapReader mr; //used to reading/writing to file MapConverter mc; //used to converitng MapModificator mm; //used to modifying ObjectMap* objectmap= nullptr;// pointer to object map int choice, running=1, sizein, x, y; //input ints and running tells if program is running or not char new_symbol; //input char std::string file_name; //input string std::fstream file; void showOptions(); void readChoice(int a, int b); void readSize(int a); void readCoordinates(); void readSymbol(); void generating(); void reading(); void writing(); void readName(); void modifying(); void display(); void exporting(); void testing(); void quit(); void writingOnlyViewMode(); }; #endif //TANKSMAPGENERATOR_MENU_H
#include <type_traits> #include <string> namespace test { template<typename T> using Add_const_reference = T const&; template<typename T> using Add_reference = T&; template<typename... Types> class tuple; template<> class tuple<> { public: constexpr tuple() {} }; template<typename Head, typename... Tail> class tuple<Head, Tail...> : private tuple<Tail...> { using Inherited = tuple<Tail...>; public: constexpr tuple() {} tuple(Add_const_reference<Head> v, Add_const_reference<Tail>... vtail) : m_head{v}, Inherited{vtail...} {} template<typename... VValues> tuple(tuple<VValues...> const& other) : m_head{other.head()}, Inherited{other.tail()} {} template<typename... VValues> tuple& operator=(tuple<VValues...> const& other) { m_head = other.head(); tail() = other.tail(); return *this; } protected: Head m_head; private: Add_reference<Head> head() { return m_head; } Add_const_reference<Head> head() const { return m_head; } Inherited& tail() { return *this; } Inherited const& tail() const { return *this; } }; template<std::size_t N> struct print_tuple { template<typename... Ts> typename std::enable_if<(N<sizeof...(Ts))>::type print(std::ostream& os, tuple<Ts...> const& t) const { os << "," << get<N>(t); print_tuple<N+1>{}(os, t); } tmeplate<typename... Ts> typename std::enable_if<!(N<sizeof...(Ts))>::type print(std::ostream& os, tuple<Ts...> const&) const { } }; } int main() { test::tuple<int, double, std::string> t{1, 5.2, std::string{"5grewgr"}}; return 0; }
/*! * \file machine.h * \author Simon Coakley * \date 2012 * \copyright Copyright (c) 2012 University of Sheffield * \brief Header file for model machine */ #ifndef MACHINE_H_ #define MACHINE_H_ #include <QList> #include <QVariant> #include <QFile> #include "./machinemodel.h" #include "./memorymodel.h" #include "./machinescene.h" #include "./timeunit.h" class MachineItem; class Machine { public: Machine(int type, Machine *parent = 0); ~Machine(); bool writeModelXML(QFile * file); void appendChild(Machine *child); Machine *child(int row); int childCount() const; int columnCount() const; QVariant data(int column) const; int row() const; Machine *parent(); void removeChild(Machine * m); void insertChild(Machine * m, int index); void addTransitionString(QString name, QString cs, QString ns, Condition c, Mpost mpost, Communication input, Communication output, QString desc); QStringList getTimeUnits(bool b = true); QStringList getAgentMemoryNames(QString name, bool b = true); QStringList getMessageMemoryNames(QString name, bool b = true); QStringList getMessageNames(bool b = true); QStringList getDataTypes(bool b = true); Machine * getMessageType(QString name, bool = true); bool isEnabled() { return enabled; } void setEnabled(bool b) { enabled = b; } Machine * rootModel() { return myRootModel; } void setRootModel(Machine * m) { myRootModel = m; } void setTimeUnit(TimeUnit t) { myTimeUnit = t; } TimeUnit timeUnit() const { return myTimeUnit; } QString filePath(); void setTimeUnitName(QString s) { myTimeUnit.name = s; } MachineModel * machineModel; MemoryModel * memoryModel; MachineScene * machineScene; QStringList timeUnitNames; QString name; QString description; /* -1-rootItem * 0-model * 1-agent * 2-message * 3-environment * 4-timeunit * 5-datatype * 6-functionFiles */ int type; bool isSubModel; QString fileDirectory; QString fileName; QList<Machine*> childItems; private: QList<QVariant> itemData; Machine *parentItem; QFile * location; bool enabled; Machine * myRootModel; TimeUnit myTimeUnit; }; #endif // MACHINE_H_
#include "renderer.h" Renderer::Renderer(Window& window): mWindow(window), mDeviceManager(mState), mSwapChainManager(mState, mWindow), tquad(mState), suit(mState), guard(mState), dwarf(mState), fullscreenQuad(mState), sceneLights(mState), gBuffer(mState), imageIndex(0) { } Renderer::~Renderer() { } void Renderer::init() { LOG_TITLE("Device Manager"); mDeviceManager.createVkInstance(); #ifdef AMVK_DEBUG mDeviceManager.enableDebug(); #endif mSwapChainManager.createSurface(); mDeviceManager.createPhysicalDevice(mSwapChainManager); mDeviceManager.createLogicalDevice(); LOG_TITLE("Swapchain"); mSwapChainManager.createSwapChain(); mSwapChainManager.createImageViews(); mSwapChainManager.createRenderPass(); mSwapChainManager.createCommandPool(); ShaderCreator::createShaders(mState); DescriptorCreator::createDescriptorSetLayouts(mState); DescriptorCreator::createDescriptorPool(mState); gBuffer.init(mState.physicalDevice, mState.device, mSwapChainManager.getWidth(), mSwapChainManager.getHeight()); PipelineCreator::createPipelines(mState, gBuffer); tquad.init(); //fullscreenQuad.init(); suit.init(FileManager::getModelsPath("nanosuit/nanosuit.obj"), Model::DEFAULT_FLAGS | aiProcess_FlipUVs); dwarf.init(FileManager::getModelsPath("dwarf/dwarf2.ms3d"), Skinned::DEFAULT_FLAGS | aiProcess_FlipUVs | aiProcess_FlipWindingOrder, Skinned::ModelFlag_stripFullPath); dwarf.ubo.model = glm::scale(glm::vec3(0.15f, 0.15f, 0.15f)); dwarf.ubo.model = glm::rotate(glm::radians(180.f), glm::vec3(1.f, 0.f, 0.f)) * dwarf.ubo.model; dwarf.ubo.model = glm::rotate(glm::radians(0.f), glm::vec3(0.f, 1.f, 0.f)) * dwarf.ubo.model; dwarf.ubo.model = glm::translate(glm::vec3(8.0f, 0.0f, -4.0f)) * dwarf.ubo.model; dwarf.animSpeedScale = 0.5f; guard.init(FileManager::getModelsPath("guard/boblampclean.md5mesh"), Skinned::DEFAULT_FLAGS | aiProcess_FlipUVs | aiProcess_FlipWindingOrder | aiProcess_FixInfacingNormals, Skinned::ModelFlag_flipNormals); guard.ubo.model = glm::scale(glm::vec3(0.18f, 0.18f, 0.18f)); guard.ubo.model = glm::rotate(glm::radians(180.f), glm::vec3(1.f, 0.f, 0.f)) * guard.ubo.model; guard.ubo.model = glm::rotate(glm::radians(-180.f), glm::vec3(0.f, 1.f, 0.f)) * guard.ubo.model; guard.ubo.model = glm::translate(glm::vec3(-9.0f, 0.0f, -8.0f)) * guard.ubo.model; for (auto& light : gBuffer.pointLights) { PointLight& p = sceneLights.createPointLight(); p.init(mState, light.color, light.position, light.radius); } sceneLights.init(); mSwapChainManager.createDepthResources(); mSwapChainManager.createFramebuffers(mState.renderPass); mSwapChainManager.createCommandBuffers(); createFences(); createSemaphores(); LOG("INIT SUCCESSFUL"); } void Renderer::updateUniformBuffers(const Timer& timer, Camera& camera) { CmdPass cmd(mState.device, mState.commandPool, mState.graphicsQueue); tquad.update(cmd.buffer, timer, camera); suit.update(cmd.buffer, timer, camera); dwarf.update(cmd.buffer, timer, camera); guard.update(cmd.buffer, timer, camera); sceneLights.update(cmd.buffer, timer, camera); //gBuffer.update(cmd.buffer, timer, camera); CmdPass tilingCmd(mState.device, gBuffer.tilingCmdPool, mState.computeQueue); gBuffer.updateTiling(tilingCmd.buffer, timer, camera); uint32_t testValue = uint32_t(-0.33 * 0xFFFF); LOG("__FPS: %u, %u", timer.FPS(), testValue); } void Renderer::buildGBuffers(const Timer &timer, Camera &camera) { std::array<VkClearValue, GBuffer::ATTACHMENT_COUNT> clearValues; clearValues[GBuffer::INDEX_POSITION].color = { { 1.0f, 0.0f, 0.0f, 0.0f } }; clearValues[GBuffer::INDEX_NORMAL].color = { { 0.0f, 0.0f, 0.0f, 1.0f } }; clearValues[GBuffer::INDEX_ALBEDO].color = { { 0.0f, 0.0f, 0.0f, 0.0f } }; clearValues[GBuffer::INDEX_DEPTH].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderPassBeginInfo = {}; renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassBeginInfo.framebuffer = gBuffer.frameBuffer; renderPassBeginInfo.renderPass = gBuffer.renderPass; renderPassBeginInfo.renderArea.offset = {0, 0}; renderPassBeginInfo.renderArea.extent.width = gBuffer.width; renderPassBeginInfo.renderArea.extent.height = gBuffer.height; renderPassBeginInfo.clearValueCount = clearValues.size(); renderPassBeginInfo.pClearValues = clearValues.data(); VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; VkCommandBuffer& cmdBuffer = gBuffer.cmdBuffer; VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBuffer, &beginInfo)); /*VkImageMemoryBarrier albedoBarrier = {}; albedoBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; albedoBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; albedoBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; albedoBarrier.image = gBuffer.albedo().image; albedoBarrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; albedoBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; albedoBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; albedoBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; albedoBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; vkCmdPipelineBarrier( cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &albedoBarrier);*/ vkCmdBeginRenderPass(cmdBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = {}; viewport.width = (float) gBuffer.width; viewport.height = (float) gBuffer.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = {0, 0}; scissor.extent.width = gBuffer.width; scissor.extent.height = gBuffer.height; vkCmdSetViewport(cmdBuffer, 0, 1, &viewport); vkCmdSetScissor(cmdBuffer, 0, 1, &scissor); guard.draw(cmdBuffer, mState.pipelines.skinned.pipeline, mState.pipelines.skinned.layout); dwarf.draw(cmdBuffer, mState.pipelines.skinned.pipeline, mState.pipelines.skinned.layout); suit.draw(cmdBuffer, mState.pipelines.model.pipeline, mState.pipelines.model.layout); vkCmdEndRenderPass(cmdBuffer); VK_CHECK_RESULT(vkEndCommandBuffer(cmdBuffer)); } void Renderer::buildComputeBuffers(const Timer &timer, Camera &camera) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; VK_CHECK_RESULT(vkBeginCommandBuffer(gBuffer.tilingCmdBuffer, &beginInfo)); VkImageMemoryBarrier imageMemoryBarrier = {}; imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; imageMemoryBarrier.image = gBuffer.tilingImage.image; imageMemoryBarrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; imageMemoryBarrier.srcAccessMask = 0; imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; VkImageMemoryBarrier albedoBarrier = {}; albedoBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; albedoBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; albedoBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; albedoBarrier.image = gBuffer.albedo().image; albedoBarrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; albedoBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; albedoBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; albedoBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; albedoBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; vkCmdPipelineBarrier( gBuffer.tilingCmdBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &albedoBarrier); //imageMemoryBarrier.srcQueueFamilyIndex = mState.computeQueueIndex; //imageMemoryBarrier.dstQueueFamilyIndex = mState.computeQueueIndex; //imageMemoryBarrier.dstQueueFamilyIndex = mState.graphicsQueueIndex; gBuffer.dispatch(); /* VkImageMemoryBarrier afterDispatchBarriers[] = { gBuffer.createTilingSrcBarrier(gBuffer.normal().image), gBuffer.createTilingSrcBarrier(gBuffer.albedo().image) }; vkCmdPipelineBarrier( gBuffer.tilingCmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, ARRAY_SIZE(afterDispatchBarriers), afterDispatchBarriers); */ VK_CHECK_RESULT(vkEndCommandBuffer(gBuffer.tilingCmdBuffer)); } void Renderer::buildCommandBuffers(const Timer &timer, Camera &camera) { VkClearValue clearValues[] ={ {{0.4f, 0.1f, 0.1f, 1.0f}}, // VkClearColorValue color; {{1.0f, 0}} // VkClearDepthStencilValue depthStencil }; VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; VkRenderPassBeginInfo renderPassBeginInfo = {}; renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassBeginInfo.renderPass = mState.renderPass; renderPassBeginInfo.renderArea.offset = {0, 0}; renderPassBeginInfo.renderArea.extent = mState.swapChainExtent; renderPassBeginInfo.clearValueCount = ARRAY_SIZE(clearValues); renderPassBeginInfo.pClearValues = clearValues; for (size_t i = 0; i < mSwapChainManager.cmdBuffers.size(); ++i) { VkCommandBuffer& cmdBuffer = mSwapChainManager.cmdBuffers[i]; VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBuffer, &beginInfo)); /*VkImageMemoryBarrier imageMemoryBarrier = {}; imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; imageMemoryBarrier.image = gBuffer.tilingImage.image; imageMemoryBarrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; imageMemoryBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; imageMemoryBarrier.srcQueueFamilyIndex = mState.computeQueueIndex; imageMemoryBarrier.dstQueueFamilyIndex = mState.graphicsQueueIndex; vkCmdPipelineBarrier( cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier); */ VkImageSubresourceLayers subres = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; VkImageBlit blit = {}; blit.srcSubresource = subres; blit.srcOffsets[0] = {0, 0, 0}; blit.srcOffsets[1] = {gBuffer.width, gBuffer.height, 1}; blit.dstSubresource = subres; blit.dstOffsets[0] = {0, 0, 0}; blit.dstOffsets[1] = {gBuffer.width, gBuffer.height, 1}; vkCmdBlitImage( cmdBuffer, gBuffer.tilingImage.image, VK_IMAGE_LAYOUT_GENERAL, mSwapChainManager.mSwapChainImages[i], VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, 1, &blit, VK_FILTER_NEAREST); blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; vkCmdBlitImage( cmdBuffer, gBuffer.depth().image, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, mSwapChainManager.mDepthImageDesc.image, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, 1, &blit, VK_FILTER_NEAREST); /* imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; imageMemoryBarrier.image = gBuffer.tilingImage.image; imageMemoryBarrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; imageMemoryBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; imageMemoryBarrier.srcQueueFamilyIndex = mState.computeQueueIndex; imageMemoryBarrier.dstQueueFamilyIndex = mState.graphicsQueueIndex; vkCmdPipelineBarrier( cmdBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier); */ /* vkCmdBlitImage( cmdBuffer, gBuffer.albedo().image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, mSwapChainManager.mSwapChainImages[i], VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, 1, &blit, VK_FILTER_NEAREST); */ /* subres.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; vkCmdBlitImage( cmdBuffer, gBuffer.depth().image, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, mSwapChainManager.mDepthImageDesc.image, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, 1, &blit, VK_FILTER_NEAREST); */ renderPassBeginInfo.framebuffer = mSwapChainManager.framebuffers[i]; vkCmdBeginRenderPass(cmdBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float) mState.swapChainExtent.width; viewport.height = (float) mState.swapChainExtent.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = {0, 0}; scissor.extent = mState.swapChainExtent; vkCmdSetViewport(cmdBuffer, 0, 1, &viewport); vkCmdSetScissor(cmdBuffer, 0, 1, &scissor); //tquad.draw(cmdBuffer); //fullscreenQuad.draw(cmdBuffer); sceneLights.draw(cmdBuffer); //dwarf.draw(cmdBuffer, mState.pipelines.skinned.pipeline, mState.pipelines.skinned.layout); //suit.draw(cmdBuffer, mState.pipelines.model.pipeline, mState.pipelines.model.layout); //guard.draw(cmdBuffer, mState.pipelines.skinned.pipeline, mState.pipelines.skinned.layout); /* gBuffer.deferredQuad.draw( cmdBuffer, mState.pipelines.fullscreenQuad.pipeline, mState.pipelines.fullscreenQuad.layout, &gBuffer.deferredQuad.mDescriptorSet, 1); */ //gBuffer.drawDeferredQuad(cmdBuffer); vkCmdEndRenderPass(cmdBuffer); VK_CHECK_RESULT(vkEndCommandBuffer(cmdBuffer)); } } void Renderer::draw() { VkResult result = vkAcquireNextImageKHR(mState.device, mState.swapChain, UINT64_MAX, imageAquiredSemaphore, VK_NULL_HANDLE, &imageIndex); if (result == VK_ERROR_OUT_OF_DATE_KHR) { recreateSwapChain(); return; } if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { VK_THROW_RESULT_ERROR("Failed vkAcquireNextImageKHR", result); return; } //LOG("CNT %u", cnt++); vkWaitForFences(mState.device, 1, &tilingFence, VK_TRUE, UINT64_MAX); vkResetFences(mState.device, 1, &tilingFence); VkPipelineStageFlags stageFlags[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; VkPipelineStageFlags tilingFlags[] = { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT }; VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAquiredSemaphore; submitInfo.pWaitDstStageMask = stageFlags; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &gBuffer.cmdBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &offscreenSemaphore; VK_CHECK_RESULT(vkQueueSubmit(mState.graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE)); submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &offscreenSemaphore; submitInfo.pWaitDstStageMask = stageFlags; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &gBuffer.tilingCmdBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &tilingFinishedSemaphore; VK_CHECK_RESULT(vkQueueSubmit(mState.computeQueue, 1, &submitInfo, tilingFence)); submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &tilingFinishedSemaphore; submitInfo.pWaitDstStageMask = tilingFlags; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &mSwapChainManager.cmdBuffers[imageIndex]; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphore; VK_CHECK_RESULT(vkQueueSubmit(mState.graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE)); VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphore; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = &mState.swapChain; presentInfo.pImageIndices = &imageIndex; VK_CHECK_RESULT(vkQueuePresentKHR(mState.presentQueue, &presentInfo)); } void Renderer::createSemaphores() { VkSemaphoreCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VK_CHECK_RESULT(vkCreateSemaphore(mState.device, &createInfo, nullptr, &imageAquiredSemaphore)); VK_CHECK_RESULT(vkCreateSemaphore(mState.device, &createInfo, nullptr, &offscreenSemaphore)); VK_CHECK_RESULT(vkCreateSemaphore(mState.device, &createInfo, nullptr, &renderFinishedSemaphore)); VK_CHECK_RESULT(vkCreateSemaphore(mState.device, &createInfo, nullptr, &tilingFinishedSemaphore)); LOG("SEMAPHORES CREATED"); } void Renderer::createFences() { VkFenceCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; info.flags = VK_FENCE_CREATE_SIGNALED_BIT; VK_CHECK_RESULT(vkCreateFence(mState.device, &info, nullptr, &tilingFence)); } void Renderer::waitIdle() { vkDeviceWaitIdle(mState.device); } void Renderer::onWindowSizeChanged(uint32_t width, uint32_t height) { recreateSwapChain(); } void Renderer::recreateSwapChain() { /* vkQueueWaitIdle(mState.graphicsQueue); vkDeviceWaitIdle(mState.device); vkFreeCommandBuffers(mState.device, mState.commandPool, (uint32_t) mVkCommandBuffers.size(), mVkCommandBuffers.data()); for (auto& framebuffer : mSwapChainFramebuffers) vkDestroyFramebuffer(mState.device, framebuffer, nullptr); vkDestroyImageView(mState.device, mDepthImageView, nullptr); vkDestroyImage(mState.device, mDepthImage, nullptr); vkFreeMemory(mState.device, mDepthImageMem, nullptr); vkDestroyPipeline(mState.device, mVkPipeline, nullptr); vkDestroyRenderPass(mState.device, mState.renderPass, nullptr); for (size_t i = 0; i < mSwapChainImages.size(); ++i) { vkDestroyImageView(mState.device, mSwapC } vkDestroySwapchainKHR(mState.device, mState.swapChain, nullptr); createSwapChain(mWindow); createImageViews(); createRenderPass(); createPipeline(); createDepthResources(); createFramebuffers(); createCommandBuffers();*/ }
#include <bits/stdc++.h> using namespace std; long long int a,b,c,d,r; vector<long long int> arr; int N; int main() { cin >> a >> b >> N; c = a%b; for(int i=0;i<N;i++){ cin >> d; if(d%b == c) r++; } cout << r; return 0; }
#include "information.h" Information::Information() { } //This function prints out the opening instructions void Information::displayOpening() { //opnun á database Service serv; bool connect = 0; connect = serv.connect(); if (!connect) { cout << "Error database not opened!"; exit(0); } cout << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << endl << "- - - - - - - - - - - - - - Welcome - - - - - - - - - - - - - - -" << endl << endl << " This program keeps information about computers and scientists " << endl << " You can add or remove from the lists" << endl << " You can change the order in which the lists is diplayed" << endl << " You can link computer and scientist together" << endl << " And you can search through the list \n" << endl << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << endl << endl; compSciOrLink(); } // Function displays info for initial action selection void Information::compSciOrLink() { cout << endl << "Do you want to work with computers, scientists or link them together? " << endl << "Press 1 for Computer " << endl << "Press 2 for Scientist " << endl << "Press 3 for Linking " << endl << "Press 4 if you want to quit" << endl; compSciOrLinkChoice(); } //Function to input and initiate initial selection of action void Information::compSciOrLinkChoice() { char number; cin >> number; cout << endl; switch (number) { case'1':{ instructions(); choices(number); break;} case '2':{ instructions(); choices(number); //scientis break;} case '3':{ linkChoice(); break;} case '4':{ //serv.disconnect(); displayClosing(); exit(0); break;} default:{ cout << "This is invalid choice!! " << endl; compSciOrLink(); break;} } } // This function askes for the first choices void Information::instructions() { cout << endl << "What do you want to do? " << endl << "Press 1 to make changes to the list." << endl << "Press 2 to display the list." << endl << "Press 3 to search." << endl; } // let the user pick the choices and calls the next function void Information::choices(char num) // 1 == computer { //vector<Scientist> vec; char number; cin >> number; cout << endl; switch (number) { case'1':{ if (num == '1') choiceChangeComp(); else if (num == '2') choiceChangeSci(); break;} case'2':{ if (num == '1') choiceSort(num); else if (num == '2') choiceSort(num); break;} case'3':{ if (num == '1') choiceSearch(num); else if (num == '2') choiceSearch(num); break;} default:{ cout << "This is invalid choice!! " << endl; choices(num); break;} } } // If the users wants to make changes to scientists this function askes what kind of change void Information::choiceChangeSci() { cout << "Here you can add or remove from the list." << endl << "Press 1 to add a person." << endl << "Press 2 to delete a person." << endl << "Press 3 to go back." << endl; addDeleteSci(); } // If the users wants to make changes to Computers this function askes what kind of change void Information::choiceChangeComp() { cout << "Here you can add or remove from the list." << endl << "Press 1 to add a computer." << endl << "Press 2 to delete a computer." << endl << "Press 3 to go back." << endl; addDeleteComp(); // gera fall fyrir computer } // If the user wants to see the hole list, this function askes in what way void Information::choiceSort(char number) { if (number == '2'){ cout << "How do you want the list to be displayed?" << endl << "Press 1 for alphabetical order A-Z." << endl << "Press 2 for reverse alphabetical order Z-A." << endl << "Press 3 to order by birth year (ascending)." << endl << "Press 4 to order by birth year (descending)." << endl << "Press 5 to arrange by gender." << endl << "Press 6 to go back." << endl; orderSci(); } else if (number == '1'){ cout << "How do you want the list to be displayed?" << endl << "Press 1 for alphabetical order A-Z." << endl << "Press 2 for reverse alphabetical order Z-A." << endl << "Press 3 to order by build year (ascending)." << endl << "Press 4 to order by build year (descending)." << endl << "Press 5 to go back." << endl; orderComp(); } } // If the user wants to search for something this function askes what to search for void Information::choiceSearch(char number) { if (number == '1') { cout << "What do you want to search for?" << endl << "Press 1 to search by name." << endl << "Press 2 to search by build year." << endl << "Press 3 to search by type." << endl << "Press 4 if you want to go back." << endl; searchComp(); } else if (number == '2') { cout << "What do you want to search for?" << endl << "Press 1 to search by name." << endl << "Press 2 to search by birth year." << endl << "Press 3 to search by gender." << endl << "Press 4 if you want to go back." << endl; searchSci(); } } // If the user wants to add, delete og change anything he pickes one here void Information::addDeleteSci() { Service serv; char number; string nameToDelete = ""; string table = "Scientists"; cin >> number; cout << endl; switch (number) { case'1':{ addScientist(); cout << endl << "--Scientist added to database!--" << endl; compSciOrLink(); break;} case'2':{ deleteStuff('1'); compSciOrLink(); break;} case'3':{ compSciOrLink(); break;} default:{ cout << "This is invalid choice! Please try again!" << endl; addDeleteSci(); break;} } } void Information::addDeleteComp() { Service serv; char number; string nameToDelete = ""; string table = "Computers"; cin >> number; cout << endl; switch (number) { case'1':{ addComputer(); cout << endl << "--Computer added to database!--" << endl; compSciOrLink(); break;} case'2':{ deleteStuff('2'); compSciOrLink(); break;} case'3':{ compSciOrLink(); break;} default:{ cout << "This is invalid choice! Please try again!" << endl; addDeleteSci(); break;} } } // If the user wants to sort the list he tells the program in what kind of way here. void Information::orderSci() { Service serv; vector<Scientist> vec; char number; cin >> number; cout << endl; switch (number) { case'1':{ cout << "List sorted in alphabetical order:" << endl << endl; vec = serv.sortSci(number); displayAll(vec); compSciOrLink(); break;} case'2':{ cout << "List sorted in reverse alphabetical order:" << endl << endl; vec = serv.sortSci(number); displayAll(vec); compSciOrLink(); break;} case'3':{ cout << "List sorted ascendingly by year of birth:" << endl << endl; vec = serv.sortSci(number); displayAll(vec); compSciOrLink(); break;} case'4':{ cout << "List sorted descendingly by year of birth:" << endl << endl; vec = serv.sortSci(number); displayAll(vec); compSciOrLink(); break;} case'5':{ cout << "List sorted by gender (Female first):" << endl << endl; command = "SELECT * FROM Scientists ORDER BY gender, name"; serv.sortSci(number); displayAll(vec); compSciOrLink(); break;} case'6':{ instructions(); choices('2'); break;} default:{ cout << "This is invalid choice " << endl; orderSci(); break;} } } //Function to select different sorting of computers in output void Information::orderComp() { Service serv; vector<Computer> vec; char number; cin >> number; cout << endl; switch (number) { case'1':{ cout << "List sorted in alphabetical order:" << endl << endl; vec = serv.sortCom(number); displayAll(vec); compSciOrLink(); break;} case'2':{ cout << "List sorted in reverse alphabetical order:" << endl << endl; vec = serv.sortCom(number); displayAll(vec); compSciOrLink(); break;} case'3':{ cout << "List sorted ascendingly by build year:" << endl << endl; vec = serv.sortCom(number); displayAll(vec); compSciOrLink(); break;} case'4':{ cout << "List sorted descendingly by year of birth:" << endl << endl; vec = serv.sortCom(number); displayAll(vec); compSciOrLink(); break;} case'5':{ instructions(); choices('1'); break;} default:{ cout << "This is invalid choice " << endl; orderComp(); break;} } } //If the user wants to search for something, he pickes the way here void Information::searchSci() { Service serv; vector<Scientist> vec; char number; string searchStr; cin >> number; cout << endl; switch (number) { case'1':{ cout << "Enter a name to search for: " << endl; cin.ignore(); getline(cin,searchStr); cout << endl << "Search results: " << endl << endl; vec = serv.searchSci(searchStr, number); displayAll(vec); compSciOrLink(); break;} case'2':{ cout << "Enter a year of birth to search for: " << endl; cin >> searchStr; cout << endl << "Search results: " << endl << endl; vec = serv.searchSci(searchStr, number); displayAll(vec); compSciOrLink(); break;} case'3':{ cout << "Enter either 'M' or 'F' to search by gender:" << endl; cin >> searchStr; cout << endl << "Search results: " << endl << endl; serv.searchSci(searchStr, number); displayAll(vec); compSciOrLink(); break;} case'4':{ compSciOrLink(); break;} default:{ cout << endl << "This is invalid choice!" << endl; searchSci(); break;} } } //Funtion for selecting ways to search for computers void Information::searchComp() { Service serv; vector<Computer> vec; char number; string searchStr; cin >> number; cout << endl; switch (number) { case'1':{ cout << "Enter a Computer to search for: " << endl; cin.ignore(); getline(cin,searchStr); cout << endl << "Search results: " << endl << endl; vec = serv.searchCom(searchStr, number); displayAll(vec); compSciOrLink(); break;} case'2':{ cout << "Enter a buildyear to search for: " << endl; cin >> searchStr; cout << endl << "Search results: " << endl << endl; vec = serv.searchCom(searchStr, number); displayAll(vec); compSciOrLink(); break;} case'3':{ cout << "Enter a type to search for: " << endl; cin >> searchStr; cout << endl << "Search results: " << endl << endl; vec = serv.searchCom(searchStr, number); displayAll(vec); compSciOrLink(); break;} case'4':{ compSciOrLink(); break;} default:{ cout << endl << "This is invalid choice!" << endl; searchSci(); break;} } } // gives the instructions about adding a scientist void Information::addScientist() { Service serv; cout << "Enter information about the computer scientist whom you wish to add" << endl; cout << "If he/she is still alive put in '0' in 'Year of death'" << endl; cout << "In gender, enter 'M' for male or 'F' for female"<< endl; string name, gender, yod, yob; const string alive = "0"; cout << "Name: "; cin.ignore(); getline(cin,name); cout << "Year of birth: "; cin >> yob; cout << "Year of death: "; cin >> yod; cout << "Gender: "; cin >> gender; if(gender == "m") gender = "M"; else if(gender == "f") gender = "F"; serv.addScientist(name, yob, yod, gender); } //Function to get input to add computers void Information::addComputer() { Service serv; cout << "Enter information about the computer that you wish to add" << endl; string name, toc, yearBuilt; char number; string built = "1"; cout << "Name: "; cin.ignore(); getline(cin,name); cout << "Year built (0 if not built): "; cin >> yearBuilt; if (yearBuilt == "0") { built = "0"; } cout << "Type of computer: " << endl << "1. Electronical"<< endl << "2. Mechanical"<< endl << "3. Transitor"<< endl; do{ cin >> number; toc = typeOfComputer(number); } while (number != '1' && number != '2' && number != '3'); serv.addComputer(name, yearBuilt, built, toc); } // Prints out the scientists void Information::displayAll(vector<Scientist> vec) { for(unsigned int i = 0; i < vec.size(); i++){ cout << vec[i] << endl; } } // Prints out the computers void Information::displayAll(vector<Computer> vec) { for(unsigned int i = 0; i < vec.size(); i++){ cout << vec[i] << endl; } } //Function for selection of computertypes string Information::typeOfComputer(char choice) { string type; switch (choice) { case'1':{ type = "Electronical"; break;} case'2':{ type = "Mechanical"; break;} case'3':{ type = "Transitor"; break;} default:{ cout << "This is invalid choice! Please try again!" << endl; break;} } return type; } //Function to remove selected items in vectors void Information::deleteStuff(char number){ vector<Scientist> SciVec; vector<Computer> CompVec; Service serv; string nameToDelete; unsigned int numToDelete; char choice; if(number == '1'){ cout << "Enter the name of a scientist to remove:" << endl; cin.ignore(); getline(cin,nameToDelete); cout << endl << "Search results: " << endl << endl; SciVec = serv.searchSci(nameToDelete, '1'); if(SciVec.size() == 0){ cout << "No matches" << endl; deleteStuff(number);} for(unsigned int i = 0; i < SciVec.size(); i++) cout << i+1 << endl << SciVec[i] << endl; cout << "Enter the number of the scientist you wish to remove: " << endl; cin >> numToDelete; if(numToDelete > SciVec.size()){ cout << "That is an invalid choice" << endl; deleteStuff(number);} numToDelete--; nameToDelete = SciVec[numToDelete].getName(); cout << "Are you sure you want to delete " << nameToDelete << " from the database?"; cout << endl << "This can not be undone! (y/n)?" << endl; cin >> choice; if(choice == 'y'){ serv.deleteData(number, nameToDelete); cout << nameToDelete << " has now been removed." << endl; } else choiceChangeComp(); } else{ cout << "Enter the name of a computer to remove:" << endl; cin.ignore(); getline(cin,nameToDelete); cout << endl << "Search results: " << endl << endl; CompVec = serv.searchCom(nameToDelete, '1'); if(CompVec.size() == 0){ cout << "No matches" << endl; deleteStuff(number);} for(unsigned int i = 0; i < CompVec.size(); i++) cout << i+1 << endl << CompVec[i] << endl; cout << "Enter the number of the computer you wish to remove: " << endl; cin >> numToDelete; if(numToDelete > CompVec.size()){ cout << "That is an invalid choice" << endl; deleteStuff(number);} numToDelete--; nameToDelete = CompVec[numToDelete].getName(); cout << "Are you sure you want to delete " << nameToDelete << " from the database?"; cout << endl << "This can not be undone! (y/n)?" << endl; cin >> choice; if(choice == 'y'){ serv.deleteData(number, nameToDelete); cout << nameToDelete << " has now been removed." << endl; } else choiceChangeComp(); } } //Fuction to display EXIT comment void Information::displayClosing() { Service serv; bool connected = 1; connected = serv.disconnect(); if (!connected){ system("cls"); //Clears the screen cout << endl; cout << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << endl << "- - - - - - - Thank you for using this program! - - - - - - -" << endl << endl << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << endl << "\t \t Database successfully closed!" << endl << endl << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << endl << endl << endl; } exit (0); } //Function to display selection of actions for linked tables of Computers and Scientists void Information::linkChoice() { cout << endl << "Press 1 to add a link." << endl << "Press 2 to delete a link." << endl << "Press 3 to display Relations" <<endl << "Press 4 to go back" << endl; addDeleteLink(); } void Information::addDeleteLink() { Service serv; char number; cin >> number; string scientist; string computer; vector<string> vec; switch(number) { case '1':{ //Add a link cout << "Please enter the full name of a scientist :" << endl; cin.ignore(); getline(cin,scientist); cout << "Please enter the full name of a computer:" << endl; cin.ignore(); getline(cin,computer); serv.addDeleteLink(scientist, computer, number); cout << "The link has been added!" << endl; compSciOrLink();} case '2':{ //Delete a link cout << "Please enter the full name of a scientist:" << endl; cin.ignore(); getline(cin,scientist); cout << "Please enter the full name of a computer:" << endl; cin.ignore(); getline(cin,computer); serv.addDeleteLink(scientist, computer, number); cout << "The link has been removed!" << endl; compSciOrLink();} case '3':{ //display function vec =serv.getRelations(); display(vec); compSciOrLink();} case '4':{ //Go back compSciOrLink(); break;} default:{ cout << "This is not a valid choice! Please choose again." << endl; linkChoice();} } } void Information::display(vector<string> vec) { for (unsigned int i =0; i <vec.size(); i++) { cout << vec[i]<< endl; } }
#include "game/HealthBar.hpp" HealthBar::HealthBar(){ health = 100; damage = 0; x = 10; y = 10; healthBar = new SDL_Rect(); damageBar = new SDL_Rect(); BarBoundary = new SDL_Rect(); healthBar->x = x; healthBar->y = y; damageBar->x = x; damageBar->y = y; BarBoundary->x = x; BarBoundary->y = y; BarBoundary->w = (health*SCREEN_WIDTH*2)/500; BarBoundary->h = (20); UpdateBar(); } void HealthBar::UpdateBar(){ healthBar->w = ((health*SCREEN_WIDTH*2)/500); healthBar->h = (20); damageBar->w = ((health+damage)*SCREEN_WIDTH*2)/500; damageBar->h = (20); } void HealthBar::setHealth(int h){ damage = max(0, health - h); health = h; UpdateBar(); } int HealthBar::getHealth(){ return health; } int HealthBar::getDamage(){ return damage; } void HealthBar::render(){ SDL_SetRenderDrawColor(gEngine->gRenderer, 255, 0, 0, 255 ); SDL_RenderFillRect(gEngine->gRenderer, damageBar); SDL_SetRenderDrawColor(gEngine->gRenderer, 0, 255, 0, 255 ); SDL_RenderFillRect(gEngine->gRenderer, healthBar); SDL_SetRenderDrawColor(gEngine->gRenderer, 0, 0, 0, 255); SDL_RenderDrawRect(gEngine->gRenderer, BarBoundary); }
#include "MaTaille.h" CMaTaille::CMaTaille(QWidget *parent, int Largeur, int Hauteur) : QDialog(parent), m_nLargeur(Largeur), m_nHauteur(Hauteur) { ui.setupUi(this); IsModifier=false; m_proportion = static_cast<double>(Hauteur) /Largeur; ui.spinBoxHauteur->setMinimum(0); ui.spinBoxHauteur->setMaximum(Hauteur*3); ui.spinBoxHauteur->setValue(Hauteur); ui.spinBoxLargeur->setMinimum(0); ui.spinBoxLargeur->setMaximum(Largeur*3); ui.spinBoxLargeur->setValue(Largeur); connect (ui.spinBoxHauteur,SIGNAL(valueChanged(int)),this,SLOT(Haut())); connect (ui.spinBoxLargeur,SIGNAL(valueChanged(int)),this,SLOT(Larg())); connect (ui.buttonBox,SIGNAL(accepted()),this,SLOT(MonOk())); connect (ui.buttonBox,SIGNAL(rejected()),this,SLOT(close())); } CMaTaille::~CMaTaille() { } QSize CMaTaille::getDim () { return QSize(m_nLargeur, m_nHauteur); } void CMaTaille::MonOk() { m_nLargeur = ui.spinBoxLargeur->value(); m_nHauteur = ui.spinBoxHauteur->value(); close(); } void CMaTaille::Larg() { if(!IsModifier) { if(ui.checkBoxProportionel->isChecked()) { IsModifier=true; ui.spinBoxHauteur->setValue(ui.spinBoxLargeur->value()*m_proportion); } } else IsModifier=false; } void CMaTaille::Haut() { if(!IsModifier) { if(ui.checkBoxProportionel->isChecked()) { IsModifier=true; ui.spinBoxLargeur->setValue(ui.spinBoxHauteur->value()/m_proportion); } } else IsModifier=false; }
#include <iostream> using namespace std; int main() { int a, b, c; char Operator; cout<<"Enter any Operator:"; cin>>Operator; switch(Operator) { case '+': cout<<"Enter value for A:"; cin>>a; cout<<"Enter value for B:"; cin>>b; c = a + b; cout<<"Addition is:"<<c; break; case '-': cout<<"Enter value for A:"; cin>>a; cout<<"Enter value for B:"; cin>>b; c = a - b; cout<<"Subtraction is:"<<c; break; case '*': cout<<"Enter value for A:"; cin>>a; cout<<"Enter value for B:"; cin>>b; c = a * b; cout<<"Multiplication is:"<<c; break; case '/': cout<<"Enter value for A:"; cin>>a; cout<<"Enter value for B:"; cin>>b; c = a / b; cout<<"Division is:"<<c; break; default: cout<<"You have entered the wrong operator"; } return 0; }
// // Created by abel_ on 15-10-2022. // // // Created by abel_ on 15-10-2022. // #include <vector> #include <stack> #include <unordered_set> #include <iostream> #include <tuple> #include <algorithm> #include <limits> int explore(std::vector<std::vector<char>> &grid ,int row,int column,std::unordered_set<std::string> &visited){ int rowInbounds = row >= 0 and row < grid.size(); int colInbounds = column >= 0 and column < grid[0].size(); if(!rowInbounds or !colInbounds) return 0; int islandSize = 0; if(grid[row][column] == 'W') return 0; std::string key = std::to_string(row) + "," + std::to_string(column); if(visited.count(key) > 0) return 0; visited.insert(key); islandSize += explore(grid,row-1,column,visited); islandSize += explore(grid,row+1,column,visited); islandSize += explore(grid,row,column-1,visited); islandSize += explore(grid,row,column+1,visited); return islandSize + 1; } int minimumIsland(std::vector<std::vector<char>> &grid){ int minIslandCount = std::numeric_limits<int>::max(); std::unordered_set<std::string> visited; for(int row=0;row<grid.size();row++){ for(int column=0;column<grid.size();column++){ int islandSize = explore(grid,row,column,visited); // std::cout << islandSize << std::endl; if(islandSize > 0 and islandSize < minIslandCount) minIslandCount = islandSize; } } return minIslandCount; } int main(){ std::vector<std::vector<char>> grid { {'W', 'W'}, {'L', 'L'}, {'W', 'W'}, {'W', 'L'} }; std::cout<<minimumIsland(grid); // -> 2 return 0; }
void ciclo1(){ if(sensorNivel->switchMode() && contadorNivel<6){ digitalWrite(EV_EntradaAgua, LOW); digitalWrite(mRecirculacion, HIGH); if(flagContadorNivel){ contadorNivel++; } }else if(contadorNivel<6){ digitalWrite(EV_EntradaAgua, HIGH); flagContadorNivel = true; } if(contadorNivel>=6){ digitalWrite(EV_EntradaAgua, LOW); digitalWrite(mRecirculacion, LOW); } }
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef pair<int, int> pii; #define ll long long #define fi first #define se second #define pb push_back #define mp make_pair #define ALL(v) v.begin(), v.end() #define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a)) #define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a)) #define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a)) #define FOREACH(a, b) for (auto&(a) : (b)) #define REP(i, n) FOR(i, 0, n) #define REPN(i, n) FORN(i, 1, n) #define dbg(x) cout << (#x) << " is " << (x) << endl; #define dbg2(x, y) cout << (#x) << " is " << (x) << " and " << (#y) << " is " << y << endl; #define dbgarr(x, sz) \ for (int asdf = 0; asdf < (sz); asdf++) cout << x[asdf] << ' '; \ cout << endl; #define dbgarr2(x, rose, colin) \ for (int asdf2 = 0; asdf2 < rose; asdf2++) { \ dbgarr(x[asdf2], colin); \ } #define dbgitem(x) \ for (auto asdf = x.begin(); asdf != x.end(); asdf++) cout << *asdf << ' '; \ cout << endl; const int mod = 1e9 + 7, dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}, MAXN = 3e5; int n, m, diam[MAXN], reps[MAXN], Q; vi adj[MAXN]; struct Solution { Solution() { // find diams of each region memset(reps, -1, sizeof(reps)); REP(i, n) { for (int j : adj[i]) set_union(i, j); } REP(i, n) if (reps[i] == -1) diam[i] = get_diameter(i); // dbgarr(reps, n); // dbgarr(diam, n); } int find(int a) { if (reps[a] != -1) { return reps[a] = find(reps[a]); // with path compression; } return a; } int get_diameter(int i) { // returns diam from the region i is in i = farthest(i, 0, -1).second; return farthest(i, 0, -1).first; } pii farthest(int i, int d, int p) { // returns {dist, node} farthest from i; d= dist from source node pii res = {d, i}; for (int j : adj[i]) { if (j == p) continue; res = max(res, farthest(j, d + 1, i)); } return res; } void set_union(int a, int b) { int pa = find(a), pb = find(b); if (pa != pb) reps[pa] = pb; } int solve(int i) { // diam in region of i return diam[find(i)]; } void update(int a, int b) { // query 2 int pa = find(a), pb = find(b); if (pa == pb) return; reps[pa] = pb, diam[pb] = max(max(diam[pb], diam[pa]), (diam[pb] + 1) / 2 + (diam[pa] + 1) / 2 + 1); } }; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> m >> Q; int a, b; REP(i, m) { cin >> a >> b, adj[--a].push_back(--b), adj[b].push_back(a); } Solution test; while (Q--) { cin >> a >> b; if (a == 1) cout << test.solve(b - 1) << endl; else cin >> a, test.update(a - 1, b - 1); } }
// CLeftTView.cpp: 구현 파일 // #include "pch.h" #include "MFC_SplitWnd.h" #include "CLeftTView.h" // CLeftTView IMPLEMENT_DYNCREATE(CLeftTView, CTreeView) CLeftTView::CLeftTView() { } CLeftTView::~CLeftTView() { } BEGIN_MESSAGE_MAP(CLeftTView, CTreeView) END_MESSAGE_MAP() // CLeftTView 진단 #ifdef _DEBUG void CLeftTView::AssertValid() const { CTreeView::AssertValid(); } #ifndef _WIN32_WCE void CLeftTView::Dump(CDumpContext& dc) const { CTreeView::Dump(dc); } #endif #endif //_DEBUG // CLeftTView 메시지 처리기
static int ft_isspace(char c) { if (c == ' ' || c == '\n' || c == '\t' || c == '\v' || c == '\f' || c == '\r') return (1); return (0); } static int ft_isdigit(int c) { if (c >= '0' && c <= '9') return (1); return (0); } int ft_atoi(const char *s) { int i; int sign; long res; i = 0; sign = 1; res = 0; while (s[i] && ft_isspace(s[i])) i++; if (s[i] == '+' || s[i] == '-') { if (s[i] == '-') sign *= -1; i++; } while (s[i] && ft_isdigit(s[i])) { res = res * 10 + (s[i] - 48); i++; } return (res * sign); }
#include <bits/stdc++.h> using namespace std; typedef long long ll; int N_box[200001]; int main() { int n; cin >> n; vector<int> a, b; for (int i = 0; i < n; i++) { int tmp; cin >> tmp; a.push_back(tmp); } // nから0を見ていく for (int i = n; i > 0; i--) { int tmp = 0; for (int j = i; j <= n; j+=i) { tmp += N_box[j]; } //printf("[%d] a_left = %d a_right = %d \n", i, tmp, a[i-1]); if (tmp % 2 != a[i - 1]){ N_box[i] = 1; b.push_back(i); } else { N_box[i] = 0; } } cout << b.size() << endl; for(auto i: b){ cout << i << " "; } cout << endl; }
/*In this program we will be seeing about LOOPS CONTROL STATEMENTS in C++ Program*/ /*In C++ break , continue and goto are called as LOOP CONTROL STATEMENT, which is been used for controling the flow of loop in a c++ program.*/ /*In this Example lets see how CONTINUE works in a program.*/ /*Continue is a type of loop control statement which is used to terminate only particular iteration, and execute next iteration of the loop.*/ /*Syntax of continue continue; */ /*including preprocessor / header file in the program*/ #include <iostream> /*using namespace*/ using namespace std ; /*creating a main() function of the program*/ int main() { for ( int i = 1 ; i <= 10 ; i++) { if ( i == 7) { cout<<"\nContinue has been applied . Thus the next Iteration has taken placed by skipping this particular iteration. \n\nThat is it skip only when i is equal to 7 and prints the remaining." << endl ; continue; } cout<<"\nValue of i = " << i << endl ; } cout<<"\nContinue Statement has executed SUCCESSFULLY....." << endl ; }
#include"ClassDate.h" int main() { TestDate(); return 0; }
//------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com> Portions of this file are from JUCE. Copyright (c) 2013 - Raw Material Software Ltd. Please visit http://www.juce.com Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== PerformanceCounter::PerformanceCounter (const String& name_, const int runsPerPrintout, const File& loggingFile) : name (name_), numRuns (0), runsPerPrint (runsPerPrintout), totalTime (0), outputFile (loggingFile) { if (outputFile != File::nonexistent ()) { String s ("**** Counter for \""); s << name_ << "\" started at: " << Time::getCurrentTime().toString (true, true) << newLine; outputFile.appendText (s, false, false); } } PerformanceCounter::~PerformanceCounter() { printStatistics(); } void PerformanceCounter::start() { started = Time::getHighResolutionTicks(); } void PerformanceCounter::stop() { const int64 now = Time::getHighResolutionTicks(); totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started); if (++numRuns == runsPerPrint) printStatistics(); } void PerformanceCounter::printStatistics() { if (numRuns > 0) { String s ("Performance count for \""); s << name << "\" - average over " << numRuns << " run(s) = "; const int micros = (int) (totalTime * (1000.0 / numRuns)); if (micros > 10000) s << (micros/1000) << " millisecs"; else s << micros << " microsecs"; s << ", total = " << String (totalTime / 1000, 5) << " seconds"; Logger::outputDebugString (s); s << newLine; if (outputFile != File::nonexistent ()) outputFile.appendText (s, false, false); numRuns = 0; totalTime = 0; } }
#ifndef TILEDEFINITIONMODEL_HPP #define TILEDEFINITIONMODEL_HPP #include <QAbstractItemModel> #include <Tileset.hpp> #include <vector> #include <QIcon> namespace Maint { class LevelManager; class TextureManager; class TileDefinitionModel : public QAbstractItemModel { Q_OBJECT Tileset* tileset; TextureManager* _textureManager; std::vector<QIcon> tileIcons; LevelManager* _levelManager; void UpdateIcon(int row); public: explicit TileDefinitionModel(LevelManager* levelManager, TextureManager* textureManager, QObject *parent = 0); QModelIndex index(int row, int column, const QModelIndex &parent) const; QModelIndex parent(const QModelIndex &child) const; int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; void SetTileset(Tileset* tileset); void AddTileDefinition(const TileDefinition& definition); void SetTileDefinition(int index, const TileDefinition& definition); Tileset const* GetTileset(); /** * @return Returns the width of an individual tile. */ int GetTileWidth(); /** * @return Returns the height of an individual tile. */ int GetTileHeight(); signals: public slots: private slots: void Refresh(); }; } #endif // TILEDEFINITIONMODEL_HPP
/** @file ***************************************************************************** * @author This file is part of libsnark, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #include "algebra/curves/bls48/bls48_g1.hpp" namespace libsnark { #ifdef PROFILE_OP_COUNTS long long bls48_G1::add_cnt = 0; long long bls48_G1::dbl_cnt = 0; #endif std::vector<size_t> bls48_G1::wnaf_window_table; std::vector<size_t> bls48_G1::fixed_base_exp_window_table; bls48_G1 bls48_G1::G1_zero; bls48_G1 bls48_G1::G1_one; bls48_G1::bls48_G1() { this->X = G1_zero.X; this->Y = G1_zero.Y; this->Z = G1_zero.Z; } void bls48_G1::print() const { if (this->is_zero()) { printf("O\n"); } else { bls48_G1 copy(*this); copy.to_affine_coordinates(); gmp_printf("(%Nd , %Nd)\n", copy.X.as_bigint().data, bls48_Fq::num_limbs, copy.Y.as_bigint().data, bls48_Fq::num_limbs); } } void bls48_G1::print_coordinates() const { if (this->is_zero()) { printf("O\n"); } else { gmp_printf("(%Nd : %Nd : %Nd)\n", this->X.as_bigint().data, bls48_Fq::num_limbs, this->Y.as_bigint().data, bls48_Fq::num_limbs, this->Z.as_bigint().data, bls48_Fq::num_limbs); } } void bls48_G1::to_affine_coordinates() { if (this->is_zero()) { this->X = bls48_Fq::zero(); this->Y = bls48_Fq::one(); this->Z = bls48_Fq::zero(); } else { bls48_Fq Z_inv = Z.inverse(); bls48_Fq Z2_inv = Z_inv.squared(); bls48_Fq Z3_inv = Z2_inv * Z_inv; this->X = this->X * Z2_inv; this->Y = this->Y * Z3_inv; this->Z = bls48_Fq::one(); } } void bls48_G1::to_special() { this->to_affine_coordinates(); } bool bls48_G1::is_special() const { return (this->is_zero() || this->Z == bls48_Fq::one()); } bool bls48_G1::is_zero() const { return (this->Z.is_zero()); } bool bls48_G1::operator==(const bls48_G1 &other) const { if (this->is_zero()) { return other.is_zero(); } if (other.is_zero()) { return false; } /* now neither is O */ // using Jacobian coordinates so: // (X1:Y1:Z1) = (X2:Y2:Z2) // iff // X1/Z1^2 == X2/Z2^2 and Y1/Z1^3 == Y2/Z2^3 // iff // X1 * Z2^2 == X2 * Z1^2 and Y1 * Z2^3 == Y2 * Z1^3 bls48_Fq Z1_squared = (this->Z).squared(); bls48_Fq Z2_squared = (other.Z).squared(); if ((this->X * Z2_squared) != (other.X * Z1_squared)) { return false; } bls48_Fq Z1_cubed = (this->Z) * Z1_squared; bls48_Fq Z2_cubed = (other.Z) * Z2_squared; if ((this->Y * Z2_cubed) != (other.Y * Z1_cubed)) { return false; } return true; } bool bls48_G1::operator!=(const bls48_G1& other) const { return !(operator==(other)); } bls48_G1 bls48_G1::operator+(const bls48_G1 &other) const { // handle special cases having to do with O if (this->is_zero()) { return other; } if (other.is_zero()) { return *this; } // no need to handle points of order 2,4 // (they cannot exist in a prime-order subgroup) // check for doubling case // using Jacobian coordinates so: // (X1:Y1:Z1) = (X2:Y2:Z2) // iff // X1/Z1^2 == X2/Z2^2 and Y1/Z1^3 == Y2/Z2^3 // iff // X1 * Z2^2 == X2 * Z1^2 and Y1 * Z2^3 == Y2 * Z1^3 bls48_Fq Z1Z1 = (this->Z).squared(); bls48_Fq Z2Z2 = (other.Z).squared(); bls48_Fq U1 = this->X * Z2Z2; bls48_Fq U2 = other.X * Z1Z1; bls48_Fq Z1_cubed = (this->Z) * Z1Z1; bls48_Fq Z2_cubed = (other.Z) * Z2Z2; bls48_Fq S1 = (this->Y) * Z2_cubed; // S1 = Y1 * Z2 * Z2Z2 bls48_Fq S2 = (other.Y) * Z1_cubed; // S2 = Y2 * Z1 * Z1Z1 if (U1 == U2 && S1 == S2) { // dbl case; nothing of above can be reused return this->dbl(); } // rest of add case bls48_Fq H = U2 - U1; // H = U2-U1 bls48_Fq S2_minus_S1 = S2-S1; bls48_Fq I = (H+H).squared(); // I = (2 * H)^2 bls48_Fq J = H * I; // J = H * I bls48_Fq r = S2_minus_S1 + S2_minus_S1; // r = 2 * (S2-S1) bls48_Fq V = U1 * I; // V = U1 * I bls48_Fq X3 = r.squared() - J - (V+V); // X3 = r^2 - J - 2 * V bls48_Fq S1_J = S1 * J; bls48_Fq Y3 = r * (V-X3) - (S1_J+S1_J); // Y3 = r * (V-X3)-2 S1 J bls48_Fq Z3 = ((this->Z+other.Z).squared()-Z1Z1-Z2Z2) * H; // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H return bls48_G1(X3, Y3, Z3); } bls48_G1 bls48_G1::operator-() const { return bls48_G1(this->X, -(this->Y), this->Z); } bls48_G1 bls48_G1::operator-(const bls48_G1 &other) const { return (*this) + (-other); } bls48_G1 bls48_G1::add(const bls48_G1 &other) const { // handle special cases having to do with O if (this->is_zero()) { return other; } if (other.is_zero()) { return *this; } // no need to handle points of order 2,4 // (they cannot exist in a prime-order subgroup) // handle double case if (this->operator==(other)) { return this->dbl(); } #ifdef PROFILE_OP_COUNTS this->add_cnt++; #endif // NOTE: does not handle O and pts of order 2,4 // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl bls48_Fq Z1Z1 = (this->Z).squared(); // Z1Z1 = Z1^2 bls48_Fq Z2Z2 = (other.Z).squared(); // Z2Z2 = Z2^2 bls48_Fq U1 = (this->X) * Z2Z2; // U1 = X1 * Z2Z2 bls48_Fq U2 = (other.X) * Z1Z1; // U2 = X2 * Z1Z1 bls48_Fq S1 = (this->Y) * (other.Z) * Z2Z2; // S1 = Y1 * Z2 * Z2Z2 bls48_Fq S2 = (other.Y) * (this->Z) * Z1Z1; // S2 = Y2 * Z1 * Z1Z1 bls48_Fq H = U2 - U1; // H = U2-U1 bls48_Fq S2_minus_S1 = S2-S1; bls48_Fq I = (H+H).squared(); // I = (2 * H)^2 bls48_Fq J = H * I; // J = H * I bls48_Fq r = S2_minus_S1 + S2_minus_S1; // r = 2 * (S2-S1) bls48_Fq V = U1 * I; // V = U1 * I bls48_Fq X3 = r.squared() - J - (V+V); // X3 = r^2 - J - 2 * V bls48_Fq S1_J = S1 * J; bls48_Fq Y3 = r * (V-X3) - (S1_J+S1_J); // Y3 = r * (V-X3)-2 S1 J bls48_Fq Z3 = ((this->Z+other.Z).squared()-Z1Z1-Z2Z2) * H; // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H return bls48_G1(X3, Y3, Z3); } bls48_G1 bls48_G1::mixed_add(const bls48_G1 &other) const { #ifdef DEBUG assert(other.is_special()); #endif // handle special cases having to do with O if (this->is_zero()) { return other; } if (other.is_zero()) { return *this; } // no need to handle points of order 2,4 // (they cannot exist in a prime-order subgroup) // check for doubling case // using Jacobian coordinates so: // (X1:Y1:Z1) = (X2:Y2:Z2) // iff // X1/Z1^2 == X2/Z2^2 and Y1/Z1^3 == Y2/Z2^3 // iff // X1 * Z2^2 == X2 * Z1^2 and Y1 * Z2^3 == Y2 * Z1^3 // we know that Z2 = 1 const bls48_Fq Z1Z1 = (this->Z).squared(); const bls48_Fq &U1 = this->X; const bls48_Fq U2 = other.X * Z1Z1; const bls48_Fq Z1_cubed = (this->Z) * Z1Z1; const bls48_Fq &S1 = (this->Y); // S1 = Y1 * Z2 * Z2Z2 const bls48_Fq S2 = (other.Y) * Z1_cubed; // S2 = Y2 * Z1 * Z1Z1 if (U1 == U2 && S1 == S2) { // dbl case; nothing of above can be reused return this->dbl(); } #ifdef PROFILE_OP_COUNTS this->add_cnt++; #endif // NOTE: does not handle O and pts of order 2,4 // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-madd-2007-bl bls48_Fq H = U2-(this->X); // H = U2-X1 bls48_Fq HH = H.squared() ; // HH = H^2 bls48_Fq I = H*HH; // I = H^3 bls48_Fq J = (this->X)*HH; // J = X1*HH bls48_Fq r = S2-(this->Y); // r = S2-Y1 bls48_Fq X3 = r.squared()-I-J-J; // X3 = r^2-I-2*J bls48_Fq Y3 = (this->Y)*I; // Y3 = r*(J-X3)-Y1*I Y3 = r*(J-X3) - Y3; bls48_Fq Z3 = (this->Z)*H; // Z3 = Z1*H return bls48_G1(X3, Y3, Z3); } bls48_G1 bls48_G1::dbl() const { #ifdef PROFILE_OP_COUNTS this->dbl_cnt++; #endif // handle point at infinity if (this->is_zero()) { return (*this); } // no need to handle points of order 2,4 // (they cannot exist in a prime-order subgroup) // NOTE: does not handle O and pts of order 2,4 // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l bls48_Fq A = (this->Y).squared(); // A = Y1^2 bls48_Fq B = (this->X)*A; // B = 4*X1*A B = B+B+B+B; bls48_Fq C = A.squared(); // C = 8A^2 bls48_Fq eightC = C+C; eightC = eightC + eightC; eightC = eightC + eightC; bls48_Fq D = ((this->X).squared()); // D = 3*X1^2 D = D+D+D; bls48_Fq X3 = D.squared() - (B+B); // X3 = D^2 - 2B bls48_Fq Y3 = D * (B - X3) - eightC; // Y3 = D * (B - X3) - 8*C bls48_Fq Y1Z1 = (this->Y)*(this->Z); bls48_Fq Z3 = Y1Z1 + Y1Z1; // Z3 = 2 * Y1 * Z1 return bls48_G1(X3, Y3, Z3); } bool bls48_G1::is_well_formed() const { if (this->is_zero()) { return true; } else { /* y^2 = x^3 + b We are using Jacobian coordinates, so equation we need to check is actually (y/z^3)^2 = (x/z^2)^3 + b y^2 / z^6 = x^3 / z^6 + b y^2 = x^3 + b z^6 */ bls48_Fq X2 = this->X.squared(); bls48_Fq Y2 = this->Y.squared(); bls48_Fq Z2 = this->Z.squared(); bls48_Fq X3 = this->X * X2; bls48_Fq Z3 = this->Z * Z2; bls48_Fq Z6 = Z3.squared(); return (Y2 == X3 + bls48_coeff_b * Z6); } } bls48_G1 bls48_G1::zero() { return G1_zero; } bls48_G1 bls48_G1::one() { return G1_one; } bls48_G1 bls48_G1::random_element() { return (scalar_field::random_element().as_bigint()) * G1_one; } std::ostream& operator<<(std::ostream &out, const bls48_G1 &g) { bls48_G1 copy(g); copy.to_affine_coordinates(); out << (copy.is_zero() ? 1 : 0) << OUTPUT_SEPARATOR; #ifdef NO_PT_COMPRESSION out << copy.X << OUTPUT_SEPARATOR << copy.Y; #else /* storing LSB of Y */ out << copy.X << OUTPUT_SEPARATOR << (copy.Y.as_bigint().data[0] & 1); #endif return out; } std::istream& operator>>(std::istream &in, bls48_G1 &g) { char is_zero; bls48_Fq tX, tY; #ifdef NO_PT_COMPRESSION in >> is_zero >> tX >> tY; is_zero -= '0'; #else in.read((char*)&is_zero, 1); // this reads is_zero; is_zero -= '0'; consume_OUTPUT_SEPARATOR(in); unsigned char Y_lsb; in >> tX; consume_OUTPUT_SEPARATOR(in); in.read((char*)&Y_lsb, 1); Y_lsb -= '0'; // y = +/- sqrt(x^3 + b) if (!is_zero) { bls48_Fq tX2 = tX.squared(); bls48_Fq tY2 = tX2*tX + bls48_coeff_b; tY = tY2.sqrt(); if ((tY.as_bigint().data[0] & 1) != Y_lsb) { tY = -tY; } } #endif // using Jacobian coordinates if (!is_zero) { g.X = tX; g.Y = tY; g.Z = bls48_Fq::one(); } else { g = bls48_G1::zero(); } return in; } std::ostream& operator<<(std::ostream& out, const std::vector<bls48_G1> &v) { out << v.size() << "\n"; for (const bls48_G1& t : v) { out << t << OUTPUT_NEWLINE; } return out; } std::istream& operator>>(std::istream& in, std::vector<bls48_G1> &v) { v.clear(); size_t s; in >> s; consume_newline(in); v.reserve(s); for (size_t i = 0; i < s; ++i) { bls48_G1 g; in >> g; consume_OUTPUT_NEWLINE(in); v.emplace_back(g); } return in; } template<> void batch_to_special_all_non_zeros<bls48_G1>(std::vector<bls48_G1> &vec) { std::vector<bls48_Fq> Z_vec; Z_vec.reserve(vec.size()); for (auto &el: vec) { Z_vec.emplace_back(el.Z); } batch_invert<bls48_Fq>(Z_vec); const bls48_Fq one = bls48_Fq::one(); for (size_t i = 0; i < vec.size(); ++i) { bls48_Fq Z2 = Z_vec[i].squared(); bls48_Fq Z3 = Z_vec[i] * Z2; vec[i].X = vec[i].X * Z2; vec[i].Y = vec[i].Y * Z3; vec[i].Z = one; } } } // libsnark
#include <bits/stdc++.h> using namespace std; #define ll long long #define ld long double #define oo 666666666 int DP[1001][1001]; vector<int>pos[256]; string s; int n; int solve(int i, int j)//Longest Palindromic subsequence { if(i > j)return 0; if(i==j)return 1; if(i+1==j && s[i]==s[j])return 2; if(DP[i][j]!=-1)return DP[i][j]; if(s[i]==s[j])return DP[i][j] = 2 + solve(i+1,j-1); return DP[i][j] = max(solve(i+1,j), solve(i,j-1)); } string lex(int l, int r) { if(l>r)return ""; if(l==r)return s.substr(r,1); int opt = solve(l,r); for(char i='a'; i<='z'; i++) { auto L = lower_bound(pos[i].begin(),pos[i].end(),l); auto R = upper_bound(pos[i].begin(),pos[i].end(),r); if(L==pos[i].end() || R==pos[i].begin())continue; R--; if(*L > r || *R < l)continue; if(*L!=*R && 2+solve(*L+1,*R-1)==opt) return s.substr(*L,1)+lex(*L+1,*R-1)+s.substr(*R,1); else if(*L==*R && 1==opt) return s.substr(*L,1); } return ""; } int main() { ios::sync_with_stdio(0);cin.tie(0); while(cin>>s) { n = s.size(); for(int i=0; i<n; i++) for(int j=0; j<n; j++) DP[i][j]=-1; for(int i='a'; i<='z'; i++) pos[i].clear(); for(int i=0; i<n; i++) pos[s[i]].push_back(i); cout<<lex(0,n-1)<<"\n"; } }
#include "Tests.hpp" #include <Tanker/Compat/TrustchainFactory.hpp> #include <Helpers/TimeoutTerminate.hpp> #include <Tanker/Init.hpp> #include <Tanker/Version.hpp> #include <docopt/docopt.h> using namespace std::string_literals; using namespace std::literals::chrono_literals; static const char USAGE[] = R"(compat cli Usage: compat (encrypt|group|unlock) [--path=<basePath>] (--state=<statePath>) (--tc-temp-config=<trustchainPath>) (--base | --next) Options: --path=<filePath> directory path to store devices [default: /tmp] --state=<filePath> file path to store/load serialized state (--base|--next) use base or new code scenario )"; auto getRunner = [](std::string const& command, auto trustchain, std::string tankerPath, std::string statePath) -> std::unique_ptr<Command> { if (command == "encrypt") return std::make_unique<EncryptCompat>( std::move(trustchain), std::move(tankerPath), std::move(statePath)); else if (command == "group") return std::make_unique<GroupCompat>( std::move(trustchain), std::move(tankerPath), std::move(statePath)); else if (command == "unlock") return std::make_unique<UnlockCompat>( std::move(trustchain), std::move(tankerPath), std::move(statePath)); else throw std::runtime_error("not implemented"); }; auto getCommand = [](auto args) { if (args.at("encrypt").asBool()) return "encrypt"s; else if (args.at("group").asBool()) return "group"s; else if (args.at("unlock").asBool()) return "unlock"s; else throw std::runtime_error("not implemented"); }; auto getTrustchain(TrustchainFactory& tf, std::string const& command, std::string path, bool create) { if (create) { auto trustchain = tf.createTrustchain( fmt::format("compat-{}-{}", command, TANKER_VERSION), true) .get(); tf.saveTrustchainConfig(path, trustchain->toConfig()); return trustchain; } return tf.useTrustchain(path).get(); } int main(int argc, char** argv) { Tanker::TimeoutTerminate tt(5min); auto args = docopt::docopt(USAGE, {argv + 1, argv + argc}, true, TANKER_VERSION); auto const tankerPath = args.at("--path").asString(); auto const statePath = args.at("--state").asString(); auto const command = getCommand(args); auto trustchainFactory = TrustchainFactory::create().get(); auto trustchain = getTrustchain(trustchainFactory, command, args.at("--tc-temp-config").asString(), args.at("--base").asBool()); auto runner = getRunner(command, std::move(trustchain), tankerPath, statePath); if (args.at("--base").asBool()) runner->base(); else if (args.at("--next").asBool()) runner->next(); }
// Created on: 1993-03-24 // Created by: JCV // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Geom2d_Vector_HeaderFile #define _Geom2d_Vector_HeaderFile #include <Standard.hxx> #include <gp_Vec2d.hxx> #include <Geom2d_Geometry.hxx> #include <Standard_Real.hxx> class Geom2d_Vector; DEFINE_STANDARD_HANDLE(Geom2d_Vector, Geom2d_Geometry) //! The abstract class Vector describes the common //! behavior of vectors in 2D space. //! The Geom2d package provides two concrete //! classes of vectors: Geom2d_Direction (unit vector) //! and Geom2d_VectorWithMagnitude. class Geom2d_Vector : public Geom2d_Geometry { public: //! Reverses the vector <me>. Standard_EXPORT void Reverse(); //! Returns a copy of <me> reversed. Standard_NODISCARD Standard_EXPORT Handle(Geom2d_Vector) Reversed() const; //! Computes the angular value, in radians, between this //! vector and vector Other. The result is a value //! between -Pi and Pi. The orientation is from this //! vector to vector Other. //! Raises VectorWithNullMagnitude if one of the two vectors is a vector with //! null magnitude because the angular value is indefinite. Standard_EXPORT Standard_Real Angle (const Handle(Geom2d_Vector)& Other) const; //! Returns the coordinates of <me>. Standard_EXPORT void Coord (Standard_Real& X, Standard_Real& Y) const; //! Returns the Magnitude of <me>. Standard_EXPORT virtual Standard_Real Magnitude() const = 0; //! Returns the square magnitude of <me>. Standard_EXPORT virtual Standard_Real SquareMagnitude() const = 0; //! Returns the X coordinate of <me>. Standard_EXPORT Standard_Real X() const; //! Returns the Y coordinate of <me>. Standard_EXPORT Standard_Real Y() const; //! Cross product of <me> with the vector <Other>. Standard_EXPORT virtual Standard_Real Crossed (const Handle(Geom2d_Vector)& Other) const = 0; //! Returns the scalar product of 2 Vectors. Standard_EXPORT Standard_Real Dot (const Handle(Geom2d_Vector)& Other) const; //! Returns a non persistent copy of <me>. Standard_EXPORT gp_Vec2d Vec2d() const; DEFINE_STANDARD_RTTIEXT(Geom2d_Vector,Geom2d_Geometry) protected: gp_Vec2d gpVec2d; private: }; #endif // _Geom2d_Vector_HeaderFile
#include<iostream> #include<queue> #include<stack> #include<vector> #include<stdio.h> #include<algorithm> #include<string> #include<string.h> #include<sstream> #include<math.h> #include<iomanip> #include<map> using namespace std; typedef long long int LL; struct point{ LL x,y; point(){} point(LL a, LL b){x=a;y=b;} }; struct segment{ point p1, p2; segment(point a, point b){p1=a;p2=b;} }; LL findMatrix(point p1,point p2){ return p1.x*p2.y-p1.y*p2.x; } LL findDir(point p1, point p2, point p3){ return findMatrix(p1,p2)+findMatrix(p2,p3)+findMatrix(p3,p1); } LL findDir2(segment s1, segment s2){ return findDir(s1.p1,s1.p2,s2.p1)*findDir(s1.p1,s1.p2,s2.p2); } bool between(point a, point b, point c) { if(((b.x - a.x) * (c.y - a.y) -(c.x - a.x) * (b.y - a.y)) !=0) return false; if (a.x != b.x) // Line A-B is not Vertical return (((a.x <= c.x) && (c.x <= b.x)) || ((a.x >= c.x) && (c.x >= b.x))); else return (((a.y <= c.y) && (c.y <= b.y)) || ((a.y >= c.y) && (c.y >= b.y))); } bool hasCommonPtr(segment s1, segment s2){ LL a = findDir2(s1,s2); LL b = findDir2(s2,s1); if(a<0 && b<0) return true; if(a==0) if(between(s1.p1,s1.p2,s2.p1) || between(s1.p1,s1.p2,s2.p2)) return true; if(b==0) if(between(s2.p1,s2.p2,s1.p1) || between(s2.p1,s2.p2,s1.p2)) return true; return false; } int main(){ int n,m,t; cin>>n; for(int set = 0; set<n; set++){ t=0; cin>>m; vector<segment> s; for(int i=0; i<m; i++){ LL a,b,c,d; cin>>a>>b>>c>>d; s.push_back(segment(point(a,b),point(c,d))); } for(int i=0; i<m; i++){ bool flag = true; for(int j=0; j<m; j++){ if(i!=j && hasCommonPtr(s[i],s[j])){ flag = false; break; } } if(flag){ t++; } } cout<<t<<endl; } return 0; }
#ifndef FRAGTRAP_HPP # define FRAGTRAP_HPP # include <string> # include <iostream> # include <cstdlib> # include <ctime> class FragTrap { private: unsigned int _lvl; unsigned int _hitPoints; unsigned int _maxHitPoints; unsigned int _energyPoints; unsigned int _maxEnergyPoints; unsigned int _armorDamageReduction; std::string _name; int _meleeAttackDamage; int _rangedAttackDamage; static const int _namesNumber = 5; static std::string _attackNames[_namesNumber]; const unsigned int _vhEnergyCast; const std::string &_getRandomName(void) const; FragTrap(); public: FragTrap(const std::string &name); FragTrap(const FragTrap &toCopy); FragTrap &operator=(const FragTrap &toAssign); int rangedAttack(std::string const &target) const; int meleeAttack(std::string const &target) const; void takeDamage(unsigned int damage); void beRepaired(unsigned int healthRep); int vaulthunter_dot_exe(std::string const & target); ~FragTrap(); }; #endif
#include <ionir/passes/pass.h> namespace ionir { BranchInst::BranchInst(const BranchInstOpts &opts) : Inst(opts.parent, InstKind::Branch), condition(opts.condition), consequentBasicBlock(opts.consequentBasicBlock), alternativeBasicBlock(opts.alternativeBasicBlock) { // } void BranchInst::accept(Pass &visitor) { visitor.visitBranchInst(this->dynamicCast<BranchInst>()); } Ast BranchInst::getChildrenNodes() { // TODO: What about condition? return { this->consequentBasicBlock, this->alternativeBasicBlock }; } }
class Solution1 { public: int lengthOfLIS(vector<int>& nums) { if(nums.size() <= 1) return nums.size(); vector<int> dp(nums.size(),0); int ans = 0; for(int i=0; i<nums.size(); ++i){ dp[i] = 1; for(int j=0; j<i; ++j){ if(nums[j] < nums[i]){ dp[i] = max(dp[i],dp[j]+1); } } ans = max(ans,dp[i]); } return ans; } }; class Solution2 { public: int lengthOfLIS(vector<int>& nums) { if(nums.size() <= 1) return nums.size(); vector<int> dp(nums.size(),0); vector<int> ends(nums.size(),0); dp[0] = 1; ends[0] = nums[0]; int left = 0; int right = 0; int availableArea = 0; int ans = 1; for(int i=1; i<nums.size(); ++i){ left = 0; right = availableArea; while(left <= right){ int mid = left + (right-left)/2; if(nums[i] > ends[mid]){ left = mid+1; }else{ right = mid-1; } } availableArea = max(left,availableArea); ends[left] = nums[i]; dp[i] = left + 1; ans = max(ans,dp[i]); } return ans; } };
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10673" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif long long CASE; scanf("%lld",&CASE); long long x,k; long long floor,ceil; long long a,b; while( CASE-- ){ scanf("%lld %lld",&x,&k); floor = ceil = x/k; if( x%k != 0 ) floor++; long long tmp = 0; a = 0; b = k; while( (a*ceil + b*floor) != x ) a++,b--; printf("%lld %lld\n",a,b ); } return 0; }
#include "InstrTypes.h" #include "Instruction.h" #include "llvm/ADT/Twine.h" #include "BasicBlock.h" #include "Instruction.h" #include "Value.h" #include "Type.h" #include <msclr/marshal.h> using namespace LLVM; TerminatorInst::TerminatorInst(llvm::TerminatorInst *base) : base(base) , Instruction(base) { } inline TerminatorInst ^TerminatorInst::_wrap(llvm::TerminatorInst *base) { return base ? gcnew TerminatorInst(base) : nullptr; } TerminatorInst::!TerminatorInst() { } TerminatorInst::~TerminatorInst() { this->!TerminatorInst(); } unsigned TerminatorInst::getNumSuccessors() { return base->getNumSuccessors(); } BasicBlock ^TerminatorInst::getSuccessor(unsigned idx) { return BasicBlock::_wrap(base->getSuccessor(idx)); } void TerminatorInst::setSuccessor(unsigned idx, BasicBlock ^B) { base->setSuccessor(idx, B->base); } inline bool TerminatorInst::classof(Instruction ^I) { return llvm::TerminatorInst::classof(I->base); } inline bool TerminatorInst::classof(Value ^V) { return llvm::TerminatorInst::classof(V->base); } UnaryInstruction::UnaryInstruction(llvm::UnaryInstruction *base) : base(base) , Instruction(base) { } inline UnaryInstruction ^UnaryInstruction::_wrap(llvm::UnaryInstruction *base) { return base ? gcnew UnaryInstruction(base) : nullptr; } UnaryInstruction::!UnaryInstruction() { } UnaryInstruction::~UnaryInstruction() { this->!UnaryInstruction(); } inline bool UnaryInstruction::classof(Instruction ^I) { return llvm::UnaryInstruction::classof(I->base); } inline bool UnaryInstruction::classof(Value ^V) { return llvm::UnaryInstruction::classof(V->base); } BinaryOperator::BinaryOperator(llvm::BinaryOperator *base) : base(base) , Instruction(base) { } inline BinaryOperator ^BinaryOperator::_wrap(llvm::BinaryOperator *base) { return base ? gcnew BinaryOperator(base) : nullptr; } BinaryOperator::!BinaryOperator() { } BinaryOperator::~BinaryOperator() { this->!BinaryOperator(); } BinaryOperator ^BinaryOperator::Create(BinaryOps Op, Value ^S1, Value ^S2) { return BinaryOperator::_wrap(llvm::BinaryOperator::Create(safe_cast<llvm::BinaryOperator::BinaryOps>(Op), S1->base, S2->base)); } BinaryOperator ^BinaryOperator::Create(BinaryOps Op, Value ^S1, Value ^S2, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::Create(safe_cast<llvm::BinaryOperator::BinaryOps>(Op), S1->base, S2->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::Create(BinaryOps Op, Value ^S1, Value ^S2, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::Create(safe_cast<llvm::BinaryOperator::BinaryOps>(Op), S1->base, S2->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } BinaryOperator ^BinaryOperator::Create(BinaryOps Op, Value ^S1, Value ^S2, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::Create(safe_cast<llvm::BinaryOperator::BinaryOps>(Op), S1->base, S2->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } BinaryOperator ^BinaryOperator::CreateNSW(BinaryOps Opc, Value ^V1, Value ^V2) { return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNSW(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base)); } BinaryOperator ^BinaryOperator::CreateNSW(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNSW(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::CreateNSW(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name, BasicBlock ^BB) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNSW(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name), BB->base)); } BinaryOperator ^BinaryOperator::CreateNSW(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name, Instruction ^I) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNSW(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name), I->base)); } BinaryOperator ^BinaryOperator::CreateNUW(BinaryOps Opc, Value ^V1, Value ^V2) { return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNUW(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base)); } BinaryOperator ^BinaryOperator::CreateNUW(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNUW(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::CreateNUW(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name, BasicBlock ^BB) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNUW(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name), BB->base)); } BinaryOperator ^BinaryOperator::CreateNUW(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name, Instruction ^I) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNUW(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name), I->base)); } BinaryOperator ^BinaryOperator::CreateExact(BinaryOps Opc, Value ^V1, Value ^V2) { return BinaryOperator::_wrap(llvm::BinaryOperator::CreateExact(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base)); } BinaryOperator ^BinaryOperator::CreateExact(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateExact(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::CreateExact(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name, BasicBlock ^BB) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateExact(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name), BB->base)); } BinaryOperator ^BinaryOperator::CreateExact(BinaryOps Opc, Value ^V1, Value ^V2, System::String ^Name, Instruction ^I) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateExact(safe_cast<llvm::BinaryOperator::BinaryOps>(Opc), V1->base, V2->base, ctx.marshal_as<const char *>(Name), I->base)); } BinaryOperator ^BinaryOperator::CreateNeg(Value ^Op) { return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNeg(Op->base)); } BinaryOperator ^BinaryOperator::CreateNeg(Value ^Op, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNeg(Op->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::CreateNeg(Value ^Op, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNeg(Op->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } BinaryOperator ^BinaryOperator::CreateNeg(Value ^Op, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNeg(Op->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } BinaryOperator ^BinaryOperator::CreateNSWNeg(Value ^Op) { return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNSWNeg(Op->base)); } BinaryOperator ^BinaryOperator::CreateNSWNeg(Value ^Op, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNSWNeg(Op->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::CreateNSWNeg(Value ^Op, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNSWNeg(Op->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } BinaryOperator ^BinaryOperator::CreateNSWNeg(Value ^Op, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNSWNeg(Op->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } BinaryOperator ^BinaryOperator::CreateNUWNeg(Value ^Op) { return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNUWNeg(Op->base)); } BinaryOperator ^BinaryOperator::CreateNUWNeg(Value ^Op, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNUWNeg(Op->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::CreateNUWNeg(Value ^Op, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNUWNeg(Op->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } BinaryOperator ^BinaryOperator::CreateNUWNeg(Value ^Op, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNUWNeg(Op->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } BinaryOperator ^BinaryOperator::CreateFNeg(Value ^Op) { return BinaryOperator::_wrap(llvm::BinaryOperator::CreateFNeg(Op->base)); } BinaryOperator ^BinaryOperator::CreateFNeg(Value ^Op, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateFNeg(Op->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::CreateFNeg(Value ^Op, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateFNeg(Op->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } BinaryOperator ^BinaryOperator::CreateFNeg(Value ^Op, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateFNeg(Op->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } BinaryOperator ^BinaryOperator::CreateNot(Value ^Op) { return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNot(Op->base)); } BinaryOperator ^BinaryOperator::CreateNot(Value ^Op, System::String ^Name) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNot(Op->base, ctx.marshal_as<const char *>(Name))); } BinaryOperator ^BinaryOperator::CreateNot(Value ^Op, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNot(Op->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } BinaryOperator ^BinaryOperator::CreateNot(Value ^Op, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return BinaryOperator::_wrap(llvm::BinaryOperator::CreateNot(Op->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } bool BinaryOperator::isNeg(Value ^V) { return llvm::BinaryOperator::isNeg(V->base); } bool BinaryOperator::isFNeg(Value ^V) { return llvm::BinaryOperator::isFNeg(V->base); } bool BinaryOperator::isFNeg(Value ^V, bool IgnoreZeroSign) { return llvm::BinaryOperator::isFNeg(V->base, IgnoreZeroSign); } bool BinaryOperator::isNot(Value ^V) { return llvm::BinaryOperator::isNot(V->base); } Instruction::BinaryOps BinaryOperator::getOpcode() { return safe_cast<Instruction::BinaryOps>(base->getOpcode()); } bool BinaryOperator::swapOperands() { return base->swapOperands(); } void BinaryOperator::setHasNoUnsignedWrap() { base->setHasNoUnsignedWrap(); } void BinaryOperator::setHasNoUnsignedWrap(bool b) { base->setHasNoUnsignedWrap(b); } void BinaryOperator::setHasNoSignedWrap() { base->setHasNoSignedWrap(); } void BinaryOperator::setHasNoSignedWrap(bool b) { base->setHasNoSignedWrap(b); } void BinaryOperator::setIsExact() { base->setIsExact(); } void BinaryOperator::setIsExact(bool b) { base->setIsExact(b); } bool BinaryOperator::hasNoUnsignedWrap() { return base->hasNoUnsignedWrap(); } bool BinaryOperator::hasNoSignedWrap() { return base->hasNoSignedWrap(); } bool BinaryOperator::isExact() { return base->isExact(); } inline bool BinaryOperator::classof(Instruction ^I) { return llvm::BinaryOperator::classof(I->base); } inline bool BinaryOperator::classof(Value ^V) { return llvm::BinaryOperator::classof(V->base); } CastInst::CastInst(llvm::CastInst *base) : base(base) , UnaryInstruction(base) { } inline CastInst ^CastInst::_wrap(llvm::CastInst *base) { return base ? gcnew CastInst(base) : nullptr; } CastInst::!CastInst() { } CastInst::~CastInst() { this->!CastInst(); } CastInst ^CastInst::Create(Instruction::CastOps ops, Value ^S, Type ^Ty) { return CastInst::_wrap(llvm::CastInst::Create(safe_cast<llvm::Instruction::CastOps>(ops), S->base, Ty->base)); } CastInst ^CastInst::Create(Instruction::CastOps ops, Value ^S, Type ^Ty, System::String ^Name) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::Create(safe_cast<llvm::Instruction::CastOps>(ops), S->base, Ty->base, ctx.marshal_as<const char *>(Name))); } CastInst ^CastInst::Create(Instruction::CastOps ops, Value ^S, Type ^Ty, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::Create(safe_cast<llvm::Instruction::CastOps>(ops), S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } CastInst ^CastInst::Create(Instruction::CastOps ops, Value ^S, Type ^Ty, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::Create(safe_cast<llvm::Instruction::CastOps>(ops), S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } CastInst ^CastInst::CreateZExtOrBitCast(Value ^S, Type ^Ty) { return CastInst::_wrap(llvm::CastInst::CreateZExtOrBitCast(S->base, Ty->base)); } CastInst ^CastInst::CreateZExtOrBitCast(Value ^S, Type ^Ty, System::String ^Name) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateZExtOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name))); } CastInst ^CastInst::CreateZExtOrBitCast(Value ^S, Type ^Ty, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateZExtOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } CastInst ^CastInst::CreateZExtOrBitCast(Value ^S, Type ^Ty, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateZExtOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } CastInst ^CastInst::CreateSExtOrBitCast(Value ^S, Type ^Ty) { return CastInst::_wrap(llvm::CastInst::CreateSExtOrBitCast(S->base, Ty->base)); } CastInst ^CastInst::CreateSExtOrBitCast(Value ^S, Type ^Ty, System::String ^Name) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateSExtOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name))); } CastInst ^CastInst::CreateSExtOrBitCast(Value ^S, Type ^Ty, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateSExtOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } CastInst ^CastInst::CreateSExtOrBitCast(Value ^S, Type ^Ty, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateSExtOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } CastInst ^CastInst::CreatePointerCast(Value ^S, Type ^Ty, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreatePointerCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } CastInst ^CastInst::CreatePointerCast(Value ^S, Type ^Ty) { return CastInst::_wrap(llvm::CastInst::CreatePointerCast(S->base, Ty->base)); } CastInst ^CastInst::CreatePointerCast(Value ^S, Type ^Ty, System::String ^Name) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreatePointerCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name))); } CastInst ^CastInst::CreatePointerCast(Value ^S, Type ^Ty, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreatePointerCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } CastInst ^CastInst::CreateIntegerCast(Value ^S, Type ^Ty, bool isSigned) { return CastInst::_wrap(llvm::CastInst::CreateIntegerCast(S->base, Ty->base, isSigned)); } CastInst ^CastInst::CreateIntegerCast(Value ^S, Type ^Ty, bool isSigned, System::String ^Name) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateIntegerCast(S->base, Ty->base, isSigned, ctx.marshal_as<const char *>(Name))); } CastInst ^CastInst::CreateIntegerCast(Value ^S, Type ^Ty, bool isSigned, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateIntegerCast(S->base, Ty->base, isSigned, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } CastInst ^CastInst::CreateIntegerCast(Value ^S, Type ^Ty, bool isSigned, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateIntegerCast(S->base, Ty->base, isSigned, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } CastInst ^CastInst::CreateFPCast(Value ^S, Type ^Ty) { return CastInst::_wrap(llvm::CastInst::CreateFPCast(S->base, Ty->base)); } CastInst ^CastInst::CreateFPCast(Value ^S, Type ^Ty, System::String ^Name) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateFPCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name))); } CastInst ^CastInst::CreateFPCast(Value ^S, Type ^Ty, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateFPCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } CastInst ^CastInst::CreateFPCast(Value ^S, Type ^Ty, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateFPCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } CastInst ^CastInst::CreateTruncOrBitCast(Value ^S, Type ^Ty) { return CastInst::_wrap(llvm::CastInst::CreateTruncOrBitCast(S->base, Ty->base)); } CastInst ^CastInst::CreateTruncOrBitCast(Value ^S, Type ^Ty, System::String ^Name) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateTruncOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name))); } CastInst ^CastInst::CreateTruncOrBitCast(Value ^S, Type ^Ty, System::String ^Name, Instruction ^InsertBefore) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateTruncOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertBefore->base)); } CastInst ^CastInst::CreateTruncOrBitCast(Value ^S, Type ^Ty, System::String ^Name, BasicBlock ^InsertAtEnd) { msclr::interop::marshal_context ctx; return CastInst::_wrap(llvm::CastInst::CreateTruncOrBitCast(S->base, Ty->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base)); } bool CastInst::isCastable(Type ^SrcTy, Type ^DestTy) { return llvm::CastInst::isCastable(SrcTy->base, DestTy->base); } Instruction::CastOps CastInst::getCastOpcode(Value ^Val, bool SrcIsSigned, Type ^Ty, bool DstIsSigned) { return safe_cast<Instruction::CastOps>(llvm::CastInst::getCastOpcode(Val->base, SrcIsSigned, Ty->base, DstIsSigned)); } bool CastInst::isIntegerCast() { return base->isIntegerCast(); } bool CastInst::isLosslessCast() { return base->isLosslessCast(); } bool CastInst::isNoopCast(Instruction::CastOps Opcode, Type ^SrcTy, Type ^DstTy, Type ^IntPtrTy) { return llvm::CastInst::isNoopCast(safe_cast<llvm::Instruction::CastOps>(Opcode), SrcTy->base, DstTy->base, IntPtrTy->base); } bool CastInst::isNoopCast(Type ^IntPtrTy) { return base->isNoopCast(IntPtrTy->base); } unsigned CastInst::isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type ^SrcTy, Type ^MidTy, Type ^DstTy, Type ^SrcIntPtrTy, Type ^MidIntPtrTy, Type ^DstIntPtrTy) { return llvm::CastInst::isEliminableCastPair(safe_cast<llvm::Instruction::CastOps>(firstOpcode), safe_cast<llvm::Instruction::CastOps>(secondOpcode), SrcTy->base, MidTy->base, DstTy->base, SrcIntPtrTy->base, MidIntPtrTy->base, DstIntPtrTy->base); } Instruction::CastOps CastInst::getOpcode() { return safe_cast<Instruction::CastOps>(base->getOpcode()); } Type ^CastInst::getSrcTy() { return Type::_wrap(base->getSrcTy()); } Type ^CastInst::getDestTy() { return Type::_wrap(base->getDestTy()); } bool CastInst::castIsValid(Instruction::CastOps op, Value ^S, Type ^DstTy) { return llvm::CastInst::castIsValid(safe_cast<llvm::Instruction::CastOps>(op), S->base, DstTy->base); } inline bool CastInst::classof(Instruction ^I) { return llvm::CastInst::classof(I->base); } inline bool CastInst::classof(Value ^V) { return llvm::CastInst::classof(V->base); } CmpInst::CmpInst(llvm::CmpInst *base) : base(base) , Instruction(base) { } inline CmpInst ^CmpInst::_wrap(llvm::CmpInst *base) { return base ? gcnew CmpInst(base) : nullptr; } CmpInst::!CmpInst() { } CmpInst::~CmpInst() { this->!CmpInst(); } Instruction::OtherOps CmpInst::getOpcode() { return safe_cast<Instruction::OtherOps>(base->getOpcode()); } CmpInst::Predicate CmpInst::getPredicate() { return safe_cast<CmpInst::Predicate>(base->getPredicate()); } void CmpInst::setPredicate(Predicate P) { base->setPredicate(safe_cast<llvm::CmpInst::Predicate>(P)); } bool CmpInst::isFPPredicate(Predicate P) { return llvm::CmpInst::isFPPredicate(safe_cast<llvm::CmpInst::Predicate>(P)); } bool CmpInst::isIntPredicate(Predicate P) { return llvm::CmpInst::isIntPredicate(safe_cast<llvm::CmpInst::Predicate>(P)); } bool CmpInst::isFPPredicate() { return base->isFPPredicate(); } bool CmpInst::isIntPredicate() { return base->isIntPredicate(); } CmpInst::Predicate CmpInst::getInversePredicate() { return safe_cast<CmpInst::Predicate>(base->getInversePredicate()); } CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { return safe_cast<CmpInst::Predicate>(llvm::CmpInst::getInversePredicate(safe_cast<llvm::CmpInst::Predicate>(pred))); } CmpInst::Predicate CmpInst::getSwappedPredicate() { return safe_cast<CmpInst::Predicate>(base->getSwappedPredicate()); } CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { return safe_cast<CmpInst::Predicate>(llvm::CmpInst::getSwappedPredicate(safe_cast<llvm::CmpInst::Predicate>(pred))); } void CmpInst::swapOperands() { base->swapOperands(); } bool CmpInst::isCommutative() { return base->isCommutative(); } bool CmpInst::isEquality() { return base->isEquality(); } bool CmpInst::isSigned() { return base->isSigned(); } bool CmpInst::isUnsigned() { return base->isUnsigned(); } bool CmpInst::isTrueWhenEqual() { return base->isTrueWhenEqual(); } bool CmpInst::isFalseWhenEqual() { return base->isFalseWhenEqual(); } inline bool CmpInst::classof(Instruction ^I) { return llvm::CmpInst::classof(I->base); } inline bool CmpInst::classof(Value ^V) { return llvm::CmpInst::classof(V->base); } Type ^CmpInst::makeCmpResultType(Type ^opnd_type) { return Type::_wrap(llvm::CmpInst::makeCmpResultType(opnd_type->base)); }
#pragma once class GameCursor; class IconAI :public GameObject { public: ~IconAI(); bool Start(); void init(std::string py, int num, GameCursor* cursor, bool isVisualAI = false,int mark = 0); void Update(); void PostRender(); void Setpos(CVector3 pos); CVector3 Getpos(); bool isClick() { return m_isClick; } // int getVisualAIname() { return _wtoi(m_fr->getText()); } private: GameCursor* m_cursor; SpriteRender* m_dummy = nullptr; SpriteRender* m_frame = nullptr; bool m_issel = false; //const wchar_t* m_py; std::wstring m_py; int m_num = 0; bool m_isClick = false; CFont m_font; FontRender* m_fr = nullptr; FontRender* m_frShadow = nullptr; bool m_isVisualAI = false; SpriteRender* m_mark = nullptr; //visualAI 用 のマーク };
#pragma once #include <atomic> #include <condition_variable> #include <unordered_set> #include "eager_version_manager.h" #include "lazy_version_manager.h" class Transaction; class TransactionManager { public: struct TransactionSet { std::unordered_set<Transaction *> transaction_set_; std::shared_mutex transaction_mutex_; }; /** * Default constructor for TransactionManager */ TransactionManager(bool use_lazy_versioning, bool use_pessimistic_conflict_detection); /** * Begin memory transaction * @return transaction */ Transaction XBegin(); /** * Adds transaction to write set for address * * @param address location to Store value * @param transaction transaction performing store */ void Store(void *address, Transaction *transaction); /** * Adds transaction to read set for address * @param address * @param transaction transaction performing load */ void Load(void *address, Transaction *transaction); void ResolveConflictsAtCommit(Transaction *transaction); /** * Clean up all memory associated with transaction that commits * * @param transaction transaction to clean up memory for */ void XEnd(Transaction *transaction); /** * Clean up all memory associated with transaction that aborts * WARNING: MUST BE CALLED WITH EXCLUSIVE LOCKS ON THE READ AND WRITE SETS * * @param transaction transaction to clean up memory for */ void AbortWithoutLocks(Transaction *transaction); /** * Clean up all memory associated with transaction that aborts * * @param transaction transaction to clean up memory for */ void Abort(Transaction *transaction); private: bool use_lazy_versioning_; bool use_pessimistic_conflict_detection_; std::atomic<uint64_t> next_txn_id_; std::unordered_map<void *, TransactionSet> write_sets_; std::shared_mutex write_set_mutex_; std::unordered_map<void *, TransactionSet> read_sets_; std::shared_mutex read_set_mutex_; std::condition_variable_any read_stall_cv_; /** * */ /** * Check and see if there's a conflict with the current transaction * DO NOT CALL THIS METHOD WITHOUT AN EXCLUSIVE LOCK * * @param address Address to check for conflicts * @param address_map Map of transaction sets to check for conflicts in * @param transaction Transaction to check conflicts for * @param conflicting_transaction pointer to conflicting transaction * @return true if there are conflicts false otherwise */ bool CheckForConflictWithoutLocking(void *address, std::unordered_map<void *, TransactionSet> &address_map, Transaction *transaction); /** * Abort all transactions that have a conflict with the current transaction * DO NOT CALL THIS METHOD WITHOUT AN EXCLUSIVE LOCK * * @param address_map Map of transaction sets to check for conflicts in * @param transaction Transaction to check conflicts for * @return true if we were able to successfully abort other transactions false otherwise */ bool AbortTransactionsWithConflictsWithoutLocking(std::unordered_map<void *, TransactionSet> &address_map, Transaction *transaction); /** * Handle conflicts for transactions trying to read. Will either abort conflicting transactions, stall current * transaction, abort current transaction or do nothing. * * @param address Address to check for conflicts at * @param transaction Transaction to check for conflicts * @param exclusive_write_lock Acquired lock on write sets * @return */ bool HandlePessimisticReadConflicts(void *address, Transaction *transaction, std::unique_lock<std::shared_mutex> *exclusive_write_lock); /** * Add transaction to set of transactions * DO NOT CALL THIS METHOD WITHOUT AN EXCLUSIVE LOCK * * @param address Address to add * @param address_map Map of transaction sets to add address to * @param transaction Transaction to add to transaction set */ void AddTransactionToAddressSetWithoutLocking(void *address, std::unordered_map<void *, TransactionSet> &address_map, Transaction *transaction); /** * Remove transaction from set of transactions * DO NOT CALL THIS METHOD WITHOUT AN EXCLUSIVE LOCK * * @param address_set Set of address from transaction to remove * @param address_map Map of addresses to remove address set from * @param transaction Transaction to remove */ void RemoveTransactionFromAddressSetWithoutLocking(const std::unordered_set<void *> &address_set, std::unordered_map<void *, TransactionSet> &address_map, Transaction *transaction); };
#pragma once #include "base.h" #include <vector> class Long { private: std::vector<uint> digits; bool sign; #define MODULE 65536 #define MASK MODULE - 1 #define BITS 16 public: Long() : digits(1), sign(0) {} };
#include <iostream> #include <algorithm> using namespace std; int n; int dp[501][501]; int cost[501][501]; int ans = 0; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; for (int i = 1; i <= n; i++){ for (int j = 1; j <= i; j++){ cin >> cost[i][j]; } } for (int i = 1; i <= n; i++){ for (int j = 1; j <= i; j++){ dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1]) + cost[i][j]; if(i == n && dp[i][j] > ans){ ans = dp[i][j]; } } } cout << ans << '\n'; return 0; }
#include "stdafx.h" #include <cmath> GENIXAPI(void, adadelta)(const int n, float* gradient, float* gsum, float* xsum, const float rho, const float eps) { const float rhoinv = 1.0f - rho; for (int i = 0; i < n; i++) { float g = gradient[i]; gsum[i] = (rho * gsum[i]) + (rhoinv * g * g); g *= -::sqrt((xsum[i] + eps) / (gsum[i] + eps)); xsum[i] = (rho * xsum[i]) + (rhoinv * g * g); // yes, xsum lags behind gsum by 1. gradient[i] = g; } }
#include<constream.h> class calculator{ public: void add(int a, int b){ cout<<"Addition is"<<a+b<<endl; } void sub(int a,int b){ cout<<"subtration is"<<a-b<<endl; } void mul(int a,int b){ cout<<"Multiplication is"<<a*b<<endl; } void div(int a, int b){ cout<<"division is "<<a/b<<endl; } }; void main(){ clrscr(); calculator calc; calc.add(10,5); calc.add(100,25); calc.sub(5,3); calc.mul(10,5); calc.mul(5,6); calc.div(10,2); getch(); }
// ------------------------------------------------------------------------ // File name: changeDue.cpp - // Project Name: Quiz 6 - // ------------------------------------------------------------------------ // Creator's Name and Email: Dylan Rossi drossi2@saddleback.edu - // Course-Section: CS 1A Ticket# 80600 - // Creation Date: Nov. 15, 2018 - // Date of Last Modification: Nov. 15, 2018 - // ------------------------------------------------------------------------ // Purpose: Quiz 6 - // - // ------------------------------------------------------------------------ // Algorithm: - // Step 1: Find change; output using cout - // ------------------------------------------------------------------------ // - DATA DICTIONARY - // - CONSTANTS - // - - // - NAME DATA TYPE INITIAL VALUE - // - -------------- --------- ------------- - // - QUARTERS int 25 - // - DIMES int 10 - // - NICKELS int 5 - // - - // - VARIABLES - // - - // - NAME DATA TYPE INITIAL VALUE - // - -------------- --------- ------------- - // - change int inherited - // - - // - - // ------------------------------------------------------------------------ #include <iostream> //links to the header file which contains the function prototype, which links to int main //*in "quotes" must be the exact same as filename #include "ChangeDue.h" using namespace std; //displays constant variables to use within this program of changeDue //these are whole numbers, a. bc they are int, b. we assigned int change to a double cost //value with 100-(cost*100), thereby eliminating the decimal point. Just make sure to get the correct //input from the user- in decimal format, with a max price of $1 const int QUARTERS=25; const int DIMES=10; const int NICKELS=5; //inputs the change variable from int main, outputs an int value int changeDue(int change){ //no need to declare variable for change, it is brought in from int main() //divide integers, no remainder, prints out amount of quarters cout<<"Quarters: "<<change/QUARTERS<<endl; //the remainder (operand) of change/quarters, the rest of the change due, becomes the change variable change= change%QUARTERS; //divide integers, no remainder, prints out amount of dimes cout<<"Dimes: "<<change/DIMES<<endl; //the remainder (operand) of change/dimes, the rest of the change due, becomes the change variable change= change%DIMES; //divide integers, no remainder, prints out amount of nickels cout<<"Nickels: "<<change/NICKELS<<endl; //the remainder (operand) of change/nickels, the rest of the change due, becomes the change variable change= change%NICKELS; //no need for math! the change variable is down to the single digit unit, represented as pennies... cout<<"Pennies: "<<change<<endl; //returning an int change? I'm not sure about how this part works... return change; }
#include "CollisionManager.h" void CollisionManager::SetCollidableModels(vector<CollidableModel*> fCollidableModels) { CollidableModels = fCollidableModels; } void CollisionManager::AddCollidableModel(CollidableModel * model) { CollidableModels.push_back(model); } void CollisionManager::RemoveCollidableModel(int modelIndex) { CollidableModels.erase(CollidableModels.begin()+modelIndex); } void CollisionManager::RemoveCollidableModel(CollidableModel * model) { CollidableModels.erase(find(CollidableModels.begin(),CollidableModels.end(),model)); } bool CollisionManager::UpdateCollisions() { bool GunCollided = false; for (int i = 0;i < CollidableModels.size();i++) { for (int j = i + 1;j < CollidableModels.size();j++) { if(CollidableModels[i]->GetBoundingBox().IsIntersecting(CollidableModels[j]->GetBoundingBox())){ CollidableModel::ObjectType x = CollidableModels[i]->objectType; CollidableModel::ObjectType y = CollidableModels[j]->objectType; CollidableModels[i]->Collided(y); CollidableModels[j]->Collided(x); if ((x == 3 &&( y == 1||y==6) || ((x == 6||x==1) && y == 3))) { GunCollided = true; } } } } return GunCollided; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #if defined(X11API) && defined(NS4P_COMPONENT_PLUGINS) #include "platforms/x11api/plugins/plugin_watchdog.h" #include <time.h> #include <unistd.h> #ifdef DEBUG_ENABLE_OPASSERT // Expression is either zero (success) or an errno value: # define ZERO_OR_ERRNO(e) do { int const res = e; OP_ASSERT(!res); } while(0) #else # define ZERO_OR_ERRNO(e) e #endif PluginWatchdog::~PluginWatchdog() { if (!m_shared_data) return; Stop(); ZERO_OR_ERRNO(pthread_mutex_destroy(&m_shared_data->mutex)); ZERO_OR_ERRNO(pthread_cond_destroy(&m_shared_data->cond)); OP_DELETE(m_shared_data); } inline OP_STATUS PluginWatchdog::Evaluate(int status) { switch (status) { case ENOMEM: return OpStatus::ERR_NO_MEMORY; case 0: return OpStatus::OK; default: return OpStatus::ERR; } } OP_STATUS PluginWatchdog::Init() { OpAutoPtr<SharedData> shared (OP_NEW(SharedData, ())); RETURN_OOM_IF_NULL(shared.get()); pthread_condattr_t attr; RETURN_IF_ERROR(Evaluate(pthread_condattr_init(&attr))); struct CondAttr { CondAttr(pthread_condattr_t& attr) : attr(attr) {} ~CondAttr() { ZERO_OR_ERRNO(pthread_condattr_destroy(&attr)); } pthread_condattr_t& attr; } condattr_holder(attr); RETURN_IF_ERROR(Evaluate(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC))); RETURN_IF_ERROR(Evaluate(pthread_cond_init(&shared->cond, &attr))); OP_STATUS ret = Evaluate(pthread_mutex_init(&shared->mutex, NULL)); if (OpStatus::IsError(ret)) { ZERO_OR_ERRNO(pthread_cond_destroy(&shared->cond)); return ret; } m_shared_data = shared.release(); return OpStatus::OK; } OP_STATUS PluginWatchdog::Start(unsigned timeout) { OP_ASSERT(timeout != 0); OP_ASSERT(m_shared_data->timeout == 0 || !"Starting watchdog twice!"); m_shared_data->timeout = timeout; return Evaluate(pthread_create(&m_thread_id, NULL, &WatchLoop, m_shared_data)); } void* PluginWatchdog::WatchLoop(void* data) { SharedData* shared = static_cast<SharedData*>(data); while (true) { struct timespec timeout; if (clock_gettime(CLOCK_MONOTONIC, &timeout) != 0) return NULL; UINT64 timeout_ms = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000; ZERO_OR_ERRNO(pthread_mutex_lock(&shared->mutex)); if (shared->timeout == 0) { ZERO_OR_ERRNO(pthread_mutex_unlock(&shared->mutex)); break; } timeout_ms += shared->timeout; timeout.tv_sec = timeout_ms / 1000; timeout.tv_nsec = (timeout_ms % 1000) * 1000000; int result = pthread_cond_timedwait(&shared->cond, &shared->mutex, &timeout); unsigned new_timeout = shared->timeout; ZERO_OR_ERRNO(pthread_mutex_unlock(&shared->mutex)); if (new_timeout == 0) break; else if (result == ETIMEDOUT) _exit(1); else if (result != 0) break; } return NULL; } void PluginWatchdog::Stop() { ZERO_OR_ERRNO(pthread_mutex_lock(&m_shared_data->mutex)); unsigned timeout = m_shared_data->timeout; m_shared_data->timeout = 0; ZERO_OR_ERRNO(pthread_cond_signal(&m_shared_data->cond)); ZERO_OR_ERRNO(pthread_mutex_unlock(&m_shared_data->mutex)); if (timeout != 0) ZERO_OR_ERRNO(pthread_join(m_thread_id, NULL)); } void PluginWatchdog::Kick() { ZERO_OR_ERRNO(pthread_cond_signal(&m_shared_data->cond)); } #endif // defined(X11API) && defined(NS4P_COMPONENT_PLUGINS)
#include <bits/stdc++.h> using namespace std; #define REP(a,n) for(int i=a; i<n ;i++) #define pb(a) push_back(a) typedef long long ll; typedef unsigned long long ull; typedef vector<int> V; typedef pair<ll, ll> pll; typedef vector<ll> vll; typedef vector<pll> vpll; typedef vector<vll> vvll; typedef vector<string> vs; int bfs (int n, int s, int d, vector<int> v[]) { int visited[n]={0}; visited[s]=1; queue<pair<int,int>> que; que.push(make_pair(s,0)); while(!que.empty()) { pair<int,int> pr; pr=que.front(); int top=pr.first; int level=pr.second; que.pop(); if(top==d) return level; for(auto itr= v[top].begin() ; itr!=v[top].end() ; ++itr) { if(visited[*itr]==0) { que.push(make_pair(*itr,level+1)); visited[*itr]=1; } } } return 0; } int main() { #ifndef ONLINE_JUDGE freopen("input1.txt", "r", stdin) ; freopen("output1.txt", "w", stdout) ; #endif ios_base::sync_with_stdio(false); cin.tie(NULL) ; cout.tie(NULL) ; int n; cin>>n; int edge; cin>>edge; vector<int>v[2*n]; for(int i=0 ; i<edge ; i++) { int x,y; cin>>x>>y; v[x].push_back(y); v[y].push_back(x); } int source,destination; cin>>source>>destination; int visited[n]={0}; int min_edge=1000; int count=0; cout<<bfs(n,source,destination,v); }
#include <bits/stdc++.h> using namespace std; int main(){ int a,b,c; while(scanf("%d %d",&a,&b)!=EOF){ if(a==-1 && b==-1)break; c=abs(a-b); if(c>50)cout<<100-c<<endl; else cout<<abs(a-b)<<endl; } return 0; }
#pragma once #include "ofxKinectNui.h" #include "ofMain.h" #include "characters\characterBase.h" #include "shapes\block.h" class monstro1 : public characterBase { public: monstro1(); void update(); };
#include <bits/stdc++.h> using namespace std; int main(){ int a, b; string s; cin >> a >> b >> s; bool flag = true; for(int i=0; i<a; i++){ if(!isalnum(s[i])) flag = false; } if(s[a] != '-') flag = false; for(int i=a+1; i<s.size(); i++){ if(!isalnum(s[i])) flag = false; } if(flag) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
#include "radialbasisfunction.h" RadialBasisFunction::RadialBasisFunction() { }
#include "exchange.hpp" Exchange::Exchange(const string &apiUrl, const string &apiData, int msgLimit = 10) : orders{}, msgLimit{msgLimit} { connect(apiUrl, apiData); } Exchange::~Exchange() { client.close().wait(); } void Exchange::connect(const string &apiUrl, const string &apiData) { try { client.connect(apiUrl).wait(); websocket_outgoing_message out_msg; out_msg.set_utf8_message(apiData); client.send(out_msg).wait(); } catch (const std::exception &e) { std::cout << "ERROR:" << e.what() << endl; } } void Exchange::receive() { uint i = 0; while (msgLimit > i) { try { client .receive() .then([](websocket_incoming_message in_msg) { return in_msg.extract_string(); }) .then([this](string body) { if (parse(json::parse(body))) { notify(*this); } }) .wait(); } catch (const std::exception &e) { std::cout << "ERROR:" << e.what() << endl; } i++; } }
#include "engine/graphics/LButton.hpp" LButton::LButton(){} LButton::LButton(ButtonType type, LTexture* spriteSheet,SDL_Rect (&spriteClips)[BUTTON_SPRITE_TOTAL]) { mPosition.x = 0; mPosition.y = 0; button_type = type; modeSelected = 0; gButtonSpriteSheetTexture = spriteSheet; for (int i = 0; i < BUTTON_SPRITE_TOTAL; i++) { gSpriteClips[i] = spriteClips[i]; // std::cout << gSpriteClips[i].h << std::endl; } if (type==BUTTON_PRIM){ mCurrentSprite = BUTTON_SPRITE_MOUSE_OUT; } else{ mCurrentSprite = BUTTON_SPRITE_MOUSE_OUT_ALT; } } void LButton::loadAudio(){ hoverSound = gEngine->audioStore->getSourceFor(AS_HOVER_SOUND); clickSound = gEngine->audioStore->getSourceFor(AS_CLICK_SOUND); } void LButton::setPosition( int x, int y ) { mPosition.x = x; mPosition.y = y; } // modify void LButton::handleEvent( SDL_Event* e ) { //If mouse event happened if( e->type == SDL_MOUSEMOTION || e->type == SDL_MOUSEBUTTONDOWN || e->type == SDL_MOUSEBUTTONUP ) { //Get mouse position int x, y; SDL_GetMouseState( &x, &y ); //Check if mouse is in button bool inside = true; //Mouse is left of the button if( x < mPosition.x ) { inside = false; } //Mouse is right of the button else if( x > mPosition.x + BUTTON_WIDTH ) { inside = false; } //Mouse above the button else if( y < mPosition.y ) { inside = false; } //Mouse below the button else if( y > mPosition.y + BUTTON_HEIGHT ) { inside = false; } //Mouse is outside button if( !inside ) { if (button_type==BUTTON_PRIM){ mCurrentSprite = BUTTON_SPRITE_MOUSE_OUT; } else{ mCurrentSprite = BUTTON_SPRITE_MOUSE_OUT_ALT; } wasInsideBefore = false; } //Mouse is inside button else { //Set mouse over sprite switch( e->type ) { case SDL_MOUSEMOTION: if (button_type==BUTTON_PRIM){ mCurrentSprite = BUTTON_SPRITE_MOUSE_OVER_MOTION; } else{ mCurrentSprite = BUTTON_SPRITE_MOUSE_OVER_MOTION_ALT; } if(!wasInsideBefore){ hoverSound->rewind(); hoverSound->play(); } break; case SDL_MOUSEBUTTONDOWN: if (button_type==BUTTON_PRIM){ mCurrentSprite = BUTTON_SPRITE_MOUSE_DOWN; } else{ mCurrentSprite = BUTTON_SPRITE_MOUSE_DOWN_ALT; } clickSound->rewind(); clickSound->play(); break; case SDL_MOUSEBUTTONUP: if (button_type==BUTTON_PRIM){ mCurrentSprite = BUTTON_SPRITE_MOUSE_UP; modeSelected = 1; } else{ mCurrentSprite = BUTTON_SPRITE_MOUSE_UP_ALT; modeSelected = 1; } break; } wasInsideBefore = true; } } } void LButton::render() { // std::cout << mCurrentSprite << std::endl; // std::cout << gSpriteClips[ mCurrentSprite ].x << gSpriteClips[ mCurrentSprite ].y << gSpriteClips[ mCurrentSprite ].w << gSpriteClips[ mCurrentSprite ].h << std::endl; //Show current button sprite gButtonSpriteSheetTexture->render( mPosition.x, mPosition.y, &gSpriteClips[ mCurrentSprite ] ); } int LButton::getMode(){ return modeSelected; } void LButton::setMode(int a){ modeSelected = a; }
#include <iostream> #include <queue> #include <deque> #include <algorithm> #include <string> #include <vector> #include <stack> #include <set> #include <map> #include <math.h> #include <string.h> #include <bitset> #include <cmath> using namespace std; int n, vip, lastvip = 1; vector<int> cont; int dp[41]; int main() { int ret = 1; cin >> n >> vip; int tmp; while (vip--) { cin >> tmp; cont.push_back(tmp - lastvip); lastvip = tmp + 1; } cont.push_back(n - lastvip + 1); dp[1] = 1; dp[2] = 2; for (int i = 3; i <= 40; i++) dp[i] = dp[i - 1] + dp[i - 2]; for (auto x : cont) { //cout << x << endl; if (x != 0) ret *= dp[x]; } cout << ret; return 0; }
#pragma once #include <QString> #include <QVariantList> class NamedValues { public: // :: Lifecycle :: NamedValues() = default; NamedValues(const QString &name); NamedValues(const QString &name, std::initializer_list<QVariant> values); // :: Accessors :: QString getName() const; void setName(const QString &name); const QVariantList &getValues() const; void setValues(const QVariantList &values); const QVariant &getValue(ptrdiff_t index) const; // :: Indexators :: const QVariant &operator[](ptrdiff_t index) const; QVariant &operator[](ptrdiff_t index); // :: Methods :: void appendValue(const QVariant &value); bool removeValue(const QVariant &value); void removeValue(ptrdiff_t index); private: QString m_name; QVariantList m_values; }; bool operator ==(const NamedValues &lhs, const NamedValues &rhs);
class Solution { public: int lengthOfLastWord(string s) { int last=0; int now=0; bool flag = false; if(s==" ") return 0; for(int i=0; i<s.size(); i++) { if(s[i]==' ') { flag=true; } else { if(flag) { last = i; flag=false; } now=i; } } return now-last; } };
/**************************************************************************** ** Meta object code from reading C++ file 'CCategoryFactory.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../CCategoryFactory.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'CCategoryFactory.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_CCategoryFactory_t { QByteArrayData data[12]; char stringdata[178]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_CCategoryFactory_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_CCategoryFactory_t qt_meta_stringdata_CCategoryFactory = { { QT_MOC_LITERAL(0, 0, 16), QT_MOC_LITERAL(1, 17, 13), QT_MOC_LITERAL(2, 31, 0), QT_MOC_LITERAL(3, 32, 14), QT_MOC_LITERAL(4, 47, 4), QT_MOC_LITERAL(5, 52, 17), QT_MOC_LITERAL(6, 70, 37), QT_MOC_LITERAL(7, 108, 13), QT_MOC_LITERAL(8, 122, 17), QT_MOC_LITERAL(9, 140, 4), QT_MOC_LITERAL(10, 145, 15), QT_MOC_LITERAL(11, 161, 16) }, "CCategoryFactory\0upgradeNotify\0\0" "SMonitor::Type\0type\0dataChangedNotify\0" "QMap<QString,QMap<QString,SoftData> >\0" "MessageNotify\0SoftwareInstalled\0name\0" "InstallFinished\0CheckUpgradeData" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_CCategoryFactory[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 7, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 5, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 49, 2, 0x06 /* Public */, 1, 0, 52, 2, 0x26 /* Public | MethodCloned */, 5, 1, 53, 2, 0x06 /* Public */, 7, 2, 56, 2, 0x06 /* Public */, 8, 1, 61, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 10, 1, 64, 2, 0x0a /* Public */, 11, 0, 67, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 4, QMetaType::Void, QMetaType::Void, 0x80000000 | 6, 2, QMetaType::Void, QMetaType::QDateTime, QMetaType::QString, 2, 2, QMetaType::Void, QMetaType::QString, 9, // slots: parameters QMetaType::Void, QMetaType::QString, 9, QMetaType::Void, 0 // eod }; void CCategoryFactory::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { CCategoryFactory *_t = static_cast<CCategoryFactory *>(_o); switch (_id) { case 0: _t->upgradeNotify((*reinterpret_cast< SMonitor::Type(*)>(_a[1]))); break; case 1: _t->upgradeNotify(); break; case 2: _t->dataChangedNotify((*reinterpret_cast< const QMap<QString,QMap<QString,SoftData> >(*)>(_a[1]))); break; case 3: _t->MessageNotify((*reinterpret_cast< const QDateTime(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 4: _t->SoftwareInstalled((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 5: _t->InstallFinished((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 6: _t->CheckUpgradeData(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (CCategoryFactory::*_t)(SMonitor::Type ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CCategoryFactory::upgradeNotify)) { *result = 0; } } { typedef void (CCategoryFactory::*_t)(const QMap<QString,QMap<QString,SoftData> > & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CCategoryFactory::dataChangedNotify)) { *result = 2; } } { typedef void (CCategoryFactory::*_t)(const QDateTime & , const QString & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CCategoryFactory::MessageNotify)) { *result = 3; } } { typedef void (CCategoryFactory::*_t)(const QString & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CCategoryFactory::SoftwareInstalled)) { *result = 4; } } } } const QMetaObject CCategoryFactory::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_CCategoryFactory.data, qt_meta_data_CCategoryFactory, qt_static_metacall, 0, 0} }; const QMetaObject *CCategoryFactory::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *CCategoryFactory::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CCategoryFactory.stringdata)) return static_cast<void*>(const_cast< CCategoryFactory*>(this)); return QObject::qt_metacast(_clname); } int CCategoryFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 7) qt_static_metacall(this, _c, _id, _a); _id -= 7; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 7) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 7; } return _id; } // SIGNAL 0 void CCategoryFactory::upgradeNotify(SMonitor::Type _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 2 void CCategoryFactory::dataChangedNotify(const QMap<QString,QMap<QString,SoftData> > & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } // SIGNAL 3 void CCategoryFactory::MessageNotify(const QDateTime & _t1, const QString & _t2) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 3, _a); } // SIGNAL 4 void CCategoryFactory::SoftwareInstalled(const QString & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 4, _a); } QT_END_MOC_NAMESPACE
// Algoruthm : Logistic Regression // Data : binary.csv #include <iostream> #include <vector> #include "algorithms/GradientDescent.h" #include "algorithms/Newton.h" using namespace std; int main(int argc, char const *argv[]) { mat X, y ,theta; csv_to_xy("datasets/binary.csv", {"gre" ,"gpa","rank"}, "admit", X, y); // csv_to_xy("data/binary.csv", {"gre" ,"gpa"}, "admit", X, y); // Fist case :theta initialized by zeros // theta.zeros(); // Second case :theta initialized by ones // theta.ones(); // Third case :theta initialized by Gaussian/normal distribution with μ = 0 and σ = 1 theta.randn(); gradientDescent(X, y, theta,logisticCost, logisticGradient) ; theta.print("Theta found") ; return 0; }
#pragma once #include "Physics.h" #ifdef _WIN32 #include <SDL.h> #else #include <SDL2/SDL.h> #endif // _WIN32 class GameObject { public: int width; int height; Physics physics; SDL_Texture* texture; GameObject(int width, int height, Physics physics, SDL_Texture* texture); double i(); double j(); void i(double i); void j(double j); ~GameObject(); };
/** ****************************************************************************** * Copyright (c) 2019 - ~, SCUT-RobotLab Development Team * @file : referee.cpp * @author : charlie 602894526@qq.com * @brief : Code for communicating with Referee system of Robomaster 2019. * @date : 2019-03-01 * @par Change Log: * Date Author Version Notes * 2019-03-01 charlie 2.0.0 Creator * 2019-12-28 kainan 3.0.0 增加绘画类 * 2020-05-26 kainan 4.0.0 适应20年规则 ============================================================================== How to use this driver ============================================================================== Init()初始化模块 裁判系统数据接收与外部读取 1.使用unPackDataFromRF()解包裁判系统串口数据 2.如果需要用到裁判系统提供的各种数据(具体有些什么数据请查看手册),读取相应结构体即可 机器人车间通信 1. 发送端调用CV_ToOtherRobot()发送数据 2. 接收端轮询机器人ID对应的robot_com_data[]数据情况,如工程发送过来的数据为robot_com_data[1] 操作手界面UI 1.Set_DrawingLayer()设置图层,0-9 2.对应的drawin(),clean() 3.组合图形:标尺UI_ruler()、Draw_FitingGraph() 4.注意:发数据给裁判系统。务必注意等待上电稳定之后才发送,否则会丢包 \n 每个图形的name必须不同,建议name[3]不同即可 \n 注意: 串口DMA接收缓存数组大小建议设置等于256,过小容易造成解包过程数据被覆盖。 发送需要和串口接收不同任务,由于速率控制内部有大量的vTaskDelay 要等待一段时间(等串口、裁判系统稳定),再发送clean、数据、UI等 特别注意要用最新的裁判系统客户端,旧版有点问题 目前参考的是裁判系统串口协议附录V1.0-2020-02-25 如有问题,请参考《RM2020裁判系统用户接口协议附录》 2019年度裁判系统资料大全: https://bbs.robomaster.com/thread-7099-1-1.html ****************************************************************************** * @attention: * * if you had modified this file, please make sure your code does not have many * bugs, update the version NO., write dowm your name and the date, the most * important is make sure the users will have clear and definite understanding * through your new brief. ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "referee.h" #include "FreeRTOS.h" #include "task.h"//需要用到taskDelay /* Private define ------------------------------------------------------------*/ /* Private function declarations --------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ static const unsigned char CRC8_TAB[256] = { 0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41, 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc,0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62, 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff, 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07, 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a, 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24, 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9, 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd, 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50, 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee, 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73, 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b, 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16, 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8, 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35, }; static const uint16_t wCRC_Table[256] = { 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 }; /* Private type --------------------------------------------------------------*/ /* Private function declarations ---------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** * @brief * @note use in SendDrawData() and character_drawing() * @param * @retval */ template<typename Type> Type _referee_Constrain(Type input,Type min,Type max){ if (input <= min) return min; else if(input >= max) return max; else return input; } /** * @brief * @param *_huart, handle of HAL_uart * @param *getTick_fun, handle of get microtick fun * @retval */ void referee_Classdef::Init(UART_HandleTypeDef *_huart, uint32_t (*getTick_fun)(void)) { refereeUart = _huart; if(getTick_fun != NULL) Get_SystemTick = getTick_fun; } /** * @brief CRC8 data check. * @param *pchMessage:Data to be processed dwLength:Length of check data ucCRC8:Data after processing * @retval Gets the CRC8 checksum */ unsigned char referee_Classdef::Get_CRC8_Check_Sum(unsigned char *pchMessage,unsigned int dwLength,unsigned char ucCRC8) { unsigned char ucIndex; while (dwLength--) { ucIndex = ucCRC8^(*pchMessage++); ucCRC8 = CRC8_TAB[ucIndex]; } return(ucCRC8); } /** * @brief CRC16 data check. * @param *pchMessage:Data to be processed dwLength:Length of check data ucCRC8:Data after processing * @retval Gets the CRC16 checksum */ uint16_t referee_Classdef::Get_CRC16_Check_Sum(uint8_t *pchMessage,uint32_t dwLength,uint16_t wCRC) { uint8_t chData; if (pchMessage == NULL) { return 0xFFFF; } while(dwLength--) { chData = *pchMessage++; (wCRC) = ((uint16_t)(wCRC) >> 8) ^ wCRC_Table[((uint16_t)(wCRC) ^ (uint16_t)(chData)) & 0x00ff]; } return wCRC; } void referee_Classdef::unPackDataFromRF(uint8_t *data_buf, uint32_t length) { static uint8_t temp[128]; static uint8_t RFdataBuff[256]; static int32_t index,buff_read_index; static short CRC16_Function,CRC16_Referee; static uint8_t byte; static int32_t read_len; static uint16_t data_len; static uint8_t unpack_step; static uint8_t protocol_packet[PROTOCAL_FRAME_MAX_SIZE]; /*初始化读取状态*/ buff_read_index = 0; memcpy(RFdataBuff,data_buf,length); /*从头开始读取 */ read_len=length; while (read_len--) { byte = RFdataBuff[buff_read_index++]; switch(unpack_step) { case STEP_HEADER_SOF: { if(byte == START_ID) { unpack_step = STEP_LENGTH_LOW; protocol_packet[index++] = byte; } else { index = 0; } } break; case STEP_LENGTH_LOW: { data_len = byte; protocol_packet[index++] = byte; unpack_step = STEP_LENGTH_HIGH; } break; case STEP_LENGTH_HIGH: { data_len |= (byte << 8); protocol_packet[index++] = byte; if(data_len < (PROTOCAL_FRAME_MAX_SIZE - HEADER_LEN - CRC_ALL_LEN)) { unpack_step = STEP_FRAME_SEQ; } else { unpack_step = STEP_HEADER_SOF; index = 0; } } break; case STEP_FRAME_SEQ: { protocol_packet[index++] = byte; unpack_step = STEP_HEADER_CRC8; } break; case STEP_HEADER_CRC8: { protocol_packet[index++] = byte; if (index == HEADER_LEN+1) { if ( Get_CRC8_Check_Sum(protocol_packet, HEADER_LEN,0xff)== protocol_packet[HEADER_LEN]) { unpack_step = STEP_DATA_CRC16; } else { unpack_step = STEP_HEADER_SOF; index = 0; } } } break; case STEP_DATA_CRC16: { if (index < (HEADER_LEN + CMD_LEN + data_len + CRC_ALL_LEN)) { protocol_packet[index++] = byte; } if (index >= (HEADER_LEN + CMD_LEN + data_len + CRC_ALL_LEN)) { CRC16_Function=Get_CRC16_Check_Sum(protocol_packet, HEADER_LEN + CMD_LEN + data_len +CRC_8_LEN,0xffff); CRC16_Referee=* (__packed short *)(&protocol_packet[index-2]); if ( CRC16_Function==CRC16_Referee) { RefereeHandle(protocol_packet); } unpack_step = STEP_HEADER_SOF; index = 0; } } break; default: { unpack_step = STEP_HEADER_SOF; index = 0; } break; } } } /** * @brief Receive and handle referee system data * @param void * @retval void */ void referee_Classdef::RefereeHandle(uint8_t *data_buf) { switch(((FrameHeader *)data_buf)->CmdID) { case GameState_ID: GameState = *(ext_game_status_t*)(&data_buf[7]); break; case GameResult_ID: GameResult = *(ext_game_result_t*)(&data_buf[7]); break; case GameRobotHP_ID: GameRobotHP = *(ext_game_robot_HP_t*)(&data_buf[7]); break; case DartStatus_ID: DartStatus = *(ext_dart_status_t*)(&data_buf[7]); break; case EventData_ID: EventData = *(ext_event_data_t*)(&data_buf[7]); break; case SupplyProjectileAction_ID: SupplyAction = *(ext_supply_projectile_action_t*)(&data_buf[7]); break; case RefereeWarning_ID: RefereeWarning = *(ext_referee_warning_t*)(&data_buf[7]); break; case DartRemainingTime_ID: DartRemainTime = *(ext_dart_remaining_time_t*)(&data_buf[7]); break; case GameRobotState_ID: GameRobotState = *(ext_game_robot_status_t*)(&data_buf[7]); Calc_Robot_ID(GameRobotState.robot_id); break; case PowerHeatData_ID: PowerHeatData = *(ext_power_heat_data_t*)(&data_buf[7]); break; case GameRobotPos_ID: RobotPos = *(ext_game_robot_pos_t*)(&data_buf[7]); break; case BuffMusk_ID: RobotBuff = *(ext_buff_t*)(&data_buf[7]); break; case AerialRobotEnergy_ID: AerialEnergy = *(aerial_robot_energy_t*)(&data_buf[7]); break; case RobotHurt_ID: RobotHurt = *(ext_robot_hurt_t*)(&data_buf[7]); break; case ShootData_ID: ShootData = *(ext_shoot_data_t*)(&data_buf[7]); break; case BulletRemaining_ID: BulletRemaining = *(ext_bullet_remaining_t*)(&data_buf[7]); break; case RFID_Status_ID: RFID_Status = *(ext_rfid_status_t*)(&data_buf[7]); break; case RobotComData_ID: RobotInteractiveHandle((robot_interactive_data_t*)(&data_buf[7])); break; default: break; } } /** * @brief Calculate robot ID * @param local robot id * @retval */ void referee_Classdef::Calc_Robot_ID(uint8_t local_id) { if(local_id !=0 ) /* referee connection successful */ { if(local_id < 10) /* red */ { robot_client_ID.hero = 1; robot_client_ID.engineer = 2; robot_client_ID.infantry_3 = 3; robot_client_ID.infantry_4 = 4; robot_client_ID.infantry_5 = 5; robot_client_ID.aerial = 6; robot_client_ID.sentry = 7; robot_client_ID.local = local_id; robot_client_ID.client = 0x0100 + local_id; } else /* blue */ { robot_client_ID.hero = 101; robot_client_ID.engineer = 102; robot_client_ID.infantry_3 = 103; robot_client_ID.infantry_4 = 104; robot_client_ID.infantry_5 = 105; robot_client_ID.aerial = 106; robot_client_ID.sentry = 107; robot_client_ID.local = local_id; robot_client_ID.client = 0x0164 + (local_id - 100); } } } /** * @brief Transfer user system data to the server through huart * @note Referee.CV_ToOtherRobot(, Referee.robot_client_ID.hero, 123); * @param data1,data2,data3,data4:data to send * @retval void */ void referee_Classdef::CV_ToOtherRobot(uint8_t target_id, uint8_t* _data, uint8_t length) { pack_send_robotData(RobotComData_ID, target_id, (uint8_t*)_data, length); } void referee_Classdef::RobotInteractiveHandle(robot_interactive_data_t* RobotInteractiveData_t) { if(GameRobotState.robot_id == RobotInteractiveData_t->receiver_ID && GameRobotState.robot_id != 0) { if(RobotInteractiveData_t->data_cmd_id == RobotComData_ID) { /* 拷贝到对应的机器人数组 */ memcpy(&robot_com_data[RobotInteractiveData_t->sender_ID], RobotInteractiveData_t->data, RobotInteractiveData_t->data[0]); } } } /** * @brief Set the painting layer * @note Referee.line_drawing(ADD_PICTURE, 400,500,1000,900,GREEN, test); A large digital layer covers a small digital layer * @param * @retval */ void referee_Classdef::Set_DrawingLayer(uint8_t _layer) { drawing.layer = _layer; } /** * @brief Draw a straight line at the UI interface * @note Referee.line_drawing(ADD_PICTURE, 400,500,1000,900,GREEN, test); * @param * @retval */ void referee_Classdef::line_drawing(drawOperate_e _operate_type, uint16_t startx,uint16_t starty,uint16_t endx,uint16_t endy,colorType_e vcolor, uint8_t name[]) { memcpy(drawing.graphic_name,name,3); drawing.operate_tpye = _operate_type; drawing.graphic_tpye = LINE; drawing.width=5; drawing.color=vcolor; drawing.start_x=startx; drawing.start_y=starty; drawing.end_x=endx; drawing.end_y=endy; pack_send_robotData(Drawing_1_ID, robot_client_ID.client, (uint8_t*)&drawing, sizeof(drawing)); } /** * @brief * @note Referee.rectangle_drawing(ADD_PICTURE, 700,300,200,900,GREEN, test); * @param * @retval */ void referee_Classdef::rectangle_drawing(drawOperate_e _operate_type, uint16_t startx,uint16_t starty,uint16_t length_,uint16_t width_,colorType_e vcolor, uint8_t name[]) { memcpy(drawing.graphic_name, name, 3); drawing.operate_tpye = _operate_type; drawing.graphic_tpye = RECTANGLE; drawing.width=5; drawing.color=vcolor; drawing.start_x=startx; drawing.start_y=starty; drawing.end_x=startx+length_; drawing.end_y=starty+width_; pack_send_robotData(Drawing_1_ID, robot_client_ID.client, (uint8_t*)&drawing, sizeof(drawing)); } /** * @brief * @note Referee.rectangle_drawing(ADD_PICTURE, 700,300,200,900,GREEN, test); * @param * @retval */ void referee_Classdef::circle_drawing(drawOperate_e _operate_type, uint16_t centrex,uint16_t centrey,uint16_t r,colorType_e vcolor, uint8_t name[]) { memcpy(drawing.graphic_name, name, 3); drawing.operate_tpye = _operate_type; drawing.graphic_tpye = CIRCLE; drawing.width=5; drawing.color=vcolor; drawing.start_x=centrex; drawing.start_y=centrey; drawing.radius=r; pack_send_robotData(Drawing_1_ID, robot_client_ID.client, (uint8_t*)&drawing, sizeof(drawing)); } /** * @brief * @note Referee.oval_drawing(ADD_PICTURE, 800,500,200,500,GREEN,test); * @param * @retval */ void referee_Classdef::oval_drawing(drawOperate_e _operate_type, uint16_t centrex,uint16_t centrey,uint16_t minor_semi_axis,uint16_t major_semi_axis,colorType_e vcolor, uint8_t name[]) { memcpy(drawing.graphic_name, name, 3); drawing.operate_tpye = _operate_type; drawing.graphic_tpye=OVAL ; drawing.width=5; drawing.color=vcolor; drawing.start_x=centrex; drawing.start_y=centrey; drawing.end_x=major_semi_axis; drawing.end_y=minor_semi_axis; pack_send_robotData(Drawing_1_ID, robot_client_ID.client, (uint8_t*)&drawing, sizeof(drawing)); } /** * @brief * @note Referee.arc_drawing(ADD_PICTURE, 800,500,300,500,30,150,PURPLE, test); * @param * @retval */ void referee_Classdef::arc_drawing(drawOperate_e _operate_type, uint16_t centrex,uint16_t centrey,uint16_t endx,uint16_t endy,int16_t start_angle_,int16_t end_angle_,colorType_e vcolor, uint8_t name[]) { memcpy(drawing.graphic_name, name, 3); drawing.operate_tpye = _operate_type; drawing.graphic_tpye=ARC ; drawing.width=5; drawing.color=vcolor; drawing.start_x=centrex; drawing.start_y=centrey; drawing.end_x=endx; drawing.end_y=endy; drawing.start_angle=start_angle_; drawing.end_angle=end_angle_; pack_send_robotData(Drawing_1_ID, robot_client_ID.client, (uint8_t*)&drawing, sizeof(drawing)); } void referee_Classdef::float_drawing(drawOperate_e _operate_type, uint16_t startx,uint16_t starty, colorType_e vcolor, float data, uint8_t name[]) { memcpy(drawing.graphic_name, name, 3); drawing.operate_tpye = _operate_type; drawing.graphic_tpye=_FLOAT ; drawing.start_angle = 10;//需要调试 drawing.end_angle = 2;//小数位有效个数 drawing.width=5; drawing.color=vcolor; drawing.start_x=startx; drawing.start_y=starty; memcpy((void*)drawing.radius, &data, 4); pack_send_robotData(Drawing_1_ID, robot_client_ID.client, (uint8_t*)&drawing, sizeof(drawing)); } void referee_Classdef::int_drawing(drawOperate_e _operate_type, uint16_t startx,uint16_t starty,uint16_t size, uint8_t length,uint8_t character[], colorType_e vcolor, int32_t data,uint8_t name[]) { memcpy(drawing.graphic_name, name, 3); drawing.operate_tpye = _operate_type; drawing.graphic_tpye=_INT ; drawing.start_angle = 10;//需要调试 drawing.width=5; drawing.color=vcolor; drawing.start_x=startx; drawing.start_y=starty; memcpy((void*)drawing.radius, &data, 4); pack_send_robotData(Drawing_1_ID, robot_client_ID.client, (uint8_t*)&drawing, sizeof(drawing)); } /** * @brief * @note Referee.character_drawing(ADD_PICTURE, 800,500,30,3, test, BLUE, test); Character length not exceeding 30 * @param * @retval */ void referee_Classdef::character_drawing(drawOperate_e _operate_type, uint16_t startx,uint16_t starty,uint16_t size, uint8_t char_length,uint8_t character[], colorType_e vcolor, uint8_t name[]) { char_length = _referee_Constrain(char_length, (uint8_t)0, (uint8_t)30); memcpy(drawing.graphic_name, name, 3); drawing.operate_tpye = _operate_type; drawing.graphic_tpye=_CHAR ; drawing.width=5; drawing.color=vcolor; drawing.start_x=startx; drawing.start_y=starty; drawing.radius=size; drawing.start_angle=char_length; uint8_t drawing_len = sizeof(com_temp); memcpy((void*)com_temp, &drawing, drawing_len); memcpy(&com_temp[drawing_len],character, char_length);//字符串 pack_send_robotData(Drawing_Char_ID, robot_client_ID.client, (uint8_t*)&com_temp, drawing_len+char_length); } /** * @brief * @note Referee.clean_one_picture(2, test); * @param * @retval */ void referee_Classdef::clean_one_picture(uint8_t vlayer,uint8_t name[]) { memcpy(drawing.graphic_name, name, 3); drawing.layer = vlayer ; drawing.operate_tpye=CLEAR_ONE_PICTURE; pack_send_robotData(Drawing_1_ID, robot_client_ID.client, (uint8_t*)&drawing, sizeof(drawing)); } /** * @brief * @note Referee.clean_layer(2); * @param * @retval */ void referee_Classdef::clean_layer(uint8_t _layer) { cleaning.layer = _layer; cleaning.operate_tpye = CLEAR_ONE_LAYER; pack_send_robotData(Drawing_Clean_ID, robot_client_ID.client, (uint8_t*)&cleaning, sizeof(cleaning)); } /** * @brief * @note Referee.clean_all(); * @param * @retval */ void referee_Classdef::clean_all() { cleaning.operate_tpye = CLEAR_ALL; pack_send_robotData(Drawing_Clean_ID, robot_client_ID.client, (uint8_t*)&cleaning, sizeof(cleaning)); } /** * @brief draw_ruler * @note #define CIRCLE 24 准心圆半径 * @param _sys_time, sacle_num多少条刻度线(<9),ruler_tag第几条标尺, startpoint(标尺左上角起点), step(间距),scale_long(长刻度线的长度),scale_short * @retval done:1, if no done:0 */ uint8_t referee_Classdef::UI_ruler(uint32_t _sys_time, uint8_t ruler_tag, uint8_t sacle_num,uint16_t start_x, uint16_t start_y, uint16_t step, uint16_t scale_long, uint16_t scale_short, colorType_e _color) { static uint8_t scale_cnt = 0; static uint8_t draw_cnt = 0; static uint32_t last_sys_time = 0; uint8_t name[6]="ruler"; uint16_t axis_temp; if(draw_cnt<5) /* 画5次 */ { if(_sys_time - 200 >= last_sys_time) /* 单位: ms ,频率不能大于10Hz*/ { axis_temp = start_y - scale_cnt*step; name[3] = ruler_tag; name[4] = scale_cnt; if(scale_cnt == 0) { line_drawing(ADD_PICTURE, start_x,start_y,start_x,start_y-(sacle_num+1)*step,_color, name); //竖 } else { if(scale_cnt%2 == 1) line_drawing(ADD_PICTURE, start_x,axis_temp,start_x+scale_long,axis_temp,_color, name); //长 else line_drawing(ADD_PICTURE, start_x,axis_temp,start_x+scale_short,axis_temp,_color, name); //短 } scale_cnt++; last_sys_time = _sys_time; if(scale_cnt>sacle_num) { draw_cnt++; scale_cnt = 0; } } return 0; } else { scale_cnt = 0; draw_cnt = 0; return 1; } } /** * @brief 画拟合图形 * @param *data 打包完的数组,格式为[x0,y0,x1,y1...] * @param length 数组长度,应该为偶数 * @note 画图有问题的话可能是name重复了 */ void referee_Classdef::Draw_FitingGraph(uint8_t *data, uint16_t length,colorType_e _color){ static int draw_cnt = 0;//辅助命名图形 static uint8_t name[3] = "xx"; uint16_t point_cnt = length/2; for(uint16_t i = 0; i < point_cnt; i+=2){ name[0] = draw_cnt/255; name[1] = draw_cnt%255; draw_cnt++; line_drawing(ADD_PICTURE, data[i],data[i+1],data[i+2],data[i+3],_color, name); } } /** * @brief 打包机器人间交互数据并发送 * @param */ void referee_Classdef::pack_send_robotData(uint16_t _data_cmd_id, uint16_t _receiver_ID, uint8_t* _data, uint16_t _data_len) { static uint8_t temp[128]; DataHeader data_header; data_header.data_cmd_id = _data_cmd_id; data_header.send_ID = robot_client_ID.local; data_header.receiver_ID = _receiver_ID; uint8_t header_len = sizeof(data_header); memcpy((void*)temp, &data_header, header_len); memcpy((void*)(temp + header_len), _data, _data_len); if(data_header.receiver_ID == robot_client_ID.client) send_toReferee(StudentInteractiveHeaderData_ID, temp, header_len+_data_len, Client); else send_toReferee(StudentInteractiveHeaderData_ID, temp, header_len+_data_len, OtherRobot); } /** * @brief 发数据包给裁判系统,并做速率控制 * @param _cmd_id, * @param _data, * @param data_len, * @param receiver,接收方是机器人还是客户端,决定数据需不需要发多次(客户端数据经常丢包,所以需要发多次) */ void referee_Classdef::send_toReferee(uint16_t _cmd_id, uint8_t* _data, uint16_t _data_len, receiverType_e _receiver) { static uint8_t temp[128]; static uint8_t seq = 0; FrameHeader send_frame_header; send_frame_header.SOF = START_ID; send_frame_header.DataLength = _data_len; send_frame_header.Seq = seq++; send_frame_header.CRC8 = Get_CRC8_Check_Sum((uint8_t*)&send_frame_header,4,0xff); send_frame_header.CmdID = _cmd_id; uint8_t header_len = sizeof(send_frame_header); memcpy((void*)temp, &send_frame_header, header_len);//frame header memcpy((void*)(temp+header_len), _data, _data_len);//data * (__packed short *)(&temp[header_len + _data_len]) = Get_CRC16_Check_Sum(temp,header_len + _data_len,0xffff);//CRC16 uint8_t send_cnt = 3;//传输次数 uint16_t total_len = header_len + _data_len + 2;//header_len + _data_len + CRC16_len while(send_cnt != 0) { uint32_t now_time = Get_SystemTick()/1000; //ms if(now_time > next_send_time) { HAL_UART_Transmit_DMA(refereeUart,temp,total_len); /* 计算下一次允许传输的时间 */ next_send_time = now_time + float(total_len) / 3720 * 1000; if(_receiver == OtherRobot) send_cnt = 0; else send_cnt--; } vTaskDelay(5); } } /************************ COPYRIGHT(C) SCUT-ROBOTLAB **************************/
/** Kabuki SDK @file /.../Source/Kabuki_SDK-Impl/_G/String.h @author Cale McCollough @copyright Copyright 2016 Cale McCollough © @license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt @brief This file contains the _2D.Vector_f interface. */ using namespace _G; String::String () { fontSize = DefaultFontSize; fontStyle = DefalutFontStyle; fontWidth = 6; fontHeight = 15; numCharictors = 0; fontName = DefaultFontName; colour = DefaultTextColor; font = DefaultFont; } String::String (int leftEdge, int bottomEdge): Cell (leftEdge, bottomEdge, 0, 0) { } /** */ String::String (int leftEdge, int bottomEdge, string initText): Cell (leftEdge, bottomEdge, 0, 0) { text = initText; numCharictors = text.numChars (); } /** */ String::String (int leftEdge, int bottomEdge, string initText, int initFontSize): Cell (leftEdge, bottomEdge, 0, 0) { fontSize = initFontSize; text = initText; numCharictors = text.numChars (); } /** */ String::String (int leftEdge, int bottomEdge, string initText, _G.Color_i initTextColor): Cell (leftEdge, bottomEdge, 0, 0) { text = initText; colour = initTextColor; numCharictors = text.numChars (); } /** */ String::String (int leftEdge, int bottomEdge, string initText, _G.Color_i initTextColor, int initFontSize): Cell (leftEdge, bottomEdge, 0, 0) { text = initText; numCharictors = text.numChars (); colour = initTextColor; fontSize = initFontSize; } /** */ void String::AddText (string newString) { text.concat (newString); numCharictors = text.numChars (); SetWidth (text.numChars () fontWidth); } /** */ string String::AddTextOverflow (const string& newString) { int newTextWidth = newString.numChars () fontWidth; if (newTextWidth + Width > MaxWidth ()) { int difference = newTextWidth+Width -MaxWidth (), overflowIndex = (newTextWidth-Width)/fontWidth; addText (text.SubText (0,overflowIndex)); return newString.SubText (overflowIndex,newString.numChars ()); } AddText (newString); numCharictors = text.numChars (); return new string (); } /** */ bool String::InsertText (const string& newString, int here) { if (newString.numChars ()fontWidth > MaxWidth ()) return false; text = text.SubText (0, here).concat (text.SubText (here+1, text.numChars ())); numCharictors = text.numChars (); return true; } /** */ void String::RemoveCharAtIndex (int index1) { text = text.SubText (0,index1-1).concat (text.SubText (index1,text.numChars ())); numCharictors = text.numChars (); } /** */ void String::RemoveTextAtIndex (int index1, int index2) { text = text.SubText (0,index1).concat (text.SubText (index2,text.numChars ())); numCharictors = text.numChars (); } /** */ void String::SetFont (const string& newFontName) { fontName = newFontName; font = new Font (fontName, fontStyle, fontSize); } /** */ void String::SetFont (Font& newFont) { if (newFont==null) { fontName = newFont.Name; fontSize = newFont.Size (); } } /** */ void String::SetFontSyle (int newStyle) { fontStyle = newStyle; font = new Font (fontName, fontStyle, fontSize); } /** */ float String::GetFontSize () { return fontSize; } void String::SetFontSize (float newSize) { fontSize = newSize; font = new Font (fontName, fontStyle, fontSize); } /** */ Color String::GetDefaultColor () { return DefaultTextColor; } /** */ void String::SetFontColor (Color newColor) { colour = newColor; } string String::GetString () { return string; } int String::SetString (const string& S) { string = S } void String::Update () { } void String::UpdateHeight () { Char currentChar; Iterator iteration = charictors.iterator (); while (iteration.IsNotDone ()) { currentChar = (Char) iteration.nextObject (); int newHeight = currentChar.fontSizefontHeight; if (newHeight > Height) SetHeight (newHeight); } } int String::GetLength () { return numCharictors; } void String::Draw (ScreenBuffer screenBuffer) { if (text == null) return; screenBuffer.setPixel (0,0, colour); }
#ifndef __CCGREEFRIENDCODE_H__ #define __CCGREEFRIENDCODE_H__ #include "cocos2d.h" #include "GreeExtensionMacros.h" NS_CC_GREE_EXT_BEGIN class CCGreeFriendCode; class CCGreeCode; class CCGreeData; class CCGreeFriendCodeDelegate{ public: virtual void loadCodeSuccess(CCGreeCode *code){}; virtual void loadCodeFailure(int responseCode, CCString *response){}; virtual void requestCodeSuccess(CCGreeCode *code){}; virtual void requestCodeFailure(int responseCode, CCString *response){}; virtual void deleteCodeSuccess(){}; virtual void deleteCodeFailure(int responseCode, CCString *response){}; virtual void verifyCodeSuccess(){}; virtual void verifyCodeFailure(int responseCode, CCString *response){}; virtual void loadFriendIdsSuccess(int startIndex, int itemsPerPage, int totalResults, CCArray *dataArray){}; virtual void loadFriendIdsFailure(int responseCode, CCString *response){}; virtual void loadOwnerSuccess(CCGreeData *owner){}; virtual void loadOwnerFailure(int responseCode, CCString *response){}; }; class CCGreeFriendCode { public: static void loadCode(); //static void loadFriends(int startIndex, int count); static void loadFriendIds(int startIndex, int count); static void loadOwner(); static bool requestCode(const char* expireTime); static void verifyCode(const char* code); static void deleteCode(); static void handleLoadCodeOnSuccess(void* code); static void handleLoadCodeOnFailure(int responseCode, const char *response); static void handleRequestCodeOnSuccess(void* code); static void handleRequestCodeOnFailure(int responseCode, const char *response); static void handleDeleteCodeOnSuccess(); static void handleDeleteCodeOnFailure(int responseCode, const char *response); static void handleVerifyCodeOnSuccess(); static void handleVerifyCodeOnFailure(int responseCode, const char *response); static void handleLoadFriendIdsOnSuccess(int startIndex, int itemsPerPage, int totalResults, void **entries); static void handleLoadFriendIdsOnFailure(int responseCode, const char *response); static void handleLoadOwnerOnSuccess(void* owner); static void handleLoadOwnerOnFailure(int responseCode, const char *response); }; class CCGreeCode : public CCObject { public: CCGreeCode(void* code); ~CCGreeCode(); CCString *getCode(); CCString *getExpireTime(); private: void* mGreeCode; }; class CCGreeData : public CCObject { public: CCGreeData(void* data); ~CCGreeData(); CCString *getUserId(); private: void* mGreeData; }; NS_CC_GREE_EXT_END #endif
// Created on: 1995-05-29 // Created by: Jacques GOUSSARD // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _LocOpe_CurveShapeIntersector_HeaderFile #define _LocOpe_CurveShapeIntersector_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <LocOpe_SequenceOfPntFace.hxx> #include <Standard_Integer.hxx> #include <TopAbs_Orientation.hxx> class gp_Ax1; class TopoDS_Shape; class gp_Circ; class LocOpe_PntFace; //! This class provides the intersection between an //! axis or a circle and the faces of a shape. The //! intersection points are sorted in increasing //! parameter along the axis. class LocOpe_CurveShapeIntersector { public: DEFINE_STANDARD_ALLOC //! Empty constructor. LocOpe_CurveShapeIntersector(); //! Creates and performs the intersection betwwen //! <Ax1> and <S>. LocOpe_CurveShapeIntersector(const gp_Ax1& Axis, const TopoDS_Shape& S); //! Creates and performs yte intersection betwwen //! <C> and <S>. LocOpe_CurveShapeIntersector(const gp_Circ& C, const TopoDS_Shape& S); //! Performs the intersection between <Ax1 and <S>. Standard_EXPORT void Init (const gp_Ax1& Axis, const TopoDS_Shape& S); //! Performs the intersection between <Ax1 and <S>. Standard_EXPORT void Init (const gp_Circ& C, const TopoDS_Shape& S); //! Returns <Standard_True> if the intersection has //! been done. Standard_Boolean IsDone() const; //! Returns the number of intersection point. Standard_Integer NbPoints() const; //! Returns the intersection point of range <Index>. //! The points are sorted in increasing order of //! parameter along the axis. const LocOpe_PntFace& Point (const Standard_Integer Index) const; //! Searches the first intersection point located //! after the parameter <From>, which orientation is //! not TopAbs_EXTERNAL. If found, returns //! <Standard_True>. <Or> contains the orientation of //! the point, <IndFrom> and <IndTo> represents the //! interval of index in the sequence of intersection //! point corresponding to the point. (IndFrom <= //! IndTo). //! //! Otherwise, returns <Standard_False>. Standard_EXPORT Standard_Boolean LocalizeAfter (const Standard_Real From, TopAbs_Orientation& Or, Standard_Integer& IndFrom, Standard_Integer& IndTo) const; //! Searches the first intersection point located //! before the parameter <From>, which orientation is //! not TopAbs_EXTERNAL. If found, returns //! <Standard_True>. <Or> contains the orientation of //! the point, <IndFrom> and <IndTo> represents the //! interval of index in the sequence of intersection //! point corresponding to the point (IndFrom <= //! IndTo). //! //! Otherwise, returns <Standard_False>. Standard_EXPORT Standard_Boolean LocalizeBefore (const Standard_Real From, TopAbs_Orientation& Or, Standard_Integer& IndFrom, Standard_Integer& IndTo) const; //! Searches the first intersection point located //! after the index <FromInd> ( >= FromInd + 1), which //! orientation is not TopAbs_EXTERNAL. If found, //! returns <Standard_True>. <Or> contains the //! orientation of the point, <IndFrom> and <IndTo> //! represents the interval of index in the sequence //! of intersection point corresponding to the //! point. (IndFrom <= IndTo). //! //! Otherwise, returns <Standard_False>. Standard_EXPORT Standard_Boolean LocalizeAfter (const Standard_Integer FromInd, TopAbs_Orientation& Or, Standard_Integer& IndFrom, Standard_Integer& IndTo) const; //! Searches the first intersection point located //! before the index <FromInd> ( <= FromInd -1), which //! orientation is not TopAbs_EXTERNAL. If found, //! returns <Standard_True>. <Or> contains the //! orientation of the point, <IndFrom> and <IndTo> //! represents the interval of index in the sequence //! of intersection point corresponding to the point //! (IndFrom <= IndTo). //! //! Otherwise, returns <Standard_False>. Standard_EXPORT Standard_Boolean LocalizeBefore (const Standard_Integer FromInd, TopAbs_Orientation& Or, Standard_Integer& IndFrom, Standard_Integer& IndTo) const; protected: private: Standard_Boolean myDone; LocOpe_SequenceOfPntFace myPoints; }; #include <LocOpe_CurveShapeIntersector.lxx> #endif // _LocOpe_CurveShapeIntersector_HeaderFile
#pragma once #include <string> #include <vector> #include <tuple> #include <unordered_set> #include <map> #include <QTextCodec> #include <QTextStream> #include <boost/optional.hpp> #include <boost/utility/string_view.hpp> #include <boost/filesystem/path.hpp> #include "ComponentsInfrastructure.h" #include "PticaGovorunCore.h" #include "LangStat.h" #include "TextProcessing.h" namespace PticaGovorun { // Soft or hard attribute (uk: тверда/м'яка). The third enum value is 'middle-tongued'. enum class SoftHardConsonant { Hard, Palatal, // =HalfSoft Soft, }; void toString(SoftHardConsonant value, std::string& result); // eg TS for soft consonant TS1 struct PG_EXPORTS BasicPhone { int Id; std::string Name; // eg TS, CH CharGroup DerivedFromChar; // the vowel/consonant it is derived from }; // A = unvoiced vowel A // A1 = voiced vowel A // T = hard T // T1 = soft T // B2 = palatized (kind of half-soft) B struct PG_EXPORTS Phone { typedef IdWithDebugStr<int, char, 4> PhoneIdT; int Id; typedef IdWithDebugStr<int, char, 3> BasicPhoneIdT; BasicPhoneIdT BasicPhoneId; boost::optional<SoftHardConsonant> SoftHard; // valid for consonants only boost::optional<bool> IsStressed; // valid for for vowels only }; typedef Phone::PhoneIdT PhoneId; // Palatal are slightly soft consonants. enum class PalatalSupport { // Palatalized consonant is treated as is (eg P2 -> P2) AsPalatal, // Palatalized consonant is replaced by hard consonant (eg P2 -> P) AsHard, // Palatalized consonant is replaced by soft consonant (eg P2 -> P1) AsSoft, }; // The class to enlist the phones of different configurations. We may be interested in vowel phones with stress marked // or consonant phones with marked softness. So the basic vowel phone A turns into A1 under stress. // The basic phone T turns into T1 when it is softened. class PG_EXPORTS PhoneRegistry { int nextPhoneId_ = 1; // the first phone gets Id=1 std::vector<Phone> phoneReg_; std::vector<BasicPhone> basicPhones_; std::unordered_map<std::string, size_t> basicPhonesStrToId_; bool allowSoftConsonant_ = false; bool allowVowelStress_ = false; PalatalSupport palatalSupport_ = PalatalSupport::AsHard; public: typedef Phone::BasicPhoneIdT BasicPhoneIdT; private: inline BasicPhoneIdT extendBasicPhoneId(int basicPhoneStrId) const; BasicPhoneIdT getOrCreateBasicPhone(const std::string& basicPhoneStr, CharGroup charGroup); public: BasicPhoneIdT basicPhoneId(const std::string& basicPhoneStr, bool* success) const; const BasicPhone* basicPhone(BasicPhoneIdT basicPhoneId) const; PhoneId newVowelPhone(const std::string& basicPhoneStr, bool isStressed); PhoneId newConsonantPhone(const std::string& basicPhoneStr, boost::optional<SoftHardConsonant> softHard); // Augment PhoneId:int with string representation of the phone. Useful for debugging. inline PhoneId extendPhoneId(int validPhoneId) const; inline const Phone* phoneById(int phoneId) const; inline const Phone* phoneById(PhoneId phoneId) const; boost::optional<PhoneId> phoneIdSingle(const std::string& basicPhoneStr, boost::optional<SoftHardConsonant> softHard, boost::optional<bool> isStressed) const; boost::optional<PhoneId> phoneIdSingle(BasicPhoneIdT basicPhoneStrId, boost::optional<SoftHardConsonant> softHard, boost::optional<bool> isStressed) const; void findPhonesByBasicPhoneStr(const std::string& basicPhoneStr, std::vector<PhoneId>& phoneIds) const; // assumes that phones are not removed from registry and ordered consequently int phonesCount() const; // assume that phones are not removed from phone registry and are ordered consequently inline void assumeSequentialPhoneIdsWithoutGaps() const {}; bool allowSoftHardConsonant() const; bool allowVowelStress() const; PalatalSupport palatalSupport() const; void setPalatalSupport(PalatalSupport value); boost::optional<SoftHardConsonant> defaultSoftHardConsonant() const; boost::optional<bool> defaultIsVowelStressed() const; private: friend PG_EXPORTS void initPhoneRegistryUk(PhoneRegistry& phoneReg, bool allowSoftConsonant, bool allowVowelStress); }; PG_EXPORTS void initPhoneRegistryUk(PhoneRegistry& phoneReg, bool allowSoftHardConsonant, bool allowVowelStress); // Returns true if the basic phone becomes half-softened (palatized) in certain letter combinations (before letter I). // Returns false if phone becomes soft in certain letter combinations. bool usuallyHardBasicPhone(const PhoneRegistry& phoneReg, Phone::BasicPhoneIdT basicPhoneId); // Checks whether the character is unvoiced (uk:глухий). PG_EXPORTS inline bool isUnvoicedCharUk(wchar_t ch); // TODO: remove struct Pronunc { std::string StrDebug; // debug string std::vector<std::string> Phones; void setPhones(const std::vector<std::string>& phones); void pushBackPhone(const std::string& phone); }; // One possible pronunciation of a word. struct PronunciationFlavour { // The id of pronunciation. It must be unique among all pronunciations of corresponding word. // Sphinx uses 'clothes(1)' or 'clothes(2)' as unique pronunciation names for the word 'clothes'. // Seems like it is not unique. If some word is pronounced differently then temporary we can assign // different pronAsWord for it even though the same sequence of phones is already assigned to some pronAsWord. boost::wstring_view PronCode; // The actual phones of this pronunciation. std::vector<PhoneId> Phones; }; // Represents all possible pronunciations of a word. // The word 'clothes' may be pronounced as clothes(1)='K L OW1 DH Z' or clothes(2)='K L OW1 Z' struct PhoneticWord { // Important: When any field is modified, update <b>clear</b> too. boost::wstring_view Word; std::vector<PronunciationFlavour> Pronunciations; boost::optional<float> Log10ProbHint; std::string Comment; void clear(); }; class PG_EXPORTS UkrainianPhoneticSplitter { template <typename T, size_t FixedSize> struct ShortArray { std::array<T, FixedSize> Array; size_t ActualSize; }; WordsUsageInfo wordUsage_; std::unordered_map<std::wstring, ShortArray<int,2>> wordStrToPartIds_; // some words, split by default ptrdiff_t seqOneWordCounter_ = 0; ptrdiff_t seqTwoWordsCounter_ = 0; /// If phonetic split is enabled, the splitter tries to divide the word in parts. Otherwise the whole word is used. bool allowPhoneticWordSplit_ = false; const WordPart* sentStartWordPart_; const WordPart* sentEndWordPart_; const WordPart* wordPartSeparator_ = nullptr; std::shared_ptr<SentenceParser> sentParser_; QTextStream* log_ = nullptr; public: bool outputCorpus_ = false; boost::filesystem::path corpusFilePath_; bool outputCorpusNormaliz_ = false; // prints each initial and normalized sentences boost::filesystem::path corpusNormalizFilePath_; public: UkrainianPhoneticSplitter(); void bootstrapFromDeclinedWords(const std::unordered_map<std::wstring, std::unique_ptr<WordDeclensionGroup>>& declinedWords, const std::wstring& targetWord, const std::unordered_set<std::wstring>& processedWords); void gatherWordPartsSequenceUsage(const boost::filesystem::path& textFilesDir, long& totalPreSplitWords, int maxFileToProcess); const WordsUsageInfo& wordUsage() const; WordsUsageInfo& wordUsage(); void printSuffixUsageStatistics() const; // Gets the number of sequences with 'wordSeqLength' words per sequence. long wordSeqCount(int wordsPerSeq) const; const WordPart* sentStartWordPart() const; const WordPart* sentEndWordPart() const; void setAllowPhoneticWordSplit(bool value); bool allowPhoneticWordSplit() const; void setSentParser(std::shared_ptr<SentenceParser> sentParser); private: void doWordPhoneticSplit(const wv::slice<wchar_t>& wordSlice, std::vector<const WordPart*>& wordParts); void analyzeSentence(const std::vector<wv::slice<wchar_t>>& words, std::vector<RawTextLexeme>& lexemes) const; bool checkGoodSentenceUkr(const std::vector<RawTextLexeme>& lexemes) const; // split words into slices void selectWordParts(const std::vector<RawTextLexeme>& lexemes, std::vector<const WordPart*>& wordParts, long& preSplitWords); void calcNGramStatisticsOnWordPartsBatch(std::vector<const WordPart*>& wordParts); // calculate statistics on word parts list void calcLangStatistics(const std::vector<const WordPart*>& wordParts); }; // equality by value PG_EXPORTS bool operator == (const Pronunc& a, const Pronunc& b); PG_EXPORTS bool operator < (const Pronunc& a, const Pronunc& b); PG_EXPORTS bool getStressedVowelCharIndAtMostOne(boost::wstring_view word, int& stressedCharInd); PG_EXPORTS int syllableIndToVowelCharIndUk(boost::wstring_view word, int syllableInd); PG_EXPORTS int vowelCharIndToSyllableIndUk(boost::wstring_view word, int vowelCharInd); // Loads stressed vowel definitions from file. PG_EXPORTS bool loadStressedSyllableDictionaryXml(const boost::filesystem::path& dictFilePath, std::unordered_map<std::wstring, int>& wordToStressedSyllableInd, ErrMsgList* errMsg); #ifdef PG_HAS_JULIUS // Loads dictionary of word -> (phone list) from text file. // File usually has 'voca' extension. // File has Windows-1251 encodeding. // Each word may have multiple pronunciations (1-* relation); for now we neglect it and store data into map (1-1 relation). PG_EXPORTS std::tuple<bool, const char*> loadPronunciationVocabulary(const std::wstring& vocabFilePathAbs, std::map<std::wstring, std::vector<std::string>>& wordToPhoneList, const QTextCodec& textCodec); // TODO: remove #endif PG_EXPORTS void parsePronId(boost::wstring_view pronId, boost::wstring_view& pronName); PG_EXPORTS bool isWordStressAssigned(const PhoneRegistry& phoneReg, const std::vector<PhoneId>& phoneIds); /// Checks that pronCode in 'clothes(1)' format and not 'clothes' (without round parantheses). bool isPronCodeDefinesStress(boost::wstring_view pronCode); /// Parses pronCode. /// For 'clothes(2)' pronCodeName='clothes', pronCodeStressSuffix='2' bool parsePronCodeNameAndStress(boost::wstring_view pronCode, boost::wstring_view* pronCodeName, boost::wstring_view* pronCodeStressSuffix); // 'brokenLines' has lines of the dictionary which can't be read. PG_EXPORTS std::tuple<bool, const char*> loadPhoneticDictionaryPronIdPerLine(const std::basic_string<wchar_t>& vocabFilePathAbs, const PhoneRegistry& phoneReg, const QTextCodec& textCodec, std::vector<PhoneticWord>& words, std::vector<std::string>& brokenLines, GrowOnlyPinArena<wchar_t>& stringArena); PG_EXPORTS bool loadPhoneticDictionaryXml(const boost::filesystem::path& filePath, const PhoneRegistry& phoneReg, std::vector<PhoneticWord>& phoneticDict, GrowOnlyPinArena<wchar_t>& stringArena, ErrMsgList* errMsg); PG_EXPORTS bool savePhoneticDictionaryXml(const std::vector<PhoneticWord>& phoneticDict, const boost::filesystem::path& filePath, const PhoneRegistry& phoneReg, ErrMsgList* errMsg); PG_EXPORTS void normalizePronunciationVocabulary(std::map<std::wstring, std::vector<Pronunc>>& wordToPhoneList, bool toUpper = true, bool trimNumbers = true); PG_EXPORTS void trimPhoneStrExtraInfos(const std::string& phoneStr, std::string& phoneStrTrimmed, bool toUpper, bool trimNumbers); PG_EXPORTS bool phoneToStr(const PhoneRegistry& phoneReg, int phoneId, std::string& result); PG_EXPORTS bool phoneToStr(const PhoneRegistry& phoneReg, PhoneId phoneId, std::string& result); PG_EXPORTS bool phoneListToStr(const PhoneRegistry& phoneReg, wv::slice<PhoneId> pron, std::string& result); // Parses space-separated list of phones. PG_EXPORTS boost::optional<PhoneId> parsePhoneStr(const PhoneRegistry& phoneReg, boost::string_view phoneStr); PG_EXPORTS bool parsePhoneList(const PhoneRegistry& phoneReg, boost::string_view phoneListStr, std::vector<PhoneId>& result); PG_EXPORTS std::tuple<bool, const char*> parsePronuncLinesNew(const PhoneRegistry& phoneReg, const std::wstring& prons, std::vector<PronunciationFlavour>& result, GrowOnlyPinArena<wchar_t>& stringArena); // Removes phone modifiers. PG_EXPORTS void updatePhoneModifiers(const PhoneRegistry& phoneReg, bool keepConsonantSoftness, bool keepVowelStress, std::vector<PhoneId>& phonesList); // Half made phone. // The incomplete phone's data, so that complete PhoneId can't be queried from phone registry. typedef decltype(static_cast<Phone*>(nullptr)->BasicPhoneId) BasicPhoneIdT; struct PhoneBillet { BasicPhoneIdT BasicPhoneId; boost::optional<CharGroup> DerivedFromChar = boost::none; boost::optional<SoftHardConsonant> SoftHard = boost::none; // valid for consonants only boost::optional<bool> IsStressed = boost::none; // valid for for vowels only }; // Transforms text into sequence of phones. class PG_EXPORTS WordPhoneticTranscriber { public: typedef std::function<auto (boost::wstring_view, std::vector<int>&) -> bool> StressedSyllableIndFunT; private: const PhoneRegistry* phoneReg_; const std::wstring* word_; std::vector<char> isLetterStressed_; // -1 not initialized, 0=false, 1=true size_t letterInd_; std::wstring errString_; std::vector<PhoneBillet> billetPhones_; std::vector<PhoneId> outputPhones_; std::map<int, int> phoneIndToLetterInd_; StressedSyllableIndFunT stressedSyllableIndFun_ = nullptr; public: void transcribe(const PhoneRegistry& phoneReg, const std::wstring& word); void copyOutputPhoneIds(std::vector<PhoneId>& phoneIds) const; void setStressedSyllableIndFun(StressedSyllableIndFunT value); bool hasError() const; const std::wstring& errorString() const; private: // The current processed character of the word. inline wchar_t curLetter() const; inline boost::optional<bool> isCurVowelStressed() const; inline wchar_t offsetLetter(int offset) const; inline bool isFirstLetter() const; inline bool isLastLetter() const; public: int getVowelLetterInd(int vowelPhoneInd) const; private: PhoneBillet newConsonantPhone(const std::string& basicPhoneStr, boost::optional<SoftHardConsonant> SoftHard) const; PhoneBillet newVowelPhone(const std::string& basicPhoneStr, boost::optional<bool> isStressed) const; // Maps letter to a default phone candidate. More complicated cases are handled via rules. bool makePhoneFromCurLetterOneToOne(PhoneBillet& ph) const; void addPhone(const PhoneBillet& phone); void phoneBilletToStr(const PhoneBillet& phone, std::wstring& result) const; // void tryInitStressedVowels(); bool ruleIgnore(); // do not require neighbourhood info bool ruleJi(); // do not require neighbourhood info bool ruleShCh(); // do not require neighbourhood info bool ruleDzDzh(); // progressive bool ruleZhDzh(); // progressive bool ruleNtsk(); // progressive bool ruleSShEtc(); // progressive bool ruleTsEtc(); // progressive bool ruleSoftSign(); // regressive bool ruleApostrophe(); // regressive bool ruleHardConsonantBeforeE(); // regressive bool ruleSoftConsonantBeforeI(); // regressive bool ruleDoubleJaJeJu(); // regressive bool ruleSoftConsonantBeforeJaJeJu(); // regressive bool ruleDampVoicedConsonantBeforeUnvoiced(); // progressive bool ruleDefaultSimpleOneToOneMap(); // do not require neighbourhood info // Checks whether the given phone is of the kind, which mutually softens each other. bool isMutuallySoftConsonant(Phone::BasicPhoneIdT basicPhoneId) const; // Rule: checks that if there are two consequent phones of specific type, and the second is soft, then the first becomes soft too. void postRulePairOfConsonantsSoftenEachOther(); void postRuleAmplifyUnvoicedConsonantBeforeVoiced(); void buildOutputPhones(); }; // Performs word transcription (word is represented as a sequence of phonemes). PG_EXPORTS std::tuple<bool, const char*> spellWordUk(const PhoneRegistry& phoneReg, const std::wstring& word, std::vector<PhoneId>& phones, WordPhoneticTranscriber::StressedSyllableIndFunT stressedSyllableIndFun = nullptr); template <typename MapT> void reshapeAsDict(const std::vector<PhoneticWord>& phoneticDictWordsList, MapT& phoneticDict) { for (const PhoneticWord& item : phoneticDictWordsList) { boost::wstring_view w = item.Word; // IMPORTANT: the word must not move in memory phoneticDict[w] = item; } } PG_EXPORTS void populatePronCodes(const std::vector<PhoneticWord>& phoneticDict, std::map<boost::wstring_view, PronunciationFlavour>& pronCodeToObj, std::vector<boost::wstring_view>& duplicatePronCodes); // Integrate new pronunciations from extra dictionary into base dictionary. Pronunciations with existent code are ignored. PG_EXPORTS void mergePhoneticDictOnlyNew(std::map<boost::wstring_view, PhoneticWord>& basePhoneticDict, const std::vector<PhoneticWord>& extraPhoneticDict); // PG_EXPORTS int phoneticSplitOfWord(wv::slice<wchar_t> word, boost::optional<PartOfSpeech> wordClass, int* pMatchedSuffixInd = nullptr); // <sil> pseudo word. PG_EXPORTS boost::wstring_view fillerSilence(); PG_EXPORTS boost::string_view fillerSilence1(); // <s> pseudo word. PG_EXPORTS boost::wstring_view fillerStartSilence(); // </s> pseudo word. PG_EXPORTS boost::wstring_view fillerEndSilence(); // [sp] pseudo word. PG_EXPORTS boost::wstring_view fillerShortPause(); // _s pseudo word. Short pause but shorter than [sp]. PG_EXPORTS boost::wstring_view fillerSingleSpace(); // [inh] pseudo word. PG_EXPORTS boost::wstring_view fillerInhale(); // [exh] pseudo word. PG_EXPORTS boost::wstring_view fillerExhale(); // [eee] (latin 'e') pseudo word. PG_EXPORTS boost::wstring_view fillerEee(); // [yyy] (latin 'y') pseudo word. PG_EXPORTS boost::wstring_view fillerYyy(); /// _ignore PG_EXPORTS boost::string_view keywordIgnore(); }
#pragma once #include "stdafx.h" #include "Voxel.h" #include "skeleton.h" #include "boneAbstract.h" #include "cutTree.h" #include "neighbor.h" #include "octreeSolid.h" #include "cutTreef.h" #include "boneTransform.h" #include "voxelObject.h" #include "poseManager.h" #include "FilterCutDialog.h" class cutSurfTreeMngr2 { public: cutSurfTreeMngr2(void); ~cutSurfTreeMngr2(void); void drawLeaf(int mode); void drawSuggestionsText(int mode, CDC* pDC); void updateDisplay(int idx1, int idx2); void updateDisplayFilter(int idx1, int idx2); int updateBestIdxFilter(int idx1); void setSavedPose1(int idx1); void showWeightInputDialog(); // coded but not implemented int findBestOption(int yIdx); //Export std::vector<meshCutRough> convertBoxesToMeshCut(std::vector<Boxi> centerBoxi); void exportMesh(); void drawLocalCoord(cutTreefNode * node); // Core functions to set up tree void init(); void parserSkeletonGroup(); void constructCutTree(); void filterPose(std::vector<neighborPos> pp); void getListOfBestPoses(); private: void setVoxelArray(); void drawNeighborRelation(int mode); public: // Group bone // Share data from main document skeleton *s_groupSkeleton; voxelObject *s_voxelObj; std::vector<voxelBox>* s_boxes; // Data load from file VoxelObj m_voxelHighRes; octreeSolid m_octree; // Different poses poseManager poseMngr; // Hash voxel std::vector<voxelBox> boxes; // all voxel pixel box hashVoxel hashTable; bool bUniformCut; cutTreef m_tree2; cutTreefNode *leatE2Node2; // variables std::vector<boneAbstract> m_boneOrder; std::vector<std::pair<int,int>> neighborPair; // With symmetric std::vector<boneAbstract> m_centerBoneOrder; std::vector<boneAbstract> m_sideBoneOrder; std::vector<neighbor> neighborInfo; int m_roughScaleStep; // Step for rough estimation float octreeSizef; // tree cutTree m_tree; cutTreeNode *leatE2Node; // Debug cutTreefNode* curNode; int poseIdx, nodeIdx; // Index in pose array std::vector<boneTransform2> coords; std::vector<CString> names; std::vector<Vec3f> centerPos; arrayVec2i meshNeighbor; neighborPose currentPose; neighborPose *curPose; std::vector<meshPiece> allMeshes; // Saved 1 cutTreefNode* savedNode1; int savedPoseIdx1, savedNodeIdx1; // Index in pose array std::vector<CString> savedNames1; std::vector<Vec3f> savedCenterPos1; arrayVec2i savedMeshNeighbor1; neighborPose *savedPose1; std::vector<meshPiece> savedAllMeshes1; // User define weight error Vec3f m_weightError; // neighbor - aspect - volume FilterCutDialog *m_dlg; Vec3f m_weights; void connectWithDialog(FilterCutDialog *cd); void calculateSortingRequirements(std::vector<int> idealHashes); void calculateEstimatedCBLengths(); void updateSortEvaluations(float weights[3]); bool drawNeedsUpdate; };
//Program Name: Hello World #include <iostream> using std::cin; using std::cout; using std::endl; int main() { int var = 1100; cout << "variable = " << var << endl; cout << "var memory ref address = " << &var << endl; }
#include <bits/stdc++.h> using namespace std; int main() { int n, t, a, i=1; while(scanf("%d %d", &n, &t) && n && t) { a = ceil(((double)n-t)/t); if(a>26) printf("Case %d: impossible\n", i); else printf("Case %d: %d\n", i, a); i++; } return 0; }
#include "CObject.h" #include "3DModel.h" #include "PrimitiveBase.h" #include "RenderAttributes.h" CObject::CObject( PhysicBody::E physicBody ) { m_bodyType = physicBody; } CObject::CObject() { m_bodyType = PhysicBody::NONE; } void CObject::Create( const Mat4D::CVector4D& bodySize, float fDensity, std::weak_ptr<PrimitiveBase> renderModel, chrono::ChSystem* pSystem ) { static std::shared_ptr<chrono::ChMaterialSurface> pMaterialSurface; if ( !pMaterialSurface ) { pMaterialSurface = std::make_shared<chrono::ChMaterialSurface>(); pMaterialSurface->SetFriction( 0.4f ); pMaterialSurface->SetCompliance( 0.0000005f ); pMaterialSurface->SetComplianceT( 0.0000005f ); pMaterialSurface->SetDampingF( 0.2f ); } m_renderModel = renderModel; switch ( m_bodyType ) { case PhysicBody::CUBE_STATIC: CTransform::SetScale( bodySize.x * 0.5f, bodySize.y * 0.5f, bodySize.z * 0.5f ); m_physicBody = std::make_shared<chrono::ChBodyEasyBox>( bodySize.x, bodySize.y, bodySize.z, fDensity, true, false ); m_physicBody->SetMaterialSurface( pMaterialSurface ); m_physicBody->SetBodyFixed( true ); pSystem->AddBody( m_physicBody ); break; case PhysicBody::CUBE: CTransform::SetScale( bodySize.x * 0.5f, bodySize.y * 0.5f, bodySize.z * 0.5f ); m_physicBody = std::make_shared<chrono::ChBodyEasyBox>( bodySize.x, bodySize.y, bodySize.z, fDensity, true, false ); m_physicBody->SetMaterialSurface( pMaterialSurface ); m_physicBody->SetBodyFixed( false ); pSystem->AddBody( m_physicBody ); break; case PhysicBody::NONE: default: break; } } void CObject::Update( float dt ) { if ( m_physicBody ) { auto pos = m_physicBody->GetPos(); CTransform::SetPosition( (float)pos.x(), (float)pos.y(), (float)pos.z() ); /*auto angleQ = m_physicBody->GetRot(); Mat4D::CQuaternion qt( (float)angleQ.e0(), (float)angleQ.e1(), (float)angleQ.e2(), (float)angleQ.e3() ); Mat4D::CMatrix4D m4; qt.FillMatrix( m4.v ); CTransform::SetRotation( m4 );*/ } } void CObject::Draw( SRenderAttributes & renderAttribs ) { if ( auto model = m_renderModel.lock() ) model->Draw( GetTransformed().v, renderAttribs ); } void CObject::SetRotationX( float angle ) { if ( m_physicBody ) m_physicBody->SetRot( chrono::Q_from_AngX( angle ) ); else CTransform::SetRotationX( angle ); } void CObject::RotateX( float angle ) { if ( m_physicBody ) m_physicBody->SetRot( m_physicBody->GetRot() * chrono::Q_from_AngX( angle ) ); else CTransform::RotateX( angle ); } void CObject::SetRotationY( float angle ) { if ( m_physicBody ) m_physicBody->SetRot( chrono::Q_from_AngY( angle ) ); else CTransform::SetRotationY( angle ); } void CObject::RotateY( float angle ) { if ( m_physicBody ) m_physicBody->SetRot( m_physicBody->GetRot() * chrono::Q_from_AngY( angle ) ); else CTransform::RotateY( angle ); } void CObject::SetRotationZ( float angle ) { if ( m_physicBody ) m_physicBody->SetRot( chrono::Q_from_AngZ( angle ) ); else CTransform::SetRotationZ( angle ); } void CObject::RotateZ( float angle ) { if ( m_physicBody ) m_physicBody->SetRot( m_physicBody->GetRot() * chrono::Q_from_AngZ( angle ) ); else CTransform::RotateZ( angle ); } void CObject::SetRotation( float x, float y, float z ) { if ( m_physicBody ) m_physicBody->SetRot( chrono::Q_from_AngX( x ) * chrono::Q_from_AngY( y ) * chrono::Q_from_AngZ( x ) ); else CTransform::Rotate( x, y, z ); } void CObject::Rotate( float x, float y, float z ) { if ( m_physicBody ) m_physicBody->SetRot( m_physicBody->GetRot() * chrono::Q_from_AngX( x ) * chrono::Q_from_AngY( y ) * chrono::Q_from_AngZ( x ) ); else CTransform::Rotate( x, y, z ); } void CObject::SetPosition( float x, float y, float z ) { if ( m_physicBody ) m_physicBody->SetPos( { x, y, z } ); else CTransform::SetPosition( x, y, z ); } void CObject::SetPosition( const Mat4D::CVector4D& position ) { if ( m_physicBody ) m_physicBody->SetPos( { position.x, position.y, position.z } ); else CTransform::SetPosition( position ); } void CObject::Move( float x, float y, float z ) { if ( m_physicBody ) m_physicBody->Move( chrono::ChVector<>{ x, y, z } ); else CTransform::Move( x, y, z ); } void CObject::Move( const Mat4D::CVector4D& distance ) { if ( m_physicBody ) m_physicBody->Move( chrono::ChVector<>{ distance.x, distance.y, distance.z } ); else CTransform::Move( distance ); } CObject::~CObject() { }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; int f[510],dis[510],vis[510]; stack<int> S; int find(int k) { while (f[k] != k && f[k] != -1) { S.push(k); k = f[k]; } while (!S.empty()) { int p = S.top();S.pop(); dis[p] = (dis[p] + dis[f[p]])%3; f[p] = k; } return k; } int main() { int n,m; int a,b,c; char op; while (scanf("%d%d",&n,&m) != EOF) { for (int i = 0;i < n; i++) {f[i] = i;dis[i] = 0;} memset(vis,0,sizeof(vis)); for (int i = 1;i <= m; i++) { scanf("%d%c%d",&a,&op,&b); if (op == '=') c = 0; else if (op == '>') c = 1; else c = 2; int x = find(a),y = find(b); if (x == -1 || y == -1) continue; //cout << dis[a] << " " << dis[b] << " " << c << endl; if (x == y && dis[a] != (dis[b] + c)%3) { if (vis[a] == -1 || vis[b] == -1) { if (vis[a] == -1) {vis[a] = i;f[a] = -1;} if (vis[b] == -1) {vis[b] = i;f[b] = -1;} } else { vis[a] = vis[b] = -1; } } else { f[x] = y; dis[x] = (c + dis[b] - dis[a] + 3)%3; } //cout << x << " " << y << endl; } int ans = -1,cou = 0; if (n == 1) ans = 0; for (int i = 0;i < n; i++) { //cout << vis[i] << " "; if (vis[i] > 0) { if (ans == -1) ans = i; else ans = -2; } if (vis[i] < 0) cou++; } //cout << endl; if (cou > 2 || ans == -2) puts("Impossible"); else if (ans == -1) puts("Can not determine"); else printf("Player %d can be determined to be the judge after %d lines\n",ans,vis[ans]); } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef MODULES_UTIL_SMARTPTR_H #define MODULES_UTIL_SMARTPTR_H #include "modules/util/simset.h" /** * OpReferenceCounter is the base class used for all classes that * will be referenced by OpSmartPointer instances. */ class OpReferenceCounter { private: unsigned int reference_counter; public: #ifdef _DEBUG #ifdef YNP_WORK Head debug_list; #endif #endif /** Default constructor */ OpReferenceCounter(){reference_counter = 0;} /** Copy Constructor. Works like Default constructor */ OpReferenceCounter(OpReferenceCounter &){reference_counter = 0;} /** Destructor */ virtual ~OpReferenceCounter(){ #ifdef _DEBUG #ifdef YNP_WORK //OP_ASSERT(debug_list.Empty()); #endif #endif //OP_ASSERT(reference_counter == 0); } /** Assignment operator. Does not do anything */ OpReferenceCounter &operator =(OpReferenceCounter &){return *this;} /** Increment reference count*/ unsigned int Increment_Reference(){return ++reference_counter;} /** Decrement reference count. Cannot decrement below 0*/ unsigned int Decrement_Reference(){if (reference_counter){ reference_counter--;} return reference_counter;} /** Returns the current reference count for this object */ unsigned int Get_Reference_Count() const {return reference_counter;} }; /** * SmartPointer template class * * This class takes care of all housekeeping concerning reference counting. * * NOTE This implementation DOES NOT delete the target if the reference * count is reduced to zero. Cleanup is assumed to be done by designated * code. * * @param T Class of type OpReferenceCounter */ template<class T> class OpSmartPointerNoDelete #ifdef _DEBUG #ifdef YNP_WORK : public Link #endif #endif { private: T *object; public: /** Default Constructor */ OpSmartPointerNoDelete(): object(NULL){}; /** * Copy Constructor * * @param ptr Another Smart pointer, after this call this object will * also reference the object ptr references */ OpSmartPointerNoDelete(const OpSmartPointerNoDelete &ptr): object(NULL){SetNewValue((T *) ptr.object);}; /** * Constructor with pointer argument * * @param ptr This object will be pointing to the object ptr is pointing to */ OpSmartPointerNoDelete(T *ptr): object(NULL){SetNewValue((T *) ptr);}; /** Destructor, the reference counter of the current object (if any) will be decremented */ ~OpSmartPointerNoDelete(){SetNewValue(NULL);}; /** Returns the current pointer of this object */ operator T *(){return object;} /** Returns the current pointer of this object */ operator const T *() const {return object;} /** Returns the current pointer of this object */ T *operator ->(){return object;} /** Returns the current pointer of this object */ const T *operator ->() const {return object;} /** Returns a reference to the currently referenced object * NOTE: This function DOES NOT take into account NULL pointers, * but in debug mode an OP_ASSERT will be triggered. */ T &operator *(){OP_ASSERT(object); return *object;} /** Returns a reference to the currently referenced object * NOTE: This function DOES NOT take into account NULL pointers, * but in debug mode an OP_ASSERT will be triggered. */ const T &operator *() const {OP_ASSERT(object); return *object;} /** * Equality operator. Returns TRUE (non-zero) if the pointers of both this * object and ptr are the same, FALSE (zero) if they are not. */ BOOL operator ==(const OpSmartPointerNoDelete &ptr) const {return (object == ptr.object);} /** * Equality operator. Returns TRUE (non-zero) if the pointer of this * object and ptr are the same, FALSE (zero) if they are not. */ BOOL operator ==(T *ptr) const {return (object == ptr);} /** * Inequality operator. Returns TRUE (non-zero) if the pointers of both this * object and ptr are not the same, FALSE (zero) if they are the same. */ BOOL operator !=(const OpSmartPointerNoDelete &ptr) const {return (object != ptr.object);} /** * Inequality operator. Returns TRUE (non-zero) if the pointer of this * object and ptr are not the same, FALSE (zero) if they are the same. */ BOOL operator !=(T *ptr) const {return (object != ptr);} /** * Assignment operator * * This object will be set to point at the same object that ptr is pointing to, with * reference counters appropriately set for the old and new objects * * @param ptr Reference to the smartpointer holding the new pointer value. The object is not updated * * @return Reference to this Object */ OpSmartPointerNoDelete &operator =(const OpSmartPointerNoDelete &ptr){SetNewValue((T *) ptr.object);return *this;}; /** * Assignment operator * * This object will be set to point at the same object that ptr is pointing to, with * reference counters appropriately set for the old and new objects * * @param ptr Pointer to the object that this object will point to. * * @return Reference to this Object */ OpSmartPointerNoDelete &operator =(T *ptr){SetNewValue((T *) ptr); return *this;}; private: /** * Decrements the reference counter of the previous object, * increments the reference counte of the new object, and assigns it to * the object pointer. * @param new_value Pointer to a OpReferenceCounter object. * This pointer-value will be assigned to target * If non-NULL the reference counter of the referenced object * will be incremented. */ void SetNewValue(T *new_value) { #if defined (_DEBUG) && defined(YNP_WORK) if(InList()) Out(); if(new_value) Into(&new_value->debug_list); #endif // _DEBUG && YNP_WORK if(object) { object->Decrement_Reference(); } object = new_value; if(object) { object->Increment_Reference(); } } }; /** * SmartPointer template class * * This class takes care of all housekeeping concerning reference counting. * * NOTE: This implementation deletes the target if the reference * count is reduced to zero. * * @param T Class of type OpReferenceCounter */ template<class T> class OpSmartPointerWithDelete #ifdef _DEBUG #ifdef YNP_WORK : public Link #endif #endif { private: T *object; public: /** Default Constructor */ OpSmartPointerWithDelete(): object(NULL){}; /** * Copy Constructor * * @param ptr Another Smart pointer, after this call this object will * also reference the object ptr references */ OpSmartPointerWithDelete(const OpSmartPointerWithDelete &ptr): object(NULL){SetNewValue((T *) ptr.object);}; /** * Constructor with pointer argument * * @param ptr This object will be pointing to the object ptr is pointing to */ OpSmartPointerWithDelete(T *ptr): object(NULL){SetNewValue((T *) ptr);}; /** Destructor, the reference counter of the current object (if any) will be decremented */ ~OpSmartPointerWithDelete(){SetNewValue(NULL);}; /** Returns the current pointer of this object */ operator T *(){return object;} /** Returns the current pointer of this object */ operator const T *() const {return object;} /** Returns the current pointer of this object */ T *operator ->(){return object;} /** Returns the current pointer of this object */ const T *operator ->() const {return object;} /** Returns a reference to the currently referenced object * NOTE: This function DOES NOT take into account NULL pointers, * but in debug mode an OP_ASSERT will be triggered. */ T &operator *() const {OP_ASSERT(object); return *object;} /** * Equality operator. Returns TRUE (non-zero) if the pointers of both this * object and ptr are the same, FALSE (zero) if they are not. */ BOOL operator ==(const OpSmartPointerWithDelete &ptr) const {return (object == ptr.object);} /** * Equality operator. Returns TRUE (non-zero) if the pointer of this * object and ptr are the same, FALSE (zero) if they are not. */ BOOL operator ==(T *ptr) const {return (object == ptr);} /** * Inequality operator. Returns TRUE (non-zero) if the pointers of both this * object and ptr are not the same, FALSE (zero) if they are the same. */ BOOL operator !=(const OpSmartPointerWithDelete &ptr) const {return (object != ptr.object);} /** * Inequality operator. Returns TRUE (non-zero) if the pointer of this * object and ptr are not the same, FALSE (zero) if they are the same. */ BOOL operator !=(T *ptr) const {return (object != ptr);} /** * Assignment operator * * This object will be set to point at the same object that ptr is pointing to, with * reference counters appropriately set for the old and new objects * * @param ptr Reference to the smartpointer holding the new pointer value. The object is not updated * * @return Reference to this Object */ OpSmartPointerWithDelete &operator =(const OpSmartPointerWithDelete &ptr){SetNewValue((T *) ptr.object);return *this;}; /** * Assignment operator * * This object will be set to point at the same object that ptr is pointing to, with * reference counters appropriately set for the old and new objects * * @param ptr Pointer to the object that this object will point to. * * @return Reference to this Object */ OpSmartPointerWithDelete &operator =(T *ptr){SetNewValue((T *) ptr); return *this;}; private: /** * Decrements the reference counter of the previous object, * increments the reference counte of the new object, and assigns it to * the object pointer. * * If the reference count of the present object reaches zero, it is deleted. * * @param new_value Pointer to a OpReferenceCounter object. * This pointer-value will be assigned to target * If non-NULL the reference counter of the referenced object * will be incremented. */ void SetNewValue(T *new_value) { #if defined (_DEBUG) && defined(YNP_WORK) if(InList()) Out(); if(new_value) Into(&new_value->debug_list); #endif // _DEBUG && YNP_WORK if(new_value) { new_value->Increment_Reference(); } if(object) { if(object->Decrement_Reference() == 0) OP_DELETE(object); } object = new_value; } }; #endif // !MODULES_UTIL_SMARTPTR_H
//Using floodfill. Time-0.000s #include <bits/stdc++.h> using namespace std; #define ll long long #define vll vector<ll> int dr[] = {1,0,0,-1}; int dc[] = {0,1,-1,0}; char a[51][51]; ll w,h,cnt; void dfs1(ll i,ll j) { if(i >= h || j >= w || i < 0 || j < 0) return; if(a[i][j]!='X') return; a[i][j]='*'; for(int k=0;k<4;k++) { dfs1(i+dr[k],j+dc[k]); } } void dfs(ll i, ll j) { if(i >= h || j >= w || i < 0 || j < 0) return; if(a[i][j]=='.') return; if(a[i][j]=='X') { cnt++; dfs1(i,j); } a[i][j]='.'; for(int k=0;k<4;k++) { dfs(i+dr[k],j+dc[k]); } } int main() { ll t=0; while(cin>>w>>h) { if(w==0 && h==0) break; t++; cout<<"Throw "<<t<<"\n"; for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { cin>>a[i][j]; } } vll ans; for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { if(a[i][j]!='.') { cnt=0; dfs(i,j); ans.push_back(cnt); } } } sort(ans.begin(),ans.end()); cout<<ans[0]; for(int i=1;i<ans.size();i++) { cout<<" "<<ans[i]; } cout<<"\n\n"; } }
#include "GameUserWidget.h" #include "EngineUtils.h" #include "Fire.h" #include "Kismet/GameplayStatics.h" #include "GameFramework/PlayerState.h" #include "GameFramework/Character.h" void UGameUserWidget::ShowSingleScore(FString Name, float Score) { ScoreBoard->SetRenderOpacity(1); USingleScore* Single = Cast<USingleScore>(CreateWidget(UGameplayStatics::GetPlayerController(GetWorld(), 0), SingleScoreUI)); Single->Order->SetText(FText::FromString(FString::Printf(TEXT("%02d"), Order++))); Single->Name->SetText(FText::FromString(Name)); Single->Score->SetText(FText::FromString(FString::FromInt(int(Score)))); ScoreArea->AddChild(Single); } void UGameUserWidget::NativeConstruct() { Super::NativeConstruct(); MyCharacter = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0); FireComponent = MyCharacter->FindComponentByClass<UFire>(); ShootButton->OnClicked.AddDynamic(this, &UGameUserWidget::Fire); JumpButton->OnClicked.AddDynamic(this, &UGameUserWidget::Jump); ScoreBoard->SetRenderOpacity(0); } void UGameUserWidget::NativeTick(const FGeometry& MyGeometry, float InDeltaTime) { Super::NativeTick(MyGeometry, InDeltaTime); ScoreText->SetText(FText::FromString(FString::Printf(TEXT("Your Score: %d\n"), int(MyCharacter->GetPlayerState()->GetScore())))); } void UGameUserWidget::Fire() { FireComponent->Fire(); } void UGameUserWidget::Jump() { MyCharacter->Jump(); } UGameUserWidget::UGameUserWidget(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { }
#ifndef _vector_h #define _vector_h #include "color.hpp" #include <iostream> #include <math.h> using namespace std; class Vector { public: double x,y,z; Vector() : x(0.0),y(0.0),z(0.0) {} Vector(double x, double y, double z) { this->x = x; this->y = y; this->z = z; } Vector operator+ (const Vector& vec2) { Vector vec1(0.0,0.0,0.0); vec1.x = this->x + vec2.x; vec1.y = this->y + vec2.y; vec1.z = this->z + vec2.z; return vec1; } Vector operator- (const Vector& vec2) { Vector vec1(0.0,0.0,0.0); vec1.x = this->x - vec2.x; vec1.y = this->y - vec2.y; vec1.z = this->z - vec2.z; return vec1; } Vector& operator= (const Vector& vec) { this->x = vec.x; this->y = vec.y; this->z = vec.z; return *this; } bool operator!= (const Vector& vec) { if (this->x == vec.x && this->y == vec.y && this->z == vec.z) { return true; } return false; } Vector operator/ (const double& k) { Vector v1(0.0,0.0,0.0); v1.x = this->x/k; v1.y = this->y/k; v1.z = this->z/k; return v1; } Vector operator* (const double& k) { Vector v1(0.0,0.0,0.0); v1.x = this->x * k; v1.y = this->y * k; v1.z = this->z * k; return v1; } Vector& operator *= (const double& k) { this->x *= k; this->y *= k; this->z *= k; return *this; } // Vector operator * (const double& k, const Vector& vec1) // { // return Vector( // k * vec1.x, // k * vec1.y, // k * vec1.z); // } Vector& operator /= (const double& k) { this->x /= k; this->y /= k; this->z /= k; return *this; } Vector& operator += (const Vector& vec) { this->x += vec.x; this->y += vec.y; this->z += vec.z; return *this; } Vector& operator -= (const Vector& vec) { this->x -= vec.x; this->y -= vec.y; this->z -= vec.z; return *this; } double DotProduct (const Vector& vec1, const Vector& vec2) { return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z); } Vector CrossProduct (const Vector& vec1, const Vector& vec2) { return Vector( (vec1.y * vec2.z) - (vec1.z * vec2.y), (vec1.z * vec2.x) - (vec1.x * vec2.z), (vec1.x * vec2.y) - (vec1.y * vec2.x) ); } const double mag_square() { return ((x*x) + (y*y) + (z*z)); } const double mag() { return sqrt(mag_square()); } const Vector unit_vector() { const double m = mag(); return Vector(x/m, y/m, z/m); } void display_vector() { cout << "[" << x << "," << y << "," << z << "]" << endl; } }; /* Ray struct */ struct Ray { Vector pos; Vector dir; Color col; }; #endif
#include "read_input_file.h" #include <fstream> #include <iostream> #include <sstream> using std::string; using std::vector; void read_input_file(const string s, double **lm, double **wp, size_t& N_lm, size_t& N_wp) { int scale = 1; read_input_file_and_scale(s, scale, lm, wp, N_lm, N_wp); } /***************************************************************************** * Should have highest priority to be translated to C. Just make * the matrices a 2D array with fixed size for now. * **************************************************************************/ void read_input_file_and_scale(const string s, const int scale, double **lm, double **wp, size_t& N_lm, size_t& N_wp) { using std::ifstream; using std::istringstream; if(access(s.c_str(),R_OK) == -1) { std::cerr << "Unable to read input file" << s << std::endl; exit(EXIT_FAILURE); } ifstream in(s.c_str()); int lineno = 0; int lm_rows = 0; int lm_cols = 0; int wp_rows = 0; int wp_cols = 0; while(in) { lineno++; string str; getline(in,str); std::istringstream line(str); vector<string> tokens; std::copy(std::istream_iterator<string>(line), std::istream_iterator<string>(), std::back_inserter<vector<string> > (tokens)); if(tokens.size() ==0) { continue; } else if (tokens[0][0] =='#') { continue; } else if (tokens[0] == "lm") { if(tokens.size() != 3) { std::cerr<<"Wrong args for lm!"<<std::endl; std::cerr<<"Error occuredon line"<<lineno<<std::endl; std::cerr<<"line:"<<str<<std::endl; exit(EXIT_FAILURE); } lm_rows = strtof(tokens[1].c_str(),NULL); lm_cols = strtof(tokens[2].c_str(),NULL); N_lm = lm_rows*scale; (*lm) = (double*)malloc(lm_rows*lm_cols*scale*sizeof(double)); for (int r = 0; r<lm_rows; r++) { lineno++; if (!in) { std::cerr<<"EOF after reading" << std::endl; exit(EXIT_FAILURE); } getline(in,str); std::istringstream line(str); vector<string> tokens; std::copy(std::istream_iterator<string>(line), std::istream_iterator<string>(), std::back_inserter<vector<string> > (tokens)); if(tokens.size() < lm_cols) { std::cerr<<"invalid line for lm coordinate!"<<std::endl; std::cerr<<"Error occured on line "<<lineno<<std::endl; std::cerr<<"line: "<<str<<std::endl; exit(EXIT_FAILURE); } for (unsigned c=0; c < lm_cols; c++) { for (int i=0; i<scale; i++){ (*lm)[r*lm_cols*scale + c + i*lm_cols] = strtof(tokens[c].c_str(),NULL); } } } } else if (tokens[0] == "wp") { if(tokens.size() != 3) { std::cerr<<"Wrong args for wp!"<<std::endl; std::cerr<<"Error occured on line"<<lineno<<std::endl; std::cerr<<"line:"<<str<<std::endl; exit(EXIT_FAILURE); } wp_rows = strtof(tokens[1].c_str(),NULL); wp_cols = strtof(tokens[2].c_str(),NULL); N_wp = wp_rows; (*wp) = (double*)malloc(wp_rows*wp_cols*sizeof(double)); for (int r =0; r<wp_rows; r++) { lineno++; if (!in) { std::cerr<<"EOF after reading" << std::endl; exit(EXIT_FAILURE); } getline(in,str); std::istringstream line(str); std::vector<string> tokens; std::copy(std::istream_iterator<string>(line), std::istream_iterator<string>(), std::back_inserter<std::vector<string> > (tokens)); if(tokens.size() < wp_cols) { std::cerr<<"invalid line for wp coordinate!"<<std::endl; std::cerr<<"Error occured on line "<<lineno<<std::endl; std::cerr<<"line: "<<str<<std::endl; exit(EXIT_FAILURE); } for (int c=0; c < wp_cols; c++) { (*wp)[r*wp_cols + c] = strtof(tokens[c].c_str(),NULL); //Wrong, waypoints shouldnt scale! } } } else { std::cerr << "Unkwown command" << tokens[0] << std::endl; std::cerr << "Error occured on line" << lineno << std::endl; std::cerr << "line: " << str << std::endl; exit(EXIT_FAILURE); } } } void read_sequential_input_file(const std::string s, double **lm, size_t& N_lm, size_t& N_features) { using std::ifstream; using std::istringstream; if(access(s.c_str(),R_OK) == -1) { std::cerr << "Unable to read input file" << s << std::endl; exit(EXIT_FAILURE); } ifstream in(s.c_str()); int lineno = 0; int lm_rows = 0; int lm_cols = 0; int wp_rows = 0; int wp_cols = 0; while(in) { lineno++; string str; getline(in,str); std::istringstream line(str); vector<string> tokens; std::copy(std::istream_iterator<string>(line), std::istream_iterator<string>(), std::back_inserter<vector<string> > (tokens)); if(tokens.size() ==0) { continue; } else if (tokens[0][0] =='#') { continue; } if(tokens.size() != 3) { std::cerr<<"Wrong args for lm!"<<std::endl; std::cerr<<"Error occuredon line"<<lineno<<std::endl; std::cerr<<"line:"<<str<<std::endl; exit(EXIT_FAILURE); } else if (tokens[0] == "lm") { if(tokens.size() != 3) { std::cerr<<"Wrong args for lm!"<<std::endl; std::cerr<<"Error occuredon line"<<lineno<<std::endl; std::cerr<<"line:"<<str<<std::endl; exit(EXIT_FAILURE); } N_features=0; lm_rows = strtof(tokens[1].c_str(),NULL); lm_cols = strtof(tokens[2].c_str(),NULL); N_lm = lm_rows; (*lm) = (double*)malloc(lm_rows*lm_cols*sizeof(double)); for (int r = 0; r<lm_rows; r++) { lineno++; if (!in) { std::cerr<<"EOF after reading" << std::endl; exit(EXIT_FAILURE); } getline(in,str); std::istringstream line(str); vector<string> tokens; std::copy(std::istream_iterator<string>(line), std::istream_iterator<string>(), std::back_inserter<vector<string> > (tokens)); if(tokens.size() < lm_cols) { std::cerr<<"invalid line for lm coordinate!"<<std::endl; std::cerr<<"Error occured on line "<<lineno<<std::endl; std::cerr<<"line: "<<str<<std::endl; exit(EXIT_FAILURE); } for (unsigned c=0; c < lm_cols; c++) { if (c == 1) { int f_index = strtof(tokens[c].c_str(), NULL); if (f_index > -1) { if (f_index > N_features) { N_features = f_index; } } } (*lm)[r*lm_cols + c] = strtof(tokens[c].c_str(),NULL); } } } else { std::cerr << "Unkwown command" << tokens[0] << std::endl; std::cerr << "Error occured on line" << lineno << std::endl; std::cerr << "line: " << str << std::endl; exit(EXIT_FAILURE); } } }
#include "systemc.h" #include "tester.h" #include <iostream> #include <fstream> void Tester::testing() { bool t_enable, t_reset; bool t_data; while(1) { if (infile >> t_enable >> t_reset >> t_data) { wait(); out.write(t_data); enable_reg.write(t_enable); reset_reg.write(t_reset); } else { break; } } sc_stop(); }
// Find the largest palindromic number made from the product of two 3 digit numbers #include<cstdlib> #include<string> #include<iostream> #include<sstream> using namespace std; int main() { unsigned int max = 0; for(unsigned int i = 999; i != 99; --i) for(unsigned int j = 999; j != 99; --j) { int prod = i*j; stringstream ss; ss << prod; string string = ss.str(); int len = string.length(); bool check = true; for(unsigned int k = 0; k < len/2.0; ++k) if(string[k] != string[(len-k)-1]) { check = false; break; } if(max <= prod && check) max = prod; } cout << max << endl; return 0; }
#include "Notebook.h" std::string Notebook::inputString() { std::string temp_string; std::getline(std::cin, temp_string); return temp_string; } //---------яеррепш---------- void Notebook::setNoteName(std::string note_name) { m_note_name = note_name; } void Notebook::setNoteContent(std::string note_content) { m_note_content = note_content; } void Notebook::setStatus(bool status) { m_status = status; } void Notebook::setPriority(int priority) { m_priority = priority; } //---------церрепш---------- std::string Notebook::getNoteName() { return m_note_name; } std::string Notebook::getNoteContent() { return m_note_content; } bool Notebook::getStatus() { return m_status; } int Notebook::getPriority() { return m_priority; }
#ifndef BOMBA_H #define BOMBA_H #include "Enemigo.h" class Bomba : public Enemigo { public: bool explotar; Bomba(int x, int y,SDL_Surface* img); virtual ~Bomba(); void mover(vector<Tile*> tiles, int xMapa, int yMapa); void mostrar(SDL_Surface* screen, int xMapa, int yMapa); protected: private: SDL_Rect clips[11]; }; #endif // BOMBA_H
/* BEGIN LICENSE */ /***************************************************************************** * SKCore : the SK core library * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: unicodesimplifier.h,v 1.6.2.2 2005/02/17 15:29:24 krys Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #ifndef __SKC_UNICODESIMPLIFIER_H_ #define __SKC_UNICODESIMPLIFIER_H_ class skStringUnicodeSimplifier : public skIStringSimplifier { public: static SKERR CreateUnicodeSimplifier(const char* pszParam, SKRefCount** ppInstance); SK_REFCOUNT_INTF(skStringUnicodeSimplifier); SK_REFCOUNT_INTF_CREATOR(skStringUnicodeSimplifier)(const char* pszParam); skStringUnicodeSimplifier(const char* pszParam); virtual ~skStringUnicodeSimplifier(); virtual SKERR SimplifyFirstChar( const char* pcIn, PRUint32 *piRead, char* pcOut, PRUint32* piWritten); virtual SKERR CompareFirstChar( const char* pc1, PRUint32* plLen1, const char* pc2, PRUint32* plLen2, PRInt32* iCmp = NULL); virtual void ComputeIdentity(); private: PRUint32 SimpCharUniCase(PRUint32 iChar); PRUint32 SimpCharUniComp(PRUint32 iChar); PRUint32 SimpCharUniSpace(PRUint32 iChar); protected: // static PRInt32 CompareChar(PRUint32 iFlags, PRUint32 c1, PRUint32 c2); char* m_pszParam; PRBool m_bSimpUniCase; PRBool m_bSimpUniComp; PRBool m_bSimpUniSpaces; PRBool m_bFrSloppyUppercaseMatch; typedef struct Mapping { PRUint32 lChar; char* pcString; } Mapping; PRUint32 m_iMapSize; PRUint32 m_iMapCount; Mapping* m_pMap; }; #endif // __SKC_UNICODESIMPLIFIER_H_
#pragma once #include <string> using namespace std; class Coords { friend bool operator==(const Coords &c1, const Coords &c2); friend bool operator!=(const Coords &c1, const Coords &c2); friend ostream &operator<<(ostream &os, const Coords coords); private: int id; int x; int y; public: Coords(); Coords(int x, int y, int id); int GetId(); void SetX(int x); int GetX() const; void SetY(int y); int GetY() const; };
#include "Core_PCH.h" namespace ServerEngine { void NetModule::StartModule() { printf_s("NetModule::StartModule\n"); } void NetModule::ShutdownModule() { printf_s("NetModule::ShutdownModule\n"); } }
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <map> #include <vector> #include <algorithm> #include <math.h> #define pb push_back using namespace std; int moneys[] = {1, 5, 10, 20, 50}; int q[5]; int n; void input() { scanf("%d", &n); } void solve() { // solution 1 /*do { if (n >= moneys[4]) { q[4] = n/moneys[4]; n = n%moneys[4]; } else if (n >= moneys[3]) { q[3] = n/moneys[3]; n = n%moneys[3]; } else if (n >= moneys[2]) { q[2] = n/moneys[2]; n = n%moneys[2]; } else if (n >= moneys[1]){ q[1] = n/moneys[1]; n = n%moneys[1]; } else { q[0] = n/moneys[0]; n = n%moneys[0]; } } while (n != 0);*/ // better solution int x = n; for (int i = 4; i >= 0; i--) { if (x >= 0) { q[i] = x/moneys[i]; x = x%moneys[i]; } } } void output() { for (int i = 0; i < 5; i++) { printf("(%d) %d ", moneys[i], q[i]); } printf("\n"); } int main() { int ntest; freopen("tieuhoc3.inp", "r", stdin); scanf("%d", &ntest); for (int itest = 0; itest < ntest; itest++) { input(); solve(); output(); } return 0; }
#include <string> #include "Rectangle.h" #include "Vector2d.h" #include "glfw3.h" #include "Control.h" #if DEBUG == 1 #include <iostream> #include "DebugLine.h" #endif namespace Engine2d { Rectangle::Rectangle(const float x, const float y, const float width, const float height, const float theta, const bool isStatic, const float mass, const float restitution, std::string name) { this->position.x = x; this->position.y = y; this->radius = std::sqrt(width*width + height*height) / 2; this->centerAngle_1 = 2 * std::acos(height / (2*radius)); this->centerAngle_2 = M_PI - this->centerAngle_1; this->theta = theta; this->dx.x = 0; this->dx.y = 0; this->updatePosition(); this->isStatic = isStatic; this->mass = mass; this->invMass = 1/mass; this->restitution = (restitution < 2.5 ? 2.5 : restitution); // Min limit of 2.5 to prevent weird stuff this->name = name; this->collision = false; } void Rectangle::operator=(Rectangle other) { this->name = other.name; for (int i = 0; i < 4; ++i) this->P[i] = other.P[i]; this->position = other.position; this->dx = other.dx; this->theta = other.theta; this->dtheta = other.dtheta; this->collision = other.collision; this->width = other.width; this->height = other.height; this->centerAngle_1 = other.centerAngle_1; this->centerAngle_2 = other.centerAngle_2; this->mass = other.mass; this->invMass = other.invMass; this->restitution = other.restitution; this->radius = other.radius; this->isStatic = other.isStatic; } void Rectangle::applyImpulse(Vector2d impulse) { this->dx += impulse/this->mass; } void Rectangle::updatePosition() { this->position = this->position + this->dx; this->P[0].x = position.x + radius * std::cos(theta + centerAngle_1 + centerAngle_2 * 3 / 2); this->P[0].y = position.y + radius * std::sin(theta + centerAngle_1 + centerAngle_2 * 3 / 2); this->P[1].x = position.x + radius * std::cos(theta + 2 * centerAngle_1 + centerAngle_2 * 3 / 2); this->P[1].y = position.y + radius * std::sin(theta + 2 * centerAngle_1 + centerAngle_2 * 3 / 2); this->P[2].x = position.x + radius * std::cos(theta + centerAngle_2 / 2); this->P[2].y = position.y + radius * std::sin(theta + centerAngle_2 / 2); this->P[3].x = position.x + radius * std::cos(theta + centerAngle_1 + centerAngle_2 / 2); this->P[3].y = position.y + radius * std::sin(theta + centerAngle_1 + centerAngle_2 / 2); } void Rectangle::update() { updatePosition(); } void Rectangle::draw() const { GLfloat lineVertices[] = { P[0].x, P[0].y, P[1].x, P[1].y, P[1].x, P[1].y, P[2].x, P[2].y, P[2].x, P[2].y, P[3].x, P[3].y, P[3].x, P[3].y, P[0].x, P[0].y }; glColor3f(1.0f, 1.0f, 1.0f); if (this->collision) glColor3f(0.0f, 0.0f, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, lineVertices); glDrawArrays(GL_LINES, 0, 8); glDisableClientState(GL_VERTEX_ARRAY); } }
#ifndef _TRANSFORM_HPP_ #define _TRANSFORM_HPP_ #pragma once #include "Vector3.hpp" class Transform { public: Vector3 position; Vector3 rotation; Vector3 scale; Transform(Vector3 position = Vector3(0, 0, 0), Vector3 rotation = Vector3(0, 0, 0), Vector3 scale = Vector3(1, 1, 1)); }; #endif
/////////////////////////////////////////////////////////////////////////////// // // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is MP4v2. // // The Initial Developer of the Original Code is Kona Blend. // Portions created by Kona Blend are Copyright (C) 2008. // Portions created by David Byron are Copyright (C) 2010. // All Rights Reserved. // // Contributors: // Kona Blend, kona8lend@@gmail.com // David Byron, dbyron@dbyron.com // /////////////////////////////////////////////////////////////////////////////// #include "util/impl.h" namespace mp4v2 { namespace util { /////////////////////////////////////////////////////////////////////////////// class FileUtility : public Utility { private: enum FileLongCode { LC_LIST = _LC_MAX, LC_OPTIMIZE, LC_DUMP, }; public: FileUtility( int, char** ); protected: // delegates implementation bool utility_option( int, bool& ); bool utility_job( JobContext& ); private: bool actionList ( JobContext& ); bool actionOptimize ( JobContext& ); bool actionDump ( JobContext& ); private: Group _actionGroup; bool (FileUtility::*_action)( JobContext& ); }; /////////////////////////////////////////////////////////////////////////////// FileUtility::FileUtility( int argc, char** argv ) : Utility ( "mp4file", argc, argv ) , _actionGroup ( "ACTIONS" ) , _action ( NULL ) { // add standard options which make sense for this utility _group.add( STD_DRYRUN ); _group.add( STD_KEEPGOING ); _group.add( STD_QUIET ); _group.add( STD_DEBUG ); _group.add( STD_VERBOSE ); _group.add( STD_HELP ); _group.add( STD_VERSION ); _group.add( STD_VERSIONX ); _actionGroup.add( "list", false, LC_LIST, "list (summary information)" ); _actionGroup.add( "optimize", false, LC_OPTIMIZE, "optimize mp4 structure" ); _actionGroup.add( "dump", false, LC_DUMP, "dump mp4 structure in human-readable format" ); _groups.push_back( &_actionGroup ); _usage = "[OPTION]... ACTION file..."; _description = // 79-cols, inclusive, max desired width // |----------------------------------------------------------------------------| "\nFor each mp4 file specified, perform the specified ACTION. An action must be" "\nspecified. Some options are not applicable to some actions."; } /////////////////////////////////////////////////////////////////////////////// bool FileUtility::actionDump( JobContext& job ) { job.fileHandle = MP4Read( job.file.c_str() ); if( job.fileHandle == MP4_INVALID_FILE_HANDLE ) return herrf( "unable to open for read: %s\n", job.file.c_str() ); if( !MP4Dump( job.fileHandle, _debugImplicits )) return herrf( "dump failed: %s\n", job.file.c_str() ); return SUCCESS; } /////////////////////////////////////////////////////////////////////////////// bool FileUtility::actionList( JobContext& job ) { ostringstream report; const int wbrand = 5; const int wcompat = 18; const int wsizing = 6; const string sep = " "; if( _jobCount == 0 ) { report << setw(wbrand) << left << "BRAND" << sep << setw(wcompat) << left << "COMPAT" << sep << setw(wsizing) << left << "SIZING" << sep << setw(0) << "FILE" << '\n'; report << setfill('-') << setw(70) << "" << setfill(' ') << '\n'; } job.fileHandle = MP4Read( job.file.c_str() ); if( job.fileHandle == MP4_INVALID_FILE_HANDLE ) return herrf( "unable to open for read: %s\n", job.file.c_str() ); FileSummaryInfo info; if( fileFetchSummaryInfo( job.fileHandle, info )) return herrf( "unable to fetch file summary info" ); string compat; { const FileSummaryInfo::BrandSet::iterator ie = info.compatible_brands.end(); int count = 0; for( FileSummaryInfo::BrandSet::iterator it = info.compatible_brands.begin(); it != ie; it++, count++ ) { if( count > 0 ) compat += ','; compat += *it; } } const bool sizing = info.nlargesize | info.nversion1 | info.nspecial; report << setw(wbrand) << left << info.major_brand << sep << setw(wcompat) << left << compat << sep << setw(wsizing) << left << (sizing ? "64-bit" : "32-bit") << sep << job.file << '\n'; verbose1f( "%s", report.str().c_str() ); return SUCCESS; } /////////////////////////////////////////////////////////////////////////////// bool FileUtility::actionOptimize( JobContext& job ) { verbose1f( "optimizing %s\n", job.file.c_str() ); if( dryrunAbort() ) return SUCCESS; if( !MP4Optimize( job.file.c_str(), NULL )) return herrf( "optimize failed: %s\n", job.file.c_str() ); return SUCCESS; } /////////////////////////////////////////////////////////////////////////////// bool FileUtility::utility_job( JobContext& job ) { if( !_action ) return herrf( "no action specified\n" ); return (this->*_action)( job ); } /////////////////////////////////////////////////////////////////////////////// bool FileUtility::utility_option( int code, bool& handled ) { handled = true; switch( code ) { case LC_LIST: _action = &FileUtility::actionList; break; case LC_OPTIMIZE: _action = &FileUtility::actionOptimize; break; case LC_DUMP: _action = &FileUtility::actionDump; break; default: handled = false; break; } return SUCCESS; } /////////////////////////////////////////////////////////////////////////////// }} // namespace mp4v2::util ///////////////////////////////////////////////////////////////////////////////
#include <iostream> #include <map> #include <utility> #include <vector> #include <string> #include <tuple> int main() { int numberofcar; std::string madeCar = ""; std::string modelCar = ""; int nameEnterCode = 0; std::string careMadeSort = ""; int yearCar = 0; std::cin >> numberofcar; std::map<std::string, std::pair<std::string, int>> car; for ( int i = 0; i < numberofcar; ++i ) { std::cin >> madeCar; std::cin >> modelCar; std::cin >> yearCar; car.insert(std::make_pair(madeCar, std::make_pair(modelCar, yearCar))); } std::cin >> nameEnterCode; if (nameEnterCode == 1) { std::cin>>careMadeSort; for ( auto &b : car ) { if (b.first == careMadeSort) { std::cout << b.first << " " << b.second.first << " " << b.second.second << std::endl; } } } if (nameEnterCode == 2) { for ( auto &b : car ) { std::cout << b.first << " " << b.second.first << " " << b.second.second << std::endl; } } return 0; }
#pragma once #include "ofMain.h" #include "ofxSpriteSheetRenderer.h" static animation_t walkAnimation = { 0, //.index 0, //.frame 2, //.totalframes 1, //.width 1, //.height 90, //.frameduration 0, //.nexttick -1, //.loops -1, //.finalindex 1 //.frameskip }; struct basicSprite { animation_t animation; int tileName; //used for static sprites? ofPoint pos; float speed; }; class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofxSpriteSheetRenderer* spriteRenderer; basicSprite * link; vector<basicSprite *> backgrounds; ofPoint playerpos; ofPoint cameraCenter; const float SCALE = 3; const int GRIDW = 30; const int GRIDH = 30; bool rightPressed; bool leftPressed; bool upPressed; bool downPressed; void spaceFree(int dir); int getTileName(int x, int y); };
#ifndef __MAXHEAP_H__ #define __MAXHEAP_H__ #include "Node.h" using namespace std; class maxHeap { public: maxHeap(); ~maxHeap(); void Insert(string name, float distance, int count_view); void LevelOrder(); void heapify(Node *arr, int size, int i); void buildHeap(); void SearchMostReviewedRestaurant(); void RemoveMostReviewedRestaurant(); //@tag: Help method int GetSize(); bool isEmpty(); bool findName(string name, float distance, int count_review); void swap(Node *arr, int i, int j); int GetHeight(Node *temp, int index); private: int size = 0; Node *maxHeapArr; const int MAXSIZE = 20; int index = -1; void buildHeap(Node *arr, int size); }; #endif // __MAXHEAP_H__
\ // LED Array Testing Code // Light Integrated Threads // // #include <FFT.h> #include <SPI.h> #include <LPD8806.h> //#include <LEDArray.h> #include <Grid.h> Grid myGrid(18,18); int* spectrum; //int color[3]; //FFT fft(fftAnalogPin,fftStrobePin,fftResetPin); void setup() { Serial.begin(9600); myGrid.strip->begin(); myGrid.update(); } void loop() { myGrid.allOff(); delay(30); int* spectrum = myGrid.freqChip->sample(); int first = ((spectrum[0]) + (spectrum[1]))/2; int second = ((spectrum[2]) + (spectrum[3]) + (spectrum[3]))/3; int third = ((spectrum[4]) + (spectrum[5]) + (spectrum[6]))/3; first = first/150; second = second/30; third = third/20; //divide up grid into three regions if(myGrid.freqChip->detectBeat(spectrum, 1, 40)) { for(int r = 0; r < 100; r++) { myGrid.drawPixel(rand()%18,rand()%18,magenta); } } else { for(int r = 18; r > 18 - first; r--) { myGrid.drawXLine(r, 1, 18, blue); } } if(myGrid.freqChip->detectBeat(spectrum, 3, 40)) { for(int r = 0; r < 100; r++) { myGrid.drawPixel(rand()%18,rand()%18,yellow); } } else { for(int r = 1; r < second; r++) { myGrid.drawXLine(r, 1, 9, green); } } if(myGrid.freqChip->detectBeat(spectrum, 5, 40)) { for(int r = 0; r < 100; r++) { myGrid.drawPixel(rand()%18,rand()%18,white); } } else { for(int r = 1; r < third; r++) { myGrid.drawXLine(r, 10, 18, red); } } myGrid.update(); }
/* * SDEV 340 Week 8 Problem 1 * An abstract class for comparing sorting algortihms, with a simple sort subclass * Benjamin Lovy */ #include <algorithm> #include <iostream> class AbstractSort { // For tracking how many comparisons are performed int numCompares = 0; protected: // Compare two elements, incrementing counter. True if is 'one' is higher, else false bool compare(int one, int two); public: // Retrieve total compares performed int getCompares() const; // Virtual sort() prototype virtual void sort(int arr[], int size) = 0; }; // Compare two elements, incrementing counter. True if is 'one' is higher, else false bool AbstractSort::compare(int one, int two) { numCompares++; return one > two; } // Retrieve total compares performed int AbstractSort::getCompares() const { return numCompares; } class SimpleSort : public AbstractSort { public: virtual void sort(int arr[], int size) { // Marker to track completion bool finished = true; // Iterate through collection, swapping until we're done do { // Assume complete finished = true; for (int i = 0; i < size - 1; i++) { // Compare i to i+1 if (compare(arr[i], arr[i + 1])) { // unset marker finished = false; // swap them std::swap(arr[i], arr[i + 1]); } } } while (!finished); } }; // Output an array template <typename T> void showArr(T arr[], int size) { using std::cout; cout << "["; for (int i = 0; i < size; i++) { cout << arr[i]; if (i < size - 1) { cout << ", "; } } cout << "]"; } int main() { using std::cout; // Init collection const int numsLen = 6; int nums[numsLen] = {3, 6, 5, 2, 1, 4}; cout << "Numbers: "; showArr(nums, numsLen); cout << "\n"; // Init simple sort object SimpleSort ss; // Sort collection ss.sort(nums, numsLen); // Display result cout << "Sorted: "; showArr(nums, numsLen); cout << "\nTotal compares: " << ss.getCompares(); // Exit success return 0; }
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { long n; cin>>n; double mp=0.0; vector<double> a(n); for(int i=0;i<n;i++) { cin>>a[i]; if(mp<a[i]) { mp=a[i]; } } double d,s; long c; cin>>c>>d>>s; double ans=(double)((c-1)*mp); cout<<setprecision(20); cout<<ans<<"\n"; } return 0; }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) typedef long long ll; int main() { ll n, k; cin >> n >> k; vector<int> a; rep(i, n){ int tmp; cin >> tmp; a.push_back(tmp);} for (int i = (k - 1) % n; i < n; i++) { /* code */ } }
#include <QFile> #include <QApplication> #include <QQmlApplicationEngine> #include <QDebug> #include "opener.h" #include "prefmodel.h" #ifdef Q_OS_ANDROID #include <contentdevice.h> #include <sharedpreferences.h> #endif int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication app(argc, argv); qmlRegisterType<Opener>("de.skycoder42.androidutils.demo", 1, 0, "Opener"); qmlRegisterType<PrefModel>("de.skycoder42.androidutils.demo", 1, 0, "PrefModel"); QQmlApplicationEngine engine; engine.load(QUrl(QLatin1String("qrc:/main.qml"))); return app.exec(); }
#include <Wire.h> #include <stdlib.h> #include <Servo.h> #include <IRremote.h> #define ACTIVATED HIGH unsigned long elapsed_time; float sample_time; unsigned long last_time_print; /*--- Propeller Servos -------------------------------------------------------*/ Servo right_prop; Servo left_prop; double throttle = 1100; int button_state = 0; int previous_time_pressed; bool start_motors = false; //--- Simple Moving Average Globals ------------------------------------------*/ const int samples = 5; int a_x_readings[samples]; int a_y_readings[samples]; int a_z_readings[samples]; long int a_read_index = 0; long int a_read_total[3] = {0, 0, 0}; long int a_read_ave[3] = {0, 0, 0}; /*--- Time Control -----------------------------------------------------------*/ int refresh_rate = 250; float dt = 1 / refresh_rate; const float loop_micros = (dt) * 1000000; /*--- IMU Globals ------------------------------------------------------------*/ float rad_to_degrees = 57.29577951f; float degrees_to_rad = 0.017453293f; double lsb_coefficient = (1.0f / 32.8f); float roll, pitch, yaw; float initial_roll, initial_pitch, initial_yaw; long g_cal[3]; float qi_0, qi_1, qi_2, qi_3; float q_0 = 1.0f; float q_1 = 0.0f; float q_2 = 0.0f; float q_3 = 0.0f; float correction_gain = 0.2f; /*--- PID Globals ------------------------------------------------------------*/ float pid, pwm_right, pwm_left, error, previous_error, previous_roll; float pid_p = 0, pid_i = 0, pid_d = 0; float k_p = 3.78f; //3.5 float k_i = 0.05f; // float k_d = 1.03f; //0.85 // float k_p = 1.4; // float k_i = 1.82; // float k_d = 1.04; float desired_angle = 0.0; /*--- REMOTE CONTROL ---------------------------------------------------------*/ IRrecv irrecv(12); // IR reciver digital input to pin 12. decode_results results; byte last_channel_1, last_channel_2, last_channel_3, last_channel_4; int receiver_input_channel_1, receiver_input_channel_2, receiver_input_channel_3, receiver_input_channel_4; unsigned long timer_1, timer_2, timer_3, timer_4; /*--- DEBUGGING --------------------------------------------------------------*/ void debugging(){ int mode = 1; if (elapsed_time - last_time_print > 20000){ if(mode == 1){ Serial.print("Roll: "); Serial.print(roll); Serial.print(" - Pitch: "); Serial.print(pitch); Serial.print(" - pwm left: "); Serial.print(pwm_left); Serial.print(" - pwm right: "); Serial.print(pwm_right); Serial.print(" - PID: "); Serial.print(pid); Serial.print(" - Run Motors?: "); Serial.print(start_motors); Serial.print(" - k_p: "); Serial.print(k_p); Serial.print(" - k_i: "); Serial.print(k_i); Serial.print(" - k_d: "); Serial.print(k_d); Serial.print("\n"); } if(mode == 2){ // Serial.print(""); // Serial.print(); // Serial.print(" aPitch: "); // Serial.print(a_pitch); // Serial.print("gPitch: "); Serial.print(pitch); Serial.print(" "); // Serial.print(" - aRoll: "); // Serial.print(a_roll); // Serial.print(" - gRoll: "); Serial.print(roll); // Serial.print(" "); // Serial.print(90); // Serial.print(" "); // Serial.print(-90); Serial.print("\n"); } if(mode == 3){ // Serial.print(" gRoll: "); // Serial.print(roll); // Serial.print(" - gPitch: "); Serial.print(pitch); // Serial.print(" "); // Serial.print(90); // Serial.print(" "); // Serial.print(-90); // Serial.print(" - k_p: "); // Serial.print(k_p); // Serial.print(" - k_i: "); // Serial.print(k_i); // Serial.print(" - k_d: "); // Serial.print(k_d); Serial.print("\n"); } last_time_print = micros(); } } void debug_loopTime(){ if (elapsed_time - last_time_print > 100000){ Serial.print(micros() - elapsed_time); Serial.print("\n"); last_time_print = micros(); } } /*--- SETUP MPU --------------------------------------------------------------*/ void setup_mpu(){ // Activate the MPU-6050 // 0x68 = Registry address of mpu6050 // 0x6B = Send starting register // 0x00 = Tell the MPU not to be asleep Wire.beginTransmission(0x68); Wire.write(0x6B); Wire.write(0x00); Wire.endTransmission(); // Configure the accelerometer (+/-8g) // 0x68 = Registry address of mpu6050 // 0x1C = Registry address of accelerometer // 0x10 = Full scale range of accelerometer (data sheet) Wire.beginTransmission(0x68); Wire.write(0x1C); Wire.write(0x10); Wire.endTransmission(); // Configure the gyro (500dps full scale // 0x68 = Registry address of mpu6050 // 0x1B = Registry address of gyroscope // 0x08 = 500 degree / sec Range of the gyro in degree/sec (data sheet) // 0x10 = 1000 degree / sec range // 0x12 = 2000 degree / sec range Wire.beginTransmission(0x68); Wire.write(0x1B); Wire.write(0x10); Wire.endTransmission(); } /*--- READ MPU --------------------------------------------------------------*/ void read_mpu(int ** sensor_output_array){ int array_size = 10; *sensor_output_array = (int*) malloc(sizeof(int) * array_size); /* Access the accellerometer register and requst 14 bits. Assign each high and low bit to a variable. */ Wire.beginTransmission(0x68); Wire.write(0x3B); Wire.endTransmission(); Wire.requestFrom(0x68, 14); while(Wire.available() < 14){}; // Wait for all of the bits to be recieved: // Assign values to each element of the array: (*sensor_output_array)[0] = Wire.read()<<8|Wire.read(); // a_x (*sensor_output_array)[1] = Wire.read()<<8|Wire.read(); // a_y (*sensor_output_array)[2] = Wire.read()<<8|Wire.read(); // a_z (*sensor_output_array)[3] = Wire.read()<<8|Wire.read(); // temp (*sensor_output_array)[4] = Wire.read()<<8|Wire.read(); // g_x (*sensor_output_array)[5] = Wire.read()<<8|Wire.read(); // g_y (*sensor_output_array)[6] = Wire.read()<<8|Wire.read(); // g_z } /*--- DATA PROCESSING --------------------------------------------------------*/ void accel_data_processing(int * sensor_data[]){ //Simple moving average filter a_read_total[0] -= a_x_readings[a_read_index]; a_read_total[1] -= a_y_readings[a_read_index]; a_read_total[2] -= a_z_readings[a_read_index]; a_x_readings[a_read_index] = (*sensor_data)[0]; a_y_readings[a_read_index] = (*sensor_data)[1]; a_z_readings[a_read_index] = (*sensor_data)[2]; a_read_total[0] += a_x_readings[a_read_index]; a_read_total[1] += a_y_readings[a_read_index]; a_read_total[2] += a_z_readings[a_read_index]; a_read_index += 1; if (a_read_index >= samples){ a_read_index = 0; } a_read_ave[0] = a_read_total[0] / samples; a_read_ave[1] = a_read_total[1] / samples; a_read_ave[2] = a_read_total[2] / samples; } void gyro_data_processing(int * sensor_data[]){ (*sensor_data)[4] -= g_cal[0]; (*sensor_data)[5] -= g_cal[1]; (*sensor_data)[6] -= g_cal[2]; } /*--- CALCULATE ATTITUDE -----------------------------------------------------*/ float invSqrt( float number ){ union { float f; uint32_t i; } conv; float x2; const float threehalfs = 1.5F; x2 = number * 0.5F; conv.f = number; conv.i = 0x5f3759df - ( conv.i >> 1 ); conv.f = conv.f * ( threehalfs - ( x2 * conv.f * conv.f ) ); return conv.f; } void calculate_initial_attitude(int sensor_data[]){ float a_magnitude = sqrt(a_read_ave[0] * a_read_ave[0] + a_read_ave[1] * a_read_ave[1] + a_read_ave[2] * a_read_ave[2]); initial_roll += asin((float)a_read_ave[1] / a_magnitude) * rad_to_degrees; // X initial_pitch += asin((float)a_read_ave[0] / a_magnitude) * rad_to_degrees * (-1.0f); } void calculate_attitude(int sensor_data[]){ /*--- Madgwick Filter ------------------------------------------------------*/ float normalize; float a_x = sensor_data[0]; float a_y = sensor_data[1]; float a_z = sensor_data[2]; normalize = invSqrt(a_x*a_x + a_y*a_y + a_z*a_z); a_x *= normalize; a_y *= normalize; a_z *= normalize; float a_magnitude = sqrt(a_read_ave[0] * a_read_ave[0] + a_read_ave[1] * a_read_ave[1] + a_read_ave[2] * a_read_ave[2]); initial_roll += asin((float)a_read_ave[1] / a_magnitude) * rad_to_degrees; // X initial_pitch += asin((float)a_read_ave[0] / a_magnitude) * rad_to_degrees * (-1.0f); // 1.09 = fudge factor. g_x in radians / sec float g_x = sensor_data[4] * (lsb_coefficient) * (1.00) * degrees_to_rad; float g_y = sensor_data[5] * (lsb_coefficient) * (1.00) * degrees_to_rad; float g_z = sensor_data[6] * (lsb_coefficient) * (1.00) * degrees_to_rad; // Rotation matrix q_dot = 0.5 angular velocity rotation maxtrix * q // Source: Inertial Navigation Systems with Geodetic Applications, Christopher Jekeli, Eq. 1.76 - 4x4 Skew Matrix float qDot_0 = 0.5f*(-q_1*g_x - q_2*g_y - q_3*g_z); float qDot_1 = 0.5f*(q_0*g_x + q_2*g_z - q_3*g_y); float qDot_2 = 0.5f*(q_0*g_y + q_2*g_x - q_1*g_z); float qDot_3 = 0.5f*(q_0*g_z + q_1*g_y - q_2*g_x); // If accelerometer is working carry out gradient descent algorithm. if(!((a_x == 0.0f) && (a_y == 0.0f) && (a_z == 0.0f))) { float delF_0 = 4.0f*q_2*q_2*q_0 + 4.0f*q_0*q_1*q_1 + 2.0f*q_2*a_x - 2.0f*q_1*a_y; float delF_1 = 8.0f*q_1*q_1*q_1 + 4.0f*q_3*q_3*q_1 + 4.0f*q_0*q_0*q_1 - 4.0f*q_1 + 8.0f*q_2*q_2*q_1 - 2.0f*q_3*a_x - 2.0f*q_0*a_y + 4.0f*q_1*a_z; float delF_2 = 8.0f*q_2*q_2*q_2 - 4.0f*q_2 + 4.0f*q_2*q_3*q_3 + 4.0f*q_2*q_0*q_0 + 8.0f*q_2*q_1*q_1 + 2.0f*q_0*a_x - 2.0f*q_3*a_y + 4.0f*q_2*a_z; float delF_3 = 4.0f*q_2*q_2*q_3 + 4.0f*q_3*q_1*q_1 - 2.0f*q_1*a_x - 2.0f*q_2*a_y; normalize = invSqrt(delF_0*delF_0 + delF_1*delF_1 + delF_2*delF_2 + delF_3*delF_3); delF_0 *= normalize; delF_1 *= normalize; delF_2 *= normalize; delF_3 *= normalize; // Change correction_gain for more or less influence on gyro rates. qDot_0 -= correction_gain * delF_0; qDot_1 -= correction_gain * delF_1; qDot_2 -= correction_gain * delF_2; qDot_3 -= correction_gain * delF_3; } q_0 += qDot_0 * sample_time; q_1 += qDot_1 * sample_time; q_2 += qDot_2 * sample_time; q_3 += qDot_3 * sample_time; roll = atan2f(2*(q_0*q_1 + q_2*q_3), 1.0f - 2.0f*(q_1*q_1 + q_2*q_2)) * rad_to_degrees; pitch = asinf(2.0f * (q_0*q_2 - q_1*q_3)) * rad_to_degrees; //yaw = atan2f(2*(q_0*q_3 + q_1*q_2), 1.0f - 2.0f*(q_2*q_2 + q_3*q_3)) * rad_to_degrees; } /*--- CALIBRATE IMU ----------------------------------------------------------*/ void calibrate_imu(){ /* THE IMU MUST NOT BE MOVED DURING SETUP */ /*--- Simple Moving ave Setup ---*/ for (int i = 0; i < samples; i++){ a_x_readings[i] = 0; a_y_readings[i] = 0; a_z_readings[i] = 0; } /*--- Calibrate gyroscope data and initial attitude: ---*/ int cal_count = 750; Serial.print("\nCalibrating \n"); for (int i = 0; i < cal_count; i ++){ sample_time = (micros() - elapsed_time) / 1000000.0f; elapsed_time = micros(); // Print the loading bar blips n times if(i % 50 == 0) { Serial.print("-"); } // Collect data from MPU int * data_xyzt; read_mpu(&data_xyzt); g_cal[0] += data_xyzt[4]; g_cal[1] += data_xyzt[5]; g_cal[2] += data_xyzt[6]; accel_data_processing(&data_xyzt); calculate_initial_attitude(data_xyzt); free(data_xyzt); // Clear dynamic memory allocation delay(3); } // Find the average value of the data that was recorded above: g_cal[0] /= cal_count; g_cal[1] /= cal_count; g_cal[2] /= cal_count; initial_pitch /= cal_count; initial_roll /= cal_count; initial_yaw = 0; // // float c1, c2, c3, s1, s2, s3; // // c1 = cos(initial_yaw / 2); // c2 = cos(initial_pitch / 2); // c3 = cos(initial_roll / 2); // s1 = sin(initial_yaw / 2); // s2 = sin(initial_pitch / 2); // s3 = sin(initial_roll / 2); // q_0 = c1*c2*c3 - s1*s2*s3; // q_1 = s1*s2*c3 + c1*c2*s3; // q_2 = s1*c2*c3 + c1*s2*s3; // q_3 = c1*s2*c3 - s1*c2*s3; } /*--- FLIGHT CONTROLLER ------------------------------------------------------*/ void flight_controller(){ error = desired_angle - roll; // PROPORTIONAL COMPONENET pid_p = k_p * error; // INTEGRAL COMPONENT int k_i_thresh = 8; if (error < k_i_thresh && error > -k_i_thresh) { pid_i = pid_i * (k_i * error); } if (error > k_i_thresh && error < -k_i_thresh){ pid_i = 0; } /* DERIVATIVE COMPONENT*/ // Derivitive of the process variable (roll), NOT THE ERROR // Taking derivative of the error results in "Derivative Kick". // https://www.youtube.com/watch?v=KErYuh4VDtI pid_d = (-1.0f) * k_d * ((roll - previous_roll) / sample_time); // pid_d = k_d * ((error - previous_error) / sample_time); /* Sum the the components to find the total pid value. */ pid = pid_p + pid_i + pid_d; /* Clamp the maximum & minimum pid values*/ if (pid < -1000){ pid = -1000; } if (pid > 1000){ pid = 1000; } /* Calculate PWM width. */ pwm_right = throttle + pid; pwm_left = throttle - pid; /* clamp the PWM values. */ //----------Right---------// if (pwm_right < 1000){ pwm_right = 1000; } if (pwm_right > 2000){ pwm_right = 2000; } //----------Left---------// if (pwm_left < 1000){ pwm_left = 1000; } if (pwm_left > 2000){ pwm_left = 2000; } if (start_motors == true){ right_prop.writeMicroseconds(pwm_right); left_prop.writeMicroseconds(pwm_left); } else{ right_prop.writeMicroseconds(1000); left_prop.writeMicroseconds(1000); } previous_error = error; previous_roll = roll; } void motors_on_off(){ button_state = digitalRead(13); long int elapsed_time = millis(); if (button_state == ACTIVATED && start_motors == false && ((elapsed_time - previous_time_pressed) > 700)){ start_motors = true; previous_time_pressed = millis(); } else if(button_state == ACTIVATED && start_motors == true && ((elapsed_time - previous_time_pressed) > 700)){ start_motors = false; previous_time_pressed = millis(); } } void IR_remoteControl(){ /*--- Store IR reciever remote value ---*/ if(irrecv.decode(&results)){ if(results.value != 4294967295){ //Serial.println(results.value, HEX); /*--- Change PID gain values ---*/ switch(results.value){ case 1320906895: // Power Button: if (start_motors){ start_motors = false; } else{ start_motors = true; } break; case 1320929335: // Button 1 k_p += 0.05; break; case 1320880375: // Button 2 k_d += 0.05; break; case 1320913015: // Button 3 k_i += 0.02; break; case 1320939535: // Button 4 k_p -= 0.02; break; case 1320890575: // Button 5 k_d -= 0.02; break; case 1320923215: // Button 6 k_i -= 0.02; break; case 1320887005: // Up Button throttle += 50; break; case 1320925255: throttle -= 50; // Down Button break; default: break; } } irrecv.resume(); } } void change_setpoint(){ if (receiver_input_channel_1 != 0){ desired_angle = map(receiver_input_channel_1, 1000, 2000, 30, -30); } } void setup_interrupts(){ // put your setup code here, to run once: PCICR |= (1 << PCIE0); // Set OCIE0 to enable PCMSK0 to scan PCMSK0 |= (1 << PCINT0); // set digital input 8 to trigger an interrupt on state change. PCMSK0 |= (1 << PCINT1); // etc PCMSK0 |= (1 << PCINT2); PCMSK0 |= (1 << PCINT3); } /*--- SETUP ------------------------------------------------------------------*/ void setup() { pinMode(7, INPUT); setup_interrupts(); Serial.begin(2000000); Wire.begin(); irrecv.enableIRIn(); // Motors right_prop.attach(5); left_prop.attach(3); right_prop.writeMicroseconds(1000); left_prop.writeMicroseconds(1000); // Calibrate imu setup_mpu(); calibrate_imu(); } /*--- MAIN -------------------------------------------------------------------*/ void loop(){ sample_time = (micros() - elapsed_time) / 1000000.0f; elapsed_time = micros(); //IMU int * data_xyzt; change_setpoint(); read_mpu(&data_xyzt); accel_data_processing(&data_xyzt); gyro_data_processing(&data_xyzt); calculate_attitude(data_xyzt); free(data_xyzt); // Clear allocated memory for data array. // FLIGHT CONTROLLER roll = roll - 5; flight_controller(); // DEBUGGING debugging(); //CALIBRATION CONTROLS IR_remoteControl(); //debug_loopTime(); // REFRESH RATE while (micros() - elapsed_time < 5500); // if (micros() - elapsed_time > 5500){ //Freeze if the loop takes too long // while(true); // } } ISR(PCINT0_vect){ /*----- CHANNEL 1 -----*/ if(last_channel_1 == 0 && PINB & B00000001){ last_channel_1 = 1; timer_1 = micros(); } else if(last_channel_1 == 1 && !(PINB & B00000001)){ last_channel_1 = 0; receiver_input_channel_1 = micros() - timer_1; } }
#include <Servo.h> Servo sg; int blue = 3; int green = 5; int red = 6; int i=255; int pos = 0; int j; void setup() { Serial.begin(4800); sg.attach(9); sg.write(pos); } void loop() { for(j=0;j<60;j++){ analogWrite(blue,255); sg.write(j); delay(15); } analogWrite(blue,0); delay(500); for(j=60;j<120;j++){ analogWrite(green,255); sg.write(j); delay(15); } analogWrite(green,0); delay(500); for(j=120;j<180;j++){ analogWrite(red,255); sg.write(j); delay(15); } analogWrite(red,0); delay(500); for(j=180;j=0;j--){ analogWrite(red,250); analogWrite(green,250); sg.write(j); delay(15); } delay(500); }
//Muffin.h class Muffin { public: string getDescription() const; void setDescription(const string& inDescription); int getSize() const; void setSize(int inSize); bool getHasChocolateChips() const; void setHasChocolateChips(bool inChips); void output(); //Add a function for use of "printf". protected: string mDescription; int mSize; bool mHasChocolateChips; }; string Muffin::getDescription() const {return mDescription;} void Muffin::setDescription(const string& inDescription) { mDescription=inDescription; } int Muffin::getSize() const {return mSize;} void Muffin::setSize(int inSize) {mSize=inSize;} bool Muffin::getHasChocolateChips() const {return mHasChocolateChips;} void Muffin::setHasChocolateChips(bool inChocolateChips) {mHasChocolateChips=inChocolateChips;} void Muffin::output() { printf("%s,Size is %s\n",getDescription().c_str(),getSize(),(getHasChocolateChips()? "Has Chips":"No Chips")) }