text:
Pretty Print Polynomials
Introduction
Humans are a remarkable species, but we can be very awkward to understand sometimes—especially for computers.
In particular, we seem to like writing polynomials in a very convoluted fashion with seemingly arbitrary rules.
What is the shortest program you can write to format a polynomial correctly using these rules?
Challenge
Input

A list of integers between -1000 and 1000 (inclusive), representing the coefficients of a polynomial, with the last entry being the coefficient of x^0 (the constant), the second last being the coefficient of x^1, etc.

Output

A string representing this polynomial in the correctly formatted mathematical notation of humans.

Rules:

The sign on the leading coefficient is only shown if it is negative.

Right: -x^2+3
Wrong: +x^2+3

Components with coefficient of 0 are not printed (except for the corner case where all coefficients are 0*).

Right: x^5-x^2+3
Wrong: x^5+0x^4+0x^3-x^2+0x+3

Coefficients -1 and +1 are to be displayed without the 1, unless they are the constant.

Right: x^5-x^2+1
Wrong: 1x^5-1x^2+1

The exponent is only shown if it is greater than 1 and the variable is only shown if the exponent is greater than 0.

Right: 3x^3-7x^2+2x+1
Wrong: 3x^3-7x^2+2x^1+1x^0

*Corner case: while zero values usually result in not printing that component, if all coefficients are zero the constant 0 should be printed.

Right: 0
Wrong: 0x+0
Wrong: (nothing)

This is code-golf so the winner will be the program with the fewest bytes.

Example Input and Output
Input:                  Output:
      [0]                      0
      [0,0]                    0
      [0,-1,35,0]             -x^2+35x
      [5,1,7,-9]               5x^3+x^2+7x-9
      [100,0,0,-1]             100x^3-1
      [931,21,-11,1]           931x^3+21x^2-11x+1

I look forward to seeing your solutions. Have fun!
EDIT:

You can surround operations by whitespace if you wish. So 3x+5 and 3x + 5 are both fine. 3x+ 5 and 3x +5 are not.
If you want to produce actual exponent characters (say in Tex) that is allowed as it is even closer to how humans write.
Coefficients must appear without any decimals e.g. 9x^2 is correct, 9.0x^2 is not.

A question which I should have asked in the sandbox but didn't, can we print with whitespace between the operators? So 3x^2 + 4 versus 3x^2+4?

Do we need to output exponents using carets? Or would producing an actual superscript character be allowed (e.g. for an answer in TeX)?

Can we take the input as strings instead of integers?

Are we allowed to output 5.0x^3+x^2+7.0x-9.0 instead of 5x^3+x^2+7x-9?

@KevinCruijssen I'm not the OP but I would say not, because most humans don't write like that.

@Giuseppe Thank you! Fixed now. And yes you can have whitespace surrounding operators. Thanks for the question.

@Tutleman Yes, as that is closer to human behaviour. Thanks for the question!

@ManishKundu Yeah sure you can take the input as strings.

@KevinCruijssen Nope but thanks for the question!

Suggestion: Inputs should also be allowed to be taken in the order of increasing powers, i.e, first x^0, then x^1 and so on...

@ManishKundu No, I'm just going stick with this order to avoid ambiguity and keep a single standard.

@DLosc [931, 21, -11, 1] -> 931x^3+21x^2-11x+1 added to the description as well. I'm expecting something very funky from you now.

@OisínMoran Nothing funky, just making sure a simple 1x -> x replacement doesn't change 21x^2 into 2x^2.

May we also optionally take the length of the array?

@Giuseppe I think I'll keep it as is but thanks for the suggestion!

What is the expected behaviour if the function is given an empty array? Also, if we're not allowed to pass the array length to the function, is a sentinel allowed for languages that don't pass array bounds to functions (i.e. C)?

Retina 0.8.2, 56 bytes
(?=( \S+)+)
x^$#1
\b0x.\d+

\b1x
x
x.1
x
 0

 -
-

+

Try it online! Link includes test cases. Explanation:
(?=( \S+)+)
x^$#1

Insert all of the powers of x, including x^1 but not x^0.
\b0x.\d+

Delete all powers of x with zero coefficients, but not a trailing 0 (yet).
\b1x
x

Delete a multiplier of 1 (but not a constant 1).
x.1
x

Delete the ^1 of x^1.
 0

Delete a constant 0 unless it is the only thing left.
 -
-

Delete the space before a -.

+

Change any remaining spaces to +s.

JavaScript (ES6), 107 106 bytes
a=>a.map(c=>c?s+=(c>0&&s?'+':_)+(!--e|c*c-1?c:c<0?'-':_)+(e?e-1?'x^'+e:'x':_):e--,e=a.length,_=s='')&&s||0

Try it online!
How?
The output is built by applying the following formulas to each coefficient c of the input array a[ ] while keeping track of the current exponent e.
1st formula: plus sign
If the coefficient is strictly positive and this is not the first term in the output expression, we append a +. Otherwise, we append nothing.
c > 0 && s ? '+' : _

2nd formula: minus sign and coefficient
If the exponent is zero or the absolute value of the coefficient is not equal to 1, we append the coefficient (which may include a leading -). Otherwise, we append either a - (if the coefficient is negative) or nothing.
!--e | c * c - 1 ? c : c < 0 ? '-' : _

3rd formula: variable and exponent
If the exponent is 0, we append nothing. If the exponent is 1, we append x. Otherwise, we append x^ followed by the exponent.
e ? e - 1 ? 'x^' + e : 'x' : _

This fails in this case:
[0,1,35,0]  , it will lead with  +x^2

@Makotosan Thanks for reporting this! Should be OK now.

Python 3, 279 277 258 251 bytes
k=str.replace
def f(x):
 z=len(x)
 y='--'*(['-1']==[c for c in x if'0'!=c][:1])
 for i,v in enumerate(x):
  p=str(z+~i)
  if v in'-1'and~i+z:y+='+x^'+p
  elif'0'!=v:y+='+'+v+'x^'+p
 return y and k(k(k(k(y[1:],'+-','-'),'^1',''),'x^0',''),'-+','-')or 0

Takes input as a list of strings. This solution is not highly golfed yet. This basically works by replacing things to suit the output format, which highly increases the byte count.
Try It Online!
Special thanks to ovs and NK1406.

Fixed all errors.

You can reorder you equality checks to make them if'0'!=i and if'-1'==i.

258 bytes

251 bytes by adding some variables for repeated expressions

Stax, 37 bytes
┴₧↕ê♦•Vªâÿσ9s╘dσ■à@@ⁿ■o─╦ñºº┌x╡ER▓ δ¿

Run and debug it online
Here's the unpacked, ungolfed version.
r{          reverse the input and map using block ...
  |c        skip this coefficient if it's falsy (zero)
  0<.+-@    sign char; e.g. '+'
  _|aYv i!+ abs(coeff)!=1 || i>0
    y$      str(abs(coeff)); e.g. '7'
    z       ""
  ?+        if-then-else, concatenate; e.g. '+7'
  "x^`i"    string template e.g. 'x^3' or 'x^0'
  iJ(T+     truncate string at i*i and trim. e.g. 'x^3' or ''
mr$         re-reverse mapped array, and flatten to string
c43=t       if it starts with '+', drop the first character
c0?         if the result is blank, use 0 instead

Run this one

APL (Dyalog Classic), 114 113 109 107 106 bytes
{{⍵≡'':⍕0⋄⍵↓⍨'+'=⊃⍵}∊⍵{{'1x'≡2↑1↓⍵:¯1⌽1↓1⌽⍵⋄⍵}('-0+'[1+×⍺]~⍕0),∊(U/⍕|⍺),(U←⍺≠0)/(⍵>⍳2)/¨'x'('^',⍕⍵)}¨⌽⍳⍴⍵}

Try it online!
-4 bytes thanks to @dzaima!
This can definitely be golfed down further. This requires ⎕IO←0

I finally shaved those two bytes off...

Pari/GP, 41 bytes
p->concat([c|c<-Vec(Str(Pol(p))),c!="*"])

Try it online!

If an * between the coefficient and the variable is allowed:
Pari/GP, 3 bytes
Pol

Try it online!

Even Mathematica didn't seem to have a builtin for this one!

C#, 237 bytes
c=>{var b=1>0;var r="";int l=c.Length;var p=!b;for(int i=0;i<l;i++){int n=c[i];int e=l-1-i;var o=p&&i>0&&n>0?"+":n==-1&&e!=0?"-":"";p=n!=0?b:p;r+=n==0?"":o+(e==0?$"{n}":e==1?$"{n}x":n==1||n==-1?$"x^{e}":$"{n}x^{e}");}return r==""?"0":r;}

Welcome to PPCG!

Pip, 78 bytes
(RV(B."x^"._MERVg)J'+)R[`\b0[^+]+``x.0|\^1|^\++|\++$``\b1x``\++-?`][xx'x_@v]|0

Takes the coefficients as command-line arguments. Try it online!
Uses ME (map-enumerate) and J (join) to generate something of the form 0x^3+-1x^2+35x^1+0x^0, and then a bunch of regex replacements to transform this into the proper format.

Clean, 172 bytes
import StdEnv,Text
r=reverse
@""="0"
@a|a.[size a-1]<'0'=a+"1"=a
? -1="-"
?1=""
?a=a<+""
$l=join"-"(split"+-"(join"+"(r[?v+e\\v<-r l&e<-["","x":map((<+)"x^")[1..]]|v<>0])))

Try it online!

@BMO fixed temporarily pending more golfing.

Perl 5 -a, 94 bytes
($_=shift@F)&&push@a,@a*!/-/>0&&'+',@F?s/\b1\b//r:$_,@F>0&&'x',@F>1&&'^'.@F while@F;say@a?@a:0

Try it online!

Doesn't seem to work correctly if the final (constant) coefficient is 1 or -1.

Dang.  Must have broken that while I was golfing it.  Fixed it with a few more bytes.

APL (Dyalog Classic), 79 76 bytes
{'^$' '\b1x' '\+?¯' '^\+'⎕r('0x-',⊂⍬)∊⍕¨(0≠⍵)⌿'+',⍵,⊖⍪((⊢↓⍨2≤⊢)↑'x^',⍕)¨⍳≢⍵}

Try it online!

Wolfram Language/Mathematica, 39 bytes
TraditionalForm@Expand@FromDigits[#,x]&

Try it online!
Turns out there is a built-in to get in in the right order.
Previous solution:
Wolfram Language/Mathematica, 93 bytes
StringReplace[StringRiffle[ToString/@InputForm/@MonomialList@FromDigits[#,x],"+"],"+-"->"-"]&

At least to me, this is suprisingly long for a language designed for mathematical manipulation. It seems like Expand@FromDigits[#,x]& should work, but the default ordering for polynomials is the reverse of what the question requires, so some extra finagling is required.
Explanation
FromDigits[#,x]               converts input list to polynomial (technically converts to a number in base x)
MonomialList@                 gets list of terms of polynomial
InputForm/@                   converts each term to the form a*x^n
ToString/@                    then to a string version of that
StringRiffle[...,"+"]         joins using +'s
StringReplace[...,"+-"->"-"]& replaces +-'s with -'s

Shouldn't SringReplace be StringReplace?

@ScottMilner Must've been a mistake when I was copying it over. Thanks for noticing it!

Python 3, 161 162 bytes
Fixed a bug thanks to ovs.
l=len
lambda p:''.join(['+'*(i>0)*(c>0)+(str(c)[:-1],str(c))[abs(c)!=1or i==l(p)-1]+'x'*(i!=l(p)-1)+('^%d'%(l(p)+~i))*(i<l(p)-2)for i,c in enumerate(p)if c])or'0'

Expanded:
l=len # Alias the len function since we use it a lot
lambda p: ''.join([ # Join a list of strings
    '+'*(i>0)*(c>0) # Prepend a + if this isn't the first term and the coefficient is positive
    + (str(c)[:-1], str(c))[abs(c) != 1 or i == l(p) - 1] # If the coefficient is 1 and this isn't the last term, delete the '1' from the string representation, otherwise just use the string representation
    + 'x' * (i != l(p) - 1) # If this isn't the last term, append an x
    + ('^%d' % (l(p) + ~i)) * (i < l(p) - 2) # If this isn't one of the last two terms, append the exponent
for i, c in enumerate(p) if c]) # Iterating over each coefficient with its index, discarding the term if the coefficient is zero
or '0' # If all of the above resulted in an empty string, replace it with '0'

Python3: 150 146 bytes
f=lambda l:''.join('+-'[a<0]+str(a)[a<0:5*((abs(a)!=1)|(1>i))]+'x^'[:i]+str(i)[:i-1]for i,a in zip(range(len(l)-1,-1,-1),l)if a).lstrip('+')or '0'

(previous implementations):
f=lambda l: ''.join('+-'[a<0]+str(a)[a<0:5*((abs(a)!=1)|(1>i))]+'x^'[:i]+str(i)[:i-1] for i,a in zip(range(len(l)-1,-1,-1),l) if a).lstrip('+') or '0'

You can try it online
Kudos to: @Benjamin

Arhg, got me! You bring it down by 4 by removing some spaces: f=lambda l:''.join('+-'[a<0]+str(a)[a<0:5*((abs(a)!=1)|(1>i))]+'x^'[:i]+str(i)[:i-1]for i,a in zip(range(len(l)-1,-1,-1),l)if a).lstrip('+')or '0'

Retina 0.8.2, 113 bytes
\w+
a$'b$&
a( [^b ]*)*?b(\d+)
$2x^$#1
(\^1|x\^0)(?!\d)

(?<= |-|^)(1(?=x)|0[^ -]*)

([ -])*
$1
[ -]$|^

^$
0

+

Try it online!
I'm sure there is a lot to golf here...

Husk, 44 43 41 40 bytes
|s0Ψf¤|□ṁ`:'+f¹zμ+↓s²_&ε²¹↑□¹+"x^"s)¹m←ṡ

Try it online!
This feels a bit clunky; Husk is not optimized for string manipulation.
I borrowed some ideas from the Stax answer.
Explanation
         Implicit input, say L = [2,-3,0,-1].
         First we compute the exponents.
ṡ        Reversed indices: [4,3,2,1]
m←       Decrement each: [3,2,1,0]
         Then we format the individual terms of the polynomial.
zμ...)¹  Zip with L using two-argument lambda:
          Arguments are coefficient and index, say C = -3 and I = 2.
+"x^"s    Convert I to string and concatenate to "x^": "x^2"
↑□¹       Take first I*I characters (relevant when I = 0 or I = 1): "x^2"
_&ε²¹     Check if abs(C) <= 1 and I != 0, negate; returns -1 if true, 0 if false.
↓s²       Convert C to string and drop that many elements (from the end, since negative).
          Result: "-3"
          The drop is relevant if C = 1 or C = -1.
+         Concatenate: "-3x^2"
         Result of zipping is ["2x^3","-3x^2","x","-1"]
f¹       Keep those where the corresponding element of L is nonzero: ["2x^3","-3x^2","-1"]
         Next we join the terms with + and remove extraneous +s.
ṁ        Map and concatenate
`:'+      appending '+': "2x^3+-3x^2+-1+"
Ψf       Adjacent filter: keep those chars A with right neighbor B
¤|□       where at least one of A or B is alphanumeric: "2x^3-3x^2-1"
|s0      Finally, if the result is empty, return "0" instead.

Ruby, 111 bytes
->a{i=a.size;s=a.map{|x|i-=1;"%+d"%x+[?x,"x^#{i}",""][i<=>1]if x!=0}*'';s[0]?s.gsub(/(?<!\d)1(?=x)|^\+/,""):?0}

Try it online!
Solving this in Ruby turned out to be a bit frustrating, mainly due to the fact that unlike most languages, in Ruby (almost) everything is truthy, including 0-s and empty strings, so that even a simple check for zero becomes nowhere near as short as x?.
I played with various methods of constructing the string, and ultimately settled on a mix of several approaches:

Terms with 0 coefficients are dropped using a simple conditional
+ and - signs are produced by formatting syntax with forced sign: %+d
The correct form or x^i is selected using rocket operator
indexing [...][i<=>1]
Leading + and unnecessary 1-s are removed by
regex replacements

Perl 6, 97 bytes
{$!=+$_;.map({('+'x?($_&&$++&$_>0)~.substr(--$!&&2>.abs)~(<<''x>>[$!]//'x^'~$!))x?$_}).join||'0'}

Try it online!
Explanation:
$!=+$_;

$! keeps track of the current exponent.
'+'x?($_&&$++&$_>0)

Add + before positive coefficients, except if it's the first non-zero one. The $_&& short circuit makes sure that the anonymous state variable $ is only incremented for non-zero coefficients. The & junction is collapsed when coerced to Bool with ?.
.substr(--$!&&2>.abs)

Decrement $!. Chop 1 or -1 coefficient unless it's constant.
<<''x>>[$!]//'x^'~$!

Special-case linear and constant terms. Using the quote-protecting << >>  construct is one byte shorter than the equivalent ('','x') or 2>$!??'x'x$!!!'x^'~$!.
x?$_

Hide zero terms, but always evaluate the preceding expression for the --$! side effect.
||'0'

Return 0 if all coefficients are zero.

Haskell, 166 163 bytes
g s|l<-length s,v:w:r<-id=<<["- +"!!(1+signum m):(id=<<[show$abs m|abs m>1||e==0]++["x"|e>0]++['^':show e|e>1])|(e,m)<-zip[l-1,l-2..]s,m/=0]=[v|v>'+']++w:r|1<3="0"

Try it online! Example usage: g [0,-1,35,0] yields "-x^2+35x".

Previous 166 byte solution, which is slightly better readable:
0#n=show n
m#n=id=<<[show n|n>1]++"x":['^':show m|m>1]
m%0=""
m%n|n<0='-':m#(-n)|1<3='+':m#n
g s|l<-length s,v:m:r<-id=<<zipWith(%)[l-1,l-2..]s=[v|v>'+']++m:r|1<3="0"

Try it online!

Java 8, 202 176 174 173 bytes
a->{String r="";int j=a.length;for(int i:a)r+=i==0*j--?"":"+"+i+(j<1?"":j<2?"x":"x^"+j);return r.isEmpty()?"0":r.substring(1).replace("+-","-").replaceAll("(\\D)1x","$1x");}

26 bytes thanks to @Nevay.

Explanation:
Try it online.
a->{                     // Method with String-array parameter and String return-type
  String r="";           //  Result-String, starting empty
  int j=a.length;        //  Power-integer, starting at the size of the input-array
  for(int i:a)           //  Loop over the array
    r+=i==0              //   If the current item is 0
           *j--?         //   (And decrease `j` by 1 at the same time)
        ""               //    Append the result with nothing
       :                 //   Else:
        "+"              //    Append the result with a "+",
        +i               //    and the current item,
        +(j<1?           //    +If `j` is 0:
           ""            //      Append nothing more
          :j<2?          //     Else-if `j` is 1:
           "x"           //      Append "x"
          :              //     Else:
           "x^"+j);      //      Append "x^" and `j`
  return r.isEmpty()?    //  If `r` is still empty
    "0"                  //   Return "0"
   :                     //  Else:
    r.substring(1)       //   Return the result minus the leading "+",
     .replace("+-","-")  //   and change all occurrences of "+-" to "-",
     .replaceAll("(\\D)1x","$1x");}
                         //   and all occurrences of "1x" to "x"

176 bytes: a->{String r="";int j=a.length;for(int u:a)r+=u==(j^j--)?"":"+"+u+(j<1?"":j<2?"x":"x^"+j);return r.isEmpty()?"0":r.substring(1).replace("+-","-").replaceAll("([+-])1x","$1x");}

@Nevay I only now realize all inputs are integers.. I used a String-input because I thought decimal inputs were allowed as well.. >.> Anyway, thanks for the -26 bytes. And I've been able to golf 2 more by changing (j^j--) to 0*j--.

Python, 165 bytes
lambda a:"".join([("+"if c>0 and i+1<len(a)else"")+(str(c)if i==0 or abs(c)!=1 else "")+{0:"",1:"x"}.get(i,"x^"+str(i))for i,c in enumerate(a[::-1])if c][::-1])or"0"

PHP, 213 Bytes
$p=0;for($i=count($a=array_reverse(explode(',',trim($argv[1],'[]'))))-1;$i>=0;$i--)if(($b=(float)$a[$i])||(!$i&&!$p)){$k=abs($b);echo ($b<0?'-':($p?'+':'')).((($k!=1)||!$i)?$k:'').($i>1?'x^'.$i:($i?'x':''));$p=1;}

Command line argument as requested by OP (single argument with brackets and commas).
Pretty print and some explanation:
$p = false; /* No part of the polynomial has yet been printed. */
for ($i = count($a = array_reverse(explode(',',trim($argv[1],'[]')))) - 1; $i >= 0; $i--)
{
    $b = (float)$a[$i]; /* Cast to float to avoid -0 and numbers like 1.0 */
    if (($b != 0) or (($i == 0) and !$p)) /* Print, if $b != 0 or the constant if there is no part until here. */
    {
        $k = abs($b);
        echo ($b < 0 ? '-' : ( $p ? '+' : '')); /* Sign. The first sign is suppressed (if $p is false) if $b positive. */
        echo ((($k != 1) || ($i == 0)) ? $k : '');  /* Coefficient */
        echo ($i > 1 ? 'x^' . $i : (($i != 0) ? 'x' : ''));  /* x^3, x^2, x, constant with empty string. */
        $p = true; /* Part of the polynomial has been printed. */
    }
}

PowerShell, 295 bytes
$c=$args[0]
$p=$c.length-1
$i=0
$q=""
while($p -ge 0){$t="";$e="";$d=$c[$i];switch($p){0{$t=""}1{$t="x"}Default{$t="x^";$e=$p}}if($d-eq 0){$t=""}elseif($d-eq 1){$t="+$t$e"}elseif($d-eq-1){$t="-$t$e"}elseif($d-lt 0 -or$i -eq 0){$t="$d$t$e"}else{$t="+$d$t$e"}$q+=$t;$i++;$p--}if($q -eq""){$q=0}
$q


text:
Help me play the Trumpet
The trumpet is a valved aerophone instrument, usually pitched in B♭. The sound is made when the player vibrates their lips to displace air inside the instrument. That vibration is acquired by setting one's mouth in a specific way, called the embouchure. Different embouchures, with tighter or looser lips, produce different pitches.
Furthermore, each valve in the trumpet also changes the pitch of the instrument. When depressed, a valve closes a path inside the tubing of the instrument, making the air flow through a longer path, thus lowering the pitch of the original sound. For the purposes of this challenge, we'll consider the standard, B♭ trumpet, in which the first valve lowers the pitch by a full step, the second lowers the pitch by a half-step, and the third lowers the pitch by one and a half step.
The Challenge
Your challenge is to create a program or function that, given two inputs embouchure and valves, determines the pitch of the note being played.
For the purposes of this challenge, the notes will follow the sequence:
B♭, B, C, C♯, D, E♭, E, F, F♯, G, G♯, A.

Rules

I/O can be taken/given in any reasonable method.
Standard loopholes apply.
You're allowed to use b and # instead of ♭ and ♯ if you wish to.
Input for valves can be taken as a list of depressed valves (1, 3) or a boolean list (1, 0, 1).
This is code-golf, so shortest code in each language wins.

Test Cases:
Valves in these test cases is given as a boolean list, where 0 means depressed and 1 means pressed.
Embouchure:    Valves:   Output:
B♭             0 0 0     B♭
B♭             0 1 0     A
B♭             1 0 1     F
C♯             0 0 1     B♭
C♯             1 1 1     G
E♭             1 0 0     C♯
G              0 1 1     E♭
G♯             1 0 0     F♯
G♯             0 0 1     F
G              1 0 0     F
F♯             1 0 0     E
D              1 0 1     A
A              1 1 1     E♭
E              1 1 0     C♯
E              0 0 1     C♯

Disclaimer: I'm not much of a musician yet, so I do apologize for any butchering I might've made on the test cases. Corrections are appreciated.

Sandbox

Percussionist here. Wait wait, that's how you spell embouchure. Always thought it started with an a ;-)

Some of these test cases don't seem to match the problem. For example, G#, 1, 1, 0 should be F, not F#, and C#, 1, 1, 1 should be G, not F#.

@vasilescur you're right. I'll fix those and review any other possible mistakes. Thanks for the heads up.

As someone who's played trumpet a long time, I'm really confused by the Embouchure measurement... For example what is a C# Embouchure?

@bendl I’m still beginning my studies on the trumpet, so I can’t really tell if those are particularly accurate or not. I tried to gather as much information as possible, and inferred some of that information from what I had available. Does that change whether or not the challenge is viable? If not, I think I’ll leave it as it is. As I said in the disclaimer, I’m not much of a musician yet and apologize for any inaccuracies.

Should F# 100 be E not F?

I don't think it changes the viability, I was just totally confused by the concept.

@LevelRiverSt yes, thanks!

@bendl There's no such thing. You can't play a C# on a trumpet without pressing down any valves. Just specific notes (B♭-F-B♭-D-F-A♭-B♭...), the overtone series of B♭. Still, even if it doesn't reflect a real instrument the challenge is perfectly well defined.

@bendl Same, got confused there

@bendl playing only on the mouthpiece, sure you can have a C# embouchure. Attach the instrument and it won't work so well, as noted in other comments, unless you play in a high enough octave... :)

Python 3 2, 125 119 81 bytes
lambda e,f,s,t,n=2*'A G# G F# F E Eb D C# C B Bb'.split():n[n.index(e)+2*f+s+3*t]

Try it online!
Saved a lot of bytes thanks to Jonathan Allan.

My original solution (in Python 3):
n=2*'Bb B C C# D Eb E F F# G G# A'.split()
e,f,s,t=str(input()).split()
print(n[n.index(e,9)-2*int(f)-int(s)-3*int(t)])

Try it online!
Saved 6 bytes thanks to @HyperNeutrino.

Explanation
First, I make an array of notes, but doubled in length so I don't have to worry about looping around from Bb to A.
Then, I take input in the following format (for example):
Bb 1 0 1

I then find the index of the starting note using n.index(e,9) (the 9 is there to make sure that I start well in the middle of the (doubled) list. I calculate the desired offset with the expression:
2*int(f) - int(s) - 3*int(t)

Where f is the first valve, s is the second valve, and t is the third.
Finally, it simply prints the note found in the list by subtracting the offset from the starting index.

save a few bytes by separating by spaces. "<some string>".split() splits by whitespace by default

Save 30 bytes by moving to Python 2 (avoiding str and int casts and allowing evaluated input) and reversing the notes and offsetting forward (avoiding the ,9 in the index call. Try It Online!

...and another 8 moving to function (which works in Python 2 or 3) Try It Online!

@JonathanAllan I learned several Python golfing tricks from your improvements. Thank you so much!

...in fact you can use the list in its original order without repetition and subtract values since the negative index never goes out of bounds (the most negative would be 'Bb', 1, 1, 1 taking you to index -6 which would be E, as required) - it's what TFeld has since done.

Wolfram Language (Mathematica), 100 bytes (and 134 for a working trumpet)
l="Bb,B,C,C#,D,Eb,E,F,F#,G,G#,A"~StringSplit~",";f=l[[Mod[#&@@#&@@l~Position~#-2#2-#3-3#4-1,12]+1]]&

Try it online!
Quite straightforward.
l="Bb,B,C,C#,D,Eb,E,F,F#,G,G#,A"~StringSplit~",";f=EmitSound@SoundNote[l[[Mod[#&@@#&@@l~Position~#-2#2-#3-3#4-1,12]+1]],1,"Trumpet"]&

A better output for the cost of 34 bytes.

Wait ... Mathematica has Audio output??? Wicked!

Of course Mathematica has a built-in for audio output. This is gold.

Ruby, 71 bytes
->e,(b,c,d){a=%w{Bb B C C# D Eb E F F# G G# A};a[a.index(e)-b*2-c-d*3]}

Try it online!
70 chars but 80 bytes
->e,(b,c,d){a="B♭BCC♯DE♭EFF♯GG♯A".scan /.\W?/;a[a.index(e)-b*2-c-d*3]}

Try it online!

Jelly,  37  36 bytes
ØAḣ7;⁾#b“®JXrẊỤȥ’ṃnŒl$œṗ$Ḋ©i_⁸æ.J¤ị®

A dyadic link accepting the valves as a list of 1s or 0s as a list representing [second, first, third] on the left and the embouchure as a list of characters on the right which returns a list of characters.
Try it online!
How?
ØAḣ7;⁾#b“®JXrẊỤȥ’ṃnŒl$œṗ$Ḋ©i_⁸æ.J¤ị® - Link: list of integers, V; list of characters, E
ØA                                   - yield uppercase alphabet
  ḣ7                                 - head to index 7 = "ABCDEFG"
     ⁾#b                             - literal list of characters = "#b"
    ;                                - concatenate = "ABCDEFG#b"
        “®JXrẊỤȥ’                    - literal integer = 2270857278734171
                 ṃ                   - base decompress (i.e. convert to base 9 using the 'digits' "bABCDEFG#")
                                     -                 = "ABbBCC#DEbEFF#GG#"
                        $            - last two links as a monad:
                     $               -   last two links as a monad:
                   Œl                -     to lower case = "abbbcc#debeff#gg#"
                  n                  -     not equal? (vectorises) = [1,1,0,1,1,1,0,1,1,0,1,1,1,0,1,1,0]
                      œṗ             -   partition at truthy indices = [[],"A","Bb","B","C","C#","D","Eb","E","F","F#","G","G#"]
                         Ḋ           - dequeue = ["A","Bb","B","C","C#","D","Eb","E","F","F#","G","G#"]
                          ©          - copy to register and yield
                           i         - first index of E in there
                                 ¤   - nilad followed by links as a nilad:
                             ⁸       -   chain's left argument, V
                                J    -   range of length [1,2,3]
                              æ.     -   dot product (i.e. 1*second + 2*first + 3*third)
                            _        - subtract
                                   ® - recall from register
                                  ị  - index into (1-based and modular)

Javascript 96 bytes
Following @vasilescur idea, this is the implementation in js
(a,b,c,d,_="B♭,B,C,C♯,D,E♭,E,F,F♯,G,G♯,A".split`,`)=>(l=_.concat(_))[l.indexOf(a,9)-(2*b+c+3*d)]

a=(a,b,c,d,_="B♭,B,C,C♯,D,E♭,E,F,F♯,G,G♯,A".split`,`)=>(l=_.concat(_))[l.indexOf(a,9)-(2*b+c+3*d)]
console.log(a('B♭',0,0,0))
console.log(a('B♭',0,1,0))
console.log(a('B♭',1,0,1))
console.log(a('C♯',0,0,1))
console.log(a('C♯',1,1,1))
console.log(a('E♭',1,0,0))
console.log(a('G',0,1,1))
console.log(a('G♯',1,0,0))
console.log(a('G♯',0,0,1))
console.log(a('G',1,0,0))
console.log(a('F♯',1,0,0))
console.log(a('D',1,0,1))
console.log(a('A',1,1,1))
console.log(a('E',1,1,0))
console.log(a('E',0,0,1))

3 bytes less ;) BTW the flats and sharps should be counted as 3 bytes aren't they?

Oh nvm (I didn't see that b and # are allowed) but you need to use b and # instead of flats and sharps.

Batch, 188 bytes
@set n=%1
@set/aC=0,D=2,Eb=3,E=4,F=5,G=7,A=9,Bb=10,B=11,n=(%n:#=+1%+12-%2*2-%3-%4*3)%%12
@for %%n in (C.0 C#.1 D.2 Eb.3 E.4 F.5 F#.6 G.7 G#.8 A.9 Bb.10 B.11)do @if %%~xn==.%n% echo %%~nn

Uses # and b: this means that Eb and Bb are legal variable names; # is handled by doing a string replacement to +1. The result of the string replacement is then automatically evaluated and the valves are then taken into account before the result is looked up in a list.

Stax, 32 bytes
τ┤=Yº○!AÄΔâß₧←╥╟ö'ÄD├æñßf╧å▬tó÷╖

Run and debug it online
It takes a note name and a list of depressed valves. It builds an array of note names, then calculates the total valve interval, and gets the note at that offset in the array.
"AbABbBCC#DEbEFF#G" just a literal
{VA#}(Y             partition at capital letters and store in y
,]I                 get the index of the input note
,2R:t               swap 1s and 2s in valve list
{-F                 subtract valve list from note index
y@                  look up result from note array

Run this one

Python 2, 84 79 bytes
lambda e,a,b,c,s='Bb B C C# D Eb E F F# G G# A'.split():s[s.index(e)-2*a-b-3*c]

Try it online!

C (gcc), 92 86 82 bytes
*r=L"扢bc⍣d扥ef⍦g⍧a",*u;v(z,y,x,w)short*z;{u=wcschr(r,*z);u-=2*y+x+3*w;u+=(u<r)*12;}

Try it online!
Adapted from @Vazt's implementation.

Perl6/Rakudo 73 chars
Technically this is 83 bytes because I put the Unicode characters in, but swapping them for the ASCII equivalents would give 73 bytes.
As a {code block} with parameters like $^a this is a lambda, with a signature ($a, $b, $c, $d).
{$_=2*$^b+$^c+3*$^d;'AG♯GF♯FEE♭DC♯CBB♭'x 2~~/$^a(\w\W?)**{$_}/~~/\w\W?$/}

Call it:
say { ... }("D", 1, 0, 1)
>> A

Less-golfed:
sub f($a, $b, $c, $d) {
   my $totalShift = 2*$b + $c + 3*$d;
   my $doubledScale = 'AG♯GF♯FEE♭DC♯CBB♭' x 2;
   my $matchEmbOnward = $doubledScale ~~ / $^a (\w\W?)**{$totalShift} /;
   my $matchFinalNote = $marchEmbOnward ~~ / \w \W? $ /;
   return $matchFinalNote;
}

Here we double a string '...' x 2 using the x infix operator, then searching for the embouchure followed by n notes using the smartmatch operator '...' ~~ /.../ - the regex hinges on \w\W? which is a word char then maybe a non-word char.
We look for n instances of that via (\w\W?)**{$_}, where we've already calculated n=$_ from params $b to $d. This yields a match from the embouchure note to the resulting note, of which we just want the last so we match that with another ~~ /\w\W?$/.
The calculation of $_ first is necessary to permit $^b implicit param creation on the block.
76 chars
An alternative using an array rather than string matches is 3 more chars:
{$_=<B♭ B C C♯ D E♭ E F F♯ G G♯ A>;.[((.first: $^a,:k)-2*$^b-$^c-3*$^d)%12]}

Finding the embouchure in the list is achieved with @arr.first: $^a, :k, which returns the index (key) of the found element with :k.
Setting the array to $_ (as an object) lets us use .first and .[ ] on it without spending too many characters.

C (gcc), 155 bytes
char r[][12]={"bb","b","c","c#","d","eb","e","f","f#","g","g#","a"};u;v(z,y,x,w)char*z;{for(;u<12;u++)if(!strcmp(z,r[u]))break;u=u-2*y-x-3*w;u=u<0?12+u:u;}

Try it online!
Simple approach.
Valve input is 0,1.
Embouchure input must be lowercase. Interestingly, TiO is not finding strcmpi() without including string.h, whereas mingw-gcc allows it with the standard -Wimplicit-function-declaration warning.

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:
Transitive Equality
The Challenge
Your program should take 3 inputs:

A positive integer which is the number of variables,
A set of unordered pairs of nonnegative integers, where each pair represents an equality between variables, and
A positive integer which represents the starting variable,

It should return a set of nonnegative integers which represent all variables which can be shown to be transitively equal to the starting variable (including the starting variable itself).
In other words, given inputs N, E, and S, return a set Q, such that:

S ∈ Q.
If Z ∈ Q and (Y = Z) ∈ E, then Y ∈ Q.
If Z ∈ Q and (Z = Y) ∈ E, then Y ∈ Q.

This can also be expressed as a graph-theory problem:

Given an undirected graph and a vertex in the graph, list the vertices in its connected component.

Specifications

You can choose to use 0-based or 1-based indexing.
The first input counts the number of variables that are present, where variables are given as numbers. Alternatively, you can not take this input, in which case this is assumed to be equal to either the highest variable index present, or one more than this, depending on your indexing scheme.
You can assume the input is well formed: you will not be given variables outside of the range specified by the first input. For example, 3, [1 = 2, 2 = 0], 1 is a valid input, while 4, [1 = 719, 1 = 2, 3 = 2], -3 is not.
You cannot assume that any variable will have any equalities associated with with it. If given a third input that is "lonely" (has no equalities), the correct output is a singleton set containing only that input (since it is equal to itself).
You can assume that the equalities will not contain an equality from a variable to itself, and that the same equality will not be given multiple times (this includes things like 1 = 2 and 2 = 1).
You can assume that all integers given will be within your language's representable range.
You can take the second input in any reasonable format.

Here are some reasonable formats:
0 = 2
0 = 3
1 = 0

{(0, 2), (0, 3), (1, 0)}

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

0 2 0 3 1 0

Graph[{{0, 2}, {0, 3}, {1, 0}}]

[0 = 2, 0 = 3, 1 = 0]

You can output in any reasonable format (i.e. set, list, etc.). Order is irrelevant.

Scoring
This is code-golf, so the shortest valid program (in bytes) wins.
Test Cases (0-indexed)
3, [1 = 2, 2 = 0], 1                      -> {0, 1, 2}
5, [0 = 2, 0 = 3, 1 = 2], 3               -> {0, 1, 2, 3}
6, [0 = 3, 1 = 3, 2 = 4, 5 = 1], 4        -> {2, 4}
6, [0 = 3, 1 = 3, 2 = 4, 5 = 1], 5        -> {0, 1, 3, 5}
5, [0 = 1, 2 = 0, 0 = 3, 4 = 0], 2        -> {0, 1, 2, 3, 4}
6, [0 = 1, 1 = 2, 2 = 3, 3 = 4, 4 = 5], 3 -> {0, 1, 2, 3, 4, 5}
4, [0 = 1, 1 = 2, 2 = 0], 3               -> {3}
5, [0 = 2, 2 = 4], 2                      -> {0, 2, 4}
8, [], 7                                  -> {7}

Test Cases (1-indexed)
3, [2 = 3, 3 = 1], 2                      -> {1, 2, 3}
5, [1 = 3, 1 = 4, 2 = 3], 4               -> {1, 2, 3, 4}
6, [1 = 4, 2 = 4, 3 = 5, 6 = 2], 5        -> {3, 5}
6, [1 = 4, 2 = 4, 3 = 5, 6 = 2], 6        -> {1, 2, 4, 6}
5, [1 = 2, 3 = 1, 1 = 4, 5 = 1], 3        -> {1, 2, 3, 4, 5}
6, [1 = 2, 2 = 3, 3 = 4, 4 = 5, 5 = 6], 4 -> {1, 2, 3, 4, 5, 6}
4, [1 = 2, 2 = 3, 3 = 1], 4               -> {4}
5, [1 = 3, 3 = 5], 3                      -> {1, 3, 5}
8, [], 8                                  -> {8}

Sandbox

Can we forgo taking the first input if we desire? I think it's not necessary to get the correct output

@dylnan "The first input counts the number of variables that are present, where variables are given as numbers. Alternatively, you can not take this input, in which case this is assumed to be equal to either the highest variable index present, or one more than this, depending on your indexing scheme." (point 2 of the spec)

Sorry sometimes I forget to finish reading

May the output contain duplicates ? (I can claim it represents a set...)

Can we take the starting variable in a singleton set?

@TonHospel Sure.

@xnor Sure, fine with me.

Brachylog, 22 bytes
{tc⊇,?k.&¬(t∋;.xȮ)∧}ᶠt

Try it online!
Explanation
{tc⊇,?k.&¬(t∋;.xȮ)∧}ᶠt  Input is a pair, say [2,[[1,3],[2,4],[5,2]]]
{                   }ᶠ   Find all outputs of this predicate:
 t                        Tail: [[1,3],[2,4],[5,2]]
  c                       Concatenate: [1,3,2,4,5,2]
   ⊇                      Choose a subset: [4,5]
    ,?                    Append the input: [4,5,2,[[1,3],[2,4],[5,2]]]
      k                   Remove the last element: [4,5,2]
       .                  This list is the output.
        &¬(      )∧       Also, the following is not true:
           t∋              There is a pair P in the second part of the input.
             ;.x           If you remove from P those elements that occur in the output,
                Ȯ          the result is a one-element list.
                      t  Take the last one of these outputs, which is the shortest one.

Python 2, 65 63 bytes
-2 bytes thanks to ovs

def f(e,s):b={s};exec"for p in e:b|=b&p and p\n"*len(e);print b

Try it online!

Pyth, 12 bytes
u|sf@TGQG.{E

Test suite.

Operation Flashpoint scripting language, 364 bytes
f={t=_this;r=t select 1;i=0;while{i<t select 0}do{call format["V%1=[%1]",i];i=i+1};i=0;while{i<count r}do{call format(["V%1=V%1+V%2;V%2=V%1"]+(r select i));i=i+1};l=call format["V%1",t select 2];g={i=0;c=count l;while{i<c}do{if(i<count l)then{e=l select i;call _this};i=i+1}};{l=l+call format["V%1",e]}call g;"l=l-[e]+[e];if(count l<c)then{c=count l;i=0}"call g;l}

Call with:
hint format
[
    "%1\n%2\n%3\n%4\n%5\n%6\n%7\n%8\n%9",
    [3, [[1, 2], [2, 0]], 1] call f,
    [5, [[0, 2], [0, 3], [1, 2]], 3] call f,
    [6, [[0, 3], [1, 3], [2, 4], [5, 1]], 4] call f,
    [6, [[0, 3], [1, 3], [2, 4], [5, 1]], 5] call f,
    [5, [[0, 1], [2, 0], [0, 3], [4, 0]], 2] call f,
    [6, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]], 3] call f,
    [4, [[0, 1], [1, 2], [2, 0]], 3] call f,
    [5, [[0, 2], [2, 4]], 2] call f,
    [8, [], 7] call f
]

Output:

Unrolled:
f =
{
    t = _this;
    r = t select 1;
    i = 0;
    while {i < t select 0} do
    {
        call format["V%1=[%1]", i];
        i = i + 1
    };

    i = 0;
    while {i < count r} do
    {
        call format(["V%1=V%1+V%2;V%2=V%1"] + (r select i));
        i = i + 1
    };

    l = call format["V%1", t select 2];

    g =
    {
        i = 0;
        c = count l;
        while {i < c} do
        {
            if (i < count l) then
            {
                e = l select i;
                call _this
            };
            i = i + 1
        }
    };

    {l = l + call format["V%1", e]} call g;
    "l = l - [e] + [e];

    if (count l<c)then
    {
        c = count l;
        i = 0
    }" call g;

    l
}

Clean, 85 81 bytes
import StdEnv
$l=limit o iterate(\v=removeDup(flatten[v:filter(isAnyMember v)l]))

Try it online!
Defines the function $ :: [[Int]] -> ([Int] -> [Int])

Interesting. How does limit work?

@EsolangingFruit it takes a list, assumed to be infinite, and returns the first element that occurs twice in a row.

Oh, that seems very useful!

Wolfram Language (Mathematica), 32 bytes
#~VertexComponent~#2~Check~{#2}&

Input format: {2<->3, 3<->1}, 3. It does not take the first input.
Try it online!

Jelly,  12   11  10 bytes
-1 thanks to Erik the Outgolfer (replace the atom œ& with f)
⁹fÐfȯFµÐLQ

A dyadic link accepting E on the left (as a list of length-two-lists) and S on the right (as an integer) returning a [de-duplicated] list.
Try it online! or see a test-suite.
How?
⁹fÐfȯFµÐLQ - Link: list of lists, E; integer S
      µÐL  - repeat the monadic chain to the left until a fixed point is reached:
  Ðf       -   (for each pair in E) filter keep if:
 f         -     filter discard if in
⁹          -     chain's right argument
           -     (originally [S], thereafter the previous result as monadic)
    ȯ      -   logical OR with implicit right
           -   (force first pass to become S if nothing was kept)
     F     -   flatten to a single list
           -   (S -> [S] / [[1,4],[1,0]]->[1,4,1,0] / etc...)
         Q - de-duplicate

œ&'s and f's return values always have the same boolean property.

Perl 5 -n0, 49 39 bytes
Give starting value on a line on STDIN followed by lines of pairs of equivalent numbers (or give the starting value last or in the middle or give multiple starting values, it all works)
#!/usr/bin/perl -n0
s/
$1? | $1/
/ while/^(\d+
)/msg;say//g

Try it online!
This can output an element in the result set multiple times. This 48 bytes variation outputs each equivalent element only once:
s/
$1? | $1/
/ while/^(\d+
)(?!.*^\1)/msg;say//g

Try it online!

Python 2, 53 bytes
e,s,n=input()
b={s}
for p in n*e:b|=b&p and p
print b

Try it online!
Same length as function:
lambda e,s,n:reduce(lambda b,p:b|(b&p and p),n*e,{s})

Try it online!
This is based off Rod's nice solution using the short-circuiting update b|=b&p and p. Taking the number of variables as an input n helps shorten the loop code.

K (ngn/k), 37 36 35 bytes
{&a[z]=a:{y[x]&:|y x;y}[+y,,&2]/!x}

Try it online!
{ } function with arguments x, y, and z representing N, E, and S respectively
!x is the list 0 1 ... x-1
&2 is the list 0 0
y,,&2 we add the pair 0 0 to y to avoid the special case of an empty y
+y,,&2 same thing transposed from a list of pairs to a pair of lists
{ }[+y,,&2] is a projection, i.e. a function in which x will be the value of +y,,&2 and y will be the argument passed in when calling the projection
|y x is y at indices x, reversed (|)
@[y;x;&;|y x] amend y at indices x by taking the minimum (&) of the existing element and an element from |y x
/ keep calling until convergence
a: assign to a
a[z]=z boolean mask of the elements of a equal to the z-th
& convert the boolean mask to a list of indices

Ruby, 39 bytes
->e,*s{e.map{e.map{|a|a-s!=a&&s|=a}};s}

Try it online!

Octave, 48 45 bytes
t=@(A,u)find(((eye(size(A))+A+A')^nnz(A))(u,:));

Takes input as "adjacency-matrix", for example uses [0 0 0; 0 0 1; 1 0 0] for [2 = 3, 3 = 1], try it online!
Explanation
First we construct the complete adjacency matrix for the transitive graph, using the sum of eye(size(A)) (elements are reflexive), A (input) and A' (the relation is symmetric).
We compute the transitive closure by computing the power to nnz(A) which suffices (nnz(A) is upper bound for a path's length), so from there all that's left is to get the right row with (u,:) and find all non-zero entries.

Python 2, 87 bytes
g,v=input();x={v};d=[v]
for c in d:x|={c};d+={k[k[0]==c]for k in g if c in k}-x
print x

Try it online!

Pari/GP, 80 bytes
f(g,p)=c=concat;if(p==q=c(c(p=Set(p),[e|e<-g,setintersect(Set(e),p)])),p,f(g,q))

Try it online!

JavaScript (ES6), 87 bytes
(a,n)=>a.map(([b,c])=>[...d[b]||[b],...d[c]||[c]].map((e,_,a)=>d[e]=a),d=[])&&d[n]||[n]

Deduplication would be possible using &&[...new Set(d[n]||[n])] at a cost of 14 bytes.

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

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


text:
Insist on a new filename
At runtime, keep prompting for a line of input until the user input is not the name of an existing file or directory or other file system item, relative to the current working directory. Then return/print that last inputted filename. You may assume that all user inputs will be valid filenames.
Pseudo-code 1
myform = new form("GUI")
myform.mytxt = new editfield("")
myform.ok = new button("OK")
repeat
  waitfor(myform.ok,"click")
until not filesystem.exists(myform.mytxt.content)
return(myform.mytxt.content)

Pseudo-code 2
LET TEXT = "."
WHILE HASFILE(TEXT) DO
  TEXT = PROMPT("")
ENDWHILE
RETURN TEXT

Examples of user input which will cause re-prompting when on TIO:
.
..
.env.tio
/
/bin/[
/lost+found

Examples of user input which will return when on TIO:
...
env.tio
../../bin/]
/lost/found

I'm fairly new to code golf here and can't seem to find any information on what counts as a solution.  Do I need to include the main() function for languages that require it in a program, or can that be part of the header? Can import statements be a part of the header in TIO, or do they need to be part of the code and count against the byte count? For example, I have this solution: https://goo.gl/8RWNgu but not sure if it the bytes would be legitimate.

@Makotosan Both functions and full programs are fine, although in the case of functions they need to be reusable. Imports generally need to be included in the byte count.

Batch, 37 bytes
@set/ps=
@if exist %s% %0
@echo %s%

(For some reason current Windows 10 CMD.EXE corrupts the title when it executes the %0.)

Mathematica, 33 28 bytes
f:=Input[]/._?FileExistsQ:>f

This assumes Mathematica's notebook environment where we can query input from the user with Input[]. The user input should be an actual string literal, so e.g. "ab/cd.ef" instead of just ab/cd.ef. The upside is that the input can be an arbitrary Mathematica expression that computes the input string.
This defines a symbol f which, when evaluated performs the required computation and ultimately evaluates to the first non-existent user input. It's essentially a nullary function, where we don't have to include ...[] to call it.
We can also save a bunch of bytes over a traditional If expression by making use of the pattern substitution operator /..

This fails if the user inputs the same thing twice

@Mathe172 Good catch, too bad, then I'll have to go with the boring loop.

Turns out I don't, and it's even a byte shorter. :)

Perl 5 -ln, 12 10 bytes
-2 bytes thanks to @DomHastings
#!/usr/bin/perl -ln
-e||1/!say

Try it online!

I think -e works without specifying $_, might not work for some cases though I guess...

@DomHastings Should work in all cases. It's documented that $_ is used when there is no argument to -e.

@DomHastings Thanks.For some reason I thought -e was an exception but of course it isn't

PowerShell 2 (through 6), 35 bytes
while(Test-Path($x=Read-Host)){};$x

Read-Host waits for input (if given a string as a parameter, uses the string as a prompt). If the provided input is a filename (or folder name) for one that exists, Test-Path returns $true, and the do-nothing block {} executes, and it re-prompts for input. If Test-Path returns $false because the input is not an extant file or folder, the do-nothing block does not execute, and the input name is printed.

Welcome to PPCG!

You don't need the semi-colon after the {} to save a byte.

@Veskah - I did in PS2, and it doesn't break PS3+

Ah, my bad. Didn't test it in 2.

Bash, 29
read f
[ -e $f ]&&$0||echo $f

Why doesn't this work?

@Adám I'm not sure why it doesn't work in TIO.  Suffice to say if you save it as a script file and run it, I think it works as expected

@Adám This works, the problem you had was that the program was trying to call .code.tio which contains the body of the script, but no information on how to run it. I'm not sure if there is a nice way to work around the shebang or this script needing to be in your path, though.

You can get around both (at the cost of two bytes) by changing $0 to . $0. Try it online!. Since . uses relative path names and the current shell.

What does it think of * as input?

C (gcc), 62 bytes
main(){char b[99];while(scanf("%s",b)&&!access(b,0));puts(b);}

Try it online!
main(){
    char b[99]; // Declare buffer b
    while (scanf("%s",b)&&!access(b,0));    // Take one line of input, and test if file is accessible (exists)
    puts (b);   // If doesn't exist, loop ends and print file
}

Welcome to PPCG! You can use while(gets(b),!access(b,0)); to save 7 bytes.

C#, 101 bytes
()=>{var s="";try{for(;;System.IO.File.GetAttributes(s=System.Console.ReadLine()));}catch{}return s;}

For each of the 4 valid return values:

Try it online! (returns '...')
Try it online! (returns 'env.tio')
Try it online! (returns '../..bin/])
Try it online! (returns '/lost/found)

Ungolfed
() =>
{
    var s = "";
    try
    {
        for(;; System.IO.File.GetAttributes(s = System.Console.ReadLine()));
    }
    catch {}
    return s;
}

Explanation
relies on the fact that File.GetAttributes() throws an exception if file system object specified in its argument doesn't exist.

Python 3, 55 bytes
import glob
s="."
while glob.glob(s):s=input()
print(s)

Try it online!
-4 bytes thanks to ManfP
-6 bytes thanks to Rick Rongen

@Adám terrible misinterpretation, sorry

You could replace the first input() with "."

import os and os.path.exists is three bytes shorter.

Rick Rongen suggested import glob and while glob.glob(s):... in an edit.

@MartinEnder thanks for telling me :)

@JonathanAllan Thanks; already got it down below -3 with another suggestion :)

Haskell, 76 bytes
import System.Directory
f=do x<-getLine;b<-doesPathExist x;last$pure x:[f|b]

Try it online!
Returns IO x where x is the inputted name of the file that does not exist.
Ungolfed
import System.Directory

insist = do { file <- getLine;
              exists <- doesPathExist file;
              if exists then insist else pure file }

Funky, 40 bytes
tryfor)io.open(s=io.read())catchprint(s)

In true funky style, this uses keywords jammed against eachother, unmatching brackets and implicit keywords. Cleaned up, this looks like:
try{
    while(true){
        s = io.read()
        io.open(s)
    }
}catch(e){
    print(s)
}

Breakdown
try                                     // Try statement, this one is expected to fail.
   for)                                 // for) is a for loop with no arguments, which is functionally equivilent to a while(true) loop, much like for(;;)
       io.open(                         // Try to open a file relative to the CWD. If this fails to find a file, it will throw an error and escape the try/catch
               s=io.read()              // Read a line from STDIN and store it as s, this will still pass it to the arguments of the call.
                          )
                           catch        // When io.open fails
                                print(s)// Print out the last entered line.

R, 66 51 bytes
while((s=readline())%in%list.files(a=T)){};print(s)

-15 bytes thanks to plannapus
Runs a potentially infinite loop, where on each iteration

A single line of user input is stored in the variable s
We check if the input is in the list of filenames for the working directory (the a=T option for list.files() must be used to pick up things like ..)
If s is in that list, we go to the next iteration; if not, we break the loop and print s.

How about shortening it to while((s=readline())%in%list.files(a=T)){};print(s)?

@plannapus Great idea! Incorporated.

You're welcome. Also, I didn't think of it right away but functions list.files and dir are synonyms, so you can replace it with dir here.

you could also replace readline() with scan(,'')

And print with cat

32 bytes: while((s=scan(,''))%in%dir())t;s

Java 9, 87 bytes
v->{String s;for(;new java.io.File(s=System.console().readLine()).exists(););return s;}

Ungolfed
TIO's JVM apparently has no system Console, so it's not testable there (see System.console()).
import java.util.function.*;
class Main {
  public static void main(String[] args) {
    Function<Void,String> f =

v->{
  String s;
  for(;new java.io.File(s=System.console().readLine()).exists(););
  return s;
}

;
    System.out.println(f.apply(null));
  }
}

JavaScript (Node.js), 158 118 bytes
require('readline').createInterface({input:process.stdin}).on('line',s=>require('fs').existsSync(s)||--console.log(s))

Try it online!
Credit to @ConorO'Brien for coming up with shorter version. Inlined objects instead of using consts and utilizing error exit condition instead of explicitly exiting.

Nice answer so far, but there's room for potential. You can golf this approach in a few ways: you can omit both const, and you can also replace each variable with it's definition. Then, instead of using s=>{if(...){...}}, you could use s=>require('fs').existsSync(s)||process.exit(console.log(s)). Additionally, you can exit with an error, so you can write the lambda as s=>require('fs').existsSync(s)||--console.log(s). Try it online!

Great ideas! Thanks!

Powershell 3.0, 75 bytes
$x=1;while($x){$i=Read-Host;$x=Test-Path("$PSScriptRoot\$i")};Write-Host $i

First attempt; I'm sure there are a few optimizations I could make.
A slightly more readable form:
$x=1;                                                                       # Make sure we enter our while loop.
     while($x){                                                             # While we keep getting file names,
               $i=Read-Host;                                                # Get input from the user
                            $x=Test-Path("$PSScriptRoot\$i")};              # Combine our path with the user input, and see if it already exists.
                                                              Write-Host $i # Return the final (valid) file name.

Wouldn't it work even without $PSScriptRoot\?

Welcome to PPCG! A few quick golfs -- you can use a for loop instead, which allows you to move the initialization into the loop constructor for($x=1;$x){...}. Secondly, you can get rid of the Write-Host since there's an implicit Write-Output at program completion for anything left on the pipeline, so just leaving $i there will suffice.

See my solution below; I've halved your byte count.

@Adám: Maybe! I hadn't actually considered that. :P
AdmBorkBork Thank you! I spent a long time lurking. Those are good ideas; the implicit output didn't even cross my mind...

Kotlin, 67 bytes
val f={var s="."
while(java.io.File(s).exists()){s=readLine()!!}
s}

Try it online!

Attache, 35 bytes
{While[FileExists[x:=Prompt[]],0]x}

Try it online!
Alternative solutions
35 bytes: {If[FileExists[x:=Prompt[]],$[],x]}, recursive function.
37 bytes: {NestWhile[p:=Prompt,p[],FileExists]}, iterative function.

Clean, 100 94 bytes
import System.IO,System.File
Start w#(s,w)=evalIO getLine w
#(b,w)=fileExists s w
|b=Start w=s

Try it online!
single-expression version:
import System.IO,System.File
Start w=(\(s,v)=(\(b,w)|b=Start w=s)(fileExists s v))(evalIO getLine w)

Try it online!

APL (Dyalog), 17 bytes
{⍞}⍣{~⎕NEXISTS⍺}⍬

Try it online!

Returns the second non-existing input, (the_prev_wasnt_filename instead of env.tio). Change ⍵ → ⍺ and then you can get rid of '.' too.

Perl 6, 39 bytes
my$f=".";while $f.IO.e {$f=get};say $f;

This works in the REPL, but it doesn't seem to work properly in TIO.

What about say first !*.IO.e,lines (23 bytes)?

The above probably blocks indefinitely when run on the command line, but something like {}while ($_=get).IO.e;.say should work.

PHP, 43 bytes
<?for(;file_exists($f=readline()););echo$f;

Run as CLI. Quite easy to understand.

Ruby, 40 39 37 bytes
{}while File.exist? gets.chomp
$><<$_

Try it online!

Min, 38 bytes
"." :a (a exists?) ("" ask @a) while a

Leaves last entered filename on the stack.
Explanation
"."         ; Put . on the stack. Every directory should contain this...
:a          ; Assign to a
(a exists?) ; A quot that checks if a exists in current directory
("" ask @a) ; Read line from stdin, assign to a
while       ; Do the second quote while the first leaves true on the stack
a           ; Leave a on the stack

SmileBASIC, 27 bytes
INPUT S$EXEC!CHKFILE(S$)?S$


text:
N times program for the N-th number
Given an array of positive integers A as the input, generate a program that, when repeated for k times, output the kth(1-index) value of the array.
For example, if the array is [1,11], the output should be a program that outputs 1, and when repeated twice, output 11. Code like print(end="1"); in Python 3 works: print(end="1"); prints 1 and print(end="1");print(end="1"); prints 11
Smallest sum of code lengths to solve all test cases win. Your meta code should solve 500 test cases in 60s, and each of your solution code should return in 10s. Meta code and solution code needn't be in the same language, but all solutions your meta-program generates should be in same language.
Pretest data and generator can be seen here. 7 days later will use the sum of submission time(e.g. 12:34 mean 1234) to be the random seed and generate another test case as the final test case.

The final seed is 7335 in GMT+8, so the final test data is here

What does "repeated for k times" means? NewSourceCode = repeat SourceCode k times? e.g. SourceCode = "ABC", k = 3, then NewSourceCode = "ABCABCABC"?

print(end="1"); repeated for 2 times is print(end="1");print(end="1");

What does "sum of code lengths" means? Should we submit more than one program?

You submit one program which generates 500 programs

So submit a program that generates a list of 500 programs where the first program outputs the first element of the input list, the second program is the first program repeated twice and outputs the second element of the list and so on?

@Emigna To my understanding, that's no different from LengthOfSingleSourceCode * 1275 ...

Will the programs our program generate have access to the input?

@Emigna I'm assuming not- why even bother with a generator if that's the case?

@Emigna No, for each list it generates a single program. Say that program is just x. Then x should give the first element of the list, xx should give the second element of the list, xxx should give the third, and so on.

500 programs because there are 500 test cases

It looks people are just generating code that indexes into the array written verbatim and counts up the index with each copy. This means the only role the array plays is to potentially be compressed into the code, which strikes me as a chameleon challenge.

I meant, e.g. for an array of length 1, they can directly output the number. That kind of optimization may appear? as I don't limit the generator length @xnor

That's an interesting thought, I hadn't considered special-casing small lengths. I still expect array compression to be a much bigger factor though.

I expect the winner will handle both special cases and general compression well.

Me too. Now how to move the comment into chat?

Will the input always be a non-empty list of integers in the range 1–100?

@Adám Not sure about 1 to 100, but the porbably of 1 is 15%, 2 is 12.75%, 3 is 10.8375% ... I don't know the max number in the possible seeds

Do we need to allow for modular indexing - i.e., if the array is length 5, and the code is repeated 7 times, do we still need to return the 2nd element?

@Sok no as print(end="1"); doesnt

@l4m2: Is this going to be scored?

Python 3, generates Stax
This uses a variety of strategies.  Most strategies only apply under certain conditions, but there's one fallback strategy that is always usable.  At the end, the smallest candidate program is selected.

from functools import reduce
from math import sqrt

symbols = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}"

def uncycle(arr):
    for size in range(1, len(arr)):
        if all(e == arr[i % size] for (i, e) in enumerate(arr)):
            return arr[:size]
    return arr

def constant(val):
    return "A" if val == 10 else str(val)

def shift(val):
    if not val: return ""
    return constant(abs(val)) + "+-"[val < 0]

def encode(a, offsetMode):
    result = "";
    if offsetMode:
        for i in range(len(a) - 1, 0, -1):
            a[i] -= a[i - 1]
    for i in range(len(a)):
        parts = []
        signBit = (a[i] < 0) * 2
        continuing = (offsetMode and i == len(a) - 1) * 1
        remain = abs(a[i])
        while remain > 22:
            parts.insert(0, remain % 46 * 2 + continuing);
            remain //= 46
            continuing = 1

        parts.insert(0, remain * 4 + signBit + continuing)
        result += "".join(symbols[p] for p in parts)

    return result

def cram(arr):
    flat = encode(arr, False)
    offset = encode(arr, True)
    return offset if len(offset) < len(flat) else flat;

def issquare(num):
    root = int(sqrt(num))
    return root * root == num

def isgeometric(arr):
    r = arr[0]
    return all(r ** (i + 1) == e for (i,e) in enumerate(arr))

def generateProgram(arr):
    candidates = []
    rotated = uncycle(arr)
    rotated = rotated[-1:] + rotated[:-1]

    deltas = [b - a for a,b in zip(arr, arr[1:])]

    # single constant strategy
    if len(arr) == 1:
        candidates.append(constant(arr[0]))

    # repeated constant
    elif len(set(arr)) == 1:
        num = arr[0]
        if num == 10: candidates.append("A")
        if num % 2 == 0: candidates.append(constant(num // 2) + "H")
        if issquare(num): candidates.append(str(int(sqrt(num))) + "J")
        candidates.append(constant(num - 1) +  "^")

    # repdigit
    if len(arr) == 2 and 10 < arr[1] == arr[0] * 11 < 100:
        candidates.append(str(arr[0]) + "p")

    # single digits
    if max(arr) < 10:
        candidates.append("".join(map(str, rotated)) + "E|X@")

    # max 10
    if max(arr) == 10 and rotated[0] != 1:
        candidates.append("".join(str(e - 1) for e in rotated) + "E|X@^")

    fns = [
        ("", lambda x: x),
        ("H", lambda x: 2 * x),
        ("^", lambda x: x + 1),
        ("J", lambda x: x * x),
        ("Hv", lambda x: 2 * x - 1),
        ("H^", lambda x: 2 * x + 1),
        ("^H", lambda x: 2 * x + 2),
        ("HJ", lambda x: 4 * x * x),
        ("JH", lambda x: 2 * x * x),
        (":T", lambda x: x * (x + 1) / 2),
        ("|F", lambda x: reduce(lambda a, b: a*b, range(1, x+1))),
        ("J^", lambda x: x * x + 1),
        ("^J", lambda x: x * x + 2 * x + 1),
    ]
    for (stax, fn) in fns:
        if all(fn(i + 1) == e for (i,e) in enumerate(arr)):
            candidates.append("|X" + stax)

    # fixed delta
    if len(set(deltas)) == 1:
        delta = deltas[0]
        start = arr[0] - delta
        if start == 0:
            candidates.append(shift(delta))
        if delta == 1:
            candidates.append("|X" + shift(start))
        elif delta == -1:
            candidates.append("|x" + shift(start))
        elif delta > 1:
            candidates.append("|X" + constant(delta) + "*" + shift(start))
        elif delta < -1:
            candidates.append("|x" + constant(-delta) + "*" + shift(start))

    # geometric series
    if isgeometric(arr):
        candidates.append(constant(arr[0]) + "*")

    # prefix
    if len(arr) == 2 and arr[1] // 10 == arr[0] < 10:
        candidates.append("." + str(arr[1]) + "|X(")

    # suffix
    if len(arr) == 2 and arr[0] % 10 == arr[1] < 10:
        candidates.append("." + "".join(map(str, arr)) + "|X)")

    # uncycled cram
    candidates.append('"' + cram(rotated) + '"!|X@')

    candidates.sort(key=len)
    return candidates[0]

while True:
    arr = eval(input())
    prog = generateProgram(arr)
    print(prog)

Try it online!
Update: Validation  It will be time consuming to execute each multiplicity of each program separately.  It's possible to run them all at the same time.  In order to do this, a small piece of code must be used.  It's responsible for a few things.

Do implicit output if any.  Normally, at the end of a stax program, the top of stack is printed if there has been no other output.  When running multiple programs in the same source file, this must be done explicitly.
Clear both stacks.
Reset registers.  For these programs only the x register is used.

This boilerplate should be applied after every individual program to be executed.
|d{P}{zP}?0XLd

For example, the input [5,2,7,3] produces the stax program 3527E|X@.  All four multiplicities can be tested at once.
3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@3527E|X@3527E|X@
|d{P}{zP}?0XLd

Try it online!
In this way, it's possible to test all the multiplicities of all the program in the same run, assuming nothing breaks.  It would probably be the largest stax program ever executed if all 500 are done.

final score 7862

Perl 5 -p, generates Perl 5 -p, overhead 19 17 13
-1 thanks to @Dom Hastings
The score for one input will be length of the input + 13. Can obviously be improved by generating self-decompressing programs for larger inputs, but I won't bother.
Give the input array separated by commas on one line on STDIN.
#!/usr/bin/perl -p
chomp;$_="}{\$_=($_)[\$%++]"

Try it online!
Run the output concatenated n times with no input (e.g. redirect from /dev/null)
Sample way to run it for input 2,6,4,7 and the resulting program repeated 4 times:
perl -p '}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]' < /dev/null

Try it online!
If you don't like the resulting program trying to read from STDIN use this version with overhead 17:
#!/usr/bin/perl -p
chomp;$_="1/!say+($_)[\$-++],"

Try it online!
Sample way to run it for input 2,6,4,7 and the resulting program repeated 4 times:
perl -E '1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],'

Try it online!
This version crashes after printing the required output

I'm not sure I quite get the scoring, but is this program 1 byte less: s/ /,/g;$_="die say+($_)[\$-++],"?

@DomHastings Indeed it does.

final score 17106

05AB1E, generates 05AB1E
¸»“"ÿ"#.g<“ƵƒçJ

Try it online!
The generated program for the input [5,17,7,13,2] is "5 17 7 13 2"#.g<è.
Test suite for [5,17,7,13,2]
The length of the generated program is len(input) + 5

To be clear, len(input) is not the count of integers, but the length of the string holding them all.  I misunderstood at first.

final score 14606

APL (Dyalog Unicode)
Anonymous prefix lambda. Returns a program body.
 {
     1=≢⍵:⍕⍵ ⍝ single element

     (2=≢⍵)∧(⍵[2]=11×⍵[1]):⍕⍵[1] ⍝ 2, 22 etc.

     1=≢∪⍵:'⊢',⍕⊃⍵ ⍝ all the same

     (⊢≡⊃×⍳∘≢)⍵:'+',⍕⊃⍵ ⍝ linear

     ((⌊=⊢)!⍣¯1⊢⊃⍵)∧(1∧.=1↓⍵):'!',⍕!⍣¯1⊃⍵ ⍝ factorial followed by all 1s

     (⍵[2]∧.=1↓⍵)∧(⍵[1]=10|2⊃⍵):(⍕⊃⍵),'⌈',(⊃⍕2⊃⍵) ⍝ b ab ab ab

     e←{∊⍉2 2⍴'+×',⍕¨⍵}¨⍸(⊃⍵)=∘.×⍨⍳10
     b←⍵∘≡¨e(({0::⍬ ⋄ ⍎⍵}¨,\)⍴∘⊂)¨⍨(≢⍵)
     ∨/b:⊃b/e

     Q←{'''',⍨⍵/⍨1+''''=⍵}
     (5∧.≤⍵)∧(≢⍕⍵)>6+(+/14=⍵)+≢⍵:'{⍺←⎕AV⍳⊃⋄1⌽⍺⊢⍵}''',Q ⎕AV[⍵] ⍝ string fallback

     (≢⍕⍵)>9+(+/5=⍵)+≢⍵:'{⍺←¯4+⎕AV⍳⊃⋄1⌽⍺⊢⍵}''',Q ⎕AV[4+⍵] ⍝ offset string fallback

     '{⍺←⊃⋄1⌽⍺⊢⍵}',⍕⍵ ⍝ fallback
 }

Try it online!
Methods
This explores various methods and returns the first usable one, eventually falling back to a universally applicable method.
Single element
If the list has only one element, it is returned as-is.
2, 22 etc.
A single digit can just be repeated to generate the number 11 times bigger,
All the same
We just return the rightmost (⊢) number.
Linear
f(n) = k×n sequences just insert a plus before the first term.
Factorial followed by all 1s
When the first number n=!m and subsequent numbers are 1, then !m is a solution because !m is n and m!m is 1 and !1 is 1.
b ab ab ab
Since all two-digit numbers are larger than all single-digit numbers, a running maximum, where the front of the first number is glued to the back of the second number, is a solution.
The three-line-code
Check whether any formula of the type +a×b is valid.
String fallback
Long sequences with no numbers under 5 (because 4 is a line break) can be encoded as characters of the SBCS.
Offset string fallback
If there are numbers under 5, we shift up by 9 to avoid those.
Fallback
Simple string concatenation of the string "{⍺←⊃⋄1⌽⍺⊢⍵}" and the stringified (⍕) input. E.g. [3,1,4] returns the program body {⍺←⊃⋄1⌽⍺⊢⍵}3 1 4.
The part in braces is an ambivalent function which means it can be either a prefix function or an infix function. Thus the leftmost instance of it will run in prefix mode, and all the others in infix mode. The difference between the modes is whether ⍺, signifying the left argument, has a value. If it doesn't then it will be assigned the function ⊃ (first).
Explanation of fallback method
{…} anonymous lambda:
 ⍺←⊃ If there is no left argument (⍺) assign the function ⊃ (first) to ⍺
 ⋄ then:
At this point, the following code means two different things depending on whether ⍺ is a list of numbers (infix call) or the function "first" (prefix call).
 If ⍺ is a list of numbers:
  ⍺⊢⍵ discard the left argument in favour of the right argument
  1⌽ rotate that one step left
 If ⍺ is the function "first":
  ⊢⍵ yield the right argument
  ⍺ pick the first element of that
  1⌽ rotate it one step (a no-op on a scalar)
Example run of fallback method
Executing 3 1 4's code, {⍺←⊃⋄1⌽⍺⊢⍵}3 1 4, assigns the "first" function to ⍺ and thus returns the first element; 3.
Executing {⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4 lets the rightmost lambda "capture" the left 3 1 4 as its left argument, so ⍺ has a value which is discarded in favour of 3 1 4 which is then rotated one step left and yields 1 4 3 as result. This is then used as sole argument to the leftmost lambda, where ⍺ becomes the "first" function, causing the result to be the first element; 1.
Executing {⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4 lets the rightmost lambda "capture" the middle 3 1 4 as its left argument which is then discarded in favour of the right argument, 3 1 4, which when rotated one step left is 1 4 3. This is then used as right argument of the middle lambda together with the leftmost 3 1 4 as left argument. The left argument is discarded for the right, which rotated one step left yields 4 3 1. This then becomes the sole argument of the leftmost lambda, so ⍺ becomes the "first function", returning the first element; 4.
Scoring
When it becomes time to test using actual data, use this test harness (linked populated with pretest data). The test cases go in the Input field, and the Output will be the total byte count of all 500 programs together. (It will also throw an error, but that's just because it afterwards tries to evaluate the Input as-is.)

final score 14028

Haskell, generates Haskell
main = interact $ ("main=print$("++) . (++"!!)$ -1\n +1--")

Try it online! For the first testcase [5,2,7,3,2,3,15,10,7,2,14,11,16,16,3,3,4,3,8,4] it produces the following program:
main=print$([5,2,7,3,2,3,15,10,7,2,14,11,16,16,3,3,4,3,8,4]!!)$ -1
 +1--

Try it once, doubled and trippled. This uses the same approach as my Haskell answer to I double the source, you double the output.
The length of each generated program is the length of the input list as string plus 25, thus the score for the currently available testcases is 12266 + 500 * 25 = 24766. This shows that the code to data ratio is basically equal, and I doubt it is possible to write small enough decompression code which will decreases the score. It might be possible if the lists where much larger.

Charcoal
´⎚´§´⪪⪫ＩＡ ”y¦ Ｌυ⊞υω

Try it online! Link is to verbose version of code. Explanation:
´⎚´§´⪪

Output the literal string ⎚§⪪.
⪫ＩＡ

Cast the input array to string, join with spaces, and print.
”y¦ Ｌυ⊞υω

Output the literal string ¦ Ｌυ⊞υω.
Output of for example 5,17,7,13,2 is ⎚§⪪5 17 7 13 2¦ Ｌυ⊞υω. Try it online! Explanation:
⎚

Clear the canvas, so that only the last output is visible.
§⪪5 17 7 13 2¦ Ｌυ

Take the length of the predefined list u. Use that to index into the list of integers that have been split on spaces and output the selected element.
⊞υω

Push a dummy variable to the predefined list u, so that the next copy will output the next element of the list.
Total output length = (length of all integers in all lists) + (number of integers in all lists) + (number of lists * 9) characters (SBCS).

Python 2, generates Python 2
import sys
a=`input()[::-1]`.replace(' ','')
sys.stdout.write('print%s[-open(__file__,"a").tell()/%s]#'%(a,len(a)+37))

Try it online!
For the input
[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]

the generated program is
print[29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10][-open(__file__,"a").tell()/98]#

which is 98 bytes.
Adapted from this solution in "I double the source, you double the output!".
Dammit, two shorter answers popped in before I finished writing this answer.

An extra newline is at the end, which makes it outputs for k times

The expected behavior is "A '\n' character is written at the end, unless the print statement ends with a comma." I don't know why TIO shows extra newline on stdout.

Changed print to sys.stdout.write to remove the trailing "something".

final score 30606

Java 8, generates Python 2
interface M{static void main(String[]a){int l=a[0].length();System.out.print("print"+a[0]+"[open(__file__,'a').tell()/"+(l+35+(l+"").length())+"]#");}}

Try it online.
I.e. [3,4,5,6,7] generates this Python 2 program:
print[3,4,5,6,7][open(__file__,'a').tell()/48]#

Try it online once; Try it online twice; Try it online three times.
Generated Python program is based on @Mr.Xcoder's answer for the Third time the charm challenge.
Explanation:
Java 8 code:
interface M{                    // Class
  static void main(String[]a){  //  Mandatory main-method
    int l=a[0].length();        //   The length of the first argument
                                //   (Note that this is the length of the input as String,
                                //   not the size of the array)
    System.out.print(           //   Print:
      "print"                   //    Literal "print"
      +a[0]                     //    Appended with the argument
      +"[open(__file__,'a').tell()/"
                                //    Appended with literal "[open(__file__,'a').tell()/"
      +                         //    Appended with an integer that is formed by:
       (l                       //     Getting the length we got earlier
       +35                      //     +34 for the rest of the Python 2 code + 1
       +(l+"").length())        //     + the length of the length (<10→1; 10-99→2; etc.)
       +"]#");}}                //    Appended with literal "]#"

Python 2 code:
print                        # Print
 [3,4,5,6,7]                 #  From this array
 [                           #   The `k`'th item,
  open(__file__,'a').tell()  #   where `k` is the length of its own source code
  /                          #   divided by
  48                         #   the length of its own source code (once) + 1
 ]#                          # With a trailing comment, so we can repeat the program

Python 2, Generates C++
This isn't going to beat any records, I was mainly interested in thinking about if I could figure out how to do it :) Use the fact that global variables are run before main, and so can increment a global variable, then using a #ifdef to ensure main is only defined once.
import sys
print("""#include <stdio.h>
#ifndef A
#define A
int v;
int d[]={""" + sys.argv[1] + """};
struct C{C(){v++;}};
int main(void){ printf("%d",d[v]); }
#else
C c1;
#endif
""")

Bash, outputs programs in Perl 5
Bash program can be called like script.sh 1,2,3.
Perl program should be called with the -E flag.
echo "shift@a;@a=($1)unless@a;END{say\$a[0];exec'true'}"

The generated perl code for an input of 4,7,8 is:
shift@a;@a=(4,7,8)unless@a;END{say$a[0];exec'true'}

Pretty brute force. Removes an element of the array (perl doesn't care that the array doesn't exist at first), sets it if it is not already set. It then echoes the first element of the array at the end. (The END block is run last). The exec 'true' quits the program, so that the further END blocks are not executed.
Example:
#Once
$ perl -E "$(bash script.sh 4,7,8)"
4

#Duplicated twice
$ perl -E "$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)"
7

#Duplicated thrice
$ perl -E "$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)"
8

final score 34106

Runic Enchantments, generates Runic
74akw94/85akw
R32B~~?US' Sqq1Ky1Ky
\i<{1[lil1-{S{)]{{1KyB
D'0$'´$$' $     Rl0) ?
R"{Zs$;|1|l;|y"@
"UwR'10<|I+}"$~ /' Su0
       Rakwc4akw/

Try it online!
Takes input as a space-separated list of values.
Output done once
Output done twice
Output done four times
Utilizes the continuous numerical read mode command, ´ that was committed on Jan 12 and I found this question on the 14th. This command allows arbitrary length values can be encoded as without this feature it would be very difficult to do so (e.g. 1392 would need to be represented as 1X3+X9+X2+, necessitating an additional loop at a minimum); precisely the problem I wanted to solve when I created the ´ command.
In the original code, the | in the strings "{Zs$;|1|l;|y" and "UwR'10<|I+}" are replaced with \n (which sit in the grid and not modify it, as they normally would) with write commands: 74akw, 94/Rakw, c4akw, and 85akw. The original characters can be literally anything. | was chosen to be a symbolic placeholder that visually represented what I wanted. Several bytes saved (if unscoring ones) by not having to reflectively add an entry point, as wR'10< writes an R into a location where one already exists (position 0,1), and then proceeds to fill its stack with junk before running out of mana, following a looping sequence U"'i34.
The resulting output code works by using the write command to change the first character on the second line to a Right redirection (so only one IP executes a print statement), with clever use of stack length resulting from taller and taller programs to determine which index to read. Every other IP changes that same location to the same instruction and terminates. Everything else goes unused.

Image is out of date, but sufficient for flow explanation.
Each execution of 1Iy maintains the IP's ability to handle a larger and larger stack (caused by the l command), the size of which allows the program to determine how many copies of the base source code there are. The final 1 is used to increment the previous l to the required number when rotating the stack (created next) in order to arrive at the correct value. The Z command negates this value so that the stack rotates in the correct direction.
The original input array is then encoded using continuous read mode, primed with a 0 to avoid incrementally modifying the same value, to read the original inputs. The space NOP is required to exit continuous read mode and allow the subsequent 0 to prime the stack again.
Score should equal approximately 3+v.toString().length, for each array entry v, +23 for each array. Approximately (2.55*total length of input) or 33837 for the sample input, if I did things right.
Minor changes were introduced into my expected final program due to side effects introduced in the same build regarding the s command, however it resulted in a better score at the same time.


text:
Self-Validating Triangular Checkerboard Program
A checkerboard program is a program where each individual character's ordinal value alternates from even to odd, excluding the line terminator (which can be any standard line-endings).
A triangular program is a program where each line has one additional character than the preceding line, with the first line having one character. You do not need to handle empty input.
Your task is to build a program that validates that the given input adheres to those criteria and outputs/returns something truthy if the program meets the criteria, or something falsy otherwise.
Your program must also meet these criteria.
Examples of valid programs
G
`e
@u^
5r{B

^
cB
+$C
VA01

Rules

Your program may start with either an odd or an even byte as long as the parity of the characters alternates.
Your program must validate programs that start with either an odd or an even character.
For unicode characters, the underlying byte values must have alternating parity.
You can assume that input only contains printable characters. If your program contains unprintables, it should still be able to validate itself.
Your program may include one trailing newline, this does not need to be allowed by your validation as you can assume this is removed prior to validating.
Standard loopholes are forbidden.
The shortest code in bytes, in each language, wins.

@MartinEnder Thank you for your input! Hopefully this is now clear. Related to this, should I have left this in the sandbox for longer?

is the even/odd alternating both horizontal and vertical ? I assume yes from "checkerboard", but I don't see where you say so.

@DomHastings A week seems fine. If you don't get any feedback after a few days, you can ask in chat if anyone has any more comments.

@TonHospel My original examples did this, but it contradicted with my description, so for this implementation, no, it should be:
E\nOE\nOEO. Hope that helps!

Can we assume that the input contains only printable characters?

@Laikoni Damn, that's a tough call. I'll assume yes for now and add a note to the Q, but I don't know how to validate any programs that would contain unprintables (since programs should self-validate). I don't know how likely that is.

"For unicode characters, the underlying byte values must have alternating parity".  Can we choose an encoding?  Otherwise, what do you consider to be the "underlying byte value" of a character?

@recursive I envisaged this as if a file is saved to disk, the bytes written would be alternative parity, for example î might be valid as it is made up of the bytes \xAE\xC3. Does that address the encoding issue too?

I understand the intention.  It's not clear to me how to interpret this rule in online environments like TIO, where inputs and outputs are strings, not byte streams AFAIK, but I suppose that's not the fault of the challenge.

@DomHastings Can you confirm that answers must validate inputs starting with a newline in all cases or only if the source code itself contains a leading newline ?

@Kaldo I originally wanted to support the flexible input for all programs, but I don't intend to add pointless complexity to the challenge. Perhaps this did indeed need a bit more of a push in the sandbox. What're your opinions?

My opinion: let answers assume input does not start or end with a newline.

@Lynn Done. Thanks for the feedback!

@Jakob I'm not sure what you mean? I'm happy to accept any reasonable truthy/fasly values as output! Hope that helps!

@DomHastings Actually never mind; this no longer applies to my solution.

Stax, 26 bytes
L
Y$
i:-
 {2%
*OFyF
%vi =*

Run test cases online
I had to introduce 3 junk characters. i is a no-op when outside all loop constructs.    is always a no-op.  O tucks a 1 under the top of the stack, but the value isn't used in the program.
LY      move input lines into a list and store in Y register
$       flatten
i       no-op
:-      get pairwise differences
{2%*OF  foreach delta, mod by 2, and multiply, then tuck a 1 under the top of stack
yF      foreach line in original input do...
  %v    subtract 1 from length of line
  i=    is equal to iteration index?
  *     multiply

Run this one

Hey, I hope this doesn't mess with your code too much, but you can drop the leading newline validation.

C (gcc), 189 bytes
j
;l
;b;
d;f␉
(char
␉*␉t)
{b=*␉t%
2;for␉(␉
j=d=0;j=j
+ 1,␉l=j+
1,␉*␉t; ) {
for␉(;l=l- 1
 ;t=t+ 1 )b=
!b␉,␉d=d+ !(␉*
␉t␉*␉(␉*␉t- 10)
*␉(␉*␉t%2-b) ) ;
d␉|=*␉t- 10;t=t+
1 ; }b= !d; } ␉ ␉

Try it online!
␉ represents a tab character (I'm sorry). Note that there are several trailing spaces/tabs (I'm more sorry). The original with tabs intact is best viewed in vim with :set tabstop=1 (words cannot express how sorry I am).
It's a function (called f, which isn't immediately obvious from glancing at it) that takes a string as an argument and returns either 0 or 1.
I could reduce this by at least one and probably two or more lines, but note that it gets increasingly messy and low-effort towards the end, mostly because writing such awful code (even by PPCG  standards) was making me feel like a bad person and I wanted to stop as soon as possible.
The basic idea here is to avoid constructions that necessarily break the format (++, +=, return, etc.). Miraculously, important keywords like for, char, and while (which I didn't end up using) happen to fit the alternating parity rule. Then I used spaces (even parity) and tabs (odd parity) as padding to make the rest fit the rules.

I did not expect to see a solution in C!

If you isolate the solution portion of the program in the TIO by putting other stuff in the "Header" and "Footer" sections it's easier for people to verify the byte count.

Haskell, 1080 1033 bytes
;
f=
 g
ij=f
a =hi
hi = g
hij= ij
g ' ' =0
g '"' =0;
 g '$' =0;
 g '&' =0-0
g '(' =0-0-0
g '*' =0-0-0;
 g ',' =0-0-0;
 g '.' =0-0-0-0
g '0' =0-0-0-0-0
g '2' =0-0-0-0-0;
 g '4' =0-0-0-0-0;
 g '6' =0; g '8' =0
g ':' =0; g '<' =0-0
g '>' =0; g '@' =0-0;
 g 'B' =0; g 'D' =0-0;
 g 'F' =0; g 'H' =0-0-0
g 'J' =0; g 'L' =0-0-0-0
g 'N' =0; g 'P' =0-0-0-0;
 g 'R' =0; g 'T' =0-0-0-0;
 g 'V' =0; g 'X' =0-0-0-0-0
g 'Z' =0; g '^' =0; g '`' =0
g 'b' =0; g 'd' =0; g 'f' =0;
 g 'h' =0; g 'j' =0; g 'l' =0;
 g 'n' =0; g 'p' =0; g 'r' =0-0
g 't' =0; g 'v' =0; g 'x' =0-0-0
g 'z' =0; g '\92' =0-0; g '|' =0;
 g '~' =0; g y = 1 ;z=0; i(-0)z=z;
 i m('\10':y ) ="y"; ; ; ; ; ; ; ;
i m(mnmnmnmnm:y ) = i(m - 1 ) y ; ;
i k m ="y"; ; k i [ ] =01<1010101010;
 k m('\10':y ) = k(m + 1 )(i m y ) ; ;
 k m y =01>10; m o = k 1$'\10':o ; ; ;
o i('\10':y ) = o i y ; ; ; ; ; ; ; ; ;
o i(k:y )|g k<i = o(1 - i ) y ; ; ; ; ; ;
 o i(k:y )|g k>i = o(1 - i ) y ; ; ; ; ; ;
 o i [ ] =01<10; o i y =01>10;v=01>10101010
s y|o 1 y = m y|o(-0) y = m y ; s y =v; ; ;

Try it online!
Explanation
This has been quite the interesting task for Haskell.
Parity
To start we need some way of determining if a character has an even or odd code-point.  The normal way one might do this is to get the code-point and mod it by 2.  However as one might be aware, getting the code-point of a character requires an import, which due to the source restriction means that it cannot be used.  A more experienced Haskeller would think to use recursion.  Char's are part of the Enum typeclass so we can get their predecessors and successors.  However pred and succ are also both unusable because they don't alternate byte parity.
So this leaves us pretty stuck we pretty much can't do any manipulation with chars.  The solution to this is to hardcode everything.  We can represent (most) even chars as literals, odds we have trouble with because ' is odd so it can't be next to the char itself making the literal impossible to express most of the odd chars.  So we hard code all of the even bytes, and then add a catch all for the odd bytes at the end.
The problem Bytes
You may notice that there are some even bytes for which literals cannot be made by wrapping it in single-quotes.  They are the unprintables, newlines and \.  We don't need to worry about unprintables since as long as we don't use any of them we don't need to verify.  In fact we can still use odd unprintables, like tab, I just don't end up needing to.  Newline can sagely be ignored because it will be trimmed from the program anyway.  (We could include newline, because it's code-point is rather convenient, but we don't need to). This leaves \, now \ has the codepoint 92, which conveniently is an odd number followed by an even number, so \92 alternates between evens and odds thus the literal '\92' is perfectly valid.  Later on when we do need to represent newline we will notice that it luckily has this same property '\10'.
Spacing problems
Now in order to start writing actual code we need to be able to put a sizable number of characters on a single line.  In order to do this I wrote the cap:
;
f=
 g
ij=f
a =hi
hi = g
hij= ij

The cap doesn't do anything except be valid Haskell.
I had initially hoped to make definitions that would help us in the code later, but it didn't.  There are also easier ways to make the cap, for example whitespace and semicolons, but they don't save bytes over this way so I haven't bothered to change it.
Hardcoder
So now that I have enough space on a line I start hardcoding values.  This is mostly pretty boring, but there are a few things of interest.  For one once the lines start getting even longer we can use ; to put multiple declarations on a line, which saves us a ton of bytes.
The second is that since we can't always start a line with a g every so often we have to indent the lines a bit.  Now Haskell really cares about indentation, so it will complain about this.  However if the last line before the indented line ends in a semicolon it will allow it.  Why?  I haven't the faintest, but it works.  So we just have to remember to put the semicolons on the end of the lines.
Function Building Blocks
Once the hardcoder is done it is smooth sailing to the end of the program.  We need to build a few simple functions.  First I build a version of drop, called i.  i is different from drop in that if we attempt to drop past the end of the string it just returns "y". i is different from drop also in that if it attempts to drop a newline it will return "y",  These will be useful because later when we are verifying that the program is a triangle this will allow us to return False when the last line is not complete, or when a line ends early.
Next we have k which in fact verifies that some string is triangular.  k is pretty simple, it takes a number \$n\$ and a string \$s\$.  If \$s\$ is empty it returns True.  If the string begins with a newline it removes the newline and \$n\$ characters from the front.  It then calls k again with \$n+1\$ and the new string.  If the string does not start with a newline it returns False.
We then make an alias for k, m. m is just k with 1 in the first argument, and a newline prepended to the second argument.
Next we have o.  o takes a number and a string.  It determines if the string bytes (ignoring newlines) alternate in parity (using our g) starting with the input number.
Lastly we have s which runs o with both 1 and 0, if either succeeds it defers to m.  If it fails both it just returns False.  This is the function we want.  It determines that the input is triangular and alternating.

A triangular string starts with a 1-character line, not an empty line.

@Jakob I think that's dumb but it was an easy enough fix.

05AB1E, 34 26 bytes
¶
¡D
©€g
´ā´Q
´sJÇÈ
¥Ä{´нP

Try it online!
Takes the input as a multiline string (input between """). Explanations to come later.

Unless I've misunderstood the rules, the program needs to be able to validate input starting with a newline as well.

@Emigna I think your program has to be able to validate a leading newline only if it itself starts with a leading newline.

I have no idea if this is correct (I am awful at reading specifications): Try it online!

@MagicOctopusUrn Your answer looks OK to me but I'm wondering about the input: are we allowed to take it as an array ? In your link, your first input is an empty space, not a newline char.

@MagicOctopusUrn: Depends on the code-page used. I would assume that both 05AB1E and unicode would be fine. Although if you use unicode you can't count all commands as 1 byte each. Both unicode and 05AB1E has 0 at 48 though.

@MagicOctopusUrn: Not for any encoding I know.

Hey, I hope this doesn't mess with your code too much, but you can drop the leading newline validation.

@DomHastings Thanks for specifying that :-)

Python 3 (3.4?), 350 bytes
A tricky challenge for a language as particular about whitespace as Python 3. The submission prints 0 or 1 to standard out and crashes for some inputs. The program expects the final line to be properly terminated, i.e. end with a newline character. The final line of the program is similarly terminated. UTF-8 is used to check byte parity.
Tabs are replaced with spaces in this view.
0
i\
= 1
t=(#
 '0'*
 0) ;(
g,) =(#
 open (1
, "w"),)
k = eval (
'p' + 'rin'
 + 't' ) #01
for  a in (#0
open ( 0) ):#0
#01010101010101
 a = a [:- 1 ] #
 if ( len (a )<i\
or len (a )>i ):[\
k('0' ),1 /0] #0101
 i, t= -~i, t+ a #01
(k( 2-len ({(c^i )&1\
 for  i,c in  eval (#0
 "enu"+"m"+"erate")(#01
 eval ( " byte"+"s")( t#
,' u8' ) ) } ) ) ) #01010

Works for me with Python 3.4.2; doesn't work on any Python 3 on TIO. Seems to me to be a bug in TIO's interpreters.
Hex Dump
Revert with xxd -p -r on Unix.

300a695c0a3d20310a743d28230a202730272a0a093029203b280a672c29
203d28230a206f70656e0928310a2c09227722292c29200a6b203d206576
616c09280a277027202b202772696e270a202b202774272029202330310a
666f7209206120696e092823300a6f70656e092809302920293a23300a23
30313031303130313031303130310a2061203d2061205b3a2d2031205d20
230a2069660928096c656e09286120293c695c0a6f72096c656e09286120
293e6920293a5b5c0a6b2827302720292c31202f305d2023303130310a20
692c09743d202d7e692c09742b2061202330310a286b2809322d6c656e09
287b28635e69202926315c0a09666f720920692c6320696e09206576616c
092823300a0922656e75222b226d222b2265726174652229282330310a20
6576616c092809220962797465222b22732229280974230a2c2720753827
20292029207d202920292029202330313031300a

Java 10, 209 bytes
A void lambda taking an iterable or array of byte. Indicates true by returning normally, false by throwing a runtime exception. The program expects the final line to be properly terminated, i.e. end with a newline character. The final line of the program is similarly terminated.
Everything is done under UTF-8, with the interpretation that "character" refers to Unicode code points.
Tabs are replaced with spaces in this view.
d
->
{
long
f= 1,
 h=0 ,
c = - 1
,e ;for
( byte a:
 d) {var b
=(e = a^10)
<1&e>- 1 ;f=
b?( h ^ f)> 0
?0/0 : f+ 1: f
;h=b?0 :a>-65 ?
h+ 1: h; c =b? c
:c>=0 & ( (c^a )&
1 )<1 ?0/0 :a ; }
/*1010101010101*/ }

Try It Online
Hex dump
Revert with xxd -p -r on Unix.

640a2d3e0a7b20090a6c6f6e670a663d20312c0a09683d30092c0a63203d
202d20310a2c65203b666f72090a28096279746520613a0a096429207b76
617209620a3d2865203d20615e3130290a3c3126653e2d2031203b663d0a
623f280968095e0966293e09300a3f302f30093a09662b20313a09660a3b
683d623f30093a613e2d3635203f0a682b20313a09683b2063203d623f20
630a3a633e3d30092609280928635e612029260a3120293c31203f302f30
093a61203b207d200a2f2a313031303130313031303130312a2f207d0a

Ungolfed
d -> {
    long f = 1, h = 0, c = ~h, e;
    for (byte a : d) {
        var b = (e = a^10) < 1 & e > -1;
        f = b ?
            (h^f) > 0 ? 0/0 : f + 1
            : f
        ;
        h = b ? 0 :
            a > -65 ? h + 1 : h
        ;
        c = b ? c :
            c >= 0 & ((c^a) & 1) < 1 ? 0/0 : a
        ;
    }
}

f is the expected number of characters on the current line, h is the number of characters seen so far on the current line, c is the last byte seen, and b is whether a is the newline.
The condition a > -65 tests whether a is the first byte in a character. This works because the single-byte (ASCII) characters are nonnegative in 8-bit two's complement, the first byte of longer characters has binary form 11xxxxxx (at least -64 in two's complement), and the non-leading bytes in those characters are of the form 10xxxxxx, at most -65 in two's complement. (Source)
When a character violates the triangular or checkerboard pattern (i.e. a newline appears early or late or a byte of the wrong parity appears), the left branch of the corresponding ternary (in assignment to f or c) activates and the method throws an arithmetic exception.