Sunday, April 17, 2011

Dropdown box Index issue

I have one dropdownbox(ddlCountry) containing allcountries,If i select USA it will display grid displaying Tax information related to USA.If i edit information in grid and if we change country USA to UK in dropdown box in the ddlCountry(not the dropdownbox coming in the edit window of grid,,no problem for that) it displaying error like

Specified argument was out of the range of valid values. Parameter name: ItemHierarchicalIndex Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: ItemHierarchicalIndex

Source Error:

Line 86: } Line 87: Line 88: if( rgStateTax.EditItems.Count > 0 ) Line 89: { Line 90: foreach( GridDataItem item in rgStateTax.Items )

Source File: c:\Projects\ACS\sample.Acs.Administration\UserControls\TaxManager.ascx.cs Line: 88

Stack Trace:

[ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: ItemHierarchicalIndex] Telerik.WebControls.GridItemCollection.get_Item(String hierarchicalIndex) +323 Telerik.WebControls.GridDataItemCollection.get_Item(String hierarchicalIndex) +37 Telerik.WebControls.RadGrid.get_EditItems() +215 sample.Acs.Administration.TaxManager.rgStateTax_PreRender(Object sender, EventArgs e) in c:\Projects\ACS\sample.Acs.Administration\UserControls\TaxManager.ascx.cs:88 System.Web.UI.Control.OnPreRender(EventArgs e) +8682870 System.Web.UI.WebControls.BaseDataBoundControl.OnPreRender(EventArgs e) +31 Telerik.RadGridUtils.RadControl.OnPreRender(EventArgs e) +36 Telerik.RadGridUtils.RadAJAXControl.OnPreRender(EventArgs e) +37 Telerik.WebControls.RadGrid.OnPreRender(EventArgs e) +40 System.Web.UI.Control.PreRenderRecursiveInternal() +80 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842

this is the grid(rgstatetax) prerender event

protected void rgStateTax_PreRender( object sender, EventArgs e )
    {
        if( rgStateTax.MasterTableView.IsItemInserted )
        {
            foreach( GridItem item in rgStateTax.Items )
            {
                item.Visible = false;
            }
        }

        if( rgStateTax.EditItems.Count > 0 )
        {
            foreach( GridDataItem item in rgStateTax.Items )
            {
                if( item != rgStateTax.EditItems[0] )
                {
                    item.Visible = false;
                }
            }
        }

Code in UI

protected void ddlCountryTax_SelectedIndexChanged( object sender, EventArgs e ) { long locationId = ddlCountryTax.SelectedItem.Value.AsLong();

        ContentAdministrationServiceClient client = null;
        List<DCTaxRate> taxRate = null;
        try
        {
            client = new ContentAdministrationServiceClient();
            taxRate = client.GetTaxRatesByCountryIdAndLocationTypeName( locationId, "State" );
            client.Close();
        }
        catch( FaultException )
        {
            AbortClient(client);
            throw;
        }

        rgStateTax.DataSource = taxRate;
        rgStateTax.Rebind();

    }

Code in wrapper layer

public List GetTaxRatesByCountryIdAndLocationTypeName( long countryId, string locationTypeName ) { DCTaxRateCollection taxRates = new DCTaxRateCollection(); taxRates.GetByCountryIdAndLoactionTypeName( countryId, locationTypeName );

        return taxRates.ToList();
    }

    public void GetByCountryIdAndLoactionTypeName( long countryId, string locationTypeName )
    {
        IBOTaxRateCollection iboTaxRates = new BOTaxRateCollection();
        iboTaxRates.GetByCountryIdAndLocationTypeName( countryId, locationTypeName );

        SetItems( iboTaxRates );
    }

In Bo layer

    public void GetByCountryIdAndLocationTypeName( long countryId, string locationTypeName )
    {
        ISingleResult<TaxRate> taxRates = Database.TaxRateReadByCountryIdAndLocationTypeName( countryId, locationTypeName );
        PopulateCollection( taxRates );
    }
From stackoverflow
  • This occurs when the list of values in the dropdown does not include the value being bound to the SelectedValue property. If this is because you have a null value you could get the data adapter to return an empty string when the field is null (if that is the problem) and then insert a value in the dropdown list to match:

    <asp:DropDownList ID="dd_bound" runat="server" AppendDataBoundItems="True">
        <asp:ListItem Value="" Text="Select one..." />
    </asp:DropDownList>
    

    Note the AppendDataBoundItems value.

    peter : i made appenddatabounditems to true still the same error coming
    Richard : do you know what the value being bound to is? is it null or another value which is not in the list?
    peter : reading the country collection/ list beyond its bound into the dropdown.Thats wat hapened here ..Any way thanks 4 the replay
  • This link will give some what related to this issue

    http://www.telerik.com/community/forums/aspnet/grid/specified-argument-was-out-of-the-range-of-valid-values-parameter-name-itemhierarchicalindex.aspx

Search in SVN repository for a file name

Issue:- Search in SVN epository for with file name.

The Problem is:- We have a bulk repository for code contain thousands of folder and sub folder, i want to search under this repositor with file name or with some word.

Exp:-

Root folder a\ b\ c\ d\ e\ f\ab\ f\ab\cd.txt

I want to search for cd.txt but dont know where it is in SVN Repository, for that i want to perform a search on the root folder of SVN where i will put the file name cd.txt and run the command, will check in each folder and will display the file details result....

Hope requirement is clear. Can you please help me on this.

From stackoverflow
  • svn list --depth infinity <your-repo-here> to get a list of files in the repo, and then svn cat to get contents. You can add --xml key to list command to make parsing a bit simpler.

  • If the file is in your working copy, then if you are using svn 1.5:

    svn list --depth infinity | grep <filename>
    

    or an earlier version of svn:

    find . -name <filename> -not -path '*.svn*'
    

    If you need to find the file in history (deleted or moved):

    svn log -v | less
    

    and search for it with:

    \<filename><return>
    

Abuse of version control

Is version control suited for a project where content is essentially binary data files ? I am thinking about package that weight something like 10 giga, with a lot of BMP and TGA files.

Can subversion handle something like this ? Is it possible to generate some kind of binary patch that would allow users to download only what was modified. Rsync could be an option, but then there is no going back. I would really like to be able to go back to an earlier version easily.

I looked at this question too, but was not satisfied with the answer

From stackoverflow
  • Subversion only sends the differences over the line, not the entire files, when doing updates. However the initial checkout of the files DO require a download of all the files. Which will basically mean download 10GB. Also binary files are a nightmare to merge so as long as you work in a master / slave environment where only 1 person can commit and the others are slaves who only update the files this will work very well. Otherwise you're likely to end up with conflict after conflict.

    Is it not possible to split the 10GB over multiple repositories ? Do they really need to be versioned as a whole ?

  • You issue is a release management one which includes:

    • building: how and how fast are you able to regenerate some or all of the delivery content ?
    • packaging: how many files are present in that delivery ?
      if your content includes too many files, it will simply not be easy to deploy (i.e. copy or rsync) in any remote environment, not so much because of the global size, but because of the number of transactions needed.
    • publishing: where do you store your delivery and how to you link it to the initial development environment that produced it ?

    I would argue that such a massive delivery is not made to be published in a VCS, but rather store in a filesystem-based repository, with a proper name (or version.txt) to be able to identify its version and link it back to the development content (stored and tagged in subversion).
    Maven is an example of such a repo.

    I would also point out a content made to be delivered should include a limited number of files, which means:

    • compressed lots of related files together into one compressed file
    • run a script which does not just rsynch, but also un-compressed those files
  • Subversion uses xdelta for binary files.

    http://subversion.tigris.org/faq.html#binary-files

    BTW. related question: http://stackoverflow.com/questions/538643/how-good-is-subversion-at-storing-lots-of-binary-files

    leppie : I somehow doubt SVN uses xdelta for binary diff, as SVN would have to be GPL licensed then, and it is using an Apache/BSD style license.
    vartec : Xdelta 2.0 (that's when SVN started using it) was BSD licensed -- http://www.xcf.berkeley.edu/~jmacd/xdelta.html
    vartec : http://subversion.tigris.org/svn_1.2_releasenotes.html "The repository is now using the xdelta differencing algorithm (instead of vdelta)" http://subversion.tigris.org/svn_1.4_releasenotes.html "Subversion uses the xdelta algorithm to compute differences between strings of bytes."
  • You might want to look at some dedicated asset managing system, instead of trying to violently bend a source versioning system into your needs. The only one I've heard of (but have no experience nor affiliation with) is http://www.alienbrain.com/ - and it co$t$.

  • The short answer is yes.

    We used subversion for a relatively large (40GB checkout) game development project. I will say it handled binaries surprisingly well. The downside is for now you will only get text information for changes, ie: "Changed texture to fit updated main character model." But even this little bit of information can save you when you're looking for performance issues and simply making sure that every one is using the same binary files for development. Patching, as far as I know, would require the full file.

  • Well, but allienbrain is also version control, right?

    Tom : this should be a comment, not an answer.
    pablo : True, sorry, didn't realize

Windows Username maximim length

How long is the maximium lenght of a windows username incl. domain?

domain\username

regards

From stackoverflow

Adding a new dimension based on a key in fact table linked to one of the dimension tables

Hi, I have a fact table that holds all date & time attributes as keys which links to actual DATE & TIME dimension. When I create a cube on top of it using SSAS 2005, these datetime attributes are split into individual dimensions for the CUBE, which is OK.

Problem is when I add a new datetime attribute to the fact table, my cube doesn't accept that and would not create a new datetime dimension just like the other ones, unless I recreate the cube from scratch.

Can anyone please suggest, how can I add this new attribute separately as a dimension, without having to recreate the cube?

From stackoverflow
  • I'm struggling to understand your issue.

    It sounds as if you are trying to add a new datetime column(fact) (referenced to your apporpriate Dimension/s attribute) to the Fact table. If so, this changes the structure of the cube and so requires that the cube be re-processed.

    To qualify correct use of terminology, a Dimension contains Attributes. A Fact table contains Facts not attributes.

    The following reference may be of use.

    http://msdn.microsoft.com/en-us/library/aa905984(SQL.80).aspx

    Re: Comments

    Any structural changes need to be applied/registered within the Data Source View (DSV) in the Business Intelligence Development Studio (BIDS), prior to processing the cube. Clicking the refresh button on the DSV, should prompt you with an option to apply any discovered changes to your tables. Also, should any of your additions/modifications be to the underlying tables of Dimensions, then you may also need to add the attributes in question to the appoprirate Dimension .dim file, prior to re-processing the cube.

    Hope this makes sense.

    Vineet : Well I guess I got the terminology wrong but here is the actual problem. Add a new datetime column(fact), refreh data source view, this does not bring the appropriate dimension(inheriting datetime dimension attributes) in the cube by itself. I hope it makes sense this time. Any idea why?
    Vineet : Re processing the cube doesn't help as it is not taking up this new structural change to the cube. Even tried Process Structural Chages option while processing the cube.
  • The problem usually comes because of Unknown Member and Null Processing options setup along with the snowflake schema if you have it in your cube. I figured out what the problem actually was. If you have a case as one mentioned, then SSAS doesn't bring up the structural changes by itself when you refresh the Data source view. In my case, since it was date & time dimensions, I had to add new dimensions manually (Cube dimensions) and setting their NULL Processing options correctly (in my case UnknownMember and not Automatic).

    Since it can be tad difficult to do these changes for all such new columns added to underlying fact table, you can try updating the XMLA script using Find & Replace method, carefully crafted.

SQL Server - An error occurred while executing batch. Error message is: The directory name is invalid.

Our database server had run out of disk space, after freeing up some disk space any query run in sql server management studio, with the results sent to grid view, resulted in this error:
An error occurred while executing batch. Error message is: The directory name is invalid.

When the results sent to text view the queries worked fine.

Does anyone know why this error occurs and how to get rid of it?

From stackoverflow
  • I know it can sound like a joke, but have you tried restarting SQL Server instance?

  • Is the "Default Location for saving Query Results" set to a valid path in Tools/Options/Query Results/SQL Server/General?

    Do the TMP/TEMP environment variables point to valid directories?

    Reinstalling the client tools will probably fix the problem.

Software design vs. software architecture

Could someone explain the difference between software design and software architecture? More specifically; if you tell someone to present you the 'design' - what would you expect them to present? Same goes for 'architecture'.

My current understanding is:

design: UML diagram/flow chart/simple wireframes (for UI) for a specific module/part of the system

architecture: component diagram (showing how the different modules of the system communicates with each other and other systems), what language is to be used, patterns...?

Correct me if I'm wrong. I see Wikipedia has articles on http://en.wikipedia.org/wiki/Software_design and http://en.wikipedia.org/wiki/Software_architecture, but I'm not sure if I have understood them correctly.

From stackoverflow
  • Yep that sounds right to me. The design is what you're going to do, and architecture is the way in which the bits and pieces of the design will be joined together. It could be language agnostic, but would normally specify the technologies to be used ie LAMP v Windows, Web Service v RPC.

  • You're right yes. The architecture of a system is its 'skeleton'. It's the highest level of abstraction of a system. What kind of data storage is present, how do modules interact with eachother, what recovery systems are in place. Just like design patterns, there are architectural patterns: MVC, 3-tier layered design, etc.

    Software design is about designing the individual modules / components. What are the responsibilities, functions, of module x? Of class Y? What can it do, and what not? What design patterns can be used?

    So in short, Software architecture is more about the design of the entire system, while software design emphasizes on module / component / class level.

    Asaf R : Also, architecture usually deals with what (is done) and where (it's done), but never with how. That is think is the principle difference - design completes the how that architecture doesn't (and shouldn't) talk about.
  • Software architecture is best used at the system level, when you need to project business and functions identify by higher architecture levels into applications.

    For instance, your business is about "Profit and Loss" for traders, and your main functions involved "portfolio evaluation" and "risk computation".

    But when a Software Architect will details his solution, he will realize that:

    "portfolio evaluation" can not be just one application. It needs to be refined in manageable projects like:

    • GUI
    • Launcher
    • Dispatcher
    • ...

    (because the operations involved are so huge they need to be split between several computers, while still being monitored at all times through a common GUI)

    a Software design will examine the different applications, their technical relationship and their internal sub-components.
    It will produce the specifications needed for the last Architecture layer (the "Technical Architecture") to work on (in term of technical framework or transversal components), and for the project teams (more oriented on the implementation of the business functions) to begin their respective projects.

Associating an image with a post in WordPress

Hi,

What's the best way to associate an image with a post in WordPress?

What I mean by that is when each post has a 'header' image which is not in the body of the post. You'd most likely use it to show a small image next to each post when they're listed somewhere.

I know you can use custom fields with posts, but are there any better ways of doing it?

Thanks in advance.

From stackoverflow
  • Not really any better way than custom fields, although you could always write out a unique class name containing the post ID on the container div and add the images via CSS each time you add a post. You'd end with a potentially huge CSS file though so I'd go for custom fields myself.

  • If you go the custom field route - in your template code you can save the value of the custom field to a variable and then echo it out to your image.

    <?php $post_image = get_post_meta($post->ID, post_image, true); ?>
    <?php if( $post_image != "" && isset($post_image) ) : ?>
       <p><img src="<?php echo $post_image; ?>" alt="<?php echo $post_image; ?>" /></p>
    <?php endif; ?>
    <?php the_content('read more...'); ?>
    

    The function the_content() may or may not be what you will end up using - for more control, you can try setting a new WP_Query() and then revamping the loop.

  • If you want a different image per post then use Customs Fields as suggested before - the only problem with that will be that Custom Fields are text fields and so you will have to upload your image and then paste the filename into your Custom Field. You could use the normal Add Image facility in the main post entry form but that will break up your workflow a bit as you will have to: upload the image in main post form, copy image url from HTML of form, remove image from form, paste URL into a custom field.

    A bit of a pain!

    If you want to use an image per category. Say, for example, you have a thumbnail for news items and a thumbnail for tutorials and so on. You could edit your WP theme template, check the category inside The Loop and show the relevant image from there.

    The first option is a bit of a pain and the second requires some PHP coding.

  • A good way of associating an image with a post is to call the first image attached to that post in your template file.

    I've elaborated a bit in this thread:

    http://stackoverflow.com/questions/682926/how-would-you-recommend-adding-an-image-as-a-custom-field-in-wordpress

Importing in Python between three or more files not working

Hello,

I hav codes eg1.py , eg2.py , eg3.py eg3.py imports eg2.py which in turn imports eg1.py

When i run eg3.py for first time everything is fine If i import it again and again only eg3.py runs

I need a solution for this.

I will code eg3.py in such a way that :

while(1):
    import eg2.py

Where I went wrong.Please give me a solution.

From stackoverflow
  • Huh? You can't loop an import, they are cached so it doesn't really do anything except waste cycles, after the first iteration.

    How do you know that "only eg3.py" runs?

    : thank you....i wanna know in depth about importing.which document should i refer ?
  • Do you want to execute the code in eg2.py when you import it? That is not a good solution. You should have a function containing your code in eg2.py and then execute this function in your while loop.

    In eg2.py:

    def my_func():
        # do useful stuff
        pass
    

    In eg3.py

    import eg2
    while True:
        eg2.my_func()
    
  • If you import a module that is already imported, executable code in that module will not be re-run.

    E.g.:

    >>> import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    >>> import this
    >>>
    

    Deleting the module from sys.modules will force a complete reload:

    E.g.:

    >>> import sys
    >>> import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    >>> del(sys.modules["this"])
    >>> import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    >>>
    

    Edit: Also, what heikogerlach said: you're better off calling functions in the already imported modules than deleting/reloading them most of the time.

Are there any open source command line tools to refactor java code?

I use vim as my editor but I would like to get some of the same power of the IDE's for java when it comes to refactoring. Are there any commandline tools for refactoring java? I could probably hack something together using perl or vim scripting but if there is something already out there I'd rather use that.

From stackoverflow
  • Why not borrow from Eclipse source?

  • Check out jrefactory, and its command line option.

    stepancheg : It does almost nothing.
    Adeel Ansari : Yeah, not that sophisticated. I use IntelliJ and Netbeans, though.
  • Code refactoring is a very context-sensitive and interaction-heavy process which doesn't lend itself very well to command-line interfaces. There can be dozens of types of refactorings you could do to a particular file (or set of files) and coming up with a vim interface to integrate all of this would be a major challenge.

    If you want IDE functionality, why not use an IDE? Especially with Java, which lends itself so well to automatic refactoring by a complex piece of software like Eclipse.

  • I use sed sometimes.

    Adeel Ansari : sounds like work. :)
  • I would strongly advise you to use VIM within an IDE (e.g. VIMPlugin and Eclipse - this is the combination I use and it works very well).

    I used to be a VIM diehard. However the refactoring and code analysis within a modern IDE will far surpass any capabilities that VIM will provide (with plugins etc.).

    Don't get me wrong. I love VIM and still use it for all sorts of stuff. Modern IDEs are the most productive route forward, however.

    Jeremy Wall : I've tried those but the vim plugin doesn't give me any of the ide benefits. I might as well just use vim and the ide side by side.

Getting the Type of a ContextBoundObject when intercepting a method call

I'm intercepting method calls into a ContextBoundObject. Is there a way to get hold of the Type of the object I'm calling when in the message sink?

Say I've got a class

 [Intercept]
 [Synchronization]
 public class Test : ContextBoundObject
 {
    [Timeout(10010)]
    public void Method()
    {
        // Do something
    }
 }

In the message sink before the call is put through to Method is there someway to get hold of the Test type so I can query the custom attribute Timeout? eg

public IMessage SyncProcessMessage(IMessage msg)
{
      Type type = GetType(); // << Need to get hold of Test type here
      object[] custom = type.GetMethod("Method").GetCustomAttributes(false);;
      TimeoutAttribute ta = custom[0] as TimeoutAttribute;
      int time = ta.Ticks;

      IMessage returnedMessage = _nextSink.SyncProcessMessage(msg);
      return returnedMessage;
}

ta

From stackoverflow
  • After a little messing I found it.

    The type name is passed into SyncProcessMessage in the Properties dictionary in IMessage.

    So the code above becomes

    public IMessage SyncProcessMessage(IMessage msg)
    {
          Type type = Type.GetType(msg.Properties["__TypeName"].ToString());
    
          object[] custom = type.GetMethod("Method").GetCustomAttributes(false);
          TimeoutAttribute ta = custom[0] as TimeoutAttribute;
          int time = ta.Ticks;
    
          IMessage returnedMessage = _nextSink.SyncProcessMessage(msg);
          return returnedMessage;
    }
    

Why doesn't jQuery Append work for the end of HTML List Items?

I'm trying to clone a list item, and then append it to the bottom of that cloned list item, note that it should be below the list item being cloned, not at the bottom of the list as I can do that myself. The purpose is to use it with jQuery.ui sortable.

Everything is working fine, in fact I can even get the cloning and the appending right. However, it appends it before the closing </li> tag, and for the life of me I can't force it to append after this tag.

This is the HTML Markup:

<ul id="column-2" class="connectedSortable">
    <li class="ui-state-default">
     <div class="label">feature</div>
     <div class="action">
      <div class="delete"></div>
      <div class="other"></div>
     </div>
    </li>
</ul>

The part we're concerned with is class="other" which upon being clicked on will duplicate the list item.

This is the jQuery so far:

// This works fine
$(".other").click(function() {

    // This needs to be set (global) to be used later on in some future code.
    actionTarget = this;   

    // This grabs the whole list item
    var targetStory = $(actionTarget).parent().parent();

    // This clones the list item, as well as appending 
    // that clone to the cloned list item
    $(targetStory).clone().appendTo(targetStory);

})

This works well, it grabs the list item, clones it, then dumps it on the screen - but in the wrong place :(

<ul id="column-2" class="connectedSortable">
    <li class="ui-state-default">
     <div class="label">feature</div>
     <div class="action">
      <div class="delete"></div>
      <div class="other"></div>
     </div>
     <li class="ui-state-default">
         <div class="label">feature</div>
         <div class="action">
          <div class="delete"></div>
          <div class="other"></div>
         </div>
     </li>
    </li>
</ul>

Anyone have any idea why it's not appending to the end of the list item being cloned, and how to resolve this?

From stackoverflow
  • i think what you want is this:

    $(targetStory).clone().appendTo(targetStory.parent());
    
    jakeisonline : Almost, it's something Id' already tried. Instead, it adds it to the bottom of the list, rather than after the list item being cloned.
  • perhaps you want to use after instead of appendTo

    jakeisonline : Yep! This does the trick, thanks cobbal $(targetStory).after(targetStory.clone());
    SuperRoach : For reference: http://docs.jquery.com/Manipulation/appendTo States that the element you have , it will be inside it - just placed at the end of the content inside it. Hence the word, Appending. .After like you found is the way to go.
    jakeisonline : True, I missed the clarification of "inside it", too much skimming.
  • I think insertAfter is what you're looking for. after would insert the original node after the clone, rather than the clone after the original node. Something like this should work:

    $(targetStory).clone().inserAfter(targetStory);
    
    jakeisonline : Thanks Mishac, cobbal already managed to nab the answer! $(targetStory).after(targetStory.clone());

Can I transpose a file in vim?

I know I can use awk but I am on a windows box I am making a function for others that may not have awk. I also know I can write a C program but I would love not have to create maintain and compile something for a little vim utility I am making.

THe original file might be

THE DAY WAS LONG 
THE WAY WAS FAST

and it would become

TT
HH
EE

DW
AA
YY

WW
AA
SS

LF
OA
NS
GT

UPDATE: Golf rules apply to selecting correct answer.

UPDATE: Python fans should check out Mr. Duffy's answer below.

From stackoverflow
  • Vim support for a number of scripting languages built in -- see the Python interface as an example.

    Just modify vim.current.buffer appropriately and you're set.

    To be a little more specific:

    function! Rotate()
    python <<EOF
    import vim, itertools
    max_len = max((len(n) for n in vim.current.buffer))
    
    vim.current.buffer[:] = [
        ''.join(n) for n in itertools.izip(
         *( n + ' ' * (max_len - len(n))
            for n in vim.current.buffer))]
    EOF
    endfunction
    
    ojblass : Sweet Jesus look at all all that! So much text manipulation goodness!
    guns : ++ oooh - was unaware that vim supported more than vimscript! Also perl, tcl, and ruby -- awesome!
    Mykola Golubyev : It supports those scripts but not by default. You have to turn them on during build.
    Charles Duffy : Right. Just about every distribution has a vim-full or vim-enhanced version, and I tested what I posted here against the Windows gvim
    ojblass : Crazy Kudos I am going to wait to see if any golf answer like four key strokes and your done win out. I wonder what assumptions I should be allowed to make about the vim bulid itself to still be considered portable.
    George V. Reilly : You still have to have python2X.dll somewhere on your computer for this to work. Python itself is not embedded in Vim.
  • Here is a command in Vim language. So you don't have to compile Vim with +python support.

    function! s:transpose()
        let maxcol = 0
        let lines = getline(1, line('$'))
    
        for line in lines
            let len = len(line)
            if len > maxcol 
                let maxcol = len
            endif
        endfor
    
        let newlines = []
        for col in range(0, maxcol - 1)
            let newline = ''
            for line in lines
                let line_with_extra_spaces = printf('%-'.maxcol.'s', line)
                let newline .= line_with_extra_spaces[col]
            endfor
            call add(newlines, newline)
        endfor
    
        1,$"_d
        call setline(1, newlines)
    endfunction
    
    command! TransposeBuffer call s:transpose()
    

    Put this in newly created .vim file inside vim/plugin dir or put this to your [._]vimrc.
    Execute :TransposeBuffer to transpose current buffer

    ojblass : Pure vim gets you the nod. Thank you so much!
  • If scripts don't do it for you, you could record the actions to a register (the carriage returns are added for readability):

    qa
    1G0
    xGo<Esc>p
    1G0j
    xGp
    q
    

    This will give you a macro that you could run against the example above, or any 2-line strings of the same length. You only need to know the length of the string so you can iterate the operation the correct number of time

    16@a
    

    A fairly basic solution, but it works.

    ojblass : The input domain could be more than two lines with the same length.

Binding complex properties in Silverlight/WPF

Lets say I have a custom data type that looks something like this:

public class MyDataType
{
  public string SimpleProp1;
  public string SimpleProp2;
  public List<SomeType> ComplexProp;
}

now I hava a data bound control (i.e. ItemsControl or DataGrid), that is created dynamically. How would the binding defined in xaml code look like to acces a subproperty of the complex property? I thought it should look something like this:

<TextBox Text="{Binding simpleSubProp, path=ComplexProp[0]}" />

or

<TextBox Text="{Binding path=ComplexProp[0].simpleSubProp}" />

but both of those give me xml parse errors. How should it look correctly? Is it even possible to refer to a specific item of a collection property in souch a way? If it is not, what other options do I have?

EDIT, The scenario doesn't seem to be clear enough:

I have an

IEnumberable<MyDataType>

that is bound to an ItemsControl, inside the DataTemplate I have multiple TextBoxes that need to refer to subproperties of an object in the List of the complex property.

From stackoverflow
  • I'm not sure you can do that. Usually you will bind a list to something like a listbox (or another "repeating" control) and then each item inside that will be able to bind to the relevent element in the list.

    gsnerf : I may not have made that clear enough, I have an IEnumerable bound to an ItemsControl. Inside the DataTemplate of my ItemsControl I need to reference the subproperty of a specific item in the complex property.
  • Try {Binding ComplexProp(0).simpleSubProp}. If that doesn't work, you can write a simple Converter to do this too.

    gsnerf : Thx for your answer, unfortunately this gives me an System.ArgumentException "Invalid Binding Path; character". How would a converter for this look like? I thought converters would be normaly used for formating data in a specific way
  • According to the Path Syntax on MSDN, you can just do:

    <TextBox Text="{Binding ComplexProp[0].simpleSubProp}" />
    

    It may be the lowercase "path=" that gave you errors? Try "Path=". Also, not sure if this works in Silverlight...

    HTH, Kent

    mattmanser : That page is for WPF, not Silverlight. Silverlight doesn't support indexed properties in binding.
    Kent Boogaart : The title of the question says "Silverlight/WPF".
    gsnerf : The indexing method seems to only work for some cases in silverlight, thx nevertheless!
    JasonRShaver : Silverlight 3 supports indexed properties in binding.
  • Looks like poperty path indexers are broken in Silverlight Indexers in property paths are broken. The way to get around it is as suggested in the post and to use an IValueConverter.

    XAML

    <UserControl x:Class="Silverlight.Mine.Page"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:sys="System"
      xmlns:sm="clr-namespace:Silverlight.Mine;assembly=Silverlight.Mine"
      Width="400" Height="300">
        <UserControl.Resources> 
           <sm:SomeTypeConverter x:Key="MySomeTypeConverter" />
        </UserControl.Resources>    
        <Grid x:Name="LayoutRoot" Background="White">
            <TextBlock x:Name="myTextBlock" Text="{Binding Path=SomeDates, Converter={StaticResource MySomeTypeConverter}}" />
        </Grid>
    </UserControl>
    

    C# Page.xaml.cs

    namespace Silverlight.Mine
    {
        public partial class Page : UserControl
        {
            private SomeType m_mySomeType = new SomeType();
    
            public Page()
            {
                InitializeComponent();
                myTextBlock.DataContext = m_mySomeType;
            }
        }
    }
    

    C# SomeType.cs

    namespace Silverlight.Mine
    {
        public class SomeType
        {
            public List<DateTime> SomeDates { get; set; }
    
            public SomeType()
            {
                SomeDates = new List<DateTime>();
                SomeDates.Add(DateTime.Now.AddDays(-1));
                SomeDates.Add(DateTime.Now);
                SomeDates.Add(DateTime.Now.AddDays(1));
            }
        }
    
        public class SomeTypeConverter : IValueConverter
        {
            public object Convert(object value,
                           Type targetType,
                           object parameter,
                           CultureInfo culture)
            {
                if (value != null)
                {
                    List<DateTime> myList = (List<DateTime>)value;
                    return myList[0].ToString("dd MMM yyyy");
                }
                else
                {
                     return String.Empty;
                }
            }
    
            public object ConvertBack(object value,
                                  Type targetType,
                                  object parameter,
                                  CultureInfo culture)
            {
                if (value != null)
                {
                    return (List<DateTime>)value;
                }
                return null;
            }
        }
    }
    
    gsnerf : I will give that a try, thx!
  • I do this kind of thing all the time, there are two ways I would approach this problem depending on what you want out of it.

    If you really want only the one specific member of the list, you can use a converter. The XAML would look something like this:

    <TextBox Text="{Binding MyDataTypeInstance, Converter={StatacResources SpecificInstanceConverter}}" />
    

    That's not usually what I need though, usually I need one control to display the whole comlex object, if that's the case the way to do it is more like as follows:

    <StackPanel>
         <Textblock Text="{Binding SimpleProp1}"/>
         <TextBlock Text="{Bidning SimpleProp2}"/>
         <ItemsControl ItemsSource="{Binding ComplexProp}>
              <ItemsControl.ItemsTemplate>
                   <DataTemplate>
                        <StackPanel>
                             <TextBlock Text="{Binding ComplexPropertyName}/>
                             <InputToolkit:NumericUpDown Value="{Binding ComplexPropertyValue}/>
                        </StackPanel>
                   </DataTemplate>
              </ItemsControl.ItemsTemplate>
         </ItemsControl>
    </StackPanel>
    

    I like this method because my GUI matches my business objects, and as a result it usually ends up a lot cleaner than if I'm checking for specific indexes in code-behind.

  • To generalise this all the way, I suggest you use a value converter as mentioned by others, and use the ConverterParam option to pass an index.

Chaos with InterfaceBuilder

Hi Friends,

Please clear this scenario.

I created a viewController named RootViewController,so obiviously we'll get RootViewController.h and RootViewController.m

Then i created a nibfile named ViewScreen.xib by selecting a newFile named viewXib, so automatically we'll get a View in the xibfile.And i linked FilesOwner class to RootViewController.

so if i want to set the back ground color of the view as "groupTableViewBackgroundColor" ,can't i set that in attributes inspector,is the only way to set that color to view is by doing manually in RootViewController.m(declaring a view and setting view.backgroundColor=[UIColor groupTableViewBackgroundColor]; can't we do the same by using interfaceBuilder.

if any one is interested to solve this ,please go on.

From stackoverflow
  • If you change the colour palette to "Developer" you'll find the list of system colours, including the background colour for tables.

    IQpierce : I can't find any color palette named "Developer" in Interface Builder. Can you clarify where this can be set?
    IQpierce : Ah, I found this - it's on the "Color Palettes" tab of the Color Picker dialog (the middle of the five buttons at the top of that view). HOWEVER, I didn't find groupTableViewBackgroundColor there - rather it was under the "iPhone SDK" palette.
    Stephen Darlington : @IQpierce Yes, Apple keep moving it around and renaming it. In the current version (3.2.3) there's a drop-down next to the colour button; you don't have to click through to the colour picker itself.

HttpRuntime..cctor takes forever to execute

Dead simple code:

using System;
using System.Diagnostics;
using System.Web;
using System.Web.Caching;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = Stopwatch.StartNew();
            Cache cache = HttpRuntime.Cache;
            Console.WriteLine(sw.Elapsed.ToString());
            Console.ReadLine();
        }
    }
}

And I've already been waiting for output for over 5 minutes. This problem started to manifest itself about a week ago (may be less) and three more computers (my coworkers' boxes) experience the same behavior, except that some of them manage to initialize HttpRuntime in under a minute, which is still very weird.

Has anybody experienced that? And what do I do with it?

From stackoverflow

SWT/JFace: remove widgets

Group group = new Group(parent, SWT.NONE);
StyledText comment = new StyledText(group, SWT.BORDER_DASH);

This creates a group with a text area inside.

How can I later delete the text (remove it from the screen so that I can replace it with something else)?

From stackoverflow
  • You have to either call comment.changeParent(newParent) or comment.setVisible(false) to remove/hide it from the Group. I am unsure if comment.changeParent(null) would work but I would give that a try.

    We do it this way because SWT uses the Composite Pattern.

    Thilo : comment.changeParent(null) does indeed raise SWT.ERROR_NULL_ARGUMENT ...
  • Use Widget.dispose.

    public class DisposeDemo {
    
      private static void addControls(final Shell shell) {
        shell.setLayout(new GridLayout());
        Button button = new Button(shell, SWT.PUSH);
        button
            .setText("Click to remove all controls from shell");
        button.addSelectionListener(new SelectionListener() {
          @Override
          public void widgetDefaultSelected(SelectionEvent event) {
          }
    
          @Override
          public void widgetSelected(SelectionEvent event) {
            for (Control kid : shell.getChildren()) {
              kid.dispose();
            }
          }
        });
    
        for (int i = 0; i < 5; i++) {
          Label label = new Label(shell, SWT.NONE);
          label.setText("Hello, World!");
        }
    
        shell.pack();
      }
    
      public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        addControls(shell);
        shell.open();
        while (!shell.isDisposed()) {
          if (!display.readAndDispatch())
            display.sleep();
        }
        display.dispose();
      }
    
    }
    
  • Another option is to use a StackLayout to switch between underlying controls. This prevents you from running into a "widget is disposed" error.

C# Easy question, how do I loop through an array and display values inline?

Hi all,

Basically I have this which I know won't work but I it illustrates what I'm trying to do:

MessageBox.Show("Found these: " + keywords[i] + " keywords.");

And I need to see this:

Found these: Item1, Item2 keywords.

There may be 1 keyword there may be 4, how should I do this?

Many thanks.

From stackoverflow
  • You could use string.Join:

    MessageBox.Show("Found these: " + string.Join(", ", keywords) 
                    + " keywords.");
    
  • Jon Skeet has a good answer with string.Join. your other option for more complicated formatting would be to use a string builder

    StringBuilder sb = new StringBuilder();
    seperator = "";
    foreach(string current in keywords){
     sb.Append(seperator);
     sb.Append(current);
     seperator = ", ";
    }
    
    MessageBox.Show("Found these: " + sb.ToString() + " keywords.");
    
    PoweRoy : sb.Length -= 2; // Remove the last ", " Should only happen when a string is in keywords else sb has a negative length and i dont know how it handles it :P

Linq Count Returned Results

//Feedback Check
var generalFeedbackQuery = from feedbackElements in xml.Elements("feedback")
                           select new
                           {
                               Feedback = feedbackElements.Element("general").Value,
                               PostiveFeedback = feedbackElements.Element("positive").Value,
                               NegativeFeedback = feedbackElements.Element("negative").Value
                           };

Assert.AreEqual(actual.feedback, generalFeedbackQuery.ElementAt(0).Feedback);
Assert.AreEqual(actual.positiveFeedback, generalFeedbackQuery.ElementAt(0).PostiveFeedback);
Assert.AreEqual(actual.negativeFeedback, generalFeedbackQuery.ElementAt(0).NegativeFeedback);

Is it possible to check whether the query returned anything?

Like

if(generalFeedbackQuery.Count())....

This seems to work, but if you add a watch on the Count it doesn't seem to exist...

From stackoverflow
  • The best way of seeing whether or not anything was returned is to use Any(). That will stop and return true as soon as it gets any results, rather than looping through all of them.

    (If you actually want the count, then Count() is indeed the right way to go. My guess is that the Watch window is confused by it being an extension method. You could explicitly call System.Linq.Enumerable.Count(generalFeedbackQuery) which may work.)

Library to generate .NET XmlDocument from HTML tag soup

I'm looking for a .NET library that can generate a clean Xml tree, ideally System.Xml.XmlDocument, from invalid HTML code. I.E. it should make the kind of best effort guesses, repairs, and substitutions browsers do when confronted with this situation, and generate a pretend XmlDocument. The library should also be well-maintained. :)

I realize this is a lot (too much?) to ask, and I would appreciate any useful leads. There seem to be a fair number of implementations of this for Java, but I would rather not generate my own bindings. So far for .NET I have found http://www.majestic12.co.uk/projects/html_parser.php and http://users.rcn.com/creitzel/tidy.html#dotnet, and http://sourceforge.net/projects/tidyfornet .

I have not yet built or tested any of these, but from the (sparse) docs and rare updates they do not seem like they have what I'm looking for. So what recommendations do you have, either among these choices, or from your past experience.

From stackoverflow
  • The HTML Agility Pack is highly rated. It will certainly do the parsing / best guess etc.

    The model is intentially similar to XmlDocument, including SelectNodes etc for querying.

    If you need xhtml output, there is a OptionOutputAsXml flag; I assume that setting this to true and calling Save results in xhtml.

    Matthew Flaschen : Thank you! So far it looks very solid, though I had to make a couple tweaks to compile it and there's no real docs.
    Matthew Flaschen : I've completed the parsing code, and I still think it's an excellent library. Thank you for the tip. One slightly odd thing is that it doesn't seem to have an option to automatically expand entities (e.g.  ). You have to manually call DeEntitize. Luckily, I only needed this for 1 node.