text:
Tips for golfing in vim
I've recently realized how vim works great for golfing, especially for kolmogorov-complexity. Also, according to meta vim is a perfectly acceptable 'programming language' at least, for the scope of this site, that is.
What general tips do you have for golfing in Vim? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Vim (e.g. "remove comments" is not an answer).
Please post one tip per answer.

This is a particularly helpful tips question because "Tips for golfing in vim" and "Tips for using vim efficiently as a text editor" are basically the same thing.

Be aware of the uppercase variants of common commands. This can trivially save one keystroke in a lot of contexts. For example:
A = $a
C = c$
D = d$
I = ^i
S = cc
X = dh
Y = yy

Another one is to use G instead of gg, but only if you use a count! For example, without a count, gg moves to the beginning, and G moves to the end. However, with a count, they both move to the line you specify, so 5G is shorter than but equivalent to 5gg
    .
Another one, is to use H in place of gg, but it's important to note that this only works if you can guarantee that any input will not take up more than the default number of rows (I believe this is 24, but it may vary).

If a challenge specifically editor golf (and therefore usually scored by keystrokes) an upper-case letter is two keystrokes as well (so is $ though, so at least C and D would save something).

Something I'm not clear about when scoring in keystrokes is whether consecutive letters that require the shift key only count the shift key once per group, since you could (at least for practical purposes) hold it down while you hit the other keys.

@AlexA. Personallly, I think modifiers shouldn't count. Maybe we need a meta post on this...

G and gg are not equivalent. The former goes to the end of the buffer and the latter goes to the beginning.

@Jordan That's a good point. I meant they're the same when given a count, e.g. 5G is equivalent to 5gg. I'll add some more details about that point.

Anytime a command fails, it will make a ding noise, which will cancel the current macro. You can (ab)use this to create a crude form of loop. For example, if you want to repeat the keystrokes <foobar> until your buffer has less than 3 lines in it. You can do
qq<foobar>3G``@qq

which means:
qq                 'Start recording in register q
  <foobar>         'Keystrokes
          3G       'Go to line 3. If line 3 doesn't exist, this is effectively a "break" statement.
            ``     'Jump back to previous cursor location
              @q   'Call macro q
                q  'Stop recording

It's important to note that if you are testing this in a vim session, the @q might have unintended side effects, since macros are loaded from .vim_profile. You can get around this a couple different ways. Probably the best workaround is to launch vim with
vim -i NONE

You could also delete your .viminfo.
If you have already launched vim, you can type
qqq

at the beginning to zero the macro out.
Other conditions you can replace the 3G with are
f<char>    'Jump to first occurence of <char>. Also see F, t and T

or
<number>|  'Go to the <number>'th character on the current line.

The alphabet in 10 keystrokes
All credit for this technique goes to Lynn, who first used it in this answer. I'm writing it up here for posterity.
Use the following ten keystrokes to yank the lowercase alphabet:
:h<_␍jjYZZ

(Where ␍ is a carriage return, i.e. the Enter key.)
Explanation
:h<_␍ opens the help section v_b_<_example (an example of visual blockwise selection), which happens to contain the text abcdefghijklmnopqrstuvwyxz. jjY moves down to that line and yanks it, then ZZ closes the help window.

Wow that's creative

:%s/\n//g

is always equivalent to
:%s/\n//

which happens to also be equivalent to
:%s/\n

surprisingly enough. (In general, without any flags, the last slash in a :s expression is never necessary.)

This works for newline, but doesn't work for any character that could appear more than once in a line. For example :%s/x doesn't remove every occurrence of x, just the first one on each line.

You can also use :&& to repeat a substitute command and it's flags.

There are more shortened versions of ex commands that you think. For example, you probably already knew that :global can be shortened to :g, but did you know that :nnoremap is equivalent to :nn?
It's a good idea to run :h :foo on all the ex commands you're using in your answer to see if there's a shorter version.

Let's say you're in insert mode, and you want to make a single normal mode command. You might write that like this:
isome_text<esc><foobar>gisome_more_text

Don't do it that way. Instead, use <C-o>, which executes a single normal command then immediately returns to insert mode.
isome_text<C-o><foobar>some_more_text

I don't think those spaces are necessary either

@QPaysTaxes You're right, they aren't. I thought it would make it more readable. I'll edit that.

You don't need a <CR> after <foobar> to send the command?

@QPaysTaxes Only if it's an ex command or a search. (E.g. any command starting with a :, /, or ?)

Oh, my bad. I confused command and normal modes. Cool :D

A similar one: <M-<foobar>> executes a command while you're in insert mode - it just doesn't return you to insert mode afterwards. If you're in insert mode in the middle of a line and want to start typing on a new line underneath, rather than doing <C-o>o, you can do it in one stroke, <M-o>.

I believe <M-<foobar>> is system dependent. Which makes me curious if it's allowed over at VimGolf.com

@m-chrzan I believe that is not a valid shortening. If  works that way, that is because it is being represented as an Escape character followed by an o, and thus should be counted as two bytes.

Golfier movements
Frequently if you're working with a block of text (especially in ascii-art challenges), you'll need to move to the first or last character in the buffer. G and gg are pretty good, but there are some annoying things. For example, to get the last character, you need G$ and gg will not necessarily put you on the first column if there's leading whitespace. Here are some nicer movements, although note that they only work if your text doesn't have empty lines in the middle of it:

First character of the buffer: { is better than gg0. If there are empty lines in the middle of the text, you can also use go which brings you to the first character in the buffer no matter what.

Last character of the buffer: } is better than G$

These also work as an argument to an operator, but note that they are character-wise movements, not line-wise movements!

H is golfier than gg

@KritixiLithos except that H is not reliable. It's behavior depends on the size of the visible window and where you are in the buffer. (It's remapped in V to avoid this confusion)

This came up in chat earlier, so I thought I might as well post it as a full tip.
<C-a> and <C-x> increment and decrement the next number on the line. This is an extremely useful feature for some simple math, but it also allows for a neat little hack.
Let's say you need to jump to the next number. For example, we need to change
I need 2 spell better

to
I need to spell better

The obvious way is to jump to the 2, then do:
sto                "Synonymous with 'clto'

Since this is shorter than
:s/2/to<cr>

There are many different ways to jump to the 2. For example,
/2<cr>
ww
2w
ee
2e
8|
f2

As well as many other ways.
These are all 2 (or more) keystrokes. However, since <C-a> and <C-x> not only increment/decrement numbers, but  also jump to the next number, we can take a byte off with
<C-a>sto

Just make sure you didn't add 'alpha' to 'nrformats' and forget, like I did...major confusion! (Though, using vimgolf.com's required vimrc will prevent this from happening.)

There are three "change case" operators,
gu    "Convert to lowercase
gU    "Convert to uppercase
g~    "Toggle case

Since these are operators, they take a motion, so to convert the current character to lowercase you would use
gul

Here's where the fun trick comes in. :) If you want to change the case of a single character or the current line, it's a byte shorter in visual mode. For example gul is equivalent to
vu

And gu_ (_ is current line) is equivalent to
Vu

This trick does not work for toggling, because v? triggers a backwards search in visual mode, (just like v/ but moving in the opposite direction) so you need vg? instead. However, here's where you can use the ~ operator, to save even more bytes! (Thanks @Doorknob for pointing this out)
You can see this trick in action on my vim answer here, and on the equivalent V answer on the and post.

Don't forget ~, which toggles the case of the character under the cursor and moves one to the right!

Know your registers
Yanking or deleting text into a specific register (e.g. "aY) to use it later isn't always necessary. Vim has several registers that are automatically populated with the subjects of various commands. Type :help registers to see them all, but here's a few of particular note:

Unnamed register: "" - The last text that was yanked or deleted.
Numbered register "0 - The last text that was yanked.
Numbered registers "1–"9 - The last text that was deleted unless it was less than one line. Each time "1 is filled its previous contents are shifted to "2 and so on.
Small delete register: "- - The last text shorter than one line that was deleted.
Last inserted text: ".

In particular, the "- and "1 registers can be useful together, enabling you to delete some text with e.g. dd into the "1 register and delete some other text with D into the "- (of course, the semantics aren't identical, but often they don't need to be).
All of the registers can be a little tough to keep track of, but you can see the contents of all of your registers at any time by typing :registers.

Do calculations with the expression register
You can do calculations in both normal mode and insert mode.
Normal mode
In normal mode, if you type @= your cursor will move to the command line, where you can enter any expression. When you press enter, the result of the expression will be executed as normal mode commands.
For example, suppose you want to go to the middle column of the current line. The function call col('$') returns the number of columns in the line, so we can accomplish what by typing the following:
@=col('$')/2<CR>|

When you press enter, the cursor returns to the buffer and vim waits for an operator (like |) as though you had just entered a number. Alternatively, you could have entered this:
@=col('$')/2.'|'

...but of course that's more bytes.
Insert mode
You can use the expression register in insert mode, too, by pressing <Ctrl-r>= instead of @=. It works the same in normal mode, except the result of the expression you enter will be executed in insert mode. For example, if you typed <Ctrl-r>=col('$')<CR>, the number of columns in the current line would be inserted at the cursor as though you had typed it.
For more information on the expression register, type :help "=.
Reusing expressions
The last expression you used is stored in the expression register, "=. Typing @=<CR> in normal mode or <Ctrl-r>=<CR> in insert mode will evaluate the expression again, allowing you to use them much like macros.
Do calculations in substitutions
You can evaluate expressions when doing regular expression substitutions, too. All you have to do is begin your substitution with \=. For example, suppose you wanted to number the lines in this file:
foo
bar
baz

The function call line('.') returns the current line number, so the job is easy. Entering this:
:s/^/\=line('.').' '/g<CR>

...yields the desired result:
1 foo
2 bar
3 baz

To use captured groups in such an expression you can use the submatch() function, where e.g. submatch(0) is equivalent to \0 in an ordinary substitution, submatch(1) is equivalent to \1, etc. This eats up a lot of keystrokes, unfortunately.
For more information on expression substitution, type :help sub-replace-expression.

For your last example there are shorter ways. For example i1 <esc>bqqywjPb<C-a>@qq@q is a pure normal mode solution that is 5 bytes shorter. And if you're on unix, you could even do :%!nl. Still good tips though!

My goal was to demonstrate how to use the feature, not how to number lines in the fewest keystrokes.

Rotate your loops
Rotating loops is a golfing trick in many languages but I've found it to be more frequently useful in vim, largely due to the fact that loops usually exit by failure. This allows you to determine a subset of code to be executed on the first and/or last iteration.
Thus, when you have code like <init>qq<loop>@qq@q<finalize>, try to see if you can rotate the loop in order to overlap with either the init code or the finalize code so that they can be merged. Here's an example I used in a recent golf.
A straightforward 16 byte solution might look like this:
x$pqqF xp@qq@qZZ

This moves the first character to the end, and then in the loop moves backwards to the previous space character and swaps it with the letter that follows it, once it reaches the first space character. One can check that this algorithm solves the challenge in general.
The observation we can make here is that we wrote p twice: once just before the loop and once just at the end of it. It turns out we can merge them together like so:
x$qqpF x@qq@qZZ

Notice how we managed to save a character by only writing p once: we rotated the loop by one character and had the first iteration of the loop do us the favor of finishing up the init work of pasting the first character at the end of the string. Note that the total execution pattern of this solution is exactly the same as the previous one, since we will still exit the loop on failure of the final F  command.
(Technical NB: there's some added subtleties on the Anarchy Golf server since macro definitions are saved between test cases, and because of this the solution above won't work on the 2nd and 3rd test cases when q is already defined. My linked solution is roughly equivalent but loses a bit of generality to get around this.)

You can directly modify the text of a macro, which can be significantly shorter than a convoluted conditional. For example, let's say you want to paste something n times, where n is user input. I first tried to do this:
qq/[1-9]<enter><c-x>``p@qq@q

Explanation:
qq                             #Start Recording
  /[1-9]<enter>                #Search for a number that isn't 0.
                <c-x>          #Decrement that number
                     ``p       #jump back to your previous location and paste.
                        @q     #Recursive call to macro 'q'
                          q@q  #Stop recording, and run the macro

This is 18 keystrokes, and a really ugly way to do it. Instead, go to the location of that number, and do this:
Ap<esc>"qdd@q

Explanation:
Ap<esc>                 #Append a 'p' to the end of the current line.
       "qdd             #Delete the current line into register q
           @q           #Run macro q.

This is 9 keystrokes, a huge improvement.
Edit:
Even shorter is to run the macro for your number, and then type your command. For example:
"qdd@qp

Explanation:
"qdd         #Delete the current line into register q
    @q       #Run register q
      p      #Paste

7 keytstrokes.

Use D, not dd. 2. If the command doesn't involve registers, you can make it even shorter. For example, if you want to repeat the character x as many times as the number under the cursor, instead of "qD@qix<esc>, use D@"ix<esc>.


text:
Display powers of Phi with Fibonacci precision
Write some code that takes a single non-negative integer \$n\$ and outputs the \$n\$th power of phi (\$\phi\$, the Golden Ratio, approximately 1.61803398874989) with the same number of decimal digits as the \$n\$th Fibonacci number.
Your code must produce the correct sequence of digits for all inputs up to at least 10 (55 decimal digits). The output must be human-readable decimal. You may choose whether to round the last digit to the closest value, or truncate the value. Please specify which one your code uses.
\$n\$ and output, up to 10, rounding down:
 0   1
 1   1.6
 2   2.6
 3   4.23
 4   6.854
 5  11.09016
 6  17.94427190
 7  29.0344418537486
 8  46.978713763747791812296
 9  76.0131556174964248389559523684316960
10 122.9918693812442166512522758901100964746170048893169574174

\$n\$ and output, up to 10, rounding to the closest value:
 0   1
 1   1.6
 2   2.6
 3   4.24
 4   6.854
 5  11.09017
 6  17.94427191
 7  29.0344418537486
 8  46.978713763747791812296
 9  76.0131556174964248389559523684316960
10 122.9918693812442166512522758901100964746170048893169574174

The 7th Fibonacci number is 13, so the output for \$n=7\$, \$\phi^7\$, has 13 decimal places. You must not truncate trailing zeros that would display too few digits; see output for 6 in the first table, which ends in a single zero to keep the decimal precision at 8 digits.
Maybe as a bonus, say what the highest number your program can correctly output is.

What about languages that can't handle that many decimal places? I got a 24 byte Pyth solution here that only works till n=7, since I can't display more than 15 decimal places. Should I post it anyway?

@DenkerAffe Sure, you can post it but with a note saying that it's not valid because it can't do the last three test cases. It might be inspiration for someone to add precision to your answer!

dc, 26 bytes
99k5v1+2/?^d5v/.5+0k1/k1/p

Due to the initial precision of 99 digits after the comma, this will work up yo input 11. A dynamic (or higher static) precision is possible, but would elevate the byte count.
Test cases
$ for ((i = 0; i < 11; i++)) { dc -e '99k5v1+2/?^d5v/.5+0k1/k1/p' <<< $i; }
1
1.6
2.6
4.23
6.854
11.09016
17.94427190
29.0344418537486
46.978713763747791812296
76.0131556174964248389559523684316960
122.9918693812442166512522758901100964746170048893169574174

How it works
Since the desired output is φn, we can calculate the the Fibonacci number F(n) as ⌊φn ÷ √5 + 0.5⌋ with little additional effort.
99k                         Set the precision to 99.
   5v                       Compute the square root of 5.
     1+                     Add 1.
       2/                   Divide by 2.
                            This pushes the golden ratio.
         ?                  Read the input from STDIN.
          ^                 Elevate the golden ratio to that power.
           d                Push a copy.
            5v/             Divide it by the square root of 5.
               .5+          Add 0.5.
                  0k        Set the precision to 0.
                    1/      Divide by 1, truncating to the desired precision.
                            This pushes F(n).
                      k     Set the precision to F(n).
                       1/   Divide by 1, truncating to the desired precision.
                         p  Print.

Mathematica, 50 bytes
N[GoldenRatio^#,2^#]~NumberForm~{2^#,Fibonacci@#}&

Basic solution. Rounds to the nearest value. Still verifying the highest value that won't make my computer run out of memory. Input 32 works, but it takes 45 minutes and uses 16GiB of RAM. However, given infinite time and memory, this could theoretically run for any value.

Would you post the output please? I need to cheat and use your output to add the last few test cases. Which way are you rounding? Down or to nearest? "Infinite resources" is good enough. I don't require that you run out of memory!

Javascript, 65 bytes
a=>Math.pow((1+Math.sqrt(5))/2,a).toFixed(k(a));k=b=>b?b+k(b-1):0

Getting Phi by calculating (1+Math.sqrt(5))/2.
Getting Fib value using the function: k=b=>b?b+k(b-1):0.
Try it out

.5+Math.sqrt(5)/2 removes 1 byte

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Electrical outlet
This is a problem from NCPC 2005.  Roy has
an apartment with only one single electrical outlet, but he has a bunch of power strips.
Compute the maximum number of outlets he can have using the power strips he
has.  The number of outlets per power strip is given as input.
It turns out that if the number of outlets of the strips respectively are
$$p_1,  p_2, \dots, p_n$$
then the number of outlets is
$$1 - n + \sum_i p_i$$ ,
or
$$1 + p_1-1 + p_2-1 + \dots + p_n-1$$.
The input to the program or function is a non-empty series of positive integers.
Examples
2 3 4
> 7
2 4 6
> 10
1 1 1 1 1 1 1 1
> 1
100 1000 10000
> 11098

And I thought you weren't supposed to chain power strips ...

As far as I can tell my Retina answer is the only answer using unary input. You might want to have a look at the comment discussion there: http://codegolf.stackexchange.com/questions/71047/electrical-outlet/71062#comment174286_71059 ... If you think that the unary solution is too much of a hack that's not in the spirit of the challenge, I'm happy for you to specify that the input should be in decimal (and will then fix my answer accordingly).

@PålGD The tied Jelly answer was posted earlier anyway.

Because electricity is so expensive, your code should be as short as possible as to avoid using more energy

If a space-separated list of unary numbers is okay, how about a backspace-separated list of unary numbers?

@cat Time to dig out the old hamster driven turing machine and mechanical computers.

@immibis sure, but the output would be treated as the information contained in the byte stream not as what happens to by rendered by your terminal.

Jelly, 3 bytes
’S‘

Decrement (all), sum, increment. Try it here.

Retina, 3 bytes
 1

The trailing linefeed is significant.
Input is a space-separated list of unary numbers.
Try it online!
Explanation
The code simply removes all spaces as well as the 1 after them from the string. Here is why that works:
Addition in unary is simple: just concatenate the numbers which is the same as removing the delimiters. Decrementing by 1 is also simple: just remove a 1 from each number. We want 1 more than the sum of the decremented inputs though, so we simply only remove the 1s we find after spaces, thereby decrementing all but the first input.

I'm wondering if input in unary should be allowed.

@JanDvorak it is by default, unless the challenge explicitly specifies decimal input. (See the link in the answer.) Doesn't matter though, Jelly is winning anyway.

@MartinBüttner There's sample data both in this question and the original assignment. Don't you think (unless otherwise stated) that it should be a necessary (though not sufficient) criterion for passing, that the code works with the verbatim sample data?

@nitro2k01 No (in  that case most answers would probably be invalid). Unless the challenge explicitly specifies one particular input format we normally assume that lists can be taken in any native list format. Same goes for number formats (at least unary and taking integers as byte values are allowed by consensus unless the challenge forbids them). It's pretty much impossible to include sample data in every thinkable native input format in the challenge.

@MartinBüttner Imo, that's not the problem that the recommendation is addressing. What still speaks against this is that (unless I'm mistaken) this doesn't work because unary is a supported or native number format in Retina but it happens to work when you process the string as string data. It's a hack. It's even a clever hack, but I'm still not convinced that's it's according to the rules. If space-separated unary numbers was a native format in Retina in the same way that a list of bytes is a native format in bf, I would agree the recommendation applies and I would have a different opinion.

For completeness, perhaps its worth adding to- and from-unary conversion, just because it can be done.  Of course a score of 22 is nowhere near as spectacular a 3 ...

If a space-separated list of unary numbers is okay, how about a backspace-separated list of unary numbers?

Hexagony, 18 14 bytes
.?<_(@'")>{+.!

Unfolded:
  . ? <
 _ ( @ '
" ) > { +
 . ! . .
  . . .

Try it online!
I don't think side-length 2 is possible, but there must might be a more efficient side-length 3 solution that this.
This is the usual "decrement all, sum, increment" approach, but I'll have to add diagrams later to show how exactly it works in Hexagony.

Python, 24 bytes
lambda*n:1-len(n)+sum(n)

Try it online

This assumes that the function is first assigned, then applied to the input from other variable.

@juandesant ...which is perfectly fine. It's a function literal, which is a valid form of submission.

Mathematica, 9 bytes
Tr[#-1]+1&

Haskell, 17 15 bytes
foldl1$(+).pred

Usage example: ( foldl1$(+).pred ) [2,4,6] -> 10.
Old version, different approach, 17 bytes: succ.sum.map pred.

J, 6 bytes
+/+1-#

Sum plus one minus length. Parenthesize and apply it, like so:
   (+/+1-#) 2 3 4
7

Labyrinth, 9 bytes
"?;)!@
+(

Try it online!
The usual primer:

Labyrinth is 2D and stack-based. Stacks have an infinite number of zeroes on the bottom.
When the instruction pointer reaches a junction, it checks the top of the stack to determine where to turn next. Negative is left, zero is forward and positive is right.

Here we start at the top left ", a no-op, heading rightward. Next is ?, which reads an int from STDIN (throwing away chars it can't parse as an integer, e.g. spaces). Now we have two cases:
If the input is positive, we turn right, performing:
(            decrement top of stack
+            add top two stack elements
             [continue loop]

If the input is zero (which occurs at EOF), we go straight ahead, performing:
;            pop zero from EOF
)            increment top of stack
!            output top of stack as number
@            halt program

Pyth, 5 bytes
hstMQ

increment(sum(map(decrement, input)))

ES6, 25 bytes
a=>a.map(n=>r+=n-1,r=1)|r

I was going to post: "One of the rare cases when reduce wins the game" ... and it's 25 too l=>l.reduce((a,b)=>a+b-1).

@edc65 Yeah, the (,b) is costly, but I like that version too.

MATL, 3 bytes
qsQ

Try it online.
Explanation
qsQ
q      thread decrement over the input array
  s    sum
   Q   increment

Starry, 26 24 bytes
, + '`      + ** `, +'*.

Expects newline-separated integers. Try it online!
Thanks to @MartinBüttner for -2 bytes.
,           Read line as integer
 + '        Dupe and jump to label 1 if nonzero
`           Set label 0
      +     Push 1
 *          Sub
*           Add
 `          Set label 1
,           Read line as integer
 + '        Dupe and jump to label 0 if nonzero
*           Add
.           Output as integer

The loop is unrolled so that the first number is not decremented, negating the need to increment. Pushing numbers is expensive in Starry...

I count only 20 bytes.

@VoteToClose Did you count the leading spaces? (I'm assuming you're talking about the 26 byte)

05AB1E, 4 bytes
Code:
E<O>

Explanation:
E     # Evaluates input
 <    # Decrement on list
  O   # Compute the total sum
   >  # Increment on the sum
      # Implicit: output top of the stack

Takes input like an array (e.g. [3, 4, 5]).

Very elegant for a golfing lang

Bash + GNU utilities, 16
If there are N power strips, then there should be N-1 separators in the comma-separated input list.  All we need to do is replace the separators with - 1 + and arithmetically evaluate:
sed s/,/-1+/g|bc

Or using the same trick:
Pure Bash (no external utilities), 19
echo $[${1//,/-1+}]

APL (NARS 2000), 13 10 bytes
{1+(+/⍵)-⍴∊⍵}
Edit: Down to 10 with Lynn's (better) approach.
{1++/1-⍨⍵}

CJam, 7 bytes
q~:(:+)

Test it here.
Same approach as Lynn's (decrement all, sum, increment). This also works for 8 bytes (and is maybe a bit more interesting):
q~{(+}*

This folds "decrement, add" over the list. By doing that, the decrement is only applied to all elements except the first, such that we don't need to take care of the increment separately.

gs2, 5 bytes
(CP437-encoded.)
W&Φd'

That’s read-nums dec m1 sum inc.

Seriously, 7 bytes
,;l@Σ-u

Try it online!
Explanation:
,;l@Σ-u
,        push input
 ;       dupe
  l@     push length (n), swap
    Σ-u  push sum, subtract n, add one

C, 60 59 55 bytes
x;main(s){while(~scanf("%i",&x))s+=x-1;printf("%i",s);}

Perl 6, 14 bytes
{1+[+] --«@_}

usage
my &f = {1+[+] --«@_}

say f([2,3,4]) # 7
say f([2,4,6]) # 10
say f([1,1,1,1,1,1,1,1]) # 1
say f([100,1000,10000]) # 11098

I fully intended to edit my answer to the very same thing ( see the html comment)

11 bytes: {.sum-$_+1}

Mornington Crescent,  1909 1873  1839 bytes
Take Northern Line to Stockwell
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Embankment
Take Northern Line to Stockwell
Take Northern Line to Embankment
Take Circle Line to Temple
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Blackfriars
Take Circle Line to Embankment
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Parsons Green
Take District Line to Embankment
Take Circle Line to Blackfriars
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

Try it online!

"90% of all instructions involve takeing the District Line." It's because District is where all the arithmetic stations are. However, on TIO, it doesn't seem to work for any of the examples.

1873 bytes by using shorter line names where possible

TIO's interpreter has a bug and doesn't implement Turnham Green

Nice catch. I've sent a PR that fixes it upstream.

Perl 6, 20 bytes
put 1+sum --«@*ARGS

( You can use << instead of « )
Usage:
$ perl6 -e 'put 1+sum --«@*ARGS' 100 1000 10000
11098

« is a Perl operator?

@immibis Actually it's part of several Perl 6 operators @arraya »+« @arrayb ++«@array @array».method @array»++ « a 'space separated' list of words » Several of those are what is known as Meta operators, in that they combine with other operators. ( Perl 5 doesn't have those operators currently. )

Perl 5 23+2=25 or 19+2=21
Requires -ap flags:
map{$.+=($_-1)}@F;$_=$.

Saved in a file and run as
perl -ap file.pl

EDIT: Another answer, smaller (19+2) but basically copied from dev-null answer:
$.+=$_-1for@F;$_=$.

F#, 25 bytes
Seq.fold(fun s n->s+n-1)1

This is a function that takes in an array/list/sequence of integers and returns the required result.
How it works:
Seq.fold allows you to apply a function to every element of a sequence while carrying some state around while it does so. The result of the function as applied to the first element will give the state that will be put into the function for the second element, and so forth. For example, to sum up the list [1; 3; 4; 10], you'd write it like this:
Seq.fold (fun sum element -> sum + element) 0 [1; 3; 4; 10]
         (       function to apply        ) ^ (sequence to process)
                                     ( initial state )

Which would be applied like so:
// First, initial state  + first element
0 + 1  = 1
// Then, previous state + next element until the end of the sequence
1 + 3  = 4
4 + 4  = 8
8 + 10 = 18

With the last state being the return value of Seq.fold.

, 5 chars / 7 bytes
ï⒭+‡_

Try it here (Firefox only).
Uses a custom encoding with 10-bit chars (thx @Dennis!). Run encode('ï⒭+‡_') in the JS console to get encoded form, and decode(/*ENCODED TEXT HERE*/) to decode encoded form.
Explanation
Translates to Javascript ES6 as:
i=>i.reduce(($,_)=>$+--_)

Interesting encoding.

It works quite nicely, too.

Python 3, 79 bytes
import sys
print(sum(map(lambda x: int(x)-1, sys.stdin.readline().split()))+1)

Looks like you're counting a newline as two bytes. Maybe replace it with a semi-colon to save a byte. A few spaces can be removed too.

Perl, 21 + 2 = 23 bytes
$a+=$_-1for@F;say++$a

Requires -a and -E:
$ perl -aE'$a+=$_-1for@F;say++$a'<<<'2 3 4'
7

You can use the -a flag to get @F variable with already split elements, and replace -n with -p so you dont'need say, reducing it to 21+2: $a+=$_-1for@F;$_=++$a

Using -p instead of say is the same because I need to use $_= anyway.

@ChatterOne -a is a good idea!

Ruby, 30 bytes
$*.inject(1){|s,v|s+=v.to_i-1}

Simple enough - starting from 1, add up the supplied numbers, each -1 (command line args are in $*). Shame inject is such a long word.

PowerShell, 19 bytes
$args-join'-1+'|iex

Note that 1 + p1-1 + p2-1 + ... + pn-1 is equivalent to p1-1 + p2-1 + ... + pn.
Takes input as separate command-line arguments with $args. We -join those together with a -1+ delimiter to create a string, such as 2-1+3-1+4. The string is then piped to Invoke-Expression (similar to eval), and outputs the result.

Brainfuck, 15 bytes
Assumption: The , operator returns 0 once all input has been exhausted, and there are no extension cords with 0 plugs. Also, the IO needs to be in byte values instead of ASCII character codes.
+>,[-[-<+>],]<.

Explanation:
This uses 2 registers. A "Value" accumulator register, representing the number of devices that can be plugged in, and a "current cord" register that keeps track of the value of the current cord. It starts off by incrementing the value by 1, for the existing outlet. Then, for each extension cord, it subtracts one from the value since a plug is being taken up, then increments the value by the number of plugs.
Most online interpreters don't operate in raw byte input mode. To test it online, use this code:
+>,[->-[>+<-----]>---[-<+>]<[-<->]<[-<+>],]<.

Can I test the program somewhere?

Thanks, corrected those mistakes. I'm not aware of any online interpreters that operate in byte mode. I can throw together an implementation that subtracts '0' from the inputs that will run on any online interpreter.

If you want to test out the code, run it here: https://copy.sh/brainfuck/
Don't put spaces in between the numerical values. Unfortunately, since it's operating in ASCII mode, the demo code will only work on single digit values. However, the 15 byte version will work properly on an value <= 255.
After you run it, view the memory dump to view the final value.

One day BF will have proper standards for expected IO and we'll just be able to say 'using standard 3' instead of e.g. 'input and output are all asciii terminated by null char'.

PARI/GP, 17 bytes
Completely straightforward.
v->vecsum(v)-#v+1

Pylons, 6
Takes a list of space separated numbers on the command line then sums them all and subtracts the length.
1(i)-s

How it works:
1   # Push 1 to the stack.
(   # Start a list.
 i  # Get command line input.
  ) # End a list.
-   # Subtract the top two elements of the stack. In the case where one of the elements is
    # a list, it does matrix subtraction.
s   # Sum the stack.
    # Print the stack implicitly.

R, 24 14 bytes
sum(1,scan()-1)

Edit: Fixed bug!

@PålGD it was a bug [untested code posted on phone]

Python, 10+22=32 bytes
s=input();print(sum(s)-len(s)+1)

Main issue is not having a default input variable in Python, or implicit printing.

APL Nars 9 chars
{1++/⍵-1}

test
f←{1++/⍵-1}
  f 2 3 4
7
  f 2 4 6
10
  f 1 1 1 1 1 1 1 1
1
  f 100 1000 10000
11098

TIS, 93 bytes
Code:
@0
MOV ANY ANY
@1
MOV UP ACC
JGZ G
SWP
ADD 1
MOV ACC DOWN
G:SUB 1
MOV ACC ANY
SWP
ADD ANY
SWP

Layout:
1 2 CC
I1 NUMERIC -
O1 NUMERIC -

Try it online!
Note that this solution requires the list to be terminated by a zero (or more accurately, a non-positive value).
With TIS, we'd need to choose one of the following a) a terminating character, b) a length-prefixed array, or c) a running output for every value. Otherwise, a program would never print any output because there (theoretically) could be more input on the way.
Explanation:
Each node has two accumulators, called ACC and BAK. BAK can only be accessed by the SWP instruction, which swaps the values in ACC and BAK. In the following, I will use variables X and Y to track the values more directly. I'll also use Z as shorthand for the entire node 0.
Additionally, each node implicitly loops back to the top when it reaches the bottom.
                                  |    Input 0    | Input as whitespace-delimited numbers
                  +--------+------+--------+------+
                  | Node 0 |      | Node 1 |      |
Node 0 is just an +--------+      +--------+      |
extra memory cell | MOV ANY ANY   | MOV UP ACC    | Put input value into X
so we can perform |               | JGZ G         | If X>0, jump to label G
logic on input    |               | SWP           | Swap focus to Y
values easier     |               | ADD 1         | Y++
                  |               | MOV ACC DOWN  | Output the value Y
                  |               |               | (end program -- see note 1 below)
                  |               | G:SUB 1       | Label G: X--
                  |               | MOV ACC ANY   | Z = X (also see note 2 below)
                  |               | SWP           | Swap focus to Y
                  |               | ADD ANY       | Y += Z (also see note 2 below)
                  |               | SWP           | Swap focus to X
                  +---------------+---------------+
                                  |   Output 0    | Output as whitespace-delimited numbers

Note 1, regarding the termination of this program:
The TIS emulator I am using here will terminate the program once there is no more active processing. The most common reason for getting into such a state is to exhaust all available input, though things like deadlocks can also get us to this state.
Once the value in this program has been output, calculation will continue on at label G, mangling the data in the registers (it forgets which register is X and which is Y). However, it will quickly return to the line that reads input, and because the input will now be exhausted, the program will terminate.
Some minor modifications may be made to adjust the program to handle data after the terminator:

Adding the instruction HCF just before the label G will cause the program to forcibly terminate at this point instead of relying on input exhaustion.
Adding the instructions SWP and JRO -99 just before the label G will cause the program to return to a good state, then jump back to top (relative jumps can't wrap, so anything further than -15 will always go to the top line; offhand, I think -7 is the exact value needed here). This turns the terminator into a 'print' instruction instead.
The value Y could be reset to zero, in addition to the jump described above, to treat extended input as two or more distinct invocations.

Note 2, regarding the use of ANY in node 1:
The use of ANY on the two marked lines of Node 1 is possible due to an implementation detail (this quirk is true in both this emulator and in the original Zachtronics game).
When ANY is used as the source, it looks at the node's neighbors in this order: LEFT, RIGHT, UP, DOWN. When ANY is used as the destination, it looks at the neighbors in this order: UP, LEFT, RIGHT, DOWN. (The destination ordering is a consequence of both the source ordering and the order in which the nodes are run.)
Of course, the nodes not only need to be present but also be ready to send/receive a value to be selected.
Since LEFT appears before UP as a source, and before DOWN as a destination, ANY will always be LEFT in this case.
To make this program "implementation-independent", simply replace those two ANYs with LEFTs.
The reason that the ANYs in node 0 are of no concern is that node 0 only ever has one neighbor to talk to.

K (oK), 6 bytes
1+/-1+

Try it online!

Dodos, 27 bytes
	dot dip +
+

	dot dab dot

Try it online!
Explanation:
The main function (top line, implicitly named main) is called at the start of the program. It contains this command:
dot dip +

+ is called on the tuple given as separate command-line arguments. This is +:

dot dab dot
The empty command simply returns the argument as-is. The other command, dot dab dot, returns 0. It has to be able to convert any given tuple to zero, so here's how this does it, right-to-left:
First of all, dot returns a 1-element tuple that contains the sum of the input's elements. The actual sum doesn't matter here, what matters is that dot will always return a 1-element tuple, so that we can use dab on it to remove its first (i.e. only) element, since there's no built-in to empty a tuple. The sum of an empty tuple is 0, so we just dot this empty tuple to return the singleton 0.
After this process, the two results of the + function (the input and 0) are implicitly concatenated. We now return to main.
The dip command will decrement each positive number by 1, and convert each 0 to 1, in +'s result. This will decrement each number of available outlets, and also increment the final 0, so we don't miss a free outlet.
Finally, the tuple will be dotted again, so we're computing the number of available outlets over all of the power strips, minus the number of power strips, plus one (no strip occupies an outlet of the last strip).

Common Lisp, 40 bytes
(lambda(x)(1+(-(reduce'+ x)(length x))))

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What language is this word?
Your should write a program or function that determines the language of a given word.
The task is to recognize some of the 5000 most common words in 4 languages:

English
German
Italian
Hungarian

The word lists can be found in this GitHub repository.
You are allowed to make mistakes in 40% of the provided test cases. I.e. you can miscategorize 8000 of the 20000 inputs.
Details

The lists only contain words with lowercase letters a-z so e.g. won't and möchte are not included.
A few words appear in multiple languages which means your code can't always guess the expected output correctly.
For convenience you can download all the test cases as one list. In each line a number indicates the language of the word. (1 for English, 2 for German, 3 for Italian and 4 for Hungarian.)
Standard loopholes are disallowed.
Using word lists our similar data provided by your programming language is forbidden.

Input

A string containing only lowercase English letters (a-z).
Trailing newline is optional.

Output

You can categorize the words by providing a distinct and consistent (always the same) output for each language. (E.g. 1 for English, 2 for German, 3 for Italian and 4 for Hungarian.)

This is code golf so the shortest program or function wins.
Related code golf question: Is this even a word?
The word lists were taken from wiktionary.org and 101languages.net.

are you sure the lists are correct? Im pretty sure i never heard the in german. Does outputting an array with all possible languages count? e.g. the apparently is in all languages so it woul put {1,2,3,4}

@Eumel The first couple  English words might be present somewhere in the other lists as there might be English phrases in the texts of languages which were used to generate the word lists. Your can categorize an input into only one language. (Whihch means as mentioned in the question that "your code can't always guess the expected output correctly".)

The lists only contain words with lowercase letters ... That's not entirely true. The all_languages file includes dozens of capitalized words (Mr, Gutenberg, etc.) and the non-words "" (empty string) and "]]|-". I assume it's OK to lowercase the former and delete the latter?

@squeamishossifrage Thanks for the catch. Updated the English lists. (There were ~60 uppercase words and 2 non-words.)

Why remove diacritics? If the goal is to distinguish languages that don’t have diacritics, then why not use languages that don’t have diacritics?

"p" is a word? (all words list)

Retina, 51 bytes
.*[aeio]$
1
A`en$|ch|ei|au
^$
2
A`[jkz]|gy|m$
\D+
4

I came up with the regexes and @MartinBüttner did the conversion to/golfing in Retina so ... hurray for team effort?
The mapping is 1 -> Italian, 2 -> German, (empty) -> Hungarian, 4  -> English, with the amount classified in each category being 4506 + 1852 + 2092 + 3560 = 12010.
Try it online! | Modified multiline version
Explanation
First off, the equivalent Python is something like this:
import re
def f(s):
  if re.search("[aeio]$", s):
    return 1
  if re.search("en$|ch|ei|au", s):
    return 2
  if re.search("[jkz]|gy|m$", s):
    return ""
  return 4

Let me just say that o$ is an excellent indicator of Italian.
The Retina version is similar, with pairs of lines forming replacement stages. For example, the first two lines
.*[aeio]$
1

replaces matches of the first line with the contents of the second.
The next three lines do the same, but using Retina's anti-grep mode - anti-grep (specified with A`) removes the line if it matches the given regex, and the following two lines is a replacement from an empty line to the desired output.
A`en$|ch|ei|au
^$
2

The following line uses anti-grep again, but doesn't replace the empty line, giving the fixed output for Hungarian.
A`[jkz]|gy|m$

Finally, the last two lines
\D+
4

replaces a non-empty non-digit line with 4. All of the substitutions can only happen if no previous substitution activated, simulating an if/else if chain.

Why do you return "" for Hungarian, and not 3?

LabVIEW, 29 LabVIEW Primitives and 148.950 Bytes
cycles through the languages and puts the iterator into an array if the word is there. This gets checked by the inner loop, picking the ith line and doing =. In LabVIEW it only gives a true if the Strings are exactly the same.
Now take the first element of output array so englishgoes over the rest.
The output for now is 0 for English, 1 for German, 2 for Italian and 3 for Hungarian.

I'm not familiar with LabView, but how do you store the values (word lists) and how are they reflected in the LabView Primitives? The meta entry says: "Constants: strings are 1 LabVIEW Primitive per character". Wouldn't that heavily increase the Primitive count?

I load the from a file which is directory path + build path with string + load file. The storage is done internally and gets passed by the wires.

I might be wrong, but I think core of the challenge is about how to compress/store the wordlists. So loading from an external file might be disallowed. Will ask the OP about that. :)

If you use an external file, it's size should be added to your code size as that is a part of your solution.

i was under the impression that those were supposed to be given but ill add them np

Java, 3416 bytes, 62%
this is my solution, i analyze list of given words and find 60 most commons bigrams and trigrams for each languages. Now i'm checking my n-grams against word, and choosing language with most n-grams in word.
public class Classificator {

    String[][] triGr = {
            {"ing","ion","ent","tio","ted","nce","ter","res","ati","con","ess","ate","pro","ain","est","ons","men","ect","red","rea","com","ere","ers","nte","ine","her","ble","ist","tin","for","per","der","ear","str","ght","pre","ver","int","nde","the","igh","ive","sta","ure","end","enc","ned","ste","dis","ous","all","and","anc","ant","oun","ten","tra","are","sed","cti"},
            {"sch","che","ver","gen","ten","cht","ich","ein","ste","ter","hen","nde","nge","ach","ere","ung","den","sse","ers","and","eit","ier","ren","sen","ges","ang","ben","rei","est","nen","nte","men","aus","der","ent","hei","her","lle","ern","ert","uch","ine","ehe","auf","lie","tte","ige","ing","hte","mme","end","wei","len","hre","rau","ite","bes","ken","cha","ebe"},
            {"ent","are","ato","nte","ett","ere","ion","chi","con","one","men","nti","gli","pre","ess","att","tto","par","per","sta","tra","zio","and","iam","end","ter","res","est","nto","tta","acc","sci","cia","ver","ndo","amo","ant","str","tro","ssi","pro","era","eri","nta","der","ate","ort","com","man","tor","rat","ell","ale","gio","ont","col","tti","ano","ore","ist"},
            {"sze","ere","meg","ett","gye","ele","ond","egy","enn","ott","tte","ete","unk","ban","tem","agy","zer","esz","tet","ara","nek","hal","dol","mon","art","ala","ato","szt","len","men","ben","kap","ent","min","ndo","eze","sza","isz","fog","kez","ind","ten","tam","nak","fel","ene","all","asz","gon","mar","zem","szo","tek","zet","elm","het","eve","ssz","hat","ell"}

                    };
    static String[][] biGr = {
        {"in","ed","re","er","es","en","on","te","ng","st","nt","ti","ar","le","an","se","de","at","ea","co","ri","ce","or","io","al","is","it","ne","ra","ro","ou","ve","me","nd","el","li","he","ly","si","pr","ur","th","di","pe","la","ta","ss","ns","nc","ll","ec","tr","as","ai","ic","il","us","ch","un","ct"},
        {"en","er","ch","te","ge","ei","st","an","re","in","he","ie","be","sc","de","es","le","au","se","ne","el","ng","nd","un","ra","ar","nt","ve","ic","et","me","ri","li","ss","it","ht","ha","la","is","al","eh","ll","we","or","ke","fe","us","rt","ig","on","ma","ti","nn","ac","rs","at","eg","ta","ck","ol"},
        {"re","er","to","ar","en","te","ta","at","an","nt","ra","ri","co","on","ti","ia","or","io","in","st","tt","ca","es","ro","ci","di","li","no","ma","al","am","ne","me","le","sc","ve","sa","si","tr","nd","se","pa","ss","et","ic","na","pe","de","pr","ol","mo","do","so","it","la","ce","ie","is","mi","cc"},
        {"el","en","sz","te","et","er","an","me","ta","on","al","ar","ha","le","gy","eg","re","ze","em","ol","at","ek","es","tt","ke","ni","la","ra","ne","ve","nd","ak","ka","in","am","ad","ye","is","ok","ba","na","ma","ed","to","mi","do","om","be","se","ag","as","ez","ot","ko","or","cs","he","ll","nn","ny"}

                    };

    public int guess(String word) {

        if (word.length() < 3) {
            return 4; // most words below 2 characters on list are hungarians
        }
        int score[] = { 0, 0, 0, 0 };
        for (int i = 0; i < 4; i++) {
            for (String s : triGr[i]) {
                if (word.contains(s)) {
                    score[i] = score[i] + 2;
                }
            }
            for (String s : biGr[i]) {
                if (word.contains(s)) {
                    score[i] = score[i] + 1;
                }
            }
        }
        int v = -1;
        int max = 0;
        for (int i = 0; i < 4; i++) {
            if (score[i] > max) {
                max = score[i];
                v = i;
            }
        }
        v++;
        return v==0?Math.round(4)+1:v;
    }
}

and this is my testcase
public class Test {

    Map<String, List<Integer>> words = new HashMap<String, List<Integer>>();

    boolean validate(String word, Integer lang) {
        List<Integer> langs = words.get(word);
        return langs.contains(lang);
    }

    public static void main(String[] args) throws FileNotFoundException {

        FileReader reader = new FileReader("list.txt");
        BufferedReader buf = new BufferedReader(reader);
        Classificator cl = new Classificator();
        Test test = new Test();
        buf.lines().forEach(x -> test.process(x));
        int guess = 0, words = 0;
        for (String word : test.words.keySet()) {
            int lang = cl.guess(word);
            if (lang==0){
                continue;
            }
            boolean result = test.validate(word, lang);
            words++;
            if (result) {
                guess++;
            }
        }
        System.out.println(guess+ " "+words+ "    "+(guess*100f/words));
    }

    private void process(String x) {
        String arr[] = x.split("\\s+");
        String word = arr[0].trim();
        List<Integer> langs = words.get(word);
        if (langs == null) {
            langs = new ArrayList<Integer>();
            words.put(word, langs);
        }
        langs.add(Integer.parseInt(arr[1].trim()));

    }

}

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Build a chessboard
Saw this in a PHP challenge. The objective is to make a chessboard with 64 squares (8*8) with the minimum amount of code.
Simple enough, I made mine in PHP in 356 bytes (not impressive, I know) and I would like to see some other aproaches.
This can be made in a language of your choice, as long as you keep it vanilla, so no imports.
Smallest byte count wins.
The output should look like this:

And my code:

<?php
$c='black';function p($c,$n){echo'	';if($n==1){echo"
";}}for($i=1;$i<=64;$i++){if($i%8==0&&$c=="black"){$c="white";$n=1;}elseif($i%8==0&&$c=="white"){$c="black";$n=1;}elseif(isset($n)&&$n==1){$n=0;}elseif($c=="black"){$n=0;$c="white";}elseif($c=="white"){$n=0;$c="black";}p($c,$n);}

Or readable:

<?php
$color = 'black';
function printcolor($color, $nl) {

    echo '	';
    if ($nl == true) {
        echo "

";
    }
}
for ($i=1; $i<=64;$i++) {
    if ($i % 8 == 0 && $color == "black") {
        $color = "white";
        $nl = true;
    } elseif ($i % 8 == 0 && $color == "white") {
        $color = "black";
        $nl = true;
    } elseif (isset($nl) && $nl == true) {
        $nl = false;
    } elseif ($color == "black") {
        $nl = false;
        $color = "white";
        }
    elseif ($color == "white")  {
        $nl = false;
        $color = "black";
    }
    printcolor($color, $nl);
}

Edit:
Sorry I wasn't very specific at first:

Squares should have 50px * 50px except for vectorial images.
Output format or size is not relevant nor it needs to be an image.
For evaluation purposes the output must be visible such as in an image file or a screenshot
No libraries written after the challenge was posted

Minimum number of pixels? I assume 64 is not sufficient?

Welcome to PPCG, as it stands, this challenge doesn't really have anything to do with PHP, so I changed your tags. Also, I believe your reference implementation belongs as an answer, not in your question. As Stewie brought up, you should specify the required size of the image output, as well as things like colour specifics and whether a lossy image is allowed.

Can the output be in any image format?

Sorry for the delay, for some reason the JS on stackexchange has issues on my Google chrome. Sorry for not being very specific, it's my first post here. Image format or size is not relevant. Squares should have 50px * 50px.

So some ASCII-magic is not allowed? :(

This pattern is more commonly referred to as a checkerboard, this challenge doesn't really have anything to do with chess as a game.

@DenkerAffe You could output in PPM.

@mınxomaτ Sorry, I just saw the title and instinctively added the chess tag :P I'll remove that.

How will you evaluate that the program works? Online compilers don't usually allow graphic output. Also, should the upper-left square be white, or can it be black?

@DenkerAffe, for ASCII there is Chessboard pattern.

@LuisMendo The output must be visible, like an image file or a print screen. It should start and end with a white square

Are vector graphics allowed as output?

Also can there be any kind of frame around the result?

@MartinBüttner Vector graphics are allowed, as long as the colors and dimensions of the squares are correct. There can be a frame around the result.

Define "imports"? Does using external programs in Bash count as imports? (Keep in mind that this would be a very severe restriction—even basic commands like cat are external programs.)

Basic commands in bash like cat are allowed.

How basic is basic? What is the definition of an "import"?

Bash suport cat outsider the box so it's valid. However if you download and include a third party library, it's not.

@Bruno do the squares have to be black and white? Can they be black and grey for example (as long as the difference is obvious)

@muddyfish they must be b&w like a propper checkerboard :)

@Doorknob You can't say things like this and expect us not to see it as a challenge http://codegolf.stackexchange.com/a/71111/11259 ;-)

It doesn't need to be an image but each square must be at least 50px? That seems self-contradictory to me.

@Bruno Bash does not support cat "out of the box." It's an external program. It's perfectly valid to be running Bash without having cat (although it would be very, very strange).

Those last 2 requirements seem unclear and contradictory as well. It doesn't have to be any particular size, nor an image, but you have to display an image. Can I return an array that can be displayed as an image? Does that array have to have a particular size, or does it simply have to display at a minimum size?

@PeterTaylor Both the example PHP and my PowerShell answer do not output images, yet each square is 50px...

Programming languages here are very diverse, including some that are made specifically for golfing and have many builtin functions. Therefore, I recommend that the restriction to non-library functions be removed, and that this question instead follow the default (all imports counted in byte count; no libraries written after the challenge was posted).

@Bruno, the requirement certainly becomes better, but I find that ”If you have to import it, it's not valid” ambiguous. That sounds like we can draw using ImageMagick in PHP as there no explicit import is needed, but we can not do the same in Perl, Python or Ruby as there an explicit import is needed.

@manatwork that is correct. Imagemagic is built into PHP so it's valid. However, if you have to do something like @import('imagemagic') or @include('thisscriptwhereipasscolorsandsizeanditwilloutputmeapng.php') it's not.

“Imagemagic is built into PHP” – Installed as separate package (php5-imagick), provided as separate library (imagick.so), configured through separate file (imagick.ini). Not so sure it is built in.

@manatwork i understand your point. The limitation is to prevent people from creating a library that automates the process and creating a file by simply doing generatechessboard(50,#000,#FFF) on the PHP file and thus have a 30 byte count. When you install php, imagemagic is included by default and you don't need to add any header to use it in your code so it's valid.

Oh. I see your point. For that reason suggested @ThomasKwa to formulate in the usual way: “no libraries written after the challenge was posted”.

@ThomasKwa Edited the description, thanks for the suggestion

Why did you accept the Octave answer? The MATL answer is 7 bytes shorter.

The MATL answer starts with black instead of white. I couldn't test the image but I tested it with 1 and 0 online at http://matl.tryitonline.net/#code=ODp0IStRMlwK&input= by removing the TYG

@Bruno The question does not state any requirement that the top-left corner is white. That answer is valid.

The screenshots suggest otherwise. In any case, I wouldn't recommend silently disqualifying an answer because you think it doesn't work. At least post a comment on the answer.

@Mego comment #10. It should be added to the requirement but it's clearly stated

@edc65 Comments are not binding unless they are added to the spec, because comments are transient and can disappear without warning. That's one of the things listed on the things to avoid meta post.

If a border is allowed, can that border be an infinite extension of the board? It would shave Desmos down to at most 21 bytes, but it doesn't feel in the spirit of the challenge.

Octave, 20 18 bytes
Thanks to @Bruno for shaving off 2 bytes.
imshow(invhilb(8))

Result:

This answer uses a technique found here. It also relies on the automatic scaling of images in Octave depending on the size of the figure window.

@AlexA. I'm also not entirely convinced that the squares must be exactly 50x50 pixels, as the very next rule says "Output format or size is not relevant...". People have asked for clarification in the comments, but the question has not been updated.

Edited the question. Tested your code and it's working, so currently you have the lowest byte count :)

Also removed the >0 and it still works so you can shave 2 bytes there

@Bruno What? That is wild. So it's apparently clamping the values of the matrix (which are all <<0 or >>1) to 0 and 1. Thanks for the tip, I'll update! :D

Congrats on 2k!

vim, 47 46 44 43
crossed out 44 is still regular 44...
iP1 400 <C-p><cr><esc>50i1<esc>YpVr0yk3PyG49PyG:m$<cr>p2GyG3P

i          enter insert mode
P1         signal to NetPPM that we're using black&white (PBM) format
400        width
<C-p>      fancy trick that inserts the other 400 for height
<cr><esc>  exit insert mode on the next line
50i1<esc>  insert 50 '1's (black)
YpVr0      insert 50 '0's (white) by duplicating the line and replacing all chars
yk         copy both lines (yank-up)
3P         paste three times; this leaves us on line two
yG         copy from line 2 to end of file (this is a full row of pixels now)
49P        we need 50 rows of pixels to make a complete "row"; paste 49 times
yG         copy the entire row of the checkerboard
:m$<cr>    move line 2 (the line we're currently on) to the end of the file
           this gives us the "alternating rows" effect
p          we're now on the last line: paste the entire row we copied earlier
2G         hop back to line 2 (beginning of image data)
yG3P       copy the entire image data, paste 3 times

Outputs in NetPPM format (PBM):

I love that you can complete a graphical output challenge with a text editor. Are there any other examples of PBMs from golfed vim?

@dohaqatar7 I dunno, but I've done TikZ with vim before, so graphics in vim is a thing for sure.

Wow, I never thought to try <C-p> in vim without having started typing a word... that is really handy!

CSS, 244 bytes
html{background:#fff}body{width:400px;height:400px;background:linear-gradient(45deg,#000 25%,transparent 25%,transparent 75%,#000 75%)0 0/100px 100px,linear-gradient(45deg,#000 25%,transparent 25%,transparent 75%,#000 75%)50px 50px/100px 100px}

html {
    background: white;
}
body {
    width: 400px;
    height: 400px;
    background:
        linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 0px 0px / 100px 100px,
        linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 50px 50px / 100px 100px
}

Explanation: A 100x100px diagonal linear gradient is created with four stops so that most of the gradient is transparent except for two 50px triangular corners. (See below snippet). Adding a second gradient with a 50x50px offset fills in the missing halves of the squares. Increasing the size of the body then allows the resulting pattern to repeat to fill the entire chessboard.

html {
    background: white;
}
body {
    width: 100px;
    height: 100px;
    background: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 0px 0px / 100px 100px
}

Neat solution. It should work as well if you drop the last } .

Can you explain what's going on here?

@flawr I've added a second snippet showing the partial effect, I hope that helps.

This is perfect.

Do you really need the html{background:#fff}? By default 99% of browsers set the background to white, afaik

@Doᴡɴɢᴏᴀᴛ If I don't do that then the body's background gets applied to the canvas, ruining the effect.

Mathematica, 34 bytes
ArrayPlot@Array[Mod[+##,2]&,{8,8}]

The output is a vector image and is surrounded in a frame.
Instead of correctly positioning 32 rectangles, we can just generate a binary matrix and make ArrayPlot work for us:

Nice! Thanks for posting it.

Looking good. Can you please explain me where do you define each square as 50px? Also, is there an online emulator where I can test it?

@Bruno The output is a vector graphic, so there is no such thing as pixel sizes (the image has no intrinsic size - it can be scaled to and displayed at any size). That's why I asked.

Ok, silly me, I was thinking SVG :) Fair enough, I'll allow it. Good work

Wait, GenerateChessBoardWithColorsAsParameters[ColorBlack, ColorWhite, 8, 8, 50, 50] doesn't work? ;)

@CᴏɴᴏʀO'Bʀɪᴇɴ It does, but that's 73 bytes.

Oh? Darn. Haha!

33 bytes: ArrayPlot[Plus~Array~{8,8}~Mod~2]

Mathematica, 81 72 55 bytes
Graphics[Rectangle/@Select[Range@8~Tuples~2,2∣Tr@#&]]

Image is of a previous version's evaluation, but still looks the same.

Pure Bash (no external utilities), 133
I saw @Doorknob's comment as a bit of a challenge. Its a bit long, but here goes:
echo \# ImageMagick pixel enumeration:400,400,1,rgb
for((;x=p%400,y=p/400,c=1-(x/50^y/50)&1,p++<160000;));{
echo "$x,$y:($c,$c,$c)"
}

Output is in Imagemagick's .txt format.  Note this is pure Bash.  Neither Imagemagick nor any other external utilities are spawned to generate this output.  However, the output may be redirected to a .txt file and viewed with the ImageMagick display utility:

This image format is nice because not only is it pure text, it is little more than a list of all pixels (x, y and colour value), one per line.  It is a fairly simple matter to derive all pixel values arithmetically in one big loop.

Previous answer, 167
echo "\"400 400 2 1\"
\"  c white\"
\"b c black\""
printf -vf %50s
a="$f${f// /b}"
o=("\"$a$a$a$a\"" "\"${f// /b}$a$a$a$f\"")
for i in {0..399};{
echo "${o[i/50%2]}"
}

Output is in the X_PixMap text image file format, which may also be viewed with the ImageMagick display utility.
Note I've taken as much out of the XPM format as I could such that display would still accept it.  I was able to take out all the c boilerplate with the exception of the " double quotes around each line.  No idea what other - if any - utilities will accept this.

Oooh, interesting ;)

PowerShell + browser of your choice, 149 143 bytes
The inability to use imports is really tough, as all of the GDI calls (i.e., the stuff PowerShell uses to draw) are buried behind imports in .NET ...
"

"+((1..8|%{$a=$_;-join(1..8|%{'	'})})-join'

')

Edit - saved six bytes thanks to @NotThatCharles
This uses two for-loops from 1..8 to generate a big-ol' HTML string, similar to the PHP example provided, and output it onto the pipeline. Each time through we calculate whether to append ;background:#000 for the black backgrounds by taking our current position on the board modulo 2.
To use, redirect the output into the file of your choice (e.g., with something like > chessboard.htm) and then launch that in the browser of your choice. For the screenshot below, I used "c.htm" and Firefox.

This one was unespected but I quite like it somehow :)

white and black can be #fff and #000... but why bother specifying white?

try (";background:#000","")[($a+$_)%2] instead.

@NotthatCharles Durr, had my white and black flip-flopped, so it was only outputting white squares. Corrected for an additional 4 bytes saved.

Octave, 48 bytes
imwrite(kron(mod((t=0:7)+t',2),ones(50)),'.png')

This works exactly the same as my Matlab answer, but there is no spiral in Octave. Instead we use a feature that Matlab does not have: We can use the assignment of t already as an expression, and later use t again in the same expression.
(This is the rescaled version, I do not want to clutter the answers here=)

The top left corner should be white, not black.

The output should be a checkerboard, the orientation was not specified.

Sorry, flawr, the output should be a chessboard. A chessboard is always "Queen on her color, white on the right" (meaning the right hand of each player has a white corner square).

Then imagine one player sitting to the right, one to the left. Again: this was not specified by the challenge, that is just your interpretation.

Python 3, 365, 288, 270, 256 bytes
Thanks @Razetime, @mehbark and @Amazeryogo for the suggestions
from turtle import *
B=range
H=Screen()
A=Turtle()
def F():
    for C in B(4):A.fd(30);A.lt(90)
    A.fd(30)
for D in B(8):
    A.up();A.setpos(0,30*D);A.pd()
    for G in B(8):
        if(D+G)%2==0:E='black'
        else:E='white'
        A.fillcolor(E);A.begin_fill();F();A.end_fill()

Try it online!
Admittedly not good:) first contribution

forward can become fd, left to lt, down to pd. You can probably remove the definition of G since it has no parameters as well, including in main program. Since the background is white, you don't need the else statement.

oh, thanks :) will edit

269 by refactoring the if statement

@Lyxal It gives an error https://i.imgur.com/KOaiOEl.png

@agent355 just change the last ' to )

https://gyazo.com/d0c985048b2883e9dd24553556e80348
Does not work

the last for loop can be written like this
for G in B(8):A.fillcolor('white'if(D+G)%2else'black');A.begin_fill();F();A.end_fill()

I believe you can shave 3 bytes by using from turtle import* and then H=Screen() A=Turtle()

@Lyxal gyazo.com/d0c985048b2883e9dd24553556e80348 look at this, it doesn't fill them

Alright, this works for 241 bytes

It wasn't working because I forgot to re-include the part which dynamically chooses the colour (D+G) which I removed to test my refactoring.

232 bytes, verified by running it locally

Doesnt work @Lyxal   https://gyazo.com/0fbe2379d56f30e9881a3fe940291de7

Let us continue this discussion in chat.

MATL, 11 (27) bytes
8:t!+Q2\TYG

This produces the following figure. It doesn't have an intrinsic size; it's automatically scaled depending on the size of the figure window. This seems to be allowed by the challenge.

Explanation
8:      % row vector [1,2,...8]
t!      % duplicate and transpose into column vector
+       % 8x8 matrix with all pairwise additions
Q       % add 1
2\      % modulo 2. Gives 8x8 matrix of zeros and ones
TYG     % draw image

If autoscaling is not allowed:
'imshow'8:t!+Q2\50t3$Y"0#X$

produces the following figure with 50x50-pixel squares
Explanation

'imshow'   % name of Matlab function
8:t!+Q2\   % same as above. Produces 8x8 matrix of zeros and ones
50t3$Y"    % repeat each element 50 times in each dimension
0#X$       % call imshow function with above matrix as input

Pyth, 28 26 bytes
J*4+*50]255*50]0.wm_mxkdJJ

Explanation
J                          - Autoassign J = V
           *50]0           - 50*[0]
    *50]255                - 50*[255]
   +                       - ^^+^
 *4                        - 4*^
                .w         - write_greyscale(V)
                  m      J - [V for d in J]
                   _       - reversed(V)
                    m   J  - [V for k in J]
                     xkd   - k^d

Python equivalent
J = 4*(50*[255]+50*[0])
write_greyscale([[k^d for k in J][::-1] for d in J])

Try it here (just the colour values)
Output:

Nice job on the byte count but I need a valid output with visible squares :)

@Bruno Output added! I installed PIL just for you :O (I hadn't actually tested it before)

@muddyfish sorry for the trouble and thanks. The board must start with and end with a white square tho :)

PHP + CSS + HTML, 136 bytes
Taking the table aproach to a higher level:

<?for(;++$i<9;)echo'
',str_repeat(["",""][$i&1],4);?>


text:
The PPCG Handicap System
As we all know, meta is overflowing with complaints about scoring code-golf between languages (yes, each word is a separate link, and these may be just the tip of the iceberg).
With so much jealousy towards those who actually bothered to look up the Pyth documentation, I thought it would be nice to have a little bit more of a constructive challenge, befitting of a website that specializes in code challenges.

The challenge is rather straightforward. As input, we have the language name and byte count. You can take those as function inputs, stdin or your languages default input method.
As output, we have a corrected byte count, i.e., your score with the handicap applied. Respectively, the output should be the function output, stdout or your languages default output method. Output will be rounded to integers, because we love tiebreakers.
Using the most ugly, hacked together query (link - feel free to clean it up), I have managed to create a dataset (zip with .xslx, .ods and .csv) that contains a snapshot of all answers to code-golf questions. You can use this file (and assume it to be available to your program, e.g., it's in the same folder) or convert this file to another conventional format (.xls, .mat, .sav etc - but it may only contain the original data!). The name should remain QueryResults.ext with  ext the extension of choice.

Now for the specifics. For each language, there is a Boilerplate \$B\$ and Verbosity \$V\$ parameters. Together, they can be used to create a linear model of the language. Let \$n\$ be the actual number of bytes, and \$c\$ be the corrected score. Using a simple model \$n=Vc+B\$, we get for the corrected score:
$$c = \frac{n-B}V$$
Simple enough, right? Now, for determining \$V\$ and \$B\$. As you might expect, we're going to do some linear regression, or more precise, a least squares weighted linear regression. I'm not going to explain the details on that - if you're not sure how to do that, Wikipedia is your friend, or if you're lucky, your language's documentation.
The data will be as follows. Each data point will be the byte count \$n\$ and the question's average bytecount \$c\$. To account for votes, the points will be weighted, by their number of votes plus one (to account for 0 votes), let's call that \$v\$. Answers with negative votes should be discarded. In simple terms, an answer with 1 vote should count the same as two answers with 0 votes.
This data is then fitted into the aforementioned model \$n=Vc+B\$ using weighted linear regression.

For example, given the data for a given language
$$
\begin{array} \\
n_1=20, & c_1=8.2,  & v_1=1 \\
n_2=25, & c_2=10.3, & v_2=2 \\
n_3=15, & c_3=5.7,  & v_3=5
\end{array}$$
Now, we compose the relevant matrices and vectors \$A\$, \$y\$ and \$W\$, with our parameters in the vector
$$
A = \left[\begin{matrix}
1 & c_1 \\
1 & c_2 \\
1 & c_3 \\
\end{matrix}\right]
y = \left[\begin{matrix}
n_1 \\
n_2 \\
n_3 \\
\end{matrix}\right]
W = \left[\begin{matrix}
1 & 0 & 0 \\
0 & 2 & 0 \\
0 & 0 & 5 \\
\end{matrix}\right]
x = \left[\begin{matrix}
B \\
V \\
\end{matrix}\right]
$$
we solve the matrix equation (with \${}^T\$ denoting the matrix transpose)
$$A^TWAx=A^TWy$$
for \$x\$ (and consequently, we get our \$B\$ and \$V\$ parameter).

Your score will be the output of your program, when given your own language name and bytecount. So yes, this time even Java and C++ users can win!
WARNING: The query generates a dataset with a lot of invalid rows due to people using 'cool' header formatting and people tagging their code-challenge questions as code-golf. The download I provided has most of the outliers removed. Do NOT use the CSV provided with the query.
Happy coding!

s/look up the Pyth documentation/carefully study the two existing pieces of Jelly documentation

Your query doesn't seem to distinguish between Perl 5 and Perl 6. Which is similar to not distinguishing C++ from Haskell.

@BradGilbertb2gills I know - it does a whole lot of quirky things, mostly due to people going crazy with formatting. Feel free to improve on it, but right now, it's a trade-off between a lack of version numbering and languages called C++ <s>6 bytes</s>. Besides, I never did any T-SQL before today and I'm already impressed with myself that I managed to extract the bytecount.

Can we remove outliers, ie any languages with only one entry (usually incorrect language names) or the ones that have >10,000 bytes?

@RobertFraser I thought that would be too much for a single challenge. I'll fix the data file, see edit.

This is a neat little challenge.  If it makes languages I know start scoring more competitively, I might do some golfing ;D

Can you provide a comprehensive set of test cases for this challenge? Otherwise, something like input(); print -1000000 cannot be distinguished from a valid answer.

@quintopia The input/output is deterministic, so if your values differ from the values produced by the competitor(s), either of you must have a mistake. I believe that I am just as likely to make a mistake as you, so reference values produced by me are no more valuable than those produced by your competitor(s).

@Draco18s You can check out the current Mathematica answer and see if any of the languages njpipeorgan has checked give you an advantage.

"In simple terms, an answer with 0 votes should count the same as two answers with 1 vote."
Flip this, right?

@LeifWillerts Yes. :)

I have an idea that built-ins could be counted as (# built-ins)/256 bytes. Then languages without one byte functions could be "fairly" scored as having one byte functions. I've played with trying to detect most-used words for each language in mathematica, but am having trouble with the query and extracting answers. If anyone is willing to help, let's open a community wiki!

Mathematica, 0:0 ...Please tell me this shouldn't work.

Mathematica, 244.719 (245 bytes)
f[l_,n_]:=x/.Solve[d=Rest@Import@"QueryResults.csv";LinearModelFit[#.#2/Tr@#&@@{#~Max~-1&/@#4+1,#3}&@@Thread@#&/@{#,#~Cases~{_,l,__}}&/@d~GroupBy~Last/@#[[;;,1,5]],x,x,Weights->Tr/@#[[;;,;;,4]]]&[d~Cases~{_,l,_,v_/;v>=0,_}~GatherBy~Last]@x==n,x]

Test case
f["mathematica", n]   (* { .820033 (n + 53.4263) } *)
f["mathematica", 245] (* { 244.719 } *)

What about other languages?
f["c++", n]           (* { .821181 (n - 79.5437) } *)
f["java", n]          (* { .717579 (n - 56.0858) } *)
f["cjam", n]          (* { 2.21357 (n + 2.73772) } *)
f["pyth", n]          (* { 4.52194 (n - 8.82806) } *)

Alternative model: \$\log(c)=\log\left(\frac{n-B}V\right)\$
One notable feature of code golf (and probably other coding problems) is that the distribution of the lengths of programs tends to be exponential distribution (in contrast to uniform distribution). Hence model \$\log(n)=\log(Vc+B)\$ is much more likely to balance the influences between points with large \$c\$ and small \$c\$.
As we can see in the graphs below, the distribution of points are suitable for fitting in logarithmic scale.

Results of the new model
Language       V       B

Python       1.365   -19.4
Javascript   1.002     1.6
Ruby         0.724     1.7
Perl         1.177   -32.7
C            1.105     1.5
Haskell      1.454   -24.5
Mathematica  1.319   -39.7
PHP          1.799   -62.0
Java         1.642     4.4
C#           1.407     4.5

CJam         0.608   -12.5
Pyth         0.519   -11.4
Golfscript   0.766   -18.0
J            0.863   -21.4
APL          0.744   -17.7
K            0.933   -23.3
Retina       1.322   -37.9
MATL         0.762   -13.3
Jelly        0.965   -23.8

We have found two exceptional language - Ruby with \$V=0.72\$` and Retina with \$V=1.322\$, and a criterion of being a popular golfing language - having a large negative boilerplate.

@sanchises So far so good, except that you use semicolons as delimiters in csv.

That's Microsoft Excel for you. Apparently saving as csv is too difficult for it.

So apparently CJam has a negative boilerplate length. Interesting.

@Pietu1998 Linear model is not so accurate, I think.

@Pietu1998 Not entirely surprising, since golfing languages generally take implicit input and may return implicit output. Note that "Boilerplate length" is defined w.r.t the average, not w.r.t an ideal boilerplateless language. I'm actually positively surprised by how well this simple model seems to be doing when glancing at these results.

@sanchises Good explanation. Now I understand why Mathematica has such a large negative boilerplate to some degree.

@njpipeorgan Perhaps you can plot some data and see how languages compare visually; that might give some insight.

I'm now curious to Retina's score.  I've seen a couple answers that look like 1 (plus some whitespace that the ` markup can't wrap but which is important) e.g this answer (3 bytes).  It must have some amount of negative boilerplate.

@Draco18s Retina gets the first place among golfing languages in terms of boilerplate.

@njpipeorgan That appears that it does.

I like how my original challenge got closed as 'too broad', and you just did exactly what I had in mind for the original challenge (i.e., try and construct an appropriate model using graphs etc.) Cheers!

Congratulations on your bounty + accepted bonus; well-deserved too given the extra effort you put in. One remark: I believe a straight line through a log-log plot is a polynomial of form x^p with p the slope of your straight line, and not an exponential distribution.

@sanchises Thanks. Exponential distribution is a hint for me to use logarithmic scale, and the fitting result shows x^p just as what you said.

Python3, 765.19 (765) bytes
Probably some room for golfing here.  Requires numpy for matrix stuff.  Reads from stdin, formatted as follows: [lang] [bytes/n].  Stops when you send q.
import numpy as n,csv
L={};Q={};X={};D=n.dot;f=open('QueryResults.csv',encoding="utf8");R=csv.reader(f);f.readline();Z=list.append;M=n.matrix
for r in R:
 if r[1] not in L:L[r[1]]=[]
 if r[4] not in Q:Q[r[4]]=[]
 Z(L[r[1]],r);Z(Q[r[4]],r)
for l in L:
 b=[];a=[];v=[];t=[]
 for r in L[l]:
  if int(r[3])>-1:
   Z(b,int(r[2]));o=[]
   for q in Q[r[4]]:Z(o,int(q[2]))
   Z(a,sum(o)/len(o));Z(v,int(r[3])+1)
 for k in a:Z(t,[1,k])
 if len(t)<1:continue
 A=M(t);T=A.transpose();W=n.diag(v);y=M(b).reshape((len(b),1));e=D(D(T,W),A)
 if n.linalg.det(e)==0:continue
 i=n.linalg.inv(e);X[l]=D(i,D(D(T,W),y))
p=input()
while(p!="q"):
 S=p.split()
 if S[1]=='n':print("(n-("+str(X[S[0]].item(0))+"))/"+str(X[S[0]].item(1)))
 else:print(str((int(S[1])-X[S[0]].item(0))/X[S[0]].item(1)))
 p=input()

Results
I might have done something wrong at some point; I get different results than the Mathematica answer:
python3 808 -> 765.19
python3 n   -> (n-(32.41))/1.01

c++ n        -> (n-(71.86))/1.17
cjam n       -> (n-(-14.09))/0.51
java n       -> (n-(18.08))/1.64
pyth n       -> (n-(1.42))/0.28
jelly n      -> (n-(-4.88))/0.34
golfscript n -> (n-(-0.31))/0.44


text:
Shortest code to cycle through RGB LEDs
Given four RGB LEDs and 8 colors, your task is to light up each LED in order with a color, and cycle through the LEDs as you cycle through the colors; with only one LED lit up at a time.
So for 8 colors across 4 RGB LEDs, it would look like this (at a hardware level (since there are three channels for each LED)):
LED1            LED2            LED3            LED4
0xFF,0x00,0x00  OFF             OFF             OFF
OFF             0xFF,0XA5,0x00  OFF             OFF
OFF             OFF             0xFF,0XFF,0x00  OFF
OFF             OFF             OFF             0x00,0xFF,0x00
0x00,0x0,0xFF   OFF             OFF             OFF
OFF             0xFF,0X00,0xFF  OFF             OFF
OFF             OFF             0xFF,0X00,0xFF  OFF
OFF             OFF             OFF             0xFF,0xC0,0xCB

Inputs:
None
Program End Condition:
User presses the SpaceBar key.
Program Behavior
There should be a 500ms delay between each LED shift, and each LED will remain "Lit" for 1 second (in our case; this simply means that should the user press the spacebar before the next color is shown, then the currently "lit" LED will be chosen.  This should happen until the user presses the spacebar.
At that point, output the color the user has chosen.
%> myprog
   LED      COLOR
   ---    --------
    1     0xFF0000
    2     0xFFA500
    3     0xFFFF00
    4     0x00FF00
    1     0x0000FF
    2     0xFF00FF

Output:
1:
2: 0xFF00FF
3:
4:

Just because they're beautiful, and to make it a little harder, I chose Magenta and Pink for the final two colors.
Win Condition
The winning condition is the shortest amount of code in bytes to implement this function.
Any language that is capable of being run from the command line is eligible (although if there's a JavaScript version for the browser that wins; that'd also be interesting).

It still looks unclear to me. Exactly what input do we need to take?

I get that there's no input but  I don't see any mention of a spacebar in the spec :-S ?? Also, it appears we are now allowed to output text to stdout? Can you show more of the cycle to show exactly what the output should be. It may seem like pedantry but if the spec is vague and open to interpretation, it makes it impossible to decide if an entry is valid or not.

@ThomasKwa Why is it still unclear after my edits?

"Given four RGB LEDs, your task is to cycle through all the LEDs, with one Color Per LED, and only one LED displaying a color at a time. So for 8 colors across 4 RGB LEDs ..." The spec appears to contradict itself within the first two sentences. If the intended question is "Time how long it takes from program start until the user presses the spacebar, divide by 500ms, round down to an integer, take value modulo 8, and then output one of these 8 hard-coded outputs" then that would IMO be a much clearer explanation than the current text.

@PeterTaylor edited.

Also, why does it matter that each LED stays lit for a full second if we only output the final choice?

@ThomasKwa To throw more of a challenge in there and to accurately reflect what would happen for a user. As far as the colors; those are chosen because they there is some variability there; you can't just do bitwise manipulation of a specific amount each time.  I will probably add my solution; but since I'm not a code-golfer generally, it'd probably be mocked mercilessly.

Please add your solution, and don't golf it. Without it I can't tell what the challenge is.

So the colors are fixed at exactly the ones in the first code block?

@ThomasKwa Yes.

You said that my rewording of the problem wasn't what you intended, but the edit doesn't tell me what I misunderstood, so I still find it unclear.

@PeterTaylor I'm still not sure what you want out of me here. I'd love to edit it to fit whatever you find unclear; but we have a disconnect.

Which part of "Time how long it takes from program start until the user presses the spacebar, divide by 500ms, round down to an integer, take value modulo 8, and then output one of these 8 hard-coded outputs" is not correct? Or did you delete your comment because it is correct after all?

@PeterTaylor There are a few incorrect things there; we don't care about how long the user spends doing something. They could spend all eternity; we're not dividing by 500ms because each LED stays active for 1 second; so you have a potential of 2 seconds (or 1.5 seconds, depending) where the state could be active; "take value modulo 8" and the '8 hardcoded outputs' matter; part of the program is the most efficient way to write those hardcoded values to their output (in this case, the LED).

2 seconds or 1.5 seconds depending on what? Could you provide a reference implementation?