Search Results

Search found 21054 results on 843 pages for 'void'.

Page 15/843 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Is It possible to use the second part of this code for repository patterns and generics

    - by newToCSharp
    Is there any issues in using version 2,to get the same results as version 1. Or is this just bad coding. Any Ideas public class Customer { public int CustomerID { get; set; } public string EmailAddress { get; set; } int Age { get; set; } } public interface ICustomer { void AddNewCustomer(Customer Customer); void AddNewCustomer(string EmailAddress, int Age); void RemoveCustomer(Customer Customer); } public class BALCustomer { private readonly ICustomer dalCustomer; public BALCustomer(ICustomer dalCustomer) { this.dalCustomer = dalCustomer; } public void Add_A_New_Customer(Customer Customer) { dalCustomer.AddNewCustomer(Customer); } public void Remove_A_Existing_Customer(Customer Customer) { dalCustomer.RemoveCustomer(Customer); } } public class CustomerDataAccess : ICustomer { public void AddNewCustomer(Customer Customer) { // MAKE DB CONNECTION AND EXECUTE throw new NotImplementedException(); } public void AddNewCustomer(string EmailAddress, int Age) { // MAKE DB CONNECTION AND EXECUTE throw new NotImplementedException(); } public void RemoveCustomer(Customer Customer) { // MAKE DB CONNECTION AND EXECUTE throw new NotImplementedException(); } } // VERSION 2 public class Customer_New : DataRespository<CustomerDataAccess> { public int CustomerID { get; set; } public string EmailAddress { get; set; } public int Age { get; set; } } public class DataRespository<T> where T:class,new() { private T item = new T(); public T Execute { get { return item; } set { item = value; } } public void Update() { //TO BE CODED } public void Save() { //TO BE CODED } public void Remove() { //TO BE CODED } } class Program { static void Main(string[] args) { Customer_New cus = new Customer_New() { Age = 10, EmailAddress = "[email protected]" }; cus.Save(); cus.Execute.RemoveCustomer(new Customer()); // Repository Version Customer customer = new Customer() { EmailAddress = "[email protected]", CustomerID = 10 }; BALCustomer bal = new BALCustomer(new CustomerDataAccess()); bal.Add_A_New_Customer(customer); } } }

    Read the article

  • Initializing and accessing a pointer from an array of pointers

    - by idealistikz
    Suppose I have the following: void **Init(int numElems) { //What is the best way to intialize 'ptrElems' to store an array of void *'s? void **ptrElems = malloc(numElems * sizeof(void *)); return ptrElems; } //What is the best way to return a pointer pointing at the index passed as a parameter? void **GetPtr(void **ptrElems, int index) { void **elem = elems + (index * sizeof(void *)); return elem; } First, what is the best way to intialize 'ptrElems' to store an array of pointers? I use malloc because assigning it to an array will not persist after the end of the function. Second, what is the best way to point to the pointer at the specified index? I tried typecasting the first line of the 'GetPtr' function to ensure proper pointer arithmetic, but I receive the warning, 'initialization from incompatible pointer type'. Is it necessary to typecast?

    Read the article

  • Subclassing and adding data members

    - by Marius
    I have an hierarchy of classes that looks like the following: class Critical { public: Critical(int a, int b) : m_a(a), m_b(b) { } virtual ~Critical() { } int GetA() { return m_a; } int GetB() { return m_b; } void SetA(int a) { m_a = a; } void SetB(int b) { m_b = b; } protected: int m_a; int m_b; }; class CriticalFlavor : public Critical { public: CriticalFlavor(int a, int b, int flavor) : Critical(a, b), m_flavor(flavor) { } virtual ~CriticalFlavor() { } int GetFlavor() { return m_flavor; } void SetFlavor(int flavor) { m_flavor = flavor; } protected: int m_flavor; }; class CriticalTwist : public Critical { public: CriticalTwist(int a, int b, int twist) : Critical(a, b), m_twist(twist) { } virtual ~CriticalTwist() { } int GetTwist() { return m_twist; } void SetTwist(int twist) { m_twist = twist; } protected: int m_twist; }; The above does not seem right to me in terms of the design and what bothers me the most is the fact that the addition of member variables seems to drive the interface of these classes (the real code that does the above is a little more complex but still embracing the same pattern). That will proliferate when in need for another "Critical" class that just adds some other property. Does this feel right to you? How could I refactor such code? An idea would be to have just a set of interfaces and use composition when it comes to the base object like the following: class Critical { public: virtual int GetA() = 0; virtual int GetB() = 0; virtual void SetA(int a) = 0; virtual void SetB(int b) = 0; }; class CriticalImpl { public: CriticalImpl(int a, int b) : m_a(a), m_b(b) { } ~CriticalImpl() { } int GetA() { return m_a; } int GetB() { return m_b; } void SetA(int a) { m_a = a; } void SetB(int b) { m_b = b; } private: int m_a; int m_b; }; class CriticalFlavor { public: virtual int GetFlavor() = 0; virtual void SetFlavor(int flavor) = 0; }; class CriticalFlavorImpl : public Critical, public CriticalFlavor { public: CriticalFlavorImpl(int a, int b, int flavor) : m_flavor(flavor), m_critical(new CriticalImpl(a, b)) { } ~CriticalFlavorImpl() { delete m_critical; } int GetFlavor() { return m_flavor; } void SetFlavor(int flavor) { m_flavor = flavor; } int GetA() { return m_critical-GetA(); } int GetB() { return m_critical-GetB(); } void SetA(int a) { m_critical-SetA(a); } void SetB(int b) { m_critical-SetB(b); } private: int m_flavor; CriticalImpl* m_critical; };

    Read the article

  • Problem with Command Pattern under Visual Studio 2008 (C++)

    - by D.Giunchi
    Dear All, I've a problem with this pattern under c++ on VS 2008. The same code has been tested in gcc (linux, mac and mingw for widnows) and it works. I copy/paste the code here: class MyCommand { public: virtual void execute() = 0; virtual ~MyCommand () {}; }; class MyOperation { public: virtual void DoIt() {}; //I also write it not inline }; class MyOperationDerived : public MyOperation { public: virtual void DoIt() {}; //I also write it not inline }; class MyUndoStackCommand : public MyCommand { public: typedef void(MyOperation::*Action)(); MyUndoStackCommand(MyOperation *rec, Action action); /*virtual*/ void execute(); /*virtual*/ ~MyUndoStackCommand(); private: MyOperation *myReceiver; Action myAction ; }; in cpp: #include "MyUndoStackCommand.h" #include "MyOperation.h" MyUndoStackCommand::~MyUndoStackCommand() { } MyUndoStackCommand::MyUndoStackCommand(myOperation *rec, Action action): myReceiver(rec), myAction(action) { } void MyUndoStackCommand::execute() { ((myReceiver)->*(myAction))(); } use in main.cpp: MyReceiver receiver; MyUndoStackCommand usc(&receiver, &MyOperation::DoIt); usc.execute(); when I debug under visual studio only if I set inside MyUndoStackCommand, directly myAction = &MyOperation::DoIt , it works, otherwise not. Any advice? thank you very much, dan Edit: The following code compiles with g++ - changes by Neil Butterworth flagged as //NB. class MyCommand { public: virtual void execute() = 0; virtual ~MyCommand () {}; }; class MyOperation { public: virtual void DoIt() {}; //I also write it not inline }; class MyOperationDerived : public MyOperation { public: virtual void DoIt() {}; //I also write it not inline }; class MyUndoStackCommand : public MyCommand { public: typedef void(MyOperation::*Action)(); MyUndoStackCommand(MyOperation *rec, Action action); /*virtual*/ void execute(); /*virtual*/ ~MyUndoStackCommand(); private: MyOperation *myReceiver; Action myAction ; }; MyUndoStackCommand::~MyUndoStackCommand() { } MyUndoStackCommand::MyUndoStackCommand(MyOperation *rec, //NB Action action) : myReceiver(rec), myAction(action) { } void MyUndoStackCommand::execute() { ((myReceiver)->*(myAction))(); } int main() { MyOperation receiver; //NB MyUndoStackCommand usc(&receiver, &MyOperation::DoIt); usc.execute(); }

    Read the article

  • C++ class functions calling fortran subroutine

    - by user2863626
    Okay so I am trying to make my code work. It is a simple C++ program with a class "CArray". This class has 2 properties, the array size, and the value. I want the main C++ program to create two instances of the class CArray. In the class CArray, I have a function called "AddArray( CArray )" where it adds another array to the current array. The problem I am stuck with, is that I want the function "AddArray" to add the two arrays in fortran. I know, much more complicated, but that is what I need. I am having issues with linking the two inside the class code. #include <iostream> using namespace std; class CArray { public: CArray(); ~CArray(); int Size; int* Val; void SetSize( int ); void SetValues(); void GetArray(); extern "C" { void Add( int*, int*, int*, int*); void Subtract( int*, int*, int*, int*); void Muliply( int*, int*, int *, int* ); } void AddArray( CArray ); void SubtractArray( CArray ); void MultiplyArray( CArray ); }; Also here is the CArray function file. #include "Array.h" #include <iostream> using namespace std; CArray::CArray() { } CArray::~CArray() { } void CArray::SetSize( int s ) { Size = s; for ( int i=0; i<s; i++ ) { Val = new int[Size]; } } void CArray::SetValues() { for ( int i=0; i<Size; i++ ) { cout << "Element " << i+1 << ": "; cin >> Val[i]; } } void CArray::GetArray() { for ( int i=0; i<Size; i++ ) { cout << Val[i] << " "; } } void CArray::AddArray( CArray a ) { if ( Size == a.Size ) { Add(&Val, &a.Val); } else { cout << "Array dimensions do not agree!" << endl; } } void CArray::SubtractArray( CArray a ) { Subtract( &Val, &a, &Size, &a.Size); GetArray(); } Here is my Fortran code. module SubtractArrays use ico_c_binding implicit none contains subroutine Subtract(a,b,s1,s2) bind(c,name='Subtract') integer s1,s2 integer a(s1),b(s2) if ( s1.eq.s2 ) do i=1,s1 a(i) = a(i) - b(i) end return end end If someone could just help me with setting me up to send arrays of integers from C++ classes to fortran I would greatly appreciate it! Thank you, Josh Derrick

    Read the article

  • C#.NET: How to update multiple .NET pages when a particular event occurs in one .Net page? In another words how to use Observer pattern(Publish and subscribe to events)

    Problem: Suppose you have a scenario in which you have to update multiple pages when an event occurs in main page. For example imagine you have a main page where you are dispalying a tab control. This tab control has 3 tab pages where you are loading 3 different user controls. On click of an update button in main page imagine if you have do something in all the 3 tab panels. In other words an event in main page has to be handled in many other pages. An event in main page which contains the tab control has to be handled in all the tab panels(user controls) Answer: Use Observer pattern Define a base page for the page that contains the tab control. Main page which contains the tab: Baseline_Baseline Basepage for the above main page: BaselineBasePage User control that has to be udpated for an event in main page: Baseline_PriorNonDeloitte Source Code: public class BaselineBasePage : System.Web.UI.Page { IList lstControls = new List(); public void Add(IObserver userControl) { lstControls.Add(userControl); } public void Remove(IObserver userControl) { lstControls.Remove(userControl); } public void RemoveAllUserControls() { lstControls.Clear(); } public void Update(SaveEventArgs e) { foreach (IObserver LobjControl in lstControls) { LobjControl.Save(e); } } } public interface IObserver { void Update(SaveEventArgs e); } public partial class Baseline_Baseline : BaselineBasePage { . . . this.Add(_ucPI); this.Add(_ucPI1); protected void abActionBar_saveClicked(object sender, EventArgs e) { SaveEventArgs se = new SaveEventArgs(); se.TabType = (BaselineTabType)tcBaseline.ActiveTabIndex; this.Update(se); } } Public class Baseline_PriorNonDeloitte : System.Web.UI.UserControl,IObserver { public void Update(SaveEventArgs e) { } } More info at: http://www.dofactory.com/Patterns/PatternObserver.aspx span.fullpost {display:none;}

    Read the article

  • OpenGL, draw two polygons in the same time (by mouse clicks)

    - by YoungSalafi
    im trying to draw 2 polygons at the same time depending on user input from the opengl screen... so i made 2 arrays which each one of them will carry the vertices of each polygon ... i think my logic is right but the program still prints only polygon and delete the old polygon if you draw a polygon again . and its acting weird too please check the code yourself here it is : P.S dont mind the delete function right now.. i know it missing something. #include <windows.h> #include <gl/gl.h> #include <gl/glut.h> void Draw(); void Set_Transformations(); void Initialize(int argc, char *argv[]); void OnKeyPress(unsigned char key, int x, int y); void DeleteVer(); void MouseClick(int bin, int state , int x , int y); void GetOGLPos(int x, int y,float* arrY,float* arrX); void DrawPolygon(float* arrX,float* arrY); float xPos[20]; float yPos[20]; float xPos2[20]; float yPos2[20]; float fx = 0,fy = 0; float size = 10; int count = 0; bool done = false; bool flag = true; void Initialize(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(600, 600); glutCreateWindow("OpenGL Lab1"); Set_Transformations(); glutDisplayFunc(Draw); glutMouseFunc(MouseClick); glutKeyboardFunc(OnKeyPress); glutMainLoop(); } void Set_Transformations() { glClearColor(1, 1, 1, 1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-200, 200, -200, 200); } void OnKeyPress(unsigned char key, int x, int y) { if (key == 27) exit(0); switch(key) { case 13: //enter key it will draw done = true; glutPostRedisplay(); flag=!flag; // this flag to switch to the other array that the vertices will be stored in, in order to draw the second polygon break; } } void MouseClick(int button, int state , int x , int y) { switch (button) { case GLUT_RIGHT_BUTTON: if (state == GLUT_DOWN) { if (count>0) { DeleteVer(); //dont mind this right now } } break; case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { if(count<20) { if(flag =true){ // drawing first polygon GetOGLPos(x, y,xPos,yPos);} if (flag=false) //drawing second polygon after Enter is pressed GetOGLPos(x, y,xPos2,yPos2); } } break; } } void GetOGLPos(int x, int y,float* arrY,float* arrX) //getting the vertices from the user { GLint viewport[4]; GLdouble modelview[16]; GLdouble projection[16]; GLfloat winX, winY, winZ; GLdouble posX, posY, posZ; glGetDoublev( GL_MODELVIEW_MATRIX, modelview ); glGetDoublev( GL_PROJECTION_MATRIX, projection ); glGetIntegerv( GL_VIEWPORT, viewport ); winX = (float)x; winY = (float)viewport[3] - (float)y; glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ ); gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ); arrX[count] = posX; arrY[count] = posY; count++; glPointSize( 6.0 ); glBegin(GL_POINTS); glVertex2f(posX,posY); glEnd(); glFlush(); } void DeleteVer(){ //dont mind this glColor3f ( 1, 1, 1); glBegin(GL_POINTS); glVertex2f(xPos[count-1],yPos[count-1]); glEnd(); glFlush(); xPos[count] = NULL; yPos[count] = NULL; count--; glColor3f ( 0, 0, 0); } void DrawPolygon(float* arrX,float* arrY) { int n=0; glColor3f ( 0, 0, 0); glBegin(GL_POLYGON); while(n<count) { glVertex2f(arrX[n],arrY[n]); n++; } count=0; glEnd(); glFlush(); } void Draw() //main drawing func { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0, 0, 0); if(done) { DrawPolygon(xPos,yPos); DrawPolygon(xPos2,yPos2); } glFlush(); } int main(int argc, char *argv[]) { Initialize(argc, argv); return 0; }

    Read the article

  • Feedback + Bad output

    - by user1770094
    So I've got an assignment I think I'm more or less done with, but there is something which is messing up the output badly somewhere down the line, or even the calculation, and I don't see where the problem is. The assignment is to make a game in which a certain ammount of players run up through a tunnel towards a spot,where they will stop and spin around it,and then their dizziness is supposed to make them randomly either progress towards goal or regress back towards start.And each time they get another spot closer to goal,they get another "marking",and it goes on like this until one of them reaches goal. The program includes three files: one main.cpp,one header file and another cpp file. The header file: #ifndef COMPETITOR_H #define COMPETITOR_H #include <string> using namespace std; class Competitor { public: void setName(); string getName(); void spin(); void move(); int checkScore(); void printResult(); private: string name; int direction; int markedSpots; }; #endif // COMPETITOR_H The second cpp file: #include <iostream> #include <string> #include <cstdlib> #include <ctime> #include "Competitor.h" using namespace std; void Competitor::setName() { cin>>name; } string Competitor::getName() { return name; } void Competitor::spin() { srand(time(NULL)); direction = rand()%1+0; } void Competitor::move() { if(direction == 1) { markedSpots++; } else if(direction == 0 && markedSpots != 0) { markedSpots--; } } int Competitor::checkScore() { return markedSpots; } void Competitor::printResult() { if(direction == 1) { cout<<" is heading towards goal and has currently "<<markedSpots<<" markings."; } else if(direction == 0) { cout<<"\n"<<getName()<<" is heading towards start and has currently "<<markedSpots<<" markings."; } } The main cpp file: #include <iostream> #include <string> #include <cstdlib> #include <ctime> #include "Competitor.h" using namespace std; void inputAndSetNames(Competitor comps[],int nrOfComps); void makeTwist(Competitor comps[],int nrOfComps); void makeMove(Competitor comps[],int nrOfComps); void showAll(Competitor comps[],int nrOfComps); int winner(Competitor comps[],int nrOfComps, int nrOfTwistPlaces); int main() { int nrOfTwistPlaces; int nrOfComps; int noWinner = -1; int laps = 0; cout<<"How many spinning places should there be? "; cin>>nrOfTwistPlaces; cout<<"How many competitors should there be? "; cin>>nrOfComps; Competitor * comps = new Competitor[nrOfComps]; inputAndSetNames(comps, nrOfComps); do { laps++; cout<<"\nSpin "<<laps<<":"; makeTwist(comps, nrOfComps); makeMove(comps, nrOfComps); showAll(comps, nrOfComps); }while(noWinner == -1); delete [] comps; return 0; } void inputAndSetNames(Competitor comps[],int nrOfComps) { cout<<"Type in the names of the "<<nrOfComps<<" competitors:\n"; for(int i=0;i<nrOfComps;i++) { comps[i].setName(); } cout<<"\n"; } void makeTwist(Competitor comps[],int nrOfComps) { for(int i=0;i<nrOfComps;i++) { comps[i].spin(); } } void makeMove(Competitor comps[],int nrOfComps) { for(int i=0;i<nrOfComps;i++) { comps[i].move(); } } void showAll(Competitor comps[],int nrOfComps) { for(int i=0;i<nrOfComps;i++) { comps[i].printResult(); } cout<<"\n\n"; system("pause"); } int winner(Competitor comps[],int nrOfComps, int nrOfTwistPlaces) { int end = 0; int score = 0; for(int i=0;i<nrOfComps;i++) { score = comps[i].checkScore(); if(score == nrOfTwistPlaces) { end = 1; } else end = -1; } return end; } I'd be grateful if you would point out other mistakes if you see any.Thanks in advance.

    Read the article

  • Including a C header which declares a variable called "new"?

    - by StackedCrooked
    I'm trying to use the OpenCA library in a C++ application. However, when including the file pki_x509_data_st.h the following code fragment is encountered: typedef struct pki_x509_callbacks_st { /* ---------------- Memory Management -------------------- */ void * (*new) (void ); void (*free) (void *x ); void * (*dup) (void *x ); This won't compile because of the "new" pointer declaration. How can I make it work?

    Read the article

  • Bullet physics debug drawing not working

    - by Krishnabhadra
    Background I am following on from this question, which isn't answered yet. Basically I have a cube and a UVSphere in my scene, with UVSphere on the top of the cube without touching the cube. Both exported from blender. When I run the app The UVSphere does circle around the cube for 3 or 4 times and jump out of the scene. What I actually expect was the sphere to fall on top of the cube. What this question about From the comment to the linked question, I got to know about bullet debug drawing, which helps in debugging by drawing outline of physics bodies which are normally invisible. I did some research on that and came up with the code given below. From whatever I have read, below code should work, but it doesn't. My Code My bullet initialization code. -(void) initializeScene { /*Setup physics world*/ _physicsWorld = [[CC3PhysicsWorld alloc] init]; [_physicsWorld setGravity:0 y:-9.8 z:0]; /*Setting up debug draw*/ MyDebugDraw *draw = new MyDebugDraw; draw->setDebugMode(draw->getDebugMode() | btIDebugDraw::DBG_DrawWireframe ); _physicsWorld._discreteDynamicsWorld->setDebugDrawer(draw); /*Setup camera and lamb*/ ………….. //This simpleCube.pod contains the cube [self addContentFromPODFile: @"simpleCube.pod"]; //This file contains sphere [self addContentFromPODFile: @"SimpleSphere.pod"]; [self createGLBuffers]; CC3MeshNode* cubeNode = (CC3MeshNode*)[self getNodeNamed:@"Cube"]; CC3MeshNode* sphereNode = (CC3MeshNode*)[self getNodeNamed:@"Sphere"]; // both cubeNode and sphereNode are not nil from this point float *cVertexData = (float*)((CC3VertexArrayMesh*)cubeNode.mesh) .vertexLocations.vertices; int cVertexCount = ((CC3VertexArrayMesh*)cubeNode.mesh) .vertexLocations.vertexCount; btTriangleMesh* cTriangleMesh = new btTriangleMesh(); int offset = 0; for (int i = 0; i < (cVertexCount / 3); i++) { unsigned int index1 = offset; unsigned int index2 = offset+6; unsigned int index3 = offset+12; cTriangleMesh->addTriangle( btVector3(cVertexData[index1], cVertexData[index1+1], cVertexData[index1+2]), btVector3(cVertexData[index2], cVertexData[index2+1], cVertexData[index2+2]), btVector3(cVertexData[index3], cVertexData[index3+1], cVertexData[index3+2])); offset += 18; } [self releaseRedundantData]; /*Create a triangle mesh from the vertices*/ btBvhTriangleMeshShape* cTriMeshShape = new btBvhTriangleMeshShape(cTriangleMesh,true); btCollisionShape *sphereShape = new btSphereShape(1); gTriMeshObject = [_physicsWorld createPhysicsObjectTrimesh:cubeNode shape:cTriMeshShape mass:0 restitution:1.0 position:cubeNode.location]; sphereObject = [_physicsWorld createPhysicsObject:sphereNode shape:sphereShape mass:1 restitution:0.1 position:sphereNode.location]; sphereObject.rigidBody->setDamping(0.1,0.8); /*Enable debug drawing*/ _physicsWorld._discreteDynamicsWorld->debugDrawWorld(); } And My btIDebugDraw implementation (MyDebugDraw.h) //MyDebugDraw.h class MyDebugDraw: public btIDebugDraw{ int m_debugMode; public: virtual void drawLine(const btVector3& from,const btVector3& to ,const btVector3& color); virtual void drawContactPoint(const btVector3& PointOnB ,const btVector3& normalOnB,btScalar distance ,int lifeTime,const btVector3& color); virtual void reportErrorWarning(const char* warningString); virtual void draw3dText(const btVector3& location ,const char* textString); virtual void setDebugMode(int debugMode); virtual int getDebugMode() const; }; void MyDebugDraw::drawLine(const btVector3& from,const btVector3& to ,const btVector3& color){ LogInfo(@"Works!!"); glPushMatrix(); glColor4f(color.getX(), color.getY(), color.getZ(), 1.0); const GLfloat line[] = { from.getX()*1, from.getY()*1, from.getZ()*1, //point A to.getX()*1, to.getY()*1,to.getZ()*1 //point B }; glVertexPointer( 3, GL_FLOAT, 0, &line ); glPointSize( 5.0f ); glDrawArrays( GL_POINTS, 0, 2 ); glDrawArrays( GL_LINES, 0, 2 ); glPopMatrix(); } void MyDebugDraw::drawContactPoint(const btVector3 &PointOnB ,const btVector3 &normalOnB, btScalar distance ,int lifeTime, const btVector3 &color){ } void MyDebugDraw::reportErrorWarning(const char *warningString){ } void MyDebugDraw::draw3dText(const btVector3 &location , const char *textString){ } void MyDebugDraw::setDebugMode(int debugMode){ } int MyDebugDraw::getDebugMode() const{ return DBG_DrawWireframe; } My Problem The drawLine method is getting called. I can see the cube and sphere in place. Sphere again does some circling around the cube before jumping off. No debug lines are getting drawn.

    Read the article

  • Use WLST to Delete All JMS Messages From a Destination

    - by james.bayer
    I got a question today about whether WebLogic Server has any tools to delete all messages from a JMS Queue.  It just so happens that the WLS Console has this capability already.  It’s available on the screen after the “Show Messages” button is clicked on a destination’s Monitoring tab as seen in the screen shot below. The console is great for something ad-hoc, but what if I want to automate this?  Well it just so happens that the console is just a weblogic application layered on top of the JMX Management interface.  If you look at the MBean Reference, you’ll find a JMSDestinationRuntimeMBean that includes the operation deleteMessages that takes a JMS Message Selector as an argument.  If you pass an empty string, that is essentially a wild card that matches all messages. Coding a stand-alone JMX client for this is kind of lame, so let’s do something more suitable to scripting.  In addition to the console, WebLogic Scripting Tool (WLST) based on Jython is another way to browse and invoke MBeans, so an equivalent interactive shell session to delete messages from a destination would looks like this: D:\Oracle\fmw11gr1ps3\user_projects\domains\hotspot_domain\bin>setDomainEnv.cmd D:\Oracle\fmw11gr1ps3\user_projects\domains\hotspot_domain>java weblogic.WLST   Initializing WebLogic Scripting Tool (WLST) ...   Welcome to WebLogic Server Administration Scripting Shell   Type help() for help on available commands   wls:/offline> connect('weblogic','welcome1','t3://localhost:7001') Connecting to t3://localhost:7001 with userid weblogic ... Successfully connected to Admin Server 'AdminServer' that belongs to domain 'hotspot_domain'.   Warning: An insecure protocol was used to connect to the server. To ensure on-the-wire security, the SSL port or Admin port should be used instead.   wls:/hotspot_domain/serverConfig> serverRuntime() Location changed to serverRuntime tree. This is a read-only tree with ServerRuntimeMBean as the root. For more help, use help(serverRuntime)   wls:/hotspot_domain/serverRuntime> cd('JMSRuntime/AdminServer.jms/JMSServers/JMSServer-0/Destinations/SystemModule-0!Queue-0') wls:/hotspot_domain/serverRuntime/JMSRuntime/AdminServer.jms/JMSServers/JMSServer-0/Destinations/SystemModule-0!Queue-0> ls() dr-- DurableSubscribers   -r-- BytesCurrentCount 0 -r-- BytesHighCount 174620 -r-- BytesPendingCount 0 -r-- BytesReceivedCount 253548 -r-- BytesThresholdTime 0 -r-- ConsumersCurrentCount 0 -r-- ConsumersHighCount 0 -r-- ConsumersTotalCount 0 -r-- ConsumptionPaused false -r-- ConsumptionPausedState Consumption-Enabled -r-- DestinationInfo javax.management.openmbean.CompositeDataSupport(compositeType=javax.management.openmbean.CompositeType(name=DestinationInfo,items=((itemName=ApplicationName,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=ModuleName,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName openmbean.SimpleType(name=java.lang.Boolean)),(itemName=SerializedDestination,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=ServerName,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=Topic,itemType=javax.management.openmbean.SimpleType(name=java.lang.Boolean)),(itemName=VersionNumber,itemType=javax.management.op ule-0!Queue-0, Queue=true, SerializedDestination=rO0ABXNyACN3ZWJsb2dpYy5qbXMuY29tbW9uLkRlc3RpbmF0aW9uSW1wbFSmyJ1qZfv8DAAAeHB3kLZBABZTeXN0ZW1Nb2R1bGUtMCFRdWV1ZS0wAAtKTVNTZXJ2ZXItMAAOU3lzdGVtTW9kdWxlLTABAANBbGwCAlb6IS6T5qL/AAAACgEAC0FkbWluU2VydmVyAC2EGgJW+iEuk+ai/wAAAAsBAAtBZG1pblNlcnZlcgAthBoAAQAQX1dMU19BZG1pblNlcnZlcng=, ServerName=JMSServer-0, Topic=false, VersionNumber=1}) -r-- DestinationType Queue -r-- DurableSubscribers null -r-- InsertionPaused false -r-- InsertionPausedState Insertion-Enabled -r-- MessagesCurrentCount 0 -r-- MessagesDeletedCurrentCount 3 -r-- MessagesHighCount 2 -r-- MessagesMovedCurrentCount 0 -r-- MessagesPendingCount 0 -r-- MessagesReceivedCount 3 -r-- MessagesThresholdTime 0 -r-- Name SystemModule-0!Queue-0 -r-- Paused false -r-- ProductionPaused false -r-- ProductionPausedState Production-Enabled -r-- State advertised_in_cluster_jndi -r-- Type JMSDestinationRuntime   -r-x closeCursor Void : String(cursorHandle) -r-x deleteMessages Integer : String(selector) -r-x getCursorEndPosition Long : String(cursorHandle) -r-x getCursorSize Long : String(cursorHandle) -r-x getCursorStartPosition Long : String(cursorHandle) -r-x getItems javax.management.openmbean.CompositeData[] : String(cursorHandle),Long(start),Integer(count) -r-x getMessage javax.management.openmbean.CompositeData : String(cursorHandle),Long(messageHandle) -r-x getMessage javax.management.openmbean.CompositeData : String(cursorHandle),String(messageID) -r-x getMessage javax.management.openmbean.CompositeData : String(messageID) -r-x getMessages String : String(selector),Integer(timeout) -r-x getMessages String : String(selector),Integer(timeout),Integer(state) -r-x getNext javax.management.openmbean.CompositeData[] : String(cursorHandle),Integer(count) -r-x getPrevious javax.management.openmbean.CompositeData[] : String(cursorHandle),Integer(count) -r-x importMessages Void : javax.management.openmbean.CompositeData[],Boolean(replaceOnly) -r-x moveMessages Integer : String(java.lang.String),javax.management.openmbean.CompositeData,Integer(java.lang.Integer) -r-x moveMessages Integer : String(selector),javax.management.openmbean.CompositeData -r-x pause Void : -r-x pauseConsumption Void : -r-x pauseInsertion Void : -r-x pauseProduction Void : -r-x preDeregister Void : -r-x resume Void : -r-x resumeConsumption Void : -r-x resumeInsertion Void : -r-x resumeProduction Void : -r-x sort Long : String(cursorHandle),Long(start),String[](fields),Boolean[](ascending)   wls:/hotspot_domain/serverRuntime/JMSRuntime/AdminServer.jms/JMSServers/JMSServer-0/Destinations/SystemModule-0!Queue-0> cmo.deleteMessages('') 2 where the domain name is “hotspot_domain”, the JMS Server name is “JMSServer-0”, the Queue name is “Queue-0” and the System Module is named “SystemModule-0”.  To invoke the operation, I use the “cmo” object, which is the “Current Management Object” that represents the currently navigated to MBean.  The 2 indicates that two messages were deleted.  Combining this WLST code with a recent post by my colleague Steve that shows you how to use an encrypted file to store the authentication credentials, you could easily turn this into a secure automated script.  If you need help with that step, a long while back I blogged about some WLST basics.  Happy scripting.

    Read the article

  • Obj-msg-send error in numberOfSectionsInTableView

    - by mukeshpawar
    import "AddBillerCategoryViewController.h" import "Globals.h" import "AddBillerViewController.h" import "AddBillerListViewController.h" import"KlinnkAppDelegate.h" @implementation AddBillerCategoryViewController @synthesize REASON, RESPVAR, currentAttribute,tbldata,strOptions; // This recipe adds a title for each section //Initialize the table view controller with the grouped style (AddBillerCategoryViewController *) init { if (self = [super initWithStyle:UITableViewStyleGrouped]);// self.title = @"Crayon Colors"; return self; } -(void)showBack { [[self navigationController] pushViewController:[[AddBillerViewController alloc] init] animated:YES]; } (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { if ([viewController isKindOfClass:[AddBillerCategoryViewController class]]) { AddBillerCategoryViewController *controller = (AddBillerCategoryViewController *)viewController; [controller.tbldata reloadData]; } } (void)viewDidLoad { appDelegate = (KlinnkAppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.catListArray.count; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; //self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] // initWithTitle:@"Back" // style:UIBarButtonItemStylePlain // target:self // action:@selector(showBack)] autorelease]; if(gotOK == 0) { //self.navigationItem.leftBarButtonItem.enabled = FALSE; dt = [[DateTime alloc] init]; strChannelID = @"IGLOO|MOBILE"; strDateTime = [dt findDateTime]; strTemp = [dt findSessionTime]; strSessionID = [appDelegate.KMobile stringByAppendingString:strTemp]; strResponseURL = @"http://115.113.110.139/Test/CbbpServerRequestHandler"; strResponseVar = @"serverResponseXML"; strRequestType = @"GETCATEGORY"; NSLog(@"Current Session id - %@", strSessionID); //conn = [[NSURLConnection alloc] init]; receivedData = [[NSMutableData data] retain]; //.................... currentAttribute = [[NSMutableString alloc] init]; // create XMl xmlData = [[NSData alloc] init]; xmlData = [self createXML]; // XMl has been created now convert it in to string xmlString = [[NSString alloc] initWithData:xmlData encoding:NSASCIIStringEncoding]; // Ataching other infromatin to he xml parameterString = [[NSString alloc] initWithString:@"mobileRequestXML="]; requestString = [[NSString alloc] init]; requestString = [parameterString stringByAppendingString:xmlString]; // give space betn two element. requestString = [requestString stringByReplacingOccurrencesOfString:@"<" withString:@" <"]; // Initalizing other parameters postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; postLength = [NSString stringWithFormat:@"%d",[postData length]]; firstRequest = [[[NSMutableURLRequest alloc] init] autorelease]; REASON = [[NSMutableString alloc] init]; RESPVAR = [[NSMutableString alloc] init]; NSLog(@"\n \n Sending for 1st time........\n"); [self sendRequest]; NSLog(@"\n \n Sending for 2nd time........\n"); [self sendRequest]; NSLog(@"\n \n both request send........\n \n "); } //[tbldata reloadData]; [self retain]; [super viewDidLoad]; } -(void)sendRequest { finished = FALSE; NSLog(@"\n Sending Request \n\n %@", requestString); conn = [[NSURLConnection alloc] init]; if(gotOK == 0) [firstRequest setURL:[NSURL URLWithString:@"http://115.113.110.139/Test/CbbpMobileRequestHandler"]]; if(gotOK == 1) { [firstRequest setURL:[NSURL URLWithString:@"http://115.113.110.139//secure"]]; gotOK = 2; } [firstRequest setHTTPMethod:@"POST"]; [firstRequest setValue:postLength forHTTPHeaderField:@"Content-Length"]; [firstRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [firstRequest setHTTPBody:postData]; conn = [conn initWithRequest:firstRequest delegate:self startImmediately:YES]; [conn start]; while(!finished) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } if (conn) { //receivedData = [[NSMutableData data] retain]; NSLog(@"\n\n Received %d bytes of data",[receivedData length]); } else { NSLog(@"\n Not responding"); } } (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@" \n Send didReciveResponse"); [receivedData setLength:0]; } (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@" \n Send didReciveData"); [receivedData appendData:data]; } (void)connectionDidFinishLoading:(NSURLConnection *)connection { finished = TRUE; NSLog(@" \n Send didFinishLaunching"); // do something with the data // receivedData is declared as a method instance elsewhere NSLog(@"\n\n Succeeded! DIDFINISH Received %d bytes of data\n\n ",[receivedData length]); NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]; NSLog(aStr); //[conn release]; if([aStr isEqualToString:@"OK"]) gotOK = 1; NSLog(@" Value of gotOK - %d", gotOK); if(gotOK == 2) { responseData = [aStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; parser = [[NSXMLParser alloc] initWithData:responseData]; [parser setDelegate:self]; NSLog(@"\n start parsing"); [parser parse]; NSLog(@"\n PArsing over"); NSLog(@"\n check U / S and the RESVAR is - %@",RESPVAR); NSRange textRange; textRange =[aStr rangeOfString:@"<"]; if(textRange.location != NSNotFound) { if([RESPVAR isEqualToString:@"U"]) { self.navigationItem.rightBarButtonItem.enabled = TRUE; self.navigationItem.leftBarButtonItem.enabled = TRUE; NSLog(@" \n U......."); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:REASON delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alert show]; [alert release]; } if([RESPVAR isEqualToString:@"S"]) { NSLog(@"\n S........"); [[self navigationController] pushViewController:[[AddBillerCategoryViewController alloc] init] animated:YES]; //[self viewDidLoad]; //[tbldata reloadData]; } } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Problem" message:@"Enable to process your request at this time. Please try again." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alert show]; [alert release]; //self.navigationItem.leftBarButtonItem.enabled = TRUE; } } NSLog(@"\n Last line of connectionDidFinish "); //[tableView reloadData]; } -(NSData *)createXML { NSString *strXmlNode = @" channel alliaceid session reqtype responseurl responsevar "; NSString *tempchannel = [strXmlNode stringByReplacingOccurrencesOfString:@"channel" withString:strChannelID options:NSBackwardsSearch range:NSMakeRange(0, [strXmlNode length])]; NSString *tempalliance = [tempchannel stringByReplacingOccurrencesOfString:@"alliaceid" withString:@"WALLET365" options:NSBackwardsSearch range:NSMakeRange(0, [tempchannel length])]; NSString *tempsession = [tempalliance stringByReplacingOccurrencesOfString:@"session" withString:strSessionID options:NSBackwardsSearch range:NSMakeRange(0, [tempalliance length])]; NSString *tempreqtype = [tempsession stringByReplacingOccurrencesOfString:@"reqtype" withString:strRequestType options:NSBackwardsSearch range:NSMakeRange(0,[tempsession length])]; NSString *tempresponseurl = [tempreqtype stringByReplacingOccurrencesOfString:@"responseurl" withString:strResponseURL options:NSBackwardsSearch range:NSMakeRange(0, [tempreqtype length])]; NSString *tempresponsevar = [tempresponseurl stringByReplacingOccurrencesOfString:@"responsevar" withString:strResponseVar options:NSBackwardsSearch range:NSMakeRange(0,[tempresponseurl length])]; NSData *data= [[NSString stringWithString:tempresponsevar] dataUsingEncoding:NSUTF8StringEncoding]; return data; } (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if([elementName isEqualToString:@"RESPVAL"]) currentAttribute = [NSMutableString string]; if([elementName isEqualToString:@"REASON"]) currentAttribute = [NSMutableString string]; if([elementName isEqualToString:@"COUNT"]) currentAttribute = [NSMutableString string]; if([elementName isEqualToString:@"CATNAME"]) currentAttribute = [NSMutableString string]; } (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if([elementName isEqualToString:@"RESPVAL"]) { [RESPVAR setString:currentAttribute]; //NSLog(@"\n Response VAR - %@", RESPVAR); } if([elementName isEqualToString:@"REASON"]) { [REASON setString:currentAttribute]; //NSLog(@"\n Reason - %@", REASON); } if([elementName isEqualToString:@"COUNT"]) { NSString *temp1 = [[NSString alloc] init]; temp1 = [temp1 stringByAppendingString:currentAttribute]; catCount = [temp1 intValue]; [temp1 release]; //NSLog(@"\n Cat Count - %d", catCount); } if([elementName isEqualToString:@"CATNAME"]) { [appDelegate.catListArray addObject:[NSString stringWithFormat:currentAttribute]]; //NSLog(@"%@", appDelegate.catListArray); } } (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if(self.currentAttribute) [self.currentAttribute setString:string]; } /* (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } */ /* (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ /* (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } */ /* (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ /* // Override to allow orientations other than the default portrait orientation. (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview // Release anything that's not essential, such as cached data } pragma mark Table view methods -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { KlinnkAppDelegate *appDelegated = (KlinnkAppDelegate *)[[UIApplication sharedApplication] delegate]; return appDelegated.catListArray.count; } // Customize the appearance of table view cells. (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... AddBillerCategoryViewController *mbvc = (AddBillerCategoryViewController *)[appDelegate.catListArray objectAtIndex:indexPath.row]; [cell setText:mbvc.strOptions]; return cell; } (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. // AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil]; // [self.navigationController pushViewController:anotherViewController]; // [anotherViewController release]; gotOK = 0; int j = indexPath.row; appDelegate.catName = [[NSString alloc] init]; appDelegate.catName = [appDelegate.catName stringByAppendingString:[appDelegate.catListArray objectAtIndex:j]]; [[self navigationController] pushViewController:[[AddBillerListViewController alloc] init] animated:YES]; } /* // Override to support conditional editing of the table view. (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ (void)dealloc { [REASON release]; [RESPVAR release]; [currentAttribute release]; [tbldata release]; [super dealloc]; } @end In the Above code .. numberOfSectionsInTableView ,i get error of obj-msg-send i have intialize the array catlist and even not released it anywhere still why i am getting this error please help me i am badly stuck' thanks in advacnce

    Read the article

  • Program crash on deque from queue

    - by SwedishGit
    My first question asked here, so please excuse if I fail to include something... I'm working on a homework project, which basically consists of creating a "Jukebox" (importing/exporting albums from txt files, creating and "playing" a playlist, etc.). I've become stuck on one point: When "playing" the playlist, which consists of a self-made Queue, a copy of it is made from which songs are dequeued and printed out with a time delay. This appears to run fine on the first run through the program, but if the "play" option is chosen again (with the same playlist, created from a different menu option), it crashes before managing to print the first song. It also crashes if creating a new playlist, but then it manages to print some songs (seem to depend on the number of songs in the first/new playlists...) before crashing. With printouts I've been able to track the crashing down to being on the "item = n-data" call in the deque function... but can't get my head around why this would crash. Below is the code I think should be relevant... let me know if there are other parts that would help if I include. Edit: The Debug Error shown on crash is: R6010 abort() has been called The method to play from the playlist: void Jukebox::playList() { if(songList.getNodes() > 0) { Queue tmpList(songList); Song tmpSong; while(tmpList.deque(tmpSong)) { clock_t temp; temp = clock () + 2 * CLOCKS_PER_SEC ; while (clock() < temp) {} } } else cout << "There are no songs in the playlist!" << endl; } Queue: // Queue.h - Projekt-uppgift // Håkan Sjölin 2014-05-31 //----------------------------------------------------------------------------- #ifndef queue_h #define queue_h #include "Song.h" using namespace std; typedef Song Item; class Node; class Queue { private: Node *first; Node *last; int nodes; public: Queue():first(nullptr),last(nullptr),nodes(0){}; ~Queue(); void enque(Item item); bool deque(Item &item); int getNodes() const { return nodes; } void empty(); }; #endif // Queue.cpp - Projekt-uppgift // Håkan Sjölin 2014-05-31 //----------------------------------------------------------------------------- #include "queue.h" using namespace std; class Node { public: Node *next; Item data; Node (Node *n, Item newData) : next(n), data(newData) {} }; //------------------------------------------------------------------------------ // Funktionsdefinitioner för klassen Queue //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Destruktor //------------------------------------------------------------------------------ Queue::~Queue() { while(first!=0) { Node *tmp = first; first = first->next; delete tmp; } } //------------------------------------------------------------------------------ // Lägg till data sist i kön //------------------------------------------------------------------------------ void Queue::enque(Item item) { Node *pNew = new Node(0,item); if(getNodes() < 1) first = pNew; else last->next = pNew; last = pNew; nodes++; } //------------------------------------------------------------------------------ // Ta bort data först i kön //------------------------------------------------------------------------------ bool Queue::deque(Item &item) { if(getNodes() < 1) return false; //cout << "deque: test2" << endl; Node *n = first; //cout << "deque: test3" << endl; //cout << "item = " << item << endl; //cout << "first = " << first << endl; //cout << "n->data = " << n->data << endl; item = n->data; //cout << "deque: test4" << endl; first = first->next; //delete n; nodes--; if(getNodes() < 1) // Kön BLEV tom last = nullptr; return true; } //------------------------------------------------------------------------------ // Töm kön //------------------------------------------------------------------------------ void Queue::empty() { while (getNodes() > 0) { Item item; deque(item); } } //------------------------------------------------------------------------------ Song: // Song.h - Projekt-uppgift // Håkan Sjölin 2014-05-15 //----------------------------------------------------------------------------- #ifndef song_h #define song_h #include "Time.h" #include <string> #include <iostream> using namespace std; class Song { private: string title; string artist; Time length; public: Song(); Song(string pTitle, string pArtist, Time pLength); // Setfunktioner void setTitle(string pTitle); void setArtist(string pArtist); void setLength(Time pLength); // Getfunktioner string getTitle() const { return title;} string getArtist() const { return artist;} Time getLength() const { return length;} }; ostream &operator<<(ostream &os, const Song &song); istream &operator>>(istream &is, Song &song); #endif // Song.cpp - Projekt-uppgift // Håkan Sjölin 2014-05-15 //----------------------------------------------------------------------------- #include "Song.h" #include "Constants.h" #include <iostream> //------------------------------------------------------------------------------ // Definiering av Songs medlemsfunktioner //------------------------------------------------------------------------------ // Fövald konstruktor //------------------------------------------------------------------------------ Song::Song() { } //------------------------------------------------------------------------------ // Initieringskonstruktor //------------------------------------------------------------------------------ Song::Song(string pTitle, string pArtist, Time pLength) { title = pTitle; artist = pArtist; length = pLength; } //------------------------------------------------------------------------------ // Setfunktioner //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // setTitle // Ange titel //------------------------------------------------------------------------------ void Song::setTitle(string pTitle) { title = pTitle; } //------------------------------------------------------------------------------ // setArtist // Ange artist //------------------------------------------------------------------------------ void Song::setArtist(string pArtist) { artist = pArtist; } //------------------------------------------------------------------------------ // setTitle // Ange titel //------------------------------------------------------------------------------ void Song::setLength(Time pLength) { length = pLength; } //--------------------------------------------------------------------------- // Överlagring av utskriftsoperatorn //--------------------------------------------------------------------------- ostream &operator<<(ostream &os, const Song &song) { os << song.getTitle() << DELIM << song.getArtist() << DELIM << song.getLength(); return os; } //--------------------------------------------------------------------------- // Överlagring av inmatningsoperatorn //--------------------------------------------------------------------------- istream &operator>>(istream &is, Song &song) { string tmpString; Time tmpLength; getline(is, tmpString, DELIM); song.setTitle(tmpString); getline(is, tmpString, DELIM); song.setArtist(tmpString); is >> tmpLength; is.get(); song.setLength(tmpLength); return is; } //--------------------------------------------------------------------------- Album: // Album.h - Projekt-uppgift // Håkan Sjölin 2014-05-17 //----------------------------------------------------------------------------- #ifndef album_h #define album_h #include "Song.h" #include <string> #include <vector> #include <iostream> using namespace std; class Album { private: string name; vector<Song> songs; public: Album(); Album(string pNameTitle, vector<Song> pSongs); // Setfunktioner void setName(string pName); // Getfunktioner string getName() const { return name;} vector<Song> getSongs() const { return songs;} int getNumberOfSongs() const { return songs.size();} Time getTotalTime() const; void addSong(Song pSong); bool operator<(const Album &album) const; }; ostream &operator<<(ostream &os, const Album &album); istream &operator>>(istream &is, Album &album); #endif // Album.cpp - Projekt-uppgift // Håkan Sjölin 2014-05-17 //----------------------------------------------------------------------------- #include "Album.h" #include "Constants.h" #include <iostream> #include <string> //------------------------------------------------------------------------------ // Definiering av Albums medlemsfunktioner //------------------------------------------------------------------------------ // Fövald konstruktor //------------------------------------------------------------------------------ Album::Album() { } //------------------------------------------------------------------------------ // Initieringskonstruktor //------------------------------------------------------------------------------ Album::Album(string pName, vector<Song> pSongs) { name = pName; songs = pSongs; } //------------------------------------------------------------------------------ // Setfunktioner //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // setName // Ange namn //------------------------------------------------------------------------------ void Album::setName(string pName) { name = pName; } //------------------------------------------------------------------------------ // addSong // Lägg till song //------------------------------------------------------------------------------ void Album::addSong(Song pSong) { songs.push_back(pSong); } //------------------------------------------------------------------------------ // getTotalTime // Returnera total speltid //------------------------------------------------------------------------------ Time Album::getTotalTime() const { Time tTime(0,0,0); for(Song s : songs) { tTime = tTime + s.getLength(); } return tTime; } //--------------------------------------------------------------------------- // Mindre än //--------------------------------------------------------------------------- bool Album::operator<(const Album &album) const { return getTotalTime() < album.getTotalTime(); } //--------------------------------------------------------------------------- // Överlagring av utskriftsoperatorn //--------------------------------------------------------------------------- ostream &operator<<(ostream &os, const Album &album) { os << album.getName() << endl; os << album.getNumberOfSongs() << endl; for (size_t i = 0; i < album.getSongs().size(); i++) os << album.getSongs().at(i) << endl; return os; } //--------------------------------------------------------------------------- // Överlagring av inmatningsoperatorn //--------------------------------------------------------------------------- istream &operator>>(istream &is, Album &album) { string tmpString; int tmpNumberOfSongs; Song tmpSong; getline(is, tmpString); album.setName(tmpString); is >> tmpNumberOfSongs; is.get(); for (int i = 0; i < tmpNumberOfSongs; i++) { is >> tmpSong; album.addSong(tmpSong); } return is; } //--------------------------------------------------------------------------- Time: // Time.h - Projekt-uppgift // Håkan Sjölin 2014-05-15 //----------------------------------------------------------------------------- #ifndef time_h #define time_h #include <iostream> using namespace std; class Time { private: int hours; int minutes; int seconds; public: Time(); Time(int pHour, int pMinute, int pSecond); // Setfunktioner void setHour(int pHour); void setMinute(int pMinute); void setSecond(int pSecond); // Getfunktioner int getHour() const { return hours;} int getMinute() const { return minutes;} int getSecond() const { return seconds;} Time operator+(const Time &time) const; bool operator==(const Time &time) const; bool operator<(const Time &time) const; }; ostream &operator<<(ostream &os, const Time &time); istream &operator>>(istream &is, Time &Time); #endif // Time.cpp - Projekt-uppgift // Håkan Sjölin 2014-05-15 //----------------------------------------------------------------------------- #include "Time.h" #include <iostream> //------------------------------------------------------------------------------ // Definiering av Times medlemsfunktioner //------------------------------------------------------------------------------ // Fövald konstruktor //------------------------------------------------------------------------------ Time::Time() { } //------------------------------------------------------------------------------ // Initieringskonstruktor //------------------------------------------------------------------------------ Time::Time(int pHour, int pMinute, int pSecond) { setHour(pHour); setMinute(pMinute); setSecond(pSecond); } //------------------------------------------------------------------------------ // Setfunktioner //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // setHour // Ange timme //------------------------------------------------------------------------------ void Time::setHour(int pHour) { if(pHour>-1) hours = pHour; else hours = 0; } //------------------------------------------------------------------------------ // setMinute // Ange minut //------------------------------------------------------------------------------ void Time::setMinute(int pMinute) { if(pMinute < 60 && pMinute > -1) { minutes = pMinute; } else minutes = 0; } //------------------------------------------------------------------------------ // setSecond // Ange sekund //------------------------------------------------------------------------------ void Time::setSecond(int pSecond) { if(pSecond < 60 && pSecond > -1) { seconds = pSecond; } else seconds = 0; } //--------------------------------------------------------------------------- // Överlagring av utskriftsoperatorn //--------------------------------------------------------------------------- ostream &operator<<(ostream &os, const Time &time) { os << time.getHour()*3600+time.getMinute()*60+time.getSecond(); return os; } //--------------------------------------------------------------------------- // Överlagring av inmatningsoperatorn //--------------------------------------------------------------------------- istream &operator>>(istream &is, Time &time) { int tmp; is >> tmp; time.setSecond(tmp%60); time.setMinute((tmp/60)%60); time.setHour(tmp/3600); return is; } //--------------------------------------------------------------------------- // Likhet //-------------------------------------------------------------------------- bool Time::operator==(const Time &time) const { return hours == time.getHour() && minutes == time.getMinute() && seconds == time.getSecond(); } //--------------------------------------------------------------------------- // Mindre än //--------------------------------------------------------------------------- bool Time::operator<(const Time &time) const { if(hours == time.getHour()) { if(minutes == time.getMinute()) { return seconds < time.getSecond(); } else { return minutes < time.getMinute(); } } else { return hours < time.getHour(); } } //--------------------------------------------------------------------------- // Addition //--------------------------------------------------------------------------- Time Time::operator+(const Time &time) const { return Time(hours+time.getHour() + (minutes+time.getMinute() + (seconds+time.getSecond())/60)/60, (minutes+time.getMinute() + (seconds+time.getSecond())/60)%60, (seconds+time.getSecond())%60); } //--------------------------------------------------------------------------- Thanks in advance for any help! Edit2: Didn't think of including the more detailed crash info (as it didn't show in the crash pop-up, so to say). Anyway, here it is: Output: 'Jukebox.exe' (Win32): Loaded 'C:\Users\Håkan\Documents\Studier - IT\Objektbaserad programmering i C++\Inlämningsuppgifter\Projekt\Jukebox\Debug\Jukebox.exe'. Symbols loaded. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp110d.dll'. Symbols loaded. 'Jukebox.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr110d.dll'. Symbols loaded. The thread 0xe50 has exited with code 0 (0x0). Unhandled exception at 0x0083630C in Jukebox.exe: 0xC0000005: Access violation reading location 0x0000003C. Call stack: > Jukebox.exe!Song::getLength() Line 27 C++ Jukebox.exe!operator<<(std::basic_ostream<char,std::char_traits<char> > & os, const Song & song) Line 59 C++ Jukebox.exe!Queue::deque(Song & item) Line 55 C++ Jukebox.exe!Jukebox::playList() Line 493 C++ Jukebox.exe!Jukebox::play() Line 385 C++ Jukebox.exe!Jukebox::run() Line 536 C++ Jukebox.exe!main() Line 547 C++ Jukebox.exe!__tmainCRTStartup() Line 536 C Jukebox.exe!mainCRTStartup() Line 377 C kernel32.dll!754d86e3() Unknown [Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll] ntdll.dll!7748bf39() Unknown ntdll.dll!7748bf0c() Unknown

    Read the article

  • Help with Hibernate mapping

    - by GigaPr
    Hi i have the following classes public class RSS { private Integer id; private String title; private String description; private String link; private Date dateCreated; private Collection rssItems; private String url; private String language; private String rating; private Date pubDate; private Date lastBuildDate; private User user; private Date dateModified; public RSS() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public void setDescription(String description){ this.description = description; } public String getDescription(){ return this.description; } public void setLink(String link){ this.link = link; } public String getLink(){ return this.link; } public void setUrl(String url){ this.url = url; } public String getUrl(){ return this.url; } public void setLanguage(String language){ this.language = language; } public String getLanguage(){ return this.language; } public void setRating(String rating){ this.rating = rating; } public String getRating(){ return this.rating; } public Date getPubDate() { return pubDate; } public void setPubDate(Date pubDate) { this.pubDate = pubDate; } public Date getLastBuildDate() { return lastBuildDate; } public void setLastBuildDate(Date lastBuildDate) { this.lastBuildDate = lastBuildDate; } public Date getDateModified() { return dateModified; } public void setDateModified(Date dateModified) { this.dateModified = dateModified; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Collection getRssItems() { return rssItems; } public void setRssItems(Collection rssItems) { this.rssItems = rssItems; } } public class RSSItem { private RSS rss; private Integer id; private String title; private String description; private String link; private Date dateCreated; private Date dateModified; private int rss_id; public RSSItem() {} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Date getDateModified() { return dateModified; } public void setDateModified(Date dateModified) { this.dateModified = dateModified; } public RSS getRss() { return rss; } public void setRss(RSS rss) { this.rss = rss; } } that i mapped as <hibernate-mapping> <class name="com.rssFeed.domain.RSS" schema="PUBLIC" table="RSS"> <id name="id" type="int"> <column name="ID"/> <generator class="native"/> </id> <property name="title" type="string"> <column name="TITLE" not-null="true"/> </property> <property name="lastBuildDate" type="java.util.Date"> <column name="LASTBUILDDATE"/> </property> <property name="pubDate" type="java.util.Date"> <column name="PUBDATE" /> </property> <property name="dateCreated" type="java.util.Date"> <column name="DATECREATED" not-null="true"/> </property> <property name="dateModified" type="java.util.Date"> <column name="DATEMODIFIED" not-null="true"/> </property> <property name="description" type="string"> <column name="DESCRIPTION" not-null="true"/> </property> <property name="link" type="string"> <column name="LINK" not-null="true"/> </property> <property name="url" type="string"> <column name="URL" not-null="true"/> </property> <property name="language" type="string"> <column name="LANGUAGE" not-null="true"/> </property> <property name="rating" type="string"> <column name="RATING"/> </property> <set inverse="true" lazy="false" name="rssItems"> <key> <column name="RSS_ID"/> </key> <one-to-many class="com.rssFeed.domain.RSSItem"/> </set> </class> </hibernate-mapping> <hibernate-mapping> <class name="com.rssFeed.domain.RSSItem" schema="PUBLIC" table="RSSItem"> <id name="id" type="int"> <column name="ID"/> <generator class="native"/> </id> <property name="title" type="string"> <column name="TITLE" not-null="true"/> </property> <property name="description" type="string"> <column name="DESCRIPTION" not-null="true"/> </property> <property name="link" type="string"> <column name="LINK" not-null="true"/> </property> <property name="dateCreated" type="java.util.Date"> <column name="DATECREATED"/> </property> <property name="dateModified" type="java.util.Date"> <column name="DATEMODIFIED"/> </property> <many-to-one class="com.rssFeed.domain.RSS" fetch="select" name="rss"> <column name="RSS_ID"/> </many-to-one> </class> </hibernate-mapping> But when i try to fetch an RSS I get the following error Exception occurred in target VM: failed to lazily initialize a collection of role: com.rssFeed.domain.RSS.rssItems, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.rssFeed.domain.RSS.rssItems, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97) at org.hibernate.collection.PersistentSet.size(PersistentSet.java:139) at com.rssFeed.dao.hibernate.HibernateRssDao.get(HibernateRssDao.java:47) at com.rssFeed.ServiceImplementation.RssServiceImplementation.get(RssServiceImplementation.java:46) at com.rssFeed.mvc.ViewRssController.handleRequest(ViewRssController.java:20) at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:476) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:431) at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) < what does it mean? Thanks

    Read the article

  • Cnoverting application to MVC architecture

    - by terence6
    I'm practicing writing MVC applications. I have a Mastermind game, that I would like to rewrite as MVC app. I have divided my code to parts, but instead of working game I'm getting empty Frame and an error in "public void paint( Graphics g )". Error comes from calling this method in my view with null argument. But how to overcome this ? MVC was quite simple with swing but awt and it's paint methods are much more complicated. Code of working app : http://paste.pocoo.org/show/224982/ App divided to MVC : Main : public class Main { public static void main(String[] args){ Model model = new Model(); View view = new View("Mastermind", 400, 590, model); Controller controller = new Controller(model, view); view.setVisible(true); } } Controller : import java.awt.*; import java.awt.event.*; public class Controller implements MouseListener, ActionListener { private Model model; private View view; public Controller(Model m, View v){ model = m; view = v; view.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); view.addMouseListener(this); } public void actionPerformed( ActionEvent e ) { if(e.getSource() == view.checkAnswer){ if(model.isRowFull){ model.check(); } } } public void mousePressed(MouseEvent e) { Point mouse = new Point(); mouse = e.getPoint(); if (model.isPlaying){ if (mouse.x > 350) { int button = 1 + (int)((mouse.y - 32) / 50); if ((button >= 1) && (button <= 5)){ model.fillHole(button); } } } } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } View : import java.awt.*; import javax.swing.*; import java.awt.event.*; public class View extends Frame implements ActionListener { Model model; JButton checkAnswer; private JPanel button; static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516}; public View(String name, int w, int h, Model m){ model = m; setTitle( name ); setSize( w,h ); setResizable( false ); this.setLayout(new BorderLayout()); button = new JPanel(); button.setSize( new Dimension(400, 100)); button.setVisible(true); checkAnswer = new JButton("Check"); checkAnswer.addActionListener(this); checkAnswer.setSize( new Dimension(200, 30)); button.add( checkAnswer ); this.add( button, BorderLayout.SOUTH); button.setVisible(true); for ( int i=0; i < model.SCORE; i++ ){ for ( int j = 0; j < model.LINE; j++ ){ model.pins[i][j] = new Pin(20,0); model.pins[i][j].setPosition(j*50+30,510-i*50); model.pins[i+model.SCORE][j] = new Pin(8,0); model.pins[i+model.SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50); } } for ( int i=0; i < model.LINE; i++ ){ model.pins[model.OPTIONS][i] = new Pin( 20, i+2 ); model.pins[model.OPTIONS][i].setPosition( 370,i * 50 + 56); } model.combination(); model.paint(null); } public void actionPerformed( ActionEvent e ) { } } Model: import java.awt.*; public class Model extends Frame{ static final int LINE = 5, SCORE = 10, OPTIONS = 20; Pin pins[][] = new Pin[21][LINE]; int combination[] = new int[LINE]; int curPin = 0; int turn = 1; int repaintPin; boolean isUpdate = true, isPlaying = true, isRowFull = false; public Model(){ } void fillHole(int color) { pins[turn-1][curPin].setColor(color+1); repaintPins( turn ); curPin = (curPin+1) % LINE; if (curPin == 0){ isRowFull = true; } } public void paint( Graphics g ) { g.setColor( new Color(238, 238, 238)); g.fillRect( 0,0,400,590); for ( int i=0; i < pins.length; i++ ) { pins[i][0].paint(g); pins[i][1].paint(g); pins[i][2].paint(g); pins[i][3].paint(g); pins[i][4].paint(g); } } public void update( Graphics g ) { if ( isUpdate ) { paint(g); } else { isUpdate = true; pins[repaintPin-1][0].paint(g); pins[repaintPin-1][1].paint(g); pins[repaintPin-1][2].paint(g); pins[repaintPin-1][3].paint(g); pins[repaintPin-1][4].paint(g); } } void repaintPins( int pin ) { repaintPin = pin; isUpdate = false; repaint(); } void check() { int junkPegs[] = new int[LINE], junkCode[] = new int[LINE]; int pegCount = 0, pico = 0; for ( int i = 0; i < LINE; i++ ) { junkPegs[i] = pins[turn-1][i].getColor(); junkCode[i] = combination[i]; } for ( int i = 0; i < LINE; i++ ){ if (junkPegs[i]==junkCode[i]) { pins[turn+SCORE][pegCount].setColor(1); pegCount++; pico++; junkPegs[i] = 98; junkCode[i] = 99; } } for ( int i = 0; i < LINE; i++ ){ for ( int j = 0; j < LINE; j++ ) if (junkPegs[i]==junkCode[j]) { pins[turn+SCORE][pegCount].setColor(2); pegCount++; junkPegs[i] = 98; junkCode[j] = 99; j = LINE; } } repaintPins( turn+SCORE ); if ( pico == LINE ){ isPlaying = false; } else if ( turn >= 10 ){ isPlaying = false; } else{ curPin = 0; isRowFull = false; turn++; } } void combination() { for ( int i = 0; i < LINE; i++ ){ combination[i] = 1 + (int)(Math.random()*5); System.out.print(i+","); } } } class Pin{ private int color, X, Y, radius; private static final Color COLORS[] = { Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)}; public Pin(){ X = 0; Y = 0; radius = 0; color = 0; } public Pin( int r,int c ){ X = 0; Y = 0; radius = r; color = c; } public void paint( Graphics g ){ int x = X-radius; int y = Y-radius; if (color > 0){ g.setColor( COLORS[color]); g.fillOval( x,y,2*radius,2*radius ); } else{ g.setColor( new Color(238, 238, 238) ); g.drawOval( x,y,2*radius-1,2*radius-1 ); } g.setColor( Color.black ); g.drawOval( x,y,2*radius,2*radius ); } public void setPosition( int x,int y ){ this.X = x ; this.Y = y ; } public void setColor( int c ){ color = c; } public int getColor() { return color; } } Any clues on how to overcome this would be great. Have I divided my code improperly ?

    Read the article

  • Converting application to MVC architecture

    - by terence6
    I'm practicing writing MVC applications. I have a Mastermind game, that I would like to rewrite as MVC app. I have divided my code to parts, but instead of working game I'm getting empty Frame and an error in "public void paint( Graphics g )". Error comes from calling this method in my view with null argument. But how to overcome this ? MVC was quite simple with swing but awt and it's paint methods are much more complicated. Code of working app : http://paste.pocoo.org/show/224982/ App divided to MVC : Main : public class Main { public static void main(String[] args){ Model model = new Model(); View view = new View("Mastermind", 400, 590, model); Controller controller = new Controller(model, view); view.setVisible(true); } } Controller : import java.awt.*; import java.awt.event.*; public class Controller implements MouseListener, ActionListener { private Model model; private View view; public Controller(Model m, View v){ model = m; view = v; view.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); view.addMouseListener(this); } public void actionPerformed( ActionEvent e ) { if(e.getSource() == view.checkAnswer){ if(model.isRowFull){ model.check(); } } } public void mousePressed(MouseEvent e) { Point mouse = new Point(); mouse = e.getPoint(); if (model.isPlaying){ if (mouse.x > 350) { int button = 1 + (int)((mouse.y - 32) / 50); if ((button >= 1) && (button <= 5)){ model.fillHole(button); } } } } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } View : import java.awt.*; import javax.swing.*; import java.awt.event.*; public class View extends Frame implements ActionListener { Model model; JButton checkAnswer; private JPanel button; static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516}; public View(String name, int w, int h, Model m){ model = m; setTitle( name ); setSize( w,h ); setResizable( false ); this.setLayout(new BorderLayout()); button = new JPanel(); button.setSize( new Dimension(400, 100)); button.setVisible(true); checkAnswer = new JButton("Check"); checkAnswer.addActionListener(this); checkAnswer.setSize( new Dimension(200, 30)); button.add( checkAnswer ); this.add( button, BorderLayout.SOUTH); button.setVisible(true); for ( int i=0; i < model.SCORE; i++ ){ for ( int j = 0; j < model.LINE; j++ ){ model.pins[i][j] = new Pin(20,0); model.pins[i][j].setPosition(j*50+30,510-i*50); model.pins[i+model.SCORE][j] = new Pin(8,0); model.pins[i+model.SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50); } } for ( int i=0; i < model.LINE; i++ ){ model.pins[model.OPTIONS][i] = new Pin( 20, i+2 ); model.pins[model.OPTIONS][i].setPosition( 370,i * 50 + 56); } model.combination(); model.paint(null); } public void actionPerformed( ActionEvent e ) { } } Model: import java.awt.*; public class Model extends Frame{ static final int LINE = 5, SCORE = 10, OPTIONS = 20; Pin pins[][] = new Pin[21][LINE]; int combination[] = new int[LINE]; int curPin = 0; int turn = 1; int repaintPin; boolean isUpdate = true, isPlaying = true, isRowFull = false; public Model(){ } void fillHole(int color) { pins[turn-1][curPin].setColor(color+1); repaintPins( turn ); curPin = (curPin+1) % LINE; if (curPin == 0){ isRowFull = true; } } public void paint( Graphics g ) { g.setColor( new Color(238, 238, 238)); g.fillRect( 0,0,400,590); for ( int i=0; i < pins.length; i++ ) { pins[i][0].paint(g); pins[i][1].paint(g); pins[i][2].paint(g); pins[i][3].paint(g); pins[i][4].paint(g); } } public void update( Graphics g ) { if ( isUpdate ) { paint(g); } else { isUpdate = true; pins[repaintPin-1][0].paint(g); pins[repaintPin-1][1].paint(g); pins[repaintPin-1][2].paint(g); pins[repaintPin-1][3].paint(g); pins[repaintPin-1][4].paint(g); } } void repaintPins( int pin ) { repaintPin = pin; isUpdate = false; repaint(); } void check() { int junkPegs[] = new int[LINE], junkCode[] = new int[LINE]; int pegCount = 0, pico = 0; for ( int i = 0; i < LINE; i++ ) { junkPegs[i] = pins[turn-1][i].getColor(); junkCode[i] = combination[i]; } for ( int i = 0; i < LINE; i++ ){ if (junkPegs[i]==junkCode[i]) { pins[turn+SCORE][pegCount].setColor(1); pegCount++; pico++; junkPegs[i] = 98; junkCode[i] = 99; } } for ( int i = 0; i < LINE; i++ ){ for ( int j = 0; j < LINE; j++ ) if (junkPegs[i]==junkCode[j]) { pins[turn+SCORE][pegCount].setColor(2); pegCount++; junkPegs[i] = 98; junkCode[j] = 99; j = LINE; } } repaintPins( turn+SCORE ); if ( pico == LINE ){ isPlaying = false; } else if ( turn >= 10 ){ isPlaying = false; } else{ curPin = 0; isRowFull = false; turn++; } } void combination() { for ( int i = 0; i < LINE; i++ ){ combination[i] = 1 + (int)(Math.random()*5); System.out.print(i+","); } } } class Pin{ private int color, X, Y, radius; private static final Color COLORS[] = { Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)}; public Pin(){ X = 0; Y = 0; radius = 0; color = 0; } public Pin( int r,int c ){ X = 0; Y = 0; radius = r; color = c; } public void paint( Graphics g ){ int x = X-radius; int y = Y-radius; if (color > 0){ g.setColor( COLORS[color]); g.fillOval( x,y,2*radius,2*radius ); } else{ g.setColor( new Color(238, 238, 238) ); g.drawOval( x,y,2*radius-1,2*radius-1 ); } g.setColor( Color.black ); g.drawOval( x,y,2*radius,2*radius ); } public void setPosition( int x,int y ){ this.X = x ; this.Y = y ; } public void setColor( int c ){ color = c; } public int getColor() { return color; } } Any clues on how to overcome this would be great. Have I divided my code improperly ?

    Read the article

  • Calling base class constructor

    - by The Void
    In the program below, is the line Derived(double y): Base(), y_(y) correct/allowed? That is, does it follow ANSI rules? #include <iostream> class Base { public: Base(): x_(0) { std::cout << "Base default constructor called" << std::endl; } Base(int x): x_(x) { std::cout << "Base constructor called with x = " << x << std::endl; } void display() const { std::cout << x_ << std::endl; } protected: int x_; }; class Derived: public Base { public: Derived(): Base(1), y_(1.2) { std::cout << "Derived default constructor called" << std::endl; } Derived(double y): Base(), y_(y) { std::cout << "Derived constructor called with y = " << y << std::endl; } void display() const { std::cout << Base::x_ << ", " << y_ << std::endl; } private: double y_; }; int main() { Base b1; b1.display(); Derived d1; d1.display(); std::cout << std::endl; Base b2(-9); b2.display(); Derived d2(-8.7); d2.display(); return 0; }

    Read the article

  • NLog Exception Details Renderer

    - by jtimperley
    Originally posted on: http://geekswithblogs.net/jtimperley/archive/2013/07/28/nlog-exception-details-renderer.aspxI recently switch from Microsoft's Enterprise Library Logging block to NLog.  In my opinion, NLog offers a simpler and much cleaner configuration section with better use of placeholders, complemented by custom variables. Despite this, I found one deficiency in my migration; I had lost the ability to simply render all details of an exception into our logs and notification emails. This is easily remedied by implementing a custom layout renderer. Start by extending 'NLog.LayoutRenderers.LayoutRenderer' and overriding the 'Append' method. using System.Text; using NLog; using NLog.Config; using NLog.LayoutRenderers;   [ThreadAgnostic] [LayoutRenderer(Name)] public class ExceptionDetailsRenderer : LayoutRenderer { public const string Name = "exceptiondetails";   protected override void Append(StringBuilder builder, LogEventInfo logEvent) { // Todo: Append details to StringBuilder } }   Now that we have a base layout renderer, we simply need to add the formatting logic to add exception details as well as inner exception details. This is done using reflection with some simple filtering for the properties that are already being rendered. I have added an additional 'Register' method, allowing the definition to be registered in code, rather than in configuration files. This complements by 'LogWrapper' class which standardizes writing log entries throughout my applications. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using NLog; using NLog.Config; using NLog.LayoutRenderers;   [ThreadAgnostic] [LayoutRenderer(Name)] public sealed class ExceptionDetailsRenderer : LayoutRenderer { public const string Name = "exceptiondetails"; private const string _Spacer = "======================================"; private List<string> _FilteredProperties;   private List<string> FilteredProperties { get { if (_FilteredProperties == null) { _FilteredProperties = new List<string> { "StackTrace", "HResult", "InnerException", "Data" }; }   return _FilteredProperties; } }   public bool LogNulls { get; set; }   protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Append(builder, logEvent.Exception, false); }   private void Append(StringBuilder builder, Exception exception, bool isInnerException) { if (exception == null) { return; }   builder.AppendLine();   var type = exception.GetType(); if (isInnerException) { builder.Append("Inner "); }   builder.AppendLine("Exception Details:") .AppendLine(_Spacer) .Append("Exception Type: ") .AppendLine(type.ToString());   var bindingFlags = BindingFlags.Instance | BindingFlags.Public; var properties = type.GetProperties(bindingFlags); foreach (var property in properties) { var propertyName = property.Name; var isFiltered = FilteredProperties.Any(filter => String.Equals(propertyName, filter, StringComparison.InvariantCultureIgnoreCase)); if (isFiltered) { continue; }   var propertyValue = property.GetValue(exception, bindingFlags, null, null, null); if (propertyValue == null && !LogNulls) { continue; }   var valueText = propertyValue != null ? propertyValue.ToString() : "NULL"; builder.Append(propertyName) .Append(": ") .AppendLine(valueText); }   AppendStackTrace(builder, exception.StackTrace, isInnerException); Append(builder, exception.InnerException, true); }   private void AppendStackTrace(StringBuilder builder, string stackTrace, bool isInnerException) { if (String.IsNullOrEmpty(stackTrace)) { return; }   builder.AppendLine();   if (isInnerException) { builder.Append("Inner "); }   builder.AppendLine("Exception StackTrace:") .AppendLine(_Spacer) .AppendLine(stackTrace); }   public static void Register() { Type definitionType; var layoutRenderers = ConfigurationItemFactory.Default.LayoutRenderers; if (layoutRenderers.TryGetDefinition(Name, out definitionType)) { return; }   layoutRenderers.RegisterDefinition(Name, typeof(ExceptionDetailsRenderer)); LogManager.ReconfigExistingLoggers(); } } For brevity I have removed the Trace, Debug, Warn, and Fatal methods. They are modelled after the Info methods. As mentioned above, note how the log wrapper automatically registers our custom layout renderer reducing the amount of application configuration required. using System; using NLog;   public static class LogWrapper { static LogWrapper() { ExceptionDetailsRenderer.Register(); }   #region Log Methods   public static void Info(object toLog) { Log(toLog, LogLevel.Info); }   public static void Info(string messageFormat, params object[] parameters) { Log(messageFormat, parameters, LogLevel.Info); }   public static void Error(object toLog) { Log(toLog, LogLevel.Error); }   public static void Error(string message, Exception exception) { Log(message, exception, LogLevel.Error); }   private static void Log(string messageFormat, object[] parameters, LogLevel logLevel) { string message = parameters.Length == 0 ? messageFormat : string.Format(messageFormat, parameters); Log(message, (Exception)null, logLevel); }   private static void Log(object toLog, LogLevel logLevel, LogType logType = LogType.General) { if (toLog == null) { throw new ArgumentNullException("toLog"); }   if (toLog is Exception) { var exception = toLog as Exception; Log(exception.Message, exception, logLevel, logType); } else { var message = toLog.ToString(); Log(message, null, logLevel, logType); } }   private static void Log(string message, Exception exception, LogLevel logLevel, LogType logType = LogType.General) { if (exception == null && String.IsNullOrEmpty(message)) { return; }   var logger = GetLogger(logType); // Note: Using the default constructor doesn't set the current date/time var logInfo = new LogEventInfo(logLevel, logger.Name, message); logInfo.Exception = exception; logger.Log(logInfo); }   private static Logger GetLogger(LogType logType) { var loggerName = logType.ToString(); return LogManager.GetLogger(loggerName); }   #endregion   #region LogType private enum LogType { General } #endregion } The following configuration is similar to what is provided for each of my applications. The 'application' variable is all that differentiates the various applications in all of my environments, the rest has been standardized. Depending on your needs to tweak this configuration while developing and debugging, this section could easily be pushed back into code similar to the registering of our custom layout renderer.   <?xml version="1.0"?>   <configuration> <configSections> <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/> </configSections> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <variable name="application" value="Example"/> <targets> <target type="EventLog" name="EventLog" source="${application}" log="${application}" layout="${message}${onexception: ${newline}${exceptiondetails}}"/> <target type="Mail" name="Email" smtpServer="smtp.example.local" from="[email protected]" to="[email protected]" subject="(${machinename}) ${application}: ${level}" body="Machine: ${machinename}${newline}Timestamp: ${longdate}${newline}Level: ${level}${newline}Message: ${message}${onexception: ${newline}${exceptiondetails}}"/> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="EventLog" /> <logger name="*" minlevel="Error" writeTo="Email" /> </rules> </nlog> </configuration>   Now go forward, create your custom exceptions without concern for including their custom properties in your exception logs and notifications.

    Read the article

  • Do I need to store a generic rotation point/radius for rotating around a point other than the origin for object transforms?

    - by Casey
    I'm having trouble implementing a non-origin point rotation. I have a class Transform that stores each component separately in three 3D vectors for position, scale, and rotation. This is fine for local rotations based on the center of the object. The issue is how do I determine/concatenate non-origin rotations in addition to origin rotations. Normally this would be achieved as a Transform-Rotate-Transform for the center rotation followed by a Transform-Rotate-Transform for the non-origin point. The problem is because I am storing the individual components, the final Transform matrix is not calculated until needed by using the individual components to fill an appropriate Matrix. (See GetLocalTransform()) Do I need to store an additional rotation (and radius) for world rotations as well or is there a method of implementation that works while only using the single rotation value? Transform.h #ifndef A2DE_CTRANSFORM_H #define A2DE_CTRANSFORM_H #include "../a2de_vals.h" #include "CMatrix4x4.h" #include "CVector3D.h" #include <vector> A2DE_BEGIN class Transform { public: Transform(); Transform(Transform* parent); Transform(const Transform& other); Transform& operator=(const Transform& rhs); virtual ~Transform(); void SetParent(Transform* parent); void AddChild(Transform* child); void RemoveChild(Transform* child); Transform* FirstChild(); Transform* LastChild(); Transform* NextChild(); Transform* PreviousChild(); Transform* GetChild(std::size_t index); std::size_t GetChildCount() const; std::size_t GetChildCount(); void SetPosition(const a2de::Vector3D& position); const a2de::Vector3D& GetPosition() const; a2de::Vector3D& GetPosition(); void SetRotation(const a2de::Vector3D& rotation); const a2de::Vector3D& GetRotation() const; a2de::Vector3D& GetRotation(); void SetScale(const a2de::Vector3D& scale); const a2de::Vector3D& GetScale() const; a2de::Vector3D& GetScale(); a2de::Matrix4x4 GetLocalTransform() const; a2de::Matrix4x4 GetLocalTransform(); protected: private: a2de::Vector3D _position; a2de::Vector3D _scale; a2de::Vector3D _rotation; std::size_t _curChildIndex; Transform* _parent; std::vector<Transform*> _children; }; A2DE_END #endif Transform.cpp #include "CTransform.h" #include "CVector2D.h" #include "CVector4D.h" A2DE_BEGIN Transform::Transform() : _position(), _scale(1.0, 1.0), _rotation(), _curChildIndex(0), _parent(nullptr), _children() { /* DO NOTHING */ } Transform::Transform(Transform* parent) : _position(), _scale(1.0, 1.0), _rotation(), _curChildIndex(0), _parent(parent), _children() { /* DO NOTHING */ } Transform::Transform(const Transform& other) : _position(other._position), _scale(other._scale), _rotation(other._rotation), _curChildIndex(0), _parent(other._parent), _children(other._children) { /* DO NOTHING */ } Transform& Transform::operator=(const Transform& rhs) { if(this == &rhs) return *this; this->_position = rhs._position; this->_scale = rhs._scale; this->_rotation = rhs._rotation; this->_curChildIndex = 0; this->_parent = rhs._parent; this->_children = rhs._children; return *this; } Transform::~Transform() { _children.clear(); _parent = nullptr; } void Transform::SetParent(Transform* parent) { _parent = parent; } void Transform::AddChild(Transform* child) { if(child == nullptr) return; _children.push_back(child); } void Transform::RemoveChild(Transform* child) { if(_children.empty()) return; _children.erase(std::remove(_children.begin(), _children.end(), child), _children.end()); } Transform* Transform::FirstChild() { if(_children.empty()) return nullptr; return *(_children.begin()); } Transform* Transform::LastChild() { if(_children.empty()) return nullptr; return *(_children.end()); } Transform* Transform::NextChild() { if(_children.empty()) return nullptr; std::size_t s(_children.size()); if(_curChildIndex >= s) { _curChildIndex = s; return nullptr; } return _children[_curChildIndex++]; } Transform* Transform::PreviousChild() { if(_children.empty()) return nullptr; if(_curChildIndex == 0) { return nullptr; } return _children[_curChildIndex--]; } Transform* Transform::GetChild(std::size_t index) { if(_children.empty()) return nullptr; if(index > _children.size()) return nullptr; return _children[index]; } std::size_t Transform::GetChildCount() const { if(_children.empty()) return 0; return _children.size(); } std::size_t Transform::GetChildCount() { return static_cast<const Transform&>(*this).GetChildCount(); } void Transform::SetPosition(const a2de::Vector3D& position) { _position = position; } const a2de::Vector3D& Transform::GetPosition() const { return _position; } a2de::Vector3D& Transform::GetPosition() { return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetPosition()); } void Transform::SetRotation(const a2de::Vector3D& rotation) { _rotation = rotation; } const a2de::Vector3D& Transform::GetRotation() const { return _rotation; } a2de::Vector3D& Transform::GetRotation() { return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetRotation()); } void Transform::SetScale(const a2de::Vector3D& scale) { _scale = scale; } const a2de::Vector3D& Transform::GetScale() const { return _scale; } a2de::Vector3D& Transform::GetScale() { return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetScale()); } a2de::Matrix4x4 Transform::GetLocalTransform() const { Matrix4x4 p((_parent ? _parent->GetLocalTransform() : a2de::Matrix4x4::GetIdentity())); Matrix4x4 t(a2de::Matrix4x4::GetTranslationMatrix(_position)); Matrix4x4 r(a2de::Matrix4x4::GetRotationMatrix(_rotation)); Matrix4x4 s(a2de::Matrix4x4::GetScaleMatrix(_scale)); return (p * t * r * s); } a2de::Matrix4x4 Transform::GetLocalTransform() { return static_cast<const Transform&>(*this).GetLocalTransform(); } A2DE_END

    Read the article

  • The View-Matrix and Alternative Calculations

    - by P. Avery
    I'm working on a radiosity processor in DirectX 9. The process requires that the camera be placed at the center of a mesh face and a 'screenshot' be taken facing 5 different directions...forward...up...down...left...right... ...The problem is that when the mesh face is facing up( look vector: 0, 1, 0 )...a view matrix cannot be determined using standard trigonometry functions: Matrix4 LookAt( Vector3 eye, Vector3 target, Vector3 up ) { // The "look-at" vector. Vector3 zaxis = normal(target - eye); // The "right" vector. Vector3 xaxis = normal(cross(up, zaxis)); // The "up" vector. Vector3 yaxis = cross(zaxis, xaxis); // Create a 4x4 orientation matrix from the right, up, and at vectors Matrix4 orientation = { xaxis.x, yaxis.x, zaxis.x, 0, xaxis.y, yaxis.y, zaxis.y, 0, xaxis.z, yaxis.z, zaxis.z, 0, 0, 0, 0, 1 }; // Create a 4x4 translation matrix by negating the eye position. Matrix4 translation = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -eye.x, -eye.y, -eye.z, 1 }; // Combine the orientation and translation to compute the view matrix return ( translation * orientation ); } The above function comes from http://3dgep.com/?p=1700... ...Is there a mathematical approach to this problem? Edit: A problem occurs when setting the view matrix to up or down directions, here is an example of the problem when facing down: D3DXVECTOR4 vPos( 3, 3, 3, 1 ), vEye( 1.5, 3, 3, 1 ), vLook( 0, -1, 0, 1 ), vRight( 1, 0, 0, 1 ), vUp( 0, 0, 1, 1 ); D3DXMATRIX mV, mP; D3DXMatrixPerspectiveFovLH( &mP, D3DX_PI / 2, 1, 0.5f, 2000.0f ); D3DXMatrixIdentity( &mV ); memcpy( ( void* )&mV._11, ( void* )&vRight, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._21, ( void* )&vUp, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._31, ( void* )&vLook, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._41, ( void* )&(-vEye), sizeof( D3DXVECTOR3 ) ); D3DXVec4Transform( &vPos, &vPos, &( mV * mP ) ); Results: vPos = D3DXVECTOR3( 1.5, -6, -0.5, 0 ) - this vertex is not properly processed by shader as the homogenous w value is 0 it cannot be normalized to a position within device space...

    Read the article

  • Setting useLegacyV2RuntimeActivationPolicy At Runtime

    - by Reed
    Version 4.0 of the .NET Framework included a new CLR which is almost entirely backwards compatible with the 2.0 version of the CLR.  However, by default, mixed-mode assemblies targeting .NET 3.5sp1 and earlier will fail to load in a .NET 4 application.  Fixing this requires setting useLegacyV2RuntimeActivationPolicy in your app.Config for the application.  While there are many good reasons for this decision, there are times when this is extremely frustrating, especially when writing a library.  As such, there are (rare) times when it would be beneficial to set this in code, at runtime, as well as verify that it’s running correctly prior to receiving a FileLoadException. Typically, loading a pre-.NET 4 mixed mode assembly is handled simply by changing your app.Config file, and including the relevant attribute in the startup element: <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup> </configuration> .csharpcode { background-color: #ffffff; font-family: consolas, "Courier New", courier, monospace; color: black; font-size: small } .csharpcode pre { background-color: #ffffff; font-family: consolas, "Courier New", courier, monospace; color: black; font-size: small } .csharpcode pre { margin: 0em } .csharpcode .rem { color: #008000 } .csharpcode .kwrd { color: #0000ff } .csharpcode .str { color: #006080 } .csharpcode .op { color: #0000c0 } .csharpcode .preproc { color: #cc6633 } .csharpcode .asp { background-color: #ffff00 } .csharpcode .html { color: #800000 } .csharpcode .attr { color: #ff0000 } .csharpcode .alt { background-color: #f4f4f4; margin: 0em; width: 100% } .csharpcode .lnum { color: #606060 } This causes your application to run correctly, and load the older, mixed-mode assembly without issues. For full details on what’s happening here and why, I recommend reading Mark Miller’s detailed explanation of this attribute and the reasoning behind it. Before I show any code, let me say: I strongly recommend using the official approach of using app.config to set this policy. That being said, there are (rare) times when, for one reason or another, changing the application configuration file is less than ideal. While this is the supported approach to handling this issue, the CLR Hosting API includes a means of setting this programmatically via the ICLRRuntimeInfo interface.  Normally, this is used if you’re hosting the CLR in a native application in order to set this, at runtime, prior to loading the assemblies.  However, the F# Samples include a nice trick showing how to load this API and bind this policy, at runtime.  This was required in order to host the Managed DirectX API, which is built against an older version of the CLR. This is fairly easy to port to C#.  Instead of a direct port, I also added a little addition – by trapping the COM exception received if unable to bind (which will occur if the 2.0 CLR is already bound), I also allow a runtime check of whether this property was setup properly: public static class RuntimePolicyHelper { public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; } static RuntimePolicyHelper() { ICLRRuntimeInfo clrRuntimeInfo = (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject( Guid.Empty, typeof(ICLRRuntimeInfo).GUID); try { clrRuntimeInfo.BindAsLegacyV2Runtime(); LegacyV2RuntimeEnabledSuccessfully = true; } catch (COMException) { // This occurs with an HRESULT meaning // "A different runtime was already bound to the legacy CLR version 2 activation policy." LegacyV2RuntimeEnabledSuccessfully = false; } } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")] private interface ICLRRuntimeInfo { void xGetVersionString(); void xGetRuntimeDirectory(); void xIsLoaded(); void xIsLoadable(); void xLoadErrorString(); void xLoadLibrary(); void xGetProcAddress(); void xGetInterface(); void xSetDefaultStartupFlags(); void xGetDefaultStartupFlags(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void BindAsLegacyV2Runtime(); } } Using this, it’s possible to not only set this at runtime, but also verify, prior to loading your mixed mode assembly, whether this will succeed. In my case, this was quite useful – I am working on a library purely for internal use which uses a numerical package that is supplied with both a completely managed as well as a native solver.  The native solver uses a CLR 2 mixed-mode assembly, but is dramatically faster than the pure managed approach.  By checking RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully at runtime, I can decide whether to enable the native solver, and only do so if I successfully bound this policy. There are some tricks required here – To enable this sort of fallback behavior, you must make these checks in a type that doesn’t cause the mixed mode assembly to be loaded.  In my case, this forced me to encapsulate the library I was using entirely in a separate class, perform the check, then pass through the required calls to that class.  Otherwise, the library will load before the hosting process gets enabled, which in turn will fail. This code will also, of course, try to enable the runtime policy before the first time you use this class – which typically means just before the first time you check the boolean value.  As a result, checking this early on in the application is more likely to allow it to work. Finally, if you’re using a library, this has to be called prior to the 2.0 CLR loading.  This will cause it to fail if you try to use it to enable this policy in a plugin for most third party applications that don’t have their app.config setup properly, as they will likely have already loaded the 2.0 runtime. As an example, take a simple audio player.  The code below shows how this can be used to properly, at runtime, only use the “native” API if this will succeed, and fallback (or raise a nicer exception) if this will fail: public class AudioPlayer { private IAudioEngine audioEngine; public AudioPlayer() { if (RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully) { // This will load a CLR 2 mixed mode assembly this.audioEngine = new AudioEngineNative(); } else { this.audioEngine = new AudioEngineManaged(); } } public void Play(string filename) { this.audioEngine.Play(filename); } } Now – the warning: This approach works, but I would be very hesitant to use it in public facing production code, especially for anything other than initializing your own application.  While this should work in a library, using it has a very nasty side effect: you change the runtime policy of the executing application in a way that is very hidden and non-obvious.

    Read the article

  • Navigating Libgdx Menu with arrow keys or controller

    - by Phil Royer
    I'm attempting to make my menu navigable with the arrow keys or via the d-pad on a controller. So Far I've had no luck. The question is: Can someone walk me through how to make my current menu or any libgdx menu keyboard accessible? I'm a bit noobish with some stuff and I come from a Javascript background. Here's an example of what I'm trying to do: http://dl.dropboxusercontent.com/u/39448/webgl/qb/qb.html For a simple menu that you can just add a few buttons to and it run out of the box use this: http://www.sadafnoor.com/blog/how-to-create-simple-menu-in-libgdx/ Or you can use my code but I use a lot of custom styles. And here's an example of my code: import aurelienribon.tweenengine.Timeline; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenManager; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.project.game.tween.ActorAccessor; public class MainMenu implements Screen { private SpriteBatch batch; private Sprite menuBG; private Stage stage; private TextureAtlas atlas; private Skin skin; private Table table; private TweenManager tweenManager; @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); menuBG.draw(batch); batch.end(); //table.debug(); stage.act(delta); stage.draw(); //Table.drawDebug(stage); tweenManager.update(delta); } @Override public void resize(int width, int height) { menuBG.setSize(width, height); stage.setViewport(width, height, false); table.invalidateHierarchy(); } @Override public void resume() { } @Override public void show() { stage = new Stage(); Gdx.input.setInputProcessor(stage); batch = new SpriteBatch(); atlas = new TextureAtlas("ui/atlas.pack"); skin = new Skin(Gdx.files.internal("ui/menuSkin.json"), atlas); table = new Table(skin); table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // Set Background Texture menuBackgroundTexture = new Texture("images/mainMenuBackground.png"); menuBG = new Sprite(menuBackgroundTexture); menuBG.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // Create Main Menu Buttons // Button Play TextButton buttonPlay = new TextButton("START", skin, "inactive"); buttonPlay.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { ((Game) Gdx.app.getApplicationListener()).setScreen(new LevelMenu()); } }); buttonPlay.addListener(new InputListener() { public boolean keyDown (InputEvent event, int keycode) { System.out.println("down"); return true; } }); buttonPlay.padBottom(12); buttonPlay.padLeft(20); buttonPlay.getLabel().setAlignment(Align.left); // Button EXTRAS TextButton buttonExtras = new TextButton("EXTRAS", skin, "inactive"); buttonExtras.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { ((Game) Gdx.app.getApplicationListener()).setScreen(new ExtrasMenu()); } }); buttonExtras.padBottom(12); buttonExtras.padLeft(20); buttonExtras.getLabel().setAlignment(Align.left); // Button Credits TextButton buttonCredits = new TextButton("CREDITS", skin, "inactive"); buttonCredits.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { ((Game) Gdx.app.getApplicationListener()).setScreen(new Credits()); } }); buttonCredits.padBottom(12); buttonCredits.padLeft(20); buttonCredits.getLabel().setAlignment(Align.left); // Button Settings TextButton buttonSettings = new TextButton("SETTINGS", skin, "inactive"); buttonSettings.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { ((Game) Gdx.app.getApplicationListener()).setScreen(new Settings()); } }); buttonSettings.padBottom(12); buttonSettings.padLeft(20); buttonSettings.getLabel().setAlignment(Align.left); // Button Exit TextButton buttonExit = new TextButton("EXIT", skin, "inactive"); buttonExit.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { Gdx.app.exit(); } }); buttonExit.padBottom(12); buttonExit.padLeft(20); buttonExit.getLabel().setAlignment(Align.left); // Adding Heading-Buttons to the cue table.add().width(190); table.add().width((table.getWidth() / 10) * 3); table.add().width((table.getWidth() / 10) * 5).height(140).spaceBottom(50); table.add().width(190).row(); table.add().width(190); table.add(buttonPlay).spaceBottom(20).width(460).height(110); table.add().row(); table.add().width(190); table.add(buttonExtras).spaceBottom(20).width(460).height(110); table.add().row(); table.add().width(190); table.add(buttonCredits).spaceBottom(20).width(460).height(110); table.add().row(); table.add().width(190); table.add(buttonSettings).spaceBottom(20).width(460).height(110); table.add().row(); table.add().width(190); table.add(buttonExit).width(460).height(110); table.add().row(); stage.addActor(table); // Animation Settings tweenManager = new TweenManager(); Tween.registerAccessor(Actor.class, new ActorAccessor()); // Heading and Buttons Fade In Timeline.createSequence().beginSequence() .push(Tween.set(buttonPlay, ActorAccessor.ALPHA).target(0)) .push(Tween.set(buttonExtras, ActorAccessor.ALPHA).target(0)) .push(Tween.set(buttonCredits, ActorAccessor.ALPHA).target(0)) .push(Tween.set(buttonSettings, ActorAccessor.ALPHA).target(0)) .push(Tween.set(buttonExit, ActorAccessor.ALPHA).target(0)) .push(Tween.to(buttonPlay, ActorAccessor.ALPHA, .5f).target(1)) .push(Tween.to(buttonExtras, ActorAccessor.ALPHA, .5f).target(1)) .push(Tween.to(buttonCredits, ActorAccessor.ALPHA, .5f).target(1)) .push(Tween.to(buttonSettings, ActorAccessor.ALPHA, .5f).target(1)) .push(Tween.to(buttonExit, ActorAccessor.ALPHA, .5f).target(1)) .end().start(tweenManager); tweenManager.update(Gdx.graphics.getDeltaTime()); } public static Vector2 getStageLocation(Actor actor) { return actor.localToStageCoordinates(new Vector2(0, 0)); } @Override public void dispose() { stage.dispose(); atlas.dispose(); skin.dispose(); menuBG.getTexture().dispose(); } @Override public void hide() { dispose(); } @Override public void pause() { } }

    Read the article

  • Sorting a Linked List [closed]

    - by Mohit Sehgal
    I want to sort a linked list. Here Node is class representing a node in a Linked List I have written a code to bubble sort a linked list. Program does not finishes execution. Kindly point out the mistakes. class Node { public: int data; public: Node *next; Node() { data=0;next=0; } Node(int d) { data=d; } void setData(int d) { data=d; } void print() { cout<<data<<endl; } bool operator==(Node n) { return this->data==n.data; } bool operator >(Node d) { if((this->data) > (d.data)) return true; return false; } }; class LList { public: int noOfNodes; Node *start;/*Header Node*/ LList() { start=new Node; noOfNodes=0;start=0; } void addAtFront(Node* n) { n->next=(start); start=n; noOfNodes++; } void addAtLast(Node* n) { Node *cur=(start); n->next=NULL; if(start==NULL) { start=n; noOfNodes++; return; } while(cur->next!=NULL) { cur=cur->next; } cur->next=n; noOfNodes++; } void addAtPos(Node *n,int pos) { if(pos==1) { addAtFront(n);return; } Node *cur=(start); Node *prev=NULL; int curPos=0; n->next=NULL; while(cur!=NULL) { curPos++; if(pos==curPos+1) { prev=cur; } if(pos==curPos) { n->next=cur; prev->next=n; break; } cur=cur->next; } noOfNodes++; } void removeFirst() { Node *del=start; start=start->next; delete del; noOfNodes--; return; } void removeLast() { Node *cur=start,*prev=NULL; while(cur->next!=NULL) { prev=cur; cur=cur->next; } prev->next=NULL; Node *del=cur->next; delete del; noOfNodes--; return; } void removeNodeAt(int pos) { if(pos<1) return; if(pos==1) { removeFirst();return;} int curPos=1; Node* cur=start->next; Node* prev=start; Node* del=NULL; while(curPos<pos&&cur!=NULL) { curPos++; if(curPos==pos) { del=cur; prev->next=cur->next; cur->next=NULL; delete del; noOfNodes--; break; } prev=prev->next; cur=cur->next; } } void removeNode(Node *d) { Node *cur=start; if(*d==*cur) { removeFirst();return; } cur=start->next; Node *prev=start,*del=NULL; while(cur!=NULL) { if(*cur==*d) { del=cur; prev->next=cur->next; delete del; noOfNodes--; break; } prev=prev->next; cur=cur->next; } } int getPosition(Node data) { int pos=0; Node *cur=(start); while(cur!=NULL) { pos++; if(*cur==data) { return pos; } cur=cur->next; } return -1;//not found } Node getNode(int pos) { if(pos<1) return -1;// not a valid position else if(pos>noOfNodes) return -1; // not a valid position Node *cur=(start); int curPos=0; while(cur!=NULL) { if(++curPos==pos) return *cur; cur=cur->next; } } void reverseList()//reverse the list { Node* cur=start->next; Node* d=NULL; Node* prev=start; while(cur!=NULL) { d=cur->next; cur->next=start; start=cur; prev->next=d; cur=d; } } void sortBubble() { Node *i=start,*j=start,*prev=NULL,*temp=NULL,*after=NULL; int count=noOfNodes-1;int icount=0; while(i->next!=NULL) { j=start; after=j->next; icount=0; while(++icount!=count) { if((*j)>(*after)) { temp=after->next; after->next=j; prev->next=j->next; j->next=temp; prev=after; after=j->next; } else{ prev=j; j=after; after=after->next; } } i=i->next; count--; } } void traverse() { Node *cur=(start); int c=0; while(cur!=NULL) { // cout<<"start"<<start; c++; cur->print(); cur=cur->next; } noOfNodes=c; } ~LList() { delete start; } }; int main() { int n; cin>>n; int d; LList list; Node *node; Node *temp=new Node(2123); for(int i=0;i<n;i++) { cin>>d; node=new Node(d); list.addAtLast(node); } list.addAtPos(temp,1); cout<<"traverse\n"; list.traverse(); temp=new Node(12); list.removeNode(temp); cout<<"12 removed"; list.traverse(); list.reverseList(); cout<<"\nreversed\n"; list.traverse(); cout<<"bubble sort\n"; list.sortBubble(); list.traverse(); getch(); delete node; return 0; }

    Read the article

  • how this code works and how to modify this code to get my desrire work? [closed]

    - by imon_bayazid
    I dont understand how these code works here : m_MouseHookManager.MouseDoubleClick+=HookManager_MouseDoubleClick; m_MouseHookManager.MouseDoubleClick -= HookManager_MouseDoubleClick; m_KeyboardHookManager.KeyPress +=HookManager_KeyPress; m_KeyboardHookManager.KeyPress -=HookManager_KeyPress; My full Code is here : using System; using System.Windows.Forms; using MouseKeyboardActivityMonitor.WinApi; namespace MouseKeyboardActivityMonitor.Demo { public partial class TestFormHookListeners : Form { private readonly KeyboardHookListener m_KeyboardHookManager; private readonly MouseHookListener m_MouseHookManager; public TestFormHookListeners() { InitializeComponent(); m_KeyboardHookManager = new KeyboardHookListener(new GlobalHooker()); // Hooks are not active after instantiation. You need to use either Enabled property or call Start()()()() method m_KeyboardHookManager.Enabled = true;//True - The Hook is presently installed, activated, and will fire events. m_MouseHookManager = new MouseHookListener(new GlobalHooker()); m_MouseHookManager.Enabled = true; } #region Check boxes to set or remove particular event handlers. private void checkBoxMouseDoubleClick_CheckedChanged(object sender, EventArgs e) { if (checkBoxMouseDoubleClick.Checked) { m_MouseHookManager.MouseDoubleClick += HookManager_MouseDoubleClick; } else { m_MouseHookManager.MouseDoubleClick -= HookManager_MouseDoubleClick; } } private void checkBoxKeyPress_CheckedChanged(object sender, EventArgs e) { if (checkBoxKeyPress.Checked) { m_KeyboardHookManager.KeyPress +=HookManager_KeyPress; } else { m_KeyboardHookManager.KeyPress -=HookManager_KeyPress; } } #endregion #region Event handlers of particular events. They will be activated when an appropriate checkbox is checked. private void HookManager_KeyPress(object sender, KeyPressEventArgs e) { Log(string.Format("KeyPress \t\t {0}\n", e.KeyChar)); } private void HookManager_MouseDoubleClick(object sender, MouseEventArgs e) { Log(string.Format("MouseDoubleClick \t\t {0}\n", e.Button)); } private void Log(string text) { textBoxLog.AppendText(text); textBoxLog.ScrollToCaret(); } #endregion private void checkBoxEnabled_CheckedChanged(object sender, EventArgs e) { m_MouseHookManager.Enabled = checkBoxEnabled.Checked; m_KeyboardHookManager.Enabled = checkBoxEnabled.Checked; } private void radioHooksType_CheckedChanged(object sender, EventArgs e) { Hooker hook; if (radioApplication.Checked) { hook = new AppHooker();//Provides methods for subscription and unsubscription to application mouse and keyboard hooks. } else { hook = new GlobalHooker();//Provides methods for subscription and unsubscription to global mouse and keyboard hooks. } m_KeyboardHookManager.Replace(hook); m_MouseHookManager.Replace(hook);//hook->An AppHooker or GlobalHooker object. //Enables you to switch from application hooks to global hooks //and vice versa on the fly without unsubscribing from events. //Component remains enabled or disabled state after this call as it was before. //Declaration Syntax } private void HookManager_Supress(object sender, MouseEventExtArgs e) { if (e.Button != MouseButtons.Right) { return; } Log("Suppressed.\n"); e.Handled = true; } } } Can anybody help to understand that??? I want by this that whenever a F5 key-pressed my application will be active and then it checks if double-click happen it gives a message .... **How can i modify that.....??????**

    Read the article

  • The code works but when using printf it gives me a weird answer. Help please [closed]

    - by user71458
    //Programmer-William Chen //Seventh Period Computer Science II //Problem Statement - First get the elapsed times and the program will find the //split times for the user to see. // //Algorithm- First the programmer makes the prototype and calls them in the //main function. The programmer then asks the user to input lap time data. //Secondly, you convert the splits into seconds and subtract them so you can //find the splits. Then the average is all the lap time's in seconds. Finally, //the programmer printf all the results for the user to see. #include <iostream> #include <stdlib.h> #include <math.h> #include <conio.h> #include <stdio.h> using namespace std; void thisgetsElapsedTimes( int &m1, int &m2, int &m3, int &m4, int &m5, int &s1, int &s2, int &s3, int &s4, int &s5); //this is prototype void thisconvertstoseconds ( int &m1, int &m2, int &m3, int &m4, int &m5, int &s1, int &s2, int &s3, int &s4, int &s5, int &split1, int &split2, int &split3, int &split4, int &split5);//this too void thisfindsSplits(int &m1, int &m2, int &m3, int &m4, int &m5, int &split1, int &split2, int &split3, int &split4, int &split5, int &split6, int &split7, int &split8, int &split9, int &split10);// this is part of prototype void thisisthesecondconversation (int &split1M, int &split2M, int &split3M, int &split4M, int &split5M, int &split1S,int &split2S, int &split3S, int &split4S, int &split5S, int &split1, int &split2, int &split3, int &split4, int &split5);//this gets a value void thisfindstheaverage(double &average, int &split1, int &split2, int &split3, int &split4, int &split5);//and this void thisprintsstuff( int &split1M, int &split2M, int &split3M, int &split4M, int &split5M, int &split1S, int &split2S, int &split3S, int &split4S, int &split5S, double &average); //this prints int main(int argc, char *argv[]) { int m1, m2, m3, m4, m5, s1, s2, s3, s4, s5, split1, split2, split3, split4, split5, split1M, split2M, split3M, split4M, split5M, split1S, split2S, split3S, split4S, split5S; int split6, split7, split8, split9, split10; double average; char thistakescolon; thisgetsElapsedTimes ( m1, m2, m3, m4, m5, s1, s2, s3, s4, s5); thisconvertstoseconds ( m1, m2, m3, m4, m5, s1, s2, s3, s4, s5, split1, split2, split3, split4, split5); thisfindsSplits ( m1, m2, m3, m4, m5, split1, split2, split3, split4, split5, split6, split7, split8, split9, split10); thisisthesecondconversation ( split1M, split2M, split3M, split4M, split5M, split1S, split2S, split3S, split4S, split5S, split1, split2, split3, split4, split5); thisfindstheaverage ( average, split1, split2, split3, split4, split5); thisprintsstuff ( split1M, split2M, split3M, split4M, split5M, split1S, split2S, split3S, split4S, split5S, average); // these are calling statements and they call from the main function to the other functions. system("PAUSE"); return 0; } void thisgetsElapsedTimes(int &m1, int &m2, int &m3, int &m4, int &m5, int &s1, int &s2, int &s3, int &s4, int &s5) { char thistakescolon; cout << "Enter the elapsed time:" << endl; cout << " Kilometer 1 "; cin m1 thistakescolon s1; cout << " Kilometer 2 "; cin m2 thistakescolon s2; cout << " Kilometer 3 " ; cin m3 thistakescolon s3; cout << " Kilometer 4 "; cin m4 thistakescolon s4; cout << " Kilometer 5 "; cin m5 thistakescolon s5; // this gets the data required to get the results needed for the user to see // . } void thisconvertstoseconds (int &m1, int &m2, int &m3, int &m4, int &m5, int &s1, int &s2, int &s3, int &s4, int &s5, int &split1, int &split2, int &split3, int &split4, int &split5) { split1 = (m1 * 60) + s1;//this converts for minutes to seconds for m1 split2 = (m2 * 60) + s2;//this converts for minutes to seconds for m2 split3 = (m3 * 60) + s3;//this converts for minutes to seconds for m3 split4 = (m4 * 60) + s4;//this converts for minutes to seconds for m4 split5 = (m5 * 60) + s5;//this converts for minutes to seconds for m5 } void thisfindsSplits (int &m1, int &m2, int &m3, int &m4, int &m5,int &split1, int &split2, int &split3, int &split4, int &split5, int &split6, int &split7, int &split8, int &split9, int &split10)//this is function heading { split6 = split1; //this is split for the first lap. split7 = split2 - split1;//this is split for the second lap. split8 = split3 - split2;//this is split for the third lap. split9 = split4 - split3;//this is split for the fourth lap. split10 = split5 - split4;//this is split for the fifth lap. } void thisfindstheaverage(double &average, int &split1, int &split2, int &split3, int &split4, int &split5) { average = (split1 + split2 + split3 + split4 + split5)/5; // this finds the average from all the splits in seconds } void thisisthesecondconversation (int &split1M, int &split2M, int &split3M, int &split4M, int &split5M, int &split1S,int &split2S, int &split3S, int &split4S, int &split5S, int &split1, int &split2, int &split3, int &split4, int &split5) { split1M = split1 * 60; //this finds the split times split1S = split1M - split1 * 60; //then this finds split2M = split2 * 60; //and all of this split2S = split2M - split2 * 60; //does basically split3M = split3 * 60; //the same thing split3S = split3M - split3 * 60; //all of it split4M = split4 * 60; //it's also a split4S = split4M - split4 * 60; //function split5M = split5 * 60; //and it finds the splits split5S = split5M - split5 * 60; //for each lap. } void thisprintsstuff (int &split1M, int &split2M, int &split3M, int &split4M, int &split5M, int &split1S, int &split2S, int &split3S, int &split4S, int &split5S, double &average)// this is function heading { printf("\n kilometer 1 %d" , ":02%d",'split1M','split1S'); printf("\n kilometer 2 %d" , ":02%d",'split2M','split2S'); printf("\n kilometer 3 %d" , ":02%d",'split3M','split3S'); printf("\n kilometer 4 %d" , ":02%d",'split4M','split4S'); printf("\n kilometer 5 %d" , ":02%d",'split5M','split5S'); printf("\n your average pace is ",'average',"per kilometer \n", "William Chen\n"); // this printf so the programmer // can allow the user to see // the results from the data gathered. }

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >