Thursday, March 31, 2011

What is the rationale for the behavior of the 'this' keyword in JavaScript?

I am asking this from a language design point of view. So I am trying to find out

  1. What is the rationale for the behavior of this?
  2. To what degree the behavior of this was a mistake, or could be improved upon?


To clarify why I'm uneasy about this, consider this example:

var a = {};
a.f = function(){ return this; }
var f = a.f;
// f() != a.f()

Note how easily the object to which f() belong is lost: separated from a, this becomes the global object (window for browsers).

Now consider:

var newA = function(){
    var self = {};
    self.f = function(){ return self; }
    return self;
}

var a = newA();
var f = a.f;
// f() == a.f() !

Without using this at all, we are able to establish and maintain the object context regardless of where or how the method is used. I can't help but think that, with the power that closures provide, this becomes superfluous, and perhaps even a little dangerous...

I'm not on some vendetta against this, or looking to start an argument; I'm merely trying to better understand it. I do appreciate that 'this' can be useful, but recognize that it can be confusing as well... Certainly confusing to beginners, and perhaps to experts as well in sufficiently obscure cases.

And yet, it remains a heavily-used and seemingly well-respected part of the language, in a time when other core aspects of the language seem fair game for shunning (i.e., Crockford and with or new). What am I missing then, that makes this indispensable?

From stackoverflow
    • It wasn't
    • Lots of OO stuff
    • It's good the way it is
    mike g : Ok. Would you mind giving examples of what OO stuff is not possible?
    rix0rrr : This is a very unhelpful answer, since the author is stating opinion as fact without backing up with reasoning or examples. -1
    svinto : mike g: making public functions rix0rr: it's quite hard to back with facts as the other side doesn't provide any
    annakata : @rixOrr: the *question* was stating opinion as fact as well
    • It should be called 'self' instead
    • Anything that refers to current objects state.
    • By choosing 'self' as the name for 'this', and passing it explicitly (as the first argument) to all methods. This way you can easy tell instance method from static method or from function.

    Sorry, but I really like Python ;-)

    Patrick McDonald : I think it should be called Me ;)
    Abgan : Whoa, someone doesn't have sense of humour? Downvoting for 'this'?
    IonuČ› G. Stan : You forgot to mention that you want 'self' passed as a first argument to a method instead of having implicitly access to it.
    Abgan : @Ionug G. Stan: True. Updating my answer to reflect that
    annakata : I think you'll find that self is ripe for abuse. Should've been "that"
    artificialidiot : This answer would fit proggit very nicely.
  • I think unbound "this" is a mistake. Otherwise it is quite handy. Unbound "this" opens the possibility of misinterpreting the context most prominently apparent in event handling of browsers. Also javascript libraries have different opinions of what "this" should refer to in event handling and many callback constructs (like map, filter).

    Removing unbound "this" probably wouldn't make things any more difficult.

    Edit: I guess an alternative syntax example will make my stance clearer.

    function Foo()
    {
        //both this refer to the Foo instance
        this.blah=this.function(){this.bar;};
    
        //second this refers to baz
        this.blah=baz.function(){this.bar;};
    
        //second this refers to anonymous function itself
        this.blah=function(){this.bar;};
    }
    
  • I don't think making "this" unbound was a mistake. It can sometimes be confusing at first, but there are good reasons for the way it is. The first one that comes to mind is that, since JavaScript is not a class based language, functions are not associated with any specific class, so there's not a consistent way to automatically bind "this" to the correct object instance. For example,

    function Person(first, last, age) {
        this.firstName = first;
        this.lastName = last;
        this.age = age;
    }
    
    Person.prototype.getFullName = function() {
        return this.firstName + " " + this.lastName;
    };
    

    "this" needs to refer to a Person object, but the function assigned to Person.prototype.getName doesn't have any way of knowing how it's going to be used, so "this" needs to be bound to whatever object it is called on.

    Where this causes a problem, is when you have nested functions.

    // This is a really contrived example, but I can't think of anything better
    Person.prototype.getInfo = function() {
        // get name as "Last, First"
        function getNameLastFirst() {
            // oops. "this" is the global object, *not* the Person
            return this.lastName + ", " + this.firstName;
        }
    
        // expect something like "Crumley, Matthew: Age 25",
        // but you get "undefined, undefined: Age 25"
        return getNameFirstLast() + ": Age " + this.age;
    };
    

    The syntax artificialidiot suggested would be convenient, but it's pretty easy to bind "this" to a specific object using apply:

    function bind(func, obj) {
        return function() {
            return func.apply(obj, arguments);
        };
    }
    
    Person.prototype.getInfo = function() {
        // get name as "Last, First"
        var getNameLastFirst = bind(function () {
            return this.lastName + ", " + this.firstName;
        }, this);
    
        return getNameFirstLast() + ": Age " + this.age;
    };
    

    or the more "traditional" method using closures:

    Person.prototype.getInfo = function() {
        var self = this;
    
        // get name as "Last, First"
        function getNameLastFirst() {
            return self.lastName + ", " + self.firstName;
        }
    
        return getNameFirstLast() + ": Age " + this.age;
    };
    
  • I think the unbound 'this' keyword is necessary because JavaScript is a prototype-based language. Someone better informed can probably fill in the details here.

    The fact that it is, is mightily unhelpful though. Especially if you want to pass the method of an object to a higher-order function, things start to get ugly (following examples with a little help from MooTools):

    myArray.each(myObject.foo);
    

    Will not work, because the 'this' in myObject.foo will refer to myArray instead of myObject. Instead:

    myArray.each(myObject.foo.bind(myObject))
    

    Which seems very ugly to me. That's why I usually don't program in an object-oriented way in JavaScript, but I rely heavily on closures instead.

  • Consider the idiom a.f() as a shorthand for:

    a.f.call(a);
    

    It's by definition a call to the function f, using scope a.

    var f = a.f;
    f(); // f.call(this);
    a.f(); // f.call(a);
    

    If this and a are not the same object, f() and a.f() will use different scopes and therefore may behave differently. Consider the distinction between static and class methods in other languages:

    class Foo {
    public:
        static void a(Foo *scope) {
            // do something with given scope
        };
    
        void b() {
            a(this); // do something with the scope of this object
        };
    };
    
    Foo foo;
    Foo bar;
    
    foo.a(&bar) != foo.b(); // just like f() != a.f()
    foo.a(&foo) == foo.b(); // just like f.call(a) == a.f()
    
  • You seem to be expecting this to behave as it does in certain OO languages, where it always refers to the object a method belongs to.

    But in JavaScript, a function can be attached to multiple objects, or no object at all. In your example, you've written a function intended to be used in the context of one specific object... But nothing prevents me from taking that function and attaching it to any other object. That's just the nature of the language - functions are first-class, object membership is optional.

    Therefore, this refers to the context in which a function is called. Right now, that's either an arbitrary object (specified via ., .apply, or .call()) or the global object. In future versions of the language, it will refer to the context in which the function was defined: the global object for global functions, the outer this for inner functions; you can view this as a correction of a design flaw, as in practice being able to refer to the global object using this was not particularly useful.

How do I intercept a NotImplementedException in a WPF application?

How do I intercept a NotImplementedException in a WPF application?

I'll occasionally throw a NotImplementedException while testing my in-progress WPF application:

Private Sub ButtonDoSomething_Click(...) Handles ButtonDoSomething.Click
    Throw New NotImplementedException( _
        "ButtonDoSomething_Click() not implemented.")
End Sub

But, I'd rather these not crash the program.

I could replace all such exception throws with:

MessageBox.Show("ButtonDoSomething_Click() not implemented.", _
    "Not Implemented", MessageBoxButton.OK, MessageBoxImage.Information)

But that seems inellegant somehow and wouldn't work if the NotImplementedException was buried away from the interface.

How can I capture all such exceptions and display a message box?

From stackoverflow
  • You can attach to the DispatcherUnhandledException event on the Application class, which will be raised anytime an unhandled exception occurs. In there, you can check the Exception property on the DispatcherUnhandledExceptionEventArgs instance passed to the event handler to see if it is of type NotImplementedException. If it is, then set the Handled property to true, and then return.

    It should be noted that if you called MsgBox instead of throwing the exception, you would have the problem of having to actually return something and set all out/ref parameters as well, which would have been additional overhead.

  • Have a look at Application.DispatcherUnhandledException or AppDomain.UnhandledException. Both let you handle otherwise unhandled exceptions.

    siz : True, however, AppDomain.UnhandledException is an event which is raised by the AppDomain when an unhandled exception is detected. No matter what you do, the app will shutdown right after.
  • Instead of throwing a NotImplementedException or using a MessageBox, you can use Debug.Fail. For example:

    Debug.Fail("This method is not implemented yet!");
    

    It will pop up a message box with the text you provide and show you the stack trace.

Cursor disappears when TextField.selectable = false;

Cursor disappears when

TextField.selectable = false;

How can I make cursor to be visible but textfield not selectable(with mouse) or CTRL+A.

From stackoverflow
  • I believe flash/as3 sees the text cursor as a zero width selection, I dont see how it should be possible to do what you want to here, except maybe extending textfield and placing your own cursor on mouseevents

  • I've seen a similar problem in the past, but I don't remember how to duplicate it. It no longer appears in the project I first saw it in, so the two things which I know have happened since then are below. Of course, there could be some other variable, but the project is working now...

    I suspect that the field is still editable. That would be my first guess. The first thing I would try then:

    //( in a flash.text object ( Flash or Flex ) )
    myTxtFld.type = TextFieldType.DYNAMIC;
    
    //( in a mx.controls object ( Flex ) )
    myTxtFld.editable = false;
    

    If that does not work, try nesting the TextField in something with a MouseEvent.ROLL_OVER listener and useHandCursor set to False. eg:

    var spt:Sprite = new Sprite();
    spt.useHandCursor = false;
    spt.addChild( myTxtFld );
    spt.addEventListener( MouseEvent.ROLL_OVER, function( anon:* ){} );
    

What is the best solution for using transparent PNGs in Internet Explorer 6?

Lack of proper PNG support in IE6 is a well-known issue, with several solutions. There does not appear to be a clear best accepted practice or method.

What do you propose the best solution is, and why?

From stackoverflow
  • 1) Eliminate the need for alpha transparency

    Failing that

    2) Javascript for those that are absolutely necessary. SuperSleight is one option, but there are many javascript implementations.

    3) Depreciate IE6 or provide a separate CSS for IE6 users

    IE6, thankfully, is declining so option 3 is actually reasonable now.

    teedyay : Did you mean "deprecate"? Depreciate is good to though, in this case. :)
  • You could convert the *.png to *.gif with IrfanView for example. But since GIF-Format can only display 256 colors it often is leading to quality-loss and color-steps :(

  • You could use something like pngfix.js to apply the appropriate filter to PNGs in IE6.

  • Any solution involves using DirectX AlphaImageLoader

    I like Twinhelix solution most

    and version 2.0, still not thorougly tested, seems to work great with background PNG too.

    You can't neglect IE 6.0 since it still makes more than 20% in browser market share. GIF transparency is below par.

  • Use PNG-8 for transparency as it will work with IE6. It will act like a GIF image under IE6 while it allows for alpha transparency in more capable browsers.

  • The best solution I've found is Unit PNG fix. It's tiny, fast, and eliminates most of the issues found in other solutions.

How to determine an object's class (in Java) ?

If class B and class C extend class A and I have an object of type B or C, how can I determine which it instantiates?

From stackoverflow
  • Use Object.getClass(). It returns the runtime type of the object.

  • if (obj instanceof C) {
    //your code
    }
    
  • You can use:

    Object instance = new SomeClass();
    instance.getClass().getName(); //will return the name (as String) (== "SomeClass")
    instance.getClass(); //will return the SomeClass' Class object
    

    HTH. But I think most of the time it is no good practice to use that for control flow or something similar...

  • Any use of any of the methods suggested is considered a code smell which is based in a bad OO design.

    If your design is good, you should not find yourself needing to use getClass() or instanceof.

    Any of the suggested methods will do, but just something to keep in mind, design-wise.

    Bill the Lizard : Yeah, probably 99% of the uses of getClass and instanceof can be avoided with polymorphic method calls.
    carrier : i am in agreement. in this case i'm working with objects generated from xml following a poorly designed schema which i do not have ownership of.
    Yuval A : That's generally the case in these situations, legacy code, bad design not in your ownership, etc...
    MetroidFan2002 : Not nessecarily. Sometimes separation of interfaces is good. There are times when you want to know if A is a B, but you don't want to make it mandatory that A is a B, as only A is required for most functionality - B has optional functionality.
  • there is also a .isInstance method on the "Class" class. if you get an objects class via myBanana.getClass() you can see if your object myApple is an instance of the same class as myBanana via

    myBanana.getClass().isInstance(myApple)

Why does my WCF service not respond my baseAddress setting in web.config?

I'm trying to learn how to build RESTful services with WCF by recreating the project on this blog post by Anthony Steele. He uses the following XML in his config to setup the endpoint for the service.

    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8080/greeter"/>
      </baseAddresses>
    </host>

However, when I try to do the same thing in my ASP.NET 3.5 web site's web.config, I am unable to navigate to my service. Here is the XML I'm using:

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="GreeterBehavior">
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <services>
    <service behaviorConfiguration="GreeterBehavior" name="Greeter">
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:49268/TestREST/webapi/services/greeter"/>
        </baseAddresses>
      </host>
      <endpoint address="" binding="wsHttpBinding" contract="IGreeter">
        <identity>
          <dns value="localhost"/>
        </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
  </services>
</system.serviceModel>

I would imagine my configuration would allow me to navigate to http://localhost:49268/TestREST/webapi/services/greeter and see my service. All I get is a resource not found message - am I missing something?

Edit: Part of my problem was my binding was wsHttpBinding. Using webHttpBinding allowed me to use the service correctly - except, the baseAddress config section still has no effect.

From stackoverflow

How does windowing work in qt embedded?

How does windowing work in qt embedded, where Qt is drawing directly to a framebuffer instead of through a separate windowing system? Can I run multiple programs at once? Do I get compositing and the little [x] button, maximizing and so forth?

From stackoverflow
  • What part of how does it work are you asking about? If you want a basic overview, think of it kind of like a X-windows server on Linux, where the framebuffer draws the border, decorations, etc., only the Qt libraries are compiled to work more directly with the framebuffer than they do with X-windows servers. Various aspects of the framebuffer can be overridden by a program as well, rather than needing to be changed by the window server. However, for most of your UI work with Qt, you'd be using the exact some classes (QDialog, etc.) that you would on a regular desktop version. They are just drawn by a different underlying layer.

  • You need to run one application as the server to provide window management facilities; for example, by passing the -qws option at the command line when you run it.

    Any other applications are run as clients. See this page for details:

    http://doc.trolltech.com/4.5/qt-embedded-running.html

How to optimize this code?

Surely there has to be many ways to optimize the following code, where I basically have to make sure that a lot of textboxes aren't empty and then read their values:

if (foo1.Text.Length != 0 & bar1.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo1.Text + " / " + bar1.Text;
}

if (foo2.Text.Length != 0 & bar2.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo2.Text + " / " + bar2.Text;
}

if (foo3.Text.Length != 0 & bar3.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo3.Text + " / " + bar3.Text;
}

if (foo4.Text.Length != 0 & bar4.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo4.Text + " / " + bar4.Text;
}

if (foo5.Text.Length != 0 & bar5.Text.Length != 0) 
{
    output.Text += myStrings[i] + " / " + foo5.Text + " / " + bar5.Text;
}

if (foo6.Text.Length != 0 & bar6.Text.Length != 0)
    output.Text += myStrings[i] + " / " + foo6.Text + " / " + bar6.Text;

if (foo7.Text.Length != 0 & bar7.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo7.Text + " / " + bar7.Text;
}

if (foo8.Text.Length != 0 & bar8.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo8.Text + " / " + bar8.Text;
}

if (foo9.Text.Length != 0 & bar9.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo9.Text + " / " + bar9.Text;
}

if (foo10.Text.Length != 0 & bar10.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo10.Text + " / " + bar10.Text;
}
From stackoverflow
  • I would just loop over the Controls collection on which these TextBoxes reside, then filter on TextBox only and do you checks and concat.

    I also strongly advice to use a StringBuilder instead of +=.

    Jeffrey L Whitledge : +1 for StringBuilder. The string concatination in the question would be the major innefficiency here, and to the extent at which it appears to be used, it could even be noticable by the user.
    BeefTurkey : Yes, you're probably right about StringBuilder. Currently, it actually takes many seconds before all strings are generated. Thanks for the advice!
    Gerrie Schenck : Thanks for the heads up, good luck!
  • Could you make foo1-foo10 into an array, foo[10], and the same for bar? That would allow you to express this as a simple loop.

  • I would put the repeated elements in arrays and then loop over them.

    TextBox[] foos = new TextBox[] { foo1, foo2, foo3, /* etc */ };
    TextBox[] bars = new TextBox[] { bar1, bar2, bar3, /* etc */ };
    
    for (int i = 0; i <= 10; i++)
        if (foos[i].Text.Length != 0 && bars[i].Text.Length != 0)
            output.Text += myStrings[i] + "/" + foos[i].Text + bars[i].Text;
    

    Of course, if the elements are really named sequentially you can fill the arrays by looking up the controls from the form's Controls collection, with the name "foo" + number.ToString().

    BeefTurkey : This is a very nice solution! Also, the elements are named in sequence, so it makes it evey easier. Thank you!
    Greg D : As a general rule, I don't like this approach because of the implicit, non-obvious association between foos and bars. I suggest making the association explicit via a FooBar class and creating a List for subsequent use.
  • Would it be feasible to make a WebControl that has textboxes called foo and bar, and that has a function like:

    if (foo.Text.Length != 0 & bar.Text.Length != 0)
        return myStrings[i] + " / " + foo.Text + " / " + bar.Text;
    else
        return string.Empty;
    

    Put ten of those on your page, then use:

    output.Text = myControl1.FooBar + myControl2.FooBar + myControl3.FooBar + ...
    

    (Still a bit messy, but not quite so repetitive.)

  • Write a function which accepts foo & bar types. Pass all foo1 & bar1 to foo10 and bar10 to the function to get the values. You can also create array of foo and bar and you can loop and call the method to get the string.

  •  foreach (Control ctrl in Page.Controls) {
          if (ctrl is TextBox) {
              if (ctrl.Text.Length != 0) {
                  output.Text += myStrings[i] + "/" + ctrl.Text;
               }
          }
     }
    

    Untested , but should work. With this your textboxes could be named anything.

  • There are a lot of ways to refactor this. The method you choose will depend on your particular scenario and needs.

    1. Make a function that takes a foo and a bar as a parameter and returns the string, then aggregate that string in a string builder
    2. Put the foos and bars into collections and loop over those collections. In this scenario, arrays would be useful and provide a way to mutually index the arrays.
    3. Take item 2 one step further and create a new class FooBar that holds a foo and a bar together. This way you can create a collection of FooBars and you don't have an implicit association between them anymore, now it's explicit and codified.
    4. Take item 3 one step further and recognize that you're aggregating a string. If you're in a recent version of c#, take advantage of your Map/Reduce in LINQ (.Select().Aggregate()) to transform your FooBars into their corresponding strings, and then to aggregate the strings into output.

    This is all just the stuff off the top of my head. If you work at it more, I'm sure you can do even better. :)

    (If this is homework, please add a homework tag.)

    EDIT:

    I can't help but wonder about the design of the UI in general based upon your comment in another post stating that it takes "many seconds" to concatenate the strings together. 10 strings is a pretty trivial amount of time on its own, but this suggests that your outer loop (that's generating i) is fairly long running.

    If you're in a position where you have the freedom to make such decisions, are you certain that your UI is actually good for the task at hand? A large collection of pairs of text boxes is a difficult user interface in general. Perhaps a ListView would be more appropriate. It would implicitly contain a collection, so you wouldn't have to deal with this "ten text boxes" silliness and will be an easier UI for your users to follow in general.

    BeefTurkey : I think you might be on to something regarding ListView. In fact, I'm going to re-code to implement a ListView element instead of a fixed set of textboxes. Thanks for the tip.

What is the best Windows explorer replacer (File Manager) for developers

DUPLICATE: Best filemanager for developer

I don’t like the windows explorer. It lakes several important and productive features for developer.

I personally have tried 2 UltraExplorer and CubicExploere. Like both I now only use CubicExplorer because it is being actively maintained, and find it more stable.

What other File Managers are you using, that are more featured for development work?

From stackoverflow
  • I prefer Far Manager, which is quite an orthodox file manager, but is blazingly fast and extensible to no limits.

  • I have been in love with total commander since 1995, it even integrates with Tortoise SVN so I can't ask for more

  • I like SpeedCommander. It reminds me of NC visually, and I enjoy its simplicity, in contract to often bloated alternatives (no, I don't need an integrated image viewer, file editor, hex editor and whatever, all integrated into file manager :) Every tool for one job, but do it good.

  • What other File Managers are you using, that are more featured for development work?

    http://www.detalizer.com

Passing a million numbers from java to matlab?

I have a bit of code which runs in 10.919 s. Profiling it shows that 10.182 s are wasted in

opaque.double

Which is called when I use

jClass.GetArrays(jArray1,jArray2);

struct.prop1 = double(jArray1);
struct.prop2 = double(jArray1);

What can be done? I have to use Java to interact with external API.


EDIT: I used the following hack:

struct.prop1 = cell2mat( cell( jArray1) );


And got down to 1.5s / 2.2s

EDIT:

Making the java return long comma delimited string representation of the arrays and then using

data = strread(char(jString),'%f','delimiter',',' );

Produced almost bearable performance

From stackoverflow
  • You might consider saving it to a file, then reading it in on the other end. It might also be similarly slow (especially if a network is involved), but it's worth a shot.

    You might also consider converting it to a blob of binary data, then passing it, and converting it back.

    I have a sneaking suspicion that with that bad performance it's passing each element of the array in its own transaction rather than all at once.

  • The problem lays in the usage of boxed Java primitives - java.lang.Double in this case.

    Simply changing the signature of the Java from Double to double cause Matlab to seamlessly work with the array without the casting overhead.

In what thread does the VS Debug Immediate window execute commands?

I have a multi-threaded .Net app in which thread-local storage is used to hold a flag of sorts. I have reason to suspect that the flag is being set incorrectly in one of the threads and would like to use the VS debugger to inspect when and where the flag is being set.

Once I have stopped the application at a break point, can I use the immediate window to inspect that thread-local flag?

More specifically, on what thread would the immediate window execute the following command

Thread.GetData(Thread.GetNamedDataSlot(flagName))

Alternatively, can you suggest ways to monitor these flags per thread?

From stackoverflow
  • Try naming all your threads and then say ?Thread.CurrentThread.Name on the console. Or alternatively display the managed thread id.

  • Experimenting with

    Thread.CurrentThread.ManagedThreadId
    

    suggests that the immediate window does the right thing and executes in the same thread as the code with the breakpoint.

Selecting attribute values with html Agility Pack

I'm trying to retrieve a specific image from a html document, using html agility pack and this xpath:

//div[@id='topslot']/a/img/@src

As far as I can see, it finds the src-attribute, but it returns the img-tag. Why is that?

I would expect the InnerHtml/InnerText or something to be set, but both are empty strings. OuterHtml is set to the complete img-tag.

Are there any documentation for Html Agility Pack?

From stackoverflow

XML XSL Transform From Stream

Hi I have a memory stream in which I use XMLTextWriter to write out some XML. What I want to do is transform this XML using the XSL.transform feature. The thing is I don't want to create a temp. XML file, I want to somehow use the stream to Transform it into the XSL. Thank you for any suggestions.

From stackoverflow
  • Just use an XmlReader and pass it to the Transform method. You'll need to seek to the start of the stream first.

      stream.Seek(0, SeekOrigin.Begin);
      XmlReader reader = XmlReader.Create(stream, settings);
      XslCompiledTransform transform = new XslCompiledTransform();
      transform.Load(...load your transform...);
      transform.Transform(reader, resultsWriter);
    

    I've obviously removed certain elements here to simplify the code, but you should get the idea.

    morechilli : Worth noting that your transform can be loaded from many things including a stream by the above Load method. You should never need to drop down to a file.
    Jeff Yates : Yup, the Load method has many useful overrides.

Easiest Way to Print Non-Strings in Ruby

I'm constantly doing this

puts “The temperature is “ + String(temperature) + “.”

in my debugging code, and another option is to use interpolation

puts “The temperature is #{temperature}.”

is there any less cumbersome way to do this?

Edit: This is just for debugging, if that matters.

From stackoverflow
  • None that are all that worthwhile for small cases like that.

    Though, you should prefer interpolation as it's less expensive than concatenation.

  • The best way to insert dynamic variables into strings is

    #interpolation
    "foo #{my_var} bar"
    

    It will call the to_s method on whatever object the expression returns and insert that string. It really the same as

    #concatenation
    "foo " + my_var.to_s + " bar"
    

    But, as wfarr metioned, its faster to do interpolation. Easier to read too.

    Thanatos : It appears you got it backwards. Interpolation is the first example. Concatenation is the second example you gave.
    Squeegy : Perhaps it got misinterpreted that way. I clarified with labels :)
    Yar : I had forgotten baout the .to_s method. Not a bad option... depends on your typing habits. I am not using this stuff in real code, but just to figure out what's happening.
    Squeegy : to_s is generally THE way to turn an object into a string. It's defined on the Object class that all ruby objects inherit from so its always available. If you write your own classes its encouraged to override it with a decent implementation.
  • There's always the possibility to use printf style formatting:

    "The temperature is %s" % temperature
    

    This would allow for finer formatting of numbers, etc. as well. But honestly, how much less "cumbersome" than using #{} interpolation can you expect to get?

    Yar : To be honest, I type on a Spanish keyboard but I switch to English format half the time, so finding the number key and brackets is just not as easy as "thinger" + thinger like in Java. But yeah, the interpolation syntax is workable.
  • Another way is to do something stupid like this:

    "The temperature is %s." % temperature.to_s

    Personally I'd use interpolation

  • A slightly different approach is to use assertions in automated tests.

    For example using Test::Unit :-

    assert_equal 25, temperature
    

    I find that using automated tests dramatically cuts down on the amount of debugging code I have to write.

    Yar : Very interesting, I'll check into this possibility. Answers like this make my stupid questions worth it.
    Yar : So how can I get this code running from a Ruby program? TestCase.assert_not_nil(blah) I know I need some requires or something.
    floehopper : require 'test/unit' class MyTest < Test::Unit::TestCase def test_should_be_hot_today ... assert_equal 25, temperature end end
    floehopper : Alternatively if you just want the assertions: require 'test/unit/assertions' include Test::Unit::Assertions ... assert_equal 25, temperature
    floehopper : See http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit/Assertions.html
  • Use Kernel#p

    p temperature #=> 10.25
    

    When I'm debugging, I often label such statements just by copying the line, and using inserting a colon, making the variable into a symbol.

    p :attributes #=> :attributes
    p attributes  #=> { :mood => "happy", 5 => [] }
    

    Or

    p [:location, location] #=> [ :location, "@ work" ]
    

    Note that Kernel#p calls #inspect on its arguments, instead of #to_s, but this normally provides more useful debugging info anyway.

    Yar : Wow. Nice stuff. I'll check it out. Anything that can save typing in my eventually-deleted-statements helps.

HttpModule URL rewriting using IIS6 with no extensionless URLs

We are using the Intelligencia URLRewriting module for asp.net with version 2.0 of the framework and IIS6. Our URLs typically have no extension.

I understand that IIS6 cannot really deal with this situation without a blanket wildcard (which causes other problems).

However, it works! Sometimes. At other times (e.g. on one dev's machine, and on my machine when I point a different virtual directory at the app) it doesn't. By "it doesn't work" I mean the configured HttpModules never even get hit.

Can anyone explain this?

Thanks.

From stackoverflow
  • If you run a site using the Visual Studio development web server all requests will be handled by asp.net so your HttpModule will run.

    On IIS6 this should not happen unless it is set up to forward the requests to asp.net.

    Gaz : We're using IIS6 in all cases.
  • Are you sure that when "it works" you aren't running under the Cassini development web server included in VS.NET ? Because extensionless wildcards do work under Cassini, which can be very confusing to say the least.

    Gaz : Yep. No devs use Cassini. It works on various test servers which are deployed to in the same way as our live website. Because of this black magic mystery we are probably going to switch to an ISAPI filter instead but I would be interested to find out what is actually going on.
    andynormancx : I should have seen your other response. I guess I was just too keen to post about the Cassini possibility. Moving from Cassini to IIS6 and finding this doesn't work was one of my biggest "doh" moments ever.
  • So it turns out what was happening was the following:

    I guess this could prove to be a useful kludge for someone, but we're moving to an isapi filter. One heads-up is that this will by default lead to a tight loop of redirects!

How to build a C++ Dll wrapper that catches all exceptions?

Like the title says, we’re looking for a way to catch all exceptions from a piece of C++ code, and wrap this in a dll. This way we can shield of the application that uses this dll, from any errors occurring in this dll.

However, this does not seem possible with C++ under Windows.

Example:

void function()
{  
    try  
    {    
        std::list<int>::iterator fd_it;
        fd_it++;  
    } catch(...) {}
}

The exception that occurs is not caught by the standard C++ try/catch block, nor by any SEH translator function set by _set_se_translator(). Instead, the DLL crashes, and the program that uses the DLL is aborted. We compiled with Visual C++ 2005, with the option /SHa. Does anyone know if it’s possible in C++/Win32 to catch these kind of problems and make a rocksolid DLL wrapper?

From stackoverflow
  • Incrementing an iterator on a standard libary container will never throw a C++ exception. It may give you undefined behaviour.

    Aardvark : It can throw a structured exception which is a Microsoft compiler thing. With those you can catch divides by zero, bad memory access, etc... The semantics are different than C++ exceptions.
    anon : Which is undefined behaviour from a Standard C+++ perspective
    Aardvark : Sure, sure I wasn't disagreeing. Just pointing out in VC++ it actually will throw something that can be caught by catch(...). But this isn't standard C++ by any means.
  • On Windows, C++ has 2 different styles of exceptions: C++ and SEH exceptions.

    SEH is a windows only form of exceptions (somewhat akin to signals in UNIX). It's more of a system level exception. They will be thrown for such operations as invalid pointer accesses, alignment issues, etc ...

    If you want to catch every exception that can be thrown by a C++ app on windows you will need to catch both. Fortunately there is a way to mix the use of C++ and SEH exceptions. I wrote a detailed blog post about this recently, it should help you out.

    http://blogs.msdn.com/jaredpar/archive/2008/01/11/mixing-seh-and-c-exceptions.aspx

  • Have you looked at the windows API function SetUnhandledExceptionFilter?

    I usually call it in the DllMain function and have it generate a minidump when the DLL crashes. However: (a) I don't know if it traps application exceptions as well as DLL exceptions, and (b) I don't know if you can have the handler return in such a way that program execution can continue. The docs say yes, but I've never done it.

  • The only way to make a rock solid DLL wrapper is to load the buggy DLL in another process, so that if it crashes it doesn't take your primary process down with it.

    Catching all C++ exceptions seems reasonable, but catching all structured exceptions is another story. SEH might seem to get you most of the way there, because it allows you to catch access violations, divide-by-zero exceptions, etc.

    But what if the buggy DLL happens to touch an uncommitted page from another thread's stack? The memory access will page fault, the exception handler will be invoked, and now that page is no longer a guard page. When that thread needs to grow the stack, it will get an access violation, and the process will crash. (These posts describe this case in more detail.)

    Another likely problem: the buggy DLL crashes while holding a synchronization object, but you use SEH to catch the exception. If your process attempts to acquire the same synchronization object, then it deadlocks instead of crashing. The shared synchronization object may be part of the C runtime or the OS: what if buggy DLL 1 loads buggy DLL 2, which crashes in its DllMain() while buggy DLL 1 is holding the loader lock? Will your process deadlock the next time it loads a DLL?

    For more information on why this (and functions like IsBadReadPtr(), which have similar problems) is a misuse of SEH:

  • This code contains a logic error, if at all. Since a logic error constitues a bug, don't swallow the exception – fix the error!

    Of course, this is specific to the particular code. Others have offered more general advice. However, I've found that a lot of people actually do prefer catching exceptions over fixing logic errors and this is simply unacceptable.

  • The code below is taken from the Zeus IDE. It will trap any Windows generated exceptions:

    Step #1: Define an Exception Filter Function

      DWORD ExceptionFilter(EXCEPTION_POINTERS *pointers, DWORD dwException)
      {
        //-- we handle all exceptions
        DWORD dwResult = EXCEPTION_EXECUTE_HANDLER;
    
        switch (dwException)
        {
          case EXCEPTION_ACCESS_VIOLATION:
          case EXCEPTION_DATATYPE_MISALIGNMENT:
          case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
          case EXCEPTION_FLT_DENORMAL_OPERAND:
          case EXCEPTION_FLT_DIVIDE_BY_ZERO:
          case EXCEPTION_FLT_INEXACT_RESULT:
          case EXCEPTION_FLT_INVALID_OPERATION:
          case EXCEPTION_FLT_OVERFLOW:
          case EXCEPTION_FLT_STACK_CHECK:
          case EXCEPTION_FLT_UNDERFLOW:
          case EXCEPTION_INT_DIVIDE_BY_ZERO:
          case EXCEPTION_INT_OVERFLOW:
          case EXCEPTION_PRIV_INSTRUCTION:
          case EXCEPTION_NONCONTINUABLE_EXCEPTION:
          case EXCEPTION_BREAKPOINT:
            dwResult = EXCEPTION_EXECUTE_HANDLER;
            break;
        }
    
        return dwResult;
      }
    

    Step #2: Wrap the code in a *__try* and *__except* as shown below:

      __try
      {
        // call your dll entry point here
      }
      __except(ExceptionFilter(GetExceptionInformation(), 
                               GetExceptionCode()))
      {
        //-- display the fatal error message
        MessageBox(0, "An unexpected error was caught here!", 
                   "Unexpected Error", MB_OK);
      }
    
  • What are you going to do after you catch the exception (especially for SEH exceptions)?

    In reality you can make no assumptions about the state of the process, realistically the only option you have is to (optionally) dump core and exit.

    Any attempt and proceeding is absolutely going to cause you problems in the long run.

  • Konrad Rudolph: Of course this code contains a "logic error", it's to illustrate a problem that could occur. Like the man says he wants to be able to shield his dll from any possible errors. You don't think this is a legitimate question? Heard of vendor products. Some of us live in the real world and live with real problems. It's just not possible to fix everyone else's problems

limit selections in a listbox in vb.net

Hi all,

I am creating a web control in vb.net that contains a list box. I know that I am able to choose a selection mode of Single or Multiple, but I am interested in limiting a Multiple selection to a predetermined size. For example preventing a user from selecting more than 3 items.

I have tried adding a Validator to the list box, which might be a way forward, but was wondering if there was a way of changing the selection mode to something a bit different than just the two specified ones.

Any ideas or suggestions would be greatly appreciated

Edit: Unfortunately due to project limitations I am unable to use Javascript on this problem. very annoying I know!

From stackoverflow
  • You could try handling one of the SelectedIndexChange events. With multiple selection, each time this event fires you can check how many items have already been selected. If it is more than you want, have the handler deselect the one that was just selected. You could also put up a little red label under the listbox saying "Sorry, no more than [n] selections allowed."

    EDIT: Just noticed you said WEB. Same theory applies, but it would have to be done using Javascript.

    chillysapien : Thanks for that. Only problem is I am unable to use Javascript on this problem due to (annoying) project limitations.
    Dave Swersky : In that case, you *may* be able to use Autopostback, but I'm not sure if that will work for multiple selection. Is AJAX an option? That could work as well.
    TheTXI : @Dave: I don't see why it would be much different on the web. If the listbox is set up with AutoPostBack set to true, it should fire each time a selection is made. Then you can run the validation code during the postback (or partial postback in AJAX).
  • On the SelectedIndexChanged event, write a short piece of code that will check the number of selected items and if it is greater than your desired amount, unselect the new selection (or unselect the oldest one, or however you wish this to operate).

Binding a custom serializable object to controls so user and load/save preferences

Ok, so having given up on getting the built in .NET configuration system to save/load data about a custom object per user, I have moved to using a serializable object. And, to go a step further, I'd like to bind it to my controls in the options window of my application.

Please forgive the length of this question as it has some chunks of code in it...

First, the parent object:

[Serializable]
public class ConnectionSettings
{
    public List<Connection> Connections { get; set; }

    public ConnectionSettings()
    {
        Connections = new List<Connection>();
    }
}

Because there will be multiple connections that will be saved, I figured this would be the easiest way to store them.

A chunk of the Connection object:

[Serializable]
public class Connection : NotifyBase
{
    private string hostName;
    [DisplayName( "Host Name" )]
    public string HostName
    {
        get { return hostName; }
        set { SetField( ref hostName, value, "HostName" ); }
    }

    /* Other field snipped for your sanity,*/
    /* same format as host name */

    public List<string> Channels { get; set; }

    public Connection()
    {
        Channels = new List<string>();
    }
}

For a general idea of how the form looks like: I have a ComboBox that will display the Host Name of all the saved connections, when the user selects a Host Name, it will populate the other fields on the form with their respective values. I realize this shouldn't be so hard, but for some reason, I can't get the combo box portion working, and the more I think about it, I'm not sure If I know how to know which particular connection to populate the other controls with...

more info The problem is, I'm not sure how to bind everything that needs binding. I was going off of this example. What I'd like to be able to do is for every Connection object in the deserialized ConnectionSettings (from a file) display the host name in the combo box, and when you select a host name, it fill in the rest of the related data to the other controls on the form.

Any help ill be greatly appreciated.

From stackoverflow
  • Ok, I think I've figured it out. I changed the ConnectionSettings to inherit List and it seems to be working correctly.

How can I speed up jquery :selected selector?

I have a dropdown in a web page with 3830 elements in it. I know, excessive but whatever.

In jquery I get the selected option value using the statement:

$( "#institutionCombo :selected" ).val();

There is a noticeable pause before the selection is found. Once I get that value I insert it into a textbox on the page, so I know how fast. Plus I've checked it using breakpoints in Firebug.

If I go old school and use this javascript:

var div = document.getElementById( "maindiv" );
var select = div.getElementsByTagName( "select" )[ 0 ];
var ix = select.selectedIndex;
var instId = select.options[ ix ].value;

This speed is instananeous.

Is there something inherit in jquery that makes the :selected selector so slow when the numbers get too high? I'd like to stick with jquery throughout in my scripts, does anyone have a suggestion to speed up finding the selected option in jquery?

Thanks,

Craig

From stackoverflow
  • You could do this:

    var ix = $( "#institutionCombo" ).attr( "selectedIndex" );

    var value = $( "#institutionCombo option:eq(" + ix +")" ).val();

    but, that's effectively what you are doing in your old-school code.

    I'm surprised that there is a noticeable delay, since I would have thought that what I'm doing above is what the jQuery code is doing for the :selected selector.

    Otherwise, I wonder if it is a syntax error that is causing the delay, you should probably be doing

    $( "#institutionCombo option:selected" ).val();

    (note option:selected vs :selected)

  • There is no need to call the :selected when getting the val of a select box.

    The default behavior is to get the selectedIndex

    $( "#institutionCombo").val();
    

    As noted in the comment, If you need to access the text of that option you can use

    $( "#institutionCombo option[value=" + $( "#institutionCombo").val(); + "]").text();
    

    although if you know you need the text property and its different from the value you may just want to use the selectedIndex directly.

    var combo = $("#institutionCombo").get(0); 
    combo = combo ? combo : {selectedIndex: -1}; // handle no combo returned
    if (combo.selectedIndex < 0)
      return; // nothing selected
    $('#institutionCombo option:eq(' + combo.selectedIndex + ')').text()
    

    Here is the snippet from the jquery source (v1.3)

    val: function( value ) {
        // ... 
        // We need to handle select boxes special
        if ( jQuery.nodeName( elem, "select" ) ) {
         var index = elem.selectedIndex,
          values = [],
          options = elem.options,
          one = elem.type == "select-one";
    
         // Nothing was selected
         if ( index < 0 )
          return null;
    
         // Loop through all the selected options
         for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
          var option = options[ i ];
    
          if ( option.selected ) {
           // Get the specifc value for the option
           value = jQuery(option).val();
    
           // We don't need an array for one selects
           if ( one )
            return value;
    
           // Multi-Selects return an array
           values.push( value );
          }
         }
    
         return values; 
        // ... 
    },
    

    When you call the :selected selector that is going loop through all the select elements decendents looking for the .selected property to be set and will return an array of any. Either way you do this it will loop all decendents, so don't do this.

    Craig : Sorry the office lost power and was not able to respond. This is good but it sounds like you still have to revert to old school methods like Julian talked about if you want to get the selected text. Or is there a jquery method that I'm unaware of that does that too?
    Craig : Answered this question -- use var v = $( "#institutionCombo" ).val(); var t = $( "#institutionCombo [value=' + v + ']" ).text();