Monday, February 21, 2011

Why isn't Selenium capturing my keystrokes?

I'm trying out the recorder of the latest Selenium IDE Firefox extension on win32/ff3.

On one page, currently I have to hit Enter to go to the next page, but it's not on a submit button, it's captured manually. This is not picked up by the recorder. I know I can enter it manually myself after recording, but why isn't this part of it?

From stackoverflow
  • Have you tried with a different browser? Does it happen the same in FF2, IE ? Use the latest nightly version. I know that there are some problems with FF3.

    Kev : I didn't, actually...this particular test I only needed to have work on ff3. I'd be interested in results some day though, so at that point I'll try it out...
  • From the Selenium FAQ:

    http://wiki.openqa.org/display/SIDE/FAQ

    "Not every event will be recorded by Selenium IDE. Usually the ones that won't be recorded are those that involve complex HTML and/or AJAX. We hope to improve this over time, but there will always be situations where the IDE can't record everything because it has to balance recording too little with too much."

    Kev : Huh...that's kind of too bad that an Enter keypress is somehow considered "complex HTML and/or AJAX." Well, hopefully some day...
  • This problem is particularly noticable and annoying when trying to write selenium tests for google maps-based applications, because Selenium IDE doesn't record the clicks on the map. I'd very much like to see a way around this that doesn't involve inserting "clickOn()" manually into the text script.

Automatic namespaces import

Is there a way in Visual Studio (a hotkey) to automatically import a type (or choosing between known namespaces) like the CTRL+O in Eclipse?

From stackoverflow
  • Look at JetBrain's excellent Resharper product. It does this for you.

  • When the red caret appears at the end of your member, just hit SHIFT+ALT+F10, then use arrows keys to choose the right option.

    Andrew : That doesn't automatically add the right 'using' declaration though. Resharper will.
    Enreeco : tried and never seen. thnks
    controlbreak : Seems buggy under VB.NET :-/
  • Yes, VS.NET Can add the using for you. When you type in a class name, hit CTRL + . and then enter (the first option is 99.99% the right one, so just hit enter). and you can have it add the using at the top of the file for the namespace of that class. I use it all the time.

    This is easier than shift alt f10 + enter as its les keys and the . and enter are closer.

    controlbreak : Yeah, CTRL + . is shorter - Thanks for the tip. Sounds buggy too in VB.NET

XSD and Automatic Class / Message Generation

What avenues are there for using an XSD to generate message instances? I seem to remember reading about generating classes from XSD, but can't find anything specific now. I know you can generate classes and datasets from XSD, but I'm looking for a pattern for automating the actual generation of the messages.

BTW, SO is my knowledge sharer of choice, not Google.

From stackoverflow
  • xsd /c yourschema.xsd > yourschema.cs
    
    ProfK : I'm actually looking for a way to generate message _instances_, so it seems more useful to generate a typed dataset, which I can populate with message data. I was wondering if there were any other ways.
  • You can also create an XSD from XML samples with xsd.exe. Start the visual studio command prompt and use it to create an xsd from an xml sample. Then you can, as leppie shows, use xsd.exe to create a typed data set from that XSD. I wouldn't recommend doing this blindly, but it can certainly help when using a third party xml service.

    XML -> XSD -> TypedDS by using xsd.exe.

  • Visual Studio XSD should be the first port of call. It will generate classes which you can serialise and deserialize the xml documents to/from.

    XSD will work for "simple" schemas, there are plenty which it cannot cope with.

    NB: if you schema imports other schema files you need to include those schema files on the command line as well.

    Other code generation from schema files tools include XMLSpy, Enterprise Architect. Worth looking at if XSD fails your requirements.

Discover what process/query is using the oracle SGA.

I have a query to monitor SGA (non-)utilisation:

select sum(bytes)/1024/1024 " SGA Free " from v$sgastat where name='free memory';

That's great, but I need more detail about what exactly is using the space. Essentially, I'm looking for clues to tell me more precisely what might be wrong with this (rather large application).

select * from v$sgastat does not give me anything that I recognise as a developer - at least not without some pointers.

From stackoverflow
  • Here's a query that I use to see pool size in the SGA

    SELECT POOL, NAME, Round(BYTES/1024/1024,2) Mb
    FROM V$SGASTAT WHERE POOL LIKE '%pool%'
    order by 1,3
    

    Looks great in SQL Developer as a BAR_HORIZ_STACK chart.

    All the information you need ought to be in the V$SGASTAT view. Remember that it's shared space, so it's difficult to tie usage to particular processes.

    Simon Gibbs : This answer covers topics specifically excluded from the scope of the question.
    Simon Gibbs : Actually, remembering its shared space proved to be a little useful, thanks.

XML as data source : best practice for reading

I'm working on a small project where for the first time I want to use XML as the one and only data source...a file based store suits the need of the project.

When writing the DAL should I have all the get methods static? to aviod and "reading while file open" errors? Should I use CacheDependency on the file?

Thx

From stackoverflow
  • Is my question crap, boring or does no one have an opinion on it?!?

    Sklivvz : You should make the question a bit more specific, IMHO.
    kenny : with a face like that, maybe everyone is scared. :)
    SteveCl : man, ur kiddin!! This is the results or seven operations!!
  • I think you were not as clear as you could have been. How big are these files going to be? Would it make sense for the data layer to always keep the XmlDocument in memory and dump to harddisk on every update?

    How often are updates going to occur, if at all? How are you going to handle concurrency? Are updates going to be transactional across multiple xml files? How are you going to handle consistency and transactional integrity? If there are no updates, your life will be much simpler.

    Methods don't have to be static. The main thing to consider is that, in the future, you might want to change the DAL provider from XML to DB. To this end, the concrete implementation of the DAL interfaces should talk to an abstract data provider. For you, it would be an Xml provider initially, but you should be able to write a Sql Provider that implements the same interface and easily switch the implementation using dependency injection, config files or what-have-you.

    One you have instances of the DAL implementations, you can just use those objects to talk to the data layer.

    Hope this is a good start for you.

  • OK.

    The files are not likely to be huge, I would suspect the max to reach 1-2MB.

    I get you with the DAL interface needing to be interchangable with a DB, so I need to think carefully about my interfaces.

    Concurrency, well I am concerned about that and not entirly sure how I should handle it. I was thinking that static read and write methods would help.

    The XML will be updated, not that often, maybe once a day, but it could be anytime and more often.

    I am using a CacheDependancy to only get from the source when the file has changed.

    Will i run into problems reading the Cache concurrently? So how do I deal with concurrency issues?

Does a user need admin rights to install Flash player?

Will users who do not have admin rights on their computers be able to upgrade to new Flash player version by themselves?

This would be interesting to know for: Windows 98 Windows XP/2000/Vista Macs Unix/Linux

From stackoverflow
  • For Windows: yes you need admin rights for the system to install flash player. which installs through an exe file

  • Take a look at the Adobe instructions for more clarification...

    I know on Linux, at least, you do not need admin privs. Flash is installed in ~/.mozilla/plugins when you use the .tar.gzed installer script.

    On Windows, I think there's only the option of doing a system-wide install so you need Administrator rights.

    From the instructions for both Mac and Windows:

    Installation of Adobe Flash Player may require administrative access to your PC, which is normally provided by your IT department.

    May require? Thanks for being clear, Adobe =) I think it's safe to assume they do as they're both system-integrated installers. The same goes for Linux if you use the YUM/RPM installers. If you use the script, you can run it as anybody with execution rights.

  • For Mac the answer is "not really, but then again, yes" :P

    Actually he wouldn't need it. On Mac there is a directory for browser plugins. No matter if you use Safari or Firefox (or possibly another browser), it is standard or Mac that browsers search their plugins in that folder. It is named:

    Library/Internet Plug-ins
    

    And as always on Mac, this directory exists twice. Once as system directory

    /Library/Internet Plug-ins
    

    and also once for every user

    /Users/<username>/Library/Internet Plug-ins
    

    It doesn't matter into which directory a user puts a plugin, the browser will look into both. That means if I put it into the System's Library folder, all users will have the plugin, if I put it into my folder only, only my user has it.

    So far the theory. The problem in practice is that Adobe doesn't ship the flash plugin as a plugin file, you could just copy into either location (why not? On Mac almost any app or plugin could just be shipped as a file. It really won't kill the user to manually copy it somewhere), but it ships an installer (I hate installers on Mac). And the installer wants to put it into the System's Library folder for all users AFAIK. To do that, it will prompt the user for the appropriate permissions and only an admin user can grant these permissions.

    David Arno : Excellent answer
  • I just managed to get it working for a Mac OS X without admin rights.

    Download the installer from Adobe and make sure to save it somewhere, rather than letting it automatically open. Unzip the installation archive and you should end up with "Install Flash Player 10" mounted. Check inside that, but instead of opening "Adobe Flash Player.pkg", right click that file to Show Package Contents.

    In the folder that pops up, open Contents and look for archive.pax.gz or resources/adobe flash player.pax.gz, both seem to contain the same things. Unzip that archive.

    You'll find flashplayer.xpt and flash player.plugin in there. Copy both of them to users/whichever user you are/library/internet plugins... if you see those files there already, it's the right place, just want to replace them with the new ones, then restart your browser.

    Hopefully that'll work for you.

  • NO If your using Firefox Download the XPI archive of the Flash Player Plugin to your hard drive http://fpdownload.macromedia.com/get/flashplayer/xpi/current/flashplayer-win.xpi

    Rename the file you downloaded, called flashplayer-win.xpi, into flashplayer-win.zip Extract the files in the archive

    Copy the files flashplayer.xpt and NPSWF32.dll to %APPDATA%\Mozilla\Plugins\

    * %APPDATA% is the folder which holds your applications profiles and settings.
    * You can open this folder simply choosing "Start → Run → Type in %APPDATA% → OK".
    

    Restart Firefox

    Tmdean : Thanks; tried this and worked great.
  • This works perfectly. Thank you. I downloaded the xpi with Explorer so Firefox wouldn't try to install it, though.

Best way to simulate a WAN network

Simplified, I have an application where data is intended to flow over the internet between two servers. Ideally, I'd like to test at what point the software ceases to function. At what lowerbound limit (bandwidth, latency, dropped packets) do things stop working to test the reliability of the software.

What I thought I would do was the following:

  1. Setup up 3 machines (VMware instances)
  2. Install the 2 applications on two of the servers.
  3. Setup up the 3rd server to sit between the two machines by doing some sort of magic with Routing and Remote Access on Windows 2003
  4. Install either Traffic Shaper XP or NetLimiter to limit the bandwidth
  5. Run something like TMnetSim Network Simulator to simulate a bad connection.

Does this sound like a good idea or are there easier/better ways of doing this? I'm not that comfortable on Linux and my team mates are even less so.

From stackoverflow
  • FreeBSDs ipfw has provisions to simulate links with a given bandwith, latency or error rate. You could use that FreeBSD machine as your machine "in the middle" in your above setup.

    You probably can also run at least one of the endpoints on the same machine if you want to reduce the amount of servers involved.

    Flash Sheridan : A colleague and I used ipfw with great success for proxy load testing, many years ago. It replaced an expensive solution (which shall remain nameless) which worked so poorly that I tried to get our money back.
  • We had a similar requirement some ten years ago - I'll see if I can recall how we managed it.

    If I remember, we wrote a socket proxy program which was controlled by inetd on a UNIX box. This socket would accept connections from a client and open equivalent sessions through to the server. It would then loop, passing messages in both directions.

    The way we achieved WAN characteristics was to introduce random delays (with upper and lower limits) in both the connection establishment and the passing of data once the link was up.

    It also had the feature to drop the link occasionally as WAN links were less reliable for us than local traffic.

    I recall we had to make it threaded to stop the delays from affecting reverse traffic on the link.

  • Someone actually packaged up the settings and whatnot necessary for the FreeBSD solution to this problem and they call it DUMMYNET.

    It simulates/enforces queue and bandwidth limitations, delays, packet losses, and multipath effects. It also implements a variant of Weighted Fair Queueing called WF2Q+. It can be used on user's workstations, or on FreeBSD machines acting as routers or bridges.

    It can simulate exactly what you want, and its free and will boot onto commodity hardware. They even have a canned install of it that is small enough to put on a floppy disk (!) that you can download at that link.

    Richard Nienaber : Can DummyNet work on VMware machines? I downloaded and looked at it and seems to only work on physical machines. The examples I've seen use two crossover cables between the machines and freebsd machine and I'm not sure how to setup freebsd as a gateway.
    Tim Farley : I haven't tried dummynet on VMware, but that is certainly an interesting idea. Potentially if you built a cheap fast box with a bunch of network cards you could simulate a whole topology with it.
  • WANem does exactly this. We have used it both in a virtual machine on the desktop and on a dedicated old pc and it worked great. It can simulate all sorts of broken connectivity.

How do I trigger a BulletedList in LinkButton-mode with javascript?

Hi!

I have a BulletedList in asp.net that is set to DisplayMode="LinkButton". I would like to trigger the first "bullet" from a javascript, can this be done? And if so, how?

From stackoverflow
  • Say you have the BulletedList as

    <asp:BulletedList runat="server" ID="MyLovelyBulletedList" DisplayMode="LinkButton">
        <asp:ListItem Text="My Lovely Text 1" />
        <asp:ListItem Text="My Lovely Text 2" />
    </asp:BulletedList>
    

    ... then you can fire the "onclick" event like this (cross-browser):

    var links = document.getElementById('<%= MyLovelyBulletedList.ClientID %>').getElementsByTagName('a');
    
    var targetLink = links[0];
    
    if (targetLink.fireEvent)
    {
        // IE
        targetLink.fireEvent("onclick");
    }
    else if (targetLink.dispatchEvent)
    {
        // W3C
        var evt = document.createEvent("MouseEvents");
    
        evt.initMouseEvent("click", true, true, window,
         0, 0, 0, 0, 0, false, false, false, false, 0, null);
    
        targetLink.dispatchEvent(evt);
    }
    
    Cros : The targetLink.fireEvent("onclick"); line doesn't seem to work. Using alert I can see that targetLink is the correct link, but it won't fire.
    Alexander Gyoshev : rather strange - i'll try to run it again. as a side-note, if you wish to simply make a post-back, you could call __doPostBack ('<%= MyLovelyBulletedList.ClientID %>', 0);
    Cros : Sadly this doesn't work for me. For some reason it just "fires" the first hyperlink on the page instead.
    Cros : This solution works in Opera and Google Chrome, but not in Firefox and Internet Explorer.
  • Similar to what Alexander indicated except that you could use jQuery to fire the event and depend on their cross-browser support rather than maintain it on your own.

    $('#<%= MyLovelyBulletedList.ClientID %>')
        .contents()
        .find('a:first')
        .trigger('click');
    
    Alexander Gyoshev : that too :) it looks so damn good with jQuery! I guess that soon we'll make John Resig chapels all over the world...
    Alexander Gyoshev : and... it could be written as $('#<%= MyLovelyBulletedList.ClientID %> > a:first').trigger('click');
    Cros : We don't use jQuery as of now, but damn that looks smooth :)
  • After a lot of testing it seems the only dependent way to do this is by manually firing the __doPostBack-script like so:

    __doPostBack('MyLovelyBulletedList', '0');
    

    as suggested by Alexander Gyoshev

Tomahawk and scrolling tabs

Hello,

is there a tomahawk component, that enables "scrollable tabs"? What I mean is something for the following situation:

If I have very many tabs, the tab-bar gets a little arrow on the side to scroll through all the open tabs (like in firefox).

image

Is there a tomahawk component for creating something similar?

From stackoverflow
  • Are you/have you tried using the panelTabbedPane tag?

    Mo : No, I have not tried panelTabbedPane. But I just glanced over it and if I am not mistaken, it misses the feature of scrollable tabs. (Although thanks for the tag - I did not knew it!)

Finding the end of a substring match in .NET

I am trying to find the index of a substring in a string that matches another string under a specific culture (provided from a System.CultureInfo).

For example the string "ass" matches the substring "aß" in "straße" under a German culture.

I can find the index of the start of the match using

culture.CompareInfo.IndexOf(value, substring);

but without resorting to brute force, is there an easy way of identifying that 2 characters were matched, and not 3?

From stackoverflow
  • Does regular expressions handle that distinction of ss vs. ß?

  • If you use a capture group, you can capture the exact match that was found, and from that you can determine how many characters were matched.

    I'm a bit timestressed right now to give an example, so I hope you can figure it out from my description.

    Perhaps I'll ammend my answer later.

    Dave

    Oliver Hallam : I was not aware that a regular expression could be run under a particular culture - how is this done?
    Dave Van den Eynde : The documentation states that case-insensitive operations are culture-sensitive by default. The Thread.CurrentCulture is used at this point. But apparently (under .NET 2.0) it doesn't match "ß" with "ss", even though they are the same under that culture. So my anser doesn't help you.
    Oliver Hallam : I know I have experienced issues with MS's regex before. Its case-insensitive matching fails to match a lower case k with a kelvin sign for example (despite them both having the same upper case), and fails to deal with multibyte characters (which is another requirement here).

Easy IIS install of php

Are there any "all-in-one" installers for php + mysql on iis? Preferably with a gui configuration interface.

From stackoverflow
  • I don't know of any all-in-one installers for both MySql and PHP, but PHP itself comes with an automated installer that will attach itself to IIS - but the preferred method is still manual (the automated procedure only uses CGI). There are plenty of how-to pages on the web that give you the step-by-step procedure required to get setup (and these differ based on your version of IIS) - I suggest you use one of those instead.

    Some links to get you started:
    PHP Documentation
    Installing PHP 5 on IIS in 5 simple steps

    William : It is actually more for running open source bug tracking apps, project management apps, etc and not for doing any dev so speed isn't that important.
  • I know this is not a direct answer, but a point of interest only. If you are looking for something that runs php/mysql that is quick to get setup for testing purposes you could try using a virtual appliance+vmware server/player

    William : I've tried running virtual machines but the server doesn't like the extra load.
    mattlant : Really? Hrm, thats inetrsting. I have found that the specialized virtual machines can run on tiny amounts of ram (depends of course on what you are doing) and the server desnt even break a sweat. Oh well. Anyhow, sorry i could not have been more help.
  • The PHP part is easy with Web Platform Installer:

    http://php.iis.net/

    MySQL is a breeze to install on Windows:

    http://dev.mysql.com/downloads/mysql/5.1.html#win32

DB: To use identity column or not?

While designing a table my colleague here says that I should avoid identity column as it is specific to SQL Server and MS Access, But I differ with his views as it makes my coding simpler.

Should I use identity column or not? If not what is best way to create the identity columns from application code?

From stackoverflow
  • Does it matter that it is specific to the Microsoft platform? Is your application meant to be portable, i.e. are you planning to migrate it to mysql/postgres/whatever?

    Kishork : It is not planned as of now, However I guess it will be MS SQL server forever, unless MS will run into trouble in future.
  • You can't completely divorce an application from the database vendor. If you do you won't be able to take advantages of whatever features your database provides you.

    I'd say use the identity column. If you move over to Oracle (for example), you can use a Sequence. Hardly a big change.

    I don't know what technology you're using, but one thing that would help is using a tool such as Hibernate or iBATIS (I think they're both available for Java and .NET) which separates you a bit from the database implementation details. Then if you change database vendor you won't need to change application code, just configuration. (In theory, at least!)

  • As far as i am aware, every slightly serious RDBMS has some sort of unique numbering scheme per table.

    1. Access and SQL Server have identity columns
    2. MySQL has auto increment columns
    3. PostgreSQL has sequences
    4. sqlite has an implicit ROWID column
    5. Oracle has some sort of sequence though I'm not at all familiar with it

    I mostly use it, theoretically it's not always a requirement but if you want to maintain referential integrity an int is less to store and easier to compare than a varchar, especially if your foreign keys would be more complex than a single column.

    Dave Van den Eynde : You're not familiar with sequencers in Oracle, so you decide that "every slightly serious RDBMS has a number scheme per table"?
  • Use Identity column!

    It do separate your "Application Logic" from "Business Logic"

    Let's say you use "email" as primary key (which do make sense in term of "business logic"). You'll get into trouble when that email no longer exist and your user want to edit your email.

  • This is one of the problems I face with Oracle, and could be anybody that has SqlServer background. I was developing a code generator tool (for stored procedure) for Oracle, and I wanted to detect identity columns. It was a difficult task because oracle corp does not store information on column that uses a particular sequence.

    I tried to manage though ALL_SEQUENCES and ALL_TRIGGER_COLS metadata tables.

    cheer!

    Ojulari Hakeem

What to do if I don't have Visual Basic 6.0 and need to compile a VB6 project?

A client wants me to do some maintenance work to a VB 6.0 application (migration to .NET is also in the pipeline), but he doesn't have the development tools because he received just the source code and running application from the original programmer, who is no longer available.

Microsoft doesn't sell Visual Studio 6.0, as far as I know. How can I modify and compile the source code for a VB6 application without VB6? or Where do I get Visual Studio 6.0 if Microsoft is not selling it?.

Even if I migrate everything to .NET without releasing a new VB6 version, I would like to be able to open the project and see it compile and run to better understand it.

I have VS 2005 and VB 2008. But I understand that if I try to open the project the code will be converted to VB.NET and that's not what I would want before getting to know the project better.

From stackoverflow
  • To get a feel of the code, you could try to compile parts of the application in M$ Office / VBA.

    Of course, this will only offer limited functionality, but may suffice for some testing.

    Sergio Acosta : I have both worked with VB6 and VBA and know them well, and I don't think that the complexity of this application could be handled by VBA. If I just wanted to understand a few functions I don't need to run them, I can just read the code without problem.
  • Hunt Ebay or Craigslist. Or call your regular software vendor, I'm sure they can still get it for this sort of reason.

    Sergio Acosta : I suppose this is the easiest way. thanks for the suggestion.
  • From what I recall the Visual Studio 6.0 is available for MSDN Subscribers.

    Sergio Acosta : Why was this downvoted? I'm curious? Is VB6 still available to MSDN suscribers? That could be useful.
    Roel : Correct, I just checked - VB6 Enterprise Edition is there in the MSDN downloads.
  • Both Amazon and eBay currently have copies for sale (although they seem a tad expensive but this would be a pass-through cost to your customer so it's up to them whether they pay this).

    You may want to check out the licence for VB.net; it may allow you to run previous versions of the software.

    The MSDN "Visual Studio 2008 Professional with MSDN Professional" has previous version of Visual Studio tools but it comes in at USD1200 so, if you just want VB6, eBay is the better option.

    Keep in mind that MSDN pack has all the Visual Studio languages and VS6 through to VS2008 so it's probably got everything you need.

    The other option I thought of is not legal so I won't suggest it.

  • Visual Basic 5 Control Creation Edition might be suitable to tide you over until you can get hold of a full version of VB6. There are limitations and it is 5 not 6, but depending on the scope and complexity of the application it might work for you as an interim measure.

    Karl E. Peterson : Nope, can't recompile (anything but an OCX) with CCE. Given that was a stated requirement, it won't work for this situation.
    Rob : Umm - I'm pretty sure CCE will allow you to fulfill the "I would like to be able to open the project and see it compile and run to better understand it." element of it, as you can run a compiled EXE, VB just doesn't write it to disk anywhere so you can't take the EXE and use it (which is why I suggested it as an *interim* measure).
  • Many textbooks on Visual Basic 6 frequently included a fairly usable version if VB (I can't recall the exact name offhand, perhaps VB 6 student edition?) that allowed the compiling of .exe files. VB 5 textbooks usually bundled VB 5 CCE, VB 4 books bundled VB 4 WM, neither of these are suitable replacements for a production VB 6 app IMHO, especially their lack of ability to create .exe files.

    I will say, Visual Studio 2005 (VB 8) converted VB 6 apps quite well if that's an acceptable interim solution (which it may not be given the requirement for the large .NET 2.0 runtimes).

WeakReference and event handling

Is it a good practice to implement event handling through WeakReference if that event is the only thing holding the reference and that we would need the object to be garbage collected?

As an argument to this:

Folks say that if you subscribe to something it’s your responsibility to unsubscribe and you should do it.

From stackoverflow
  • While what you suggest solves one set of problems (event reference management and memory leak prevention), it is likely to open up a new set of problems.

    One problem I can see is during event handling process if the source object is garbage collected (as it was only held with a weak reference), any code that access the source object will result in null reference exception. You can argue that the event handler should either not access the source object or it must have a strong reference, but it can be argued that this could be a worse problem than the one you are trying to solve in the first place.

    Ilya Ryzhenkov : When CLR already executes event handler, stack will hold reference to "this" and objects will not be collected.
  • Weak delegate pattern is something that should be there in CLR. Normal events exhibit "notify me while you are alive" semantics, while often we need "notify me while I'm alive". Just having delegate on WeakReference is wrong, because delegate is an object too and even when recepient is still alive and have incoming references, delegate itself is only being referenced by said WeakReference and will be collected instantly. See this old post for an example of implementation.

  • Weak references in their own right, don't solve the problem as the delegate holds the reference. In the Composite Application Library which ships with Prism (www.microsoft.com/compositewpf) there is a WeakDelegate class that you could pull from the source. The WeakDelegate basically ues reflection and creates a delegate only for a moment in time and then releases it, thereby no holding any pointers. Within CAL it is used by the EventAggregator class, but you are free to rip it out for your own usage as it is under MS-PL.

  • You can take a look at how this problem is approached in WPF here:
    http://msdn.microsoft.com/en-us/library/aa970850.aspx

  • It is good to get in the habit of unsubscribing from events when you can, but sometimes there isn't an obvious "cleanup" method where it can be done. We recently posted a blog article on this subject; it includes methods that make it easy to subscribe to an event with a WeakReference.

  • I found another quite nice implementation here:

    http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx

    Andrew Garrison : very nice resource

Stripping out a link in jQuery

I have a bit of html like so:

<a href="#somthing" id="a1"><img src="something" /></a>
<a href="#somthing" id="a2"><img src="something" /></a>

I need to strip off the links so I'm just left with a couple of image tags. What would be the most efficient way to do this with jQuery?

From stackoverflow
  • $("a > img").parent()   // match all <a><img></a>, select <a> parents
       .each( function()    // for each link
       { 
          $(this).replaceWith(              // replace the <a>
             $(this).children().remove() ); // with its detached children.
       });
    
    Sugendran : If there are any siblings to the image then this will copy them as well. You may want to use $(this).children("img").remove() instead.
    Shog9 : @Sugendran: true.
    defrex : There don't happen to be any siblings. But that is a good point.
  • This should do it:

    $('a[id^=a]').each(function() { $(this).replaceWith($(this).html()); });
    
  • Ain''t got any idea of how a jQuery code would be, but in plain javascript it would be something like:

    <script type="text/javascript">
    window.onload = function(){
      var l = document.getElementsByTagName("a");
      for(i=0, im=l.length; im>i; i++){
        if(l[i].firstChild.tagName == "img"){
          l[i].parentNode.replaceChild(l[i].firstChild,l[i]);
        }
      }
    }
    </script>
    
    Alexander Prokofyev : jQuery is being used today to elegantly replace peaces of code like your propose here. Thanks anyway!
    Adhip Gupta : Seriously, this snippet just shows the elegance of jQuery. This code and the code by Shog9 are exactly the same but, one is smaller and so much neater to read. Though, this code will perfectly do the job too!
    roenving : Elegantly -- yes it looks rather neat, but inside jQuery it's much larger, so if you ain't got other reasons to engage a huge library, use this. But of course, defrex asked for a jQuery-thing and this isn't !-)
    defrex : Perhaps this is bad of me, but I've gotten so used to jquery (and libraries like it) that I can't even imagine trying to code in raw js again. I think my users can handle the overhead.

java.beans.Introspector getBeanInfo does not pickup any superinterface's properties

I just noticed that java.beans.Introspector getBeanInfo does not pickup any superinterface's properties. Example:

public interface Person {
    String getName();
}
public interface Employee extends Person {
    int getSalary();
}

Introspecting on Employee only yields salary even though name is inherited from Person.

Why is this? I would rather not have to use reflection to get all the getters.

From stackoverflow
  • Try using

    public static BeanInfo getBeanInfo(Class<?> beanClass, Introspector.USE_ALL_BEANINFO);
    

    and see if this yields the result you're looking for.

    Steve Kuo : I tried that and it didn't work. My solution was introspect the superclass and parent interfaces by calling the class's getInterfaces() and getSuperclass().
    MetroidFan2002 : Do you only want the properties? You can get the property descriptors from BeanInfo, I believe it contains all the properties including ones from superclasses.
  • In such a case, you should write a custom BeanInfo class.

    Scott Stanchfield : note that you'll need to define getAdditionalBeanInfo() if you have define a custom BeanInfo
  • This issue is covered in Sun bug java.beans.Introspector doesn't work for interfaces

Os.path : can you explain this behavior ?

I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.

I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :

filepath = r"c:\ttemp\FILEPA~1.EXE"
print os.path.basename(filepath)
'c:\\ttemp\\FILEPA~1.EXE']
print os.path.splitdrive(filepath)
('', 'c:\ttemp\\FILEPA~1.EXE')

WTF ?

It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".

Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.

From stackoverflow
  • From a os.path documentation:

    os.path.splitdrive(path)
    Split the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.

    If you running this on unix, it doesnt use drive specifications, hence - drive will be empty string.

    If you want to solve windows paths on any platform, you can just use a simple regexp:

    import re
    (drive, tail) = re.compile('([a-zA-Z]\:){0,1}(.*)').match(filepath).groups()
    

    drive will be a drive letter followed by : (eg. c:, u:) or None, and tail the whole rest :)

    e-satis : Yep, just realize that : the string process is based on the OS, not on syntax. It does not make any difference between win and unix path, it just apply a different algo according to you platform. Crap.
    Moe : Don't use regular expressions, use the ntpath module instead - see my answer.
    e-satis : No offense kender, he's right :-)
    kender : I agree :) Never had to deal with windows-style patchs, just had no idea of that module:)
  • See the documentation here, specifically:

    splitdrive(p) Split a pathname into drive and path. On Posix, drive is always empty.

    So this won't work on a Linux box.

  • If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux)

    >>> import ntpath
    >>> filepath = r"c:\ttemp\FILEPA~1.EXE"
    >>> print ntpath.basename(filepath)
    FILEPA~1.EXE
    >>> print ntpath.splitdrive(filepath)
    ('c:', '\\ttemp\\FILEPA~1.EXE')
    
    Eli Bendersky : This is an excellent answer that deserves to be the accepted one, IMHO. It is much better to use ready-made tools than craft your own regexps.
    efotinis : +1 for ntpath; that's the right thing to do
    e-satis : My gof, this is brillant !

Overriding the java equals() method quirk

I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.

Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.

Anyhow -

I was developing a basic shopping cart which could contain an ArrayList of Book objects. In order to implement the addBook(), removeBook(), and hasBook() methods of the Cart, I wanted to check if the Book already existed in the cart. So off I go -

public boolean equals(Book b) {
    ... // More code here - null checks
    if (b.getID() == this.getID()) return true;
    else return false;
}

All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the Cart and everything works fine. I read that you can either have equals(TYPE var) or equals(Object o) { (CAST) var } but assumed that since it was working, it didn't matter too much.

Then I ran into a problem - I needed to create a Book object with only the ID in it from within the Book class. No other data would be entered into it. Basically the following:

public boolean hasBook(int i) {
    Book b = new Book(i);
    return hasBook(b);
}

public boolean hasBook(Book b) {
    // .. more code here
    return this.equals(b);
}

All of a sudden, the equals(Book b) method no longer works. This took a VERY long time to track down without a good debugger and assuming the Cart class was properly tested and correct. After swaapping the equals() method to the following:

public boolean equals(Object o) {
    Book b = (Book) o;
    ... // The rest goes here   
}

Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly was a Book object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?

From stackoverflow
  • In Java, the equals() method that is inherited from Object is:

    public boolean equals(Object other);
    

    In other words, the parameter must be of type Object.

    The ArrayList uses the correct equals method, where you were always calling the one that didn't properly override Object's equals.

    Not overriding the method correctly can cause problems.

    I override equals the following everytime:

    @Override
    public boolean equals(Object other){
        if (other == null) return false;
        if (other == this) return true;
        if (this.getClass() != other.getClass())return false;
        MyClass otherMyClass = (MyClass)other;
        ...test other properties here...
    }
    

    The use of the @Override annotation can help a ton with silly mistakes.

    Use it whenever you think you are overriding an super class's or interface's method. That way, if you do it wrong you will get a compile error.

    Cowan : This is a good argument in favour of the @Override annotation... if the OP had use @Override his compiler would have told him that he wasn't actually overriding a parent class method...
    jjnguy : Totally agreed!!!!! I will add that to my answer in a sec
    Josh Smeaton : Was never aware of the @Override, thanks for that! I'd also like to add that overriding hashCode() really should have been done and may have spotted the error sooner.
    sk : Some IDEs (e.g. Eclipse) can even autogenerate equals() and hashcode() methods for you based on the class member variables.
    jjnguy : Eclipse usually does a good job too.
    Michael Myers : +1 for @Override. And--that last edit made me laugh. :)
    jjnguy : thanks, it came a month late. I'm surprised nobody noticed it until now.
    Michael Myers : Maybe they thought it was intentional.
  • I am sorry I am kind of sleepy .. but you can read here to get an idea of your problem :) http://forums.sun.com/thread.jspa?threadID=620716&messageID=3497835

  • jjnguy has the right idea. I'd also like to add that you should always override hashCode whenever overriding equals.

    jjnguy : I wonder why you got a downvote. Its not an answer to the question...but it can't be unhelpful. Its always good to have a reminder.
    Julie : thanks for your support :-)
  • Slightly off-topic to your question, but it's probably worth mentioning anyway:

    Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.

    I also agree that you should use the @Override annotation whenever you're overriding equals (or any other method).

    tunaranch : If you're an eclipse user, you can also go `right click -> source -> generate hashCode() and equals()`,

Insert array into database in a single row

I wonder if this would be doable ? To insert an array into one field in the database.

For instance I have a title, I want to have that title with only one id, but it's going to be bilingually used on the website.

It feels a bit unnecessary to make another table to have their global ids and then another table with the actual titles linked to the table with the global id.

I just want to have something like this

ID      TITLE
1       Array("english title", "nederlandse titel");

I'm using PHP/MSYQL, so if it would be doable could you please explain in these languages.

Oh yeah I figured that I could format it funky and use the split function to turn it into an array again. But I wonder if I could just store it as an array right away, I case the user might type something with the same formatting (one out of a million)

From stackoverflow
  • Can I ask why you wouldnt want to utilize a relational database to its fullest potential?

    Robert Gould : Well, this is not my project, but occasionally for very small and specific projects, simply storing data like Owen is suggesting isn't such a bad idea, since it simplifies the work required. Of course if you don't need to query, but just retrieve by key
    Optimal Solutions : I read your comment about storing scripts in the DB, and for that - I can see its usefulness.
  • There's really only two reasonable choices here:

    Join with another table
    pros: unlimited titles in unlimited languages
    cons: join overhead is more computationally expensive, SQL is marginally more complex to update/insert etc

    Multiple columns
    eg: TITLE_EN, TITLE_NL, TITLE_DE
    pros: fast to insert, select, etc
    cons: limited number of languages, adding more is an ALTER TABLE

    Given our two choices, you usually should should pick the first one. Unless you're dealing with just an obscene amount of transactions that cannot be parallelized, or you absosmurfly can ensure that you will never add languages, the extra flexibility in schema layout will save you headaches in the long run.

  • it's doable:

    $title = serialize($array);
    

    and then to decode:

    $title = unserialize($mysql_data);
    

    but as mentioned it really lessens the benefits of a database in the first place. i'd definitely suggest looking into a multi-table or multi-column option instead, depending on the amount of languages you want to support and if that number will change in the future.

    edit: a good point mentioned by dcousineau (see comments)

    Sometimes the serialized output, even after escaping, throws characters into the query that screws things up. You may want to wrap your serialize() in base64_encode() calls and then use base64_decode() before you unserialize.

    adjusted code for those situations:

    $title = base64_encode(serialize($array) );
    $title = unserialize(base64_decode($mysql_data) );
    
    Nick Stinemates : Beat me to it ;)
    Robert Gould : As a side note, Owen's solution is also useful if you need to store scripts in a database.
    bmdhacks : I'm having trouble expressing how dangerous this approach is. If you ever decide that you need to query this data (which you do, in databases), you're screwed. And it's not a simple alter table that will fix it. I speak from experience with this, you're going to get burned with this approach.
    Owen : i don't think anyone would disagree with you. but if the question is "how do i store an array" the answer is "serialize". me and others have offered reasons and alternatives to not use this solution, but ultimately it's up to the OP to choose what works for him.
    Darryl Hein : Serializing into a db is great when you want say log something so you can look at it later and maybe only want to search for a string (without ordering of course). And that searching is only done by you, not by a user.
    dcousineau : A caveat: Sometimes the serialized output, even after escaping, throws characters into the query that screws things up. You may want to wrap your serialize() in base64_encode() calls and then use base64_decode() before you unserialize.
  • Arrays do violate normalization; in my experience with internationalization databases I've found that having a the phrases normalized is the best design,

    I allows you to easily make wholesale copies of rows - for instance 'es' to 'es-mx' or 'en' to 'en-US', 'en-GB', and my favorite: 'xx-piglatin'. In an array schema, you would either have to re-write every record or add complex parsing or use something more complex than arrays, like XML.

    It is relatively easy to use LEFT JOINs for find untranslated phrases for work and also to use COALESCE to return a default so the program remains usable even if the phrase is not translated.

  • Use a table with 3 columns !

    ID, TITLE_EN, TITLE_NL

    There is no good reason to serialize that, REALLY !