Monday, April 25, 2011

Read error response body in Java

In Java, this code throws an exception when the HTTP result is 404 range:

URL url = new URL("http://stackoverflow.com/asdf404notfound");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getInputStream(); // throws!

In my case, I happen to know that the content is 404, but I'd still like to read the body of the response anyway.

(In my actual case the response code is 403, but the body of the response explains the reason for rejection, and I'd like to display that to the user.)

How can I access the response body?

From stackoverflow
  • I know that this doesn't answer the question directly, but instead of using the HTTP connection library provided by Sun, you might want to take a look at Commons HttpClient, which (in my opinion) has a far easier API to work with.

  • First check the response code and then use HttpURLConnection.getErrorStream()

  • Here is the bug report (close, will not fix, not a bug).

    There advice there is to code like this:

    HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
    InputStream _is;
    if (httpConn.getResponseCode() >= 400) {
        _is = httpConn.getInputStream();
    } else {
         /* error from server */
        _is = httpConn.getErrorStream();
    }
    
    matt b : Does indeed seem "as expected" given the API design, sounds reasonable to me
    Stephen Swensen : Wouldn't you want to get the error stream when the response code is >= 400, rather than the other way around?
    TofuBeer : @Stephen yeah, I assume so, but I just grabbed the code at the link...
  • InputStream is = null;
    if (httpConn.getResponseCode() !=200) {
        is = httpConn.getErrorStream();
    } else {
         /* error from server */
        is = httpConn.getInputStream();
    }
    

How to replace a character with a newline in Emacs

In Emacs, I tried to replace a character say ";" with a new line using replace-string and/or replace-regexp.

Below commands are what I have tried.

M-x replace-string ; \n   (will replace ";" with 2 characters "\n" )

M-x replace-regex ; \n ( get below error from minibuffer )

Invalid use of `\' in replacement text.

Is there anything wrong using replace-string. Or if there is any other way to do that? Thanks.

From stackoverflow
  • M-x replace-string ; C-q C-j
    

    C-q for quoted-insert

    C-j is a newline.

    Cheers!

    Joe Casadonte : C-q is really `quote-insert` which quotes the next character.
    Bryan Oakley : I believe it's actually "quoted" rather than "quote", as in "quoted-insert". At least that's the way it is on version 22.1.
    jrockway : yes, you're right. fixed.
    Jonathan Arkell : Whups! Thanks guys
  • Don't forget that you can always cut and paste into the minibuffer.

    So you can just copy a newline character (or any string) from your buffer, then yank it when prompted for the replacement text.

    Lei : It's really a good idea for the characters which I don't know the key bind.

Debug error when calling a Storyboard to Start.

I have some storyboards in XAML (WPF Project) and I´m calling them from the VB code with this:

Dim ServiceOff As Storyboard = DirectCast(FindResource("ServiceStopped"), Storyboard)
ServiceOff.Begin()

I´m getting the following error when trying to build:

Overload resolution failed because no accessible 'Begin' accepts this number of arguments.

Any ideas?

From stackoverflow
  • I answered in your other question.

    You need to call ServiceOff.Begin(me) if you're not using .NET 3.5 SP1

    TuxMeister : Thanks, seems to accept it that way but I´m getting tons of other errors and I think I messed up somewhere else. It´s a simple test app so I´ll start over in a cleaner way. Thanks again for the help! Oh, and sorry for the double post, though you couldn't see the new comments on old posts. thanks!
    Ray : No problem, I'll fix up your question too.
    Ray : Oh, and the best thanks is an upvote and accepted answer :)

Css: apply style to first level of TD only

Is there a way to apply a Class' style to only ONE level of td tags?

<style>.MyClass td {border: solid 1px red;}</style>

<table class="MyClass">
  <tr>
    <td>
      THIS SHOULD HAVE RED BORDERS
    </td>
    <td>
      THIS SHOULD HAVE RED BORDERS
      <table><tr><td>THIS SHOULD NOT HAVE ANY</td></tr></table>
    </td>
  </tr>
</table>
From stackoverflow
  • I guess you could try

    table tr td { color: red; }
    table tr td table tr td { color: black; }
    

    Or

    body table tr td { color: red; }
    

    where 'body' is a selector for your table's parent

    But classes are most likely the right way to go here.

  • Is there a way to apply a Class' style to only ONE level of td tags?

    Yes*:

    .MyClass>tbody>tr>td { border: solid 1px red; }
    

    But! The ‘>’ direct-child selector does not work in IE6. If you need to support that browser (which you probably do, alas), all you can do is select the inner element separately and un-set the style:

    .MyClass td { border: solid 1px red; }
    .MyClass td td { border: none; }
    


    *Note that the first example references a tbody element not found in your HTML. It should have been in your HTML, but browsers are generally ok with leaving it out... they just add it in behind the scenes.

    Nick Presta : Your first snippet (using the child selector) doesn't appear to work in Firefox 3.0.1. I get a red border around the 'THIS SHOULD NOT HAVE ANY' part.
    bstoney : This doesn't work in Chrome either
    nickf : your second example is correct, but your first example would put borders on everything. ".MyClass > tr > td" would probably work (in good browsers)
    bobince : oop. My fingers done gone wrong. ;-) thanks for the catch, fixed
    Nick Presta : Your first snippet doesn't apply _any_ red border in any 'good' browser (Fx 3.0.1, Chrome).
    Shog9 : The phantom TBODY strikes again...
    Nick Presta : I thought it might be that but I wasn't sure. Fixing it to '.MyClass>tbody>tr>td' does indeed work. :-)
    bobince : oh FFS. Thanks Shog — I think I need some more sleep. Amazing anyone still voted it up, eh? ;-)
    Simon Buchan : Hey, it *looks* good...
  • This style:

    table tr td { border: 1px solid red; }
    td table tr td { border: none; }
    

    gives me:

    this

    However, using a class is probably the right approach here.

    thomasrutter : Using a class on every single td element may be a little redundant, you'd probably use a class on the containing table element, and then you'd still have to exclude second levels of tables - ie your first example is correct.
  • Just make a selector for tables inside a MyClass.

    .MyClass td {border: solid 1px red;}
    .MyClass table td {border: none}
    

    (To generically apply to all inner tables, you could also do table table td.)

  • how about using the CSS :first-child pseudo-class like: .MyClass td:first-child { border: solid 1px red; }

Eric Schmidt's aspects of e-mail not in Twitter

In Google CEO Eric Schmidt's comments about twitter he highlights some aspects of the e-mail system that twitter lacks.

The aspects of e-mail he mentions are:

  • storage
  • revocation
  • identity

Could anyone explain these aspects of the traditional e-mail system? I'm interested in creating a twitter-like system and would like to better understand existing communication protocols and their abilities/characteristics.

From stackoverflow
  • Since after 6 hrs. no one has answered this I'll give it a try.

    • storage

    Well you can't store your tweets the same way you can store your e-mail, do you?

    • revocation

    Mmhh, perhaps because in an e-mail you can take back some comment or discuss back and forward about some topic keeping the thread in one place.

    • identity

      The email identifies you as a user in a domain ( user@domain ) hence creates an on line identity. Twitter does not ( at least yet )

    Twitter didn't include these kind of features because its nature was well, not being an e-mail susbtitute.

    web-forums ( like this ) also evolved from the e-mail system, where all the questions/answers use the e-mail as communication channel.

    Rex M : I don't know about the identity one. rexm@twitter is as globally unique as rex@rexmorgan.net. Just one is more commonly accepted.
    Daniel Gill : For storage, on twitter one can still see the history of their tweets, no? Interesting take on revocation. And I would agree with Rex's idea of on-line identity.
    OscarRyz : @Daniel: Not like in e-mail ( at least not like gmail :P ) @Both: On the identity, I don't know my self either. I move from Yahoo to gmail once, so I was not so tied to the e-mail after all. But definitely my work e-mail and my friends e-mail are used as my web identity. Only time will tell

Is "regex" in modern programming languages really "context sensitive grammar"?

Over the years, "regex" pattern matching has been getting more and more powerful to the point where I wonder: is it really just context-sensitive-grammar matching? Is it a variation/extension of context-free-grammar matching? Where is it right now and why don't we just call it that instead of the old, restrictive "regular expression"?

From stackoverflow
  • In particular backreferences to capturing parentheses make regular expressions more complex than regular, context-free, or context-sensitive grammars. The name is simply historically grown (as many words). See also this section in Wikipedia and this explanation with an example from Perl.

    SealedSun : Could you please explain the difference between `regular language` and `regular expression`?
    notnot : Is it really more powerful than CSG? Could you give an example?
    Fabian Steeg : A regular language can be described by a regular grammar (see http://en.wikipedia.org/wiki/Regular_grammar), while regular expressions are a pattern matching language that is less restricted and therefore more complex to process.
    Fabian Steeg : Thanks for your comment notnot, I've added a link to a sample and some details.
    notnot : Hmmm... does this mean that we can match against arbitrary CSG's using today's tools.
    Fabian Steeg : Hm, not really sure what you are asking but I believe no, it simply means some regular expressions can't even be described with a CSG and so can't be parsed by a linear bounded automaton.
    notnot : Where are the boundary lines, then, on our regex tools? How can we write expressions that defy the limits of CSG's and yet not be able to express all CSG's?
    Fabian Steeg : I don't know, I just meant to say that the fact that some things work that cannot be expressed by a CFG does not necessarily imply that all things that can be will work too.
    13ren : Hey, I like the idea of defining "regex" as distinct from "regular expressions", and not just a contraction. Problem is, it still looks like a contraction.
  • The way I see it:

    • Regular languages:
      • Matched by state machines. Only one variable can be used to represent the current "location" in the grammar to be matched: Recursion cannot be implemented
    • Context-free languages:
      • Matched by a stack machine. The current "location" in the grammar is represented by a stack in one or another form. Cannot "remember" anything that occurred before
    • Context-sensitive languages:
      • Most programming languages
      • All Most human languages

    I do know of regular expression parsers that allow you to match against something the parser has already encountered, achieving something like a context-sensitive grammar.

    Still, regular expression parsers, however sophisticated they may be, don't allow for recursive application of rules, which is a definite requirement for context-free grammars.

    The term regex, in my opinion, mostly refers to the syntax used to express those regular grammars (the stars and question marks).

    notnot : Lookahead/lookbehind and naming definitely add something that sits outside of standard regular expressions - memory. So aren't we at PDA level?
    Fabian Steeg : It's not in general true that natural language is context-sensitive, see http://www.eecs.harvard.edu/~shieber/Biblio/Papers/shieber85.pdf
    notnot : ah, that's the good stuff
    SealedSun : Fascinating, thx for the link.
  • There are features in modern regular expression implementations that break the rules of the classic regular expression definition.

    For example Microsoft’s .NET Balancing Group (?<name1-name2> … ):

    ^(?:0(?<L>)|1(?<-L>))*(?(L)(?!))$
    

    This does match the language L₀₁ = {ε, 01, 0011, 000111, … }. But this language is not regular according to the Pumping Lemma.

    notnot : I know that it goes beyond classic regex, but I'm wondering how much further. Fabian's link above is interesting.

SQL Server Timeout troubleshooting

I have a web service that's been running fine without modification for a couple of years now. Suddenly today it decides that it would not like to function, and throws a SQL timeout:

System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Interesting to note that this web service lives on the same server as the database, and also that if I pull the query out of a SQL trace and run it in management studio, it returns in under a second. But it's timing out after exactly 30 seconds when called from the web service without fail. I'm using the Enterprise Library to connect to the database, so I can't imagine that randomly started failing.

I'm not quite sure what could suddenly make it stop working. I've recycled the app pool it's in, and even restarted the SQL process that I saw it was using. Same behavior. Any way I can troubleshoot this?

UPDATE: Mitch nailed it. As soon as I added "WITH RECOMPILE" before the "AS" keyword in the sproc definition, it came back to life. Bravo!

From stackoverflow

Longest path between from a source to certain nodes in a DAG

Hi Experts, How do i find the longest path from single source to all final destinations i.e. For source i1, Give longest path between i1 -> o1 and i1 -> o2.

alt text

The legends described in the above graph are as follows: (i1, i2) are start nodes (o1, o2) are end nodes (1-8) are sub graphs The edges may have +ive/-ive weights

The longest paths in this network are in the following order:

Worst path: i1 -> 1 -> 4 -> o1

Then, all paths i1 … -> … o1

Then i1 -> 5 -> 6 -> o2

Need a way to ignore selection of (i1 -> 3) or (3 -> 4) subnetworks even though they are longer than i1 -> 5

From stackoverflow
  • Wikipedia to the rescue! Their page on this problem indicates that in the general case, your problem is NP-Complete. However, since you have a directed acyclic graph, you can invert all the edge weights and run the Bellman-Ford algorithm to solve it. The B-F algorithm normally computes single-source shortest paths in a graph. With inverted edge weights, it should produce the longest paths.

    funkyprogrammer : Thanks Kristo. But as the graph is DAG therefore wont B-F will be costly? The graph is quite sparsely populated so V*E could become expensive. I am already trying Dijkstra's which serves the purpose of given longest paths but looking for a way to filter out extra edges.
    j_random_hacker : @Kristo: The algorithm you gave in your update won't produce the maximum-weight path on a general DAG, as it favours paths containing few edges. But if all paths have the same number of edges it will work fine.
    Kristo : Can you explain why? Dijkstra's Algorithm seeks to minimize the cost of the path, not the number of edges. It cannot handle cycles, but the OP already said his graph was acyclic.
    j_random_hacker : If you add abs(most-negative edge weight) (say z) to each edge, you effectively add k*z to each path with k edges. Dijktra will find the minimum over all paths P of the expression (-sum(edges in P) + |P| * z), which is different than minimising (-sum(edges in P)) if |P| can vary.
    Kristo : Ok I understand. I've reverted my changes. I suppose if my suggestion would have worked, then Wikipedia would have suggested it instead of Bellman-Ford. :-)
    j_random_hacker : It's a tricky one... One of those approaches that feels like it *should* work! :)

Simple document management system and API

In my software I need to be able to interface to a very simple document management system.

I need to be able to:

  1. Check in/out documents
  2. Add documents
  3. delete documents
  4. maybe version documents. (The domain expert says no, I suspect he is wrong.)

At this time we have no need to search the documents.

I need to be able to do this from a C# program so there must be a .net API.

I need to have more than one client be able to do this at a time.

I will eventually need to be able to do this from a web connection as well. But only later.

This is part of a larger application that, so I must be able to keep costs low. I don't think I need anything as complex as Documentum or the higher-end DM products.

The customer will be selling the application, so there must be a friendly re-seller agreement.

Is there anything out there like this?

From stackoverflow
  • In regards to the need to version documents: your domain expert is definitely wrong. Not only will users eventually ask for this or need to merge something, but once you establish the other requirements, versioning is pretty simple to add as well so you might as well go for it.

    Perhaps you could just put a C# front end on a subversion repository.

    Khadaji : Likely you are right - but you've worked with clients before, eh? :) I expect to need it - what's more, I doubt I'd find a DM that had the others and not that.
  • Why not use WSS (Windows SharePoint Services) it's free with Windows Server and provides all the functionality and API's that you're looking for to manage documents, Check In/Out version control, work flows and much more. It also already has built in admin interfaces.

    Khadaji : Thank you, that is interesting. I looked at Sharepoint, but found a Sharepoint server to be too costly for this product's pricepoint to bare. But if I'm following correctly, Sharepoint services are part of the Windows Server. I will investigate.
    James : MOSS is what you have to pay extra for, WSS is free with Windows Server 2003. WSS is all you need for what you're after.
  • Share point based solutions are the most cost effective out there right now. If you're looking to sell a product, you're probably too late. There are A LOT of document management systems that have veered away from the Documentum platform. Check out NextDocs for a pretty good SharePoint based solution.

    Khadaji : LOL. No, document management is a small requirement of an overall product. Not the end-goal.
  • Why don't you try out Alfresco. They provide quite a nice set of API capabilities as well (includes web services which can be used in .NET).

    Regarding the reseller agreement - not sure of this one.

What is the best open source application written in PHP to reference for 'good code'?

So I've read Drupal, Joomla, Magento, Wordpress all have bad PHP code... which is a shame because I was referring to them to see 'what they did' so I could hopefully get some insight. I assumed popular software meant it would have decent coding.

So, what is the best PHP open source application to study?

From stackoverflow
  • Magento is based on Zend Framework - so I'm surprised that it's considered to have "bad code". Drupal has continual, terrible security holes due to its bad code!

    alex : I think because it is abundant with singletons... just my guess.
    Ionuț G. Stan : Building an application on top of a framework does not guarantee good architecture. Not to mention that ZF is somewhere between framework and components repository.
  • Take a look at the Zend Framework; it's huge, but I've picked up some useful tips just from reading their coding style guide and their reasoning behind it.

  • You can also look at the ModX CMS, it's a nice simple clean cms. The api is well documented, and the code seems nice and clean.

    stesch : I like MODx, but the code isn't that good. Have you actually read it? There are C style for-loops where you should use a foreach, for example.
  • Joomla is not exactly an example of good php code. Mediawiki, the software used by the wikipedia is pretty much better.

    alex : I did hear it once had a vulnerability with preg_replace and the e (evaluating) flag in a regex. But I'm sure it's been fixed.
  • Don't study just one. Study two or three and compare them. I'm always learning better when I consult multiple materials. That being said I recommend you to look at the major frameworks (in no particular order):

    • Zend Framework
    • Symfony
    • CodeIgniter
    • ezComponents
    • CakePHP
  • I think the best code example in PHP is WordPress. I studied it when I wasn't already a newbie in PHP, but I think it's even possible to learn this language by reading the code.

    Brian Clozel : Wordpress, seriously? alex is asking about good practices and patterns. I'm not sure Wordpress qualifies for this (especially for a CMS related software...).
    alex : Maybe it might help a *little* when just starting out, but I like to thing I'm a little more accomplished then that.
    thomasrutter : Wordpress is successful as a product, but an example of 'good code' it most definitely ain't.
  • CakePHP is worth a look too, especially if you need to support PHP4 in addition to PHP5, and the comunity is very active which is good if you need explanation or advice.

  • I'd strongly suggest to take a look at Yii framework.

    1. Its PHP5 only and purely OOP
    2. Code is perfectly commented (also good if you use Eclipse PDT for intelisence)
    3. I've got lots to learn and seeing how well engineered the framework is teaches me a lot.
    4. The framework makes use of PHP magic methods to dynamically modify/extend behavior of classes (e.g. AR or adding behaviors to classes (sort of multiple inheritance))
    5. Follows MVC way of thinking
    6. Learning curve isn't high

    All in all, give a look, its worth it;)

Using scandir() to find folders in a directory (PHP)

I am using this peice of code..

$target = 'extracted/' . $name[0];  
$scan = scandir($target);

To scan the directory of a folder which is used for zip uploads. I want to be able to find all the folders inside my $target folder so i can delete them and there contents, leaving only the files in the $target directory.

Once i have returned the contents of the folder, i dont know how to differentiate between the folders and the files to be able to delete the folders.

Also, i have been told that the rmdir() function cant delete folders which have content inside them, is there anyway around this?

Thanks, Ben.

From stackoverflow
  • First off, rmdir() cannot delete a folder with contents. If safe mode is disabled you can use the following.

    exec("rm -rf folder/");
    

    Also look at is_dir()/is_file() or even better the PHP SPL.

    Ben McRae : your remove function worked a treat! what does rm -rf actually do? thanks
  • To determine whether or not you have a folder or file use the functions is_dir() and is_file()

    For example:

    $path = 'extracted/' . $name[0];
    $results = scandir($path);
    
    foreach ($results as $result) {
        if ($result === '.' or $result === '..') continue;
    
        if (is_dir($path . '/' . $result)) {
            //code to use if directory
        }
    }
    
    Ben McRae : This is brilliant, works perfectly! Unfotunatly i dont understand what this part does 'if ($result === '.' or $result === '..') continue;', would you mind explaining please. Thanks again.
    : @Ben McRae: This is because scandir returns the results "." and ".." as part of the array, and in most cases you want to ignore those results, which is why I included that as part of the foreach
  • $directories = scandir('images');
    foreach($directories as $directory){
        if($directory=='.' or $directory=='..' ){
            echo 'dot';
        }else{
                echo $directory .'<br />';
    }
    } 
    

    a simpler and perhaps faster version

Hosted wiki using StackOverflow-like editing tools?

We're starting developer documentation for one of our projects, and I'd like to set it up as a hosted wiki.

There will be lots of code samples, and the WMD/Prettify combination used here on StackOverflow is the simplest way I've seen to enter structured text (with headings, etc.) combined with automatically formatted code blocks.

Does anyone know of an existing hosted wiki service that uses this editing toolset, so we don't have to write our own (at least not right away)?

Thanks

From stackoverflow
  • Many wiki engines are open source

    Why not grab your favourite and add in the WMD editor?

    Screwturn.eu is a nice C# wiki with a great extensibility model, and a great markup pipeline what should be simpl-ish to upgrade to WMD

    Download v3 beta and look at /core/Formatter.cs and /core/FormattingPipeline.cs for the REGEX's to compose pages from WMD markdown

    And /WebApplication/Editor.ascx for the editor custom control, which you can plug in WMD with some LH-RH code

    Herb Caudill : Thanks- I'm looking for a hosted service on a subscription model. I'm not looking to customize and run a wiki on my own servers for now.
  • Check out Mindtouch's DekiWiki. They use fckeditor, I believe, which is pretty user friendly. There is a free hosted version (with limited extension features), and you can pay for very powerful version.

    We use it for documentation internally and it is excellent.

How long did it take you to learn LINQ to SQL?

I didn't see any questions that asked this previously so here goes:

Once you made (or had) the decision to start using LINQ to SQL how long did it take you to learn it's ins and outs?

We're looking at using it at my organization but my superiors are concerned with the initial time cost (learning it). Hours would be the most useful of answers but any insight would be appreciated.

Bonus question: how much time has LINQ saved you since you started using it?

From stackoverflow
  • I don't have any specific metric, but I can say for sure that on the first project I used it, it saved me on the first 2 week sprint more than I spent learning.

    Ps. you will find a gotcha as with any approach you use, just stay away of tables with no keys :)

  • It only took me about 8-10 days to complete a production website for a client using LINQ, never having used it before. I'd guess no more than 50% of that time was spent learning linq.

    Now I don't feel that it qualifies me as an expert by any means, but getting productive was very quick and painless.

    Having learned it however, I'll be less likely to choose it again for future projects - preferring instead to stick with my own CRUD classes, stored procedures and the SQLDataReader method of accessing data.

    : Hi E.J., I'd love it if you could you go into more detail about why you do not prefer LINQ to SQL. Thanks for your input as well.
    EJB : I was already comfortable with my own custom stuff; but wondered I was missing out on something not using LINQ...I wasn't. Didn't save me anytime, and performance was not as good; sqldatareader is the fastest method to use anyway so I stick with what I know this time around, but its good to try it.
    EJB : (continued) I also do all my data access thru SP's to SQL server and even though linq can do this, it becomes an unnecessary layer of complexity in that scenario.
  • You can learn LINQ to SQL in the subway coming back from work :). Seriously, it really doesn't take any time learning it (1-2 days max), and it's gonna save you a lot of your time!

    achinda99 : You can learn the basics in a good 4 hours. Advanced stuff is depended on your Googlefu but I wouldn't put it past some good keywords.
    : This was the feeling I was getting. I probably should have asked how you learned it as well. Thanks Amokrane.
    Amokrane : @benrjohnson: I learned it through a webcast from the Microsoft Techdays (but it's in french :/) + an other article written in french as well from http://www.developpez.com/, so I don't think it's gonna be helpful for you :). But any good tutorial on the internet could help!
  • I've messed around with it for probably a couple weeks altogether, and I'm not comfortable enough with it to say I've "learned" it. I'm unpursuaded that it provides a benefit for me, but I know SQL pretty well, and that took a long time. I think in the long run SQL solutions will provide better solutions more quickly, but LINQ may save you some of the time investment.

    It has yet to save me any time, but then I don't have much trouble coming up with a quick SQL solution.

  • It takes no time at all to learn the basics of LINQ to SQL, now learning to deal with the shortcomings of the DBML designer and some of the quirks with LINQ to SQL itself is pretty much an ongoing process. I would say that the benefits greatly outweigh it's deficiencies.

    As far as the time it has saved is concerned, like any ORM it saves a fair amount of time, I can't say exactly how much but a considerable amount compared to say having to design your models and objects with IBatis.
    You may want to consider the Entity Framework as well.

French letters on an aspx page

I have a winForm application that generates an .aspx file based on the user input in the application. The problem happens when a user enters the French letters like "é", "à", "è", "â", "ù", "ô", "ê" and "ç". It is supposed to look like a simple text on the page but it doesn't. Any ideas?

From stackoverflow
  • What does the text look like? Have you ensured the encoding type supports extended characters?

  • Assuming you want the characters to be displayed with the accents, circumflexes, etc. try the following:

    Add the following to the <head> of each (generated) page:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    

    Make sure that the .aspx files themselves are saved as UTF-8 files.

    Note: I'm assuming here that an .aspx file is somewhat similar to a .jsp file. If that assumption is false, you should probably ignore this advice.

    Ivan : I was constantly trying that meta tag with charset=UTF-8, but haven't set the encoding of my textWritter, like you and the others suggest. So I think that TextWriter tw = new StreamWriter("Default.aspx", false, Encoding.UTF8); will do the trick.
  • How are you creating the .aspx file? If you're using a TextWriter, check the Encoding. If you're trying to write an array of bytes to a FileStream, be sure you use the right encoding when converting from String to Byte[]. UTF-8 is usually the best encoding for the web.

how to get the output in column wise in a below batch file

how to get the output in column wise in a below batch file

@echo off
setlocal enableextensions enabledelayedexpansion
set Counter=0
for /f "usebackq tokens=2,5,6 delims= " %%a in (`findstr /c:"Cod " 

1231.txt`) do (        
set x=%%b
set x=!x:~3!
set y=%%c        
if %%c LSS 10 set y=!y:~1!
set item!Counter!=%%a-!x!#!y!        
set /a Counter+=1
)
set result=%item0%
for /l %%i in (1,1,!Counter!) do set result=!result!!item%%i!
FOR /F %%A IN ('CHCP') DO SET CHCP=%%A
echo  %result% >>result.txt
endlocal
From stackoverflow
  • Looks like you are concatenating the values into the result variable. Rather than:

    ... do set result=!result!!item%%i!
    

    Why not output the value directly to your output file:

    ... do echo !item%%i!>>result.txt
    
    : thank you I added the syntax what you give me. but inresult first line skipping. means i need to get the result 660-936330#9 660-936340#10ut it is notgiving result from first line it is giving from 2nd line only.
    Dave Cluderay : That's alright. The line above (set result=%item0%) was covering that first one. Change it to: echo %item0%>result.txt
    Dave Cluderay : Or instead, change the original line to: for /l %%i in (0,1,!Counter!) do echo !item%%i!>>result.txt

What's the best way to format source code on IMs to preserve indenting?

Is there a way to preserve indenting in instant messengers when you are pasting source code to a co-worker?

In particular I'm trying to write some python code via google talk, but all tabs are removed.

From stackoverflow
  • Paste the code into http://pastebin.com and get a short link to use in an IM or IRC conversation. (Disclosure: I run that site, "other pastebins are available!" :)

    Brian R. Bondy : Is there a private option?
    Paul Dixon : sort of, just make up a domain like http://brianbondy.pastebin.com

ASP.NET AJAX 3.5 and IE6?

I recently upgraded an ASP.NET app to .NET 3.5 and switched to the newer version of the ASP.NET AJAX library.

In FireFox and IE7, everything works great, in IE6, anything that would perform a callback (Partial Refresh, or calling a PageMethod/WebMethod) throws an error:

Object Doesn't support this property or method
Line: 5175
Char: 9

Is there a known compatibility issue with .NET 3.5 and IE6?

EDIT:

I attached a debugger to IE6 and was able to find the exact line it is breaking on:

 this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), true /*async*/);

It appears that IE6 is denying the permission to do "open". This is not a cross-site request, so I am puzzled. This site is currently running on a fake hostname mapped to a local server, and not on an actual domain, but I don't think that should make a difference.

EDIT: I added a bounty, this bug is still driving me nuts...HALP!

EDIT:

Solution found!

This forum post made me curious enough to search for MXSML, and sure enough, there it was, a typo in the framework library.

MsXML was typed as MXsml.

Of course, when dealing with assembly scripts, you can't do much to fix them, but I installed SP1 hoping that they were corrected there. They were...So, if you have this issue, install .NET 3.5 SP1 and it will go away.

Woo!

From stackoverflow
  • According to MSDN IE6 is supported. Make sure that the Internet Zone in the Security Zones settings are set to Medium.

    FlySwat : I've even tried "Low".
    notandy : The only other thing I'm turning up is that there could be a javascript function with the same name as a control on the page.
    annakata : that sounds quite possible - namespace pollution can be a real problem on large apps
  • How are you testing in IE6? I have come across several javascript errors when you using anything but a clean install of only IE6 in conjunction with the asp.net ajax libraries. (ie. the asp.net ajax libraries don't support multiple installs of IE, or even IETester)

    It is something in the IE security model that makes things go haywire when multiple version's of IE are used. You'll find that cookies won't work right either in anything but the "installed" version of IE on the system you are running.

    You may also look here for some more information on multiple IE installs. If found the comments to be particularly helpful!

    UPDATE I was able to dig, this up in the asp.net fourms. That's the only other thing I could find. May not be too be too helpful, but it at least sounds about like what you are hitting.

    FlySwat : Single install of IE, verified on several test lab machines too.
    Josh : Hmm, well that does make things interesting.. just found one resource though. Added it to my answer
    FlySwat : The forums link points to the same issue I am having...MXSML instead of MSXML. I am reinstalling the framework, hopefully that corrects the issue.
    FlySwat : Upgraded to SP1 and that typo is fixed, as well as it now works.
  • Another one from the asp.net forums

    http://forums.asp.net/p/1376680/2896886.aspx

    Could be caused by different versions of the XmlHttpRequest object

Atomic or Gigantic

If you are planning to write a very parallel application in C#, is it better to build things very small, like

20 small classes, making 40 larger classes, and together making 60 more, for a total of 120

or gigantic like:

making these 60 classes individually (still with reusability in mind).

So in #2 these 60 classes can contain methods to do things instead of other classes.

From stackoverflow
  • Smaller pieces are easier to test, easier to refactor, and easier to maintain.

  • Abstractly, neither one of those approaches would make a difference.

    Concretely, minimizing mutable state will make your application more paralellizable. Every time you change the state of an instance of your object, you create the potential for thread safety issues (either complexity, or bugs; choose at least one). If you look at Parallel LINQ or functional languages emphasizing parallelism, you'll notice that class design matters less than the discipline of avoiding changes in state.

    Class design is for your sanity. Loosely coupled code makes you more sane. Immutable objects make you more parallel. Combine as needed.

  • It's not the size of the classes, but the scope of the coupling that matters.

    For parallel applications, you should favor immutable objects---sometimes called "value objects" rather than objects with a lot of properties. If you need to apply operations that result in new values, just create new objects as the result.

    Observe good separation of concerns, and let that lead you to the natural number of classes to represent the concepts in your program. I recommend the SOLID principles, cataloged and popularized by Robert Martin from ObjectMentor. (That should be enough Google-fodder to locate the list!)

    Finally, I also recommend that you get intimate with both System.Threading and System.Collections. Most of the collections are not inherently thread safe, and synchronization is notoriously difficult to get right. So, you're better off using widely-used, tested, reliable synchronization primitives.

Is there a varargs null check function in Java or Apache Commons?

I've got four variables and I want to check if any one of them is null. I can do

if (null == a || null == b || null == c || null == d) {
    ...
}

but what I really want is

if (anyNull(a, b, c, d)) {
    ...
}

but I don't want to write it myself. Does this function exist in any common Java library? I checked Commons Lang and didn't see it. It should use varargs to take any number of arguments.

From stackoverflow
  • I don't know if it's in commons, but it takes about ten seconds to write:

    public static boolean anyNull(Object... objs) {
        for (Object obj : objs)
            if (obj == null)
                return true;
        return false;
    }
    
    Steven Huwig : Yeah I know but then the question is where to put it. ;)
    Michael Myers : Do you have a utilities class of some sort? It seems like I always end up with one.
    Steven Huwig : Yeah, it's Commons Lang, Commons IO, Commons Collections, etc...
    Michael Myers : Well, I just did some scouting around and found a couple of anyNull methods, but they seem to predate varargs.
    OscarRyz : nice question and nice answer
    Michael Myers : I tried searching Google Code (http://code.google.com/), but I'm not exactly sure how to formulate the search. The basic structure of the code would look something like this, but the names could be almost anything.
    Steven Huwig : Makes me wish for Hoogle: http://www.haskell.org/hoogle/
    Michael Myers : Interesting. That would indeed be useful. Joogle? Javoogle? Anyone?
    Adrian : @mmyers http://www.merobase.com
  • The best you can do with the Java library is, I think:

    if (asList(a, b, c, d).contains(null)) {
    
    Michael Myers : With a static import of java.util.Arrays.asList, I presume?
    Tom Hawtin - tackline : Yes. You have to import it someway. Although it is a bit of a cheat...
    OscarRyz : close to literate programming
    Michael Myers : A little slower, too, one would guess, but no external libraries and no figuring out where to put the anyNull method.
  • You asked in the comments where to put the static helper, I suggest

    public class All {
        public static final boolean notNull(Object... all) { ... }
    }
    

    and then use the qualified name for call, such as

    assert All.notNull(a, b, c, d);
    

    Same can then be done with a class Any and methods like isNull.

    Steven Huwig : I like that idea very much.

Website Header in HTML

How do I create a webpage with a header, content, and a footer. I am using TextEdit on my Mac and saving the file with a .HTML extension.

From stackoverflow
  • I assume you have some ability to run a scripting language on your host, so just write a header and footer file, and include those in your content page with your dynamic language of choice.

  • You can go through the 3+3 tutorials for HTML and CSS on HTML Dog.

    Sunny : RTFM is hardly a good answer.
    cherouvim : @Sunny: The question was very basic and my answer did not have any RTFM tone in it :)
    Sunny : Undoing the downvote, as the OP accepts this, but still its better to provide a solution :)
    cherouvim : @Sunny: Thanks. I still think that in this case the solution is to point the author to the tutorial itself instead of trying to guess what he means or copy pasting huge tutorial sections in here.
  • create an html file paste this frames :

    <html>
    
    <frameset rows="25%,50%,25%">
    
      <frame src="header.htm">
      <frame src="content.htm">
      <frame src="footer.htm">
    
    </frameset>
    
    </html>
    

    and then create your header, content and footer files in same directory.

    Chris Ballance : Ugh, Frames?!? Blasphemy
    Rex M : Sweet god almighty, I thought we eradicated this like Polio!
    cherouvim : Yes, frames suck but it's the only way to do modularization in a static html environment. So ++
    Rex M : No one is asking about file modularization. So this is heaping bad upon bad.
    cherouvim : @Rex M: The question was very vague and it was not clear what the intention was.
    Canavar : @Rex M : strange people, he is not asking about file modularization, ok, but not asking for one and only one file.. it's an answer, and not wrong, like or dislike..
  • <html>
    <head><title>my title</title></head>
    
    <h1>My Header</h1>
    
    <p>The quick brown fox jumps over the lazy dog.</p>
    
    <h4>My footer</h4>
    </html>
    

    my title

    My Header

    The quick brown fox jumps over the lazy dog.

    My footer


    Optionally, you can put each section in a separate file, or specifically the header and footer in separate files to be reused.

  • If your web server is Apache (I would guess on Mac), you can use server-side includes:

    <html>
    .....
    <body>
    <!--#include virtual="myheader.html" --> 
    
    YOUR CONTENT GOES HERE
    
    <!--#include virtual="myfooter.html" --> 
    </body>