Tuesday, May 3, 2011

How to prevent multiple dialogs to appear at the same time?

How can I avoid, that a dialog is shown, when there already is one on the screen?

Details: In my application many Timers are running. If a fatal error occurs, all the affected threads are going to show a JDialog (by swingx.JXErrorPane.showDialog()), which is not desired. Even if I cancel all the running Timers, still some Dialogs will appear at the same time. How can I achieve that there will only appear one dialog?

I tried to make the method which calls showDialog() synchronized, which results in my whole GUI being blocked. Usage of a flag didn't work either.

From stackoverflow
  • Turn the dialog into an observer and publish the error events to this new observer (see the Observer Design Pattern). When an event happens, the dialog should show itself (with the main frame as the parent). Display the recent errors in a table in the dialog. Add new errors to the bottom of that table.

    Another option is to display the errors in a table in the main frame. Put the table into a JSplitPane so users can minimize it.

  • Yet another option would be to turn the dialog into a singleton:

    • Give the dialog a private constructor.
    • Create a "private static MyDialog instance;" - attribute in the dialog class.
    • Create a "public static MyDialog getInstance() { ... }; - method to return the instance and first instantiate it if it is null.

    Where MyDialog should be the name of the dialog window's class.

    Then each time you need to show the dialog you simply refer to the singleton:

    MyDialog.getInstance().showDialog();

    Where showDialog just makes the dialog window visible.

PHP constructor executes before arguments for nested variables can be supplied.

First things first, here is a little snippet code to help explain my problem:

<?php
class foo {

    public $title;

    __construct{

        echo "<html>\n";
        echo "<head>\n";
        echo "<title>".$this->title."</title>\n";
        echo "</head>\n";
        echo "<body>\n";

    }

    /**
    *
    * I get $title from index.php
    *
    */
    public function setTitle( $title )
    {

        $this->title = $title;

    }


    __destruct{

        echo "</body>\n";
        echo "</html>\n";

    }

}
?>

You've probably noticed already that this code will produce a title of well, . Yah, there's an empty space there. :- )

To me this actually makes perfect sense (even if I wasn't expecting it) because the class constructor is being executed on the creation of the foo object meaning that it doesn't wait around for index.php to supply the argument for setTitle() which in turn returns the string that fills $this->title.

So if I truly understand whats going on here, what can I do to get around this issue? Should I be buffering the output using the built in buffer functions, and then modifying the stored output with the supplied title string? Any ideas?

I would really, really, really, like to keep this structure where the constructor and destructor contain this repetitive code. Its nice that these functions don't have to be called anywhere. I understand that some developers may consider this bad practice, but I am going to do it this way anyway because I want to because I think its cool. So i'm not really looking for advice in that aspect, unless you feel extremely motivated to inform me on my stupidity.

So, if you have any advice/ideas/knowlege to share with me that would be great.

Thanks, and feel free to take your time because I guess i'm going to be forced to stay inside hiding from the evil swine flu that has come to my city, so no rush!

From stackoverflow
  • You could do all the printing in the destructor. There all variables are known. However (like you said yourself) I think this is really really bad practice. I would suggest using kind of view / template files (you anyway have time enough :) ).

  • You could pass the title as an argument in the constructor?

    teh_noob : I could, but the whole idea is that the title is supplied by index.php (this is all part of a little framework i'm building).
    Schnalle : please, stop! don't build a framework that outputs html in the constructor. so wrong!
    teh_noob : I have to, some times you have to take one for the team to make a difference.
    Steven Richards : Gotta side with Schnalle and Peter here. The point of a constructor is to initialize an object, not output content to the browser.
  • schnalle: this is bad practice. this is madness.
    the_noob: madness ...?
    the_noob: (shouts) THIS ... IS ... LITTLEFRAMEWORKIMBUILDING!
    the_noob: (kicks separation of code and presentation down the well)

    i don't really get what you want to do, but just pass the title as a parameter to the constructor ...

    <?php
    
    class Title {
        public function __construct($title) {
    
            echo '<html><head><title>' . htmlspecialchars($title) . '</title></head><body>';
        }
    
        public function __destruct() {
            echo '</body></html>';
        }
    }
    
    ?>
    

    if you really want your objects to print something, i'd suggest the magic __tostring() method, so you can simply echo your object. but for html tags ... still not useful.

    i wish you luck with your framework, but you're either a genius (not likely) or a guy making the same mistakes (almost) every beginner did (before MVC arrived).

    edit: i can't help you. you want direct output when the object is created, but need to get data into the object before it is created. so you try to workaround something ugly in making it even uglier. it just doesn't work that way!
    you're trying to build a new, better kind of car by attaching wheels to a living donkey, then complain because it somehow didn't work out as you expected (donkey on wheels! wheooo!), and now you ask the community how to attach taillights in a way that makes the donkey/car go faster.

    teh_noob : LOL, yes I know i'm breaking all the rules here. But i'm done letting all these rules and standards boss me around! Its time to deviate from the dull pattern of web frameworks! So who's with me?!?!
    teh_noob : hmmmmm...interesting, however I don't like the idea of passing variables directly into a constructor like that (for no logical reason). However that gives me the idea that maybe I could pass parameters from other functions.
    teh_noob : In all seriousness, i'm no where close to a genius but i'm not dumb either. And what may come as a surprise to you, my framework is MVC based. I'm deviating from the rules a little bit though because I think it's better the way i'm doing it. You can and have already helped me. We must be seeing things from different angles because I see beauty in this. Don't hate me for asking for ideas.
    Schnalle : i don't hate you for that, i did a lot of crazy (and nonsensical) stuff myself. learned a lot from those attempts to do it the "my" way. and i agree, you can do stuff quite elegant by wrapping html around objects. but the constructors and destructors are NOT meant for this and it absolutley makes NO sense to try to force them into this role.
    teh_noob : Fair enough, but i'm still sticking with my way.
  • teh_noob. Listen to me. These words that I'm typing right here. Pretend I'm saying them, and hear the words that are coming out of my mouth. No. NO NO NO NO NO! And no, I don't give a rat's butt how "cool" you think it is.

    This is one of those unfortunate scenarios where it would be shorter to list the "right" things about this approach that the "wrong" things. That is to say, your problems are numerous. That being said, I'm going to go over only some of the things that are bad about this idea.

    First, let's just discuss OOP in general. What you are doing here is my least favorite thing to see ever: what I call "programming with classes". That is to say, structured programming in the guise of OOP because a class keyword was used. If you're gonna do this, don't bother. Just use functions. This is class abuse plain and simple.

    Classes are object blueprints.Objects lend themselves to encapsulation and instantiation. Unless you're really a fan of the Singleton pattern, why create a class that is clearly designed to be instantiated only once? And before you say "But Peter, the Singleton Pattern helps us!!!1one" try to understand that it's actually not all that great. Besides, what you're doing here isn't even a reason people turn to the Singleton pattern in the first place.

    Second is the topic of subclasses. Maybe at some point in the future you'll want some popup pages for your site. Or you'll want print-only versions that are more than just CSS-driven. Maybe you'll even want something that's not HTML at all like an RSS feed. What now? How much other work that goes on in this constructor are you going to have to duplicate for these new page types to work? But what if you've already started relying on subclasses to create individual pages? Now you're fucked. Sure, you can go back and hook up the decorator pattern, but why go through all that work when this problem can be avoided by non-stupid class design in the first place?

    Thirdly, is the idea of echoing HTML in the first place. I'm fine with echo for a word or two here, a tag or three there. But for large HTML chunks, it's just idiocy. Have the decency to escape to output mode and use HTML that's not locked down in a string. Not only is it easier to edit and read, you can actually work with it in a WYSIWYG should you so desire.

    Fourth, this badly, badly breaks the SRP.

    Fifth - this kind of ridiculous design leads to the very type of problems you're trying to solve here. Only you don't want to know that the solution is to remove the echo statements from your constructor. Is there a way around it? Sure. In fact, there's even more than one. Do I recommend any of them? No, not really.

    Lastly, let's discuss headers. Maybe you haven't learned about them yet. Maybe you have and don't care. But what's going to happen when, 6 months from now, you're working on a problem and you're working inside a method that's 10 calls deep in the stack and you realize a simple header() function will solve your problem. Maybe you need to adjust the cache-control or you need to manually set the response code - whatever. But guess what, you can't. Why? Because your silly constructor outputs to the browser the millisecond it's created.

    So, to recap: NO! Unless your actual, ultimate goal is to see some of your very on handiwork on The Daily WTF.

    What can I offer besides admonishment? Maybe part of a new direction? Well, debugging output is hard enough in well-built systems, so don't start by shooting yourself in the foot that does it implicitly. All output from your system should be explicit. If you want to make a "page" type of class, that's fine. Just don't do it like that.

    class foo
    {
        protected $title;
        protected $headers;
    
        public function setTitle( $title )
        {
            $this->title = $title;
        }
    
        public function addHeader( $header )
        {
            $this->headers[] = $header;
        }
    
        public function sendHeaders()
        {
            foreach ( $this->headers as $header )
            {
                header( $header );
            }
        }
    
        public function printPageHeader()
        {
            $this->sendHeaders();
            ?>
                <html>
                    <head>
                        <title><?php echo $this->title; ?></title>
                    </head>
                    <body>
            <?php
        }
    
        public function printPageFooter()
        {
            ?>
                    </body>
                </html>
            <?php
        }
    
        public function printPage()
        {
            $this->printPageHeader();
            $this->printPageFooter();
        }
    }
    
    $p = new foo;
    $p->setTitle( 'Just Testing' );
    $p->addHeader( 'Cache-control: no-cache' );
    $p->printPage();
    
    teh_noob : I wouldn't be being honest if I told you I agreed with everything you said there. But you do fall into the category of "extremely motivated", so I will award you the "answer" for this question. I think next time I ask a question such as this I will add more details as to the scope of my project so people will better understand what i'm getting at. Your rant made me tired i'm going to bed now. One last note my example above was only meant to help explain my question and was not actually in or a part of my framework.
    Peter Bailey : Well, I'd love to see more about what it is you're working on, and ACTUALLY trying to do.
    teh_noob : Don't drink mountain dew and then try to sleep. Maybe when i'm done ill send you a link to prove my stubbornness or everything will work fine without a problem because the code just works anyway. I could re ask my question as: "Help me find good ways to do something wrong because I know its "wrong" but I want to do it anyway because I like it that way and it works and it has an un-logical logic to it that only applies to this specific situation and its only a tiny part of the framework so it will not doom everything"

Blank xmlns="" Attributes From Import

Hi all,

I'm attempting to do a transform on an XML document. My XML transform can result in two different types of base element depending on the value of a certain element:

<xsl:template match="/">
  <xsl:choose>
    <xsl:when test="/databean/data[@id='pkhfeed']/value/text()='200'">
      <xsl:call-template name="StructureA">
        <xsl:with-param name="structure" select="//databean" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:call-template name="StructureB">
        <xsl:with-param name="structure" select="//databean" />
      </xsl:call-template>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

StructureA or StructureB are then created with their own namespaces and schemaLocations:

<StructureA xmlns="http://...">

StructureA & B share some common elements so these are defined in a separate file called "xmlcommon.xslt" that both structures include templates from. This xmlcommon file doesn't have a default namespace defined as I want it to be useable from the namespace defined in either StructureA or StructureB. But when I run my transform, any templates pulled in from the common file result in blank xmlns attributes:

<StructureA xmlns="http://...">
  <SharedElement xmlns="">Something</SharedElement>
</StructureA>

When validating, the blank namespace is then used instead of the correct parent one. Does anyone know how I can stop my templates in my common file from adding those blank xmlns attributes?

Here's an snippet from the common file:

<xsl:stylesheet version="1.0" xmlns:fn="http://www.w3.org/2005/02/xpath-functions" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template name="ControlledListStructure">
    <xsl:param name="xmlElem" />
    <xsl:param name="structure" />

    <xsl:element name="{$xmlElem}">
      <!-- Blah blah blah -->
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>
From stackoverflow
  • The key thing to realize is that your stylesheet dictates the name of each element you add to the result tree. An element's name has two parts: the local name and the namespace URI. In your code above, you supply the local name (the value of $xmlElem), but you don't specify a namespace URI, which means it will default to the empty string. (Actually, it takes on the default namespace of that stylesheet module; since there is none, then it's the empty string.) In other words, the element will be not in a namespace. When serializing the document, the XSLT processor must include the xmlns="" un-declarations so as to undeclare the default namespace that appears at the top. Otherwise, the element would take on that namespace, which is not what your stylesheet dictated. The least intrusive way of fixing this would be to add another parameter (e.g. $namespaceURI), just as you have with $xmlElem. Then you'd write:

    <xsl:element name="{$xmlElem}" namespace="{$namespaceURI}">
    

    Now, the resulting element will take on whatever namespace you tell it to take on (which will have the effect of removing those default namespace un-declarations).

    That should answer your question. I offer the following as free bonus material. ;-)

    You should remove the text() node test in your value comparison. Very rarely will you need to directly compare the values of text nodes. Instead, you can just compare the string-value of the element itself (which is defined as the concatenation of the string-values of all its descendant text nodes). That would look like this:

    <xsl:when test="/databean/data[@id='pkhfeed']/value = '200'">
    

    The advantage of doing it this way is that your code won't break if there's a comment hiding in there:

    <value>2<!--test-->00</value>
    

    In this case, there are two text nodes ("2" and "00"). Your original test would fail, since it checks to see if any of them are equal to "200". Not very likely to happen in this case, but in any case testing the string-value of the element (as opposed to its text node children) is a good practice when that's your intention.

    Finally, I encourage you to learn about template rules and XPath context. I tend to avoid <xsl:choose>, <xsl:call-template>, and <xsl:with-param> whenever possible. For one thing, template rules can help you avoid a lot of the ugly, verbose parts of XSLT.

    <xsl:template match="/databean[data[@id='pkhfeed']/value = '200']" priority="1">
      <StructureA xmlns="http://...">
        ...
      </StructureA>
    </xsl:template>
    
    <xsl:template match="/databean">
      <StructureB xmlns="http://...">
        ...
      </StructureB>
    </xsl:template>
    

    Even if you keep using <xsl:call-template>, you shouldn't have to pass that $structure parameter, as the current node will remain unchanged in the called template. You can access //databean (or /databean, which I suspect is what you mean) just as easily from within either of your StructureA or StructureB templates, because the current node will still be "/" (the document node).

    If you're interested in learning more about XSLT's core processing model, and its most powerful features (template rules), then I encourage you to check out "How XSLT Works", the free sample chapter from my XSLT 1.0 Pocket Reference.

    I hope this has been helpful to you, even if it's more than you bargained for!

    Dimitre Novatchev : Good explanation, Evan. Nothing more to add. +1 from me. Welcome to SO.
    Lee Theobald : Thanks Evan. That's a big help :) And thank you for the extra info too. I don't touch XSLT's often so it's nice to hear the better ways to do things.

Multiline strings in Javascript

Sorry, can't seem to find the syntax. Trying to look for the equivalent of

text = <<"HERE" This Is A Multiline String HERE

[from Ruby] in Javscript

From stackoverflow
  • You can do this

    var string = 'This is ' +
    'multiline' + 
    'string';
    

    You can also do it like this. According to kooiinc, it doesn't work in IE, so it's quite useless...

    var myString = ""+<r><![CDATA[
          <div id="example">
              <p>Awesome multiline string!</p>
          </div>
      ]]></r>;
    
    Itay Moav : You learn something new everyday
    Jordan S. Jones : Forgive my ignorance, but with's with the
    alex : is just an xml fragment, and the CDATA is the node.
    Anonymous : So this only applies in a valid XHTML document, or what?
    KooiInc : As far as I know the second example will only work in Firefox
    alex : I edited my answer, thanks.
    Matthew Crumley : The second example is using E4X, which is why it only works in Firefox. It does work fine in either HTML or XHTML though. The part could be anything (even empty: <>).
  • Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

    "foo \
    bar"
    
    staticsan : Be warned: some browsers will insert newlines at the continuance, some will not.
  • the pattern text = <<"HERE" This Is A Multiline String HERE is not available in js (I remember using it much in my good old Perl days).

    To keep oversight with complex or long multiline strings I sometimes use an array pattern:

    var myString = 
       ['<div id="someId">',
        'some content<br />',
        '<a href="#someRef">someRefTxt</a>',
        '</div>'
       ].join('\n');
    

    or the pattern anonymouos already showed (escape newline), which can be an ugly block in your code:

        var myString = 
           '<div id="someId"> \
    some content<br /> \
    <a href="#someRef">someRefTxt</a> \
    </div>';
    
  • i tried all above items ...but did not work in IE... anybody able to work multiline string with java script in IE (IE6/7)

    annakata : No, it can't be done. OTOH it's not exactly essential.

Suggest me a CSS-reset & base framework

Hi there,

I will not asking CSS framework such as Blueprint or 960, lately i began to think that YUI CSS reset & base was too much bloated, so i need a simpler, efficient (in size) and effective CSS reset (and it's base) that support multiple browser or at least IE6-8 (Trident), Opera(Presto), Firefox(Gecko), Webkit

Remember i don't ask about CSS framework nor grid system

Thanks

From stackoverflow
  • This question has been asked and answered before:

    Dels : yes i've read all that articles, Eric Meyer only gave us a css-reset stylesheet, what i need is reset+base (thats why i change my title)
    alex : @Dels, The reset provides the base to work from
  • I would just use the YUI reset.css. That's not to big, and then handle the rest yourself. Your probably better off building the site layout entirely from scratch because it will be way easier then learning some bloated framework, and it will be more lightweight.

    Dels : in fact i already use that, i want another alternative for that...
    teh_noob : I don't think there are really any other real alternatives. They all have to do the exact same thing so they all pretty much have the exact same code. Too make it seem lighter why don't you just compress the CSS to decrease the file size.
    anonymous coward : As far as my experience (quite a bit) Yahoo offers the best Reset+Base, when you consider how they document exactly how to control the related styles in Base, etc.
  • Don't forget that the YUI reset removes all the styles and YUI base purely adds some styles back in for cosmetic reasons to allow you to start developing.

    The intention is that you write your own styles and remove YUI base before you go into production.

    YUI reset in minimised form is 940 bytes which I don't think is bloated at all. Have you got a reason why you think it is or are you looking at YUI reset and base together?

    Mind you YUI base is 910 bytes so together you are looking at 1,850 bytes. If your website is an online one (not intranet based for example) then call the files from the Yahoo or Google infrastructure and they will be extremely fast in any case.

  • I would just use Eric Meyer's Reset Reloaded. It's pretty simple.

  • I second the alex suggestion and for the base, why do you say 960 is bloated? It's just a small file and you can make it even smaller if you strip one of either the 12 or 16 columns.

Why do on-line parsers seem to stop at regexps?

I've been wondering for long why there doesn't seem to be any parsers for, say, BNF, that behave like regexps in various libraries.

Sure, there's things like ANTLR, Yacc and many others that generate code which, in turn, can parse a CFG, but there doesn't seem to be a library that can do that without the intermediate step.

I'm interested in writing a Packrat parser, to boot all those nested-parenthesis-quirks associated with regexps (and, perhaps even more so, for the sport of it), but somehow I have this feeling that I'm just walking into another halting problem -like class of swamps.

Is there a technical/theoretical limitation for these parsers, or am I just missing something?

From stackoverflow
  • Because full-blown context-free grammars are confusing enough as they are without some cryptically dense and incomprehensible syntax to make them even more confusing?

    It's hard to know what you're asking. Are you trying to create something like a regular expression, but for context-free grammars? Like, using $var =~ /expr = expr + expr/ (in Perl) and having that match "1 + 1" or "1 + 1 + 1" or "1 + 1 + 1 + 1 + 1 + ..."? I think one of the limitations of this is going to be syntax: Having more than about three rules is going to make your "grammar-expression" even more unreadable than any modern-day regular expression.

    Henrik Paul : It seems like you are arguing the (yet unspecified) implementation, than the ability of parsing a CFG in itself? Sure, regular expressions are cryptic to the untrained eye. Perhaps, a context free language could be even more cryptic. But that wasn't the point. The point was, why are there only code generators, and not stuff I can just put into a function/object and get matched blocks of text out of them, like I do with today's regular expressions.?
    Chris Lutz : Usually, when people use a parser, they're looking to do a whole lot more than just look at some text and see if it matches their grammar or not. Not that there's anything wrong with that, but most parsers do quite a bit more.
    Chris Lutz : Plus, the implementation is a technical limitation you are going to have to deal with at some point, and you did ask about technical/theoretical limitations.
  • I think it's more of a cultural thing. The use of context-free grammars is mostly confined to compilers, which typically have code associated with each production rule. In some languages, it's easier to output code than to simulate callbacks. In others, you'll see parser libraries: parser combinators in Haskell, for example. On the other hand, regular expressions see wide use in tools like grep, where it's inconvenient to run the C compiler every time the user gives a new regular expression.

  • Side effect are the only thing I see thing that will get you. Most of the parser generators include embedded code for processing and you would need an eval to make that work.

    One way around that would be to name actions and then make an "action" function that takes the name of the action to do and the args to do it with.

  • You could theoretically do it with Boost Spirit in C++, but it is mainly made for static grammars. I think the reason this is not common is that CFGs are not as commonly used as regexs. I've never had to use a grammar except for compiler construction, but I have used regexs many times. CFGs are generally much more complex than regexs, so it makes sense to generate code statically with a tool like YACC or ANTLR.

    Henrik Paul : I would agree that the use of regular expressions are more common than what seems to be today's demand for CFG:s. But, since I've encountered a numerous questions on getting a correctly nested set pf parentheses on Stack Overflow alone, I'm sure that there is _some_ use of CFG:s. Maybe they aren't being asked for, because people know only of regexps?
    BCS : IIRC Boost::Spirit is a pure compile time implementation. I can't see any reason for it to allow run time definition of grammars.
    Zifre : Boost Spirit can be used at runtime - just shift tokens onto the end of the grammar: grammar = grammar >> ch_p('a');
  • tcllib has something like that, if you can put up with Parse Expression Grammars and also TCL. If Perl is your thing CPAN has Parse::Earley. Here's a pure Perl variation which looks promising. PLY seems to be a plausible solution for Python

  • Boost.Spirit looks like what you are after.

    If you are looking to make your own, I've used BNFC for my latest compiler project and it provides the grammar used in its own implementation. This might be a good starting point...

    Zifre : As I said in my answer, Boost.Spirit works but is mainly meant for static grammars. Thanks for mentioning BNFC though, I might use that for my compiler now. It looks really great!
  • There isn't and technical/theoretical limitation lurking in the shadows. I can't say why they aren't more popular, but I know of at least one library that provides this sort of "on-line" parsing that you seek.

    SimpleParse is a python library that lets you simply paste your hairy EBNF grammar into your program and use it to parse things right away, no itermediate steps. I've used it for several projects where I wanted a custom input language but really didn't want to commit to any formal build process.

    Here's a tiny example off the top of my head:

    decl = r"""
        root := expr
        expr := term, ("|", term)*
        term := factor+
        factor := ("(" expr ")") / [a-z]
    """
    parser = Parser(decl) 
    success, trees, next = parser.parse("(a(b|def)|c)def")
    

    The parser combinator libraries for Haskell and Scala also let your express your the grammar for your parser in the same chunk of code that uses it. However you can't, say, let the user type in a grammar at runtime (which might only be of interest to people making software to help people understand grammars anyway).

    Henrik Paul : Thanks for your informative answer!
  • Pyparsing (http://pyparsing.wikispaces.com) has built-in support for packrat parsing and it is pure Python, so you can see the actual implementation.

Weird div border problems when floating

Could I please get a explanation of why this code produces the result it does? And a way to fix it/work around it, if possible.

I dont want div 'z' and 'q' to go over 'the blue div border' on the right.

Or

I would like div 'x' to be consitant with 'z' and 'q' and also go over the blue right border as well.

Please view result

<div style='margin: 5px;width: 653px;border: blue 1px solid;float: left;'>
    <div style='margin: 0px; margin-bottom: 5px;width: 100%;border: red 1px solid;/*float: left;*/'>z</div>
    <div style='overflow: hidden;margin: 0px; margin-bottom: 5px;width: 100%;border: red 0px solid;/*float: left;*/'>
            <div style='margin: 0px; margin-bottom: 0px;width: 300px;border: red 1px solid;float: left;'>y</div>
            <div style='margin: 0px; margin-bottom: 0px;width: 300px;border: red 1px solid;float: right;'>x</div>
    </div>
     <div style='margin: 0px; margin-bottom: 5px;width: 100%;border: red 1px solid;/*float: left;*/'>q</div>

From stackoverflow
  • The red-border is actually inside the blue border in your image - but I assume you want to increase the margin on the z and q containers...

    I've taken the liberty of enclosing the attributes in double-quotes and correcting the style rules that were re-declared (margin and margin-bottom) - but apologies for the line-formatting - I couldn't seem to get it to all stay inside the code block on this forum until I took out the line breaks:

    <div style="margin: 5px;width: 653px;border: blue 1px solid;float: left;"><div style="margin: 5px;width: 100%;border: red 1px solid;">z</div><div style="overflow: hidden;margin: 5px;width: 100%;border: red 0px solid;"><div style="margin: 0px;width: 300px;border: red 1px solid;float: left;">y</div><div style="margin: 0px;width: 300px;border: red 1px solid;float: right;">x</div></div><div style="margin: 5px;width: 100%;border: red 1px solid;">q</div>
    
  • Throught what browser did you produce the screenshot? If it's IE, there's a problem with the box model that causes the border width to be ignored when calculating 100% width.

    Either you create an invisible container to size the inner div's or size your inner div to container.width -2.

    Also, try removing the width: 100%; from the div's.

    nullptr : The problem was/is in Firefox 3 and IE7 (didnt test in others). Removing width: 100% fixed my problem

How can I change Windows shell (cmd.exe) environment variables from C++?

I would like to write a program that sets an environment variable in an instance of the shell (cmd.exe) it was called from. The idea is that I could store some state in this variable and then use it again on a subsequent call.

I know there are commands like SetEnvironmentVariable, but my understanding is that those only change the variable for the current process and won't modify the calling shell's variables.

Specifically what I would like to be able to do is create a command that can bounce between two directories. Pushd/Popd can go to a directory and back, but don't have a way of returning a 2nd time to the originally pushed directory.

From stackoverflow
  • In Windows when one process creates another, it can simply let the child inherit the current environment strings, or it can give the new child process a modified, or even completely new environment.

    See the full info for the CreateProccess() win32 API

    There is no supported way for a child process to reach back to the parent process and change the parent's environment.

    That being said, with CMD scripts and PowerShell, the parent command shell can take output from the child process and update its own environment. This is a common technique.

    personly, I don't like any kind of complex CMD scripts - they are a bitch to write an debug. You may want to do this in PowerShell - there is a learning curve to be sure, but it is much richer.

  • MSDN states the following:

    Calling SetEnvironmentVariable has no effect on the system environment variables. To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates. Note that the values of the environment variables listed in this key are limited to 1024 characters.

    Considering that there are two levels of environment - System and Process - changing those in the shell would constitute changing the environment of another process. I don't believe that this is possible.

    Steve Rowe : I don't want to change the global settings, just the ones in the calling shell.
    Michael : Shell in this case is explorer. cmd.exe doesn't respond to WM_SETTINGCHANGE messages.
  • A common techniques is the write an env file, that is then "call"ed from the script.

    del env.var
    foo.exe ## writes to env.var
    call env.var
    
  • There is a way... Just inject your code into parent process and call SetEnvironmentVariableA inside cmd's process memory. After injecting just free the allocated memory.

    Steve Rowe : Thanks. I'll give that a try.

Controls "out of window/chrome" in WPF

Is there a way to have controls/images/etc "out of" the Window/Chrome (ie, Aero's glass) in WPF?

An example of what I mean is the WPF Yahoo Messenger which was released (and then discontinued) awhile back. The WindowStyle looks like it is set to None, but AllowTransparencies/CanResize set to false/true respectively - and the avatar is slightly "out of the window/chrome".

I know I could create my own glass border, but that may be a fair bit of effort to get it looking consistent.

From stackoverflow
  • Yes, I believe you will have to replace window's interface with your own. You can start with transparent window and a grid within leaving some margin around the grid. Then put thumbs, titlebar etc on the grid to simulate window behavior. Margin around the grid will allow you to draw controls outside your "window".

    <Window
    x:Class="TransparentFormDemo.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window2" Height="300" Width="300"
    AllowsTransparency="True"
    WindowStyle="None" Background="Transparent">
    <Grid Margin="20" Background="AliceBlue">
        <Thumb Name="topThumb" Height="5" HorizontalAlignment="Stretch" VerticalAlignment="Top"
               DragDelta="topThumb_DragDelta" Cursor="SizeNS"/>
        <!--Thumbs continued-->
        <Polygon Points="10,110 60,10 110,110" Fill="Blue" Margin="0,-30"/>
    </Grid>
    </Window>
    
    aeoth : Nuts, I was hoping to retain/respect the window chrome regardless of the OS version, but there wouldn't be a way to do that using that method.
    Stanislav Kniazev : Yep, you will lose standard windows themes and I don't think you can draw something outside of window control. Another way to do this is to draw an avatar on completely separate transparent window and stick this window somehow on top of main one so it looks as one single control. It looks doable, but not in pure WPF, you will need at least some PInvoke calls.

Windows Function

In my project i have 2 radio button "File" and "not File" and i also hav a textbox called "width"..

I need to disable the text box when i click on "not file" radio button and once i click "file" radio button it should enable the textbox..

Can u tell me the function in Windows programming in visual c++

EDIT : "Add variable" is disabled when i right click on the textbox

From stackoverflow
  • Attach a CTextBox member variable to your text box. Say m_tbWidth. You can do this by right clicking on the textbox in the dialog designer and selecting "Add variable..."

    In the handler for File, enter the line m_tbWidth.EnableWindow( TRUE );

    And in the handler for NotFile, enter the line m_tbWidth.EnableWindow( FALSE );

Add multiple sections to App.Config

Hi All, I need to add a section to my app.config programmatically. currently i use the Configuration editor where in there is seperate project which contains a class file with al configsection attributes set .I then use the configuration editor access this dll created and add a section .Now i want to access this same ConfigurationClass fill in values programmatically and add multiple sections to the app.config?

Need for this is i have a winForm which contains the server,dbname,usernameand password ,user can connect to multiple databases ovr a server so i need to save this information somewhere .

Thanks ,

From stackoverflow
  • Is the config file the best place for this information? Certainly, updating it programatically could lead to runtime errors, which aren't desireable.

    Can you supply more information about what the different databases are, for example Live / Test etc or just for different aspects within the same environment?

What is the syntax for creating a Dictionary with values as instances of Action<T> ?

I need to create a Dictionary object as a member field
key = string
value = an instance of Action<T> where T could be different per entry, e.g. long, int, string (a ValueType or a RefType)

However can't get the compiler to agree with me here.. To create a member field it seems to need a fixed T specification. I've passed my limit of struggle time before awareness that 'It shouldn't be this difficult'

Might be a generics noob mistake. Please enlighten..

The usage would be something like this

m_Map.Add("Key1", 
   new delegate(long l) {Console.Writeline("Woohoo !{0}", l.ToString();));
From stackoverflow
  • You can't, basically. How would the compiler know what type you were interested in for any particular entry?

    You can't even explain a relationship of Dictionary<Type, Action<T>> where each dictionary entry has a key which is a type and an action which uses that type. Generics just doesn't support that relationship.

    If you will know the kind when you try to use it, you can just make it a Dictionary<string, Delegate> and cast the value when you fetch it. Alternatively, you could use Action<object> and live with the boxing and cast you'll end up with.

    Note that to use anonymous methods or lambda expressions with just Delegate, you'll need to cast - or write a handy conversion method:

    public static Delegate ConvertAction<T>(Action<T> action)
    {
        return action;
    }
    

    That way you can write:

    Delegate dlg = ConvertAction((long x) => Console.WriteLine("Got {0}", x));
    

    or in the dictionary context:

    var dict = new Dictionary<string, Delegate>();
    dict["Key1"] = ConvertAction((long x) => Console.WriteLine("Got {0}", x));
    

    You'll still need to cast to the right type when you fetch the value out of the dictionary again though...

    A different tack...

    Instead of exposing a dictionary directly, you could encapsulate the dictionary in your own type, and have a generic Add method:

    public void Add<T>(string key, Action<T> action)
    

    So it would still be a Dictionary<string, Delegate> behind the scenes, but your type would make sure that it only contained values which were delegates taking a single argument.

    Gishu : Tried that however get a compile-error: "Can't cast anonymous method to type Delegate"...
    Jon Skeet : See the edit I was writing while you commented :)
    Gishu : The only thing that I'm trying to enforce here is that the value should be a method that takes one parameter.
    Jon Skeet : Edited to account for this. (See the bottom.)
    Gishu : I ended doing a variation of what you too proposed.. worked. Just needed your tip of having to jump via an extra method to convert the Action to a Delegate. Thanks
  • With different T per entry, perhaps standardise at Action<object>, and cast inside the actual actions?

        static void Main() {
            var m_Map = new Dictionary<string, Action<object>>();
            m_Map.Add("Key1", obj => Console.WriteLine("Woohoo !{0}", obj));
            m_Map.Add("Key2", obj => SomeMethod((int)obj));
    
            m_Map["Key1"](123);
            m_Map["Key2"](123);
        }
        static void SomeMethod(int i) {
            Console.WriteLine("SomeMethod: {0}", i);
        }
    
    Gishu : and box-unbox my value-types in these generic times.. Sacrilege! :) I must confess that I did think of that in one of my weaker moments whilst I was struggling to get this to work.
    Gishu : +1 for making me benchmark :) [.03 seconds. GC Collections = 3 for Action.Invoke] [2.81 seconds. GC Collections = 70 for Delegate.DynamicInvoke] [.03 seconds. GC Collections = 0 for Action.Invoke] Was surprised that Action runs as fast as Action - but obviously leads to more boxes and casts in code. A snippet of what I needed it for is posted in my resp to http://stackoverflow.com/questions/805505/c-marking-class-property-as-dirty/

    Read html file in variable through javascript in unix (firefox)

    OS: Linux Browser : Firefox

    I need to read a html file content into a string variable through JavaScript ?

    Is it possible in javascript ? If yes, Kindly help me with syntax/method to do this

    From stackoverflow
    • The easiest solution is probably to use the JQuery library.

      http://docs.jquery.com/Ajax/jQuery.get

      $.get("mypage.html", function(data){
        alert("Data Loaded: " + data);
      });
      
    • I think that this should do the trick. It's untested but give it a try.

      document.documentElement.innerHTML
      

      Another approach could be to query the URL through XmlHttpRequest and read the response.responseText

    asp.net: how do I wire up LinkButton-like linking functionality with delegates on a table cell background?

    I'm using ASP.NET user controls. I'm passing values to another user control via command arguments through a link button as follows:

    asp:LinkButton ID="ZoomPhotoLinkButton" CommandArgument='<%#(Eval("conid"))%>' CommandName="PassItemId" runat="server">Zoom It

    What I really want is to make the entire background cell of my table clickable, so that a click anywhere on the table cell would pass the appropriate CommandName and CommandArgument and link appropriately.

    Before I had this set up with delegates, I had the above behavior working as follows with simple JavaScript and inline codehind functions passing URLs to inline JavaScript:

    (I'm using square brackets rather than angle brackets because StackOverFlow's trying to parse my "table code"):

    [td] onclick="window.location='<%# FormatDetailPageUrl((object)Eval("conid"))%>'" style='cursor:pointer;text-align: center; border:0px;'[/td]

    I'm trying to do something functionally equivalent in terms of the click on the table cell, except to invoke the approprate CommandName and CommandArgument vs. simple Javascript.

    Thanks in advance...

    From stackoverflow
    • ASP.Net uses the __doPostBack() function to do this magic. You can call it yourself; the first parameter is the eventTarget, second param is eventArgument.

      So in your case, you can do the following:

      <td onclick="__doPostBack('PassItemId', '<%#(Eval("conid"))%>')"></td>
      

      You might also want to take a look at Page.GetPostBackEventReference

      kendor : Thanks, Nicholas, this is definitely on the right track. The code that you provide above doesn't work exactly: I do get a postback, but my values don't appear to be being passed to load the detail page. It may be a consequence of the fact that the cells are in a user control, and that's tripping things up. I'll do more reading and see if I can't get this working. Thanks again.
      kendor : Another thing that may be tripping me up: I'm trying to invoke this behavior inside of a GridView template...
    • You can probably achieve this client-side, e.g. using jQuery.

      Have a look at this article, which does the same (with DIVs instead of TDs): http://newism.com.au/blog/post/58/bigtarget-js-increasing-the-size-of-clickable-targets/

    settimer vc++

    Hi,plz can anbody explain me how settimer works in vc++,and wat is its parameters?

    thank u.

    From stackoverflow

    How to make a column case sensitive in sql 2005 or 2008

    Is it possible to change the default collation based on a column? i want to make 1 column case sensitive but all the others not

    From stackoverflow
    • ALTER TABLE ALTER COLUMN allows to change collation for a single column:

      alter table Foo alter column Bar ntext collate Latin1_General_CS_AS
      

      (collation might be incorrect)

      Eric : A note about collation: I've had to write way too many COLLATE statements as a result of a source table being Latin1_General_CS_AS and one being Latin1_General_CI_AI. This really only applies if you use SSIS to move data around, or at least, that's the only spot I've ever hit an issue in.
    • I don't specifically know SQL Server, but the generally accepted DBMS practice (for compatibility) would be to either:

      • put insert and update triggers on the table so that they're stored in the case you want.
      • use generated columns to store another copy of the column in the case you want.

      There may be a faster way to do it in SQL Server but you should be careful of solutions that push workload into the SELECT statements - they never scale well. It's almost always better doing this as part of inserts and updates since that's the only time data changes - doing it that way minimizes the extra workload.

    How do I erase passwords from memory when using Username tokens with JBossWS?

    I'm using JBoss Web Services for a payment service application. At some point I need to make remote SOAP calls to a payment service provider, and I need to authenticate with a Username token.

    The only way I know how to do this with JBossWS is like this:

    Map<String, Object> requestContext = ((BindingProvider)port).getRequestContext();
    requestContext.put(BindingProvider.USERNAME_PROPERTY, "foobar");
    requestContext.put(BindingProvider.PASSWORD_PROPERTY, "changeme");
    

    But the problem here is that the "changeme" password is now in memory as a String object and I have no control on when, if ever, it will be garbage collected. If an attacker dumps memory at this point he can find the credentials.

    Is there another way to make secure SOAP calls with JBossWS, where I can control how long a password remains in memory?

    From stackoverflow
    • I'm pretty sure there isnt a way. Strings are immutable in Java, so you wont be able to rewrite the String. You could use a byte array to store the password, and that byte array could be rewritten. But you will probably have to convert it to a String at some point anyway ...

      On the other side, if an attacker has enoug access to your machine to get a memory dump, than you are screwed anyway. If the attacker already has that much access, he can do pretty much whatever he wants ...

    Spring Integration: Hooking web services to a FIFO queue

    I'm still struggling with Spring Integration- here's my scenario:

    1. A web service gets a request from client A
    2. web service puts the request onto a queue
    3. A queue consumer processes the messages FIFO and sends a response that gets routed back to the web service
    4. Web services sends response back to client A

    There will be multiple web services all feeding messages onto this queue, and I need to ensure that they are truly processed in the order that they're received.

    What pieces of Spring Integration do I need to wire together?

    From stackoverflow
    • Note sure about Spring Integration but Java 5 has a number of BlockingQueues that can handle FIFO.

      Mike Sickler : Thanks, but I'm looking for a Spring Integration answer, and in particular a solution to the problem of hooking up a web service to a queue
    • The problem ist not spring. I think you will need a queue with elements containing the request and offering a response. But the response need to block until the element is dequed and processed. So the queue element looks like:

      public class BlockingPair {
        private final RequestBodyType request;
        private ResponseBodyType response;
      
        public BlockingPair(RequestBodyType request) {
          this.request = request;
        }
      
        public RequestBodyType getRequest() {
          return request;
        }
      
        public ResponseBodyType getResponse() {
          while (response == null) {
            Thread.currentThread().sleep(10);
          }
          return response;
        }
      
        public void setResponse(ResponseBodyType response) {
          this.response = response;
        }
      }
      

      The webservice enqueing creates the BlockingPair with its request body. Than pushes the BlockingPair element to the queue. Afterwards it creates the response getting the response body from the BlockingPair, but blocks.

      The consumer deques one BlockingPair and sets the response body. From there the webservice continues writing the response.

      You need three beans: webservice, a blocking queue and the consumer. Both webservice and consumer need the queue as bean property.

      The queue and the consumer beans need to be planed in the application context (as initilialized by the ContextLoaderListener). The queue needs a bean id to be references by the webservice (which has its own context, but the application context as a parent so the queue reference can be referenced):

      Part of the web.xml:

      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/WEB-INF/applicationContext.xml</param-value>
      </context-param>
      
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      
      <servlet>
        <servlet-name>service</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
      </servlet>
      
      <servlet-mapping>
        <servlet-name>service</servlet-name>
        <url-pattern>/*</url-pattern>
      </servlet-mapping>
      

      The applicationContext.xml contains two beans:

      <bean id="queue" class="java.util.concurrent.LinkedBlockingQueue"/>
      
      <bean id="consumer" class="...">
        <property name="queue" ref="queue"/>
      </bean>
      

      The webservice has its own context definition, here service-servlet.xml:

      <bean id="endpoint" class="org.springframework.ws.server.endpoint....PayloadEndpoint">
        <property name="queue" ref="queue"/>
      </bean>
      

      For more information on defining a spring ws endpoint, see the spring tutorial.

      The consumer need to be a background task, so i would prefer quartz, for spring integration see here.

      Mike Sickler : As I say in the question, I'm looking for a Spring Integration solution. Spring Integration has queues and other classes, but I'm not sure how to wire them together.
    • Based on the Javadoc for the QueueChannel here's my attempt at it. This does not address the web service configuration, just the code that would go in the web service back end implementation.

      This is the code that would add something to a queue (your web service).

      public class TheWebService {
      
        // Could also use QueueChannel, or PollableChannel here instead
        // just picked the most general one
        private org.springframework.integration.channel.MessageChannel queue;
      
        public void yourWebServiceMethod(SomeArg arg) {
           SomeObjectToPassThatExtendsMessage passed = someInitialProcessing(arg);
           queue.send(passed);
        }
      }
      

      This is the code that would go in your receiver/processor/dequeue class

      public class TheProcessor {
      
        // Could also use QueueChannel here instead
        // just picked the most general one
        private org.springframework.integration.channel.PollableChannel queue;
      
        // This method needs to be setup to be called by a separate thread.
        // See http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/scheduling/package-summary.html
        // and it's sub-packages.
        public void someProcessingPoller() {
           SomeObjectToPassThatExtendsMessage passed = queue.receive();
           // Do some processing with the passed object.
        }
      
      }
      

      The Spring configuration for this would look something like

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans">
      
        <bean id="webService" class="mypackage.TheWebService">
            <property name="queue" ref="queue" />
        </bean>
      
        <bean id="processor" class="mypackage.TheProcessor ">
            <property name="queue" ref="queue" />
        </bean>
      
        <bean id="queue" class="org.springframework.integration.channel.QueueChannel"/>
      </beans>
      
    • I can't help you with Spring Integration, but perhaps you need to give your architecture a second thought. In ESB systems you usually place a message in a Queue, when you know that the processing of the message will take considerable time or if you aren't certain that the remote end is ready (another reason is to bridge incompatible components). When you add the message to the queue, you immediately return to the requester indicating that the message is received, but not providing the result of the operation. The requester would then need to poll for the result or you could alternatively provide some sort of "push" functionality.

      So, if the processing of the messages in the Queue takes a lot of time, I recommend to modify your architecture. It is not common for a Web Client to wait long times for the reply and many requests could also timeout.

      If on the other hand the processing of the messages is quick and reliable, then using Queue channels is not needed. Have all your messages communicate with a central component (JEE Session Bean, Spring Bean, web service) and implement a queue mechanism yourself. They are already answers covering how you could do this.