Search Results

Search found 1510 results on 61 pages for 'barycentric coordinates'.

Page 57/61 | < Previous Page | 53 54 55 56 57 58 59 60 61  | Next Page >

  • Javascript closures with google geocoder

    - by DaNieL
    Hi all, i still have some problems with javascript closures, and input/output variables. Im playing with google maps api for a no profit project: users will place the marker into a gmap, and I have to save the locality (with coordinates) in my db. The problem comes when i need to do a second geocode in order to get a unique pairs of lat and lng for a location: lets say two users place the marker in the same town but in different places, I dont want to have the same locality twice in the database with differents coords. I know i can do the second geocode after the user select the locality, but i want to understand what am i mistaking here: // First geocoding, take the marker coords to get locality. geocoder.geocode( { 'latLng': new google.maps.LatLng($("#lat").val(), $("#lng").val()), 'language': 'it' }, function(results_1, status_1){ // initialize the html var inside this closure var html = ''; if(status_1 == google.maps.GeocoderStatus.OK) { // do stuff here for(i = 0, geolen = results_1[0].address_components.length; i != geolen) { // Second type of geocoding: for each location from the first geocoding, // i want to have a unique [lat,lan] geocoder.geocode( { 'address': results_1[0].address_components[i].long_name }, function(results_2, status_2){ // Here come the problem. I need to have the long_name here, and // 'html' var should increment. coords = results_2[0].geometry.location.toUrlValue(); html += 'some html to let the user choose the locality'; } ); } // Finally, insert the 'html' variable value into my dom... //but it never gets updated! } else { alert("Error from google geocoder:" + status_1) } } ); I tryed with: // Second type of geocoding: for each location from the first geocoding, i want // to have a unique [lat,lan] geocoder.geocode( { 'address': results_1[0].address_components[i].long_name }, (function(results_2, status_2, long_name){ // But in this way i'll never get results_2 or status_2, well, results_2 // get long_name value, status_2 and long_name is undefined. // However, html var is correctly updated. coords = results_2[0].geometry.location.toUrlValue(); html += 'some html to let the user choose the locality'; })(results_1[0].address_components[i].long_name) ); And with: // Second type of geocoding: for each location from the first geocoding, i want to have // a unique [lat,lan] geocoder.geocode( { 'address': results_1[0].address_components[i].long_name }, (function(results_2, status_2, long_name){ // But i get an obvious "results_2 is not defined" error (same for status_2). coords = results_2[0].geometry.location.toUrlValue(); html += 'some html to let the user choose the locality, that can be more than one'; })(results_2, status_2, results_1[0].address_components[i].long_name) ); Any suggestion? EDIT: My problem is how to pass an additional arguments to the geocoder inner function: function(results_2, status_2, long_name){ //[...] } becose if i do that with a clousure, I mess with the original parameters (results_2 and status_2)

    Read the article

  • How can I position some divs inside an unordered list so they line up with the root element of the l

    - by Ronedog
    I want to position all the divs to line up to the left on the same x coordinate so it looks nice. Notice the picture below, how based on the number of nested categories the div (and its contents) show up at slightly different x coordinates. I need to have the div's line up at exactly the same x coordinate no matter how deeply nested. Note, the bottom most category always has a div for the content, but that div has to be situated inside the last < li . I am using an unordered list to display the menu and thought the best solution would be to grab the root category (Cat 2, and mCat1) and obtain their left offset using jquery, then simply use that value to update the positioning of the div...but I couldn't seem to get it to work just right. I would appreciate any advice or help that you are willing to give. Heres the HTML <ul id="nav> <li>Cat 2 <ul> <li>sub cat2</li> </ul> </li> <li>mCat1 <ul> <li>Subcat A <ul> <li>Subcat A.1 <ul> <li>Annie</li> </ul> </li> </ul> </li> </ul> </li> </ul> Heres some jquery I tried (I have do insert the div inside this .each() loop in order to retrieve some values, but basically, this selector is grabbing the last < li in the menu tree and placing a div after it and that is the div that I want to position. the 245 value was something I was playing around with to see how I could get things to line up, and I know its out of wack, but the problem is still the same no matter what I do: $("#nav li:not(:has(li))").each(function () { var self = $(this); var position = self.offset(); var xLeft = Math.round(position.left)- 245; console.log("xLeft:", xLeft ); self.after( '<div id="' + self.attr('p_node') + '_p_cont_div" class="property_position" style="display:none; left:' + xLeft + 'px;" /> ' ); }); Heres the css: .property_position{ float:left; position: relative; top: 0px; padding-top:5px; padding-bottom:10px; }

    Read the article

  • current location too slow for view

    - by Christian
    Hi, I make an App with a Map in the App and a button to change to the google.Map-App. The code for my position is: -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { float avgAccuracy = (newLocation.verticalAccuracy + newLocation.horizontalAccuracy)/2.0; if (avgAccuracy < 500) { [locationManager stopUpdatingLocation]; locationManager.delegate = nil; } storedLocation = [newLocation coordinate]; The code for the view is: - (void)viewDidLoad { [super viewDidLoad]; UIImage *image = [UIImage imageNamed: @"LogoNavBar.png"]; UIImageView *imageview = [[UIImageView alloc] initWithImage: image]; UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView: imageview]; self.navigationItem.rightBarButtonItem = button; [imageview release]; [button release]; locationManager=[[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.distanceFilter = kCLDistanceFilterNone; [locationManager startUpdatingLocation]; mapView.showsUserLocation = YES; NSLog(@"storedLocation-latitude für MKregion: %f", storedLocation.latitude); MKCoordinateRegion region; region.center.latitude = (storedLocation.latitude + 45.58058)/2.0; region.center.longitude = (storedLocation.longitude - 0.546835)/2.0; region.span.latitudeDelta = ABS(storedLocation.latitude - 45.58058); region.span.longitudeDelta = ABS(storedLocation.longitude + 0.546835); [mapView setRegion:region animated:TRUE]; MKCoordinateRegion hotel; hotel.center.latitude = 45.58058; hotel.center.longitude = -0.546835; HotelPositionMarker* marker = [[HotelPositionMarker alloc] initWithCoordinate:hotel.center]; [mapView addAnnotation:marker]; [marker release]; } My problem: when the "viewDidLoad" start, the "storedLocation" is still 0.0000 it takes a bit longer to get the own position than to start the view. The Log for the "storedLocation" in the "viewDidLoad"-section is 0 while the Log of the "storedLocation" in the "-(IBAction)" when the map is visible contains the right values. How can I manage it to have my coordinates before the view load? I need them to center the view concerning the own position and the position given by me. MKCoordinateRegion region; region.center.latitude = (storedLocation.latitude + 45.58058)/2.0; region.center.longitude = (storedLocation.longitude - 0.546835)/2.0; region.span.latitudeDelta = ABS(storedLocation.latitude - 45.58058); region.span.longitudeDelta = ABS(storedLocation.longitude + 0.546835); [mapView setRegion:region animated:TRUE];

    Read the article

  • Placing a window near the system tray

    - by user227990
    I am writing a program that needs to set a window just above/below the traybar for gtk. I have tried using the 2 approaches that failed. One was using the gtk_status_icon_position_menu function and placing the window in the point where the user clicks (in the tray bar). The problem is that these solutions work in gnome(Linux) but not in Windows. In Linux they work because the window manager doesn't seem to allow placement of windows in the tray panel, honoring the closest possible. In Windows this doesn't happen and the window can go "out" of the screen which understandably is not desired. With this said i went out for a work around. My idea was to set the window in the location of mouse click and get the x and y coordinates of a normal window placement and with it's size check if it would be within the screen boundaries. If it was not make the correction. I have came up with the functions needed but for some reason the gdk_drawable_get_size(window-window ,&WindowWidth, &WindowHeight) and other similar functions only give the correct size value after the second run of the signal function. The result of the first run is just 1 to both size and width. (I have read the issue of X11 not giving correct results, but i think this is not it) event_button = (GdkEventButton *) event; if (event_button->button == 1) { if (active == 0) { gboolean dummy; gint WindowHeight, WindowWidth, WindowPosition[2]; GdkScreen *screen; gint ScreenHeight, ScreenWidth; dummy = FALSE; gtk_widget_show_all(window); gtk_window_present(GTK_WINDOW(window)); gtk_status_icon_position_menu(menu, &pos[X], &pos[Y], &dummy, statusicon); gtk_window_move(GTK_WINDOW(window), pos[X],pos[Y]); gdk_drawable_get_size(window->window ,&WindowWidth, &WindowHeight); screen = gtk_status_icon_get_screen(statusicon); ScreenWidth = gdk_screen_get_width(screen); ScreenHeight = gdk_screen_get_height(screen); g_print("Screen: %d, %d\nGeometry: %d, %d\n",ScreenWidth, ScreenHeight, WindowWidth, window->allocation.height); gtk_entry_set_text(GTK_ENTRY(entry),""); active = 1; return TRUE; } How can i do what i want in a portable way?

    Read the article

  • iphone cocos2d sprites disappearing

    - by jer
    I've been working on a game and implementing the physics stuff with chipmunk. All was going fine on the cocos2d part until the integration with chipmunk. A bit of background: The game is a game with blocks. Levels are defined in a property list, where positions, size of the blocks, gravitational forces, etc., are all defined for each block to be shown in the level. The problem is with the blocks showing up. I have a method on my BlockLayer class which is part of my game's main scene. Upon creation of the layer, the property list is read, and all the blocks are created. The following method is called to create the blocks: - (void)createBlock:(Block*)block withAssets:(NSBundle*)assets { Sprite* sprite; switch(block.blockColour) { case kBlockColourGreen: sprite = [Sprite spriteWithFile:[assets pathForResource:@"green" ofType:@"png" inDirectory:@"Blocks"]]; break; case kBlockColourOrange: sprite = [Sprite spriteWithFile:[assets pathForResource:@"orange" ofType:@"png" inDirectory:@"Blocks"]]; break; case kBlockColourRed: sprite = [Sprite spriteWithFile:[assets pathForResource:@"red" ofType:@"png" inDirectory:@"Blocks"]]; break; case kBlockColourBlue: sprite = [Sprite spriteWithFile:[assets pathForResource:@"blue" ofType:@"png" inDirectory:@"Blocks"]]; break; } sprite.position = block.bounds.origin; [self addChild:sprite]; if(block.blockColour == kBlockColourGreen || block.blockColour == kBlockColourRed) space-gravity = cpvmult(cpv(0, 10), 1000); cpVect verts[] = { cpv(-block.bounds.size.width, -block.bounds.size.height), cpv(-block.bounds.size.width, block.bounds.size.height), cpv(block.bounds.size.width, block.bounds.size.height), cpv(block.bounds.size.width, -block.bounds.size.height) }; cpBody* blockBody = cpBodyNew([block.mass floatValue], INFINITY); blockBody-p = cpv(block.bounds.origin.x, block.bounds.origin.y); blockBody-v = cpvzero; cpSpaceAddBody(space, blockBody); cpShape* blockShape = cpPolyShapeNew(blockBody, 4, verts, cpvzero); blockShape-e = 0.9f; blockShape-u = 0.9f; blockShape-data = sprite; cpSpaceAddShape(space, blockShape); } With the above code, the sprites never show up. However, if I comment out the "cpSpaceAddBody(space, blockBody);" line, the sprites show up. The position and size of the blocks are stored in the "bounds" property of instances of the Block class, which is a CGRect. Not sure if it's important, but the orientation of the app is in landscape left, and all the coordinates are based on that orientation. Any help would be greatly appreciated.

    Read the article

  • OpenGL Vertex Buffer Object code giving bad output.

    - by Matthew Mitchell
    Hello. My Vertex Buffer Object code is supposed to render textures nicely but instead the textures are being rendered oddly with some triangle shapes. What happens - http://godofgod.co.uk/my_files/wrong.png What is supposed to happen - http://godofgod.co.uk/my_files/right.png This function creates the VBO and sets the vertex and texture coordinate data: extern "C" GLuint create_box_vbo(GLdouble size[2]){ GLuint vbo; glGenBuffers(1,&vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); GLsizeiptr data_size = 8*sizeof(GLdouble); GLdouble vertices[] = {0,0, 0,size[1], size[0],0, size[0],size[1]}; glBufferData(GL_ARRAY_BUFFER, data_size, vertices, GL_STATIC_DRAW); data_size = 8*sizeof(GLint); GLint textcoords[] = {0,0, 0,1, 1,0, 1,1}; glBufferData(GL_ARRAY_BUFFER, data_size, textcoords, GL_STATIC_DRAW); return vbo; } Here is some relavant code from another function which is supposed to draw the textures with the VBO. glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor4d(1,1,1,a/255); glBindTexture(GL_TEXTURE_2D, texture); glTranslated(offset[0],offset[1],0); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexPointer(2, GL_DOUBLE, 0, 0); glEnableClientState(GL_VERTEX_ARRAY); glTexCoordPointer (2, GL_INT, 0, 0); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDrawArrays(GL_TRIANGLES, 0, 3); glDrawArrays(GL_TRIANGLES, 1, 3); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); I would have hoped for the code to use the first three coordinates (top-left,bottom-left,top-right) and the last three (bottom-left,top-right,bottom-right) to draw the triangles with the texture data correctly in the most efficient way. I don't see why triangles should make it more efficient but apparently that's the way to go. It, of-course, fails for some reason. I am asking what is broken but also am I going about it in the right way generally? Thank you.

    Read the article

  • Matlab wont extract first row & column because of matrix dimensions !

    - by ZaZu
    Hey guys, I am tracking an object that is thrown in air, and this object governs a parabolic pattern. Im tracking the object through a series of 30 images. I managed to exclude all the background and keep the object apparent, then used its centroid to get its coordinates and plot them. Now im supposed to predict where the object is going to fall, so I used polyfit & polyval .. the problem is, matlab says ??? Index exceeds matrix dimensions. Now the centroid creates its own structure with a row and 2 columns. Everytime the object moves in the loop, it updates the first row only .. Here is part of the code : For N=1:30 . . . x=centroid(1,1); % extract first row and column for x y=centroid(1,2); % extract secnd row and column for x plot_xy=plot(x,y) set(plot_xy,'XData',x(1:N),'YData',y(1:N)); fitting=polyfit(x(1:N),y(1:N),2); parabola=plot(x,nan(23,1)); evaluate=polyval(fitting,x); set(parabola,'YData',evaluate) . . end The error message I get is ??? Index exceeds matrix dimensions. It seems that (1:N) is causing the problems .. I honestly do not know why .. But when I remove N, the object is plotted along with its points, but polyfitting wont work, it gives me an error saying : Warning: Polynomial is not unique; degree >= number of data points. > In polyfit at 72 If I made it (1:N-1) or something, it plots more points before it starts giving me the same error (not unique ...) . Any ideas why ?? Thanks alot !!

    Read the article

  • Container item implementation

    - by onurozcelik
    Hi, I am working in Train Traffic Controller software project. My responsibility in this project is to develop the visual railroad GUI. We are implementing the project with Qt. By now I am using QGraphicsLinearLayout to hold my items. I am using the layout because I do not want to calculate coordinates of each item. So far I wrote item classes to add the layout. For instance SwitchItem class symbolizes railroad switch in real world. Each item class is responsible for its own painting and events. So far so good. Now I need a composite item that can contain two or more item. This class is going to be responsible for painting the items contained in it. I need this class because I have to put two or more items inside same layout cell. If I don' t put them in same cell I can' t use layout. See the image below. BlockSegmentItem and SignalItem inside same cell. Here is my compositeitem implementation. #include "compositeitem.h" CompositeItem::CompositeItem(QString id,QList<FieldItem *> _children) { children = _children; } CompositeItem::~CompositeItem() { } QRectF CompositeItem::boundingRect() const { FieldItem *child; QRectF rect(0,0,0,0); foreach(child,children) { rect = rect.united(child->boundingRect()); } return rect; } void CompositeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget ) { FieldItem *child; foreach(child,children) { child->paint(painter,option,widget); } } QSizeF CompositeItem::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { QSizeF itsSize(0,0); FieldItem *child; foreach(child,children) { // if its size empty set first child size to itsSize if(itsSize.isEmpty()) itsSize = child->sizeHint(Qt::PreferredSize); else { QSizeF childSize = child->sizeHint(Qt::PreferredSize); if(itsSize.width() < childSize.width()) itsSize.setWidth(childSize.width()); itsSize.setHeight(itsSize.height() + childSize.height()); } } return itsSize; } void CompositeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { qDebug()<<"Test"; } This code works good with painting but when it comes to item events it is problematic. QGraphicsScene treats the composite item like a single item which is right for layout but not for events. Because each item has its own event implementation.(e.g. SignalItem has its special context menu event.) I have to handle item events seperately. Also I need a composite item implementation for the layout. How can I overcome this dilemma?

    Read the article

  • Animation using AniMate with Unity3D doesn't interact with physical objects

    - by Albz
    I'm designing a maze with Unity3D. The maze has a number of bifurcations and the player will stop before each bifurcation and simply choose left or right. Then an automatic animation will move the player through the next bifurcation till the end of the maze (or till a dead end). To animate the player I'm using AniMate and C# in my Unity project. Using AniMate I'm simply creating a point-to-point animation for each bifurcation (e.g. mage below: from the start/red arrow to point 5) My problem is that my animation script (associated to the "First Person Controller") is not working properly since physics is not respected (the player passes through walls). If in the same project I enable the standard character controls in Unity, then I can navigate in the maze with the physical contrains of walls etc... (i.e. I have colliders). This is an example of the code I'm using when I press left to pass from starting point, trough point 1 to point 2: void FixedUpdate () { if (Input.GetKey(KeyCode.LeftArrow)) { //To point 1 Hashtable props = new Hashtable(); props.Add("position", new Vector3(756f,112f,1124f)); props.Add("physics", true); Ani.Mate.To(transform, 2, props); //To point 2 Hashtable props2 = new Hashtable(); props2.Add("position", new Vector3(731f,112f,1124f)); props2.Add("physics", true); Ani.Mate.To(transform, 2, props2); } } What happens practically when I press the left arrow button is that the player moves directly to point 2 using a straight line passing through the wall. I tried to pass to AniMate "Physics = true" but it doesn't seem to help. Any idea on how to solve this issue? Alternatively... any hint on how to have a more optimized code and just use a series of vector3 coordinates (one for each point) to obtain the simple animation I want without having to declare new Hashtable(); etc... every time? I chose AniMate simply because 1. I'm a beginner with Unity 2. I don't need complex animations (e.g. I don't need to use iTween), just fixed animations along straight lines and I need something really simple and quick to implement in a script. However, if someone has an equally simple solution it will be welcome. thank you in advance for your help

    Read the article

  • To detect if the user is closing the IE browser apart from onunload event, as it is triggerred when

    - by AndAars
    hi, After being through numerous forums available on the net for last 5 days, I am still not able to completely track down the browser close event. My requirement is to generate a popup message, when user tries to close the browser. I have called my javascript function on body 'onbeforeunload' event. And I have hardcoded the conditions to check the mouse-coordinates for the red 'X' buton of browser, refresh, File-close or Alt-F4. My code works fine when browser window is Maximized, but fails if we shrink it after a limit. Please help me, if some body has already found the solution to a similar problem. Thank you. Aggregated Responses of OP Ok, just tell me if it is possible to detect if a user has clicked on the Refresh button of the browser. Also, Refresh can be triggered by Right-click - Refresh or Ctrl-R. My requirement is to make a variable false on Refresh. I am just able to do it on F5, but all other ways are still out of my reach. The same would be applied to Back buton. Hi ppl, Thanks for all who replied atleast. I have talked to my seniors regarding this and they have now understood and have compromised with the browser menu buttons. So now my task has become easy. Now, I am using a variable and making it true by default. As, I mentioned earlier I just have to catch the onbeforeunload and popup a message when user tries to leave. The message will not popup when user is navigating to other pages, as I have made the variable as false on all the links of my page using following piece of code: document.onclick = function() { //To check if user is navigating from the page by clicking on a hyperlink. if (event.srcElement.tagName == 'A') blnShowMsg = false; //To not popup the warning message else blnShowMsg = true; //To popup the warning message } In my case still the message is shown when user does Refresh, back or goes to any link in Favorites, etc. Thanks buddy, but I have already gone through that and didn't find much help there too. My seniors are not happy with that solution as putting a flag on evry link of my application is a complicated job and they fear of breaking the application. Any other suggestions would be appreciated. Thanks once again. Is there no one who can think of a solution here!!! where are all the experts???

    Read the article

  • Class template specializations with shared functionality

    - by Thomas
    I'm writing a simple maths library with a template vector type: template<typename T, size_t N> class Vector { public: Vector<T, N> &operator+=(Vector<T, N> const &other); // ... more operators, functions ... }; Now I want some additional functionality specifically for some of these. Let's say I want functions x() and y() on Vector<T, 2> to access particular coordinates. I could create a partial specialization for this: template<typename T> class Vector<T, 3> { public: Vector<T, 3> &operator+=(Vector<T, 3> const &other); // ... and again all the operators and functions ... T x() const; T y() const; }; But now I'm repeating everything that already existed in the generic template. I could also use inheritance. Renaming the generic template to VectorBase, I could do this: template<typename T, size_t N> class Vector : public VectorBase<T, N> { }; template<typename T> class Vector<T, 3> : public VectorBase<T, 3> { public: T x() const; T y() const; }; However, now the problem is that all operators are defined on VectorBase, so they return VectorBase instances. These cannot be assigned to Vector variables: Vector<float, 3> v; Vector<float, 3> w; w = 5 * v; // error: no conversion from VectorBase<float, 3> to Vector<float, 3> I could give Vector an implicit conversion constructor to make this possible: template<typename T, size_t N> class Vector : public VectorBase<T, N> { public: Vector(VectorBase<T, N> const &other); }; However, now I'm converting from Vector to VectorBase and back again. Even though the types are the same in memory, and the compiler might optimize all this away, it feels clunky and I don't really like to have potential run-time overhead for what is essentially a compile-time problem. Is there any other way to solve this?

    Read the article

  • Converting OpenGL co-ordinates to lower UIView (and UIImagePickerController)

    - by John Qualis
    Hi, I am new to OpenGL over iPhone. I am developing an iPhone app similar to a barcode reader but with an extra OpenGL layer. The bottommost layer is UIImagePickerController, then I use UIView on top and draw a rectangle at certain co-ordinates on the iphone screen. So far everything is OK. Then I am trying to draw an OpenGL 3-D model in that rectangle. I am able to load a 3-D model in the iPhone based on this code here - http://iphonedevelopment.blogspot.com/2008/12/start-of-wavefront-obj-file-loader.html I am not able to transform the co-ordinates of the rectangle into OpenGL co-ordinates. Appreciate any help. Do I need to use a matrix to translate the currentPosition of the 3-D model so it is drawn within myRect? The code is given below.. Appreciate any help/pointers in this regards. John -(void)setupView:(GLView*)view { const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0; GLfloat size; glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0); CGRect rect = view.bounds; glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size / (rect.size.width / rect.size.height), zNear, zFar); glViewport(0, 0, rect.size.width, rect.size.height); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); NSString *path = [[NSBundle mainBundle] pathForResource:@"plane" ofType:@"obj"]; OpenGLWaveFrontObject *theObject = [[OpenGLWaveFrontObject alloc] initWithPath:path]; Vertex3D position; position.z = -8.0; position.y = 3.0; position.x = 2.0; theObject.currentPosition = position; self.plane = theObject; [theObject release]; } (void)drawView:(GLView*)view; { static GLfloat rotation = 0.0; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glColor4f(0.0, 0.5, 1.0, 1.0); // the coordinates of the rectangle are // myRect.x, myRect.y, myRect.width, myRect.height // Do I need to use a matrix to translate the currentPosition of the // 3-D model so it is drawn within myRect? //glOrthof(-160.0f, 160.0f, -240.0f, 240.0f, -1.0f, 1.0f); [plane drawSelf]; }

    Read the article

  • javascript works with mozilla but not with webkit based browsers

    - by GlassGhost
    Im having problems with a css text variable in this javascript with webkit based browsers(Chrome & Safari) but it works in firefox 3.6 importScript('User:Gerbrant/hidePane.js');//Special thanks to Gerbrant for this wonderful script function addGlobalStyle(css) { var head = document.getElementsByTagName('head')[0]; if (!head) { return; } var style = document.createElement('style'); style.type = 'text/css'; style.rel = 'stylesheet'; style.media = 'screen'; style.href = 'FireFox.css'; style.innerHTML = css; head.appendChild(style); } //The page styling var NewSyleText = "h1, h2, h3, h4, h5 {font-family: 'Verdana','Helvetica',sans-serif; font-style: normal; font-weight:normal;}" + "body, b {background: #fbfbfb; font-style: normal; font-family: 'Cochin','GaramondNo8','Garamond','Big Caslon','Georgia','Times',serif;font-size: 11pt;}" + "p { margin: 0pt; text-indent:1.25em; margin-top: 0.3em; }" + "a { text-decoration: none; color: Navy; background: none;}" + "a:visited { color: #500050;}" + "a:active { color: #faa700;}" + "a:hover { text-decoration: underline;}" + "a.stub { color: #772233;}" + "a.new, #p-personal a.new { color: #ba0000;}" + "a.new:visited, #p-personal a.new:visited { color: #a55858;}" + "a.new, #quickbar a.new { color: #CC2200; }" + /* removes "From Wikipedia, the free encyclopedia" for those of you who actually know what site you are on */ "#siteSub { display: none; }" + /* hides the speaker icon in some articles */ "#spoken-icon .image { display:none;}" + /* KHTMLFix.css */ "#column-content { margin-left: 0; }" + /* Remove contents of the footer, but not the footer itself */ "#f-poweredbyico, #f-copyrightico { display:none;}" + /* Needed to show the star icon in a featured article correctly */ "#featured-star div div { line-height: 10px;}" + /* And the content expands to top and left */ "#content {margin: 0; padding: 0; background:none;}" + "#content div.thumb {border-color:white;}" + /* Hiding the bar under the entry header */ "h1.firstHeading { border-bottom: none;}" + /* Used for US city entries */ "#coordinates { top:1.2em;}"; addGlobalStyle(NewSyleText);//inserts the page styling

    Read the article

  • iPhone Gps logging inaccurate

    - by Martijn
    I'm logging gps points during a walk. Below it shows the function that the coordinates are saved each 5 seconds. i Did several tests but i cannot get the right accuracy i want. (When testing the sky is clear also tests in google maps shows me that the gps signal is good). here is the code: -(void)viewDidAppear:(BOOL)animated{ if (self.locationManager == nil){ self.locationManager = [[[CLLocationManager alloc] init] autorelease]; locationManager.delegate = self; // only notify under 100 m accuracy locationManager.distanceFilter = 100.0f; locationManager.desiredAccuracy= kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; } } - start logging [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(getData) userInfo:nil repeats:YES]; </code> <code> -(void)getData{ int distance; // re-use location. if ([ [NSString stringWithFormat:@"%1.2f",previousLat] isEqualToString:@"0.00"]){ // if previous location is not available, do nothing distance = 0; }else{ CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:previousLat longitude:previousLong]; CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:latGlobal longitude:longGlobal]; distance = [loc1 getDistanceFrom: loc2]; } // overwrite latGlobal with new variable previousLat = latGlobal; previousLong = longGlobal; // store location and save data to database // this part goes ok } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { // track the time to get a new gps result (for gps indicator orb) lastPointTimestamp = [newLocation.timestamp copy]; // test that the horizontal accuracy does not indicate an invalid measurement if (newLocation.horizontalAccuracy < 0) return; // test the age of the location measurement to determine if the measurement is cached // don't rely on cached measurements NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; if (locationAge > 5.0) return; latGlobal = fabs(newLocation.coordinate.latitude); longGlobal= fabs(newLocation.coordinate.longitude); } I have taken a screenshot of the plot results (the walk takes 30 minutes) and an example of what i'am trying to acomplish: http://www.flickr.com/photos/21258341@N07/4623969014/ i really hope someone can put me in the right direction.

    Read the article

  • MATLAB plot moving data points in seperate subplots simutaneously

    - by Nate B.
    I wish to visualize the movement of a data point throughout space across a period of time within MATLAB. However, the way I want my figure to display is such that only a single instant is plotted at any given time. That was easy, I simply created a for loop to update my 3D plot display for every set of coordinates (x,y,z) in my data. However, I wish to display 4 different viewing angles of this plot at all times. I am well aware of how to setup subplots within MATLAB, that is not the issue. My issue is getting all 4 of these subplots to execute simultaneously so that all 4 subplots are always displaying the same point in time. I would appreciate if anyone could suggest how to handle this issue. As requested, my code for a figure with a single plot is shown below: datan = DATA; %data in form of x,y,z,a,b,c by column for row# of time points tib=zeros(size(datan,1),12); tib(:,1:3) = datan(:,1:3); tib_ref=tib(1,1:3); for i=1:size(datan,1) tib(i,1:3)=tib(i,1:3)-tib_ref; end angle_to_dircos close all figure('Name','Directions (Individual Cycles)','NumberTitle','off') for cc=1:2 hold off for bb=1:10:size(tib,1); scatter3(tib(bb,1),tib(bb,2),tib(bb,3),'green','filled'); %z and y axes are flipped in polhemus system hold on p0 = [tib(bb,1),tib(bb,2),tib(bb,3)]; p1 = [tib(bb,1)+10*tib(bb,4),tib(bb,2)+10*tib(bb,5),tib(bb,3)+10*tib(bb,6)]; p2 = [tib(bb,1)+10*tib(bb,7),tib(bb,2)+10*tib(bb,8),tib(bb,3)+10*tib(bb,9)]; p3 = [-(tib(bb,1)+100*tib(bb,10)),-(tib(bb,2)+100*tib(bb,11)),-(tib(bb,3)+100*tib(bb,12))]; vectarrow(p0,p1,1,0,0) hold on vectarrow(p0,p2,0,1,0) hold on vectarrow(p0,p3,0,0,1) hold on az = 90; el = 0; view(az, el); xlim([-50,50]); ylim([-50,50]); zlim([-50,50]); xlabel('distance from center in X'); ylabel('distance from center in Y'); zlabel('distance from center in Z'); title('XYZ Scatter Plots of Tracker Position'); hold on plot3(0,0,0,'sk','markerfacecolor',[0,0,0]); p0 = [0,0,0]; p1 = [10,0,0]; p2 = [0,10,0]; p3 = [0,0,100]; vectarrow(p0,p1,1,0,0) hold on vectarrow(p0,p2,0,1,0) hold on vectarrow(p0,p3,1,0,1) drawnow; end end

    Read the article

  • Using drawAtPoint with my CIImage not doing anything on screen

    - by Adam
    Stuck again. :( I have the following code crammed into a procedure invoked when I click on a button on my application main window. I'm just trying to tweak a CIIMage and then display the results. At this point I'm not even worried about exactly where / how to display it. I'm just trying to slam it up on the window to make sure my Transform worked. This code seems to work down through the drawAtPoint message. But I never see anything on the screen. What's wrong? Thanks. Also, as far as displaying it in a particular location on the window ... is the best technique to put a frame of some sort on the window, then get the coordinates of that frame and "draw into" that rectangle? Or use a specific control from IB? Or what? Thanks again. // earlier I initialize a NSImage from JPG file on disk. // then create NSBitmapImageRep from the NSImage. This all works fine. // then ... CIImage * inputCIimage = [[CIImage alloc] initWithBitmapImageRep:inputBitmap]; if (inputCIimage == Nil) NSLog(@"could not create CI Image"); else { NSLog (@"CI Image created. working on transform"); CIFilter *transform = [CIFilter filterWithName:@"CIAffineTransform"]; [transform setDefaults]; [transform setValue:inputCIimage forKey:@"inputImage"]; NSAffineTransform *affineTransform = [NSAffineTransform transform]; [affineTransform rotateByDegrees:3]; [transform setValue:affineTransform forKey:@"inputTransform"]; CIImage * myResult = [transform valueForKey:@"outputImage"]; if (myResult == Nil) NSLog(@"Transformation failed"); else { NSLog(@"Created transformation successfully ... now render it"); [myResult drawAtPoint: NSMakePoint ( 0,0 ) fromRect: NSMakeRect ( 0,0,128,128 ) operation: NSCompositeSourceOver fraction: 1.0]; //100% opaque [inputCIimage release]; } }

    Read the article

  • Java: Preventing array going out of bounds.

    - by Troy
    I'm working on a game of checkers, if you want to read more about you can view it here; http://minnie.tuhs.org/I2P/Assessment/assig2.html When I am doing my test to see if the player is able to get to a certain square on the grid (i.e. +1 +1, +1 -1 .etc) from it's current location, I get an java.lang.ArrayIndexOutOfBoundsException error. This is the code I am using to make the move; public static String makeMove(String move, int playerNumber) { // variables to contain the starting and destination coordinates, subtracting 1 to match array size int colStart = move.charAt(1) - FIRSTCOLREF - 1; int rowStart = move.charAt(0) - FIRSTROWREF - 1; int colEnd = move.charAt(4) - FIRSTCOLREF - 1; int rowEnd = move.charAt(3) - FIRSTROWREF - 1; // variable to contain which player is which char player, enemy; if (playerNumber==1) { player= WHITEPIECE; enemy= BLACKPIECE; } else { player= BLACKPIECE; enemy= WHITEPIECE; } // check that the starting square contains a player piece if (grid [ colStart ] [ rowStart ] == player) { // check that the player is making a diagonal move if (grid [ colEnd ] [ rowEnd ] == grid [ (colStart++) ] [ (rowEnd++) ] && grid [ colEnd ] [ rowEnd ] == grid [ (colStart--) ] [ (rowEnd++) ] && grid [ colEnd ] [ rowEnd ] == grid [ (colStart++) ] [ (rowEnd--) ] && grid [ colEnd ] [ rowEnd ] == grid [ (colStart--) ] [ (rowEnd--) ]) { // check that the destination square is free if (grid [ colEnd ] [ rowEnd ] == BLANK) { grid [ colStart ] [ rowStart ] = BLANK; grid [ colEnd ] [ rowEnd ] = player; } } // check if player is jumping over a piece else if (grid [ colEnd ] [ rowEnd ] == grid [ (colStart+2) ] [ (rowEnd+2) ] && grid [ colEnd ] [ rowEnd ] == grid [ (colStart-2) ] [ (rowEnd+2) ] && grid [ colEnd ] [ rowEnd ] == grid [ (colStart+2) ] [ (rowEnd-2) ] && grid [ colEnd ] [ rowEnd ] == grid [ (colStart-2) ] [ (rowEnd-2) ]) { // check that the piece in between contains an enemy if ((grid [ (colStart++) ] [ (rowEnd++) ] == enemy ) && (grid [ (colStart--) ] [ (rowEnd++) ] == enemy ) && (grid [ (colStart++) ] [ (rowEnd--) ] == enemy ) && (grid [ (colStart--) ] [ (rowEnd--) ] == enemy )) { // check that the destination is free if (grid [ colEnd ] [ rowEnd ] == BLANK) { grid [ colStart ] [ rowStart ] = BLANK; grid [ colEnd ] [ rowEnd ] = player; } } } } I'm not sure how I can prevent the error from happening, what do you recommend?

    Read the article

  • Openlayers and Bing Maps (POLYGONS)

    - by Jordan
    When trying to draw polygons onto a bing map, the initial marker is set differently on the map. How can I fix this? OpenLayers Bing Example <script src="OpenLayers.js"></script> <script> var map; function init(){ map = new OpenLayers.Map("map"); map.addControl(new OpenLayers.Control.LayerSwitcher()); var shaded = new OpenLayers.Layer.VirtualEarth("Shaded", { type: VEMapStyle.Shaded }); var hybrid = new OpenLayers.Layer.VirtualEarth("Hybrid", { type: VEMapStyle.Hybrid }); var aerial = new OpenLayers.Layer.VirtualEarth("Aerial", { type: VEMapStyle.Aerial }); var POLY_LAYER = new OpenLayers.Layer.Vector(); map.addLayers([shaded, hybrid, aerial, POLY_LAYER]); map.setCenter(new OpenLayers.LonLat(-110, 45), 3); var polygon = new OpenLayers.Control.DrawFeature(POLY_LAYER, OpenLayers.Handler.Polygon); map.addControl(polygon); polygon.activate(); } </script> Bing Example <div id="tags"> Bing, Microsoft, Virtual Earth </div> <p id="shortdesc"> Demonstrates the use of Bing layers. </p> <div id="map" class="smallmap"></div> <div id="docs">This example demonstrates the ability to create layers using tiles from Bing maps.</div> Of course the above is being initialized and page works. You can draw the polygon shapes. Notice if you zoom in or out one time, the markers are set at the correct coordinates. My app I was testing this on is really using the bing maps API keys and not VirtualEarth. But it's doing a similar thing. Is this an Openlayers bug? The below source came directly from the open layers example site, I just added and activated polygons to the map. Please let me know how I can fix this for using the Bing Map API.. I've been stuck on this for HOURS! :(

    Read the article

  • SVG via dynamic XML+XSL

    - by Daniel
    This is a bit of a vague notion which I have been running over in my head, and which I am very curious if there is an elegant method of solving. Perhaps it should be taken as a thought experiment. Imagine you have an XML schema with a corresponding XSL transform, which renders the XML as SVG in the browser. The XSL generates SVG with appropriate Javascript handlers that, ultimately, implement editing-like functionality such that properties of the objects or their locations on the SVG canvas can be edited by the user. For instance, an element can be dragged from one location to another. Now, this isn't particularly difficult - the drag/drop example is simply a matter of changing the (x,y) coordinates of the SVG object, or a resize operation would be a simple matter of changing its width or height. But is there an elegant way to have Javascript work on the DOM of the source XML document instead of the rendered SVG? Why, you ask? Well, imagine you have very complex XSL transforms, where the modification of one property results in complex changes to the SVG. You want to maintain simplicity in your Javascript code, but also a simple way to persist the modified XML back to the server. Some possibilities of how this may function: After modification of the source DOM, simply re-run the XSL transform and replace the original. Downside: brute force, potentially expensive operation. Create id/class naming conventions in the source and target XML/SVG so elements can be related back to each other, and do an XSL transform on only a subset of the new DOM. In other words, modify temporary DOM, apply XSL to it, remove changed elements from SVG, and insert the new one. Downside: May not be possible to apply XSL to temporary in-browser DOMs(?). Also, perhaps a bit convoluted or ugly to maintain. I think that it may be possible to come up with a framework that handles the second scenario, but the challenge would be making it lightweight and not heavily tied to the actual XML schema. Any ideas or other possibilities? Or is there maybe an existing method of doing this which I'm not aware of? UPDATE: To clarify, as I mentioned in a comment below, this aids in separating the draw code from the edit code. For a more concrete example of how this is useful, imagine an element which determines how it is drawn dependent on the value of a property of an adjacent element. It's better to condense that logic directly in the draw code instead of also duplicating it in the edit code.

    Read the article

  • json null error help in php

    - by bobby
    I get 'json is null' as error My php file: <?php if (isset($_REQUEST['query'])) { $query = $_REQUEST['query']; $url='https://www.googleapis.com/urlshortener/v1/'; $key='ApiKey'; $result= $url.($query).$key; $ch = curl_init($result); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1); $resp = curl_exec($ch); curl_close($ch); echo $resp; } ?> My html: <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ // when the user clicks the button $("button").click(function(){ $.getJSON("shortner.php?query="+$('#query').attr("value"),function(json){ $('#results').append('<p>Id : ' + json.id+ '</p>'); $('#results').append('<p>Longurl: ' + json.longurl+ '</p>'); }); }); }); </script> </head> <body> <input type="text" value="Enter a place" id="query" /><button>Get Coordinates</button> <div id="results"></div> Edited : <?php if (isset($_REQUEST['query'])) { $query = $_REQUEST['query']; $url='https://www.googleapis.com/urlshortener/v1/'; $key='Api'; $key2='?key='; $result= $url.$query.$key2.$key; $requestData= json_encode($result); echo var_dump($query); $ch = curl_init($requestData); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1); $resp = curl_exec($ch); curl_close($ch); echo $resp; } ?>

    Read the article

  • Can I use the [] operator in C++ to create virtual arrays

    - by Shane MacLaughlin
    I have a large code base, originally C ported to C++ many years ago, that is operating on a number of large arrays of spatial data. These arrays contain structs representing point and triangle entities that represent surface models. I need to refactor the code such that the specific way these entities are stored internally varies for specific scenarios. For example if the points lie on a regular flat grid, I don't need to store the X and Y coordinates, as they can be calculated on the fly, as can the triangles. Similarly, I want to take advantage of out of core tools such as STXXL for storage. The simplest way of doing this is replacing array access with put and get type functions, e.g. point[i].x = XV; becomes Point p = GetPoint(i); p.x = XV; PutPoint(i,p); As you can imagine, this is a very tedious refactor on a large code base, prone to all sorts of errors en route. What I'd like to do is write a class that mimics the array by overloading the [] operator. As the arrays already live on the heap, and move around with reallocs, the code already assumes that references into the array such as point *p = point + i; may not be used. Is this class feasible to write? For example writing the methods below in terms of the [] operator; void MyClass::PutPoint(int Index, Point p) { if (m_StorageStrategy == RegularGrid) { int xoffs,yoffs; ComputeGridFromIndex(Index,xoffs,yoffs); StoreGridPoint(xoffs,yoffs,p.z); } else m_PointArray[Index] = p; } } Point MyClass::GetPoint(int Index) { if (m_StorageStrategy == RegularGrid) { int xoffs,yoffs; ComputeGridFromIndex(Index,xoffs,yoffs); return GetGridPoint(xoffs,yoffs); // GetGridPoint returns Point } else return m_PointArray[Index]; } } My concern is that all the array classes I've seen tend to pass by reference, whereas I think I'll have to pass structs by value. I think it should work put other than performance, can anyone see any major pitfalls with this approach. n.b. the reason I have to pass by value is to get point[a].z = point[b].z + point[c].z to work correctly where the underlying storage type varies.

    Read the article

  • How can I link axes of imshow plots for zooming and panning?

    - by Adam Fraser
    Suppose I have a figure canvas with 3 plots... 2 are images of the same dimensions plotted with imshow, and the other is some other kind of subplot. I'd like to be able to link the x and y axes of the imshow plots so that when I zoom in one (using the zoom tool provided by the NavigationToolbar), the other zooms to the same coordinates, and when I pan in one, the other pans as well. Subplot methods such as scatter and histogram can be passed kwargs specifying an axes for sharex and sharey, but imshow has no such configuration. I started hacking my way around this by subclassing NavigationToolbar2WxAgg (shown below)... but there are several problems here. 1) This will link the axes of all plots in a canvas since all I've done is get rid of the checks for a.in_axes() 2) This worked well for panning, but zooming caused all subplots to zoom from the same global point, rather than from the same point in each of their respective axes. Can anyone suggest a workaround? Much thanks! -Adam from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg class MyNavToolbar(NavigationToolbar2WxAgg): def __init__(self, canvas, cpfig): NavigationToolbar2WxAgg.__init__(self, canvas) # overrided # As mentioned in the code below, the only difference here from overridden # method is that this one doesn't check a.in_axes(event) when deciding which # axes to start the pan in... def press_pan(self, event): 'the press mouse button in pan/zoom mode callback' if event.button == 1: self._button_pressed=1 elif event.button == 3: self._button_pressed=3 else: self._button_pressed=None return x, y = event.x, event.y # push the current view to define home if stack is empty if self._views.empty(): self.push_current() self._xypress=[] for i, a in enumerate(self.canvas.figure.get_axes()): # only difference from overridden method is that this one doesn't # check a.in_axes(event) if x is not None and y is not None and a.get_navigate(): a.start_pan(x, y, event.button) self._xypress.append((a, i)) self.canvas.mpl_disconnect(self._idDrag) self._idDrag=self.canvas.mpl_connect('motion_notify_event', self.drag_pan) # overrided def press_zoom(self, event): 'the press mouse button in zoom to rect mode callback' if event.button == 1: self._button_pressed=1 elif event.button == 3: self._button_pressed=3 else: self._button_pressed=None return x, y = event.x, event.y # push the current view to define home if stack is empty if self._views.empty(): self.push_current() self._xypress=[] for i, a in enumerate(self.canvas.figure.get_axes()): # only difference from overridden method is that this one doesn't # check a.in_axes(event) if x is not None and y is not None and a.get_navigate() and a.can_zoom(): self._xypress.append(( x, y, a, i, a.viewLim.frozen(), a.transData.frozen())) self.press(event)

    Read the article

  • Nested WHILE loops not acting as expected - Javascript / Google Apps Script

    - by dthor
    I've got a function that isn't acting as intended. Before I continue, I'd like preface this with the fact that I normally program in Mathematica and have been tasked with porting over a Mathematica function (that I wrote) to JavaScript so that it can be used in a Google Docs spreadsheet. I have about 3 hours of JavaScript experience... The entire (small) project is calculating the Gross Die per Wafer, given a wafer and die size (among other inputs). The part that isn't working is where I check to see if any corner of the die is outside of the effective radius, Reff. The function takes a list of X and Y coordinates which, when combined, create the individual XY coord of the center of the die. That is then put into a separate function "maxDistance" that calculates the distance of each of the 4 corners and returns the max. This max value is checked against Reff. If the max is inside the radius, 1 is added to the die count. // Take a list of X and Y values and calculate the Gross Die per Wafer function CoordsToGDW(Reff,xSize,ySize,xCoords,yCoords) { // Initialize Variables var count = 0; // Nested loops create all the x,y coords of the die centers for (var i = 0; i < xCoords.length; i++) { for (var j = 0; j < yCoords.length, j++) { // Add 1 to the die count if the distance is within the effective radius if (maxDistance(xCoords[i],yCoords[j],xSize,ySize) <= Reff) {count = count + 1} } } return count; } Here are some examples of what I'm getting: xArray={-52.25, -42.75, -33.25, -23.75, -14.25, -4.75, 4.75, 14.25, 23.75, 33.25, 42.75, 52.25, 61.75} yArray={-52.5, -45.5, -38.5, -31.5, -24.5, -17.5, -10.5, -3.5, 3.5, 10.5, 17.5, 24.5, 31.5, 38.5, 45.5, 52.5, 59.5} CoordsToGDW(45,9.5,7.0,xArray,yArray) returns: 49 (should be 72) xArray={-36, -28, -20, -12, -4, 4, 12, 20, 28, 36, 44} yArray={-39, -33, -27, -21, -15, -9, -3, 3, 9, 15, 21, 27, 33, 39, 45} CoordsToGDW(32.5,8,6,xArray,yArray) returns: 39 (should be 48) I know that maxDistance() is returning the correct values. So, where's my simple mistake? Also, please forgive me writing some things in Mathematica notation... Edit #1: A little bit of formatting. Edit #2: Per showi, I've changed WHILE loops to FOR loops and replaced <= with <. Still not the right answer. It did clean things up a bit though... Edit #3: What I'm essentially trying to do is take [a,b] and [a,b,c] and return [[a,a],[a,b],[a,c],[b,a],[b,b],[b,c]]

    Read the article

  • How to display an external content in my website using javascript

    - by Chris
    Hello! This is my first post! I have a question about javascript...here is my code: <html> <head> <title>Geolocation Demo</title> </head> <body> <h1>Geolocation Demo</h1> <p>Latitude: <span id="lat">0.00</span> Longitude: <span id="lon">0.00</span> City: <span id="city">Loading...</span></p> <p><a id="city_link" href="http://tinygeocoder.com/" target="_blank">View City</a></p> <p><a id="gmaps_link" href="http://maps.google.co.uk/" target="_blank">View on Google Maps</a></p> <script language="javascript"> // show the position on the page and make a google maps link function showPosition(position) { var lat = position.coords.latitude; var lon = position.coords.longitude; document.getElementById("lat").innerHTML = lat; document.getElementById("lon").innerHTML = lon; var gmaps_url = "http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=" + lat + "+" + lon; var city_url = "http://tinygeocoder.com/create-api.php?g=" + lat + "," + lon; document.getElementById("gmaps_link").href = gmaps_url; document.getElementById("city_link").href = city_url; } </script> </body> </html> As you can see, this script target my geolocation. Specifically, Lat and Lon are working perfectly. In addinition, i want to display and region info (like city). So, i found a website which i provide the coordinates and it returns me a region name. My question is if i can display the name of region without clicking the link "View city" but in the field "city"...is it possible to pass the webpage content (http://tinygeocoder.com/create-api.php?g=" + lat + "," + lon;) into my webpage? The content of this page is only the name as i said...no html tags! Thank you!

    Read the article

  • How to get ImageButton size within Android GridView?

    - by wufoo
    I'm subclassing ImageButton in order to draw lines on it and trying to figure out where the actual button coordinates are within my gridview. I am using onGlobalLayout to setup Top, Bottom, Right and Left, but these seem to be for the actual "square" within the grid, and not the actual button (see image). The purple lines are drawn in myImageButton.onDraw() using coords gathered from myImageButton.onGlobalLayout(). I thought these would be for the button, but they seem to be from something else. Not sure what. I'd like the purple lines to match the outline of the button so the lines I draw appear on the button and not just floating out in the LinearLayout somewhere. The light blue is the background color of the vertical LinearLayout holding the Textview (for the number) and myImageButton. Any way to get the actual button size? XML Layout: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/lay_cellframe" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="fill_vertical|fill_horizontal" android:orientation="vertical" > <TextView android:id="@+id/tv_cell" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:gravity="center" android:text="TextView" android:textSize="10sp" /> <com.example.icaltest2.myImageButton android:id="@+id/imageButton1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" android:layout_margin="0dp" android:adjustViewBounds="false" android:background="@android:drawable/btn_default" android:scaleType="fitXY" android:src="@android:color/transparent" /> </LinearLayout> </FrameLayout> myImageButton.java public myImageButton (Context context, AttributeSet attrs) { super (context, attrs); mBounds = new Rect(); ViewTreeObserver vto = this.getViewTreeObserver (); vto.addOnGlobalLayoutListener (ogl); Log.d (TAG, "myImageButton"); } ... OnGlobalLayoutListener ogl = new OnGlobalLayoutListener() { @Override public void onGlobalLayout () { Rect b = getDrawable ().getBounds (); mBtnTop = b.centerY () - (b.height () / 2); mBtnBot = b.centerY () + (b.height () / 2); mBtnLeft = b.centerX () - (b.width () / 2); mBtnRight = b.centerX () + (b.width () / 2); } }; ... @Override protected void onDraw (Canvas canvas) { super.onDraw (canvas); Paint p = new Paint (); p.setStyle (Paint.Style.STROKE); p.setStrokeWidth (1); p.setColor (Color.MAGENTA); canvas.drawCircle (mBtnLeft, mBtnTop, 2, p); canvas.drawCircle (mBtnLeft, mBtnBot, 2, p); canvas.drawCircle (mBtnRight, mBtnTop, 2, p); canvas.drawCircle (mBtnRight, mBtnBot, 2, p); canvas.drawRect (mBtnLeft, mBtnTop, mBtnRight, mBtnBot, p); }

    Read the article

< Previous Page | 53 54 55 56 57 58 59 60 61  | Next Page >