Sunday, May 1, 2011

More than one implementator of an interface. How with OSGi ?

I am interested in using OSGI as a means of managing plugins for a project. That is there can be many implemenators of my interface, each appearing in its own / separate OSGI bundle with the implementation class exported...

From stackoverflow
  • Declarative Service should be the way to go.

    You can declare your interface as a service

    <service>
        <provide interface="my.Interface"/>
        <property name="foo" value="bar"
    </service>
    

    Each implementation of that interface can define Bundle activation and de-activation methods.
    But what is really neat is their nature: if you are using the latest SCR (the "Service Component Runtime" which is an "extender bundle" implementing the new and improved OSGi R4.2 DS - Declarative Service - specification), your classes will not import anything from the OSGI model. They remain pure POJO.

    Then define another service which depends on your first service:

    <reference name="myInterfaceServiceName"
        interface="my.Interface"
        bind="myActivationMethod" unbind="myDeactivationMethod"
        cardinality="0..n"/>
    

    That service will detect and list all your concrete instances of your first service and deal with them as you intent to.

    See the Eclipse Extensions and Declarative Services question for more details.

    The presentation: Component Oriented Development in OSGi with Declarative Services, Spring Dynamic Modules and Apache iPOJO, from EclipseCON2009, will provide you with a concrete example.

    mP : This model has one fault - in that it seems very passive that is you can only find a bundle exists once it is activated. I was hoping to be able to get a directory of available bundles and their exported types before they are activated. Is this possible / how ?
    mP : From what i can tell this is not entirely possible because in order to learn about a bundle one must be a tracker but that means its too late, and i cant control what budnles are activate/inactive.
  • This can be done declaratively (like VonC) has detailed, or dynamically at runtime via the standard service registry.

    Any implementer can simply register their implementations as a service and consumers can get them from the registry, which is pretty basic OSGi stuff. The services can also be registered with properties, so consumers can use these properties to distinguish between implementations when looking up the service.

    mP : Yes i get that - but i want to read the meta data like wht classes are exported from a bundle without "installing" or "activating" them...Is this possible.

Copy Paste using Javascript

I have two textBoxes lets say EmailID and UserId. Currently when a user Types his/her EmailId the same gets shown in the UserID TextBox, for this I am using OnkeyDown event javascript.

The Issue That I am having is if the user copies the EmailId an Paste it in the EmailId textBox then the OnKeyDown event is not fired, is there any other Event that I need to capture or is there anyworkaround availabel for this.

From stackoverflow
  • Use the onchange event instead. That should work.

    Bryan : onchange is not fired until the textbox is blurred.
  • There isn't any event that will work for all methods of changing a textbox's contents. A workaround would be to set an interval when the EmailId text box gets focus, and cancel it when EmailId is blurred. The interval could either check if the text has changed, or just copy EmailId's value into UserID.

    Do you have to update UserID as they type? It would be cleaner to copy EmailId's value into UserId in EmailId's blur event.

  • You could make it so that the user cannot type into the UserId box, make it readonly, so you can still update it.

    Then, use an onblur on the email address box, and just copy whatever is there to the UserId box.

    There shouldn't be any way to update the email address that doesn't fire the onblur event.

How do I create collision detections for my bouncing balls?

I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.

import pygame
import random
import sys
class Ball:


    def __init__(self,X,Y):

        self.velocity = [1,1]
        self.ball_image = pygame.image.load ('Beachball.jpg'). convert()
        self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
        self.sound = pygame.mixer.Sound ('Thump.wav')
        self.rect = self.ball_image.get_rect (center=(X,Y))

if __name__ =='__main__':

    width = 800
    height = 600
    background_colour = 0,0,0
    pygame.init()
    window = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Bouncing Ball animation")
    num_balls = 3
    ball_list = []
    for number in range(num_balls):
        ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) )
    while True:
        for event in pygame.event.get():
                print event 
                if event.type == pygame.QUIT:
                        sys.exit(0)
        window.fill (background_colour)

        for ball in ball_list:
                if ball.ball_boundary.left < 0 or ball.ball_boundary.right > width:
                        ball.sound.play()
                        ball.velocity[0] = -1 * ball.velocity[0]
                if ball.ball_boundary.top < 0 or ball.ball_boundary.bottom > height:
                        ball.sound.play()
                        ball.velocity[1] = -1 * ball.velocity[1]

                ball.ball_boundary = ball.ball_boundary.move (ball.velocity)
                window.blit (ball.ball_image, ball.ball_boundary)
        pygame.display.flip()
From stackoverflow
  • Collision detection for arbitrary shapes is usually quite tricky since you have to figure out if any pixel collides.

    This is actually easier with circles. If you have two circles of radius r1 and r2, a collision has occurred if the distance between the centers is less than r1+r2.

    The distance between the two centers (x1,y1) and (x2,y2) can be calculated and compared as:

    d = sqrt((y2-y1) * (y2-y1) + (x2-x1) * (x2-x1));
    if (d < r1 + r2) { ... bang ... }
    

    Or, as jfclavette points out, square roots are expensive so it may be better to calculate using just simple operations:

    dsqrd = (y2-y1) * (y2-y1) + (x2-x1) * (x2-x1);
    if (dsqrd < (r1+r2)*(r1+r2)) { ... bang ... }
    

    The tricky bit comes in calculating the new movement vectors (the rate at which (x,y) changes over time for a given object) since you need to take into account the current movement vectors and the point of contact.

    I think as a first cut, you should just reverse the movement vectors to test if the collision detection works first.

    Then ask another question - it's better to keep individual questions specific so answers can be targeted.

    jfclavette : Just a note: square roots are rather costly operations, and you can square both sides of the equation since they are both positive. That gives you d^2 = (y2-y1) * (y2-y1) + (x2-x1) * (x2-x1) and (d^2 < (r1+r2)^2) as a test.
    paxdiablo : Good point, @jfclavette, especially if you want maximum frames/sec, incorporated into answer.
  • Detecting collisions was covered well by Pax's answer. With respect to having objects bounce off one another, I suggest checking out the following links concerning elastic collisions, inelastic collisions, and coefficients of restitution.

    EDIT: I just noticed that this was covered in another SO question, albeit not specifically for Python. You should also check there for some good links.

  • Detecting a collision is only the first step. Let's break that down.

    The fastest thing to do is calculate their square bounding boxes and see if those collide. Two of the sides need to cross (top of 1 and bottom or 2, and left of 1 and right of 2, or vice versa) in order for the bounding boxes to overlap. No overlap, no collision.

    Now, when they do overlap, you need to calculate the distance between them. If this distance is more than the sums of the radii of the balls, then no collision.

    Okay! We have two balls colliding. Now what? Well, they have to bounce off each other. Which way they bounce depends on a few factors.

    The first is their elasticity. Two rubber balls bouncing off each other rebound differently than two glass balls.

    The second is their initial velocity. Inertia states that they'll want to keep going in mostly the same direction they started in.

    The third is the mass of the balls. A ball with smaller mass will rebound off a much larger mass with a higher velocity.

    Let's deal with the second and third factors first, since they are intertwined.

    Two balls will rarely hit exactly dead on. Glancing blows are far more likely. In any case, the impact will happen along the normal of the tangent where the balls collide. You need to calculate the vector component of both along this normal given their initial velocities. This will result in a pair of normal velocities that both balls will bring to the collision. Add up the sum and store it somewhere handy.

    Now we have to figure out what each ball will take away from it. The resulting normal velocity of each ball is inversely proportional to the given ball's mass. That is to say, take the reciprocal of each ball's mass, add both masses together, and then parcel out the resultant normal velocity away from the collision based on the ratio of the ball's mass to the sum of the reciprocal of both ball's masses. Then add the tangential velocity to this, and you get the resultant velocity of the ball.

    Elasticity is mostly the same, except it requires some basic calculus due to the fact that the balls are still moving even as they compress. I'll leave it to you to find the relevant math.

    jfclavette : Circle/Circle collision is easier than axis-aligned bounding box to axis-aligned bounding box. Just skip the bounding boxes part :)
    gnovice : @jfclavette: I think he was using the bounding boxes as an easier-to-calculate first check for a potential collision before computing distances.
    jfclavette : @gnovice: Yes, I understood that. But Sphere/Sphere or Circle/Circle is faster than Box/Box. The first check is in fact harder to compute than the final check. We should therefore skip it.
    Ignacio Vazquez-Abrams : @jfclavette: I'm curious to know why you think a distance calculation is faster than "abs(x1 - x2) <= (r1 + r2) >= abs(y1 - y2)".
    jfclavette : Hmmm, I was thinking in integers where you're basically trading 2 abs for 3 muls. For floating point, abs is cheap, so you're right that it might actually be faster. Still don't thinks it's worth it for something that already has an efficient collision test tough.
  • @Pax: Your d-squared version is still computing d. It should read as follows:

    dsqrd = (y2-y1) * (y2-y1) + (x2-x1) * (x2-x1)
    if (dsqrd < (r1+r2)*(r1+r2)) { ... bang ... }
    
    gnovice : I fixed it for you. =)
    las3rjock : Thanks! Some day I will grow up and be able to fix others' broken code myself! :-)
  • I asked a similar question awhile ago:

    Ball to Ball collision detection and handling.

    Got some good responses there too.

  • I think there is somehthing simpler that you guys are missing espeically considering he's using pygame.

    Calling the get_rect function can set probably boundraies for the images and Rect that is created, is used for calculating the position of the image and if there are more than one object in the animation, it can be used for detecting collisions.

    colliderect & rect can be used, problem is i have no idea how you would implement it especially for an unkown number of balls.

    Keeping in mind it's python.

  • This doesn't answer you question but you could do the same thing in 3D via python with panda www.panda3d.org.

    Like pygame it also has smart ways to do collision detection.

  • Back in the good old times when CPU cycles were a premium coders used a simple trick to detect collision: they used such colours that they could tell from the pixel colour if it was background or an object. This was done on at least some C64 games.

    Don't know if you are willing to go this route, though..

  • First you need to check collision with rect.colliderect(other_rect)

    after that if they are colliding, you can check pixel perfect collision. So you don't mess with object's radius or shape.

    For pixel perfect collision checking, I use Masks: Make both mask objects with mask.from_surface, then put them to Mask.overlap function.

How do I show Error Message using Managed Custom Actions with Windows Installer

I am writing a managed custom action. I am using the DTF Framework from Windows Installer Xml to wrap the managed dll into a usable CA dll. The CA does what it is supposed to, but I am still having trouble with error handling:

Dim record As New Record(1)

' Field 0 intentionally left blank
' Field 1 contains error number
record(1) = 27533
session.Message(InstallMessage.Error, record)

The above code produces the following text shown in the MSI log:

MSI (c) (C4 ! C6) [13:15:08:749]: Product: TestMSI -- Error 27533. The case-sensitive passwords do not match.

The error number refers to the code contained in the Error table within the MSI. The Message shown above is correct.

My problem is: Why does Windows Installer NOT create a dialog notifying the user about the error?

From stackoverflow
  • If you want a dialog to show up that contains the message, you must do it yourself.

    Here's some code I use to do error handling in managed custom actions that run SQL. It shows a messagebox if the installation is operating with a full UI. It's in c# but hopefully you'll get the idea.

     private void _handleSqlException(SqlException ex)
     {
      StringBuilder errorMessage = new StringBuilder();
      errorMessage.Append("A SQL error has occurred.");
      for (int i = 0; i < ex.Errors.Count; i++)
      {
       errorMessage.Append("Index #" + i + "\n" +
        "Message: " + ex.Errors[i].Message + "\n" +
        "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
        "Source: " + ex.Errors[i].Source + "\n" +
        "Procedure: " + ex.Errors[i].Procedure + "\n");
      }
      session.Log(errorMessage);
      if (session["UILevel"] == "5")
      {
       MessageBox.Show(errorMessage);
      }
     }
    
  • MSI can do this, but you need to OR in some extra values for the messageType argument.

    eg.

    Record record = new Record();
    record.FormatString = string.Format("Something has gone wrong!");
    
    session.Message(
        InstallMessage.Error | (InstallMessage) ( MessageBoxIcon.Error ) |
        (InstallMessage) MessageBoxButtons.OK,
        record );
    

    See this thread from the wix-users mailing list for more details.

  • Hi thanks for the info.

    Do you know if there is a way too show big messages? When i use:

    Record record = new Record(); record.FormatString = pReallyBigMessage;

                Session.Message(InstallMessage.Error | (InstallMessage)System.Windows.Forms.MessageBoxIcon.Warning |
                    (InstallMessage)System.Windows.Forms.MessageBoxButtons.OK, record);
    

    Only parts are displayed. I would like to stick with the Session.Message functionality and not use the Windows.Forms Messagebox because of the focus.

    Greetings

  • Here is a walk-through concurring with ayeko's post.

    leogdion : Here is more information on showing a dialog or messagebox in a custom installer. http://social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/bbe69f12-8908-4c65-aa89-1963720d4c11

VB.NET getting the attributes of a .wav file

How do I get the attributes of a .wav file using VB.NET. In particular, I am looking for a property which has the Duration of the .wav.

Cheers

From stackoverflow

Please suggest some great websites for a .NET programmer.

Hi, I'm new to world of .NET programming and I want to know about websites that have articles, tips and other useful information about .NET and Microsoft technologies. The websites I currently visit are:

  • MSDN
  • StackOverflow
  • WindowsClient.NET
  • TheServerSide.NET

I'd love to learn about some new .NET websites!

Thanks, Ek

From stackoverflow

retrieving the serial number of a USB keyboard under Windows

Many USB devices contain a unique serial number (which is actually a Unicode string) which the host can use in conjunction with the 16-bit vendor and product ID numbers to uniquely identify the device.

I'm trying to figure out how to write a Windows application that would be able to display a list of all USB human interface devices attached to the system. The list would have one row for each HID, including system keyboards. There would be columns in the list for the vendor ID, product ID, and serial number.

I can get a list of USB HIDs by calling SetupDiGetClassDevs with the GUID returned by HidD_GetHidGuid and looping through the result by repeatedly calling SetupDiEnumDeviceInterfaces. I can then call SetupDiGetDeviceInterfaceDetail to get the path to each device, which I can open with CreateFile, so long as I am careful to request neither read nor write permission, which would be denied for a system keyboard. From there I can get the vendor and product ID numbers by invoking HidD_GetAttributes.

What I'm having trouble figuring out is how to retrieve the serial number string. When I search for solutions to this problem, I find a lot of information about how to get serial numbers for USB mass storage devices, but nothing that looks like it might apply to any other type of USB device. I would be happy to discover either a generic method or a HID-specific method of retrieving the serial number string.

I have a feeling that the Win32 port of libusb could manage this without too much trouble, but unfortunately I need a solution that depends only on libraries that come with Windows, such as the setupapi and hid DLLs that contain the functions mentioned above.

Any suggestions would be very much appreciated!

From stackoverflow
  • Have you tried searching for the documentation of the HID definition of input records, output records and features records for Hid keyboards. This should show you the list of "things" you can get out/in of a keyboard through HID.

    Also, I know it is possible to enumerate the HID record definition by software. I did something similar about 1 year ago, but I cannot remember the details at the top of my head. Doing so would allow you to see what the keyboard USB class is publishing as a standard interface.

    I hope it can get you a few pointers to find out what you are looking for. Sorry I could not be more precise!

    zaphod : Unfortunately, a USB string descriptor is neither a HID input report, nor an output report, nor a feature report. Thanks, though!
  • I recommend this book USB Complete. Chapter 4 Enumeration: How the Host Learns about Devices has the information you need.

    This page has many links to information and for you links to libraries and utilities you can use.

    zaphod : It's a great book -- I own a copy of the third edition, and I'm sure I would never have gotten so far as even asking this question if I hadn't read it. The chapter in question does indeed mention the information I'm trying to retrieve, though it doesn't seem to explain how to get at it from a Windows application.
  • Have you tried the USBVIew source code that comes along with the DDK. The USBView tool displays serial number for any USB device, and the source is shipped with the DDK.

  • It turns out that HID.dll defines a function called HidD_GetSerialNumberString that does exactly what I want, given the handle I got from CreateFile as described above. Just tried it out and it works great. There are also HidD_GetManufacturerString and HidD_GetProductString functions to retrieve the other string descriptors referred to in the device descriptor, and even a HidD_GetIndexedString to get an arbitrary string descriptor given its index (presumably because the HID descriptor is allowed to contain string descriptor indices). I feel pretty silly now -- the answer was right there under my nose this whole time.

    Thank you all for taking the time to read and answer my question! I'm going to go ahead and accept Alphaneo's answer since it sounds quite promising, and in fact I was waiting for the DDK to download when I stumbled across this answer.

  • Hi,

    you can use GetVolumeInformation for getting the serial number of any hardware attached.