Sunday, April 3, 2011

user key/mouse input tracking. C#

I want to track how long i been away from my keyboard/how long i took a break. I figure tracking my keyboard and mouse is a good way to see when i left and arrived. Whats the best way to track this? Some options i see

  • Have a system wide callback for every mouse and keyboard press.
  • Sleep for a 100ms and see if there is a keydown or mousemovent
  • Use a system call that actually tells me when the last userinput was and use a combo of the above for efficiently. (sleep until user is away, then use callback to track arrival)
From stackoverflow

svn:ignore property during import

How do I apply an svn:ignore glob recursively while doing an import?

From stackoverflow
  • I'm not sure what you mean by "applying svn:ignore recursively while importing".

    If you want to exclude a set of files from being imported you can set the global-ignores property in ~/.subversion/config before importing. There's no command line option to do that on-the-fly.

    Alternatively you may add the directory and delete the unwanted files before committing:

    $ svn co --non-recursive <repository_url> repo_root
    $ cp -R <project_to_import> repo_root
    $ cd repo_root
    $ svn add *
    $ find . -regex ".*\.\(bak\|obj\)" | xargs svn --force del
    $ svn ci

    Although laborious I prefer the latter approach because I'm not a big fan of svn import (the svn del part is not common for me and I like to review the file list before committing).

    Otherwise, if what you want is to set the svn:ignore property of every directory in the hierarchy before importing you must use the second method and do a svn propset (instead of svn del) before comitting:

    $ svn propset -R -F ignore.txt svn:ignore .

    (You may actually do a svn import followed by a svn propset, but not in a single commit.)

  • You can't do that with a regular import; you need an in-place import.

Is there a CEIL version of MySQL's DIV operator?

With MySQL

a DIV b

is much faster than

FLOOR(a / b).

But I need to round up so I'm using,

CEIL(a / b)

It seems strange that there wouldn't be a ceiling version of DIV, but I can't find it. Is there anything undocumented hidden away somewhere? Or any other non floating point way to do this?

From stackoverflow
  • For a > 0 you can write

    (a - 1) div b + 1
    finnw : Be careful - what happens if a is 0?
    Gleb : Thanks, actually (a + b - 1) DIV b would be better I guess.
  • Alternative:

    (a + b - 1) DIV b

"select abc from (select 1) as abc" produces "(1)" instead of "1"

In Postgre, why does

select abc from (select 1) as abc




select * from (select 1) as abc



That's really strange to me. Is that the case with MySQL, Oracle, etc? I spent hours figuring out why my conditions were failing...

From stackoverflow
  • What does

    select foo from ( select 1 foo ) as abc


    presario : did you mean? select foo from ( select 1 as foo ) as abc i guess so, anyway i got it, thanks
  • The rows returned by your queries have different type: the first one is ROW(INT), while the second one is INT.

    MySQL and others lack this feature.

    In your first query, you are selecting a whole ROW as a single column. This query

    SELECT abc FROM (SELECT 1, 2) abc

    will produce (1, 2), which is a single column too and has type ROW.

    To select the INT value, use:

    SELECT  abc.col
    FROM    (
            SELECT  1 AS col
            ) abc
    presario : aha! so that's a feature, not a bug! thanks! got it now

Pygame: Sprite animation Theory - Need Feedback

After some tweaking of some code I got from someone to cause a characters images to move in regards to its direction and up down left right input I've put this together: (hope the code isn't too messy)

Character Move Code + IMG

The Sprite sheet only runs lengthwise, so basically each sprite section is a different action. Now would there be a way I could make a code that functions with the current one to cycle down from a set 'action' in order to make an animation?

For example: 'Run Left' is sprite 3. So then after we designate that column would it be possible to loop down how ever many frames of the run animation (lets say 4) in order to make an animation?

Example Picture:

From stackoverflow
  • It should be easy.

    If you record the frame number in a variable, you can modulo this with the number of frames you have to get an animation frame number to display.

    frame_count = 0
    animation_frames = 4
    while quit == False:
        # ...
        # snip
        # ...
        area = pygame.Rect(
            image_number * 100,
            (frame_count % animation_frames) * 150,
        display.blit(sprite, sprite_pos, area)
        frame_count += 1

    If different actions have different numbers of frames, you'll have to update animation_frames when you update image_number.

    Also, this assumes that it's ok to play the animation starting at any frame. If this is not the case, you'll need to record what the frame count was when the action started, and take this away from frame count before the modulo:

        area = pygame.Rect(
            image_number * 100,
            ((frame_count - action_start_frame) % animation_frames) * 150,

    A note about your event handling. If you hold down, say, left, and tap right but keep holding down left, the sprite stops moving because the last event you processed was a keyup event, despite the fact that I'm still holding left.

    If this is not what you want, you can get around it by either keeping a record of the up/down states of the keys you are interested in, or by using the pygame.key.get_pressed interface.

    On another note, you appear to be aiming for a fixed frame rate, and at the same time determining how far to move your sprite based on the time taken in the last frame. In my opinion, this probably isn't ideal.

    2D action games generally need to work in a predictable manner. If some CPU heavy process starts in the background on your computer and causes your game to no longer be able to churn out 60 frames a second, it's probably preferable for it to slow down, rather then have your objects start skipping huge distances between frames. Imagine if this happened in a 2D action game like Metal Slug where you're having to jump around avoiding bullets?

    This also makes any physics calculations much simpler. You'll have to make a judgement call based on what type of game it is.

    RamonLion : thanks very much for your input. I agree with everything you've said about the performance and whatnot. I'm learning all these thing from references of free codes and advice given to me. Is there anything you could direct me to, to learn the things that would function much better for what I need?
    SpoonMeiser : Unfortunately, I've not found any really good tutorials. I'd suggest read any that seem appropriate, but keep in mind that just because people have published their work on the Internet, they're not necessarily experts. The main thing is just to get something working, you can clean it up later.
    RamonLion : so very true. so what would I have to change to take out the old and add in the pygame.key.get_pressed. also how do I set the framerate to be variable?
    SpoonMeiser : Do you want variable framerate or fixed framerate? I'd suggest fixed is probably better in most 2D games. Instead of finding out how long the last frame took to render, ignore the return value of Clock.ticks and assume each frame takes the same time.
    RamonLion : my plans for my project is to make a megaman X style side scroller/platformer. a fixed framerate is probably fine seeing as there won't be millions of things on the screen. and how would I go along ignoring the ticks? but setting the framerate?
    SpoonMeiser : You're already setting a framerate of 60 frames a second by passing the value 60 to Clock.ticks.
    RamonLion : oh so I don't need to change anything.
    SpoonMeiser : When you update the position of the sprite, don't do it depending on the time the last frame took, assume it took 1/60 of a second.
    RamonLion : so would that mean I'd take off: time_passed = clock.tick(60) time_passed_seconds = time_passed / 1000.0 sprite_pos += key_direction * sprite_speed * time_passed_seconds the time passed seconds?

WorkflowMarkupSerializer doesn't keep positions in a state machine workflow

I am using WorkflowMarkupSerializer to save a statemachine workflow - it saves the states OK, but does not keep their positions. The code to write the workflow is here:

        using (XmlWriter xmlWriter = XmlWriter.Create(fileName))
            WorkflowMarkupSerializer markupSerializer
                = new WorkflowMarkupSerializer();
            markupSerializer.Serialize(xmlWriter, workflow);

The code to read the workflow is:

            DesignerSerializationManager dsm
            = new DesignerSerializationManager();
        using (dsm.CreateSession())
            using (XmlReader xmlReader
                = XmlReader.Create(fileName))
                //deserialize the workflow from the XmlReader
                WorkflowMarkupSerializer markupSerializer
                    = new WorkflowMarkupSerializer();
                workflow = markupSerializer.Deserialize(
                    dsm, xmlReader) as Activity;

                if (dsm.Errors.Count > 0)
                    WorkflowMarkupSerializationException error
                        = dsm.Errors[0]
                          as WorkflowMarkupSerializationException;
                    throw error;
From stackoverflow
  • Hah, even the stupid workflow designer hosted in Visual Studio 2008 loses the positions of states randomly. This tells me it's probably not an easy task, and is information external to the Activities that comprise it. I'd dig more around the host for information; if I find something, I'll post back.

  • The position of all the states is kept in a separate file. You'll need to drag it around with the markup of the workflow itself. Luckily, it's just XML as well, so you might be able to reuse most of the code you have up there. If memory serves, I believe it's simply NameOfYourWorkflow.layout.

    I agree with x0n - the designer is really bad in Visual Studio.

  • OK, this tutorial gives good information on how to do it - although so far I am only able to save the layout, I haven't been able to correctly use the layout. The information in question is about 2/3rds down (or just do a search for .layout)

    (How does one close his own question?)

  • Note that there is a bug in either the serialize or deserialize of the XML created (named in the example with an extension of .layout.)

    It produces the following xml as the first line of the file:

    <?xml version="1.0" encoding="utf-8"?><StateMachineWorkflowDesigner xmlns:ns0="clr-namespace:System.Drawing;Assembly=System.Drawing, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Name="New" Location="30, 30" Size="519, 587" AutoSizeMargin="16, 24" xmlns="">

    When reading this back in, the size attribute causes an exception. I removed Size="519, 587" from the file and the workflow is loaded back correctly. Right now, I write the file, open it and remove the size, then close it. I need to think about a more elegant solution, but at least I am now saving and restoring a state machine workflow.

  • I have experienced that too on my workflow designer. I have a lot of state machine workflow on my project and sometimes it shows incorrectly. I have found the cause. The workflow designer does not show state machine workflow correctly because of the change of character from "," to ";" in ".layout" file.


    Incorrect: Name="C211Workflow" Location="30; 30" Size="2162; 2954" AutoSizeMargin="16; 24"

    Correct: Name="C211Workflow" Location="30, 30" Size="2162, 2954" AutoSizeMargin="16, 24"

    Incorrect: <StateDesigner Name="stateKelengkapanBerkasFormD5" Location="1834; 2453" Size="222; 80" AutoSizeMargin="16; 24">

    Correct: <StateDesigner Name="stateKelengkapanBerkasFormD5" Location="1834, 2453" Size="222, 80" AutoSizeMargin="16, 24">

    So, my temporary solution is to open the .layout file in text editor and replace the ";" with "," in Location, Size, and AutoSizeMargin attributes.

    Does anyone have more practical solution?


    Rizky Januar Akbar

  • Nice answer !!! i think it can solve my problem ...

  • Open Control Panel -> "Regional and language options" and set list separator to ',' (comma) and workflow serializer will use ',' (comma) as separator for X,Y coordinates for struct SizeF

    then select ';' and workflow serializer will use ';' (semicolon) as separator.

    This really stupid that serializer use regional setting for serialize markup.

C++ polymorphism not supported for pointer-to-pointer

I'm searching for a proper way to clean my pointers. Here the example code:

class Parent {
      int m_Var;
      Parent() : m_Var(0) {}
      virtual ~Parent() {}
      void PubFunc();

class Child : public Parent {
      bool m_Bool;
      Child() : m_Bool(false) {}
      virtual ~Child() {}
      void ChildFunc();

void RemoveObj(Parent **ppObj)
   delete *ppObj;
   ppObj = NULL;

int main()
   Parent* pPObj = NULL;
   Child*  pCObj = NULL;
   pPObj = new Parent();
   pCObj = new Child();

   RemoveObj(&pCObj); // This is line 33
   return 1;

But the compiler gives error:

classes.cpp:33: error: invalid conversion from ‘Child**’ to ‘Parent**’
classes.cpp:33: error:   initializing argument 1 of ‘void RemoveObj(Parent**)’
From stackoverflow
  • There are soo many ways to handle memory correctly.

    The one close to your example would be:

    template <typename T>
    RemoveObj(T **p)
        if (p == NULL) return;
        delete *p;
        *p = NULL;

    Additionally you might want to use std::auto_ptr instead. It would look like:

    int main()
       std::auto_ptr<Parent*> pPObj(new Parent);
       std::auto_ptr<Child*> pCObj(new Child);
       // no deletes needed anymore
    To1ne : About the first solution: What's the improvement comparing to: void RemoveObj(void **ppObj)
    Windows programmer : The first suggestion compiles and works. void RemoveObj(void **ppObj) can be defined but if you try calling it your call shouldn7t compile.
    Pontus Gagge : @To1ne: I think deleting void * is actually undefined. With the template solution, you have a correct static type. What nontrivial destructor should be called for a void *?
    : deleting 'void*' is undefined
    To1ne : I think a dynamic_cast or reinterpret_cast would not be bad either? only really needed when I want to call *p->PubFunc();
    Rob K : BTW The test for p == NULL is unnecessary. delete on a null pointer is required to do nothing.
    : The test is not done on the pointer which is deleted, but on the one which points to the pointer to be deleted. *p if p is NULL must be tested.
  • You can find some useful information from the book < C++ common knowledge> Item 8. Pointers to Pointers.

  • You don't need a wrapper for delete, keep it simple:

    int main()
      Parent* pPObj = NULL;
      Child*  pCObj = NULL;
      pPObj = new Parent();
      pCObj = new Child();
      delete pPObj;
      delete pCObj; // This is line 33
      return 1;

    And remember you will run into issues deleting array type objects with your RemoveObj (since you are always using a scalar delete). An alternative is of course to pass a flag around to indicate you want delete []. But as I said: KISS.

    To1ne : Maybe my example was too simple... I wanted to call PubFunc() in that function too...
  • To put it simple :

    Child is a subclass of Parent so that means that Child* can be substituted with Parent*


    Child* is NOT a subclass of Parent* so that means that Child** can't be substituted with Parent**

    "Child" and "Child*" are not the same types.

  • If your problem is dealing with memory and resources, the best advice would be to forget your approach completely and use smart pointers. std::auto_ptr or boost::shared_ptr would be a start point.

    If you hold all your heap allocated resources with smart pointers your code will be more robust.

  • What you need to do is nullify all the pointers to the object you just deleted. The idea of pointers is that there will be more than one pointer storing the address of the same object. If not, there is little reason to use a bare pointer, and so the pattern you're trying to capture is not very useful - but you are far from the first person to try this. As other answers have mentioned, the only way to deal with pointers is to carefully control access to them.

    The title of your question is absolutely correct! There's a good reason for it. A pointer identifies a location that stores an object of a specific type. A pointer to a pointer gives you the ability to change what object a pointer points to.

    void Foo(Parent **pp)
        *pp = new OtherChild();

    Your Child class derives from Parent, and so does my OtherChild class. Suppose the compiler allowed you to do this:

    Child *c = 0;

    You expected that to work, but if it had, then we would now have a Child pointer c that in fact pointers to an instance of OtherChild. Who says those two types are compatible?

    Again, this is a very frequent misunderstanding - it crops up repeatedly here for other languages, especially with regard to List<Parent> and List<Child> in C#.

    To1ne : Thx a lot, great explanation!!
    Daniel Earwicker : No problem! And remember - nothing says "thank you" like an up-vote.
  • Probably the most simple solution I have found:

    #define __REMOVE_OBJ(pObj) RemoveObj(pObj); pObj = NULL;

    And just call this one:


    But I don't really like it myself...

  • From discussion on make shared_ptr not use delete

    Shared pointer will ensure you cleanup when you should and that you don't access something that is destroyed. Further you can specialise and provide an alternate destruction method.

    boost::shared_ptr<T> ptr( new T, std::mem_fun_ref(&T::deleteMe) );

Should I use DataInputStream or BufferedInputStream

I want to read each line from a text file and store them in an ArrayList (each line being one entry in the ArrayList).

So far I understand that a BufferedInputStream writes to the buffer and only does another read once the buffer is empty which minimises or at least reduces the amount of operating system operations.

Am I correct - do I make sense?

If the above is the case in what situations would anyone want to use DataInputStream. And finally which of the two should I be using and why - or does it not matter.

From stackoverflow
  • Use a normal InputStream (e.g. FileInputStream) wrapped in an InputStreamReader and then wrapped in a BufferedReader - then call readLine on the BufferedReader.

    DataInputStream is good for reading primitives, length-prefixed strings etc.

  • I would advocate using Jakarta Commons IO and the readlines() method (of whatever variety).

    It'll look after buffering/closing etc. and give you back a list of text lines. I'll happily roll my own input stream wrapping with buffering etc., but nine times out of ten the Commons IO stuff works fine and is sufficient/more concise/less error prone etc.

  • The two classes are not mutually exclusive - you can use both of them if your needs suit.

    As you picked up, BufferedInputStream is about reading in blocks of data rather than a single byte at a time. It also provides the convenience method of readLine(). However, it's also used for peeking at data further in the stream then rolling back to a previous part of the stream if required (see the mark() and reset() methods).

    DataInputStream/DataOutputStream provides convenience methods for reading/writing certain data types. For example, it has a method to write/read a UTF String. If you were to do this yourself, you'd have to decide on how to determine the end of the String (i.e. with a terminator byte or by specifying the length of the string).

    This is different from BufferedInputStream's readLine() which, as the method sounds like, only returns a single line. writeUTF()/readUTF() deal with Strings - that string can have as many lines it it as it wants.

    BufferedInputStream is suitable for most text processing purposes. If you're doing something special like trying to serialize the fields of a class to a file, you'd want to use DataInput/OutputStream as it offers greater control of the data at a binary level.

    Hope that helps.

    Martin OConnor : You are confusing a BufferedInputStream with a BufferedReader. InputStreams have no concept of a line so do not have readLine()
    Mike : Whoops - yes you are right!

How to disable primary key constraint programmatically?

I have a table with primary key in my MS SQL Server 2005 table. I would like to disable it. Now i get error:

Violation of PRIMARY KEY constraint 'PK_Name'. Cannot insert duplicate key in object 'dbo.Table'.

I would like this error not to occur and to work with PRIMARY KEY like with normal column without constraint and than restore this constraint after doing my changes to it. How to disable this constraint?

Query I want to execute while PRIMARY KEY constraint is disable is complex and changes values in primary key column. In some points of this query it hits the situation when I have duplicate values in primary key column. But at the end of my query I have all values unique.

I do not know much about this constraint because i'm not a designer of this table. I have it's name, but I don't now if it's clustered and so on (what is config of this column).

From stackoverflow

    To reenable it:


    Uncomment CLUSTERED if you want your PRIMARY KEY to be clustered (i. e. the table rows themselves are being ordered)

    To figure out if the PRIMARY KEY is clustered on not, issue:

    EXEC sp_help 'mytable'

    and look in the 6th resultset returned.

    tomaszs : This seems to delete constraint. How to restore it?
    tomaszs : The problem is that I do not know if I have a primary key CLUSTERED or not. So I can not restore it in this way.
    marc_s : The primary key is clustered by default - so if you didn't change it, it's clustered.
    tomaszs : I can't guess it because I didn't designed this table.
    tomaszs : Ok, but how to do it programmatically?
    Quassnoi : Call the procedure, take the resultset, parse the result
    tomaszs : It looks like to be a messy solution for me.
    Quassnoi : And it sure is. Instead of doing it programmatically, you can figure out what the primary key is using Management Studio, it's a one time task.
    tomaszs : No, it's not one time task bacause I will issue this command from my application for many tables. So I would like to do it fully programmatically. If it would be one time task I would be doing it in Management Studio, but it is not.
    Quassnoi : Figuring out whether the PRIMARY KEY is CLUSTERED on not is a one time task. Then you can drop and create the PRIMARY KEY programmatically.
    Quassnoi : And sure, dropping and creating the PRIMARY KEY is messy. You could possibly rewrite you query so that is does not violate the PRIMARY KEY, but since you didn't ask for it, here is the solution you asked for.
  • You can only DROP, not disable a primary key or unique contraint. Then you'll have to add it again later.

    You can disable foreign key and check constraints though.

       ADD CONSTRAINT UQ_foo_column UNIQUE (col1, ...)


    Based on your edit, you'll have to drop and recreate.

    Edit again: sp_pkeys

    tomaszs : This is not a solution that suits my needs, because I don't know what is the configuration of my primary key. I only have it's name. So If I will drop it, I can not restore it later by adding it.
  • Relational tables without primary keys are a very bad thing. Each row has to be unique in some way. If none of the candidate keys are designated as primary, the whole row has to be unique.

    I'm not sure why you have to drop a primary key constraint, but I would consider doing that without replacing it with one of the other candidate keys is a red flag that should be investigated.

    tomaszs : You've pointed out why this solution is bad, so I decided to mark your answer as proper one. And further more I've asked another question about the solution that will do this job in right way I think:
  • Do not violate PKEY constraint. IMHO it's the best solution, you will avoid cost of rebuilding a PKEY and what if you can't (duplicate remaining) ?


    Read the schema to know how to rebuild the PKEY constraint then use previouly posted solution.

    tomaszs : Rebuilding PKEY is not a cost for me, so I would like to go in this direction.
  • It may be a better idea to SELECT your entire table into a temporary table, doing the transformation on the fly if possible, and then copying it back. And if you can't transform on the fly, it's a lot easier to add a simple integer row index as the primary key on the temporary table.

  • To find out what the primary key is (assuming your table is dbo.T1):

    select as name,  
    (case  when (si.status & 16) > 0 then 1 else 0 end) as isclust,
    si.keycnt as keycnt,
    si.indid as indid
    from sysindexes si
    left join sysobjects so on = 
    where  si.indid > 0 
    and  si.indid < 255 
    and so.xtype <> 'S'
    and = OBJECT_ID('dbo.T1')
    and (si.status & 2048) > 0

    This will give you something like:

    name                                   isclust     keycnt indid
    PK_T1                                      1           2      1

    Here you have your primary key name (PK_T1), whether it's clustered or not, number of fields in it (2) and index id (you'll need it later).

    Next run the following:

    select INDEX_COL('dbo.T1', 1, 1) --returns Field1
    select INDEX_COL('dbo.T1', 1, 2) --returns Field2

    This will give you the names of two fields from the index. First parameter is your table name, second is index id obtained earlier and the third one loops from 1 to keycnt (returned on the previous step).

    Having this information you should be able to reconstruct the primary key as follows:


    Update: This might not be as accurate as parsing sp_help result mentioned earlier (you will miss the sort order and filegroup), but easier programmatically.

Upload large amounts of data to production sql server with minimal contention

I am running a web site that helps manage lots of information for medical clinics. Part of the application needs to upload patient files from an excel spreadsheet. The patient table has about 1 million records and an excel import needs to insert or update 10k,20k,30k patient records at a time. All the while other customers are pounding the table. Processing time is less important than reducing contention on the database. What strategies would you recommend?

I know other sites effectively do this. Salesforce allows you to upload large amounts of data at once.

From stackoverflow
  • If each row update is independent, run a loop that gets a row, updates the table, get another row, ...

    Then you can put a delay in the loop to slow it down to avoid impacting the main site (some sort of load metric could be used to adjust this on the fly). Some sort of token ring like setup could be used to make several update throttle together.

  • Load the Excel sheet to a staging table first, then decide whether to update/insert the rows in a single batch or what.

    Typically, inserting a million rows from one table to another should be quick enough to run while the server is under load. You will have a lock during the insert, but it should be a matter of seconds. Unless you are loading billions of records a minute, or your upsert operation is very intensive, I don't see it being a problem.

    If your upsert is very complex, there are a number of ways to do it. You can insert in a single batch, but mark the production records as incomplete as their subordinate records are updated. You can mark the staging rows as unprocessed and process in batches.

    Brent Ozar : If I could award multiple upvotes to this I would. MonkeyBrother, this is the one you want to focus on.

Can you run glassfish with JRockit?

Has anyone tried running glassfish with JRockit? I see some references saying it's not possible but they are very outdated. Anyone tried this?

From stackoverflow
  • AFAIK there was a problem on windows: Linux and Solaris seems ok.

  • It is possible in Windows. We do this for several production, public facing, web apps.

    We had to remove some default Glassfish JVM flags, since they don't apply to JRockit (this is optional, it's just that the start up warnings really annoyed me), and tune the JVM a little differently, but other than that we have not run into any issues.

    (We use SJSAS though, but I don't think that should make a difference)

    Here are the versions of the software we are using:

    • Windows Server 2003
    • Sun Java System Application Server 9.1_01
    • JRockit R27.5.0 (Java 6)
  • The recently released GlassFish 3.0.1 states on

    Update JDK support:

    HotSpot JDK testing/compliance updated to HotSpot JDK 1.6.0_20

    Added Oracle JRockit 6 Update 17 R28.0.0+ support

Using "Microsoft Chart Controls for .NET 3.5" for WinForms, how can I mark certain dates with a grid mark and label?

I'm using the Microsoft Chart Controls, and displays data with dates along the X axis and want to have a grid line with a different color on some dates.

Let's say I display data for one week with 7 values along the X-axis:

05.04.09 06.04.09 07.04.09 08.04.09 09.04.09 10.04.09 11.04.09

In addition I have a collection of DateTimes and names for some events, where one is on 07.04.09 and another is on 10.04.09. I then want to have a vertical grid line drawn on each of these dates and a label added with the event name.

I just can't figure out how the heck I can achieve this. Any help appreciated.

From stackoverflow
  • As far as I know you cannot change the color of specific lines in the chart grid. A tentative solution might be to add a new chart series of type Column; the series values are non-zero in the dates you want to highlight. It's a workaround, but it might be a starting point. As for the label, I have no idea.

  • So far I've managed to get it implemented by using CustomLabels on the secondary X axis, and have the tick marks on that axis drawn with the color I want. The main issue now is to get both X axes synchronized so that the CustomLabels ends up where I want them as they currently ends up a bit scattered around.

  • I solved this by subscribing to the PostPaint event. In the event handler I simply draw the lines myself and add the labels on top of these vertical lines.

  • chartName.Series["seriesName"].Points[index]["Color"] = System.Drawing.Color.Blue;

How possible to show external links in Django Admin Interface ?

I need to generate external links in admin interface grid column, but they shows as html code:

<a href="">site</a>

Admin interface translates my links as html-entities and they doesn't shows as right links. Is it possible to show external links there, not html code?

I think list_display_links doesn't work for this purpose.

Thank you!

From stackoverflow

Using Borland C++ Code in VC++

Hi guys,

Is there a way to access Borland output in VC++, for method calls and other stuff?


From stackoverflow
  • Create a static library, then link it into VC++ project. Be careful with calling conventions.

  • My info may be (way) outdated, but what I had to before was to make sure that Borland output a COFF format OBJ or LIB file to link with VC.

    The other option is to have Borland output a DLL, and then use that from VC++. Name mangling and calling conventions may cause a pain. I honestly haven't used a Borland compiler in half a decade(even though I used to work there, a decade and half ago), so I'm not sure if a LIB for a Borland compiled DLL will link nicely with VC++.

    If all else fails, compile a DLL with the Borland compiler, use Dumpbin to find the exports, then LoadLibrary and GetProcAddress to get the function pointers.

Struts2 Tiles - how to implement ?

I am just experimenting with struts2 tiles. I don't know how to implement it. Can anyone give any link for simple example of using strus2 tiles ? What is the basic requirement for that ?

From stackoverflow

Are there open-source "rate my X" website tools?

Not as in "hot or not" type sites, but consumer/community sites like "rate my college professor" or "rate my plumber" etc., sites where people can comment and rank things.

I was just wondering if there's some kind of PHP/MySQL package which has some basics already done.

It's hard to know what to search for.

Oh and by the way, yes, I know to get legal advice about setting up a site like this.

From stackoverflow
  • Take a look at Drupal - - and in particular the voting modules.

    AmbroseChapel : Thanks. I hadn't thought of that.

FTP and EC2

I've got my EC2 instance up and running and installed vsftpd with yum install vsftpd. Now I've started the service.

But unfortunately it seems like the guides end at this point.

How do I actually use my ftp client to log into the ftp server?

What do I input server url, username, password, and all that?

Thanks in advance.

From stackoverflow
  • You just need the same credentials you use to log into a command line on the EC2 instance - the host name or IP address, plus the username (usually root) and the SSH keypair that you used when you created the instance.

    Then you'll be able to connect with any client that supports SFTP (e.g. CyberDuck on Mac, WinSCP on Windows)

    gareth_bowles : Yes, the host name is the public DNS name from ElasticFox. The SSH key you need is the file that ElasticFox asks for when you click the "Connect to Instance" button.

Replace html entities with the corresponding utf-8 characters in Python 2.6

I have a html text like this:

&lt;xml ... &gt;

and I want to convert it to something readable:

<xml ...>

Any easy (and fast) way to do it in Python?

From stackoverflow

    >>> import HTMLParser
    >>> pars = HTMLParser.HTMLParser()
    >>> pars.unescape('&copy; &euro;')
    u'\xa9 \u20ac'
    >>> print _
    © €
    webjunkie : -1 because: "Deprecated since version 2.6"
    vartec : webjunkie: corrected the link.
    Alexandru : unescape is just an internal function of HTMLParser (and it's not documented in your link). however I could use the implementation. 10x a lot
    vartec : @brtzsnr: true, that it's undocumented. Don't think that it's internal though, after all name is unescape not _unescape or __unescape.
  • There is a function here that does it, as linked from the post Fred pointed out. Copied here to make things easier.

    Credit to Fred Larson for linking to the other question on SO. Credit to dF for posting the link.

VB - Insert A Blank Row

This is child's play for all of you, but I don't know Visual Basic at all. How do I write a statement to insert a row between two rows in an Excel spreadsheet repeatedly? An example below:







From stackoverflow
  • Sub Insert_Blank_Rows()  
       ''//Select last row in worksheet.
       Do Until ActiveCell.Row = 1 
           ''//Insert blank row.
           ActiveCell.EntireRow.Insert shift:=xlDown 
            ''//Move up one row.
           ActiveCell.Offset(-1, 0).Select 
     End Sub

    VBA Express shows an example how to accomplish it

    Erin Karschnik : Thank you so much! It worked perfectly.

iPhone: Testing application on iphone through Windows

I have participated in the iPhone Developer Program. I can debug my application through Mac over the iPhone. For some reasons I need to be able to test the same application on another iPhone using Windows. Is there a way to achieve this? How do I deploy the application from Windows? Any pointers will be highly appreciated.

From stackoverflow
  • You can drag the provision profile and the app package into itunes and sync. This is how you can distribute your beta.

    Note that the phones will have to be registered(UDID) in the developer program portal.

    Clint Harris : See the following tutorials (great for non-technical testers/users, like clients) for instructions on how to get UDID and install ad-hoc: A) B)

Threading problem in WPF

Hi all,

I'm getting this Exception

System.InvalidOperationException was unhandled by user code Message="The calling thread cannot access this object because a different thread owns it."

whenever I run the following code

public partial class MainScreen : Window
        Timer trm;

        public MainScreen()

            trm = new Timer(1000);
            trm.AutoReset = true;
            trm.Elapsed += new ElapsedEventHandler(trm_Elapsed);

        void trm_Elapsed(object sender, ElapsedEventArgs e)
            lblTime.Content = System.DateTime.Now;

guys any solution... I badly wann come out of it :(

From stackoverflow
  • Any time you modify Windows controls you must do so on the UI thread (the one that created the controls).

    See this question for lots of details.

  • Use DispatcherTimer instead:

    public partial class MainScreen : Window{
    DispatcherTimer tmr;    
    public MainScreen() {
    tmr = new DispatcherTimer();
    tmr.Tick += new EventHandler(tmr_Tick);
    void tmr_Tick(object sender, EventArgs e) {
        lblTime.Content = System.DateTime.Now;
  • To be short, you should use Dispatcher.Invoke method to update UI elements.

JSF: Backing Beans with nested objects?

JSF 1.1, using a backing bean with a nested objects inside I can read all properties of the nested object.

For example assuming a backing bean named "foo" with a nested object "bar" can I set/write via h:form all the properties of

I mean something like this:

            h:inputText value="#{myBean.mySelectedReport.someProp}" /

and this in the backing bean:

        public SomeObject getMySelectedReport() {...}

but when I sent it to the correct backing bean it doesn't store the value of the someProp value

From stackoverflow
  • Nice, I can answer by myself as I solved by myself: if useful for others having the same problem the problem is the JSF 1.1 wildcard on "from-view-id", for example "/ajax/uiChannel*" match only pages without any query params into the "from url", only this one "/ajax/uiChannel.jsp?*" and "/ajax/uiChannel*?*" wildcard seems to work

What is the best way to support plugins with a Silverlight app?

I have a silverlight app that I want to support plugin development for. I'm thinking that the plugin developer would create a dll and my main silverlight app would have some sort of config file that you would list the dll and type of the plugin, and the main app would detect, download, and load the dll for the plugin.

Does this sound possible to do with silverlight?

What would be the best approach?

From stackoverflow
  • Sounds like a feasible to me. I'd probably create a set of interfaces for my plugins and provide those in some kind of development package for plugin developers. As for loading assemblies dynamically at runtime in Silverlight, check out this link:

    Silverlight - Dynamically Loading an Assembly

  • Think about storage too. I was thinking about this same curiosity. Perhaps IsoStore is a place where you can keep them. A user has a plugin for your app (that conforms to an interface) and you can have them locate it (OpenFileDialog) and load it into your app (save in IsoStore). It isn't a durable solution of course, but an interesting one.

  • Have a look at the Composite Application Library:

    This frameworks helps you to create a moduled Silverlight application. Using this frameworks you could add new modules with ease when you are familiar with the framework.

Can you have <param> type tags within a asp.NET WebUserControl?

I want to create a WebUserControl (not a custom control) in asp.NET (C#). I want to have <param> tags that can be put between the control's start/end tags when being used in an aspx page.


<abc:myWebUserControl id="myWUC" runat="server">
    <param name="pName1" value="pValue1">
    <param name="pName2" value="pValue2">
    <param name="pName3" value="pValue3">

Can this be done? and how do you do it, how do you read the param data?

Thanks a bunch for any help.

From stackoverflow

jQuery hover() not working with absolutely positioned elements and animation...

I have some html that looks like this:

<a href="#" class="move"><span class="text">add</span><span class="icon-arrow"></span></a>

And I have a jquery event registered on the anchor tag:

    function (event) {
        $(this).animate({right: '5px'}, 'fast');
    function (event) {
        $(this).animate({right: '0px'}, 'fast');

When I mouse over the anchor tag, it displays the span.text and moves the anchor 5px to the right.

Now, due to complications that I don't feel like getting into, I have to set position: relative; on the container and absolutely position the icon and the text so that the icon appears on the left and the text on the right.


When I mouse over the anchor tag, the icon moves right, and the mouse ends up over top of the text (which appears). Unfortunately, the 'out' function gets called if I move my mouse from the icon to the text and the animation starts looping like crazy. I don't understand what's causing the "out" event to fire, as the mouse is never leaving the anchor tag.


From stackoverflow
  • Instead of hover you can use the "mouseenter" and "mouseleave" events, which do not fire when child elements get in the way:

    $('a.move').bind('mouseenter', function (e) {
      $(this).animate({right: '5px'}, 'fast');
    .bind('mouseleave', function (e) {
      $(this).animate({right: '0px'}, 'fast');
    Erik van Brakel : Aaah, thanks. Solution to my problem at least ;-) +1!