Stack Exchange Vote Counter

40

5

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.

Dendrobium

Posted 2016-06-10T21:10:44.450

Reputation: 2 412

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. – msh210 – 2016-06-10T21:28:48.273

7To 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. – Dennis – 2016-06-10T21:41:37.913

13"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. – FryAmTheEggman – 2016-06-10T22:21:42.620

@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. – Dendrobium – 2016-06-10T22:33:05.640

2Alright, 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. – FryAmTheEggman – 2016-06-10T22:39:46.990

I don't get it. The question states to only use the page contents at codegolf.stackexchange.com/questions/82609 as a reference. Yet everyone appears to be using the api at api.stackexchange.com. What am I missing? – Num Lock – 2016-06-13T09:41:07.453

Are you going to accept an answer? (I want the badge about 2x outvoting the accepted answer, which is Dennis's convex one) – NoOneIsHere – 2016-08-05T20:20:14.293

@Dendrobium: I had developed an noncompeting answer that was a cousin to your KOTH idea, and I can't recommend going that route. Mine flopped miserably and was mod deleted for this and other reasons (as it should have been). Rather than undermining an answer, it went the other way and was self-deprecating while it complimented whichever author and answer was currently in the lead. This still had potential to influence votes and cause confusion if anyone had taken it seriously. – GuitarPicker – 2016-08-18T04:10:14.750

Please accept an answer. It has been quite a while. – NoOneIsHere – 2016-11-18T16:55:01.423

Answers

39

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.

NoOneIsHere

Posted 2016-06-10T21:10:44.450

Reputation: 1 916

2posts instead of answers and http instead of https saves three bytes (or perhaps you can omit http: altogether?). (Untested.) – msh210 – 2016-06-10T21:34:13.600

1Also, try d=>alert(d.items[0].score) – Conor O'Brien – 2016-06-10T21:36:59.937

2You can use http:// and it will 301 redirect to https:// Better yet, just remove the http altogether //api.stackexchange.com... – Suever – 2016-06-10T21:37:24.267

8jQuery 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. – Optimizer – 2016-06-10T21:53:53.853

10

@Optimizer: This is the proper way to do it: consider JS + jQuery to effectively be its own "language". See this meta post: http://meta.codegolf.stackexchange.com/a/9279/12914

– El'endia Starman – 2016-06-10T21:58:00.537

1@El'endiaStarman I don't really see a conclusion to that. It need more answers or more discussion on the existing answer to really call it "proper way" – Optimizer – 2016-06-10T22:05:40.643

3Use $.get instead of $.getJSON. The API's content type is application/json, and jQuery will automatically treat the response as JSON. – Rob W – 2016-06-11T11:33:54.850

Doesn't work if you are using HTTP instead of HTTPS. – wizzwizz4 – 2016-06-11T12:51:42.610

I got: { "message": "Uncaught SyntaxError: Unexpected token )", "filename": "http://stacksnippets.net/js", "lineno": 18, "colno": 74 } working with chrome

– tox123 – 2016-06-12T18:30:28.303

Doesn't this answer violate the very first rule of the question? – Num Lock – 2016-06-13T09:39:12.623

-1 not enough jQuery. – programmer5000 – 2017-04-18T16:26:29.183

@programmer5000 Did you really downvote? Vote as you see fit, but this is 100% jQuery. $ is an alias of jQuery, and the main body of my post is a call to $.post. – NoOneIsHere – 2017-04-18T16:32:18.787

24

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.

Michał Perłakowski

Posted 2016-06-10T21:10:44.450

Reputation: 520

1Well... you got me there. I never knew about this API! – Conor O'Brien – 2016-06-12T20:54:38.650

I'm getting an error that fetch isn't defined – Anthony Pham – 2016-06-13T00:13:10.633

1

@PythonMaster The Fetch API is not yet available in all browsers: http://caniuse.com/#feat=fetch

– Jordan – 2016-06-13T05:35:15.113

21

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.

Dennis

Posted 2016-06-10T21:10:44.450

Reputation: 196 637

Or --compressed, which is even longer than zcat. – Neil – 2016-06-10T23:10:38.390

9

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>

Conor O'Brien

Posted 2016-06-10T21:10:44.450

Reputation: 36 228

@Optimizer Thanks! But why use prompt? – Conor O'Brien – 2016-06-10T22:04:25.737

@Optimizer For some reason, "g" doesn't work as an option for me. – Conor O'Brien – 2016-06-10T22:07:47.317

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 – Dendrobium – 2016-06-10T22:13:21.213

@Dendrobium Oh, nice one. I forgot about with – Conor O'Brien – 2016-06-10T22:13:55.837

@Optimizer I get TypeError: response.split(...)[12] is undefined", – Conor O'Brien – 2016-06-10T22:48:57.203

@CᴏɴᴏʀO'Bʀɪᴇɴ Expanding on @Optimizer's suggestion, with(new XMLHttpRequest){open("get","//api.stackexchange.com/2.2/posts/82614?site=codegolf");send(onload=_=>alert(response.split\:`[12].split`,`[0]))}` for -10 bytes – Dendrobium – 2016-06-10T22:54:31.637

with(new XMLHttpRequest)send(open("get","//api.stackexchange.com/posts/82614?site=codegolf"),onload=_=>alert(response.match(/re..([0-9])/)[1])) for 143 bytes – Dendrobium – 2016-06-10T23:16:22.113

with(new XMLHttpRequest)send(open("get","//api.stackexchange.com/posts/82614?site=codegolf"),onload=_=>alert(response.match(/\d+/g)[25])) 137 – Optimizer – 2016-06-11T05:44:31.357

You can shave off some bytes by using synchronous XMLHttpRequest. The regexp can be shortened using exec instead of match and a look-ahead (so that the result is an array of size 1, so you don't need [1]. This works as long as you don't change your display name to end with a digit: with(new XMLHttpRequest)send(open("get","//api.stackexchange.com/posts/82614?site=codegolf",0)),alert(/\d+(?=,"l)/.exec(response)) 130 – Rob W – 2016-06-11T11:29:06.647

7

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!

Lynn

Posted 2016-06-10T21:10:44.450

Reputation: 55 648

6

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.

Dennis

Posted 2016-06-10T21:10:44.450

Reputation: 196 637

This is amazing. How did you even know that this language can do this? – Adnan – 2016-06-12T00:42:32.377

3It's a CJam fork. I originally wrote my answer in CJam (67 bytes), but then I remembered that Convex has built-in string compression. – Dennis – 2016-06-12T00:44:14.730

5

05AB1E, 89 87 81 bytes

Thanks Python...

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

Uses the CP-1252 encoding.

Adnan

Posted 2016-06-10T21:10:44.450

Reputation: 41 965

4

MATLAB, 103 bytes

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

Suever

Posted 2016-06-10T21:10:44.450

Reputation: 10 257

4

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.

MayorMonty

Posted 2016-06-10T21:10:44.450

Reputation: 778

4

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!

Alex A.

Posted 2016-06-10T21:10:44.450

Reputation: 23 761

4

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.

Michał Perłakowski

Posted 2016-06-10T21:10:44.450

Reputation: 520

3

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];

insertusernamehere

Posted 2016-06-10T21:10:44.450

Reputation: 4 551

2

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];

nicael

Posted 2016-06-10T21:10:44.450

Reputation: 4 585

Can you remove http:? – NoOneIsHere – 2016-06-16T23:15:04.317

@NoOne No, doesn't appear to work then. – nicael – 2016-06-17T06:37:20.867

1

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. ;)

Kevin Cruijssen

Posted 2016-06-10T21:10:44.450

Reputation: 67 575