text:
Shortest Pangrammatic Window
A pangram is a sentence or excerpt which contains all twenty-six letters of the alphabet, as is demonstrated in this code golf challenge. However, a pangrammatic window is a pangram in the form of some segment of text, which may end or begin halfway through a word, found somewhere within a larger work. These naturally occur everywhere, being proper subsets of true pangrams, so just verifying if something contains a pangrammatic window would be boring and also it was previously done.
So, we're interested in finding the smallest one there is in a given piece of text based on its letter length! In the shortest possible code in bytes, of course, to fit the theme.
Rules and Guidelines

Receive a string as the input and return  the string of the smallest pangrammatic window in the input if there is one. If there is not, return either a Boolean False or an empty string.
Whether a string is a pangrammatic window or not is case-insensitive and only depends on the 26 letters, not any punctuation or numbers or other odd symbols.
Similarly, a pangrammatic window's letter length is the total number of how many appearances of letters occur in it alone, and not simply the number of every character. The returned value must be smallest based on this count. We're linguists, after all, not programmers.
An output of a pangrammatic window must, however, must be an exact substring of the input, containing the same capitalization and punctuation, etc.
If there are multiple shortest pangrammatic windows of the same letter length, return any one of them.

Test Cases
'This isn't a pangram.'
==> False

'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
==> 'Quick-Brown-Fox (the one who jumped over some lazy ig'

'"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
==> 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ'

"the total number of how many appearances of letters occur in it alone" can you clarify?

That was actually meant to be more clarified from the version of it I originally posted in the sandbox, but oh well. I mean the count of letters, a-z, A-Z, ignoring any other characters. So, 'Foot!' would have a letter length of 4.

For the last test case, why isn't The five boxing wizards jump quickly returned?

For the second case, are you allowed the space preceding the Q? It doesn't add to the letter count.

@muddyfish Because it has 31 letters, whereas the expected output has only 26.

Theoretically, yeah, you could leave the space before the 'Q.'

Nice first question!

In the same vein as Neil, is ' . "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ' acceptable for the last test case?

Yep. No reason it shouldn't be. Taking the "true" minimum's in the spirit of the question, but it's not necessary.

Pyth, 20 16 14 bytes
hol@GNf!-GrT0.:

Explanation:
             .: - substrings of input()
      f!-GrT0   - filter to ones which contain the alphabet
 ol@GN          - sort by number of alphabetical chars
h               - ^[0]

      f!-GrT0   - filter(lambda T:V, substrings)
          rT0   -    T.lower()
        -G      -   alphabet-^
       !        -  not ^

 o              - sort(^, lambda N:V)
   @GN          -   filter_presence(alphabet, N)
  l             -  len(^)

Try it here!
When there isn't a correct solution, the program exits with an error with no output to stdout.

You seem to not have updated the code in the first code block. Also !-GrT0 is shorter for the filter condition, I believe. I also think you do need the l to make the sort work properly.

Oh, I misspoke, I meant the link. In your link you still have the l, and without it you get different results. I believe the problem is repeated letters, but I'm not 100% sure.

So it does matter - and thanks for the optimization!

Pyth - 22 bytes
\o/ FGITW!
h+ol@GrNZf}GS{rTZ.:z)k

Test Suite.

JavaScript (ES6), 139 138 136 bytes
s=>[r=l="",...s].map((_,b,a)=>a.map((c,i)=>i>b&&(t+=c,z=parseInt(c,36))>9&&(v++,n+=!m[z],m[z]=n<26||l&&v>l||(r=t,l=v)),t=m=[],v=n=0))&&r

Saved 2 bytes thanks to @Neil!
Indented

var solution =

s=>
  [r=l="",...s].map((_,b,a)=> // b = index of start of window to check
    a.map((c,i)=>
      i>b&&(
        t+=c,
        z=parseInt(c,36)
      )>9&&(
        v++,
        n+=!m[z],
        m[z]=
          n<26||
          v>l&&l||(
            r=t,
            l=v
          )
      ),
      t=m=[],
      v=n=0
    )
  )
  &&r
<textarea cols="70" rows="6" id="input">Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).</textarea>
<button onclick="result.textContent=solution(input.value)">Go</button>

Can you not use [r=l="",...s].map((_,b,a)=>?

@Neil Thanks, I always forget about the third parameter in the map function.

I think @edc65 can beat this though, I merged the code for his exploded substrings with that for his pangram tester and ended up with a 134 byte function.

My best is 142 so far

Sadly I didn't think to save it and my PC crashed so now I don't know what I had; the best I can do now is 138 bytes.

Ruby, 100 bytes
Returns nil if no window is found.
->s{r=0..s.size
(r.map{|i|s[i,r.find{|j|(?a..?z).all?{|c|s[i,j]=~/#{c}/i}}||0]}-['']).min_by &:size}

PowerShell v2+, 218 bytes
param($a)$z=@{};(0..($b=$a.length-1)|%{($i=$_)..$b|%{-join$a[$i..$_]}})|%{$y=$_;$j=1;65..90|%{$j*=$y.ToUpper().IndexOf([char]$_)+1};if($j){$z[($y-replace'[^A-Za-z]').Length]=$y}}
($z.GetEnumerator()|sort Name)[0].Value

Yeah, so substring manipulation (there aren't any built-ins) isn't really PowerShell's strong suit...
We take input param($a) and set a new empty hashtable $z. This will be our storage of candidate pangrammatic substrings.
Using a slight modification of my code from Exploded Substrings, we construct all substrings of the input. Yep, even one-character punctuation-only substrings. This is code-golf, not fastest-code. ;-)
All of those substrings are encapsulated in parens and piped into another loop with |%{...}. We temporarily set $y to our current substring, set a helper counter $j, and start another loop 65..90|%{...}, conveniently over the ASCII char codes for capital letters. Each inner loop, we take $y, make it all uppercase, and pull out the .IndexOf that particular char. Since this will return -1 if not found, we +1 the result before multiplying it into $j. This ensures that if any one character isn't found, $j will equal zero.
Which is exactly what the if is all about. If $j is non-zero, that means that every letter was found at least once in the substring $y, so we need to add that to our candidate pool. We do so by taking $y and -replaceing every non-letter with nothing, which gets us the letter-length of that substring. We use that as the index into hashtable $z and store $y at that index. This has the quirk of overwriting substrings of the same letter-length with the one that occurs "furthest" in the original string, but that's allowed by the rules, since we're only concerned about letter-length.
Finally, we need to sort through $z and pull out the smallest. We have to use the .GetEnumerator call in order to sort on the objects inside $z, then sort those on Name (i.e., the length index from above), selecting the [0]th one (i.e., the shortest), and outputting its .Value (i.e., the substring). If no such substring fits, this will toss an error (Cannot index into a null array) when it tries to index into $z, and output nothing, which is falsey in PowerShell. (the third test case below has an explicit cast as [bool] to show this)
Test Cases
PS C:\Tools\Scripts> .\golfing\shortest-pangrammatic-window.ps1 '"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!"

PS C:\Tools\Scripts> .\golfing\shortest-pangrammatic-window.ps1 'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
Quick-Brown-Fox (the one who jumped over some lazy ig

PS C:\Tools\Scripts> [bool](.\golfing\shortest-pangrammatic-window.ps1 "This isn't a pangram.")
Cannot index into a null array.
At C:\Tools\Scripts\golfing\shortest-pangrammatic-window.ps1:2 char:1
+ ($z.GetEnumerator()|sort Name)[0].Value
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

False

Python 3, 171, 167, 163, 157, 149 bytes.
Saved 4 bytes thanks to DSM.
Saved 8 bytes thanks to RootTwo.
lambda x,r=range:min([x[i:j]for i in r(len(x))for j in r(len(x))if{*map(chr,r(65,91))}<={*x[i:j].upper()}]or' ',key=lambda y:sum(map(str.isalpha,y)))

Having to sort based on the number of letters is killing me.
Test cases:
assert f("This isn't a pangram.") == ' '
assert f("Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).") == ' Quick-Brown-Fox (the one who jumped over some lazy ig', f("Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).")
assert f('"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.') == '. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ', f('"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.')

Don't think .upper() is needed in the key function.

@RootTwo Oops, yup, you're right. Thanks.

Haskell, 180 bytes
This was hard, but really fun without imports.
l=['a'..'z']
u=['A'..'Z']
f&[]=[];f&x=x:f&f x
g#h=(.g).h.g
f x|v<-[y|y<-(tail&)=<<(init&x),and$zipWith((`elem`y)#(||))l u]=last$[]:[z|z<-v,all((length.filter(`elem`l++u))#(<=)$z)v]

Much less golfed:
lowerCase = ['a'..'z']
upperCase = ['A'..'Z']

f & x = takeWhile (not . null) $ iterate f x

(#) = flip on

subStrings x = (tail &) =<< (init & x)

pangram p = and $ zipWith ((`elem` p) # (||)) lowerCase upperCase

leqLetters x y = (length . filter (`elem` lowerCase ++ upperCase)) # (<=)

fewestLetters xs = [ x | x <- xs, all (leqLetters x) xs]

safeHead [] = ""
safeHead xs = head xs

f x = safeHead . fewestLetters . filter pangram . subStrings

Surprise, surprise: it's really slow.

Oracle SQL 11.2, 461 bytes
WITH s AS (SELECT SUBSTR(:1,LEVEL,1)c,LEVEL p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)),v(s,f,l)AS(SELECT c,p,p FROM s UNION ALL SELECT s||c,f,p FROM v,s WHERE p=l+1),c AS(SELECT CHR(96+LEVEL)c FROM DUAL CONNECT BY LEVEL<27),a AS(SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1) a FROM c)SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))FROM(SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c)))x FROM v,c GROUP BY s,f),a WHERE x=26;

Un-golfed
WITH s AS (SELECT SUBSTR(:1,LEVEL,1)c,LEVEL p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))
,v(s,f,l) AS
(
  SELECT c,p,p FROM s
  UNION ALL
  SELECT s||c,f,p FROM v,s WHERE p=l+1
)
,c AS(SELECT CHR(96+LEVEL)c FROM DUAL CONNECT BY LEVEL<27)
,a AS(SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1) a FROM c)
SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))
FROM(SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c)))x FROM v,c GROUP BY s,f),a
WHERE x=26

The s view splits the input in characters and also returns the position of each character.
The recursive view v returns every substring of the input
  s is the substring
  f the position of the first character of the substring
  l the position of the last character added to the current substring
The c view returns the alphabet, one letter at a time
The a view returns the alphabet concatenated as a single string
SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c))
  Returns for each substring the number of distinct letters present in it
INSTR returns the pos of a letter in the substring, 0 if not present
SIGN returns 1 if pos > 0, 0 if pos = 0
WHERE x=26
  Filters the substring containing the whole alphabet
TRANSLATE(LOWER(s),' '||a,' ')
  Deletes every letter from the substring
LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')
  Length in letters is the length of the substring minus the length of the subtring without letters
SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))
  Keeps only the substring with the smaller letter count.
  If there is more than one, the first one, sorted as strings ascending, is kept

PowerShell (v4), 198 156 bytes
param($s)
-join(@(1..($y=$s.Length)|%{$w=$_
0..$y|%{(,@($s[$_..($_+$w)]))}}|?{($_-match'[a-z]'|sort -U).Count-eq26}|sort -Pr {($_-match'[a-z]').count})[0])

# Previous 198 byte golf
$a,$b,$c=@(1..($s="$args").Length|%{$w=$_
0..($s.Length-$w)|%{if((($t=$s[$_..($_+$w)]-match'[a-z]')|sort -u).Count-eq26){(,@($t.Length,$_,$w))}}}|sort -pr{$_[0]})[0]
(-join($s[$b..($b+$c)]),'')[!$a]

Test Cases
PS C:\> .\PangramWindow.ps1 "This isn't a pangram."

PS C:\> .\PangramWindow.ps1 'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
Quick-Brown-Fox (the one who jumped over some lazy ig

PS C:\> .\PangramWindow.ps1 '"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!

Ungolfed explanation of the original
It's a brute-force nested loop which makes sliding windows of all sizes:
.SubString(0, 1) -> slide window over the string
.SubString(0, 2) -> slide window over the string
..
.SubString(0, string.Length) -> slide window over the string

For each window, it filters for only letters (case insensitive regex matching by default), runs the remaining characters through a unique filter, checks if there are 26 unique characters as the pangram test.
All windows with pangrams are turned into triplets of (number of letters including dupes, start index, window length including punctuation), which get sorted to find the shortest by overall character count, the first one is picked, and the output string built from that.
There's a lot of indexing outside the bounds of the string, which PowerShell usefully returns $null for, instead of throwing exceptions.
NB. the new 156 byte one is the same approach, but rewritten to use the pipeline a lot more.
$string = "$args"

# increasing window widths, outer loop
$allPangramWindows =  foreach ($windowWidth in 1..$string.Length) {

    # sliding windows over string, inner loop
    0..($string.Length - $windowWidth) | ForEach {

        # slice window out of string, returns a char array
        $tmp = $string[$_..($_+$windowWidth)]

        # filter the char array to drop not-letters
        $tmp = $tmp -match '[a-z]'

        # Drop duplicate letters
        $tmpNoDupes = $tmp | sort -Unique

        # If we're left with a 26 character array, this is a pangrammatic window. Output
        # a PowerShell-style tuple of count of letters, start index, width.
        if($tmpNoDupes.Count -eq 26){
            (,@($tmp.Length,$_,$windowWidth))
        }
    }
}

# Force the result into an array (to handle no-results), sort it
# by the first element (num of letters in the window, total)
$allPangramWindows = @( $allPangramWindows | sort -Property {$_[0]} )

# take element 0, a window with the fewest letters
$windowCharCount, $windowStart, $WindowEnd = $allPangramWindows[0]

# uses the results to find the original string with punctuation and whitespace
if ($windowLen) {
    $string[$windowStart..($windowStart + $windowLen)] -join ''
}

NB. not sure the ungolfed version works, because I didn't write that then golf it, it's just for exposition.

Julia, 111,110,108 96 bytes
!S=minimum(['A':'Z'⊆(r=S[i:j])|>uppercase ? sum(isletter,r) : Inf,r]
for i=(k=keys(S)),j=k)[2]

Attempt This Online!

credits to @MarcMush: 96 bytes
my first attack: 108 bytes

It returns "" for falsy cases; very ineffective (both for time and for memory); it does not optimize for window size/length - only the letter length is considered

96 bytes

Haskell, 123 bytes
import Data.Lists
import Data.Char
h x=take 1$sortOn((1<$).filter isAlpha)[e|e<-powerslice x,['a'..'z']\\map toLower e==""]

Defines a function h, which returns the empty list if there's no pangrammatic window or a one element list with the minimum window.  Usage example:
*Main>  h "'The five boxing wizards jump quickly.' stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!' he shouted to the heavens."
[". 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ"]

How it works:
          [e|e<-powerslice x                  ]  -- for all continuous subsequences
                                                 -- e of the input
                ,['a'..'z']\\map toLower e==""   -- keep those where the list
                                                 -- difference with all letters is
                                                 -- empty, i.e. every letter appears
                                                 -- at least once
    sortOn((1<$).filter isAlpha)                 -- sort all remaining lists on
                                                 -- their length after removing all
                                                 -- non-letters -> (1<$) see below
take 1                                           -- take the first, i.e. the minimum

calculating the length of a list: we're not interested in the length itself, but
in the relative order of the length. (1<$) replaces each element in a list with
the number 1, e.g. "abc" -> "111", "abcd" -> "1111", etc. Such '1'-strings have
the same order as the length of the original list. One byte saved!

05AB1E, 13 bytes
ŒʒlêAå}éΣág}н

Try it online or verify all test cases.
Or alternatively with just a sort-by without filter:
ŒéΣláDêAQig]н

Try it online or verify all test cases.
Both output an empty string as falsey. (Could have been 12 bytes if we would be allowed to output -1 as falsey with ŒéΣág}.ΔlêAå.)
Explanation:
Œ       # Get all substrings of the (implicit) input-string
 ʒ      # Filter this list by:
  l     #  Convert the current substring to lowercase
   ê    #  Uniquify and sort all characters in the string
    A   #  Push "abcdefghijklmnopqrstuvwxyz"
     å  #  Check if the lowercase alphabet is in the uniquify-sorted substring
 }é     # After the filter: sort any remaining substrings from shortest to longest
   Σ    # Then sort it again by:
    á   #  Leave just all the letters of the substring
     g  #  Pop and push the length for the amount of letters
   }н   # After the sort-by: pop and leave just the first
        # (or an empty string if the list is empty)
        # (which is output implicitly as result)

Œ           # Get all substrings of the (implicit) input-string
 é          # Sort them by length (shortest to longest)
  Σ         # Then sort it again by:
   l        #  Convert the current substring to lowercase
    á       #  Leave just all the letters of the substring
     D      #  Duplicate it
      ê     #  Uniquify and sort all characters in the letters in the string
       AQi  #  Pop, and if it's equal to the lowercase alphabet:
          g #   Pop and push the length for the amount of letters
  ]         # Close both the if-statement and sort-by
            # (note, integers are always sorted before strings, even if there are
            # digits in the input-string)
   н        # Pop and leave just the first result
            # (or an empty string if the list is empty)
            # (which is output implicitly as result)


text:
Compress your code in an image
This is a quine variation.
Introduction
We all write short code, because some obscure reasons, but whatever we do, the'll take up at least 144 pixels/byte (with a 12px font). But what would happen, if we would encode our code in images? This is your task today.
Challenge
You task is to read in your own source code (non-proper quines are allowed, e.g. literally reading the source file), and create an image out of it, by setting the red, green and blue components of a pixel based on the ASCII value of the character.
Example:
We have the string "Hello world!"
Hello world!

Let's convert this to ASCII values:
72 101 108 108 111 32 119 111 114 108 100 33

Map the RGB values to it (If the source code's length is not divisible by 3, use 0s as the remaining characters):
 __________________________________________________
| R | G | B || R | G | B || R | G | B || R | G | B |
----------------------------------------------------
|72 |101|108||108|111|32 ||119|111|114||108|100|33 |
----------------------------------------------------

We then create the image with the smallest area out of it. We have 4 sets of RGB values, so the smallest image will be a 2*2 image, going from the top left pixel to the right:

And we get this awfully colored image (resized, so it's at least visible, also proves the fact how small it can get)
Rules/Additional information

There's no input
The output should be as a separate file, or in a separate window.
For multibyte characters, split the character in 2 bytes.
The source code must be at least 1 byte long
The image should be the one from the possible sizes, wich has the closest width/height ratio to 1
The pixel count on the image should exactly be ceil(byte count / 3), no extra pixels should be added

Scoring
This is a code-golf, so the smallest answer in bytes wins.

Waiting for a Piet submission... :P

What is "the smallest image"? Smallest area? Wouldn't this always be a straight line? Does the image have to be square? If so, how do we pad pixels that don't fit in the square? Could you provide some sample solutions? (Not necessarily with source code, just any string)

@DrGreenEggsandHamDJ Added an extra rule

Still not super clear. Which is more important, smallest area, or smallest width to heighth ratio? What if it was three, or any other prime number of pixels? Should I do 1x3 (smallest area) or 2x2 with a pixel missing (smallest ratio)? What should that missing pixel be?

Was this on the sandbox? It seems like it could've used some time there.

Isn't the smallest width/height ratio technically going to always be height = N and width = 1? I think you mean width/height closest to 1.

@Suever added that too

Well, the ambiguity is gone, my only thought is that it's a little bit of a chameleon challenge. The challenge is about encoding ASCII into an image, but now we also have worry about finding which set of factors is closest together. You don't have to change it, just something to think about for your next challenge.

@DrGreenEggsAndHamDJ I know, but as that part is hard-codable, I didn't thought it will be a problem.

ceil(byte count / 3) - ceil or byte length have to be divadable by 3?

@Suever I think I stated that

@Qwertiy No, it doesn't

@EᴀsᴛᴇʀʟʏIʀᴋ It's inspired by piet.

The bit about multibyte characters could be better stated as "use the raw bytes of your program's source code in the code's text encoding". Specifying 2 bytes doesn't cover the characters in UTF-8 that span 3 or 4 bytes.

Why not allow the image file contents to be printed to stdout?

@Mego Because that's not what I originally wanted

That would be the same as "print out the ascii values of your code"

@Bálint And saving it to a file is different somehow?

@Mego Then you actually need to construct an image.

@Bálint Submissions can still "construct an image" without needing to save it to a file or display it - outputting the image file contents to STDOUT is accepted by default. You override this default for no good reason. Additionally, the existence of the PPM (P6) image file format completely trivializes this challenge - a solution must simply prepend the image header P6 W H 255 to its own source code.

@Bálint Why is the Actually answer still accepted when it fails to fulfil one of your requirements? The output should be as a separate file, or in a separate window.

Actually, 12 bytes
Q"P6 4 1 255

Try it online!
This program also works in Seriously.
This program outputs a PPM image, which is acceptable by default.
Output image (scaled up 50x):

Explanation:
Q"P6 4 1 255
Q             push source code
 "P6 4 1 255  push header for a 4x1 raw (type P6) 8-bit PPM image (the closing " is implicitly added at EOF)

OP: The output should be as a separate file. Doesn't this just output the file contents to STDOUT?

MATLAB, 81 72 69 bytes
@()image(shiftdim(reshape(evalin('base','char(ans)'),3,1,23)/255,1.))

This creates an anonymous function which can be pasted into the command window and run using ans(). When run this creates a 23-pixel image (a prime) therefore the most square representation is a simple array of pixels.

Explanation
When pasted into the command window, the anonymous function will automatically assign itself to the variable ans. Then from within the anonymous function, we use:
evalin('base', 'char(ans)')

which evaluates char(ans) within the namespace of the command window rather than within the local namespace of the anonymous function. It is therefore able to convert the anonymous function itself into a string representation.
Then we have the following operations which are more straightforward:
%// Reshape the result into a 3 x 1 x 23 matrix where the first dimension is RGB
%// due to column-major ordering of MATLAB
R = reshape(string, 3, 1, 23);

%// Divide the result by 255. This implicitly converts the char to a double
%// and in order for RGB interpreted properly by MATLAB, doubles must be
%// normalized between 0 and 1.
R = R / 255;

%// Shift the dimensions to the left 1 to move the RGB channel values into
%// the third dimension. Note the extra decimal point. This is because it
%// is far shorter to lengthen the code by one byte than to pad the string
%// to give us a length divisible by 3
R = shiftdim(R, 1.);

%// Display the RGB image
image(R);

+1 for the ans idea!

Doesn't this have to be run twice to work? The first time around, I would expect it to create an image based on the value ans has until the first run is completed, which results in ans becoming the function itself. The second time around, it is using "its own" code (well actually, it is the code of a separate but identical anonymous function). That being said, I don't know MATLAB, so I may be wrong.

@Nᴮᶻ That's the beauty of using evalin to call char(ans) in the base workspace. The evalin is only evaluated at run-time so even though ans isn't defined when you paste it into the command window, when you call ans() to run this anonymous function, ans is defined and the evalin call inside the anonymous function can access it. So you do not have to run it twice. If I could rely on it being run twice, evalin('base', 'char(ans)') would be replaced by simply char(ans)

Javascript(ES6) 324 312 309 Bytes
I'm sure this could be golfed a bit:
f=()=>{s="f="+f;l=s.length/3;c=document.createElement('canvas');for(i=0;++i<l/i;l%i?0:w=i,h=l/w);c.s=c.setAttribute;c.s("width",w);c.s("height",h);(i=(t=c.getContext('2d')).createImageData(w,h)).data.map((a,b)=>i.data[b]=b%4<3?s.charCodeAt(b-~~(b/4)):255);t.putImageData(i,0,0);open(c.toDataURL('image/png'))}

creates a canvas
builds image in it
Opens data url for image in new tab

New lines for readability:
f=()=>{
    s="f="+f;l=s.length/3;
    c=document.createElement('canvas');
    for(i=0;++i<l/i;l%i?0:w=i,h=l/w);
    c.s=c.setAttribute;
    c.s("width",w);
    c.s("height",h);
    (i=(t=c.getContext('2d')).createImageData(w,h)).data.map((a,b)=>i.data[b]=b%4<3?s.charCodeAt(b-~~(b/4)):255);
    t.putImageData(i,0,0);
    open(c.toDataURL('image/png'))
}

Output

As I didn't specified it, you don't need to make it auto run.

Also, just insert a dummy variable instead of using empty paragraphs

Empty paragraphs? Where?

f=()=>{ Here, just do f=_=>, -1 byte, just don't use it, javascript is loosely typed

Ah parameters, current leaving the parens is cheaper than handling not evenly divisible by 3

I think, you don't need to specify the width and height, if you create the image data the right size, then it resizes it.

Creates a large(300x150) empty canvas for me

Javascript ES6 - 216 bytes
f=(  )=>((d=(x=(v=document.createElement`canvas`).getContext`2d`).createImageData(v.width=9,v.height=8)).data.set([..."f="+f].reduce((p,c,i)=>(c=c.charCodeAt(0),[...p,...i%3<2?[c]:[c,255]]))),x.putImageData(d,0,0),v)

Ungolfed:
f=(  )=>(                                           // define function f (extra spaces to account for missing pixel + alpha channel calculation)
 (d=(x=(v=document.createElement`canvas`).          // assign html5 canvas to v
          getContext`2d`).                          // assign graphics context to x
          createImageData(v.width=9,v.height=8)).   // create & assign ImageData to d
                                                    //   set width and height of both d and v
 data.set([..."f="+f].                              // get f's source, convert to array of chars
   reduce((p,c,i)=>(c=c.charCodeAt(0),              // convert char array to int array
                    [...p,...i%3<2?[c]:[c,255]]))), // insert alpha values 255
 x.putImageData(d,0,0),                             // draw source RGBA array to canvas
 v)                                                 // return canvas

Note: f returns a canvas.
Example run (assumes there's a <body> to append to):
document.body.appendChild(f())

Should dump the following image to the page (enlarged):

The last pixel is completely empty, can you make it, so it is 71 pixels in total?

@Bálint Whoops, didn't see the empty pixel part. Interestingly enough, if I try to make the image 71x1, that increases my byte count to 214 and incidentally, the pixel count to 72, which is 9x8, which in turn brings the byte count back to 213. It also ruins the alpha channel calculation. The current cleanest solution that meets all the reqs is to add 3 redundant chars to the solution...

PowerShell v4, 64 bytes
"P6 11 2 255"+[char[]](gc $MyInvocation.MyCommand.Name)|sc a.ppm

It gets the content of its own filename, casts the string as a char array, adds some PPM header and sets the content to a.ppm as output. 64 bytes makes it 11x2 pixels:

Node.js, 63 bytes
(F=x=>require('fs').writeFile('P6','P6 7 3 255 (F='+F+')()'))()

Outputs image into a file named P6 which is in the PPM (P6) format.
Here's a PNG rendition (7x3 pixels):

PHP, 226 bytes
Golfed
<?$b=strlen($w=join(file('p.php')));$z=imagecreatetruecolor(5,15);for($c--;++$c<$b+1|$i%3;$i%3?:$a=!imagesetpixel($z,$x%5,(int)$x++/5,$a))$a+=($c<$b?ord($w[$c]):0)*256**(2-$i++%3);header("Content-Type:image/png");imagepng($z);

Ungolfed version
<?
// Read the file into an array and join it together. Store the length of the resulting string.
$b=strlen($w=join(file('p.php')));

// Create the image. Our file is 226 bytes, 226/3 = 75 = 5 * 15
$z=imagecreatetruecolor(5,15);

// Loop through the script string, converting each character into a pixel.
// Once three characters have been converted, draw the pixel with the converted RGB value and reset the color to 0.
for($c--;++$c<$b+1|$i%3;$i%3?:$a=!imagesetpixel($z,$x%5,(int)$x++/5,$a))$a+=($c<$b?ord($w[$c]):0)*256**(2-$i++%3);

// Tell the program we're sending an image
header("Content-Type:image/png");

// And send it!
imagepng($z);

Enter this script into a file named 'p.php' and run it. You need your own method of running PHP script, because this reads from a local file.
Output image:

Java 511 chars
The length of the solution leads to a greater picture which is cool, because these pictures are really nice.
import java.awt.image.*;import java.io.*;import java.nio.file.*;import javax.imageio.*; public class Q{public static void main(String[]a)throws Throwable{int w=19,h=9;byte[]e=Files.readAllBytes(Paths.get("Q.java"));String t=new String(e);while(t.length()%3!=0)t+='\0';BufferedImage I=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);int r,c=r=0;for(int i=0;i<t.length();i++){I.setRGB(c,r,255<<24|t.charAt(i)<< 16|t.charAt(++i)<< 8|t.charAt(++i));if(++c==w){c=0;r++;}}ImageIO.write(I,"png",new File("Q.png"));}}

Note that there is an invisible trailing newline! It reads the source file, which has to be "Q.java" and creates a picture "Q.png" which looks like this:

or scaled 100x

APL (Dyalog), 33 bytes
Requires ⎕IO←0 which is default on many systems. Also, AutoFormat should be off to preserve the program exactly as given.
(⊂⎕NPUT⊃)'P',⍕⎕AV⍳'␍ɫ␉⍣',⊃⌽⎕NR'f'

Hex B9 BA FD 4E 50 55 54 BB F8 0D 50 0D C2 CD FD 41 56 B2 0D 03 0B 01 FF 0D C2 BB C8 FD 4E 52 0D 16 0D
Unicode 28 2282 2395 4E 50 55 54 2283 29 27 50 27 2C 2355 2395 41 56 2373 27 0D 026B 08 2363 27 2C 2283 233D 2395 4E 52 27 66 27
Creates P:
P3 11 1 255 185 186 253 78 80 85 84 187 248 13 80 13 194 205 253 65 86 178 13 3 11 1 255 13 194 187 200 253 78 82 13 22 13
Which you save and drop here to see:
⎕NR'f' Nested Representation of the program f
⊃⌽ pick the last (lit. first of the reversed) element (line)
'␍ɫ␉⍣', prepend the four characters (filetype, width, height, max)
⎕AV⍳ find corresponding indices in the Atomic Vector (the character set
⍕ format as text
'P', prepend a letter
(…) apply the following tacit function:
 ⊂ take the entire argument [and into a]
 ⎕NPUT Native [file,] Put [it, with a filename consisting of]
 ⊃ the first character ("P")

What codepage does this assume?

@Bálint See edit.

How come the resulting image is 42 pixels instead of 14? Is this because your "bytes" correspond to multi-byte characters?

@Suever Fixed. Thanks.

BTW, I think, if the version had a compiler before the challenge, then it is a legal one.

@Bálint I looked up on Meta. You're right. Editing...

Processing, 193 bytes
byte a[]=loadBytes("s.pde");noStroke();int x=0,y=0;for(int k=0;k<a.length%3;k++){append(a,byte(0));}for(int i=0;i<a.length-2;i+=3,x++){if(x>0){x=0;y+=1;}fill(a[i],a[i+1],a[i+2]);rect(x,y,1,1);}

Original

Resized

Even with Processing's builtins, this was very difficult.

Python, 81 bytes
q=open(__file__).read()
print'P3\n9 3 256 '+' '.join(map(lambda x:str(ord(x)),q))

Output is in PPM format.
This is what the image looks like:

Scaled up:

I don't see you reusing q

If you use the P6 format, you don't need to convert to ordinals. Additionally, for 8-bit RGB, 255 should be used instead of 256.

If you only use q once, as it seems you do, get rid of the assignment and substitute it directly -- it'll save you three bytes.

It looks like you print the file content, but OP said The output should be as a separate file.

Hello, @QPaysTaxes said print'P3\n9 3 256 '+' '.join(map(lambda x:str(ord(x)),open(__file__).read())). It's -4 bytes, tho!

@Adám or in a window, but yes, you are correct.

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:
How to find the item in a list whose f(item) is the smallest?
I have a list, l and a function f. f is not strictly increasing or decreasing. How can I find the item in the list whose f(item) is the smallest? For example, let's say the list is:
l = [1, 2, 3, 4]

and list(f(x)for x in l) is:
[2, 9, 0, 3]

f(3) is smaller than f of any of the other ones, so it should print "3". What's the shortest way to do this? I initially tried:
min(f(x) for x in l)

But this gives 0, not 3. If I was shooting for readability, not brevity, I would do:
index = 0
smallest = f(l[0])
for i in range(len(l)):
    value = f(l[i])
    if value < smallest:
        smallest = value
        index = i

This is fine, but horrendous for code-golf. Even if it was golfed
i,s=0,f(l[0])
for x in range(len(l)):
 v=f(l[x])
 if v<s:s,i=v,x

This is a bad solution. The shortest solution I can think of is:
g=[f(x)for x in l];print(l[g.index(min(g))])

(44 bytes) How can I golf this down further?

Just min(l,key=f).

@vaultah Post that as an answer.

@vaultah Wow. That is embarrassingly simple. I feel like an idiot now. Thanks! If you post that, I'd accept it.

This kind of question isn't for code golf, but for stackoverflow or some other subsection of stackexchange. Voting to close as off-topic

@KevinLau-notKenny This is a [tag:tips] question. That is on-topic.

@trichoplax actually I think it's this one: http://meta.codegolf.stackexchange.com/a/1724/31625

@FryAmTheEggman you're right - I just reread the title... Thanks :)

@DrGreenEggsandHamDJ the fact that an elegant solution comes along doesn't change that it's a good question...

Does the answer have to be in Python?

@Nᴮᶻ In general for code-golf, no. However, this isn't a code-golf question, but a [tag:tips] question (about code-golf).

@DrGreenEggsandHamDJ Still doesn't hurt, does it? ;-)

This is an interesting topic. Perhaps make it general, not limited to Python? It may be interesting to see how to do that in different languages

Use key property of min
As @vaultah said, use min(l,key=f). min(l,key=f) takes the minimum of f(i) for i in l.
It is also possible to apply this to max, and sorted. For example, max(l,key=f) is the maximum of f(i) for i in l. For sorted, the usage would be: sorted(l,key=f).

I'm accepting this for now, but will accept an answer from @vaultah if he posts it.

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


text:
Grow a Treemote!
This is my friend Thomas. He is half tree, half emoticon.
|    |
| :D |
|    |

He is lonely. Let's make him some friends!

Given a text-based emoticon as input (e.g. ಠ_ಠ, :P, >_>, not , , or ), output the corresponding treemote.
A treemote's length is how many characters it is lon (basically most builtin length functions for strings). So ಠ_ಠ has length 3.
The syntax for a treemote of length n is as follows:
|< 2+n spaces>| * ceil(n/2)
| <emote> | (note the spaces)
|< 2+n spaces>| * ceil(n/2)

So any treemote of length 3 would look like:
|     |
|     |
| ಠ_ಠ |
|     |
|     |

He has ceil(n/2) newline separated trunk segments on either side, each with 2 + n spaces inside.
Challenge: Given the text-based emoticon, output the corresponding treemote.

Other rules:

This is code-golf, which means I want you to write short code.
Standard loopholes disallowed.
You must support non-ascii characters unless your language can't handle them.

Test Cases:
^_^

|     |
|     |
| ^_^ |
|     |
|     |

\o/

|     |
|     |
| \o/ |
|     |
|     |

(✿◠‿◠)

|        |
|        |
|        |
| (✿◠‿◠) |
|        |
|        |
|        |

D:

|    |
| D: |
|    |

( ͡° ͜ʖ ͡°)

|             |
|             |
|             |
|             |
|             |
|             |
| ( ͡° ͜ʖ ͡°) |
|             |
|             |
|             |
|             |
|             |
|             |

Are trailing newlines allowed?

We assume 1-char emoticons do not exist?

By "text-based emoticon" do you mean ascii emoticon?

@Downgoat no. See the ಠ_ಠ test case.

@Nᴮᶻ no, you need to deal with 1 char emoticons.  Unless you have a really good reason, if so ask me in chat.

@R.Kap yes, trailing newlines are fine.

Maybe add a test case with a length other than 3...

@SuperJedi224 added more test cases.

is actually a character (4 bytes).

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ yes, but it still won't appear. And nice small caps btw.

05AB1E, 27 25 bytes
Code:
g©Ìð×"|ÿ|
"®;î×©„| Â¹s¶®J

Explanation:
g                  # Push the length of the input string.
 ©                 # Copy that to the register.
  Ì                # Increment by 2.
   ð×              # Multiply by spaces.
     "|ÿ|\n"       # ÿ is used for interpolation and push the string "|spaces|\n".
                   #
 ®                 # Retrieve the value from the register.
  ;î               # Divide by 2 and round up.
    ×              # Multiply that by "|spaces|".
     ©             # Copy this into the register.
      „|           # Push the string "| ".
         Â         # Bifurcate, pushing the string and the string reversed.
          ¹s       # Push input and swap.
            ¶      # Push a newline character.
             ®J    # Retrieve the value from the register and join everything in the stack.
                   # Implicitly output this.

Uses CP-1252 encoding. Try it online!.

Inputting ( ͡° ͜ʖ ͡°) returns funny results.

@ShaunWild Yeah, it's a weird test case, because ( ͡° ͜ʖ ͡°) itself is 11 characters long, but it looks 8 characters long.

Python 3.5, 76 75 73 bytes:
(Thanks to Blue for a tip which saved 2 bytes!)
def i(n):q=len(n);z=('|'+' '*(2+q)+'|\n')*-(-q//2);print(z+'| '+n+' |\n'+z)

Try It Online! (Ideone)
Also, here is a noncompeting Python 2.7.5 version since it is much longer at  87 bytes.
def i(n):q=len(n.decode('utf-8'));z=('|'+' '*(2+q)+'|\n')*-(-q/2);print z+'| '+n+' |\n'+z

This is because Python 2's default encoding is ascii, and therefore, characters such as ಠ outside the 128 unicode point range count as more than 1 byte (list('ಠ') yields ['\xe0', '\xb2', '\xa0']). The only workaround I could think of for this was to first decode the input using utf-8, and then move on with this utf-8 decoded string.
Try This Python 2 Version Online! (Ideone)

You can get rid of the parens around (-(-q//2)) for 2 bytes. I think you can save 2 more bytes by switching to Python 2.7. It doesn't need the second / in //, and only a space in the print statement.

@Blue Yeah, you're right, I can remove those second pair of parenthesis. However, I do need the second / in // to do the ceil division.

like I was saying, in Python 2.7 integer division is done with 1 /

@Blue Oh, I assumed you were saying I don't need that in Python 3. Well, in that case, then I will switch over to Python 2. Thanks for the tips! :)

@Blue If that's the case, then how do you do float division in Python 2?

Either value would have to be a float (eg. 2.0 instead of 2). In Python 3, // is now unambiguously floor division, and / is mostly true division. For more information, see http://stackoverflow.com/questions/183853

'| '+n+' |\n' can be shortened by 1 byte to '| %s |\n'%n

70 bytes: def i(n):q=len(n)+2;z=('|'+' '*q+'|\n')*(q-1>>1);print(z+'| %s |\n'%n+z)

Dyalog APL, 37 34 33 bytes
{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×≢⍵}

Chrome users: See footnote*
Test cases
      f←{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×≢⍵}

      f,'☺' ⍝ the , is necessary to create a 1 char string instead of a character scalar
|   |
| ☺ |
|   |
      f':D'
|    |
| :D |
|    |
      f'^_^'
|     |
|     |
| ^_^ |
|     |
|     |

*Chrome misdisplays the two characters ≢⍵ (U+2262,U+2375) as ≢⍵ (U+2261,U+0338,U+2375) instead of as ̸≡⍵ (U+0338,U+2262,U+2375), so here is a display version for Chrome: {↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×̸̸≡⍵}

+1 for having emoticons within your code itself {⍺⍵⍺}¨b

Ah, {⍺⍵⍺}¨b is the “APL programmer on his fifth cup of coffee giving a thumbs up” emoticon.

Vitsy, 43 bytes
IV2m3mz4m2m
3mV\D4m
V1+2/\[1m]
' || '
}}ZaO
Explanation:
IV2m3mz4m2m

I            Grab the length of the input string.
 V           Save that value to a global final variable.
  2m         Call the method at line index 2.
    3m       Call the method at line index 3.
      z      Push the entire input to the stack.
       4m    Call the method at line index 4.
         2m  Call the method at line index 2.

3mV\D4m

3m           Call the method at line index 3.
  V          Push the global variable to the stack.
   \D        Duplicate the top item on the stack that many times.
     4m      Call the method at line index 4.

V1+2/\[1m]

V            Push the global variable to the stack.
 1+          Add one to the top value.
             REASONING: We want ceil(V/2), and since repeat commands follow the floor value of repeats, we want ceil(V/2)+.5, so we add one to make this work right.
   2/        Divide by two.
     \[1m]   Call method 1 that top value of the stack times.

' || '

' || '       Push ' || ', the string, to the stack.

}}ZaO

}}           Push the bottom item of the stack to the top twice.
  Z          Output everything in the stack.
   aO        Output a newline.

Try it online!
Note that, due to a bug in TIO, input with unicode characters will not work. You'll have to use the local version instead for those. Thanks, @Dennis!

V, 60 57 bytes
I| A |ByWo=ceil(len(""")/2.0)
 dF.d0kwviWr Yu@-pH@-P

Unfortunately, V has next to nothing in terms of mathematical operations. The divide and ceil functions drastically inflated the byte count.
Since this contains a bunch of nasty unprintables, here is a reversible hexdump:
00000000: 497c 201b 4120 7c1b 4279 576f 123d 6365  I| .A |.ByWo.=ce
00000010: 696c 286c 656e 2822 1222 2229 2f32 2e30  il(len("."")/2.0
00000020: 290d 201b 6446 2e64 306b 7776 6957 7220  ). .dF.d0kwviWr
00000030: 5975 402d 7048 402d 50                   Yu@-pH@-P

Explanation:
I| A |                                #Add surrounding bars
      B                               #Move back
       yW                             #Yank a word
         o                            #Open a new line
          <C-r>=                      #Evaluate

          <C-r>"                      #Insert the yanked text into our evaluation
ceil(len("      ")/2.0)<cr>           #Evaluate ceil(len(text)/2) and insert it

 dF.                                  #Append a space and delete backward to a (.)
                                      #By default, this will be in register "-
    d0                                #Delete this number into register a
      kw                              #Move up, and forward a word
        viWr                          #Replace the emoticon with spaces
             Yu                       #Yank this line, and undo
                                      #(so we can get the emoticon back)
               @-p                    #Paste this text "- times.
                  H                   #Move to the beginning
                   @-P                #Paste this text "- times behind the cursor.

How many bytes would it have been if there were mathematical operators?

@Adnan It's hard to say, since I don't know exactly what they will look like. Optimistically I'd say around 30 bytes?

Vyxal j, 22 bytes
Lð*w?L½⌈ẋfpømƛ‛| p‛ |+

Try it Online!
Lð*                    # Length spaces
   w    ẋf             # Repeated
    ?L½⌈               # Ceiling of input length/2
          p            # Append input
           øm          # Mirror
             ƛ‛| p‛ |+ # Foreach, prepend '| ' and append ' |'

JavaScript ES6, 83 78 bytes
e=>(a=`| ${" ".repeat(n=e.length)} |
`.repeat(Math.ceil(n/2)))+`| ${e} |
${a}`

You don't need the f=, that saves you 2 bytes. Save another 2 bytes by moving e inside the template and a outside. Save another 2 bytes by inserting spaces instead of adding 2 to the repeat. Save another bunch of bytes by using bit shifting to divide by 2.

I don't think this works, it just tries to print the source code of the repeat

Try again, I fixed it @Bálint

Pyke, 31 bytes
"||
"1dQlO*:Ql_2f_*iO"|  |"2Q:i

Try it here!
Thanks @R.Kap  for saving a byte with the floor divide trick

Ruby, 57 bytes
Uses integer division tricks and takes advantages of the quirks in Ruby's puts function.
->e{s=e.size+1;puts k=[?|+' '*-~s+?|]*(s/2),"| #{e} |",k}

Pyth, 30 bytes
I'm surprised that such an easy task isn't implemented in Pyth.
Ls[K\|dbdK)j++J*/hlQ2]sym;QyQJ

Try it online!

TSQL, 96 88 bytes
DECLARE @ varchar(100)='^_^'

PRINT STUFF(REPLICATE('|'+SPACE(2+LEN(@))+'|
',LEN(@)*2-1),LEN(@)*(LEN(@)+5)-3,LEN(@),@)

Try online!

><>, 103 bytes
i:0(?\
}$&1[\~rl:::2%+*:2,
1-:?!\" "$
]{\  \~
?!\$}1-:
~&\
?!\l$:@-[l2)
~]\
}}\" || "
?!\ol
8.>]l?!;ao2

Try it online!
This solution is based on the observation that each line consists of | <x> |, where <x> is the pattern in the middle line, and the same number of spaces in the other lines.
After reading the input (length n) from STDIN, the program pushes n*(n+(n%2)) spaces. The stack is then rolled half as many times. Next, all but n characters are pulled to a new stack, leaving a stack of stacks consisting of either n spaces or the pattern itself (in the middle stack only). In the output step, the contents of the current stack are printed, surrounded by |  and  |.

C, 89 bytes
f;main(int c,char**a){for(c=strlen(*++a)+1;f<(c|1);)printf("|%*s |\n",c,f++==c/2?*a:"");}

Not sure if it will handle non-ascii emoticon though....

Can you test it with the non-ascii emoticons?

Tried and the result wasn't good - strlen counts bytes until first zero byte and as result non-ascii emoticons are considered much wider than they are.

PowerShell v3+, 72 bytes
param($a)$b=("| "+(" "*($l=$a.length))+" |`n")*($l+1-shr1);"$b| $a |";$b

Takes input string $a. Constructs $b as (the empty pipe-ended string (with $a.length spaces in the middle) and a trailing newline) repeated (length+1 shifted right one bit, i.e., divided by two and ceiling'd) times. Then outputs the copies of $b, the input string with its own pipes, and finally the copies of $b again.
Requires v3+ for the bit-shift -shr operator.
Examples
PS C:\Tools\Scripts\golfing> .\grow-a-treemote.ps1 '>:-|'
|      |
|      |
| >:-| |
|      |
|      |

PS C:\Tools\Scripts\golfing> .\grow-a-treemote.ps1 '>:`-('
|       |
|       |
|       |
| >:`-( |
|       |
|       |
|       |


text:
What's the chance that I'll win a door prize?
My local ACM chapter gives out door prizes to people who come to the meetings. You get an increased chance of winning if you solve the programming puzzle, however (but I always solve that puzzle). Thus, some people have 1 entry, while others have 2. But wait! The way the raffle program works is not by adding in another entry when someone solves the puzzle. Instead, it keeps track of the number of "lives" a person has, decrementing that if that person is chosen in each pass of it's random sampling algorithm. So it works like this:
Doorknob: 1.  xnor: 2.  Justin: 2.  Alex: 1.  Dennis: 2.

Then the program randomly chooses one of [Doorknob, xnor, Justin, Alex, Dennis], decrements the number (say it chooses Justin):
Doorknob: 1.  xnor: 2.  Justin: 1.  Alex: 1. Dennis: 2.

And repeats. If someone's number of "lives" goes to 0 (let's choose Justin again), they're removed from the list:
Doorknob: 1.  xnor: 2.  Alex: 1.  Dennis: 2.

This continues until there's one person left; that person is the winner.
Now the real question is, what was the probability that I would have won?

You will be given two inputs:

n. This is the number of people entered into the challenge
k. This is the number of people (of those n) who have 2 lives. This number always includes you.

So if I had a function p and called p(10, 5), that would be the probability of winning the prize where there are 10 people total, 5 of which only have 1 life, whereas 5 (including you) have 2 lives.

You are expected to output the probability of winning either exactly, or as a decimal. At any rate, answers must be accurate up to and including the 4th decimal place after the decimal point. Whether or not you round to that digit is up to you.
Your solution may be a randomized solution which outputs the answer to the 4th decimal place with high probability. You may assume that the built in RNG you use is truly random, and it must output the correct answer with at least 90% probability.
Furthermore, your code need only work for n, k <= 1000, although I did provide test cases larger than that for those curious.

Test Cases
Note: some of these are general formulae.
n,    k   |  output
----------+---------
1,    1   |  1
2,    2   |  0.5
2,    1   |  0.75
3,    1   |  11/18 = 0.611111111
1000, 1   |  0.007485470860550352
4,    3   |  0.3052662037037037
k,    k   |  1/k
n,    1   |  (EulerGamma + PolyGamma[1 + n])/n    (* Mathematica code *)
          |  (γ + ψ(1 + n))/n
10,   6   |  0.14424629234373537
300,  100 |  0.007871966408910648
500,  200 |  0.004218184180294532
1000, 500 |  0.0018008560286627948
---------------------------------- Extra (not needed to be a valid answer)
5000, 601 |  0.0009518052922680399
5000, 901 |  0.0007632938197806958

For another few checks, take p(n, 1) * n as follows:
n     |  output
------+---------
1     | 1
2     | 1.5
3     | 1.8333333333333335
10    | 2.928968253968254
100   | 5.1873775176396215
-------------------------- Extra (not needed to be a valid answer)
100000| 12.090146129863305

I'm no longer familiar with the tags on this site; if you think of a more appropriate tag, please edit away!

Closely related question on math.se: http://math.stackexchange.com/q/1669715/72616

So, P(n,k) = ((k-1)/n)P(n,k-1) + ((n-k)/n)P(n-1,k) + (1/n)Q(n,k-1), where Q(n,k) = ((n-k-1)/n)Q(n-1,k) + (k/n)Q(n,k-1) and Q(1,0)=1...

@KennyLau I'm not going to attempt to interpret it, but beware the math.se link, as it uses a slightly different definition of the function (I believe k is off by one)

Instead of EulerGamma.... it would be clearer to write H(n)/n where H(n) = harmonic numbers.

Is it OK to do a randomized simulation with enough trials that the answer is correct to the fourth decimal place with high probability, though of course not certainty?

If only the lives were randomly chosen then the answer would be 2/(n+k)...

@xnor I think that should be reasonable

Rounding error in p(n,1)*n? "1.833333333335" shouldnt it be "1.8333333333333"

@BlockCoder1392 I didn't worry about that because it's past the 4th decimal place. But yes, you are right

This question is for a challenge I think? Math.SE is not PPCG.SE.

MATL, 42 bytes
:<~QXJx`J`tf1Zry0*1b(-tzq]f1=vts3e8<]6L)Ym

This uses a probabilistic (Monte Carlo ) approach. The experiment is run a large number of times, from which the probability is estimated. The number of realizations is selected to ensure that the result is correct up to the fourth decimal with probability at least 90%. However, this takes a very long time and a lot of memory. In the link below the number of realizations has been reduced by a factor of 106 so that the program ends in a reasonable amout of
time; and only the first decimal is guaranteed to be accurate with at least 90% probability.
EDIT (July 29, 2016): due to changes in the language, 6L needs to be replaced by 3L. The link below incorporates that modification.
Try it online!
Background
Let p denote the probability to be computed. The experiment described in the challenge will be run for a number n of times. Each time, either you win the prize (“success”) or you don't. Let N be the number of successes. The desired probability can be estimated from N and n. The larger n is, the more accurate the estimation will be. The key question is how to select n to fulfill to the desired accuracy, namely, to assure that at least 90% of times the error will be less than 10−4.
Monte Carlo methods can be

Fixed-size: a value of n is fixed in advance (and then N is random);
Variable-size: n is determined on the fly by the simulation results.

Among the second category, a common used method is to fix N (desired number of successes) and keep simulating until that number of successes is achieved. Thus n is random. This technique, called inverse binomial sampling or negative-binomial Monte Carlo, has the advantage that the accuracy of the estimator can be bounded. For this reason it will be used here.
Specifically, with negative-binomial Monte Carlo x = (N−1)/(n−1) is an unbiased estimator of p; and the probability that x deviates from p by more than a given ratio can be upper-bounded. According to equation (1) in this paper (note also that the conditions (2) are satisfied), taking N = 2.75·108 or larger ensures that p/x belongs to the interval [1.0001, 0.9999] with at least 90% probability. In particular, this implies that x is correct up to the 4th decimal place with at least 90% probability, as desired.
Code explained
The code uses N = 3e8 to save one byte. Note that doing this many simulations would take a long time. The code in the link uses N = 300, which runs in a more reasonable amount of time (less than 1 minute in the online compiler for the first test cases); but this only assures that the first decimal is correct with probability at least 90%.
:        % Take k implicitly. Range [1 ... k]
<~       % Take n implicitly. Determine if each element in the previous array is
         % less than or equal than n
Q        % Add 1. This gives an array [2 ... 2 1 ... 1]
XJx      % Copy to clipboard J. Delete from stack
`        % Do...while. Each iteration is a Monte Carlo realization, until the
         % desired nunber of successes is reached
  J      %   Push previously computed array [2 ... 2 1 ... 1]
  `      %   Do...while. Each iteration picks one door and decrements it, until
         %   there is only one
    t    %     Duplicate
    f    %     Indices of non-zero elements of array
    1Zr  %     Choose one of them randomly with uniform distribution
    y0*  %     Copy of array with all values set to 0
    1b(  %     Assign 1 to chosen index
    -    %     Subtract
    tzq  %     Duplicate. Number of nonzero elements minus 1. This is falsy if
         %     there was only one nonzero value; in this case the loop is exited
  ]      %   End do...while
  f1=    %   Index of chosen door. True if it was 1 (success), 0 otherwise
  v      %   Concatenate vertically to results from previous realizations
  ts3e8< %   Duplicate. Is the sum less than 3e8? If so, the loop is exited
]        % End do...while
6L)      % Remove last value (which is always 1)
Ym       % Compute mean. This gives (N-1)/(n-1). Implicitly display

Haha I didn't realize that 90% would make it that difficult :-)

Yes, fourth decimal with 90% confidence is a really strong requirement :-)

Pyth, 34 bytes
Mc|!*HJ-GHch*J+*tHgGtH*gtGHKh-GHKG

Test suite
Defines a deterministic memoized recursive function g taking n, k as arguments.  g 1000 500 returns 0.0018008560286627952 in about 18 seconds (not included in the above test suite because it times out the online interpreter).
An approximate Python 3 translation would be
@memoized
def g(n,k):
    return (not k*(n-k) or (1+(n-k)*((k-1)*g(n,k-1)+g(n-1,k)*(n-k+1)))/(n-k+1))/n

JavaScript (ES6), 65 bytes
f=(n,k,d=n-k)=>(!d||(f(n-1,k)*++d*--d+1+(--k&&f(n,k)*k*d))/++d)/n

Don't try it with the big numbers though; even f(30, 10) takes a noticeable amount of time.


text:
Three Indistinguishable Dice

Given three dice rolls (integer values from 1-6) in sorted order (so as to be indistinguishable), convert them to the sum of two fair dice with an identical distribution.
The answer for three to one is summing them all, modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).
It's easy to do this for three-to-one, by summing them all modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).  Your challenge is to do the same for three-to-two.
Inspired by standupmath's The Three Indistinguishable Dice Puzzle. A follow-up "solution" video was also posted, but arguing about "elegance" of one way or another is a bit subjective. Counting characters isn't. :D
Instructions
Write a program or function that accepts three sorted integers/digits, 1-6, and outputs or returns a single integer, 2-12, such that, for the 216 possible inputs, the outputs are distributed as:
 222222
 333333333333
 444444444444444444
 555555555555555555555555
 666666666666666666666666666666
 777777777777777777777777777777777777
 888888888888888888888888888888
 999999999999999999999999
 AAAAAAAAAAAAAAAAAA
 BBBBBBBBBBBB
 CCCCCC

(I've used hex to keep to single characters; decimal output is fine)
Because the dice are indistinguishable, there is no intrinsic order to them, hence the sorted input. You cannot simply "drop the third" because that would be ambiguous.
Details

Score is the length of the program in bytes
The program can be a function that's called somehow, or executable script that reads from stdin, or whatever's convienent.
No "rerolling" by getting entropy from another source

Example (and test)
Rather than doing any sort of probabilistic testing, it's easy enough to rip through the 216 (6³) cases of all the three dice and assert that your function returns each value as many times as it should. It will be called with identical parameters (e.g. the cases 1, 2, 3 and 3, 2, 1, ... are presumed indistinguishable and are (arbitrarily) converted to 1, 2, 3).
An example answer (extremely brute-force and inefficient) and test suite is provided below in Python. Hopefully the test bits are clear enough to port to your language of choice, though doing stdin/stdout would be a bit different. The testing code is just for testing and not scored (though if you want to provide it for other users of your language or I/O method, that might be useful).
# 6x6 lists of numbers with digits sorted
LUT = [
    [[124], [133, 166], [346], [223, 355], [256], [115, 445]],
    [[233, 266], [125], [224, 455], [134], [116, 446], [356]],
    [[126], [111, 333, 555, 225], [234], [144, 366], [456], [135]],
    [[112, 244], [235], [334, 466], [145], [226, 556], [136]],
    [[146], [122, 155], [236], [113, 344], [245], [335, 566]],
    [[246], [123], [114, 336], [345], [222, 444, 666, 255], [156]],
]

def three2two(rolls):
    look_for = int('{}{}{}'.format(*sorted(rolls)))
    for i in range(6):
        for j in range(6):
            if look_for in LUT[i][j]:
                return i + j + 2

# fair distribution of the sum of two dice multiplied by 6 (because each should be hit 6x)
expected_counts = {
    2: 6,   12: 6,
    3: 12,  11: 12,
    4: 18,  10: 18,
    5: 24,   9: 24,
    6: 30,   8: 30,
    7: 36,
}

d = [1, 2, 3, 4, 5, 6]
for i in d:
    for j in d:
        for k in d:
            ijk = sorted([i, j, k])
            result = three2two(ijk)
            expected_counts[result] -= 1

for key in expected_counts:
    assert expected_counts[key] == 0

I read the question several times and don't have the slightest idea of what it's asking for.

In addition to the problem of this challenge being unclear, code golf challenges should score by bytes rather than characters, unless you have a really good reason to override that default.

I think I get it. The question is asking us to map from three dice rolls to two dice rolls, with some constraints.

@feersum you have three dice rolls. Turn that into two dice rolls. (just need the sum though, and the dice are indistinguishable: can't tell them apart)

OK. Say I roll 4,5,6. The sum is 15. How do I make 15 with 2 dice?

You're not making that with two dice, you're using the three rolls to simulate two rolls.

@feersum, you don't. That's not what the question's asking for at all. Let U(1,6) give you a uniform random variable which selects among the six smallest positive integers (i.e. a die). Then you have to generate a random variable equivalent to U(1,6) + U(1,6).

Both (a+b+c)%6+1 and (a*b*c)%7 convert a triple of unordered dice to a uniform single die roll, but unfortunately are not probabilistically independent.

Jelly, 22 20 bytes
6ṗ3Ṣ€ṢðQ€L€Ụịḷi’:6d6‘S

Try it online! or simulate all 216 outcomes.
Background
We map each unordered triplet of dice rolls (listed with respective multiplicities) to an ordered pair of dice rolls in the following fashion:
[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3] -> [1,1]
[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4] -> [1,2]
[1,2,5],[1,2,5],[1,2,5],[1,2,5],[1,2,5],[1,2,5] -> [1,3]
[1,2,6],[1,2,6],[1,2,6],[1,2,6],[1,2,6],[1,2,6] -> [1,4]
[1,3,4],[1,3,4],[1,3,4],[1,3,4],[1,3,4],[1,3,4] -> [1,5]
[1,3,5],[1,3,5],[1,3,5],[1,3,5],[1,3,5],[1,3,5] -> [1,6]
[1,3,6],[1,3,6],[1,3,6],[1,3,6],[1,3,6],[1,3,6] -> [2,1]
[1,4,5],[1,4,5],[1,4,5],[1,4,5],[1,4,5],[1,4,5] -> [2,2]
[1,4,6],[1,4,6],[1,4,6],[1,4,6],[1,4,6],[1,4,6] -> [2,3]
[1,5,6],[1,5,6],[1,5,6],[1,5,6],[1,5,6],[1,5,6] -> [2,4]
[2,3,4],[2,3,4],[2,3,4],[2,3,4],[2,3,4],[2,3,4] -> [2,5]
[2,3,5],[2,3,5],[2,3,5],[2,3,5],[2,3,5],[2,3,5] -> [2,6]
[2,3,6],[2,3,6],[2,3,6],[2,3,6],[2,3,6],[2,3,6] -> [3,1]
[2,4,5],[2,4,5],[2,4,5],[2,4,5],[2,4,5],[2,4,5] -> [3,2]
[2,4,6],[2,4,6],[2,4,6],[2,4,6],[2,4,6],[2,4,6] -> [3,3]
[2,5,6],[2,5,6],[2,5,6],[2,5,6],[2,5,6],[2,5,6] -> [3,4]
[3,4,5],[3,4,5],[3,4,5],[3,4,5],[3,4,5],[3,4,5] -> [3,5]
[3,4,6],[3,4,6],[3,4,6],[3,4,6],[3,4,6],[3,4,6] -> [3,6]
[3,5,6],[3,5,6],[3,5,6],[3,5,6],[3,5,6],[3,5,6] -> [4,1]
[4,5,6],[4,5,6],[4,5,6],[4,5,6],[4,5,6],[4,5,6] -> [4,2]
[1,2,2],[1,2,2],[1,2,2],[1,3,3],[1,3,3],[1,3,3] -> [4,3]
[1,4,4],[1,4,4],[1,4,4],[1,5,5],[1,5,5],[1,5,5] -> [4,4]
[1,6,6],[1,6,6],[1,6,6],[2,3,3],[2,3,3],[2,3,3] -> [4,5]
[2,4,4],[2,4,4],[2,4,4],[2,5,5],[2,5,5],[2,5,5] -> [4,6]
[2,6,6],[2,6,6],[2,6,6],[3,4,4],[3,4,4],[3,4,4] -> [5,1]
[3,5,5],[3,5,5],[3,5,5],[3,6,6],[3,6,6],[3,6,6] -> [5,2]
[4,5,5],[4,5,5],[4,5,5],[4,6,6],[4,6,6],[4,6,6] -> [5,3]
[5,6,6],[5,6,6],[5,6,6],[1,1,2],[1,1,2],[1,1,2] -> [5,4]
[1,1,3],[1,1,3],[1,1,3],[1,1,4],[1,1,4],[1,1,4] -> [5,5]
[1,1,5],[1,1,5],[1,1,5],[1,1,6],[1,1,6],[1,1,6] -> [5,6]
[2,2,3],[2,2,3],[2,2,3],[2,2,4],[2,2,4],[2,2,4] -> [6,1]
[2,2,5],[2,2,5],[2,2,5],[2,2,6],[2,2,6],[2,2,6] -> [6,2]
[3,3,4],[3,3,4],[3,3,4],[3,3,5],[3,3,5],[3,3,5] -> [6,3]
[3,3,6],[3,3,6],[3,3,6],[4,4,5],[4,4,5],[4,4,5] -> [6,4]
[4,4,6],[4,4,6],[4,4,6],[5,5,6],[5,5,6],[5,5,6] -> [6,5]
[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[6,6,6] -> [6,6]

This makes all outcomes equiprobable.
How it works
6ṗ3Ṣ€ṢðĠ€Ụịḷi’:6d6‘S  Main link. Argument: D (three dice rolls, sorted)

6ṗ3                     Generate lists of length 3 over [1, 2, 3, 4, 5, 6].
   Ṣ€                   Sort each triplet.
     Ṣ                  Sort the list of triplets.
      ð                 Begin a new, dyadic chain.
                        Arguments: A (list of triplets), D
       Ġ€               Group each; group the indices of each triplet by the
                        the corresponding values.
                        For a triplet [a, b, c], this yields:
                          [[1], [2], [3]] if a < b < c
                          [[1], [2, 3]]   if a < b = c
                          [[1, 2], [3]]   if a = b < c
                          [[1, 2, 3]]     if a = b = c
           Ụ            Grade up; sort the indices of A by those 2D lists.
            ịḷ          Retrieve the elements of A at those indices.
                        This sorts A as in the previous section.
              i         Find the (1-based) index of D.
               ’        Decrement to get the 0-based index.
                :6      Divide the index by 6, rounding down.
                  d6    Divmod; return quotient and remainder of division by 6.
                    ‘   Increment to map [0, ..., 5] to [1, ..., 6].
                     S  Sum the results.

Pyth, 41 27 bytes
JSSM^S6 3+2sPtj+216xo/JNJQ6

10 random testcases
Confirmation of validity.
Conversion table:
2: [111, 222, 333, 444, 555, 666]
3: [112, 113, 223, 224]
4: [114, 115, 225, 226, 355, 366]
5: [116, 122, 125, 233, 244, 445, 446]
6: [126, 133, 144, 146, 255, 266, 455, 466]
7: [134, 155, 156, 166, 246, 334, 335, 556, 566]
8: [123, 135, 234, 256, 336, 344]
9: [124, 136, 235, 345]
10: [145, 236, 346]
11: [245, 356]
12: [456]

Previous 41-byte solution:
I need to golf this...
JSM^S6 3+2f/@co,/JNNJ.u+NY*R6t+S5_S6 6TQ0

Try it online!
Conversion table:

2: [111, 222, 333, 444, 555, 666]

3: [112, 113, 114, 115]

4: [116, 122, 133, 144, 155, 166]

5: [223, 224, 225, 226, 233, 244, 255, 266]

6: [334, 335, 336, 344, 355, 366, 445, 446, 455, 466]

7: [556, 566, 123, 124, 125, 126, 134]

8: [135, 136, 145, 146, 156]

9: [234, 235, 236, 245]

10: [246, 256, 345]

11: [346, 356]

12: [456]

CJam, 37 35 bytes
Probably not golfed well. But beat Pyth.
8aq~\;[_2$>8+@7+@:U2+1$([8U4$7]])er

Try it here.

I suggest you change that description.

CJam, 25 24 bytes
6Zm*{$e`z}$q~:(a#6bW2t1b

This is a port of my Jelly answer.
Try it online! or simulate all 216 outcomes.
Thanks to @jimmy23013 for golfing off 1 byte!

Well, I should have read your code before posting an answer... But some simple golf: 6bW2t1b.

@jimmy23013 Nice. Thank you!


text:
Flatten the Array!
In this challenge, your task is to create a program which takes in a nested array and returns a single-dimensional flattened array. For Example [10,20,[30,[40]],50] should output [10,20,30,40,50].

Input
The input will be a nested array (eg. [10,20,[[[10]]]]). It will contain only Integers (both negative and positive), Strings and Arrays. You can take the input as function argument, STDIN or whatever suits your language. You can assume that the input array won't have an empty array.

Output
The output will be a flatted single-dimensional array with the same elements of same type as in the nested array and in the SAME order.

Test Cases
[10,20,30] -> [10,20,30]
[[10]] -> [10]
[["Hi"],[[10]]] -> ["Hi",10]
[[[20],["Hi"],"Hi",20]] -> [20,"Hi","Hi",20]
[[["[]"],"[]"]] -> ["[]","[]"]

Feel free to ask for any clarification by using comments. This is code-golf, so the shortest code in bytes wins!
Note: If your language contains a built-in for this, then you must NOT use it.

Edit
Please also include a link to a website where your code can be executed.

Some languages treat strings as arrays, is [["Hi"],[[10]]] -> ["H","i",10] ok?

@NᴮᶻNo, I'm afraid that isn't OK.

I'm really surprised this isn't a duplicate

@Mego I was surprised too to find out that there was an unflatten question but no flatten question on PPCG.

Is it okay if the output is an array of all strings, but still contain the same values in the same order as the input array? For instance, is it okay if the input [[[20],["Hi"],"Hi",20]] results in the output ['20', "'Hi'", "'Hi'", '20']?

What if your language only supports subarrays of the same size? (E.g. Java?) What if the type of each element must be the same? (E.g. Java, C++ etc.?) Also, please add e.g. ["[",[["[",],'[',"['['"]] as a test case.

@flawr That test case only makes sense for languages that support bot ' and " as delimiters. (But I agree that a test case involving [, ], " and \ inside a string would be useful.)

The test cases also exclude languages which do not support these kinds of arrays with multiple types, or with another notation for array literals.

@R.Kap Sorry but that's not allowed. I've edited the question also.

@flawr Of course, but I think we always assume that  you just rewrite the test cases with your language's syntax. Making using of something like redundant literal syntax that is only present in some languages seems unnecessarily specific.

@flawr Java can have subarrays of different sizes (but not different types, thus not different 'depths').

@DavidConrad not true - an array is an Object, so an Object[] can contain other arbitrary Object[]. Obviously this isn't typesafe, and any algorithm flattening an Object[] would need to use reflection to work out what's going on.

In C or asm (where polymorphic data types have to be implemented manually), I'm imagining accepting the multi-dimensional array in serialized form.  i.e. treat the problem as a text-processing problem, just removing the internal unquoted [ and ] characters :P

If your chosen language can't handle nested arrays, why are you worrying about using it for this challenge? It obviously can't do this challenge, which is fine. On a side note, using Object[] in Java and std::any[] in C++17 (or the equivalent boost::any in earlier C++ versions) would work.

What if the language automatically flattens the input?

Requiring support for both numbers and strings just makes this challenge unnecessarily complicated, and deviates from the core task.

A test case like ["1",[2]] would probably be good.

K, 3 bytes
,//

This is a fairly common idiom. "Join over converge".
try it here with oK.
How it works:
Join (,) fuses together atoms or lists to produce a list. Over (/) takes a verb (in this case join) and applies it between each element of a list, left to right. Thus, the compound ,/ will flatten all the top level elements of the list. The symbol / actually has different meanings depending on the valence (number of arguments) of the verb with which it is compounded. When we provide ,/ as the verb, the final / acts as "converge"- it repeatedly applies ,/ to the input until it stops changing. Some other languages call a feature like this a "fixed point combinator". By repeatedly fusing bottom level lists, you will eventually arrive at a single flat list, and none of the operations will perturb the order of elements. This seems to solve the problem.

All right, thanks for the explanation! Have your well-earned +1.

a similar solution to a different problem.

I came up with the same algorithm (but not in this language). +1 for picking the right language to implement it in!

@Cyoce If your language has equivalents to the three operators used here, it's an extremely natural solution. By all means post your variation.

@JohnE Long story, I'm deriving a language from algorithms I come up with, so the language isn't finished (and thus implemented) yet.

gorgeous, marvelous!

JavaScript (ES6), 35 bytes
Inspired by @user81655's answer:
f=a=>a.map?[].concat(...a.map(f)):a

Very clever! +1 for [ab]using JS's weird way of handling missing keys!

I can beat that.

@BaldBantha: We're looking forward for your answer :-)

Crap NVM My 33 byte solution fails on one of the test cases. NOOOO

@Bergi here it is anyway: i=x=>x.join().split(',');

Nevermind again! your answer does the same thing as mine! brb answering.

@BaldBantha, join-split will fail on commas inside of strings.

Mathematica, 16 14 bytes
{##&@@#&//@#}&

An unnamed function which takes and returns a list, e.g.:
{##&@@#&//@#}& @ {{{20}, {"Hi"}, "Hi", 20}}
(* {20, "Hi", "Hi", 20} *)

Explanation
Syntactic sugar party!
To understand how this works, note that every expression in Mathematica is either an atom (e.g. numbers, strings, symbols) or a compound expression of the form f[a, b, c, ...], where f, a, b, c are themselves arbitrary expressions. Here, f is called the head of the expression. Everything else on top of that is just syntactic sugar. E.g. {a, b, c} is just List[a, b, c].
We start with //@ which maps a functions over all levels of a list. For instance:
f //@ {{{20}, {"Hi"}, "Hi", 20}}
(* f[{f[{f[{f[20]}], f[{f["Hi"]}], f["Hi"], f[20]}]}] *)

Note that this maps f over atoms as well as compound expressions. What we're now looking for is a way to get rid of the list heads and keep everything else.
The Apply function is normally used to feed the elements of a list as separate arguments to a function, but its actual definition is more general and simply replaces the head of an expression. E.g. Apply[g, f[a, b]] gives g[a, b].
Now there's a special "head" called Sequence that simply vanishes. E.g. {a, Sequence[b, c], d} just evaluates to {a, b, c, d}. The idea for flattening the list is to replace the heads of all inner lists with Sequence so that they get splatted into their surrounding list. So what we want is to Apply the head Sequence to the lists. Conveniently if we Apply something to an atom, it just leaves the atom unchanged, so we don't have to distinguish between types of expressions at all.
Finally, there's one small issue: f is also applied to the outermost level, so that it also removes the outermost List, which we don't want. The shortest way to counter that is simply to wrap the result in a list again, such that the surrounding Sequence can safely vanish.
Note that there's neither Apply nor Sequence in the code. @@ is an operator form of Apply and ##& is a standard golfing trick to shorten the long built-in name Sequence. So ungolfing everything a bit, we get something like:
flatten[list_] := { MapAll[Apply[Sequence], list] }

For more details on how and why the ##& works, see the section on "Sequences of arguments" in my answer for the Mathematica tips.

First time I've seen //@.  Very useful to know about!

//@ captures a neat pattern. Reminds me a bit of some of the recursive combinators in Joy. Do you have a link to a good reference to any related functions in Mathematica? I'm very interested in ways of factoring explicit recursion out of programs.

@JohnE Well, here's the docs. You could also look at things like Map, MapAt, Apply, as well as Replace and related functions. In general though there's a lot of function which take an optional levelspec parameter (see my original 16-byte solution), which lets you apply the function at multiple/all levels at once.

Python 2, 43 bytes
f=lambda l:[l]*(l*0!=[])or sum(map(f,l),[])

On a list, recurses on the elements and concatenates the results. On a string or number, encases in a singleton list.
Unfortunately, Python 2's ordering for types int < list < string sandwiches list between the others, requiring two inequalities to check. So, instead, l*0 is checked against the empty list [], otherwise giving 0 or "".

f=lambda s:[s]["">s>f:]or sum(map(f,s),[]) saves 1.

Ruby, 43 42 34 bytes
Recursive solution. Now with exception handling! (might as well credit @akostadinov for inspiring the change though)
f=->a{a.map(&f).inject:+rescue[a]}

IDEOne link

kudos for shortness, awesome

I didn't know you could use rescue like that

@Cyoce I think it's because Ruby technically doesn't have a try block, so you use begin instead to differentiate the parts you want to be catching for and the parts that you don't. So since you're catching for the entire rest of the block before it, you technically don't need it? The rest is just trimmed whitespace, since Ruby interprets the line as ...inject(:+) rescue [a]

@KevinLau-notKenny, no, rescue on same line is different, just rescuing that line. e.g. a = raise("haha") rescue 1 would assign 1 to a. It'

@KevinLau-notKenny There's an inline rescue, like there's an inline if and while.

JavaScript (ES6), 41 bytes

f=a=>[].concat(...a.map(v=>v.pop?f(v):v))
<textarea id="input" rows="6" cols="40">[[[20],["Hi"],"Hi",20]]</textarea>
<button onclick="result.textContent=JSON.stringify(f(eval(input.value)))">Go</button>

Perl 6, 24 bytes
{gather {$_».&{.take}}}

Explanation:
{ # has $_ as an implicit parameter

  gather {

    $_\ # the parameter from the outer block
    »\  # for each single value in the structure
    .&( # call the following block as if it was a method
      { # this block has its own $_ for a parameter
        .take # call the .take method implicitly on $_
      }
    )
  }
}

Test:
#! /usr/bin/env perl6

use v6.c;
use Test;

my &flatten = {gather {$_».&{.take}}}

my @tests = (
  [10,20,30], [10,20,30],
  [[10,],], [10,],
  [["Hi",],[[10,],],], ["Hi",10],
  [[["[]",],"[]"],], ["[]","[]"],
);

plan @tests / 2;

for @tests -> $input, $expected {
  # is-deeply cares about the exact type of its inputs
  # so we have to coerce the Seq into an Array
  is-deeply flatten($input).Array, $expected, $input.perl;
}

1..4
ok 1 - $[10, 20, 30]
ok 2 - $[[10],]
ok 3 - $[["Hi"], [[10],]]
ok 4 - $[[["[]"], "[]"],]

Haskell, 43 bytes
data D a=L a|N[D a]
f(L x)=[x]
f(N l)=f=<<l

Haskell has neither nested lists with different depths of the sublists nor mixed types for the list elements. For nesting I define a custom data type D which is either a leaf L that holds some element or a node N which is a list of Ds. For the mixed elements I use the predefined data type Either which combines two types into one, here Either String Integer. The new type D and the flatten function f are fully polymorphic in the type of the leaf elements, so I don't have to take extra care of anything regarding Either.
Usage example: f (N[N[L(Right 20)], N[L(Left "Hi")], L(Left "Hi") , L(Right 20)]) -> [Right 20,Left "Hi",Left "Hi",Right 20].

JavaScript (Firefox 30-57), 43 bytes
f=a=>a.map?[for(b of a)for(c of f(b))c]:[a]

Just because I could even avoid using concat.

Isn't it ECMAScript 6 not Firefox 30+?

@SolomonUcko No, [for(of)] is only available in Firefox 30+. It was proposed for ES7 but later dropped.

thanks for explaining! Mostly, i just thought it was for(__ in __)

@SolomonUcko [for(in)] was an alternative experimental syntax which gave you the keys of the object.

Pyth, 7 6 5 bytes
us+]Y

Try it online: Demonstration or Test Suite
But of course, there is also a build-in function, that handles the task in just 2 bytes: .n (Test Suite)

Just 3 away from the current winner! +1

@Sting: Golfed away another byte.  Forgot that Pyth append the last character G implicitly,  if I don't write it.

Congratulations!

Perl, 34 29 bytes
Functions.
If needs to flatten to list like my @a = f(@a), 29 bytes:
sub f{map{ref()?f(@$_):$_}@_}

Test it on Ideone
If needs to flatten to array ref like my $a = f($a), 34 bytes:
sub f{[map{ref()?@{f(@$_)}:$_}@_]}

Test it on Ideone.
Perl 5.22.0+, 27 bytes
Thanks to hobbs.
If needs to flatten to list like my @a = f(@a), 27 bytes:
sub f{map{ref?f(@$_):$_}@_}

Test it on JDoodle
If needs to flatten to array ref like my $a = f($a), 32 bytes:
sub f{[map{ref?@{f(@$_)}:$_}@_]}

Test it on JDoodle.

I haven't tested it, but think ?@{f@$_}: should work instead of ?@{f(@$_)}:, saving two bytes.

@msh210 No, it’s not working. The compiler doesn’t khow that f is a function because f not yet declared. sub f{}sub f{... f@$_ ...} working.

ref doesn't need the parens to work, saving 2 bytes. 2. As far as I can see, sub f{map{ref?f(@$_):$_}@_} is within the rules and saves another 5. f takes an array (nonref) as a list, so it can return the same.

@hobbs 1. If no parentheses with ref then the compiler assumes that ? is starting ?PATTERN? operation like ref(?PATTERN?). So the compiler searches second ? and throws error.

@DenisIbaev ah. ?PATTERN? was removed in 5.22.0 (m?PATTERN? still works) and I'm testing on a recent version. So you can gain those two bytes by specifying 5.22+.

@hobbs 2. I thought about it. But I wasn’t sure that it’s within the rules.

@hobbs Thanks. I added all versions.

Julia, 29 bytes
f(x,y=vcat(x...))=x==y?x:f(y)

This is recursive splatting into a concatenate function until a reaching a fix point. Example
julia> f([1,[2,[3,[4,[5,[6]]]]]])
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

Attache, 14 bytes
{Reap[Sow@>_]}

Try it online!
Fortunately, Attache has a "vectorization" operator, which applies a function at the atoms of a list. In this case, all we need to do is to set up a reaper with Reap and Sow all atoms of the input _ with @>. I think it's quite elegant.
Alternatives
15 bytes: Fixpoint{`'^^_}
16 bytes: Fixpoint!&Concat
17 bytes: {q:=[]q&Push@>_q}
17 bytes: Fixpoint[&Concat]

Retina, 30 bytes
1>`("(\\.|[^"])+")|[][]
$1
$
]

Try it online! (The first line is only used to run multiple test cases at once.)
Retina has no concept of arrays, string literals or numbers, so I decided to go with a "common" input format of [...,...] style arrays and "-delimited strings, where \ can be used inside the strings to escape any character (in particular " and \ itself).
The program itself simply matches either a full string or a square bracket, and replaces them with $1 which keeps strings and removes square brackets. The limit 1> skips the first match so that we don't remove the leading [. However, this does remove the trailing ], so we add it back in in a separate stage.

Pyke, 11 bytes
.F~]+=])K~]

Try it here!
Explanation:
.F~]+=])    - Deep for loop
  ~]        -    contents of `]` ([] by default)
    +       -  ^+i
     =]     - `]` = ^
        K~] - Output value
        K   - Remove the output from the for loop
         ~] - Return the contents of `]`

Or 7 bytes after a bugfix
M?+]K~]

Try it here!
Explanation:
M?+]    - Deep map
 ?+]    -  `]` = `]`+i
    K~] - Output value
    K   - Remove the output from the for loop
     ~] - Return the contents of `]`

Or even 2 bytes if printing to stdout is allowed (This might come under built-ins)
M
<newline required>

Try it here!
This deeply applies the print_newline function to every non-sequence item in the input and recurses for sequence items.

Just 4 away from K! +1

Java (v8) 390 276 bytes
public static Object[] f(final Object[]a) {
    List<Object>r=new ArrayList<>();boolean t=false;int n=0;
    for(final Object p:a)
        if(t=p instanceof Object[]){for(final Object q:(Object[])p) r.add(q);}
        else r.add(p);
    return(t)?f(r.toArray()):r.toArray();
}

Just for completeness and all that. :) Can't say Java's code-efficient.

Hello, and welcome to PPCG! This question is [tag:code-golf], so please try to minimize your code. Thanks!

Do you have any specific suggestions? I have minimized it, Java is just a heavy language.

Remove all the unnecessary spaces, tabs, and newlines. Change oaf to o, and change flatten to f.

You don't need the finals, the whole thing can be a lambda, you don't need public static...

you could save couple characters if you use generics instead object

you could also save 2 bytes if you replace false with 1>2, and additional 2 bytes you could get if you declare n but not define (compiler automatically define it as 0)

@user902383 I don't think you understand generics, but yes in this case I suppose that 'Object' is implied by no specified type.

@David Conrad May Lambas are 'eww' in most cases. And yes I could drop the finals and strictly speaking I don't need the keywords. At the end of the day though, there's no point in changes that squeeze out less than maybe 20 bytes because Java isn't (generally speaking) an interpreted language. There's no way it will ever compete with half the languages people chose to use.

It has nothing to do with interpreted languages. This is code golf. And, no, lambdas are not 'eww'.

Look, don't play stupid. 'Eww' is a matter of opinion as are many opinions about what is good or bad code and I do in fact have a negative opinion of lambdas/anonymous functions and prefer to avoid using them when I can.

Python, 57 bytes
f=lambda a:sum([list==type(x)and f(x)or[x]for x in a],[])

Try it online: Python 2, Python 3
Thanks to Kevin Lau for the list==type(x) trick.

type(x)==list is shorter than isinstance(x,list).

“It will contain only Integers (both negative and positive), Strings and Arrays.” How about [`x`>'['and...? (That works in Python 2 only.)

Ruby
there is builtin flatten method.
You can run here:
http://www.tutorialspoint.com/execute_ruby_online.php
One 43 bytes, but thought to share:
f=->a{a.inject([]){|r,e|r+(f[e]rescue[e])}}

One 45 bytes that is more efficient than the previous and the other ruby answer:
f=->a{a.map{|e|Array===e ?f[e]:[e]}.inject:+}

here's benchmark:
require 'benchmark'
n=10^9
arr=[[[20],[[[[[[[[123]]]]]]]],"ads",[[[[[[[4]]]]]]],5,[[[[[[[[[[6]]]]]]]]]],7,8,[[[[[[[[[[9]]]]]]]]]],[[[[[[[[[[0]]]]]]]]]],[[[[[[[[[[[["Hi"]]]]]]]]]]]],[[[[[["Hi"]]]]]],[[[[[20]]]]]]]
Benchmark.bm do |x|
  x.report { f=->a{a.map(&f).inject:+rescue[a]}; f[arr] }
  x.report { f=->a{a.map{|e|e!=[*e]?[e]:f[e]}.inject:+}; f[arr] }
  x.report { f=->a{a.inject([]){|r,e|r+(f[e]rescue[e])}}; f[arr] }
  x.report { f=->a{a.map{|e|Array===e ?f[e]:[e]}.inject:+}; f[arr] }
end

result:
       user     system      total        real
   0.010000   0.000000   0.010000 (  0.000432)
   0.000000   0.000000   0.000000 (  0.000303)
   0.000000   0.000000   0.000000 (  0.000486)
   0.000000   0.000000   0.000000 (  0.000228)

Hello, and welcome to PPCG! Unfortunately, your answer is not valid, because of this rule: Note: If your language contains a built-in for this, then you must NOT use it.

@NoOneIsHere, thanks, didn't know that

How does my new update stack against time-wise against yours? Also, just like my new answer, you can remove the spaces around rescue

@KevinLau-notKenny updated, thanks! rescue looks to be rather slow btw, like try/catch in java

Update your bytecount, too

@KevinLau-notKenny, updated, also altered the faster solution by your example map.reduce and it became shorter and a little faster

Perl, 39 34 + 1 (-p flag) 35 bytes
Oneliner. Inspired by Martin Büttner.
#!perl -p
s/("(\\.|[^"])+"|]$|^\[)|[][]/$1/g

Test it on Ideone.

Clojure, 68 bytes
(def f #(if(some vector? %)(f(mapcat(fn[z](if(vector? z)z[z]))%))%))

mapcat first applies function to each element and then concats results. So every time it concats one 'nesting level' is lost. Concat does not work on not sequences so elements have to be wrapped into vector if they're not vector.
You can try it here: http://www.tryclj.com
(f [[[20],["Hi"],"Hi",20]])
(f [[["[]"],"[]"]])

Nice first code-golf. +1 :)

ANSI C, 193 bytes
#define b break;
#define c case
#define p putch(_);
char f;main(_){switch(_){c 1:putch(91);b c 34:f^=1;p b c 91:f&&p b c 93:f&&p b c 10:c 13:putch(93);return;default:p}_=getch();main(_);}

:-/, any suggestions? Btw, I did try to find an online source to compile this but the WL is strict for this code to compile. It will work for VS and gcc otherwise.

Welcome to PPCG!

Welcome to PPCG! Nice first golf. Good luck ahead!

Thanks! It was an attempt to up my points so that I can get commenting privileges elsewhere. It appears things don't work like that the accounts are for different portals. :D I will see if some nifty features from c++ can be used.

JavaScript 20 bytes
a=>(a+[]).split(',')

The array + array is equal to array.toString

@WheatWizard thanks for the welcome and I am new to the site. actually a is an argument of the function. I will try to edit out the function now.

I think now it's ok @WheatWizard. Please let me know if there is a problem with this

Actually looking at the javaScript docs an anonymous function would definitely be shorter, you would only have to add a=> to the beginning of your code.

@WheatWizard I updated with the arrow function as you mentioned. But I have to remove the snippet because arrow function doesn't support direct invoke. It is only for callbacks

Save 2 bytes with split\,``

This doesn't handle strings with commas in them correctly

Haskell + free, 7 bytes
In order to represent a ragged list in Haskell we use a free monad of lists.  Luckily for us provided with the free monad is retract, which does a lot of different things, but when given the particular type here it flattens the free monad of lists down to a single list.
retract

Try it online!
But we can also make our own solution using other tools, like foldFree:
11 bytes
foldFree id

Try it online!
However foldFree basically is just a more general version of retract, and we can do it without it:
21 bytes
iter(>>=id).fmap(:[])

Try it online!
If we want to use none of the functions provided by free just the definition of the monad and prelude functions we can do:
29 bytes
f(Pure a)=[a]
f(Free a)=a>>=f

Try it online!

Racket, 63 bytes
(define(f l)(apply append(map(λ(x)(if(list? x)(f x)`(,x)))l)))

JavaScript, 17 Bytes
a=>eval(`[${a}]`)

Finally, JavaScript's type conversions can be put to some good use! Please note that this will actually output an array, but string conversion (putting it into HTML) causes it to become a comma separated list.
If comma separated lists are acceptable output, then the following is valid:
7 Bytes
a=>""+a

NOTE: Snippet is broken for some reason

var subject =
  a=>eval(`[${a}]`)
<input oninput="try {output.innerHTML = subject(this.value)} catch(e) {output.innerHTML='Invaild Input'}" />

This doesn't seem to work when run in the console for input ["["]... I tried running (a=>eval([${a}]))(["["]) and got a SyntaxError

@jrich. You just get this error when you type character by character. If you copy and paste any valid array, it will work as expected. By the way, nice answer SpeedNinja, I would only change oninput event with a button click.

This doesn't work for strings with commas in them

Java 8 165 chars
import java.util.*;<T>T[]f(T[]a){List<T>l=new ArrayList<>();for(T e:a)if(e instanceof Object[])Collections.addAll(l,f((T[])e));else l.add(e);return(T[])l.toArray();}

Ungolfed into a class:
public class Q80096 {

    public static <T> T[] flatten(T[] array) {
        List<T> flattenedList = new ArrayList<>();
        for (T element : array)
            if (element instanceof Object[])
                 Collections.addAll(flattenedList, flatten((T[]) element));
            else
                flattenedList.add(element);
        return (T[]) flattenedList.toArray();
    }
}

This answer is based on Jeremy Harton's approach. I used it changed it in some places and created a more golf-like version.

would it be not better when using Arrays.asList() on "array" and then go the foreach with lambda and end this with a Collector?

PHP, 73 Bytes
<?array_walk_recursive($_GET,function($i)use(&$r){$r[]=$i;});print_r($r);

C# (Visual C# Interactive Compiler), 66 bytes
T[]f<T>(T[]a)=>a.SelectMany(x=>x is T[]y?f(y):new[]{x}).ToArray();

Try it online!
Recursive function that takes an object[] as input. Yes, there is a type parameter, so you could pass an array of any type... But it only works correctly if all nested arrays are of the same type. That is a requirement that I have added :)
It would be more flexible to get this to work with an input of type IList or Array.

Elixir, 74 bytes
def d(l)do l|>Stream.flat_map(fn x->if is_list(x)do d(x)else[x]end end)end

First Elixir answer, so can probably be golfed a bit.
Try it online.
Explanation:
def d(l)do l|>            # Recursive method taking a list as input:
  Stream.flat_map(fn x->  #  Map over each item `x` of the input-list:
    if is_list(x)do       #   If `x` is a list itself:
      d(x)                #    Do a recursive call with `x`
    else                  #   Else:
      [x]                 #    Simply leave `x` unchanged
    end                   #   End of the if-else statements
  end)                    #  End of the map
end                       # End of the recursive method

Of course, if builtins were allowed, this could have been 25 bytes instead:
fn(l)->List.flatten(l)end

Try it online.

Jelly, 4 bytes
;/ÐL

Try it online!
Explanation
;/   | Reduce by concatenation
  ÐL | Loop until no further changes

Built-in F would be one byte if allowed.

Wolfram Language (Mathematica), 13 bytes
#~Level~{-1}&

Try it online!
Un-golfed: F[x_] := Level[x, {-1}]
picks out the elements of the structure at the last level of its tree form. I'm not sure this counts as "avoiding the builtin" (which would be Flatten).

Brachylog, 6 bytes
ċ↰ᵐc|g

Try it online!
ċ         The input is a list,
    |     and the output is
   c      the concatenation of
 ↰ᵐ       the results of this predicate on the list's elements.
    |     If the input is not a list, then it
     g    wrapped in a list is the output.

Nial, 27 bytes
DOWN[simple,pass,pass,link]

Try it online!
strangely interesting in nial since it doesn't have fixpoint.

Lua, 123 bytes
function f(a)o,t={},function(s)for _,v in next,s do if type(v)=="table"then t(v)else o[#o+1]=v end end end t(a)return o end

I'm sure this is not the best answer, but I thought I'd post it since nobody has given a Lua solution yet. Suggestions welcome!
Try it online!

PowerShell, 35 bytes
filter f{if($_.Rank){$_|f}else{$_}}

Try it online!
Rank - Returns the number of dimensions in the array. Rank = 0 if an object is not array.

05AB1E, 13 bytes
ΔvyD1«Āië`}})

Try it online or verify all test cases
Not the easiest challenge in 05AB1E, since the merge builtin for lists is also used for strings, so reducing by concatenation like most other golfing languages are using isn't possible. Also, flattening one level down with €`  will also flatten down strings to a list of characters (and push them in reversed order), otherwise Δí€`  would have been a 4 byter:
Try it online or see the incorrect output of all test cases.
Δ          # Loop until the result no longer changes:
           # (which will use the implicit input-list in the first iteration)
 vy        #  Foreach over the items:
   D       #   Duplicate the current item
    1«     #   Append a "1" to each inner-most string/integer
      Ā    #   Truthify each inner-most string
           #   (we use the appended "1" so every string/integer - even "", "00",
           #   0, 000, etc. - becomes truthy)
       i   #   If this is truthy (will be falsey for lists of truthy values):
           #    (use the duplicated item as is)
       ë   #   Else (it's a list instead):
        `  #    Pop the list, and push all its items to the stack
       }   #   Close the if-statement
 }         #  After the foreach-loop:
  )        #  Wrap all values on the stack into a list
           # (after which the resulting flattened list is output implicitly)

With builtins, we could of course have used the single byte flatten builtin ˜:
Try it online or verify all test cases.
Interesting enough, the incorrect result of the 4-byter could have been 1 byte as well with the flattened characters builtin S:
Try it online or see all test cases.