text:
The Most Durable Pokemon Types
Background
This question is similar to this one. I have provided all of the information needed below. If you are familiar with the other challenge then note that we are ranking all defenses instead of seeing the effectiveness of a single attack. This is important because it means that the tables are inverses of each other and the goal of this challenge is to be without user input.
In Pokemon there are 18 types:
Normal    Fighting  Flying  Poison  Ground  Rock
Bug       Ghost     Steel   Fire    Water   Grass
Electric  Psychic   Ice     Dragon  Dark    Fairy

Pokemon have either one or two unique types that define them (a "type combination"). For example, a Bulbasaur has the type combination Grass/Poison (it has two types, Grass and Poison) and a Charmander has the type combination Fire (having just one type). The order of types does not matter (i.e. Grass/Poison is the same as Poison/Grass).
These types all have strengths and weaknesses:

A type can be weak to another type. Fire is weak against Water. This results in Fire having a 2× multiplier against Water.
A type can be resistant to another type. Water is resistant to Water. This results in Water having a 0.5× multiplier against Water.
A type can be immune to another type. Flying is immune to Ground. This results in Flying having a 0× multiplier against Ground.

Anything else receives a standard 1× multiplier. Normal against Normal would result in a 1× multiplier is an example of this. These strengths and weaknesses can be compounded or negated as well. For example, Fire is weak to Water but a Fire/Water dual type would have a 1× multiplier against Water since the weakness from Fire would negate the resistance from Water. For a full table and a further explanation, see below.
Objective
The goal here is to output a list of all types combinations, sorted in the order of their defensive ability, and listing their numbers of (resistances+immunities), weaknesses, and the ratio between those. Specifically, the sort order is as follows: type combinations with the best ratio of (resistances+immunities) to weaknesses are listed first, and if there is a tie, type combinations with the most resistances and immunities will win the tiebreak. You can produce this list via any means (an obvious method is to do a type effectiveness calculation against each type combination, but you are allowed to store precalculated or partially precalculated output in your program if doing so would make it shorter.)
Type effectiveness table
For a human readable table, see the Pokemon database. Note: the columns of this list are what we are considering. But just in case, here is the table I'm thinking of in a compressed computer-friendly matrix of effectiveness. I've multiplied every value by 2 so we don't have to deal with pesky decimals:
           Attacking type
            (same order)
   Nor   222222422222202222
   Fir   214211224221422211
D  Wat   211441222222222212
e  Ele   222122224122222212
f  Gra   241114241424222222
e  Ice   242221422222422242
n  Fig   222222222441122124
d  Poi   222212114241222221
i  Gro   224044212222122222
n  Fly   222414120221422222
g  Psy   222222122214242422
   Bug   242212121422422222
T  Roc   114242414122222242
y  Gho   022222012221242422
p  Dra   211114222222224224
e  Dar   222222422204212124
   Ste   142211404111121211
   Fai   222222142221220142

Example
If this problem had requested only output for single-type type combinations, then a valid output would look like this:
Steel -> 11/3 = 3.66
Electric -> 3/1 = 3
Poison -> 5/2 = 2.5
Fire -> 6/3 = 2
Water -> 4/2 = 2
Ghost -> 4/2 = 2
Fairy -> 4/2 = 2
Fly -> 4/3 = 1.333
Dragon -> 4/3 = 1.333
Fighting -> 3/3 = 1
Normal -> 1/1 = 1
Ground -> 3/3 = 1
Psychic -> 2/2 = 1
Bug -> 3/3 = 1
Dark -> 3/3 = 1
Grass -> 4/5 = 0.8
Rock -> 4/5 = 0.8
Ice -> 1/4 = 0.25

However, your program will also need to list all of the dual-type combinations in the output, so its output will be considerably longer.
Best of luck! Shortest code in bytes wins.

Related.

And welcome to PPCG! :)

I think this has the obvious problem that the answer is smaller than the data needed to solve the question, and thus a winning solution will just hardcode the output. In order to solve the issue, you probably need to change the challenge to take the type effectiveness matrix as input at runtime.

@ais523 I believe compressing the matrix is supposed to be the core of the challenge, and in principle I see nothing wrong with that (although in this case, unfortunately, this exact table has been the subject of a challenge before).

@MartinEnder in that case, how do you judge a solution objectively? The question is [tag:kolmogorov-complexity] in that, as written, it always prints the same answer, and that answer is considerably shorter than the data needed to compute it. So a compression technique that "precomputes" more of the type effectivenesses will lead to a shorter solution. I think the question might need to be placed on hold until it's been clarified what's allowed to be hardcoded in the program and what has to be calculated at runtime and how.

Alternatively, given that the answer is only slightly shorter than the question is, we could just run this as a [tag:kolmogorov-complexity]; it'd probably be quite interesting if run like that. In that case, we should probably have the exact intended output in the question somewhere.

I was actually inspired by that related question. I didn't quite understand the solution so I couldn't adapt it for my question. The core difference is that question takes an attack type and a defending type and computes the damage multiplier. Thus, that question can see a type's strengths whereas I wanted to rank each type by its weaknesses and defenses

OK, I think what this question needs is a specification of exactly how much precalculation the program is allowed to do. I can see two possible questions you can ask here, and it isn't clear which you're asking: a) you can ask for a program that outputs the type ranking, with no restrictions on how, but many of the solutions will likely hardcode the output rather than calculating it; b) you can ask for a program that computes the type ranking, in which case you need to take the type effectiveness table as input to prevent people precalculating it. Which would you find more interesting?

I guess I wasn't clear. I want an output that is similar to the example I gave but with all double types included. 18C2 is 153 different combinations and I wanted those all to be ranked. Would it really be more efficient to hardcode a 153x153 matrix than create code that generates it?

Well, you're only outputting the 153 summarized answers, and the original type matrix has 324 entries. On the other hand, the answers contain strings (generated according to a pattern) and rational numbers, and the original type matrix has only 5 possibilities per cell, so there's clearly scope for compression here. I think the challenge is probably most interesting as a "compression challenge" in which actually doing the calculation suggested is an obvious means of compression to try, and you seem to agree with that, so I'll suggest an edit to make the challenge work under those rules.

OK, I've suggested an edit to make the challenge rules mostly clear; I don't know whether you can accept the edit yourself or whether we'll have to wait for a high-reputation user to accept it. The only remaining issue is output format; do you want to allow bare-bones formats like ["Steel", 11, 3, 3.666666667] (which will likely lead to shorter programs), or do you want to require a specific format? In the latter case, you'll need a rule describing how the fractional numbers are rounded.

Wow thank you so much for all the help. I see what you mean now by the 153 summarized answers being shorter and I didn't think of that. Hope I didn't cause anyone in here too much headache trying to make my answer into a better question. I think I'm fine with the bare-bones format so I'll make sure to include that in the question as well.

@MartinEnder It's more than related... If you go over the introduction it's 100% copied and then altered to not look like it's copied. It follows the exact same structure, the starting types are in the same order, formatted the same. It's just blatant plagiarizing without mentioning it and trying to hide it.

@orlp I honestly didn't try to plagiarize. I thought of the question on my own and made a Google search. When I saw that question and that it was similar, I figured I'd make a post too. I wrote the post on my own and my question differs in that I do not want input and I want the types to be ranked. I'm new to this so I didn't know I should have linked to his question or made it related. I've added that the question was related in the description. If there's more that I need to do, please instruct me and I'd be happy to do so.

Python 2, 784 bytes
i=['Normal','222222422222202222'],['Fire','214211224221422211'],['Water','211441222222222212'],['Electric','222122224122222212'],['Grass','241114241424222222'],['Ice','242221422222422242'],['Fighting','222222222441122124'],['Poison','222212114241222221'],['Ground','224044212222122222'],['Flying','222414120221422222'],['Psychic','222222122214242422'],['Bug','242212121422422222'],['Rock','114242414122222242'],['Ghost','022222012221242422'],['Dragon','211114222222224224'],['Dark','222222422204212124'],['Steel','142211404111121211'],['Fairy','222222142221220142']
L=[]
for x,X in i:
 for y,Y in i[i.index([x,X]):]:
  S=W=0.
  for a,b in zip(X,Y):A=int(a)*int(b);W+=A>4;S+=A<4
  L+=[([x+'/'+y,x][x==y]+' -> %d/%d'%(S,W),S/W)]
for l in sorted(L, key=lambda l:-l[1]):print'%s = %.2f'%l

Outputs:
Bug/Steel -> 9/1 = 9.00
Steel/Fairy -> 11/2 = 5.50
Normal/Ghost -> 5/1 = 5.00
Water/Ground -> 5/1 = 5.00
Grass/Steel -> 10/2 = 5.00
Poison/Dark -> 5/1 = 5.00
Poison/Steel -> 10/2 = 5.00
Flying/Steel -> 10/2 = 5.00
Dragon/Steel -> 10/2 = 5.00
Normal/Steel -> 12/3 = 4.00
Electric/Poison -> 8/2 = 4.00
Electric/Steel -> 12/3 = 4.00
Ghost/Dark -> 4/1 = 4.00
Water/Steel -> 11/3 = 3.67
Dark/Steel -> 11/3 = 3.67
Steel -> 11/3 = 3.67
Fire/Steel -> 10/3 = 3.33
Fire/Ground -> 6/2 = 3.00
Water/Flying -> 6/2 = 3.00
Electric -> 3/1 = 3.00
Electric/Flying -> 6/2 = 3.00
Electric/Fairy -> 6/2 = 3.00
Ice/Steel -> 9/3 = 3.00
Fighting/Steel -> 9/3 = 3.00
Rock/Steel -> 9/3 = 3.00
Ghost/Steel -> 12/4 = 3.00
Fire/Electric -> 8/3 = 2.67
Water/Poison -> 8/3 = 2.67
Normal/Poison -> 5/2 = 2.50
Water/Electric -> 5/2 = 2.50
Poison -> 5/2 = 2.50
Ground/Flying -> 5/2 = 2.50
Ground/Steel -> 10/4 = 2.50
Psychic/Steel -> 10/4 = 2.50
Fire/Flying -> 7/3 = 2.33
Water/Fairy -> 7/3 = 2.33
Electric/Ghost -> 7/3 = 2.33
Normal/Electric -> 4/2 = 2.00
Normal/Fairy -> 4/2 = 2.00
Fire -> 6/3 = 2.00
Fire/Poison -> 8/4 = 2.00
Fire/Bug -> 6/3 = 2.00
Fire/Fairy -> 8/4 = 2.00
Water -> 4/2 = 2.00
Water/Ghost -> 8/4 = 2.00
Electric/Bug -> 4/2 = 2.00
Fighting/Poison -> 6/3 = 2.00
Poison/Fairy -> 6/3 = 2.00
Psychic/Ghost -> 4/2 = 2.00
Ghost -> 4/2 = 2.00
Ghost/Fairy -> 4/2 = 2.00
Dragon/Fairy -> 8/4 = 2.00
Fairy -> 4/2 = 2.00
Fire/Ghost -> 9/5 = 1.80
Normal/Fire -> 7/4 = 1.75
Fire/Rock -> 7/4 = 1.75
Fire/Dark -> 7/4 = 1.75
Poison/Dragon -> 7/4 = 1.75
Normal/Water -> 5/3 = 1.67
Fire/Water -> 5/3 = 1.67
Fire/Dragon -> 5/3 = 1.67
Water/Bug -> 5/3 = 1.67
Electric/Fighting -> 5/3 = 1.67
Ghost/Dragon -> 8/5 = 1.60
Fire/Fighting -> 6/4 = 1.50
Water/Dragon -> 3/2 = 1.50
Electric/Dragon -> 6/4 = 1.50
Electric/Dark -> 6/4 = 1.50
Poison/Ground -> 6/4 = 1.50
Poison/Flying -> 6/4 = 1.50
Poison/Rock -> 6/4 = 1.50
Poison/Ghost -> 6/4 = 1.50
Ground/Fairy -> 6/4 = 1.50
Flying/Dragon -> 6/4 = 1.50
Rock/Fairy -> 6/4 = 1.50
Fire/Psychic -> 7/5 = 1.40
Water/Fighting -> 7/5 = 1.40
Water/Dark -> 7/5 = 1.40
Grass/Fairy -> 7/5 = 1.40
Fighting/Dragon -> 7/5 = 1.40
Dragon/Dark -> 7/5 = 1.40
Normal/Flying -> 4/3 = 1.33
Fire/Grass -> 4/3 = 1.33
Fighting/Dark -> 4/3 = 1.33
Poison/Psychic -> 4/3 = 1.33
Ground/Dragon -> 4/3 = 1.33
Flying -> 4/3 = 1.33
Dragon -> 4/3 = 1.33
Dark/Fairy -> 4/3 = 1.33
Normal/Dragon -> 5/4 = 1.25
Water/Rock -> 5/4 = 1.25
Electric/Ground -> 5/4 = 1.25
Electric/Psychic -> 5/4 = 1.25
Electric/Rock -> 5/4 = 1.25
Grass/Poison -> 5/4 = 1.25
Fighting/Bug -> 5/4 = 1.25
Fighting/Ghost -> 5/4 = 1.25
Poison/Bug -> 5/4 = 1.25
Flying/Dark -> 5/4 = 1.25
Water/Psychic -> 6/5 = 1.20
Grass/Ghost -> 6/5 = 1.20
Ground/Ghost -> 6/5 = 1.20
Flying/Rock -> 6/5 = 1.20
Flying/Ghost -> 6/5 = 1.20
Flying/Fairy -> 6/5 = 1.20
Bug/Ghost -> 6/5 = 1.20
Bug/Fairy -> 6/5 = 1.20
Normal -> 1/1 = 1.00
Normal/Fighting -> 4/4 = 1.00
Normal/Ground -> 4/4 = 1.00
Normal/Psychic -> 2/2 = 1.00
Normal/Bug -> 3/3 = 1.00
Normal/Rock -> 5/5 = 1.00
Normal/Dark -> 3/3 = 1.00
Fire/Ice -> 4/4 = 1.00
Water/Grass -> 3/3 = 1.00
Electric/Grass -> 4/4 = 1.00
Grass/Fighting -> 6/6 = 1.00
Grass/Dark -> 7/7 = 1.00
Ice/Poison -> 5/5 = 1.00
Ice/Ghost -> 5/5 = 1.00
Ice/Fairy -> 4/4 = 1.00
Fighting -> 3/3 = 1.00
Fighting/Flying -> 5/5 = 1.00
Fighting/Fairy -> 5/5 = 1.00
Ground -> 3/3 = 1.00
Ground/Bug -> 4/4 = 1.00
Ground/Rock -> 6/6 = 1.00
Ground/Dark -> 6/6 = 1.00
Psychic/Dragon -> 6/6 = 1.00
Psychic/Fairy -> 3/3 = 1.00
Bug -> 3/3 = 1.00
Bug/Dragon -> 5/5 = 1.00
Bug/Dark -> 5/5 = 1.00
Rock/Ghost -> 6/6 = 1.00
Rock/Dark -> 7/7 = 1.00
Dark -> 3/3 = 1.00
Grass/Psychic -> 6/7 = 0.86
Fighting/Rock -> 6/7 = 0.86
Normal/Grass -> 5/6 = 0.83
Grass/Bug -> 5/6 = 0.83
Fighting/Ground -> 5/6 = 0.83
Ground/Psychic -> 5/6 = 0.83
Rock/Dragon -> 5/6 = 0.83
Grass -> 4/5 = 0.80
Grass/Flying -> 4/5 = 0.80
Flying/Psychic -> 4/5 = 0.80
Flying/Bug -> 4/5 = 0.80
Rock -> 4/5 = 0.80
Electric/Ice -> 3/4 = 0.75
Grass/Ground -> 3/4 = 0.75
Ice/Flying -> 3/4 = 0.75
Ice/Bug -> 3/4 = 0.75
Psychic/Rock -> 5/7 = 0.71
Grass/Dragon -> 4/6 = 0.67
Ice/Rock -> 4/6 = 0.67
Ice/Dark -> 4/6 = 0.67
Fighting/Psychic -> 2/3 = 0.67
Psychic -> 2/3 = 0.67
Psychic/Bug -> 4/6 = 0.67
Bug/Rock -> 2/3 = 0.67
Ice/Dragon -> 3/5 = 0.60
Grass/Ice -> 4/7 = 0.57
Normal/Ice -> 2/4 = 0.50
Water/Ice -> 2/4 = 0.50
Grass/Rock -> 2/4 = 0.50
Ice/Fighting -> 3/6 = 0.50
Psychic/Dark -> 1/2 = 0.50
Ice/Ground -> 2/5 = 0.40
Ice/Psychic -> 2/6 = 0.33
Ice -> 1/4 = 0.25

Awesome. Exactly what I wanted. Thanks mate!


text:
Prepend line number comments
Definitions:

A line is a possibly empty sequence of characters terminated by a “newline character.”
A “newline character” is a character that cannot be a component of the aforementioned character sequence.
A line number comment is a character sequence that does not alter the meaning of source code in the programming language of your submission.
It contains a decimal representation of the (integral) unique line number associated with the line of input.
(A conventional notation is sufficient, e. g. 4.2E1 for 42.)
A content line is a line that conveys meaning in the programming language of your submission.

Task:

Write a program (or function) that numbers all lines, but at least all content lines.
The program shall print a line number comment followed by the respective processed (otherwise unaltered) input line.
The function shall return a value accordingly.

Conditions:

Numbered lines must be numbered in ascending order in the order of input (i. e. not in the order a processor for the respective programming language might possibly process the input).
Line numbers must be consecutive.
That means you may not omit numbers.
The first line is identified either by the line number zero (0) or one (1).
The behavior must be consistent for all possible input.
Line numbers must reproduce:
Feeding the output back as input again produces the same line numbers.

Accommodations:

You may assume that input is valid source code in your submission’s programming language.
You may assume that no token is spread across multiple lines (e. g. multiline string literals or backslash-continuation), thus insertion of a line number comment is guaranteed not to alter the source code’s meaning.
You may assume input consists of lines.
Numbering of non-lines (that is empty input or input not terminated by a newline-character) is implementation-dependent.

Test cases:
C (note that tabulator characters are preserved):
#include <stdio.h>
int main()
{
    char c;
    c = getchar();
    do
    {
        putchar(c);
    }
    while (c);
}

/* 0*/#include <stdio.h>
/* 1*/int main()
/* 2*/{
/* 3*/  char c;
/* 4*/  c = getchar();
/* 5*/  do
/* 6*/  {
/* 7*/      putchar(c);
/* 8*/  }
/* 9*/  while (c);
/*10*/}

Pascal (note that it is not specified that input is indeed source code):
Esolanging fruit is hanging low.

{           1 }Esolanging fruit is hanging low.

If you input that output back in again, it must reproduce the same line number comments:
{           1 }{           1 }Esolanging fruit is hanging low.

SQL (note that only content lines were numbered):
-- populate foo with some data
insert into foo values (1, 'bar');
insert into foo values (2, 'foobar');

select * from foo;

-- populate foo with some data
/*0*/insert into foo values (1, 'bar');
/*1*/insert into foo values (2, 'foobar');

/*2*/select * from foo;

Good luck doing this is Retina!

Just to be clear, we must generate the type of comment our language uses? What if our language doesn't have comments?

Making the comments language-dependent makes things complicated. You already had to create a special rule for Python. What about all the other languages that don't have multi-line comments? What about languages that do not have comments at all. What about multi-line strings where comments cannot be placed without side effects?

@Dennis You don't strictly need "comments". For example in befunge I consider "text"!!!! to be a comment because it makes no changes to the program's state. The thing about multi-line strings is true; I'll mention that.

@DrMcMoylex See my reply to Dennis about comments.

Fun fact: the rule "removing the comment should make no change to the program" immediately disqualifies any Python answer, because the code—including comments—can be introspected at runtime. I have seen this in play in a production system: a piece of code would raise an AssertionError unless the stack trace contained the phrase foo.py, which was expected to come from a file name but could also appear as a line comment in the context.

@wchargin Hmmm... Let's just say that the program does not directly access its source code or runtime state like that. Also, does that mean that comments are not removed during parsing? Seriously, Python?

@Challenger5 Correct.

"The comment can only contain newlines at the end of it" is inconsistent with the C "test case".

@PeterTaylor Can, not necessarily will.

What about langs without comments?

"Can only" generally means "cannot not", hence "must". But if it should be "may only" that's still inconsistent with the C test case, which includes padding whitespace.

@PeterTaylor That's true. I edited it.

@wchargin I just don't see why that would ever be useful. Is it ever necessary to detect if a comment exists or contains some text?

@Challenger5 In Python, variables can be given a type hint with a comment. You could read the comment to work out the type of he variable and enforce type hints

Are we allowed to comment blank lines?

The edit doesn't fix the inconsistency.

@NoOneIsHere A comment is defined here as a block of code that has no effect. For example "comment"!!!!!!! is considered a comment if Befunge.

@Challenger5 So 123 is a comment? What about BF? <> (from my memory) is a comment?

@NoOneIsHere If your language does not do anything with 123, it is a comment. <> is also considered a comment in BF.

Test case needed for rule You do not have to put line numbers for lines that contain just whitespace and comments.

This question has been closed again on grounds of lacking details or clarity. Unfortunately my recent edit apparently did not resolve the issues (enough). I find it amazing that writing a specification for a “lightweight nl” with the variation of wrapping numbers into comments is really difficult.

Pyke, 7 bytes
o\Kz++r

Try it here!
o       -  o++
 \K     -  "K"
   z    -  input()
    ++  - sum(^)
      r - while no errors: GOTO start

I'm declaring integer comments to be the integer followed by the character K and then the line. An extra byte is used to stop the newline opcode from kicking in and printing an extra thing.

Perl, 8+1 = 9 bytes
say"#$."

Run with -p (1 byte penalty). (Note to people unfamiliar with PPCG rules; you also need to specify a modern version of Perl syntax using -M5.010, but we decided that options to select language versions are free and don't incur a byte penalty, so I didn't mention it in the original version of this post.)
-p places the program into an implicit loop; it basically causes the program to become a filter that processes each line separately (i.e. the entire program is run on the first line, then the second, then the third, and so on). Perl also keeps track of a line number, called $., that records how many lines of input have been read. So all the program's doing is letting -p read a line of input; output a #, the current line number ($.), and a newline (say adds a newline by default, which is helpful in this case, and is also shorter than the more commonly seen print); and then letting -p output the original line of code that it read (typically a program using -p would do some sort of processing on the input, but because we didn't, it's just output unchanged). Comments in Perl run from # to a newline (the # in the program itself doesn't start a comment because it's inside a string literal), so what we're basically doing is taking the opportunity to write comment lines into the file as we process it, without disturbing the "natural" read and write cycle of -p.

Can you explain how this works?

Sure. I've explained the operation of relevant Perl language features in a tutorial style, given that it's a very basic Perl program that doesn't really make much use of the language's power. I need to remember that not everyone knows how a -p loop or an automatically updating line number work, though.

Note that say"$.;" would work as well, because the question specified that "You may assume that every statement in the code will take up at most the entirety of 1 line".

That's not really a comment, though; although it does nothing useful, it ends up in the AST (and because Perl's optimizer is kind-of sucky, I think that actually will end up slowing the program down, something you wouldn't really want a comment to do).

Not working for rule You do not have to put line numbers for lines that contain just whitespace and comments.

"You do not have to" ≠ "You can't". I don't think any of the other answers omit line numbers on such lines either, because it would require considerably more code to do so.

Javascript, 43 39 bytes
a=>a.replace(/^/gm,_=>`/*${++b}*/`,b=0)

Thanks to ETH and Conor for saving 4 bytes.

41 bytes: a=>(b=0,a.replace(/^/gm,_=>/*${++b}*/)) (use a formatting string)

39 bytes: a=>a.replace(/^/gm,_=>`/*${++b}*/`,b=0)

V, 10 bytes
O:1òYjjP

Try it online!

Lua, 80 75 Bytes
Saved some bytes by abusing the langauge.
x=1print("--[[1]]"..(...):gsub("\n",load('x=x+1return"\\n--[["..x.."]]"')))

Simple enough starter answer.
Ungolfed, +
x=1                                                     -- Assign x to 1...
print(                                                  -- Print...
      "--[[1]]"                                         -- The first line number comment...
      ..                                                -- With...
      (...):gsub(                                       -- The input, replacing all...
                 "\n",                                  -- Newlines...
                    load                                -- with a string compiled function...
                    (' \
                    x=x+1                               --Increment x by one... \
                    return"\\n--[["..x.."]]"            -- And return the new linecomment. \
                    ')
                 )
      )

I don't know Lua, but are you sure that it will always generate comments that are the same length? For example if a program is 10 lines long than the last comment will be --[[10]] which is 1 character longer than --[[9]] unless you correctly pad it with spaces.

Oh, I didn't notice that rule. That seems... A bit redundant...

Yes. Maybe I'll remove it...
[EDIT]: removed.

Batch, 91 bytes
@set n=
@for /f "delims= tokens=*" %%a in (%1) do @set/an+=1&call echo @rem %%n%%&echo %%a

Batch doesn't have a way of reading STDIN until EOF, so instead the file name has to be passed as a command-line parameter.

Gema, 16 15 characters
*\n=\!@line\n$0

In Gema there are only line comments, starting with !.
Sample run:
bash-4.3$ cat l33t.gema
e=3
g=9
i=1
o=0
t=7

bash-4.3$ gema -f l33t.gema <<< 'Hello World!'
H3ll0 W0rld!

bash-4.3$ gema '*\n=\!@line\n$0' < l33t.gema > l33t-nr.gema

bash-4.3$ cat l33t-nr.gema
!1
e=3
!2
g=9
!3
i=1
!4
o=0
!5
t=7

bash-4.3$ gema -f l33t-nr.gema <<< 'Hello World!'
H3ll0 W0rld!

The following are to answer Adám's question, whether is possible to add the line number in kind of ignored code.
Gema code is essentially a collection of from=to transformation rules, or template=action in Gema terms. I see no way to define a template that will never ever match anything, this alone not seems to be the way.
Gema, 18 characters
*\n=c:\=@line\;:$0

Transforms e=3 into c:=1;:e=3.
Luckily in Gema there are domains, kind of namespaces. The above code defines the dummy rules in namespace c, that we never use. Unfortunately a mentioned domain remains in effect until the end of line, so we have to explicitly to switch back to default domain.
Gema, 18 characters
*\n=@line\=\$0\;$0

Transforms e=3 into 1=$0;e=3.
A less complicated alternative is to use effectless code instead of ignored one. I mean to put back exactly what was matched.

But couldn't you insert a string and have some code around it which makes it ignored?

You mean kind of e=3 transformed in if (false) { 1 }; e=3 instead of the current !1␤e=3? Yeah, there would be a 19 character long workaround.

Kotlin extension function, 69 60 bytes
fun String.a()=lines().mapIndexed{i,s->"/*$i*/$s"}.joinToString("\n")
fun String.a(){lines().mapIndexed{i,s->println("/*$i*/$s")}}
Example usage:
fun main(args: Array<String>) {
  //language=kotlin
  val code = """fun main(args: Array<String>) {
  println("Hello world!")
}"""
  code.a()
}

Output:
/*0*/fun main(args: Array<String>) {
/*1*/  println("Hello world!")
/*2*/}

awk (19 13 bytes)
19 bytes : This insert "#"+line number above each line of code
{print"#"NR"\n"$0}

13 bytes : Credit & thanks to @manatwork for two 13 bytes solution
As 1 action defaults to print $0:
{print"#"NR}1

Or by replacing $0 content
$0="#"NR RS$0

{print"#"NR}1 or $0="#"NR RS$0?

@manatwork i'm quite ashamed and grateful to discover those subtilities

BASH (+ GNU sed) 27 bytes
sed 'i#
='|sed 'N;s/\n//;N'

The first part (i# \n =) almost works in GNU sed (for 4 bytes), but it puts a newline after the #.

19 bytes: sed =|sed s/^/#/\;N, with POSIX sed and shell

APL (Dyalog Unicode), 53 bytes
N←(⍴P)[0]⋄P←((2×N)⍴0 1)⍀P⋄P[2×⍳N;]←⊂[1](N⍴'⍝'),[.5]⍳N

Try it on TryAPL.org!
The environmental variable ⎕IO←0. The program to comment is contained in an (n 1) nested array of string statements. The result is returned in the same (expanded) array.

jq, 31 characters
(27 characters code + 4 characters command line options.)
"#\(input_line_number)\n"+.

In jq there are only line comments, starting with #.
Sample run:
bash-4.3$ cat l33t.jq
gsub("e";"3")|
gsub("g";"9")|
gsub("i";"1")|
gsub("o";"0")|
gsub("t";"7")

bash-4.3$ jq -Rr -f l33t.jq <<< 'Hello World!'
H3ll0 W0rld!

bash-4.3$ jq -Rr '"#\(input_line_number)\n"+.' l33t.jq > l33t-nr.jq

bash-4.3$ cat l33t-nr.jq
#1
gsub("e";"3")|
#2
gsub("g";"9")|
#3
gsub("i";"1")|
#4
gsub("o";"0")|
#5
gsub("t";"7")

bash-4.3$ jq -Rr -f l33t-nr.jq <<< 'Hello World!'
H3ll0 W0rld!

Dear Perl and Ruby coders, please observe jq's input_line_number. Being Thanksgiving, any special feeling to express for $.?

C# 6, 66 63 bytes
Thanks to CSharpie
(666, devils code ^^) not any more ...
This works for all languages using "C style comments" (C, C++, C#, Java, ....)
It simply splits the string into lines, prepends every line with its index and joins the edited lines again with new line characters.
s=>string.Join("\n",s.Split('\n').Select((l,i)=>$"/*{i}*/"+l));

old version:
s=>string.Join("\n",s.Split('\n').Select((l,i)=>$"/*{i,3}*/{l}"));

Technically 64 since op didnt mention any padding with zeros.
Also you can save 1 more byte by wirting: $"/{i}/"+l. (Moving the L-parameter out of the interpolation.)

You're right ^^ but that destroys my "evil score" hehe

GolfScript, 23 Bytes
n/0:i;{"#"i):i+n+\+}%n*

There are only line comments starting with "#".
Ungolfed & explained:
           # the input is pushed on the stack automatically
n          # n is a predefined variable for "\n"
/          # splits the input string with the previously pushed "\n" as delimiter
0:i;       # i = 0
{          # A code block: It is used for map here (going through the input)
    "#"    # push a "#" onto the stack
    i):i  # save i + 1 in i, the value is again not popped from the stack
    +      # implicitly converts the number i to a string and concatenates "#" with it
    n      # newline
    +      # add a newline (# introduces a *line* comment)
    \      # switch the top to elements (-> yields the comment as the bottom, and the line as the top element on the stack)
    +      # concatenate them
}          # end of the code block
%          # map
n          # newline
*          # join the list with newlines between them
           # outputs are done implicitly

I am pretty sure that this can be further simplified, especially the i can probably be left out.
You can test it here: https://golfscript.apphb.com/
Because this site doesn't support adding inputs, you'll have to put a string surrounded with double quotes in front of the code. '\n' will be a newline. Be aware of the fact, that there are other escape sequences as well. User '\\' if you are not sure.

CJam, 21 Bytes
I am not well-versed in CJam at all, but I knew for a fact it has comments :)
qN%ee{"e#"o(oNo(oNo}/

Explanation coming soon.

oNo can be replaced with n on TIO.

Mathematica, 58 bytes
i = 1; StringReplace[#, StartOfLine :> "(*" <> ToString@i++ <> "*)"] &

JavaScript (Node.js), 35 bytes
Revisited this question and found a shorter solution. It saves a few bytes to append // comments instead prepending /**/ ones.
a=>a.replace(/$/gm,_=>"//"+v++,v=1)

Try it online!
JavaScript, 47 bytes
Old answer:
a=>a.split`
`.map((l,i)=>"/*"+i+"*/"+l).join`
`

If in Python the comment take whole line why not js? That saves byte

Good idea @l4m2 I just added it

Also removed the Japt solution since I realized it added JS comments instead of Japt ones (which AFAIK don't exist)

C (gcc), 54 bytes
a;main(i){for(;gets(&a);)printf("/*%d*/%s\n",i++,&a);}

Try it online!
Why not

Python 2, 82 bytes

Works for space-only indentation
for i,l in enumerate(input().split('\n')):print l.split(l.lstrip())[0]+'#%d\n'%i+l

Indentation-less version for 56 bytes
for x in enumerate(input().split('\n')):print'#%d\n%s'%x

Nim, 52 bytes
var n=0
for l in stdin.lines:n+=1;echo "#[",n,"]#",l

Attempt This Online!
Nim is indentation-sensitive, but it doesn't seem to have a problem with comments before indentation.

Haskell, 84 bytes
Assumes each indentation is done by a horizontal tab(\t).
unlines.zipWith(\n l->let(x,y)=span('\t'==)l in x++"{-"++show n++"-}"++y)[0..].lines

Pascal, 198 bytes

This is a full Pascal program as per ISO standard 10206 “Extended Pascal.”
Pascal does not permit multiline literals.
String and character literals spanning multiple lines are explicitly banned.
Therefore there is no problem with that.
The program only works correctly for up to maxInt + 1 input lines (zero-based indexing).
MaxInt is an implementation-defined value.
There is no safeguard installed when exceeding this limit.
A line is a possibly empty sequence of characters terminated by a special “end of line character.”
This program might possibly number non-lines, too.
At any rate empty input is not numbered.

program p(input,output);var n:integer;c:char;begin n:=0;while not EOF do begin write('{',n,'}');repeat read(c);write(c)until EOF or_else EOLn;if not EOF then begin writeLn;read(c)end;n:=n+1 end end.

Expanded and annotated:
program prependLineNumberComment(input, output);
    var
        { Contains the currently processed `input` line number. }
        lineNumber: integer value 0;
        { Identifiers of buffer variables (`input↑`, `output↑`) are too long. }
        c: char;
    begin
        while not EOF do
        begin
            write('{ ', lineNumber, ' }');
            lineNumber ≔ succ(lineNumber);

            { Copy `input` to `output`. }
            repeat
            begin
                { This is equivalent to: `c ≔ input↑; get(input);`: }
                read(c);
                { This is equivalent to: `output↑ ≔ c; put(output);`: }
                write(c);
            end
            { Invoking `EOLn(input)` if `EOF(input)` is `true` is fatal. }
            until EOF or_else EOLn;

            { `get(input)` requires that `EOF(input)` is `false`. }
            if not EOF then
            begin
                { The only valid method for producing a newline character is: }
                writeLn;
                { Advance reading cursor for the embracing `while`‑loop. }
                read(c);                    { Shorter than `get(input);` }
            end;
        end;
    end.

source: Stack Exchange

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

authors: набиячлэвэлиь

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

sort: votes


text:
Match the permutations!
Your challenge is to create a regex that matches every string permutation of itself, and nothing else. The match must also be case-sensitive.
So, for example, if your regex is:
ABC

It should match (and only match) these strings:
ABC
ACB
BAC
BCA
CAB
CBA

It shouldn't match things like:
AABC (contains an extra A)
ABCD (contains an extra D)
AC   (no B)
AAA  (no B and C, extra 2 A's)
abc  (case-sensitive)

Rules:

You are allowed to use any flavour of regex you like.
Standard loopholes apply.
You must have at least two different characters in your code. That means solutions like 1 are invalid.
The regex should contain only printable ASCII, and nothing else.

Related: Regex that only matches itself

Also related: Character counts in source code

I thought (ABC|ACB|BAC|BCA|CAB|CBA) but you wanted a generalized answer.

JavaScript, 64 57 bytes
4 bytes removed thanks to Martin Ender.
^(?!.*([^])(.*\1){3}]?)[$$[-^?!!.'''-*11{33}5577\\-]{57}$

Try it here.
Explanations (outdated)
^                                  # Beginning of the string.
(?!.*                              # Match only the strings that don't contain...
  (.)(.*\1){4}                     #     5 occurrences of the same character.
  [^1]?[^1]?                       #     Something that doesn't matter.
)
[]zzz^(?!!!.**[)\\1{{44}}666]{64}  # 64 occurrences of these 16 characters.
                                   # Some are duplicated to make sure the regex
                                   # contains 4 occurrences of each character.
\z                                 # End of the string.

I think this works for 60: ^(?!.*(\S)(.*\1){3}[^1]?)[]zzSS[-^?!!.'''-*1{33}0066-]{60}\z regex101

This almost works in .NET: ^(?'4'(?!(.*\4){3})[]$$[\\^^?!!..'-*{}33-5-]){54}$[5]*

What doesn't work? Trailing linefeeds?

@MartinEnder Yes.

JavaScript, 50 bytes
^(?!([^])+.*\1.*\1)[?!ZZ-__==''-22+,,//{50}$]{50}$

Try it on regex101
The key to beating jimmy23013's solution was to reduce the number of repetitions of each character from 3 to 2.
Explanation
^(?!([^])+.*\1.*\1) - assert that no character in the string is repeated at least 3 times
([^])+ is equivalent to .*([^]).
[^] works because JavaScript allows empty character classes (unlike most other regex engines, at least by default). It is equivalent to [\W\w] or . with the /s flag, i.e. it matches any character including newlines. For our purposes here, newlines don't matter, so it's equivalent to ..
Using ^(?!([^])+.*\1.*\1) instead of (?!.*([^])(.*\1){2}) or ^(?!(.)+.*\1.*\1) eliminates the need for a third (, ), or ., and this is the key to reducing the number of repetitions of every character from 3 to 2.
^...[?!ZZ-__==''-22+,,//{50}$]{50}$ - assert that the entire string consists of the 25 characters ? ! Z [ \ ] ^ _ = ' ( ) * + , - . / 0 1 2 { 5 } $ and is 50 characters in length. Combined with the first assertion this guarantees that every character occurs exactly twice (due to the generalized pigeonhole principle, if any character occurred only once, some other character would have to occur three times).
Z-_ is the range Z[\]^_. It's essential, because we already used [, \, ], and ^ twice each. We need to double the Z and _, because they aren't used elsewhere.
'-2 is the range '()*+,-./012. It's essential, because we already used (, ), *, ., and 1 twice each. We need to double the ', ,, /, and 2, because they aren't used elsewhere.
There is no other way besides ranges to include the above in our character class, because octal or hexadecimal escape codes would require using \, and a negative character class would require using ^.
== is extra padding to get us to 50 characters. It could be any arbitrary doubled character. We need it because if we went for {48}, we'd need to include two 0 somewhere, which would bring our 48 back up to 50.
Note that this can be trivially rearranged to include the delimiters:
/^(?!([^])+.*\1.*\1)[?!ZZ-__==''-22+,,{50}$]{50}$/

Try it on regex101
Perl / PCRE, 57 bytes
I'm pretty sure it's impossible to do 2 repetitions in Perl/PCRE, because [^] is not available (except with the PCRE2_ALLOW_EMPTY_CLASS flag), and the only other alternatives use \ – for example \C, \N, \X, \S, and [^\0]. So, with 3 repetitions:
^(?!(.)*(.*\1){3})[[[-\]\]^^??!!'''-*.11{335577}$$-]{57}$

Try it on regex101
This is very similar to jimmy23013's JavaScript solution. It doesn't work under JavaScript however, because ^(?!(.)*(.*\1){3}) can always match on any string; it would capture an unset \1 by doing zero repetitions on (.)*, and then \1 would match an empty string 3 times.
Making it portable to both JavaScript and Perl/PCRE by using (.)+ instead of (.)* would end up making it 60 bytes, due to adding the + character.
Alternatively:
((.)+(.*\2){3})?+^[[[-\]\]^^??+'''-**.22{335577}$$-]{57}$

Try it on regex101
This uses the possessive quantifier ?+ to atomically try to match a character repeated 4 times. If such a match is not found, it will be forced to do zero repeats (instead of one) and the ^ will match. Otherwise it will match something non-empty, and the ^ won't match.

Perl and PCRE regex, 280 bytes
^(?=(.*z){2})(?=(.*\(){43})(?=(.*\)){43})(?=(.*\*){22})(?=(.*\.){23})(?=(.*0){2})(?=(.*1){6})(?=(.*2){16})(?=(.*3){7})(?=(.*4){4})(?=(.*5){1})(?=(.*6){3})(?=(.*7){2})(?=(.*8){2})(?=(.*9){1})(?=(.*=){22})(?=(.*\?){22})(?=(.*\\){11})(?=(.*\^){2})(?=(.*\{){23})(?=(.*\}){23}).{280}\z

(Slightly) more readable:
^
(?=(.*z){2})
(?=(.*\(){43})
(?=(.*\)){43})
(?=(.*\*){22})
(?=(.*\.){23})
(?=(.*0){2})
(?=(.*1){6})
(?=(.*2){16})
(?=(.*3){7})
(?=(.*4){4})
(?=(.*5){1})
(?=(.*6){3})
(?=(.*7){2})
(?=(.*8){2})
(?=(.*9){1})
(?=(.*=){22})
(?=(.*\?){22})
(?=(.*\\){11})
(?=(.*\^){2})
(?=(.*\{){23})
(?=(.*\}){23})
.{280}\z

This runs in O(2^n) time as written, so is incredibly inefficient. The easiest way to test it is to replace every occurrence of .* with .*?, which causes the case where it matches to be checked first (meaning that it matches in linear time, but still takes exponential time if it fails to match).
The basic idea is that we enforce the length of the regex to equal 280, and use lookahead assertions to force each character in the regex to appear at least a certain number of times, e.g. (?=(.*z){2}) forces the z character to appear at least twice. 2+43+43+22+23+2+6+16+7+4+1+3+2+2+1+22+22+11+2+23+23 is 280, so we can't have any "extra" occurrences of any characters.
This is a programming example of an autogram, a sentence that describes itself by listing the number of each character it contains (and, in this case, also the total length). I got fairly lucky in constructing it (normally you have to use brute force but I stumbled across this solution while testing my brute-force program before I'd fully finished writing it).
Perl and PCRE regex, 253 bytes, in collaboration with Martin Ender
I hypothesized that there might be shorter solutions which omit some digits (most likely 9, 8, or 7). Martin Ender found one, shown below:
^(?=(.*z){2})(?=(.*\(){39})(?=(.*\)){39})(?=(.*\*){20})(?=(.*\.){21})(?=(.*0){4})(?=(.*1){6})(?=(.*2){11})(?=(.*3){6})(?=(.*4){3})(?=(.*5){2})(?=(.*6){3})(?=(.*9){4})(?=(.*=){20})(?=(.*\?){20})(?=(.*\\){9})(?=(.*\^){2})(?=(.*{){21})(?=(.*}){21}).{253}\z

Readable version:

^
(?=(.*z){2})
(?=(.*\(){39})
(?=(.*\)){39})
(?=(.*\*){20})
(?=(.*\.){21})
(?=(.*0){4})
(?=(.*1){6})
(?=(.*2){11})
(?=(.*3){6})
(?=(.*4){3})
(?=(.*5){2})
(?=(.*6){3})
(?=(.*9){4})
(?=(.*=){20})
(?=(.*\?){20})
(?=(.*\\){9})
(?=(.*\^){2})
(?=(.*{){21})
(?=(.*}){21})
.{253}\z

I don't think you need to escape those {} in the last two lookaheads. You also don't need to add things like (?=(.*5){1}) since there wouldn't be a 5 if you didn't have that lookahead. One problem is that $ allows a trailing linefeed, so you'll need to use \z there instead of $ like jimmy did, but that won't cost you a byte I think since you save the \ in the first lookahead.

I'm aware that it's possible to omit things like digits. However, they're there to make the autogram work. Removing any part of the program will cause all the rest to break, because it no longer describes the program correctly. (The counts for each line count the counts for each line! Thus it is in general basically impossible to change the program.) As for $ allowing a newline at the end of the string, that generally depends on how the regex is called by the surrounding program (they're normally run on code that's already been parsed into lines).

Or to be more precise: I do need the (?=(.*5){1}) in this case. If I removed it, there would be a 5 in the program, because the (?=(.*1){6}) line would now have to read (?=(.*1){5}).

As for the trailing linefeed there doesn't seem to be any restriction in the challenge on the kind of input to your regex, so that usually means it should work for any string whatsoever, and changing $ to \z doesn't do any harm (and doesn't break the autogram).

Oh, I see; you change the \$ … $ to z … \z. That works; I'll go change it.

I fiddled around a bit and managed to recover an autogram after dropping those unnecessary escapes, saving 3 bytes: http://pastebin.com/4hUXHDrb

Even better: I got an autogram after dropping both 7 and 8, cutting this down to 253: http://pastebin.com/uqKKUGF9

Well found. I've added it to the post as an alternative/collaborative solution (you've done enough work on it that I can hardly count it as my own solution at this point).

I'm perfectly happy for you to replace your solution with it if you credit me. It's still your idea of using an autogram, and all I did was tweak some numbers in an editor until I got an autogram again. ;)

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:
Prove 2+2=2*2 (and similar)
Output a full formal poof of such statements such as 1+2=3, 2+2=2*(1+1) etc.
Introuction
If you know Peano Arithmetic you can probably skip this section.
Here's how we define the Natural Numbers:
(Axiom 1) 0 is a number
(Axiom 2) If `x` is a number, the `S(x)`, the successor of `x`, is a number.

Hence, for example S(S(S(0))) is a number.
You can use any equivalent representation in your code. For example, all of these are valid:
0    ""    0           ()       !
1    "#"   S(0)        (())     !'
2    "##"  S(S(0))     ((()))   !''
3    "###" S(S(S(0)))  (((()))) !'''
...
etc

We can extend the rules to define addition as follows.
(Rule 1) X+0 = X
(Rule 2) X+S(Y)=S(X)+Y

With this we can prove 2+2=4 as follows
         S(S(0)) + S(S(0)) = 2 + 2
[Rule 2 with X=S(S(0)), Y=S(0)]
         S(S(S(0))) + S(0) = 3 + 1
[Rule 2 with X=S(S(S(0))), Y=0]
         S(S(S(S(0)))) + 0 = 4 + 0
[Rule 1 with X=S(S(S(S(0))))
         S(S(S(S(0))))     = 4

We can extend these rules to define multiplication as follows
(Rule 3) X*0 = 0
(Rule 4) X*S(Y) = (X*Y) + X

Although to allow this we need to define the structural role of parentheses.
(Axiom 3) If X is a number, (X) is the same number.

Addition and multiplication operators are strictly binary and parentheses must always be explicit. A+B+C is not well-defined, but (A+B)+C and A+(B+C) are.
Example
Now we have enough to prove a theorem about multiplication: 2+2=2*2
2 + 2
(2) + 2
(0 + 2) + 2
((0*2) + 2) + 2
(1*2) + 2
2*2

Requirements
A proof that A=B is a list expressions such that:

the first is A,
the last is B, and
each expression in the list apart from the first can obtained from the previous by transforming it under one of the rules.

Your program will take two valid expressions as input, each expression contains numbers, addition, multiplication, and parentheses as defined above.
Your program will output a proof, a list as defined above, that the two expressions are equal, if such a proof exists.
If the two expressions are not equal, your program will output nothing.
Proving or disproving is always possible in a finite number of steps, because each expression can be reduced to a single number and these numbers can be trivially tested for equality.
If the input expressions are not valid (e.g. unbalanced parentheses, contains non-numbers, or non-binary operators) then your program should exit with error, throw an exception, print an error, or otherwise produce some observable behaviour which is distinct from the case in which the inputs are valid but non-equal.
In summary, the normal output for admissible inputs is a list of equal numbers, including the inputs, which is produced by the following rules.
(Axiom 1) 0 is a number
(Axiom 2) If `x` is a number, the `S(x)`, the successor of `x`, is a number.
(Axiom 3) If X is a number, (X) is the same number

(Rule 1) X+0 = X
(Rule 2) X+S(Y)=S(X)+Y
(Rule 3) X*0 = 0
(Rule 4) X*S(Y) = (X*Y) + X
(Rule 5) X = (X)              (Axiom 3 expressed as a transformation rule.)

Any suitable representation of the numbers in the input and output is allowed, e.g. 0=""=(), 3="###"=(((()))), etc. Whitespace is irrelevant.
Rules can, of course, be applied in either direction. Your program does not have to output which rule is used, just the expression produced by its action on the previous expression.
Shortest code wins.

Some examples of proofs converting expressions to numbers and back

Perl, 166 + 1 bytes
Run with -p (1 byte penalty).
$r='\((S*)';(@b,@a)=@a;push@a,$_ while+s/\+S/S+/||s/$r\+\)/$1/||s/$r\*\)//||s/$r\*S(S*)/(($1*$2)+$1/||s/$r\)/$1/;$\.=/[^S]./s;$_=$b[-1]eq$a[-1]?join'',@b,reverse@a:""

More readable:

                           # implicit: read a line of input into $_
                           # we leave the newline on
$r = '\((S*)';             # we use this regex fragment a lot, factor it out
(@b, @a) = @a;             # set @b to @a, @a to empty
push @a, $_ while          # each time round the loop, append $_ to @a
+s/\+S/S+/||               # rule 2: change "+S" to "S+"
s/$r\+\)/$1/||             # rule 1: change "(X+0)" to "X"
s/$r\*\)//||               # rule 3: change "(X*0)" to ""
s/$r\*S(S*)/(($1*$2)+$1/|| # rule 4: change "(X*Y" to "((X*Y)+X"
s/$r\)/$1/;                # rule 5: change "(X) to "X"
$\.=/[^S]./s;              # append a 1 to the newline character if we
                           # see any non-S followed by anything
$_=$b[-1]eq$a[-1]?         # if @b and @a end the same way
  join'',@b,reverse@a      # then $_ becomes @b followed by (@a backwards)
  :""                      # otherwise empty $_
                           # implicit: output $_

The input format expresses numbers in unary as strings of S, and requires the two inputs on separate lines (each followed by a newline, and an EOF after both are seen). I interpreted the question as requiring that parentheses should be literally ( ) and addition/multiplication should be literally + *; I can save a few bytes through less escaping if I'm allowed to make different choices.
The algorithm actually compares the first line of input with an empty line, the second with the first, the third with the second, and so on. This fulfils the requirements of the question. Here's an example run:
My input:

(SS+SS)
(SS*SS)

Program output:

(SSS+S)
(SSSS+)
SSSS
SSSS
(SSSS+)
((SS+)SS+)
(((SS*)SS+)SS+)
(((SS*)S+S)SS+)
(((SS*)+SS)SS+)
((SS*S)SS+)
((SS*S)S+S)
((SS*S)+SS)

The duplicated SSSS in the middle is annoying but I decided it didn't violate the specification, and it's fewer bytes to leave it in.
On invalid input, I append 1 to the newline character, so you get stray 1s sprinkled in at the end of the output.

echo -e "((SS+)+(S+S))\nSS*SS" | perl -p /tmp/x.pl outputs 1.

That's correct, you're missing the brackets on the second line (which should say (SS*SS)). "Addition and multiplication operators are strictly binary and parentheses must always be explicit."


text:
I want to watch you die of thirst
You are a traveller crossing the desert between two towns. You cannot carry enough water to get across without stopping. This is a variation of a classic puzzle.
The Rules
A desert looks like this: a WxH grid of mostly empty space. The space marked S is where you start, E is where you want to end, and a square marked with the number N holds N units of water. Squares marked with a . hold zero water.
.....................................
........S............................
.....................................
.........7...........................
.....................................
.......................3.............
.....5...............................
................................2....
.....................................
.....................................
.....................................
...............................E.....
.....................................
....................7................
.....................................
.....................................

You start at S with 5 units of water.
You can carry at most 5 units of water.
Each turn you

move one square Up, Down, Left, or Right,
consume 1 unit of water that you are carrying,
pick up or drop some number of units of water.

A turn is notated thus: (direction)(+|-)(units of water), + indicates you are picking up water, - that you are dropping it.
Example turns:
D+0        Move Down
R+0        Move Right
D+2        Move Down, pick up two units of water.
U-1        Move Up, drop one unit of water.

If you perform these moves starting at S in the example above, the desert looks like this afterwards.
.....................................
........S............................
.........1...........................
.........5...........................
.....................................
.......................3.............
.....5...............................
................................2....
.....................................
.....................................
.....................................
...............................E.....
.....................................
....................7................
.....................................
.....................................

You can pick up no more water than is already on your square. When you pick up the water, deduct that number of units from the tile's count.
You can only pick up water to hold a maximum of 5 units.
No tile can hold more than 9 units, except S which holds infinity units.
You can only drop as much water as you are currently holding.
Water on the ground remains unchanged until you pick it up again.
If you return to S you can pick up any quantity of water without depleting it.
If you reach E then you win. You still win if you consume your last unit of water on E.
If, after your turn, you have zero water and you are not on E, you die.
Input and Output
Your program will receive a starting map of arbitrary size on STDIN as ASCII art in the format above. You can assume it is rectangular i.e. all lines the same length, that there is exactly one S and one E square, all lines are terminated with \n, and the whole of STDIN will conform to this regex: /^[SE1-9\.\n]+$/
Your program will write the following output to STDOUT:

the list of moves,
the final state of the map.

You may output the list of moves in any convenient format.
The final state of the map will be printed in the same format as the input except that it will additionally show the route you took through the desert by marking all visited tiles with #, if that tile contains no water and is not S or E (i.e. it is .).
EXAMPLE input:
.....S.
.......
.......
E......
....8..

EXAMPLE winning output:
D+0
D+0
D+0
D+0
L+5
L+0
L+0
L+0
L+0
U+0
.....S.
.....#.
.....#.
E....#.
####3#.

Nontriviality
When you post your code, post a sample map input which your code finds a solution for which satisfies the following non-triviality conditions:

S and E are at least 10 moves apart.
Any square which initially contains N units of water must be surrounded by a N-width border in which all squares are . (no water, not S or E)

EXAMPLE
........2.
..........
..........
S.1..2....
..........
..........
........1.
..3.......
.........E

If you increase the amount of water on any tile, the above becomes trivial.
Requirements
Presumably your program will encounter a number of failed attempts before it finds a solution, if any.

Your program must eventually solve any solvable input.
I want to watch you die -- your program will output the moves and final map of the route to death for each and every failed attempt to find a solution.
If you encounter a winning solution, print the full output for that and terminate.
Run until a solution is found, but do not attempt the same solution twice -- all deaths should be by distinct routes.
Use this a test input:

(it requires at least one move to drop a water cache at some midpoint).
 S........
 .........
 .........
 ........E

Shortest code which is posted with a non-trivial demonstration input which it solves wins.

This needs to be clarified to specify whether the program needs to be able to solve any solvable map, or whether it only has to work for one map. I'd definitely encourage the former; in the case of one map, it'll be easier to hardcode the solution than to calculate it.

Edited for clarity. Yes you win if you have more than zero water, and yes your program must solve all solvable inputs.

What's stopping you to use an algorithm such as A* and dropping a path of 5 units on each tile you successively go to and go back to the start if you step onto a tile without 5 water?

Nothing. Go ahead.

The 'carry all water from S' strategy should work, although it will be terribly tedious. Consider S.,.,.,.,.e....E where , and e are really dots. The commas are where you keep your stashes along the way, and 'e' is where you need to have 5 water to make a run for E. 4 steps to move 1 water to the first comma (E+0 E-1 W+0 W+4). 16 steps to move 1 water to the second comma. 52 to the third, 160 to the fourth, 484 to drop 1 water to e and get back to S. 1926 steps and you're at e carrying 5 water, 5 more to run to E, 1931 steps. Every two steps of path effectively triples your solution length.

@Sparr: My solution's actually even more inefficient, because the goal is to write a short program to generate the output rather than a short output. "Clever" algorithms to generate a more optimal output are unlikely to win a [tag:code-golf].

@ais523 I did see that. I have ideas for an even less efficient solution :)

Perl, 299 + 1 = 300 254 + 1 = 255 bytes
This will almost certainly be beaten by one of the golfing languages when people see my algorithm :-)
Run with -n (1 byte penalty).
The previous version didn't quite comply with the spec because it left extra water on the map and didn't show it in the final version of the map; while changing the algorithm to deal with that situation, I managed to golf it a bit smaller in the process.
push@a,[split//];($s,$t)=(length$`,$.)if/S/;($e,$f)=(length$`,$.)if/E/}{$_.=$s<$e?($s++,R):$s>$e?($s--,L):$t<$f?($t++,D):($t--,U);$\=reverse$";$".=y/LRUD/RLDU/r.Y.reverse.($"=~y/Y/X/r);$a[$t-1][$s]=~y/./#/;$\.=$s-$e||$t-$f?redo:$_;print map{join'',@$_}@a

Example (I've added line-breaks to the output to avoid the need to scroll and to show the structure):

E.....
#.....
#.....
#.....
#####S
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUXDRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUUXDDRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUXDRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUUUYDDDRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUXDRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUUYDDRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUYDRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLYRRRRR
 LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLYRRRR
 LXR LLXRR LXR LLLYRRR LXR LLYRR LYR LLLLLUUUU
In the notation used by the program, movement is represented via L, R, U, and D for left, up, right, down respectively. By default, you pick up 1 unit of water after every move, but this can be modified by appending a character:

X: drop 2 units of water, rather than picking 1 up
Y: drop 1 unit of water, rather than picking 1 up
  (i.e. space): completely refill on water (only output after a move to S; the program is also output with a leading space, which makes sense because you start full on water)

As you can see, it's possible to cross this (rather barren) map using no extra pools at all. In fact, it's possible to get any distance under these rules, on any map, without the help of any preplaced water. As such, this algorithm just ignores any preplaced water, meaning I don't have to waste bytes trying to handle it. This also means that you're not going to see the bot die, sorry. It never moves beyond the range in which it knows it's guaranteed to survive.
The reason we need both X and Y (and a bit of extra code to ensure we have X throughout most of the strategy but the occasional Y at the end) is that the spec requires the final version of the map to be output. The easiest way to implement this is to leave the map entirely untouched (apart from our path through initially empty squares), especially as a square which started with 9 water would end up with 10 (breaking the ASCII art) if it happened to be on the path and we only used X, and thus we need to find some solution that avoids dropping extra water on the map. The algorithm here would "naturally" drop 1 extra unit of water on each square on the route; as such, the penultimate time we visit each square, we reduce the amount of water dropped by 1 via the use of Y rather than X, so that on our final visit, we drain the square back to its original quantity of water, rather than leaving it slightly wetter than when we started.
I'd recommend against running this on a large map, because it has O(2^n) performance (although the bot never dies of thirst, it's plausible to think it would die of hunger using a strategy like this.)
Readable version:
# implicit with -n: read a line of input into $_
push @a, [split //]; #/ split $_ into characters, store at the end of @a
($s,$t) = (length$`,$.) if /S/; # if we see S, store its coordinates
($e,$f) = (length$`,$.) if /E/  # if we see E, store its coordinates
}{ # Due to -n, loop back to start if there are more lines.

# From here onwards, $" stores the partial solution this iteration;
#                    $\ stores the partial solution last iteration;
#                    $_ stores the path from ($s,$t) to S.
# At the start of the program, $" is a space, $\ and $_ are empty.

$_ .=  # Work out the next step on the path:
  $s < $e ? ($s++,R) # if too far left, move right, record that in $_;
: $s > $e ? ($s--,L) # if too far right, move left, record that in $_;
: $t < $f ? ($t++,D) # if too far up,    move down, record that in $_;
: ($t--,U);          # in other cases we must be too far down.
$\ = reverse $";     # Store last iteration; $" is constructed backwards.
$" .=                # Extend $" by appending
  y/LRUD/RLDU/r .    # the path from ($s, $t) back to S;
  Y .                # a literal 'Y';
  reverse .          # $/ backwards (i.e. the path from S to ($s, $t);
  ($"=~y/Y/X/r);     # a copy of $" with all 'Y' changed to 'X'.
$a[$t-1][$s] =~      # At the current path coordinate,
  y/./#/;            # replace any '.' with '#'.
$\ .=                # Start appending to $\;
  $s-$e||$t-$f?redo  # if we're not at E, abort that and jump back to {{,
: $_;                # otherwise append $_ (the path from S to E).
print map            # For each element of some array
  {join'',@$_}       # output its concatenated elements
  @a                 # specifying that array as @a.
# Implicitly: print $\ (which specifies the sort of newline print uses).

Would flood filling the world in a spiral be less code than your block of conditionals for direction to seek the exit?

I don't think it would be (although it's possible there's some way that I'm just not seeing; it's certainly an idea worth considering). You still have to deal with four directions, and you now also have to deal with the edge of the map, something which isn't a problem in this version of the algorithm.

Good point, re edges. I think it could be done on an infinite map.


text:
Generate a cipher
Generate a cipher given a number and string
Your task is simple. Given a string s and a number 0 <= n <= 9 as inputs, insert a pseudo-random printable ASCII character between each character of the string n times. Such that for each character of s there are n random characters between them. Spaces should be trimmed.
Input:

string s phrase to encrypt in the cipher
integer n in the range of 0 <= n <= 9

Example:
Input:
The treasure is here
2

Output:

T!0h32eF4t0irlkehma7ys#0u*&r*he!2iH^sB,h!@e0)r$he

This is code-golf so the shortest code wins! Good Luck and have fun!

Can the printable ASCII character be the same?

@MayorMonty sure just randomize it for obscurity

Do each individual character need to be random or can there be a set of n unique random ascii characters between the letters (no duplicate random characters between the letters)?

each individual character needs to be random

random printable ASCII character You need to define what random means here. Shold all printable ASCII characters have the same probability? Should they be statistically independent? What flexibility do we have regarding this?

Are n trailing cipher characters after the last character in the string acceptable?

@Yodle Yes that is acceptable

@LuisMendo thanks for the comment, I don't think that level of granularity is necessary. I think random is pretty well understood within the computing community.

@jacksonecac I disagree. Just saying random is not enough. For example, if I only pick random characters with even ASCII codes, that's still random but that's probably not accepted (or ist it?) If each series of n characters consists of n copies of the same random character, they are still random, but they are not statistically independent. And so on

@jacksonecac "random" is a very broad term. Can I choose the characters with a normal distribution, so that characters around O are more likely than spaces or ~? If it has to be uniform, then you should say so explicitly. And if it doesn't have to be uniform, then you should at least state something like each character needs to have a non-zero probability. You've also stated in a previous comment that each character does have to have an independent distribution, so if this is important, it should be mentioned in the challenge. There is a very broad spectrum of randomness.

This isn't really a cipher. It's steganographic, perhaps.

@MartinEnder "made, done, happening, or chosen without method or conscious decision."

That's not an appropriate response to @MartinEnder 's valid point. A solution would be to specify explicitly that the characters have to be uniform and statistically independent of each other and the comments will stop. An alternative (but more open to abuse) specification would be that skewed distributions  or those where characters are dependent on one another are OK so long as all characters have nonzero possibility of occuring. In code golf specification is important for fairness. As you seem unwilling to address these valid comments on an otherwise good challenge, I`m voting to close.

@LevelRiverSt if you are such a stickler on rules, then recognize that I am not going to define more parameters for answering this question after there are 11 answers already, which would not be fair to them. thanks.

The issue with not defining what distribution the samples should approximately follow is that it we need to make assumptions on what is allowed and it therefore it becomes ambigous if a solution is valid. We could for example replace String.fromCharCode(...[...Array(n)].map(_=>Math.random()*95+32)) with [...Array(n)].map(_=>'TX'[+(Math.random()>.5)]).join('') and lazily outgolf the current ES6 submission by 9 bytes.  According to the spec it should count because it is a random character. However, it seems unfair, doesn't it? So should that count? See where this is going?

I posted an attempt at a standard definition over on meta (http://meta.codegolf.stackexchange.com/a/10663/56071) to avoid ambiguities in the future. It is consistent with the answers I can read that have been posted so far, FWIW.

@Lmis that would be a fine solution in my book. There were no strict guidelines on this to allow any number of solutions. I don't see what that would be cheating.

@GregMartin I guess it can be seen as a variant of the Scytale cipher (with just one line used and the rest filled randomly), or a Grille cipher (with a quite regular grille).

I guess I wouldn't really call those ciphers either; but I take your point about the historical usage of the word :)

05AB1E, 11 bytes
ð-vy²FžQ.RJ

Try it online!
Explanation
ð-           # remove spaces from input string
  v          # for each char in the string
   y         # push the char
    ²F       # input-2 number of times do:
      žQ.R   # push a random ascii character
          J  # join to string

close! trim the spaces! :)

@jacksonecac: Missed that part sorry. Fixed now :)

nice job! that works!

Does ð-vy²FžQ.R}«}\J also work?

@Adnan: Not for other values of nthan 2. But I think the general idea is sound.

ð-vy²FžQ.R}J is 12 bytes and seems to be fine.

@carusocomputing: That adds random characters after the last letter as well. Not just in between letters.

@Emigna After a recent comment under the question this seems to be fine :)

C#, 141 131 bytes
Pretty similar to @Geobit's Java answer, except longer currently :(
(I,n)=>{var R=new System.Random();var o="";int i,r;foreach(var c in I)if(c>32)for(i=r=0,o+=c;i++<n;){r=R.Next(33,127);o+=(char)r;}return o;};

Full lambda stuff:
Func<string, int, string> a = (I,n) =>
{
    var R=new System.Random();
    var o="";
    int i;
    foreach(var c in I)
        if(c>32)
            for(i=0,o+=c;i++<n;o+=(char)R.Next(33,127));
    return o;
};

why R=... You can just directly use new System.Random().Next(...) I think

@RomanGräf https://msdn.microsoft.com/en-us/library/h343ddh9(v=vs.110).aspx  C#'s Random class, without a seed, will use the System clock, so if you call in rapid succession (such as within the loop there), most of the values end up being identical, which wouldn't work in most cases :(  Believe me, I always try and then remember that.

Java 7, 132 124 bytes
String f(int n,char[]a){String o="";int i;for(char b:a)if(b>32)for(i=0,o+=b;i++<n;o+=(char)(33+Math.random()*94));return o;}

Nothing fancy, just a double loop like you'd expect. Outer to loop the string, inner to fill in randoms:
String f(int n,char[]a){
    String o="";
    int i;
    for(char b:a)
        if(b>32)
            for(i=0,
                o+=b;
                    i++<n;
                        o+=(char)(33+Math.random()*94));
    return o;
}

No need for k: String f(int n,char[]a){String o="";for(char b:a)if(b>32){o+=b;for(int i=0;i++<n;o+=(char)(33+Math.random()*94));}return o;} (125 bytes)

Oooh right. I was using it with a different method. Didn't think about taking it out when I went with the char cast. Thanks!

My bad. I miscounted, my suggestion was also 124 bytes: I checked the column instead of the length ;)

Yeah, I noticed that when comparing the two :)

Pyke, 12 11 9 bytes
d-FQV~KHs

Try it here!
d-        -  remove spaces from input
  F       - for i in ^:
   QV     -  repeat (number) times:
     ~KH  -    random_from(printable)
        s -   sum(^)

Trailing random characters is fine according to OP.

Octave, 43 bytes
@(s,n)[s(s>32);33+94*rand(n,nnz(s>32))](:)'

This takes a string s and an integer n as input. A string in Octave is simply an array of characters. s>32 is a logical map with 1 for any non-space characers. The code appends a matrix with n rows and the same number of columns as s(s>32) has, containing floating point numbers between 33 and 126. It is implicitly rounded to integers and converted to ASCII-characters when it's concatenated with the string s. (:)' straightens this to a horizontal array of characters.
Test it here!

Implicit rounding! Nice

Python 2, 123 122 118 114 98 Bytes
Man, I wish random wasn't so expensive (and that we didn't have to filter for spaces). Now we have big savings from being allowed to have cipher characters at the end :) Anyways, here ya go:
from random import*
f=lambda s,n:s and(' '<s[0])*eval('s[0]'+'+chr(randint(32,126))'*n)+f(s[1:],n)

JavaScript (Firefox 30+), 96 bytes
(s,n)=>s.replace(/. */g,x=>x[0]+String.fromCharCode(...[for(_ of Array(n))Math.random()*95+32]))

Pure ES6 is two bytes longer:
(s,n)=>s.replace(/. */g,x=>x[0]+String.fromCharCode(...[...Array(n)].map(_=>Math.random()*95+32)))

Here's a really cool approach which is sadly 26 bytes longer:
(s,n)=>String.raw({raw:s.split` `.join``},...[for(_ of s)String.fromCharCode(...[for(_ of Array(n))Math.random()*95+32])])

Strictly speaking /. *(?=.)/ doesn't work for strings beginning or ending in spaces, not that anyone cares. (You're even allowed trailing random characters now.)

@Neil Trailing random chars are allowed? I guess I can just remove the (?=.) which takes care of spaces at the end of strings.

The spec is not so clear, but I think you shold avoid inserting blank spaces, so 94+33 instead of 95+32

CJam, 21 18 bytes
lS-(ol~f{{95mrSc+\}*}

Try it online!
Prints n random trailing characters.
Explanation
lS-        e# Read line and remove spaces.
l~         e# Read and evaluate another line.
f{         e# For each character (passing in N)...
  {        e#   Do this N times...
    95mr   e#     Push random integer in [0, 95).
    Sc+    e#     Add to space character, giving a random printable ASCII character.
  }*
}
           e# All characters remaining on the stack are printed implicitly
           e# at the end of the program.

R, 97 bytes
Unnamed function taking inputs x (string)  and n.
function(x,n,l=nchar(x))for(i in 1:l)cat(substr(x,i,i),if(i<l)intToUtf8(sample(32:126,n)),sep="")

Try it on R-fiddle

Q/KDB+, 39 36 34 Bytes

raze{""sv(raze x;`char$40+n?87)}prior s
(,/)({""sv((,/)x;`char$40+n?87)}':)s

(,/)({""sv((,/)x;10h$40+n?87)}':)s

Variables in use:
s:"The treasure is here"
n:2

This uses the prior adverb, which applies the function to it's left between each item to the right and its predecessor. (Essentially, applies function to the left between each character on the right.)
Generate n random numbers between 40 and 126 then convert them to a character equivilent: (q seems to only have characters for these)
`char$40+n?87

//Possible characters.
()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Example output:
TVghrveVp Rpti+r0sea3a9nsIjuRXrAReJ; +di=ys`{ ikhKTe4trTZesz

EDIT:
Saved 3 bytes by converting q's raze into (,/) using the k notation and similarly changed prior to `:
Thanks to @slackwear for the update, shaved 2 bytes :)

can save a couple of bytes by casting with 10h$

Bash, 124 bytes
Pure bash + coreutils, no control flow structures, no sub-languages, no "eval"
Golfed
E() { N=${1// /};paste <(fold -1<<<$N) <(tr -cd "\\40-\\176"<\/dev\/urandom|head -c$(($2*${#N}-$2))|fold -$2)|tr -d '\t\n';}

Test
>E "The treasure is here" 2
TkZhf(e&Rt@FrS,edha+-sJTuh.rX@eVKi+3s<7hftey8r*/e

Java 8, 114 bytes
Golfed
(n,s)->s.chars().forEach((c)->{if(c>32)for(int i=0;i<=n;)System.out.print((char)(++i==1?c:33+Math.random()*94));})

Lambda that accepts an Integer and a String. Inspired by the Java 7 answer, double loop using some Java 8 Stream syntax (String.chars) to save a few bytes.
Input
3, "Hello world!"

Output
HfKIedb3l<-Ul%}vod"Bw\"|oa`%rH-}l/-{dMS;!B#X

Scala, 95 94 Bytes
def c(s:String,i:Int)=s.filter(_>32).mkString(scala.util.Random.alphanumeric.take(i).mkString)

Nothing overly fancy, besides the use of mkString on a String. It treats the string as a list of characters, and allows me to insert a separator between them. My separator is the appropriate number of randomly generated alphanumeric characters.

Not quite answers the question. The nature of Random.alphanumeric will cause each chunk to be the same, so it's a lame cipher... See this example: scala> c("Hello", 1) res0: String = Hbeblblbo

BTW, you can remove the filter. Invoking mkString on a String will treat it as a character collection.

@Jacob the filter is the most efficient way I could think of to remove spaces. I left the random as is since it seemed sufficient, but if I have time I'll add in a separate function for proper random text.

Perl 5, 81 bytes
($_,$n)=<>;chomp;y/ //d;$\=chop;print map{$_,map{chr 33+int rand 94}1..$n}split//

I hope the following helps you understand what the one-liner does:
($_, $n) = <STDIN>;  # Reads in the string into $_,
                     # and the number into $n, from standard input.
                     # (<STDIN> works slightly different from <>.)
chomp($_);           # Removes the newline from the string.
$_ =~ tr/ //d;       # `Tr/`ansliterates ASCII space characters
                     # into nothing, effectively `/d`eleting them.
$\ = chop($_);       # Chop()s off the last character out of $_ and
                     # appends it to the output when print()ing.
                     # (Perl always prints $\ after you call print().)
print( map {         # Each element of [List 1] will be mapped to:
    $_,              #   -- Itself, and
                     # (When mapping, each element is available as $_.)
    map {            # (`map` resembles `foreach` but returns a list.)
        chr(         #   -- A random ASCII character, in the range
          33 + int(rand(94)) ) # from 33 (!, hex 21) to 126 (~, hex 7E)
    } 1..$n          # ...$n times! (Over the range 1 to $n, actually.)
} split(//, $_) );   # [List 1] is $_, split() into characters.

><> (Fish), 107 106 103 bytes
<v}:{r&" "
1xv+
2<v+
v}<
<~v!?=&:&:
6.>ol2-?!;a
:{{:}l1-[rv
v2<
<1x|!}:}-1<v!?:{{:o-+
^3<v ~}}r]~<
.40<

Try it online!
It isn't super random, but it is random. Just place the string and integer on the stack (Example: "Hello world!", 5).
Input: "Hello world!", 5
Output: H^\^]^eceeedldcdeclgfffhowhhfggojkkkkrdccedl]]\]\d

Full Explanation
This is a slightly older version of the code, until I update the explanation. It's mostly the same, just maybe a bit easier to read:
< v}:{r&" "
+1xv
+2<v
   }
:&:<~ v!?=&
?!;a6.>ol2-
:{{:}l1-[rv
v2<
<1x|!}:}-1<v!?:{{:o+*
^3<v ~}}r]~<
.43<

We'll pretend the string parameter is s and the integer parameter is i.
< v}:{r&" "

The < tells the fish to immediately move left, which wraps around to " ", which adds a space characted to the stack. Then the fish travels over &, which adds the space to the register. r reverses the stack and {:} shifts the stack to the left (putting i on the end of the stack), copies the value on the end of the stack, then shifts it to the right. v tells the fish to begin moving downwards.
+1xv
+2<v
   }

x tells the fish to move in a random direction, ultimately resulting in the fish going right and continuing downwards, or pass over 1+ or 2+ beforehand. These add 1 or 2 respectively to the number on the end of the stack. If the fish travels upwards, it hits v again and travels back down. } shifts the stack to the right, then having i at position 1 on the stack and this new variable at position 0 (we'll call it m).
:&:<~ v!?=&

This section is a function, let's call it whitespaceTrimmer. It begins where the < is. It simply strips spaces that're on the end of the stack (so the beginning of the string) until it runs into a non-space character.
So immediately the fish swims into a < and must travel to the left. It then runs into :&:& which copies the value on the end of the stack, places the space from the register onto the end of the stack, copies it, then places it back onto the register.
Then the fish hits =?!v ~, or more specifically, =, which pops the last two values (the two we just created) off of the stack, compares them, places a 1 on the end of the stack if they're equal, and a 0 on the end of the stack if they're different. The ? pops the new value off the end of the stack, if it is 0 it doesn't execute the next instruction, which in this case is !, it instead executes v, which orders the fish to move downwards (exiting the function).
If it is 1 however, then it has found a space, so it executes the ! which is a trampoline, and that causes the fish to skip the next instruction, which is a v, so the fish continues. In front of the fish, it sees ~ which tells it to pop the last value off the stack (confirmed to be a space), then the fish continues, and runs the function again.
?!;a6.>ol2-

The fish is immediately told to swim right by a >, then output the last character on the stack by o (which, the first time this is run, is the first character of s). It gets the length of the stack from l, places a 2 on the end of the stack, then - causes 2 to be subtracted from l. It hits ?!; which, remembering what ? does, causes the fish to skip the ! if the stack is empty, and land on ;, which ends the program.
Following if there are still characters on the stack, we execute ! which causes the fish to bounce over the ; and execute a6., which stores a (AKA 10), and 6 on the end of the stack, which are x, y coordinates for ., which pops them off the end of the stack, then teleports the fish to 10, 6, and execute the instruction to the right of that postion (as the fish is swimming right).
This is less complicated than it sounds when you realise y position 6 is the line below this one. x position 10 is then v, and to the right of that is , which is a no-op. This causes the fish to continue swimming right and actually begin execution at the beginning of the line...
:{{:}l1-[rv
v2<
<1x|!}:}-1<v!?:{{:o+*
^3<v ~}}r]~<
.43<

So this is the function that adds the random text in between the characters. It's a bit of a mouthful, but that's just because I tried to make it a little bit extra random. Let's call this genRandomChars.
The :{{:}l1-[rv is actually the setup for the function, and less-so part of the actual function itself. The fish first swims over :{{ which copies the value on the end of the stack, then shifts it to the left twice. If you recall that i was at postion 1 on the stack, then you'd know i is now on the end of the stack.
The fish then swims over :} which copies i, and shifts the stack to the right, placing i both at the beginning and end of the stack. l1-[ has the fish place the length on the end of the stack, subtract 1 from it, then [ creates a new stack, moving l-1 (stack length minus 1) values to the new stack (so just leaving i on the old stack). Then the fish simply hits rv which reverses the stack again (I think creating a new stack reverses it for some reason), and orders the fish to swim downwards once more, truely beginning the function at the < below.
So currently the end of the stack has m and our temporary i, which we'll call ti. Immediately the fish swims over 1-}, which subtracts 1 from ti and moves it to the beginning of the stack. Then :} which simply copies m and moves it to the beginning of the stack (putting ti at stack position 1).
This is when we hit this little thing:
v2<
<1x|!
^3<

This is actually dead simple. The ! causes the fish to skip | and execute x. Remembering what x does, we remember this makes the fish move in any 4 directions. | is simply a mirror, and causes the fish to swim back to x. So basically, the fish will place 1, 2, or 3 onto the end of the stack, and continue moving left, wrapping around.
The fish then executes *+o which causes the last two values on the stack to be popped off, multiplied together, and the result push back on, then the same thing with addition, then the final value is popped off the stack and outputted with o. Our stack is now relatively normal again containing just [m, ti, s].
:}}: causes the value on the end of the stack (basically s position 0) ot be copied, then the stack is shifted to the right twice (placing ti on the front again), then ti is copied. ?!v should be pretty easy to understand by now. Basically if ti is 0 then we exit the function with v, otherwise we execute ! and skip v (doing another loop).
If ti is 0 and we are done outputting slightly random characters, then we execute v and see:
   v ~}}r]~<
.43<

Nothing too fancy here. We remove ti from the stack via ~. Then ] is new, it pops all our values off the stack and places them on the old stack! Because of the reversal issue we reverse with r, then shift the stack right twice with }}~, shufting the stack to the right, giving us [m, i, s], the ~ is to remove the extra duplicated s[0] from earlier in the function as we'd need it if we were doing a loop (but we're not, we're exiting). v tells the fish to swim down and into >34. (inverted to show execution order), which tells the fish to simply swim left and into 3, 4 (because the . is a jump!). 3, 4 is actually just to the right of the beginning whitespaceTrimmer, which is perfect because we are travelling left.
Following all this logic we can follow the fish until the stack is ultimately empty and program exits just after whitespaceTrimmer is executed.

Hmm I didn't see that the character has to be printable. This will require slight modification which might make it less random and smaller.

It doesn't really look a whole lot less random. I believe it should work in most cases, I haven't had it fail yet. It will work with any capital or lowercase letter for sure, and some symbols. I'm pretty sure this satisfies the requirements of the challenge.

Clojure, 126 123 118 122 117 bytes
(defn c[m n](apply str(remove #(=\space %)(mapcat #(apply str %(for [_(range n)](char(rand-nth(range 32 127)))))m))))

Maps over the message, inserts random characters in, then concatenates the result.
The instructions suggest that all spaces should be stripped from the result string. If only spaces from the original message are supposed to be stripped, I can change that.
Ungolfed:
(defn cipher [message n]
  (apply str
    (remove #(= \space %)
        (mapcat #(apply str %
                     (for [_ (range n)]
                       (char (rand-nth (range 32 127)))))
                message))))

Python 3, 127 Bytes
import random
a,b=input(),input()
print(''.join([x+''.join([chr(random.randint(33,126))for c in range(int(b))]) for x in a]))

Probably way longer than necessary, but this is mine golfed so far.

This adds random characters in front of the first character, and spaces are not trimmed. I think both of these things breaks the rules.

PHP, 96 bytes
Takes String as argument 1 and Number as argument 2
for(;($s=str_replace(' ','',$argv[1]))[$j]>'';)echo$i++%($argv[2]+1)?chr(rand(33,127)):$s[$j++];

Try it online

Python 3, 133 Bytes
from random import *
c=int(input())
print(''.join([i+''.join([chr(randint(33,126))for i in range(c)])for i in input().strip(' ')])[:-c])

Node.js, 88 bytes
(s,n)=>s.replace(/./g,c=>c!=" "?c+crypto.randomBytes(n).toString`base64`.substr(0,n):"")

Example outputs:
f("The treasure is here", 2)
// THphdwekAtMArbSeU1aDTsZWuqnr2yek1iyUsKshqXewvrVCeTi

f("The treasure is here", 2)
// TYshlcep6t4Iru7e29aQ1sl/uvQrlzeSJihysDhhOLe1urpte1m

Try it online!

C, 102 100 bytes
-2 bytes for skipping continue.
i;f(char*s,int n){do{while(*s==32)++s;putchar(*s);i=n;while(i--)putchar(32+rand()%95);}while(*s++);}

Ungolfed:
i;
f(char*s,int n){
 do{
  while(*s==32)++s;
  putchar(*s);
  i=n;
  while(i--)
    putchar(32+rand()%95);
 }while(*s++);
}

Usage:
main(){
  char a[]="A   A A";
  f(a,3);
}


text:
Hexagonal coordinates: Polar to Cartesian
Wikipedia says about Polar Coordinates:

In mathematics, the polar coordinate system is a two-dimensional coordinate system in which each point on a plane is determined by a distance from a reference point and an angle from a reference direction.

This seems perfect for describing hexagonal grids. Take the following hexagonal grid for example:
  A B C
 D E F G
H I J K L
 M N O P
  Q R S

Our reference point will be the center of the hexagon ('J'), and our reference angle will be to the top left corner of the hexagon ('A'). However, we'll describe the angle in terms of the number of clockwise steps around the outside of the hexagon from this point, not in angles. So we'll call it "Step number" instead of angle.
For example, 'C' is at (2, 2) because it has a radius of 2 (since it is two rings away from the center, 'J'), and an step number of 2 (2 clockwise steps forward from 'A'). Similarly, 'O' is at (1, 3), because it is one ring away from the center, and three clockwise steps forward from 'E' (which is on the reference angle).
For completeness, 'J' is at (0, 0), since you need 0 steps out and 0 steps clockwise to reach it.
Now, you can also describe a hexagonal with Cartesian Coordinates, but because of the offset this is a little weird. Just like with our polar coordinates, we will put the center at (0, 0). Each space takes up a coordinate also, so 'K' is at (2, 0), not (1, 0). This would put 'A' at (-2, 2), and 'O' at (1, -1).
The challenge
Given polar hexagonal coordinates, output the same coordinates in Cartesian coordinates. You may take these coords, and the output the answer in any reasonable format. This means that you may reverse the order of the inputs if you like. This also means you could output the coords as (Y, X), but if you do, please mention this in your answer to avoid confusion.
You do not have to handle negative radii, but you may get negative angles, or angles that go more than a full revolution around the hexagon. For example, you may receive (1, 10), or (1, -2) as input. These would both correspond to 'N' in our previous hexagon. You do not have to handle non-integers for input.
Sample IO
#Polar      #Cartesian
(0, 0)      (0, 0)
(1, 2)      (2, 0)
(6, 0)      (-6, 6)
(2, -3)     (-3, -1)
(4, 23),    (-5, 3)
(5, -3),    (-8, 2)
(10, 50),   (-20, 0)
(6, 10),    (10, 2)
(8, 28),    (0, -8)
(8, -20),   (0, -8)

someone answer this in hexagony...

To clarify, do the units used to measure the angle depend on the radius? (e.g. (1, 1) is an angle of 60° from the reference angle, but (2, 1) is only 30° because it's further out and thus there are more letters there). The question seems to imply that, but that's not the normal way polar coordinates work, so it may be worth explaining that yours are differnet.

Do we only have to consider a distance of up to 2 from the origin, or does it have to work further away than that?

@ais523 Yes, it's measured in steps not angles. I've clarified that a little bit in the post.

@LevelRiverSt No, it should theoretically work for any radius. The test IO goes up to 10.

JavaScript (ES6), 93 bytes
(r,d)=>[...Array(d+r*6)].map((_,i)=>x+="431013"[y+="122100"[i=i/r%6|0]-1,i]-2,x=y=-r)&&[x,-y]

Test snippet:

f=(r,d)=>[...Array(d+r*6)].map((_,i)=>x+="431013"[y+="122100"[i=i/r%6|0]-1,i]-2,x=y=-r)&&[x,-y]

g=([r,d],e)=>console.log(`f(${r},${d}):`, `[${f(r,d)}]`, "expected:", `[${e}]`)

g([0,0],[0,0])
g([1,2],[2,0])
g([6,0],[-6,6])
g([2,-3],[-3,-1])
g([4,23],[-5,3])
g([5,-3],[-8,2])
g([10,50],[-20,0])
g([6,10],[10,2])
g([8,28],[0,-8])
g([8,-20],[0,-8])

You have to handle angles that go more than a full revolution; your code doesn't seem to work for (1, -7).

JavaScript (ES6), 95 bytes
f=(r,t,x=-r,y=r,d=2,e=0)=>t<0?f(r,t+r*6):t>r?g(r,t-r,x+r*d,y+r*e,d+e*3>>1,e-d>>1):[x+t*d,y+t*e]

Explanation: The solution for a zero angle is simply -r,r, so we start at that point. If the angle is negative, we add on a whole hexagon and call ourselves recursively, otherwise we start walking around the hexagon with a d,e=2,0 step. Where possible, we leap r such steps, then rotating the step using the formula d+e*3>>1,e-d>>1 to progress to the next side. Finally we take any remaining steps to reach our destination.


text:
Can you pretty-print a tree?
Goal:
A tree can be represented as a nested list: the list elements represent nodes, and a node is a pair of the node name and node children.
Your program takes as input a nested list of pairs, and should output a pretty tree.
Examples:
Here are four example test cases below
["stump",[]]

["trunk",[["branch",[["leaf",[]],["leaf",[]]]],["branch",[]]]]

[".",[["bin",[]],["usr",[["bin",[]],["local",[["bin",[]],["lib",[]]]]]]]]

["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]]

And these are the corresponding outputs
1
stump

2
trunk
├── branch
│   ├── leaf
│   └── leaf
└── branch

3
.
├── bin
└── usr
    ├── bin
    └── local
        ├── bin
        └── lib

4
kingdom
├── mineral
├── animal
│   └── dog
│       ├── schnauzer
│       └── whippet
└── vegetable
    └── cabbage

Notes:

If the characters │, ├, └, ─ are not conveniently available in your language, you may substitute with the ASCII characters |, +, L, - respectively.
You may assume there is one unique root node.  You may assume the input will be "nice", it doesn't matter what your program does if the input is not well-formed.
To avoid unfair advantages to any particular language, some flexibility in the input format is allowed within reason.  For example, specifying the nesting with parens () or braces {} is OK.  If it's more convenient for the node labels to be integers instead of strings, that's OK.  Extra whitespace in the input is OK, as long as it's not being used to define structure.  If you take the input as a string literal and parse it directly, that's OK.
No messing with the underlying structure of the tree!  E.g., you may not change how a leaf node is represented.
Tip: the representation used in the examples is valid json, so you can paste it into a json linter to better see the nesting.

Scoring:
This is code golf, shortest code wins.

Closely related. (Same output, different input.)

I'm not a regular on this site, if you think the question can be improved please comment or edit directly.  Thanks!

what is the exact input format? Is it a string or an object?

@Ludonope Whatever makes your code easier.  See note 3.  I expect most people will use an object, because writing a parser is probably not fun, but I don't want to discourage any possible interesting stack based approaches.

The characters  │, ├, └, ─ are conveniently available in most languages, but each one requires 3 bytes in UTF8, so using the ASCII gives a better score

Perl 5, 146 bytes
sub f{my$r=@_-1;my$p=$r?pop:[];while(my$n=shift){my($t,$c)=@$n;say$r?((map$_?'|   ':$"x4,@$p),@_?'+':L,'-- '):(),$t;f(@$c,[@$p,$r?!!@_:()])if@$c}}

Try it online!

Haskell, 159 bytes
With preprocessing of the input to fit the defined tree datatype (included in score) since trees can't be represented as a nested list.
data T=T[Char][T]
r=reverse;z=zipWith;a%b=a:cycle[b]
p(T s b)|k<-r$p<$>b=s:(concat$r$z(z(++))(("└── "%"    ")%("├── "%"│   "))k)
mapM putStrLn.p

Usage:
> mapM putStrLn.p $ T"kingdom"[T"mineral"[],T"animal"[T"dog"[T"schnauzer"[],T"whippet"[]]],T"vegetable"[T"cabbage"[]]]
kingdom
├── mineral
├── animal
│   └── dog
│       ├── schnauzer
│       └── whippet
└── vegetable
    └── cabbage

JavaScript (ES6), 123 125 bytes
Using 5 unicode graphic character, 3 bytes each. The char count is 115.
x=>(o=x[0],r=(l,p)=>l[0]&&l.map((x,i)=>r(x[1],p+'│ '[q=+!l[i+1]]+'   ',o+=`
${p+'├└'[q]}── `+x[0])),r(x[1],''),o)

Less golfed
l=>(
  o = l[0],
  r = (l,p)=> // recursive tree printer
      l[0] &&
      l.map((x,i)=>
             (
               q = +!l[i+1],
               o += `\n${p+'├└'[q]}── ` + x[0],
               r(x[1], p+'│ '[q]+'   ')
             )
      ),
  r(l[1],''),
  o
)

F=
x=>(o=x[0],r=(l,p)=>l[0]&&l.map((x,i)=>r(x[1],p+'│ '[q=+!l[i+1]]+'   ',o+=`
${p+'├└'[q]}── `+x[0])),r(x[1],''),o)

out=x=>O.textContent+=x+'\n\n'

;[["stump",[]]
,["trunk",[["branch",[["leaf",[]],["leaf",[]]]],["branch",[]]]]
,[".",[["bin",[]],["usr",[["bin",[]],["local",[["bin",[]],["lib",[]]]]]]]]
,["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]]
].forEach(t=>out(JSON.stringify(t)+'\n'+F(t)))

K (ngn/k), 96 bytes
` 0:4_'{r:o@x,y[1],"   ";(,x,(*y),"-- ",*z),/$[z@1;("+|"r/:-1_z@1),"L "r/:-1#z@1;""]}["";"  ";]@

Try it online!
Quite a shame that this took so long, but I'm glad that I stuck with the problem.
Recursive function which prints each line of the tree separately. ngn/k's json parser is used to get the array.
-6 bytes from coltim.
-1 from ngn.

I was able to trim 6 bytes with some incremental golfs.

Python 3, 110 109 bytes
Down to 109 thanks to att
def f(l,p='',a=0,o=0):
 x,c=l;print(p+(('+L'[o]+'-- ')*a)+x)
 for i in c:f(i,p+('| '[o]+'   ')*a,1,c[-1]is i)

Call as:
f(["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]])

To get output:
kingdom
+-- mineral
+-- animal
|   L-- dog
|       +-- schnauzer
|       L-- whippet
L-- vegetable
    L-- cabbage

This is my first code-golf, so I welcome any feedback or suggestions.  I ended up using flags for the recursive function to know when an element was the root node or when it was the last leaf of a node, allowing it to differentiate the prefix that needed to be applied.  I wanted to have the last argument for the recursive call originally be i==c[-1], but ran into an issue with the call
f(["trunk",[["branch",[["leaf",[]],["leaf",[]]]],["branch",[]]]])

where the two branches are equivalent but not identical, so a is call was necessary instead of ==.

c[-1]is i for -1

Python 2, 118 119 bytes
def f(x,q='',p='',r=''):
 m,w=x;l=len(w);print q+r+m
 for i in range(l):a=l-i>1;f(w[i],q+p,' |'[a]+'   ','L+'[a]+'-- ')

Call as:
f(["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]])

Outputs:
kingdom
+-- mineral
+-- animal
|   L-- dog
|       +-- schnauzer
|       L-- whippet
L-- vegetable
    L-- cabbage