Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write a program that connects to this site, downloads the very answer in which it is posted, extracts its own source code and prints it out. The output must be identical to the source code. Shortest code (in bytes) wins.

Rules:

  • No URL shorteners allowed.
  • The answer must have a regular format - a heading with the language name and size, optional description, code block, optional description and explanation. No unnatural delimiters allowed.
  • The output must originate from the actual code block posted on the site.
  • The functionality must not depend on the position in the answer list; it should work even if there are multiple pages and the answer it not on the first one.
share|improve this question
10  
Catch-22: How am I supposed to test my submission? –  m.buettner yesterday
6  
I forsee people posting answers and deleting them, so they can test their code. –  Quincunx yesterday
1  
@m.buettner answers can be tested on other answers (to other questions) first, then posted, then edited to change the URL :) –  aditsu yesterday
3  
@hexafraction if comments are able to interfere with an answer, then the answer is not very good... –  aditsu yesterday
2  
A question stuck in my head: How to write a tweet that links to itself without using any URL shorteners, but by estimating the tweet id your tweet? –  SHiNKiROU 21 hours ago
show 11 more comments

14 Answers

Ruby, 155 186 195 148 138 110 97 characters

require'open-uri';puts open('http://codegolf.stackexchange.com/posts/28159/body').read[/req.+;/];

I had to make it one line, because otherwise it would output newlines as \n instead of actual newlines.

  • +31 characters because I didn't notice some characters were being escaped.
  • +9 characters to get rid of the annoying backslash.
  • Thanks to Nathan Osman for saving 2 chars, and Ventero for saving 55 (!!!) by removing the need for most of the fixes listed above.

The explanation

Let's beautify this a bit first. However, I'm going to have to use a somewhat... interesting notation in this code. I can't use semicolons at all in this post, for reasons explained later, so I will use {SEMI} in place of semicolons instead.

require 'open-uri'
resp = open('http://codegolf.stackexchange.com/posts/28159/body').read
puts resp.match(/req.+{SEMI}/){SEMI}

Alright, now let's walk through this. The first two lines are fairly self-explanatory -- they fetch the HTML text of this answer.

Now, the last line is the interesting one here. You see that seemingly useless semicolon at the end of the code? It's absolutely required, and here's why.

First, resp.match extracts the code to be printed. The regexp it uses for this is the trick: /req.+{SEMI}/. It grabs the start of the code, REQuire'net/http', by searching for req (re would grab my REputation). Then, it finds the end of the code by searching for a semicolon! Since + is greedy by default, it will keep going until it finds the semicolon that signifies the end of the code. See why I can't use semicolons anymore?

After that, I don't have to unescape anything thanks to Ventero's fix of not using \ at all anymore. All I have to do is fix {AMPERSAND} changing into {AMPERSAND}amp{SEMI}, which can be achieved simply by removing the amp{SEMI} part. No need for this anymore because of new URL. After that, the original code has been retrieved! (Note: I can't use the ampersand either, because that gets HTML-encoded which causes a semicolon to be created.)

share|improve this answer
    
Some characters are getting escaped.. –  aditsu yesterday
    
@aditsu Gah; didn't notice that. Fixed. –  Doorknob yesterday
    
You're gonna hate this.. a backslash is getting duplicated. There's also a newline difference, but that's a minor thing. –  aditsu yesterday
    
@aditsu Argh! :P Fixed also. The newline thing is because of puts; it could be fixed with print but meh. Just pretend there's a trailing newline in the code, even though SE won't be able to show it. –  Doorknob yesterday
    
You can shave off two bytes by using withbody in the filter instead of !9WA((ItYa. –  Nathan Osman yesterday
show 7 more comments

Bash + coreutils + Lynx browser, 61 bytes

Thanks to @FDinoff for the tips:

lynx -dump codegolf.stackexchange.com/posts/28164/body|grep 2
share|improve this answer
3  
And what happens if I type that magic word grep is looking for? –  Shade yesterday
1  
lynx lynx lynx lynx. This comment will be grepped out (and the heading as well) –  hexafraction yesterday
    
@hexafraction Awww. You had to go and ruin it! –  Shade yesterday
    
I would assume that no answer above you can use a "keyword" so you could select only the first result. –  hexafraction yesterday
4  
This url should work. codegolf.stackexchange.com/posts/28164/body And it ignores comments. I also think its within the rules that you can use it... –  FDinoff yesterday
show 7 more comments

JavaScript - 123 122 101 95 92 91 87

with(new XMLHttpRequest)send(open(0,'/posts/28175/body',0)),alert(/w.*/.exec(response))

Runs in the console of your web browser on this page. Tested on the latest Chrome and Firefox.

share|improve this answer
add comment

Ruby + wget + gunzip, 159 86 82 71

Using tip of @FDinoff to use http://codegolf.stackexchange.com/posts/28173/body.

puts `wget -qO- codegolf.stackexchange.com/posts/28173/body`[/pu.*\]/]

Tested. Thanks to @ace and @Bob for command line optimization.

share|improve this answer
2  
You can combine the flags in wget, as in wget -qO- url. Also, in bash you do not need the double quotes for the url, so this may also work for you. –  ace 15 hours ago
    
@ace Thanks, works great! –  dtldarek 13 hours ago
    
You can leave out the http://. –  Bob 11 hours ago
add comment

Rebmu, 91 characters

Due to the Catch-22 I have to post to get this answer's URL. :-/ Okay, got it.

paTSrd http://codegolf.stackexchange.com/a/28154[th<a name="28154">th<code>cpCto</code>]prC

Rebmu is a dialect of Rebol, and you can read all 'bout it. The equivalent Rebol here would be:

parse to-string read http://codegolf.stackexchange.com/a/28154 [
    thru <a name="28154">
    thru <code>
    copy c to </code>
]
print c

Rebol's PARSE is a sort of highly-literate answer to RegEx. It starts a parser position of the input (which can be any series, including structural blocks...binary data...or string types). The rules are a language for how the parse position moves.

Tags and URLs are really just strings under the hood in the language. But they are "flavored", and as Rebol is dynamically typed you can check that type. READ for instance knows that if you give it a URL-flavored string, then it should dispatch to a scheme handler to do the reading. (In this case, the one registered for HTTP). You get back UTF-8 bytes by default, so we use to-string to decode that and get a series of codepoints in a normal Unicode string.

In the case of the parse dialect, encountering a tag type is just matched as if it were a string that looked like the tag. THRU is an instruction meaning "skip until the ensuing rule is matched, and then place the match position at the end of what you just matched." (TO is the analogue that matches, but leaves the parse position before the element).

So we zip along past the <a name="28154">. Then we zip past the next occurrence of <code>, with our parse position now located right after the >. PARSE's COPY command then lets us copy data up to another rule, in this case that rule is [TO </code>]... so we get into the variable C everything up until right before that <.

Cool, huh? :-)

Technically I could shave more off it, for instance by seeking TO "</" and that saves three characters--there's no need to match the whole </code> end tag when just </ would do. Similar arguments could me made for the start tag. But Rebmu is about literate golfing...even if you might think it looks odd at first!

share|improve this answer
add comment

CJam - 53

"codegolf.stackexchange.com/posts/28184/body"g54/1=);

I'm making this community wiki since I'm answering my own question and don't really want to compete :p
Credits to FDinoff for the URL choice.

share|improve this answer
add comment

Python, 175 bytes

This uses two external libraries; I didn't read that it was unauthorized.

import bs4, requests
print(bs4.BeautifulSoup(requests.get('http://codegolf.stackexchange.com/questions/28154').text).select('#answer-28171')[0].select('pre > code')[1].string)

Longer, but nicer looking code:

import bs4, requests
request = requests.get('http://codegolf.stackexchange.com/questions/28154')
soup = bs4.BeautifulSoup(request.text)
answer = soup.select('#answer-28171')[0]
code = answer.select('pre > code')[0].string
print(code)
share|improve this answer
    
The questions in the url can be replaced with q: http://codegolf.stackexchange.com/q/28154 –  Quincunx yesterday
    
The space in bs4, requests (line 1) can be removed to reduce 1 byte. –  ace 15 hours ago
add comment

Java 852, was 1004

Golfed: now replaces &gt with >

//bacchus
package golf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class G{
public static void main(String[] args) throws IOException {
URL u;
URLConnection c;
InputStream i;
InputStreamReader r;
BufferedReader b;
String s;
int x=0;
try {
u=new URL("http://codegolf.stackexchange.com/questions/28154/write-a-program-that-downloads-itself");
c=u.openConnection();
i=c.getInputStream();
r=new InputStreamReader(i);
b=new BufferedReader(r);
while((s=b.readLine())!=null)
{
if(s.contains("//bacchus")) x++;
if(s.contains("&gt;")){
s=s.replace("&gt;", ">");
}
if(x>0)System.out.println(s);
if(x>2) break;
}
i.close();
b.close();
} catch (MalformedURLException ex) {
}
}
}
//bacchus

Submitting for testing, I will edit and try golfing it shortly. Needed to change x>1 to x>2 because test string is also in my code. Note: Code golf replaces > symbol to &gt.

//bacchus
package golf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Golf {

    public static void main(String[] args) throws IOException {
        URL u;
        URLConnection c;
        InputStream i;
        InputStreamReader r;
        BufferedReader b;
        String s;
        int x=0;
        try {
            u=new URL("http://codegolf.stackexchange.com/questions/28154/write-a-program-that-downloads-itself");
            c=u.openConnection();
            i=c.getInputStream();
            r=new InputStreamReader(i);
            b=new BufferedReader(r);
            while((s=b.readLine())!=null)
            {
                if(s.contains("//bacchus")) x++;
                if(x>0)System.out.println(s);
                if(x>2) break;
            }
            i.close();
            b.close();
        } catch (MalformedURLException ex) {

        }
    }

}
//bacchus
share|improve this answer
6  
How do you handle comments containing //bacchus? –  hexafraction yesterday
2  
You could inline a lot of stuff, try-with-resources, and use * imports to save a lot of code. –  Simon Kuang 19 hours ago
    
@SimonKuang - I'd also just leave the streams open rather than closing stuff. Also, throws Exception rather than trying to handle anything. Also, I think using a Scanner rather than a BufferedReader would be simpler, especially as you could set the delimiter to //bacchus, which would make things somewhat easier... –  Jules 10 hours ago
add comment

JavaScript, 200

r=new XMLHttpRequest()
r.open('GET','/posts/28157/body')
r.onreadystatechange=function(){if(this.readyState==4)alert((a=r.responseText).substr(i=a.indexOf(c='code')+5,a.indexOf('/'+c)-i-1))}
r.send()

Runs on this page.

share|improve this answer
    
How do you run it? –  aditsu yesterday
    
@aditsu It is supposed to be run on the JavaScript console of a browser. But I am still testing (and fixing) it, please wait –  ace yesterday
    
@aditsu It should work now. Open your browser console (press F12) and paste this code there. –  ace yesterday
    
you sir, need a if(this.readyState == this.DONE) inside the function. –  Fabricio yesterday
    
@Fabricio You're right! Thanks a lot :) –  ace yesterday
add comment

Java, 300

//jules
import java.net.*;import java.util.*;public class G{public static void main(String[]a)throws Exception{Scanner s=new Scanner(new URL("http://codegolf.stackexchange.com/a/28189").openConnection ().getInputStream ()).useDelimiter ("//[j]ules");s.next ();System.out.print (s.next ());}}
//jules

An improved version of bacchusbeale's answer which:

  • doesn't close resources unnecessarily
  • doesn't declare unnecessary variables
  • uses a Scanner to avoid having to loop over the input
  • uses a regexp that doesn't match itself to avoid having to skip over a middle occurrence of the start/end marker.
share|improve this answer
add comment
curl -sL http://codegolf.stackexchange.com/q/28154 |awk -F\> '/\#/ {print $3}'

78 chars

share|improve this answer
1  
Doesn't seem to work - it outputs a lot of other stuff along with this answer. –  Riking 16 hours ago
    
@Riking true, it seems to be position-dependent (breaking the last rule) –  aditsu 16 hours ago
    
You can leave out the http://. –  Bob 11 hours ago
add comment

Haskell, 563 613 bytes

import Control.Monad
import Data.List
import Network.HTTP
m%f=join(fmap f m)
q s=(simpleHTTP(getRequest"http://codegolf.stackexchange.com/questions/28154/write-a-program-that-downloads-itself?answertab=oldest#tab-top"))%getResponseBody%(putStrLn.head.filter((==)(s++show s)).map(take 613).tails)
main=q"import Control.Monad\nimport Data.List\nimport Network.HTTP\nm%f=join(fmap f m)\nq s=(simpleHTTP(getRequest\"http://codegolf.stackexchange.com/questions/28154/write-a-program-that-downloads-itself?answertab=oldest#tab-top\"))%getResponseBody%(putStrLn.head.filter((==)(s++show s)).map(take 613).tails)\nmain=q"

Tested. Has page support via "oldest posts" feature. Uses quine-line structure to find what to print. The import Control.Monad is only because >>= generates &gt; in HTML.

share|improve this answer
add comment

Javascript, 138

a=window.open("http://codegolf.stackexchange.com/posts/28160/body");setTimeout('alert(a.document.body.innerHTML.match(/a=.*9\\)/)[0])',99)

This works assuming that the page loads in under 99 ms. It also has to be run via a console opened on a codegolf.SE page, because of the same origin policy.

share|improve this answer
    
Just a note: you don't need the slug in the URL, and questions can be replaced by q. –  Schism yesterday
    
Note that you could do http://codegolf.stackexchange.com/a/28160 instead of http://codegolf.stackexchange.com/a/28160/12551 –  Quincunx yesterday
add comment

Ruby, 237

require 'open-uri';require 'htmlentities';open ('http://codegolf.stackexchange.com/a/28159') {|f| f.each{|l| b = '' if l =~ /<c(.*)'htmlentities'/;puts HTMLEntities.new.decode l.gsub(/<\/?[^>]+>/, '') if b;break if l =~ /<\/code>/ && b}}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.