Friday, April 29, 2011

cocos2d help find points on a circle

I am trying to solve a tricky math problem, in a cocos2d for iphone context.

Basically I have a roullette wheel which is rotating over time.

I want to have a Sprite latch onto the wheel at certain points (like compass ordinal points N, S, E, W) and bounce off at all other points.

I have the image of the wheel rotating, and just need to solve the part where I can test for whether a sprite has intersected with the circle at the right point on the circle as it is rotating.

I think this question is going in the right direction, but I can't get my head around it. Can anyone help explain?

http://stackoverflow.com/questions/300871/best-way-to-find-a-point-on-a-circle-closest-to-a-given-point

From stackoverflow
  • So you have a circle of radius r, with center (x0,y0).

    A point lies outside of the circle, at coordinates (x,y). Your question is to find the closest point on the circle itself to the point (x,y).

    The solution is simple. The closest projection of a point onto a circle is accomplished by a simple scaling. Thus,

    d = sqrt((x-x0)^2 + (y-y0)^2)
    xp = x0 + (x - x0)*r/d
    yp = y0 + (y - y0)*r/d
    

    The new point (xp,yp) will lie on the circle itself. To be honest, you would be better off to work in polar coordinates, with the origin at the center of the circle. Then everything gets much easier.

    Your next question will be where did it hit on the circle? Don't forget the points of the compass on the circle are rotating with time. An atan2 function will give you the angle that the point (xp-x0,yp-y0) lies at. Most toolsets will have that functionality. See that I've subtracted off the origin here.

  • If I understand correctly:

    First check the distance between the sprite and the centre of the roulette wheel. This will tell you if the sprite is at the edge of the wheel. (If not, nothing happens, right?)

    Then, find the angle that the sprite makes from the "x-axis" of the roulette wheel.

    spriteAngle = atan2(sprite.x - rouletteCentre.x, sprite.y - rouletteCentre.y)
    

    You'll need to find the equivalent of the atan2() function. It usually returns an answer in radians; you may want to convert it to degrees or quarter-turns or something if you prefer.

    Then, subtract the angle that the roulette wheel itself is rotated by (if the wheel itself is rotating, if not then you're already done). Make sure your angle measurement is consistent.

    actualAngle = spriteAngle - rouletteRotationAngle
    

    Note that actualAngle may be outside the range 0-360 degrees, and you will need to make it "wrap around".

    Lastly, you will want to allow a small range of values as acceptable (e.g. 98 degrees to 102 might count as "North").

Business Object - Void Data Provider

I am creating a BO report with six data providers. For Some reasons, there is a ghost data provider appears in the Report Manager which has same name as one other data provider but it has no objects in it.

I couldn't able to edit/delete this data provider(ghost) as it is not appearing in the data manager.

Any suggestion, for deleting this data provider(ghost)

From stackoverflow
  • Thanks, it got resolved.

    What I did is,

    I right clicked on the data provider,which is just below this dataprovider(ghost),

    I clicked edit data provider, which ends up in a new query panel with no objects in it, however I expected some objects in it.

    So, I added a object and saved the query. And Now, the Ghost Data provider name got changed to (Query 10), and also, starts appearing in the data manager.

    Seems like a wierd bug.

How much support does GWT have for Java layout managers?

This seems to be a question where the answer is implicit, hence I can't find anything explicit.

Does Google Web Toolkit only support custom layout managers, or a sub-set of the Java layout managers?

For example, is it possible to take a Java Swing application using GroupLayout and get it to work with GWT?

From stackoverflow
  • No, GWT doesn't support Layout managers from Swing/AWT. These are not compatible.

    Source of incompatibility is that those are totally different technologies with different APIs. Swing/AWT is pixel-based, while GWT renders to HTML. GWT layouts simply output different HTML tags (div/table/inline elements, ...), while Swing/AWT layouts do actually compute position of children components. In GWT, position of children is computed by browser, when they are displayed.

    Grundlefleck : Okay, thanks. You wouldn't happen to know of any sources explaining the incompatibility would you? +1
  • Most bottom line issue is that World Wide Web isn't Desktop Application no matter how much you'd want it to be. There's numerous issues involved, these are some which pop into mind:

    • WWW is stateless, desktop applications aren't. WWW is made stateful usually by cookies, URI parameters and session management and now that we've those for a couple of decades, we've mostly gone over the stateful/stateless issue of WWW.

    • WWW pages are (nowadays) described with some form of XML and usually CSS, in which the page is described as a tree. Comparing to Desktop Applications, while it's possibly to do nearly the same with XML and just plain component clustering, it just isn't the same. Once again one of the biggest issues is that in DA those components, widgets are stateful by nature on the application level while in WWW you can be truly stateful on the page level at most and even that requires JavaScript/AJAX.

    So, direct use of layout managers is a no-go. But, assuming the Web UI Framework you're using allows it, you may create something that behaves quite similarly to layout managers. While I don't know about GWT specifically, I believe that one could do at least a simple layout manager in JSP (or my favorite, Apache Wicket) and make it behave just as the Swing layout managers do.

    Note that I really do mean re-creating the whole concept of layout managers here as a set of specialized classes/whatnot, just as Peter Štibraný replied, GWT doesn't support them directly (in fact I haven't heard anything beyond Swing does) and I believe it would be more of an effort to create a wrapped/adapter for Swing Layout Managers instead of just creating your own, properietary ones for WWW.

  • GWT layout support is done through subclasses of 'Panel'. Some of them like 'DockPanel' behave a little bit like Swing layouts (BorderLayout) but there's no way you'll ever be able to take Swing code and compile it into GWT.

    This is a common mis-understanding when it comes to GWT. It's written in Java solely because Java is statically type and widely supported with world class editors. The fact that it's written in Java has nothing to do with any desire by the GWT team to allow you to port SWT/AWT/Swing to GWT. The web is a different environment to the desktop, and since your code ends up compiled into javascript it would never make sense to take any kind of Java Desktop application and hit the convert button. That's what Applets tried to do many years back...and we all know how that turned out ;)

  • IF you want a Swing Web application, consider AjaxSwing, but be prepared for network latency and consuming server resources. I think as soon as there's libraries for SVG/VML, we'll see more stuff move to the web. If you want to see a JavaScript IDE, check out Lively Kernel from Sun Labs. Have people tried porting Swing to GWT? It seems evident that there's AjaxSwing that a lot of Swing Could be ported to GWT, just perhaps not the Java2D stuff. Probably some smart company will figure out how to convert Swing to web client technology.

Problem with Array type "DAMPAR" in MATLAB deconvolucy.m

Below is part of the code that i tried to edit from, MATLAB's deconvolucy.
it appears to have problem with DAMPAR where the class type does not match.

can anyone help or does anyone know a better way to call in an image that I (as in deconvolucy.m) would tolerate?

[perhaps i should convert the image into array before use? how do i do so?]

// -- code -- //
I = imread('C:\Users\Lem\Desktop\III\TIFF\69_M.000.tif', 'tif');
class(I)
PSF = fspecial('gaussian',7,10);
V = .0001;
BlurredNoisy = imnoise(imfilter(I,PSF),'gaussian',0,V);
WT = zeros(size(I));
WT(5:end-4,5:end-4) = 1;
J1 = deconvlucy(BlurredNoisy,PSF);
J2 = deconvlucy(BlurredNoisy,PSF,20,sqrt(V));
J3 = deconvlucy(BlurredNoisy,PSF,20,sqrt(V),WT);
//...
...
...//

??? Error using ==> deconvlucy>parse_inputs at 316
In function deconvlucy, DAMPAR has to be of the same class as the input image.

Error in ==> deconvlucy at 102
[J,PSF,NUMIT,DAMPAR,READOUT,WEIGHT,SUBSMPL,sizeI,classI,numNSdim]=...

From stackoverflow
  • You have read in an image using imread. So it is probably coming in as uint8? The help for imread says the result will be integer of some order for a tiff image. What class was I when it was returned?

    You then filtered the image. It appears that imfilter will return an integer image for an integer input image.

    Next, you add noise, using imnoise. From the online help for imnoise, it internally converts the image to a [0,1] (double) number, adds the Gaussian noise, then converts back to integer output. So your blurred image should still be integer, probably uint8 elements.

    The help for fspecial says it will return a double precision output for PSF.

    You called deconvolucy with only two arguments, so it is using the default value for DAMPAR. (I'll argue that this should not fail here. The author of deconvolucy appears not to have supplied a default value that was consistent in type with the inputs.)

    Not knowing enough about the IPT or deconvolucy, I might first suggest re-running this code, using two different calls.

    J1 = deconvlucy(BlurredNoisy,PSF,[],0);
    
    J1 = deconvlucy(BlurredNoisy,PSF,[],uint8(0));
    

    If one of these calls did not fix the problem, it suggests that deconvolucy expects a double input for the image, BlurredNoisy. The online help for deconvolucy was not specific here. It says only that I may be an N dimensional array or a cell array. Further on in the help, it calls the result a numeric array. So I believe that the image for deconvolucy is expected to be a floating point image. (By my standards, this is a flaw in the help.)

    I would then probably try scaling your image to [0,1] as a double. It is just a guess however. So something like:

    BlurredNoisy = double(BlurredNoisy)/255;
    

    This assumes your image was uint8 in class originally.

What is the best way to learn Eclipse RCP? Does it feel different to only me?

I am used to structural programming (eg:C), OO programming(eg:Java), Scripting(eg:Javascript), Web (eg:HTML,JSP,Servlets,CSS) etc.

Now, when I am getting started with Eclipse RCP plugin development, the whole thing gives a strange feel to me in terms of programming. The way things are in Eclipse RCP development is quite different from other languages that I have mentioned above and honestly I don't enjoy the fact much.

Am I the only who feels this way?

What other things you suggest to make my transition into Eclipse RCP life better? (if it can feel any better).

P.S.: I have already seen this thread, for the tutorials, just wanted to know how others feel if their development background is similar to me!

From stackoverflow
  • It may feel different because it is heavily based on OSGI

    That involves splitting your application into components, which should typically have a set of responsibilities that can be isolated from the rest of your application through a set of interfaces and class dependencies.

    Identifying these dependencies purely by hand can range from rather straightforward for a well designed highly cohesive but loosely coupled application to a nightmare for interlocked source code that you are not familiar with.

    So building an RCP application involves respecting the whiteboard pattern on which the services concept of OSGi is build, and that can be quite different than traditional OO development.

  • There are 2 main approaches to building an RCP app
    1.) You are using RCP just for the platform features - SWT/startup exe/Auto-update. The application code will be isolated from RCP conventions and libraries as much as possible for the actual app biz functionality.
    2.) Your app is completely immersed in RCP. You try to reuse RCP API's wherever possible

    I have tried out Option 1. In this case, the experience is very similar to Java development. You might want to try this option out. The advantages are -
    -- SWT is very well integrated into RCP. You dont need to run into hoops to get it working. I would recommend SWT over Swing any day as it is very easy for an average programmer to create a responsive and native-feeling SWT app while it takes a Swing expert to create a decent Swing app
    -- With a client app, the ability to auto-update is very useful. Eclipse automatically offers this functionality.

    RCP stuff you still need to learn are:
    -- How the Eclipse classloader works. This is to ensure you can explicitly load resources from your jars in the correct way [NOTE: It is not simple]
    -- You will need to package the JVM along with the app. And invoke the JVM on startup using relative naming convention

  • Yes, I feel the same way... I have read many articles about eclipse RCP to develop a UI program but still don know if I need to learn SWT and Jface or not! Would anybody help and get me out of confusion?

Custom form designer, move/resize controls using WinAPI

I have to fix some problems and enchance form designer written long ago for a database project. In Design Panel class code I encountered these lines

private void DesignPanel_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
     (sender as Control).Capture = false;
     switch (FMousePosition)
     {
     case MousePosition.mpNone: 
      SendMessage((sender as Control).Handle, WM_SYSCOMMAND, 0xF009, 0);
      break;// Move
     case MousePosition.mpRightBottom: 
      SendMessage((sender as Control).Handle, WM_SYSCOMMAND, 0xF008, 0);
      break;//RB
     case MousePosition.mpLeftBottom: 
      SendMessage((sender as Control).Handle, WM_SYSCOMMAND, 0xF007, 0); 
            // ... here are similar cases ...
     case MousePosition.mpLeft:
      SendMessage((sender as Control).Handle, WM_SYSCOMMAND, 0xF001, 0);
      break;//L  
     }
    }
}

FMousePosition indicates whether mouse was over any edge of selected control.

What confusing me is these windows messages: it seems there is no documentation on WM_SYSCOMMAND with parameters 0xF001-0xF009 (maybe it starts some kind of 'drag/resize sequence'). Any ideas?

If my suggestion is right, then how can I cancel these sequences?

From stackoverflow
  • See APIViewer and check out constants starting with SC_

  • They are undocumented parameters. After searching I managed to find this list.

    • 0xF000 (Centre cursor on the form)
    • 0xF001 (Resize from left)
    • 0xF002 (Resize from right)
    • 0xF003 (Resize from up)
    • 0xF004 (Lock the bottom right corner of the form, the up left corner move for resize)
    • 0xF005 (Same from bottom left corner)
    • 0xF006 (Lock up right and left border, resize other)
    • 0xF007 (Lock up and right border, resize other border)
    • 0xF008 (Lock left and up border and resize other)
    • 0xF009 (Drag from anywhere)
    • 0xF010 (Put cursor centred at the upper order)
    • 0xF020 (Auto-Minimize Form)
    • 0xF030 (Auto-Maximize Form)

    Reference: http://www.delphi3000.com/articles/article_1054.asp#Comments

  • Based on my Win32 Programming (Rector and Newcomer) p902-903 explains WM_SYSCOMMAND is sent when the user selects an item from the system menu (rather than sending the normal WM_COMMAND).

    The MSDN help says SC_SIZE = 0xF000 and it and Win32 Programming also say Windows uses the four low-order bits of the predefined system menu IDs internally but doesn't go on to clarify their use. Thanks stukelly for clarifying them.

How do you stay focused when a difficult task deadline is looming?

I've recently become active on SO, mainly because it's a lot more inspiring than the deadline for the big wodge of documentation that no one's ever going to read that is looming ever larger in my headlights.

I'm wondering why I'm risking discipline/unemployment more as each hour slips by, especially when the Global Financial Crisis is starting to bite round here.

If anyone has any advice that's practiable, please let me know.

(Yes, this is somewhat tongue-in-cheek, but it's also true, and becoming increasingly important in my shortening career ...)

From stackoverflow
  • Keep track of your work accomplishments in writing. Where I work, I have to submit a list of what I've done every week to my boss, but even if I didn't I'd keep writing them. Nothing is more motivating than having only one bullet-point done on Thursday morning.

    EnderMB : Exactly what I do with all of my projects. There's nothing more satisfying than wiping a bullet-point off of my whiteboard.
  • Grow up and shut down your browser. If you must put a fake entry in your hosts file. You lose your job you won't have much reason to come here so stop reading right now and get your work done.

    JoshBerke : gracious blorgbeard
  • Look into productivity tools which can help you better organize your time. One of my co-workers struggled with something similar, and found his ability to work tended to increase when he regularly scheduled small (<2min) breaks every hour or so. Though I hesitate to give you yet another website, lifehacker has some great utilities listed which can aid in productivity.

    Above all, block yourself (as mentioned above) from any websites which drain your ability to work. There really isn't ever a good time to lose your job because of slacking off.

    Edit: don't look up these tools at work :)

  • http://www.paulgraham.com/distraction.html

    Maybe in the long term the right answer for dealing with Internet distractions will be software that watches and controls them. But in the meantime I've found a more drastic solution that definitely works: to set up a separate computer for using the Internet.

    I now leave wifi turned off on my main computer except when I need to transfer a file or edit a web page, and I have a separate laptop on the other side of the room that I use to check mail or browse the web. (Irony of ironies, it's the computer Steve Huffman wrote Reddit on. When Steve and Alexis auctioned off their old laptops for charity, I bought them for the Y Combinator museum.)

    My rule is that I can spend as much time online as I want, as long as I do it on that computer. And this turns out to be enough. When I have to sit on the other side of the room to check email or browse the web, I become much more aware of it. Sufficiently aware, in my case at least, that it's hard to spend more than about an hour a day online.

    tharkun : quite hard to implement for a modern developer, especially web dev. my firefox tabs from left to right: unfuddle, current project, stackoverflow, php manual, zend framework manual, plesk, ... :D

How to use @BasicMap for a HashMap whose key values are entities

How should I use EclipseLink's @BasicMap annotation for a map whose key value is an entity and the value is an Integer?


@Entity
class A {

   // This doesn't work, as the key is an entity
   @BasicMap
   private Map<B, Integer> myMap = new HashMap<B, Integer>();

}

@Entity
class B {
 ...
}

From stackoverflow
  • I found out that this is not possible, as BasicMap only works for primary datatypes.

How to use WSAAsyncSelect from WinAPI in C#?

Hello,

I'm tired of the .NET BeginRead,EndRead stuff.I'd love to use WSAAsyncSelect the way I used to in Delphi/C++

//Async CallBack handler Declaration
procedure MessageHandler(var Msg:Tmessage);Message WM_WINSOCK_ASYNC_MSG;

//Where i setup the Async
dwError := WSAAsyncSelect(Sock, form1.handle, WM_WINSOCK_ASYNC_MSG, FD_CLOSE or FD_READ);

//Async Callback Handler
procedure Tform1.MessageHandler(var Msg:Tmessage);
begin
  case WSAGetSelectEvent(MSG.LParam) of //LParam is FD_READ/FR_CLOSE/FD_WRITE
    FD_READ: OnSocketRead(MSG.WParam); //WPARAM is the Socket itself.
    FD_CLOSE: OnSocketClose(MSG.WParam);
  end;
end;

Is it possible to set that event in C#?

From stackoverflow

Why is XST optimizing away my registers and how do I stop it?

I have a simple verilog program that increments a 32 bit counter, converts the number to an ASCII string using $sformat and then pushes the string to the host machine 1 byte at a time using an FTDI FT245RL.

Unfortunately Xilinx XST keeps optimizing away the string register vector. I've tried mucking around with various initialization and access routines with no success. I can't seem to turn off optimization, and all of the examples I find online differ very little from my initialization routines. What am I doing wrong?

module counter(CK12, TXE_, WR, RD_, LED, USBD);

   input CK12;
   input TXE_;
   output WR;
   output RD_;
   output [7:0] LED;
   inout [7:0] USBD;

   reg [31:0] count = 0;

   reg [7:0] k;
   reg wrf  = 0;
   reg rd   = 1;
   reg [7:0] lbyte = 8'b00000000;   

   reg td        = 1;
   parameter MEM_SIZE  = 88;
   parameter STR_SIZE  = 11;
   reg [MEM_SIZE - 1:0] str;
   reg [7:0] strpos = 8'b00000000;

   initial
     begin
     for (k = 0; k < MEM_SIZE; k = k + 1)
       begin
       str[k]    = 0;
       end
     end

   always @(posedge CK12)
     begin
     if (TXE_ == 0 && wrf == 1)
       begin
       count    = count + 1;
       wrf       = 0;
       end


     else if (wrf == 0)  // If we've already lowered the strobe, latch the data
       begin
       if(td)
         begin
         $sformat(str, "%0000000000d\n", count);
         strpos = 0;
         td   = 0;
         end

       str      = str << 8;
       wrf    = 1;
       strpos   = strpos + 1;   

       if(strpos == STR_SIZE)
         td    = 1;

       end  
     end

   assign RD_       = rd;
   assign WR        = wrf;
   assign USBD         = str[87:80];
   assign LED       = count[31:24];

endmodule

Loading device for application Rf_Device from file '3s100e.nph' in environment /opt/Xilinx/10.1/ISE. WARNING:Xst:1293 - FF/Latch str_0 has a constant value of 0 in block . This FF/Latch will be trimmed during the optimization process.

WARNING:Xst:1896 - Due to other FF/Latch trimming, FF/Latch str_1 has a constant value of 0 in block . This FF/Latch will be trimmed during the optimization process.

WARNING:Xst:1896 - Due to other FF/Latch trimming, FF/Latch str_2 has a constant value of 0 in block . This FF/Latch will be trimmed during the optimization process.

From stackoverflow
  • The $sformat task is unlikely to be synthesisable - consider what hardware the compiler would need to produce to implement this function! This means your 'str' register never gets updated, so the compiler thinks it can optimize it away. Consider a BCD counter, and maybe a lookup table to convert the BCD codes to ASCII codes.

    AFAIK 'initial' blocks are not synthesisable. To initialize flops, use a reset signal. Memories need a 'for' loop like you have, but which triggers only after reset.

    MrEvil : Alright! I initially didn't understand half of what you said, but I spent the last couple of minutes looking up what a BCD is and it looks exactly like what I want. I just need to figure out how to do the look-up table now. I was suspicious of $sformat but the compiler didn't complain and it worked perfectly in simulation, but I guess I know now. Thanks!
    Marty : Lookup tables are easy - they're `case` statements! In simulation, you can do anything - it'll treat the code as a program. For stuff you want synthesised, you have to keep in mind that you're describing hardware, not programming as such.

Char shifting in C

Greetings I am trying to find the function in the library that shifts chars back and forward as I want for instance:

if this function consumes 'a' and a number to shift forward 3 , it will be shifted 3 times and the output will be 'd'.

if it this function consumes '5' and a number to shift forward 3 , it will be shifted 3 times and the output will be '8'.

how can I achieve this?

Regards

From stackoverflow
  • Given what you've asked for, this does that:

    char char_shift(char c, int n) {
       return (char)(c + n);
    }
    

    If you meant something else (perhaps intending that 'Z' + 1 = 'A'), then rewrite your question...

    Gabi Davar : The question is indeed incomplete - how should overflow/underflow is to be handled. Without this no complete solution can be given.
  • You don't need to call a function to do this. Just add the number to the character directly.

    For example:

    'a' + 3
    

    evaluates to

    'd'
    
    Lars Wirzenius : This is true for ASCII, and character sets based on it, for the A-Z letters. This covers pretty much all relevant machines in the modern world. EBCDIC would be the big exception, but it seems to be pretty much extinct.
    paxdiablo : You might want to rethink that comment, @liw.fi. EBCDIC is alive and well on z/OS which pretty well runs ALL the world-class banks and other financial organizations. It's even in the encapsulated UNIX run on that platform (which sometimes makes it hard to compile FOSS that depends on ASCII ordering, zLinux uses ASCII so that's better).
  • In C, a char is an integer type (like int, and long long int).

    It functions just like the other integer types, except the range of values it can store is typically limited to -128 to 127, or 0 to 255, although this depends on implementation.

    For example:

    char x = 3;
    char y = 6;
    int z;
    
    z = x + y;
    printf("z = %d\n", z); //prints z = 9
    

    The char type (usually as part of an array) is most often used to store text, where each character is encoded as a number.

    Character and string constants are a convenience. If we assume the machine uses the ASCII character set (which is almost ubiquitous today), in which case capital A is encoded as 65, then:

    char x = 'A';
    char str[] = "AAA";
    

    is equivalent to

    char x = 65;
    char str[] = {65, 65, 65, 0};
    

    Therefore, something like 'X' + 6 makes perfect sense - what the result will be depends on the character encoding. In ASCII, it's equivalent to 88 + 6 which is 94 which is '^'.

How to send value through URL in FLEX

Hi,

I want to send current date with URL in flex from client side and want to get it on the server. I am using MXML and ActonScript.

Please help me.

From stackoverflow
  • you may have a look at

    http://livedocs.adobe.com/flex/3/html/help.html?content=Part4_data_access_1.html

    and read from there to see, what you need for your kinf od request (HTML, XML).

    in short, you have to have some dataservice (f.e. mx:HTTPService) and appropriate methods (send) and connect them with your controls

    EDIT: system time: http://livedocs.adobe.com/flex/3/html/help.html?content=08_Dates_and_times_3.html

  • Thanks for your reply. I have done what u r saying. Have a look.

    <mx:request xmlns="">
      <sysdatetime>{sysdatetime}</sysdatetime>
     </mx:request>
    

    AT the server,

    echo "GET: ".$_GET['sysdatetime'];

    I have called it like, creationComplete="test.send();"

    sysdatetime gives me current date time of client system. But at the server, i am not getting it.

    Peter Miehle : please do not answer your own post, but instead edit your original question to provide the relevant information!
    Peter Miehle : to answer my comment:-) this is not a forum in classical style, but the posts are reordered according to votes, so if someone else would answer, nobody would figure out, which answer your "..for your reply.." is bound to.
  • Here's an example of how to pass an object using the HTTPService's send() method. Just wrap your Date object and pass it via a send() call.

Changing the default modal result of a form.showModal

In my Delphi application I have a custom Yes, No, Cancel dialogue, which will be called from the main form to confirm saving the changes made to the current file edited. This would normally be achieved by messageDlg() but I wanted this dialogue to have customised looks, so I am trying to achieve this functionality by

case myDialogue.showModal of
  mrYes: <<save changes>>;
  mrNo: <<quit application without saving changes>>
  mrCancel: <<set the closeAction to caNone and do nothing>>
end;

The problem is that, by default, the form reacts to pressing the Escape key by returning mrNo TModalResult. And you can see how BAAAD this is, since your intuition tells you that Esc-aping the modal dialogue will CANCEL the intended Quit Application process, but in fact what happens is you issue a Don't save any changes command and application quits.

I have not noticed this behaviour until I lost an hour's work in this fashion. No FormKeyPressed event handler or anything responding to key presses was put into the myModalDialogue code. It just so works that pressing the Esc in forms shown using showModal will return mrNo. How can I override this default behaviour?

From stackoverflow
  • You need to make sure that the Cancel property of the "No" button is False, and that the Cancel property of the "Cancel" button is True.

    Peter Perháč : this worked. Thanks!
  • Set the Cancel and Default properties of the buttons in your dialog.

    Peter Perháč : +1 for a correct answer. Thanks, I can't believe it was so simple... And I was going nuts trying to fix this...

Calculating the contours of a 3D heightmap?

I am looking for a function or example to produce a list of lines representing contours at a specific height within a heightmap.

Eg,

Lines[] = GetContours(Heights[512,512], HeightValue)

Where Heights is a 512x512 array of floating point values, HeightValue is the height at which the contour should be drawn. Heights may contain multiple lines for that specific height (eg a Saddle, or island chain)

Does anyone have or know where to get an algorithm to generate this?

From stackoverflow
  • What you're actually trying to do is to draw an iso-line.
    see my question about it a while ago.
    The link given in one of the answers was very helpful.

  • The standard algorithm is marching squares.

  • Algorithm:

    a) Find which polygons have vertices above&below the height you're interested in.

    b) Intersect the edges of those polygons with the plane to get lines on the plane.

    c) Join the lines together in strips.

  • Take a look at Srtm2Osm, a tool I've made to generate contours from NASA's SRTM data. You can find the algorithm in the C# code.

Alternate posts in wordpress

In order to put ads on my wordpress site, but only every few posts, I want to add a simple conditional to the bottom of each post, containing my ad code.

I have ssomething like the following:

<?php if (the_ID() % 3 == 0){ ?>
ad code

<?php } ?>

But all this does is echo the id of the post.... for EVERY post!

What am I doing wrong?

From stackoverflow
  • What the_ID does is simply to echo the ID of the current post.

    If you want to get the ID, use get_the_ID() instead.

    wheresrhys : fantastic - thanks

Custom error pages using only one file...

Although I'm sure it's possible I cannot see how I would be able to do the following.

Using .htaccess to point the html errors to a single error handling page (this bit not a a problem).

That page then checks what the error code actually was (404, 500 etc.) and displays a message according to each one.

I am trying to do it in a PHP environment, and it's for a minimalistic site so the less files the better.

This is an example of a 404 I'm producing, http://isitup.org/404, and all I want is to switch the number accordingly.

From stackoverflow
  • I always put in my .htaccess:

    ErrorDocument 403  /error.php?error=403
    ErrorDocument 404  /error.php?error=404
    ErrorDocument 500  /error.php?error=500
    

    etc for whatever errors I want, then just switch case on $_GET['error'].

    Don't think there is any more sophisticated way of doing it.

    Sam : Thanks, that's so simple :P
  • Since you're using .htaccess to redirect errors to a custom error handler file, you can use $_SERVER['REDIRECT_STATUS'] to obtain the HTTP error code. Based on that, you can display a different message depending on the error code.

Autostart a batch file on Windows

Hi,

I want to create a script that will run whenever a server is turned on to do basic things like create a directory and copy a binary from an FTP server to it. I need it to run before a user logs in, as soon as the server is turned on. This will be deployed on my EC2 windows servers.

Checking around (http://www.bleepingcomputer.com/tutorials/tutorial44.html) I saw that only services can run before a user logs in.

I saw that I can make my batch into a com (bat2exe) and set it as a service but that doesn't work with internal commands like ECHO, md, etc. I can also fake a service to be "cmd /k batch.cmd".

Both seem cumbersome. Is there an elegant way to do this?

Thanks,

Miki

From stackoverflow
  • You can use the Task Scheduler. Scheduled tasks can run at startup, even before a user logs on (they run in a specified user's context, however).

  • You can use the Windows Task Scheduler and set it for when the system is booted. Here's more info on that Task Scheduler

Java: Dependency Injection on foreign-constructed objects?

Hello!

I'm a huge fan of D.I.
I'm currently developing a not-so-small project which uses D.I. everywhere
(classic and beautiful D.I. by hand).

From my point of view there are following advantages:

  • It's intuitive when you got used to it,
  • doesn't affect readability in negative way (in fact, it gets even better),
  • but the most important thing is: if I want to test parts or whole project with different implementations of some interfaces, I can do it by changing few characters, instead of doing complex refactoring/renaming or other workarounds.

But, sadly, I can't figure out, how D.I. can be used with foreign-created objects in an elegant way (without some frameworks, remember, I do D.I. by hand).

D.I. by hand means: you pass something to a c-tor. No global factories or similar, God forbid!

JAXB, for example, creates objects by itself. There is no way to tell the JAXBContext: "please, use following parameters to create my objects". JAXB only accepts parameterless c-tors.

Any ideas?

From stackoverflow
  • People have been known to use getter injection to do this. I wouldn't know how to do this in a luddite DI environment.

  • Doesn't the JAXBContext use a factory method anyway? You can pass parameters into this like you would a constructor. If that doesn't do what you want, traditional setter injection (i.e. calling context.setXyz(xyzInstance) methods) after creating your object would emulate by hand what spring et al do automatically...

    eglasius : +1 I would go with either of the ones suggested. @ivan if you are still not comfortable with the lines of code that would call it, wrap them and move that code elsewhere. Its a restriction and you have to deal with it at some point. I also don't know if java allows, but in .net you can call the constructor of the already instantiated object through reflection.
  • Why does "D.I. by hand" have to mean "pass something to a c-tor"?

    Could you do this?

    ThingOne one = new ThingOne();
    one.setInjectedItem( a );
    one.setOtherInjectedItem( b );
    

    In spring dependency injection, this would be injection via a property and I don't see why this can't be done "by hand."

How can I rotate a line of text each page refresh?

Right now, Reddit is down. Every time you go to it, it displays a logo and below it a funny message. Every time you refresh the page it displays a new message.

alt text

How could I write something simple that ~rotates~ (not random) a line of text on the page every refresh?

I'm using ASP.NET MVC but if there is a JavaScript solution to this problem that is fine too.

From stackoverflow
  • Here's an example of how to do it in javascript:

    http://www.webdevelopersnotes.com/tips/html/random_text_display_using_javascript_1.php3

    Mithrax : Sorry, but I tried to specify in my post i'm ~not~ looking for random. Thanks anyway though
  • This is how you could write it:

    For javascript, simply use the link posted by Andy White and replace the call to Math.floor(7*Math.random()) to a get/set cookie value. You can find ready-to-use javascript functions to read and write cookies on google.

    For asp.net mvc, the code won't differ a lot, you just have to look for functions to easily manipulate cookies as they are built-in.

  • Load your message into an array or some sort of collection that is accessible by index.

    Something like (i did not verify all syntax):

    string getQuote(){
     //Load collection of lines
      ArrayList quotes = getQuotesData();
      int quoteCount = quotes.Count;
    
     // Set session or application variable to some number
      int counter;
      if( !Integer.parse( Session("counter"), counter ) ) { counter = 0; }
      if( counter > quoteCount ) { counter = 0; }
    
      return quotes[counter];
    }
    

    Also, I'm sure something similar is possible in javascript.

How access Jquery TreeView on the server?

How do I access Jquery Treeview inside the .aspx file upon form submit? also, Can I add nodes to Jquery Treeview on the fly? (on the client side)

I am using asp.net web forms, c#

EDITED: someone mentioned the following in one of the questions: "on form submit, someone is going to have to write code on the client to collect that data and send it via Ajax to a server method"

how is this done?????

From stackoverflow
  • Since jQuery Treeview is a client-side component, you can't access it from the server-side. So in order to pass any data from your tree to the server, you have to write client-side javascript code (actually jQuery code). The same thing regarding adding nodes to the treeview on the fly: only using client-side jQuery code. Remember that your C# on the server-side has no idea about your TreeView.

    The integration between jQuery and ASP.NET WebForms is rather problematic and "not so natural", because ASP.NET is built on different concept... So if you are working with ASP.NET WebForms, I would suggest you to use server-side components instead (it can be Microsoft's own ASP:TreeView or other 3rd-party WebForms-aimed components). Alternatively, you can try the new ASP.NET MVC Framework - it is built on more common (for other web-development platforms) concept, and the integration between it and jQuery is straightforward (actually jQuery is even shipped with it).

    Don't get me wrong... I am not saying that the integration between jQuery and ASP.NET WebForms is totally impossible. It is possible. But you'll need to do "not-so-beautiful" things and work hard for every simple operation. If you still want to use jQuery, then use it only for the client-side animations...

    UPDATE: As for this quote - "on form submit, someone is going to have to write code on the client to collect that data and send it via Ajax to a server method" - well, this is exactly what I am talking about. On the client-side you call javascript method when submitting the form (for example, by setting onclick='mymethod();' on your "Submit" button). This code does what it needs to do and then... it is supposed to perform AJAX call using jQuery nice syntax. But this won't work with ASP.NET WebForms, as I've explained before. Well, you can read about Microsoft AJAX Client-side library (here: http://msdn.microsoft.com/en-us/magazine/cc163300.aspx), perhaps this will help. But I still think that this integration won't be easy and straightforward. Use jQuery for the animation and ASP.NET server-side components for all other things!

    gnomixa : thanks Dmitry, I am not stuck on using jQuery treeview. I just need a pure client based treeview. All I need is a treeview on the client side, then Save button will trigger a callback which will collect the treeview data and send it to the server.
    gnomixa : Of course I could implement my own treeview but at this day and age I shouldn't have to.
    gnomixa : From what I understand, as long as I can access the tree on the client, I should be able to use MS callback (my page will implement System.Web.UI.ICallbackEventHandler interface) to consume the tree and pass the data to the server, JSON format. I realize that using Jquery ajax wont work with .net
    Dmitry Perets : Well, if your treeview should be on client-side, then perhaps you do want to use jQuery for it, just because it is nicer and simpler to use. But you understand correctly: you won't be able to use its ajax functionality. You'll need MS AJAX Client-side library (which I am not so familiar with it =( )
    gnomixa : So essentially, to send the tree information to the server method, I need to use ASP.NET AJAX library?
    gnomixa : I don't think that you are the only one who is not so familiar with Microsoft AJAX Library. I could only find one link (the one you published) on google. Other links all led to some book that was published in 2007. I am not even sure who uses this library.
    gnomixa : Out of the links available, I really don't get enough info for my case - it is so poorly explained using the simplest examples. How do i send tree data (which could be large) over to the asp.net server method???? that's all i want to know. I have been trying to find info on this for over a week.
  • Well, I think I've found what you want. Take a look here.

    In brief, you must define a WebMethod on your server side, and then you can easily access it using jQuery. An exellent working example is under the link above, and here I'll modify it to show how you can pass arguments. So...

    In your page code-behind *.cs:

    // We'll use this class to communicate
    public class Dog
    {
        public string Name { get; set; }
        public string Color { get; set; }
    }
    
    // This is your page, in my case Default.aspx
    public partial class _Default : System.Web.UI.Page
    {
        [WebMethod]
        public static string ProcessData(Dog myDog)
        {
            return "Your " + myDog.Color + " dog's name is " + myDog.Name + "!";
        }
    }
    

    Then on your *.aspx:

    <script src="jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="json2.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    
        $(document).ready(function() {
            $("#btnProcess").click(function() {
                // This is what we want to send to the server
                var dogItem =
                {
                     Color: $("#txtColor").val(),
                     Name: $("#txtName").val()
                };
    
                // And this is how it should be sent - in serialized way
                var dogItemSerialized = JSON.stringify(dogItem);
    
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/ProcessData",
                    data: "{'myDog':" + dogItemSerialized + "}",    
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        $("#result").text(msg.d);
                    }
                });
            });
        });
    
    </script>
    Color: <input id="txtColor" type="text" /><br />
    Name: <input id="txtName" type="text" /><br />
    <input id="btnProcess" type="button" value="Click Me" />
    <div id="result"></div>
    

    So here you fill textboxes and then your data is sent to the server which understands it as a Dog object. Pay attention to arguments passing, because this is the most confusing part. You should pass them in JSON format, which is a little bit "too-much-stringy". So I use here json2.js script which helps to convert usual javascript object into JSON-serialized string (JSON.stringify() method). It is available here. But it is still rather ugly =) It is important that I pass argument called "myDog" which value is the serialized dogItem. Because this is exactly what the server expects to get (so, for example, I can't change the argument name, this won't work:

    data: "{'someAnotherArgumentName':" + dogItemSerialized + "}"
    

    And the last thing. Pay attention to the following line:

    success: function(msg) {
                $("#result").text(msg.d);
             }
    

    If you are working with ASP.NET prior to 3.5 (for example, ASP.NET 2.0), then you'll need to write just $("#result").text(msg) instead of msg.d. Only ASP.NET 3.5 encapsulates all the data under "d" member for some reason...

    Anyway, in the above article you can find useful links (both inside the article and in comments), so you can read more about arguments, "msg.d" and so on.

    I hope this helps!

Custom view transition in OpenGL ES

I'm trying to create a custom transition, to serve as a replacement for a default transition you would get here, for example:

[self.navigationController pushViewController:someController animated:YES];

I have prepared an OpenGL-based view that performs an effect on some static texture mapped to a plane (let's say it's a copy of the flip effect in Core Animation). What I don't know how to do is:

  • grab current view content and make a texture out of it (I remember seeing a function that does just that, but can't find it)
  • how to do the same for the view that is currently offscreen and is going to replace current view
  • are there some APIs I can hook to in order to make my transition class as native as possible (make it a kind of Core Animation effect)?

Any thoughts or links are greatly appreciated!

UPDATE

Jeffrey Forbes's answer works great as a solution to capture the content of a view.

What I haven't figured out yet is how to capture the content of the view I want to transition to, which should be invisible until the transition is done.

Also, which method should I use to present the OpenGL view? For demonstration purposes I used pushViewController. That affects the navbar, though, which I actually want to go one item back, with animation, check this vid for explanation:

http://vimeo.com/4649397.

Another option would be to go with presentViewController, but that shows fullscreen. Do you think maybe creating another window (or view?) could be useful?

From stackoverflow
  • While I cannot completely answer your question without doing some more research of my own, I can help a bit:

    -In order to get the view of a UINavigationController, you need to take a screenshot. The easiest way to do this is by grabbing it into a UIImage:

    UIGraphicsBeginImageContext(self.view.frame.size);
    [[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* test = UIGraphicsGetImageFromCurrentImageContext();
    UIImageView* view = [[UIImageView alloc] initWithImage:test];
    UIGraphicsEndImageContext();
    

    I am not sure if you can render a GLContext (not familiar on the phone) into a CGImage, but I would do something like that (and init a UIImage from that). I would prerender every frame of the animation you are trying to do and slap it into an UIImageView using the animation stuff provided within. That is, if your animation is simple enough. Otherwise, it might come down to writing your own animation function :-/

    melfar : Thanks for your advice and sorry for my extra slow reaction! Could you check the updated question, maybe you will have some further advice?
  • I think the function you might be thinking of is http://www.opengl.org/sdk/docs/man/xhtml/glCopyTexImage2D.xml ... you set the viewport to the texture size and then draw as usual, then do glCopyTexImage2D to copy the scene onto a texture.

    or you should look into FrameBuffer Objects. The default OpenGL template in XCode uses these. Just generate the example project to see how those work.

  • I have just put together a transition class to implement your own transition animation in OpenGL ES.

    Feel free to read about it here

    There are two example transitions in the project, feel free to add you own to it.

Rectifying JScript runtime error

Hi, When i am running the application,i got an error as follows:

Microsoft JScript runtime error:Sys.ArgumentTypeException:Object of type 'Sys._Application' cannot be converted to type 'Sys._Application'.Parameter name:instance

From stackoverflow
  • This error can happen if your web.config is not properly configured to use Microsoft's ASP.NET Ajax.

    If you have VS2008, this settings are added automatically. In VS2005, if your ASP.NET project does not start out as Ajax, you need to add the settings manually.

    Here's an example:

    <configuration>
    
      <configSections>
    
        <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    
          <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    
            <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    
            <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    
              <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
    
              <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    
              <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    
            </sectionGroup>
    
          </sectionGroup>
    
        </sectionGroup>
    
      </configSections>
    
      <system.web>
    
        <pages>
    
          <controls>
    
            <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
          </controls>
    
        </pages>
    
        <compilation debug="true">
    
          <assemblies>
    
            <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
            <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
    
            <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    
          </assemblies>
    
        </compilation>
    
        <httpHandlers>
    
          <remove verb="*" path="*.asmx"/>
    
          <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
          <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
          <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
    
        </httpHandlers>
    
        <httpModules>
    
          <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
        </httpModules>
    
      </system.web>
    
      <system.web.extensions>
    
        <scripting>
    
          <webServices>
    
            <!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
    
            <!--
    
              <jsonSerialization maxJsonLength="500">
    
                <converters>
    
                  <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
    
                </converters>
    
              </jsonSerialization>
    
            -->
    
            <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
    
            <!--
    
              <authenticationService enabled="true" requireSSL = "true|false"/>
    
            -->
    
            <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
    
                 and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
    
                 writeAccessProperties attributes. -->
    
            <!--
    
              <profileService enabled="true"
    
                readAccessProperties="propertyname1,propertyname2"
    
                writeAccessProperties="propertyname1,propertyname2" />
    
            -->
    
          </webServices>
    
          <!--
    
            <scriptResourceHandler enableCompression="true" enableCaching="true" />
    
          -->
    
        </scripting>
    
      </system.web.extensions>
    
      <system.webServer>
    
        <validation validateIntegratedModeConfiguration="false"/>
    
        <modules>
    
          <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
        </modules>
    
        <handlers>
    
          <remove name="WebServiceHandlerFactory-Integrated"/>
    
          <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
          <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
          <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    
        </handlers>
    
      </system.webServer>
    
    </configuration>
    
  • Set the ScriptMode attribute of ScriptManager to Release.

  • Thanks! ScriptMode="Release" helps me to resove a problem on the page dispayed using Tranfer.Redirect