text:
Alex is sometimes right
This challenge is to lift the spirits of our mod Alex A., who is usually wrong.

Suppose you have a friend named Alex who needs help with basic logic and math, specifically mathematical equivalence.
He gives you a list of equations of the form [variable] = [variable] where a [variable] is always a single uppercase letter A to Z (not a lowercase letter, not a number, nor anything else). There's one equation per line in the list except for a single line that only says therefore.
All the equations above the therefore are premises, facts that are assumed to be true. All the equations below the therefore are unverified propositions, facts that Alex is attempting to infer from the premises, and they may or may not be true.
For example, in this equation list the single conclusionary proposition A = C happens to be true:
A = B
B = C
therefore
A = C

It's your job to tell Alex if all of his propositions logically follow from the given premises. That is, you need to tell Alex if he is wrong or right in his conclusions.
Write a program/function that takes in a string of a list of equations as described and prints/returns
Alex is right

if all the conclusions follow logically from the premises, and otherwise outputs
Alex is wrong

if any conclusion does not logically follow from the premises.
The shortest code in bytes wins.
Be sure to watch out for these cases:

Variable always equals themselves. e.g.
B = A
therefore
A = A
X = X

results in Alex is right.
Variables with unknown relationships cannot be assumed to be equal. e.g.
P = Q
therefore
E = R

results in Alex is wrong.
When there are no equations after the therefore then the conclusions are vacuously true. e.g.
D = C
therefore
and
therefore
both result in Alex is right.
When there are no equations before the therefore then only self-equality can be inferred. e.g.
therefore
R = R

results in Alex is right, but
therefore
R = W

results in Alex is wrong.

More Examples
Alex is wrong cases: (separated by empty lines)
A = B
C = D
therefore
A = C

A = L
E = X
A = I
S = W
R = O
N = G
therefore
G = N
L = I
R = O
S = A
X = X
X = E

D = K
D = Q
L = P
O = L
M = O
therefore
K = L

A = B
therefore
B = C

Z = A
S = S
therefore
A = Z
A = A
S = A
A = S
Z = A
Z = A

K = L
K = X
therefore
X = P
L = X
L = P

therefore
A = B
B = C
A = C

therefore
A = A
B = B
C = C
D = D
E = E
F = F
G = G
H = H
I = I
J = J
K = K
T = I
L = L
M = M
N = N
O = O
P = P
Q = Q
R = R
S = S
T = T
U = U
V = V
W = W
X = X
Y = Y
Z = Z

A = B
B = C
C = D
D = E
E = F
F = G
G = H
H = I
I = J
J = K
K = L
L = M
M = N
N = O
O = P
P = O
Q = R
R = S
S = T
T = U
U = V
V = W
W = X
X = Y
Y = Z
therefore
A = Z

therefore
C = D
T = Y
A = Z

P = Q
therefore
E = R

therefore
R = W
Alex is right cases:
H = J
therefore
J = H

K = L
K = X
therefore
L = X

C = B
B = A
therefore
A = B

K = L
K = X
K = P
therefore
L = X
L = P
X = P

A = Y
Y = Q
Q = O
therefore
O = Y
O = A

C = C
therefore
C = C

A = B
B = A
therefore
A = B
B = A

A = B
B = C
C = D
therefore
A = A
A = B
A = C
A = D
B = A
B = B
B = C
B = D
C = A
C = B
C = C
C = D
D = A
D = B
D = C
D = D

therefore
A = A
B = B
C = C
D = D
E = E
F = F
G = G
H = H
I = I
J = J
K = K
L = L
M = M
N = N
O = O
P = P
Q = Q
R = R
S = S
T = T
U = U
V = V
W = W
X = X
Y = Y
Z = Z

D = I
F = H
J = M
therefore
M = J
D = I
H = F

A = B
B = C
C = D
D = E
E = F
F = G
G = H
H = I
I = J
J = K
K = L
L = M
M = N
N = O
O = P
P = Q
Q = R
R = S
S = T
T = U
U = V
V = W
W = X
X = Y
Y = Z
therefore
Z = A
F = R
G = I
W = L

A = B
B = C
therefore
A = C

B = A
therefore
A = A
X = X

P = P
C = G
M = C
therefore

D = C
therefore

therefore

therefore
R = R

PHP,  13 bytes Alex is wrong Verifies all test cases.

Hey, sometimes is better than never. ¯\(ツ)/¯

[tag:alex-is-wrong]

Also, -1 for lies

therefore\nTABS < SPACES --> Alex is right

Love to see a solution in prolog.

@DerFlatulator i think prolog is considered a loophole :p

@DerFlatulator I thought about it, but I don't know a good way to transform the input format into something that Prolog could make sense of... maybe someone who knows the language better could, though.

CJam, 49
"Alex is "qN%S{f{)er}(_el-}h;{)#},"wrong""right"?

Inspired from histocrat's Ruby solution. Try it online
3 bytes obliterated thanks to jimmy23013 :)
Explanation:
For each premise, the program replaces the first variable with the 2nd variable in the rest of the text. It then checks if there's any conclusion with different variables.
"Alex is "    first push the part we know
qN%           read the input and split into lines
S             push a space (initial no-op replacement string, see below)
{…}h          do-while
  f{…}        for each line and the replacement string
    )         take out the last character
    er        replace the remaining character(s) with that character
  (           afterwards, take out the first line
  _el         duplicate and convert to lowercase
  -           remove all the resulting characters from the line
               this removes all lowercase letters and non-letters
               "X = Y" becomes "XY" (new replacement string)
               and "therefore" becomes "" (ending the loop)
              this is the loop condition and is left on the stack every time
;             after the loop, pop the empty string (from "therefore")
{…},          filter the remaining (conclusion) lines using the condition block
  )           take out the last character
  #           find its index in the remaining string
               this is 0 (false) iff the first character is the same as the last
              afterwards, we have an array of lines with non-equal variables
"wrong"       push "wrong"
"right"       push "right"
?             choose "wrong" if the array was not empty, else choose "right"

Old version, 85
"Alex is "26,:A;{:i{{_A=_@-}g}%$~}:F;0q"= "-'t/Nf%~\{A\Ft:A;}/1>{F=}%-"right""wrong"?

This uses a union-find algorithm. Try it online

"Alex is "qN%S{f{)er}(_el-}h;{)#},"wrong""right"?.

I just read that last line as ‘This uses a unicorn-find algorithm’ … waitwot? xD

Alex is * wrong * right * ?

Ruby, 80 76 + 2 = 78
With command-line flags p0, run
gsub$1,$2%p=$`[/e/]while~/(.) = (?!\1)(.)/
$_="Alex is #{p ?:wrong: :right}"

Explanation:
This uses pure string manipulation. p0 reads the full input as a single string into the variable $_. Then, we repeatedly match that string against the regular expression /(.) = (?!\1)(.)/, which finds all strings of the form "X = Y" where X and Y aren't the same letter, and assigns X to $1 and Y to $2. When such a match is found, gsub$1,$2 replaces all instances of X with Y in the string. We also check whether this match occurred before or after the "therefore" with
$`[/e/]

If it occurred after, it's an unjustified claim and Alex is wrong. We track whether any such occurrences have happened using p=. The use of p as a tracking variable prevents things from breaking if the loop never hits even once, since p will return nil if it's never been assigned to.
As of this post, the CJam solution is longer. A proud, if no doubt fleeting moment.
Edit: Yup, quickly dethroned. Also, to finish the explanation, with the p flag the final value of $_ is output at the end of execution, so the last line is the output.

The sweetest moments are those before one's solution is slaughtered by an esolang.

The abuse of String#format to get both the gsub call and assignment into one expression is a pretty neat idea, +1!

CJam, 83 75 68 67 64 bytes
Thanks to Dennis for saving 1 byte.
"Alex is "q_elN--N/:$La/~{)-},\{__m*{:&},::^|}5*-"wrong""right"?

Test suite. The test cases are too long for a permalink, so simply copy them in from the question. Note that this is fairly slow - it takes a minute or two in the online interpreter. You can make it much faster by changing 5* to 2* in which case it will finish almost instantly and solve all but one test case.
Explanation
(Slightly outdated.)
The idea is to do a sort of "flood fill" of possible equalities and then remove all the equalities we obtained from the conclusion list. It can be shown that we need no more than 5 steps of the flood fill, because those would cover a distance (in the initial graph of inequalities) of 25 = 32 but the maximum distance is 25.
"Alex is " e# Push the string.
q          e# Read the input.
_elN-      e# Make a copy, convert to lower case, remove linefeeds. This gives us a string
           e# with all the characters we don't want from the input.
-          e# Remove them from the input. This leaves two upper-case letters on each line
           e# and an empty line between premises and conclusions.
N/         e# Split into lines.
La/        e# Split around the empty line.
~          e# Dump both halves on the stack.
{)-},      e# Remove any "A = A"-type equalities from the conclusions.
\          e# Swap with the premises.
{          e# Extend the premises 5 times...
  _Wf%     e#   Duplicate the premises and reverse each one, because = is symmetric.
  |        e#   Set union with the original premises.
  __m*     e#   Make two copies and get an array of every possible pair of premises.
  {:&},    e#   Select those which have at least one character in common.
  ::^      e#   For each such pair, take the mutual set difference, i.e. those characters
           e#   that are in only one of the strings.
  |        e#   Set union with the original premises.
}5*
-          e# Remove all the equalities we've obtained from the conclusions. If all
           e# conclusions were valid, the result will now be a empty array, which is falsy.
!          e# Logical not.
"wrong""right"?
           e# Select "wrong" or "right", respectively.

Constructing the transitive closure, eh? I'm not familiar with CJam, but it seems like the 5th generation of equalities might only be generated in one direction. If they are, you'd need one more iteration to reverse those equalities.

@user2357112 I believe they should be generated in both directions, because the first step adds all reverses of the input (or in the version that's golfed further, I sort all premise and conclusion equalities to begin with).

When you take the symmetric differences, though, do you get edges in both directions? (Or, in the further-golfed version, do the symmetric differences produce the edges in the needed direction?)

@user2357112 Since I'm processing the entire Cartesian product, I will get each pair of equalities in both orderings, which will result in both orderings of the drawn conclusion (The only reason I need to reverse explicitly, or sort the initial input, is that the original premises are not necessarily generated in this process, so they are not reversed by taking the set differences of the Cartesian product).

R, 183 192 bytes
I have modified my answer to address a limitation pointed out by user2357112. There is still an extremely small probability of calling Alex out when he is in fact right (which itself does not seem to happen very often if I understand the context of the challenge :-). I hope he won't mind.
i=grep("t",z<-scan(,"",,,"\n"))
cat("Alex is",if(eval(parse(t=c(paste(LETTERS,"=",1:26),sample(rep(head(z,i-1),1e3)),paste(c(TRUE,sub("=","==",tail(z,-i))),collapse="&")))))"right"else"wrong")

I need to de-golf this a bit:
lines = scan(, what = "", sep = "\n")
therefore_idx = grep("therefore", lines)
setup = paste(LETTERS, "=", 1:26)
premises = sample(rep(head(lines, therefore_idx - 1), 1000))
propositions = paste(c(TRUE, sub("=", "==", tail(lines, -therefore_idx))), collapse = "&")
things_to_evaluate = c(setup, premises, propositions)
boolean_result = eval(parse(text = things_to_evaluate))
cat("Alex is", if (boolean_result) "right" else "wrong")

For example, if the input is
A = B
B = C
therefore
A = C
B = C

it will first evaluate the setup:
A = 1
B = 2
...
Z = 26

then the premises
A = B
B = C

will be run 1,000 times each in a random order. This is to make sure ("almost sure") that all equalities are propagated. Finally, it will evaluate the propositions:
TRUE & A == B & B == C

If the premises are A = B, B = C, C = A, the values just cycle around forever. 26 rounds of evaluation aren't enough.

My failed logic... Thanks for the example, I'll have to work something else then.

I think fixed it, or almost...!

Haskell, 208 bytes
import Data.Equivalence.Persistent
c l=equate(l!!0)$last l
r=foldr(c)$emptyEquivalence('A','Z')
l#r=equiv r(l!!0)$last l
f x|(h,_:t)<-span((<'t').head)$lines x="Alex is "++if all(#r h)t then"right"else"wrong"

I'm offloading the work to the Data.Equivalence.Persistent module, which provides functions for manipulating equivalence classes. All left to do is parsing the input and calling functions which sometimes have too long names for proper golfing.
Usage example:
*Main> f "A = B\nB = C\ntherefore\nA = C"
"Alex is right"

*Main> f "A = B\nB = D\ntherefore\nA = C"
"Alex is wrong"

Python 2, 264 bytes
There's already a remarkable Python 3 answer by mbomb007. This answer steals flagrantly from that one (in particular the "Alex is wrriognhgt" trick).
And this answer is also significantly longer than that one...
Well, anyway, the idea in this answer is to maintain a dictionary of key-value pairs, where the keys are the 26 capital letter characters, and each key's corresponding value is the set of letters that are equivalent to the key.  (If all 26 letters were equivalent, then each key would have a set of 26 letters for its corresponding value.)
def a(s):
 d={C:set(C)for C in map(chr,range(65,91))};p,c=s.split('t');c,p=[x.split('\n')for x in[c[9:],p]]
 for u in p[:-1]:
    g,h=u[::4];y=d[g]|d[h]
    for v in y:
     for w in y:d[v]|=d[w];d[w]|=d[v]
 print'Alex is','wrriognhgt'[all(u[0]in d[u[4]]for u in c if u)::2]

(To save bytes, this answer mixes spaces and tabs, which is legal in Python 2.)
This code is really pretty efficient, because the dictionary is limited to a maximum possible size (26 by 26 as described above) which doesn't depend on the number of lines of input.
Now, as I was golfing this solution, I realized that I could save four bytes by using strings instead of sets for the dictionary values, by replacing
d={C:set(C)for C in map(

with
d={C:C for C in map(

Of course then you also have to replace (NOTE: DON'T DO THIS) the three instances of the set union operation | with string concatenation +, but that doesn't change the code length.  The result is that everything should still work just the same, except it won't eliminate duplicates like you do with sets (it'll just keep adding onto the end of the string).  Sounds OK--a little less efficient, sure, but 260 bytes instead of 264.
Well, it turns out that the 260-byte version is so inefficient that it caused a MemoryError when I tested it with
A = B
A = B
therefore
B = A

This was surprising to me.  Let's investigate the 260-byte "string concatenation" version!
Of course it would start out with the key-value pairs A:A and B:B (plus 24 others that don't matter). We'll write d[A] to mean the dictionary value corresponding to the key A, so at the beginning we'd have d[A] = A. Now, given the premise A = B, it would start by concatenating the values d[A]=A and d[B]=B to get y = AB.  Then it'd loop over this string twice: for v in AB: for w in AB:...
So, the first time through the loop, we have v=A and w=A. Applying d[v] += d[w] and d[w] += d[v] results in the following sequence of dictionaries:
{A:A, B:B}      (start)
{A:AA, B:B}     (d[A] += d[A])
{A:AAAA, B:B}     (d[A] += d[A])

Next, with v=A and w=B:
{A:AAAA, B:B}     (start)
{A:AAAAB, B:B}    (d[A] += d[B])
{A:AAAAB, B:BAAAAB}   (d[B] += d[A])

Next, v=B, w=A:
{A:AAAAB, B:BAAAAB}   (start)
{A:AAAAB, B:BAAAABAAAAB}     (d[B] += d[A])
{A:AAAABBAAAABAAAAB, B:BAAAABAAAAB}     (d[A] += d[B])

And v=B, w=B:
{A:AAAABBAAAABAAAAB, B:BAAAABAAAAB}     (start)
{A:AAAABBAAAABAAAAB, B:BAAAABAAAABBAAAABAAAAB}     (d[B] += d[B])
{A:AAAABBAAAABAAAAB, B:BAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB}     (d[B] += d[B])

The above sequence of steps would implement the single premise A = B, with the conclusion that A is equal to every letter in the string AAAABBAAAABAAAAB, while B is equal to every letter in BAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB.
Now, suppose that the next premise is A = B again.  You first calculate y = d[A] + d[B] = AAAABBAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB.
Next, you loop over this string twice: for v in y: for w in y:...
Yeah.  Maybe that wouldn't be a very efficient implementation.

My answer isn't "great" since it's invalid, but it was a noteworthy attempt. Too bad I couldn't get it to work.

@mbomb007 Huh, I'm sorry to hear that. (I did think you had a cool approach!) Since you objected to the word "great", I have substituted "remarkable". :)

Mathematica, 182
f[s_]:="Alex is "<>If[True===And@@Simplify[#2,#1]&@@(StringSplit[s,"\n"]/.{a___,"therefore",b___}:>StringSplit/@{{a},{b}}/.{x_,_,y_}:>Symbol[x<>"$"]==Symbol[y<>"$"]),"right","wrong"]

Works on string input, as per the challenge.
In[]:= f["A = B
B = C
therefore
A = C"]
Out[]= Alex is right

In[]:= f["D = K
D = Q
L = P
O = L
M = O
therefore
K = L"]
Out[]= Alex is wrong

You can lose 8 bytes by declaring f as a pure function, replacing Simplify[#2,#1] with #2~Simplify~#, and replacing StringSplit[s,"\n"] with #~StringSplit~"<actual newline>".

Good points! Also q=StringSplit; and then s/StringSplit/q/ for another 6 bytes or so saved. But in the end, this is not a good challenge for Mathematica I'm afraid, even though the logic character seemed a perfect fit.

Also, a___ and b___ can probably be changed to a__ and b__, and s=Symbol;.

a__ and b__ won't work if premises, propositions or both are empty though

Retina, 90 bytes
To run, place the following 12 lines of code in 12 separate files (+11 bytes counted for each file beyond the first). <empty> designates an empty file; \n designates a literal newline. Alternately, keep the \ns as they are, put all lines in a single file, and use the -s option. Make sure that all files use literal newlines, not Windows \r\n, and note the space at the end of the last line.
s+`^(.) = (.)(.*)\1
$1 = $2$3$2
)`^. .+\n
<empty>
^.+|(.) = \1
<empty>
^\n*$
right
^[^r]+
wrong
^
Alex is

How it works
The first replacement matches the first premise in the input, whenever the lhs of the premise occurs later on in the file. It replaces that later occurrence with the rhs of the premise. The + modifier ensures that the replacement is repeated until it doesn't match any more. Thus, if the first premise is A = B, all subsequent As in the file get transmuted into Bs.
The second replacement removes the first premise from the input, since we're done with it now. Then the ) modifier loops back to the first replacement, and repeats until there were no changes in a whole pass through the loop. This happens when all the premises have been substituted and removed, and the input starts with therefore.
The third replacement matches the first line of input (which is therefore) or anything of the form A = A, and deletes it. If all propositions are supported by the premises, all of them will match this form, so what remains should consist solely of newlines. The fourth replacement changes this into right. Otherwise, the fifth replacement changes everything remaining (which doesn't contain r since therefore was deleted) into wrong. Finally, the last replacement adds Alex is  at the beginning.

ES6, 128 bytes
Loosely based on the Ruby version.
r=s=>(m=/^[^e]*(.) = (?!\1)(.)/.exec(s))?r(s.replace(RegExp(m[1],'g'),m[2])):'Alex is '+(/(.) = (?!\1)/.test(s)?'wrong':'right')

Looks for any non-self-equality before the "therefore" and recurisvely replaces the variable throughout the string each time (this saves bytes over a while loop).

C, 240 bytes
#define V[v-65]
v[26];char*r[]={"wrong","right"};i=65;j;g(a){return a V^a?g(a V):a;}main(){char b[16];for(;i<91;++i)i V=i;while(gets(b)&&*b<99)b[0]V=b[4]V=b[0]V<b[4]V?b[0]V:b[4]V;while(gets(b))j|=g(*b)^g(b[4]);printf("Alex is %s\n",r[!j]);}

This works by combining values into set trees, so any equivalent values lead to the same set root. Ungolfed, with implicit types made explicit.
// Anything before `V` becomes an index into `v`, offset by -'A'.
#define V [v-65]
int v[26];
char* r[] = {"wrong", "right"};
int i=65;
int j;
// Finds a set identifier for a by recursing until some index points to itself.
int g(int a) {
    return a V ^ a
           ? g(a V)
           : a;
}
int main() {
    char b[16];
    // Initialize all entries to point to themselves.
    for(; i < 91; ++i)
        i V = i;
    // For each premise "A = B", set the entries for A and B to point to the
    // smaller of their current values. This exits after reading "therefore"
    // as 't' > 99.
    while (gets(b) && *b < 99)
        b[0]V = b[4]V = b[0]V < b[4]V
                        ? b[0]V
                        : b[4]V;
    // For each conclusion "A = B", OR j with non-zero if the set identifiers
    // for A and B are different.
    while (gets(b))
        j |= g(*b) ^ g(b[4]);
    printf("Alex is %s\n", r[!j]);
}

180 bytes
This shorter version works for all cases from the OP, but for some other inputs incorrectly claims Alex is wrong. It uses a similar approach, but for each premise simply sets the second entry to the current value of the first entry. When comparing, it looks only at exact values instead of searching up a tree.
v[26];*V=v-65;char*r[]={"wrong","right"};i;j;main(){char b[16];for(;i<26;++i)v[i]=i;while(gets(b)&&*b<99)V[b[4]]=V[*b];while(gets(b))j|=V[*b]^V[b[4]];printf("Alex is %s\n",r[!j]);}

An example input for which this fails:

A = B
  C = B
  therefore
  A = C

05AB1E, 32 bytes
…±º€ˆ „–Ñƒ©#|€á[ćD.l#`:}\€ËPè«.ª

Inspired by @aditsu's CJam answer.
Try it online or verify all test cases.
Explanation:
…±º€ˆ      # Push dictionary string "alex is "
„–Ñƒ©      # Push dictionary string "wrong right"
     #     # Split by spaces: ["wrong","right"]
|          # Push all input-lines as list
 €à        # Only leave the letters of each line
   [       # Start an infinite loop:
    ć      #  Extract the head of the list; pop and push remainder-list and head separately
     D     #  Duplicate the head
      .l   #  If it's a lowercase string:
        #  #   Stop the infinite loop
    `      #  Push both letters in the string to the stack
     :     #  Replace all these letters in the remainder-list
 }\        # After the infinite loop: discard the duplicated "therefore"
   €       # For each letter-pair in the remainder list of condition-lines:
    Ë      #  Check if both letters are equal (1 if truhy; 0 if falsey)
   P       # Check if everything was truthy by taking the product
    è      # Use this to index into the earlier ["wrong","right"]-list
     «     # Append it to the "alex is " string
      .ª   # Sentence capitalize it
           # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why …±º€ˆ  is "alex is " and „–Ñƒ© is "wrong right".

bash + awk + SWI-Prolog, 167 bytes
head -n1 <(awk '/therefore/{s=1;next};{if(s)print"?=("$1","$3")";else print};END{print"write(\"Alex is right\");write(\"Alex is wrong\"). halt."}' -|paste -sd ,|swipl)

Try it online!
Originally, this was just going to be a Prolog answer, but the tools I could find to actually transform the input format into something usable were limited enough that I decided to do that part of it in bash, even though I had next to no experience doing anything in bash, and had never even touched awk. I ended up spending enough hours on it to want to post it even after it grew into this 167-byte, barely golfed at all monster.
Essentially, what the awk program does is take the input from stdin, erase the line with therefore, replace every A = B after it with ?=(A,B), and append write(\"Alex is right\");write(\"Alex is wrong\"). halt.. Then, paste -sd , replaces every newline but the last with a comma, transforming it into a valid two queries to the SWI-Prolog shell, which are then run with the printed result being truncated to one line by head -n1, which requires <(...) instead of a pipe for reasons beyond my understanding. All this, just to use a builtin!


text:
Simulate a game of Craps
Craps is a fairly simple dice game often played in casinos. Even if you aren't a gambler (which I'm not), it's still a fairly interesting game. Here's the rules:
At the start of a game of Craps there's what is called the come-out round. The player rolls two d6s (six-sided die) and the two die rolls are added. If the result is 7 or 11, the person automatically wins (this is known as a natural). If the result is 2, 3 or 12 the person automatically loses (this is known as crapping out). Otherwise, the result is set as the point for the point round.
After this, the point round begins. During the point round, the player must continuously roll 2 d6s until the person rolls a 7 or his/her point from the previous round. If the person rolls a 7, they lose. If they roll their point, they win.
Challenge
Implement a simple program that simulates a game of craps. If the person rolls a natural or a crap-out during the come-out round, the program should output "Natural: " or "Crapping out: " followed by the die-roll and then exit. Otherwise, it should output "Point: " followed by the point. Then, during the point round, it should output every die-roll until a 7 or the point is reached. If the person wins, it should output "Pass"; if they lose it should output "Don't Pass".
Reference Implementation
Groovy, 277 bytes
def a={return Math.random()*6+1};int b=a()+a();(b<4||b==12)?{println"Crapping out: "+b}():{(b==7||b==11)?{println"Natural: "+b}():{println"Point: "+b;for(;;){int x=a()+a();println x;(x==7)?{println"Don't Pass";System.exit(0)}():{if(x==b){println"Pass";System.exit(0)}}()}}()}()

Try it online.
Sample outputs
Natural: 7
Crapping out: 3
Point: 9
4
8
11
9
Pass

and
Point: 5
3
7
Don't Pass

This is code-golf, so shortest code wins.
(DISCLAIMER: This challenge is not intended to promote gambling in any way. Remember, the house always wins.)

You can't make your program shorter by picking a random number between 1 and 12 for the die roll; it must be two numbers picked between 1 and 6. - What about picking a random value in [1, 12] from a distribution that is identical to adding two uniform random values in [1, 6]?

@Mego Whoa, old challenge. Yes that would be fine. I think that warning was mostly just to make sure people realized that a uniform distribution between [1, 12] isn't the same as a 2d6. I'll rewrite it a little bit.

Ruby 164
Pretty straightforward. Interesting features:
The crapping out cases are summarised as r%12<4 and the remaining natural cases are summarised as r%4==3.
The initial string is stored in c and further rolls are taken only if this is later alphabetically than the single letter ?P (which only occurs for Point.)
f=->{rand(6)+rand(6)+2}
s=0
r=f[]
print c=r%12<4?'Crapping out':r%4==3?'Natural':'Point',": #{r}
"
c>?P&&(until s==r||s==7
p s=f[]end
print s==7?"Don't ":"","Pass")

Love the way how you check for the remainder instead for 2,3,7,11 or 12 seperatly!

Python 3, 190 bytes
from random import*
r=randrange
p=print
a=r(5)+r(5)+2
c=890145//3**a%3
p(['Point:','Crapping out:','Natural:'][c],a)
if c<1:
 while 7!=c!=a:c=r(5)+r(5)+2;p(c)
 p(['Pass',"Don't pass"][c==7])

This is based on Celeo's answer; I replaced some lengthy conditionals with a magic number that encodes a LUT for each number, reused a variable, and did a few other miscellaneous golfs. Still room to golf; it's probably possible to get under 170.
I didn't try to use Python 2, so I don't know if it would be shorter.

Care to explain how you got that magic number and how it works?

Python 2, 226 224 bytes
First pass and there's a lot of code there:
from random import*
r=randrange
a=r(5)+r(5)+2
if a in[7,11]:print'Natural:',a
elif a in[2,3,12]:print'Crapping out:',a
else:
 print'Point:',a
 b=0
 while b not in[7,a]:b=r(5)+r(5)+2;print b
 print'Pass'if b-7else"Don't pass"

Thanks to Mego for 2 bytes!

Few issues with this. It doesn't print out "Point: " followed by the number if the roll wasn't a natural or a crap. Also, there should be a space between the : and the number.

Whoops! Fixed not printing 'Point: #'. In the output, there is a space.

Ah OK. I don't use Python very much anymore so I was uncertain about how the ,a works.

I golfed your code down to 198 in Python 3, which is 192 in Python 2. Do you want the suggestions, or should I post my own answer?

@ThomasKwa If you put a bunch of work into it, post as a separate answer so you can get some rep for it.

@Mego Thanks for the suggestion!

C99, 366 312 293 277 bytes
This is my first post here, so I'm going to guess that this can be improved by a lot.
#include<stdlib.h>
#include<time.h>
#define r rand()%6+1
#define p printf(
main(c,s){srand(time(0));s=r+r;int*a=s==7||s==11?"Natural:%d":2-s||3-s||12-s?0:"Crapping out:%d";if(a){p a,s);return 0;}p"Point:%d\n",c=s);do p"%d\n",s=r+r);while(7-s&&s-c);p(7-s)?"Pass":"Don't pass");}

Expanded Version
#include<stdlib.h>
#include<time.h>
#define r rand()%6+1
#define p printf(
main(c,s){
    srand(time(0));
    s=r+r;
    int*a=s==7||s==11?"Natural:%d":2-s||3-s||12-s?0:"Crapping out:%d";
    if(a) {p a,s);return 0;}
    p"Point:%d\n",c=s);
    do p"%d\n",s=r+r);
    while(7-s&&s-c);
    p(7-s)?"Pass":"Don't pass");
}

As you can see, there's a good amount of redundancy here that can most likely be done away with.
Credits to @Mego for helping to make this smaller.

As long as it compiles somewhere, you're good.

@Mego thanks for pointing that out, that managed to get rid of 19 bytes.

Got some more off getting rid of a and b and also using the subtraction method along with ternary operators.

PHP 230 228 218 199 192 188 Bytes
186 bytes without the <?
<?$a=rand(1,6)+rand(1,6);$a%4==3?die("Natural: $a"):$a%12<4?die("Crapping out: $a"):print"Point: $a
";while(1){($b=rand(1,6)+rand(1,6))==7?die("Don't Pass"):$b==$a?die("Pass"):print"$b
";}

First attempt at code golf! Not sure if using </br> would be allowed though? As this would not work in a console (as a new line). Let me know if this is not allowed and will alter my code.
EDIT (16-8-16): After getting better at codegolf I noticed some possible improvements. This still works using the command line interface. Replaced </br> with an hard enter.

Natural is spelt "Natural" and not "Naturel".

Changed it. Thanks

Javascript 262
var r=(x=>Math.floor(Math.random()*6+1)),a=r()+r();if(a<4||a==12){alert("Crapping out: "+a)}else if(a==7||a==11){alert("Natural: "+a)}else{alert("Point: "+a);while(1){var b = r()+r();if(b==a){alert("pass");break}if(b==7){alert("dont't pass");break}alert(""+b)}}

PowerShell, 181 183 179 178 167 165 bytes
-10 bytes thanks to mazzy
-2 bytes thanks to Xcali

switch -r($z=&($x={(random 6)+(random 6)+2})){'7|11'{"Natural: $z"}'2|3'{"Crapping out: $z"}default{"Point: $z"
do{($m=&$x)}until($m-in7,$z)"Don't "*!($m-7)+'Pass'}}

Try it online!
Unrolled version:
#Switch using regex on $z which is...
#&($x={...}) first assigns $x to a scriptblock then calls it, saving the return to $z
switch -r($z=&($x={(random 6)+(random 6)+2})){
    '7|11' {"Natural: $z"}
    '2|3' {"Crapping out: $z"}
    default{
        "Point: $z"

        #Call the diceroll scriptblock until you Pass,
        #while pushing each roll to output
        do{($m=&$x)}
        until($m-in7,$z)
        "Don't "*!($m-7)+'Pass'
    }
}

There's a few less sticking points now that the list-building logic has been rebuilt into a switch. I think it's still a pretty alright approach. +2 bytes fixing a bug.

awesome! shorten it up to 178 bytes

I think the condition -notin (7,$z) is not relevant tu the rule During the point round, the player must continuously roll ... the previous round. Now the loop finish when $m equals to 7 or the first round.

@mazzy That is a wording issue in the question. There's only two rounds. You set the Point only once in the Come-out round and that is your target number for the entire Point round. The previous round refers to the Come-out round

thanks. 168 bytes

@mazzy Dang, I always forget about regex switches. Good stuff

You should be able to take two more off by removing the 1? from your craps regex.

Perl 5, 140 bytes
sub d{1+int rand 6}say$"=($p=&d+&d)%12<4?"Crapping out":$p%4-3?Point:Natural,": $p";if($"gt O){say$_=&d+&d until/7|$p/;say"Don't "x/7/,Pass}

Try it online!

R, 197 bytes
 r=sum(sample(6,2,T));if(r%%12<4)cat("Crap Out",r)else if(r%%4==3)cat("Natural",r)else{cat("Point",r);while(T){cat("",q<-sum(sample(6,2,T)));if(q==7){cat(" Don't");break};if(q>r)break};cat(" Pass")}

Ungolfed
r=sum(sample(6,2,T))
if (r%%12<4)  {
    cat("Crap Out",r)
} else if (r%%4==3) {
    cat("Natural",r)
} else {
    cat("Point",r)
    while (T) {
        q = sum(sample(6,2,T))
        cat("",q)
        if (q==7) {
            cat(" Don't")
            break
        }
        if (q>r) break
    }
    cat(" Pass")
}

Pyth, 108 bytes
p|K?}J+OS6OS6,7 11"Natural"?}J[2 3 12)"Crapping out"k"Point"+": "JI!KW!}Z,7JIq7=Z
+OS6OS6=K"Don't "))+K"Pass

Try it online!
First pass, can probably find a few savings.

Runic Enchantments, 151 bytes
R}}6'RA6'RA2++{{B͍
00B:7=S:b={+?\"Natural: "@>
pping out: "@\:2=}:3=}:c={{++?/"Cra
{:}≠   ?\ 6?;$$k\/ak$00B:$:7≠?\
"Don't "R"Pass"a/\$:$" :tnioP"\

Try it online!
After fixing a bug regarding random numbers (it was re-seeding every time 'RA was called, and the seed was system time, resulting in massive runs of repeated values) this works correctly.
Explanation
Entry is on the second line, as the first line up until B͍ is a function for rolling two dice and summing them.
Program flow, with some edge-wrapping and curled redirections unrolled for readability
   R}}6'RA6'RA2++{{B͍                      Roll 2, sum, return
   >00B:7=S:b={+?\                        Entry, make first roll, compare to 7 and 11.
                  "Natural: "@            If true, print "Natural: " and the value, else go down
                 \:2=}:3=}:c={{++?/       Compare to 2, 3, and 12.
"Crapping out: "@                         If true, print "Crapping out: " and the value, else go up
                     \$:$" :tnioP"\       Print "Point: " and value (IP is travelling RTL)
                     /ak$00B:$            Print newline, roll, print
:7≠?\                                     Compare to 7
    \"Don't "R"Pass"ak$$;                 If equal, print a newline and "Don't Pass"
     {:}≠   ?\                            Else compare to initial roll.
             R"Pass"ak$$;                 If equal, print a newline and "Pass"
              6?......ak$00B              Else return to roll loop by printing a newline
                                              and rolling again (. are skipped instructions)

There are only 4 NOP instructions ({:}≠...?\.6?) that would be very difficult to remove due to the space required on other lines (Namely the length of the "Don't " string).

source: Stack Exchange

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/

sort: votes


text:
IT'S CAPS LOCK DAY
OCTOBER 22 IS INTERNATIONAL CAPS LOCK DAY! UNFORTUNATELY, SOME DO NOT RECOGNIZE THE GLORY OF THE ALMIGHTY CAPS LOCK. THEY SAY IT SEEMS "OBNOXIOUS" OR "LIKE SHOUTING" OR SOME NONSENSE. IN ORDER TO CONFORM TO THESE OBVIOUSLY ILLOGICAL AND INANE COMPLAINTS, PLEASE WRITE ME A PROGRAM THAT TURNS NORMAL TEXT INTO "SENSIBLE" OR "REASONABLE" TEXT TO MAKE PEOPLE STOP COMPLAINING.
Description
The input and output for your solution will both be strings that contain only printable ASCII characters.
The input string will contain zero or more caps lock runs. A caps lock run (or CLR for short) is defined as the following:

The CLR must contain no lowercase letters (a-z), except as the first character of a word.

A word, for the purposes of this challenge, is a sequence of non-spaces. So, PPCG, correcthorsebatterystaple, and jkl#@_>00()@#__f-023\f[ are all considered words.

The CLR must also contain at least one space; hence, it must be at least two words.
Each of the words in the CLR must contain at least two letters (A-Za-z).

Note that this refers to the CLR taken by itself, without any surrounding characters that may not have been included in the CLR. For example, foO Bar is not a CLR because the string O B by itself has words with less than two letters.

CLRs should be parsed "greedily"—that is, you should always find the longest CLRs possible.
Once you have identified all of the CLRs in the input string, swap the case of all letters inside of the CLRs and output the resulting string.
Test cases
The first line is input, and the second is output. Bolded portions of the input are substrings that are considered CLRs.
CAPS LOCK IS THE BEST!
caps lock is the best!
I really LOVE pROGRAMMING pUZZLES AND cOde Golf!
I really love Programming Puzzles and Code Golf!
This is a challenge on PPCG. This is a test CASE. TEST
This is a challenge on PPCG. This is a test case. test
LorEM iPSUM DOLoR sIT amet, conSECTETur ADIPISciNG eLIT. MAECENAS iD orci
Lorem Ipsum doloR sIT amet, conSECTETur ADIPIScing Elit. maecenas Id orci
;'>}{/[]'"A*(389971(*(#$&B#@*(% c'>#{@D#$! :,>/;[e.[{$893F
;'>}{/[]'"a*(389971(*(#$&b#@*(% C'>#{@d#$! :,>/;[e.[{$893F
iT'S cAPS lOCK DAY!!! cELebraTE THis WONDERFUL key
It's Caps Lock day!!! Celebrate this WONDERFUL key
aBcDE fGHIj KLmNO pQrST (uVwXY) ZZ___Zz__Z
aBcde Fghij KLmno PqrST (uVwxy) zz___zz__Z
#aA# aA
#aA# aA
Rules

You may assume that the input will never contain two or more spaces in a row, and that it will never contain a leading or trailing space.
20% bonus (multiply your code length by .8) if your entire code is a CLR. ;) (mostly just for fun, since it's unlikely that the winning submission will have this bonus)
This is code-golf, so the shortest code in bytes wins.

Please, stop shouting.

Also, for test case #3, wouldn't the capitalized PPCG get lowercased too? (PPCG. T contains a space)

@Dr.EmmettBrown See the last bullet point under Description.

CAPS LOCK IS HOW I FEEL INSIDE RICK. ALL THE TIME.

@Dennis I read that in Morty's voice (from Rick and Morty), b/c he's talking to "Rick".

The a in Programming Puzzles and Code Golf! should be capitalized, I think.

@isaacg yep, that was a typo

"bonus points for your code being a CLR" just makes me want to do this in LOLCODE...

@TheDoctor seems not because "Each of the words in the CLR must contain at least two letters" and second word T has only one.

The third example of a word, jkl#@_>00()@#__f-023\f[: that's already CJam, right?

"correct horse battery staple" would be a strong password...

CJam, 100 86 83 81 bytes
Ml{_,),{1$<_S/(4$!>\1f>s+_eu=*S%_{'[,_el^:Af&s,2<},!*1>},_{W=/(AA26m>er}{;(}?\s}h

Try this fiddle in the CJam interpreter or verify all test cases at once.
Algorithm

Identify the longest possible CLR that starts with the first character.
If it exists, swap its case, print it, and remove it from the beginning of the string.
Else, remove a single character from the beginning of the string, and print it unmodified.
If there are more characters left, go back to step 1.

How it works
Ml         e# Push an empty string and a line from STDIN.
{          e# Do:
  _,       e#   Copy the string on the stack and compute its length (L).
  ),       e#   Push [0 ... L].
  {        e#   Filter; for each integer I in that array:
    1$<    e#     Copy the string and keep its first I characters.
    _S/    e#     Push a copy and split at spaces.
    (      e#     Shift out the first word.
    4$!    e#     Push the logical NOT of the fifth topmost item of the stack.
           e#     This pushes 1 for the empty string on the bottom, and 0
           e#     for non-empty strings and printable characters.
    >      e#     Remove that many characters from the beginning of the first word.
           e#     This will remove the first character iff the string on the
           e#     stack is the entire input. This is to account for the fact that
           e#     the first word is not preceded by a space.
    \1f>   e#     Remove the first character of all remaining words.
    s+     e#     Concatenate all of them.
    _eu=   e#     Convert a copy to uppercase and check for equality.
    *      e#     Repeat the I characters 1 or 0 times.
    S%_    e#     Split at runs of spaces, and push a copy.
    {      e#     Filter; for each non-empty word:
      '[,  e#       Push the string of all ASCII characters up to 'Z'.
      _el  e#       Push a copy and convert to lowercase.
      ^    e#       Perform symmetric difference, pushing all letters (both cases).
      :A   e#       Store the result in A.
      f&s  e#       Intersect A with each character of the word. Cast to string.
      s    e#       This removes all non-letters from the word.
      ,2<  e#       Count the letters, and compare the result to 2.
    },     e#     If there are less than 2 letters, keep the word.
    !      e#     Push the logical NOT of the result.
           e#     This pushes 1 iff all words contain enough letters.
    *      e#     Repeat the array of words that many times.
    1>     e#     Remove the first word.
  },       e#   Keep I if there are still words left.
  _{       e#   If at least one I was kept:
    W=     e#     Select the last (highest) one.
    /      e#     Split the string on the stack into chunks of that length.
    (      e#     Shift out the first chunk.
    AA26m> e#     Push "A...Za...z" and "a...zA...Z".
    er     e#     Perform transliteration to swap cases.
  }{       e#   Else:
    ;      e#     Discard the filtered array.
    (      e#     Shift out the first character of the string on the stack.
  }?       e#
  \s       e#   Swap the shifted out chunk/character with the rest of the string.
}h         e# If the remainder of the string is non-empty, repeat.

How it works: plays 20 E# notes on the piano.

I've added a few more details. :P

Perl, 96 82 80 bytes
-pe'$y=qr/[^a-z ]{2,}|\b\S[^a-z ]+/;s#$y( $y)+#join$,,map{uc eq$_?lc:uc}$&=~/./g#eg'

Passes all tests. Assumes input from STDIN, prints to STDOUT.
How it works:

setup a regex ($y) that matches

at least two non-lowercase, non-whitespace characters OR
a word boundary, followed by a non-whitespace character, followed by one or more non-lowercase, non-whitespace characters

match multiple instances of space-separated strings that match $y, use s/// to invert case

I'm sure there's room for improvement. If there is a way to get rid of the whole join-map-split deal there may still be a chance to qualify for the bonus :)

You can save a few bytes by using a-z instead of [:lower:]. Also, -pe is usually counted as 1 byte, and the single quotes as zero bytes.

@Dennis : Thanks for the suggestion! That allowed me to simplify the code somewhat - down to 81 as per your guidelines about Perl one-liners

This answer is invalid, since it doesn't pass the last test case (recently added courtesy of Dennis).

Javascript, 193

decapslock =

a=>a.replace(/(^[a-z][^a-z ]+|[^a-z ]{2,})( [a-z][^a-z ]+| [^a-z ]{2,})+/g,b=>b.split` `.some(f=>f.split(/[a-z]/i).length<3)?b:b.split``.map(e=>e==(E=e.toUpperCase())?e.toLowerCase():E).join``)

<input placeholder='sAMPLE tEXT' oninput="document.getElementsByTagName('p')[0].innerText=decapslock(this.value)" />

Explanation:
a=>a.replace(/* giant regex */,
  b=>
    b.split` `.some(
      f=>
        f.split(/[a-z]/i).length < 3   // check for 2+ letters
    )
      ? b                              // .some() immediately returns true if it's invalid
      : b.split``.map(                 // otherwise it's valid, so flip case
          e=>
            e == (E = e.toUpperCase()) // is it uppercase?
              ? e.toLowerCase()        // change it to LC
              : E                      // change it to UC, which was already done for
                                       // the case check
            ).join``
        )

(
^[a-z][^a-z ]+ // check for a CLR starting at the beginning with LC
|
[^a-z ]{2,}    // check for a CLR that begins in the middle of a word or starts at the
               // beginning with UC
               // in both cases, 2+ letters are required
)
(
 [a-z][^a-z ]+ // check for the next word of the CLR, starting with LC
|
 [^a-z ]{2,}   // check for the next word of the CLR, starting with UC
)+             // check for 1 or more next words

This answer is invalid, since it doesn't pass the last test case (recently added courtesy of Dennis).

Argh, the fix added tons of bytes to this. But, it's fixed

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


text:
Humans hate pows and programmers hate humans - let's connect them!
Background
The task is simple but every programmer has implemented it at least once. Stackoverflow has a lot of samples, but are they short enough to win?
Problem story
You're a grumpy programmer who was given the task of implementing file size input for the users. Since users don't use bytes everyone will just enter "1M", "1K", "3G", "3.14M" - but you need bytes! So you write a program to do the conversion.
Then your manager hands you dozens of user reports with complaints about weird large numbers in file size input. It seems you'll need to code the reverse conversion too.
What do you need to do?
Here's the trick: you should implement two-way conversion in single piece of code. Two separate functions used as needed? Nah, that's too simple - let's make one, short one!
For the purposes of this challenge, "kilobyte" means 1024 bytes, "megabyte" means 1024*1024 = 1048576 bytes, and "gigabyte" means 1024*1024*1024 = 1073741824 bytes.
Test data
Input   -> Output
5       -> 5
1023    -> 1023
1024    -> 1K
1K      -> 1024
1.5K    -> 1536
1536    -> 1.5K
1048576 -> 1M
1M      -> 1048576

Rules

Test value will not exceed 2*1024*1024*1024 or 2G
The following postfixes are used by users: K for kilobytes, M for megabytes, G for gigabytes
Code is not required to work with negative numbers
Do not use any external libraries (e.g. BCMath in PHP) besides bundled ones (e.g. math.h)
Standard loopholes are disallowed
Code should not produce anything on stderr
Your program can take input and produce output using [standard methods].(http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)

Usually programs don't take variable input and output...

And why do you want us to convert bytes back to postfixed numbers? Your question stated that "you need bytes!"

@Dr.EmmettBrown: In real application it wouldn't make sense, but hey - it's code-golf. If number is <1024 you should leave it as-is, for 1024 you should convert to 1k, for 1k you should convert to 1024 ;)
I slightly edited rules regarding data i/o.

1024 is not a kilobyte (k); it's a kibibyte (KiB). Similarly, 1048576 is not a megabyte (M); it's a mebibyte (MiB).

@killer129 As it stands this two-way conversion would be a little ridiculous.

@ToddLehman: As for lowercase "k" I have to agree with you, but KB/MB/GB are commonly used to denote size of files. Why? Probably due to JDEC.

@Dr.EmmettBrown: Implementing it one way is easy - try to do it two-way ;)

Despite perhaps not being useful for real life, this challenge is well-specified and a non-trivial task. I for one think it just needs a little more polish on the wording. FYI, @kiler129, for future challenges you can get all these kinks worked out ahead of time by posting in the Sandbox first.

@DLosc: Thank you for recommendation - I didn't know about it :) It's 1:21AM in my tz and I was implementing [again] conversion from and to human readable values and "the magic programmer vortex" sucked me into THAT weird thinking "what if..." ;)

I edited your post for grammar and clarity. The main thing I think you need to decide is the I/O methods. As TheDoctor said, variables aren't a default I/O method. You're free to override those defaults for your question if you like, but I'd say there's no reason to. However, I'll leave that decision up to you.

Possible duplicate: http://codegolf.stackexchange.com/questions/51928/format-the-given-number-of-bytes-to-a-human-readable-format

@DLosc: I appreciate you since english is not my mother tongue. After little thinking and reading poll you linked I think it's safer to stick with default one, since it's easier for everyone to verify code and there's no confusion if variable counts etc.

@DigitalTrauma: Actually I seen that challenge and it was easy - I raised the bar ;)

@kiler129 — Sure, those were common in the 70s and 80s. But the new IEC units have been around for 17 years now (since 1998) and a US NIST requirement for 7 years (since 2008), so people should really be using them instead of the old units (which were always wrong anyway). Just my 2¢.

how many decimal digits do you want? 1024 = 1k, 1025 = 1.0 k or 1k? 1526398 = 1.45568656921 M....

There exist different sets of standards. Some still use the power-2 convention on the base-10 prefixes - as such, I would say that it is excusable here.

So we should implement function or whole program?

@Zereges: Only the conversion algorithm which from given input produces correct output.

Can we take string in one way and number another way?

Python 2, 204 190 bytes
This is my first ever codegolf.
s=raw_input()
p=' KMG'
if s[-1]<='9':
 e=0;r=int(s)
 while r>=1024:r/=1024.0;e+=1
else:
 e=p.index(s[-1]);r=eval(s[:-1])
 while e>0:r*=1024;e-=1
print(`r`if r%1!=0 else`int(r)`)+p[e].strip()

-25 bytes. works by replacing the loop with the power operator (**) and changing the r%1!=0 to r%1

Pip, 60 bytes
l:" KMG"Fi1,4Ia>=Y1024x:(a/:y).l@ix|aR`.+([KMG])`_*y**(l@?B)

Takes input from the command line (assigned to a variable) and outputs to stdout.
Ungolfed version:
l : " KMG"
Y 1024
F i 1,4
 I a>=y {
  a /: y
  x : a . l@i
 }
x | a R `.+([KMG])` {a*y**(l@?b)}

Algorithm:

For i from 1 through 3:

If a >= 1024, this is a byte value that needs to be converted to a larger unit:

Divide a by 1024
Set x to be the current value of a concatenated with the current unit

If x was set by the previous step, output it. Otherwise, a was less than 1024 (with a possible unit suffix), so:

Do a regex replacement with a function on a if it has one of KMG at the end: translate the letter to the appropriate power of 1024 and multiply the number by the result.
For values less than 1024 without a suffix, this leaves the value unchanged.

What is pip? Can you put a link or something?

Sure! Pip is a golfing language that I made.

JavaScript, 144 106 bytes
n=>((G=(M=(K=2<<9)<<10)<<10),+n>0?n<K?n:n<M?n/K+'K':n<G?n/M+'M':n/G+'G':eval(n.replace(/[KMG]/,m=>'*'+m)))

This can definitely be shortened, and will do later. Just wanted to get something ugly out there ;)

C 206 183 bytes
Got rid of as much as I could.
#include<stdlib.h>
main(y,z)char**z;{char*i="KMG";float f=atof(*++z);while(*++*z)y=**z;if(y>57){do f*=1024;while(y!=*i++);y=0;}else while(f>1023)y=*i++,f/=1024;printf("%.1lf%c",f,y);}

Output
Input: 1023
Output: 1023.0

Input: 1M
Output: 1048576.0

Input: 1048576
Output: 1.0M

Explanation
#include <stdlib.h> //needed for atof()
main(y,z)char **z; //y will hold the size indicator
{
    char *i="KMG";//holds the characters for the size indicators
    float f=atof(*++z); //get the number from the string

    while(*++*z) //loops through the string
        y=**z;
    if(y>57) //57 is ASCII for 9
    {
        do f*=1024;
        while(y!=*i++); //loop through until we hit the correct size
        y=0;
    }
    else
        while(f>1023) //loop through until number is less than 1024
            y=*i++,f/=1024;
    printf("%.1lf%c",f,y); //print number and size character
}

136B

@l4m2, nice, you could edit that into the answer if you want (or post your own)

Python2 199 bytes
this is silly but it works (ignoring the decimal precision question) as long as you have dozens of gigabytes of RAM. dont run it otherwise, your machine might freeze and lockup. The first thing it does is allocate a 2gigabyte array of integers.
n,bn={'K':2**10,'M':2**20,'G':2**30},range(2**30+1)
for i in bn:
 for j in 'KMG':
  if i>=n[j]: bn[i]=str(float(i/n[j]))+j
def f(i):
 if i[-1] in 'KMG': return n[i[-1]]*float(i[:-1])
 return bn[int(i)]

JavaScript (Node.js), 91 bytes
f=(n,m)=>n<1024?n+['.KMG'[m]]:n>0?f(n/1024,-~m):eval(n.replace(/.$/,'*32**$&',K=2,M=4,G=6))

Try it online!

@tsh If you use parseFloat(as there's case 1.5K they're same length)

Ruby -nl, 100 bytes
~/.$/
i,n,s,k=0,$_.to_f,' KMG',1024
$&<?A?((n/=k;i+=1)until n<k):n*=k**(s=~/#$&/)
print n,s[i].strip

Try it online!

C (gcc), 114 bytes
*i=L"KMG",d;c;main(S){float f;for(scanf(S="%f%c",&f,&c);c?f*=1024,c-*i++:f>1023?f/=1024,d=*i++:0;);printf(S,f,d);}

Try it online!
Thank ceilingcat for -11 bytes

@ceilingcat Fail on 512, output inf

@ceilingcat First argument of main is 1, but now the arg has its use

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


text:
Evaluating the score based from a chess FEN string
Challenge
Forsyth–Edwards Notation (FEN) is a standard notation for describing a particular board position of a chess game. Your challenge is to evaluate the score using the FEN string. This is an example of a FEN string:
5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8

Using this string, you can calculate the material score for each color with the following score table:

p / P = Pawn = 1 point
n / N = Knight = 3 points
b / B = Bishop = 3 points
r / R = Rook = 5 points
q / Q = Queen = 9 points
k / K = King, these don't have any points because every legal position contains a king for each side

White pieces are designated using upper-case letters ("PNBRQK") while black pieces use lowercase ("pnbrqk"). Empty squares are noted using digits 1 through 8 (the number of empty squares), and "/" separates ranks.
From the example FEN string, we can calculate the material scores for each side:
For black:

5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8
All the black pieces left: p + p + p + p + r, this is a total of 9

For white:

5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8
All the white pieces left: P + R + P + N + P + P + P, this is a total of 13

The final score is determined with the following formula: White score - Black score = Final score, so for the example the final score would be: 13 - 9 = 4
Example :
Input:
5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8

Output:
4

All code-golf rules apply here, the solution with the least amount of bytes wins.

How to post
# Language Name, N bytes

 [code]

 [explaination, etc.]

So the actual position doesn't matter? You just count letters in the string?

Nitpick: That's not a complete FEN string. Also, kr1NQQQQ/2rNQQQQ/3NQQQQ/3NQQQQ/3NQQQQ/3NQQQQ/3NQQQQ/K2NQQQQ is winning for white, with black to move? :P

@xnor Yes, I think if the evaluation is also strategically based, it will get too complicated. You can also assume that all the inputs are legal positions, so don't worry about that.

@Doorknob, yes, the score is only material based to simplify things

CJam, 28 27 26 bytes
0l{i32mdD%[5ZZX9]=\3%(*+}/

Try it online in the CJam interpreter.
How it works
0l         e# Push a 0 (accumulator) and a line from STDIN.
{          e# For each character of that line:
  i32md    e#   Divide its code point by 32; push quotient and residue.
           e#   This serves two purposes:
           e#     1. The quotient will let us distinguish between uppercase
           e#        letters, lowercase letters and non-letters.
           e#     2. The residue will be the same for uppercase and lowercase
           e#        variants of the same letter.
  D%       e#   Take the residue modulo 13.
           e#   This maps R,N,B,P,Q -> 5,1,2,3,4
  [5ZZX9]= e#   Select the element at that index (5 ≡ 0) from [5 3 3 1 9].
  \        e#   Swap the quotient on top of the stack.
           e#   1 is digit or slash, 1 is uppercase, 2 is lowercase.
  3%(      e#   Take the quotient modulo 3 and subtract 1 from the result.
           e#   This maps 1,2,3 -> 0,1,-1.
  *+       e#   Multiply the generated integers.
  +        e#   Add the product to the accumulator.
}/         e#

><>, 64 57 56 53 bytes
"QRBNP"013359v
$0p4}:{:v?=1l<p4+' '{-
g4v?(0:i<+
n~<;

(-7 bytes with some inspiration from @El'endiaStarman's answer, -3 bytes thanks to @randomra)
Explanation
The program uses the codebox as a lookup table. Out-of-range puts/gets don't work with the online interpreter, so this only works with the official Python interpreter.
The first line pushes the pieces, followed by the piece values. It also pushes an initial 0 to kick off the total for the third line.
The second line then puts the appropriate positive or negative value at the corresponding piece cell, e.g. -1 is placed at ('p', 4) and 1 is placed ('P', 4). The length of the stack is checked to make sure the loop runs 5 times.
After the loop is over, the stack consists of our single zero from the first line. For each char we perform a lookup at the corresponding cell in the table and add it to our total. By default, uninitialised cell values are 0, which is perfect for our purposes.
The last line merely prints the result.

Ruby, 88 chars
->s{s.chars.map{|c|({P:1,N:3,B:3,R:5,Q:9}[:"#{c.upcase}"]||0)*(c.ord<90?1:-1)}.inject:+}

This is awkward and ugly, and there's probably a better way, but oh well.
Ruby's {foo: 'bar'} syntax is actually just sugar for {:foo => 'bar'}—this is annoying for golf because it means I have to convert the key to a symbol before using it to access a hash element (:"#{x}" is one char shorter than x.to_sym).

Pip, 39 bytes
I'll take my brief turn in the lead before the CJam and Pyth answers come along...
$+Y(95<=>A_)*013359@{"KPNBRQ"@?UCa|0}Ma

Takes the FEN string as a command-line argument. Here's an explanation for a slightly ungolfed version:
$+({(95<=>Aa)*013359@("KPNBRQ"@?UCa|0)}Ma)

   {                                  }Ma   Map this function to each character in input:
                                UCa          Uppercase version of character
                      "KPNBRQ"@?             Its index in this string, nil if not present
                                   |0        Logical or with 0 (to turn nil into 0)
              013359@(               )       Index into this number to get piece's score
          Aa                                 ASCII value of character
     95<=>                                   1 if less than 95, -1 if greater than 95
    (       )*                               Multiply by the score
$+(                                      )  Sum all scores and autoprint result

Perl, 44 bytes
#!perl -p
$\+=lc=~y/pnbrq/13359/r*(a cmp$_)for/\D/g}{

Counting the shebang as one, input is taken from stdin.

Sample Usage
$ echo 5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8 | perl fen-score.pl
4

Explanation
Pieces are transliterated with their respective values. If the piece is capitalized (i.e. less than a), its value is added to the sum, if not it is subtracted.

JavaScript ES7, 79 bytes 124 131
s=>(i=0,[for(q of s)i+={P:1,N:3,B:3,R:5,Q:9,p:-1,n:-3,b:-3,r:-5,q:-9}[q]||0],i)

As short as I can get. Uses fancy array comprehensions, to loop through the string.
Explanation
s=>(     // Define function with an argument

    i=0, // this var will store the score

    [for(q of s)   // Loops through input
      i+=          // Adds to score by...

         {P:1,...,   // Defines value of each letter
          p:-1,...}  // Negative value instead, which will subtract
         || 0        // Otherwise add 0

    ], i           // Return score

Minkolang 0.9, 72 65 64 60 44 42 41 bytes
13359"QRBNP"m5[d3~c~$r48*+0p0p]$I[o0q+]N.

Try it here.
Much thanks to Sp3000 for pointing out a much more efficient way to do this!
Explanation
13359"QRBNP"m pushes the scores and their corresponding characters, then interleaves them, so the stack looks like this: [1,80,3,78,3,66,5,82,9,81]. Then 5[d3~c~$r48*+0p0p] puts the score of each character, both lowercase and uppercase, at its location in the code space. Finally, $I[o0q+]N. loops through the input until it's empty, adding up the scores as it goes along.

Perl 5, 71 63 bytes
%a=(P,1,N,3,B,3,R,5,Q,9);$\+=$a{$_}||-$a{uc$_}for<>=~/./g;print

This modifies $\ (the line separator for print, which starts false) for every alphanumeric in the string that's a key of the hash %a defined at the beginning. It increments $\ by the value of the hash if the letter is a key as is; otherwise, it increments by negative the value of the hash if the uppercased letter is a key; otherwise it adds nothing.
Many thanks to primo for saving me eight bytes (in a comment on this answer).

I can save another byte with another suggestion from primo (thanks!): change $a{$_}||-$a{uc$_} to $a{$_}-$a{$"^$_}. But that's a rather different answer than mine, I think, so I'll not take the "credit" (of −1 byte) for it.

CJam, 33 bytes
q{"PNBRQ"_el+#13359Ab_Wf*+0+=}%:+

Here's the super-naïve string-find way. Try it online.

Ouroboros, 82
Ouroboros is an esolang I designed this week. Time to take it for a spin!
i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+
)L!4*(4Sn1(

Each line of single-char commands1 represents an ouroboros snake, wherein execution proceeds from head (start) to tail (end) and loops back to the head. The ( and ) commands let you eat part of the tail or regurgitate it, thus changing what commands get executed. If the instruction pointer is ever swallowed, the snake dies (stops executing). An Ouroboros program consists of one or more snakes executing in parallel. Each snake has a stack of its own, and there is also a shared stack.
1One exception, which distinguishes Ouroboros from many 2D languages: multi-digit numbers can be written straightforwardly, without having to do math or push a 0 first.
Snake 1
The first snake reads a character (i) and checks whether it's -1 / EOF (.1+!). If so, it eats most of its tail, up to and including the M (57*().
The snake then swaps the character code with the tally that is above it on the stack (\), moves the tally to the shared stack (m), and swallows another character (1(). If it had already swallowed a bunch, this means it swallows the ( that the IP is currently on and dies. Otherwise, execution proceeds by moving the tally back to snake 1's stack, swapping it with the char code, and regurgitating the character that was previously swallowed (M\1)).
We then use math and stack operations to generate the appropriate score for the character. .96> tests whether it's lowercase or not; the subsequent 32*- converts to uppercase. Then the long stretch from .80= to 81=9*++++ maps P -> 1, N -> 3, etc. Finally, \2*1\-* negates the score if the letter was lowercase, and + adds it to the running tally. The snake then loops and reads another character.
Snake 2
The second snake starts with a regurgitate operation ()), which does nothing the first time through (since nothing's been swallowed yet, and also since popping an empty stack gives 0). Next, it pushes the length of the shared stack to its own stack and logically negates (L!). This gives 1 if the stack is empty, 0 otherwise. The snake multiplies by 4 and eats that many characters (4*().
If the shared stack was empty, this means the snake now ends before the S. It pushes 4 and loops back to the ), where it regurgitates the characters it just swallowed and starts over again.
If there was a value on the shared stack, however, no characters are swallowed and execution continues. The snake switches to the shared stack and outputs the number there (Sn); then it swallows its last character and dies (1().
Synchronization
The two snakes must be carefully synchronized so that there is never a value on the shared stack when snake 2 does its check, until the end of input is reached. Snake 1 puts a value on the shared stack briefly on each pass through its loop. Thus, snake 2's L command must never be executed between the m and M commands in snake 1. Fortunately, the snakes line up very well. Crucially, the length of snake 1's loop (70 instructions) is a multiple of snake 2's loop (7 instructions), so the two will never get out of sync:
i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+
)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5
          |__|
       Danger zone

If the numbers hadn't worked out so perfectly, I would have padded one or both snakes with spaces to make them align as needed.
All of this is very well, but I want to see it in action!
Here is the above program via Stack Snippet. Even on 1000 operations per second, it takes about 10 seconds to spit out the answer for the sample input--but it does get there!

// Define Stack class
function Stack() {
  this.stack = [];
  this.length = 0;
}
Stack.prototype.push = function(item) {
  this.stack.push(item);
  this.length++;
}
Stack.prototype.pop = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack.pop();
    this.length--;
  }
  return result;
}
Stack.prototype.top = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack[this.length - 1];
  }
  return result;
}
Stack.prototype.toString = function() {
    return "" + this.stack;
  }

// Define Snake class
function Snake(code) {
  this.code = code;
  this.length = this.code.length;
  this.ip = 0;
  this.ownStack = new Stack();
  this.currStack = this.ownStack;
  this.alive = true;
  this.wait = 0;
  this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
    if (!this.alive) {
      return null;
    }
    if (this.wait > 0) {
      this.wait--;
      return null;
    }
    var instruction = this.code.charAt(this.ip);
    var output = null;
    if (this.partialString !== null) {
      // We're in the middle of a double-quoted string
      if (instruction == '"') {
        // Close the string and push its character codes in reverse order
        for (var i = this.partialString.length - 1; i >= 0; i--) {
          this.currStack.push(this.partialString.charCodeAt(i));
        }
        this.partialString = null;
      } else {
        this.partialString += instruction;
      }
    } else if (instruction == '"') {
      this.partialString = "";
    } else if ("0" <= instruction && instruction <= "9") {
      if (this.partialNumber !== null) {
        this.partialNumber = this.partialNumber + instruction; // NB: concatenation!
      } else {
        this.partialNumber = instruction;
      }
      next = this.code.charAt((this.ip + 1) % this.length);
      if (next < "0" || "9" < next) {
        // Next instruction is non-numeric, so end number and push it
        this.currStack.push(+this.partialNumber);
        this.partialNumber = null;
      }
    } else if ("a" <= instruction && instruction <= "f") {
      // a-f push numbers 10 through 15
      var value = instruction.charCodeAt(0) - 87;
      this.currStack.push(value);
    } else if (instruction == "$") {
      // Toggle the current stack
      if (this.currStack === this.ownStack) {
        this.currStack = this.program.sharedStack;
      } else {
        this.currStack = this.ownStack;
      }
    } else if (instruction == "s") {
      this.currStack = this.ownStack;
    } else if (instruction == "S") {
      this.currStack = this.program.sharedStack;
    } else if (instruction == "l") {
      this.currStack.push(this.ownStack.length);
    } else if (instruction == "L") {
      this.currStack.push(this.program.sharedStack.length);
    } else if (instruction == ".") {
      var item = this.currStack.pop();
      this.currStack.push(item);
      this.currStack.push(item);
    } else if (instruction == "m") {
      var item = this.ownStack.pop();
      this.program.sharedStack.push(item);
    } else if (instruction == "M") {
      var item = this.program.sharedStack.pop();
      this.ownStack.push(item);
    } else if (instruction == "y") {
      var item = this.ownStack.top();
      this.program.sharedStack.push(item);
    } else if (instruction == "Y") {
      var item = this.program.sharedStack.top();
      this.ownStack.push(item);
    } else if (instruction == "\\") {
      var top = this.currStack.pop();
      var next = this.currStack.pop()
      this.currStack.push(top);
      this.currStack.push(next);
    } else if (instruction == "@") {
      var c = this.currStack.pop();
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(c);
      this.currStack.push(a);
      this.currStack.push(b);
    } else if (instruction == ";") {
      this.currStack.pop();
    } else if (instruction == "+") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a + b);
    } else if (instruction == "-") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a - b);
    } else if (instruction == "*") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a * b);
    } else if (instruction == "/") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a / b);
    } else if (instruction == "%") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a % b);
    } else if (instruction == "_") {
      this.currStack.push(-this.currStack.pop());
    } else if (instruction == "I") {
      var value = this.currStack.pop();
      if (value < 0) {
        this.currStack.push(Math.ceil(value));
      } else {
        this.currStack.push(Math.floor(value));
      }
    } else if (instruction == ">") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a > b));
    } else if (instruction == "<") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a < b));
    } else if (instruction == "=") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a == b));
    } else if (instruction == "!") {
      this.currStack.push(+!this.currStack.pop());
    } else if (instruction == "?") {
      this.currStack.push(Math.random());
    } else if (instruction == "n") {
      output = "" + this.currStack.pop();
    } else if (instruction == "o") {
      output = String.fromCharCode(this.currStack.pop());
    } else if (instruction == "r") {
      var input = this.program.io.getNumber();
      this.currStack.push(input);
    } else if (instruction == "i") {
      var input = this.program.io.getChar();
      this.currStack.push(input);
    } else if (instruction == "(") {
      this.length -= Math.floor(this.currStack.pop());
      this.length = Math.max(this.length, 0);
    } else if (instruction == ")") {
      this.length += Math.floor(this.currStack.pop());
      this.length = Math.min(this.length, this.code.length);
    } else if (instruction == "w") {
      this.wait = this.currStack.pop();
    }
    // Any instruction not covered by the above cases is ignored
    if (this.ip >= this.length) {
      // We've swallowed the IP, so this snake dies
      this.alive = false;
      this.program.snakesLiving--;
    } else {
      // Increment IP and loop if appropriate
      this.ip = (this.ip + 1) % this.length;
    }
    return output;
  }

// Define Program class
function Program(source, speed, io) {
  this.sharedStack = new Stack();
  this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
    var snake = new Snake(snakeCode);
    snake.program = this;
    snake.sharedStack = this.sharedStack;
    return snake;
  }.bind(this));
  this.snakesLiving = this.snakes.length;
  this.io = io;
  this.speed = speed || 10;
  this.halting = false;
}
Program.prototype.run = function() {
  if (this.snakesLiving) {
    this.step();
    this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
  }
}
Program.prototype.step = function() {
  for (var s = 0; s < this.snakes.length; s++) {
    var output = this.snakes[s].step();
    if (output) {
      this.io.print(output);
    }
  }
}
Program.prototype.halt = function() {
  window.clearTimeout(this.timeout);
}
var ioFunctions = {
  print: function(item) {
    var stdout = document.getElementById('stdout');
    stdout.value += "" + item;
  },
  getChar: function() {
    if (inputData) {
      var inputChar = inputData[0];
      inputData = inputData.slice(1);
      return inputChar.charCodeAt(0);
    } else {
      return -1;
    }
  },
  getNumber: function() {
    while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
      inputData = inputData.slice(1);
    }
    if (inputData) {
      var inputNumber = inputData.match(/\d+/)[0];
      inputData = inputData.slice(inputNumber.length);
      return +inputNumber;
    } else {
      return -1;
    }
  }
};
var program = null;
var inputData = null;

function resetProgram() {
  var stdout = document.getElementById('stdout');
  stdout.value = null;
  if (program !== null) {
    program.halt();
  }
  program = null;
  inputData = null;
}

function initProgram() {
  var source = document.getElementById('source'),
    stepsPerSecond = document.getElementById('steps-per-second'),
    stdin = document.getElementById('stdin');
  program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
  inputData = stdin.value;
}

function runBtnClick() {
  if (program === null || program.snakesLiving == 0) {
    resetProgram();
    initProgram();
  } else {
    program.halt();
    var stepsPerSecond = document.getElementById('steps-per-second');
    program.speed = +stepsPerSecond.innerHTML;
  }
  program.run();
}

function stepBtnClick() {
  if (program === null) {
    initProgram();
  } else {
    program.halt();
  }
  program.step();
}
.container {
  width: 100%;
}
.so-box {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  font-weight: bold;
  color: #fff;
  text-align: center;
  padding: .3em .7em;
  font-size: 1em;
  line-height: 1.1;
  border: 1px solid #c47b07;
  -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
  background: #f88912;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
  display: inline-block;
  border-radius: 6px;
  float: left;
  margin-right: 25px;
  cursor: pointer;
}
.option {
  padding: 10px 20px;
  margin-right: 25px;
  float: left;
}
h1 {
  text-align: center;
  font-family: Georgia, 'Times New Roman', serif;
}
a {
  text-decoration: none;
}
input,
textarea {
  box-sizing: border-box;
}
textarea {
  display: block;
  white-space: pre;
  overflow: auto;
  height: 40px;
  width: 100%;
  max-width: 100%;
  min-height: 25px;
}
span[contenteditable] {
  padding: 2px 6px;
  background: #cc7801;
  color: #fff;
}
#stdout-container,
#stdin-container {
  height: auto;
  padding: 6px 0;
}
#reset {
  float: right;
}
#source-display-wrapper {
  display: none;
  width: 100%;
  height: 100%;
  overflow: auto;
  border: 1px solid black;
  box-sizing: border-box;
}
#source-display {
  font-family: monospace;
  white-space: pre;
  padding: 2px;
}
.activeToken {
  background: #f88912;
}
.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  display: inline-block;
}
* html .clearfix {
  height: 1%;
}
.clearfix {
  display: block;
}
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
  <textarea id="source" placeholder="Enter your program here" wrap="off">i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+
)L!4*(4Sn1(</textarea>
  <div id="source-display-wrapper">
    <div id="source-display"></div>
  </div>
</div>
<div id="stdin-container" class="container">
  <textarea id="stdin" placeholder="Input" wrap="off">5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8</textarea>
</div>
<div id="controls-container" class="container clearfix">
  <input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" />
  <input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" />
  <input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" />
  <input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" />
</div>
<div id="stdout-container" class="container">
  <textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea>
</div>
<div id="options-container" class="container">
  <div class="option so-box">Steps per Second: <span id="steps-per-second" contenteditable>1000</span>
  </div>
</div>

JavaScript ES6, 71
As an anonymous function
n=>[...n].map(x=>t+=~(y='q   rnb p PBN R   Q'.search(x))?y-9|1:0,t=0)|t

Python 3, 93
v=dict(zip('pbnrqPBNRQ',[1,3,3,5,9]*2))
print(sum(v.get(c,0)*(-1)**(c>'Z')for c in input()))

Clojure/ClojureScript, 63 chars
#(apply +(map{"P"1"N"3"B"3"R"5"Q"9"p"-1"n"-3"b"-3"r"-5"q"-9}%))

Written using a ClojureScript REPL, should also be valid Clojure.  Try it here.  Enter it, then call it using (*1 "FEN_string_here")
Pretty straightforward.  {"P"1..."q"-9} is a data structure literal for a map of "P" to 1, "N" to 3, etc.  map takes the function as the first argument and the data structure to process as the second--in this case, it's using the feature that a data structure (the map literal) can act as its own accessor function.  The string parameter (% from the function macro) can be treated as a list of individual character strings.  Any character not in the map will end up as nil in the resulting list, which + happily ignores.

Pyth, 25 bytes
-Fmsmhy/4@S5%Ck12@Gd_rBz2

Demonstration
This uses the following mapping formula for letters in pbnrq, if k is the letter:
(4 / (((chr(k) % 12) % 5) + 1) * 2 + 1

This is represented in Pyth as:
hy/4@S5%Ck12

First, the program creates the case-swapped version of the input, then on both strings filters for lowercase letters, then applies the above formula, then sums and subtracts the black values from the white values.


text:
Dynamic Encoding: A CIA Mission
The Challenge Mission
You are Jim, a CIA agent in charge of super secret spies around the world. However, your enemies, the Naissurs, are highly trained in computer intelligence, and they can hack into your super secret communication systems. To contact your super secret spies, you must encrypt each message with a 16-character-long key. To encrypt a message, you must correspond each number of the key to each letter of the message. The number corresponding to each letter tells how many times to go ahead one letter. For example, if 3 corresponds to the letter a, we get a -> b -> c -> d and our new letter is d after encryption.
Example
Key: 1111222233334444 Message: "Hello World"
Encrypted Message: "Ifmmq Yquog"
However, Naissurs have found your key time after time, and you find a way to have the key be dynamic. For this mission, you must create an encoder and decoder using this encryption method, such that the key is incremented every time the program decrypts a message.
Input
Your program must take in the input e <message> for encoding, and d <message> for decoding. Your program also must generate a random 16-digit key upon running it. To set a key, you must  be able to use the command s <key> to define the key.
Example
Here is an example of the inputs and outputs of a program which generated the key 1111111111111111:
>e "Jim SMELLS Nice"
Kjn TNFMMT Ojdf
>d "Kjn TNFMMT Ojdf"
Jim SMELLS Nice
>s 0000000000000000
>e "Hello World"
Hello World!
Scoring
This is code-golf, so the least amount of bytes wins the challenge solves the mission and is promoted!

We need test cases that contain a sequence of commands.

Related (not sure if similar enough to be a duplicate)

@DLosc I'd say they're different enough. Different input format, numeric keys, random persistent keys, variable capitalization.

Can the number of characters in the message be longer than the key? If not, what to do with the characters after length 16 ?  And why not also encode the spaces? (would be more secure)

implementing a crappy affine. hmmm...no thanks.


text:
Cell Phone Keyboard Typing
Cell Phone Keyboard Typing
This question was asked a while back, but was closed due to poor specs. So, I'm redoing it, with better specs. This question is related, but goes in the opposite direction.
Before T9 came around, in order to type a character in a text message, you had to press one of the number keys a number of times to get the character you wanted. For reference, here is the standard mapping:
+-------+-------+-------+
|   1   |   2   |   3   |
|  .?!1 |  ABC2 |  DEF3 |
+-------+-------+-------+
|   4   |   5   |   6   |
|  GHI4 |  JKL5 |  MNO6 |
+-------+-------+-------+
|   7   |   8   |   9   |
| PQRS7 |  TUV8 | WXYZ9 |
+-------+-------+-------+
|   *   |   0   |   #   |
|   ←   |SPACE 0|   →   |
+-------+-------+-------+

* is backspace, 0 is a space (' ') or the number 0, and # confirms the current character. For the sake of simplicity, all characters are uppercase.
When you pressed a key multiple times, the selected character cycles through the possible characters for that key: 2 -> A, 22 -> B, 222 -> C, 2222 -> 2, 22222 -> A, and so on. Note that, since * only has one option, pressing it repeatedly causes multiple backspaces to be entered. Pressing # multiple times in a row has no effect. A trailing # is unnecessary.
Additionally, if a different key is pressed immediately after pressing a key, the previous keypress is automatically confirmed. Thus, 223 is functionally identical to 22#3.
Your challenge is to translate a series of keypresses into the corresponding string a cell phone would display.
Examples
8#99999#055#33#999#22#666#2#777#3#1 -> T9 KEYBOARD
4433555#55566609666666677755533*3111 -> HELLO WORLD!
7##222#222**7#222#4 -> PPCG
00#0#00 -> 0 0

Rules

This is code-golf, so the shortest correct solution (in bytes) wins
The winning answer will be chosen in one week
Standard loopholes are forbidden
Your answer may be in the form of a full program, a named function, or an anonymous function, taking input and producing output in one of the standard methods

Leaderboard
The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

How do you produce numbers? You have the number '9' in an example, but your specification (2 -> A, 22 -> B..., 2222 -> A....) does not allow any numbers to be produced.

@C.Quilley That's what I get for blindly copying that diagram over, fixed now.

Closely related, possible dupe.

@AlexA. Not a dupe, it's standard phone numpad input, not T9 dictionary lookup.

K5, 112 bytes
{(20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)[.*x]20!#1_x}'(){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}

This one is really a mess, but I think there's a fair amount of room to golf it down.
First we need to construct a lookup table for the keymap. There are keys with 2, 4 and 5 characters mapped to them, so padding every entry out to 20 simplifies the process of cyclically indexing this table later:
  (20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)
(" 0 0 0 0 0 0 0 0 0 0"
 ".?!1.?!1.?!1.?!1.?!1"
 "ABC2ABC2ABC2ABC2ABC2"
 "DEF3DEF3DEF3DEF3DEF3"
 "GHI4GHI4GHI4GHI4GHI4"
 "JKL5JKL5JKL5JKL5JKL5"
 "MNO6MNO6MNO6MNO6MNO6"
 "PQRS7PQRS7PQRS7PQRS7"
 "TUV8TUV8TUV8TUV8TUV8"
 "WXYZ9WXYZ9WXYZ9WXYZ9")

Then I split the input into runs:
 {(&~0=':x)_x}"8#99999#055#33#999"
(,"8"
 ,"#"
 "99999"
 ,"#"
 ,"0"
 "55"
 ,"#"
 "33"
 ,"#"
 "999")

Drop any # runs and strip trailing runs every time I encounter a *:
  (){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}"8#99999#055#33#999"
(,"8"
 "99999"
 ,"0"
 "55"
 "33"
 "999")

And then I'm ready to simply index into that lookup table based on the length and first element of each run.
All together:
  {(20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10)[.*x]20!#1_x}'(){$[42=*y;(-#y)_x;35=*y;x;x,,y]}/{(&~0=':x)_x}"4433555#55566609666666677755533*3111"
"HELLO WORLD!"

Edit:
Save 5 bytes:
0 3 6 9 12 15 19 22
((3*!6),19 22)

You can shorten (20#'((" ";".?!"),0 3 6 9 12 15 19 22_`c$65+!26),'$!10) to (20#'((" ";".?!"),((3*!6),19 22)_`c$65+!26),'$!10).

Yeah, I actually just found that a few minutes ago.

JavaScript, 214 184 168 162 bytes
x=>(x.match(/(.)\1*/g,f='').map(a=>f=(l=a.length,v=' 0#.?!1#ABC2#DEF3#GHI4#JKL5#MNO6#PQRS7#TUV8#WXYZ9'.split`#`[a[0]])?f+v[--l%v.length]:a<'*'?f:f.slice(0,-l)),f)

This can probably be made a little smaller, but I'm pretty happy with the result. Splits characters into repeated groups of one or more, then steps through the array, mapping each character to it's value in the hash and adding it onto the final string. If it comes across any number of '#', it ignores it. If it comes across any '*', it removes that number of them from the end of the final string.

Python 2, 230 206 bytes
import re
f=lambda a,b=dict(zip("0123456789*#"," 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9~\b~".split("~"))):"".join([j and b[j][(len(i)-1)%len(b[j])]or b[i]for i,j in re.findall(r"((\d)\2*|.)",a)])

This one creates a function f which takes a string of keypresses as argument and returns the corresponding string a cell phone would display. It also happens to take an optional second argument as a dictionary mapping keys to their corresponding characters, eg {"0": " 0", "1": ".?!1", ...}.
First, the string of keypresses is grouped by repeating characters, eg ["8", "#", "99999", "#", ...]. Then, the first character of each group is mapped in the dictionary passed as second argument, eg 9 maps to WXYZ9. Finally, the length of the group is used as offset in the value from the dictionary.
Note that the offset must use modulo on the length of the group of repeating characters because keypresses might cycle. Also note that the # character is mapped to \0 and only removed at the end because 99#99 is not the same as 9999.
Here is the output of the function for each of the examples in the question:
>>> print f("8#99999#055#33#999#22#666#2#777#3#1")
T9 KEYBOARD.
>>> print f("4433555#55566609666666677755533*3111")
HELLO WORLD!
>>> print f("7##222#222**7#222#4")
PPCG
>>> print f("00#0#00")
0 0

Python 2, 265 bytes
It's way too long. IO: stdin, stdout.
a=reduce(lambda q,w:q+" "+[w,""][w=="#"]if q[-1]!=w else q+w,raw_input()).split()
while "*" in a:del a[a.index("*")-1:a.index("*")+1]
print"".join([(lambda a:a[len(q)%len(a)-1])(" 0:.?!1:ABC2:DEF3:GHI4:JKL5:MNO6:PQRS7:TUV8:WXYZ9".split(":")[int(q[0])])for q in a])

The third example, 7##222#222**7#222#4, will cause your script to raise a ValueError: invalid literal for int() with base 10: '*'.

Python 2, 237 bytes
Using cr3's dictionary, but without re.
def f(i):
 d=dict(zip("0123456789"," 0|.?!1|ABC2|DEF3|GHI4|JKL5|MNO6|PQRS7|TUV8|WXYZ9".split("|")))
 s,x,j='',i[0],0
 for c in i[1:]+'#':
  if c==x:j+=1
  else:
   if x>'/':s+=d[x][j%len(d[x])]
   j=0
  if c=='*':s=s[:-1]
  x=c
 return s