Search Results

Search found 6094 results on 244 pages for 'double gras'.

Page 73/244 | < Previous Page | 69 70 71 72 73 74 75 76 77 78 79 80  | Next Page >

  • c# Find value in a range using lambda

    - by n4rzul
    I'm trying to find an item in a list of values based on another value using a lambda expression using the Find method. In this example I'm expecting to get back -1000, but for the life of me, I just can't come up with the proper lamda expression. If that sounds confusing I hope the code and comments below explain it better. TIA. using System; using System.Collections.Generic; namespace TestingStuff { class Program { static void Main(string[] args) { double amount = -200; //The Range of values List<MyValue> values = new List<MyValue>(); values.Add(new MyValue(-1000)); values.Add(new MyValue(-100)); values.Add(new MyValue(-10)); values.Add(new MyValue(0)); values.Add(new MyValue(100)); values.Add(new MyValue(1000)); //Find it!!! MyValue fVal = values.Find(x => (x.Value > amount) && (x.Value < amount)); //Expecting -1000 as a result here since -200 falls between -1000 and -100 //if it were -90 I'd expect -100 since it falls between -100 and 0 if (fVal != null) Console.WriteLine(fVal.Value); Console.ReadKey(); } } public class MyValue { public double Value { get; set; } public MyValue(double value) { Value = value; } } }

    Read the article

  • How do I conditionally compile C code snippets to my Perl module?

    - by mobrule
    I have a module that will target several different operating systems and configurations. Sometimes, some C code can make this module's task a little easier, so I have some C functions that I would like to bind the code. I don't have to bind the C functions -- I can't guarantee that the end-user even has a C compiler, for instance, and it's generally not a problem to failover gracefully to a pure Perl way of accomplishing the same thing -- but it would be nice if I could call the C functions from the Perl script. Still with me? Here's another tricky part. Just about all of the C code is system specific -- a function written for Windows won't compile on Linux and vice-versa, and the function that does a similar thing on Solaris will look totally different. #include <some/Windows/headerfile.h> int foo_for_Windows_c(int a,double b) { do_windows_stuff(); return 42; } #include <path/to/linux/headerfile.h> int foo_for_linux_c(int a,double b) { do_linux_stuff(7); return 42; } Furthermore, even for native code that targets the same system, it's possible that only some of them can be compiled on any particular configuration. #include <some/headerfile/that/might/not/even/exist.h> int bar_for_solaris_c(int a,double b) { call_solaris_library_that_might_be_installed_here(11); return 19; } But ideally we could still use the C functions that would compile with that configuration. So my questions are: how can I compile C functions conditionally (compile only the code that is appropriate for the current value of $^O)? how can I compile C functions individually (some functions might not compile, but we still want to use the ones that can)? can I do this at build-time (while the end-user is installing the module) or at run-time (with Inline::C, for example)? Which way is better? how would I tell which functions were successfully compiled and are available for use from Perl? All thoughts appreciated!

    Read the article

  • Outer product using CBLAS

    - by The Dude
    I am having trouble utilizing CBLAS to perform an Outer Product. My code is as follows: //===SET UP===// double x1[] = {1,2,3,4}; double x2[] = {1,2,3}; int dx1 = 4; int dx2 = 3; double X[dx1 * dx2]; for (int i = 0; i < (dx1*dx2); i++) {X[i] = 0.0;} //===DO THE OUTER PRODUCT===// cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, dx1, dx2, 1, 1.0, x1, dx1, x2, 1, 0.0, X, dx1); //===PRINT THE RESULTS===// printf("\nMatrix X (%d x %d) = x1 (*) x2 is:\n", dx1, dx2); for (i=0; i<4; i++) { for (j=0; j<3; j++) { printf ("%lf ", X[j+i*3]); } printf ("\n"); } I get: Matrix X (4 x 3) = x1 (*) x2 is: 1.000000 2.000000 3.000000 0.000000 -1.000000 -2.000000 -3.000000 0.000000 7.000000 14.000000 21.000000 0.000000 But the correct answer is found here: https://www.sharcnet.ca/help/index.php/BLAS_and_CBLAS_Usage_and_Examples I have seen: Efficient computation of kronecker products in C But, it doesn't help me because they don't actually say how to utilize dgemm to actually do this... Any help? What am I doing wrong here?

    Read the article

  • How do I select every 6th element from a list (using Linq)

    - by iDog
    Hi, I've got a list of 'double' values. I need to select every 6th record. It's a list of coordinates, where I need to get the minimum and maximum value of every 6th value. List of coordinates (sample): [2.1, 4.3, 1.0, 7.1, 10.6, 39.23, 0.5, ... ] with hundrets of coordinates. Result should look like: [x_min, y_min, z_min, x_max, y_max, z_max] with exactly 6 coordinates. Following code works, but it takes to long to iterate over all coordinates. I'd like to use Linq instead (maybe faster?) for (int i = 0; i < 6; i++) { List<double> coordinateRange = new List<double>(); for (int j = i; j < allCoordinates.Count(); j = j + 6) coordinateRange.Add(allCoordinates[j]); if (i < 3) boundingBox.Add(coordinateRange.Min()); else boundingBox.Add(coordinateRange.Max()); } Any suggestions? Many thanks! Greets!

    Read the article

  • Efficiently get the size of a parameter pack up to a certain index

    - by NmdMystery
    I want to be able to determine the number of bytes that are in a subset of a parameter pack from 0 to a given index. Right now I'm using a non-constexpr way of doing this. Below is my code: template <size_t index, typename... args> struct pack_size_index; template <size_t index, typename type_t, typename... args> struct pack_size_index <index, type_t, args...> { static const size_t index_v = index; static const size_t value(void) { if (index_v > 0) { return sizeof(type_t) + pack_size_index<index - 1, args...>::value(); } return 0; } }; template <size_t index> struct pack_size_index <index> { static const size_t index_v = index; static const size_t value(void) { return 0; } }; Usage: //output: 5 (equal to 1 + 4) std::cout << pack_size_index<2, bool, float, int, double>::value() << std::endl; //output: 20 (equal to 8 + 8 + 4) std::cout << pack_size_index<3, double, double, float, int>::value() << std::endl; This gets the job done, but this uses runtime comparison and the resulting executable increases in size rapidly whenever this is used. What's a less expensive way of doing this?

    Read the article

  • Python server open all ports

    - by user1670178
    I am trying to open all ports using this code, why can I not create a loop to perform this function? http://www.kellbot.com/2010/02/tutorial-writing-a-tcp-server-in-python/ #!/usr/bin/python # This is server.py file ##server.py from socket import * #import the socket library n=1025 while n<1050: ##let's set up some constants HOST = '' #we are the host PORT = n #arbitrary port not currently in use ADDR = (HOST,PORT) #we need a tuple for the address BUFSIZE = 4096 #reasonably sized buffer for data ## now we create a new socket object (serv) ## see the python docs for more information on the socket types/flags serv = socket( AF_INET,SOCK_STREAM) ##bind our socket to the address serv.bind((ADDR)) #the double parens are to create a tuple with one element serv.listen(5) #5 is the maximum number of queued connections we'll allow serv = socket( AF_INET,SOCK_STREAM) ##bind our socket to the address serv.bind((ADDR)) #the double parens are to create a tuple with one element serv.listen(5) #5 is the maximum number of queued connections we'll allow print 'listening...' n=n+1 conn,addr = serv.accept() #accept the connection print '...connected!' conn.send('TEST') conn.close() How do I make this work so that I can specify input range and have the server open all ports up to 65535? #!/usr/bin/python # This is server.py file from socket import * #import the socket library startingPort=input("\nPlease enter starting port: ") startingPort=int(startingPort) #print startingPort def connection(): ## let's set up some constants HOST = '' #we are the host PORT = startingPort #arbitrary port not currently in use ADDR = (HOST,PORT) #we need a tuple for the address BUFSIZE = 4096 #reasonably sized buffer for data def socketObject(): ## now we create a new socket object (serv) serv = socket( AF_INET,SOCK_STREAM) def bind(): ## bind our socket to the address serv = socket( AF_INET,SOCK_STREAM) serv.bind((ADDR)) #the double parens are to create a tuple with one element serv.listen(5) #5 is the maximum number of queued connections we'll allow serv = socket( AF_INET,SOCK_STREAM) print 'listening...' def accept(): conn,addr = serv.accept() #accept the connection print '...connected!' conn.send('TEST') def close(): conn.close() ## Main while startingPort<65535: connection() socketObject() bind() accept() startingPort=startingPort+1

    Read the article

  • Java reflection Method invocations yield result faster than Fields?

    - by omerkudat
    I was microbenchmarking some code (please be nice) and came across this puzzle: when reading a field using reflection, invoking the getter Method is faster than reading the Field. Simple test class: private static final class Foo { public Foo(double val) { this.val = val; } public double getVal() { return val; } public final double val; // only public for demo purposes } We have two reflections: Method m = Foo.class.getDeclaredMethod("getVal", null); Field f = Foo.class.getDeclaredField("val"); Now I call the two reflections in a loop, invoke on the Method, and get on the Field. A first run is done to warm up the VM, a second run is done with 10M iterations. The Method invocation is consistently 30% faster, but why? Note that getDeclaredMethod and getDeclaredField are not called in the loop. They are called once and executed on the same object in the loop. I also tried some minor variations: made the field non-final, transitive, non-public, etc. All of these combinations resulted in statistically similar performance. Edit: This is on WinXP, Intel Core2 Duo, Sun JavaSE build 1.6.0_16-b01, running under jUnit4 and Eclipse.

    Read the article

  • How can I put back a character that I've read when I detect it's the start of a new row?

    - by gcc
    char nm; int i=0; double thelow, theupp; double numbers[200]; for(i=0;i<4;++i) { { char nm; double thelow,theupp; /*after erased ,created again*/ scanf("%c %lf %lf", &nm, &thelow, &theupp); for (k = 0; ; ++k) ; { scanf("%lf",numbers[k]); if(numbers[k]=='\n') break; } /*calling function and sending data(nm,..) to it*/ } /*after } is seen (nm ..) is erased*/ ; } I want say compiler : hey my dear code read only i-th row,dont touch characters at placed in next line. because characters at placed in next line is token after i increased by 1 and nm ,thelow,theupp is being zero or erased after then again created. how can I do ? input; D -1.5 0.5 .012 .025 .05 .1 .1 .1 .025 .012 0 0 0 .012 .025 .1 .2 .1 .05 .039 .025 .025 B 1 3 .117 .058 .029 .015 .007 .007 .007 .015 .022 .029 .036 .044 .051 .058 .066 .073 .080 .088 .095 .103

    Read the article

  • Avoiding instanceof in Java

    - by Mark Lutton
    Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism". How would I do it in this case? There are a number of subclasses of a base class; none of them are under my control. An analogous situation would be with the Java classes Integer, Double, BigDecimal etc. if (obj instanceof Integer) {NumberStuff.handle((Integer)obj);} else if (obj instanceof BigDecimal) {BigDecimalStuff.handle((BigDecimal)obj);} else if (obj instanceof Double) {DoubleStuff.handle((Double)obj);} I do have control over NumberStuff and so on. I don't want to use many lines of code where a few lines would do. (Sometimes I make a HashMap mapping Integer.class to an instance of IntegerStuff, BigDecimal.class to an instance of BigDecimalStuff etc. But today I want something simpler.) I'd like something as simple as this: public static handle(Integer num) { ... } public static handle(BigDecimal num) { ... } But Java just doesn't work that way. I'd like to use static methods when formatting. The things I'm formatting are composite, where a Thing1 can contain an array Thing2s and a Thing2 can contain an array of Thing1s. I had a problem when I implemented my formatters like this: class Thing1Formatter { private static Thing2Formatter thing2Formatter = new Thing2Formatter(); public format(Thing thing) { thing2Formatter.format(thing.innerThing2); } } class Thing2Formatter { private static Thing1Formatter thing1Formatter = new Thing1Formatter(); public format(Thing2 thing) { thing1Formatter.format(thing.innerThing1); } } Yes, I know the HashMap and a bit more code can fix that too. But the "instanceof" seems so readable and maintainable by comparison. Is there anything simple but not smelly?

    Read the article

  • correct method "get next value"

    - by kapec
    Hello!! i need your help! this is my code, it not so good as i wander - it is not working. i have not idea anymore. </code>// need to get next parameter static double getParametr(){ Scanner scanner = new Scanner(System.in); param = scanner.nextDouble(); return param; } .......... ................ if (i==1){ System.out.println("vvedite storoni pryamougolnika: "); Shape parA = new Rectangle(); parA.a = Shape.getParametr(); --- this is ok double aa = parA.a; Shape parB = new Rectangle(); parB.b = Shape.getParametr(); ------ this is no work!!! double bb = parB.b; Rectangle rec = new Rectangle(aa, bb); arrayFigur[i] = rec.area(); } how fix mistake?

    Read the article

  • Help with Collision Resolution?

    - by Milo
    I'm trying to learn about physics by trying to make a simplified GTA 2 clone. My only problem is collision resolution. Everything else works great. I have a rigid body class and from there cars and a wheel class: class RigidBody extends Entity { //linear private Vector2D velocity = new Vector2D(); private Vector2D forces = new Vector2D(); private OBB2D predictionRect = new OBB2D(new Vector2D(), 1.0f, 1.0f, 0.0f); private float mass; private Vector2D deltaVec = new Vector2D(); private Vector2D v = new Vector2D(); //angular private float angularVelocity; private float torque; private float inertia; //graphical private Vector2D halfSize = new Vector2D(); private Bitmap image; private Matrix mat = new Matrix(); private float[] Vector2Ds = new float[2]; private Vector2D tangent = new Vector2D(); private static Vector2D worldRelVec = new Vector2D(); private static Vector2D relWorldVec = new Vector2D(); private static Vector2D pointVelVec = new Vector2D(); public RigidBody() { //set these defaults so we don't get divide by zeros mass = 1.0f; inertia = 1.0f; setLayer(LAYER_OBJECTS); } protected void rectChanged() { if(getWorld() != null) { getWorld().updateDynamic(this); } } //intialize out parameters public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //store physical parameters this.halfSize = halfSize; this.mass = mass; image = bitmap; inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass; RectF rect = new RectF(); float scalar = 10.0f; rect.left = (int)-halfSize.x * scalar; rect.top = (int)-halfSize.y * scalar; rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar); rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar); setRect(rect); predictionRect.set(rect); } public void setLocation(Vector2D position, float angle) { getRect().set(position, getWidth(), getHeight(), angle); rectChanged(); } public void setPredictionLocation(Vector2D position, float angle) { getPredictionRect().set(position, getWidth(), getHeight(), angle); } public void setPredictionCenter(Vector2D center) { getPredictionRect().moveTo(center); } public void setPredictionAngle(float angle) { predictionRect.setAngle(angle); } public Vector2D getPosition() { return getRect().getCenter(); } public OBB2D getPredictionRect() { return predictionRect; } @Override public void update(float timeStep) { doUpdate(false,timeStep); } public void doUpdate(boolean prediction, float timeStep) { //integrate physics //linear Vector2D acceleration = Vector2D.scalarDivide(forces, mass); if(prediction) { Vector2D velocity = Vector2D.add(this.velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); c = Vector2D.add(getRect().getCenter(), Vector2D.scalarMultiply(velocity , timeStep)); setPredictionCenter(c); //forces = new Vector2D(0,0); //clear forces } else { velocity.x += (acceleration.x * timeStep); velocity.y += (acceleration.y * timeStep); //velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); v.x = getRect().getCenter().getX() + (velocity.x * timeStep); v.y = getRect().getCenter().getY() + (velocity.y * timeStep); deltaVec.x = v.x - c.x; deltaVec.y = v.y - c.y; deltaVec.normalize(); setCenter(v.x, v.y); forces.x = 0; //clear forces forces.y = 0; } //angular float angAcc = torque / inertia; if(prediction) { float angularVelocity = this.angularVelocity + angAcc * timeStep; setPredictionAngle(getAngle() + angularVelocity * timeStep); //torque = 0; //clear torque } else { angularVelocity += angAcc * timeStep; setAngle(getAngle() + angularVelocity * timeStep); torque = 0; //clear torque } } public void updatePrediction(float timeStep) { doUpdate(true, timeStep); } //take a relative Vector2D and make it a world Vector2D public Vector2D relativeToWorld(Vector2D relative) { mat.reset(); Vector2Ds[0] = relative.x; Vector2Ds[1] = relative.y; mat.postRotate(JMath.radToDeg(getAngle())); mat.mapVectors(Vector2Ds); relWorldVec.x = Vector2Ds[0]; relWorldVec.y = Vector2Ds[1]; return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //take a world Vector2D and make it a relative Vector2D public Vector2D worldToRelative(Vector2D world) { mat.reset(); Vector2Ds[0] = world.x; Vector2Ds[1] = world.y; mat.postRotate(JMath.radToDeg(-getAngle())); mat.mapVectors(Vector2Ds); return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //velocity of a point on body public Vector2D pointVelocity(Vector2D worldOffset) { tangent.x = -worldOffset.y; tangent.y = worldOffset.x; return Vector2D.add( Vector2D.scalarMultiply(tangent, angularVelocity) , velocity); } public void applyForce(Vector2D worldForce, Vector2D worldOffset) { //add linear force forces.x += worldForce.x; forces.y += worldForce.y; //add associated torque torque += Vector2D.cross(worldOffset, worldForce); } @Override public void draw( GraphicsContext c) { c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y, getWidth(), getHeight(), getAngle()); } public Vector2D getVelocity() { return velocity; } public void setVelocity(Vector2D velocity) { this.velocity = velocity; } public Vector2D getDeltaVec() { return deltaVec; } } Vehicle public class Wheel { private Vector2D forwardVec; private Vector2D sideVec; private float wheelTorque; private float wheelSpeed; private float wheelInertia; private float wheelRadius; private Vector2D position = new Vector2D(); public Wheel(Vector2D position, float radius) { this.position = position; setSteeringAngle(0); wheelSpeed = 0; wheelRadius = radius; wheelInertia = (radius * radius) * 1.1f; } public void setSteeringAngle(float newAngle) { Matrix mat = new Matrix(); float []vecArray = new float[4]; //forward Vector vecArray[0] = 0; vecArray[1] = 1; //side Vector vecArray[2] = -1; vecArray[3] = 0; mat.postRotate(newAngle / (float)Math.PI * 180.0f); mat.mapVectors(vecArray); forwardVec = new Vector2D(vecArray[0], vecArray[1]); sideVec = new Vector2D(vecArray[2], vecArray[3]); } public void addTransmissionTorque(float newValue) { wheelTorque += newValue; } public float getWheelSpeed() { return wheelSpeed; } public Vector2D getAnchorPoint() { return position; } public Vector2D calculateForce(Vector2D relativeGroundSpeed, float timeStep, boolean prediction) { //calculate speed of tire patch at ground Vector2D patchSpeed = Vector2D.scalarMultiply(Vector2D.scalarMultiply( Vector2D.negative(forwardVec), wheelSpeed), wheelRadius); //get velocity difference between ground and patch Vector2D velDifference = Vector2D.add(relativeGroundSpeed , patchSpeed); //project ground speed onto side axis Float forwardMag = new Float(0.0f); Vector2D sideVel = velDifference.project(sideVec); Vector2D forwardVel = velDifference.project(forwardVec, forwardMag); //calculate super fake friction forces //calculate response force Vector2D responseForce = Vector2D.scalarMultiply(Vector2D.negative(sideVel), 2.0f); responseForce = Vector2D.subtract(responseForce, forwardVel); float topSpeed = 500.0f; //calculate torque on wheel wheelTorque += forwardMag * wheelRadius; //integrate total torque into wheel wheelSpeed += wheelTorque / wheelInertia * timeStep; //top speed limit (kind of a hack) if(wheelSpeed > topSpeed) { wheelSpeed = topSpeed; } //clear our transmission torque accumulator wheelTorque = 0; //return force acting on body return responseForce; } public void setTransmissionTorque(float newValue) { wheelTorque = newValue; } public float getTransmissionTourque() { return wheelTorque; } public void setWheelSpeed(float speed) { wheelSpeed = speed; } } //our vehicle object public class Vehicle extends RigidBody { private Wheel [] wheels = new Wheel[4]; private boolean throttled = false; public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //front wheels wheels[0] = new Wheel(new Vector2D(halfSize.x, halfSize.y), 0.45f); wheels[1] = new Wheel(new Vector2D(-halfSize.x, halfSize.y), 0.45f); //rear wheels wheels[2] = new Wheel(new Vector2D(halfSize.x, -halfSize.y), 0.75f); wheels[3] = new Wheel(new Vector2D(-halfSize.x, -halfSize.y), 0.75f); super.initialize(halfSize, mass, bitmap); } public void setSteering(float steering) { float steeringLock = 0.13f; //apply steering angle to front wheels wheels[0].setSteeringAngle(steering * steeringLock); wheels[1].setSteeringAngle(steering * steeringLock); } public void setThrottle(float throttle, boolean allWheel) { float torque = 85.0f; throttled = true; //apply transmission torque to back wheels if (allWheel) { wheels[0].addTransmissionTorque(throttle * torque); wheels[1].addTransmissionTorque(throttle * torque); } wheels[2].addTransmissionTorque(throttle * torque); wheels[3].addTransmissionTorque(throttle * torque); } public void setBrakes(float brakes) { float brakeTorque = 15.0f; //apply brake torque opposing wheel vel for (Wheel wheel : wheels) { float wheelVel = wheel.getWheelSpeed(); wheel.addTransmissionTorque(-wheelVel * brakeTorque * brakes); } } public void doUpdate(float timeStep, boolean prediction) { for (Wheel wheel : wheels) { float wheelVel = wheel.getWheelSpeed(); //apply negative force to naturally slow down car if(!throttled && !prediction) wheel.addTransmissionTorque(-wheelVel * 0.11f); Vector2D worldWheelOffset = relativeToWorld(wheel.getAnchorPoint()); Vector2D worldGroundVel = pointVelocity(worldWheelOffset); Vector2D relativeGroundSpeed = worldToRelative(worldGroundVel); Vector2D relativeResponseForce = wheel.calculateForce(relativeGroundSpeed, timeStep,prediction); Vector2D worldResponseForce = relativeToWorld(relativeResponseForce); applyForce(worldResponseForce, worldWheelOffset); } //no throttling yet this frame throttled = false; if(prediction) { super.updatePrediction(timeStep); } else { super.update(timeStep); } } @Override public void update(float timeStep) { doUpdate(timeStep,false); } public void updatePrediction(float timeStep) { doUpdate(timeStep,true); } public void inverseThrottle() { float scalar = 0.2f; for(Wheel wheel : wheels) { wheel.setTransmissionTorque(-wheel.getTransmissionTourque() * scalar); wheel.setWheelSpeed(-wheel.getWheelSpeed() * 0.1f); } } } And my big hack collision resolution: private void update() { camera.setPosition((vehicle.getPosition().x * camera.getScale()) - ((getWidth() ) / 2.0f), (vehicle.getPosition().y * camera.getScale()) - ((getHeight() ) / 2.0f)); //camera.move(input.getAnalogStick().getStickValueX() * 15.0f, input.getAnalogStick().getStickValueY() * 15.0f); if(input.isPressed(ControlButton.BUTTON_GAS)) { vehicle.setThrottle(1.0f, false); } if(input.isPressed(ControlButton.BUTTON_STEAL_CAR)) { vehicle.setThrottle(-1.0f, false); } if(input.isPressed(ControlButton.BUTTON_BRAKE)) { vehicle.setBrakes(1.0f); } vehicle.setSteering(input.getAnalogStick().getStickValueX()); //vehicle.update(16.6666666f / 1000.0f); boolean colided = false; vehicle.updatePrediction(16.66666f / 1000.0f); List<Entity> buildings = world.queryStaticSolid(vehicle,vehicle.getPredictionRect()); if(buildings.size() > 0) { colided = true; } if(!colided) { vehicle.update(16.66f / 1000.0f); } else { Vector2D delta = vehicle.getDeltaVec(); vehicle.setVelocity(Vector2D.negative(vehicle.getVelocity().multiply(0.2f)). add(delta.multiply(-1.0f))); vehicle.inverseThrottle(); } } Here is OBB public class OBB2D { // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(Vector2D center, float w, float h, float angle) { set(center,w,h,angle); } public OBB2D(float left, float top, float width, float height) { set(new Vector2D(left + (width / 2), top + (height / 2)),width,height,0.0f); } public void set(Vector2D center,float w, float h,float angle) { Vector2D X = new Vector2D( (float)Math.cos(angle), (float)Math.sin(angle)); Vector2D Y = new Vector2D((float)-Math.sin(angle), (float)Math.cos(angle)); X = X.multiply( w / 2); Y = Y.multiply( h / 2); corner[0] = center.subtract(X).subtract(Y); corner[1] = center.add(X).subtract(Y); corner[2] = center.add(X).add(Y); corner[3] = center.subtract(X).add(Y); computeAxes(); extents.x = w / 2; extents.y = h / 2; computeDimensions(center,angle); } private void computeDimensions(Vector2D center,float angle) { this.center.x = center.x; this.center.y = center.y; this.angle = angle; boundingRect.left = Math.min(Math.min(corner[0].x, corner[3].x), Math.min(corner[1].x, corner[2].x)); boundingRect.top = Math.min(Math.min(corner[0].y, corner[1].y),Math.min(corner[2].y, corner[3].y)); boundingRect.right = Math.max(Math.max(corner[1].x, corner[2].x), Math.max(corner[0].x, corner[3].x)); boundingRect.bottom = Math.max(Math.max(corner[2].y, corner[3].y),Math.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(new Vector2D(rect.centerX(),rect.centerY()),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0] = corner[1].subtract(corner[0]); axis[1] = corner[3].subtract(corner[0]); // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { axis[a] = axis[a].divide((axis[a].length() * axis[a].length())); origin[a] = corner[0].dot(axis[a]); } } public void moveTo(Vector2D center) { Vector2D centroid = (corner[0].add(corner[1]).add(corner[2]).add(corner[3])).divide(4.0f); Vector2D translation = center.subtract(centroid); for (int c = 0; c < 4; ++c) { corner[c] = corner[c].add(translation); } computeAxes(); computeDimensions(center,angle); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } }; What I do is when I predict a hit on the car, I force it back. It does not work that well and seems like a bad idea. What could I do to have more proper collision resolution. Such that if I hit a wall I will never get stuck in it and if I hit the side of a wall I can steer my way out of it. Thanks I found this nice ppt. It talks about pulling objects apart and calculating new velocities. How could I calc new velocities in my case? http://www.google.ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CC8QFjAB&url=http%3A%2F%2Fcoitweb.uncc.edu%2F~tbarnes2%2FGameDesignFall05%2FSlides%2FCh4.2-CollDet.ppt&ei=x4ucULy5M6-N0QGRy4D4Cg&usg=AFQjCNG7FVDXWRdLv8_-T5qnFyYld53cTQ&cad=rja

    Read the article

  • Lock application window movement on Mac

    - by Martin Tóth
    Sometimes, when I use touchpad to control cursor and I'm clicking or double clicking, I move the application window a few pixels because my finger does not tap the touchpad on one place. Is there a way (Mac OS X) to lock application window, so that it can't be moved with cursor unless unlocked again? Is there another way to solve this? (Besides me being more careful when double clicking...) Edit: Is there even an attribute of "window object" that can lock it's position? I can try to write an App that handles just that (or a script run every time I run Application which I want to lock windows for). If there isn't would an OS X Application that "watches" windows movements and counters them (moves back) be hard to code?

    Read the article

  • OpenGL/SharpGL - Points only on -near surface of Ortho projection?

    - by FTLPhysicsGuy
    When you create points using three dimensions for each point and you use an Ortho projection to view the points, would there be a reason that only the points on the -near surface would appear? For example, if you use (the SharpGL method) gl.Ortho(0, width, height, 0, -10, 10), only the points at z=10 (because the near surface is at -10) actually show up. I'm currently using SharpGL - but I'm hoping the issue I'm having isn't with that particular implementation/library. EDIT: I'm adding the code below that demonstrates the issue. Note that this example requires SharpGL and is in fact a modification of a WPF sample project that comes with the current SharpGL source code (the original sample project is called TwoDSample). The project requires a MainWindow.xaml and a MainWindow.xaml.cs. Here's the xaml: <Window x:Class="TwoDSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:SharpGL.WPF;assembly=SharpGL.WPF"> <Grid> <my:OpenGLControl Name="openGLControl1" OpenGLDraw="openGLControl1_OpenGLDraw" OpenGLInitialized="openGLControl1_OpenGLInitialized" Resized="openGLControl1_Resized"/> </Grid> </Window> Here is the code behind: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using SharpGL.Enumerations; namespace TwoDSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } // NOTE: I use this to restrict the openGLControl1_OpenGLDraw method to // drawing only once after m_drawCount is set to zero; int m_drawCount = 0; private void openGLControl1_OpenGLDraw(object sender, SharpGL.SceneGraph.OpenGLEventArgs args) { // NOTE: Only draw once after m_drawCount is set to zero if (m_drawCount < 1) { // Get the OpenGL instance. var gl = args.OpenGL; gl.Color(1f, 0f, 0f); gl.PointSize(2.0f); // Draw 10000 random points. gl.Begin(BeginMode.Points); Random random = new Random(); for (int i = 0; i < 10000; i++) { double x = 10 + 400 * random.NextDouble(); double y = 10 + 400 * random.NextDouble(); double z = (double)random.Next(-10, 0); // Color the point according to z value gl.Color(0f, 0f, 1f); // default to blue if (z == -10) gl.Color(1f, 0f, 0f); // Red for z = -10 else if (z == -1) gl.Color(0f, 1f, 0f); // Green for z = -1 gl.Vertex(x, y, z); } gl.End(); m_drawCount++; } } private void openGLControl1_OpenGLInitialized(object sender, SharpGL.SceneGraph.OpenGLEventArgs args) { } private void openGLControl1_Resized(object sender, SharpGL.SceneGraph.OpenGLEventArgs args) { // NOTE: force the draw routine to happen again when resize occurs m_drawCount = 0; // Get the OpenGL instance. var gl = args.OpenGL; // Create an orthographic projection. gl.MatrixMode(MatrixMode.Projection); gl.LoadIdentity(); // NOTE: Basically no matter what I do, the only points I see are those at // the "near" surface (with z = -zNear)--in this case, I only see green points gl.Ortho(0, openGLControl1.ActualWidth, openGLControl1.ActualHeight, 0, 1, 10); // Back to the modelview. gl.MatrixMode(MatrixMode.Modelview); } } }

    Read the article

  • Ubuntu mount hard drive confusing

    - by Fresheyeball
    I'm new to linux and have a home server set up running ubuntu. In the ui its very easy to mount my additional internal harddrives. I just double click on them. Since I have made this server headless, I now need to mount via the command line. How can I replicate the very simple double click gui behavior? So far all the information I've found is very complex. Ubuntu auto generated folders for each hd in under /media and I can see the harddrives under /dev but have no idea which is which as the hardware is identical between them. I also don't know how they are formated. Thanks in advance for any advice you have.

    Read the article

  • How to pass user-defined structs using boost mpi

    - by lava
    I am trying to send a user-defined structure named ABC using boost::mpi::send () call. The given struct contains a vector "data" whose size is determined at runtime. Objects of struct ABC are sent by master to slaves. But the slaves need to know the size of vector "data" so that the sufficient buffer is available on the slave to receive this data. I can work around it by sending the size first and initialize sufficient buffer on the slave before receiving the objects of struct ABC. But that defeats the whole purpose of using STL containers. Does anyone know of a better way to do handle this ? Any suggestions are greatly appreciated. Here is a sample code that describes the intent of my program. This code fails at runtime due to above mentioned reason. struct ABC { double cur_stock_price; double strike_price; double risk_free_rate; double option_price; std::vector <char> data; }; namespace boost { namespace serialization { template<class Archive> void serialize (Archive &ar, struct ABC &abc, unsigned int version) { ar & abc.cur_stock_price; ar & abc.strike_price; ar & abc.risk_free_rate; ar & abc.option_price; ar & bopr.data; } } } BOOST_IS_MPI_DATATYPE (ABC); int main(int argc, char* argv[]) { mpi::environment env (argc, argv); mpi::communicator world; if (world.rank () == 0) { ABC abc_obj; abc.cur_stock_price = 1.0; abc.strike_price = 5.0; abc.risk_free_rate = 2.5; abc.option_price = 3.0; abc_obj.data.push_back ('a'); abc_obj.data.push_back ('b'); world.send ( 1, ANY_TAG, abc_obj;); std::cout << "Rank 0 OK!" << std::endl; } else if (world.rank () == 1) { ABC abc_obj; // Fails here because abc_obj is not big enough world.recv (0,ANY_TAG, abc_obj;); std::cout << "Rank 1 OK!" << std::endl; for (int i = 0; i < abc_obj;.data.size(); i++) std::cout << i << "=" << abc_obj.data[i] << std::endl; } MPI_Finalize(); return 0; }

    Read the article

  • Maxi/minimizing active applications in system tray

    - by ldigas
    This is a little hard to explain, so I'll try with an examle ... I got a lot of always active applications that have the feature which enables them to be minimized to system tray. Double click / or single click to restore them, and down there again they go. So I spend a lot of time double/single clicking. Is it possible, and how would one go about it, to define an for example AHK shortcut for minimizing/restoring back again those applications (where every app. would have its own shortcut, of course) ? Of course, all other approaches are equally welcomed.

    Read the article

  • Running Excel 2007 as admin on Win7 causes “There was a problem sending the command to the program”

    - by Flack
    I am running Excel 2007 on Windows 7 64bit. I need to run Excel as administrator so I have the "Run as Administrator" box in the Excel shortcut checked. Now, when I try to open an Excel file by double clicking, I get the following error: There was a problem sending the command to the program Excel opens fine after that, and I can open the file fine through Excel's File/Open menu. Why can't I open the file by double clicking? Some sites suggest changing a specific Excel option. I tried while checking/unchecking Excel's "Ignore other applications that use Dynamic Data Exchange (DDE)" but that didn't help. The issue goes away if I uncheck "Run as Administrator" but I want to be able to leave that checked. Any ideas?

    Read the article

  • Custom links in RichTextBox

    - by IVlad
    Suppose I want every word starting with a # to generate an event on double click. For this I have implemented the following test code: private bool IsChannel(Point position, out int start, out int end) { if (richTextBox1.Text.Length == 0) { start = end = -1; return false; } int index = richTextBox1.GetCharIndexFromPosition(position); int stop = index; while (index >= 0 && richTextBox1.Text[index] != '#') { if (richTextBox1.Text[index] == ' ') { break; } --index; } if (index < 0 || richTextBox1.Text[index] != '#') { start = end = -1; return false; } while (stop < richTextBox1.Text.Length && richTextBox1.Text[stop] != ' ') { ++stop; } --stop; start = index; end = stop; return true; } private void richTextBox1_MouseMove(object sender, MouseEventArgs e) { textBox1.Text = richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y)).ToString(); int d1, d2; if (IsChannel(new Point(e.X, e.Y), out d1, out d2) == true) { if (richTextBox1.Cursor != Cursors.Hand) { richTextBox1.Cursor = Cursors.Hand; } } else { richTextBox1.Cursor = Cursors.Arrow; } } This handles detecting words that start with # and making the mouse cursor a hand when it hovers over them. However, I have the following two problems: If I try to implement a double click event for richTextBox1, I can detect when a word is clicked, however that word is highlighted (selected), which I'd like to avoid. I can deselect it programmatically by selecting the end of the text, but that causes a flicker, which I would like to avoid. What ways are there to do this? The GetCharIndexFromPosition method returns the index of the character that is closest to the cursor. This means that if the only thing my RichTextBox contains is a word starting with a # then the cursor will be a hand no matter where on the rich text control it is. How can I make it so that it is only a hand when it hovers over an actual word or character that is part of a word I'm interested in? The implemented URL detection also partially suffers from this problem. If I enable detection of URLs and only write www.test.com in the rich text editor, the cursor will be a hand as long as it is on or below the link. It will not be a hand if it's to the right of the link however. I'm fine even with this functionality if making the cursor a hand if and only if it's on the text proves to be too difficult. I'm guessing I'll have to resort to some sort of Windows API calls, but I don't really know where to start. I am using Visual Studio 2008 and I would like to implement this myself. Update: The flickering problem would be solved if I could make it so that no text is selectable through double clicking, only through dragging the mouse cursor. Is this easier to achieve? Because I don't really care if one can select text or not by double clicking in this case.

    Read the article

  • Unable to open attachment in Windows Live Mail 2011 (Build 15.4.3502.0922)

    - by Anon2010
    I use Windows Live Mail 2011 (Build 15.4.3502.0922), in Windows 7 Pro 64. When I receive an email message that has an attachment, when I double click to open this attachment, nothing happens. Any kind of attachment, nothing happens. If I right click and choose "Open", nothing happens either. If I right click and choose Save As, I can save the file to disk and open it via Windows Explorer. I would like to be able to double click to open the attachment. I tried to repair WLM but that didn't make any difference. My antivirus is Microsoft Security Essentials. Does anyone know anything about this issue? Thanks

    Read the article

  • image processing algorithm in MATLAB

    - by user261002
    I am trying to reconstruct an algorithm belong to this paper: Decomposition of biospeckle images in temporary spectral bands Here is an explanation of the algorithm: We recorded a sequence of N successive speckle images with a sampling frequency fs. In this way it was possible to observe how a pixel evolves through the N images. That evolution can be treated as a time series and can be processed in the following way: Each signal corresponding to the evolution of every pixel was used as input to a bank of filters. The intensity values were previously divided by their temporal mean value to minimize local differences in reflectivity or illumination of the object. The maximum frequency that can be adequately analyzed is determined by the sampling theorem and s half of sampling frequency fs. The latter is set by the CCD camera, the size of the image, and the frame grabber. The bank of filters is outlined in Fig. 1. In our case, ten 5° order Butterworth11 filters were used, but this number can be varied according to the required discrimination. The bank was implemented in a computer using MATLAB software. We chose the Butter-worth filter because, in addition to its simplicity, it is maximally flat. Other filters, an infinite impulse response, or a finite impulse response could be used. By means of this bank of filters, ten corresponding signals of each filter of each temporary pixel evolution were obtained as output. Average energy Eb in each signal was then calculated: where pb(n) is the intensity of the filtered pixel in the nth image for filter b divided by its mean value and N is the total number of images. In this way, en values of energy for each pixel were obtained, each of hem belonging to one of the frequency bands in Fig. 1. With these values it is possible to build ten images of the active object, each one of which shows how much energy of time-varying speckle there is in a certain frequency band. False color assignment to the gray levels in the results would help in discrimination. and here is my MATLAB code base on that : clear all for i=0:39 str = num2str(i); str1 = strcat(str,'.mat'); load(str1); D{i+1}=A; end new_max = max(max(A)); new_min = min(min(A)); for i=20:180 for j=20:140 ts = []; for k=1:40 ts = [ts D{k}(i,j)]; %%% kth image pixel i,j --- ts is time series end ts = double(ts); temp = mean(ts); ts = ts-temp; ts = ts/temp; N = 5; % filter order W = [0.00001 0.05;0.05 0.1;0.1 0.15;0.15 0.20;0.20 0.25;0.25 0.30;0.30 0.35;0.35 0.40;0.40 0.45;0.45 0.50]; N1 = 5; for ind = 1:10 Wn = W(ind,:); [B,A] = butter(N1,Wn); ts_f(ind,:) = filter(B,A,ts); end for ind=1:10 imag_test1{ind}(i,j) =sum((ts_f(ind,:)./mean(ts_f(ind,:))).^2); end end end for i=1:10 temp_imag = imag_test1{i}(:,:); x=isnan(temp_imag); temp_imag(x)=0; temp_imag=medfilt2(temp_imag); t_max = max(max(temp_imag)); t_min = min(min(temp_imag)); temp_imag = (temp_imag-t_min).*(double(new_max-new_min)/double(t_max-t_min))+double(new_min); imag_test2{i}(:,:) = temp_imag; end for i=1:10 A=imag_test2{i}(:,:); B=A/max(max(A)); B=histeq(B); figure,imshow(B) colorbar end but I am not getting the same result as paper. has anybody has aby idea why? or where I have gone wrong? Refrence Link to the paper

    Read the article

  • Word mergefield wildcard not correctly matching

    - by aZn137
    Hello, Below is my mergefield code: { IF { MERGEFIELD Subs_State } = "GA" "blah blah" "{ IF { MERGEFIELD CEOrgStates } = "GA" "blah blah" ""} "} I'm pulling records from a MS Access db. My goal is to check whether a record has Subs_State field matching "GA", or the CEOrgStates has the word "GA" (some records have stuff like "|FL|CA|GA|CT|KY|" (no quotes)). When I merged the docs, Word doesnt seem to be able to match with the wildcards: If I use and compare "*GA" (fields ending with GA), it works; however, the double wildcards "*GA*" dont seem to work at all. Here are the things I’ve tried: Have data in lowercase, then compare with lowercase Have data in lowercase, convert to and then compare with uppercase Do the opposite of the above 2 with uppercase data Use “*GA*” and “*ga*” (no pipe) Use different delimiters Nothing seems to work with the double wildcard matching. What am I doing wrong? Thanks!

    Read the article

  • How to add the coding for displaying the address when a particular set of latitude and longitude is

    - by KKC
    import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.AdapterView.OnItemSelectedListener; public class PopularAttractions extends MapActivity { private String[ ][ ] locations = { {"Singapore Zoological Garden","1.40502,103.793449"}, {"Singapore Night Safari","1.4037,103.789467"}, {"Jurong BirdPark","1.32005,103.707153"}, {"Jurong Reptile Park","1.321177,103.708486"}, {"Singapore Botanic Garden","1.31471,103.815689"}, {"Sungei Buloh Wetland Reserver","1.445144,103.729595"}, {"Escape Theme Park","1.38104,103.936928"}, {"Snow City","1.32823,103.74263"}, {"Super Ice World","1.300422,103.875348"}, {"Chinatown Heritage Center","1.2836,103.84425"}, {"Singapore Science Center","1.3249,103.740578"}, {"Red Dot Design Museum","1.277762,103.846225"}, {"G-Max Reverse Bungy","1.2906,103.845322"}, {"NEWater Visitor Center","1.33105,103.955311"} }; private Spinner spinnerView; private MapView mapView; private MapController mc; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); spinnerView = (Spinner) this.findViewById(R.id.spinner1); mapView = (MapView) findViewById(R.id.mapview1); mc = mapView.getController(); ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item); //--add the various locations--- for(int i = 0; i < locations.length; i++) adapter.add(locations[i][0]); adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); spinnerView.setAdapter(adapter); spinnerView.setOnItemSelectedListener(selectListener); gotoSelected(); } //---when user selects an item--- private OnItemSelectedListener selectListener = new OnItemSelectedListener() { //---these are two methods you need to implement--- public void onItemSelected( AdapterView<?>parent, View v, int position, long id) { gotoSelected(); } public void onNothingSelected(AdapterView<?> arg0) {} }; //---when an item has been selected--- public void gotoSelected() { int index = spinnerView.getSelectedItemPosition(); String[] coordinates = locations[index][1].split(","); double lat = Double.parseDouble(coordinates[0]); double lng = Double.parseDouble(coordinates[1]); GeoPoint location = new GeoPoint ( (int)(lat * 1E6), (int)(lng * 1E6)); mc.animateTo(location); mc.setZoom(16); if (mapView.isSatellite()) mapView.setSatellite(false); else mapView.setStreetView(true); mapView.invalidate(); } public boolean onKeyDown(int keyCode, KeyEvent event) { MapController mc = mapView.getController(); switch (keyCode) { case KeyEvent.KEYCODE_3: mc.zoomIn(); break; case KeyEvent.KEYCODE_1: mc.zoomOut(); break; } return super.onKeyDown(keyCode, event); } @Override protected boolean isRouteDisplayed(){ //TODO Auto-generated method sub return false; } }

    Read the article

  • I create a JPanel and GridBagLayout within an object but when I get it in the main object, attributes are missing

    - by chickeneaterguy
    public oijoij() { String name = "Jackie"; int priority = 50; int minPriority = 90; setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JPanel panel = new JPanel(); GridBagLayout gbc_panel = new GridBagLayout(); gbc_panel.columnWidths = new int[]{0,0,0}; gbc_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0}; gbc_panel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE}; gbc_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; panel.setBorder(new LineBorder(new Color(0,0,0),1)); panel.setLayout(gbc_panel); panel.setAlignmentX(Component.LEFT_ALIGNMENT); panel.setMinimumSize(new Dimension(110,110)); panel.setPreferredSize(new Dimension(110, 110)); panel.setSize(new Dimension(110,110)); JLabel lblNewLabel = new JLabel("Process ID:"); GridBagConstraints gbc_lblNewLabel = new GridBagConstraints(); gbc_lblNewLabel.gridheight = 2; gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5); gbc_lblNewLabel.gridx = 0; gbc_lblNewLabel.gridy = 0; panel.add(lblNewLabel, gbc_lblNewLabel); JLabel lblNewLabel_1 = new JLabel(name); GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints(); gbc_lblNewLabel_1.gridheight = 2; gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 0); gbc_lblNewLabel_1.gridx = 1; gbc_lblNewLabel_1.gridy = 0; panel.add(lblNewLabel_1, gbc_lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel("Priority:"); GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints(); gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5); gbc_lblNewLabel_2.gridx = 0; gbc_lblNewLabel_2.gridy = 2; panel.add(lblNewLabel_2, gbc_lblNewLabel_2); JLabel lblNum = new JLabel(Integer.toString(priority)); GridBagConstraints gbc_lblNum = new GridBagConstraints(); gbc_lblNum.insets = new Insets(0, 0, 5, 0); gbc_lblNum.gridx = 1; gbc_lblNum.gridy = 2; panel.add(lblNum, gbc_lblNum); JLabel lblNewLabel_3 = new JLabel("Min Priority:"); GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints(); gbc_lblNewLabel_3.insets = new Insets(0, 0, 5, 5); gbc_lblNewLabel_3.gridx = 0; gbc_lblNewLabel_3.gridy = 3; panel.add(lblNewLabel_3, gbc_lblNewLabel_3); JLabel lblMp = new JLabel(Integer.toString(minPriority)); GridBagConstraints gbc_lblMp = new GridBagConstraints(); gbc_lblMp.insets = new Insets(0, 0, 5, 0); gbc_lblMp.gridx = 1; gbc_lblMp.gridy = 3; panel.add(lblMp, gbc_lblMp); JLabel lblTimeSlice = new JLabel("Time Slice:"); GridBagConstraints gbc_lblTimeSlice = new GridBagConstraints(); gbc_lblTimeSlice.insets = new Insets(0, 0, 0, 5); gbc_lblTimeSlice.gridx = 0; gbc_lblTimeSlice.gridy = 4; panel.add(lblTimeSlice, gbc_lblTimeSlice); Random r = new Random(System.currentTimeMillis()); panel.setBackground(new Color( r.nextInt(255 - 210) + 210, r.nextInt(255 - 210) + 210, r.nextInt(255 - 210) + 210)); } I have accessor methods for the GridBagLayout and the JPanel. When calling the functions in another file, it looks like I just get the JPanel (but without any labels or the layout or other GridBagLayout features). Help?

    Read the article

  • GLSL Error: failed to preprocess the source. How can I troubleshoot this?

    - by Brent Parker
    I'm trying to learn to play with OpenGL GLSL shaders. I've written a very simple program to simply create a shader and compile it. However, whenever I get to the compile step, I get the error: Error: Preprocessor error Error: failed to preprocess the source. Here's my very simple code: #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <GL/glext.h> #include <time.h> #include <stdio.h> #include <iostream> #include <stdlib.h> using namespace std; const int screenWidth = 640; const int screenHeight = 480; const GLchar* gravity_shader[] = { "#version 140" "uniform float t;" "uniform mat4 MVP;" "in vec4 pos;" "in vec4 vel;" "const vec4 g = vec4(0.0, 0.0, -9.80, 0.0);" "void main() {" " vec4 position = pos;" " position += t*vel + t*t*g;" " gl_Position = MVP * position;" "}" }; double pointX = (double)screenWidth/2.0; double pointY = (double)screenWidth/2.0; void initShader() { GLuint shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(shader, 1, gravity_shader, NULL); glCompileShader(shader); GLint compiled = true; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if(!compiled) { GLint length; GLchar* log; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); log = (GLchar*)malloc(length); glGetShaderInfoLog(shader, length, &length, log); std::cout << log <<std::endl; free(log); } exit(0); } bool myInit() { initShader(); glClearColor(1.0f, 1.0f, 1.0f, 0.0f); glColor3f(0.0f, 0.0f, 0.0f); glPointSize(1.0); glLineWidth(1.0f); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, (GLdouble) screenWidth, 0.0, (GLdouble) screenHeight); glEnable(GL_DEPTH_TEST); return true; } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(screenWidth, screenHeight); glutInitWindowPosition(100, 150); glutCreateWindow("Mouse Interaction Display"); myInit(); glutMainLoop(); return 0; } Where am I going wrong? If it helps, I am trying to do this on a Acer Aspire One with an atom processor and integrated Intel video running the latest Ubuntu. It's not very powerful, but then again, this is a very simple shader. Thanks a lot for taking a look!

    Read the article

< Previous Page | 69 70 71 72 73 74 75 76 77 78 79 80  | Next Page >