text:
Is it Valid Modified UTF-8?
UTF-8 is a relatively simple way to encode Unicode codepoints in a variable-width format such that it doesn't easily confuse code that isn't Unicode aware.
UTF-8 overview

Bytes in the range of 1-0x7F, inclusive, are normally valid
Bytes with the bit pattern 10XX XXXX are considered continuation bytes, with the six least significant bits being used to encode part of a codepoint. These must not appear unless they are expected by a preceding byte.
Bytes with the pattern 110X XXXX expect one continuation byte afterward
Bytes with the pattern 1110 XXXX expect two continuation bytes afterward
Bytes with the pattern 1111 0XXX expect three continuation bytes afterward
All other bytes are invalid and should not appear anywhere in a UTF-8 stream. 5, 6, and 7 byte clusters are possible in theory, but will not be allowed for the purposes of this challenge.

Overlong encodings
UTF-8 also requires that a codepoint should be represented with the minimum number of bytes. Any byte sequence that could be represented with fewer bytes is not valid. Modified UTF-8 adds one exception to this for null characters (U+0000), which should be represented as C0 80 (hex representation)), and instead disallows null bytes to appear anywhere in the stream. (This makes it compatible with null-terminated strings)
Challenge
You are to make a program that, when given a string of bytes, will determine if that string represents valid Modified UTF-8 and will return a truthy value if valid and a falsy value otherwise. Note that you must check for overlong encodings and null bytes (since this is Modified UTF-8). You do not need to decode the UTF-8 values.
Examples
41 42 43  ==> yes (all bytes are in the 0-0x7F range)
00 01 02  ==> no (there is a null byte in the stream)
80 7F 41  ==> no (there is a continuation byte without a starter byte)
D9 84 10  ==> yes (the correct number of continuation bytes follow a starter byte)
F0 81 82 41  ==> no (there are not enough continuation bytes after F0)
EF 8A A7 91  ==> no (too many continuation bytes)
E1 E1 01  ==> no (starter byte where a continuation byte is expected)
E0 80 87  ==> no (overlong encoding)
41 C0 80  ==> yes (null byte encoded with the only legal overlong encoding)
F8 42 43  ==> no (invalid byte 'F8')

Rules

Standard rules and loopholes apply
Input and output can be in any convenient format as long as all values in the unsigned byte range (0-255) can be read in.

You may need to use an array or file rather than a null-terminated string. You need to be able to read null bytes.

Shortest code wins!
Note that using builtins to decode the UTF-8 is not guaranteed to conform to the requirements given here. You may need to work around it and create special cases.

EDIT: added bonus for not using builtins that decode UTF-8
EDIT2: removed bonus since only the Rust answer qualified and it's awkward to define.

I've been waiting for this one.

You may want to add a test case with an invalid byte in the range 0xF8-0xFF.

It seems that surrogates (0xD800 - 0xDFFF) and codepoints beyond 0x10FFFF are allowed, contrary to the "modern" UTF-8 spec. I think this should be clarified, ideally with additional test cases.

more examples would be helpful

"Bytes in the range of 0-0x7F, inclusive, are normally valid " is that supposed to be 1 to 0x7f?

Please avoid bonuses — especially those added a day after the challenge was posted.

dont worry about it, i will be ready for what i am sure is to be coming, your EBCDIC challenge, where the bonus rules will be well sorted out beforehand, ready for the gyre and gimble of the macthers of patterns, the switchers of case, the curlers of brackets...

Late to the game, but I have a quick question: My understanding is that sequences starting with 1111 0XXX aren't legal Modified UTF-8. See https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html#wp16542 for more info. Or is that a Java-specific extension to Modified UTF-8?

@EdwardFalk That's probably Java-specific since it stores strings as UTF-16 and therefore probably barfs on 4-byte sequences. That might also be the surrogate pair range, but I'm not sure.

Elixir, 69 bytes
import String
&valid? replace replace(&1,<<0>>,"\xFF"),"\xC0\x80","0"

Try it online!
Makes use of built-in string validation function. Takes input as Elixir binary.

APL (Dyalog Unicode), 41 39 bytesSBCS
Anonymous tacit prefix function. Takes a Unicode string as argument where the characters' code points represent the input bytes.
{0::0⋄×⌊/'UTF-8'⎕UCS⍣2⎕UCS⍵}'À\x80'⎕R⎕A

Try it online!
'À\x80'⎕R⎕A Replace C0 80s with the uppercase Alphabet
{…} apply the following anonymous function, where the argument is ⍵:
 0:: if any error happens:
  0 return zero
 ⋄ try:
  ⎕UCS⍵ convert the string to code points
  'UTF-8'⎕UCS⍣2 interpret as UTF-8 bytes and convert resulting text back to bytes
  ⌊/ lowest byte (zero if a null byte is present, positive if not, "infinity" if empty string)
  × sign (zero if null byte is present, one if not)

Wouldn't this return truthy for D9 C0 80 84 C0 80 10?

@Neil It does indeed. Is that wrong because removing C0 80 makes unrelated bytes be adjacent in a way that's valid, though they are invalid when separate? Edit: Updated to fix that at no byte cost.

some of the characters are coming up on my screen as just rectangles or boxes, is that normal? im in firefox on linux. APL is a very interesting language.

@donbright In my experience, APL characters always render correctly, even if sometimes less than beautifully, so those boxes are probably just Quads of which there should be four in the main code. It should render like this. And yes, APL is amazing, and lot's of fun. You can easily and quickly learn it too — just come on over in the APL Orchard.

yes they are quads. thanks.

Rust - 191 bytes 313 bytes
Per comment below original did not work properly. New and improved version. No libraries are used, because The Mighty Rust Has No Need For You And Your Libraries. This code uses pattern matching with a state machine. By shamelessly ripping off the UTF8 spec, after finding it via reference and discussion by Jon Skeet, we can copy the spec almost character for character into a rust Match pattern match block. At the end, we add in Beefster's special Mutf8 requirement for C0 80 to be considered valid. Ungolfed:
/* http://www.unicode.org/versions/corrigendum1.html
 Code Points        1st Byte    2nd Byte    3rd Byte    4th Byte
U+0000..U+007F      00..7F
U+0080..U+07FF      C2..DF      80..BF
U+0800..U+0FFF      E0          A0..BF      80..BF
U+1000..U+FFFF      E1..EF      80..BF      80..BF
U+10000..U+3FFFF    F0          90..BF      80..BF      80..BF
U+40000..U+FFFFF    F1..F3      80..BF      80..BF      80..BF
U+100000..U+10FFFF  F4          80..8F      80..BF      80..BF
*/

let m=|v:&Vec<u8>|v.iter().fold(0, |s, b| match (s, b) {
        (0, 0x01..=0x7F) => 0,
        (0, 0xc2..=0xdf) => 1,
        (0, 0xe0) => 2,
        (0, 0xe1..=0xef) => 4,
        (0, 0xf0) => 5,
        (0, 0xf1..=0xf3) => 6,
        (0, 0xf4) => 7,
        (1, 0x80..=0xbf) => 0,
        (2, 0xa0..=0xbf) => 1,
        (4, 0x80..=0xbf) => 1,
        (5, 0x90..=0xbf) => 4,
        (6, 0x80..=0xbf) => 4,
        (7, 0x80..=0x8f) => 4,
        (0, 0xc0) => 8, // beefster mutf8 null
        (8, 0x80) => 0, // beefster mutf8 null
        _ => -1,
    })==0;

try it on the rust playground

Props for doing it manually, but I think your overlong check is incorrect.

Your challenge, dear sir, provokes me to imitation, and I conclude this letter by challenging you, in my turn, to fix upon a man who will expose your question more bluntly (https://bit.ly/2T8tXhO)

Python 2, 104 102 bytes
''.join(chr(int(c,16))for c in input().replace('00','-').replace('C0 80','0').split()).decode('utf-8')

Try it online!
Outputs via exit code


text:
Increment a GUID
Inspired by a recent Daily WTF article...
Write a program or function that takes a GUID (string in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, where each X represents a hexadecimal digit), and outputs the GUID incremented by one.
Examples
>>> increment_guid('7f128bd4-b0ba-4597-8f35-3a2f2756dfbb')
'7f128bd4-b0ba-4597-8f35-3a2f2756dfbc'
>>> increment_guid('06b86883-f3e7-4f9d-87c5-a047e89a19fa')
'06b86883-f3e7-4f9d-87c5-a047e89a19fb'
>>> increment_guid('89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2cf')
'89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2d0'
>>> increment_guid('89f25f2f-2f7b-4aa6-b9d7-46a98e3cb29f')
'89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2a0'
>>> increment_guid('8e0f9835-4086-406b-b7a4-532da46963ff')
'8e0f9835-4086-406b-b7a4-532da4696400'
>>> increment_guid('7f128bd4-b0ba-4597-ffff-ffffffffffff')
'7f128bd4-b0ba-4598-0000-000000000000'

Notes

Unlike in the linked article, incrementing a GUID that ends in F must “carry” to the previous hex digit.  See examples above.
You may assume that the input will not be ffffffff-ffff-ffff-ffff-ffffffffffff.
For hex digits above 9, you may use either upper (A-F) or lower (a-f) case.
Yes, GUIDs may start with a 0.
Your output must consist of exactly 32 hex digits and 4 hyphens in the expected format, including any necessary leading 0s.
You do not have to preserve the version number or other fixed bits of the GUID.  Assume it's just a 128-bit integer where none of the bits have any special meaning.  Similarly, GUIDs are assumed to sort in straightforward lexicographical order rather than in the binary order of a Windows GUID struct.
If writing a function, the input may be of any sequence-of-char data type: string, char[], List<char>, etc.

Are we supposed to leave the 6 fixed bits in the UUIDv4 intact?

@FilipHaglund: No, just treat the GUID as a 128-bit number, where none of the bits have any special meaning.  Similarly, GUIDs are assumed to sort in straightforward lexicographical order rather than in the binary order of a Windows GUID struct.

Suggested test case: 89f25f2f-2f7b-4aa6-b9d7-46a98e3cb29f to ensure that answers can make the transition 9 -> a.

@dana: You may use any data type for which your language's equivalent of C#'s foreach (char ch in theInput) is valid.

05AB1E, 17 15 18 bytes
Saved 2 bytes thanks to Kevin Cruijssen
'-K1ìH>h¦Ž¦˜S·£'-ý

Try it online!
or as a Test Suite
Explanation
'-K                  # remove "-" from input
   1ì                # prepend a 1 (to preserve leading 0s)
     H               # convert from hex to base 10
      >              # increment
       h             # convert to hex from base 10
        ¦            # remove the extra 1
         Ž¦˜S·       # push [8, 4, 4, 4, 12]
              £      # split into parts of these sizes
               '-ý   # join on "-"

Dang, you beat me to it.. Had something very similar, but with žKÃ instead of '-K. Btw, you can save 2 bytes by changing •É]•S3+ to Ž¦˜S·.

@KevinCruijssen: Thanks! I don't know how many times I've kept forgetting that Ž is a thing now...

I un-accepted this answer because someone pointed out that it will drop leading 0's.  Please fix.

@dan04: Good call! I hadn't thought of that. Should be fixed now :)

Python 2, 50

3 bytes saved thanks to @Dennis.

lambda s:UUID(int=UUID(s).int+1)
from uuid import*

Try it online!

JavaScript (ES6), 85 bytes
The output string is in lowercase.
s=>(g=(c,x=+('0x'+s[--n])+!!c)=>1/x?g(x>>4)+(x&15).toString(16):~n?g(c)+'-':'')(n=36)

Try it online!
Commented
s => (                   // s = GUID
  g = (                  // g = recursive function taking:
    c,                   //   c = carry from the previous iteration
    x = +('0x' + s[--n]) //   x = decimal conversion of the current digit
        + !!c            //       add the carry
  ) =>                   //
    1 / x ?              // if x is numeric:
      g(x >> 4) +        //   do a recursive call, using the new carry
      (x & 15)           //   and append the next digit
      .toString(16)      //   converted back to hexadecimal
    :                    // else:
      ~n ?               //   if n is not equal to -1:
        g(c)             //     do a recursive call, leaving the current carry unchanged
        + '-'            //     and append a hyphen
      :                  //   else:
        ''               //     stop recursion
)(n = 36)                // initial call to g with n = 36 and a truthy carry

Python 2, 82 bytes
q='f0123456789abcdef--'
f=lambda s:[str,f][s[-1]in'f-'](s[:-1])+q[q.find(s[-1])+1]

Try it online!
No imports or hex conversion.
This scans from the back of the string, moving each character along the cycle 0123456789abcdef, with - going  to itself. After it hits a symbol other than f or -, it stops scanning leftwards, and just returns the remainder unchanged. This solution isn't specific to the UUID format -- any number of blocks of any number of hex letters would work.
The base case of [str,f][s[-1]in'f-'](s[:-1]) is a trick I haven't seen used in a golf before. It terminates the recursion without any if, and, or, or other explicit control flow.
Based on the condition [s[-1]in'f-'] of the last character, the code either returns f(s[:-1]) or just s[:-1] unchanged. Since str is the identity on strings, we can select one of the functions [str,f] and apply it to s[:-1]. Note that the recursive call with f is not made if it is not chosen, getting around the common issue problem that Python eagerly evaluates unused options, leading to infinite regress in recursions.

well, there goes my brain for the morning.

APL (Dyalog Unicode), 46 bytesSBCS
Anonymous tacit prefix function.
⎕CY'dfns'
(∊1hex 16(|+1⌽=)⍣≡1+@32dec¨)@('-'≠⊢)

Try it online!
⎕CY'dfns' copy the "dfns" library (to get hex and dec)
(…)
 ⊢ the argument
 ≠ differs from
 '-' a dash
(…)@ on the subset consisting of the locations at which the above criterion is true, apply:
 dec¨ convert each hexadecimal character to a decimal number
 …@32 at position 32 (the last digit), apply:
  1+ increment
 16(…)⍣≡ repeatedly apply with left argument 16 until stable:
  = compare (gives mask where the hexadecimal digits are 16)
  1⌽ cyclically rotate one step left (this is the carry bit)
  |+ to that, add the division remainder when divided (by sixteen, thus making all 16 into 0)
 1hex  turn digits into length-one hexadecimal character representations
 ∊ ϵnlist (flatten)

Ruby -pl, 62 57 55 bytes
$_="%032x"%-~gsub(?-,"").hex
7.step(22,5){|i|$_[i]+=?-}

Try it online!

Java 11, 152 149 111 108 bytes
s->{var b=s.getLeastSignificantBits()+1;return new java.util.UUID(s.getMostSignificantBits()+(b==0?1:0),b);}

-38 bytes thank to @OlivierGrégoire.
-3 bytes thanks to @ASCII-only.
Try it online.
Explanation:
s->{         // Method with UUID as both parameter and return-type
  var b=s.getLeastSignificantBits()
             //  Get the 64 least significant bits of the input-UUID's 128 bits as long
        +1;  //  And increase it by 1
  return new java.util.UUID(
             //  Return a new UUID with:
    s.getMostSignificantBits()
             //   The 64 most significant bits of the input-UUID's 128 bits as long
    +(b==0?  //    And if the 64 least significant bits + 1 are exactly 0:
       1     //     Increase the 64 most significant bits by 1 as well
      :      //    Else:
       0,    //     Don't change the 64 most significant bits by adding 0
     b);}    //   And the 64 least significant bits + 1

Old 149 bytes answer:
s->{var t=new java.math.BigInteger(s.replace("-",""),16);return(t.add(t.ONE).toString(16)).replaceAll("(.{4})".repeat(5)+"(.*)","$1$2-$3-$4-$5-$6");}

Try it online.
Explanation:
s->{                              // Method with String as both parameter and return-type
  var t=new java.math.BigInteger( //  Create a BigInteger
         s.replace("-",""),       //  Of the input-string with all "-" removed
         16);                     //  Converted from Hexadecimal
  return(t.add(t.ONE)             //  Add 1
         .toString(16))           //  And convert it back to a Hexadecimal String
         .replaceAll("(.{4})".repeat(5)+"(.*)",
                                  //  And split the string into parts of sizes 4,4,4,4,4,rest
           "$1$2-$3-$4-$5-$6");}  //  And insert "-" after parts of size 8,4,4,4,
                                  //  and return it as result

111 bytes

@OlivierGrégoire Hadn't thought about using an actual UUID! Nice and shorter alternative. :D

109

-1 more with var instead of long

Python 3, 50 bytes
from uuid import*
lambda u:UUID(int=UUID(u).int+1)

Try it online!

Python 2, 113 112 bytes
def f(s):a=hex(int(s.replace('-',''),16)+1+2**128);return'-'.join((a[3:11],a[11:15],a[15:19],a[19:23],a[23:-1]))

Try it online!
Without imports

Retina 0.8.2, 21 bytes
T`FfdlL`0dlL`.[-Ff]*$

Try it online! Link includes test cases. 9 becomes a. Explanation: The regex matches all trailing fs and -s plus one preceding character. The transliteration then cyclically increments those characters as if they were hex digits. Alternate approach, also 21 bytes:
T`L`l
T`fo`dl`.[-f]*$

Try it online! Link includes test cases. Works by lowercasing the input to simplify the transliteration. Would therefore be 15 bytes if it only had to support lowercase. Try it online! Link includes test cases.

MATLAB, 138 bytes
a=1;Z=a;for r=flip(split(input(''),'-'))'
q=r{:};z=dec2hex(hex2dec(q)+a,nnz(q));try
z+q;a=0;catch
z=~q+48;end
Z=[z 45 Z];end;disp(Z(1:36))

Fixed a bug in case a chunk is all zeros. Also golfed off a lot by abusing try/catch. Net result: 0 bytes saved.
An attempt to 'cheat' by using java.util.UUID failed because the long value returned from java.util.UUID.get[Most/Least]SignificantBits gets converted to a double which incurs a loss of precision. I invite you to take a look at this table and silently utter "...but why?"
Explanation
The hex2dec function spits out a double, so it cannot process the entire GUID at once to avoid exceeding flintmax. Instead, we have to process the GUID chunk by chunck, using split. The variable a checks if we need to carry a one, and cheatingly also is the initial increment we add. The condition for carrying over is whether the lengths of the original and incremented strings are no longer equal.
Original version was just under 160 bytes so I'd like to think this should not be easy to outgolf.

C# (Visual C# Interactive Compiler), 77 bytes
x=>{for(int i=35,c;(x[i]=(char)((c=x[i--])<48?c:c==57?65:c>69?48:c+1))<49;);}

Try it online!
-1 byte thanks to @ASCIIOnly!
Anonymous function that takes a char[] as input and outputs by modifying an argument.
Input is scanned from right to left and replaced using the following rules.

The - character is ignored and processing continues
The F character is converted to 0 and processing continues
The 9 character is converted to A and processing stops
The characters A-E and 0-8 are incremented by 1 and processing stops

==70 -> >69

Excellent - Thanks :)

Python 2, 99 bytes
s='%032x'%-~int(input().replace('-',''),16)
print'-'.join((s[:8],s[8:12],s[12:16],s[16:20],s[20:]))

Try it online!
No uuid.UUID usage.

Powershell, 101 bytes
for($p=1;$d=+"$args"[--$i]){$d+=$p*(1-@{45=1;57=-7;70=23;102=55}.$d)
$p*=$d-in45,48
$r=[char]$d+$r}$r

Try it online!
No external library or hex conversion. Any string length. Lower case and upper case are allowed. Input string matching to ^[f-]*$ is allowed too.
This script scans from the back of the string and inrement each char by the value from hashtable:

-: increment=1-1
9: increment=1+7, result=A
F: increment=1-23, result=0
f: increment=1-55, result=0
increment=1 for other chars

Next, the script uses $p to determine whether to increment the current char.
Test script:
$f = {

for($p=1;$d=+"$args"[--$i]){$d+=$p*(1-@{45=1;57=-7;70=23;102=55}.$d)
$p*=$d-in45,48
$r=[char]$d+$r}$r

}

@(
    ,('f','0')
    ,('F','0')
    ,('0','1')
    ,('9','A')
    ,('A','B')
    ,('a','b')
    ,('0-f','1-0')
    ,('0-F','1-0')
    ,("7f128bd4-b0ba-4597-8f35-3a2f2756dfbb","7f128bd4-b0ba-4597-8f35-3a2f2756dfbc")
    ,("06b86883-f3e7-4f9d-87c5-a047e89a19f9","06b86883-f3e7-4f9d-87c5-a047e89a19fa")
    ,("89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2cf","89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2d0")
    ,("8e0f9835-4086-406b-b7a4-532da46963ff","8e0f9835-4086-406b-b7a4-532da4696400")
    ,("7f128bd4-b0ba-4597-ffff-ffffffffffff","7f128bd4-b0ba-4598-0000-000000000000")
    ,("89f25f2f-2f7b-4aa6-b9d7-46a98e3cb29f","89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2a0")
    ,("ffffffff-ffff-ffff-ffff-ffffffffffff","00000000-0000-0000-0000-000000000000")
) | % {
    $guid,$expected = $_
    $result = &$f $guid
    "$($result-eq$expected): $result"
}

Output:
True: 0
True: 0
True: 1
True: A
True: B
True: b
True: 1-0
True: 1-0
True: 7f128bd4-b0ba-4597-8f35-3a2f2756dfbc
True: 06b86883-f3e7-4f9d-87c5-a047e89a19fA
True: 89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2d0
True: 8e0f9835-4086-406b-b7a4-532da4696400
True: 7f128bd4-b0ba-4598-0000-000000000000
True: 89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2A0
True: 00000000-0000-0000-0000-000000000000

Perl 6, 65 bytes
{(:16(TR/-//)+1).base(16).comb.rotor(8,4,4,4,*)».join.join('-')}

Test it

The OP has clarified that leading zeroes must be preserved.

56 bytes with leading zeroes

Or 53 bytes by handling stuff more manually

Jelly, 20 bytes
-2 (and a bug fix) thanks to Dennis!
ØhiⱮṣ0µẎḅ⁴‘ḃ⁴ịØhṁj”-

Try it online!

JavaScript (Node.js), 78 bytes
s=>s.replace(/.([f-]*)$/,(s,y)=>('0x'+s[0]-~0).toString(16)+y.replace(/f/g,0))

Try it online!

PowerShell, 126 bytes
$a=("{0:X32}" -f (1+[Numerics.BigInteger]::Parse($args[0]-replace"-", 'AllowHexSpecifier')));5..2|%{$a=$a.Insert(4*$_,"-")};$a

Try it online!
Pretty trivial answer. Just thought I'd get the beloved PowerShell added to the list :)

Rust, 258 bytes
let x=|s:&str|s.chars().rev().scan(1,|a,c|{let d=c.to_digit(16).unwrap_or(99);match(d,*a){(15,1)=>{*a=1;Some(0)}(0..=14,1)=>{*a = 0;Some(d + 1)}_=> Some(d),}}).collect::<Vec<u32>>().iter().rev().for_each(|d| print!("{}", std::char::from_digit(*d, 16).unwrap_or('-')));

yes its long.. but technically its only one line with 1 expression? and no fancy libraries? and it will not crash on a fuzz input? ungolf:
let x=|s:&str|s.chars().rev().scan(1, |a, c| {
            let d = c.to_digit(16).unwrap_or(99);
            match (d, *a) {
                (15, 1) => {*a = 1;Some(0)}
                (0..=14, 1) => {*a = 0;Some(d + 1)}
                _ => Some(d),
            }
        }).collect::<Vec<u32>>().iter().rev()
        .for_each(|d| print!("{}", std::char::from_digit(*d, 16).unwrap_or('-')));

try it on rust playground

btw you don't need the whitespace

16/32/64-bit x86 assembly code, 28 bytes
bytes: 83C623FDAC3C2D74FB403C3A7502B0613C677502B03088460173E9C3
code:
     add esi, 35       ;point to end of string - 1
     std               ;go backwards
l1:  lodsb             ;fetch a character
     cmp al, '-'
     je  l1            ;skip '-'
     inc eax           ;otherwise increment
     cmp al, '9' + 1
     jne l2            ;branch if not out of numbers
     mov al, 'a'       ;otherwise switch '9'+1 to 'a'
l2:  cmp al, 'f' + 1   ;sets carry if less
     jne l3            ;branch if not out of letters
     mov al, '0'       ;otherwise switch 'f'+1 to '0'
                       ;and carry is clear
l3:  mov [esi + 1], al ;replace character
     jnb l1            ;and loop while carry is clear
     ret
Call with ESI pointing to GUID.  Replace ESI with SI for 16-bit, or RSI for 64-bit (and +2 bytes).

Common Lisp, 166 bytes
(lambda(s &aux(r(format()"~32,'0x"(1+(parse-integer(remove #\- s):radix 16)))))(format()"~{~a~^-~}"(mapcar(lambda(x y)(subseq r x y))#1='(0 8 12 16 20 32)(cdr #1#))))

Try it online!

C (clang), 62 bytes
g(char*i){for(i+=36;(*--i-45?*i+=*i-70?*i-57?1:8:-22:0)<49;);}

Try it online!

wait. does the lowercase/uppercase check not cost anything???

i mean, it can handle both lowercase and uppercase at no cost to bytecount?!

Ah ok.. ch-70%32 ? : to '0'...
64 and 96 are multiple of 32 so 70-6 and 102-6  %32 .

you don't actually have to handle both, so 64

Perl 5, 64 bytes
$c=reverse((1+hex s/-//gr)->as_hex);$c=~s/..$//;s/[^-]/chop$c/ge

The number of parentheses necessary here makes me sad, but -> binds very tightly, as ->as_hex is the quickest way I can find to get hexadecimal-formatted output.
Run with perl -Mbigint -p. Basically, it just converts the number to a bigint hexadecimal, adds one, and then subtitutes the digits of the result back into the original value, leaving dashes untouched.

source: Stack Exchange

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

sort: votes


text:
Matrix rotation sort
Lets define a non-empty, unsorted and finite matrix with unique numbers as follow:
 $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$
Lets define 4 matrix moves as:

↑* (up): Moves a column up
↓* (down): Moves a column down
→* (right): Moves a row to the right
←* (left): Moves a row to the left

The asterisk(*) represents the column/row that is affected by the move (It can be 0-indexed or 1-indexed. Up to you. Please state which one in your answer).

The challenge is, using above moves, sort the matrix in a ascendant order (being the top left corner the lowest and the bottom right corner the highest).
Example
Input:
$$N=\begin{Bmatrix}4&2&3\\1&5&6 \end{Bmatrix}$$
Possible Output: ↑0 or ↓0. (Notice any of those moves can sort the matrix so both answer are correct)

Input:
$$N=\begin{Bmatrix}2&3&1\\4&5&6 \end{Bmatrix}$$
Possible Output: →0

Input (Example test case):
 $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$
Possible Output: ↑0↑1←1↑2

Input:
$$N = \begin{Bmatrix} 5&9&6\\ 8&2&4\\ 1&7&3 \end{Bmatrix}$$
Possible Output:
↑0↑2→0→2↑0→2↑1↑2←1

Input:
$$N = \begin{Bmatrix} 1 & 27 & 28 & 29 & 6 \\10 & 2 & 3 & 4 & 5 \\17 & 7 & 8 & 13 & 9 \\15 & 11 & 12 & 18 & 14 \\26 & 16 & 21 & 19 & 20 \\30 & 22 & 23 & 24 & 25  \end{Bmatrix}$$
Possible Output:
↑2↑1←3→0←3↓0←0←2→3↑3↑4

Input:
$$N = \begin{Bmatrix} 1  \end{Bmatrix} $$
Output:
 or any move

Input:
$$N = \begin{Bmatrix} 1&2\\3&4  \end{Bmatrix} $$
Output:

Notes

There can be different correct outputs (there don't need to be necessarily the same as the test cases or the shortest one)
You can assume it will be always a way to order the matrix
Edges connects (like pacman :v)
There wont be a matrix with more than 9 columns or/and rows
Assume matrix contains only positive non-zero unique integers
You can use any 4 distinct values other than numbers to represent the moves (in case of that, please state that in your answer)
Column/row can be 0 or 1 indexed
Winning criteria code-golf

Extra test cases are always welcome

Here's a website where you can solve these puzzles yourself.

@Doorknob That would have been useful when I was writing the challenge Dx. Thanks anyway!

I don't think you say anywhere that the solution given has to be as short as possible. Is that intentional? For example is ←0←0 a valid solution for the second example where you have given a solution as →0. If it is, I think half of the move options likely won't be used.

@FryAmTheEggman Yes, It doesnt matter how long your solution (output) is as long as it creates the correct result

Related? https://codegolf.stackexchange.com/questions/172824/rubik-sorting-a-matrix-a-k-a-the-torus-puzzle

Will you always be able to perfectly sort it or can you end up with a row like 13 14 16 15?

@fəˈnɛtɪk You can assume it will be always a way to solve it. I'll add it to the notes

@Sumner18 Ah, that's the one I was thinking about when I mentioned a similar challenge in the Sandbox! I couldn't find it anymore. :)

Also some people might want to try https://www.openprocessing.org/sketch/580366 made by a youtuber called carykh. It is called "loopover"

can you use some other encoding for the output?  eg, where each move is mapped to a unique int?

@Jonah, "You can use any 4 distinct values other than numbers to represent the moves".

I was thinking of encoding row (or col) + direction into a single int, which is not necessarily allowed by the quoted rule

JavaScript (ES6),  226  219 bytes
Brute force search, using right ("R") and down ("D") moves.
Returns either a string describing the moves, or an empty array if the input matrix is already sorted. Columns and rows in the output are 0-indexed.
f=(m,M=2)=>(g=(s,m)=>m[S='some'](p=r=>r[S](x=>p>(p=x)))?!s[M]&&m[0][S]((_,x,a)=>g(s+'D'+x,m.map(([...r],y)=>(r[x]=(m[y+1]||a)[x])&&r)))|m[S]((_,y)=>g(s+'R'+y,m.map(([...r])=>y--?r:[r.pop(),...r]))):o=s)([],m)?o:f(m,M+2)

Try it online!
Commented
f =                              // f = main recursive function taking:
(m, M = 2) => (                  //   m[] = input matrix; M = maximum length of the solution
  g =                            // g = recursive solver taking:
  (s, m) =>                      //   s = solution, m[] = current matrix
    m[S = 'some'](p =            // we first test whether m[] is sorted
      r =>                       // by iterating on each row
        r[S](x =>                // and each column
          p > (p = x)            // and comparing each cell x with the previous cell p
        )                        //
    ) ?                          // if the matrix is not sorted:
      !s[M] &&                   //   if we haven't reached the maximum length:
      m[0][S]((_, x, a) =>       //     try all 'down' moves:
        g(                       //       do a recursive call:
          s + 'D' + x,           //         append the move to s
          m.map(([...r], y) =>   //         for each row r[] at position y:
            (r[x] =              //           rotate the column x by replacing r[x] with
              (m[y + 1] || a)[x] //           m[y + 1][x] or a[x] for the last row (a = m[0])
            ) && r               //           yield the updated row
      ))) |                      //
      m[S]((_, y) =>             //     try all 'right' moves:
        g(                       //       do a recursive call:
          s + 'R' + y,           //         append the move to s
          m.map(([...r]) =>      //         for each row:
            y-- ?                //           if this is not the row we're looking for:
              r                  //             leave it unchanged
            :                    //           else:
              [r.pop(), ...r]    //             rotate it to the right
      )))                        //
    :                            // else (the matrix is sorted):
      o = s                      //   store the solution in o
)([], m) ?                       // initial call to g(); if we have a solution:
  o                              //   return it
:                                // else:
  f(m, M + 2)                    //   try again with a larger maximum length

Nice answer.  Do you know if there exists an efficient algo for this, or if it's possible to determine  the maximum number of moves a solution can have without brute forcing?

@Jonah Here is a paper describing a solution and giving an upper bound of the number of moves. (See also this challenge which is basically the same task with a different winning criterion.)

Wow, thank you @Arnauld

Python 2, 296 277 245 Python 3, 200 194 bytes
from numpy import*
def f(p):
 s='';u=[]
 while any(ediff1d(p)<0):u+=[(copy(p),s+f'v{v}',f':,{v}')for v in r_[:shape(p)[1]]]+[(p,s+'>0',0)];p,s,i=u.pop(0);exec(f'p[{i}]=roll(p[{i}],1)')
 return s

Try it online!
-19: unicode arrows weren't required...
-32: slightly reworked, but much slower performance on average.
-45: took some inspiration from @Arnauld's answer. Switched to Python 3 for f'' (-4 bytes)
-6: range( )→r_[: ], diff(ravel( ))→ediff1d( )

Exhaustively searches combinations of all possible ↓ moves and →0. Times out on the third test case.
Since →n is equivalent to
↓0↓1...↓(c-1) 	... repeated r-n times
→0
↓0↓1...↓(c-1)	... repeated n times

where r and c are the numbers of rows and columns, these moves are sufficient to find every solution.

from numpy import*
def f(p):
    s=''                                    #s: sequence of moves, as string
    u=[]                                    #u: queue of states to check
    while any(ediff1d(p)<0):                #while p is not sorted
        u+=[(copy(p),s+f'v{v}',f':,{v}')    #add p,↓v to queue
            for v in r_[:shape(p)[1]]]      # for all 0<=v<#columns
        u+=[(p,s+'>0',0)]                   #add p,→0
        p,s,i=u.pop(0)                      #get the first item of queue
        exec(f'p[{i}]=roll(p[{i}],1)')      #transform it
    return s                                #return the moves taken

>v correspond respectively to →↓. (others undefined)

Jelly, 35 bytes
ṙ€LXȮƊ¦1
ÇZÇZƊ⁾ULXȮOịØ.¤?F⁻Ṣ$$¿,“”Ṫ

Try it online!
Full program. Outputs moves to STDOUT using L for left and R for right. Keeps trying random moves until the matrix is sorted, so not very efficient in terms of speed or algorithmic complexity.

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


text:
Generate a password
It is very hard to remember my password, so I came up with a way to generate a password.
The way I generate my password is from a word or a sentence, following these steps:

Start from left to right
Find the count of each letter
Put letter with its count in an order

Letters with higher repetition will be in the end
Letters with the same repetition will be ordered alphabetically

Numbers and special letters will be ignored including whitespace (e.g. 9, 4, @, (, *, etc. are ignored)
Group letters ignoring case. In the output, use the case of the last occurrence in the input
The count of the letter can be any number e.g. 5H17M345K
If input is all numbers or special letters then output will be empty string e.g. Input "12$*34^!" then output ""
when order for the same occurrence alphabetically case does not matter e.g. 1a1B1c

Example:
Input: Kitkat Tango
(2k / 1i / 3T / 2a / 1n / 1g / 1o)
Output: 1g1i1n1o2a2k3T

Another example:
Input: Database Partitions Task
(1D / 5a / 4T / 1b / 3s / 1e / 1P / 1r / 2i / 1o / 1n / 3s / 1k)
Output: 1b1D1e1k1n1o1P1r2i3s4T5a

Note: the letters with 1 repeat are in the beginning ordered alphabetically
then the letters with more reps
This is code-golf, the shortest code wins.

By 'count in each letter', do you mean how many times a letter appears in the input sentence?

Can a letter appear more than 9 times?

Can we output as an array? e.g., ["1g","1i","1n","1o","2a","2k","3T"] or even [["1","g"],["1","i"],["1","n"],["1","o"],["2","a"],["2","k"],["3","T"]]

"Numbers and special letters will be ignored including whitespace (e.g. 9, 4, @, (, *, etc. are ignored)" - does this mean [a-z][A-Z] only?

"Letters with the same repetition will be ordered alphabetically" - usually 'D' sorts before 'a', so here do you explicitly mean "...ignoring case" or would 1D1P1b1e1k1n1o1r2i3s4T5a be an acceptable output for "Database Partitions Task"?

Why was this put on hold? Maybe the question was initially not very nicely formatted, but it's clear enough to understand and the formatting has been fixed.

@BMO, I voted to close because shaggy's high voted question, which may make a difference in choosing the strategy. Is irritating to find out after you worked out and posted a solution that is either invalid or overcomplicated. I hope the OP will not take the close personally, after all there are 12 up and 0 downvotes.

@manatwork: But that's not unclear (note, their answer didn't assume that letters appear less than 10 times), it's just trying to loosen the input restrictions.

@BMO, neither of the questions I asked would make a difference to my own solution ;) Currently, though, by what's included in the challenge, it's not explicitly clear whether or not there's an upper limit on the number of times any one letter can appear in the input. Personally, I would assume not but others could easily assume otherwise.

@EmbodimentofIgnorance Yes

@Shaggy Yes, it can appear as many as possible it will be 12e for example

@Shaggy No, the output as the examples above only

@JonathanAllan yes a-z and A-Z only

@JonathanAllan case will be ignored in the order, D is before g so it will be 1D1g

@manatwork nothing personal, i hope the question is clear enough

make sure to add these clarifications to the actual question body, so answerers don't have to hunt through the comments

May I assume input will always be non-empty after removing non-alpha characters? e.g. input wont be "123", "" ect.

@tsh if input is all number then output will be empty string

Comments do not a specification make. You need to update the challenge to 1. add at least 1 test case that includes more than 9 occurrences of one or more letters, 2. specify that output must be a string (although I'd strongly recommend against being that strict; it adds nothing to the challenge), 3. specify that we must be able to handle inputs containing no letters, and, 4. clarify whether or not we need to handle an empty string as input.

Once you've done that then you will then have to test all existing solutions and inform them if they need to make any changes. I've already found quite a number of solutions that fail on point 1. Also, in the future you might consider using our Sandbox to try to iron out issues like these before posting a challenge.

@Shaggy I test the shortest code, if it pass then it is the answer if not, then I write a comment for them about the failure and then test the next shortest answer.

@asmgx You still haven't actually added the specs to the question, so it's not their fault that their solution doesn't match them. By community consensus, rules made in comments aren't valid until they are put in the actual question for this reason

Suggested test case: Looooooooooooooooooooooooooooaaaaaaaaaaaaaaaaaaaaaads Of The Same Letters -> 1d1f1h1m1r2L3s3t4e23a29O (or any other test case with a letter more than 9 times)

I've VTCed this as unclear until all issues raised in the comments have been addressed in the spec. Please ping me when they have and I'll retract my vote (or cast my vote to reopen).

Japt v2.0a0 -P, 14 bytes
f\l üv ñÊ®ÌiZÊ

Try it
f\l üv ñÊ®ÌiZÊ     :Implicit input of string
                   > e.g., "Kitkat Tango"

f                  :Split to an array of characters
 \l                :  Matching RegEx /[a-z]/gi
                   > ["K","i","t","k","a","t","T","a","n","g","o"]

    ü              :Sort & group (Preserves original order within each group)
     v             :  By lowercase
                   > [["a","a"],["g"],["i"],["K","k"],["n"],["o"],["t","t","T"]]

       ñ           :Sort
        Ê          :  By length
                   > [["g"],["i"],["n"],["o"],["a","a"],["K","k"],["t","t","T"]]

         ®         :Map each Z
          Ì        :  Last element of Z
                   >   ["g","i","n","o","a","k","T"]
           i       :  Prepend
            ZÊ     :    Length of Z
                   >   ["1g","1i","1n","1o","2a","2k","3T"]

                   :Implicitly join & output
                   > "1g1i1n1o2a2k3T"

05AB1E, 19 17 16 bytes
Saved 1 byte thanks to Kevin Cruijssen
áΣl}.γl}éεgyθJ}J

Try it online!
or as a Test Suite
Explanation
á                  # keep only letters in input
 Σl}               # sort by lower-case
    .γl}           # group by lower-case
        é          # sort by length (stable)
         ε    }    # map each to
          g        # its length
             J     # joined with
           yθ      # the last letter
               J   # join to string

You can save a byte by changing the ‚ (pair with) to a « (concat/merge), so one of the two Js (joins) can be removed.

@KevinCruijssen: Wow. I feel stupid now :) Why didn't I just move a J inside? Edit: Actually, I needed them as a pair in the 19-byte version and I didn't think to change it when I made the 17 one :P

You might be able to drop the second Join, depending on the answer to this question

-1 by changing εgyθJ}J to vygyθJ. And another -3 by changing Σl}.γl} to .¡l} (we now have an actual group-by builtin, yay).

Perl 6, 66 63 bytes
{[~] map {+$_~.tail},sort {+$_,.lc},m:g/<:L>/.classify(&lc){*}}

Try it online!
Explanation
{                                                             }  # Anon block
                                    m:g/<:L>/  # Match all letters
                                             .classify(&lc)  # Group by lowercase
                                                           {*}  # Get hash values
                     sort {+$_,.lc},  # Sort by array length and lowercase
     map {         },  # Map to
          +$_~.tail  # Concat array length and last letter
 [~]  # Join

C# (Visual C# Interactive Compiler), 105 bytes
x=>x.Where(char.IsLetter).GroupBy(a=>a%32).OrderBy(a=>(a.Count(),a.Key)).Select(a=>a.Count()+""+a.Last())

Try it online!
Thanks to dana for bringing it down to 105 bytes from 138 bytes.

why not just .OrderBy(a=>a) ?

105?

Retina, 67 66 41 39 bytes
\P{L}

O$`.
$l$0
ir`\1*(.)
$.0$1
N`\d+.

-25 bytes and a minor bug-fix thanks to @Neil.
-2 bytes thanks to @Neil and @Shaggy together.
Try it online or verify all test cases.
Explanation:
Remove everything except for upper- and lowercase letters:
i.e. Kitkat Tango 123! → KitkatTango
\P{L}

Sort the individual letters case-insensitive (thanks to @MartinEnder for this):
i.e. KitkatTango → aagiKknottT
O$`.
$l$0

Capture every chunk of case-insensitive repeated adjacent letters:
i.e. aagiKknottT → [aa,g,i,Kk,n,o,ttT]
ir`\1*(.)

Prepend the length of every match, and only keep the last letter of every chunk:
i.e. [aa,g,i,Kk,n,o,ttT] → 2a1g1i2k1n1o3T
$.0$1

Sort the numbers and letter groups based on the numbers:
2a1g1i2k1n1o3T → 1g1i1n1o2a2k3T
N`\d+.

After which the result is output implicitly.

Are you sure that's a bug? Is it not just sorting lexicographically? ("aA" < "aa")

@Shaggy You're right it's not a bug. I meant a bug in my program, not in Retina itself. It's behaving as you would expect indeed. I've edited it to 'problem'. If only I could do O$i to sort case-insensitive, just like I can List or match case-insensitive by using $i..

@Shaggy Fixed. Apparently there is a case-insensitive sort now. :)

And a hell of a saving! Nice :) I was going to suggest sorting each pair by its first character, otherwise, if Retina can do that.

@Shaggy I'm not sure if it can. Because the \w and . in the O`\w. were used to indicate that we're sorting pairs of characters. Not sure if we can sort every pair of characters, but only sort it based on the first character. But ah well, Martin's suggestion to sort each character based on a substitution (which is the lowercase variant of the match) works like a charm. :)

Can it be done in 41 bytes or am I missing something?

@Neil Ah nice! Btw, where in the documents can I find the lowercase r builtin? Nice use of the N sorting.. Completely forgot about that one for some reason, even though I remember using it once before in a Retina answer of mine (also suggested by you at the time iIrc xD)

https://github.com/m-ender/retina/wiki/The-Language#regex-modifiers

[\W\d_]? Does Retina not have a character class to match letters only?

@Shaggy Not that I can see on https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions

@Shaggy Not that I know of, except when using the Transliterate builtin, which seems to have builtins for 0-9, 02468, 13579, 0-9A-F, 0-9a-f, A-Z, a-z, AEIOU, aeiou, _0-9A-Za-z,and <sp>-~ (<sp> being a space). Why these builtins aren't available for the entire code with a prefix of some sort I don't know.

@Shaggy Actually reading further, \P{L} might work, which saves 2 bytes.

Perl 5 (-n), 74, 68, 66, 65 bytes
-6 bytes changing -p to -n and using say instead of $_=join"",
-2 bytes thanks to Abigail using \pL instead of [a-z]
-1 byte thanks to Kjetil S. removing i flag no more necessary after using \pL
s/\pL/($h{lc$&}+=1).=$&/ge;say sort{$a-$b||lc$a cmp lc$b}values%h

TIO
58 bytes, in case there is no more than 9 occurence of each character
s/\pL/($h{lc$&}+=1).=$&/ge;say sort{lc$a cmp lc$b}values%h

@Abigail, thank you, in the second program it was an oversight a after update

Shave a byte by replacing /gie with /ge. Since \pL is case insensitive.

@KjetilS. thank you, updated

Pyth, 27 24 22 bytes
ssrD0m,lded.gr0k@+Gr1G

Try it online here.
ssrD0m,lded.gr0k@+Gr1GQ   Implicit: Q=eval(input()), G=lowercase alphabet
                          Trailing Q inferred
                   r1G    Uppercase alphabet
                 +G       Concatenate with lowercase alphabet
                @     Q   Keep those characters in Q which are also in the above
           .g             Group the remaining characters, as k, using:
             r0k             Convert k to lowercase
                              (Grouping preserves relative order)
     m                    Map the sorted groups, as d, using:
       ld                   Length of d
      ,                     Pair the above with...
         ed                 ... last element of d
   D                      Sort the above...
  r 0                     ... by their lowercase values
ss                        Flatten, then concatenate the result of the above into a string, implicit print

Edit: Golfed 3 bytes by ordering by character before group, previous version: sm+ldedo,lNr0eN.gr0kf}r0TGQ
Edit 2: Golfed off another 2 bytes by formatting output before any ordering, previous version: sm+ldedlD.gr0krD0f}r0TGQ
Edit 3: Golfed off another byte by changing the filter, thanks to @FryAmTheEggman. Also had to fix a bug when OP clarified that a single letter can appear more than 9 times, which added a byte back on :o( Previous version: srD0m+lded.gr0kf}r0TGQ

Python 3, 105 bytes
s=input()
t=s.upper()
for n,c in sorted((t.count(i),i)for i in{*t}if'@'<i<'['):print(n,end=s[t.rfind(c)])

Try it online!
-1 thanks to ArBo.

Wolfram Language (Mathematica), 102 96 93 87 bytes
""<>Map@ToString/@Sort[(r=Reverse)/@Tally[r@#/." "->Nothing,Equal@@ToLowerCase@{##}&]]&

Try it online!
Tally[r@#/." "->Nothing,Equal@@ToLowerCase@{##}&]      Start with a char list
        #/." "->Nothing                                Remove spaces
      r@                                               Reverse the result
Tally[                 ,Equal@@ToLowerCase@{##}&]
                                             Make a list of letters and multiplicities,
                                             where two letters are considered the same if
                                             their lowercase values are equal. Then:

""<>Map@ToString/@Sort[(r=Reverse)/@ ... ]&
                       (r=Reverse)           Reverse each {letter, freq} to {freq,letter}.
                                             Then the standard Wolfram order function sorts
                                               lower frequencies first, with ties broken by
                                               by letters earlier in the alphabet,
                  Sort[                  ]     exactly what we want.

    Map@ToString/@                           @ has higher precedence than /@, so
                                               this effectively does Map[Map[ToString]].
""<>                                         StringJoin the nested list into a single string.

Scala, 103 bytes
_.filter(_.isLetter).groupBy(_%32).values.map(l=>l.size+""+l.last).toSeq.sortBy(_.toLowerCase).mkString

Try it online!

Python 2, 116 bytes
def f(s):a=s.lower();return''.join(`n`+s[a.rfind(c)] for n,c in sorted((a.count(c),c)for c in set(a)if c.isalpha()))

Try it online!

The output for Database Partitions Task is not equal to 1b1D1e1k1n1o1P1r2i3s4T5a

@mdahmoune thanks, should be fixed.

In the output, use the case of the last occurrence in the input you'll need rfind instead of find for this. ...] for can become ...]for to offset that though.

Red, 220 196 206 bytes
func[s][a: charset[#"a"-#"z"#"A"-#"Z"]trim/all form sort/skip collect[foreach c sort
unique reverse rejoin parse s[collect[any[keep[a]| skip]]][i: 0
foreach d s[if(c% 32)=(d% 32)[i: i + 1]]keep i keep c]]2]

Try it online!
Thanks to Shaggy for finding a bug.

Haskell, 114/113 105 bytes
-9 bytes thanks to Laikoni (using list-comprehension and (||) instead of filter with elem & shorten length to get rid of ugly zip)!
f s=id=<<[show(h r)++[last r]|l<-[1..h s],a<-['A'..'Z'],r<-[[x|x<-s,x==a||x==[a..]!!32]],h r==l]
h=length

Try it online!

107 bytes: Try it online!

105: Try it online!

@Laikoni: Now shorter than with imports, very nice!!

Java 10, 223 209 301 bytes
s->{int i=32,t;String M[]=new String[i],r,R="";for(var c:s)M[c%32]+=c>64&c<91|c>96&c<123?c:R;for(;i-->0;M[i]=(t=r.length()-4)>0?t+r.split(R)[t+3]:R)r=M[i]+R;java.util.Arrays.sort(M);for(var p:M)R+=p;return R;}

+92 bytes as a fix for inputs with more than 9 of a single letter.. Will see if I can bring that down again with a different approach.
Try it online.
Explanation:
s->{                        // Method with character-array parameter and String return-type
  int i=32,                 //  Index-integer, starting at 32
      t;                    //  Temp-integer, uninitialized
  String M[]=new String[i], //  Create a String-array of size 32, filled with null by default
         R="",              //  Result-String, starting empty
         r;                 //  Temp-String, uninitialized
  for(var c:s)              //  Loop over the characters of the input-array:
    M[c%32]+=               //   Append the string at index code-point of `c` modulo-32 with:
     c>64&c<91|c>96&c<123?  //    If the character is a letter:
      c                     //     Append the character
     :                      //    Else:
      R;                    //     Append an empty String
  for(;i-->0                //  Loop `i` in the range (32, 0]:
      ;                     //    After every iteration:
       M[i]=                //     Replace the String at index `i` with:
        (t=r.length()-4)    //      Set `t` to the length of String `r` minus 4
                            //      (the minus 4 is for the prepended "null")
         >0?                //      If this length minus 4 is larger than 0:
          t                 //       Set the String to this length minus 4
          +r.split(R)[t+3]  //       Appended with the last character of `r` as String
         :                  //      Else:
          R)                //       Make the String at index `i` empty
    r=M[i]                  //   Set `r` to the `i`'th String
          +R;               //  Converted to String
                            // (null becomes "null", to prevent NullPointerException-errors)
  java.util.Arrays.sort(M,  //  Now sort the array of Strings on:
   (a,b)->                  //   For each pair of two Strings:
     new Byte(              //    Convert the first String to a number
      (0+a).replaceAll("\\D",""))
                            //    after we've added a leading 0 and removed all non-digits
    .compareTo(             //   And compare it to:
     new Byte(              //    The second String converted to a number
      (0+b).replaceAll("\\D",""))));
                            //    after we've added a leading 0 and remove all non-digits
  for(var p:M)              //  Loop over the Strings of the array:
    R+=p;                   //   And append each to the result-String `R`
  return R;}                //  And finally return the result-String `R`

@Shaggy Dang.. fixed at the cost of 92 bytes.. >.< Will see if I can golf it down again by not using a Comparator to sort but sort manually myself later on..

Ouch! Sorry about that!

Swift 4.2.1/Xcode 10.1, 1054 1050 1048 370 368 364 bytes
s.map{String($0)}.filter{$0.rangeOfCharacter(from:.letters) != nil}.reversed().reduce(into:[String:Int]()){d,s in if let l=[s.uppercased(),s.lowercased()].first(where:{d[$0] != nil}){d[l]=d[l]!+1}else{d[s]=1}}.sorted{let c=$0.value-$1.value;return c==0 ?$0.key.compare($1.key,options:.caseInsensitive) == .orderedAscending:c<0}.map{"\($0.value)\($0.key)"}.joined()

Try it online!
@KevinCruijssen also removed some spaces.

Hi, welcome to PPCG! I don't know Swift, but it seems you forgot to remove some spaces, and you can also golf all false to 0>1 and true to 1>0. Try it online 1027 bytes. Probably loads more can be golfed, like the duplicated if let v=$0.key.escaped(asASCII:0>1).lowercased().unicodeScalars.first?.value{return v<$1.key.value}else{return 0>1} you have, but I'll leave that to someone who actually knows Swift.

Also, if you haven't seen it yet: Tips for golfing in  and Tips for golfing in Swift might be interesting to read through. Again welcome, and enjoy your stay! :)

Hello @KevinCruijssen. Thanks for tips, I removed true and false from my answer.

Nice, you've golfed it quite a lot from your initial 1000+ bytes. :) I see 6 more spaces that can be removed after/before all =-assigns: Try it online 364 bytes. Enjoy your stay! :)

Jelly, 15 bytes
fØẠµŒlĠLÞịµL,Ṫ)

A full program printing the password as specified (as a monadic Link it yields a list of lists each containing an integer and a character).
Try it online!

Husk, 15 bytes
No problems with imports when using Husk, therefore we can make use of the various handy functions such as groupOn, sortOn, toLower etc:
ṁ§:osL→ÖLSġÖ_f√

Try it online or try them all!
Explanation
ṁ§:(sL)→ÖLSġÖ_f√  -- example input: "Kitkat Tango"
              f√  -- `filter isAlpha`: "KitkatTango"
          S  _    -- apply _ to .. then ..
            Ö     -- | sortOn: `sortOn toLower`
           ġ      -- | groupOn: `groupOn toLower`
                  -- .. compose: `groupOn toLower . sortOn toLower`
                  -- `sortOn toLower` (stable): "aagiKknottT"
                  -- `groupOn toLower`: ["aa","g","i","Kk","n","o","ttT"]
        ÖL        -- `sortOn length` (stable): ["g","i","n","o","aa","Kk","ttT"]
ṁ                 -- map and flatten (`concatMap`)
 §                -- | fork argument ..
       →          -- | | `last`: ['g','i','n','o','a','k','T']
   (sL)           -- | | `show . length`: ["1","1","1","1","2","2","3"]
  :               -- | .. and `snoc`: ["1g","1i","1n","1o","2a","2k","3T"]
                  -- : "1g1i1n1o2a2k3T"

APL (Dyalog Extended), 28 bytesSBCS
Anonymous tacit prefix function.
(∊⍤∧⌊(⊂⍕⍤≢,⊢/)⍤⊢⌸⊢)'\PL'⎕R''

Try it online!
'\PL' non-letters
⎕R PCRE Replaced with
'' empty strings
(…) apply the following tacit function:
 ⌊ with the lowercase as keys,
 …⌸ apply the below tacit function to each key and its corresponding set of values, namely
 ⊢ the argument:
  (…) apply the following tacit function
  ⍤ to
  ⊢ the list of values:
   ⊢/ the last value
   …, prepend the following to that:
    ⍕ the stringification
    ⍤ of
    ≢ the tally
   ⊂ enclose (to treat character list as single string)
 ∊ ϵnlist (flatten)
 ⍤ the
 ∧ sorted-ascending version of that

JavaScript (Node.js), 127 bytes
s=>[...s].sort(o=(x,y)=>p(0+x,36)-p(0+y,36),p=parseInt).join``.match(/([a-z])\1*/ig).map(x=>(l=x.length)+x[l-1]).sort(o).join``

Try it online!

parseInt(numberAsString, radix) will try to parse integer in the beginning of string. For example, parseInt('120px', 10) will output 120. When parsing failed, it returns NaN instead. We connect an '0' to the beginning of each character so it will return 0 for any non numeric-alpha characters. And we can sort same letters together and non-alpha character to the beginning by this algorithm.
After sort and join, "Hello world!123" would become " !123deHllloorw". An matching against /([a-z])\1*/ig will ignore any non-alpha character and split the string into chunks with same letters. `.
map convert "aaa" to "3a" as required in the question.
The second sort use same function as the first one. Thanks to the number system, "3b" would be less than "12a" in base 36 just as we expect: It compare counts first (n div 36), and compare the letter later (n mod 36).
Finally join them together.

JavaScript (Node.js), 146 bytes
f=(s,...a)=>(s=s.replace(/[^a-z]/ig,''))?f(s.replace(RegExp(s[c=0],'ig'),x=>(l=++c+x,'')),...a,l):a.sort((x,y)=>p(x,36)-p(y,36),p=parseInt).join``

Try it online!

Why not submit the shorter solution as your main solution? Also, it can be 2 bytes shorter as it's not recursive.

@Shaggy Ah, totally forgot to remove f=. The first one used to be shorter. But it gets 4 bytes more since OP asked the output may be empty string. And I just kept them there...

@Shaggy OK, just find out the second one may be even more shorter. And I placed it as first.

Julia 1.0, 158 bytes
¬t=(c=Dict();C=Dict();for i=eachmatch(r"\w",t);l=i.match;k=lowercase(l);c[k]=get(c,k,0)+1;C[k]=l;end;*(["$v$(C[k])" for (v,k)=sort([(v,k) for (k,v)=c])]...))

Original ungolfed version with same logic:
function password(text)
    letter_counts = Dict()
    cases = Dict()

    for i in eachmatch(r"\w", text)
        letter = i.match[1]
        letter_key = lowercase(letter)
        letter_counts[letter_key] = get(letter_counts, letter_key, 0) + 1
        cases[letter_key] = letter
    end

    sorted_counts = sort([(value, key) for (key, value) in letter_counts])

    return string(["$v$(cases[k])" for (v,k) in sorted_counts]...)
end

Try it online!

Charcoal, 30 bytes
Ｆ⌈Ｅβ№↧θιＦβ¿⁼№↧θκ⊕ι⁺⊕ι§Φθ⁼↧λκ±¹

Try it online! Link is to verbose version of code. Explanation:
Ｆ⌈Ｅβ№↧θι

Run through the lowercase alphabet and find the highest character count in the lowercased input. Loop over the implicit range. (The loop actually goes from 0 to n-1 so I have to increment the loop variable at each use.)
Ｆβ

Loop over the lowercase alphabet again.
¿⁼№↧θκ⊕ι

If the count of the current letter is equal to the outer loop value...
⁺⊕ι§Φθ⁼↧λκ±¹

Concatenate the current count with the last occurrence of the current letter and implicitly print.

Jelly, 14 bytes
fØẠŒuL,ṪƊƙ$ŒuÞ

Try it online!
Full program.

NodeJS, 299 bytes, -6 bytes thank to @tsh
Not so beauty but it work!
(x,l={},g=p=>p.charCodeAt(),q=p=>p.toLowerCase())=>Object.entries([...x[R='replace'](/[^a-z]/gi,'')].reduce((m,n)=>(r=q(n),l[r]=g(n)>96?1:0,{...m,[r]:-~m[r]}),{})).sort((a,b)=>a[1]^b[1]?a[1]-b[1]:g(q(a[0]))-g(q(b[0]))).map(([m,n])=>[n,m]).join``[R](/,/g,'')[R](/[a-z]/g,v=>l[v]?q(v):v.toUpperCase())

Javascript (ES8) (Firefox or Chrome), 294 bytes, -1 byte thank to @tsh
With new .flat method, I can save 10 bytes:
(x,l={},g=p=>p.charCodeAt(),q=p=>p.toLowerCase())=>Object.entries([...x[R='replace'](/[^a-z]/gi,'')].reduce((m,n)=>(r=q(n),l[r]=g(n)>96?1:0,{...m,[r]:-~m[r]}),{})).sort((a,b)=>a[1]^b[1]?a[1]-b[1]:g(q(a[0]))-g(q(b[0]))).map(([m,n])=>[n,m]).flat().join``[R](/[a-z]/g,v=>l[v]?q(v):v.toUpperCase())

Try this online:
https://repl.it/repls/ConcernedHorribleHypothesis

Hello and welcome to PPCG. It would be nice if you provided a way to test your submission, like linking to an online interpreter.

@JonathanFrech I just added test cases, thank you!

.replace x 3 times -> [R='replace] and [R] x 2 times

.charCodeAt(0) -> .charCodeAt() (0 is default)

@tsh Thank you a lot for all your good tips, I just updated my answer!

@tsh your solution beats my solution, btw I upvoted it but I got error that my reputation is not enough so it will not appear, but I want to inform you that I loved this and I learn a lot so I upvoted your solution!

R, 131 129 bytes
cat(paste0(N<-by(X<-utf8ToInt(gsub('[^a-z]','',scan(,''),T)),G<-X%%32,length),L<-intToUtf8(by(X,G,tail,1),T))[order(N,L)],sep='')

Try it online!

Perl 6, 86 82 bytes
{[~] flat map *[0,2],sort map {+$^b,$^a,$b[*-1]},kv classify &lc,.comb: /<alpha>/}

Rebol, 149, 146 bytes
f: func[s][l: charset[#"a"- #"z"#"A"- #"Z"]rejoin sort/skip collect[parse sort s[any[copy t[copy o l any o](keep length? t keep last t)| skip]]]2]

Try it online!
Ungolfed:
f: func [s] [
    l: charset[#"a" - #"z" #"A" - #"Z"]
    rejoin sort/skip collect [
        parse sort s [
            any [
                copy t [copy o l any o] (keep length? t keep last t)
                | skip
            ]
        ]
    ] 2
]

Example usage in Rebol console:
>> f "Kitkat Tango"
== "1g1i1n1o2a2k3T"

>> f "Database Partitions Task"
== "1b1D1e1k1n1o1P1r2i3s4T5a"

>> f "12$*34^!"
== ""


text:
Count the Closed Polygons
Input:
An NxM grid or multi-line string (or other reasonable input-format), containing only printable ASCII (unicode range [32,126]).
Output:
The amount of closed polygons of the same character that can be found, with two special rules:

Spaces are wildcards and can be used (multiple times) for any character
o, O, and 0 are counted as closed polygons themselves

Challenge rules:

(Anti-)Diagonal connections between the same characters (or spaces) are included to form closed polygons.
You cannot go over other characters (except for the wild-card spaces). (I.e. in the first test case/example below, you cannot form two triangles with the A's by going over the x.) So all characters used for a closed polygon should be connected (horizontally, vertically, and/or (anti-)diagonally).
Polygons are at least three characters (excluding the single characters o, O, 0).
Lines of adjacent characters are not closed polygons.
The same characters cannot be used for multiple polygons, excluding wildcard spaces.
Wildcard spaces cannot be counted as o, O, or 0.
Three or more spaces alone cannot form a closed polygon. It should always have at least one non-space (and non o/O/0) character.
Input can be in any reasonable format. Can be a character-matrix, new-line delimiter string, string-array, character-array with added integer width, etc.
The inputs will always be an N by M rectangle (or square), so no weird input-shapes
Since the same characters cannot be used more than once and we want to have as many closed polygons, using multiple characters to form two (or more) closed polygons instead of one larger polygon is of course the intended goal in the counting (which is also why closed polygons formed by o, O, or 0 will never be counted, since they are already closed polygons individually).
Uppercase and lowercase letters are of course counted as individual characters.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Examples / Test Cases:
Input:
AAAw
AxA4
'AoQ

Output: 2, because these polygons can be formed:

Input:
1822uaslkoo
12*2sl ljoo
a* 0a91)j$*
()*#J9dddj*
*Q#ID dJj!"
*UJD SO&*93

Output: 12, because these polygons can be formed:

Note that:
- The yellow one below is not a polygon, because the o's are already counted as separated polygons
- The purple and brown ones aren't closed
- The red, grey, green, and light-blue use one or more non-space characters that were already used for other closed polygons

Input (dimensions are 2x4):
3  3
  2

Output: 3, because these polygons can be formed:

Input:
AAAA
AAAA
AAxA

Output: 3, because these polygons can be formed:

Of course other polygons are possible here, but no more than 3. Here another valid example with 3 polygons:

Input:
0QoO

Output: 3, because these polygons can be formed:

Input:
W w
 Ww

Output: 3, because these polygons can be formed:

Note that the top layer space is used for all three polygons. Here are the three polygons individually highlighted:

Input:
W W
 WW

Output: 3, because the same three polygons as in the previous test can be formed. So no, it's not 2 with these two polygons:

Input:
abcdQefg
hQiQjQQk
QlQmnopQ
QqrstQQu
QvQQQwxy
QQz0QQQQ

Output: 3, because these polygons can be formed:

I want to +1 this but I really don't see what special casing the os, Os & 0s adds to the challenge.

It seems like all example polygons are convex. Unless concave polygons are excluded, I'd suggest to add a test case including one.

@Arnauld Added a test case at the bottom. Not sure if it is sufficient for what you meant, since it only goes inwards once. The grid has to be pretty big to make a concave polygon. If you have any suggested test case I should add in addition, let me know.

@Shaggy You're kinda right. When I made the challenge I saw the shape of the o, O, 0 being circles as individual polygons, but in a solution it doesn't add much, except that the o, O, 0 should be avoided when forming larger polygons, and adding a count for them. Too late to change it now, though.

Python 2, 714 737 821 bytes

-23 bytes thanks to Kevin Cruijssen

M=input()
m=''.join(M)
def P(L):
 if len(L)<2:yield[L];return
 for p in P(L[1:]):
	for n,s in enumerate(p):yield p[:n]+[[L[0]]+s]+p[n+1:]
	yield[[L[0]]]+p
h,w,R,C=len(M),len(M[0]),0,[-1,0,1]
K=[(i,j)for i in range(h)for j in range(w)]
Z=[(i,j)for i,j in K if' '==M[i][j]]
from networkx import*
for l in set(m):
 G,S=[],[]
 if l in'oO0':R+=m.count(l);continue
 for I in K:
  i,j=I
  for p in C:
	for q in C:
	 X=x,y=i+p,j+q
	 if X in K and X!=I and set(M[i][j]+M[x][y])<=set(' '+l):G+=[(I,X)];S+=[I,X]
 B=0
 for L in P(list(set(S))):
  b=0
  for p in L:
	for i,j in p:
	 if' '!=M[i][j]:
		try:find_cycle(from_edgelist([(I,X)for I,X in G if I in p+Z and X in p+Z]));b+=1
		except:1
		break
	if b>B:B=b
 R+=B
print R

Try it online!

For each letter A (except  o, O, and 0) the code build a graph representing the adjacency of the different occurrences of letter A and space in the initial given matrix. Then it computes the set of semi-separated cycles covering the graph when maximizing the number of cycles (separation is based only on the letter A, the same space can be used for several cycles).
The code passes all tests.
Input: the list of lines of the matrix.
More explanation and golfing coming soon.

714 bytes by using a combination of tabs and spaces as indentations, instead of only spaces.


text:
Connect 4: Spot the Fake!
The bank has been broken into, and all the local mafia thugs have an unusual alibi: they were at home playing Connect 4!  In order to assist with the investigation, you are asked to write a program to validate all the Connect 4 boards that have been seized in order to check that the positions are indeed positions from a valid Connect 4 game, and have not been hastily put together as soon as the police knocked on the door.
The rules for connect 4: players R and Y take it in turns to drop tiles of their colour into columns of a 7x6 grid.  When a player drops a tile into the column, it falls down to occupy the lowest unfilled position in that column.  If a player manages to get a horizontal, vertical or diagonal run of four tiles of their colour on the board, then they win and the game ends immediately.
For example (with R starting), the following is an impossible Connect 4 position.
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R| | | | |
| | |Y| | | | |
|R| |Y| | | | |

Your program or function must take in a Connect 4 board and return either

A falsy value, indicating that the position is impossible or
A string of numbers from 1 to 7, indicating one possible sequence of moves leading to that position (the columns are numbered 1 to 7 from left to right, and so the sequence 112, for example, indicates a red move in column 1, followed by a yellow move in column 1, followed by a red move in column 2).  You may choose a column-numbering other than 1234567 if you like, as long as you specify in your solution.  If you want to return the list in some other format; for example as an array [2, 4, 3, 1, 1, 3] then that is fine too, as long as it is easy to see what the moves are.

You can choose to read the board in in any sensible format including using letters other than R and Y for the players, but you must specify which player goes first.  You can assume that the board will always be 6x7, with two players.
You may assume that the positions you receive are at least physically possible to create on a standard Connect 4 board; i.e., that there will be no 'floating' pieces.  You can assume that the board will be non-empty.
This is code golf, so shortest answer wins.  Standard loopholes apply.
Examples
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | | --> 1234567 (one possible answer)
| | | | | | | |
|R|Y|R|Y|R|Y|R|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R| | | | | --> false
| | |Y| | | | |
|R| |Y| | | | |

| | | | | | | |
| | |Y| | | | |
| | |R| | | | |
| | |Y| | | | | --> 323333 (only possible answer)
| | |R| | | | |
| |Y|R| | | | |

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | | --> false (this is the position arising after
| |Y|Y|Y|Y| | |     the moves 11223344, but using those moves
| |R|R|R|R| | |     the game would have ended once R made a 4)

| | | | | | | |
| | | | | | | |
|Y| | | | | | |
|R|Y| | | | | | --> 2134231211 (among other possibilities)
|R|R|Y| | | | |
|Y|R|R|Y| | | |

| | | | | | | |
| | | | | | | |
|Y| | | | | | |
|R|Y| | | | | | --> false (for example, 21342312117 does not
|R|R|Y| | | | |     work, because Y has already made a diagonal 4)
|Y|R|R|Y| | |R|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | | --> 112244553 or similar
|Y|Y| |Y|Y| | |
|R|R|R|R|R| | |

John, out of curiosity, do you know if a non-brute-force algorithm exists?

Jelly, 57 bytes
ŒṪŒ!µ0ịŒṬ¬a³ZU,Ɗ;ŒD$€Ẏṡ€4Ḅo1%15;Ḋ€ṢṚ$Ƒƙ$Ȧȧœị³$2R¤ṁ$ƑµƇṪṪ€

Takes a matrix where 0 is unfilled, 1 played first, and 2 played second. Yields a list of 1-indexed columns, empty if a fake was identified.
Try it online! (too inefficient for more than 7 pieces to run in under a minute)
Note:

Assumes that no "floating" pieces are present (fix this by prepending ZṠṢ€Ƒȧ for +6 bytes)
Assumes that the empty board is a fake

JavaScript (ES6),  202 194 187  183 bytes
Takes input as a matrix with \$2\$ for red, \$4\$ for yellow and \$0\$ for empty. Returns a string of 0-indexed moves (or an empty string if there's no solution). Reds start the game.
m=>(p=[...'5555555'],g=(c,s=o='')=>/2|4/.test(m)?['',0,2,4].some(n=>m.join``.match(`(1|3)(.{1${n}}\\1){3}`))?o:p.map((y,x)=>m[m[y][x]--^c||p[g(c^6,s+x,p[x]--),x]++,y][x]++)&&o:o=s)(2)

Try it online!
How?
The recursive function \$g\$ attempts to replace all \$2\$'s and \$4\$'s in the input matrix with \$1\$'s and \$3\$'s respectively.
While doing so, it makes sure that we don't have any run of four consecutive odd values until all even values have disappeared (i.e. if a side wins, it must be the last move).
The row \$y\$ of the next available slot for each column \$x\$ is stored in \$p[x]\$.
Commented
m => (                            // m[] = input matrix
  p = [...'5555555'],             // p[] = next row for each column
  g = (c,                         // g = recursive function taking c = color,
          s = o = '') =>          //     s = current solution, o = final output
    /2|4/.test(m) ?               // if the matrix still contains at least a 2 or a 4:
      ['', 0, 2, 4]               //   see if we have four consecutive 1's or 3's
      .some(n =>                  //   by testing the four possible directions
        m.join``                  //   on the joined matrix, using
        .match(                   //   a regular expression where the number of characters
          `(1|3)(.{1${n}}\\1){3}` //   between each occurrence is either 1, 10, 12 or 14
        )                         //   (horizontal, diagonal, vertical, anti-diagonal)
      ) ?                         //   if we have a match:
        o                         //     abort and just return the current value of o
      :                           //   else:
        p.map((y, x) =>           //     for each cell at (x, y = p[x]):
          m[                      //
            m[y][x]--             //       decrement the value of the cell
            ^ c ||                //       compare the original value with c
            p[                    //       if they're equal:
              g(                  //         do a recursive call with:
                c ^ 6,            //           the other color
                s + x,            //           the updated solution
                p[x]--            //           the updated row for this column
              ),                  //         end of recursive call
              x                   //         then:
            ]++,                  //         restore p[x]
            y                     //         and restore m[y][x]
          ][x]++                  //         to their initial values
        ) && o                    //     end of map(); yield o
    :                             // else:
      o = s                       //   we've found a solution: copy s to o
)(2)                              // initial call to g() with c = 2

Note I have asked "May we assume that the empty board will not be given as input?" - if we have to handle this then your code will need a tweak.

i don't know why, f([ [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,2,0,2,0,0], [0,2,2,0,2,2,0], [1,1,1,1,1,1,1] ]) terminates by 0  and f([ [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,2,0,2,0,0], [2,2,2,0,2,2,1], [1,1,1,1,1,1,1] ]) should be true

@NahuelFouilleul Thanks for reporting this. I've fixed the code add added these test cases.

Python 2, 295 285 bytes
def f(a):
 if 1-any(a):return[]
 p=sum(map(len,a))%2
 for i in R(7):
	if a[i][-1:]==`p`:
	 b=a[:];b[i]=b[i][:-1];L=f(b)
	 if L>1>(`1-p`*4in','.join([J((u[j]+' '*14)[n-j]for j in R(7))for n in R(12)for u in[b,b[::-1]]]+b+map(J,zip(*[r+' '*7for r in b])))):return L+[i]
R=range;J=''.join

Try it online!
-10 thx to Jo King.
Input is a list of strings representing the columns; with '1' for Red and '0' for Yellow. The strings are not ' '-padded. So the (falsey) case:
| | | | | | | |
| | | | | | | |
|Y| | | | | | |
|R|Y| | | | | |
|R|R|Y| | | | |
|Y|R|R|Y| | |R|

is input as:
[
  '0110',
  '110',
  '10',
  '0',
  '',
  '',
  '1'
]

Output is a list of column indexes, 0-indexed, that could make the board; or None if it's not valid.
Accepts the empty board as valid (returns the empty list [] instead of None).
This approach is recursive from the last move to the first move: based on the parity of the total number of moves taken, we remove either the last Red move or the last Yellow move (or fail if that is not possible); check the resulting board to see if the opponent has 4-in-a-row (in which case fail, because the game should have stopped already); otherwise, recurse until the board is empty (which is valid).
The 4-in-a-row code is the most bloaty part. All the diagonal strings for the matrix b are generated by:
[
    ''.join(
        (u[j]+' '*14)[n-j] for j in range(7)
    )
    for u in[b,b[::-1]]for n in range(12)
]

which first lists out the 'down-sloping' diagonals, and then 'up-sloping' ones.


text:
No-alphanumeric code exec
Introduction
In most interpreted languages, there is an operation that will run code generated at runtime. It generally requires alphanumeric characters to refer to this operation. Write a program, using as few alphanumeric characters as possible, that is able to download and execute any string in the language you're working with, using as few alphanumeric characters as possible.
Informal bonus points for commonly used languages where this is a very difficult task, such as python.
Challenge
Inputs: a url to code in your language of choice, via either stdin or argv.
Outputs: output of executing the downloaded code.
Your program must generate the string to execute and call the eval/exec function/operator without reading from any existing files (excluding the file readings done by your interpreter of choice on startup and reading of standard library files by your language's import mechanism).
Winning entries must be written using only printable ascii characters. Compiled languages are allowed, if you can find a way to invoke the same compiler at runtime with the same settings.
Submissions will be scored, per-language, based on who uses the fewest executable alphanumeric characters. Non-alphanumeric characters do not count towards your score, nor do comments - try to make your non-alphanumeric code readable.
Input and Output example
Contents of my example target gist for python:
print("run by no-alphanum code exec")

example run:
$ python noalpha.py https://gist.githubusercontent.com/lahwran/77e94ef11493d4f36c726efe030f58e4/raw/5f7a0483a9fe7928ae2cf3f786d6d35f9d7870b9/example.py
run by no-alphanum code exec
$

You say only printable ascii, does that include newlines and tabs?

Ah, yes, it does.

I'm confused: so you're basically just telling us to reimplement exec or eval? How much of the language needs to be interpreted? What if our language doesn't have a builtin function to execute code?

Also, why ban non-ASCII and allow comments? That seems nonsensical. If the point is to make it short (alphanumerically), then just make it short?

Python 2, 5 alphanumerics
__=-~-~([]==[])
__*=__
_=__*-~-~-~__
exec('%c'*~-~-~-(__*~-~-__))%(~-~-~-_,-~_,-~-~-~-~_,-~-~-~_,-~-~-~-~-~-~_,-~-~-~-~-~-~-~-~_,' ',_+__,-~-~-~-~-~-~_,_,_,~-~-~-_,~-_-__,' ',~-~-_-__,-~-~-~-~-~-~-~_,' ',_+__,',',-~-~-~-~-~-~-~_,-~-~-~-~_+__,-~-~-~-~-~-~-~_,';',~-~-~-~-~-~-~-_,-~-~-~_+__,~-~-~-~-~-~-~-_,_-__,' ',_+__,'.',_+__,-~-~-~-~-~-~_,_,-~-~-~_,-~-~-~-~_,~-~-~-~-~-~-~-_,-~-~_,'(',-~-~-~-~-~-~-~_,-~-~-~-~_+__,-~-~-~-~-~-~-~_,'.',~-~-_-__,-~-~-~-~-~-~_,~-~-~-~-~-_,-~_+__,'[','_','=','=','_',']',')','.',-~-~-~-~-~-~_,~-~-~-~-~-~-~-_,~-~-_-__,~-~-~-~-~-~-~-~-_,'(',')')

Try it online (with print not exec)
It helps with a bit of experience with Symbolic Python, where alphanumerics are banned anyway. This is rather lazily golfed and could probably be a few dozen bytes shorter, but hey, this isn't code-golf. The 5 alphanumerics here are the exec and the c of %c. If we were allowed unprintables, the %c could be bypassed with the help of the repr operator `.
The executed format string translates to import urllib as u,sys;exec u.urlopen(sys.argv[_==_]).read(), which fetches the resource and executes it.
Explanation:
Python can use variables with names entirely composed of underscores, which really helps us. It also treats True/False as 1/0, which means we can compose numbers entirely without alphanumerics. For example, the first part of the code does:
__=-~-~([]==[])   # Set __ to 3
__*=__            # Square it to 9
_=__*-~-~-~__     # Set _ to 9*12 = 108

Here's where we reach the unavoidable letters. To make letter in a string, we can use %c in a format string to take a number and return the character with that ordinal value. We can then pass this string into the exec statement and voila! We can execute arbitrary code with only 5 alpha-numerics. The majority of the rest of the code is just repeating the %c enough times, then creating the numbers representing each letter.

Javascript, 0 Alphanumerics
This is my first answer, so hopefully I haven't accidentally broken a rule :)
Here's the code before extreme obfuscation:
var str = prompt("Enter relative URL of code to exec:", "");
var xhr = new XMLHttpRequest();
xhr.open('GET', str, true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4)  {
    eval(xhr.responseText);
  }
};
xhr.send(null);

It isn't verified, and neither is the obfuscated (and de-alphanumerized) version.
I used a form of obfuscated JS which you can find here. The actual solution is more than 220,000 characters long. It does have to be run in a browser. Also, there are no comments in the obfuscated code, but the de-obfuscated code speaks for itself if you have JS experience.
There are several online translators.
It takes the input URL through a prompt. You have to run it in a web browser while on the domain that the code is on.
Here's a link to the file, since pastebin lagged out after I pasted it: Source file

Bash, 4 alphanumerics
wget $@
. ${@##*/}

No TIO link because TIO doesn't have hostname resolution.


text:
Binary self-rotation
Given a binary 3D array, for each layer, cyclically rotate up each of its columns as many steps as indicated by the binary encoding of the columns of the layer above it, and then cyclically rotate left each of its rows as many steps as indicated by the binary encoding of the rows of the layer below it.
There will always be at least three layers. The top layer's columns and the bottom layer's rows should not be rotated.
Walk-through
Lets start with the small 4-layer, 2-row, 3-column array:
[[[1,0,1],
  [1,0,0]],

 [[1,0,1],
  [0,1,1]],

 [[0,1,1],
  [1,1,1]],

 [[1,1,0],
  [1,1,1]]]

The first step is evaluating the numbers encoded in binary by the columns and rows of each layer:
     3 0 2
5 [[[1,0,1],
4   [1,0,0]],

     2 1 3
5  [[1,0,1],
3   [0,1,1]],

     1 3 3
3  [[0,1,1],
7   [1,1,1]],

     3 3 1
6  [[1,1,0],
7   [1,1,1]]]

The first layer, [[1,0,1],[1,0,0]] will not have its columns rotated, but its rows will be cyclically rotated left 5 steps and 3 step respectively, thus becoming [[1,1,0],[1,0,0]].
 The second layer, [[1,0,1],[0,1,1]], will have its columns cyclically rotated up 3, 0, and 2 steps respectively, giving [[0,0,1],[1,1,1]], and then the rows are cyclically rotated left 3 and 7 steps respectively, with no visible change.
 The third layer, [[0,1,1],[1,1,1]] rotated up 2, 1, and 3 steps stays the same, and neither does rotating left 6 and 7 steps do anything.
 Finally, the fourth layer, [[1,1,0],[1,1,1]] rotated up 1, 3, and 3 steps is [[1,1,1],[1,1,0]], but its rows are not rotated afterwards, as it is the last layer.
 Putting all the layers together again, gives us the binary self-rotated 3D array:
[[[1,1,0],
  [1,0,0]],

 [[0,0,1],
  [1,1,1]],

 [[0,1,1],
  [1,1,1]],

 [[1,1,1],
  [1,1,0]]]

Example cases:
[[[1,0,1],[1,0,0]],[[1,0,1],[0,1,1]],[[0,1,1],[1,1,1]],[[1,1,0],[1,1,1]]] gives
[[[1,1,0],[1,0,0]],[[0,0,1],[1,1,1]],[[0,1,1],[1,1,1]],[[1,1,1],[1,1,0]]]
[[[1]],[[1]],[[0]]] gives
[[[1]],[[1]],[[0]]]
[[[1,0,1],[1,0,1],[1,0,1]],[[0,0,1],[0,0,1],[0,0,1]],[[1,0,0],[1,0,1],[0,0,1]]] gives
[[[0,1,1],[0,1,1],[0,1,1]],[[0,1,0],[1,0,0],[0,1,0]],[[1,0,1],[1,0,1],[0,0,0]]]

Jelly,  18  17 bytes
ṙ""Ḅ}
Z€çŻṖ$$Z€çḊ

Try it online!
How?
ṙ""Ḅ} - Link 1, rotation helper: 3d matrix to rotate, 3d matrix of rotation instructions
    } - use the right argument for:
   Ḅ  -   un-binary (vectorises) - get the rotation amounts as a 2d matrix
  "   - zip with:
 "    -  zip with:
ṙ     -    rotate (the current row) left by (the current amount)

Z€çŻṖ$ $Z€çḊ - Main Link: 3d matrix, M
Z€           - transpose €ach (layer of M)
       $     - last two links as a monad:
     $       -   last two links as a monad:
   Ż         -     prepend a zero
    Ṗ        -     pop (i.e. remove the tail)
  ç          -   call the last Link as a dyad (i.e. f(Z€ result, ŻṖ$ result) )
        Z€   - transpose €ach (layer of that)
           Ḋ - dequeue (i.e. remove the head layer of M)
          ç  - call the last Link as a dyad (i.e. f(Z€çŻṖ$$Z€ result, Ḋ result) )

Note: $$ (or possibly $$ ... $$?) seems to mess up the code-block formatting (but only once posted, not in the preview), so I added a space to make my life easier.

Python 2, 220 211 209 185 176 174 164 161 159 bytes
lambda m:map(R,z(map(R,z(m,['']+[z(*l)for l in m])),m[1:]+['']))
R=lambda(l,L):map(lambda r,i:r[i:]+r[:i or 0],z(*l),[int(`b`[1::3],2)%len(b)for b in L])
z=zip

Try it online!
-2 bytes, thanks to Jonathan Allan

Since you handle None during the slicing for the rotation I believe both of the ['0'] can become [[]].

@JonathanAllan Thanks :)

APL+WIN, 53 39 bytes
Many thanks to Adám for saving 14 bytes
(1 0↓⍉2⊥⍉m⍪0)⌽(¯1 0↓2⊥2 1 3⍉0⍪m)⊖[2]m←⎕

Try it online! Courtesy of Dyalog Classic
Prompts for input of a 3d array of the form:
4 2 3⍴1 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 1 1 1 0 1 1 1

which yields:
1 0 1
1 0 0

1 0 1
0 1 1

0 1 1
1 1 1

1 1 0
1 1 1

Explanation:
m←⎕ Prompt for input

(¯1 0↓2⊥2 1 3⍉0⍪m) Calculate column rotations

(1 0↓⍉2⊥⍉m⍪0) Calculate row rotations

(...)⌽(...)⊖[2]m Apply column and row rotation and output resulting 3d array:

1 1 0
1 0 0

0 0 1
1 1 1

0 1 1
1 1 1

1 1 1
1 1 0

Instead of enclosing and using ¨, just process the entire array at once. Try it online!

@Adám Many thanks. I do not know why I over thought this one and went the nested route :( Getting old?

R, 226 216 205 bytes
-21 bytes thanks to digEmAll
function(a,L=`for`){d=dim(b<-a)
r=function(a,n,l=sum(a|1))a[(1:l+sum(n*2^(sum(n|1):1-1))-1)%%l+1]
L(i,I<-2:d[3],L(j,1:d,b[j,,i]<-r(b[j,,i],a[j,,i-1])))
L(i,I-1,L(k,1:d[2],b[,k,i]<-r(b[,k,i],a[,k,i+1])))
b}

Try it online!

05AB1E, 41 39 bytes
εNĀiø¹N<èøJC‚øε`._}ø}N¹g<Êi¹N>èJC‚øε`._

This feels way too long.. Can definitely be golfed some more.
Try it online or verify all test cases.
Explanation:
ε                    # Map each layer in the (implicit) input to:
                     # (`N` is the layer-index of this map)
 NĀi                 #  If it is not the first layer:
    ø                #   Zip/transpose the current layer; swapping rows/columns
    ¹N<è             #   Get the `N-1`'th layer of the input
        ø            #   Zip/transpose; swapping rows/columns
         J           #   Join all inner lists (the columns) together
          C          #   And convert it from binary to integer
           ‚         #   Pair it with the current layer's columns we're mapping
            ø        #   Zip/transpose; to pair each integer with a layer's columns
             ε   }   #   Map over these pairs:
              `      #    Push both values of the pair separately to the stack
               ._    #    Rotate the column the integer amount of times
    ø                #   Zip/transpose the rows/columns of the current layer back
   }                 #  Close the if-statement
 N¹g<Êi              #  If this is not the last layer (layer-index-1 != amount_of_layers):
       ¹N>è          #   Get the `N+1`'th layer of the input
           J         #   Join all inner lists (the rows) together
            C        #   And convert it from binary to integer
             ‚       #   Pair it with the current layer's rows we're mapping
              ø      #   Zip/transpose; to pair each integer with a layer's rows
               ε     #   Map over these pairs:
                `    #    Push both values of the pair separately to the stack
                 ._  #    Rotate the row the integer amount of times
                     # (implicitly output the result after the layer-mapping is done)

Wolfram Language (Mathematica), 138 131 125 123 bytes
t=Map@Thread
m=MapThread[r=RotateLeft,#,2]&
b=(a=ArrayPad)[Map@Fold[#+##&]/@#,1]~r~#2~a~-1&
g=m@{t@m@{t@#,t@#~b~-1},#~b~1}&

Try it online!

Map[Thread] is equivalent to Transpose[a, {1,3,2}], which transposes the columns and rows.
Fold[#+##&] is shorter than IntegerDigits[#,2] for converting from binary.