39
\$\begingroup\$

Write a program/function that returns the vote count of its own Stack Exchange answer at the time of its execution.

  • Your program/function may access this page (codegolf.stackexchange.com/questions/82609) off the internet, however:
  • Your program/function may not accept any user input and
  • The use of URL shorteners is not allowed
  • Your program/function may use only its own source as a reference point to its vote count (for example: no referencing strings of text in its contained answer but not in its own source)
  • Your program/function must output its own vote count and only its own vote count (for example: no returning all vote counts on this page)

This is code-golf, shortest code wins.

\$\endgroup\$
  • \$\begingroup\$ perl -e'($_)=`curl -s http://api.stackexchange.com/2.2/posts/123?site=codegolf`;/score":(\d+)/&&print$1' looks like it should work, but doesn't. But maybe someone can use that. \$\endgroup\$ – msh210 Jun 10 '16 at 21:28
  • 7
    \$\begingroup\$ To everyone else who's trying and failing to use the API: It serves the response gzip encoded, even if the client does not support it. \$\endgroup\$ – Dennis Jun 10 '16 at 21:41
  • 13
    \$\begingroup\$ "Your program/function may use only its own source as a reference point to its vote count" Is a bit confusing. Does this mean that answers should try to identify themselves only using knowledge of their own code, and not through something like a post id? I don't think that such a rule would be good, as it can be broken by anyone else posting a new answer. \$\endgroup\$ – FryAmTheEggman Jun 10 '16 at 22:21
  • \$\begingroup\$ @FryAmTheEggman I did put a bit of thought into breaking other peoples answers, and I even considered making this a KOTH where your source tries to undermine another answer, although in the end that seemed to be pushing the format more than I wanted... I added the using its own source bit to prevent users from setting up the page to make it easier to find itself without contributing to its byte count, in the case that the answer doesn't use the post id method. \$\endgroup\$ – Dendrobium Jun 10 '16 at 22:33
  • 2
    \$\begingroup\$ Alright, the wording is a bit weird. I would recommend instead of allowing certain behaviour in this way, instead directly ban using any web services besides those supplied by stackexchange (unless I've misunderstood you). As a side note, due to the nature of the completeness problem, it is not possible to make something like this unbreakable. The best you can do is make it implausible to be broken. \$\endgroup\$ – FryAmTheEggman Jun 10 '16 at 22:39

14 Answers 14

39
\$\begingroup\$

jQuery + JavaScript, 85 bytes

$.get("//api.stackexchange.com/posts/82610?site=codegolf",d=>alert(d.items[0].score))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

History

  • -6 bytes because I was using the var data instead of d.
  • -3 bytes thanks to @msh210
  • -13 bytes thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ
  • -4 bytes thanks to @user6188402
  • -5 bytes thanks to @Suever
  • -4 bytes thanks to @RobW

Recommended usage

  • Run snippet.
  • Upvote.
  • Run snippet, and be amazed as the number magically increases.

Bonus!!

Who doesn't like a bonus?

$.getJSON("//api.stackexchange.com/posts/" + prompt() + "?site=codegolf",d=>alert(d.items[0].score));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Enter the ID into the bonus and it will tell you the score.

Even more bonus!! Run this snippet to automatically run the program, upvote, and run again! (Requires rep > 15, auth). If it doesn't work, please tell me.

\$\endgroup\$
  • 2
    \$\begingroup\$ posts instead of answers and http instead of https saves three bytes (or perhaps you can omit http: altogether?). (Untested.) \$\endgroup\$ – msh210 Jun 10 '16 at 21:34
  • 2
    \$\begingroup\$ You can use http:// and it will 301 redirect to https:// Better yet, just remove the http altogether //api.stackexchange.com... \$\endgroup\$ – Suever Jun 10 '16 at 21:37
  • 8
    \$\begingroup\$ jQuery is not a language, neither an inbuilt library in JS. So if you are using that, include the byte count of jQuery in your score too. \$\endgroup\$ – Optimizer Jun 10 '16 at 21:53
  • 10
    \$\begingroup\$ @Optimizer: This is the proper way to do it: consider JS + jQuery to effectively be its own "language". See this meta post: meta.codegolf.stackexchange.com/a/9279/12914 \$\endgroup\$ – El'endia Starman Jun 10 '16 at 21:58
  • 3
    \$\begingroup\$ Use $.get instead of $.getJSON. The API's content type is application/json, and jQuery will automatically treat the response as JSON. \$\endgroup\$ – Rob W Jun 11 '16 at 11:33
24
\$\begingroup\$

JavaScript ES6, 107 bytes

fetch`//api.stackexchange.com/posts/82672?site=codegolf`.then(r=>r.json()).then(b=>alert(b.items[0].score))

Real programmers don't use XMLHttpRequest. Real programmers use the Fetch API.

\$\endgroup\$
  • 1
    \$\begingroup\$ Well... you got me there. I never knew about this API! \$\endgroup\$ – Conor O'Brien Jun 12 '16 at 20:54
  • \$\begingroup\$ I'm getting an error that fetch isn't defined \$\endgroup\$ – Anthony Pham Jun 13 '16 at 0:13
  • 1
    \$\begingroup\$ @PythonMaster The Fetch API is not yet available in all browsers: caniuse.com/#feat=fetch \$\endgroup\$ – Jordan Jun 13 '16 at 5:35
21
\$\begingroup\$

Bash, 80 79 75 69 bytes

w3m api.stackexchange.com/posts/82616?site=codegolf|tr ,: \\t|cut -f20

For scoring purposes, \t should be replaced with a TAB character.

This requires w3m, which should be available by default on most Linux distros.

Thanks to @NoOneIsHere for -2 bytes!

How it works

w3m is a command-line web browser. It queries the URL and (normally) displays its content in a readable format. Here, we just (ab)use it to avoid the call to zcat that curl would require, since SE serves the API response gzip-compressed.

tr ,: \^I replaces all commas and colons with tabs, which are cut's default field delimiter.

Finally, cut -f20 removes everything but the twentieth field, which is the vote count.

\$\endgroup\$
  • \$\begingroup\$ Or --compressed, which is even longer than zcat. \$\endgroup\$ – Neil Jun 10 '16 at 23:10
9
\$\begingroup\$

JavaScript ES6, 175 165 160 145 bytes

Saved lotsa bytes thanks to Optimizer and Dendrobium! They're all multiples of five!

Using plain ol' javascript. Who needs those newfangled libraries? Real programmers use XMLHttpRequest()

with(new XMLHttpRequest)send(open("get","//api.stackexchange.com/posts/82614?site=codegolf"),onload=_=>alert(response.match(/re..([0-9]+)/)[1]))

Test it out

alert=x=>o.innerHTML=x;

with(new XMLHttpRequest)send(open("get","//api.stackexchange.com/posts/82614?site=codegolf"),onload=_=>alert(response.match(/re..([0-9]+)/)[1]))
*{font-family:Consolas,monospace;}
<div id=o></div>

\$\endgroup\$
  • \$\begingroup\$ @Optimizer Thanks! But why use prompt? \$\endgroup\$ – Conor O'Brien Jun 10 '16 at 22:04
  • \$\begingroup\$ @Optimizer For some reason, "g" doesn't work as an option for me. \$\endgroup\$ – Conor O'Brien Jun 10 '16 at 22:07
  • \$\begingroup\$ with(new XMLHttpRequest)(open("get","//api.stackexchange.com/2.2/posts/82614?site=codegolf"),onload=_=>alert(response.items[0].score),send(responseType="json")) for -5 bytes \$\endgroup\$ – Dendrobium Jun 10 '16 at 22:13
  • \$\begingroup\$ @Dendrobium Oh, nice one. I forgot about with \$\endgroup\$ – Conor O'Brien Jun 10 '16 at 22:13
  • \$\begingroup\$ @Optimizer I get TypeError: response.split(...)[12] is undefined", \$\endgroup\$ – Conor O'Brien Jun 10 '16 at 22:48
7
\$\begingroup\$

bash+jq, 69 bytes

w3m api.stackexchange.com/posts/82615?site=codegolf|jq .items[].score

I used curl and zcat before; w3m is inspired by Dennis’s (strikingly similar) answer. It turns out jq and tr/cut have the same byte cost!

\$\endgroup\$
6
\$\begingroup\$

Convex 0.5, 63 bytes

0000000: 22 d1 2e 46 91 32 e5 69 5d b2 66 81 12 a4 8d d1  "..F.2.i].f.....
0000010: 27 40 b5 32 47 68 97 2c b9 5c 22 05 16 49 10 31  '@.2Gh.,.\"..I.1
0000020: 44 9e f3 0a 6a 16 b0 68 91 93 35 0b 96 dc 91 0a  D...j..h..5.....
0000030: 3c 18 80 22 dc 67 27 3c 2f 32 36 39 3d 37 3e     <..".g'</269=7>

This retrieves the score from the search page instead of the API, specifically from the query https://codegolf.stackexchange.com/search?q=inquestion:82714. Fortunately, inquestion also works for answers.

Verification

$ echo $LANG
en_US
$ cat gen.convex
"codegolf.stackexchange.com:80/search?q=inquestion:82714"Ö`"Üg'</269=7>"
$ java -jar Convex/out/builds/convex-0.5/convex/convex.jar gen.conv > count.conv
$ cksum count.conv
2414634109 63 count.conv
$ java -jar Convex/out/builds/convex-0.5/convex/convex.jar count.conv
1

How it works

"..."Ü           e# Use the built-in string compression to push
                 e# "codegolf.stackexchange.com:80/search?q=inquestion:82714".
      g          e# Retrieve the HTML page at that URL.
       '</       e# Split at occurrences of '<'.
          269=   e# Select the chunk at index 269.
                 e# This pushes "strong>", followed by the vote count.
              7> e# Discard the leading seven characters.
\$\endgroup\$
  • \$\begingroup\$ This is amazing. How did you even know that this language can do this? \$\endgroup\$ – Adnan Jun 12 '16 at 0:42
  • 3
    \$\begingroup\$ It's a CJam fork. I originally wrote my answer in CJam (67 bytes), but then I remembered that Convex has built-in string compression. \$\endgroup\$ – Dennis Jun 12 '16 at 0:44
5
\$\begingroup\$

05AB1E, 89 87 81 bytes

Thanks Python...

•1Ö8•D’£Ø ˆå§¾.‡¢ as g;#.¾¿„–(g.ˆåƒÛ('·Ç://ƒËŠˆ.‚‹º.ŒŒ/…é/ÿ/').‚Ø())’.er¡14èžz£þ

Uses the CP-1252 encoding.

\$\endgroup\$
4
\$\begingroup\$

MATLAB, 103 bytes

g=@getfield;g(g(webread('http://api.stackexchange.com/2.2/posts/82611?site=codegolf'),'items'),'score')
\$\endgroup\$
4
\$\begingroup\$

JavaScript (Node.js + Unirest), 123 bytes

require("unirest").get("http://api.stackexchange.com/posts/82683?site=codegolf").end(x=>console.log(x.body.items[0].score))

I like this library, because it automatically parses JSON.

\$\endgroup\$
4
\$\begingroup\$

Julia, 128 107 bytes

using Requests
f()=split(readall(get("http://api.stackexchange.com/posts/82621?site=codegolf")),r":|,")[20]

This is a function that takes no input and returns the score of this post as a string. It requires the Requests package to be installed.

How it works:

  • get makes a GET request to the SE API
  • readall reads the raw bytes in the response and returns a string
  • split splits the string at colons and commas
  • The 20th element of the resulting array is the score of the post

Saved 21 bytes thanks to Dennis!

\$\endgroup\$
4
\$\begingroup\$

JavaScript (Node.js), 166 Bytes

-1 byte because @CᴏɴᴏʀO'Bʀɪᴇɴ taught me how to count ;)

-4 bytes thanks to @NoOneIsHere

require("http").get("http://api.stackexchange.com/posts/82620?site=codegolf",a=>a.on("data",d=>console.log(JSON.parse(require("zlib").gunzipSync(d)).items[0].score)))

This is somewhat embarrassing. Dang you SE for gzipping your API! /s

Any improvements are very welcome.

\$\endgroup\$
3
\$\begingroup\$

PHP, 137 bytes

Pretty straight forward. The uncompressing takes a lot of bytes:

<?=json_decode(gzinflate(substr(file_get_contents('http://api.stackexchange.com/2.2/posts/82619?site=codegolf'),10)),1)[items][0][score];

Ungolfed

print
  json_decode(
    gzinflate(
      substr(
        file_get_contents('http://api.stackexchange.com/2.2/posts/82619?site=codegolf'),
        10
      )
    ),
    1
  )
  [items][0][score];
\$\endgroup\$
2
\$\begingroup\$

PHP, 121 bytes

Without api.

<?php preg_match('/t ">(.*)/',file_get_contents('http://codegolf.stackexchange.com/posts/82799/ajax-load'),$v);echo$v[1];

Gets the whole post and extracts the vote counts with regex. (don't parse HTML with regex!)

Ungolfed:

<?php
   preg_match('/t ">(.*)/',
              file_get_contents('http://codegolf.stackexchange.com/posts/82799/ajax-load'),
              $v);

   echo $v[1];
\$\endgroup\$
  • \$\begingroup\$ Can you remove http:? \$\endgroup\$ – NoOneIsHere Jun 16 '16 at 23:15
  • \$\begingroup\$ @NoOne No, doesn't appear to work then. \$\endgroup\$ – nicael Jun 17 '16 at 6:37
1
\$\begingroup\$

05AB1E, 45 bytes

•2íЕ’¸¸.‚‹º.ŒŒ/„¤/ÿ?€¼=ƒËŠˆ’žYì.w'ŒÂ¡θ',¡нþ

No TIO for the entire program, because the .w builtin to access the internet doesn't work on TIO.

Explanation:

We start by creating the url, and accessing it:

•2íЕ       # Push compressed integer 190437 (the id of this answer)
  ’¸¸.‚‹º.ŒŒ/„¤/ÿ?€¼=ƒËŠˆ’
            # Push dictionary string "api.stackexchange.com/posts/ÿ?site=codegolf",
            # where the `ÿ` is automatically filled with the 190437
    žY      # Push builtin "https://"
      ì     # And prepend it in front of the string
.w          # Go to this website, and get all its contents

Try it online (without the .w).

After that, we extract the score from the JSON:

'ŒÂ        '# Push dictionary string "score"
   ¡        # Split the website content on this
    θ       # Only leave the last item (of the two)
     ',¡   '# Split this string on ","
        н   # And this time leave the first item (i.e. `":10`)
         þ  # Only leave the digits of this string
            # (which is output implicitly as result)

Try it online.

An equal 10-bytes alternative for this second part could be:

„ŒÂ‚¡       # Push dictionary string "score after"
     #      # Split it on spaces: ["score","after"]
      ¡     # Split the website content on these
       Ås   # Only leave the middle element
         þ  # Only leave the digits of this string
            # (which is output implicitly as result)

Try it online.

See this 05AB1E tip of mine (sections How to use the dictionary? and How to compress large integers?) to understand why •2íЕ is 190437, ’¸¸.‚‹º.ŒŒ/„¤/ÿ?€¼=ƒËŠˆ’ is "api.stackexchange.com/posts/ÿ?site=codegolf", 'ŒÂ is "score", and „ŒÂ‚¡ is "score after".

PS/EDIT: I realize that by using the þ I assume I will never get a negative score. ;)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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