text:
Code a code page
Introduction
A code page maps integer values to a specific character. We can visualize a code page like this:

+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | q | w | e | r | t | z | u | i | o | p | a | s | d | f | g | j |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 1 | k | l | y | x | c | v | b | n | m | Q | W | E | R | T | Z | U |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 2 | I | O | P | A | S | D | F | G | H | J |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

The rows specify the first digit and the columns the second digit of the hex-number.
The Challenge
Given a string of 16-255 unique characters, output the corresponding code page using the zero-based index of each character in the string as it's value.
The input qwertzuiopasdfgjklyxcvbnmQWERTZUIOPASDFGHJ for example would yield the table above.

The output has to be in the exact same format as the table above. Only a trailing newline is optional.
If the input length is not a multiple of 16, you need to start a new row for the remaining characters and leave the unused cells empty (=filled with 3 spaces).
Each character is placed exactly in the middle of a cell, padded by one space to the left and right.
The values in the first row and column are given by hex-numbers with the digits 0123456789ABCDEF. Those are padded with one space to the left and right as well. You may choose to use lowercase hex-digits but you need to stick to one.
The only characters present in the output are hyphens -, pluses +, pipes |, spaces  , the digits for hexadecimal numbers and the characters from the input.
Any builtins that are related to ASCII-art tables or trivialize the problem in any way are forbidden.
You may assume that the input consists only of characters of a specific encoding. Please specify if that is the case.
If your language can only handle ASCII input, you may assume ASCII-only input and repeated characters.

Rules

Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Happy Coding!

Can we use lowercase hex digits?

@Doorknob Yes, clarified it in the challenge.

Can we assume the input is ASCII (with possibly repeated characters)?

@DenkerAffe That would conflict with the word "unique" or with "255" in Given a string of 16-255 unique characters, though...

@DenkerAffe It's a pity, because using non-ASCII will leave quite a few languages out. You could always allow sequences with repeated characters, and so allow ASCII-only languages too. The spirit of the challenge is not altered by that, and more languages can participate

@LuisMendo Hmm yea, thats true. Gonna allow that for languages that can only handle ASCII.

@DenkerAffe Is it okay if the code page is not in exactly the same format as the one you show?

@R.Kap No, the output has to be exactly as specified.

@DenkerAffe I'm talking about the look of the page. For example,is it okay to print out the first row like  | 1 || 2 || 3 || 4 |... instead of what you show in your example?

@R.Kap That's not an example, thats the reference format. You have to use this and nothing else. Othwewise the answers wouldn't be compareable.

@DenkerAffe Ah, okay. I'll use that format then.

So you have a QWERTZ keyboard, right?

Pyth, 60 bytes

K+*"+---"hJ16\+Vm++"| "j" | "d" |"+]+]d.HMJ.e+.Hk.[bdJczJNK

The leading newline is significant.
Try it here.

Can you show the transpiled code?

@CatsAreFluffy Just enable the debug mode in the online interpreter.

What does the newline do?

@Adnan Whoops, that was an oversight on my part. Fixed, thanks.

@KennyLau It prints the first +---+---+---[...]. In Pyth, the newline function prints and returns its argument.

I just did not know that "\n" means, I thought it means the string "n" (because "" is used for strings)

Python 3.5, 326 355 bytes:
(+29 bytes since if the length of the last row is not a multiple of 16, unused cells should be left empty (although, in my opinion, it looks much better if those empty cells are just not even shown))
def f(r):o=' 0123456789ABCDEF';r=[r[0+i:16+i]for i in range(0,len(r),16)];print('+---'*17+'+\n|',end='');[print(' {} |'.format(h),end='')for h in o];print(''.join([str(e+' | ')if e.isdigit()or e.isalpha()else str(e)for e in''.join([str('\n'+'+---'*17+'+\n| '+x[0]+x[1])for x in zip(o[1::1],r)])]),end='');print('  |'+'   |'*(15-len(r[-1]))+'\n'+'+---'*17+'+')

Works like a charm!
Sample Inputs and Outputs:
Input: 'hopper'

Output:

    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    |   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 0 | h | o | p | p | e | r |   |   |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

Input: 'honkhonkhonkhonkhonk'

Output:

    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    |   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 0 | h | o | n | k | h | o | n | k | h | o | n | k | h | o | n | k |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 1 | h | o | n | k |   |   |   |   |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

Input: 'hi'

Output:

    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    |   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 0 | h | i |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

I hope this is okay.
Also, here is another version I created for this challenge, which, although is an invalid candidate since it does not print out extra empty cells for the last row if its length is not a multiple 16, in my opinion outputs a much better looking page than the one required by OP, mainly because it does not even show empty cells if the last row is not a multiple of 16, but instead just shows filled cells, and that's it:
def f2(r):o=' 0123456789ABCDEF';r=[r[0+i:16+i]for i in range(0,len(r),16)];print('+---'*17+'+\n|',end='');[print(' {} |'.format(h),end='')for h in o];print(''.join([str(e+' | ')if e.isdigit()or e.isalpha()else str(e)for e in''.join([str('\n'+'+---'*17+'+\n| '+x[0]+x[1])for x in zip(o[1::1],r)])]));print('+---'*(len(r[-1])+1)+'+')

Here is a sample input and output for the inapplicable code above:
Input: 'ggreuuobgugoubgoubguorgoruguor'

Output:

    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    |   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 0 | g | g | r | e | u | u | o | b | g | u | g | o | u | b | g | o |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 1 | u | b | g | u | o | r | g | o | r | u | g | u | o | r |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

    (As you can see, there are no empty cells shown in the entire table. This looks much better to me.)

"If the input length is not a multiple of 16, you need to start a new row for the remaining characters and leave the unused cells empty (=filled with 3 spaces)."

@KennyLau Ah, yes. I did not see that. Dang...edit now in progress. Honestly though, this looks much better than the one OP shows, don't you think?

Why the down vote?

@R.Kap I couldn't quite tell you, but here, have an upvote

Excel VBA, 157 146 Bytes (Cheating?)
Anonymous VBE Immediate Window function that destructively takes input from range [A1] and outputs to the ActiveSheet object.
Golfed
[B1:Q1]="=Dec2Hex(Column(B1)-2)":L=[Len(A1)]:For i=0To l:Cells(i\16+2,i Mod 16+2)=Mid([A1],i+1,1):Next:For i=1To l\16+1:Cells(i+1,1)=i:Next:[A1]="

Formatted
[B1:Q1]="=Dec2Hex(Column(B1)-2)"
L=[Len(A1)]
For i=0To l:Cells(Int(i/16)+2,i Mod 16+2)=Mid([A1],i+1,1):Next
For i=1To Int(l/16)+1:Cells(i+1,1)=i:Next
[A1]=""

Input / Output
Given:
[A1]="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJ"

the generated output is

probs not valid, but cool anyway.
To make it more similar (but  still invalid?) you should turn on the appropriate cell boarders.

Excel (Version 1911), 247
A1 =DEC2HEX(COLUMN(A1:P1)-1)
A2 'Input String
A3 =2+LEN(A2)/16
A4 =CONCAT(" ",C2#)
A5 =TEXTJOIN("
"&REPT("+---",17)&"+
",0,,"| "&MID(A4,B2#+1,1)&" | "&MID(TEXTJOIN(" | ",0,A1#,MID(A2&REPT(" ",16),HEX2DEC(C2#&A1#)+1,1)),B2#*64+1,61)&" |",) ' Output
B2 =SEQUENCE(A3)-1
C2 =DEC2HEX(SEQUENCE(A3-1)-1)

Sample Test

Excel (Joke answer), 88 Bytes
Not a valid solution, but fun
B2 'Input
C4 =DEC2HEX(SEQUENCE(,16,0))
B5 =DEC2HEX(SEQUENCE(1+LEN(B2)/16)-1)
C5 =MID(B2,HEX2DEC(B5#&C4#)+1,1)

Output

JavaScript (ES6), 148 bytes
s=>(s=' 0123456789ABCDEF'+s+' '.repeat(15)).match(/(?!^).{16}/g).map((t,i)=>d+`+
| `+[s[i],...t].join` | `,d=`+---`.repeat(17)).join` |
`+` |
${d}+`

The ' 0123456789ABCDEF' exists to populate the first column, but conveniently also covers the first row. The input string is then padded with spaces to allow it to be split into substrings of length 16, with the (?!^) preventing the leading space from being matched. The rest is just joining up the pieces.

05AB1E, 65 63 bytes
Code:
"+---"17×'+J©,žhAu6£¹J16÷)v„| ?N>iðëN<16B}y«ð17×ðñvy„ |ðJ?}¶?®,

Try it online!. Uses CP-1252 encoding.

PowerShell, 127 126 121 bytes
($d='+---'*17+'+')
($n="0123456789ABCDEF$args"+' '*16)|sls '.{16}'-a|% m*|% v*|%{"$($n[$i++-1]+$_|% t*y|%{"| $_"}) |"
$d}

Try it online!

Perl 5 -pF, 134 109 106 bytes
@F=(@a=($",0..9,A..F),@F);shift@F;printf+($_="+---"x@a.'+
')."|%2s "x@a."|
",$a[$i++],splice@F,0,16while@F

Try it online!

Perl 5 -pl, 127 120 bytes
@.=($",0..9,A..F);$\='+---'x@..'+
';$_=join'',@.,s;.{1,16};$.[$.++].sprintf'%-16s',$&;gre;s;.;| $& ;g;s;.{1,68};$\$&|
;g

Try it online!
Previous version:
@.=($",0..9,A..F);$~='+'.'---+'x@.;$_=join'',@.,s;.{1,16};$.[$.++].sprintf'%-16s',$&;gre;s;.;| $& ;g;s;.{1,68};$~
$&|
;g;$_.=$~

Try it online!

05AB1E, 47 45 bytes
Thanks to Kevin Cruijssen for -2 bytes!
16ôí16jí15ÝhJš¬ðìsøv"+---"69∍=yS3j€ÀõšĆ'|ý,},

Try it online!
Commented:
16ô                     # split the input into groups of (up to) 16
   í16jí                # right-pad the groups to 16 with reverse, left-pad, reverse
        15Ý             # push [0, 1, ..., 15]
           hJ           # convert each number to hexadecimal and join into string
                        #  => "0123456789ABCDEF"
               š        # prepend this string to the list
                ¬       # get the string back from the list
                 ðìs    # prepend a space
                    ø   # zip the list and the string

v              }        # iterate over the list
 "+---"                 # push the string "+---"
       69∍              # extend it to length 69
          =             # print it without removing the string from the stack
 y                      # push the current entry
  S                     # split into a list of characters
   3j                   # left-pad each to 3 chars with spaces
     €À                 # rotate each string left
       õšĆ              # prepend and append the empty string
          '|ý           # join by "|"
             ,          # print the string

,                       # after the loop: print "+---"69∍, which is still on the stack

Try the first part with step-by-step output
Try one loop-iteration with step-by-step output

DŠšs can be š¬ for -2

PS: It doesn't save bytes here, but just in case you're unaware of it, there is a builtin "surround with" .ø. The 3j€Àõš could alternatively have been ðδ.øõ.ø.

@KevinCruijssen That does look a little cleaner, I did not know about this builtin. I had õšĆ… | ý¦¨ as a same-length alternative and I guess ðì€ĆõšĆ works too.

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


text:
Ordering words to fit in a given string
Given a string of letters and a set of words, output an ordering of the words so
that they can be found in the string by dropping letters that are not needed.
Words may occur more than once in the word set. The input string and all words
will consist of 1 to 1000 lower case letters each. The letters to be dropped may occur inside words or between words.
Your program or function can accept the letter string and words as lists, a string, or from STDIN, and must output all words in a correct order as a list
or string output. If there is more than one correct solution, only output one of
them. If there is no possible correct solution, output an empty list or an empty
string.
Examples:
dogcatfrog cat frog dog
-> dog cat frog

xxcatfixsxhingonxgrapexxxfishingcxat cat grape catfish fishing
-> catfish grape fishing cat

dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc
-> da ab ba ba ba cc bb aa ac dc db dd

flea antelope
->
(no solution)

This is code golf. Lowest number of bytes wins.
Edit: Explained that extra characters can be inside words.

Can the input format be one string and then another list of the remaining strings?

@Doorknob, yes, that is fine. Input and output structures are flexible. Added to challenge.

From the test cases it appears that the dropped letters are always between words. Is that so? You should state that in the challenge, or include a test case with letters dropped within a word

I don't understand that third test case; your answer puts cc before bb but the bb and cc substrings only appear once and the bb substring appears first.

@Neil, in the ccbcb part of the string we output the cc then output bb after dropping the middle c.

@LuisMendo, there is an example with a c in the bb word in the third example, but I will make it more clear by some obvious x characters in the second example.

Is it possible to have some strings present and some not of the list, and if yes, what would be the output? For example: thisisatest test is random ate; should this output is ate test; is ate test random (concatting all non-matching strings); or this just isn't a valid test case?

I feel like there's an easy way to do this with regex... Hmmm...

Pyth, 20 24 bytes
My first attempt on Pyth :)
Jcw;FG.ptJI:hJj".*"G0jdG

How it works:
Jcw;FG.ptJI:hJj".*"G0jdG
Jcw                         assign("J",chop(input()))
    FG.ptJ                  for G in permutations(tail(J)):
          I:hJj".*"G0        if match(head(J),join(".*",G)):
                     jdG      print(join(" ",G))

Notes: it takes a long time in the third example (dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc).

Pyth, 10 bytes
h@s./Myz.p

Demonstration
This program is very much brute force. It first constructs every subset of the input, then every partition of the subsets, then checks for the first one which is a reordering of the word list. No possibilities is handled via erroring with no output to stdout, which is allowed by meta consensus. The error can be removed for 2 extra bytes.
Note that for many of the given test cases, the program will not complete in a reasonable period of time.

You missed the second testcase.

@KennyLau When I try that case, it simply doesn't return in a reasonable period of time. It doesn't give the wrong answer, however. I think it works. Do you have a test case where it does return an answer, and that answer is wrong?

Really nice method.

You defeated me.

Could you add that to the answer?

JavaScript (ES6), 119 bytes
(s,a,t=``,...r)=>a[0]?a.find((w,i)=>(b=[...a],b.splice(i,1),f(s,b,w+t,w,...r)))&&q:~s.search(t.split``.join`.*`)&&(q=r)

Accepts a string and an array of words and returns an array of words or undefined on failure. Add 2 bytes if it must return the empty string on failure (?q:``), in which case this alternative version is only 120 bytes and returns the empty string on failure, and can even save 2 bytes if it's allowed to return 0 on failure:
(s,a,t=``,...r)=>a[0]?a.reduce((q,w,i)=>q||(b=[...a],b.splice(i,1),f(s,b,w+t,w,...r)),0):~s.search([...t].join`.*`)?r:``

(After writing this I noticed that the algorithm is basically the same as @KennyLau's Pyth answer.)
Edited edit: updated after clarification of question, but is now really slow on the third test case; I set it off the night before last and this morning I've just noticed that it has actually found the solution, somewhere between 30 and 40 hours later. I was really mean though and fed the solution to it (it works best with the reversed solution, which it will verify instantly).

Java 7, 256 bytes
import java.util.*;String c(String...a){Map s=new HashMap();int j,i=1,l=a[0].length();for(;i<a.length;i++)if((j=a[0].indexOf(a[i]))>-1)s.put(j,s.get(j)!=null?s.get(j)+" "+a[i]:a[i]);a[0]="";for(j=0;j<l;j++)a[0]+=s.get(j)!=null?s.get(j)+" ":"";return a[0];}

It should definitely be possible to golf this more by using a different approach, but this will do for now..
Ungolfed & test code:
Try it here.
import java.util.*;
class M{
  static String c(String... a){
    Map s = new HashMap();
    int j,
        i = 1,
        l = a[0].length();
    for(; i < a.length; i++){
      if((j = a[0].indexOf(a[i])) > -1){
        s.put(j, s.get(j) != null
                  ? s.get(j) + " " + a[i]
                  : a[i]);
      }
    }
    a[0] = "";
    for(j = 0; j < l; j++){
      a[0] += s.get(j) != null
               ? s.get(j) + " "
               : "";
    }
    return a[0];
  }

  public static void main(String[] a){
    System.out.println(c("dogcatfrog", "cat", "frog", "dog"));
    System.out.println(c("xxcatfixsxhingonxgrapexxxfishingcxat", "cat", "grape", "catfish", "fishing"));
    System.out.println(
        c("dababbabadbaccbcbaaacdacdbdd ", "aa", "bb", "cc", "dd", "ba", "ba", "ba", "ab", "ac", "da", "db", "dc"));
    System.out.println(c("flea", "antelope"));
  }
}

Output:
dog cat frog
cat grape fishing
da ab ba ba ba bb db ac cc aa dd

Groovy (44 Bytes)
I can't believe nobody else used regexes for this...
{a,b->a.findAll(/${b.join('|')}/).join(" ")}

Explanation
/${b.join('|')}/ - Create a regex to find any of the words in a string.
.findAll(...) - Find and collect all occurrences in the string into an array.
.join(" ") - Join the array together with spaces.
Basically, if there aren't any occurrences, the array is empty and returns an empty string implicitly. If it does find occurrences, it returns an array object with the occurrences then flattens it into a string.

source: Stack Exchange

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

sort: votes


text:
Find the shortest way to advance a counter to a certain number
I have a counter. It's a small device that looks like this:

The display goes from 0000 to 9999. It has a little push-button at the top that increases the count by 1, and a little knob at the right whose purpose is to reset the counter back to 0.
Now, the thing about the little knob is that if you turn it backwards, you can make it increase any digit that you want once you turn it forwards again. So if I push the counter button 10 times so that the counter shows 0010, I can then turn the knob backwards until i hear a tiny click, then turn it forwards again and make it go straight to 0090.
But, the knob will always increase all occurrences of the same digit by 1 every time it pushes numbers forward. So if the counter shows 6060, you can only make it increase to 7070, not to 6070 or 7060. Also, the knob will roll 9s over to 0 without carrying, so 0990 will advance to 0000 instead of 1000 or 1100.

I want to know the most efficient way to set the counter to a certain number. Your task is to write a program or function that will determine the shortest sequence of button pushes and knob advancements required to do so.
Your program will take as input a 4-digit number from 0000 to 9999, and return a series of steps in the following format:
> 0001
C
> 0093
C12345678C12345678CCC
> 1000
C12345678C12345678C12345678C12345678C12345678C12345678C12345678C
> 9999
012345678

Where C stands for "push the counter button" and any digit D from 0 to 9 stands for "use the knob to advance all occurrences of D by 1".
Your program must produce a valid sequence of steps for all possible four-digit combinations, and will be scored by the total number of steps required for all 10,000 cases. In the case of a tie (most likely when the optimal algorithm is found), the shorter code will win.

What happens if you turn the knob forward? Will it turn 0010 into 0020 in that case? Or can you only turn the knob backwards? And also, does each "D" count as "D" number of advancements of the knob (for instance, does 1234567 mean turn the knob 1 time, then 2 times, then 3 times, so on so forth)? Or does it just signify each separate knob turn (for instance, does 1234567 just mean turn the knob 7 times)?

Looks like the above and the below are unrelated.

The knob can even choose digits in the below.

Turning the knob forward will either advance 0010 to 0020 or 1111, depending on the position the knob is already in. You turn the knob backwards to set its position, and then forward to advance the digits.

each D signifies a separate advancement of the digits, so 1234567 signifies turning the knob 7 units.

Seriously, this guy needs his counter at the correct value!!!! NOW!!!

@edc65 0093:C12345678C12345678CCC. After C12345678: 0009. After another C: 0010. After another 12345678: 0090. Then after CCC: 0093.

Pyth, 327763 steps (optimum, 130 bytes)
Since the online compiler is inept at dealing with such enormous task, I have given it less work, so that it only generates 0, 1, and 1111. However, it can theoretically solve the problem, because it uses the same algorithm as the Lua at the top.
Try it online!
=Y.d((0k;V53=ZYFGY XZG=k@YG=N%"%04d"GV4=b@NH=di:Nb%"%d"ehibTT XZd.x?>l@Ydlk+kb@Yd+kb)=bhGI<G9999 XZb.x?>l@Yblk+k\C@Yb+k\C))=YZ;@YQ

How it works:
=Y.d((0k;V53=ZYFGY XZG=k@YG=N%"%04d"GV4=b@NH=di:Nb%"%d"ehibTT XZd.x?>l@Ydlk+kb@Yd+kb)=bhGI<G9999 XZb.x?>l@Yblk+k\C@Yb+k\C))=YZ)@YQ
                  assign_copy('Q',eval_input())
=Y.d((0k;         assign_copy('Y',dict(0=k))
V53               for N in range(0,53):
=ZY                   assign_copy('Z',Y)
FGY                   for G in num_to_range(Y):
 XZG=k@YG                 no_print(Z[G] = assign_copy('k',lookup(Y,G)))
=N%"%04d"G                assign_copy('N',format("%04d",G))
V4                        for H in range(0,4):
=b@NH                         assign_copy('b',lookup(N,H))
=di:Nb%"%d"ehibTT             assign_copy('d',base(replace(N,b,format("%d",mod10(increment(base(b,10))))),10))
 XZd.x?>l@Ydlk+kb@Yd+kb       no_print(Z[d]=try_and_catch(greater_than(Plen(lookup(Y,d)),Plen(k)) ? concat(k,b) : lookup(Y,d)), lambda:plus(k,b))
)                         <anti-indent>
=bhG                      assign_copy('b',head(G))
I<G9999                   if less_than(G,9999):
 XZb.x?>l@Yblk+k\C@Yb+k\C     no_print(Z[b]=try_and_catch(greater_than(Plen(lookup(Y,b)),Plen(k)) ? concat(k,"C") : lookup(Y,b)), lambda:plus(k,"C"))
)                         <anti-indent>
)                     <anti-indent>
=YZ                   assign('Y',Z)
)                 <anti-indent>
@YQ               print(lookup(Y,Q))

Just noting: The lua one is below. :P  But this is amazing, good work.

Is still above for me :o

I sort by active, maybe you have votes. But it doesn't really matter.

Oh it's below for me now lol

Lua, 327763 steps (optimum, 276 bytes)
Golfed version:
a={[0]=""}t=tonumber for i=0,52 do A={}for k,v in pairs(a)do A[k]=v L=("%04d"):format(k)for i=1,4 do c=L:sub(i,i)d=L:gsub(c,(t(c)+1)%10)e=a[t(d)]A[d]=(not e or #e>#v)and v..c or e end b=k+1 if k<9999then e=a[b]A[b]=(not e or #e>#v)and v.."C"or e end end a=A endprint(a[(...)])

Improved version of the examples in question (only 1000 is improved):
0001:C
0093:CCCCCCCCCC12345678CCC
1000:0CCCCCCCCCCC2345678C23456789
     (0000>1111>1122>1199>1200>1000)
9999:012345678

Ungolfed version:
a = {[0]=""}
for i=0,52 do
    A = {}
    for k,v in pairs(a) do
        A[k] = v
        L=("%04d"):format(k)
        for i=1,4 do
           c=L:sub(i,i)
           d=L:gsub(c,(tonumber(c)+1)%10)
           e=a[tonumber(d)]
           A[d] = (not e or #e > #v) and v..c or e
        end
        b=k+1
        if k < 9999 then
            e=a[b]
            A[b] = (not e or #e > #v) and v.."C" or e
        end
    end
    a=A
end
print(a[93],a[1000],a[9999])

Mathematica, score 512710
Unprotect[StringRepeat]
StringRepeat[x_String, 0]:=""
Protect[StringRepeat]
#<>StringRepeat["C",#3-#2*1111]&[Array[ToString@#&,#,0],##]&[If[#<10^3,0,Quotient[#,1111]],#]&

Fixes a bug with StringRepeat (behaves incorrectly for StringRepeat[x_String,0])

Does there need to be a space in StringRepeat[x_String, 0]:=""?

Nope, but I was too lazy to remove it. Is that a problem?

Not at all :P It was just curious to me that the rest of the code is golfed except for one whitespace.

... that is golfed, right? Or is Mathematica the new line noise?

@cat This isn't [tag:code-golf]

@pppery and yet the code looks golfed

JavaScript (ES6), 327763 steps (optimum, 184 bytes)
A Breadth First Search, not so smart and not so fast.
t=>eval("for(k=[],s=[['0000',i='']];[u,p]=s[i++],u-t;k[v=(1+u-~0+'').slice(-4)]=k[v]||s.push([v,p+'C']))[...u].map(x=>k[v=[...u].map(y=>x-y?y:-~x%10).join``]=k[v]||s.push([v,p+x]));p")

Less golfed
t=>{
  k=[]; // mark values already found to reduce search
  for( i=0, s=[['0000','']];
       [u,p]=s[i++], // u: current code, p:current steps
       u != t; // exit if target found
     )
  {
     // try all digits present in current code
     [...u].map(x=> {
       v=[...u].map(y=>x-y?y:-~x%10).join`` // apply digit x to u
       if (!k[v]) // check if value v not found already
          k[v] = s.push([v,p+x]));
     })
     v=(1+u-~0+'').slice(-4); // try operator C
     if (!k[v]) // check if value v not found already
       k[v] = s.push([v,p+'C']))
  }
  return p
}

Test

f=t=>eval("for(k=[],s=[['0000',i='']];[u,p]=s[i++],u-t;k[v=(1+u-~0+'').slice(-4)]=k[v]||s.push([v,p+'C']))[...u].map(x=>k[v=[...u].map(y=>x-y?y:-~x%10).join``]=k[v]||s.push([v,p+x]));p")

function SingleTest()
{
  var i=S.value
  if (/^\d{4}$/.test(i)) X.value=f(i)
  else X.value='invalid input'
}

SingleTest()

function LongTest()
{
  var i=0,v,r,t=0

  var step=_=>{
    v = ('000'+i).slice(-4);
    r = f(v);
    t+= r.length
    V.value = v;
    R.value = r;
    T.value = t;
    ++i;
    if(i<10000) setTimeout(step, 0)
  }

  step()
}
#V,#T,#S { width:5em }
#R,#X { width: 25em }
Single Test <input id=S value='0093'><button onclick="SingleTest()">-></button><input readonly id=X>

Long test (0000 ... 9999) <button onclick="LongTest()">Go</button>(i mean long, runtime 1 hour)

<input readonly id=V>
<input readonly id=R>
Total steps:<input readonly id=T>

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


text:
Turn a string into a windmill
The code on this site is rapidly being depleted. We need to invest in renewable strings. So you must write a program that takes a string and converts it into a windmill.
The Challenge
Let's take a simple wind-mill string as an example. Take the string abc. The pivot is the center character, in this case b. Since the string is 3 chars long, every output will be exactly three lines tall and three characters wide. Here is your output on step 1. (Note the whitespace)

abc

To get the next step, rotate each character around the pivot clockwise. Here is step 2:

a
 b
  c

Here are steps 3-8:

 a
 b
 c

  a
 b
c

cba

c
 b
  a

 c
 b
 a

  c
 b
a

And on the ninth step, it comes around full circle to the original string:

abc

Note that the b stayed in the same spot the whole time. This is because b is the pivot character. You must write a program or function that takes a string as input and repeatedly prints out this sequence until the program is closed.
Clarifications

All input strings will have an odd number of characters. (So that every windmill will have a pivot)

To keep the challenge simple, all strings will only contain upper and lowercase alphabet characters.

The output must be len(input_string) characters wide and tall.

It doesn't matter which step of the sequence you start on, just as long as you continue rotating and looping forever.

More Test IO:
Since the post is already pretty long, here is a link to  the output for "windmill":
Sidenote:
Since this is supposed to be a windmill, it would be awesome if you include some boilerplate code to animate it with a small time delay or a user input between each step. However, since some languages don't have time builtins, this is not mandatory. The competing part of your submission can just print the sequence as fast as possible.

Related

MATL, 35 33 21 bytes
jtn2/kYaG1$Xd`wtD3X!T

The following will animate the windmill (26 bytes)
jtn2/kYaG1$Xd`wtXxDlY.3X!T

Online Demo
In this version , the Xx specifies to clear the display and the 1Y. is a 1-second pause.
Explanation
The basic idea is that we want to create two versions of the input. An "orthogonal" version
+-----+
|     |
|     |
|abcde|
|     |
|     |
+-----+

And a "diagonal" version
+-----+
|a    |
| b   |
|  c  |
|   d |
|    e|
+-----+

We push these two versions onto the stack. Each time through the loop, we switch the order of stack and rotate the top one clockwise.
j       % Grab the input as a string
t       % Duplicate the input

%--- Create the "orthogonal" version ---%

n2/     % Determine numel(input) / 2
k       % Round down to nearest integer
Ya      % Pad the input string with floor(numel(input)/2) rows above and below

%--- Create the "diagonal" version ---%

G       % Grab the input again
1$Xd    % Place the input along the diagonal of a matrix

`       % do...while loop
  w     % Flip the order of the first two elements on the stack
  t     % Duplicate the top of the stack

  %--- OCTAVE ONLY (converts NULL to space chars) ---%

  O       % Create a scalar zero
  32      % Number literal (ASCII code for ' ')
  XE      % Replaces 0 elements in our 3D array with 32 (' ')

  %--- END OCTAVE ONLY ---%

  D     % Display the element
  3X!   % Rotate this element 90 degrees counter-clockwise 3 times (clockwise)
  T     % Explicit TRUE to create an infinite loop
        % Implicit end of while loop

JavaScript (ES6), 291 bytes

r=a=>{w.textContent=a.map(a=>a.join``).join`
`;for(i=j=h=a.length>>1;j++,i--;){t=a[i][i];a[i][i]=a[h][i];a[h][i]=a[j][i];a[j][i]=a[j][h];a[j][h]=a[j][j];a[j][j]=a[h][j];a[h][j]=a[i][j];a[i][j]=a[i][h];a[i][h]=t}}
s=w=>{a=[...w=[...w]].map(_=>w.map(_=>' '));a[w.length>>1]=w;setInterval(r,1000,a)}
s("windmills")
<pre id=w>

Couldn't you golf away a few bytes by reducing the weight time?

05AB1E, 88 53 bytes
Code:
¹VYg;ïU[2FX¶×DYsJ,YvNð×y¶J?}YvðX×yJ,}Yv¹gN>-ð×yJ,}YRV

Try it online!. Make sure to hit the kill button right after you run it, because it goes into an infinite loop.

That was savage.

Ruby, 122119 bytes
->n{c=0
loop{i=[l=n.size,m=l+1,m+1,1][3-c=c+1&7]*(3.5<=>c)
s=(' '*l+$/)*l
l.times{|j|s[m*l/2-1+(j-l/2)*i]=n[j]}
$><<s}}

Ungolfed version with sleep, in test program
The rotation isn't very convincing at full console height. But if you reduce the height to the the length of the input string, the rotation is a lot more convincing.
f=->n{
  c=0                                     #loop counter
  m=1+l=n.size                            #l=string length. m=l+1
  loop{                                   #start infinite loop
    s=(' '*l+$/)*l                        #make a string of l newline-terminated lines of l spaces. Total m characters per line.
    i=[m-1,m,m+1,1][3-c=c+1&7]*(3.5<=>c)  #array contains positive distance between characters in string 1=horizontal, m=vertical, etc.
                                          #c=c+1&7 cycles through 0..7. Array index 3..-4 (negative indices count from end of array, so 3=-1, 0=-4 etc)
                                          #(3.5<=>c) = 1 or -1. We use to flip the sign. This is shorter than simply using 8 element array [m-1,m,m+1,1,1-m,-m,-m+1,-1]
    l.times{|j|s[m*l/2-1+i*(j-l/2)]=n[j]} #for each character in n, write the appropriate space character in s to the character in n
    puts s                                #print s
    sleep 1                               #sleep for 1 second
  }
}

f[gets.chomp]                             #get input, remove newline, call function

MATL, 47 44 bytes
' 'jntX"tGtnXyg(wGtnQ2/Y(XJDXKD`J@_X!DK3X!DT

Try it online! (but kill it immediately, infinite loop)
With 1-second pause: 56 bytes
' 'jntX"tGtnXyg(wGtnQ2/Y(XJD1Y.XKD1Y.`J@_X!D1Y.K3X!D1Y.T

Try it online! (again, infinite loop)

Python 3, 193 bytes

def c(a):e=' ';s=len(a);l=int(s/2);b=range(s);m='\n'*l;print(m,a,m);for x in b:print(e*x,a[x]);for x in b:print(e*l,a[x]);for x in b:print(e*(s-1-x),a[x]); a=input();while True:c(a);c(a[::-1]);

Ungolfed

def c(a):
    e=' ';s=len(a);l=int(s/2);b=range(s);m='\n'*l;
    print(m,a,m);
    for x in b:print(e*x,a[x]);
    for x in b:print(e*l,a[x]);
    for x in b:print(e*(s-1-x),a[x]);
a=input();
while True:
    c(a);
    c(a[::-1]);

Recursive, 177 bytes
(crash after a few seconds)

def c(a):e=' ';s=len(a);l=int(s/2);b=range(s);m='\n'*l;print(m,a,m);for x in b:print(e*x,a[x]);for x in b:print(e*l,a[x]);for x in b:print(e*(s-1-x),a[x]);c(a[::-1]);c(input());

Ungolfed

def c(a):
    e=' ';s=len(a);l=int(s/2);b=range(s);m='\n'*l;
    print(m,a,m);
    for x in b:print(e*x,a[x]);
    for x in b:print(e*l,a[x]);
    for x in b:print(e*(s-1-x),a[x]);
    c(a[::-1])
c(input());

Another solution, 268 bytes

import itertools as i;def w(a):e=' ';s=len(a);l=int(s/2);t='\n';m=(l-1)*t;h=list(i.chain.from_iterable((e*x+a[x],e*l+a[x],e*(s-1-x)+a[x]) for x in range(s)));print(m,a,m,t.join(h[::3]),t.join(h[1::3]),t.join(h[2::3]),sep=t,end='');a=input();while True:w(a);w(a[::-1]);

Ungolfed

import itertools as i;
def w(a):
    e=' ';s=len(a);l=int(s/2);t='\n';m=(l-1)*t;
    h=list(i.chain.from_iterable((e*x+a[x],e*l+a[x],e*(s-1-x)+a[x]) for x in range(s)))
    print(m,a,m,t.join(h[::3]),t.join(h[1::3]),t.join(h[2::3]),sep=t,end='');
a=input();
while True:
    w(a);
    w(a[::-1]);

Can I borrow this?

By the way, welcome to PPCG!

Also, you forgot to reverse the string at the end (first-level-indentation).

This output is invalid. Steps one and five are missing leading whitespace.

changed! @MyHamDJ

Pyth, 48 bytes
JlzK/J2#*btKz*btKM+*dG@zHVJgNN)VJgKN)VJg-JNN)=_z

Try it online! (Note: this is a version that does not forever loop, because it would crash the interpreter.)
Shamelessly translated from the Python 3 solution by @ByHH.
How it works:
JlzK/J2#*btKz*btKM+*dG@zHVJgNN)VJgKN)VJg-JNN)=_z
                                                 assign('z',input())
Jlz                                              assign("J",Plen(z))
   K/J2                                          assign("K",div(J,2))
       #                                         loop-until-error:
        *btK                                      imp_print(times(b,tail(K)))
            z                                     imp_print(z)
             *btK                                 imp_print(times(b,tail(K)))
                                                  @memoized
                 M                                def gte(G,H):
                  +*dG@zH                          return plus(times(d,G),lookup(z,H))
                         VJ   )                   for N in num_to_range(J):
                           gNN                     imp_print(gte(N,N))
                               VJ   )             for N in num_to_range(J):
                                 gKN               imp_print(gte(K,N))
                                     VJ     )     for N in num_to_range(J):
                                       g-JNN       imp_print(gte(minus(J,N),N))
                                             =_z  assign('z',neg(z))

This output is invalid. Steps one and five are missing leading whitespace.

Is it ok now???

Yep that looks great. ;)


text:
Optimal solution to go to opposite corner of a rectangle
Your job is to write a program that finds the optimal number of moves it takes to get from the lower-left corner of a rectangle to the upper-right corner directly opposite.
Your program will accept input as an ordered pair (width, height). These will be the dimensions of the rectangle you will work with. Your program will create an ASCII-art of the solution (use . for empty square and # for part of the solution, X for starting square) and count the number of moves it takes to reach the endpoint. Diagonal moves are not allowed. If there are multiple solutions, choose one to output.
The shortest program in bytes wins.
Example
Input: (4, 5)
Output:
..##
..#.
.##.
.#..
X#..

Move count: 7

So should the output contain the number of # in "the optimal solution" (which is any solution that never moves left or down) as well?

Re "Sorry, this is my first code-golf question so I'm not very good at making these." Let me recommend the sandbox where you can post challenge ideas and receive feedback before posting them on main. And welcome to PPCG! :)

@MartinBüttner Yes, the move count is essentially the number of # because it's illogical to go left or down.

Is it ok to separate each char with spaces?

Do we have to output the move count AND the ascii art? How exactly should the output look like?

Nice easy question to practice string repetition or nested for loop :)

05AB1E, 27 24 bytes
Code:
+Í,¹<'.×'#¶J²<×'X'#¹<×J,

Explanation:
+                         # Add the length and the height.
 Í                        # Decrease by two.
  ,                       # Print this value with a newline.
   ¹<'.×                  # Take the first input, decrease by 1 and multiply with ".".
        '#¶               # Push a "#"-character and a newline character.
           J              # Join the string.
            ²<            # Take the second input and decrease by 1.
              ×           # Multiply the joined string with this value.
               'X         # Push the "X"-character.
                 '#¹<×J   # Multiply the "#"-character with (first input - 1).
                       ,  # Pop and print with a newline.

Try it online!. Uses CP-1252 encoding.

What is the difference between a byte and a character?

@KennyLau I keep forgetting to mention that in my posts... 05AB1E uses CP-1252 encoding, each character used in the code here is 1 byte.

Retina, 54 53 bytes
\d+
$*.
S_`(?<=(.+)¶.*).|\D
T`.`#`.¶|.*$
:m-1=`^#
X
#

Takes input separated by a linefeed and outputs the solution grid followed by the move count.
Try it online!
Explanation
\d+
$*.

Turn both integers into that many .s, i.e. convert them to unary.
S_`(?<=(.+)¶.*).|\D

This builds a grid of .s, by matching each . in the unary height and capturing the unary representation of the width. The S activates split mode which returns the captured strings, and the |\D and _ together ensure that everything else is removed from the string.
T`.`#`.¶|.*$

This turns the last character of each line as well as the entire last line into #s.
:m-1=`^#
X

This uses a ton of options to convert only the first # on the last row to X (we need to make sure that only the last row is affected because of width-1 inputs). m activates multi-line mode which makes ^ match the beginning of lines. -1= tells Retina to perform the substitution only on the last match. Finally, : switches off the default silent mode such that the grid is printed to STDOUT as an intermediate result.
#

Finally, we simply count the number # in the string, which corresponds to the number of moves.

Maybe a built in should be added to retina for converting to unary.

Pyke, 26 bytes
DtQ+RtF; Q\.*t\#+)\X\#Qt*+

Try it here

Or a noncompetitive 34 bytes, add apply node with an ast)
jUa]Dm!X|RZjht]q+".#X"R@)Fs
);jmts

Try it here!
Or 30 bytes if allowed spaces as padding
jUa]Dm!X|RZjht]q+".#X"R@)Pjmts

Why is it non-competitive?

I changed the language after the challenge was posted

@muddyfish Internal server error when you click try it here

@Insane fixed the bug (hopefully) The internal test for time was failing whenever the day changed.

Pyth, 32 29 24 bytes
AtMQVH+*\.G\#;+\X*\#G+GH

Try it online!
Sample input:
(4, 5)

Sample output:
...#
...#
...#
...#
X###
7

How it works:
AtMQVH+*\.G\#;+\X*\#G+GH
                           assign('Q',eval_input())
AtMQ                       assign('[G,H]',Pmap(lambda d:tail(d),Q))
    VH       ;             for N in range(H):
      +*\.G\#                  implicit_print(plus(times(".",G),"#"))
              +\X*\#G      implicit_print(plus("X",times("#",G)))
                     +GH   implicit_print(plus(G,H))

Previous attempt:
JthQK@Q1+*++*\.J\#btK+\X*\#Jt+JK

Try it online!
Sample input:
(4, 5)

Sample output:
...#
...#
...#
...#
X###
7

How it works:
JthQK@Q1+*++*\.J\#btK+\X*\#Jt+JK
                                 assign('Q',eval_input())        --Q is now an official pair of numbers (4, 5)
JthQ                             assign("J",decrement(first(Q))) --gets the first element, and then take 1 from it, and assign it to J
    K@Q1                         assign("K",lookup(Q,1))         --K is now the second element (count from 0) of the pair.
        +            +\X*\#J     concat(-----------------------------------------------------------,concat("X",times("#",J)))
         *         tK                   repeat(--------------------------------------,decrement(K))
          +       b                            concat(-------------------------,"\n")
           +    \#                                    concat(-------------,"#")
            *\.J                                             repeat(".",J)
                            t+JK decrement(add(J,K)) <--- auto-print

@MartinBüttner Maybe you could help me golf this?

@KennyLau I don't know any Pyth...

@MartinBüttner It's quite embarrassing for Pyth to be defeated, right

You can combine the first two assignments with AtMQ.  This assigns the two values to G and H.

CJam, 35 33 bytes
q~\(_2$(+p'.*a*'#f+)W%_"X#"era+N*

Takes input in the form width height and outputs the move count on the first line, followed by the solution grid.
Test it here.
This also works for the same byte count:
q~\('.*a*'#f+)W%_"X#"era+N*_'#e=p

Haven't seen a CJam solution in a while.

@Cyoce You need to look harder. ;)

Ruby, 48 bytes
This is an anonymous function, which according to this meta post is acceptable unless the question states "full program." I wouldn't normally be pedantic about this but the problem is very simple and doing a program would be a significant % increase to the score.
Input is two arguments. Return value is an array containing the ASCII art string and the number of # in the path.
->w,h{[(?.*(w-=1)+'#
')*(h-=1)+?X+?#*w,w+h]}

In test program
f=->w,h{[(?.*(w-=1)+'#
')*(h-=1)+?X+?#*w,w+h]}

puts f[4,5]

Output
...#
...#
...#
...#
X###
7

It's just a string of h-1 rows of w-1 dots, followed by a # and newline. I put the # at the end in order to use a single #\n literal for both # and newline (the code contains an actual newline rather than an escape sequence.) The final row is then an X followed by w-1 #'s.
It was shorter to decrement the values of w and h during the ASCII art generation, so that the final calculation is simply w+h.

MATL, 28 26 25 bytes
+qq35IMwX"46 5Lt4$(88HG(c

EDIT (June 10, 2016): the link below includes a modification ( 5L is replaced by IL) to adapt to changes in the language
Try it online!
Explanation
+       % take two inputs. Add them
qq      % subtract 2
35      % push ASCII for '#'
IMw     % push the two inputs again. Swap them
X"      % 2D char array of '#'  repeated as indicated by inputs
46      % push ASCII for '.'
5Lt4$(  % fill all but last and row columns with that
88HG(   % fill 88 (ASCII for 'X') at linear index given by second input
c       % convert to char

JavaScript (ES6), 60 bytes
w=>h=>--w+--h+`
${"."[r="repeat"](w)}#`[r](h)+`
X`+"#"[r](w)

Usage
f(4)(5)

7
...#
...#
...#
...#
X###

Java, 137 132 bytes
w->h->{String s="";int i=0,j;for(;i<h;i++){for(j=1;j<w;j++)s+=".";s+="#\n";}s+="X";for(j=1;j<w;j++)s+=".";s+="\n"+(w+h-2);return s;}

Java isn't exactly a joke though...

s+= instead of s=s+ will save you a couple bytes

Scala, 118 bytes
(w:Int,h:Int)=>{print(Array.fill(h-1,w-1)('.')map(new String(_))mkString("","#\n","#\nX"));Seq.fill(w-1)(print("#"))}

(w:Int,h:Int)=>{...}           //define a function with 2 Ints as parameters
print(                        //print ...
  Array.fill(h-1,w-1)('.')    //an array of arrays with dimensions (h-1,w-1)
                              //and fill it with a dot
  map(new String(_))          //map each inner array of chars to a string
  mkString("","#\n","#\nX")   //create a string from the array, with
                              //an empty string before the array,
                              //"#\n" as a seperator between the elements
                              //and "#\nX" at the end
);
Seq.fill(w-1)(print("#"))     //w-1 times print "#"

Haskell, 64 bytes
c!n=c<$[2..n]
w#h=unlines$('.'!w++"#")!h++['X':'#'!w,show$w+h-2]

Usage example:
*Main> putStr $ 4 # 5
...#
...#
...#
...#
X###
7

How it works:
c!n = c <$ [2..n]                       -- helper function: make (n-1) copies of c

                                        -- main function
                     !h                 -- (h-1) times
       ('.'!w ++ "#")                   --    (w-1) dots and a hash sign
                       ++[      ,     ] -- followed by
                          'X' : '#'!w   --    an 'X' and (w-1) hash signs
                            show$w+h-2  --    and the number of steps
unlines                                 -- join everything with newlines in-between

Lua, 81 bytes
Try it online!
Golfed:
w,h=(...)print((("."):rep(w-1).."#\n"):rep(h-1).."X"..("#"):rep(w-1))print(w+h-2)

Ungolfed:
w,h=4,5
print((("."):rep(w-1).."#\n"):rep(h-1).."X"..("#"):rep(w-1))
print(w+h-2)

Python, 48.
lambda w,h:('.'*(w-1)+'#\n')*(h-1)+'X'+'#'*(w-1)

To use it, add f= before the line above and call it like this:
f(4, 5)

Result:
...#
...#
...#
...#
X###


text:
Draw a random hexa-glyph

The above image is called a hexa-glyph.  Hexa-glyphs are some cool patterns I made up while doodling during my DiffEq class.  Here's how you make one:

Consider the following set of points, shaped like a regular hexagram.  The inner hexagon is what will contain the final glyph, while the outer 6 points form a star and are where we will start drawing our lines.

From the outer six points, randomly select a pair.  For efficiency, there should be at least one other point between the two selected points (otherwise, it would have no effect on the final figure).  Then, from each of the two points, cast a ray towards the other.  This ray is blocked by previous lines.

Repeat this process until all 9 edges have been formed, as shown in the next few images.

Here is an example of rays being blocked.  The ends of the ray segment are still visible, but the middle portion is occluded by the first two segments we drew.

These two rays are also "blocked," but this doesn't cause any visible difference because they are blocked by the same other line.

Fast-forwarding until all 9 lines are drawn.  If you want a more detailed explanation of these skipped steps, I can expound.

Finally, remove the points of the star.  To make it look prettier, the thick dots are also removed.

The challenge
You challenge is to output a visual representation of a random hexa-glyph.  This is code-golf, fewest bytes wins.

All possible hexa-glyphs should appear with some positive probability. Different hexa-glyphs are generated by changing the order in which the 9 edges are drawn.
Furthermore, all images output by your program must be valid hexa-glyphs. Certain patterns (like a complete outline of the inner hexagon) cannot possibly appear as a hexa-glyph, and so you program mustn't output these.
The output should be a graphical image (printed to screen or file).
The hexagon must be regular, but can appear in any orientation.
Reflections / rotations are not considered unique.  (This might make requirement 1 easier to follow).

I made up while doodling during my DiffEq class.  The way all great discoveries happen... :P

What are the minimal requirements for the image? To which extent must an ASCII art be recognizable as long as each edge is represented and placed in vaguely the right spot?

@JanDvorak I removed the ASCII art option of the challenge  (like within 2 minutes of posting) because programs that produce ASCII-art and graphical outputs aren't easily comparable.

what about pixel art then? A PPM header isn't too heavy, and afterwards the only difference is using '01' with space interleaved instead of ' *'.

@JanDvorak Output would then be a properly formatted image file, right?  Then I don't see anything wrong with it.

This reminds me of glyph hacking - Ingress, anyone?

My question is, how accurate do I need to be when placing the "lines"? I guess I can't just dump 18 pixels randomly to the top left corner, but can I dump 18 pixels in the approximately right spot and assume the user can read it already?

@JanDvorak Sorry for my late reply.  I'm going to say, that yes, you can form a line by placing 18 pixels in approximately the right spot.

Mathematica, 273 268 264 242 bytes
c=CirclePoints;b@_=k=1>0;Graphics[Line/@Cases[Append[Join@@({c@6,{3^.5/2,-Pi/6}~c~6}),{0,0}][[b@#=!k;#]]&/@TakeWhile[#,t=k;(r=t;t=b@#;r)&]&/@Join@@RandomSample[{#,Reverse@#}&/@Partition[Range@12,3,2,1]~Join~Array[{2#,13,2#+6}&,3]],{_,__}]]

The  renders as a superscript T in Mathematica and is a postfix transpose operator.
Sorting out the bugs in this took forever... towards the end I hacked a few things together to make it work, so this is definitely suboptimal. I also wonder whether it might be better overall to implement the spec more literally via the lines across the outer hexagon and let Mathematica's geometry functions handle the intersections.
Note that this is a full program and if you want to run the code multiple times within a single REPL session you'll have to prefix it with Clear[b].
Here are the results of 20 runs:

Explanation
This solution doesn't make use of the outer star points at all. Instead it works directly with the points that are part of the hexaglyph and lines that cover three of them at a time.
Let's label the points:

1 starts on a slightly weird corner but this is due to the (also somewhat weird) default behaviour of CirclePoints. Starting the hexagon from there turned out cheapest.
Now we want to find the relevant lines through three of those points which correspond to connected points of the outer star. The ones around the hexagon are of course just 3 adjacent points (modulo 12), starting from an odd number. The ones across the centre consist of an even number n, 13 and n+6.
Representations of these lines (in the form of lists of three points are generated by the following code):
Partition[Range@12,3,2,1]~Join~Array[{2#,13,2#+6}&,3]

The Partition generates the lines around the hexagon and the Array the lines through the centre. To process both beams, we map this function over the list of lines:
{#,Reverse@#}&

Now we shuffle these with RandomSample to process them in a random order. Join @@ flattens the list of pairs so that we have a list of beams.
Short intermission: to keep track of which points are already blocked we use a lookup function b, which is initialised to True for all values by b@_=k=1>0;. When processing a beam we keep all points until the first point that has b[n] == False (including that one):
TakeWhile[#,t=k;(r=t;t=b@#;r)&]&

I feel like this is the most golfable part right now... the use of two temporary variables to play Mastermind seems really expensive. Anyway, the result of this gives us the points in a line we're allowed to draw. Now this function is mapped over each of those points:
Append[Join@@({c@6,{3^.5/2,-Pi/6}~c~6}),{0,0}][[b@#=!k;#]]&

The first part generates the list of all 13 points using the interleaved results of two calls to CirclePoints (with different radii for the edge centres and the corners of the hexagon). Note the b@#=!k which now sets the lookup table's value for the current point to False so that no further beam can pass through it. Finally, the value is used as an index into the list of coordinates to get the correct 2D point.
Cases[...,{_,__}]

This discards all single-element lists, because they would render as individual (and visible) points. Finally we render the result:
Graphics[Line/@...]

b@_=1>0=b=1>0&

@CatsAreFluffy I don't think that works, because I need to be able to overwrite individual values later on.

Nice use of CirclePoints.

I appreciated that Youtube link.

Shoes (Ruby) Rev C 184 bytes
12 bytes saved by transferring responsibility for checking if a particular half-line should be drawn from the main program to the drawing method. The main program still has to check if the whole line is completely blocked, though.
Shoes.app{t=[]
d=->p,q{t[p]&&t[q]||line(p/6*8,p%6*14,q/6*8,q%6*14)}
%w{1I IW WM M5 5' '1 =A P. R,}.shuffle.map{|i|b=i.sum/2
c=b*2-a=i.ord
t[a]&&t[c]||(d[a,b]
d[b,c]
t[a]=t[b]=t[c]=1)}}

Shoes (Ruby) 205 ... Rev B 196  bytes
Shoes is a ruby-based tool for building GUI's etc. It's the first time I've used it. mothereff.in/byte-counter counts my submission as 196 bytes, but for some reason Shoes counts it as 202.
Also, Ruby lets you do things like t[a=i.ord] but strangely, it seems not to work as expected with Shoes.
Shoes.app{t=[]
d=->p,q{line(p/6*8,p%6*14,q/6*8,q%6*14)}
%w{1I IW WM M5 5' '1 =A P. R,}.shuffle.map{|i|b=i.sum/2
c=b*2-a=i.ord
t[a]&&t[c]||(t[a]&&t[b]||d[a,b]
t[b]&&t[c]||d[b,c]
t[a]=t[b]=t[c]=1)}}

Explanation
I don't consider the parts of the line outside the hexagon. I only draw the part that needs to be drawn. The important thing is whether the lines cross the intersections (If we only draw the parts that need to be drawn, this means they begin / end at the intersections.)
The basic rule is that if both endpoints of a line have been visited, the line is blocked and should not be drawn. As the lines are drawn in two halves, we also have to check if the midpoint has been visited to see if each half should be drawn or not.
I keep track of which points have been visited in the array t[]. This ends up containing an entry for each physical coordinate on the grid below. There is no separate 13-element logical array. By the end, t[] may have 87 elements, though only up to 13 will contain useful data.
Internally, the coordinates of the endpoints of the lines are given by a single number z, where z%6 is the y coordinate and z/6 is the x coordinate. In this system the hexagon is flattened. When the lines are plotted, the x scale is multiplied by 8 and the y scale is multiplied by 14, which is a very close rational approximation to the correct ratio: 14/8=1.75 vs sqrt(3)=1.732.
The internal coordinate system is shown below, with a few sample outputs.

Ungolfed
Shoes.app{
  t=[]                                          #Empty array for status tracking
  d=->p,q{line(p/6*8,p%6*14,q/6*8,q%6*14)}      #Drawing method. Convert p and q into x,y pairs, scale and draw line.
  %w{1I IW WM M5 5' '1 =A P. R,}.shuffle.map{|i|#take an array of the coordinates of the endpoints of each line, shuffle, then for each line
    b=i.sum/2                                   #b = midpoint of line, convert ASCII sum to number (average of the two coordinates)
    a=i.ord                                     #a = first endpoint of line, convert ASCII to number (no need to write i[0].ord)
    c=b*2-a                                     #c = second endpoint of line (calculating is shorter than writing i[1].ord)
    t[a]&&t[c]||(                               #if both endpoints have already been visited, line is completely blocked, do nothing. ELSE
      t[a]&&t[b]||d[a,b]                        #if first endpoint and midpoint have not both been visited, draw first half of line
      t[b]&&t[c]||d[b,c]                        #if second endpoint and midpoint have not both been visited, draw second half of line
      t[a]=t[b]=t[c]=1                          #mark all three points of the line as visited
    )
  }
}

More Sample outputs
These were done with an older version of the program. The only difference is that the positioning of the hexaglyph in the window is now slightly different.

mothereff.in/byte-counter counts my submission as 196 bytes, but for some reason Shoes counts it as 202. I don't 100% know if this is true, but I think that the reason that Shoes counted your code as 202 bytes instead of 196 is because your newlines are actually a two character sequence "\r\n." This makes every newline get counted twice. Here is a stack overflow answer regarding \r and \n.

Hehe I can't get over the name Ruby with Shoes XD

Python, 604 591 574 561 538 531 536 534 528 493 483 452 431 420 419 415 388 385 384 bytes
I have adapted Level River St's idea of checking if a line will be blocked by checking if both endpoints of the line have already been visited before. This saves 27 bytes. Golfing suggestions welcome.
Edit: Bug fixing and golfing g(p,q) for 3 bytes. Golfed L for one byte.
from turtle import*
from random import*
R=range
G=goto
*L,=R(9)
shuffle(L)
a=[0]*13
ht()
T=12
c=[(j.imag,j.real)for j in(1j**(i/3)*T*.75**(i%2/2)for i in R(T))]+[(0,0)]
def g(p,q):pu();G(c[p]);a[p]*a[q]or pd();G(c[q])
for m in L:
 p=2*m;x,y,z=R(p,p+3)
 if m<6:
  if a[x]*a[z%T]<1:g(x,y);g(y,z%T);a[x]=a[y]=a[z%T]=1
 else:
  if a[p-11]*a[p-5]<1:g(p-11,T);g(p-5,T);a[p-11]=a[p-5]=a[T]=1

Ungolfing:
from turtle import*
from random import*

def draw_line(points, p_1, p_2):
    penup()
    goto(points[p_1])
    if not (a[p] and a[q]):
        pendown()
    goto(points[p_2])

def draw_glyph():
    ht()
    nine_lines = list(range(9))
    shuffle(nine_lines)
    size = 12
    center = [0,0]

    points = []
    for i in range(12):      # put in a point of a dodecagon
                             # if i is even, keep as hexagon point
                             # else, convert to hexagon midpoint
        d = 1j**(i/3) * 12   # dodecagon point
        if i%2:
            d *= .75**.5     # divide by sqrt(3/4) to get midpoint
        points += (d.imag, d.real)
    points.append(center)

    a = [0]*13
    for m in nine_lines:
        p = 2*m
        if m<6:
            x, y, z = p, p+1, p+2
            if not (a[x] and a[z%12]):
                draw_line(points, x, y)
                draw_line(points, y, z%12)
                a[x] = a[y] = a[z%12] = 1
        else:
            if not (a[p-11] and a[p-5]):
                draw_line(p-11, 12)
                draw_line(p-5, 12)
                a[p-11] = a[p-5] = a[12] = 1

The hexa-glyphs themselves are quite small as we use a 12-pixel hexagon as a base (for golfing reasons). Here are some example hexa-glyphs (apologies for the poor cropping):

Could save a few bytes: R=range;G=goto


text:
Validate a Wikipedia page name
Wikipedia has several restrictions on an article's title. I summarize them here:

It may not be empty.
It may not begin with a lowercase letter. A character is considered lowercase if it has an Ll after its name in UnicodeData.txt.
It may not contain any of the characters: # < > [ ] | { } _
It may not be . or ..
It may not begin with ./ or ../.
It may not contain /./ or /../.
It may not end with /. or /...
It may not contain any space character (a character is considered a space if it has Zs after its name in UnicodeData.txt) except for U+0020 SPACE.
It may not contain more than one consecutive space.
It may not consist entirely of spaces.
It may not begin with a colon.
It may not begin with the language prefix of any of the 292 language editions of Wikipedia followed by a colon. This includes en: for English.
It may not begin with the prefix of another Wikimedia Foundation project or its shortcut followed by a colon.
It may not contain the character % followed by two hexadecimal digits.
It may not contain a named HTML character entity. Numbered entities are already forbidden through #.
It must contain no more than 256 bytes when encoded in UTF-8.

Write a function that takes in a string (or whatever data type your language normally uses to manipulate text) and outputs a boolean indicating whether the string is a valid Wikipedia article title. You are permitted to use networking libraries to download and read from any page that I linked in this question.

true/false or yes/no? The latter will save me some bytes :p

This question needs a lot of work: it contains multiple links to required external data which is likely to change, and has several unclear requirements.

For the second condition, is the Greek small letter eta (η) allowed?

@feersum Please explain all of what is unclear, so I can fix it. The external data will be referenced by the revision of those pages at the moment I made this question

I am not going to list all that is unclear as there is too much. Here's a few questions to start with: 1. Does may not contain more than one consecutive space or underscore apply to underscore followed by space, or space followed by undescore? 2. What counts as an HTML entity? Only a finite list of them, any characters between & and #, or ... ? 3. No reference is given for which Unicode characters count as spaces or lowercase letters.

@feersum All those problems have been fixed.

This is extremely far from self-contained. Please avoid external links in challenges.

Retina, 1221 bytes
^(?=...:|\w|(^|.*/)\.\.?(/.*|$)|.*([#<>\[\]|{}]|  |__|%[0-9a-fA-F]{2}|&#(\d{4}|[0-9a-fA-F]{4}|a(mp|pos)|(l|g|quo)t);|~~~)|[ _]*$|.{257,}).*
no
^(?!no$).+
yes

where ... is:
(w(ik(i(s(pecies|ource)|v(ersity|oyage)|([mp]edi|dat)a|(book|new)s|quote|tech)|t(ionary)?)|m(i[dlnt]|c[ahz]|a[ru]|b[de]|d[ek]|h[ku]|n[lo]|r[su]|u[ak]|fi?|mk|pl|se|tw)|ar?|uu|o)?|m(e(dia(wikiwiki|zilla)|t(awikipedi)?a)|a(p-bms|i)|[klnr]|[ghi]|[iz]n|[st]|yv?|df|hr|rj|us|wl)|s([degh]|t(rategy|q)|i(mple)?|[klmnoqr]|c(n?|o)|pecies|[uvw]|[st]|ah?|rn|zl)|b(a(t-smg|r?)|ug(zilla)?|e-tarask|[eghi]|[mno]|[rs]|cl|jn|py|xr)|t([aghw]|e(stwiki|t)?|[iklno]|oollabs|[rst]|yv?|pi|um)|c(o(mmons)?|h[ory]?|[es]b?|bk-zam|[uvy]|rh?|do|kb|a)|p(habricator|a[gmp]?|n[bt]|[st]|f?l|ih?|cd|dc|ms)|n(ds(-nl)?|[glno]|a[hp]?|[vy]|ew?|ov|rm|so)|a([afkm]|r[cz]?|[vyz]|ng?|st?|z?b|ce|dy|ls)|k([gijklmnor]|[uvwy]|a[ab]?|sh?|bd|oi|rc)|z(h(-(classical|min-nan|yue))?|e?a|u)|f([afijory]|oundation|iu-vro|r[pr]|ur)|l([gi]|[no]|ad?|be?|tg?|ez|ij|mo|rc|v)|r([nw]|o(a-(tara|rup))?|my?|ue?)|g(a[gn]?|[dln]|o[mt]|[uv]|lk)|h([eiortu]|a[kw]?|[yz]|if|sb)|i([adegikostu]|ncubator|lo)|v(e(c?|p)|oy?|ls|i)|d([vz]|[ae]|iq|sb)|e([elnostu]|ml|xt)|u([gz]|[kr]|dm)|j([av]|bo)|x(al|mf|h)|[nbqsvcdm]|o[cmrs]|y[io]|qu|)

(I used this regex optimizer and manutally typed in all the data)
Try it online without the ...!

Does this test for all the lowercase letters? There are a lot more than 26 of them, there are 1984 of them according to that file.


text:
The Arithmetic Derivative
The derivative of a function is a cornerstone of mathematics, engineering, physics, biology, chemistry, and a large number of other sciences as well. Today we're going to be calculating something only tangentially related: the arithmetic derivative.
Definition
The arithmetic derivative a(n) or n' is defined here (A003415) by a number of properties that are similar to the derivative of a function.

a(0) = a(1) = 0,
a(p) = 1, where p is any prime, and
a(mn) = m*a(n) + n*a(m).

The third rule is based on the product rule for differentiation of functions: for functions f(x) and g(x), (fg)' = f'g + fg'. So with numbers, (ab)' = a'b + ab'.
Also of note, since the arithmetic derivative can be extended to the negative numbers via this simple relation, a(-n) = -a(n), the input may be negative.
Rules

Write a program or function that, given any integer n, returns the arithmetic derivative of n.
Inputs will be -230 < n < 230, to avoid problems with integer sizes and numbers too large to factor in a reasonable amount of time. Your algorithm should still be able to theoretically calculate the arithmetic derivative of numbers outside this range.
Built-ins for symbolic math, prime factorization and differentiation are allowed.

Examples
> a(1)
0
> a(7)
1
> a(14)   # a(7)*2 + a(2)*7 = 1*2 + 1*7 = 9
9
> a(-5)   # a(-5) = -a(5) = -1
-1
> a(8)    # a(8) = a(2**3) = 3*2**2 = 12
12
> a(225)  # a(225) = a(9)*25 + a(25)*9 = 6*25 + 10*9 = 150 + 90 = 240
240
> a(299792458)  # a(299792458) = a(2)*149896229 + a(7)*42827494 + a(73)*4106746 + a(293339)*1022 = 1*149896229 + 1*42827494 + 1*4106746 + 1*1022 = 149896229 + 42827494 + 4106746 + 1022 = 196831491
196831491

As always, if the problem is unclear, please let me know. Good luck and good golfing!

What, exactly, is prime in a(prime)?  Is it just a prime number?

Also, I don't get how you decomposed the last example.

@Stackstuck Yes, it's any prime. I've edited for clarity. Also, I added to the last example to hopefully make it clearer.

MATL, 12 bytes
|1>?GtYf/s}0

Try it online!
Explanation
Consider an integer a with |a|>1, and let the (possibly repeated) prime factors of |a| be f1, ..., fn. Then the desired result is a·(1/f1 + ... + 1/fn).
|1>     % take input's absolute value. Is it greater than 1?
?       % if so:
  Gt    %   push input twice
  Yf    %   prime factors. For negative input uses its absolute value
  /     %   divide element-wise
  s     %   sum of the array
}       % else:
  0     %   push 0

Isn't the sum of the prime factors of 1 equal to 0? Or doesn't that work in MATL?

@wythagoras Actually 1 gives 1 as its "prime" number decomposition. It's a strange result (an empty array would be more meaningful). But that's how Matlab works. And also CJam. So I guess there must be good reason to output 1 in that case? What do you think? I've been tempted to redefine the Yf function to output an empty array for 1, but I wasn't sure

Pyth gives an empty array, fwiw.

@isaacg Thanks! Maybe I'll change that

Same in Mathematica (was almost a problem once)

Python, 59 bytes
f=lambda n,p=2:+(n*n>1)and(n%p and f(n,p+1)or p*f(n/p)+n/p)

A recursive function. On large inputs, it runs out of stack depth on typical systems unless you run it with something like Stackless Python.
The recursive definition is implemented directly, counting up to search for candidate prime factors. Since f(prime)=1, if n has a prime p as a factor, we have f(n) == p*f(n/p)+n/p.

Don't you need input and print? At least when I run this (Python 2), I get no result.

@wythagoras By default, functions are allowed as an alternative to programs. Also, this challenge says "program or function".

Jelly, 8 7 bytes
-1 byte by @Dennis
ÆfḟṠ³:S

Uses the same formula everyone else does. However, there's a little trick to deal with 0.
o¬AÆfİS×     Main link. Inputs: n
o¬             Logical OR of n with its logical NOT
               That is, 0 goes to 1 and everything else goes to itself.
  A            Then take the absolute value
   Æf          get its list of prime factors
     İ         divide 1 by those
      S        sum
       ×       and multiply by the input.

Try it here.

Can you please add an explanation? I like answers to have explanations before I upvote them.

@Sherlock9 Done.

I see that your answer has been golfed and the explanation is now out-of-date. Would you please fix that? Thanks :D

Python 2, 87 78 76 74 bytes
a=b=input()
d=2
s=0
while d<=abs(b):
    if a%d==0:
        a=a/d
        s+=b/d
    else:
        d+=1
print s

Improvements thanks to @Maltysen:
a=b=input()
d=2
s=0
while d<=abs(b):
    if a%d==0:a/=d;s+=b/d
    else:d+=1
print s

Further improvement by two bytes:
a=b=input()
d=2
s=0
while abs(a)>1:
    if a%d<1:a/=d;s+=b/d
    else:d+=1
print s

Further improvement thanks to @xnor:
a=b=input()
d=2
s=0
while a*a>1:
    if a%d<1:a/=d;s+=b/d
    else:d+=1
print s

Explanation
The arithmetic derivative of a is equal to a times the sum of the reciprocals of the prime factors of a. No exception for 1 is needed since the sum of the reciprocals of the prime factors of 1 is zero.

abs(a)>1 can be a*a>1.

@xnor Yes, thank you.

Replace line 2 with d,s = 2,0

@AgnishomChattopadhyay Both are 8 bytes in total.

J, 30 27 19 chars
Thanks to @Dennis for chopping off 3 characters.
Thanks to @Zgarb for chopping off 8 characters.
0:`(*[:+/%@q:@|)@.*

Try it online!
Sample input:
0:`(*[:+/%@q:@|)@.* _8
_12

0:`(*[:+/%@q:@|)@.* 0
0

0:`(*[:+/%@q:@|)@.* 8
12

How it works:
0:`(*[:+/%@q:@|)@.* N
XX`YYYYYYYYYYYYY@.Z   if Z then Y else X end
0:                        X:  return 0
                  Z       Z:  signum(N)
   (*[:+/%@q:@|)          Y:  N*add_all(reciprocal_all(all_prime_factors(abs(N))))
                              N
    *                          *
      [:+/                      add_all(                                         )
          %@                            reciprocal_all(                         )
            q:@                                       all_prime_factors(      )
               |                                                        abs( )
                                                                            N

Haskell, 203 90 bytes
Thanks @nimi!
I still have no idea when what indentations cause what interpretation, this is the shortest I managed so far, and as always, I'm sure it can be golfed a lot more. I'm going to try again in the evening.
n#(x:_)|y<-div n x=x*a y+y*a x;_#_=1
a n|n<0= -a(-n)|n<2=0|1<2=n#[i|i<-[2..n-1],mod n i<1]

Thank you very much, teacher=)  I can always learn so much whenever you help me out here! Feel free to add your version as your own answer!

Pyth - 10 8 bytes
Lovin' the implicit input! Should bring it on par with Jelly for most things (Except Dennis' golfing skills).
*scL1P.a

Test Suite.
*             Times the input, implicitly (This also adds the sign back in)
 s            Sum
  cL1         Reciprocal mapped over lit
   P          Prime factorization
    .a        Absolute value of input, implicitly

Haskell, 59 bytes
n%p|n*n<2=0|mod n p>0=n%(p+1)|r<-div n p=r+p*r%2
(%2)

Implements the recursive definition directly, with an auxiliary variable p that counts up to search for potential prime factors, starting from 2. The last line is the main function, which plugs p=2 to the binary function defined in the first line.
The function checks each case in turn:

If n*n<2, then n is one of -1,0,1, and the result is 0.
If n is not a multiple of p, then increment p and continue.
Otherwise, express n=p*r, and by the "derivative" property, the result is r*a(p)+p*a(r), which simplifies to r+p*a(r) because p is prime.

The last case saves bytes by binding r in a guard, which also avoids the 1>0 for the boilerplate otherwise. If r could be bound earlier, the second condition mod n p>0 could be checked as r*p==n, which is 3 bytes shorter, but I don't see how to do that.

APL (Dyalog Extended), 13 9 bytes
A simple solution. The Dyalog Unicode version was simply a longer version of this so it has been omitted.
Edit: Saved 4 bytes by adopting the method in lirtosiast's Jelly solution.
{+/⍵÷⍭|⍵}

Try it online!
Ungolfing
{+/⍵÷⍭|⍵}

{        }  A dfn, a function in {} brackets.
     ⍭|⍵   The prime factors of the absolute value of our input.
   ⍵÷      Then divide our input by the above array,
            giving us a list of products for the product rule.
 +/         We sum the above numbers, giving us our arithmetic derivative.

Japt -x, 16 13 10 bytes
ÒU©a k £/X

- 6 bytes thanks to @Shaggy
Try it online!

Both fail for negative numbers because, for some reason, N.k() doesn't work on them.

Here's a fix, with some golfing.

Or -2 more byes with the -x flag.

Knocked another byte off

@Shaggy Thanks, nice

11 bytes

(Or 10, with -x)

@Shaggy Ah, nice, still learning! :) Forgot about flags and the fact that summing can take a function, as with many other functions in japt

Julia, 72 43 bytes
n->n^2>1?sum(p->n÷/(p...),factor(n^2))/2:0

This is an anonymous function that accepts an integer and returns a float. To call it, assign it to a variable.
For an input integer n, if n2 ≤ 1 return 0. Otherwise obtain the prime factorization of n2 as a Dict, then for each prime/exponent pair, divide the prime by its exponent, then divide n by the result. This is just computing n x / p, where p is the prime factor and x is its exponent, which is the same as summing n / p, x times. We sum the resulting array and divide that by 2, since we've summed twice as much as we need. That's due to the fact that we're factoring n2 rather than n. (Doing that is a byte shorter than factoring |n|.)
Saved 29 bytes thanks to Dennis!

Seriously, 17 14 11 12 bytes
My first ever Seriously answer. This answer is based on Luis Mendo's MATL answer and the idea that the arithmetic derivative of a number m is equal to m·(1/p1 + 1/p2 + ... + 1/pn) where p1...pn is every prime factor of n to multiplicity. My addition is to note that, if m = p1e1·p2e2·...·pnen, then a(m) = m·(e1/p1 + e2/p2 + ... + en/pn). Thanks to Mego for golfing and bug fixing help. Try it online!
,;w`i@/`MΣ*l

Ungolfing:
,             get a single input
 ;w           duplicate input and get prime factorization, p_f
               for input [-1..1], this returns [] and is dealt with at the end
   `   `M     map the function inside `` to p_f
    i         pop all elements of p_f[i], the prime and the exponent, to the stack
     @        rotate so that the exponent is at the top of the stack
      /       divide the exponent by the prime
         Σ    sum it all together
          *   multiply this sum with the input
           l  map and multiply do not affect an empty list, so we just take the length, 0
               l is a no-op for a number, so the result is unchanged for all other inputs

Ruby, 87 66 80 75 70 68 bytes
This answer is based on Luis Mendo's MATL answer, wythagoras's Python answer, and the idea that the arithmetic derivative of a number m is equal to m·(1/p1 + 1/p2 + ... + 1/pn) where p1...pn is every prime factor of n to multiplicity.
->n{s=0;(2...m=n.abs).map{|d|(m/=d;s+=n/d)while m%d<1};m<2?0:s+0**s}

This function is called in the following way:
> a=->n{s=0;(2...m=n.abs).map{|d|(m/=d;s+=n/d)while m%d<1};m<2?0:s+0**s}
> a[299792458]
196831491

Ungolfing:
def a(n)
  s = 0
  m = n.abs
  (2...m).each do |z|
    while m%d == 0
      m /= d
      s += n / d
    end
  end
  if s == 0
    if n > 1
      s += 1 # if s is 0, either n is prime and the while loop added nothing, so add 1
             # or n.abs < 2, so return 0 anyway
             # 0**s is used in the code because it returns 1 if s == 0 and 0 for all other s
    end
  end
  return s
end

Mathematica 10.0, 39 bytes
Tr[If[#>1,#2/#,0]&@@@FactorInteger@#]#&

Can you please add an explanation? I like answers to have explanations before I upvote them.

@Sherlock9 This is a quite uninteresting answer so I don't plan to add one. It's OK if no one upvotes it.

Alright, then. Have a good day :)

In the current Mathematica version, FactorInteger@1 yields {1,1}, so the If function is no longer necessary, saving 10 bytes.

@GregMartin Seriously? That's even more inconsistent than the value, {{1,1}}, returned by my version ({} is the expected result to me).

Sorry, I meant {{1,1}}. Mathematically {} makes more sense, of course ... but I admit that {{1,1}} makes coding a little easier. And FactorInteger[-1] returns {{-1,1}} (maybe that's not a change).

@GregMartin I don't understand how an inconsistent behavior would make coding easier... anyway, {{1,1}} is not a different result than when I wrote this answer, so the If must be there for a good reason.

Jolf, 13 bytes
*jmauΜm)jd/1H

Kudos to the MATL answer for the algorithm! Try it here, or test them all at once. (Outputs [key,out] in an array.)
Explanation
*jmauΜm)jd/1H
*j             input times
      m)j         p.f. of input
     Μ   d/1H      mapped to inverse
    u            sum of
  ma            abs of

APL(NARS), 35 char, 70 bytes
{1≥a←∣⍵:0⋄1=≢k←πa:×⍵⋄c+m×∇c←⍵÷m←↑k}

test and how to use:
  f←{1≥a←∣⍵:0⋄1=≢k←πa:×⍵⋄c+m×∇c←⍵÷m←↑k}
  f 14
9
  f 8
12
  f 225
240
  f ¯5
¯1
  f 299792458
196831491

I thought that it would not be ok because I don't know if c variable is composed (and not a prime)... But seems ok for the test...

05AB1E, 7 4 bytes
ÄÒ÷O

Port of @lirtosiast's Jelly answer.
Try it online or verify all test cases.
Explanation:
Ä     # Take the absolute value of the (implicit) input
 Ò    # Get all its prime factors (with duplicates)
  ÷   # Integer divide the (implicit) input by each of these prime factors
   O  # And take the sum (which is output implicitly)

Pari/GP, 44 bytes
n->n*vecsum([i[2]/p|i<-factor(n)~,0<p=i[1]])

Try it online!

Vyxal s, 3 bytes
ȧǐ/

Try it Online!
ȧ   # Abs. val
 ǐ  # All prime factors
    # (Implicit input)
  / # Divided by each factor.
    # (s flag) sum of stack

-1 thx to Underslash

3 bytes -s If you remove the -r flag, you can get implicit input for the dividing.

@Underslash Thx!

Perl 5, 62 bytes
perl -MMath::Prime::Util=:all -E"map$i+=1/$_,factor abs($j=<>);say$i*$j"

Uses the formula (from OEIS): If n = Product p_i^e_i, a(n) = n * Sum (e_i/p_i).

Perl 6, 90
sub A(\n) {0>n??-A(-n)!!(n>1)*{$_??n/$_*A($_)+$_*A n/$_!!1}(first n%%*,2..^n)};say A slurp

This might be a bit slow for large numbers. Replace 2..^n with 2..n.sqrt for longer code but faster computation.

Ink, 183 bytes
==function a(n)
{n<0:
~return-a(-n)
}
{n<2:
~return 0
}
~temp f=t(n,2)
{f:
~return a(n/f)*f+n/f
}
~return 1
==function t(n,i)
{n>1&&n-i:
{n%i:
~return t(n,i+1)
}
~return i
}
~return 0

Try it online!
I refuse to believe this is a good solution, but I can't see a way to improve it either.

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


text:
Shortest code to secure wipe a disk
Let's write the shortest code to perform a simplified variant of the DoD 5220.22-M Wipe Method with only two writing passes.
Any programming language accepted, but the use of disk-wiping-oriented libraries is prohibited.
Here's how we are to implement it in pseudocode:
Set x to 0

[Start]
'Write Pass
For each sector in disk write the content of x
'Verification Pass
For each sector in disk {
    If sector does not contain the content of x then goto [Start]
}
'Check whether we already did the pass with 1
If x is not 1 then {
    Set x to 1
    GoTo [Start]
}
Else end

In other words, this code will run twice, with a write pass and verification pass for 0, and a write pass and verification pass for 1.
Anyone ballsy enough to implement it code-golf style? ;)

I doubt this will get any answers because of how hard it will be to test.

Good point :-/.

The problem with that link is that there are links on that page to "free" software but said "free" software isn't actually open source

Seriously, what did your SSD do to you to deserve this kind of treatment? Did it kill your entire teddy bear collection or something?

Really want to try and tackle this...also really don't want to sacrifice my HDD to test it.

Try it on a flash drive or something you don't use.

What assumptions, if any, can we make on the interface of the SSD if we are doing this on an FPGA? Can it be a simple SPI flash that is sufficiently fast to operate with single clock cycle turnaround?

It does not matter what drive you do it on, as long as I can use the same generic code and run it on a popular operating system.

I'm voting to close this question as off-topic because this challenge asks for malicious code.

I would argue otherwise. This challenge asks for code that promotes privacy and information security.

The referenced standard is for wiping "real" disks (i.e. ones with discs of magnetic material in them). To securely wipe an SSD (or an SD card) you have to get access to the CPU in the disk itself which controls which sectors are available, because otherwise wear levelling means that you can't guarantee that the writes are covering the full address space.

On Linux, one can set up a file as a disk, partition it, and formats the partitions, and go from there. These utilities do not care if they are accessing block devices or simple files. The same goes for FreeBSD (and I'm certain it is possible in other BSD's and OSX).

x86 machine code (Linux), 116 109 106 bytes
00000000: 89cb 6a02 5999 894c 24f4 b005 cd80 505b  ..j.Y..L$.....P[
00000010: 536a 025a 31c9 b013 cd80 89c6 5b53 9931  Sj.Z1.......[S.1
00000020: c9b0 13cd 8089 f75b 53b2 018d 4c24 f8b0  .......[S...L$..
00000030: 04cd 804e 75f1 5b53 9931 c9b0 13cd 8089  ...Nu.[S.1......
00000040: fe5b 538d 4c24 f4b2 01b0 03cd 804e 740c  .[S.L$.......Nt.
00000050: 8a44 24f8 3844 24f4 74e7 ebb3 89fe b001  .D$.8D$.t.......
00000060: 8644 24f8 3c01 75a7 58c3                 .D$.<.u.X.

Function that takes filename as argument, uses fastcall convention.
Assembly (NASM):
section .text
	global func
func:

	;open file
        mov ebx, ecx	;first argument to func (filename)
	push 0x2	;flag O_RDWR
	pop ecx		;pushing a constant is shorter than mov
	cdq	        ;edx=mode=0
	mov [esp-12], ecx ;set first byte (msg) to write to 0. msg later in esp-8, buf in esp-12
	mov al, 5
	int 0x80	;syscall open
	push eax	;save file descriptor

	write_verify:

	;get file size
	pop ebx		;get fd
	push ebx
	push 0x2	;flag SEEK_END
	pop edx
	xor ecx, ecx 	;offset 0
	mov al, 0x13
	int 0x80	;syscall lseek
	mov esi, eax	;save file byte count in esi

	;reset index of file to 0
	pop ebx		;get fd
	push ebx
	cdq	        ;edx=flag SEEK_SET=0
	xor ecx, ecx	;ecx=0
	mov al, 0x13
	int 0x80	;syscall lseek

	;***write pass***
	mov edi, esi
	write_loop:	;for each byte in byte count, write [msg]
		;write to file
		pop ebx		;file descriptor
		push ebx
		mov dl, 1	;bytes to write
		lea ecx, [esp-8] ;buffer to write from
		mov al, 4
		int 0x80	;syscall write
		dec esi		;decrement (byte count) to 0
		jne write_loop	;while esi!=0, loop

	;reset index of file to 0
	pop ebx		;get fd
	push ebx
	cdq 	        ;edx=SEEK_SET=0
	xor ecx, ecx	;ecx=0
	mov al, 0x13
	int 0x80	;syscall lseek

	;***verification pass***
	mov esi, edi
	verify_loop:	;for each byte in byte count, verify written byte
		pop ebx		;get fd
		push ebx
		lea ecx, [esp-12] ;buffer to store read byte
		mov dl, 1	;read 1 byte
		mov al, 3
		int 0x80	;syscall read
		dec esi
		je end_verify	;at final byte, end verification
		mov al, [esp-8]
		cmp byte [esp-12],al
		je verify_loop	 ;loop if expected value found
		jmp write_verify ;if byte!=expected value, restart

	end_verify:
	mov esi, edi
	mov al, 1
	xchg byte [esp-8],al	;set new byte to write to 1
	cmp al, 1
	jne write_verify	;if old byte to write!=1, goto start

	pop eax			;reset stack
	ret

Try it online!
-7 bytes and -3 bytes thanks to @EasyasPi

-7 bytes using cdq and removing manual zero checks after dec

-3 bytes: mov al, [esp-8]; mov byte[esp-8], 1 to mov al, 1; xchg byte[esp-8], al

On a linux system there's no need for special handling of devices. Just use the device file interface.
Python 3 (byte strings) - 141 bytes
d=input()
f=open(d,'r+b')
z=f.seek
z(0,2)
s=f.tell()
i=0
while i<2:
 z(0);f.write([b'\0',b'\xff'][i]*s);f.flush();z(0)
 if f.read()==x:i+=1

It's fairly straightforward, and not really optimised heavily, but it works. Here's a basic rundown.

Get input (device file path)
Open device file
Seek to the end, get filesize (block devices are always their real size)
enter write-and-check loop
construct 0-bit and 1-bit strings (x)
write bitstring
flush output (I could have set buffering=0 but this is shorter)
test file against x, and increment step of loop if it passes

exit loop when the increment is high enough
As a bonus, you could modify this for any set and number of byte-modification patterns, like 0x55/0xaa for stronger overwriting effects.
I did actually test this on a device file, using loopback. However, I'm not 100% sure the checking actually works. It might be necessary to close and reopen the file each pass, due to buffering behaviors. I would hope flush prevents this.
*edited to incorporate some suggestions in the comments

Welcome to the site.  You certainly don't need whitespace around an = in python.  You can also reduce your byte count by using ; to reduce indentation.

Normally, we count submissions in bytes, not characters. You can also alias some of your functions, e.g. f.seek(0);f.seek(0) (19 bytes) can be s=f.seek;s(0);s(0) (18 bytes). Furthermore, if f.read()==x:i+=1 can be i+=f.read()==x.

You also shouldn’t need the empty string as an argument to input.

I think b'\0' instead of b'\x00' should work.

Just realized an important feature. This program will consume RAM equal to the size of the device wiped.

@WilliamShipley Programs can assume unbounded RAM.

C (clang), -DZ=lseek(d,0 + 139 = 152 bytes
g,j,x,d,s,i,c;f(n){x=0;d=open(n,2);s=Z,2);for(j=2;j--;x++){Z,0);for(i=s;i--;write(d,&x,1));Z,0);for(i=s;i--;read(d,&c,1),c!=x&&x--&&j--);}}

Try it online!
Takes the filename as an argument
Ungolfed:
#include <unistd.h>
int g,j,x,d,s,i,c;
void f(char*n){
	x=0; /*Byte to write*/
	d=open(n,O_RDWR);
	s=lseek(d,0,SEEK_END); /*Get size of file*/
	j=0;
	for(j=0;j<2;j++){
		/*Write Pass*/
		lseek(d,0,SEEK_SET); /*Start writing from start of file*/
		for(i=0;i<s;i++){
			write(d,&x,1);
		}

		/*Verification Pass*/
		lseek(d,0,SEEK_SET);
		for(i=0;i<s;i++){
			read(d,&c,1);
			if(c!=x)x--,j--; /*If verification fails, repeat loop with the same value*/
		}
		x++;
	}
}

Hmm ... will the TiO wipe the internet? ;-D

@Titus It creates a temporary file and wipes it.

Tcl, 286 bytes
proc f {o i l} {seek $o 0
set s [string repeat $i $l]
puts -nonewline $o $s
flush $o
seek $o 0
return [string equal [read $o $l] $s]}
set n [open $argv r+]
fconfigure $n -translation binary
seek $n 0 end
set m [tell $n]
while {![f $n "\0" $m]} {}
while {![f $n "\xff" $m]} {}

Not really optimized that well. I tried what I could, but I don't know that much about Tcl.
Save as "f.tcl" and run on Unix with tclsh f.tcl "your filename". Make sure there's exactly one argument! I tested this on a plain file, but it should work on a device file as well.
Setting variables and indexing is more involved in Tcl, so I decided to put the common code between the passes into a function. Then I call it first with "\0", and repeat while it fails to verify. I do the same thing with "\xff".
I flushed after writes; it might not be necessary. fconfigure -translation binary -buffering none is longer.
-2 bytes by removing quotes around r+.


text:
Go to opposite corner of rectangle in all directions - Harder
This is essentially the same thing as this question, except harder. You are again to write a program that gets from the lower-left corner of a rectangle to the upper-right corner. However, this time diagonal moves are allowed.
The program will accept an ordered pair (width, height), and use these as the dimensions for a rectangle. Your program will then create an ASCII-art of the solution (use . for an empty square, # for part of the solution, and X for starting square) and count the number of moves it takes to reach the endpoint.
Example
Input: (5, 6)
Output:
....#
....#
...#.
..#..
.#...
X....
Move count: 5

Shortest answer in bytes wins!

It isn't, the solutions will require LOTS of editing

This challenge, like the suggested duplicate, is a trivially simple problem that is non-trivial to golf, which is a great combination. Despite the similarity, this challenge requires a different approach and well golfed solutions to the previous challenge cannot be trivially amended to be competitive here.

It could do with a more distinguishing title though...

yeah, any ideas?

@CoolestVeto This will actually be a great deal harder, since in that one, diagonal movements are not allowed.

Close-voters, think why you want to close it. Then justify it. Then try to counter your justification. If you still think it should be closed, comment with your justification. If the justification doesn't hold up, please retract your vote. If it does hold up, please vote to reopen when it is fixed.

By the way, that other question was also created by me. I based this one off of that one, but the answers will most likely be totally different.

I think this is a great challenge. IMO it's much harder than the last one.

@ericw31415 What are the minimum values of the two input numbers?

@LuisMendo The minimum is the smallest possible grid; 1 by 1.

MATL, 38 bytes
'.#X'!iSPXytf0)Jh1w(tzqDQI1()Gd0<?!]XP

Try it online!
Explanation
Let m and n be the sorted inputs, such that m is greater than or equal to n. The code initially builds an mxn matrix as follows:

Value 2 along the main diagonal, and on the lower part of the last column. This corresponds to character #. The number of these entries minus 1 is the move count.
Value 3 at entry (1,1), corresponding to the X.
The remaining entries contain 1, corresponding to character .

If needed, the matrix is now transposed so that it has the desired shape. Note that the first dimension of a matrix is its height, not width, so it corresponds to the second input.
The matrix is then flipped upside down so that X appears at the bottom of the first column, and its entries are used as indices into the string '.#X' to produce the desired 2D char array.
'.#X'    % push this string
!        % transpose into a column
i        % input array
SP       % sort it in non-increasing order
Xy       % identity matrix with that size: fill diagonal with 1, rest entries are 0
tf0)     % linear index of last 1
Jh       % append 1j (imaginary unit): linear index of lowest part of last column
1w(      % fill those entries with 1
tzq      % duplicate. Number of nonzero entries minus 1: this is the move count
D        % display move count (and remove it from the stack)
Q        % add 1. Matrix now contains values 1 and 2
I1(      % set first entry (in linear order) to value 3
)        % use matrix as index into the initial string. Gives 2D char array
Gd0<     % push input array again. Is it decreasing?
?        % if so
  !      %   transpose char array
]        % end
XP       % flip upside down. Implicitly display

It doesn't say the move count...?

@ericw31415 Sorry. Solved now

Pyth, 46 45 44 bytes
eSKtMQjsM_mm?sJ,kd?q#J.umtWbbNeSKK\#\.\XhQeQ

Try it here.
Explanation:
move-count-printing:

  K     assign K to...
     Q  the input, a 2-length array...
   tM   with each element decremented
eS      take the max and output it (this is the number of moves)

main path-finding logic:

    mm                     hQeQ  map over x-values and y-values...
        J,kd                     assign J to [x,y]
      ?s                         if both x and y are NOT zero (sum is truthy)...
            ?q#J[...]              if [x,y] is present in [...] (see below)...
                     \#            ... put a # at this position in the output
                       \.          ... else, put a . at this position
                         \X      ... else, put the X here (at [0,0])
jsM_                             reverse and output in the proper format

the [...] part in the code above, which finds positions where #s go:

.u      eSKK  cumulative reduce on <number of moves> elements, starting at K,
                which is [max_x, max_y] as assigned at the beginning
  m    N      map over x and y...
   tWbb       decrement, only if the value is > 0

JavaScript (ES6), 132
Edit 2 bytes saved thx @Neil
(w,h)=>[...Array(--h)].map((_,i)=>R(w-i)+'#'+R(i),--w,R=(n,c='.')=>c.repeat(n>w?w:n>0&&n)).join`
`+`
x${R(w-h,'#')+R(h)}
`+(h>w?h:w)

Test

f=(w,h)=>[...Array(--h)].map((_,i)=>R(w-i)+'#'+R(i),--w,R=(n,c='.')=>c.repeat(n>w?w:n>0&&n)).join`
`+`
x${R(w-h,'#')+R(h)}
`+(h>w?h:w)

function test() {
  var w,h
  [w,h]=I.value.match(/\d+/g)
  O.textContent=f(w,h)
}

test()
Test <input id=I value="4 5"><button onclick="test()">-></button>

Save 2 bytes by moving the w--,R=... into the map().

Python 3, 161 156 bytes
def f(w,h):
 x=[['.']*w for i in[0]*h];i=0
 while i<w or i<h:x[~min(i,h-1)][min(i,w-1)]=['#','X'][i<1];i+=1
 for i in x:print(''.join(i))
 print(max(w,h)-1)

A function that takes input via argument and prints the ascii-art, followed by the move count, to STDOUT.
How it works
The program first creates a list of lists, where each list represents one row of the grid and each element of the component lists is .. Each element that should be # has the property that if the output grid was square, the ordinates representing its location would be equal; hence, looping over some index i and inserting # at location (i, i) would give the desired output. However, the grid is not always square, and thus the indices are clamped to the grid by taking the minimum of the index and width/height (decremented due to zero-indexing) as required. If the index is zero, the current position must be the bottom-left entry, and thus X is instead inserted. Next, the elements in each line are concatenated, and each line is printed to STDOUT. The number of moves is the maximum of the width/height decremented; this is also printed.
Try it on Ideone

Javascript (using external library) (235 bytes)
Jeez this was hard! Well...my library wasn't really the right task for this haha. But I liked the challenge
(x,y)=>{r=x-1;s=y-1;m=Math.max(r,s);n=Math.min(r,s);l=_.RangeDown(s,y).WriteLine(z=>_.Range(0,x).Write("",w=>z==0&&w==0?"X":(z==w||(z==s&&w>=n)||(w==r&&z>=n))?"#":"."));return l+"\r\nMove count: "+(l.length-l.split("#").join("").length)}

Link to lib: https://github.com/mvegh1/Enumerable
Code explanation: Create function of 2 variables. Store x-1 and y-1 into variables. Store max and min of those into variables. Create a vertically descending range of numbers from (y-1) for a count of y. For each element on the vertical range, write a line for the current element, according to the complex predicate. That predicate creates an ascending range of integers from 0, for a count of x. For each element in that range, concatenate into 1 string according to a complex predicate. That predicate checks if on bottom left, else checks if on diagonal, else checks we're at X or Y border. Finally, all of that was stored in a variable. Then to get the move count, we basically just count the #'s. Then concatenate that to the stored variable, and return the result
That was a mouthful haha. The screenshot has the wrong bytecount because I found a way to save 4 bytes while posting this
EDIT: I see other answers aren't putting "Move count: " in their output, but mine is. If that isn't a requirement, that shaves a bunch of bytes...


text:
Shortest code for key-logger
Okay, I propose a shortest-key-logger challenge. As explained by the gentleman at "Are key-logger questions allowed?", strict rules have to be imposed in order to make this challenge valid for PPCG.

The key-logger has to run on Windows, Linux or Mac OSX (any programming language is welcome).
Upon execution, it has to show the message: "I'm gonna log you" (either in a console or using GUI).
The keys that are relevant for logging in this challenge are letters (case is not important) and numbers, all others such as symbols, control keys and whitespace are optional and can be ignored.
All relevant key presses that occur during runtime (even when the application is not in focus) have to be saved in a log file that can be read and verified using any text editor (even an esoteric one, as long as I can verify it using that text editor).

Anyone up for it? Whatdayatink?

"4. [...] saved in a log file" in what format?

Updated my question to specify intended format.

I can easily log what is typed in my program's REPL, is that sufficient or should it work work when I type anything in my browser or any other application too?

Yes, it should work for anything, "even when the application is not in focus".

Can we write a program that runs on mac (AppleScript), if we provide an example gif of it running?

Okay, added MacOSX to the list of valid operating systems :P

I’m voting to close this question because it asks for code which can be trivially modified to be malicious. The linked meta question's (only) answer states that asking for programs that are covertly keyloggers is disallowed, and aside from printing an easily-modifiable message, that's what this is asking for ("All relevant key presses that occur during runtime (even when the application is not in focus)").

Bash, 90 bytes
This works on Ubuntu, and requires evtest. It picks a device that is a keyboard, and saves evtest's output to the file l. If you want a more formatted output, I can do that with more bytes.
echo I\'m gonna log you
sudo evtest /dev/input/by-path/`ls /dev/input/by-path/|grep kbd`>l

You sir deserve respect.