text:
Output the alphabet, the ALPHABET, or just a character
The challenge is simple:
Write a function or program that takes an input x, and outputs the lower case alphabet if x is part of the lower case alphabet, outputs the upper case alphabet if x is part of the upper case alphabet and outputs just x if it's not part of either.
Rules:

The input can be function argument or from STDIN
The input will be any of the printable ASCII characters from 32 to 126 (space to tilde).
The input may be inside quotation marks,'x' or "x", but remember that ' and " are valid input and should be supported.
The input can be any of the letters in the alphabet, i.e. you can't assume it will be a or A.
The output should be only one of the alphabets or the single symbol, but trailing newlines are OK.
The letters in the alphabet should not be separated by spaces, commas or anything else.

Some examples:
F
ABCDEFGHIJKLMNOPQRSTUVWXYZ

z
abcdefghijklmnopqrstuvwxyz

"
"

    <- Input:  Space
    <- Output: Space

Shortest code in bytes win.

Optional but appreciated: If your language has an online interpreter, please also post a link so that it can be easily tested by others.

Leaderboard
The Stack Snippet at the bottom of this post generates the catalog 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

var QUESTION_ID=67357,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

Are we allowed to import packages like, in Python for example: import Random and then use Random.randint (obviously not for this challenge but still)?

Yes, you may import packages. but the bytes for writing for instance import string are counted, thus it's often better to do workarounds. Note that the package must exist before the challenge is posted. Many challenges have something like: "Using packages that does this is not allowed", but that is not the case in this challenge.

I'm assuming that by "quotes are valid input and must be supported" you mean that if your input method requires quotes then quotes as input would be escaped

May we assume a REPL environment?

Is it single char input?

TeaScript, 5 bytes
xN(0)

TeaScript has a (almost) built-in for this :D
Try it online (note: the online interpreter has been updated to TeaScript v3 so in which this is N0)
Try all the test cases

TeaScript 3, 2 bytes [non-competing]
Using TeaScript 3, this can become 2-bytes. This is non-competing because TeaScript 3 was made after this challenge
N0

1 byte alternative
If we could output 0123456789 for digits, then this could be:
°

TeaScript 3 is valid. So, you may use it!

Pyth, 10 bytes
h/#z[GrG1z

Test suite
We start by constructing a list with 3 elements: the lowercase alphabet, the uppercase alphabet, and the input. ([GrG1z) Then, we filter this list on the number of appearances of the input in the elements being nonzero. (/#z) Finally, we take the first element of the filtered list.

Seriously, is there anything you couldn't solve with a few bytes of Pyth? I really need to learn this language..

Learn which language?...you mentioned two by name. :P

@quintopia Well, why not both? :)

Holy cow, this is clever! I just went with the obvious solution of ternary statements, which ended up being 14 bytes
?}zGG?}zKrG1Kz

LabVIEW, 23 LabVIEW Primitives
The selector (the ? on the cse structure) is connected to a vi that is called Lexical Class. It ouputs numbers from 1-6 depending on input, 5 is lower case 4 is upper case.
The for loop goes 26 times to create an alphabet or once to pass the symbol through.

As someone who had the (privilege? misfortune? you decide) of working in LabVIEW many years ago, your answers bring a smile to my day. =)

Haskell, 48 bytes
f c=filter(elem c)[['a'..'z'],['A'..'Z'],[c]]!!0

Usage example:
*Main> f 'g'
"abcdefghijklmnopqrstuvwxyz"
*Main> f 'H'
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
*Main> f '\''
"'"

Take all lists of ['a'..'z'], ['A'..'Z'] and the singleton list with the input char c where c is element of. For letters we have always two matches, so we pick the first one.

JavaScript (ES6), 79 bytes
x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)

Explanation
JavaScript compares the code of each character alphabetically when comparing strings, so the codes of the characters used in the comparisons are 1 below and above the required range of characters.
x=>(
  a="abcdefghijklmnopqrstuvwxyz", // a = lower-case alphabet
  x>"`"&x<"{"?a:                  // if x is a lower-case letter, output alphabet
  x>"@"&x<"["?a.toUpperCase():    // if x is an upper-case letter, output upper-case
  x                               // else just output x
)

Test

var solution = x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)
X = <input type="text" oninput="result.textContent=solution(this.value)" />

Is that actually the shortest way to produce a string with the entire alphabet in Javascript? If you wanted the entire printable ASCII-range, would you have to type every single character?

@StewieGriffin Sadly it is. The only other way would be something like: for(a="",i=64;++i<91;)a+=String.fromCharCode(i). String.fromCharCode is very unsuitable for golfing, but sometimes it's the only way!

In this case the balance is between String.fromCharCode and .toUpperCase (Dumb and Dumber) but toUpperCase is the winner

Nice! I've tried a few different ways of golfing this further, but haven't found one that works. x=>x.replace(/[A-Z]/i,c=>c>"`"?a:a.toUpperCase(),a="abcdefghijklmnopqrstuvwxyz") does, but is one byte longer. Changing [A-Z] to \w works for everything except _. Your solution seems to be the shortest possible.

Here's one of the shortests way to generate ABC...abc...? without a real for loop: (some padding) [for(_ of[...Array(i=64)])if(i++%32<26)String.fromCharCode(i)].join``+x

@ETHproductions I was wondering about that; the best I had managed was String.fromCharCode(...Array(91).keys()).slice(65) which takes 50 bytes just to produce the uppercase alphabet, or String.fromCharCode(...Array(123).keys()).replace(/[^a-z]/gi,'') which concatenates both in "only" 64 bytes.

Bah, /[^\W_]/ is no shorter than /[A-Z]/i.

R, 90 75 bytes
a=scan(,'');l=letters;L=LETTERS;cat("if"(a%in%l,l,"if"(a%in%L,L,a)),sep="")

Thanks to Giuseppe.
Old version (90 bytes):
a=scan(,'');l=letters;L=LETTERS;if(a%in%l)cat(l,sep="")else if(a%in%L)cat(L,sep="")else a

Looks ugly, but those cats cannot be outsourced to functions, IMHO.

75 bytes

73 bytes: the 2nd parameter of scan can be any object of type character, so you can letters instead of ''.

Can you replace the last sep="" with just the ""?

Python 3, 92 84 82 74 bytes
Current version: 74, thanks to isaacg and wnnmaw!
lambda c:(c,''.join(chr(x+(67,97)[c>'Z'])for x in range(25)))[c.isalpha()]

Ungolfed: (for some definition of ungolfed)
lambda c:
    (
        c,
        ''.join([chr(x + (67,97)[c > 'Z']) for x in range(25)])
    )
    [c.isalpha()]

First version: 92
def f(c):print(''.join([chr(x+(97if c>'Z'else 65)) for x in range(25)])if c.isalpha()else c)

Second version: 82, thanks to isaacg! :)
lambda c:''.join(chr(x+(97if c>'Z'else 65))for x in range(25))if c.isalpha()else c

Hi, and welcome to PPCG! Nice answer. Here's a golfing suggestion: You can use a lambda expression (lambda c:) instead of an explicit definition (def f(c):print(), and save some bytes. Also, you don't need the space before the for.

Ah, I assumed "output" to mean print, and not just return :) Neat, if that's the case it's down to 84, lambda c:''.join([chr(x+(97if c>'Z'else 65))for x in range(25)])if c.isalpha()else c. Thanks!

Yeah, the standard definition of output on the site allow returning from functions, so you can edit the new version into your answer. Another golf is that the brackets aren't necessary - the function works exactly the same without them, as a generator comprehension instead of a list comprehension.

Ah, haven't actually used generator comprehensions before, learning new things! Thanks again :)

Note that when inputing " to the function, you need \" instead.

You can save 5 bytes by replacing (97if c>'Z'else 65) with (67,97)[c>'Z']

True! We can actually use the same trick to replace the if else. Down to 76, neat! :)

Python 3, 118 105 98 97 83 bytes
Simple solution. EDIT: Golfed with thanks to Erik the Golfer's suggestion.
lambda s,a='ABCDEFGHIJKLMNOPQRSTUVWXYZ':(s,(a,a.lower())[s.islower()])[s.isalpha()]

Ungolfed:
def f(s):
 a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 if s.isalpha():
  if s.islower():return a.lower()
  else:return a
 return s

Could you use a ternary operator to save a few bytes? Something like return a.lower() if s.islower() else a.

@DavidRobertson I'm not sure if you're reading my solution, which is the top line of code, correctly, but that is exactly what I'm doing.

Ah! I was reading the ungolfed version. Sorry about that!

@DavidRobertson Not a problem

Golfed: lambda s,a='abcdefghijklmnopqrstuvwxyz':(s,(a,a.upper())[s.isupper()])[s.isalpha()]

Can you do something like map(chr,range(65,91))?

@Cyoce I don't think I can. I can't .lower() a map and ''.join would add too many bytes.

PHP, 62 76 82 bytes
PHP is doing OK now:
<?=ctype_alpha($x=$argv[1])?join(range(Z<$x?a:A,Z<$x?z:Z)):$x;

Takes an input from command line, like:
$ php alphabet.php A
$ php alphabet.php "a"
$ php alphabet.php " "
$ php alphabet.php _

Edits

Saved 6 bytes by replacing 91>ord($x) with Z<$x. Thought way to complicated. Thanks to manatwork.
Saved 14 bytes by removing strtoupper and building the demanded range directly.

That ord() looks bad there. Try Z<$x?$a:strtoupper($a).

@manatwork Haha, I've thought way to complicated in that second part. Thanks to point it out.

Try ' '&$x^A to make uppercase and lowercase a and z. That is, your code becomes <?=ctype_alpha($x=$argv[1])?join(range(' '&$x^A,' '&$x^Z)):$x;

@IsmaelMiguel This will have the exact same byte count.

@insertusernamehere -.- you're right... I counted those bytes incorrectly. sorry :/

Don't worry - and it's still a nice way to obfuscate. ;)

Wow, I just php-golfed this challenge myself as an exercise and came up with exactly this code, byte for byte.

Save 4 bytes with range($x&a|A,$x&z|Z) and one byte with $argn and -R.

Perl, 46 34 33 bytes
includes +2 for -nE
say/[a-z]/?a..z:/[A-Z]/?A..Z:$_

Run as
perl -nE 'say/[a-z]/?a..z:/[A-Z]/?A..Z:$_'

update 34 save 12 bytes by omitting for and using barewords, thanks to @Dom Hastings.
update 33 save 1 byte using -E and say instead of print.

@DomHastings Thanks! Should have known barewords were allowed there - and I should've seen that for :-/. Tried a bunch of approaches, (-p with $"='';$_="@_", even $a='/[a-z]/?a..z:';print eval$a.uc$a.'$_' but everything is longer...

Had a think on this, if you set $_= instead of printing and use the -p flag instead of -n you can save another two... I still can't think of any other ways to save more so far...

@DomHastings I tried that, but I can't set $_ to a list (that I know of). It would have to be interpolated ($_="@_") but that uses space as a separator so I'd have to do $"='' as well, (or use a join'',) which makes it longer.  Not much wiggle room on this one!

Hah, of course! You even said that (when I re-read the comment after not being at the pub...) I'll keep thinking on it, but you might be the shortest you'll get without using say instead of print!

Ruby, 41 + 1 = 42
With switch -p, run
([*?A..?z]*'').scan(/\w+/){$&[$_]&&$_=$&}

This generates the string
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz

and checks each contiguous block of "word characters", which happen to be just the lowercase and uppercase alphabets and the underscore character. If there were multiple consecutive word characters between Z and a, this trick wouldn't work.
Edited to add explanation, by request:
The -p flag does essentially
while( $_ = STDIN.gets )
  #execute code
  print $_
end

[*?A..?z] is the array of characters between uppercase A and lowercase Z, in ASCII order. That's the uppercase alphabet, some non-letter characters, and the lowercase alphabet. *'' joins the array into a string, so we can call .scan on it. scan will find each match of the regular expression /\w+/, populate the magic variable $& with it, and call the block. Each time the block is iterated, it checks whether the matched string contains $_ and sets the output to that string if so. So if $_ is contained in either the uppercase or lowercase alphabet, it gets modified accordingly, otherwise it's unchanged.
The ungolfed version would look something like
while ($_ = STDIN.gets )
 %w[ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz].each do |alphabet|
  $_ = alphabet if alphabet.include?($_)
 end
 print $_
end

Can you post an un-golfed version? I'm still not understanding fully how this works.

Sure, posted one.

Ruby, 46 43 characters
(42 characters code + 1 character command line option)
[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}

Thanks to:

Jordan for the === magic (-3 characters)

Sample run:
bash-4.3$ echo -n 'm' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ echo -n 'W' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ echo -n '@' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
@

CJam, 18 bytes
'[,65>_elr:R]{R&}=

'[,65> pushes the uppercase alphabet, _el the lowercase alphabet, and r:R a single-char string that is read from STDIN and assigned to variable R. These are wrapped in an array (]) and the first one that has any chars in common with R is selected using {R&}=.

I'm trying to understand how to CJam, but I'm lost between the official doc and what I'm reading here. Can someone give me for example a page where I can understand why is _el the lowercase alphabet?

Ah, el means "convert to lowercase". I've just pushed the uppercase alphabet, so now I duplicate it with _, then call el on the resulting copy.

I made a nice pdf containing (almost) all CJam commands.

Retina, 62 bytes
[a-z]
abcdefghijklmnopqrstuvwxyz
[A-Z]
ABCDEFGHIJKLMNOPQRSTUVWXYZ

The two short lines are the regex to match. If the input is lowercase (in the range [a-z]), it replaces that character (in this case, that is the entire input) with the lowercase alphabet. The process is similar for uppercase. If it's not a letter, no replacements are made, and it is outputted untouched.
Try it online.

#MATL, 22 bytes
jtt1Y2XIm~Iw?km?Ik]]1$

This uses the current version (3.1.0) of the language.
EDIT (Sep 15, 2017): Try it at MATL Online! (with a newer version of the language).
###Examples
>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> e
abcdefghijklmnopqrstuvwxyz

>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> T
ABCDEFGHIJKLMNOPQRSTUVWXYZ

>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> "
"

###Explanation
j              % input string (assumed to be a single character)
tt             % duplicate twice
1Y2            % predefined literal: uppercase letters
XI             % copy to clipboard I
m~             % check if not member
I              % paste from clipboard I
w              % swap elements in stack
?              % if
    k          % convert string to lowercase
    m          % check if member
    ?          % if
        I      % paste from clipboard I
        k      % convert string to lowercase
    ]          % end
]              % end
1$             % input specification for implicit printing

Python 2.7.10, 95 93 79 bytes
This is my first time even attempting to golf, so please, any help or advice is extremely appreciated!
from string import*
lambda i:(i,(uppercase,lowercase)[i.islower()])[i.isalpha()]

Thanks to Morgan Thrapp for the help!

@MorganThrapp, that doesn't seem to work. Are you sure that it works in Python 2.7.10?

It works in 2.7.8. What doesn't work?

@MorganThrapp, actually, could you please explain first exactly how that works? Maybe it's just that I don't understand so I'm doing something wrong.

Sure, it uses the fact that False == 0 and True == 1 to index into tuples. So, it first checks if it's a letter with isalpha, if it is, it returns 1 and then checks if it's lowercase and does the same.

@MorganThrapp, oh wow. That's pretty cool. Thanks!

No problem! I love golfing, so I'm always happy to help out someone new!

Let us continue this discussion in chat.

Lua, 98 97 bytes
Sadly, I didn't find a solution shorter than 26 bytes to set a with the alphabet. In fact, I didn't find shorter than 32.
Edit : save 1 Byte thanks to @ATaco, was doing this error a lot when started with Lua :p
c=io.read()a="abcdefghijklmnopqrstuvwyz"print(not c:find"%a"and c or c:find"%u"and a:upper()or a)

You can test it online on the official site or on ideone. If you use the former, the input won't work (disabled), so use the following source, where it is wrapped into a function.
function f(c)
  a="abcdefghijklmnopqrstuvwyz"
  print(not c:find"%a"and c or c:find"%u"and a:upper()or a)
end

print(f("\""))
print(f("a"))
print(f("Q"))

You are not the only who not found shorter way to generate the alphabet in Lua. :(

@manatwork haha, exactly the same thing, except I didn't have to print it, but to concatenate it ^^. At least, that mean there isn't a hidden trick I didn't know to do it ^^'.

You can save a byte with c=io.read()a="abcdefghijklmnopqrstuvwyz" instead of a,c=...

Perl, 23 bytes
Includes +2 for -nE (instead of the normal +1) to be fair to the other perl solution
Run with the input on STDIN without trailing newline:
echo -n g | perl -lnE 'say/\pL/?a&$_|A..Z:$_'

Just the code:
say/\pL/?a&$_|A..Z:$_

Nice use of the fact that input is limited to 7-bit characters.

Japt, 9 bytes
;[CBU]æøU

Run it online

C (gcc), 91 bytes
A function that accepts a char and prints the result via stdout (91 bytes):
f(x){puts(isalpha(x)?x>90?"abcdefghijklmnopqrstuvwxyz":"ABCDEFGHIJKLMNOPQRSTUVWXYZ":&x);}

Try it online!
Bonus (a shorter version of MD XF's answer, since I don't have enough reputation to comment (90 bytes):)
#define f(x)isalpha(x)?x>90?"abcdefghijklmnopqrstuvwxyz":"ABCDEFGHIJKLMNOPQRSTUVWXYZ":&x

Try it online!

You now have enough reputation to comment.

SpecBAS, 111 bytes
I've been through several versions of this, 111 seems to be the best I can manage.
1 INPUT l$: a$="abcdefghijklmnopqrstuvwxyz"
2  ?IIF$(l$ IN ["a" TO "z","A" TO "Z"],IIF$(l$=UP$ l$,UP$ a$,a$),l$)

Line 2 uses the ? shortcut for PRINT and nested inline IF statements
Pseudo code explanation
IF character IN "a".."z","A".."Z"
THEN
 IF character = UPPERCASE character
 THEN
  print UPPERCASE alphabet
 ELSE
  print alphabet
 ENDIF
ELSE
 print the character
ENDIF

It's hard to make ["a" TO "z","A" TO "Z"] look more like a pseudo code than it already does. "a".."z","A".."Z" looks more like a "real code", at least in my eyes... Both are very easy to understand though =)

Spec what????

Mathematica, 75 bytes
#/.Thread[Join[a=Alphabet[],b=ToUpperCase@a]->Array[""<>If[#>26,b,a]&,52]]&

Pretty good score for a non-golfing language... Any solutions using character code processing would take more bytes, due to the costs of ToCharacterCode and FromCharacterCode.

Python, 81 bytes
f=lambda z,a="abcdefghijklmnopqrstuvwxyz":[k for k in[a,a.upper(),z]if z in k][0]

This is basically a translation of the Pyth answer. It defines a function f that takes as argument the character and returns the result.

You mean if z in k, right? Also, f= is optional by default.

@xnor Yes. Apparently I missed a Ctrl-C.

Remove f=, make the function anonymous. -2

MATLAB: 71 68 bytes
i=input('');b=i<65|i>122|(i>90&i<97);[i*b,~b*((65:90)+32*(i>96)),'']

(thanks to OP for saving 3 bytes)
Test:
i='a'
ans=
abcdefghijklmnopqrstuvwxyz

i='A'
ans=
ABCDEFGHIJKLMNOPQRSTUVWXYZ

i='~'
ans=
~

Explanation:
Uppercase alphabet occupies 65:90 ASCII characters. Lowercase alphabet is at 97:122 ASCII. So, b=i<65|i>122|(i>90&i<97) checks whether the input character i is NOT alphabetic. If so, input is returned. The uppercase alphabet is returned if b==1 and i<97 (uppercase character). If b==1 and i>96, 32 is added to 65:90 that corresponds to 97:122 - the lowercase alphabet.

Nice submission. Two comments: It's common to either use i=input('') if the submission is a script, or as a function argument if it's a function @(i)i^2. i='a' is in general not accepted. Also, you can save 3 bytes by doing [1,2,3,''] instead of char([1,2,3]).

Ok, edited. Thanks for suggestion!

Swift 2, 142 Bytes
func d(s:String)->String{let a="abcdefghijklmnopqrstuvwxyz";for v in s.utf8{return v>64&&v<91 ?a.uppercaseString:(v>96&&v<123 ?a:s)};return s}

Ungolfed
func d(s: String) -> String{
    let a="abcdefghijklmnopqrstuvwxyz"
    for v in s.utf8{
        return (
            v > 64 && v < 91 ?
            a.uppercaseString :
            (
                v > 96 && v < 123 ?
                a :
                s
            )
        )
     }
    return s
}

C (function), 71 bytes
f(s,n,c){n=1;if(isalpha(s))s-=s%32-1,n=26;for(c=s;c<s+n;)putchar(c++);}

f(s,n,c){for(c=s-=(n=isalpha(s)?26:1)>1?s%32-1:0;c<s+n;)putchar(c++);} saves a byte.

f(s,n){for(n=isalpha(s)?s-=s%32-1,s+26:s+1;s<n;)putchar(s++);} for 62 bytes

Jolf, 17 bytes
Try it here.
? hpLipl? hpUipui
?                  if
  hpL               the lowercase alphabet (array) contains
     i               the input
      pl            return the lowercase alphabet (string)
        ?          else if
          hpU       the uppercase alphabet (array) contains
             i       the input
              pu    return the uppercase alphabet (string)
                i  otherwise, return the input
                   implicit: print the result

Java, 165 characters
class A {public static void main(String[]p){int c=p[0].charAt(0),d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);for(;e<f;e++){System.out.print((char)e);}}}

Generates the required output to stdout (rather than returning it).
Input is via the runtime arguments.
How it works.
1) Setup some integer variables
c = the ASCII value of the first character of the first parameter of the runtime arguments.
d = c converted to lowercase ASCII value (by ORing it with 32)
b = calculation to see if d is a letter. Will be <0 if a letter.
e = The start character for output. If ASCII value in d is a letter (see b) then it is set to 'A' (or 'a' by adding c AND 32 to 'A' ASCII value) else it is set to the original value of c.
f = the number of characters to output. If it not a letter (see b) then this is set to 1 else it is set to 26
2) Loop from e to e+f outputing each character to stdout.

You know that for most challenges the solution can be provided either as complete program or a function? Given the enormous amount of boilerplate code in Java, a function may be shorter.

Applying a couple of small tricks, without changing the logic, I got this: void f(char c){for(int d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);e<f;)System.out.print((char)e++);}.

05AB1E, 19 16 bytes
-3 bytes thanks to else
DAsåiAëDAusåiAuë

How it works
                   # implicit input
D                  # duplicate
 A                 # push lowercase alphabet
  s                # swap last two elements
   å               # push a in b
    i              # if
     A             # lowercase alphabet
      ë            # else
         D         # duplicate
          Au       # uppercase alphabet
            s      # swap last two elements
             å     # push a in b
              I    # if
               Au  # uppercase alphabet
                 ë # else leave input
                   # implicit print

Try it online!

Not sure if ¹ (first input) already existed when you posted your answer, but you can golf 2 bytes with it: A¹åiAëAu¹åiAuë (Try it online or test suite).

I think you can leave out the last ë since that's implicit

Java SE 8, 71 69 bytes
Golfed:
(a,s)->{char b=97;if(a<91)b-=32;a=b;b+=26;while(a{          // String as a parameter. If declaration is necessary it adds 8 bytes
char b = 97;      // Uppercase A char, this is important
if (a < 91)       // If it is not past 'z', where a is a char param
    b -= 32;      // Then go back to the lowercase alphabet
a = b;            // Done to prevent a cast
b += 26;          // End of alphabet
while (a < b)     // Go to end of alphabet
    s += a++;     // Append character
return s;}        // Then return

I had originally implemented the following
String s="";char b=96;if(a-91<0)b-=32;for(char c=b;++c<b+27;)s+=c;return s;

It's more elegant but sadly it's one byte larger. This is assuming that behavior for non alpha characters is undefined and string s is initialized to "" prior to execution. Be gentle it's my first post.
edit: 2 bytes saved by Stewie Griffin by changing
a - 91 < 0 to a < 91

Welcome to the site! :)

Thanks! Been lurking for a few years now and really interested to see if I can make competing Java/C++ answers :)

a<91 should work, or...?

Scala, 91 characters
(c:Char)=>{var a='a'.to('z').mkString;if(c.isUpper)a=a.toUpperCase;if(!c.isLetter)a=""+c;a}

Un-golfed
def f(c: Char): String = {
    var a='a'.to('z').mkString //set up lower case default response
    if (c.isUpper) {
        a = a.toUpperCase     //mutate the result if upper case
    }
    if (!c.isLetter) {
      a = ""+c                 //mutate the result if not a letter
    }
    a                         //return result
}

Having a initial mutable result rather than returning an immutable value from 3 distinct if else blocks saved me 2 chars, even though I hate it.
Scala-thonic method
A better method for scala would be something like this:
def convertToAlphabet(c: Char): String = {
    c match {
      case x if !x.isLetter => x.toString
      case x if x.isUpper => ('A' to 'Z').mkString
      case _ => ('a' to 'z').mkString
    }
}

Brachylog, 8 bytes
∈Ạ|ḷ∈Ạụ|

Try it online!
∈Ạ          The input is a member of the lowercase alphabet,
  |         which is output, or
   ḷ∈Ạ      the input lowercased is a member of the lowercase alphabet,
      ụ|    which is output uppercased, or the input is output.

It'd be two bytes shorter if we had a constant for the uppercase alphabet but we don't :(

Keg, -ir 45 37 21 bytes
:AZ"•[_AZɧ|:az"•[_azɧ

Try it online!
-16 bytes due to using ranges
Answer History
37 bytes
::`>$\~<*[_z(|:;)^|:A1->[_Z(|:;)^|,

-8 bytes thanks to A__
Try it online!

37B by using control characters.

Pip, 13 bytes
aNz?zaNAZ?AZa

builtins.
Try it online!

Is this a reference to sporeball's esolang?!?!?!

without a doubt

Vyxal, 9 bytes
Ǎ[æ[kA|ka

Try it Online!
Explanation:
           # Implicit input
Ǎ[         # If input is a letter:
  æ[       #   If input is capitalized:
    kA     #     Push 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      |    #   Else:
       ka  #     Push 'abcdefghijklmnopqrstuvwxyz'
           # Implicit output

Pip, 12 bytes
aN_FI[zAZ]|a

Try it online!
Razetime's answer is the approach I thought of too, but 13 bytes seemed rather long. So I went looking for other approaches...
     [zAZ]    List containing the lowercase alphabet and the uppercase alphabet
   FI         Filter on this function:
aN_            Is the command-line argument in each string?
              If the argument is lowercase, the result is the lowercase alphabet*; if
              it's uppercase, the result is the uppercase alphabet*; and if it's
              neither, the result is an empty list, so...
          |a  Logical OR with the argument: if filter result is [], print arg instead

* As a single-element list, but without flags, that doesn't affect how it is displayed

Python 3.8, 108 93 bytes
-15 bytes thanks to Aaron Miller
a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(a if(x:=input())in a else a.lower()if x.islower()else x)

100 bytes

Scratch that, 93 bytes

TI-Basic, 111 bytes
Input Str1
"inString(Ans,Str1→u
"ABCDEFGHIJKLMNOPQRSTUVWXYZ
If u
Stop
"abcdefghijklmnopqrstuvwxyz
If u
Stop
Str1

Output is stored in Ans.

Gema, 60 characters
\A=@set{a;abcdefghijklmnopqrstuvwxyz}
<J>=$a
<K>=@upcase{$a}

Sample run:
bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< 'm'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< 'W'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< '@'
@

Python 2, 67 bytes
f=lambda c,i=26:c[c.isalpha():]or c*i and f(c,i-1)+chr(i^ord(c)&96)

For letter inputs, generates the string of letters recursively. Doing ord(c)&96 removes the 5 high bits, and the xor'ing the values i from 1 to 26 gives the letter char codes. For control flow, we count i down, adding new letters to the end, stopping when i=0. When the input c is not a letter, immediately outputs it and stops.
Thanks to Mauris for 2 bytes.
Previous solution (68):
lambda c:[c,str(bytearray(range(ord(c)&96,255)[1:27]))][c.isalpha()]

The input will be any of the printable ASCII characters from 32 to 126 (space to tilde). Wouldn't ord(c)&96 suffice, then?

@Mauris Yes, good call.

I think '_' --> c works and saves a byte in your recursive solution.

Sed, 61 characters
(60 characters code + 1 character command line option)
s/[a-z]/&abcdefghijklmnopqrstuvwxyz/i
s/[A-Z].*/\U&/
T
s/.//

Sample run:
bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< 'm'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< 'W'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< '@'
@

Python 2.7, 88 bytes (incl. print)
from string import*
def f(c):print[c,uppercase,c,lowercase,c][sorted('@Z`z'+c).index(c)]

JavaScript (ES6), 99 87 79 78 bytes
x=>(y='abcdefghijklmnopqrstuvwxyz',parseInt(x,36)>9?x>'`'?y:y.toUpperCase():x)

Uses the short array fill trick to allocate space, then just math and String.fromCharCode to get the alphabet. Thought it would be shorter until I realized the rule about non-alphabet characters. parseInt turned out to be helpful in determining if the character was in the alphabet.
Test

var F=x=>(y='abcdefghijklmnopqrstuvwxyz',parseInt(x,36)>9?x>'`'?y:y.toUpperCase():x)
x = <input type="text" oninput="result.textContent=this.value?F(this.value):''" />

x=>parseInt(x,36,y='abcdefghijklmnopqrstuvwxyz')>9?x>{}?y:y.toUpperCase():x

Mouse-2002, 125 bytes
... or 126 bytes if I can't assume a REPL envrironment (which assumes a $ at the end of the program; the non-REPL interpreter crashes without one)
An attempt at code deduplication... probably a failed one.
Golfed:
?'a:123b:a.65*1=a.90>a.97<*1=+a.122>+1=[a.!']a.63>a.91<*1=[65i:(i.91<^i.!'i.1+i:)]a.96>a.b.<*1=[97i:(i.b.<^i.!'i.1+i:)]

Ungolfed:
?' a:                    ~ a = getchar();
123 b:                   ~ b = 123
a. 65 <                  ~ return whether a < 65
a. 31 >                  ~ same for 31
  * 1 =                    ~ AND
a. 90 >                  ~ a > 90 ?
a. 97 <                  ~ a < 97 ?
  * 1 =                    ~ AND
+                          ~ OR
a.122 >                  ~ a > 122 ?
  + 1 =                    ~ OR
[                          ~ if 1
  a.!'                       ~ print ascii codepoint
]                          ~ fi
a. 63 >                  ~ a > 63 ?
a. 91 <                  ~ a < 91 ?
  * 1 =                    ~ AND
[                          ~ if 1
  65 i:                      ~ for i = 65;
  (                          ~ do;
    i. 91 < ^                  ~ i < 91;
    i.!'                       ~ print(charAt(i));
    i. 1+ i:                   ~ i++;
  )                         ~ done;
]                          ~ fi
a. 96 >                  ~ a > 96 ?
a. b. <                  ~ a < b ?
  * 1 =                    ~ AND
[                          ~ if 1
  97 i:                      ~ for i = 97;
  (                          ~ do;
    i. b. < ^                  ~ i < 91;
    i.!'                       ~ print(charAt(i));
    i. 1+ i:                   ~ i++;
  )                          ~ done;
]                          ~ fi
$                        ~ \bye

Ruby, 56+2 = 58 bytes
2 bytes for -p flag
c=$_[0]
[?a..?z,?A..?Z].map{|r|r===c&&c=r.to_a.join}
p c

Ungolfed version (no -p flag)
while true
  char = gets.chars.first
  [("a".."z"),("A".."Z")].each do |range|
    char = range.to_a.join("") if range.include? char
  end
  p char
end

s-lang, 40 bytes (non-competing)
Replaces any letter with the alphabet, matching the case.
t@[[a-z]][abcdefghijklmnopqrstuvwxyz]

t Replace with regex function
@ Match case for entire match parameter for t function
[[a-z]] first argument ([a-z]) regex for matching any letter (@ parameter makes it so this function ignores the case when matching, so we don't need A-Z too)
abcdefghijklmnopqrstuvwxyz what to replace it with

Try it here

Java 7, 99 bytes
void f(char c){for(int a=c|32,i=97;i<123;i++)System.out.print(a<123&a>96?(char)(i-a+c):i<98?c:"");}

Slightly more readable, with no scrollbars:
void f(char c){
    for(int a=c|32,i=97;i<123;i++)  // a is lowercased input, i loops alphabet
        System.out.print(
            a<123&a>96?             // if a is a letter
                (char)(i-a+c):      //   subtract diff between lower and input
                    i<98?c:"");     // else print input if first iteration
}

The logic here is pretty straightforward, but a different method than the other Java answer.

Perl 6, 50
{join "",/<:Lu>/??"A".."Z"!!/<:Ll>/??"a".."z"!!$_}

PHP, 60 bytes
for(ctype_alpha($c=$argn)?$c=$c&a|A:$z=25;$z++<26;)echo$c++;

Run as pipe with -R.

Recursiva, 13 bytes
||&N(a(&N)a)a

Try it online!
Explanation:
This roughly translates to 'N(a and (' or 'N)a and )' or a. N(a checks if a is in (. ( and ) are upper and lower-case alphabet yield.

Ly, 32 bytes
"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;

Try it online!
Explanation:
"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;

     is                          # take input and save it
"AZ"R  ~[    ]                   # is it in the uppercase alphabet?
         p&o;                    # output the stack, terminate
              &p                 # clear stack
                     l           # load input
                "az"R ~[    ]    # is it in the lowercase alphabet?
                        p&o;     # output the stack, terminate
                             lo; # output the input, terminate

Python 2, 73 bytes
c=ord(input())
print[chr(c),bytearray(range(c&96|1,c&96|27))][64<c&95<91]

Try it online!

APL (Dyalog Unicode), 26 24 bytes
t←{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵}

Try it online!
The byte count does not include t← because it's not necessary, it just assigns the function to t (so you can call it by using t input).
If input is not a number, it needs to be enclosed in single quotes. For the input ', you need to escape it by typing it twice (so the call is t '''')
Thanks to @Adám for 2 bytes.
How it works:
{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵} ⍝ Main function
             :            ⍝ if
         f←⎕A             ⍝ Assigns the uppercase alphabet to f
   g←819⌶                 ⍝ Assigns the I-Beam command 819 (case convert) over the uppercase alphabet (f) to g
 ⍵∊                       ⍝ The right argument 'is in' the lowercase alphabet
              g           ⍝ then print g (the lowercase alphabet)
               ⋄   :      ⍝ else if
                ⍵∊f       ⍝ the right argument 'is in' f (the uppercase alphabet)
                    f     ⍝ print f
                     ⋄⍵   ⍝ else, print the right argument.

APL (Dyalog), 22 bytes
Unnamed prefix lambda.
{⊃a/⍨⍵∊¨a←⎕A(819⌶⎕A)⍵}

Try it online!
{…} anonymous function where ⍵ represents the argument:
 ⎕A(819⌶⎕A)⍵ uppercase Alphabet, lowercased Alphabet, argument
 a← store in a (for all)
 ⍵∊¨ three Booleans for argument's membership of each those
 a/⍨ filter a by that
 ⊃ pick the first

C (gcc), 94 bytes
#define f(c)isupper(c)?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":islower(c)?"abcdefghijklmnopqrstuvwxyz":&c

#define f(c) is like declaring a function f that takes a variable c.
isupper(c) checks if c is an uppercase letter, returns the uppercase alphabet if so. Otherwise, it checks if it's lowercase. If so, it returns the lowercase alphabet. Otherwise, it returns a pointer to c, which can be printed as a string (since you must pass a char or int to f).
Try it online!

Is it possible to store the alphabet in a variable and use toupper in here (I don't know C)

@StewieGriffin toupper only works on chars, and strtoupper/strupper is not standard C (nor implemented on many systems).

R, 80 bytes
s=(r=65:90)+32
a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%r,r,"if"(a%in%s,s,a)))

Try it online!
-1 byte thanks to Giuseppe. Still not the golfiest way (see here). Similar ideas include:
R, 87 bytes
f=function(x,y)"if"(a%in%x,x,y)
a=utf8ToInt(scan(,''));intToUtf8(f(r<-65:90,f(r+32,a)))

Try it online!
a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%c(32:64,91:96,123:126),a,65:90+32*(a>90)))

and my favorite:
a=utf8ToInt(scan(,''));intToUtf8(c(a,65:90+32*(a>90))[2*a%in%c(32:64,91:96,123:126)-1])

and inspired by the other R solution (same bytecount):
"+"=function(x,y)"if"(a%in%x,x,y)
a=scan(,'');cat(letters+LETTERS+a,sep="")

Try it online!

80 bytes

Noether, 40 bytes
{0A~bI~a/~c}{bP}b{Ua/~d}{bUP}1{cd|-}{aP}

Try it online!
Uses Noether's built-in constant function A to return the string abcdefghijklmnopqrstuvwxyx.

C# .NET, 193 bytes
class P{static void Main(string[]a){var z="ABCDEFGHIJKLMNOPQRSTUVWXYZ";var b=a[0];System.Console.Write(b.Length>1?b:z.IndexOf((b[0]))>-1?z:z.ToLower().IndexOf((b[0]))>-1?z.ToLower():b[0]+"");}}

Try Online EDIT: Variable assignment with if statements is stupid

Zsh, 75 bytes
l=${(j::):-{a..z}} u=$l:u
<<<${${${l:#*$1*}:+${${${u:#*$1*}:+$1}:-$u}}:-$l}

l=${(j::):-{a..z}}                                  # set l to the (j::)oined lowercase
                   u=$l:u                           # set u to :uppercase'd l
<<<${${${l:#*$1*}:+${${${u:#*$1*}:+$1}:-$u}}:-$l}
       ${l:#*$1*}                                   # remove *$1* from $l (is empty if $1 is lower)
     ${          :+                        }        # If non-empty, then...
                       ${u:#*$1*}                   # remove *$1* from $u (is empty if $1 is upper)
                     ${          :+$1}              # If non-empty, substitute $1
                   ${                 :-$u}         # If empty, substitute $u
    ${                                       :-$l}  # If empty, substitute $l

Try it online!

50 bytes using grep

Nice! Post that as a Zsh+coreutils answer if you want, I'll keep this as a pure Zsh answer.

Python 3, 84 bytes
lambda x,a='abcdefghijklmnopqrstuvwxyz':[x,a,a.upper()][(x in a)+2*(x in a.upper())]

Try it online!

Wolfram Language (Mathematica), 62 49 bytes
#/.(#|##->""<>##&)@@@{A=Alphabet[],Capitalize@A}&

Try it online!

Python 3, 93 bytes
i=input();a="abcdefghijklmnopqrstuvwxyz";A=a.upper();print(i in a and a or i in A and A or i)

Under 100 bytes!

C - 65 Bytes
f(c){for(c=islower(c)?97:c>64&c<91?65:c;(putchar(c++)|32)<122;);}

Thanks to @ceilingcat for -5 bytes
Ungolfed (original version)
i = 65;

f(c)
{
    if(isalpha(c))
        while(i < 91)
            putchar(c & 32 | i++);
    else
        putchar(c);
}

Explanation
A function that receives an integer (the input character) and prints it if it is not a letter or prints the entire alphabet with the capitalization of the input character.

Seriously, 17 bytes
    ;;ú(úíuIúû;(@íuI

Hex Dump:
093b3ba328a3a17549a3963b2840a17549

Try It Online
Given that it pretty much just reads in an unformatted byte, checks if it's in the lowercase alphabet, then checks if it's in the uppercase alphabet, the automatic documentation given in the link is sufficient. (Note, however, that the documentation for í has the argument order reversed; it pops the sequence first.)

k4, 24 bytes
{*b@&x in/:b:(.Q`A`a),x}

Another port of the Pyth answer—constructs a list of upper, lower, and the arg, and returns the first one that contains the arg.

Sprects, 207 bytes
|<CHAR>|ZA|YA|XA|WA|VA|UA|TA|SA|RA|QA|PA|OA|NA|MA|LA|KA|JA|IA|HA|GA|FA|EA|DA|CA|BA|AABCDEFGHIJKLMNOPQRSTUVWXYZ|za|ya|xa|wa|va|ua|ta|sa|ra|qa|pa|oa|na|ma|la|ka|ja|ia|ha|ga|fa|ea|da|ca|ba|aabcdefghijklmnopqrstuvwxyz

Enter character on <CHAR>.

AWK 104 bytes
/[a-z]/{print"abcdefghijklmnopqrstuvwxyz"}
/[A-Z]/{print"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
/[^A-z]/{print$0}

Powershell, 116 bytes
$b='j';$a='ABCDEFGHIJKLMNOPQRSTUVWXYZ';switch($b){{$b-cmatch'[a-z]'}{$a.ToLower()}{$b-cmatch'[A-Z]'}{$a}default{$_}}

Change $b='j' to modify result.
I couldn't figure out a way to get the alphabet that was shorter than just writing the alphabet unfortunately.
e.g. (65..90|%{[char][byte]$_})-join''

This appears to be whats called a snippet program, where input is taken from a variable, in this case b.  Snippets are not allowed so you should restructure to either a function or a full program.

Hi and welcome to PPCG! Take a look at New users' guide to PowerShell and Tips for golfing in Windows PowerShell to get some basics. Secondly, to get the alphabet shorter, try -join[char[]](65..90) for 21 bytes.

REXX, 75 bytes
b=arg(1)
a=xrange(a,z)
if b>z then a=lower(a)
if verify(b,a) then a=b
say a

Excel VBA, 114 Bytes
Anonymous VBE immediate window function that takes input and outputs to the VBE immediate window.
a=Asc([A1]):i=IIf(a>64And a<91,64,(a>96And a<123)*-96):?IIf(i=0,[A1],"");:If i>0 Then For j=1To 26:?Chr(i+j);:Next

Jelly, 11 bytes
XØA,Øa¤ċÐfȯ

Try it online!

Ink, 103 bytes
VAR u="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
VAR l="abcdefghijklmnopqrstuvwxyz"
=o(c)
{u?c:{u}|{l?c:{l}|{c}}}->->

Try it online!

05AB1E, 17 bytes
AsAus©åiAuë®åiAë®

Try it online or verify all test cases.
                   # (implicit) push STDIN to stack
A                  # push "abcdefghijklmnopqrstuvwxyz"
 s                 # swap top two values of stack
  Au               # push "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    s              # swap top two values of stack
     ©             # store top of stack in register_c
      åi           # if top of stack in second-to-top of stack...
        Au         # push "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
          ë®åi     # elif value of register_c in second-to-top of stack...
              A    # push "abcdefghijklmnopqrstuvwxyz"
               ë   # else...
                ®  # push value of register_c
                   # (implicit) output top of stack to STDOUT

Pyt, 17 bytes
ĐĐʊɔ?ĉʊ:ŕɫɔ?ĉɫ:ŕ;

Try it online!
ĐĐ                     implicit input; duplicate twice on stack
  ʊɔ?ĉʊ:               is it a lowercase letter? if so, push lowercase letters
        ŕɫɔ?ĉɫ:        else is it an uppercase letter? if so, push uppercase letters
               ŕ       otherwise, leave input on stack
                ;      end if-then-else statements; implicit print

Zsh*+coreutils, 45 bytes
l=${(j::):-{a-z}};<<<"$l
$l:u"|grep $1||<<<$1

Try it online!
(*) Using setopt braceccl to save 1 byte

Thunno 2, 9 bytes
A?fh?kA:Ạ

Attempt This Online!
Thunno 2, 13 bytes
ẠD$Ƈ?:RD$Ƈ?:$

Attempt This Online!
Explanation
A?fh?kA:Ạ  # Implicit input
A?         # If it's alphabetic:
  fh?      #  If it's uppercase:
     kA    #   Push the uppercase alphabet
       :   #  Otherwise:
        Ạ  #   Push the lowercase alphabet
           # Otherwise, the input remains on top
           # Implicit output

ẠD$Ƈ?:RD$Ƈ?:$  # Implicit input
ẠD             # Push the lowercase alphabet and duplicate
  $Ƈ           # Pop one copy and check if the input is in it
    ?          # If it is, do nothing, leaving the lowercase alphabet
               # on the top of the stack to be implicitly output
     :         # Otherwise:
      RD       #  Push the uppercase alphabet and duplicate
        $Ƈ     #  Pop one copy and check if the input is in it
          ?    #  If it is, do nothing, leaving the uppercase alphabet
               #  on the top of the stack to be implicitly output
           :$  #  Otherwise, push the input
               # Implicit output of top of stack


text:
Recreate the sentence
This challenge consists of two parts. The winner will be the solution with the lowest total byte count. The same language must be used for both challenges.
Part 1:
Write a function or program that takes a sentence with only valid words as input, and outputs a list of the used characters, the number of times each letter is used, and the number of letters in each of the words in the original sentence. The output from this program must be valid input to the next program (exactly as it is outputted)
I'll add examples and detailed rules further down.
Part 2:
Write a function or program that takes the output from the first program as input and uses this list of English words and recreates a sentence with the information from the output. The sentence doesn't have to be the same as the original sentence.
More information. rules and restrictions:
Part 1:

The first input can be on any suitable format, with or without quotation marks, as function argument or from STDIN, with or without brackets etc.
The input sentence will not contain any punctuation or special characters, except for a period/dot in the end. Except for the period symbol, all characters that are in the input will be in the word list.
The first letter of the sentence will be upper case, the rest will be lower case.
The output of part 2 must start with the same upper case letter as the original sentence (so converting the input to lower case is not recommended (but OK).
The output can be on any suitable format:

It must be possible to copy-paste the output directly into the next program / function
No alterations can be made when copy-pasting, the entire output must be copied and pasted as a whole, not in parts.
You may for instance output a histogram of all letters in the alphabet, or only the ones used (in general, whatever is necessary to complete part 2)
You can not output a list of characters where multiple occurrences are repeated. For instance, The queue can't yield an output: Teeehquu (3,5), it should be something like: Tehqu, (1 3 1 1 2),(3 5).

Part 2:

The program / function must accept the input exactly as is from part 1 (one exception, see comment below about taking file name as input.).

If surrounding brackets, quotation marks or similar are necessary to parse the input then these must be part of the output from part 1.

The word list can be found here.

The word list can either be saved locally as w.txt, or it can be fetched from the url. The url will only count as 5 bytes, so you don't need a url-shortener.
If the program can't open a file without reading the name as an input from STDIN (I believe this is was the case for Pyth at least), then the file name can be taken as a separate input argument.

The output must be only a sentence (list of valid words), ending with a period and an optional newline.

The output must have words with the same number of letters as the original sentence in part 1 (in correct order)
All the letters that were used in the original sentence must be used in the new output.
The sentence must start with the same upper case letter as the original input sentence and end with a period.

Both parts:

Neither of the parts should take more than 2 minutes to execute (randomly picking out words until a solution is reached is not accepted).

With the rules listed above, there should be a fair chance that the exact same sentence is reproduced, however that is not a requirement.
Examples:
In the below examples, a few different input and output formats are shown. Many more are accepted.
Part 1:
Input:
Zulus win.

Output type 1:
Z i l n s u w
1 1 1 1 1 2 1
5 3

Output type 2:
(('Z',1),('i',1),('l',1),('n',1),('s',1),('u',2),('w',1)), (5,2)

Output type 3:
'Zilnsuuw',[1,1,1,1,1,2,1],[5,2]

Part 2:
Input: An exact copy of the output from part 1.
Output:
Zulus win.

Note that other word combinations are accepted as long as they start with a Z, and the first word has 5 letters and the second has 3.
The shortest code in bytes win.

Here's the commit: https://github.com/isaacg1/pyth/commit/f17cfaced7e0f75ffb3f53a4924529e188e2542b

@LegionMammal978: Yes, you can do this under the following restrictions: The output from f1 that's pasted into f2 must contain all the data specified in the challenge. No additional data can be part of the output from f1. No data can be "stored" in f1 making information available when calling it from f2. f1 can only take one string as input per call.

The chance to get the same sentence out with more than 3 words is actually pretty bad i think

In general yes, but there are many cases where you're likely to get the same sentence out. If your grandma is tired of redoing your old sweater, she might be: "quitting refitting knitting". I haven't checked, but I would think your grandma will still be quitting after part 2. Also combinations of longer words might give the same sentence back.

There are a lot of commonly used sentences that will probably give the same sentence back... For instance: Wow counterrevolutionaries characteristically use wigs. I'll admit, I don't know for sure, but it's at least likely.

@StewieGriffin You could easily get "Wig...wows." back with that example sentence.

LabVIEW, 166 LabVIEW Primitives
First of all i did not create 2 seperate programms because Labview does dataflow so theres really no need.
Saves the histogramm with first element = ascii code of first letter rest from 1-26 go by amount. Lenght simply gets saved in an array.
The first word has 3 checks, first letter, lenght and available letters in histogram. The first letter check stops after the first word.
I check the histogram by decrementing it for every letter and checking if it would fall below 0.
If i found my Nth word and there are no words that are buildable from the left over letters i will start deleting words from the dictonary and redo the Nth word and so on until i have found a solution.
This might or might not work for sentences there are, since that would take forever to compute (my example took a few seconds already).
What i tried
In: Zulus win.
Out: Zulus win.

In: Dovecot flagships oleander.
Out: Dolphin advocates forelegs.

In: Abash abel mammal test.
Out: Amass abbe hamlet malt.

Perl, 516 504 bytes
includes 2x +1 for -p
@l=map{length}/\w+/g;s/\w/$c{$&}++/eg;@h=map{"$_$c{$_}"}keys%c;$_="@h @l";chomp(@w=`cat w.txt`);s/([A-Z])1//;$o=$1;s/(\w)(\d)/$h{$1}=$2,''/eg;@L=/\d/g;$l=shift@L;@O=$_,s/^.//,g([@L],%h)&&last for grep{$l==length&&/^$o/i&&h(\%h,substr$_,1)}@w;$_="@O.";s/^./uc$&/e;sub g{my%g;($R,%g)=@_;my@R=@$R;if($j=shift@R){s/./$g{$&}--/eg;my@C=grep{$j==length&&h(\%g,$_)}@w;push(@O,$_),g([@R],%g)and return 1 or pop@O for@C;0}else{1}}sub h{($y,$z)=@_;my%T;$z=~s/\w/$T{$&}++/eg;$K=1;$K&=$T{$_}<=$y->{$_}for keys%T;$K}

Requires to have w.txt in unix format (\n line endings). Uses cat to read the file; change to type for windows.
Save the oneliner above in 534.pl and run as echo Test. | perl -p 534.pl.
Pretty large, but it's a start - lots of golfing opportunities, but I just wanted to post it
to make the LabVIEW answer less lonely ;-).
I've omitted the optimisations for sub-second execution, saving 30+ bytes.

First snippet (73 bytes):
@l=map{length}/\w+/g;s/\w/$c{$&}++/eg;@h=map{"$_$c{$_}"}keys%c;$_="@h @l"

It produces a histogram and the word lenghts in a compact format. For input Zulus win. it produces a type-2 output
without the (,), which aren't necessary here:
s1 l1 u2 Z1 w1 i1 n1 5 3

Here it is, ungolfed:
sub i{
    $_=shift;                       # get parameter
    @l = map{length} /\w+/g;        # cound word lengths
    s/\w/$c{$&}++/eg;               # count letters in hash %c
    @h=map{"$_$c{$_}"}keys%c;       # construct letter-frequency pairs
    "@h @l"                         # implicit interpolation with $" (space) separator
}

Second snippet (441 bytes)
This main part deals with I/O and the special treatment of the first letter,
using subroutines g and h that are listed below.
sub o {
    $_=shift;
    chomp(@w=`cat w.txt`);          # load the wordlist.

    s/([A-Z])1//; $o=$1;            # get and remove the uppercase character,
    s/(\w)(\d)/$h{$1}=$2,''/eg;     # reconstruct histogram in hash %h.
    @L=/\d/g;                       # get the word counts.

    $l = shift @L;                  # get the first word length.

    @O = $_,                        # initialize output with first word,
    s/^.//,                         # strip first char of word
    g([@L],%h) && last              # call the main algoritm and quit on success

    for grep {
            $l==length &&           # check length
            /^$o/i &&               # only match words starting with the uppercase char
            h(\%h,substr$_,1)       # check if the word satisfies the histogram
        } @w;                       # iterates all words (speedups removed).

    $_="@O.";                       # construct output sentence.
    s/^./uc$&/e;                    # make first char uppercase.
    $_
}

This recursive function takes a copy of the histogram, a copy of the remaining word counts,
and the current word.
If the word-length array is empty, returns true.
Else it decrements the histogram count for the letters in the given word, takes the next
word-length, and finds a list of suitable words from the wordlist. For each suitable word,
it recurses.
sub g {
    my%g;                           # local version of histogram
    ($R,%g)=@_;                     # get parameters.
    my@R=@$R;                       # dereference arrayref copy of word lengths.

    if($j=shift @R)                 # get the next word-length.
    {
        s/./$g{$&}--/eg;            # update histogram

        my @C =                     # get a list of suitable words.
        grep { $j==length && h(\%g,$_) }
        @w;

        push(@O,$_),                # append word to output
        g( [@R], %g )               # recurse.
            and return 1            # true: append word we're done.
            or pop @O               # remove word from output
        for @C                      # (for some reason the @C=grep doesn't work here)

        ;0
    } else { 1 }                    # no more words, done!
}

And finally, this subroutine is given a word and the sentence histogram.
It calculates a new histogram for the word
and checks whether all letters do not occur more often than
permitted by the sentence histogram.
# check if first histogram is within bounds of second
sub h{
    ($y,$z)=@_;
    my%T; $z =~ s/\w/$T{$&}++/eg;    # calc histogram

    $K=1;
    $K &= $T{$_} <= $y->{$_}
    for keys %T;#$_[0];
    $K
}

You can paste the ungolfed snippets (sub i/o/g/h) in a single file and append the below
test code.
sub t {
    print $i=i(shift),$/,o($i),$/x2;
    %c=%h=@L=@X=@O=();
}

t "Test.";                              # Test.
t "Zulus win.";                         # Zulus win.
t "Happy solstice.";                    # Happy solstice.
t "Abash abel mammal test.";            # Abase alms embalm that.
t "Dovecot flagships oleander.";        # Dangled horoscope festival.
t 'This code requires further golfing.';# Tech deer fighting ferrous liquors.

update 504: save 12 bytes eliminating a substr and a parameter for sub g.

I see, stealing my examples! Just kidding the rasults are hilarious XD

@Eumel Yeah, they were different from yours so I included them :-)

Python 2.7, 353 bytes
Unfortunately, I can't test it with the actual w.txt file ATM because QPython for Android can't seem to handle file I/O. It worked with data I copied and pasted though.
Part 1, 76 bytes
h=lambda s:({c:s.count(c)for c in s if c.isalnum()},map(len,s[:-1].split()))

In: 'Hi there.'
Out: {'H':1, 'i':1, 't':1, 'h':1, 'e':2, 'r':1}, (2, 5)
so, a list containing:

a hashmap with the histogram

a list of letter counts

Part 2, 277 bytes
import itertools as i
m=lambda c:' '.join([s for s in i.product(*[[w for w in open('w.txt')if len(w)==length]for length in c[1]])if sorted(''.join(s))==sorted(sum([[k.lower()]*n for k,n in c[0].items()],[]))and s[0][0]==filter(str.isupper,c[0])[0].lower()][0]).capitalize()+'.'

I'm really glad I managed to make it 100% pure functional. Not sure if that helps with the actual golfing, but I certainly got the obfuscation part right :D Here's A more human friendly version of pt. 2 (exactly the same flow, but with variable names):
from itertools import product

def matching(counts):
  histo, word_lengths = counts
  first_letter = filter(str.isupper, histo)[0].lower()

  letters_nested = [ [char.lower()]*count for char, count in histo.items() ]
  letters = sum(letters_nested, [])

  word_options = [[word for word in open('w.txt') if len(word)==length] for length in word_lengths]

  sentences = product(*word_options)

  valid = [sentence for sentence in sentences if sorted(''.join(sentence))==sorted(letters) and sentence[0][0]==first_letter]
  return ' '.join(valid[0]).capitalize()+'.'

source: Stack Exchange

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

sort: votes


text:
Forgotten Realms date calculator
In an effort to level the playing field between languages with built-in date libraries and those without, let's work with a fictional calendar. The Forgotten Realms are a (the?) campaign setting for Dungeons & Dragons. Of course, each have their own calendar.
The Calendar of Harptos
Conveniently, a year in the Forgotten Realms also has 365 days. Furthermore, the calendar also has 12 months. However, this is where it gets interesting. Each month is exactly 30 days long. The remaining 5 days are holidays which fall between the months. Here are the months and holidays in order (with holidays indented):
1   Deepwinter
        Midwinter
2   The Claw of Winter
3   The Claw of the Sunsets
4   The Claw of the Storms
        Greengrass
5   The Melting
6   The Time of Flowers
7   Summertide
        Midsummer
        [Shieldmeet]
8   Highsun
9   The Fading
        Highharvestide
10  Leaffall
11  The Rotting
        The Feast of the Moon
12  The Drawing Down

Notice that I've inserted a sixth holiday in brackets. This is the leap day which only occurs every four years (yes, that's it — there are no additional shenanigans with the centuries).
Side note about month names: each month has a formal and a common name. The above are the common names. I've picked those because I think they allow for more interesting compression.
There are several numberings of the years, but the most widespread one is Dalereckoning, shortened to DR. (Also, every year has one or more names, but we're not going to bother with that.)
The components of a date should be separated by a comma and a space. All in all, a valid date might look like:
4, The Melting, 1491 DR

or
Shieldmeet, 1464 DR

Note that there is no day number for the holidays. (I suppose 4th of The Melting would be nicer for the days of the months, but I don't want to drag ordinal numbers into this.)
Footnote: I came up with this when xnor complained that every single date challenge needs the leap year computation. I've failed in eliminating it completely, but at least it's only a single modulo in this calendar.
The Challenge
Given a valid date of the Calendar of Harptos, as well as an integer D, output the date D days later. Note that D may be negative, in which case you should return the date D days earlier.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
You may assume that the year is positive and less than 2000.
Standard code-golf rules apply.
Test Cases
The first dozen or so test cases should test all the edge cases surrounding holidays and leap years. The next set are to test that ranges across multiple years work and all months and holidays have been implemented. The second half is all the same test cases again but with negative offsets.
"30, Summertide, 1491 DR" 1                 => "Midsummer, 1491 DR"
"30, Summertide, 1491 DR" 2                 => "1, Highsun, 1491 DR"
"Midsummer, 1491 DR" 1                      => "1, Highsun, 1491 DR"
"30, Summertide, 1492 DR" 1                 => "Midsummer, 1492 DR"
"30, Summertide, 1492 DR" 2                 => "Shieldmeet, 1492 DR"
"30, Summertide, 1492 DR" 3                 => "1, Highsun, 1492 DR"
"Midsummer, 1492 DR" 1                      => "Shieldmeet, 1492 DR"
"Midsummer, 1492 DR" 2                      => "1, Highsun, 1492 DR"
"Shieldmeet, 1492 DR" 1                     => "1, Highsun, 1492 DR"
"1, Highsun, 1490 DR" 365                   => "1, Highsun, 1491 DR"
"1, Highsun, 1491 DR" 365                   => "Shieldmeet, 1492 DR"
"Shieldmeet, 1492 DR" 365                   => "Midsummer, 1493 DR"
"Midsummer, 1493 DR" 365                    => "Midsummer, 1494 DR"
"Shieldmeet, 1500 DR" 365                   => "Midsummer, 1501 DR"

"14, Deepwinter, 654 DR" 5069               => "The Feast of the Moon, 667 DR"
"Midwinter, 17 DR" 7897                     => "15, The Fading, 38 DR"
"3, The Claw of Winter, 1000 DR" 813        => "25, The Claw of the Storms, 1002 DR"
"Greengrass, 5 DR" 26246                    => "9, The Claw of the Sunsets, 77 DR"
"30, The Melting, 321 DR" 394               => "29, The Time of Flowers, 322 DR"
"17, The Time of Flowers, 867 DR" 13579     => "20, Highsun, 904 DR"
"Highharvestide, 1814 DR" 456               => "30, The Drawing Down, 1815 DR"
"23, The Rotting, 1814 DR" 3616             => "16, Leaffall, 1824 DR"
"1, Deepwinter, 1 DR" 730499                => "30, The Drawing Down, 2000 DR"

"Midsummer, 1491 DR" -1                     => "30, Summertide, 1491 DR"
"1, Highsun, 1491 DR" -2                    => "30, Summertide, 1491 DR"
"1, Highsun, 1491 DR" -1                    => "Midsummer, 1491 DR"
"Midsummer, 1492 DR" -1                     => "30, Summertide, 1492 DR"
"Shieldmeet, 1492 DR" -2                    => "30, Summertide, 1492 DR"
"1, Highsun, 1492 DR" -3                    => "30, Summertide, 1492 DR"
"Shieldmeet, 1492 DR" -1                    => "Midsummer, 1492 DR"
"1, Highsun, 1492 DR" -2                    => "Midsummer, 1492 DR"
"1, Highsun, 1492 DR" -1                    => "Shieldmeet, 1492 DR"
"1, Highsun, 1491 DR" -365                  => "1, Highsun, 1490 DR"
"Shieldmeet, 1492 DR" -365                  => "1, Highsun, 1491 DR"
"Midsummer, 1493 DR" -365                   => "Shieldmeet, 1492 DR"
"Midsummer, 1494 DR" -365                   => "Midsummer, 1493 DR"
"Midsummer, 1501 DR" -365                   => "Shieldmeet, 1500 DR"

"The Feast of the Moon, 667 DR" -5069       => "14, Deepwinter, 654 DR"
"15, The Fading, 38 DR" -7897               => "Midwinter, 17 DR"
"25, The Claw of the Storms, 1002 DR" -813  => "3, The Claw of Winter, 1000 DR"
"9, The Claw of the Sunsets, 77 DR" -26246  => "Greengrass, 5 DR"
"29, The Time of Flowers, 322 DR" -394      => "30, The Melting, 321 DR"
"20, Highsun, 904 DR" -13579                => "17, The Time of Flowers, 867 DR"
"30, The Drawing Down, 1815 DR" -456        => "Highharvestide, 1814 DR"
"16, Leaffall, 1824 DR" -3616               => "23, The Rotting, 1814 DR"
"30, The Drawing Down, 2000 DR" -730499     => "1, Deepwinter, 1 DR"

DragonLance is another major D&D campaign setting. I can't remember much about their calendar except for their three moons, the orbits of which were explained in detail in some reference book.

Ruby, 543 523 521 498 511 509 bytes
To encourage more answers to this question, I'm going to post a Ruby version of my Python answer, since I figured it would be shorter. This answer is shorter but not by much. Can you do better?
Edit: With thanks to Martin Büttner and his suggestion here.
Edit: I golfed the "number of days in a month" list down considerably.
Edit: While golfing down how I handled d[10]=r%4<1?1:0 to d[10]=0**(r%4) for a byte, I noticed I'd introduced a bug while golfing down d, the number of days list, so that Shieldmeet had 30 days by accident. And so, the byte count has come back up. I will also edit the Python answer to fix this bug there.
Edit: I forgot that functions don't need to be named in this question.
->s,n{x=s[0..-4].split(", ");x=x[2]?x:[1,*x];t=(["Deepwinter,Midwinter","Winter","Sunsets","the Storms,Greengrass,The Melting,The Time of Flowers,Summertide,Midsummer,Shieldmeet,Highsun,The Fading,Highharvestide,Leaffall,The Rotting,The Feast of the Moon,The Drawing Down"]*',The Claw of ').split(?,);p,q,r=x[0].to_i+n,t.index(x[1]),x[2].to_i;d=[30,1,30,30]*4+[1,30];d[10]=0**(r%4);(a=p<1?1:-1;q=(q-a)%18;p+=a*d[a<0?q-1:q];r-=a*0**q;d[10]=0**(r%4))until(1..d[q])===p;z=d[q]<2?[t[q],r]:[p,t[q],r];z*", "+" DR"}

Ungolfed:
def h(s,n)
  x=s[0..-4].split(", ")
  x=x[2]?x:[1,*x]
  t=["Deepwinter,Midwinter","Winter","Sunsets","the Storms,Greengrass,The Melting,The Time of Flowers,Summertide,Midsummer,Shieldmeet,Highsun,The Fading,Highharvestide,Leaffall,The Rotting,The Feast of the Moon,The Drawing Down"]
  t=t*',The Claw of '           # turns the above array into a string with "Claw"s inserted
  t=t.split(?,)                 # then splits that string back up again by ","
  p=x[0].to_i+n
  q=t.index(x[1])
  r=x[2].to_i
  d=[30,1,30,30]*4+[1,30]
  d[10]=0**(r%4)
  until(1..d[q])===p
    a=p<1?1:-1
    q=(q-a)%18
    p+=a*d[a<0?q-1:q]
    r-=a*0**q
    d[10]=0**(r%4)
  end
  z=d[q]<2?[t[q],r]:[p,t[q],r]  # putting z=[t[q],r] on another line saved me no bytes
  z*", "+" DR"
end

Python 3, 712 652 636 567 563 552 550 548 529 540 bytes
At last, I found time to write an answer for this excellent question. It isn't very golfed yet (the month names list and the number of days list are is particularly egregious in this case, and the fact that handling negative D requires a separate while loop) but at least it's an answer.
Edit: Fixing a bug
def h(s,n):
 x=s[:-3].split(", ");x=[1]*(len(x)<3)+x;t="Deepwinter,Midwinter,The Claw of Winter,The Claw of the Sunsets,The Claw of the Storms,Greengrass,The Melting,The Time of Flowers,Summertide,Midsummer,Shieldmeet,Highsun,The Fading,Highharvestide,Leaffall,The Rotting,The Feast of the Moon,The Drawing Down".split(",");p,q,r=int(x[0])+n,t.index(x[1]),int(x[2]);d=[30,1,30,30]*4+[1,30];d[10]=r%4<1
 while p>d[q]or p<1:a=[-1,1][p<1];q=(q-a)%18;p+=a*d[q-(a<0)];r-=a*0**q;d[10]=r%4<1
 return', '.join([str(p)]*(d[q]>2)+[t[q],str(r)])+" DR"

Ungolfed:
def harptos(date, num):
    t = "Deepwinter,Midwinter,The Claw of Winter,The Claw of the Sunsets,The Claw of the Storms,Greengrass,The Melting,The Time of Flowers,Summertide,Midsummer,Shieldmeet,Highsun,The Fading,Highharvestide,Leaffall,The Rotting,The Feast of the Moon,The Drawing Down"
    t = t.split(",")        # split up the names of the months
    x = date[:-3]           # removes " DR"
    x = x.split(", ")
    if len(x) < 3:
        x = [1] + x         # if we have two items (holiday), append a "day of the month"
    p = int(x[0]) + num     # initialize the "date" by adding num to it
    q = t.index(x[1])
    r = int(x[2])
    d=[30,1,30,30]*4+[1,30] # all the month lengths
    d[10] = r%4 < 1         # leap year toggle
    while p > d[q]:         # while the "date" > the number of days in the current month
        p -= d[q]           # decrement by number of days in current month
        q = (q+1)%18        # increment month
        r += 0**q           # increment year if the incremented month == the first month
        d[10] = r%4 < 1     # leap year toggle
    while p < 1:            # while the "date" is negative
        q = (q-1)%18        # decrement month first
        p += d[q]           # add the number of days in the decremented month
        r -= 0**q            # decrement year if the decremented month == the first month
        d[10] = r%4 < 1     # leap year toggle
    m = [t[q],str(r)]       # start the result array
    if d[q] > 2:
        m = [str(p)] + m    # if the month is NOT a holiday, add the day
    return ", ".join(m) + " DR"

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


text:
cat file reader with line numbering
You must do a program that reads a file given in first argument and print it's content to STDOUT and number the lines on the file, the numbers should be followed by a space.
For instance, assuming that your program is named cat, we could write
./cat "myfile.txt" (or execute it with its interpreter)
With myfile.txt:
Hello, world, this
is a file with
multiple characters..0

And the program should output to STDOUT :
1  Hello, world, this
2  is a file with
3  multiple characters..0

The shortest program in bytes win.
For example :
Perl
$r++&print"$r ".$_ while<>

Well, this one is a bit simpler than the Line numbering - implement nl. On this last one, there are restrictions on the length of the file and the program must return error codes. What I want to do here is the smallest program in many languages for just a simple thinks, no matter the length of the file and with only one file at a time.

LabVIEW, 32 LabVIEW Primitives
Reads line by line and concatenates numbers space and newlines, then deletes a trailing number, space and newline.


text:
Find my word(s)!
The idea of this challenge is to find all the words from a dictionary on a grid of letters. Your input should come from stdin or function arg and will come in the following format:
[your dictionary as a list of space sep words]
[a grid of letters]

Example:

The cool car
looc
thea
jopr

Rules for finding a match
A match is valid if it is found diagonally, horizontally, or vertically on the board (case insensitive). The direction doesn't matter (e.g. look matches kool). If there are multiple matches of the same word, mark all of them.
Output:
Your output will be the grid you were given - with the minor change that the letters will be space separated and the lines will be double spaced. Example:
Input:
looc
thea
jopr

Output:
l o o c

t h e a

j o p r

To represent a match you will put an arrow between letters that go together. The arrows (/\-|X) will point to each pair of letters that are grouped in a match. X is used if /\ intersect.
Examples:
Input:
The cool car
looc
thea
jopr

Output:
l-o-o-c
      |
t-h-e a
      |
j o p r

Input:
Atomic chess is cool
achess
btoikm
bloosi
nowmlp
hewiir
asdfec

Output:
a c-h-e-s-s
 \ \   /
b t o i k m
   \ \ \
b l o o s-i
     \ \
n o w m l p
       \
h e w i i r
         \
a s d f e c

Input:
This is very neat words var are fun rob bot robot
wotsdsearn
siiewfvery
chheruoawd
tetoennore
asbdrgrehe
aobyedycab
tweosttgwt

Output:
w o t s d s e a r n
     /
s-i i e w f v-e-r-y
   /      |  \
c h h e r u o a w d
 /     /  |    X
t e t o e n n o r e
     /       X   \
a s b d r g r e h e
   /       /   \
a o b y e d y c a b
 /       /       \
t w e o s t t g w t

Related: http://codegolf.stackexchange.com/q/37940/42963

I can't imagine this going under 30 bytes.

how much time did you spend writing the test inputs? it seems like a lot of work

About 10-15 min. It wasn't to hard, even by hand (though is is quite error prone).

This seems actually very challenging to program, even without golfing it.

I don't know if it's worth changing with two answers already on the board, but we usually allow a more flexible input format here.

Drat, I didn't think about that. I forgot to include that you could write a function that takes a string...

@ThomasKwa What other formats would be considered common?

I'm still waiting for that Pyth or CJam answer that will be under 40 bytes...

Uh, reviewing the text of the challenge I see that I should get a single string as input, my fuction has 2 parameters instead. I'll fix it later

Some questions ... is the grid always lowercase as in the example? And if not, the casing should be kept in output?

... and (case intensive) should be read (case insensitive) or plainly the contrary?

Darn, I didn't think of that. Well its a little late to change it so I just go ahead and ignore casing.

JavaScript (ES6), 303 315
Mostly based on this answer
Edit 1

Following OP comment, ignoring casing and forcing all to lowercase.
Fixed the arguments, now just a single string argument that get splitted

Note: using template strings, there are 3 newlines in the code that are significant and incuded in the byte count
l=>(l=l.toLowerCase().split`
`).shift(r=l[1].length*4).split` `.map(v=>[2,-2,r,-r,r+2,-r-2,r-2,2-r].map((d,k)=>o.map((t,p)=>[...v].some((c,i)=>z[i?(z[i=t+d/2]=z[i]>' '?'X':'-|\\/'[k>>1],t+=d):t=p]!=c,z=[...o])?0:o=z)),o=[...l.map(s=>' '.repeat(r/2-1)+`
${[...s].join` `}
`).join``.slice(r/2)])&&o.join``

Explained (outdated)
// Note a pattern : in golfed code (but not in the following explanation),
//                  simple operations that have to done before calling .map or .every
//                  are inserted as parameter 2,3,etc... to the same function
//                  as each parameter is evaluated before calling a function
//
F=( l, // word list as a space separated string
    o, // character grid as a newline separated string - each row is the same length
    // default parameters used as local variables
    r = 4 * o.search`\n` // offset from a line to next nonblank line in resulting output
  )=>(
    w = ' ', // shortcut for blank
    // given the input string in o, build the result as a single dimension array filled with blanks
    // between characters and runs of blank chars betweem each row
    // .map used as a shorter .forEach
    z = w, // init z to a single blank
    [...o].map( c=> // for each char of o execute the following
                c > w // check if c is a letter (>' ') or a newline
                 ? z+=w+c // if c is a letter, add ' '+c to z
                 : ( // if c is a newline add chars to array o
                     z = z.slice(2), // remove the first 2 char of z ('  ' or '\n ')
                     z = [...z], // convert to array
                     o.push(...z, // push one by one the chars of z
                            c, // then c (a newline)
                            ...z.fill(w), // the same number of char as z, but all blanks
                            z = c // a newline again, meanwhile reset z
                           )
                   )
            , o=[] // o is reset to an empty array just in the map call
                   // reusing o just to avoid another global variable (no real need in fact)
    ), // end of .map call
    l.split` `.map( // split l into words and exec the following for each word
      v => [2,-2,r,-r,r+2,-r-2,r-2,2-r].map( // for each scan direction
        (d,k) => // d is the move offset , k is the index 0 to 7
        o.map( // for each char in (including fill blanks and newlines, the scan will fail for them)
          (t,p) => // t is the first character but NOT USED (var t reused), p is the start position
          (
            z=[...o], // make a copy of o in z
            t = p-d, // current position-d goes in t, it will be incremented before using
            [...v].every( // check the following conditions for every char of word v
            (c,i) => // c: current char of word, i: index used to differentiate the first check when i==0
              (
                // while scanning I already modify the result working copy in z
                i ? // if i != 0
                  // fill the intermediate position with the right fiil character
                  // based on direction index in k, or X if the position is already full
                  z[i = t+d/2] = z[i] > w ? 'X' : '--||\\\\//'[k]
                : 0, // else do nothing
                // case insensitive comparison, if not a letter parseInt returns NaN that is != from any value
                // this is the condition retured to the .every function
                parseInt(c,36)==parseInt(o[t+=d],36) // meanwhile increment position in T
              )
            ) ? // check the result of .every
            o = z // if true, update o from the working copy
            : 0 // if false do nothing
          ) // end of o.map operations
        ) // end of o.map function call
      ) // end of direction list map function call
    ) // end of l.split.map function call
    , o.join``
  )

TEST

console.log=(...x)=>O.textContent+=x.join` `+`\n`;

F=l=>
  (l=l.toLowerCase().split`\n`)
  .shift(r=l[1].length*4).split` `.map(v=>[2,-2,r,-r,r+2,-r-2,r-2,2-r].map((d,k)=>o.map((t,p)=>
    [...v].some((c,i)=>z[i?(z[i=t+d/2]=z[i]>' '?'X':'-|\\/'[k>>1],t+=d):t=p]!=c
    ,z=[...o])?0:o=z)
  ),o=[...l.map(s=>' '.repeat(r/2-1)+`\n${[...s].join` `}\n`).join``.slice(r/2)])
  &&o.join``

console.log(F('Atomic chess is cool\nachess\nbtoikm\nbloosi\nnowmlp\nhewiir\nasdfec'))

console.log(F("RANDOM VERTICAL HORIZONTAL WIKIPEDIA Tail WordSearch CODEGOLF UNICORN\nWVERTICALL\nROOAFFLSAB\nACRILIATOA\nNDODKONWDC\nDRKESOODDK\nOEEPZEGLIW\nMSIIHOAERA\nALRKRRIRER\nKODIDEDRCD\nHELWSLEUTH"))

Very very impressive

Did not see that. You destroyed my answer. :( +1

Javascript (ES6), 908 901 609 603 556 552 bytes
a=>(a=a.toLowerCase().replace(/\n/g,`

`).split`
`,b=a.slice(2).map(r=>r.length?r.replace(/./g,i=>i+` `).trim().split``:Array(a[2].length*2-1).fill(` `)),a[0].split` `.forEach(c=>{for(y=0;y<b.length;y+=2){for(x=0;x{d.map(k=>{e=`\\|/
-o-
/|\\`.split(`
`)[l/2+1][k/2+1];try{(f=(g,h,j)=>g>=c.length?1:(ch=c[g],((k||l)&&b[j+l][h+k]==ch&&f(g+1,h+k,j+l))?(b[j+l/2][h+k/2]=((b[j+l/2][h+k/2]=='\\'&&e=='/')||(b[j+l/2][h+k/2]=='/'&&e=='\\'))?'x':e):0))(1,x,y);}catch(e){}})})}}}),b.map(r=>r.join``).join`
`)

Ungolfed:
inp => (
    inp = inp.toLowerCase().replace(/\n/g, `

`).split `
`,
    puzzle = inp.slice(2).map(r => r.length ? r.replace(/./g, i => i + ` `).trim().split `` : Array(inp[2].length * 2 - 1).fill(` `)),

    inp[0].split ` `.forEach(word => {
        for (y = 0; y < puzzle.length; y += 2) {
            for (x = 0; x < puzzle[y].length; x += 2) {
                word[0] == puzzle[y][x] &&
                    (dirs = [-2, 0, 2]).map(ydir => {
                        dirs.map(xdir => {
                            symb = `\\|/
-o-
/|\\`.split(`
`)[ydir / 2 + 1][xdir / 2 + 1];

                            try {
                                (findWord = (chnum, xcoord, ycoord) =>
                                    chnum >= word.length ? 1 : (
                                        ch = word[chnum],
                                        ((xdir || ydir) && puzzle[ycoord + ydir][xcoord + xdir] == ch && findWord(chnum + 1, xcoord + xdir, ycoord + ydir)) ?
                                            (puzzle[ycoord + ydir / 2][xcoord + xdir / 2] = ((puzzle[ycoord + ydir / 2][xcoord + xdir / 2] == '\\' && symb == '/') || (puzzle[ycoord + ydir / 2][xcoord + xdir / 2] == '/' && symb == '\\')) ? 'x' : symb)
                                            : 0
                                    )
                                )(1, x, y);
                            } catch (e) {}
                        })
                    })
            }
        }
    }),

    puzzle.map(r => r.join ``).join `
`
)

Test (should work with modern browsers that have some ES6 support):

func=a=>(a=a.toLowerCase().replace(/\n/g,`

`).split`
`,b=a.slice(2).map(r=>r.length?r.replace(/./g,i=>i+` `).trim().split``:Array(a[2].length*2-1).fill(` `)),a[0].split` `.forEach(c=>{for(y=0;y<b.length;y+=2){for(x=0;x{d.map(k=>{e=`\\|/
-o-
/|\\`.split(`
`)[l/2+1][k/2+1];try{(f=(g,h,j)=>g>=c.length?1:(ch=c[g],((k||l)&&b[j+l][h+k]==ch&&f(g+1,h+k,j+l))?(b[j+l/2][h+k/2]=((b[j+l/2][h+k/2]=='\\'&&e=='/')||(b[j+l/2][h+k/2]=='/'&&e=='\\'))?'x':e):0))(1,x,y);}catch(e){}})})}}}),b.map(r=>r.join``).join`
`);
<textarea id="_input">Atomic chess is cool
achess
btoikm
bloosi
nowmlp
hewiir
asdfec</textarea>

<button onclick="document.getElementById('_output').innerHTML = func(document.getElementById('_input').value)">Run!</button>

Python 3, 1387
k=input().lower().split(" ")
a=[]
while 1:
 a.append(input())
 if not a[-1]:a.pop();break
b=sum([[list(' '.join(list(i))),[' ']*(len(i)*2-1)]for i in a],[])[:-1]
w,h=len(a[0]),len(a)
for l in range(h):
 r=a[l];c=list([1 if w in r else 2 if w in r[::-1] else 0, w] for w in k)
 for t,v in c:
  if not t:continue
  if t==2:v=v[::-1]
  i=r.index(v)
  for m in range(i,i+len(v)-1):b[l*2][m*2+1]="-"
for l in range(w):
 u=''.join(x[l]for x in a);_=list([1 if w in u else 2 if w in u[::-1]else 0,w]for w in k)
 for t,v in _:
  if not t:continue
  if t==2:v=v[::-1]
  i=u.index(v)
  for m in range(i,i+len(v)-1):b[m*2+1][l*2]="|"
def d(g,r=1,o=0):
 if g>=len(a[0]):o=g-w+1;g=w-1
 f=range(0,min(g+1,h-o));return[a[i+o][w-1-(g-i)if r else g-i]for i in f],[(i+o,w-1-(g-i)if r else g-i)for i in f]
for l in range(w+h-1):
 x,c=d(l);_=''.join(x);z=list([1 if w in _ else 2 if w in _[::-1]else 0,w]for w in k)
 for t,v in z:
  if not t:continue
  if t==2:v=v[::-1]
  i=_.index(v)
  for m in range(i,i+len(v)-1):b[c[m][0]*2+1][c[m][1]*2+1]="\\"
for l in range(w+h-1):
 x,c=d(l,0);_=''.join(x);z=list([1 if w in _ else 2 if w in _[::-1]else 0,w]for w in k)
 for t,v in z:
  if not t:continue
  if t==2:v=v[::-1]
  i=_.index(v)
  for m in range(i,i+len(v)-1):y=c[m][0]*2+1;x=c[m][1]*2-1;j=b[y][x];b[y][x]="x"if j=="\\"else"/"
print('\n'.join(''.join(x) for x in b))

An "is" was missed in the second example
Atomic chess is cool
achess
btoikm
bloosi
nowmlp
hewiir
asdfec

a c-h-e-s-s
 \ \   /
b t o i k m
   \ \ \
b l o o s-i
     \ \
n o w m l p
       \
h e w i i r
         \
a s d f e c

Sorta ungolfed
words = input().lower().split(" ")
square = []
while 1:
 square.append(input())
 if not square[-1]:square.pop();break

solved = sum([[list(' '.join(list(i))),[' ']*(len(i)*2-1)]for i in square], [])[:-1]
w,h = len(square[0]), len(square)

for l in range(h):
 r = square[l]
 rm = list([1 if w in r else 2 if w in r[::-1] else 0, w] for w in words)
 for t,v in rm:
  if not t:continue
  v = v[::-1] if t==2 else v
  i = r.index(v)

  for m in range(i,i+len(v)-1):solved[l*2][m*2+1]="-"

for l in range(w):
 u = ''.join(x[l] for x in square)
 um = list([1 if w in u else 2 if w in u[::-1] else 0, w] for w in words)
 for t,v in um:
  if not t:continue
  v = v[::-1] if t==2 else v
  i = u.index(v)

  for m in range(i,i+len(v)-1):solved[m*2+1][l*2]="|"

def d(m,ind,r=1,o=0):
 if ind>=len(m[0]):o=ind-len(m[0])+1;ind=len(m[0])-1
 f=range(0,min(ind+1,len(m)-o));return[m[i+o][len(m[0])-1-(ind-i)if r else ind-i]for i in f],[(i+o,len(m[0])-1-(ind-i)if r else ind-i)for i in f]

for l in range(w+h-1):
 x,c = d(square,l)
 dl = ''.join(x)
 dlm = list([1 if w in dl else 2 if w in dl[::-1] else 0, w] for w in words)
 for t,v in dlm:
  if not t:continue
  v = v[::-1] if t==2 else v
  i = dl.index(v)
  for m in range(i,i+len(v)-1):solved[c[m][0]*2+1][c[m][1]*2+1]="\\"

for l in range(w+h-1):
 x,c = d(square,l,0)
 dr = ''.join(x)
 drm = list([1 if w in dr else 2 if w in dr[::-1] else 0, w] for w in words)
 for t,v in drm:
  if not t:continue
  v = v[::-1] if

t==2 else v
  i = dr.index(v)
  for m in range(i,i+len(v)-1):y=c[m][0]*2+1;x=c[m][1]*2-1;j=solved[y][x];solved[y][x]="x"if j=="\\"else"/"

print('\n'.join(''.join(x) for x in solved))

looks at other answers, weeps

LoL, this vs this...

If I could understand the python answer for the word search puzzle question, this may have been shorter.

Mathematica, 478 bytes
f[j_,k_]:=({m,p}=ToCharacterCode@*StringSplit/@{j,ToLowerCase@k};
    t=Transpose;v=Length@m[[1]];i=MapIndexed;r=RotateLeft;
    y@d_:=t@i[r[PadLeft[#,2v d],#2 d]&,m];z[m_,d_,p_]:=i[r[#,#2d]&,t@m][[All,p]];
    c[m_,s_]:=(a=0~Table~{v};a[[Join@@(Range[#,#2-1]&@@@SequencePosition[#,s|Reverse@s])]]=1;a)&/@m;
    FromCharacterCode@Flatten@Riffle[#,10]&@
        Flatten[BitOr@@({{m,8m~c~#},{4t@c[t@m,#],2z[y@1~c~#,-1,-v;;-1]+z[c[y@-1,#],1,2;;v+1]}}&/@p)
            /.{0->32,1->47,2->92,3->88,4->124,8->45},{{3,1},{4,2}}])

Test case:
f["wotsdsearn\nsiiewfvery\nchheruoawd\ntetoennore\nasbdrgrehe\naobyedycab\ntweosttgwt",
    "This is very neat words var are fun rob bot robot"]
(*
w o t s d s e a r n
     /
s-i i e w f v-e-r-y
   /      |  \
c h h e r u o a w d
 /     /  |    X
t e t o e n n o r e
     /       X   \
a s b d r g r e h e
   /       /   \
a o b y e d y c a b
 /       /       \
t w e o s t t g w t
*)


text:
Card pair probability
Given a deck consisting of N copies of cards with integer values [1,M] for a total of N*M cards, compute the probability that a card with the value of 1 is adjacent to a card with the value of 2.
Your solution may be exact or approximated, and it does not need to be the same for every run given the same inputs. The given answer should be within +/-5% of the true solution (barring really rare chances the RNG is not in your favor). Your program should give the answer in a reasonable amount of time (say, less than 10 minutes on whatever hardware you have). You may assume that M and N are reasonable small and error checking is not required.
The deck is not cyclical, so if the first card is a 1 and the last card is a 2, this does not meet the adjacency requirements.
As a test case, for N=4 and M=13 (a standard 52-card deck) the expected solution is ~48.6%.
Here is an example un-golfed implementation in Python+NumPy using random shuffles:
from __future__ import division
from numpy import *

def adjacent(N, M):
    deck = array([i for i in range(1, M+1)]*N)
    trials = 100000
    count = 0
    for i in range(trials):
        random.shuffle(deck)
        ores = (deck == 1)
        tres = (deck == 2)
        if(any(logical_and(ores[1:], tres[:-1])) or
           any(logical_and(ores[:-1], tres[1:]))):
            count += 1
    return count/trials

The output may be in any form you find convenient (function return value, terminal output, file, etc.), and input may be in any form you find convenient (function parameter, terminal input, command line arg, etc.)
Standard loop-holes apply.
This is code golf, the shortest code (in bytes) wins.
Leaderboard

var QUESTION_ID=67431,OVERRIDE_USER=31729;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

adjacency not wrapping around is a deceptively complicated twist

@Sparr You gave me an idea! :-)

MATL, 44 46 bytes
This uses release 3.1.0 of the language, which is earlier than this challenge.
The computation is done with a loop that draws 1000 random realizations. It takes a couple of seconds to run. It could be done faster in a vectorized way. Input is of the form [N M].
Old version: generates a random deck of cards and checks it twice: first in the forward and then in the backward direction.
itpw1)1e3:"2$twZ@w/Y]t1HhXfnwH1hXfn|bb]xxN$hYm

New version: generates a random deck of cards and then appends a flipped version of it with a 0 in between. That way checking can be done just once, in the forward direction. This saves two bytes.
itpw1)1e3:"2$twZ@w/Y]tP0whh1HhXfngbb]xxN$hYm

Example
>> matl itpw1)1e3:"2$twZ@w/Y]tP0whh1HhXfngbb]xxN$hYm
> [4 13]
0.469

Explanation
i                 % input: [N M]
tpw1)             % produce N*M and N
1e3:"             % repeat 1000 times
  2$twZ@w/Y]      % produce random deck of cards from 1 to N*M
  tP0whh          % append 0 and then flipped version of deck
  1Hh             % vector [1 2]
  Xf              % find one string/vector within another
  ng              % was it found at least once?
  bb              % bubble up element in stack, twice
]                 % end
xx                % delete top of the stack, twice
N$h               % vector with all elements in stack
Ym                % mean value

Pyth, 23 22 bytes
csm}1sM.:.S*vzUQ2J^T4J

Runs 10000 iterations. The number can be changed at no byte cost. Input is newline separated. Takes about 9 seconds on my computer.
Demonstration
csm}1sM.:.S*vzUQ2J^T4J
                 J^T4     J = 10000
  m              J        Do the following J times.
           *vzUQ          Set up the deck. (0 .. n-1, repeated m times.)
         .S               Shuffle the deck.
       .:       2         Find all 2 elment substrings.
     sM                   Add them up.
   }1                     Check if any pairs add to 1 ([0, 1] or [1, 0])
 s                        Add up the results (True = 1, False = 0)
c                     J   Divide by J.

LabVIEW, 58 LabVIEW Primitives
creats card arrays then shuffles them. Search for 1s then check adjacent cards for 2s.

MATL, 44 38 bytes
This also uses MATL version 3.1.0, which is earlier than this challenge.
New version, thanks to Luis Mendo for saving 4 bytes!
iiXI*XJxO1e4XH:"JZ@I\TTo3X53$X+1=a+]H/

Old version (44 bytes):
OiitXIx*XJx1e4XH:"JJZrI\[1 1]3X5,3$X+1=a+]H/

Explanation
i               % take input for N
i               % take input for M
XI              % save M into clipboard I
*XJ             % multiply N and M and store in clipboard J
x               % clear the stack
O               % make a zero to initialise count of pairs
1e4XH:"         % 1e4=10000, XH saves into clipboard H, : makes the vector 1:1e4
                % which is used to index a for loop, started using "
    JZ@         % Use randperm to generate a random permutation of the vector 1:N*M
    I\          % take the result mod M, now each card has a value one less than before
    TTo3X53$X+  % convolve vector of card values with [1 1] to do pairwise summation
    1=a         % find if any sums equal 1, which means there is a [0 1] or [1 0]
    +           % add the logical value to the count of pairs
]
H/              % divide the count by the number of deals to get the probability

For example,
>> matl 'iiXI*XJxO1e4XH:"JZ@I\TTo3X53$X+1=a+]H/'
> 4
> 13
0.4861

Note (21/5/16): As of MATL release 18.0.0, X+ has been removed, but Y+ can be used in its place. The changes from MATL version 3.1.0 to 18.0.0 mean that this answer can now be written in just 31 bytes, *xO1e4:"2:Gtb*Z@w\TT2&Y+1=ah]Ym.

I know there is already a MATL answer, but I think the methods are quite different so I've still posted this one.

I love convolution!

You can save a little changing [1 1] into TTo. Also, you don't need the comma

@LuisMendo thanks! I thought there must have been a better way to do that!

Now I see how convolution works here. Using 0-based naming of the cards was very clever!

Pyth, 16 bytes
JE?>J1-1^-1c2JQZ

Demonstration.
This follows the

make an educated guess,
check that it's close enough,
repeat

strategy of programming. The winning educated guess in this case is
1 - (1 - 2 / M) ** N

which roughly says that there are N chances to fall into buckets, and fraction of valid buckets is 2 / M. The buckets being slots places next to 0s, and the chances being 1s.
The error never seems to go above 3% (surprisingly), and seems to converge to 0% as the parameters get larger (as I would expect).
Input is newline separated.
              Q  Q = eval(input())
JE               J = eval(input())
  ?>J1           if J > 1
      -1^-1c2JQ  then 1 - (1 - 2 / J) ** Q
               Z else 0

You can save a character if you accept the plainly obvious fact that False == 0, and do JE&>J1-1^-1c2JQ instead.

This happens to be my first go at Pyth (and my first answer), so criticism and help is especially welcome.

Mathematica, 93 92 91 bytes
N@Count[RandomSample@Flatten[Range@#~Table~{#2}]~Table~{a=1*^5},{b=___,1,2,b}|{b,2,1,b}]/a&

Still looking for a closed form...

it's going to involve a nested loop of permutation calculations.