Search Results

Search found 1803 results on 73 pages for 'pi calculation'.

Page 23/73 | < Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >

  • Inverse Kinematics with OpenGL/Eigen3 : unstable jacobian pseudoinverse

    - by SigTerm
    I'm trying to implement simple inverse kinematics test using OpenGL, Eigen3 and "jacobian pseudoinverse" method. The system works fine using "jacobian transpose" algorithm, however, as soon as I attempt to use "pseudoinverse", joints become unstable and start jerking around (eventually they freeze completely - unless I use "jacobian transpose" fallback computation). I've investigated the issue and turns out that in some cases jacobian.inverse()*jacobian has zero determinant and cannot be inverted. However, I've seen other demos on the internet (youtube) that claim to use same method and they do not seem to have this problem. So I'm uncertain where is the cause of the issue. Code is attached below: *.h: struct Ik{ float targetAngle; float ikLength; VectorXf angles; Vector3f root, target; Vector3f jointPos(int ikIndex); size_t size() const; Vector3f getEndPos(int index, const VectorXf& vec); void resize(size_t size); void update(float t); void render(); Ik(): targetAngle(0), ikLength(10){ } }; *.cpp: size_t Ik::size() const{ return angles.rows(); } Vector3f Ik::getEndPos(int index, const VectorXf& vec){ Vector3f pos(0, 0, 0); while(true){ Eigen::Affine3f t; float radAngle = pi*vec[index]/180.0f; t = Eigen::AngleAxisf(radAngle, Vector3f(-1, 0, 0)) * Eigen::Translation3f(Vector3f(0, 0, ikLength)); pos = t * pos; if (index == 0) break; index--; } return pos; } void Ik::resize(size_t size){ angles.resize(size); angles.setZero(); } void drawMarker(Vector3f p){ glBegin(GL_LINES); glVertex3f(p[0]-1, p[1], p[2]); glVertex3f(p[0]+1, p[1], p[2]); glVertex3f(p[0], p[1]-1, p[2]); glVertex3f(p[0], p[1]+1, p[2]); glVertex3f(p[0], p[1], p[2]-1); glVertex3f(p[0], p[1], p[2]+1); glEnd(); } void drawIkArm(float length){ glBegin(GL_LINES); float f = 0.25f; glVertex3f(0, 0, length); glVertex3f(-f, -f, 0); glVertex3f(0, 0, length); glVertex3f(f, -f, 0); glVertex3f(0, 0, length); glVertex3f(f, f, 0); glVertex3f(0, 0, length); glVertex3f(-f, f, 0); glEnd(); glBegin(GL_LINE_LOOP); glVertex3f(f, f, 0); glVertex3f(-f, f, 0); glVertex3f(-f, -f, 0); glVertex3f(f, -f, 0); glEnd(); } void Ik::update(float t){ targetAngle += t * pi*2.0f/10.0f; while (t > pi*2.0f) t -= pi*2.0f; target << 0, 8 + 3*sinf(targetAngle), cosf(targetAngle)*4.0f+5.0f; Vector3f tmpTarget = target; Vector3f targetDiff = tmpTarget - root; float l = targetDiff.norm(); float maxLen = ikLength*(float)angles.size() - 0.01f; if (l > maxLen){ targetDiff *= maxLen/l; l = targetDiff.norm(); tmpTarget = root + targetDiff; } Vector3f endPos = getEndPos(size()-1, angles); Vector3f diff = tmpTarget - endPos; float maxAngle = 360.0f/(float)angles.size(); for(int loop = 0; loop < 1; loop++){ MatrixXf jacobian(diff.rows(), angles.rows()); jacobian.setZero(); float step = 1.0f; for (int i = 0; i < angles.size(); i++){ Vector3f curRoot = root; if (i) curRoot = getEndPos(i-1, angles); Vector3f axis(1, 0, 0); Vector3f n = endPos - curRoot; float l = n.norm(); if (l) n /= l; n = n.cross(axis); if (l) n *= l*step*pi/180.0f; //std::cout << n << "\n"; for (int j = 0; j < 3; j++) jacobian(j, i) = n[j]; } std::cout << jacobian << std::endl; MatrixXf jjt = jacobian.transpose()*jacobian; //std::cout << jjt << std::endl; float d = jjt.determinant(); MatrixXf invJ; float scale = 0.1f; if (!d /*|| true*/){ invJ = jacobian.transpose(); scale = 5.0f; std::cout << "fallback to jacobian transpose!\n"; } else{ invJ = jjt.inverse()*jacobian.transpose(); std::cout << "jacobian pseudo-inverse!\n"; } //std::cout << invJ << std::endl; VectorXf add = invJ*diff*step*scale; //std::cout << add << std::endl; float maxSpeed = 15.0f; for (int i = 0; i < add.size(); i++){ float& cur = add[i]; cur = std::max(-maxSpeed, std::min(maxSpeed, cur)); } angles += add; for (int i = 0; i < angles.size(); i++){ float& cur = angles[i]; if (i) cur = std::max(-maxAngle, std::min(maxAngle, cur)); } } } void Ik::render(){ glPushMatrix(); glTranslatef(root[0], root[1], root[2]); for (int i = 0; i < angles.size(); i++){ glRotatef(angles[i], -1, 0, 0); drawIkArm(ikLength); glTranslatef(0, 0, ikLength); } glPopMatrix(); drawMarker(target); for (int i = 0; i < angles.size(); i++) drawMarker(getEndPos(i, angles)); } Any help will be appreciated.

    Read the article

  • Load dll's from Environment Variable Path from a service

    - by Paulo Manuel Santos
    We install Matlab Runtime on a machine, then we restart a .net windows service that invokes methods from the Matlab Runtime. The problem is that we receive TypeInitializationException errors until we restart windows. We think this happens because Environment Variables are not changed on services until restart and Matlab uses the %Path% variable to reference it's core DLL's. My question is, do you think I can change the %Path% variable so that Matlab will use it when referencing the core dll's for it's engine? Or is it possible to add a directory to the runtime DLL loading mechanism of .NET so that those Matlab core dll's would be referenced correctly without restarting the machine? Here is the exception we get System.TypeInitializationException: The type initializer for 'MatlabCalculation.Calculation' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'mclmcrrt710.dll': Kan opgegeven module niet vinden. (Exception from HRESULT: 0x8007007E) at MathWorks.MATLAB.NET.Utility.MWMCR.mclmcrInitialize() at MathWorks.MATLAB.NET.Utility.MWMCR..cctor() --- End of inner exception stack trace --- at MatlabCalculation.Calculation..cctor() --- End of inner exception stack trace --- at MatlabCalculation.Calculation.Finalize() "Kan opgegeven module niet vinden" = "The specified module not found"

    Read the article

  • Generating permutation in Python with specific rule

    - by twfx
    Let say a=[A, B, C, D], each element has a weight w, and is set to 1 if selected, 0 if otherwise. I'd like to generate permutation in the below order 1,1,1,1 1,1,1,0 1,1,0,1 1,1,0,0 1,0,1,1 1,0,1,0 1,0,0,1 1,0,0,0 Let's w=[1,2,3,4] for item A,B,C,D ... and max_weight = 4. For each permutation, if the accum weight has exceeded max_weight, stop calculation for that permutation, move to next permutation. For eg. 1,1,1 --> 6 > 4, exceeded, stop, move to next 1,1,1 --> 6 > 4, exceeded, stop, move to next 1,1,0,1 --> 7 > 4 finished, move to next 1,1,0,0 --> 3 finished, move to next 1,0,1,1 --> 8 > 4, finished, stop, move to next 1,0,1,0 --> 4 finished, move to next 1,0,0,1 --> 5 > 4 finished, move to next 1,0,0,0 --> 1 finished, move to next [1,0,1,0] is the best combination which does not exceeded max_weight 4 My questions are What's the algorithm which generate the required permutation? Or any suggestion I could generate the permutation? As the number of element can be up to 10000, and the calculation stop if the accum weight for the branch exceeds max_weight, it is not necessary to generate all permutation first before the calculation. How can the algo in (1) generate permutation on the fly?

    Read the article

  • Solving problems involving more complex data structures with CUDA

    - by Nils
    So I read a bit about CUDA and GPU programming. I noticed a few things such that access to global memory is slow (therefore shared memory should be used) and that the execution path of threads in a warp should not diverge. I also looked at the (dense) matrix multiplication example, described in the programmers manual and the nbody problem. And the trick with the implementation seems to be the same: Arrange the calculation in a grid (which it already is in case of the matrix mul); then subdivide the grid into smaller tiles; fetch the tiles into shared memory and let the threads calculate as long as possible, until it needs to reload data from the global memory into shared memory. In case of the nbody problem the calculation for each body-body interaction is exactly the same (page 682): bodyBodyInteraction(float4 bi, float4 bj, float3 ai) It takes two bodies and an acceleration vectors. The body vector has four components it's position and the weight. When reading the paper, the calculation is understood easily. But what is if we have a more complex object, with a dynamic data structure? For now just assume that we have an object (similar to the body object presented in the paper) which has a list of other objects attached and the number of objects attached is different in each thread. How could I implement that without having the execution paths of the threads to diverge? I'm also looking for literature which explains how different algorithms involving more complex data structures can be effectively implemented in CUDA.

    Read the article

  • Ajax Form submittion in Google App Engine with jQuery

    - by user271785
    could not figure out why it is not working: i need to send request to server, generate some fragment of html in python with meanCal method, and then want that fragment embedded into submitting html file using calculation method and dynamically shows in dyContent div. all the processes are done by single click on submit button in a form. any suggestions??? thanks in advance. the submitting html: <div id="dyContent" style="height: 200px;"> waiting for user... {{ mgs }} </div> <div id="leturetext"> <form id="mean" method="post" action="/calculation"> <select name="meanselect"> <option value=10>example</option> <option value=11>exercise</option> </select> <input type="button" name="btnMean" value="Check Results" /> </form> </div> <script type="text/javascript"> $(document).ready(function() { //$("#btnMean").live("click", function() { $("#mean").submit(function(){ $.ajax({ type: "POST", cache: false, url: "/meanCal", success: function(html) { $("#dyContent").html(html); } }); return false; }); }); </script> python: class MainHandler(webapp.RequestHandler): def get(self): path = self.request.path if doRender(self, path): return doRender(self,'index.htm') class calculationHandler(webapp.RequestHandler): def post(self): doRender(self, 'Diagnostic_stats.htm', {'mgs' : "refreshed.", }) def get(self): doRender(self, 'Diagnostic_stats.htm') class meanHandler(webapp.RequestHandler): def get(self): global GL index = self.request.get('meanselect'.value) if (index == 10): allData = GL.exampleData dataString = ','.join(map(str, allData)) dataMean = (str)(stats.lmean(allData)) doRender(self, 'Result.htm', { 'dataIn' : dataString, 'MEAN' : "Example Mean is: " + dataMean, }) return else: allData = GL.exerciseData dataString = ','.join(map(str, allData)) dataMean = (str)(stats.lmean(allData)) doRender(self, 'Result.htm', { 'dataIn' : dataString, 'MEAN' : "Exercise Mean is: " + dataMean, }) def main(): global GL GL = GlobalVariables() application = webapp.WSGIApplication( [('/calculation', calculationHandler), ('/meanCal', meanHandler), ('.*', MainHandler), ], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()

    Read the article

  • iPhone slide view passing variables

    - by sebastyuiop
    Right, I'm trying to make an app that has a calculation that involves a stopwatch. When a button on the calculation view is clicked a stopwatch slides in from the bottom. This all works fine, the problem I can't get my head around is how to send the recorded time back to the previous controller to update a textfield. I've simplified the code and stripped out most irrelevant stuff. Many thanks. CalculationViewController.h #import <UIKit/UIKit.h> @interface CalculationViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { IBOutlet UITextField *inputTxt; } @property (nonatomic, retain) UITextField *inputTxt; - (IBAction)showTimer:(id)sender; @end CalculationViewController.m #import "CalculationViewController.h" #import "TimerViewController.h" @implementation CalculationViewController - (IBAction)showTimer:(id)sender { TimerViewController *timerView = [[TimerViewController alloc] init]; [self.navigationController presentModalViewController:timerView animated:YES]; } TimerViewController.h #import <UIKit/UIKit.h> @interface TimerViewController : UIViewController { IBOutlet UILabel *time; NSTimer *myTicker; } - (IBAction)start; - (IBAction)stop; - (IBAction)reset; - (void)showActivity; @end TimerViewController.m #import "TimerViewController.h" #import "CalculationViewController.h" @implementation TimerViewController - (IBAction)start { myTicker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES]; } - (IBAction)stop { [myTicker invalidate]; #Update inputTxt on calculation view here [self dismissModalViewControllerAnimated:YES]; } - (IBAction)reset { time.text = @"0"; } - (void)showActivity { int currentTime = [time.text intValue]; int newTime = currentTime + 1; time.text = [NSString stringWithFormat:@"%d", newTime]; } @end

    Read the article

  • Rewriting a for loop in pure NumPy to decrease execution time

    - by Statto
    I recently asked about trying to optimise a Python loop for a scientific application, and received an excellent, smart way of recoding it within NumPy which reduced execution time by a factor of around 100 for me! However, calculation of the B value is actually nested within a few other loops, because it is evaluated at a regular grid of positions. Is there a similarly smart NumPy rewrite to shave time off this procedure? I suspect the performance gain for this part would be less marked, and the disadvantages would presumably be that it would not be possible to report back to the user on the progress of the calculation, that the results could not be written to the output file until the end of the calculation, and possibly that doing this in one enormous step would have memory implications? Is it possible to circumvent any of these? import numpy as np import time def reshape_vector(v): b = np.empty((3,1)) for i in range(3): b[i][0] = v[i] return b def unit_vectors(r): return r / np.sqrt((r*r).sum(0)) def calculate_dipole(mu, r_i, mom_i): relative = mu - r_i r_unit = unit_vectors(relative) A = 1e-7 num = A*(3*np.sum(mom_i*r_unit, 0)*r_unit - mom_i) den = np.sqrt(np.sum(relative*relative, 0))**3 B = np.sum(num/den, 1) return B N = 20000 # number of dipoles r_i = np.random.random((3,N)) # positions of dipoles mom_i = np.random.random((3,N)) # moments of dipoles a = np.random.random((3,3)) # three basis vectors for this crystal n = [10,10,10] # points at which to evaluate sum gamma_mu = 135.5 # a constant t_start = time.clock() for i in range(n[0]): r_frac_x = np.float(i)/np.float(n[0]) r_test_x = r_frac_x * a[0] for j in range(n[1]): r_frac_y = np.float(j)/np.float(n[1]) r_test_y = r_frac_y * a[1] for k in range(n[2]): r_frac_z = np.float(k)/np.float(n[2]) r_test = r_test_x +r_test_y + r_frac_z * a[2] r_test_fast = reshape_vector(r_test) B = calculate_dipole(r_test_fast, r_i, mom_i) omega = gamma_mu*np.sqrt(np.dot(B,B)) # write r_test, B and omega to a file frac_done = np.float(i+1)/(n[0]+1) t_elapsed = (time.clock()-t_start) t_remain = (1-frac_done)*t_elapsed/frac_done print frac_done*100,'% done in',t_elapsed/60.,'minutes...approximately',t_remain/60.,'minutes remaining'

    Read the article

  • is this a design pattern?

    - by Michel
    Hi all, i have to build some financial data report, and for making the calculation, there are a lot of 'if then' situations: if it's a large client, subtract 10%, if it's postal code equals '10101', add 10%, if the day is on a saturday, make a difficult calculation etc. so i once read about this kind of example, and what they did was (hope i remember well) create a class with some base info and make it possible to add all kinds of calculationobjects to it. So to put what i remembered in pseudo code Basecalc bc = new baseCalc(); //put the info in the bc so other objects can do their if bc.Add(new Largecustomercalc()); bc.Add(new PostalcodeCalc()); bc.add(new WeekdayCalc()); the the bc would run the Calc() methods of all of the added Calc objects. As i type this i think all the Calc objects must be able to see the Basecalc properties to correctly perform their calculation logic. So all the if's are in the different Calc objects and not ALL in the Basecalc. does this make sense? I was wondering if this is some kind of design pattern?

    Read the article

  • c++ floating point precision loss: 3015/0.00025298219406977296

    - by SigTerm
    The problem. Microsoft Visual C++ 2005 compiler, 32bit windows xp sp3, amd 64 x2 cpu. Code: double a = 3015.0; double b = 0.00025298219406977296; //*((unsigned __int64*)(&a)) == 0x40a78e0000000000 //*((unsigned __int64*)(&b)) == 0x3f30945640000000 double f = a/b;//3015/0.00025298219406977296; the result of calculation (i.e. "f") is 11917835.000000000 (*((unsigned __int64*)(&f)) == 0x4166bb4160000000) although it should be 11917834.814763514 (i.e. *((unsigned __int64*)(&f)) == 0x4166bb415a128aef). I.e. fractional part is lost. Unfortunately, I need fractional part to be correct. Questions: 1) Why does this happen? 2) How can I fix the problem? Additional info: 0) The result is taken directly from "watch" window (it wasn't printed, and I didn't forget to set printing precision). I also provided hex dump of floating point variable, so I'm absolutely sure about calculation result. 1) The disassembly of f = a/b is: fld qword ptr [a] fdiv qword ptr [b] fstp qword ptr [f] 2) f = 3015/0.00025298219406977296; yields correct result (f == 11917834.814763514 , *((unsigned __int64*)(&f)) == 0x4166bb415a128aef ), but it looks like in this case result is simply calculated during compile-time: fld qword ptr [__real@4166bb415a128aef (828EA0h)] fstp qword ptr [f] So, how can I fix this problem? P.S. I've found a temporary workaround (i need only fractional part of division, so I simply use f = fmod(a/b)/b at the moment), but I still would like to know how to fix this problem properly - double precision is supposed to be 16 decimal digits, so such calculation isn't supposed to cause problems.

    Read the article

  • The first day of JavaOne is already over!

    - by delabassee
    In the past Sunday used to be a more relaxing day with ‘just’ some JavaOne activities going on. Sunday used to be a soft day to prepare yourself for an exhausting week. This is now over as JavaOne is expanding; Sunday is now an integral part of the conference. One of the side effect of this extra day is that some activities related to JavaOne and OpenWorld such as MySQL Connect are being push to start a day earlier on Saturday (can you spot the pattern here?). On the GlassFish front, Sunday was a very busy day! It started at the Moscone Center with the annual GlassFish Community Event where the Java EE 7 and GF 4 roadmaps were presented and discussed. During the event, different GlassFish users such as ZeroTurnaround (the JRebel guys), Grupo RBS and IDR Solutions shared their views on GF, why they like GF but also what could be improved. The event was also a forum for the GF community to exchange with some of the key Java EE / GlassFish Oracle Executives and the different GF team members. The Strategy keynote and the Technical keynote were held in the Masonic Auditorium later in the after-noon. Oracle executives have presented the plans for Java SE, Java FX and Java EE. As on-demand replays will be available soon, I will not summarize several hours of content but here are some personal takeaways from those keynotes. Modularity Modularity is a big deal. We know by now that Project Jigsaw will not be ready for Java SE 8 but in any case, it is already possible (and encouraged) to test Jigsaw today. In the future, Java EE plan to rely on the modularity features provided by Java SE, so Project Jigsaw is also relevant for Java EE developers. Shorter term, to cover some of the modular requirements, Java SE will adopt the approach that was used for Java EE 6 and the notion of Profiles. This approach does not define a module system per say; Profiles is a way to clearly define different subsets of Java SE to fulfill different needs (e.g. the full JRE is not required for a headless application). The introduction of different Profiles, from the Base profile (10mb) to the Full Profile (+50mb), has been proposed for Java SE 8. Embedded Embedded is a strong theme going forward for the Java Plaform. There is now a dedicated program : Java Embedded @ JavaOne Java by nature (e.g. platform independence, built-in security, ability easily talks to any back-end systems, large set of skills available on the market, etc.) is probably the most suited platform for the Internet of Things. You can quickly be up-to-speed and develop services and applications for that space just by using your current Java skills. All you need to start developing on ARM is a 35$ Raspberry Pi ARM board (25$ if you are cheap and can live without an ethernet connection) and the recently released JDK for Linux/ARM. Obviously, GlassFish runs on Raspberry Pi. If you wan to go further in the embedded space, you should take a look Java SE Embedded, an optimized, low footprint, Java environment that support the major embedded architectures (ARM, PPC and x86). Finally, Oracle has recently introduced Java Embedded Suite, a new solution that brings modern middleware capabilities to the embedded space. Java Embedded Suite is an optimized solution that leverage Java SE Embedded but also GlassFish, Jersey and JavaDB to deploy advanced value added capabilities (eg. sensor data filtering and) deeper in the network, closer to the devices. JavaFX JavaFX is going strong! Starting from Java SE 7u6, JavaFX is bundled with the JDK. JavaFX is now available for all the major desktop platforms (Windows, Linux and Mac OS X). JavaFX is now also available, in developer preview, for low end device running Linux/ARM. During the keynote, JavaFX was shown running on a Raspberry Pi! And as announced during the keynote, JavaFX should be fully open-sourced by the end of the year; contributions are welcome!. There is a strong momentum around JavaFX, it’s the ideal client solution for the Java platform. A client layer that works perfectly with GlassFish on the back-end. If you were not convince by JavaFX, it’s time to reconsider it! As an old Chinese proverb say “One tweet is worth a thousand words!” HTML5, Project Avatar and Java EE 7 HTML5 got a lot of airtime too, it was covered during the Java EE 7 section of the keynote. Some details about Project Avatar, Oracle’s incubator project for a TSA (Thin Server Architecture) solution, were diluted and shown during the keynote. On the tooling side, Project Easel running on NetBeans 7.3 beta was demo’ed, including a cool NetBeans debugging session running in Chrome! HTML 5, Project Avatar and Java EE 7 deserve separate posts... Feedback We need your feedback! There are many projects, JSRs and products cooking : GlassFish 4, Project Jigsaw, Concurrency Utilities for Java EE (JSR 236), OpenJFX, OpenJDK to name just a few. Those projects, those specifications will have a profound impact on the Java platform for the years to come! So if you have the opportunity, download, install, learn, tests them and give feedback! Remember, you can "Make the Future Java!" Finally, the traditional GlassFish Party at the Thirsty Bear concluded the first JavaOne day. This party is another place where the community can freely exchange with the GlassFish team in a more relaxed, more friendly (but sometime more noisy) atmosphere. Arun has posted a set of pictures to reflect the atmosphere of the keynotes and the GlassFish party. You can find more details on the others Java EE and GlassFish activities here.

    Read the article

  • rotate player based off of joystick

    - by pengume
    Hey everyone I have this game that i am making in android and I have a touch screen joystick that moves the player around based on the joysticks position. I cant figure out how to also get the player to rotate at the same angle of the joystick. so when the joystick is to the left the players bitmap is rotated to the left as well. Maybe someone here has some sample code I could look at here is the joysticks class that I am using. `public class GameControls implements OnTouchListener { public float initx = DroidzActivity.screenWidth - 45; //255; // 320 og 425 public float inity = DroidzActivity.screenHeight - 45;//425; // 480 og 267 public Point _touchingPoint = new Point( DroidzActivity.screenWidth - 45, DroidzActivity.screenHeight - 45); public Point _pointerPosition = new Point(DroidzActivity.screenWidth - 100, DroidzActivity.screenHeight - 100); // ogx 220 ogy 150 private Boolean _dragging = false; private boolean attackMode = false; @Override public boolean onTouch(View v, MotionEvent event) { update(event); return true; } private MotionEvent lastEvent; public boolean ControlDragged; private static double angle; public void update(MotionEvent event) { if (event == null && lastEvent == null) { return; } else if (event == null && lastEvent != null) { event = lastEvent; } else { lastEvent = event; } // drag drop if (event.getAction() == MotionEvent.ACTION_DOWN) { if ((int) event.getX() > 0 && (int) event.getX() < 50 && (int) event.getY() > DroidzActivity.screenHeight - 160 && (int) event.getY() < DroidzActivity.screenHeight - 0) { setAttackMode(true); } else { _dragging = true; } } else if (event.getAction() == MotionEvent.ACTION_UP) { if(isAttackMode()){ setAttackMode(false); } _dragging = false; } if (_dragging) { ControlDragged = true; // get the pos _touchingPoint.x = (int) event.getX(); _touchingPoint.y = (int) event.getY(); // Log.d("GameControls", "x = " + _touchingPoint.x + " y = " //+ _touchingPoint.y); // bound to a box if (_touchingPoint.x < DroidzActivity.screenWidth - 75) { // og 400 _touchingPoint.x = DroidzActivity.screenWidth - 75; } if (_touchingPoint.x > DroidzActivity.screenWidth - 15) {// og 450 _touchingPoint.x = DroidzActivity.screenWidth - 15; } if (_touchingPoint.y < DroidzActivity.screenHeight - 75) {// og 240 _touchingPoint.y = DroidzActivity.screenHeight - 75; } if (_touchingPoint.y > DroidzActivity.screenHeight - 15) {// og 290 _touchingPoint.y = DroidzActivity.screenHeight - 15; } // get the angle setAngle(Math.atan2(_touchingPoint.y - inity, _touchingPoint.x - initx) / (Math.PI / 180)); // Move the ninja in proportion to how far // the joystick is dragged from its center _pointerPosition.y += Math.sin(getAngle() * (Math.PI / 180)) * (_touchingPoint.x / 70); // og 180 70 _pointerPosition.x += Math.cos(getAngle() * (Math.PI / 180)) * (_touchingPoint.x / 70); // make the pointer go thru if (_pointerPosition.x > DroidzActivity.screenWidth) { _pointerPosition.x = 0; } if (_pointerPosition.x < 0) { _pointerPosition.x = DroidzActivity.screenWidth; } if (_pointerPosition.y > DroidzActivity.screenHeight) { _pointerPosition.y = 0; } if (_pointerPosition.y < 0) { _pointerPosition.y = DroidzActivity.screenHeight; } } else if (!_dragging) { ControlDragged = false; // Snap back to center when the joystick is released _touchingPoint.x = (int) initx; _touchingPoint.y = (int) inity; // shaft.alpha = 0; } } public void setAttackMode(boolean attackMode) { this.attackMode = attackMode; } public boolean isAttackMode() { return attackMode; } public void setAngle(double angle) { this.angle = angle; } public static double getAngle() { return angle; } }` I should also note that the player has animations based on when he is moving or attacking. EDIT: I got the angle and am rotating the sprite around in the correct angle however it rotates on the wrong spot. My sprite is one giant bitmap that gets cut into four pieces and only one shown at a time to animate walking. here is the code I am using to rotate him right now. ` public void draw(Canvas canvas,int pointerX, int pointerY) { Matrix m; if (setRotation){ // canvas.save(); m = new Matrix(); m.reset(); // spriteWidth and spriteHeight are for just the current frame showed //m.setTranslate(spriteWidth / 2, spriteHeight / 2); //get and set rotation for ninja based off of joystick m.preRotate((float) GameControls.getRotation()); //create the rotated bitmap flipedSprite = Bitmap.createBitmap(bitmap , 0, 0,bitmap.getWidth(),bitmap.getHeight() , m, true); //set new bitmap to rotated ninja setBitmap(flipedSprite); setRotation = false; // canvas.restore(); Log.d("Ninja View", "angle of rotation= " +(float) GameControls.getRotation()); } ` And then the draw method // create the destination rectangle for the ninjas current animation frame // pointerX and pointerY are from the joystick moving the ninja around destRect = new Rect(pointerX, pointerY, pointerX + spriteWidth, pointerY + spriteHeight); canvas.drawBitmap(bitmap, getSourceRect(), destRect, null);

    Read the article

  • Optimum number of threads while multitasking

    - by Gun Deniz
    I know similar questions have been asked but I think my case is a little bit diffrent. Let's say I have a computer with 8 cores and infinite memory with a Linux OS. I have a calculation software called Gaussian that can take advantage of multithreading. So I set its thread count to 8 for a single calculation for maximum speed. However I really can't decide what to do when I need to do run for instance 8 calculations simultaneously. In that case should I set the thread count to 1(total 8 threads spawned in 8 processes) or keep it 8(total 64 threads spawned in 8 processes) for each job? Does it really matter much? A related question is does the OS automatically does the core-parking to diffrent cores for each thread?

    Read the article

  • Calculate age in days/months/years in OpenOffice

    - by Sanjay
    In need to find the age in days - months - years in OpenOffice. There is DATEDIF() in Microsoft Excel. You can use it to find the difference in days/months/years between two dates. Age Calculation You can calculate a persons age based on their birthday and todays date. The calculation uses the DATEDIF() function. The DATEDIF() is not documented in Excel 5, 7 or 97, but it is in 2000. (Makes you wonder what else Microsoft forgot to tell us!) Birth date : 01-Jan-60 Years lived : 52 =DATEDIF(C8,TODAY(),"y") and the months : 4 =DATEDIF(C8,TODAY(),"ym") and the days : 30 =DATEDIF(C8,TODAY(),"md") One can calculate by below formula, but it is cumbersome to calculate months. Another way to calculate age This method gives you an age which may potentially have decimal places representing the months. If the age is 20.5, the .5 represents 6 months. Birth date : 01-Jan-60 Age is : 52.41 =(TODAY()-C23)/365.25

    Read the article

  • What's the value of a Facebook fan?

    - by David Dorf
    In his blog posting titled "Why Each Facebook Fan Is Worth $2,000 to J. Crew," Joe Skorupa lays out a simplistic calculation for assigning a value to social media efforts within Facebook. While I don't believe the metric, at least its a metric that can be applied consistently. Trying to explain the ROI to management to start a program, then benchmarking to show progress isn't straightforward at all. Social media isn't really mature enough to have hard-and-fast rules around valuation (yet). When I'm asked by retailers how to measure social media efforts, I usually fess-up and say I can't show an ROI but the investment is so low you might was well take a risk. Intuitively, it just seems like a good way to interact with consumers, and since your competition is doing it, you better do it as well. Vitrue, a social media management company, has calculated a fan as being worth $3.60 per year based on impressions generated in Facebook's news feed. That means a fan base of 1 million translates into at least $3.6 million in equivalent media over a year. Don't believe that number either? Fine, Vitrue now has a tool that let's you adjust the earned media value of a fan. Jump over to http://evaluator.vitrue.com/ and enter your brand's Facebook URL to get an assessment of the current value and potential value. For fun, I compared Abercrombie & Fitch (1,077,480 fans), Gap (567,772 fans), and Wet Seal (294,479 fans). The image below shows the results assuming the default $5 earned media value for a fan. The calculation is more complicated than just counting fans. It also accounts for postings and comments. Its possible for a brand with fewer fans to have a higher value based on frequency and relevancy of posts. The tool gathers data via the Social Graph API for the past 30 days of activity. I'm not sure this tool assigns the correct value either, but hey, its a great start.

    Read the article

  • controlling an object through another object ?

    - by Stefano Borini
    Today I've seen the following pattern: you have an object A and an object B. Object B accepts a pointer to A at its constructor. Once B is created, there's a method B.doCalc() that performs a calculation (internally using A's information). The result is obtained with method B.getResult(). In order to perform another calculation, A is modified, and B.doCalc() is called again. What is your opinion on this choice ? I would have designed it differently, but I want to hear your voice. Edit : note that my main objection is to modify A to have a different result from B, without touching B. Although similar, I think that just this discipline expresses a much better feeling of what's going on. Instead of a = new A a.whatever = 5 b = new B(a) b.doCalc() res = b.getResult() a.whatever = 6 b.doCalc() res = b.getResult() You get the a pointer object from b itself. a = new A a.whatever = 5 b = new B(a) b.doCalc() res = b.getResult() a = b.getAPointer() a.whatever = 6 b.doCalc() res = b.getResult() because it makes more explicit the fact that a is taken from b and then modified. I still don't like it, though...

    Read the article

  • Calculating distance from viewer to object in a shader

    - by Jay
    Good morning, I'm working through creating the spherical billboards technique outlined in this paper. I'm trying to create a shader that calculates the distance from the camera to all objects in the scene and stores the results in a texture. I keep getting either a completely black or white texture. Here are my questions: I assume the position that's automatically sent to the vertex shader from ogre is in object space? The gpu interpolates the output position from the vertex shader when it sends it to the fragment shader. Does it do the same for my depth calculation or do I need to move that calculation to the fragment shader? Is there a way to debug shaders? I have no errors but I'm not sure I'm getting my parameters passed into the shaders correctly. Here's my shader code: void DepthVertexShader( float4 position : POSITION, uniform float4x4 worldViewProjMatrix, uniform float3 eyePosition, out float4 outPosition : POSITION, out float Depth ) { // position is in object space // outPosition is in camera space outPosition = mul( worldViewProjMatrix, position ); // calculate distance from camera to vertex Depth = length( eyePosition - position ); } void DepthFragmentShader( float Depth : TEXCOORD0, uniform float fNear, uniform float fFar, out float4 outColor : COLOR ) { // clamp output using clip planes float fColor = 1.0 - smoothstep( fNear, fFar, Depth ); outColor = float4( fColor, fColor, fColor, 1.0 ); } fNear is the near clip plane for the scene fFar is the far clip plane for the scene

    Read the article

  • Where ORMs blur the lines between code and data, how do you decide what logic should be a stored procedure, and what should be coded?

    - by PhonicUK
    Take the following pseudocode: CreateInvoiceAndCalculate(ItemsAndQuantities, DispatchAddress, User); And say CreateInvoice does the following: Create a new entry in an Invoices table belonging to the specified User to be sent to the given DispatchAddress. Create a new entry in an InvoiceItems table for each of the items in ItemsAndQuantities, storing the Item, the Quantity, and the cost of the item as of now (by looking it up from an Items table) Calculate the total amount of the invoice (ex shipping and taxes) and store it in the new Invoice row. At a glace you wouldn't be able to tell if this was a method in my applications code, or a stored procedure in the database that is being exposed as a function by the ORM. And to some extent it doesn't really matter. Now technically none of this is business logic. You're not making any decisions - just performing a calculation and creating records. However some may argue that because you are performing a calculation that affects the business (the total amount to be invoiced) that this isn't something that should be done in a stored procedure and instead should be in code. So for this specific example - why would it be more appropriate to do one or the other? And where do you draw the line? Or does it even particular matter as long as it's sufficiently well documented?

    Read the article

  • Having trouble binding a ksoap object to an ArrayList in Android

    - by Maskau
    I'm working on an app that calls a web service, then the webservice returns an array list. My problem is I am having trouble getting the data into the ArrayList and then displaying in a ListView. Any ideas what I am doing wrong? I know for a fact the web service returns an ArrayList. Everything seems to be working fine, just no data in the ListView or the ArrayList.....Thanks in advance! EDIT: So I added more code to the catch block of run() and now it's returning "org.ksoap2.serialization.SoapObject".....no more no less....and I am even more confused now... package com.maskau; import java.util.ArrayList; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.AndroidHttpTransport; import android.app.*; import android.os.*; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.view.View; import android.view.View.OnClickListener; public class Home extends Activity implements Runnable{ /** Called when the activity is first created. */ public static final String SOAP_ACTION = "http://bb.mcrcog.com/GetArtist"; public static final String METHOD_NAME = "GetArtist"; public static final String NAMESPACE = "http://bb.mcrcog.com"; public static final String URL = "http://bb.mcrcog.com/karaoke/service.asmx"; String wt; public static ProgressDialog pd; TextView text1; ListView lv; static EditText myEditText; static Button but; private ArrayList<String> Artist_Result = new ArrayList<String>(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); myEditText = (EditText)findViewById(R.id.myEditText); text1 = (TextView)findViewById(R.id.text1); lv = (ListView)findViewById(R.id.lv); but = (Button)findViewById(R.id.but); but.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { wt = ("Searching for " + myEditText.getText().toString()); text1.setText(""); pd = ProgressDialog.show(Home.this, "Working...", wt , true, false); Thread thread = new Thread(Home.this); thread.start(); } } ); } public void run() { try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); PropertyInfo pi = new PropertyInfo(); pi.setName("ArtistQuery"); pi.setValue(Home.myEditText.getText().toString()); request.addProperty(pi); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); AndroidHttpTransport at = new AndroidHttpTransport(URL); at.call(SOAP_ACTION, envelope); java.util.Vector<Object> rs = (java.util.Vector<Object>)envelope.getResponse(); if (rs != null) { for (Object cs : rs) { Artist_Result.add(cs.toString()); } } } catch (Exception e) { // Added this line, throws "org.ksoap2.serialization.SoapObject" when run Artist_Result.add(e.getMessage()); } handler.sendEmptyMessage(0); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { ArrayAdapter<String> aa; aa = new ArrayAdapter<String>(Home.this, android.R.layout.simple_list_item_1, Artist_Result); lv.setAdapter(aa); try { if (Artist_Result.isEmpty()) { text1.setText("No Results"); } else { text1.setText("Complete"); myEditText.setText("Search Artist"); } } catch(Exception e) { text1.setText(e.getMessage()); } aa.notifyDataSetChanged(); pd.dismiss(); } }; }

    Read the article

  • How to convert an object into a double?

    - by george t.
    I am working on VS C# on the following code, which converts an user input math expression and computes it. MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl(); sc.Language = "VBScript"; sc.ExecuteStatement( "function pi\n" + "pi = 3.14159265\n" + "end function"); sc.ExecuteStatement( "function e\n" + "e = exp(1)\n" + "end function"); expression = textBox1.Text.ToString(); expression = expression.Replace("x", i.ToString()); object y = sc.Eval(expression); string k = y.ToString(); double result = double.Parse(k); While this outputs onto the console with the correct result, I want to use the values to make a graph of the function user inputs and it's not doing it correctly. Thank you for your help.

    Read the article

  • Angle between two 2d vectors, diff between two methods?

    - by Sean Ochoa
    Hey all. I've got this code snippet, and I'm wondering why the results of the first method differ from the results of the second method, given the same input? public double AngleBetween_1(vector a, vector b) { var dotProd = a.Dot(b); var lenProd = a.Len*b.Len; var divOperation = dotProd/lenProd; return Math.Acos(divOperation) * (180.0 / Math.PI); } public double AngleBetween_2(vector a, vector b) { var dotProd = a.Dot(b); var lenProd = a.Len*b.Len; var divOperation = dotProd/lenProd; return (1/Math.Cos(divOperation)) * (180.0 / Math.PI); }

    Read the article

  • CGBitmapContextCreate: unsupported parameter combination

    - by tarmes
    I'm getting this error when creating a bitmap context: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 24 bits/pixel; 3-component color space; kCGImageAlphaNone; 7936 bytes/row. Here's the code (note that the context is based on the parameters of an existing CGImage: context = CGBitmapContextCreate(NULL, (int)pi.bufferSizeRequired.width, (int)pi.bufferSizeRequired.height, CGImageGetBitsPerComponent(imageRef), 0, CGImageGetColorSpace(imageRef), CGImageGetBitmapInfo(imageRef)); Width is 2626, height is 3981. I've leaving bytesPerRow at zero so that it gets calculated automatically for me, and it's chosen 7936 of its own accord. So, where on Earth is the inconsistency? It's driving me nuts.

    Read the article

  • Using python to play two sine tones at once

    - by Alex
    I'm using python to play a sine tone. The tone is based off the computer's internal time in minutes, but I'd like to simultaneously play one based off the second for a harmonized or dualing sound. This is what I have so far; can someone point me in the right direction? from struct import pack from math import sin, pi import time def au_file(name, freq, dur, vol): fout = open(name, 'wb') # header needs size, encoding=2, sampling_rate=8000, channel=1 fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1)) factor = 2 * pi * freq/8000 # write data for seg in range(8 * dur): # sine wave calculations sin_seg = sin(seg * factor) fout.write(pack('b', vol * 127 * sin_seg)) fout.close() t = time.strftime("%S", time.localtime()) ti = time.strftime("%M", time.localtime()) tis = float(t) tis = tis * 100 tim = float(ti) tim = tim * 100 if __name__ == '__main__': au_file(name='timeSound1.au', freq = tim, dur=1000, vol=1.0) import os os.startfile('timeSound1.au')

    Read the article

  • ASP.NET MVC 2.0 RTM cannot work with VWD 2008 Express on a new Windows 7 Pro

    - by silent
    The MVC 2.0 RTM works great on my old Vista computer with VWD 2008 Express, but I just bought a new computer with Windows 7 Pro, I installed VWD 2008 Express SP1 and MVC 2.0 RTM by using Web PI 2.0. but after installation, I found the VWD doesn't have any MVC options, that means I can't either create new MVC projects or compile existing MVC projects. Why? What other steps I need to do to make it work? I'm sure the MVC has been installed properly since my MVC site on the new computer works well (so the IIS side has no problem), just the VWD can't 'realize' that the MVC framework is already installed... (tried to uninstall and install many times, and I also tried to install MVC separately without Web PI, but it just won't work)

    Read the article

  • Using python to play two sin tones at once

    - by Alex
    Im using python to a sine tone. the tone is based off the computers internal time in minutes, but id like to simultaneously play one based off the second for a harmonized or dualing sound. This is what I have so far can someone point me in the right direction. from struct import pack from math import sin, pi import time def au_file(name, freq, dur, vol): fout = open(name, 'wb') # header needs size, encoding=2, sampling_rate=8000, channel=1 fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1)) factor = 2 * pi * freq/8000 # write data for seg in range(8 * dur): # sine wave calculations sin_seg = sin(seg * factor) fout.write(pack('b', vol * 127 * sin_seg)) fout.close() t = time.strftime("%S", time.localtime()) ti = time.strftime("%M", time.localtime()) tis = float(t) tis = tis * 100 tim = float(ti) tim = tim * 100 if name == 'main': au_file(name='timeSound1.au', freq = tim, dur=1000, vol=1.0) import os os.startfile('timeSound1.au')

    Read the article

  • Inheritance of Custom Attributes on Abstract Properties

    - by Marty Trenouth
    I've got a custom attribute that I want to apply to my base abstract class so that I can skip elements that don't need to be viewed by the user when displaying the item in HTML. It seems that the properties overriding the base class are not inheriting the attributes. Does overriding base properties (abstract or virtual) blow away attributes placed on the original property? From Attribute class Defination [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public class NoHtmlOutput : Attribute { } From Abstract Class Defination [NoHtmlOutput] public abstract Guid UniqueID { get; set; } From Concrete Class Defination public override Guid UniqueID{ get{ return MasterId;} set{MasterId = value;}} From class checking for attribute Type t = o.GetType(); foreach (PropertyInfo pi in t.GetProperties()) { if (pi.GetCustomAttributes(typeof(NoHtmlOutput), true).Length == 1) continue; // processing logic goes here }

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >