text:
Working on my Knight moves
Hexagonal chess describes a family of chess variants played on a board where the cells are hexagons instead of the traditional squares. There are many such variants; in this challenge we'll be focusing on Gliński's variant, which is the most common.
The board is composed of three colors (so that the same color doesn't share an edge), with the edges of the hexagons facing the players. The board has 11 files, marked by letters a through l (letter j is not used), and 11 ranks (which bend 60° at file f). Ranks 1 through 6 each contain 11 cells, rank 7 has 9 cells, rank 8 has 7, and so on. Rank 11 contains exactly one cell: f11. (If it helps, think of each rank as making a very wide "V" shape.)
Here is an example picture of the board, with the knight on the center cell. The cells marked with a dot are the legal moves of this particular knight. The knight moves in a similar fashion to "normal" chess, two-down-and-one-over. In hexagonal chess terms, it's an orthogonal move (across an edge), then a diagonal move in the same direction (the closest move to the same color). For example with the knight below, an orthogonal move "up" to the light brown is then accompanied by a diagonal move "up and right" or "up and left" to the nearest light brown.

From the public domain via https://commons.wikimedia.org/wiki/File:Glinski_Chess_Knight.svg
This knight is positioned at f6 and the legal moves are thus
c4, c5, d3, d7, e3, e8, g3, g8, h3, h7, i4, i5

Input
A single input giving the starting cell of our knight. This can be as a single string "b6", as two strings, "b", "6", etc., in any convenient format. The input letters can be uppercase or lowercase -- your choice.
Output
A list of the valid moves that a knight on that location can make. This can be as an array of strings, a single string with an unambiguous and consistent delimiter, separate strings by newlines, etc., whatever is most convenient. The output does not necessarily need to be in sorted order, and can be in either uppercase or lowercase -- your choice.
Rules

Assume no other pieces are on the board or interfere with the moves. We're focusing on just the knight.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples
b6
a3, c4, d5, d9, e7, e8

f6
c4, c5, d3, d7, e3, e8, g3, g8, h3, h7, i4, i5

f11
d8, e8, g8, h8

i1
f2, f3, g4, h4, l2, k3

This coordinate system is the work of the devil.

@MartinEnder Points if you do it in Hexagony then :)

I feel like I could transform this into another vector space by redefining the two axes to the horizontal and the 60 degree diagonal, and then just use regular moves and then translate it back using linear algebra, but I think that's overcomplicating things :P And also I agree that the coordinate system is the most evile thing I have seen around here on this site. :P

JavaScript (ES6), 184 bytes
Takes the file F as a character and the rank R as an integer in currying syntax (F)(R). Returns an array of strings.
F=>R=>[...'100124566542'].map((X,i)=>(X-=3-(x=(s='abcdefghikl').search(F)))-7<(Y=('9641001469'[i]||10)-(A=Math.abs)(x-5)+17-2*R)&X+Y>3&X+16>Y&X+Y<27&&s[X]+(22-Y-A(X-5))/2).filter(n=>n)

How?
Step #1: convert file/rank to Cartesian coordinates
We convert the hexagonal chess coordinates to Cartesian coordinates (x, y) with x in [0 .. 10] and y in [0 .. 20]:
      00 01 02 03 04 05 06 07 08 09 10
   +----------------------------------
00 |                f11                     F = file (letter)
01 |             e10   g10                  R = rank in [1 .. 11]
02 |          d09   f10   h09
03 |       c08   e09   g09   i08            F | a b c d e f g h i k l
04 |    b07   d08   f09   h08   k07         --+-----------------------
05 | a06   c07   e08   g08   i07   l06      x | 0 1 2 3 4 5 6 7 8 9 10
06 |    b06   d07   f08   h07   k06
07 | a05   c06   e07   g07   i06   l05      y = 22 - |x - 5| - 2R
08 |    b05   d06   f07   h06   k05
09 | a04   c05   e06   g06   i05   l04
10 |    b04   d05   f06   h05   k04
11 | a03   c04   e05   g05   i04   l03
12 |    b03   d04   f05   h04   k03
13 | a02   c03   e04   g04   i03   l02
14 |    b02   d03   f04   h03   k02
15 | a01   c02   e03   g03   i02   l01
16 |    b01   d02   f03   h02   k01
17 |       c01   e02   g02   i01
18 |          d01   f02   h01
19 |             e01   g01
20 |                f01

Step #2: apply the move vectors
Below is the list of the move vectors in the Cartesian system:
(-2, +4), (-1, -5), (+3, +1),
(-3, +1), (+1, -5), (+2, +4),
(-3, -1), (+2, -4), (+1, +5),
(-2, -4), (+3, -1), (-1, +5)

We apply each of them to the source coordinates (x, y) and get a list of target coordinates (X, Y).
Step #3: test the target coordinates
We now need to check which target coordinates are actually located inside the board. This is done by testing X + Y and X - Y:

The coordinates are valid if all the following comparisons are true:

X + Y > 3
X + Y < 27
X - Y < 7
X - Y > -17

We should also verify that X is in [0 .. 10]. This is not done explicitly because s[X] is undefined if it's not, which eventually results in a falsy value that gets filtered out.
Step #4: convert back to hexagonal chess coordinates
Finally the valid target coordinates are converted back to hexagonal chess coordinates, using the inverse of the formulas described at step #1.
Test cases

let f =

F=>R=>[...'100124566542'].map((X,i)=>(X-=3-(x=(s='abcdefghikl').search(F)))-7<(Y=('9641001469'[i]||10)-(A=Math.abs)(x-5)+17-2*R)&X+Y>3&X+16>Y&X+Y<27&&s[X]+(22-Y-A(X-5))/2).filter(n=>n)

console.log(JSON.stringify(f('b')(6)))
console.log(JSON.stringify(f('f')(6)))
console.log(JSON.stringify(f('f')(11)))
console.log(JSON.stringify(f('i')(1)))

Ah, that's a really clever way of getting around the hexagonal coordinate system. Nice!

Batch. 403 bytes
@echo off
set j=a b c d e f g h i k l
set f=0
for %%f in (%j%)do set/af+=1&if %%f==%1 goto l
:l
set j=j%j: =%
set/a"r=6-f,r*=r>>31,r+=%2
for %%s in ("-3 -2" "-3 -1" "-2 1" "2 -1" "3 1" "3 2")do call:c %%~s
exit/b
:c
call:l %2 %1
:l
set/ag=f+%1,s=r+%2,t=g-s
if %g% geq 1 if %g% leq 11 if %s% geq 1 if %s% leq 11 if %t% geq -5 if %t% leq 5 set/a"t=6-g,s-=t*=t>>31"&call echo %%j:~%g%,1%%%%s%%

Adjusts the coordinate system, although in a different way to @Arnauld's answer. The c subroutine takes advantage of the symmetry by trying the mirror reflection of each move. (I also tried rotating but that took too many bytes.)

JavaScript (ES6), 184 bytes
(s,t,j=' abcdefghikl',f=j.search(s),r=f<6?t:t+f-6)=>[...'120405..162645'].map((c,i)=>[(i>>1)-3+f,c-3+r]).filter(([f,r])=>f>0&f<12&r>0&r<12&f-r<6&r-f<6).map(([f,r])=>j[f]+(f<6?r:r+6-f))

I thought I'd port my Batch solution to ES6 to see how it compared... I didn't expect it to be that close...

CJam, 77
1Z2W2Z]_Wf*+2/_Wf%+[r('a-_9>-_6-We>@~+]f.+{_~m5++B,-!},{~1$6-We>-\_8>+'a+\S}/

Try it online
Overview:
I'm using a coordinate system that looks like a..f and 1..6 on the left side, extended without bending, with letters replaced with numbers, and changed to be 0-based (b3→[1 2], g1→[6 1], k3→[9 6]). The relative moves in this system are [1 3], [2 -1], [2 3] and their reflections (negative and swapped, e.g. [1 3] → [-1 -3], [3 1], [-3 -1]). A resulting [x y] position is valid iff [x y z] ⊂ [0 1 .. 10] where z=x-y+5.

Interesting. So you translate the input to that coordinate system, perform the calculations, and then translate back? Neat.

@AdmBorkBork pretty much, yeah

Dyalog APL, 72 bytes
(6=|×/t,-/t←↑j[a⍳⊂⍞]-j←⊃,/i,¨¨↓∘i¨i-6)/a←⊃,/(11⍴⎕a~'J'),∘⍕¨¨⍳¨5+i⌊⌽i←⍳11

try
builds a list a of all valid cells: 'A1' 'A2' ... 'L6'
a is used for both input and output
builds a list j of the corresponding coordinates to a in a system where
the x axis is along A6-L1 and y along F1-F11
an imaginary third coordinate is the difference of the first two
if the input cell is translated to coords 0 0 0, a knight can move to those cells whose product of coords is 6 or -6

Python 3.6, 149
H='abcdefghikl'
lambda f,r:[H[i]+str(j)for i,j in[(H.find(f)+p%4*s,int(r)+p//4)for p in[9,6,-1,-5,-11,-10]for s in(1,-1)]if 0<i<11if 0<j<12-abs(6-i)]

An anonymous function called with two strings for the file and rank; returns a list of strings.
Ungolfed:
def h(f,r):
    H='abcdefghikl'

    A = []
    for p in[9,6,-1,-5,-11,-10]:
        for s in(1,-1):
            i = H.find(f) + p%4*s
            j = int(r) + p//4
            A.append(i, j)

    B = []
    for i,j in A:
        if 0 < i < 11 and 0 < j < 12 - abs(6 - i):
            B.append(H[i] + str(j))

    return B


text:
Calculate a square and a square root!
You must make a polyglot that outputs the square of the input in one language and the square root of the input in another. The shortest answer in bytes wins!
You must have a precision of at least 3 decimal places, and the input will always be a positive float.

Jolf and MATL, 1 byte
U

Square root in Jolf, square in MATL.
Try it online! (MATL)
Try the Jolf code. Only works on Firefox.
These are both 1 byte, as MATL and Jolf both use ASCII/extended ASCII codepages, so all commands are 1 byte.

C and C++, 68 65 bytes
#include<math.h>
float f(float n){auto p=.5;return pow(n,2-p*3);}

Original answer:
#include<math.h>
float f(float n){return pow(n,sizeof('-')-1?2:.5);}

For both versions, C produces n^2 and C++ produces sqrt(n).

+1 as a "Ha!" for all those people who treat C and C++ as the same thing.

How does C interpret this to get n^2? Does p get set to 0? I'm reading it like C++ would and have no idea how C interprets it differently.

@CAD97: In C, auto means "allocate on the stack". The keyword is fairly useless because that's the default anyway, so C++ repurposed it to mean something else. In C, though, it doesn't express any opinion about the type of p (it's a storage class, not a type), so it counts as an int by default (this default-to-int behaviour is discouraged nowadays, and likely only exists because some of C's predecessors didn't have data types at all, but compilers still understand it). And of course, (int)0.5 is 0.

This is brilliant.

How is sizeof('-') interpreted differently in C and C++? Is '-' an int in C?

@YSC It does seem like that's the case for C, for C++ it's 1 indeed

Found a Stack Overflow question about it.

Been writing C for donkey's years, never seen "auto" before.  Awesome.

I think the explanation for this answer would be improved by editing in @ais523's comment explaining why C produces n^2.

@BrianJ normally I put a full explanation in my answers, but in this case I found so many unexpected differences between the languages that I think it's more interesting for people to look up what's going on for themselves and stumble across some of the others.

The repurposing of auto in C++ was introduced in 2011.  For all C++ standards before 2011, the version using auto would produce the same in both C and C++.   The sizeof version works for all C and C++ standards.

What about #include<math.h> #define f(n) pow(n,sizeof('-')*1.5-1)? It seems to be shorter than both. Or do codegolf rules recommend using functions instead of preprocessor macros?

@Sasha sizeof('-')*1.5-1 wouldn't work unless the machine has a 16-bit int: it gives 5 if int is 32-bit or 11 if int is 64-bit. As for using macros rather than functions, you'd have to check meta for confirmation, but I haven't seen it done.

@Dave, you're right. Then #include<math.h> #define f(n) pow(n,sizeof('-')>1?2:.5). It's anyway shorter.

sizeof doesn't need parentheses, so the longer version could just be sizeof'-'-1?... (or indeed with >), but that's still longer than the auto version.

Python 2 & Python 3, 23 21 bytes
lambda n:n**(1/2or 2)

Python 2.x produces n^2, Python 3.x produces sqrt(n).
2 bytes saved thanks to @Dennis!

this is so cool!

Why? Is it the lack of space before or?

@chx In Py2, / does integer division (1/2==0). In Py3, it does floating point division (1/2==0.5). 0 is falsey.

then why not remove the space after or?

@chx Try it yourself. It throws a syntax error if you do.

@chx removing the space after or will cause python to read or2 as a function or variable name.  You can remove the space before or though, as python variables/functions can't start with a number, so 2or is parsed as 2 or.

2sable / Jelly, 2 bytes
*.

2sable computes the square. Try it online!
Jelly computes the square root. Try it online!
How it works
2sable
*   Read the input twice and compute the product of both copies.
    This pushes the square of the input.
 .  Unrecognized token (ignored).

Jelly
 .  Numeric literal; yield 0.5.
*   Raise the input to the power 0.5.
    This yields the square root.

It's like these languages were created just for this challenge

C (clang) and Python, 109 107 69 53 bytes
#/*
lambda n:n**.5;'''*/
float a(i){return i*i;}//'''

C: Try it online!
Python: Try it online!
Works by using comments to polyglot. The rest is pretty explanatory.
First time using C!

Saved quite a few bytes thanks to @Riker.
Saved 2 bytes by removing unnecessary whitespace.
Saved very many bytes by using a function for C instead of STDIN/OUT.
Saved 16 bytes thanks to @Delioth by removing import statement at the top.

I believe you can remove one newline after the C comment (line 2, last character) since C doesn't need whitespace and it's already a literal string for python. Since you aren't returning any special code, you can omit the return 0; from the end- C99 holds an implicit return of 0 on main() specifically. Source

@Delioth It actually made more sense just to use the function, and wipe out the io.

Oh, yeah- much better. Do you even need to include stdio.h in that case?

@Delioth I don't. Whoops!

Ohm and Jelly, 3 bytes
Outputs the square in Ohm, the square root in Jelly.
Ohm and Jelly use different single-byte codepages, so the program will appear differently in each encoding.
xxd hexdump of the program:
00000000: fd7f 0a                                  ...

Jelly
Using Jelly's codepage, it appears like this:
’
½

Jelly takes the bottom most line to be its main link, and ignores the other links unless specifically called. So here it just does the square root (½) and implicitly outputs it.
Ohm
Using Ohm's codepage (CP437), it appears like this:
²⌂◙

² is the square function, and ⌂ and ◙ are both undefined, so the program just squares the implicitly read input and implicitly outputs it.

Nice! The byte count is fine.

I edited my answer to 5 bytes because of this as well, good catch.

Wow, the first Ohm answer not written by me! Well done!

If you use the Jelly code page to get the ½ at a byte, what does the ² map to? Is it just junk that is still ignored? And vice-versa for Ohm? Then it would seem to be 2 bytes.

Both of those chars are in Jelly's code page and in Ohm's codepage it should seem... So those count as single bytes. If you don't need the space and the newlines I agree with @AdmBorkBork

@AdmBorkBork Are you saying I should take Ohm's codepoint for ² and use the Jelly character at that codepoint? (or vice versa)

I'll make up an example, since I don't want to bother looking up the actual code points. Suppose that ² in Ohm is at code point 5. Code point 5 in Jelly is % and does nothing, so it doesn't matter what the first line is. Suppose that ½ in Jelly is at 27, and code point 27 in Ohm is J and does nothing, so it doesn't matter what the second line is. Thus, if you have a file of 00000101<newline>00011011, it's 3 bytes. I guess the only problem is if the newline is at a different location in the code pages.

@NickClifford I did one too. http://codegolf.stackexchange.com/a/112657/56341

@RomanGräf Whoa, you've really been using the language a lot! Guess I'm just blind or something :P

C89 and C99, 47+3 = 50 bytes
float f(float n){return n//*
/sqrt(n)//*/1*n
;}

Requires -lm flag (+3)
C89 produces n^2, C99 produces sqrt(n). To test in C89, Try it online!

Getting C89 to do the sqrt version ought to take less code, but it insists on implicitly declaring the sqrt function with ints, so this is the best I could manage.

Octave / MATLAB, 31 29 bytes
 @(x)x^(2-3*any(version>60)/2)

This outputs the square in Octave, and the square root in MATLAB.
Explanation:
The syntax is of course identical in MATLAB and Octave (for this little piece of code at least).
This creates an anonymous function:
@(x)                                 % Take x as input
    x^(                     )        % Raise x to the power of ...
               version                 % Returns the version number
                                       % 4.2.0 in Octave,
                                       % '9.2.0.538062 (R2017a)' in MATLAB
               version>60              % 'R' is larger than 60. All others are smaller
         3*any(version>60)/2           % Checks if there is an 'R' and multiplies it by 1.5 if it is.
       2-3*any(version>60)           % 2-1.5*(is there an 'R')

Basic / Delphi – 6 characters
sqr(x)

Square root in Basic and square in Delphi.
You can use a debugger to inspect the expression, thereby fulfilling any output requirements!

Does this take input by itself?

No, but neither do some other submissions, including the C/C++ one.

Still invalid though, that doesn't change anything. I'll try to comment on those also.

Can you link any that don't? I can't find any. The C/C++ one is a function, doesn't take input, instead a parameter.

sqr is a function as well, and takes a parameter. It happens to be built-in like some of the golfing languages.

Yes, but what is x? You can't assume it's saved to a value. But you might actually be able to remove the (x), and label it as returning a function.

05AB1E / Fireball, 3 bytes
The following bytes make up the program:
FD B9 74

05AB1E calculates square root, Fireball squares.
Explanation (05AB1E - ý¹t):
ý       Pushes an empty string to the stack (not entirely sure why)
 ¹      Push first input
  t     Square root

Explanation (Fireball - ²╣t):
²       Square input
 ╣      Unassigned
  t     Unassigned

Sometimes, it helps to have an incomplete language ;)

05AB1E and Fireball use different encodings. Does this affect the programs?

@Dennis I didn't think about that. So saving the same program in different encodings doesn't count for polygots?

Afaik, the default is that the byte streams must match.

PHP7 + JavaScript, 62 61 58 bytes
This was actually more challenging than I expected!  I am quite surprised of how long my code is.

eval(['alert((_=prompt())*_)','echo$argv[1]**.5'][+![]]);

How does it work?
This works by selecting the code to run, from the array.
PHP and JavaScript detection is made with +![].
In PHP, [] (empty array) is a falsy value, while in JavaScript it is a truthy value (objects (except null) are always truthy, even new Boolean(false) is truthy!).
But, I need to get it to a numeric value, so, I just use a not (!) and convert it to integer (with the +).
Now, PHP yields the value 1, while JavaScript yields 0.
Placing the code inside an array, at those indexes, will allow us to select the right code for the desired language.
This can be used as [JS,PHP][+![]], to get the code of the right language.
On previous polyglots, I've used '\0'=="\0", which is true in JavaScript (since \0 is parsed as the NULL-byte) and false in PHP (the '\0' won't be parsed as the NULL-byte, comparing the literal string \0 with the NULL-byte).
I'm happy that I've managed to reduce this check to +!'0'.
I'm even more happy about @rckd, which reduced it to the current version!
From there on, it simply evals the code required.
PHP
PHP will execute echo$argv[1]**.5 (equivalent to echo sqrt($argv[1]);, square-root the number), receiving the value from the 2nd argument and displays it in the standard output.
JavaScript
JavaScript executes alert((_=prompt())*_), which displays the squared number in an alert.

Thank you to @rckd for saving 1 byte, and @user59178 for saving 3 bytes!

![] will save you 1 byte :-)

@rckd Holy cow! Totally forgot about empty arrays. Thank you! I've edited into the question, with an explanation on how it works.

you can save 3 bytes by using echo$argv[1]**.5 rather than echo sqrt($argv[1])

Wow, nice saving! Thank you! I've added it into the answer.

05AB1E and Jelly, 4 bytes
nqƓ½

(05AB1E) - (Jelly)
nq   # Ignored by Jelly, push n**2 in 05AB1E then quit.
  Ɠ½ # Ignored by 05AB1E due to quit, push sqroot of input in Jelly.

Someone else made a good point, I guess since the UTF-8 characters do not share the same operation across code pages that they are technically 2-bytes each to encode. However, when looking at this in terms of the hex dump:
6e 71 93 0a

In 05AB1E's CP1252 encoding this results in:
nq“\n

Meaning it will still output the square and quit, ignoring the rest. When these bytes are encoded using Jelly's codepage:
nqƓ½

Which is the original intended code, when executed, results in the desired result of taking the input and taking the sqrt.

This is actually 6 bytes in UTF-8, as both Ɠ and ½ require two bytes to be encoded. However, the byte sequence 6e 71 93 0a (nqƓ½ for Jelly, nq“\n for CP-1252) should work in both languages.

@Dennis ½ being on both code-pages doesn't allow for it to count as a single because they're different operations I assume? I'm still fuzzy on the whole code-page thing.

Scoring in bytes means were counting byte streams. Unless the interpreter actually supports encoding some characters in one code page and other characters in another, we cannot do this for scoring purposes.

@carusocomputing your submission is the 4 bytes 6e 71 93 0a so there's no "theoretically" about claiming 4 bytes. Just claim 4 bytes. It just so happens that in 05AB1E's standard encoding, it reads one thing which does what you want, while in Jelly's standard encoding, it reads another which does what you want. As an aside, just because 2 encodings can encode the same character doesn't mean that character will be the same in both of them. Just think of encodings like a numeric cypher with a lookup table already shared and hopefully that'll give you a good starting mental-model.

@Dave I must've misinterpreted Dennis then.

It's actually 4 bytes, you can remove 6 bytes entirely from the header. The byte stream is 6e 71 93 0a.

Python 2 and Forth, 43 33 bytes
( """ )
fsqrt
\ """);lambda n:n*n

Try it online: Python 2 (square) | Forth (sqrt)
This evaluates to an anonymous function in Python, and a built-in function fsqrt in Forth. Python can have a named function f for 2 bytes more by putting f= in front of the lambda.
The Forth program takes a floating point literal, which in Forth must be written in scientific notation. Pi truncated to 3 decimal places (3.141) would be written like this:
3141e-3

CJam / MATL, 8 bytes
ld_*GX^!

Computes the square in CJam (Try it online!) and the square root in MATL (Try it online!).
Explanation of square in CJam
ld    e# Read input line and interpret as a double
_     e# Duplicate
*     e# Multiply. Pops the input number twice, pushes its square
G     e# Push 16
X     e# Push 1
^     e# Bitwise XOR. Pops 16 and 1, and pushes 17
!     e# Negate. Pops 17, pushes 0
      e# Implicitly display. This prints the squared input with decimals,
      e# immediately followed by the 0 coming from the negate operation
      e# Even if the square of the input number is an integer, say 5,
      e# it is displayed as 5.0, so including an extra 0 always gives a
      e# correct result

Explanation of square root in MATL
l      % Push 1. This is a number or equivalently a 1×1 array
d      % Consecutive differences. Pops 1, pushes [] (empty array)
_      % Negate (element-wise). This leaves [] as is
*      % Implicitly input a number and push it. Multiply (element-wise):
       % pops [] and the input number, pushes []
G      % Push input number again
X^     % Square root. Pops number, pushes its square root
!      % Transpose. For a number (1×1 array) this does nothing
       % Implicitly display. The stack contains [] and the result; but
       % [] is not displayed at all

Hey! Nice submission! Care to add an explanation like other answers?

@programmer5000 I fixed an error and added the explanations

JavaScript (ES6) / JavaScript (ES7), 52 bytes
f=a=>eval(`try{eval("a**2")}catch(e){Math.sqrt(a)}`)

Returns the square of the input in ES7 and the square root in ES6. Quite difficult to test, unless you have an older browser which support ES6 but not ES7.

f=a=>eval(`try{eval("a**2")}catch(e){Math.sqrt(a)}`)

console.log(f(4));

Clever! Nice job on this one!

Is there a reason for the backticks? Seems like single quotes would do the job.

@JLRishe Nope, no reason :)

a**.5 and a*a saves some bytes reversing type

C, Operation Flashpoint scripting language, 52 bytes
;float f(float x){return sqrt(x);}char*
F="_this^2";

In an OFP script, a semicolon at the beginning of a line makes that line a comment, whereas C doesn't care about the additional semicolon.
C:
Try it online!
OFP scripting language:
Save as init.sqs in the mission folder, then call it with hint format["%1", 2 call F].
Result:

Okay, this is pretty cool.  How'd you think of using that scritping lang?

@Riker Operation Flashpoint always was one of my favorite games; I used to do lots of stuff in it with its scripting language.

Vyxal, Grok 10 12 bytes
Edit: In my first version, I forgot that casting to int would remove precision in the Vyxal code. Added +2 bytes to fix it.
I√`#:Yp*zq`_

Vyxal (Square Root):
              # Implicit input
I             # Cast to int
 √            # Square root
  `#:Yp*zq`   # Push string
           _  # Delete string
              # Implicit output

Try it Online in Vyxal!
Grok (Square):
I√            # Push '√' to the register
  `#          # Skip ‘#’ command
    :         # Take input from STDIN
     Yp       # Duplicate
       *z     # Multiply and output as int
         q    # Quit
          `_  # Never gets executed

Try it Online in Grok!

PHP and CJam, 30 29 25 bytes
ECHO"$argv[1]"**2;#];rdmq

Calculates the square in PHP and the square root in CJam. Has to be run using -r in PHP.
PHP
Raises the first command line argument ($argv[1]) to the power 2 and outputs it. Here $argv[1] is actually put as an inline variable in a string, which is cast to a number before doing the exponentiation. This is because v is not a valid instruction in CJam and will cause it to error out while parsing, but putting it in a string won't cause any problems.
# starts a comment, so everything after is ignored.
Try it online!
CJam
The first part of the code, ECHO"$argv[1]"**2;# pushes a bunch of values and does a bunch of operations, all of which are thoroughly useless. The only important thing is that they doesn't cause any errors, because right afterwards is ];, which wraps the entire stack in an array and then discards it.
After that, it reads a double from input (rd), and gets its square root (mq), and implicitly outputs it.
Try it online!

Desmos and Pip, 12 bytes
YRTa
f(y)=yy

Run in Desmos
Run in Pip
Desmos
The first line is four undefined variables multiplied together. Desmos complains about it, but ultimately it's a no-op.
The second line defines a function f(y) as y times y (with an implicit multiplication operator). This function can be used in other lines and will return the square of any argument number. As a bonus, we also get to see a graph of x = f(y).
Pip
RTa calculates the square root of the command-line argument a, and Y stores the result in y. The second line parses as three expressions:

f (evaluates to the main function)
(y)=y (evaluates to 1 because y always equals itself)
y (evaluates to the value stored in y previously)

The last of these expressions ends the program and is therefore autoprinted.

Python / PARI/GP, 60 bytes
#/*
n=int(input());print(n**2);"""*/
print(sqrt(input))\\"""

Basically a modification from the C / Python answer.
Python does square. PARI/GP does square root.
Takes input from stdin.
Python: Try It Online!
PARI/GP: Try It Online!

QBIC / QBasic, 26 18 bytes
input a
?a^2'^.25

In QBasic, it takes a number, and prints that number squared. The rest of the code is ignored because QBasic sees it as a comment (').
QBIC uses the same input statement. It then goes on to print that same number squared, then raised to the power of a quarter, effectively rooting it twice. This is because 'is seen as a code literal: Pure QBasic code that is not parsed by QBIC.

Reticular / Befunge-98, 15 bytes
2D languages!
/&:*.@
>in:o#p;

Befunge-98
/&:*.@

/          divide top two (no-op)
 &         read decimal input
  :        duplicate
   *       square
    .      output
     @     terminate

Reticular
/           mirror up, then right
>in:o#p;

 i          read line of input
  n         cast to number
   :o#      square root
      p     print
       ;    terminate

GolfScript/Befunge, 15 bytes
#>&:*.@
~2-1??
Befunge:

#>&:*.@
#>      // jumps over the arrow
  &     // takes an integer as input
   :*   // multiplies the top of the stack by itself
     .  // outputs as integer
      @ // halts
~2-1??  // is not executed

GolfScript:

#>&:*.@ // is a comment
~2-1??
~       // evaluates the input string
 2-1?   /* calculates 2^-1 = 1/2 (GolfScript does not support non-integers, but
           due to a missed int cast in the interpreter, they can be generated with
           the exponent function */
     ?  // calculates x^1/2 = sqrt(x)
        // the stack is output implicitly

This is my first golf, please let me know if I'm doing something wrong :)

Edited to be more portable, thanks to Wzl

Welcome to Code Golf! This looks really neat.

I believe in some befunge versions (98?) space is not an instruction, so it will skip over the &. Your program is working, but you could change it to another character for portability :)

Vyxal and ><> (Fish), 10* bytes
<?√,;n*:

Try it in Vyxal (Square root)
*this is 8 bytes in Vyxal but 10 in ><>. I'm scoring them both in UTF-8.
Try it in ><> (Square)
Explanation
What Vyxal sees:
<       # less than
 ?      # push input
  √     # sqrt
   ,    # print that sqrt
        # (rest doesn't matter)

What ><> sees:
<     # point left and wrap around executing the following
 :    # dup
  *   # multiply
   n  # output
    ; # end execution

Thunno 2 and Vyxal, 4 bytes
Thunno 2 encoding:
Ẋ,$ƭ

Vyxal encoding:
²,$₃

This looks like two different programs, since Thunno 2 and Vyxal have different encodings, but it's really the same sequence of bytes.

(Thunno 2: square root)
Try it Online! (Vyxal: square)
Explanation
Ẋ,$ƭ  # Implicit input
Ẋ,    # (No effect)
  $   # Push the input
   ƭ  # Square root
      # Implicit output

²,$₃  # Implicit input
²     # Square the input
 ,    # Print the result
  $₃  # (No effect)

><> / Jelly, 9 bytes (7 bytes code + 2 for the '-v' flag in ><>)
Man, I'm really having fun with the Jelly link structure.
:*n;
½

Calculates the square
in ><>
, and the square root
in Jelly.

Are you allowed to not use the -v in jelly too?

The use of -v is, in my opinion, in line with the [top-voted answer[(https://codegolf.meta.stackexchange.com/a/11431/44874) on a meta querstion handling this case. The ><> interpreter needs that -v and this is therefor the simplest possible invocation.

Python 3 + JavaScript, 101 bytes
0//1or exec("function=lambda a:(lambda b:a);x=0")
y=2//2/2
f=(function(x)(x**y))//1 or(lambda x:x**y)

Square root in JS, square in Python.
Works on Firefox (tested on FF 52) and requires (function(x) x)(42) === 42 being valid syntax. Also requires ES7 for the ** operator.

Tested on Firefox and it is working. Is it possible to use x=>x**y instead? Or Python will choke on that?

@IsmaelMiguel python doesn't support arrow functinos.

This doesn't work for python. Function isn't a keyword.

It does work. Since function is not a keyword, it's a valid identifier. So I just assigned a noop function to it (inside the execstatement).

bash and sh, 48 bytes
Update: I must concede defeat. Digital Trauma's bash/sh answer is far more elegant than this one.

bc -l<<<"sqrt($1^(($(kill -l|wc -l)*3-3)/7+1))"

bash produces n^2, sh produces sqrt(n).

bc is only needed so that sqrt can be calculated. The difference in behaviour is between bash and sh.
OK, technically the "sh" I'm using is still bash, but bash in "POSIX" mode (which happens if you invoke /bin/sh instead of /bin/bash on systems where /bin/sh is an alias for bash). If this is the case on your system, you can test with:
/bin/bash prog.sh 4
/bin/sh prog.sh 4

This is based on one of the differences explained here: https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html

How does this work?

@BrianMinton Try running kill -l (lists possible signals; doesn't change anything) in bash and sh. It's one of many differences you can find here: https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html

macOS Bash and sh, 24 bytes
p=^4 :
bc<<<"sqrt($1)$p"

On the Mac, sh is bash running in Posix mode, and in this case as per https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html:

Assignment statements preceding POSIX special builtins persist in the shell environment after the builtin completes

Thus for sh, the variable p has the value ^4 after the : is run, but for bash, the variable p only has this value while : is run, and is empty afterwards.
Being still really bash under the covers, some bashisms such as <<< herestrings still work for both the bash and sh cases.

Bash and dash (and GNU utils), 27
On Ubuntu 16.01, sh is a symlink to dash, which doesn't do <<< herestrings.  So we have this instead:
p=^4 :
echo "sqrt($1)$p"|bc

Try it online.

Nice use of a different mode/ env!

This is much better than my version!

Python 3 and Python 2, 18 bytes
I took inspiration from this answer
(1/2or 2).__rpow__

Python 3 : Try it online!
1/2 is evaluated to 0.5 so 1/2or 2 is equal to 0.5 => sqrt
Python 2 : Try it online!
1/2 is evaluated to 0 so 1/2or 2 is equal to 2 => ^2

Java and Groovy, 50 bytes
double f(int a){return Math.pow(a, 1/2==0?2:0.5);}

Try Java online!
Try Groovy online!
Java squares, Groovy roots. Inspiration taken from this answer, although it is unfortunate that Java does not have type coercion like Python and that Groovy has different lambdas than Java does. This works because in Java, 1/2 is equal to 0, while in Groovy it is 0.5.

C and C#, 56 bytes
double f(double x){return//\
System.Math.Sqrt(x);
x*=x;}

C# doesn't use \ as a line continuation character, at least not for line comments.
Try it in C!
Try it in C#!
I was originally going to do Swift + something else, since /*/**/this// */ is only a comment in Swift, but it ended up being shorter to abuse C's line continuation and use another language with the same syntax.

Jelly / Pip, 6 bytes
EDIT: It's a byte shorter to reverse operations.
RTa
²

Try Jelly online!
Jelly starts execution at the bottom of the code (its 'main link') and sees if it needs anything higher: it sees the command to square and takes care of input and output implicitly.
Try Pip online!
Pip executes the top line, squaring the (implicitly read from the cmd line) var a and implicitly prints that. The bottom line is ignored.

Alternative 6-byter: PRTaVS.

Wolfram Language / PHP, 25 bytes
Get the square of a number in Wolfram Language and get the square root in PHP;
n^2
echo sqrt(_GET["n"]);

First line is Wolfram Language. First, you are the ones to change n in the searchbar in Wolfram Alpha so the code is also the input. Then it's will generate the answer upon pressing enter
n^2

Second line is PHP, It gets the square root of the n which is to be inputted in the address bar (eg. ppcg.php.net?n=213, where 213 is n's value)
echo sqrt($_GET["n"]);

Welcome to PPCG! However, you must take input somehow. You can't assume the number is stored in a variable. Sorry about that. You can view the list of acceptable i/o methods here. (positive scores on the answers mean it's allowed, negative means not allowed)

Got it. I'll just edit my answer. :) Another thing, I'll just explain why adding another code for input in wolfram is not applicable.

Happy to help! Hope you stick around in ppcg!

Wolfram|Alpha is not a valid language.

Wolfram Language is based on mathematica which needs mathematical formula to be type in a non-natural way. Another thing, the answerer clears it out, its the website that's not the language but the wolfram language is the language that supports it. Wolfrsm Language and WolframAlpha is related to each ofher but not the same. The'yre totally different.

PHP 5.6 and PHP 7, 55 bytes
function f($n){list($a[],$a[])=[.5,2];echo $n**$a[0];}

PHP 5.6 produces n^2, PHP 7 produces sqrt(n).

Swift 5.0 and Swift 5.1, 112 bytes
func f(_ x:Any)->Double{let y=x as!Double
return y*y}
func f<T>(_ x:T)->Double{return(x as!Double).squareRoot()}

SwiftFiddle link
Swift 5.1 changed overload resolution for functions with unlabelled arguments, so f(_:) resolves as the square function in Swift 5.0 and as the square root in Swift 5.1. The permissive argument types are required for this to work; if you don't pass it a double, this will compile but crash at runtime.
The lack of argument labels is required: if you remove the underscores to make this f(x:), it will print the square root in both versions.
Swift 4 and Swift 5, 125 113 bytes
import Foundation
func s(x:Double)->Double{return pow(x,Double("\(try?{()throws->Int?in 0}())".count)*0.15-1.15)}

SwiftFiddle link
The function s(x:) computes the square in Swift 4 and the square root in Swift 5.
The original answer had the throwing function on its own line, rather than being an inline IIFE.
This was harder than I expected.
The try? operator is one of three legal prefixes for a call to a throwing function -- the others being try and try!. try requires a catch, try! promotes errors to fatal errors, and try? ignores errors and returns nil instead. For example, consider the following code snippet:
func foo() throws -> Int {
    // ...
}

let bar = try? foo()

The type of bar is now Optional<Int>, since it might be nil.
What if foo() already returns Optional<Int>? In Swift 5, the optionals are flattened, and bar is still Optional<Int>. In Swift 4, this is not the case, and bar is now Optional<Optional<Int>>.
When you convert an optional value to a string, it wraps it in "Optional("...")". So, the following code:
func foo() throws -> Int? {
    return 0
}

print("\(try? foo())")

Prints Optional(0) in Swift 5 and Optional(Optional(0)) in Swift 4. (If you don't wrap it in the string interpolation, it fails to compile. I have no idea why.)
From there, I use .count to get the length of the string, and do some simple arithmetic to get 2.0 in Swift 4 and 0.5 in Swift 5.
Swift 4 and Swift 5, cheating, 85 bytes
func s(x:Double)->Double{#if swift(>=5)
return x.squareRoot()#else
return x*x#endif
}

I shouldn't have to explain this.

Octave / Cardinal, 28 bytes
This program squares the input in Cardinal and gets the square root in Octave
 %:=t.
disp(sqrt(input("")))

Try it online! (Octave)
Try it online! (Cardinal)
So % is single line comment in Octave so it just gets input and prints the square root
disp(sqrt(input("")))

So that the Cardinal program doesn't encounter a divide by 0 error and die, the program
%:=t.

has been shifted with a space, which is ignored by both programs
Explanation of the Cardinal program:
The program starts at the %
It receives input and stores the value as active :
It sets the inactive to be equal to the active =
It multiplies the active by the inactive t
Finally it outputs the active value .

PHP / JavaScript, 43 bytes
<body onload=alert(<?=$x*$x.')>'.sqrt($x)?>

Input goes like:
<?php $x = 10; ?>

Kinda self-explaining, but does it fit the rules? My first code golf tho :-)

Welcome to code golf! Input must be a float or a string that is only a float. If I understand correctly, this requires separate input.

Are you sure this runs as JavaScript? It looks like both versions need a PHP processing stage (JavaScript wouldn't know what to do with alert(<?=$x*$x.')>'.sqrt($x)?)

CGL (CGL Golfing Language) / JS (ES6), 13 bytes(non-competing)
Non-competing because:

CGL was released after this question.
CGL is not a valid language. Because of ＋ and ⓟ, CGL is technically a valid language.

Code:
 x=>x**2
//-₂

JS:
Simple: an anonymous arrow function that returns its first argument squared. The unnamed language code is commented out.
CGL:
The non-breaking space before the first line acts like a comment. The /s are no-ops. The - in the second line means to decrement the current stack number, which by default is 0. That then sets it to -1, where input is stored. The ₂ replaces the first item in the current stack with its square root, which is now where input is placed. By default, the current stack is outputted, outputting the square root of the input.

This is 13 bytes. I dunno about CGL, but I'm fairly certain JS uses ascii/utf-8.  CGL would probably also use UTF-8, unless it has it's own codepage.

@Riker for now, it uses ascii/utf-8. Thanks.

Python 2 and ><> 23 bytes
#n*:i
print input()**.5

Python: Try it online!
><>: Try it online!

source: Stack Exchange

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

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

sort: votes


text:
Charlie and the evil hyphen
Here's the phonetic alphabet:
Alfa
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliett
Kilo
Lima
Mike
November
Oscar
Papa
Quebec
Romeo
Sierra
Tango
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu

In the fewest bytes possible:

Input will be these words in a random  order, with the first letters removed.
Your goal is to arrange the words back to their original order using only the letters you now have. In other words: work out how '[A]lfa' comes before '[B]ravo', and so on. Your code must not refer the original list, index keys, etc.
Restore the original first letters of each word.

Rules

The hyphen in X-ray is probably evil, but needs to stay, for I am also evil.
The result can be a string (comma or newline separated, for example), or an array.
The spellings and letter cases are non-negotiable.
No need to show example output in answers.

@LevelRiverSt The sorting is very different without the first character though

@fəˈnɛtɪk tagging each word fragment with its first letter is arguably a method of sorting. I think sparklepony's proposal is within the OP's intent. Really the OP should answer this, but I would be inclined to closevote again due to nonobservable requirements if the OP said no. It gets messy (what if you use a loop to fish them out one by one, add a letter and print - then you're doing both together. )I'm with Martin's meta OP in cases like this. (and the post he referenced with 19 upvotes and 0 downvotes)

If anyone feels this might be useful, a string which has uniquely identified each of the input words from the start of the string is "l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u"

I'm not sure I understand what the output is intended to be. Is it simply the exact phonetic text (or line array) kolmogorov complexity style, except you have a mangled version as input?

@xnor You are supposed to return an array of the exact phonetic text by performing operations on the input I think.

@fəˈnɛtɪk But what does "performing operations on the input" mean? Could one just disregard the input and output the fixed text? I don't expect it to be competitive, but am not clear if it's allowed.

@xnor It might work better then if you are given a random selection of the phonetic alphabet shuffled then you need to return it in order, in which case the fixed text would not be a valid output.

Two questions: 1. Does start with the words in a random order mean we'll receive them as input? That's what I inferred from the comments. 2. By text variable, do you mean string?

Jelly, 21 bytes
“ṣȤW¶¬þḷẒ⁶4ẹ’Œ?ịṢØA;"

Input and output are string arrays.
Try it online!
Background
While there are 26! = 403291461126605635584000000 different inputs, we can sort the input so we have to deal only with one permutation of this phonetic alphabet. Sorting lexicographically, we get
-ray
ango
ankee
apa
cho
elta
harlie
hiskey
ictor
ierra
ike
ilo
ima
lfa
ndia
niform
olf
omeo
otel
ovember
oxtrot
ravo
scar
uebec
uliett
ulu

We can simply index into this array to sort it by the removed letters. The (1-based) indices are
14 22  7  6  5 21 17 19 15 25 12 13 11 20 23  4 24 18 10  2 16  9  8  1  3 26

All that's left to do is to prepend the uppercase letters of the alphabet to the strings in the result.
How it works
“ṣȤW¶¬þḷẒ⁶4ẹ’Œ?ịṢØA;"  Main link. Argument: A (string array)

“ṣȤW¶¬þḷẒ⁶4ẹ’          Replace the characters by their indices in Jelly's code page
                       and convert the result from bijective base 250 to integer.
                       This yields k := 214215675539094608445950965.
             Œ?        Construct the k-th permutation (sorted lexicographically)
                       of [1, ..., n], with minimal n (26 here). This yields
                       [14, 22,  7,  6,  5, 21, 17, 19, 15, 25, 12, 13, 11,
                        20, 23,  4, 24, 18, 10,  2, 16,  9,  8,  1,  3, 26].
                Ṣ      Yield A, sorted.
               ị       For each j in the array to the left, select the j-th string
                       from the array to the right.
                 ØA    Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
                   ;"  Concatenate zipwith; prepend the j-th character from the
                       alphabet to the j-th string of the permuted input.

It amazes me how well you can golf...

Python 3, 76 71 bytes
lambda x,S=sorted:S(map(str.__add__,'XTYPEDCWVSMKLAIUGRHNFBOQJZ',S(x)))

Try it online!

JavaScript, 169/195 bytes
If replacing the first letter can be done prior to sorting 169 bytes
x=>x.map(k=>{for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split`,`[i++]))return String.fromCharCode(i+64)+k}).sort()

Try it online!
If sorting must be done prior to adding the first letter 195 bytes
x=>x.sort((a,b)=>g(a)-g(b)).map(a=>String.fromCharCode(g(a)+64)+a)
g=k=>{for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split`,`[i++]))return i}

Try it online!
A full 20 bytes of each of these programs is just String.fromCharCode() to regain the character...
Another 69 bytes is the string which uniquely identifies the start of each of the words in the phonetic alphabet.
Explanation of first example
for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split,[i++]))return i
The string hardcoded here is separated into a list of the unique identifying characters that start the phonetic alphabet words after the first character is removed.
return String.fromCharCode(i+64)+k

This information is used to find the index where the string falls in the alphabet in order to put the starting character back on.
.sort()

JavaScript implicitly sorts as strings by the ASCII values of the characters
Explanation of the second example
The function g=k=>... finds the index for which the string should fall in the phonetic alphabet.
.sort((a,b)=>g(a)-g(b))

Sorts the strings by the numbers returned by performing g(...)
.map(a=>String.fromCharCode(g(a)+64)+a)

Replaces the first character of each of the phonetic alphabet strings

Why the .sort() in your 169 byte answer? In the question it states "3. Restore the original first letters of each word.", but it doesn't mention the output has to be sorted as well.

@KevinCruijssen Your goal is to arrange the words back to their original order using only the letters you now have. In other words: work out how '[A]lfa' comes before '[B]ravo', and so on. Your code must not refer the original list, index keys, etc.

Ah, I misread a part from the 2nd bullet. I'll edit my code.

PHP, 94 bytes
<?for(sort($_GET);$i<26;sort($r))$r[]=XTYPEDCWVSMKLAIUGRHNFBOQJZ[$i].$_GET[+$i++];print_r($r);

Try it online!

05AB1E, 29 27 bytes
.•C5ê™вrΓ˜3åóMîõxÿ•uS|{)øJ{

Try it online!
.•C5ê™вrΓ˜3åóMîõxÿ•uS       # Push exploded XTYPEDCWVSMKLAIUGRHNFBOQJZ.
                     |{)    # Push input in array, sorted.
                        øJ{ # Zip together, join, resort.

-2 thanks to Emigna's magical .•.

You could also construct the string with .•C5ê™вrΓ˜3åóMîõxÿ•u.

Is that just a keyspace indexed using A-Za-z0-9 instead of 0-9A-Za-z?

It's a base-27 map into a-z

Java 7, 169 bytes
import java.util.*;List c(List l){Collections.sort(l);int i=0;for(Object s:l)l.set(i,""+"XTYPEDCWVSMKLAIUGRHNFBOQJZ".charAt(i)+l.get(i++));Collections.sort(l);return l;}

Try it here.
Explanation:
import java.util.*;                            // Import used for List and Collections

void c(List l){                                // Method with list parameter and no return-type
  Collections.sort(l);                         //  Sort the given list
  int i=0; for(Object s:l)                     //  Loop over the Strings in the list
    l.set(i,""+                                //   Replace the String-item in the list with:
      +"XTYPEDCWVSMKLAIUGRHNFBOQJZ".charAt(i)  //    The leading capital character
      +l.get(i++);                             //    Followed by itself
                                               //  End of loop (implicit / single-line body)
}                                              // End of method

It needs to return in the original order (Alfa Bravo Charlie...)

@fəˈnɛtɪk Fixed at the cost of 18 bytes, making it 169.

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


text:
Cyclic Levenquine
Background
As most PPCG regulars will know, a quine is a program which outputs its own source code when run; and the Levenshtein distance between two strings is the minimum number of insertions, deletions, and edits needed to change one string into the other. In this challenge, we're combining the two concepts into a "levenquine": a program that outputs its own source code, but with one instance of one character inserted, deleted, or replaced with a different character. (In other words, the Levenshtein distance between the program and its output is 1.)
The task
Write a levenquine such that its output is a levenquine, the output of that program is also a levenquine, and so on. Additionally, at some point, the sequence of repeatedly running the program, running its output, running its output's output, etc. must eventually come back to the original program.
There's one additional restriction that makes things much harder: there must be two distinct programs somewhere within this cycle which have no characters in common (in other words, there's no character that exists within one program and also exists within the other program). Your program is therefore going to have to gradually transform itself into a different character set, and back again.
If you're using a programming language which has unavoidable boilerplate that's required in any program that produces output (e.g. it only has one way to write a print statement and no other useful forms of output), you may treat that boilerplate as nonexistent for the purpose of determining which characters two programs have in common. You must, however, still count that boilerplate for the purpose of determining the Levenquine property of the code.
Clarifications

Each of the "programs" in the cycle can be either a full program or a function. They don't all have to be the same, e.g. some could be full programs and some could be functions.
Not all the programs in the cycle need to use the same form of output. For example, some could output via standard output, and some could output via standard error.
Your programs will be run with no input (or in languages which require input to do anything at all, the simplest possible input).
Proper quine rules apply; although a Levenquine is not a true quine, you may not do anything that would be illegal when writing a proper quine. In particular, the null program is never valid output from a proper Levenquine (and thus cannot be part of your cycle).
The Levenquine restriction is measured in terms of characters, rather than bytes (e.g. ê is one character even when the source is encoded in UTF-8). The no-characters-in-common restriction is also measured in terms of characters. The victory condition, however, counts in bytes.

Victory condition
Please submit at least the following three programs from the cycle: the shortest program (measured in bytes); and two programs from the cycle that have no characters in common. It's possible that two of these are the same, and it's also possible that all three are distinct. The score is based on the length in bytes of the shortest program, with shorter being better, thus making this a kind of code-golf competition.

For people who can see deleted posts: the Sandbox post was here.

I think it'd also be good for answers to include the length of the cycle.

What if, say, the language has several functions for performing output, but they all pairwise share characters?

@ØrjanJohansen: I guess I wouldn't be too opposed to just picking one of them and sticking with it in that case. However, it's arguably noncompeting; I wanted the rule to be objective, because otherwise people have a tendency to try to poke loopholes in it, and if you try to make the rule too complex there tend to be arguments over what it means.

Can it be a levenquine bit-wise? As in the distance from the original source code is 1 byte off?

Gol><>, 252 167 bytes
1>'r&ff9++r}}r&f*bc++1z.r}r6=z?Hzznr6rHr}r:ee+6+=z9*5c*+1z . }&z+5c*&H}rebe*b+ke++rHS6PWSb`S6P$$1W5/11b6W6EE/W6EE`S6P$$W61`S6P5W6$5_61P1WW_b_

Try it online!
And the mutually distinct (Verification) program:
0<CŽB‚‚UGGŽ™™ŽB‚F~GGM–JŽ™ŽRY–[d––ŠŽRŽdŽ™ŽVGRGY–UFQFGM–<J<™B–GQFBd™Ž~F~G‡GGŽd;oRl-7-7so~|;oRl@@-Ms7QKMM3-3-3~R-4sRaaK-3sRaa|;oRl@@sR43M|;oRlQ-sR43@Q{RMlMss3{~{"

Try it online!
This is mostly inspired by my answer to the Mutually Exclusive Quines challenge, with kudos also going to Bubbler's Gol><> answer.
Here is a verification program you can run. Unfortunately, it times out, but you can watch how one section of code builds the other section and then you can copy the last version printed and paste it into the input to continue. Eventually, you'll reach the first program you put in.
Explanation
Both sections of code are composed of two sections, the actual executing part and the data containing the other section of code. They both function practically identically:
They depend on a flag (the first character of the code, either 1 or 0). If the flag is set, they will start building the other section of code by taking the 252th character down, adding/subtracting 28 from it and appending it to the code.
For example, here are the first two iterations of the code after the first program above:
1>'r&ff9++r}}r&f*bc++1z.r}r6=z?Hzznr6rHr}r:ee+6+=z9*5c*+1z . }&z+5c*&H}rebe*b+ke++rHS6PWSb`S6P$$1W5/11b6W6EE/W6EE`S6P$$W61`S6P5W6$5_61P1WW_b_C

1>'r&ff9++r}}r&f*bc++1z.r}r6=z?Hzznr6rHr}r:ee+6+=z9*5c*+1z . }&z+5c*&H}rebe*b+ke++rHS6PWSb`S6P$$1W5/11b6W6EE/W6EE`S6P$$W61`S6P5W6$5_61P1WW_b_CŽ

Eventually when it reaches the end of the current section, it flips the second character of the code (< to > and back again) to point to the other section.
Here are both sections together, about to switch from executing the first section to executing the second.
1>'r&ff9++r}}r&f*bc++1z.r}r6=z?Hzznr6rHr}r:ee+6+=z9*5c*+1z . }&z+5c*&H}rebe*b+ke++rHS6PWSb`S6P$$1W5/11b6W6EE/W6EE`S6P$$W61`S6P5W6$5_61P1WW_b_CŽB‚‚UGGŽ™™ŽB‚F~GGM–JŽ™ŽRY–[d––ŠŽRŽdŽ™ŽVGRGY–UFQFGM–<J<™B–GQFBd™Ž~F~G‡GGŽd;oRl-7-7so~|;oRl@@-Ms7QKMM3-3-3~R-4sRaaK-3sRaa|;oRl@@sR43M|;oRlQ-sR43@Q{RMlMss3{~{"

Try it online!
The flags are the opposite for each section, so the newly executing section will start deleting the other section of code until it reaches its own code. At this point, it flips the flag and the cycle repeats again.


text:
Hexadecimal to Binary
Convert a hexadecimal number (of any size) into a binary number.
Input
A POSITIVE hexadecimal number with a 0x in the beginning. A valid input will always match the following regex: 0x[0-9a-fA-F]+. If the input is not a valid hexadecimal number, that is, anything not matching this regex, the output should be 0.
Output
The hexadecimal converted to binary.
Winning
Original Code-Golf Rules, Lowest amount of bites (bytes).
Examples
IN: 0x12
OUT: 10010

IN: 0xFF
OUT: 11111111

IN: 0XFF
OUT: 0

IN: #0ac4
OUT: 0

IN: 0x00101011
OUT: 100000001000000010001

IN: 0x525600
OUT: 10100100101011000000000

IN: 0x58f70555118ec400
OUT: 101100011110111000001010101010100010001100011101100010000000000

IN: 0x6669795966AF3000
OUT: 110011001101001011110010101100101100110101011110011000000000000

IN: 0b018474
OUT: 0

IN: 9577383
OUT: 0

IN: -483355
OUT: 0

IN: -0xf9ad92
OUT: 0

IN: 0xG
OUT: 0

IN: 0x0xa
OUT: 0

When you say "If the input isn't a valid hexadecimal number", what types of things can it be? A number in a different base? A non-numeric object? Some object made to crash the program is evaluated, possibly in a non-catchable way? Really, I would have suggested avoiding input validation at all; it feels like a chameleon challenge.

@xnor, you're right. It does seem a bit focused on the input checking. But a valid hexadecimal number is pretty self-explanatory. Look at the examples, I think those explain it better than I can.

@HashimKayani: The problem's not to do with what valid input can arrive, but what invalid input can arrive. Suppose someone's writing a function submission. Can the input be, say, a hashtable rather than a string? (That said, is a hexadecimal number even a string in the first place?) Or suppose someone's writing a full program submission, attempts to take input, and gets a disk I/O error. Is that considered something that isn't a hexadecimal number (leading to an output of 0), or can the program just crash in that case?

Inferring rules from test cases is not OK and likely will get the challenge closed as unclear. Besides that, the examples aren't clear to me. "#0ac4" makes it seem like any extra character(s) can be included.

Okay, I'll make the rules a bit more clear. I apologize for that. It does seem a bit vague.

I'm still not clear after the edit what inputs are possible. Is #0ac4 still a valid test case?

Your second testcase doesn't match your regex (the X is uppercase).

Do we need to take care of leading zeroes? Can we output something like 00011010

Can You add a test case with the correct prefix but invalid data please (0xG e.g.)

Pyth, 15 bytes
.B&qr0<z2"0x"vz

Explanation:
             vz  Evaluate the input as a literal, to get a number (casts to integer for hexadecimal input)
      <z2        Select the first two characters of (string) input
    r0           cast to lowercase (0X -> 0x)
   q     "0x"    check whether the text starts with "0x" or "0X" (negative numbers don't)
  &              If it does, return the casted number
.B               and convert to binary string

Test Suite
With a rules clarification (that 0x must be lowercase) in the OP, you can remove r0 for 13 bytes.
.B&q<z2"0x"vz

Python 2, 67 62 60 59 bytes
n=input()
try:print bin(int(n,n[1]<'x'))[2:]
except:print 0

Try it online!
Version that errors on invalid input (27 bytes):
lambda n:bin(int(n,16))[2:]

Try it online!

05AB1E, 11 bytes
Î2£„0xQi¹Hb

Try it online!
Explanation
Î             # initialize stack with 0 and push input
 2£           # get the first 2 chars of input
   „0xQ       # compare to "0x"
       i      # if equal
        ¹H    # convert input from base-16 to base-10
          b   # convert to binary

Doesn't work with the test case 0XFF.

@Okx: Both the regex and the input section of the question states that correct input starts with 0x so I'd say that specific test-case is wrong.

Ah yeah, I didn't notice that.

9 bytes by using the new Å? or 10 bytes by still using the legacy.

PHP, 66 65 63 bytes
<?=decbin(hexdec(preg_filter("#^0x([a-f\d]+$)#i","$1",$argn)));

run as pipe with -F.
Without the 0x, the worst problem would be that both hexdec and base_convert simply ignore characters that are not hex; but with it, there has to be an explicit validity check anyway.

45 bytes without the 0x:
<?=decbin(ctype_xdigit($argn)*hexdec($argn));

echo stristr($a=$argn,"0X")==$a?decbin(hexdec(ltrim($a,Xx0))):0; Is this a nice Alternative? It should working for the given testcases

@JörgHülsermann: It´s a nice alternative, and it´s working for all given test cases, but it does not check the hex value for validity (see my comment on hexdec and base_convert).

I know and I think the question is a joke with the given testcases.

echo decbin(hexdec(preg_filter("#^0x([a-f\d]+$)#i","$1",$argn)));

-2 Bytes <?= istead of echo  with -F option

Batch, 402 bytes
@echo off
set/ps=
set r=0
if not %s:~0,2%==0x goto g
if %s%==0x goto g
if %s:0=%==x goto g
set t=%s%
for %%h in (0 1 2 3 4 5 6 7 8 9 a b c d e f)do call set t=%%t:%%h=%%
if not %t%==x goto g
set s=%s:~2%
for %%h in (0.0000 1.0001 2.0010 3.0011 4.0100 5.0101 6.0110 7.0111 8.1000 9.1001 a.1010 b.1011 c.1100 d.1101 e.1110 f.1111)do call set s=%%s:%%~nh=%%~xh%%
set r=%s:.=%
:g
echo %r:*1=1%

Takes input on STDIN. 8 lines are then mostly wasted on input validation, so the interesting lines are line 11, which replaces each hex digit with its binary equivalent, but due to Batch limitations, with a leading ., line 12, which deletes all the .s, and line 14, which removes leading 0s. However this fails for inputs like 0x0 so I "invalidate" those which means 0 is output instead.

Perl 6, 35 bytes
{(m/^0x(.+)/&&:16(~$0)//0).base(2)}

JavaScript (ES6), 53 52 49 50 52 45 bytes
(Non-competing as it doesn't handle inputs of any size; I just got lucky with the sample inputs)

f=

h=>+/^0x[\da-f]+$/i.test(h)&&(+h).toString(2)

console.log(f`0x12`);
console.log(f`0XFF`);
console.log(f`#0ac4`);
console.log(f`0x00101011`);
console.log(f`0x525600`);
console.log(f`0x58f70555118ec400`);
console.log(f`0x6669795966AF3000`);
console.log(f`0b018474`);
console.log(f`9577383`);
console.log(f`-483355`);
console.log(f`-0xf9ad92`);

JavaScript (ES6), 116 111 110 bytes

f=
s=>/^0x[\da-f]+$/i.test(s)?s.replace(/./g,c=>parseInt(4+c,36).toString(2).slice(4)).replace(/0+10*(.)/,'$1'):0
<input oninput=o.textContent=f(this.value)><pre id=o>0

Not limited to 53 bits of precision. Edit: Saved 5 bytes by rewriting my digit conversion, which also reduces my language requirements to ES6. Saved 1 byte thanks to @l4m2.

You can reduce the length by 13 bytes by evaluating each character as the hex value. Try it Online

@fəˈnɛtɪk That doesn't solve the question as posed.

Here, I removed leading zeroes from from the first conversion Try it Online still 2 bytes shorter.

@fəˈnɛtɪk I combined it with Arnauld's answer and got it down to 103: Try it online!

@fəˈnɛtɪk Wait, that doesn't work for the fifth test case 0x00101011, sorry.

Can you .slice(4) rather than .slice(-4)?

JavaScript (ES6), 109 108 107 bytes
-1 thanks to l4m2
Works for any input size.
s=>/1.*|0$/.exec((/^0x([\da-f]+)$/i.exec(s)||'_0')[1].replace(/./g,d=>(`0x1`+d-0).toString(2).slice(1)))[0]

Try it online!

Hmm ... 2 experienced golfers submitting JS solutions more than twice as long as mine has me wondering if I've missed something in the challenge.

@Shaggy It all depends on the interpretation of the first line of the challenge. I took it for granted that 'of any size' was a definite requirement -- and so did Neil apparently.

@Shaggy Just to clarify for everyone: your approach works for up to 0x1fffffffffffff -- aka Number.MAX_SAFE_INTEGER -- and returns rounded results beyond that. By luck, the two large test cases are rounded correctly.

Huh, I didn't realise that @Shaggy's code worked by accident; I guess I should have counted the distance between the first and last 1 bits in the result. By the way, do you need the $ in the first regexp?

@Neil I don't think I can get rid of this $. The idea is to get the final zero if there's no 1 at all in the result.

Yes, I was just forgetting how regexps matched alternations.

+`0x1${d}`  => '0x1'+d-0

REXX, 45 bytes
arg '0X' n
if n>'' then say x2b(n)
else say 0

Retina, 149 bytes
.
;$&
T`L`l
f
71
e
70
d
61
c
60
b
51
a
50
9
41
8
40
7
31
6
30
5
21
4
20
3
11
2
10
;(\d{4})
$1
;(\d{3})
0$1
;(\d\d)
00$1
;
000
^(?!0{7}x).*
0
0{7}x0*

(note the trailing newline)
Try it online!
Here is an alternate solution at the cost of 7 bytes: Try it!

Slightly golfed. Alternative approach.

perl, 25
(code 24 + 1 flag -n)
printf"%8b",/^0x/i?hex:0

8086 machine code - 63 bytes
Works for any input up to 125 chars (the maximum command line length in DOS)
00000000  be 82 00 bf 3f 01 89 fa  ad 3d 30 78 75 24 ac 3c  |....?....=0xu$.<|
00000010  0d 74 22 2c 30 3c 09 76  08 24 df 2c 07 3c 0f 77  |.t",0<.v.$.,.<.w|
00000020  11 b1 04 c1 e0 0c d0 e4  0f 92 c0 0c 30 aa e2 f6  |............0...|
00000030  eb dc ba 3d 01 b0 24 aa  b4 09 cd 21 c3 30 24     |...=..$....!.0$|
0000003f

CJam, 24 bytes
q2/("0x"={seu:~Gb2bo}&;0

Try it online!
Explanation
q      e# Read the input
2/     e# Split it into 2-length segments
(      e# Pull out the first segment
"0x"=  e# Check if it equals "0x"
{      e# If it does, run this block:
 s     e#  Join the segments back together
 eu    e#  Make the string uppercase
 :~    e#  Eval each character (A-K are 10-20)
 Gb    e#  Convert from base 16 to base 10
 2b    e#  Convert to base 2
 o     e#  Output the binary number
}&     e# (end of block)
;0     e# Delete the top stack element and push 0. If the block was run, nothing is left
       e# on the stack, so the program terminates with an error before pushing 0.

JavaScript (ES6), 107 characters

f=
b=>/0x[\da-f]+$/i.test(b)&&b.match(/[\da-f](?!x)/gi).map(x=>((+('0x1'+x)).toString(2)).slice(-4)).join('')||0

console.log(f('0x1f'))
console.log(f('0x6669795966AF3000'))

Javascript, 63 bytes
f=
x=>0|/^0x[A-Fa-f0-9]+$/.test(x)&&Number.parseInt(x).toString(2)

Ruby -p, 44 bytes
~/^0x[0-9a-fA-F]+$/
$_=$&.hex.to_s 2rescue 0

Attempt This Online!

JavaScript (Node.js), 92 bytes
x=>/^0000x0*([01]+)$|/i.exec(x.replace(/./g,c=>('0x1'+c-0||1+c).toString(2).slice(1)))[1]||0

Try it online!
no 253 limit
JavaScript (Node.js), 37 bytes
to compare with Shaggy's solution
x=>(/x/i.test(x[1])*x||0).toString(2)

Try it online!
253 limit, issue when x end with space

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


text:
Hello world that handles errors
Write a program or function with the following functionality:

The program/function first attempts to write the string Hello, world! to the standard output stream. (No other forms of output are acceptable for this challenge, as the focus is very much on the I/O rather than the trivial behaviour of the program itself.) Depending on whether it succeeded:

If it succeeded in outputting Hello, world!, the program/function exits without any further behaviour.
If it failed to produce the correct output due to an error, the program/function attempts to write the string Error writing "Hello, world!" to the standard error stream. (For the purposes of this challenge, you don't need error handling for the error handling itself.)

Clarifications

Your program/function will be run with no input (unless it's written in a language which absolutely requires input to work, in which case it will be run with the simplest possible input).
When producing output, you may also produce a single trailing newline if you wish, but doing so is not mandatory.
The definition of "error writing to standard output" that your program implements must treat at least the following cases as errors:

Standard output being nonexistent (i.e. stdout is a closed filehandle, no file descriptor 1 exists, or however those cases translate to the language and OS you're using);
Standard output referring to a file on a disk that has no free space left;
Standard output connecting to another program, which has already closed its end of the connection.

and must treat at least the following cases as success (i.e. not an error):

Standard output connects to a terminal, and Hello, world! is displayed onscreen.
Standard output connects to a file, and Hello, world! is written into the file.

You can choose the details of what counts as an output error, so long as it's consistent with the above rules.
Your program/function should not crash upon encountering any of the error situations listed above. It's up to you what exit code you use.
Your program/function should not describe the nature of the encountered error on the standard error stream; it should just print the string specified above. Extraneous output on standard error (e.g. compiler warnings) is only legal if it's produced unconditionally, regardless of whether an error is encountered or not.
Your program only needs to work on one operating system (although it must be one on which the errors listed above make sense; I've tried to keep them general enough to work on most multitasking consumer operating systems, but weirder operating systems may well be excluded from this challenge). If your program is nonportable, list the assumptions it needs to run in the title of your submission.
This task may not be possible in every language (not every language allows a program to handle output errors in a custom way). You'll have to pick a language where it is possible.
Make sure that your program/function works! Don't just trust the documentation of library functions to do what they say they do. The error handling of simple output functions often turns out to be broken in practice, even if the functions claim to handle errors in theory.

Test cases
Here's a way to simulate each of the error conditions above using bash on Linux (you don't have to use Linux, but it's likely the easiest system to test this on):
your_program_here >&-           # nonexistent stdout
your_program_here > /dev/full   # out of disk space
mkfifo test  # note: change "test" to a filename that isn't in use
true < test &
your_program_here > test        # connecting to a program that doesn't want input
rm test      # clean up the FIFO we used earlier

The first two testcases are deterministic. The last isn't (it relies on a race condition); for testing purposes, I recommend adding a delay between the start of your program and the actual output to standard output, in order to ensure that the race condition is resolved in the way that exposes the error.
Victory condition
This is a code-golf challenge, so shorter is better. As (nearly) always, we're measuring the length of the program in bytes.

Do you know if there is a way to test this on Windows? I can test the first criterion, but not the part about the disk being full...

To reduce the race condition, could you use sleep 1 < test; (sleep 2; your_program_here) > test?

Related

Bash, 71 60 bytes
h=Hello,\ world!
(echo $h)2>&-||echo Error writing \"$h\">&2

Try it online!
How it works
After saving Hello, world! to the variable h, we do the following.
First, (echo $h)2>&- attempts to print Hello, world! to STDOUT. 2>&- is required to prevent displaying the error message echo: write error: Bad file descriptor in case the write fails. Since writing to a named pipe that doesn't accept input would kill the Bash program with signal 13 (SIGPIPE), we execute the command in a subshell ((...)), so only the subshell will get killed.
Finally, if printing to STDOUT failed, the subshell will exit with a non-zero status code (141 for SIGPIPE, 1 for a generic error), so echo Error writing \"$h\">&2 prints the desired message to STDERR.

Python 2, 65 bytes
h='Hello, world!'
try:print h
except:exit('Error writing "%s"'%h)

Two bytes could be saved by printing single quotes.
Try it online!

Zsh, 55 bytes
h=Hello,\ world!
2>&-<<<$h||<<<'Error writing "'$h\">&2

Unlike its cousin Bash, Zsh refuses to die because of a broken pipe.
Try it online!

PowerShell, 80 Bytes
try{echo($h="Hello, World!") -ea 4}catch{$host.ui|% *rL* "Error writing ""$h"""}

explained:
try{
    #Attempt to 'echo' (write output) the string, and assign it to $h
    #Make sure the 'error action' is set to '4' to make it a terminating error.
    echo($h="Hello, World!") -ea 4
} catch {
    #Use the "WriteErrorLine" function in $host.ui to stderr
    $host.ui|% *rL* "Error writing ""$h"""
}

haven't managed to actually try this when it errors, but it definitely ~should~ work.

The error message should be written to STDERR. Writing it to STDOUT isn't possible if an error occurs during the first write attempt.

@Dennis thanks for that, updated there, didn't read the question fully.

Afaict PowerShell only catches fatal exceptions, so you'd need Write-Host -ErrorAction Stop or something like that. Also, the throw produces additional debugging ingormation apart of the line it should print, which by the way should have a lowercase W and double quotes around the HW string.

@Dennis the additional debug info has crushed me, answer updated there now.

C (gcc), 87 86 bytes
f(){signal(13,1);write(1-puts("Hello, world!"),"Error writing \"Hello, world!\"",29);}

Try it online!
Ungolfed
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

void f(void)
{
    signal(SIGPIPE, SIG_IGN); // Works (and is required) on TIO. YMMV
    int fd = (puts("Hello, world!")) < 0 ? 2 : -13;
    write(fd, "Error writing \"Hello, world!\"", 29);
}

how do you know what return puts? here says just it is >=0 for to be all ok...

puts returns the number of bytes that have been written or -1 in case of an error, so it either returns 14 (Hello World plus newline) or -1. (That may be platform-specific, but this is how it behaves with glibc.)

K&R2 says it return EOF [-1 praticly] if error; or a value not negative if all ok

On PPCG, languages are defined by their implementation, and gcc/glibc behave like I said they do.

i prefer the old book

Perl 5, 51 bytes
requires -M5.01, which is free
say$h="Hello, world!"or die"Error writing \"$h\"$/"

Tested in Strawberry Perl 5.24.0 by running the program as-is (printed to standard output) and by running
print f $h="Hello, world!"or die"Error writing \"$h\"$/"

(printed to standard error). I don't know how to test for other errors using Strawberry, but they should be handled the same….

As far as I can tell, this doesn't work. https://tio.run/nexus/bash#jY3NDoIwEITvfYq1IXCiiD83ys3Ei2/ghdDFNlZLliIx8d0R4YAHTTjMZrKTb6YsPOSgO1FbyDKIRNQ3xTPQkh/RWgedI6tW3BEog/xANLiOjDf3C5x5oAclvBeMYakdSCkhHe8LPCIkCh9J4xUSsRrJQnzai3U67c3IZikCeRjP2HY5NuVVa79Wd3/w27UylRvejWeeWoRs9BD@LP5E/Rs (The string is also missing a comma.)

I don't know what to make of that page you linked to; can you explain, please? Also, note that the script needs to work on one OS only. And I'll add the comma; thanks.

Output should display Hello, world! after === 1 === and nothing after the others. Debug should display nothing after  === 1 === and Error writing "Hello, world!" after the others. I'm aware that your program doesn't have to work on TIO, but print f... shows the intended error messages while the original program does not.

"Output" and "Debug" both display nothing as far as I see. I also don't know what the "Header" and "Footer" sections are supposed to be. And I'm wholly unfamiliar with TIO, but note that Strawberry Perl runs on MS Windows.

Hat-tip to Dennis for the idea of storing the string in a variable (though I probably would've thought of it had I not seen it there).

Header and Footer run the program with the four conditions described in the challenge (normal output, closed file descriptor, full disk, and broken pipe). At least on Linux, the intended error message isn't printed, but Unable to flush stdout: Bad file descriptor and Unable to flush stdout: No space left on device are, while the last one is killed because of a broken pipe before producing any output. While I have no idea how to close file descriptors or create broken pipes on Windows, a full disk should be a bit cumbersome but ultimately straightforward.

Javascript, 79 76 bytes
try{(l=console).log(a="Hello, world!")}catch(e){l.error('Error writing '+a)}

Note that the string you should output is 'Hello, world!', which is one byte longer than what you use. Also, I suppose assigning a inside the call to console.log would be shorter (1B) and removing the semicolon after l.log(a) saves another byte.

@Luke Thanks, That was quite a big mistake!

try{(l=console).log(a="Hello, world!")}catch(e){l.error('Error writing '+a)} for 76 bytes. First, console is assigned to l, then "Hello, world!' is assigned to a, and then it's executed.

REXX, 111 106 bytes
signal on notready
a='Hello, world!'
_=lineout(,a)
exit
notready:_=lineout('stderr','Error writing "'a'"')

The program relies on there being a stream called 'stderr'. This will probably not be the case on IBM systems.

C, 77 bytes
f(a){a="Error writing \"Hello, world!\"";write(1,a+15,13)-13&&write(2,a,29);}

for call
main(){f(1); return 0;}

On which platform did you test this? It doesn't work on Linux if a broken pipe is encountered.

R, 91 bytes
s="Hello, world!"
tryCatch(cat(s),error=function(e)cat('Error writing "','"',file=2,sep=s))

Try it online!
I tried erroring it by running it with cat(s,file=12) instead of cat(s), and it prints the correct text to stderr. This is an invalid connection error otherwise.

Any idea how to test for other output errors?


text:
Derive the Units
Challenge
Given a list of SI base units, a list of equations and a target, you must derive the units of the target using only the base units.
Derived Units
From Wikipedia:

The International System of Units (SI) specifies a set of seven base units from which all other SI units of measurement are derived. Each of these other units (SI derived units) is either dimensionless or can be expressed as a product of powers of one or more of the base units.
For example, the SI derived unit of area is the square metre (m2), and the SI derived unit of density is the kilogram per cubic metre (kg/m3 or kg m−3).

The seven SI base units are:

Ampere, A
Candela, cd
Kelvin, K
Kilogram, kg
Metre, m
Mole, mol
Second, s

Example
Input
Base units:
d [m]
m [kg]
t [s]

Equations:
v = d/t
a = v/t
F = m*a
E = F*d

Target:
E

Output
E [kg*m*m/s/s]

Input
Base units:
G [cd]
L [m]
y [A]
a [K]

Equations:
T = y*y/L
A = T*G

Target:
A

Output
A [cd*A*A/m]

Rules
The units will be always be given in the form
a [b]

Where a will be a single uppercase or lowercase alphabetical letter and b will be a unit (one or more characters).
The equation will be in the form
a = c

Where c will be an expression which will only ever use previously defined units and the operators * and /.
Powers must be expanded. For example, the unit of area is officially m^2, but you should represent this as m*m. The same applies to negative powers such as speed (m*s^-1) which should be represented as a division: m/s. Similarly, the units for acceleration, m/s^2 or m*s^-2, should be represented as m/s/s.
You do not have to do any cancelling out. For example, an output C*s/kg/s is valid even though it can be cancelled down to C/kg.
There is no specific order for the multiplication: kg*s/m, s/m*kg, s*kg/m are all valid (but /m*s*kg is invalid).
Note: You will never have to divide by a derived unit.
Winning
The shortest code in bytes wins

Related.

Does input (output) need to be taken (given) as a string, or are other types / structures, e.g. symbols, acceptable?

@JulianWolf No, I/O has to be as strings

Retina, 50 48 bytes
 =

+`((.) (.+)\D*)\2(?!\w*])
$1$3
A-2`
](.).
$1

Try it online!
Explanation
 =

Remove all equals signs together with the space in front of them. Who needs those anyway...
+`((.) (.+)\D*)\2(?!\w*])
$1$3

This performs the substitutions of known quantities. It repeatedly matches a quantity definition (the quantity is any character in front of a space and the definition the string after it), as well as some place after the definition where that quantity is used, and insert the definition for the usage. We exclude units from those matches (by ensuring that there is no ] after the match), so that we don't replace [m] with [[kg]] for example. This substitution is repeated until the regex no longer matches (which means that there are no usages of a quantity left, and all lines have been turned into expressions of units).
A-2`

Discard all but the last line.
](.).
$1

Finally, remove extraneous square brackets. Basically, we want to keep the first [ and the last ] but discard all others. Those others always appear with an operator in between, so either as ]*[ or as ]/[. But more importantly, those are the only cases where a ] is followed by two more characters. So we match all ] with two characters after them, and replace that with the second of those three characters to retain the operator.

JavaScript (ES6), 155 153 152 bytes
(U,E,T)=>(u={},U.map(x=>u[x[0]]=x.slice(3,-1)),e={},E.map(x=>e[x[0]]=x.slice(4)).map(_=>s=s.replace(r=/[A-z]/g,m=>e[m]||m),s=e[T]),s.replace(r,m=>u[m]))

Takes base units and equations as arrays of strings.

f=
(U,E,T)=>(u={},U.map(x=>u[x[0]]=x.slice(3,-1)),e={},E.map(x=>e[x[0]]=x.slice(4)).map(_=>s=s.replace(r=/[A-z]/g,m=>e[m]||m),s=e[T]),s.replace(r,m=>u[m]))

console.log(
  f(
    ['d [m]', 'm [kg]', 't [s]'],
    ['v = d/t', 'a = v/t', 'F = m*a', 'E = F*d'],
    'E'
  )
)
console.log(
  f(
    ['G [cd]', 'L [m]', 'y [A]', 'a [K]'],
    ['T = y*y/L', 'A = T*G'],
    'A'
  )
)

Explanation
// Base Units, Equations, Target
(U,E,T)=>(
    // Map variable names to SI units
    u={},
    U.map(x=>u[x[0]]=x.slice(3,-1)), // x[0] is the variable name,
                                     // x.slice(3,-1) is the unit

    // Map variable names to equations
    e={},
    E.map(x=>e[x[0]]=x.slice(4)) // x[0] is the variable name,
                                 // x.slice(4) is the unit

    // (Initialize return string to the target variable's equation
    // using the (useless) second argument to .map() below)
    // s=e[T]

    // For as many times as there are equations (chained from above),
    .map(_=>
        // Substitute each variable with its equivalent expression
        // if there is one.
        s=s.replace(
            r=/[A-z]/g, // Save this regex for final step.
            m=>e[m]||m
        ),

        // The working string variable is initialized here.
        s=e[T]
    ),

    // Substitute remaining variables with SI units and return.
    s.replace(r,m=>u[m])
)