text:
3... 2... 1... Crash off!
Your task is to write a full program that will continue to count down from 10 every time it is run.

The first time you run the program, it should print 10.
The next time, it should output 9.
The next time, it should output 8, and so on.
Instead of printing 0, the program should crash. You do not have to handle the program running any more times after that.
Any facilities used for storage may be assumed to be empty before the first execution of the program.

Here's an example implementation in Python 3:
try:f=open("a","r+");v=int(f.read())
except:f=open("a","w");v=10
1/v
print(v)
f.seek(0)
f.write(str(v-1))

This is code-golf, so the shortest answer (measured in bytes) wins.

What does crashing entail?

@ConorO'Brien Hmm... this hasn't been discussed in meta?

@Challenger5 Not that I know of. Would throwing an error be sufficient?

@ConorO'Brien Yes.

Related.

Why can't I submit an (impure) function?

@pxeger It would defeat the main goal of the challenge, which is to require self-modification or some other form of interaction with the filesystem/OS to achieve persistent storage.

6502 machine language + Apple ][+ ROM, 12 (11? 10? 9?) bytes
CE 06 80 F0 01 A2 0B A9 00 4C 24 ED

Should start at $8000. Crashes to the system monitor when the count reaches 0.

C6 B6 F0 01 A2 0B A9 00 4C 24 ED

Should start at $B1. This saves a byte since I can use the (two-byte) zero-page version of DEC, but overwrites the critical Applesoft routine CHRGET; you'll need to load it and call it from the monitor, and use CTRL+BReturn to re-initialize BASIC once you're done. Not sure if this invalidates it or not.

CE 06 80 F0 01 A2 0B 4C 26 ED

Should start at $8000. This doesn't initialize $9E, saving two bytes. However, this means you must not call it with a negative address (or, if you call it from the monitor, you have to call the monitor with a positive address). If you do, Applesoft's CALL routine will store FF in $9E, causing it to add 65280 to the number when printing it. Again, not sure if this invalidates the solution or not.

C6 B6 F0 01 A2 0B 4C 26 ED

Should start at $B1. This is a combination of the above two programs, saving a total of three bytes; you'll have to call the monitor with a positive address, load it and run it from there, and use Ctrl+BReturn to re-initialize BASIC once you're done.

Note that these programs only modify the program in memory; re-loading the program from disk will reset the countdown. This works because the Apple ][ (and ][+, //e, and //c) have no memory protection system whatsoever; the program (and its self-modifications) will stay in memory even after it exits, so you can keep running it from memory until you overwrite that memory with something  else.

Sample run
]BLOAD COUNT THEN BRK
]CALL 32768
10
]CALL 32768
9
]CALL 32768
8
]CALL 32768
7
]CALL 32768
6
]CALL 32768
5
]CALL 32768
4
]CALL 32768
3
]CALL 32768
2
]CALL 32768
1
]CALL 32768

8008-    A=80 X=9D Y=00 P=36 S=EE
*

Explanation
     DEC NUM+1  ; Decrement the LDX instruction's operand
     BEQ NUM+1  ; If it is now zero, branch to it; 00 is the opcode for the BRK instruction, which causes the program to crash to the monitor
NUM  LDX #$0B   ; Load the X register with 0x0A; the operand has already been decremented once
     LDA #$00   ; Load the accumulator with 0
     JMP $ED24  ; Jump to $ED24, an Applesoft ROM routine which prints A (high byte),X (low byte) in decimal

Explanation of 10 byte version
     DEC NUM+1  ; Decrement the LDX instruction's operand
     BEQ NUM+1  ; If it is now zero, branch to it; 00 is the opcode for the BRK instruction, which causes the program to crash to the monitor
NUM  LDX #$0B   ; Load the X register with 0x0A; the operand has already been decremented once
     JMP $ED26  ; Jump to $ED26, which is two bytes into the Applesoft routine at $ED24. The two skipped bytes would store the accumulator in $9E

Variants
Prints ERR and beeps when count reaches 0
Normal - 15 bytes
CE 06 80 F0 07 A2 0B A9 00 4C 24 ED 4C 2D FF

Overwrites CHRGET - 14 bytes
C6 B6 F0 07 A2 0B A9 00 4C 24 ED 4C 2D FF

Doesn't initialize $9E - 13 bytes
CE 06 80 F0 05 A2 0B 4C 26 ED 4C 2D FF

Overwrites CHRGET and doesn't initialize $9E - 12 bytes
C6 B6 F0 05 A2 0B 4C 26 ED 4C 2D FF

Freezes when count reaches 0
Normal - 12 bytes
CE 06 80 F0 FE A2 0B A9 00 4C 24 ED

Overwrites CHRGET - 11 bytes
C6 B6 F0 FE A2 0B A9 00 4C 24 ED

Doesn't initialize $9E - 10 bytes
CE 06 80 F0 FE A2 0B 4C 26 ED

Overwrites CHRGET and doesn't initialize $9E - 9 bytes
C6 B6 F0 FE A2 0B 4C 26 ED

I'm not sure I understand this .. Wouldn't this be the same as having a function in Python that decrements a global variable and only works if executed in the shell? Is that allowed? What I mean is, isn't it normally expected for a program to leave the memory at some point, to be reloaded again later?

@redstarcoder No - the Apple II has literally no memory allocation system; you can store anything anywhere in RAM and it will stay accessible by any program until it's overwritten with another value.

@inset_name_here, I'm not sure how it being accessible anywhere in RAM changes anything. Could you run other programs reliably and still run this program later? Maybe I'm not familiar enough with the rules around here to fully understand, so I'll just drop it. I just expect a full program to persist through reboots and be able to run fine usually if other programs are run in between its executions, but I don't know what the community rules a full program to be.

@redstarcoder the general consensus is that the program is run on a development computer with nothing but the required software and not doing anything else in the mean time.

@TomCarpenter, thanks! What about execution? If a program is typically loaded then executed, is it valid to assume subsquent executions are not loaded? Just because then I get back to my initial Python shell question, but that's starting to seem valid anyways in my head now.

8 bytes if you run from $6E instead: C6 75 F0 03 4C 22 ED 0B

Perl on Linux, 17 bytes
I thought it might be interesting to create a program that doesn't maintain any state itself, and doesn't modify its own source code; in other words, it actually checks how often it's been run by asking the OS. The question says "Any facilities used for storage may be assumed to be empty before the first execution of the program.", and thus we'd want to start from a completely blank OS. As such, I'd better explain just how you go about doing that, as otherwise testing the program is difficult.
There are actually two ways to set up for running the program. Either way, the minimal OS for the purpose would be running nothing but a shell (to enable us to run Perl in turn), and the simplest possible shell at that (so that it doesn't do anything fancy that makes the OS non-blank). /bin/dash is a good choice here, as it was intended as a minimal shell for system recovery. Then, we need to start Linux in such a way that it's running nothing but dash. We can either do this by rebooting the computer with init=/bin/dash on the Linux command line so that it starts nothing besides dash, or (much more conveniently) creating a Linux container using unshare -Urfp /bin/dash in a terminal (unshare doesn't actually create a blank OS, but it does simulate one; notably, the inside of the container thinks it's root, dash thinks it's init, etc., just as would happen on an actual blank OS). Disclaimer: I haven't actually tested this on bare metal yet, only inside unshare, but it should work both ways in theory.
Finally, once we've got that set up, we simply have to look at the PID; as we're on a blank system, the init system (here, the shell) will have PID 1, so the executions of Perl will have PIDs from 2 up to 12 inclusive. So our program looks like this:
say 12-$$||die

Here's a sample run:
$ unshare -Urfp /bin/dash
# perl -E 'say 12-$$||die'
10
# perl -E 'say 12-$$||die'
9
# perl -E 'say 12-$$||die'
8
# perl -E 'say 12-$$||die'
7
# perl -E 'say 12-$$||die'
6
# perl -E 'say 12-$$||die'
5
# perl -E 'say 12-$$||die'
4
# perl -E 'say 12-$$||die'
3
# perl -E 'say 12-$$||die'
2
# perl -E 'say 12-$$||die'
1
# perl -E 'say 12-$$||die'
Died at -e line 1.
#

What OS are you running this on? I'm on Ubuntu Linux 14.04, and unshare doesn't support any of the flags -Urfp.

@isaacg: Ubuntu 16.04. unshare is pretty new (it's an interface to an OS feature that's also pretty new) and the bugs only really got ironed out over the last year or so. If you're using a 2½-year-old version, it's unsurprising that it's very limited in functionality.

Bash + sed, 41 40 38 bytes
echo $[n=10/1]
sed -i s/$n/$[n-1]/g $0

Try it online!

The TIO link has a header and footer, don't those add to byte count?

No, those are just to run the program 11 times.

I get sed: invalid option -- '/'. sed (GNU sed) 4.2.2

@shrx Huh. I have the same version of sed locally and on TIO, and they don't show that error.

Javascript, 42 bytes
y=localStorage;y.a=y.a||10;alert(y.a--||a)

Test it out with this fiddle - be sure to clear your local storage to reset the countdown.
Thanks to steenbergh, Lmis, and obarakon for lots of bytes!

y=localStorage;y.a=y.a||10;alert(y.a>0?y.a--:a) can save you a byte.

You can use sessionStorage to test with an easier reset (just use a fresh tab) but of course +2 bytes.

Ouch, sorry, i just saw your answer, i ended up doing almost the same. If you want to, you can use l=localStorage;l.l=-~l.l;alert(10-l.l||l) to save a byte, i'd delete mine

@Mego Of course :)
I don't see a console.log here, but i'd prefer that either

@C5H8NNaO4 Err... I forgot I changed it over to alert! I blame sleep deprivation.

@Mego Just curious, what caused the exception when y.a reaches 0?

@obarakon When it reaches 0, the Boolean OR tries to evaluate the a, which is undefined.

@Mego Ah ok, so everything that isn't 0 gets interpreted as true?

@obarakon Yep, and Boolean short-circuiting prevents the a from evaluating when the value in localstorage isn't 0.

Dyalog APL, 33 28 22/20? bytes
I am not sure if this is valid, as it consists of a function (which must be called with a dummy argument). However, all APL programs (purely functional or not) have the same status, and indeed some APL versions do not have traditional programs, only functions. In compensation, I have added two bytes to name it, although that is not necessary for the desired effect.
f←{6::⊢c∘←10⋄÷÷c∘←c-1}

Note that this relies on an unofficial quirk, that ∘← assigns globally.
6:: upon any value error
⊢c return c
∘←10 which is globally set to 10
⋄ now
÷÷c return the twice inverted (errors on zero) c
∘← which is globally set to
c-1 one less than c
TryAPL online!

Certainly valid 28 byte version:
f
⍎'c←11'/⍨0=⎕NC'c'
⊢c←÷÷c-1

Works by setting c to 11 if missing, then subtracting 1 from c, inverting twice (which gives div-by-zero error if c-1 is 0), assigning to c, and outputting the new value.

Old 33 byte version:
f
÷÷≢2↓r⊣⎕FX¯1↓r←⎕NR'f'

Works by redefining itself on each run, but with one less trailing newline. Outputs the twice inverted number of remaining lines (less two), thus giving a div-by-zero error when only two lines are left (the header and the actual code).

Er... why are there so many newlines?

@KritixiLithos The program redefines itself with one less line for each run.

C#, 197 160 159 125 bytes
namespace System.IO{class P{static void Main(){int n=11;for(;File.Exists(""+--n););File.Create(""+n);Console.Write(n*n/n);}}}

Saved 34 bytes thanks to milk
And a formatted version (With ReadKey added so you can view the output):
namespace System.IO
{
    class P
    {
        static void Main()
        {
            int n=11;
            for(;File.Exists(""+--n););
            File.Create(""+n);
            Console.Write(n*n/n);
        }
    }
}

It is longer than I thought it would be so there's probably room for golfing.

File.Exists and File.Create instead of ReadAllText and WriteAllText. Just check if a filename exists, don't both with the file contents. Also, namespace System.IO and you can remove the namespace from System.Console.Write. 125 bytes: namespace System.IO{class P{static void Main(){var n=11;for(;File.Exists(""+--n););File.Create(""+n);Console.Write(n*n/n);}}}

@milk Thanks a lot! Can't believe I didn't think of using the filename only though! And I didn't know about that namespace trick, awesome.

Perl, 37 36 bytes
9=~//;print$'-sysopen$~,$0,print$'+1

Crashes when the initial value reaches -1 (which would have printed 0), as it writes over the =~ operator.
Saved a byte using sysopen rather than open. This allows me to print to STDOUT first, using the return value as the file mode (1, a.k.a. O_WRONLY), before $~ is reassigned.
Sample Usage
$ perl crash-off.pl
10
$ perl crash-off.pl
9
$ perl crash-off.pl
8

...

$ perl crash-off.pl
2
$ perl crash-off.pl
1
$ perl crash-off.pl
syntax error at crash-off.pl line 1, near "1~"
Execution of crash-off.pl aborted due to compilation errors.

Python 2, 65 bytes
f=open(__file__,"r+")
x=75-len(f.read())
x/x
print x
f.write('#')

Inspired by L3viathan's answer.
Can be reduced to 60 bytes if you can choose to name the file a single character like x and then replace __file__ with 'x'. In that case, replace 75 with 70.

@Flp.Tkc yes, but isn't that the same number of bytes?

oh, that's true :P

Perl 6,  60  58 bytes
put 10-$=finish.lines||die;
$*PROGRAM.open(:a).put;
=finish

open($*PROGRAM,a=>put 10-$=finish.lines||die).put
=finish

Needs newline character after =finish.
die can be replaced with 1/0.
Explanation:
It gets a list of lines after =finish ($=finish.lines) subtracts that from 10, and if the result isn't 0 it prints it, otherwise it dies.
The last thing it does is open itself in append mode, and add another line to the end.

Permalink for those who don't have Perl 6.

@Dennis At least that one isn't as far out of date as what Ideone has ( run say $*PERL.compiler.version )

2014.7... wow! Is 2016.11 very different from 2016.7? If so, I can build it from source.

@Dennis The official release of Perl 6 was 2015-12-25. There was a big change in late 2015 called The Great List Refactor (GLR), so getting code to also work on 2014.7 is almost impossible. Most of what's been happening in 2016 is performance related, though there have been plenty of edge condition fixes. Most of the golfed code here should work on anything after the 2015.12 release of Rakudo. So I think v2016.07 is fine.

PHP 57 bytes
echo$n=($f=file(f))?$f[0]:10?:die;fputs(fopen(f,w),--$n);

doesn´t really crash but exit (without counting down) when it hits 0. Is that sufficient?
Run with -r.

C#, 156 bytes
I golfed @TheLethalCoder's answer for a bit, and was able to save 3 bytes by reordering the statements and eliminating the int.parse().  Still room for improvement, I'm sure.
using System.IO;class P{static void Main(){int n;try{n=File.ReadAllText("f")[0]-48;}catch{n=10;}System.Console.Write(n/n*n);File.WriteAllText("f",""+--n);}}

Ungolfed:
using System.IO;
class P
{
    static void Main()
    {
        int n;
        try
        {
            n = File.ReadAllText("f")[0] - 48;
        }
        catch {
            n = 10;
        }
        System.Console.Write(n / n * n);
        File.WriteAllText("f", "" + --n);
    }
}

Meta-question: It may be hack-y to take TheLethalCoder's work as a starting point for my answer.  Would it be better (once I have the rep) to add this as a comment on their answer?  I'm not trying to compete with them, I just want to show off my golf, for mutual edification.

People usually leave comments underneath the other persons answer suggesting improvements, however because of the improvements on mine suggested by milk mine is now much different so yours is fine on its own

I usually go by if they are improvements to someone else's answer comment but if it is different enough to theirs then post your own answer

Jolf, 20 bytes
γ-@▲lqΈ?␡γ?γaγ0₯I₯C1

Try it here! Errors when 0 is printed. Modifies the code. Explanation to come.

I'm not very familiar with Jolf, but it does not immediately seem to work in the online interpreter.

@Challenger5 The language usually only works on firefox.

Applesoft BASIC, 21 bytes (tokenized)
0  PRINT 9 + 1: CALL 2066: END : OR <CTRL-F><CTRL-H>`

Replace <CTRL-F> and <CTRL-H> with their literal versions. Note that this only modifies the program in memory; re-loading it from the disk will reset the countdown.

Sample run
]RUN
10

]RUN
9

]RUN
8

]RUN
7

]RUN
6

]RUN
5

]RUN
4

]RUN
3

]RUN
2

]RUN
1

]RUN

?SYNTAX ERROR IN 0

Explanation
PRINT 9 + 1 does what you'd expect. CALL 2066 calls the 6502 machine-language routine at memory location 2066, which is after END :. END halts the program so that the machine-language routine (which, to the Applesoft interpreter, is garbage) isn't executed.
The machine-language routine simply decrements the 9 in PRINT 9 + 1. Disassembly:
0812-   CE 06 08    DEC $0806
0815-   60          RTS

After the counter reaches 0, it is "decremented" to /; attempting to run the program will then cause a syntax error.

*><>, 20 18 bytes
a1Fi:0(?b1-:?:1Fn;

This actually works on Linux (and whatever supports files named \n I guess). It creates a file named \n on first run and outputs 10. It proceeds to output one less number on each subsquent run, except 0 where it crashes instead.
Explanation
a1F                   open file named "\n"
   i:                 recieve input and duplicate it (-1 if empty)
     0(?b             if the file is empty, push 11 to the stack
         1-           subtract one
           :          duplicate the number
            ?:        if the number isn't 0, duplicate it again
              1F      save the number to the file
                n     output the number (crash if non-existant)
                 ;    exit

Convenient that *><> adds IO

SQLite, 142 137
This could probably be done much more cleverly. 141 136 chars for code:
create table if not exists t(n not null);insert into t select 11;update t set n=case n when 1 then null else n-1 end;select min(n)from t

Plus 1 for the filename x in sqlite3 x '…'.

Nice!  Haven't seen SQLite used like this before.
You can squeeze a few bytes by replacing "values(11)" with "select 11", and "select n from t limit 1" with "select min(n) from t"

Ruby, 94 87 84 61 59 bytes
j=File.open(?a,"a+");1/(i=j.readlines.size-14);p -i;j.puts

Please leave suggestions below.
Thanks @ConorO'Brien for the ideas (some shamelessly ripped off from his answer).

puts i => p i

Use new and size instead of open and length.

JavaScript, 74 bytes
x=typeof x!=typeof 1?10:x!=1?x-=1:_
l=localStorage;l.a=typeof l.a!=typeof""?10:l.a!=1?l.a=--l.a:_;alert(l.a)

The OP has clarified (in the comments) that a full program is required.

@Dennis Does my revised submission qualify as a full program?

I don't know, but I don't think so. I'd say that without a call to alert or similar, it's just a REPL snippet.

Looks good to me. (Can't test it from my phone.)

Powershell V2.0, 49 bytes
(First ever code golf, couldn't find the rules on how to calculate bytes. I used a String to bytes calculator online)
if(!$n){$n=10;$n}else{$n-=1;if($n-eq0){throw};$n}

Running:
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
10

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
9

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
8

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
7

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
6

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
5

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
4

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
3

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
2

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
1

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
ScriptHalted
At line:1 char:49
+ if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw <<<< };$n;}
    + CategoryInfo          : OperationStopped: (:) [], RuntimeException
    + FullyQualifiedErrorId : ScriptHalted

Welcome to PPCG! The rules to calculate bytes depend on the character encoding used by the language. Powershell probably uses ASCII or UTF-8 encoding, and so for a script with only ASCII codes, as is the case here, each character takes up 1 byte

Welcome to PPCG! Per the challenge writer, all submissions must be a complete program, which this is not -- as is, it's essentially being run in PowerShell's equivalent of a REPL.

If I wrote this inside of a .ps1 and executed that 10 times crash-off.ps1 for example, does that count as a full program?

@KieronDavies Yes, provided that if you closed and reopened the shell in between each time, you still got the same result. Keeping items "in memory" in the shell between execution is what defines the "REPL environment" of PowerShell from a "full program" environment.

Java, 343 bytes
My first golfing attempt
import java.io.PrintWriter;class M{public static void main(String[] a) throws Exception{if(!new java.io.File("x").exists()) try(PrintWriter p=new java.io.PrintWriter("x")){p.write("10");}int b=new java.util.Scanner(new java.io.File("x")).nextInt();try(PrintWriter p=new java.io.PrintWriter("x")){p.print(b/b*b-1+"");System.out.print(b+"");}}}

ungolfed
import java.io.PrintWriter;

class M {
    public static void main(String[] a) throws Exception {
        if (!new java.io.File("x").exists()) {
            try (PrintWriter p = new java.io.PrintWriter("x")) {
                p.write("10");
            }
        }
        int b = new java.util.Scanner(new java.io.File("x")).nextInt();
        try (PrintWriter p = new java.io.PrintWriter("x")) {
            p.print(b / b * b - 1 + "");
            System.out.print(b + "");
        }
    }
}

You can get it down to 300 bytes by importing java.io.* and avoiding using fully-qualified constructor names, and you can cut another 8 by using the fact that "print" will automatically stringify its arguments: import java.io.*;class M{public static void main(String[] a) throws Exception{if(!new File("x").exists()) try(PrintWriter p=new PrintWriter("x")){p.print(10);}int b=new java.util.Scanner(new File("x")).nextInt();try(PrintWriter p=new PrintWriter("x")){p.print(b/b*b-1);System.out.print(b);}}}

You can get it down to 237 bytes by not writing the "10" to file, and instead just using the ? operator based on file existence when you read b: import java.io.*;class M{public static void main(String[] a) throws Exception{int b=new File("x").exists()?new java.util.Scanner(new File("x")).nextInt():10;try(PrintWriter p=new PrintWriter("x")){p.print(b/b*b-1);System.out.print(b);}}}

Most optimized I could make: 220 bytes. Here's the beast: import java.io.*;class A{public static void main(String[]a)throws Exception{File f=new File("f");int b=f.exists()?new FileInputStream(f).read()-48:10;new PrintWriter(f).printf("%d",b/b*b-1).close();System.out.print(b);}}

thx for the suggestions :)

JavaScript, 41
l=localStorage;l.l=-~l.l;alert(11-l.l||I)

@Mego Yes obviously, I don't know how this could happen... I had an a instead of the l when i wrote it, and changed it without thinking, because i thought it looks more fun... it's been too late and herby, thanks for pointing that out.

TI-BASIC (TI-84 Plus) (15 bytes)
If not(Ans
11
Ans-1
AnsAns/Ans

Ans should equal 0 (the default value) before the first run.
Since AnsAns/Ans is the last line of the program, it will be outputted and stored to Ans unless Ans is 0, in which case a divide by 0 error occurs.

Ruby, 52 + 1 = 53 bytes
Assumes the file is named a (+1 byte).
q=File.read ?a
0/h=62-q.size
p h
File.write ?a,q+?1#

Running
C:\Users\Conor O'Brien\Documents\Programming
λ type a
q=File.read ?a
0/h=62-q.size
p h
File.write ?a,q+?1#
C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
10

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
9

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
8

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
7

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
6

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
5

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
4

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
3

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
2

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
1

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
a:2:in `/': divided by 0 (ZeroDivisionError)
        from a:2:in `<main>'

...you can assume names?

You could use $0 instead of a and 'echo>>#$0' (with backticks) on the last line.

@GB It's still more bytes than assuming a (which is only +1).

?a is 2 bytes, $0 is 2 bytes, but doesn't need whitepaces.

Python 2, 89 bytes
x=10
x/x
print x
f=open(__file__,"r+")
s=f.read()
f.seek(0)
f.write(s.replace(`x`,`x-1`))

I liked your idea of opening __file__ so I made use of that in my answer.

@AlexHall Great idea with len

@Flp.Tkc I won't save any characters with that. I still need to use the variable s, because I need to read, then seek, then write. The print x/x*x would work, but doesn't improve the byte count.

PHP, 45 bytes
Honestly not sure if this one counts.
<?session_start();echo10-$_SESSION[0]++?:die;

I'd post a link to an example, but all the online testers that I know don't allow session_start() to be used.
This will keep counting down each time you refresh the page until 0, when the die command is ran.

GNU Smalltalk, 70, 68 bytes
66 bytes code +2 bytes for the "-S" flag
EDITS

Removed unnecessary parentheses, -2 bytes

Golfed
X=Y ifTrue:[Smalltalk at:#X put:10]ifFalse:[X:=X-1].(X*X/X)printNl

Test
>seq 11|xargs -L1 sudo gst -S fail.st 2>/dev/null
10
9
8
7
6
5
4
3
2
1
Object: 0 error: The program attempted to divide a number by zero
ZeroDivide(Exception)>>signal (ExcHandling.st:254)
SmallInteger(Number)>>zeroDivide (SysExcept.st:1426)
SmallInteger>>/ (SmallInt.st:277)
UndefinedObject>>executeStatements (fail.st:1)

Important
You must run gst as root, for it to be able to modify the default image, or specify your own image with -I.

QBIC, 70 bytes
open"r",1,"a.b" $get#1,1,e|~e=0|e=z\e=e-1]?e~e=0|$error 1|]$put#1,1,e|

Opens file a.b (or creates it when not found on first run), reads record 1 into e. If that record is not found, assume 10, else sub 1. At e==0, raise an error. Write back e to a.b.
File access is not built into QBIC, this relies heavily on the underlying QBasic.

Batch, 72 bytes
@call:l
@if %n%==0 goto g
@echo %n%
@cmd/cset/a-1>>%0
:l
@set/an=10

Needs to be invoked using the full file name including extension. Last line must not have a trailing newline. Works by writing -1 to the end of the last line so that it evaluates to 1 less each time. goto g errors out because there's no label :g.

R, 52 bytes
`if`(!"x"%in%ls(),cat(x<-10),`if`(x>0,cat(x<-x-1),))

Essentially uses ls() to list the names of all globally stored objects. If we assume that the global environment is empty and "x" doesn't exist already, generate x=10, else if x!=0 subtract 1 else call a missing argument which returns an error.

You can save a byte by removing the ! and switching the order of the then and else arguments, and another two by changing x>0 to x. (Also, exists("x") is a little neater than "x"%in%ls(), although equal in byte count.)

Ah, re-reading the comments in the specification, it looks like a full program is required, which means you can't rely on object persistence between runs.

@rturnbull Although I cannot find where this is explicitly stated. I will delete the answer if you can point me to it.

It's mentioned here, although it hasn't been edited into the spec.

Windows Batch, 61 bytes
@if %n%.==. set n=10
@if %n%==0 goto.
@set /a n-=1&@echo %n%

JavaScript, 44 bytes

function* f(n=11){for(;--n;yield n);throw''}

p=f()
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)


text:
Array alignment addition
Introduction
Consider two non-empty integer arrays, say A = [0 3 2 2 8 4] and B = [7 8 7 2].
To perform alignment addition on them, we do the following:

Repeat each array enough times to have total length \$\text{lcm(length(A), length(B))}\$. Here \$\text{lcm}\$ stands for lowest common multiple.
 A -> [0 3 2 2  8 4][0 3  2 2 8 4]
 B -> [7 8 7 2][7 8  7 2][7 8 7 2]

Perform element-wise addition on the repeated arrays, and cut the result at every position where there's a cut in either of them.
 A -> [0  3 2 2   8  4][0 3  2  2  8 4]
 B -> [7  8 7 2][ 7  8  7 2][7  8  7 2]
   -> [7 11 9 4][15 12][7 5][9 10 15 6]

This array of arrays is your result.

The task
Your inputs are two non-empty arrays of integers, and your output shall be the result of their alignment addition, as defined above.
The inputs and output can be in any reasonable format.
You don't have to worry about integer overflow when performing the addition.
Rules and scoring
You can write a full program or a function.
The lowest byte count wins.
Test cases
[1] [4] -> [[5]]
[1,2,-3,-4] [15] -> [[16],[17],[12],[11]]
[0,-4] [2,1,0,-3] -> [[2,-3],[0,-7]]
[0,3,2,2,8,4] [7,8,7,2] -> [[7,11,9,4],[15,12],[7,5],[9,10,15,6]]
[18,17,16] [-1,-2,-3,-4] -> [[17,15,13],[14],[16,14],[15,13],[15],[16,14,12]]
[18,17,16,15] [-1,-2,-3,-4] -> [[17,15,13,11]]
[1,1,1,1,1] [6,5,6,5,6,5,6,2,1] -> [[7,6,7,6,7],[6,7,3,2],[7],[6,7,6,7,6],[7,3,2],[7,6],[7,6,7,6,7],[3,2],[7,6,7],[6,7,6,7,3],[2],[7,6,7,6],[7,6,7,3,2]]
[1,1,1,1,1,1] [6,5,6,5,6,5,6,2,1] -> [[7,6,7,6,7,6],[7,3,2],[7,6,7],[6,7,6,7,3,2]]
[1,1,1,1,1,1,1] [6,5,6,5,6,5,6,2,1] -> [[7,6,7,6,7,6,7],[3,2],[7,6,7,6,7],[6,7,3,2],[7,6,7],[6,7,6,7,3,2],[7],[6,7,6,7,6,7,3],[2],[7,6,7,6,7,6],[7,3,2],[7,6,7,6],[7,6,7,3,2],[7,6],[7,6,7,6,7,3,2]]

C doesn't have a way to know an array's length -- can I request the length of the array as an argument, or have it stored at the beginning of the array?

@cat You can take the lengths as extra arguments, if there's no other way of getting them.

JavaScript (ES6), 101 99 bytes
Takes input as 2 arrays. Returns a string.
f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`

How it works
We iterate on the first array a with a pointer i while updating another pointer j into the second array b. The sums a[i] + b[j] are appended to the output string s. A separator is inserted each time i == 0 or j == 0. We repeat this process until j is back exactly at the beginning of b at the end of an iteration.
Note: When the | operator is applied, a.map(...) is coerced to either NaN (if a contains more than one element) or the current value of j (if a contains exactly one element). Therefore, a.map(...)|j == j in all cases and is safe to use here.
Test cases

f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`

console.log(f([1], [4]));
console.log(f([1,2,-3,-4], [15]));
console.log(f([0,-4], [2,1,0,-3]));
console.log(f([0,3,2,2,8,4], [7,8,7,2]));
console.log(f([18,17,16], [-1,-2,-3,-4]));
console.log(f([18,17,16,15], [-1,-2,-3,-4]));
console.log(f([1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));

I have not even tried to understand the answer, +1 for the note. I'll copy and keep it to paste when needed

Haskell, 84 79 bytes
a#b=a%b where(c:d)%(e:f)|(x:y)<-d%f=(c+e:x):y;[]%[]=[[]];c%[]=[]:c%b;_%d=[]:a%d

My first version was the same in more readable layout:
a#b=a%b where
 (c:d)%(e:f)|(x:y)<-d%f=(c+e:x):y
 []%[]=[[]]
 c%[]=[]:c%b
 _%d=[]:a%d

Using a local definition to avoid having to give (%) extra arguments for a and b. Amazingly, this is almost the same solution given at almost the same time as @nimi's, from whom I took the idea of using only one line for the local definition.
Usage:
*Main> [0,3,2,2,8,4] # [7,8,7,2]
[[7,11,9,4],[15,12],[7,5],[9,10,15,6]]

Oh, that's a nice way to prepend the sum to the first element of the list. Far shorter than my cumbersome !.

PHP, 126 120 bytes
function($a,$b){do{$c[$j][]=$a[$i%$x=count($a)]+$b[$i%$y=count($b)];++$i%$x&&$i%$y?:$j++;}while($i%$x|$i%$y);return$c;};

Try it here!
Anonymous function that returns the resulting array of arrays.
Essentially, we loop through the contents of both of our arrays, modding our iterator by the length of the array to simulate 'copying' them. Taking each of the values from the arrays, we sum them and add them to an array in $c. If we reach the end of one of our input arrays (a split, in terms of the challenge), we start assigning into a new array in $c.
The reason for the do while loop is because our condition is based on $i, which starts at 0. If we use a loop where the condition is checked at the beginning, the loop wouldn't run
We only end the summation once we reach the end of both of the arrays at the same time, which would imply the LCM.

Shouldn´t that be $b[$i%$y]? You can save 3 bytes by moving $x=count($a) to the first usage of $x; same for $y=count($b) and one byte with bitwise or in the while condition

But I think anonymous functions are considered snippets and hence are no valid answers.

@Titus Anonymous functions are allowed by default as per consensus on Meta.

Thanks for the suggestions @Titus, I just kinda threw this together cause I wanted to beat the other PHP answers :P

Haskell, 87 84 bytes
a#b=a%b where[]%[]=[[]];(e:f)%(g:h)=f%h!(e+g);e%[]=[]:e%b;_%g=[]:a%g
(m:n)!l=(l:m):n

Usage example: [0,3,2,2,8,4] # [7,8,7,2] -> [[7,11,9,4],[15,12],[7,5],[9,10,15,6]].
Simple recursion. Base case: both lists are empty. If only one of them is empty, restart with a full version and start a new cluster in the output. If none is empty, prepend the sum to the from element.
Have also a look at @Christian Sievers' answer, which is almost identical and was posted a few seconds earlier.

Are you sure? Is there a way to get the exact times?

@ChristianSievers: I don't know if you can see the times directly. When the times of our edits were shown in minutes, I remember that yours was counted up a few seconds (about 20) earlier than mine.

You're right: I found timestamps in the html source code of this page

Hover over the time in "answered 2 days ago" to see the exact time. (Hint: this is a standard UI across the internet, so (a) if you want an exact time, try hovering the relative time, and (b) if you ever implement something that shows relative time, please show the exact time on hover!)

CJam, 30 bytes
{Sf*Laf+_s,f*:.+La/0=S2*a-Sa/}

Try it online!
Takes input as a pair of lists.
Explanation
The idea is to insert some markers into the input arrays (in the form of short strings) which indicate where the aligned array ends, and where we need to insert the breaks in the arrays. This way we can avoid having to compute the LCM.
Sf*    e# Riffle each list with spaces. These are just place holders, so that having
       e# an array-end marker between two elements doesn't misalign subsequent elements.
Laf+   e# Append an empty string to each list. This is the array-end marker.
_s,    e# Convert the pair of lists to a string and get its length. This is always
       e# greater than the number of elements in either input.
f*     e# Repeat either array that many times. This is definitely more than necessary
       e# to reach the LCM (since multiplying by the length of the other list always
       e# gives a common multiple).
:.+    e# Pairwise addition of the list elements. There are four cases:
       e# - Both elements are numbers, add them. This is the actual addition
       e#   we need for the problem.
       e# - Both elements are spaces. This is just a regular position between
       e#   list elements.
       e# - One is a space, one is empty: the result is a single space, and
       e#   this marks a position where one of the arrays ended, which means
       e#   we need to split here.
       e# - Both elements are empty. This happens at the LCM of both list lengths
       e#   and indicates where we need to stop the output.
La/0=  e# Split the input around empty strings and discard everything except
       e# the first chunk.
S2*a-  e# Remove the double-space strings, we no longer need them.
Sa/    e# Split the list around single spaces.

Jelly, 21 20 18 bytes
ṁ€L€æl/$S
J€ỊÇœṗÇḊ

Try it online!
How it works
ṁ€L€æl/$S  Helper link. Argument [X, Y] (arrays of integers).

       $   Combine the two links to the left into a monadic chain.
  L€       Length each; yield the lengths of X and Y.
    æl/    Reduce by least common multiple.
ṁ€         Mold each; cyclically repeat the elements of X and Y to extend them
           to length lcm(length(X), length(Y)).
        S  Compute the sum of the extended X and Y arrays.

J€ỊÇœṗÇḊ   Main link. Argument [A, B] (arrays of integers).

J€         Indices each; replace A and B by the arrays of there 1-based indices.
  Ị        Insignificant; map 1 to itself, all other indices to 0.
   Ç       Apply the helper link to the result.
           This yield a Boolean array with a 1 (or 2) at all indices where a new
           repetition of A or B (or both) begins.
      Ç    Apply the helper link to [A, B].
    œṗ     Partition; break the result to the right at truthy elements (1 or 2) in
           the result to the right.
       Ḋ   Dequeue; remove the first element of the partition (empty array).

J, 34 32 bytes
[:(<;.1~*)/[:+/*.&#$&>,:&(;2>#\)

Try it online!
Explanation
[:(<;.1~*)/[:+/*.&#$&>,:&(;2>#\)  Input: array A (LHS), array B (RHS)
                             #\   Length of each prefix of A and B
                           2>     Less than 2
                          ;       Link each with A and B
                      ,:&         Pair them
                  #               Length of A and B
               *.&                LCM of the lengths
                    &>            For each box
                   $              Reshape it to the LCM of the lengths
           [:+/                   Reduce by addition
[:        /                       Reduce by
        *                           Sign of RHS
   <;.1~                            Box each partition of LHS

Python 3.5 - (146137134130+12) = 142 Bytes
import math
def s(a,b):
 l,k,*r=map(len,[a,b])
 for i in range(l*k//math.gcd(l,k)):
  r+=a[i%l]+b[i%k],
  if i%k==k-1or i%l==l-1:print(r);r=[]

I cannot figure out how to put the whole for loop in one line.
Edits:

Thanks zgarb
for saving 9 bytes!
Thanks vaultah for saving 3 bytes!
Thanks mathmandan saving 5 bytes!

This gives an error for me. The gcd function is in fractions, not math.

@Zgarb the gcd in fractions module is deprecated, you can check the change here . I guess rexter is using the old version 3.4.3.

Neat, I didn't know about this change. You should mark the language as "Python 3.5" though, since it doesn't work in 3.4 or earlier. Also, you can drop the parentheses around l*k and have print(r);r=[] on the last line.

Are you sure your byte count is correct? I think there're only 145 bytes.

In any case, you can save some more bytes: 1) l,k,*r=map(len,[a,b]) 2) r+=a[i%l]+b[i%k], 3) if i%k==k-1or i%l==l-1:...

@vaultah Yes, the byte count is correct. And r+=[....] is needed. Thanks for other suggestions.

@GurupadMamadapur you don't need square brackets if you add a comma in the end.

@vaultah Whoa, I didn't see that comma.

I'm getting 142 bytes.  Are you using Windows?  Windows usually counts newlines as 2 bytes each, but here each newline is counted as a single byte.

@mathmandan Thanks for saving lots of bytes in every answer of mine :D

Python 2, 119 bytes
a=input()
i,v,l=0,list(a),len
while 1:q=l(v[0])>l(v[1]);print map(sum,zip(*v)[i:]);i=l(v[q]);v[q]+=a[q];1/(i-l(v[q^1]))

Takes input from stdin as two tuples separated by comma, outputs resulting lists to stdout. Terminates by raising the ZeroDivisionError exception, since that seems to be allowed.
For example, if the input is (0, 3, 2, 2, 8, 4), (7, 8, 7, 2), the program will print
[7, 11, 9, 4]
[15, 12]
[7, 5]
[9, 10, 15, 6]

to stdout and the exception traceback to stderr.

You can exit the program by throwing an error. Then you might be able to get the loop into a single line.

Octave , 113 bytes
@(a,b)mat2cell(sum([repmat(a,1,(L=lcm(A=numel(a),B=numel(b)))/A);repmat(b,1,L/B)]),1,diff(unique([0:A:L,0:B:L])))

this function is directly callable to call it place it in parenthesis and call as (@(a,b)...)([1 2 3 4],[6 4 5])

Now TIO-Nexus supports Octave. Here's a link to test the code

@LuisMendo Thanks, interesting service

Python 3.5, 210 176 173 169 158 Bytes
def f(a,b):
 x=[];e=f=0
 while 1:
  if e==len(a):
   print(x);x=[];e=0;
   if f==len(b):break
  if f==len(b):print(x);x=[];f=0
 x+=a[e]+b[f],;e+=1;f+=1

Takes two lists as input and prints all the lists.
Its my first answer and I don't know how to golf yet. The basic idea I've used is to have two counters for each list which indicate a split and a current list where the added values are appended onto; as soon as a split is encountered, we print the current list and make a new empty one.

Saved 34 bytes: Thanks to Dennis and  TimmyD
Saved 3 bytes: was using c and d for len(a) and len(b), but turns out they weren't useful
Saved 4 bytes: Thanks to orlp, removed unwanted paranthesis
Saved 11 bytes: rearranged some blocks and crunched them down

Hi, and welcome to Programming Puzzles & Code Golf! Non-competing means something else here; you should remove that. You can save quite a few bytes by eliminating whitespace. For example, lines 2 to 5 can become x=[];c=len(a);d=len(b);e=f=0. Also, true can become 1, and x.append(a[e]+b[f]) can become x+=a[e]+b[f],.

Welcome to PPCG! In addition to Dennis' specific tweaks, check out Tips for Golfing in Python to get some more general hints and tricks.

if and while statements do not need parenthesis.

PowerShell, 147 145 bytes
param($a,$b)$o=@{};do{$o[+$j]+=,($a[+$i%($x=$a.count)]+$b[$i++%($y=$b.count)]);if(!($i%$x-and$i%$y)){$j++}}until(($x,$y|?{!($i%$_)}).count-eq2)$o

Try it online!
(Golfing suggestions welcome. I feel there's probably another 10 to 15 bytes that can be squeezed out of this.)
Takes input as two explicit arrays (with the @(...) syntax) as command-line arguments. Returns a hashtable of the resulting arrays, because multidimensional arrays in PowerShell can get weird, and this is more consistent. Sets some initial variables, then enters a do/until loop again, with the conditional being until $i is the lcm of the array counts.
Each loop iteration, we add the corresponding $a and $b values together, treat it as an array ,(...) before adding it into the hashtable $o at the appropriate spot $j. The array encapsulation is necessary to prevent arithmetical addition -- this forces the += to overload to array concatenation instead. Then, a conditional on $x and $y (the counts) to determine if we're at an array edge - if so, we increment $j.
Finally, we leave $o on the pipeline and output is implicit.
(NB: Due to how PowerShell enumerates hashtables with the default Write-Output, this tends to be output "backward"; as in, the "0th" resultant array is on the "bottom" of the output. The hash itself is fine, and would be used just fine if you e.g., encapsulated this code in a return variable ... it just looks odd when it's printed.)
Saved 2 bytes by moving $x and $y into the array indexing rather than separate (saved two semicolons).

Python 2, 113 bytes
a,b=input()
i=m=n=0;r=[]
while(not i)+m+n:r+=[[]]*(not m*n);r[-1]+=[a[m]+b[n]];i+=1;m=i%len(a);n=i%len(b)
print r

Could the nots be <1s instead?

Racket 373 bytes
(let*((lg length)(fl flatten)(ml make-list)(t rest)(r reverse)(m modulo)(o cons)(ln(lg l))(jn(lg j))(c(lcm ln jn))(l2(fl(ml(/ c ln)l)))
(j2(fl(ml(/ c jn)j)))(ll(for/list((a l2)(b j2))(+ a b))))(let p((ll ll)(ol '())(tl '())(n 0))(cond[(empty? ll)(t(r(o(r tl)ol)))]
[(or(= 0(m n ln))(= 0(m n jn)))(p(t ll)(o(r tl)ol)(take ll 1)(+ 1 n))][(p(t ll)ol(o(first ll)tl)(+ 1 n))])))

Ungolfed:
(define(f l j)
  (let* ((ln (length l))
         (jn (length j))
         (c (lcm ln jn))
         (l2 (flatten (make-list (/ c ln) l)))
         (j2 (flatten (make-list (/ c jn) j)))
         (ll (for/list ((a l2)(b j2))
               (+ a b))))

    ; TO CUT LIST INTO PARTS:
    (let loop ((ll ll)
               (ol '())
               (templ '())
               (n 0))
      (cond
        [(empty? ll)
         (rest (reverse (cons (reverse templ) ol)))]
        [(or (= 0 (modulo n ln))
             (= 0 (modulo n jn)))
         (loop (rest ll)
               (cons (reverse templ) ol)
               (list (first ll))
               (add1 n))]
        [(loop (rest ll)
               ol
               (cons (first ll) templ)
               (add1 n))]))))

Testing:
(f '[1]  '[4])
(f '[1 2 -3 -4] '[15])
(f '[0 3 2 2 8 4]  '[7 8 7 2])

Output:
'((5))
'((16) (17) (12) (11))
'((7 11 9 4) (15 12) (7 5) (9 10 15 6))

Clojure, 280 206 bytes
(fn[a b](let[A(count a)B(count b)Q quot](map #(map last %)(partition-by first(take-while #((% 0)2)(map-indexed(fn[i s][[(Q i A)(Q i B)(or(= i 0)(>(mod i A)0)(>(mod i B)0))]s])(map +(cycle a)(cycle b))))))))

Well this makes a lot more sense. Generating the element-wise sum, adding positional metadata, taking while we haven't repeated yet and putting the sum value to each partition.
(def f (fn[a b]
         (let[A(count a)B(count b)Q quot]
           (->> (map +(cycle a)(cycle b))
                (map-indexed (fn [i s][[(Q i A)(Q i B)(or(= i 0)(>(mod i A)0)(>(mod i B)0))]s]))
                (take-while #((% 0)2))
                (partition-by first)
                (map #(map last %))))))

Original:
I'm hoping to improve this but this is the sortest one I have for now.
(fn[a b](let [C cycle o count c(take-while #(or(=(% 0)0)(>(% 1)0)(>(% 2)0))(map-indexed(fn[i[A B]][i(mod i(o a))(mod i(o b))(+ A B)])(map(fn[& v]v)(C a)(C b))))](map #(map last %)(partition-by first(map(fn[p c][p(last c)])(reductions + (map #(if(or(=(% 1)0)(=(% 2)0))1 0)c))c)))))

Ungolfed and verbose:
(def f (fn[a b]
         (let [c(->> (map (fn[& v]v) (cycle a) (cycle b))
                     (map-indexed (fn[i[A B]][i (mod i(count a)) (mod i(count b)) (+ A B)]))
                     (take-while #(or(=(% 0)0)(>(% 1)0)(>(% 2)0))))]
           (->> (map (fn[p c][p(last c)]) (reductions +(map #(if(or(=(% 1)0)(=(% 2)0))1 0)c)) c)
                (partition-by first)
                (map #(map last %))))))

Starts by "merging" an infinite cycle of collections a and b, adds metadata on each element's index within the collection, takes until both sequences start from index 0 again.
This collection c is then merged with partition data (a cumulative sum of ones and zeroes), partitioned and the last element (being sum of items) is selected.
I think for significant improvements a totally different approach is required.

Haskell, 166 bytes
This is probably not the most elegant approach: Basically the function ? creates one list of the needed length with thesums, and % is cutting this sum up again. ! is the final function that merges those two.
l=length
a?b=take(lcm(l a)$l b)$zipWith(+)(cycle a)$cycle b
l%(i:ind)|l==[]=[]|1>0=take i l:(drop i l)%(map(+(-i))ind)
a!b=(a?b)%[k|k<-[1..],k`mod`l a<1||k`mod`l b<1]

You can replace ind by k or something, and there are some unnecessary parentheses around drop i l and map(+(-i))ind. Consider also having two cases for %, with pattern matching on l.

[PHP], 183 152 135 bytes
function O($A,$B){while($f<2){$O[$k][]=$A[+$i]+$B[+$j];$f=0;isset($A[++$i])?:$i=!++$k|!++$f;isset($B[++$j])?:$j=!++$k|!++$f;}return$O;}

Nice version:
function O($A,$B)
{
    while($f<2) {
        $O[$k][]=$A[+$i]+$B[+$j];
        $f=0;
        isset($A[++$i])?:$i=!++$k|!++$f;
        isset($B[++$j])?:$j=!++$k|!++$f;
    }

    return$O;
}

Output:
array (size=4)
  0 =>
    array (size=4)
      0 => int 7
      1 => int 11
      2 => int 9
      3 => int 4
  1 =>
    array (size=2)
      0 => int 15
      1 => int 12
  2 =>
    array (size=2)
      0 => int 7
      1 => int 5
  3 =>
    array (size=4)
      0 => int 9
      1 => int 10
      2 => int 15
      3 => int 6

Draw even with me using these tweaks: $i=$j=$k=0; is unnecessary if you use +$i etc. for the array indexes in the appending assignment (-8 bytes). $i++;if(!isset($A[$i])){$i=0;$k++;} --> isset($A[++$i])?:$i=!++$k; (-9, twice). $i==0&&$j==0&&!isset() --> !$i&!$j&!isset() (-6). return$O; needs no space (-1).

@Titus can't remove $i=$j=0; part since first values from arrays won't be correct. I've modified logic a little so not sure how to implement ternary operators in this case. Thanks for ++$i advices.

Try unset($i);$A[+$i]. The + will cast null to integer 0.

if(!isset($A[++$i])){$i=0;++$k;++$f;} --> isset($A[++$i])?:$i=!++$k|!++$f; still saves 5 bytes each. Save one more with $f<2 instead of $f!=2. and another two with while($f=$f<3){...} instead of while($f<2){$f=0;...} (initializes and resets $f to 1 unless it´s incremented twice)

@Titus Thanks a lot, it is shorter now.

Oh and I think with while(!$k|$i|$j) you can remove $f again. (That should get you down to 125 bytes).

PHP, 150 121 119 bytes
function($a,$b){while($i<2|$x|$y)$r[$k+=!($x=$i%count($a))|!$y=$i++%count($b)][]=$a[$x]+$b[$y];array_pop($r);return$r;}

anonymous function takes input as arrays.
breakdown
while($i<2|$x|$y)   // loop while either $a or $b has NO cut
    $r[
                // if either $a or $b has a cut, increment $k; post-increment $i
        $k+=!($x=$i%count($a))|!$y=$i++%count($b)
                // append current $a + current $b to $r[$k]
    ][]=$a[$x]+$b[$y];
array_pop($r);  // $r has one element too much; remove it
return$r;

C++14, 206 bytes
As unnamed generic lambda, requiring input containers P,Q and output container R to be like vector<vector<int>>.
[](auto P,auto Q,auto&R){R.clear();auto a=P.begin(),b=Q.begin(),x=P.end(),y=Q.end();auto A=a,B=b;do{R.emplace_back();while(a!=x&&b!=y)R.back().push_back(*a+++*b++);a=a==x?A:a;b=b==y?B:b;}while(a!=A||b!=B);}

Ungolfed and usage:
#include<vector>
#include<iostream>

using namespace std;

auto f=
[](auto P,auto Q,auto&R){
 R.clear();               //just clear the output to be sure
 //a and b are the iterators, x and y is the end
 auto a=P.begin(),b=Q.begin(),x=P.end(),y=Q.end();
 //just some abbreviations for .begin()
 auto A=a,B=b;
 do{
  R.emplace_back();      //add new vector
  while(a!=x&&b!=y)      //while not at the end of one vector
   R.back().push_back(*a+++*b++);  //add the pointed elements and advance
  a=a==x?A:a;            //reset if at the end
  b=b==y?B:b;
 }while(a!=A||b!=B);     //if both were resetted, then finish
}
;

int main(){
 vector<int> A = {0, 3, 2, 2, 8, 4};
 vector<int> B = {7, 8, 7, 2};
 vector<vector<int>> R;
 f(A,B,R);
 for (auto c:R){
  for (int x:c)
   cout << x << ", ";
  cout << endl;
 }
 cout << endl;
}

Mathematica 112 Bytes
This could probably be improved upon.  The idea is to create a 2D array with the second element used to track the lessor of the counter i mod the length of each input array.
Split[Table[{#[[1,(m=Mod[i,d=Length/@#,1])[[1]]]]+#[[2,m[[2]]]],Min@m},{i,LCM@@d}],#2[[2]]>#1[[2]]&][[;;,;;,1]]&

Usage
%@{{0,3,2,2,8,4},{7,8,7,2}}

JavaScript (ES6), 131 bytes
(a,b,g=(r,[n,...d]=a,[m,...e]=b,s=[])=>1/n?1/m?g(r,d,e,[...s,n+m]):g([...r,s],[n,...d]):1/m?g([...r,s],a,[m,...e]):[...r,s])=>g([])

Slightly ungolfed:
(a,b,r=[],[n,...d]=a,[m,...e]=b,s=[])
=>1/n?1/m?f(a,b,r,d,e,[...s,n+m])
         :f(a,b,[...r,s],[n,...d],b,[])
     :1/m?f(a,b,[...r,s],a,[m,...e],[])
         :[...r,s]

If both arrays d and e contain numbers, the sum of the first number is appended to s and the remaining elements are processed recursively
If one of the arrays contains numbers, the array of sums s is appended to the result r and the other array is reset to its initial array
If both arrays are empty then simply return the result with the last sums appended.

Sadly this solution doesn't have the ruthless efficiency of @Arnauld's, but at least I think it's a beautiful solution.

Jelly, 17 bytes
Ẉæl/
ẈḍⱮÇ§kṁ€ÇSƊṖ

Try it online!
How it works
Ẉæl/ - Helper link. Takes an array [A, B] on the left
Ẉ    - Lengths; [len(A), len(B)]
   / - Reduce by:
 æl  -   LCM
       This yields R := lcm(length(A), length(B))

ẈḍⱮÇ§kṁ€ÇSƊṖ - Main link. Takes [A, B] on the left
Ẉ            - [len(A), len(B)]
   Ç         - Call the helper link on [A, B]
  Ɱ          - Over each integer i = 1, 2, ..., R:
 ḍ           -   Yield [x, y] where:
                   x = 1 if len(A) % i == 0 else 0
                   y = 1 if len(B) % i == 0 else 0
    §        - For each pair, yield 0 if x = y = 0 else a non-zero element
          Ɗ  - To [A, B]:
        Ç    -   Yield R
       €     -   Over each element A, B:
      ṁ      -     Mold to length R
         S   -   Columnwise sums
     k       - Partition this array on the right at the non-zero indexes on the left
           Ṗ - Remove the trailing empty array

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:
It's almost Christmas!
Because of this, families from all over the world are building Christmas trees.
But this normal tree can get boring after a while, so let's make an ASCII tree!
Leafs are represented by # and must be arranged as shown in the example output. We have 5 balls (O) and 5 candy canes (J), which we place randomly around the tree. We also have a candle on top.
Input: none
Output:
         ^
         |
        ###
       ##O##
      #######
       #####
      ####J##
     #########
    ####O######
   #############
      ###J###
     #########
    ####O###J##
   #######O#####
  ###J########O##
 ###########J#####
        ###
        ###

Rules (if it's not in the rules, assume you can)

Balls and candy canes must be randomly placed on the tree and must have at least one leaf between them, not counting diagonals.
Each leaf must have a non-zero chance of getting a ball or a candy cane.
There may be leading or trailing spaces on each line, as long as the tree has the proper shape.
This is code-golf, so shortest code in characters wins.

related

@Billywob it's a close one, this one has a randomised factor and a candle tho :P

Yeah, this is most certainly more difficult imo.

related: http://codegolf.stackexchange.com/q/15860/7209

“But this normal tree can get boring after a while.” Then why the old school candle and not something creative?

@manatwork ohwow, that's a nice deco, I was actually reffering to a physical tree

Related.

Since no one else has mentioned, I'll recommend that you post future challenges to the Sandbox where you can get meaningful feedback and tweak challenges before you post them to Main.

If you don't answers that look like this, I suggest scoring by bytes rather than characters.

Is it legal to usually place all of the balls?  For example, if you flip a coin for every leaf to see if it gets an ornament, then every leaf has a non-zero chance of getting an ornament, but there's also a remote (but non-zero) chance that you don't place all of the ornaments.  Supposing there was a 99% chance that you place them correctly, is that a fair answer?

Should the trunk be considered leafs as well or not?

JavaScript (ES6), 148 bytes
Hopefully, this should comply with the 'random enough' condition.
_=>[...'887656543254321077'].map(n=>' '.repeat(n)+'#'.repeat(17-2*n)).join`
`.replace(/#/g,_=>'OJ^|#'[++i<4?i:i>133|++j%13?4:j/13&1],i=1,j=new Date)

Demo

let f =

_=>[...'887656543254321077'].map(n=>' '.repeat(n)+'#'.repeat(17-2*n)).join`
`.replace(/#/g,_=>'OJ^|#'[++i<4?i:i>133|++j%13?4:j/13&1],i=1,j=new Date)

console.log(f())

I've tested and got a tree that brokes 'and must have at least one leaf (#) inbetween them, not counting diagonals'

@user2216 Unless I somehow missed or misunderstood something, the modulo was chosen in such a way that it can't possibly happen -- except along diagonals. (There are 13 distinct patterns that you can test by replacing j=new Date with j=0 to j=12.)

CS-Script - 306 bytes
var c=new string(' ',342).ToCharArray();var r=new Random();int e=18,i,j,w;for(;i<e;i++){c[i*e+e]='\n';w=i<5?i:i<10?i-2:i<16?i-6:2;for(j=1;j++<w*2;)c[i*e+8-w+j]='#';}for(i=0;i<10;){j=37+r.Next(288);if(c[j]=='#'&c[j+1]<42&c[j-1]<42&c[j+e]<42&c[j-e]<42)c[j]=i++<5?'J':'O';}c[8]='^';c[27]='|';Console.Write(c);

Once more with formatting and comments:
// create 'char bitmap' filled with spaces
var c=new string(' ',342).ToCharArray();
// Random for placing ornaments
var r=new Random();
int e=18,i,j,w;
// once for each row
for(;i<e;i++)
{
    // add new lines
    c[i*e+e]='\n';
    // determine width of tree for this row
    w=i<5?i:i<10?i-2:i<16?i-6:2;
    for(j=1;j++<w*2;)
        // add leaves
        c[i*e+8-w+j]='#';
}
for(i=0;i<10;)
{
    // select random location
    j=37+r.Next(288);
    if( // check we have a leaf
        c[j]=='#' &
        // check surrounding to be leaf/space/new-line
        c[j+1]<42 & c[j-1]<42 & c[j+e]<42 & c[j-e]<42)
        // add ornament if location is valid
        c[j]=i++<5?'J':'O';
}
// light candle
c[8]='^';
c[27]='|';
// print
Console.Write(c);

It's basically C#, but using CS-Script allows me to skip all the boiler-plate.
Try it here!
Notes:
This currently outputs another line of white spaces below the tree to make sure the that 'checking for existing ornaments below' does not throw an IndexOutOfBoundsException. Other solutions would be:

Checking if it is the last line before checking below (adds a few more character)
Not adding ornaments to the 'stem' of the tree (Same byte count, but seems to me to be against rules)

I'll leave it to the OP if this should be changed.
Lastly, this is my first golf, so any feedback is appreciated. ;)

Nice solution. It think you might need to include using System; in your byte count though, as you can't use Random or Console without it. http://meta.codegolf.stackexchange.com/questions/10081/byte-count-for-imports-or-other-things-not-needed-for-definition-but-for-exec/10848#10848 Sorry to add 13 bytes :(

@Erresen: Thanks for the link! As far as I can tell, it only talks about imports necessary for execution though, and for cs-script using System; is not needed (it automatically imports common namespaces). But maybe I'm splitting hairs. ¯_(ツ)_/¯

who knows! I only started playing the other day myself. Didn't know about cs script before seeing your answer. Really useful for avoiding some C# disadvantages in golfing. Whatever the answer is, I don't think a c# script's gonna win any time soon.

That much is certain, yeah. :D

If you compile to a function, if possible in CS-Script, you could reduce the byte count i.e. _=>{var c=... return c;}

TSQL, 556 532 494 476 bytes
This script needs to be executed on the master database
Golfed:
DECLARE @ varchar(max)='',@h INT=0,@w INT=0WHILE @h<18SELECT
@+=space(9-@w)+REPLICATE(char(IIF(@h<2,94+30*@h,35)),@w*2+1)+space(9-@w)+CHAR(10),@h+=1,@w+=CHOOSE(@h,0,1,1,1,-1,1,1,1,1,-2,1,1,1,1,1,-8,0)WHILE
@h>7WITH C as(SELECT*,substring(@,number,1)v,number/20r,number%20c
FROM spt_values WHERE type='P'and number<358)SELECT @=stuff(@,number,1,CHAR(74+@h%2*5)),@h-=1FROM
c d WHERE v='#'and not exists(SELECT*FROM c WHERE abs(d.c-c)+abs(d.r-r)<2and'A'<v)ORDER BY newid()PRINT @

Ungolfed:
DECLARE @ varchar(max)='',@h INT=0,@w INT=0

WHILE @h<18
  SELECT @+=
    space(9-@w)+REPLICATE(char(IIF(@h<2,94+30*@h,35)),@w*2+1)
      +space(9-@w)+CHAR(10),
    @h+=1,
    @w+=CHOOSE(@h,0,1,1,1,-1,1,1,1,1,-2,1,1,1,1,1,-8,0)

WHILE @h>7
  WITH C as
  (
    SELECT*,substring(@,number,1)v,number/20r,number%20c
    FROM spt_values
    WHERE type='P'and number<358
  )
  SELECT @=stuff(@,number,1,CHAR(74+@h%2*5)),@h-=1
  FROM c d
  WHERE v='#'and not exists(SELECT*FROM c WHERE abs(d.c-c)+abs(d.r-r)<2and'A'<v)
  ORDER BY newid()

PRINT @

Try it out

Python 3  - 450 427 bytes
I know 450 is too much for python. But, but.....
from random import randint as r
t=lambda o,g:(o*g).center(19,' ')+';';s,z='','#';s+=t(z,3)*2
for h,w in zip([6,5,3],[17,13,7]):
 for i in range(h):s+=t(z,w);w-=2
s+=t('|',1)+t('^',1);s=[list(i)for i in s.split(';')]
for o in'O'*5+'J'*5:
 while 1:
  h,w=r(2,15),r(1,16)
  m=s[h]
  C,m[w]=m[w],o
  P=s[h-1][w]+s[h+1][w]+m[w-1]+m[w+1]
  if not('O'in P or'J'in P)and C!=' ':break
  m[w]=C
print (*[''.join(i)+'\n'for i in s][::-1])

If the for i in'O'*... is turned into a better recursive function then lots of bytes can be cut down.
Try it here
Edit:
Saved 2 bytes by using ; as delimiter and several bytes by taking newline byte count as 1 byte.

JavaScript, 204 bytes

f=(s='^|1232345634567811'.replace(/./g,x=>(y=x|0,' '.repeat(8-y)+(y?'#'.repeat(y*2+1):x)+`
`)),o=5,j=5,r=(Math.random()*56|0)*4,k)=>j?f(s.replace(/###/g,(_,i)=>i-r?_:k=o?'#O#':'#J#'),k?o-!!o:o,k?j-!o:j):s

console.log(f());
.as-console-wrapper{max-height:100%!important;top:0}

why are you counting \n as 1 byte?

Not anymore, sorry

PHP, 200 bytes
might be shorter with a more sophisticated approach; but I´m in a hurry.
for(;$c="^|2343456745678922"[$i++];)$s.=str_pad(+$c?str_pad("",2*$c-1,"#"):$c,17," ",2)."
";for(;$n++<10;)$s[$p=rand(0,288)]!="#"|($s[$p-18]|$s[$p+18]|$s[$p-1]|$s[$p+1])>A?$n--:$s[$p]=OJ[$n&1];echo$s;

requires PHP 5.6 or 7.0. Run with -nr or try it online.

Scala, 329 bytes
var r=scala.util.Random;var z=r.nextInt(2);def t{print(new StringBuilder({"^|234345645678922".map(x=>{val t=if(x>57)8 else(57-x);" "*t+{if(x>57)""+x else "#"}*(17-(t*2))+" "*t+" \n"})}.mkString)match{case e=>{var w=0;while(w<10){{val b=(r.nextInt(e.size/2)*2)+z;if(e.charAt(b)=='#'){e.setCharAt(b,if(w<5)'O'else'J');w+=1}}};e}})}

APL (Dyalog Unicode), 101 bytes
↑¯9↑¨'^|'
f←{⍵×(≢⍵)⍴2?2}
{(5/'OJ')@(x[10?≢x←⍸↑f¨f¯2↓↓'#'=⍵])⊢⍵}↑{' #'/⍨⍵,17-2×⍵}¨⍎¨'7656543254321077'

Try it online!
A full program which returns the tree.
Tree creation algorithm borrowed from Arnauld's answer.
Explanation
Displaying the top
↑¯9↑¨'^|'
     '^|' string
 ¯9↑¨     pad each with 8 spaces
↑         convert to matrix

Distancing the ornaments
f←{⍵×(≢⍵)⍴2?2} store the following lambda as f:
          2?2  generate 0 1 or 1 0 (random)
     (≢⍵)⍴     reshape to the length of the input
   ⍵×          multiply the input with it(vectorizes)

Display the tree
↑{' #'/⍨⍵,17-2×⍵}¨⍎¨'7656543254321077'
                  ⍎¨'7656543254321077' create an array of digits from the string
 {              }¨                     for each digit x:
        ⍵,17-2×⍵                       array [x,17-2*x]
  ' #'/⍨                               replicate spaces and hashes as per that
↑                                      convert to matrix

Add the ornaments:
{(5/'OJ')@(x[10?≢x←⍸↑f¨f¯2↓↓'#'=⍵])⊢⍵} apply the following to the tree:
                            '#'=⍵      boolean matrix for the tree
                           ↓           convert to 2d array
                        ¯2↓            remove trunk rows
                     f¨f               convert to swiss cheese with function f
                   ⍸↑                  get the indices of all 1s
                 x←                    and store in x
             10?≢                      pick 10 random indices in length(x) range
           x[                    ]     and take those from x
         @(                       )⊢⍵  replace those coordinates with:
 (5/'OJ')                              5 instances of 'O' and 5 instances of 'J'

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

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


text:
Help PPCG Claus Deliver his Presents!
Help PPCG Claus Deliver his Presents
Overview
PPCG Claus is running hella late delivering his gifts because nowadays we have so many odd little kiddos out there. This makes it much harder for PPCG Claus to get all the presents to the correct place. Your challenge is to help him delvier his presents correctly.
The Complexity
Given a list of capitalized first names representing the kids he's supposed to deliver to and a list of presents represented by numbers, you must figure out how to distribute the presents among said children. Of course there's a catch though....
Nowadays kids are getting picky, if the kiddo is an odd fellow (first initial is ASCII-code odd) he wants an odd gift! If he's an even fellow (first initial is ASCII-code even) he obviously must be given an even one! Any child divisible by 3, however, is a naughty, naughty lad, so PPCG Claus must completely ignore them to make them behave next year. To consider his route a success he must deliver all presents to all children who deserve them and must not give any one child too many presents. If any child gets 3+ more presents than his or her peers, he risks becoming a naughty child next year, and that's just not right! Also, if any good child were to receive a present when another good child didn't, that also would turn that child evil.
Example
The kids are as follows:
Kids = ["Amy", "Betty", "Clyde", "Dave", "Francine"] = [A,B,C,D,F] = [65,66,67,68,70]

Betty is the bane of humanity, clearly in cahoots with the number 3.
Amy and Clyde have been weirdos since birth and would hate to receive
even presents.
Dave and Francine are normal, even, kids; they should only receive even presents!

The presents are as follows:
Presents = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
One possible output would be:
[
    ['Amy',[1,3,5]],
    ['Betty',[]],
    ['Clyde',[7,9,11,13]],
    ['Dave',[2,4,6,8]],
    ['Francine',[10,12,14]]
]

Exception Scenarios
However, just because PPCG Claus is ready and willing, doesn't mean PPCG Claus can. Here's a list of exception scenarios where you must break the bad news to PPCG Claus with a message of:
PPCGmas is cancelled!
The following scenarios will result in Christmas being cancelled:

There are no children.

[],[1,2,3] - Wellp, they ded.

There are no good children.

["Betty"],[1,2,3] - Seriously, screw Betty.

There are no presents, or less presents than good children.

["Amy","Charles"],[] - One or more would receive no presents.
["Amy","Charles"],[1] - One or more would receive no presents.

There are not odd/even presents to satisfy all good children.

["Amy","Dave"],[2,4,6] - Amy is screwed over.

Here's a list of scenarios that shouldn't affect PPCGmas:

Leftover Presents (All children should receive the maximal amount of presents).

["Amy","Dave"],[2,4,6,8,10,12,14,7,9] = [["Amy",[7,9]],["Dave",[2,4,6,8]]]

Main Rules Reiterated

Good children are either even or odd, based on their first initial.
Bad children have a first initial wholly divisible by 3.
All good children must receive at least one present.
No good child is to receive greater than 2 presents more than any other good child.
If there are to be leftover presents you must maximally distribute them, without violating 4.
Bad children must receive no presents at all.
If ANY of these is violated, you must output PPCGmas is cancelled!, exactly.

I/O Format Requirements

The 1st input must be an array/list/comma-delimited string of full names, not just the first initial.
The 2nd input must be a array/list/comma-delimited string of positive integers.
The output may be any denotation of how you distributed the presents that makes sense; or PPCGmas is Cancelled!.

Winning Criterion: code-golf
TL;DR: Betty is a jerk, don't compete.

I don't understand, in the example, why doesn't Betty get 3? EDIT: If one should "screw Betty", why is she in the challenge at all?

@SeeOneRhino B = 66, 66 % 3 = 0, 66 is divisible by 0, Betty is naughty.

APL, 171 bytes
{D←{⍵=1:⊂⍺⋄0~⍨¨↓⍵↑⍉↑⍺⊂⍨1=⍵|⍳⍴⍺}⋄e←⍺~o←⍺/⍨2|⍺⋄(0=≢G)∨0∊≢¨P←P↑⍨¨(2+⌊/R)⌊R←≢¨P←(o D≢O),e D≢E←G~O←G/⍨2|⎕A⍳⊃¨G←⍵/⍨×3|⊃∘⎕UCS¨⍵:'PPCGmas is cancelled!'⋄(O,E,B),[⍟4]P,(≢B←⍵~G)↑⊂⍬}

This takes the presents as the left argument, the children as the right argument, and returns a matrix where the first column contains the names of the children and the second column contains the presents they get.
Testcases:
      P←{D←{⍵=1:⊂⍺⋄0~⍨¨↓⍵↑⍉↑⍺⊂⍨1=⍵|⍳⍴⍺}⋄e←⍺~o←⍺/⍨2|⍺⋄(0=≢G)∨0∊≢¨P←P↑⍨¨(2+⌊/R)⌊R←≢¨P←(o D≢O),e D≢E←G~O←G/⍨2|⎕A⍳⊃¨G←⍵/⍨×3|⊃∘⎕UCS¨⍵:'PPCGmas is cancelled!'⋄(O,E,B),[⍟4]P,(≢B←⍵~G)↑⊂⍬}
      (⍳14) P 'Amy' 'Betty' 'Clyde' 'Dave' 'Francine'
┌────────┬─────────┐
│Amy     │1 5 9 13 │
├────────┼─────────┤
│Clyde   │3 7 11   │
├────────┼─────────┤
│Dave    │2 6 10 14│
├────────┼─────────┤
│Francine│4 8 12   │
├────────┼─────────┤
│Betty   │         │
└────────┴─────────┘
      1 2 3 P ⍬
PPCGmas is cancelled!
      1 2 3 P ⊂'Betty'
PPCGmas is cancelled!
      ⍬ P 'Amy' 'Charles'
PPCGmas is cancelled!
      (,1) P 'Amy' 'Charles'
PPCGmas is cancelled!
      2 4 6 P 'Amy' 'Dave'
PPCGmas is cancelled!
      2 4 6 8 10 12 14 7 9 P 'Amy' 'Dave'
┌────┬───────┐
│Amy │7 9    │
├────┼───────┤
│Dave│2 4 6 8│
└────┴───────┘

Ungolfed version here.

What's this "christmas" of which you speak in the ungolfed version :P?

JavaScript (ES6), 525 492 454 453 bytes
-71 bytes thanks to @Guedes
-1 bit thanks to @Jake Cobb
P=(K,p)=>{y='charCodeAt';n=(C)=>C[y](0)%3>0;N=(C)=>C[y](0)%3<1;E=(C)=>C[y](0)%2>0;O=(C)=>C[y](0)%2<1;f=(U)=>U%2<1;F=(U)=>U%2;M=(U,C)=>C%s==S;s=S=0;a=new Array();G='filter';e=p[G](f);o=p[G](F);J=K[G](n);r=J[G](O);L='length';i=J[G](E);s=r[L];for(S=0;S<r[L];S++){a.push([r[S],e[G](M)]);}s=i[L];for(S=0;S<i[L];S++){a.push([i[S],o[G](M)]);}K=K[G](N);for(S=0;S<K[L];S++){a.push(K[S],[]);}return(e[L]<r[L]||o[L]<i[L]||(r[L]+i[L])<1)?"PPCGmas is Cancelled!":a;}

Try it online !
Non-golfed version
Can be more golfed I think. I just did a litteral translation of the non-golfed version.
This is now shorter than the sum of the CharCode composing "santa" (115 + 97 + 110 + 116 + 97 = 535). Yeay

C[0] instead of C.charCodeAt(0) saves 11 bytes. Also, when a property repeats many times you can store its name like L='length', and use i[L] instead of i.length.

By the way, welcome to PPCG!!

Thank you for the advices ! :D. Well I've tried C[0] instead of C.charCodeAt(0) (modern firefox browser on repl.it) and it returns "PPCGmas is cancelled" on the first verification. As for the second, it works well, thanks for the Bytes :)

This has the same bug as my original answer where it fails if the good children are all even or all odd, try this test: P(["Amy", "Betty", "Clyde"],[1,2,3,4,5,6,7,8,9,10,11,12,13,14]);

That's true ! It was because I used "&&" instead of "+" in one of the last verification. Thanks to you this problem is now fixed, and I gained one byte.

Python 2, 334 355 354 bytes
k,p=input()
z=zip
l=len
e=[];o=[];g=[];b=[];q=[];r=[]
for x in k:[g,b][ord(x[0])%3<1]+=x,
for x in g:[e,o][ord(x[0])&1]+=x,
for x in p:[q,r][x&1]+=x,
v=l(e)
w=l(o)
t=v and l(q)/v
u=w and l(r)/w
if u:t=min(t,u+2)
if t:u=min(u,t+2)
if l(g)*(t or v<1)*(u or w<1)<1:exit('PPCGmas is cancelled!')
print z(e,z(*[iter(q)]*t))+z(o,z(*[iter(r)]*u))+z(b,[()]*l(b))

Lost 21 bytes to handle case of only-even or only-odd children.
Saved 1 byte thanks to @TuukkaX.

Doesn't work, ord('A')%3==0 is False but 1-ord('A')%3 is -1.

Oh yes, you're right. My apologies. %3<1 should work.

Javascript (ES6), 218 216 Bytes
(a,b)=>{c={};a.forEach(d=>c[d]=[]);e=f=0;while(!e){e=g=1;a.forEach(h=>(j=h.charCodeAt())%3?(k=b.findIndex(l=>l%2==j%2))<0?g=0:c[h][f+1]?0:e=0&c[h].push(b.splice(k,1)[0]):0);f+=!e&g}return f?c:"PPCGmas is cancelled!"}

The output (if it's not the error string) is an object whose keys are the children's names; the value is the array of presents that child receives.
Saved two bytes when I realized I had a pair of redundant parentheses.
Ungolfed version:
(names, gifts) => {

  // Initialize result. Set every child's gift array to empty
  var result = {};
  names.forEach(name =>
    result[name] = [];
  );

  // Initialize external loop values
  var done = false;
  var leastNumberOfPresentsAmongGoodChildren = 0;

  // Give the gifts
  while (!done) {

    // Initialize internal loop values
    done = true;
    var everyGoodChildGotGift = true;

    // Try to give at most one gift to every good child
    names.forEach(name => {
      var nameCode = name.charCodeAt(0);

      // Ignore bad children
      if ((nameCode % 3) != 0) {

        // Try to find an appropriate gift
        var giftIndex = gifts.findIndex(gift => (gift % 2) == (nameCode % 2));

        // If there is no gift, set the flag
        if (giftIndex < 0)
          everyGoodChildGotGift = false;

        // Make sure we don't give too many gifts
        else if (result[name].length < leastNumberOfPresentsAmongGoodChildren + 2) {

          // Remove the gift from the gifts array (we can't give it again)
          var giftToGive = gifts.splice(giftIndex, 1)[0];

          // Give the gift to the child
          result[name].push(giftToGive);

          // If at least one child got a gift, try to give more gifts
          done = false;
        }
      }
    }); // end forEach

    // If we're done, that means we couldn't give a gift to any good child
    if (done)
      everyGoodChildGotGift = false;

    // If every good child got a gift, then increase the count
    if (everyGoodChildGotGift)
      leastNumberOfPresentsAmongGoodChildren++;

  } // end while

  // If every good child gets at least one gift, return who gets what
  if (leastNumberOfPresentsAmongGoodChildren != 0)
    return result;
  else
    return "PPCGMas is cancelled!"; // IT'S ALL YOUR FAULT, BETTY. YOU'VE RUINED PPCGMAS.
}

Hi, Welcome to PPCG!
Glad to see you seem to understand how posts are formatted. Happy Code-Golfing!

@ATaco Thanks! I lurk


text:
Print a Singing Angel
Keeping with a festive theme, print a carol singing angel with the shortest possible code. The angel is raising money for the homeless, so must be able to sing all three of the below songs available at request. To illustrate she can sing them, the title of the song must be placed within the speech bubble. This song title will be input by the user. Examples include:

Mother Mary
Jingle Bells
Silent Night

Input:
Title: 1 of the 3 songs.
Output:
                  ____________
(\   ___   /)    /            \
( \ (‘o‘) / )   /              \
(           )  <
 (  ‘> <’  )    \              /
    /    \       \____________/
   /      \
  ‘ – “ - ‘

Please paste the result of your singing angel along with the song: "Silent Night".
Speech Bubble Rules:
The speech bubble must always have a frame of 12 underscore lines long.
The title of the song must always start on the second line.
The title of the song must always start 3 underscore spaces inside the bubble.
                  123456789...
(\   ___   /)    /            \
( \ (‘o‘) / )   /    Song      \
(           )  <     Title
 (  ‘> <’  )    \              /
    /    \       \____________/
   /      \
  ‘ – “ - ‘

Examples below:
                  ____________
(\   ___   /)    /            \
( \ (‘o‘) / )   /    Mother    \
(           )  <     Mary
 (  ‘> <’  )    \              /
    /    \       \____________/
   /      \
  ‘ – “ - ‘

                  ____________
(\   ___   /)    /            \
( \ (‘o‘) / )   /    Jingle    \
(           )  <     Bells
 (  ‘> <’  )    \              /
    /    \       \____________/
   /      \
  ‘ – “ - ‘

                  ____________
(\   ___   /)    /            \
( \ (‘o‘) / )   /    Silent    \
(           )  <     Night
 (  ‘> <’  )    \              /
    /    \       \____________/
   /      \
  ‘ – “ - ‘

The  / and \ in your angel's skirt are asymmetrical. Is this intentional? 2. What is the purpose of showing the output, if it should be identical to the question?

Thanks Level River St for those questions. Being honest - the angel's skirt wasn't intentional. Despite this, I will keep this asymmetrical, so please do answer the question in this way. I wanted two words within the speech bubble that wouldn't misalign the box. These three titles are examples of carols and fit the box, hence fit the criteria nicely.

What assumptions can be made about the length of the song title, and the length of the individual words of the song title? Is it always 2 words that each fit into a line?

If you want to be exact - 9 letters long, 2 words, but the focus is more on the three songs listed in the description as opposed to other song titles.

This isn't ASCII-art! `‘–“ are not ASCII-characters. Also, why do you have different types of dashes?

@StewieGriffin I would bet this was an unintended consequence of typing or pasting the text in an editor with a "smart quotes/dashes" feature. TextEdit on OS X is pathological about this. We regularly get questions on SO along the lines of, "Why doesn't puts “hello” work?"

Indeed it is @Jordan....

PHP, 215 bytes
<?=($p=str_pad)($p($s=" ".$t="   ",18),30,_),$p("
(\   ___$t/)$s/",31),$p("\
( \ (‘o‘) / )$t/$t$argv[1]",37),"\
($s$s$t)  <$s$argv[2]",$p("
 (  ‘> <’  )$s\\",36),$p("/
$s/$s\\$s$t\\",32,_),"/
$t/$t$t\
  ‘ – “ - ‘";

takes title from first two command line arguments.
For Windows: add 1 to all pad-lengths after the first line, or duplicate backslashes before line breaks and replace all line breaks with \n

JS (ES6), 328 330 bytes
a=(b,c)=>b.repeat(c);f=prompt().split(" ");if(f[1].length<5)f[1]+=" ";console.log(a(" ",18)+a("_",12)+`
(\\   ___   /)    /`+a(" ",12)+`\\
( \\ (‘o‘) / )   /    `+f[0]+`    \\
(`+a(" ",11)+`)  <     `+f[1]+a(" ",21)+`
 (  ‘> <’  )    \\`+a(" ",14)+`/
    /    \\       \\`+a("_",12)+`/
   /      \\
  ‘ – “ - ‘`)

1 helper function (a gets charcode (one char shorter) and repeats c times)
1 variable for getting input via prompt() and doing a split to array
arguably abuses the special cases there but still does the job
I assumed the extra 21 spaces in the middle column were needed

a=(b,c)=>b.repeat(c);f=prompt().split(" ");if(f[1].length<5)f[1]+=" ";console.log(a(" ",18)+a("_",12)+`
(\\   ___   /)    /`+a(" ",12)+`\\
( \\ (‘o‘) / )   /    `+f[0]+`    \\
(`+a(" ",11)+`)  <     `+f[1]+a(" ",21)+`
 (  ‘> <’  )    \\`+a(" ",14)+`/
    /    \\       \\`+a("_",12)+`/
   /      \\
  ‘ – “ - ‘`)

With UTF8 encoding, this is 344 bytes, not 328.
What encoding did you use to count the bytes?

smls is correct; this is 328 chars, but 344 bytes. You can save 14 just by getting rid of String.fromCharCode and doing a=(b,c)=>b.repeat(c), then calling with an actual space or underscore each time

@ETHproductions, fixed.

@n4melyh4xor
Is it okay to accept the song title in pre-split form, i.e. to implement the code as a lambda that takes two separate parameters for the two words? Or does the song title have to come in as one string, and the splitting be done as part of the code? (The Python 3.6 solutions does the former, and if you green-light it I'll use it to shorten my Perl 6 solution, too... :))

@smls, I think it should be taken in as one string and then you can do whatever you want.

Python 3.5, 207 chars, 226 bytes
def f(s):a,b=s.split();u='_'*12;[print(' '*int(x)if x.isdigit()else x,end='')for x in"99"+u+"\n(\\3___3/)4/66\\\n( \\ (‘o‘) / )3/4"+a+"4\\\n(92)2<5"+b+"\n (2‘> <’2)4\\95/\n4/4\\7\\"+u+"/\n3/6\\\n2‘ – “ - ‘"]

Output:
                  ____________
(\   ___   /)    /            \
( \ (‘o‘) / )   /    Jingle    \
(           )  <     Bells
 (  ‘> <’  )    \              /
    /    \       \____________/
   /      \
  ‘ – “ - ‘

Slightly ungolfed:
def angel(s):
    a, b = s.split()
    u = '_' * 12;
    out = "99" + u + "\n"
    out += "(\\3___3/)4/66\\\n"
    out += "( \\ (‘o‘) / )3/4" + a + "4\\\n"
    out += "(92)2<5" + b + "\n"
    out += " (2‘> <’2)4\\95/\n"
    out += "4/4\\7\\" + u + "/\n"
    out += "3/6\\\n"
    out += "2‘ – “ - ‘"
    [print(' '*int(x) if x.isdigit() else x, end='') for x in out]

It replaces numerical digits with the same number of spaces.

Python 3.6 -  286 241 224 bytes
def x(L):X,Y=L.split();E,D=' '*11,'_'*12;print(f"""{' '*18}{D}
(\   ___   /)    /{E} \\
( \ (‘o‘) / )   /    {X+' '*(10-len(X))}\\
({E})  <     {Y}
 (  ‘> <’  )    \{E}   /
    /    \       \{D}/
   /      \
  ‘ – “ - ‘""")

Input:
x("Silent Night")

Output:
                  ____________
(\   ___   /)    /            \
( \ (‘o‘) / )   /    Silent    \
(           )  <     Night
 (  ‘> <’  )    \              /
    /    \       \____________/
   /      \
  ‘ – “ - ‘

Note - The version is 3.6 where string literal formatting was introduced. Hence, this won't work in earlier versions.

Python 2.6, 391 bytes
def angel(a):
    X,Y=a.split()
    print("                  ____________")
    print"(\   ___   /)    /            \\"
    print"( \ (‘o‘) / )   /  ",  X,  "    \\"
    print"(           )  <   ", Y,        "  "
    print" (  ‘> <’  )    \              /"
    print"    /    \       \____________/"
    print("   /      \  ")
    print"  ‘ –

Test Case:
angel("Silent Night")
                  ____________
(\   ___   /)    /            \
( \ (‘o‘) / )   /   Silent     \
(           )  <    Night
 (  ‘> <’  )    \              /
    /    \       \____________/
   /      \
  ‘ – “ - ‘

What´s the byte count? You may want to use #title instead of **title*

Little late (OK, a lot late) but you can use 1 space for indentation to save a lot of bytes, and you can say p=print to shorten your prints

Perl 6, 234 bytes (218 characters)
{"{' 'x 18}{'_'x 12}
(\\   ___   /)    /{' 'x 12}\\
( \\ (‘o‘) / )   /    {.words[0].fmt('%-9s')} \\
({' 'x 11})  <     {.words[1]}
(  ‘> <’  )    \\{' 'x 14}/
    /    \\       \\{'_'x 12}/
  /      \\
  ‘ – “ - ‘"}

A lambda that inputs the song name as a string, and outputs the snow angle as a string.

Assumes that trailing spaces are not required.
Bytes count is for UTF8 encoding, because that's how Perl 6 expects source code.


text:
Column-wise Sum
Given a nonempty list of nonempty rows of numbers, compute the column wise sum, which is another list that has the length of the longest input row. The first entry of the output list is the sum of all the first entires of the input rows, the second one is the sum of all the second elements (if available) etc. I think following example will explain it way better:
Input:      {[1,2,3,4],[1],[5,2,3],[6,1]}
Computation: [1,2,3,4]
              + . . .
             [1]. . .
              + + + .
             [5,2,3].
              + + . .
             [6,1]. .
              = = = =
    Output: [13,5,6,4]

Test Cases
{[0]}                         -> 0
{[1],[1,1,1,1]}               -> [2,1,1,1]
{[1],[1,2],[1,2,3],[1,2,3,4]} -> [4,6,6,4]
{[1,6,2,-6],[-1,2,3,5]}       -> [0,8,5,-1]

Will the arrays only contain integers?

I did not think about that so far but I think you can assume that. Is there anything speaking against that?

I don't think so. All of your test cases use only integers, and I'm fairly certain it won't invalidate any existing answers (and may even save bytes for some answers).

Well then I think that this assumption is perfectly acceptable. It also doesn't change the challenge itself.

Jelly, 1 byte
S

Try it online! or verify all test cases.
How it works
The sum atom S is a shorthand for +/, which performs reduction by addition.
The quick / reduces along the outmost dimension, so it calls its link for the elements of the input. Here, the elements are the rows.
The addition atom + vectorizes, so adding two row vectors perform element-by-element addition. When the arguments have different lengths, the elements of the longer argument that have no counterpart in the shorter one are left unaltered.
All in all, with an irregular matrix as argument, S computes the column-wise sum, skipping missing entries in the shorter rows.

Huh, I'd have expected that to be row-wise sum, given the way autovectorisation normally works in Jelly. I take it row-wise sum would be S€, then?

For a 2D array, yes. / does not vectorize; it simply applies the corresponding dyad to all elements of its argument.

Python 2, 47 45 bytes
lambda x:map(lambda*y:sum(filter(None,y)),*x)

Thanks to @vaultah for golfing off 2 bytes!
Try it online!

Perl 6, 23 bytes
{roundrobin(|$_)».sum}

Mathematica, 15 bytes
Total@*PadRight

Haskell, 34 bytes
import Data.List
map sum.transpose

Try it online! Usage:
Prelude Data.List> map sum.transpose $ [[1,2,3,4],[1],[5,2,3],[6,1]]
[13,5,6,4]

Good to know the libraries, I'm always afraid of the import as it already eats up so many bytes :D

CJam, 7 5 bytes
2 bytes off thanks to Dennis!
{:.+}

This defines an anonymous block that takes a list of lists, such as [[1 2 3 4] [1] [5 2 3] [6 1]], and replaces it by a list, [13 5 6 4].
Try it online! Or verify all test cases.
Explanation
{   }   e# Define block
 :      e# Fold over the following dyadic function
  .+    e# Vectorized addition

MATL, 3 bytes
oXs

(MATL doesn't know that the plural of "ox" is "oxen"...)
Input is a cell array of numeric row vectors, in the same format as in the challenge text:
{[1,2,3,4],[1],[5,2,3],[6,1]}

Try it online! Or verify all test cases.
     % Implicit input
o    % Convert cell array to a matrix, right-padding with zeros each row
Xs   % Sum of each column
     % Implicit display

Very clever to use cells=)

JavaScript (ES6), 51 48 bytes
Saved 3 bytes, thanks to ETHproductions
a=>a.map(b=>b.map((v,i)=>r[i]=~~r[i]+v),r=[])&&r

Test cases

let f =

a=>a.map(b=>b.map((v,i)=>r[i]=~~r[i]+v),r=[])&&r

console.log(f([[1,2,3,4],[1],[5,2,3],[6,1]])); // -> [13,5,6,4]
console.log(f([[0]]));                         // -> [0]
console.log(f([[1],[1,1,1,1]]));               // -> [2,1,1,1]
console.log(f([[1],[1,2],[1,2,3],[1,2,3,4]])); // -> [4,6,6,4]
console.log(f([[1,6,2,-6],[-1,2,3,5]]));       // -> [0,8,5,-1]

What was wrong with reduce? a=>a.reduce((l,r)=>r.map((e,i)=>e+(l[i]||0))) is only 45 bytes.

@Neil Wouldn't that limit the size of the final result to the size of the last processed array?

Ah, the test cases failed to catch my error, thanks!

Dyalog APL, 3 bytes
+⌿↑

+⌿ sum column-wise
↑ the mixed (list of list, stacked into matrix, padding with zeros) argument
TryAPL online!

How on earth is this 10 bytes?

@ZacharyT That's what happens when using a template at 12:30 AM.

J, 5 bytes
+/@:>

Takes input as a boxed list of lists.
Test cases
   1 ; 1 1 1 1
+-+-------+
|1|1 1 1 1|
+-+-------+
   (+/@:>) 1 ; 1 1 1 1
2 1 1 1
   1 ; 1 2 ; 1 2 3 ; 1 2 3 4
+-+---+-----+-------+
|1|1 2|1 2 3|1 2 3 4|
+-+---+-----+-------+
   (+/@:>) 1 ; 1 2 ; 1 2 3 ; 1 2 3 4
4 6 6 4

Haskell, 61 41 40 bytes
Thanks @Laikoni for -20 bytes, @nimi for -1 byte!
f[]=[]
f l=sum[h|h:_<-l]:f[t:u|_:t:u<-l]

Explanation: It is just a recursive summation of the first elements of the list, also dealing with discarding empty lists in every intermediate step:
    sum[h|h:_<-l]                    -- sums up all the first elemetns of the list
                    [t:u|_:t:u<-l]   -- removes the first element of all the list, and removes empty lists
                   f                 -- applies f to the remaining list
                 :                   -- prepends the sum to the rest

Using list comprehensions saves quite some bytes: You can replace (sum$sum.(take 1)<$>l) with sum[h|h:_<-l] and (f$filter(/=[])$drop 1<$>l) with f[t|_:t<-l,t>[]].

Wow thank you very much! I keep forgetting about the possibility of pattern matching in [h|h:_<-l]!

One byte can be saved in the recursive call: f[t:u|_:t:u<-l].

Wonder, 11 bytes
@->#sum '#0

Transpose and map with sum function. Usage:
(@->#sum '#0)[[1 2 3 4];[1];[5 2 3];[6 1]]

C++14, 130 bytes
As unnamed generic lambda:
[](auto C,auto&r){r.clear();int i=0,b=1;while(b--){r.push_back(0);for(auto c:C)r.back()+=i<c.size()?c[b=1,i]:0;++i;}r.pop_back();}

Requires C to be like vector<vector<int>> and return value r to be like vector<int> (should be okay according to meta).
Ungolfed & usage:
#include<vector>
#include<iostream>

auto f=
[](auto C, auto&r){
 r.clear();         //clearing r just to be sure
 int i=0,b=1;       //i is the position in the row, b is a boolean
 while(b--){        //while something was added
  r.push_back(0);   //add zero
  for(auto c:C)     //for each container
   r.back() += i<c.size() ?   //add to the last element
    c[b=1,i] : 0;             //set b and get the element or zero
  ++i;
 }
 r.pop_back();      //remove last unnecessary zero
}
;

using namespace std;

int main(){
 vector<vector<int> > C = { {1,2,3,4}, {1}, {5,2,3}, {6,1} };
 vector<int> r;
 f(C,r);
 for (int i: r)
  cout << i << ", ";
 cout << endl;
}

Pyth - 4 bytes
sM.T

Try it online here.

R, 53 52 51 bytes
\(x){for(i in x)F=F+i*!seq(!i)-1:max(lengths(x));F}

Attempt This Online!
Thanks to Giuseppe for a byte saved.

Octave, 69 bytes
@(a){g=1:max(s=cellfun(@numel,a))<=s';f=g'+0;f(g')=[a{:}];sum(f')}{4}

Japt, 5 bytes
Uz mx

Test it online!
U is the input array, and z on arrays rotates the array clockwise by 90 degrees. Therefore,
[
 [1,2,3,4],
 [1      ],
 [5,2,3  ],
 [6,1    ]
]

becomes
[
 [6,5,1,1],
 [1,2,  2],
 [  3,  3],
 [      4]
]

(Spacing added only for display purposes.)
mx then maps by summation (x), which gives the desired result: [13,5,6,4].

Uiua, 4 bytes
⬚0/+

Try it!
⬚0/+
  /+  # sum columns
⬚0    # filling needed nonexistent elements with zero

R, 52 bytes
\(x)colSums(t(sapply(x,\(v)v[1:max(lengths(x))])),T)

Attempt This Online!
Only one byte longer than Kirill L.'s answer, so I thought it's worth posting as well.

Ah, the t is to avoid 1-dimensional output from the sapply, very nice; I had something similar but couldn't get it to work.

Pyke, 4 bytes
.,ms

Try it here!

Java 8, 124 bytes
this is a lambda expression for a Function< int[ ][ ], int[ ] >
i->{int L=0,t,r[];for(int[]a:i)L=(t=a.length)>L?t:L;r=new int[L];for(;0>L--;)for(int[]a:i)r[L]+=a.length>L?a[L]:0;return r;}

it takes the largest array length from the input, creates a new array of that size, and then writes the sums of each column to the array.

R, 105 97 bytes
a=c();l=length;for(i in 1:l(w)){length(w[[i]])=max(sapply(w,l));a=rbind(a,w[[i]])};colSums(a,n=T)

This takes in input a list object called w in the form :
w=list(c(1,2,3,4),c(1),c(1,2))

It outputs the column-wise sum : [1] 3 4 3 4
This solution is quite long to me. R has the particularity to recycle when you try to bind vectors of different length. For example :
a=c(1,2,3,4)
b=c(1,2)

cbind(a,b)

     a b
[1,] 1 1
[2,] 2 2
[3,] 3 1
[4,] 4 2

b is re-used once to fit, which is why I begin with a list.
The program adjusts the length of all the elements of the list as the one of the longest, binds the elements and computs the column-wise sum.
The length adjusting produces NA's, that are ignored by the sum.
-8 bytes thanks to @Jarko Dubbeldam !

colSums(a,na.rm=T) saves a few bytes.

and you can even turn na.rm=T into n=T.

Clojure, 70 bytes
#(for[i(range(apply max(map count %)))](apply +(for[v %](get v i 0))))

A basic nested loop.

PHP, 63 bytes
<?foreach($_GETas$a)foreach($a as$i=>$x)$r[$i]+=$x;print_r($r);

call in browser with GET parameters as list of inputs.
Example:
script.php?a[]=1&a[]=2&a[]=3&a[]=4&b[]=1&c[]=5&c[]=2&c[]=3&d[]=6&d[]=1
(Array names are ignored, so you can name them any way you want.)
Try this function for testing:
function s($a){foreach($a as$b)foreach($b as$i=>$x)$r[$i]+=$x;return$r;}

or use http_build_query($array,a) to convert a given array of arrays to GET parameters.

Husk, 4 bytes
mΣT0

Try it online!
Explanation
mΣT0
  T0 Transpose matrix, padding with 0's where needed
mΣ   map each column to its sum

Fż+ works for three bytes

Scala, 64 bytes
Golfed version. Try it online!
l=>{l.map(x=>x.padTo(l.map(_.size).max,0)).transpose.map(_.sum)}

Ungolfed version. Try it online!
object Main {

  def columnSum(lists: List[List[Int]]): List[Int] = {
    // Ensure the lists are of uniform length for transposing, fill shorter ones with 0s
    val maxLength = lists.map(_.length).max
    val uniformLists = lists.map(list => list.padTo(maxLength, 0))

    // Transpose the list of lists (turns columns into rows) and sum each row
    uniformLists.transpose.map(_.sum)
  }

  def main(args: Array[String]): Unit = {
    // Test cases
    println(columnSum(List(List(1,2,3,4), List(1), List(5,2,3), List(6,1)))) // Output: List(13, 5, 6, 4)
    println(columnSum(List(List(0)))) // Output: List(0)
    println(columnSum(List(List(1), List(1,1,1,1)))) // Output: List(2, 1, 1, 1)
    println(columnSum(List(List(1), List(1,2), List(1,2,3), List(1,2,3,4)))) // Output: List(4, 6, 6, 4)
    println(columnSum(List(List(1,6,2,-6), List(-1,2,3,5)))) // Output: List(0, 8, 5, -1)
  }
}


text:
Output subdivisions of international standard paper sizes
ISO Paper Sizes Defined:
The A series paper sizes are defined by the following requirements:
The length divided by the width is the square root of 2.
The A0 size has an area of 1 unit.
Each subsequent size A(n) is defined as A(n-1) cut in half parallel to its shorter sides.

Task:
given an input f[n] output A0 divided into n subdivisions.
Test cases:
f[1] to f[12]:

Here, A0 is given by f[1], but this indexing isn't essential.
Winning criteria:
The shortest code in bytes wins.

Shouldn't f[2] be an A0 with a horizontal line dividing it? i.e., isn't the f[2] in the test case actually f[3]?

@JungHwanMin adjusted now

BBC BASIC 49 ASCII characters
Tokenised filesize 44 bytes
I.n:F.i=0TOn:RECTANGLE0,0,1189>>i/2+.5,841>>i/2N.

Much shorter than before! I always forget about the bitshift operators in BBC BASIC for windows as they weren't available on my old computer back in the day.
BBC BASIC 63 ASCII characters
Tokenised filesize 58 bytes
Dowload interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html
A%=841C%=1189d=4I.n:F.i=0TOn:RECTANGLE0,0,C%,A%:d!^B%/=2d=-d:N.

Uses zero indexing, which I prefer. Thus 0 outputs the paper for A0, 1 outputs A0 divided into a pair of A1s, etc.
It is necessary to alternate between halving the X and Y coordinates, but doing that in an array would have cost too many bytes. Instead I use the fact that BBC basic has a block of static integer variables A%..Z% of 4 bytes each stored in contiguous memory. I store the X and Y values in A% and C% and access using the pointer to %B modified by the value of d, which alternates between 4 and -4.
Ungolfed
  A%=841
  C%=1189
  d=4
  INPUTn
  FORi=0TOn
    RECTANGLE0,0,C%,A%
    d!^B%/=2
    d=-d
  NEXT

Output

JavaScript (ES6) + HTML, 96 94 + 34 = 130 128 bytes

f=(n,w=297,h=210)=>n--&&f(n,h<w?w/2:w,h<w?h:h/2,(C=c.getContext`2d`).rect(0,0,w,h),C.stroke())

f(8)
<canvas id=c width=300 height=300>

JavaScript (ES6)/SVG (HTML5), 170 bytes

a=prompt();document.write('<svg width=297 height=210>');for(w=297,h=210;a--;h>w?h/=2:w/=2)document.write(`<rect fill=none stroke=#000 x=0 y=0 width=${w} height=${h} />`);

Uses 1-based indexing.

Mathematica, 87 85 bytes
Thanks @martin for 1 byte.
Graphics@{EdgeForm@Thin,White,Rectangle[#,0{,}]&/@NestList[Sort[#/a]&,{1,a=√2},#]}&

Very nice! EdgeForm@Thin: -1 byte