text:
Dennis, Doorknob, Martin Büttner, Chris Jester-Young - Pizzeria!
Programming Puzzles & Code Golf is about to get a new moderator, Dennis! This challenge is a tribute to him and our other active (or recently active) moderators: Doorknob, Martin Büttner, and Chris Jester-Young. The challenge title is meant to be read to the tune of the Pepto Bismol song.
Basically, we're going to treat them all to pizza at The Nineteenth Bite Pizzeria, but we need to make sure they share it fairly because some of the mods are known to be pizza addicts!
The pizzas sold by the pizzeria are all rectangular blocks of text. The width and length of a pizza may be any non-negative integers as long as their product is divisible by four. Each grid space in the block of text pizza represents a slice, so it's always possible to split the slices up into four equal groups.
The mods will collectively order a single pizza, providing its width and length parameters to their server in any reasonable format such as [width],[length]. Just before the pizza arrives at their table, you need to label each slice with the initial of the mod who gets to eat it to ensure they all share fairly. Everyone should get the same number of slices.

E is for Dennis
D is for Doorknob
M is for Martin
C is for Chris

The mods are a little persnickety, however, and require that their respective sets of slices be path-connected, that is, that all their slices can be reached from one another by moving up, down, left, and right, not crossing anyone else's slices (and not moving diagonal). The don't care how you do this as long as it is done.
Once you've accurately labeled each slice, deliver the pizza to the mods with an optional trailing newline.
Your labeler may be a program or a function and can print or return the labeled pizza. The shortest labeler in bites wins.
Examples
Example 1
Order: 4,1
Some Possible Labeled Pizzas:
EDMC
MEDC
CDEM
Example 2
Order: 4,4
Some Possible Labeled Pizzas:
MMMM
CCCC
DDDD
EEEE
DEMC
DEMC
DEMC
DEMC
CCCC
DEEM
DEEM
DDMM
Example 3
Order: 8,3
Some Possible Labeled Pizzas:
MMMMMMCC
DDDDCCCC
DDEEEEEE
DDDCMMMM
DCDCMEEE
DCCCMEEE
Example 4
Order: 20,5
A Possible Labeled Pizza:
DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEDMMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC
(The D's here are not simply-connected but that's ok.)

I'd love to see what goes on in your mind :D

@BetaDecay It's mainly a diarrhea rhyming device.

That is not what I imagined... D:

They require that their respective sets of slices be path-connected. It's a little scary that you'd know that about me...

Okay, what is with this weird rectangular-outline-shaped pizza slice you've given me? I want a refund!

Is there pineapple pizza available?

@flawr Not for the likes of you, non-mod.

"Shortest labeller in bites wins" - I see what you did there.

Are we allowed to transpose the pizza slices? Like, if the request is for a width of 5 and a height of 4, can we have a width of 4 and a height of 5?

@NateKerkhofs No

Oh, no! There isn't enough pizza for Alex D:

What if you made it a requirement that the path couldn't repeat itself?

@BetaDecay Luckily for Alex, if the pizza is 1x3, none of the mods get the pizza. The whole pizza is left for Alex!

CJam, 20 bytes
q~1$*4/"CEDM"e*/:$N*

I think this should work :)
Try it online
Explanation:
This first makes a pizza labeled CC…EE…DD…MM… from left to right and top to bottom, then sorts each row in alphabetical order. The only disconnections can happen between the C-E border and E-D border, or E-D border and D-M border (if they fall on adjacent rows). But the sorting ensures that the E's go to the right side and the D's go to the left side, as C<E>D<M, so the E's and the D's remain connected.
q~          read and evaluate the input
1$          copy the width
*4/         multiply with the height and divide by 4
"CEDM"e*    repeat each letter in "CEDM" that many times
/           split into rows of the given width
:$          sort each row
N*          join with newlines

Selectively reversing rows shared by Doorknob and me. That's one clever use of $!

K, 61 bytes
{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}

Examples:
ryan@DevPC-LX:~/golf$ rlwrap k2
K 2.8 2000-10-10 Copyright (C) 1993-2000 Kx Systems
Evaluation. Not for commercial use.
\ for help. \\ to exit.

  `0:{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}[4;1]
EDMC
  `0:{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}[4;4]
EEEE
DDDD
MMMM
CCCC
  `0:{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}[8;3]
EEEEEEDD
MMMMDDDD
MMCCCCCC
  `0:{[a;b]{((+:;|:)@x!2)[r@x]}'!#r:(b;a)#,/{(_(a*b)%4)#x}'"EDMC"}[20;5]
EEEEEEEEEEEEEEEEEEEE
DDDDDDDDDDDDDDDEEEEE
DDDDDDDDDDMMMMMMMMMM
CCCCCMMMMMMMMMMMMMMM
CCCCCCCCCCCCCCCCCCCC

ryan@DevPC-LX:~/golf$

I would hate to be the person who has to slice these things...

Looks like it zig-zags back and forth, top to bottom. Is that correct? (Will it work for 1,8?)

@Calvin'sHobbies It appears to work for that input.

I was going to use the same approach and I'm pretty sure it works. It's Chris though.

@Dennis Whoops. Fixed.

Pyth, 30 25 bytes
jb.eu_GkbceQs*R/*FQ4"EDMC

Live demo and all test cases.
Cut off 5 bytes thanks to @Jakube!
Same algorithm as my K answer...but a lot shorter.
30-byte version:
jb.e?%k2_bbcjkm*/*FQ4d"EDMC"hQ

Live demo and all test cases for 50-byte version.

Pyth, 20 bytes
VceQs*L/*FQ4"CEDM"SN

Uses @aditsu's sorting trick.
Demonstration.
I came up with a large number of alternative programs of the same length while trying to golf this:
VceQs*L/*FQ4"CEDM"SN
VceQsCm"CEDM"/*FQ4SN
VceQs*L*FQ"CEDM"%4SN
VceQ%4s*L*FQ"CEDM"SN
VcQs*L/*Qvz4"CEDM"SN    (Newline separated input)
jbSMceQs*L/*FQ4"CEDM
Vcs*L/*FQ4"CEDM"hQSN

Stuck, 42 33
It returns! And in awfully long form. :( -- I stole aditsu's sort idea to save 9 bytes :)
t;g*4/[4*"CEDM"z"];F*":j0GK'$:Nj

Explanation:
t;g*4/                              # Take |-separated input,
                                    #   store the first value in var stack,
                                    #   multiply the two numbers and divide by 4.
      [4*"CEDM"z                    # Wrap that value in an array, make 3 copies
                                    #   to get a list of length 4, zip with "EDMC"
                "];F*":j0GK         # For each item, multiply letter by value to
                                    #   to get string, join the result, split into
                                    #   segments the size of the saved variable.
                            '$:Nj   # For each item, sort so the letters are in the correct
                                    #   order, join by newline, print.

Example input:
20|5

Example output:
CCCCCCCCCCCCCCCCCCCC
CCCCCEEEEEEEEEEEEEEE
DDDDDDDDDDEEEEEEEEEE
DDDDDDDDDDDDDDDMMMMM
MMMMMMMMMMMMMMMMMMMM

Are you sure it will be simply connected for 8|3?

@yo' Yes. It outputs CCCCCCEE\nDDDDEEEE\nDDMMMMMM.

/me_stupid, sorry for that.

Rev 1 C, 74
i;f(w,h){for(i=w*h;i--;i%w||puts(""))putchar(h-i/w*2==1^"CDEM"[i*4/w/h]);}

For a 1-byte saving, this version reverses (only) the middle row of slices for any odd number of rows.
Rev 0 C,75
i;f(w,h){for(i=w*h;i--;i%w||puts(""))putchar(h==3&i/w==1^"CDEM"[i*4/w/h]);}

Many answers here zigzag, but in most cases, just outputting the letters in order (left to right, top to bottom) works fine:
No need to zigzag for heights 1,2 or 4
No need to zigzag for heights greater than 4 (each mod's pizza ration will wrap around.)
Therefore we only actually need to zigzag when the height is 3, and then we only need to reverse the middle row.
As it turns out, Dennis and Doorknob are the only mods on that row. And they can be interchanged by XORing their ASCII codes with 1.
This is handy given that there's no easy way to reverse a string in C.
Ungolfed in test program
i;
f(w,h){
  for(i=w*h;i--;i%w||puts(""))            //loop through all squares. puts inserts a newline at the END of each line.
  putchar(h==3&i/w==1^"CDEM"[i*4/w/h]);   //put the letter, XORing D and E for the middle row of height 3.
}

W,H;
main(){
  scanf("%d%d",&W,&H);
  f(W,H);
}

Great explanation.

JavaScript (ES6) 107
Zigzag solution. Using template string, the newline is significant and counted.
Test running the snippet with FireFox.

f=(w,h)=>{for(i=o=r='',z=l=1;--l?l:c='CDEM'[l=w*h/4,i++];r[w-1]&&(o+=r+`
`,r='',z=!z))r=z?r+c:c+r;return o}

//TEST

(test=_=>([w,h]=I.value.match(/\d+/g),O.innerHTML=f(w,h)))()
<input id=I value='8 3'><button onclick='test()'>-></button>

Retina, 83 bytes
The features used in this answer are newer than this challenge (not that it matters...). Byte count assumes ISO 8859-1 encoding.
\d+
$*#
#(?=.*¶(.+))
$1
\G####
CDEM
S_`((.)+?(?=.*¶(?<-2>#)+$))|\D
O`.
T`DE`ED
O%`.

Try it online!
This implements aditsu's solution which is now somewhat feasible thanks to the new sort stages.

Jelly, 14 bytes
×:4“CEDM”xsṢ€Y

Try it online!
Implements aditsu's algorithm
How it works
×:4“CEDM”xsṢ€Y - Main link. Takes h on the left and w on the right
×              - Yield h×w
 :4            - Integer divide by 4; Yield R = (h×w):4
   “CEDM”      - Yield "CEDM"
         x     - Repeat each character R times
          s    - Split into rows of length w
           Ṣ€  - Sort each row
             Y - Join by newlines

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:
Zigzagify a String
Write a program (or function) that takes in a non-empty string of any printable ASCII characters.
Print (or return) a zigzagging chain of the characters in the string with every neighboring pair of characters linked by:

/ if the first character occurs before the second character in normal ASCII order. e.g.
  B
 /
A

\ if the first character occurs after the second character in normal ASCII order. e.g.
B
 \
  A

- if the first and second characters are the same. e.g.
A-A

So the output for Programming Puzzles & Code Golf would be
                                                        o
                                                       / \
  r                         z-z               o   e   G   l
 / \                       /   \             / \ / \ /     \
P   o   r   m-m   n       u     l   s   &   C   d           f
     \ / \ /   \ / \     /       \ / \ / \ /
      g   a     i   g   P         e
                     \ /

If there is only one character in the input string the output would just be that character.
Your program should treat , /, \, and - just the same as all other characters.
e.g.   -\//-- \ //-  should produce:
      \
     / \
    -   /-/
   /       \
 -          ---   \   /-/
               \ / \ /   \
                          -
                           \

There should be no extraneous newlines in the output except for a single optional trailing newline. (Note that the empty line in the example just above holds the last space in the the string and is therefore not extraneous.) There may be trailing spaces on any lines in any arrangement.
The shortest code in bytes wins.
One more example - Input:
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

Output:
                          9   9       8   6   6
                         / \ / \     / \ / \ / \
            9   6       8   7   3   3   4   2   4     8       9       8-8
           / \ / \     /         \ /             \   / \     / \     /   \
      4   5   2   5   5           2               3-3   3   7   5   2     4   9       9   9-9   7
     / \ /         \ /                                   \ /     \ /       \ / \     / \ /   \ / \
3   1   1           3                                     2       0         1   7   6   3     3   5       8                             8   6
 \ /                                                                             \ /               \     / \                           / \ / \
  .                                                                               1                 1   5   2   9             9   3   7   1   4   6   8                                                   9
                                                                                \ /     \ / \           / \ / \ /         \ / \ / \                                                 /
                                                                                0       0   7   9     5   2   0           0   2   6       9-9               8   5   4             7
                                                                                \ / \   /                             \     /   \             / \ / \ / \           /
                                                                                4   4-4                               2   8     8           4   2   3   2     7   6
                                                                                \ /       \         /             \   / \ /
                                                                                0         6   8   3               1-1   0
                                                                                \ / \ /
                                                                                2   0

Pyth, 69 bytes
aY,JhzZVtzaY,@"-\/"K-<NJ>N~JN=+ZKaY,N=+ZK;jbCmX*\ h-e=GSeMYhG-edhGhdY

Demonstration. Longer inputs still work, but they don't look very good in the fixed-width output box.
I start by constructing a list, in Y, of [character, height] tuples. It is [['P', 0], ['/', -1], ['r', -2], ['\\', -1], ['o', 0], ['\\', 1], ['g', 2]] early on in the Programming Puzzles & Code Golf example.
I then make strings of spaces of the appropriate length, insert the character at the appropriate location, transpose, join on newlines and print.

Julia, 297 bytes
s->(l=length;d=sign(diff([i for i=s]));J=join([[string(s[i],d[i]>0?:'/':d[i]<0?:'\\':'-')for i=1:l(d)],s[end]]);D=reshape([d d]',2l(d));L=l(J);E=extrema(cumsum(d));b=2sumabs(E)+1;A=fill(" ",L,b);c=b-2E[2];for (i,v)=enumerate(J) A[i,c]="$v";i<l(D)&&(c-=D[i])end;for k=1:b println(join(A'[k,:]))end)

Ungolfed:
function f(s::String)
    # Get the direction for each slash or dash
    # +1 : /, -1 : \, 0 : -
    d = sign(diff([i for i in s]))

    # Interleave the string with the slashes as an array
    t = [string(s[i], d[i] > 0 ? '/' : d[i] < 0 ? '\\' : '-') for i = 1:length(d)]

    # Join the aforementioned array into a string
    J = join([t, s[end]])

    # Interleave D with itself to duplicate each element
    D = reshape(transpose([d d]), 2*length(d))

    # Get the length of the joined string
    L = length(J)

    # Get the maximum and minimum cumulative sum of the differences
    # This determines the upper and lower bounds for the curve
    E = extrema(cumsum(d))

    # Get the total required vertical size for the output curve
    b = 2*sumabs(E) + 1

    # Get the beginning vertical position for the curve
    c = b - 2*E[2]

    # Construct an array of spaces with dimensions corresponding
    # to the curve rotated 90 degrees clockwise
    A = fill(" ", L, b)

    # Fill the array with the curve from top to bottom
    for (i,v) = enumerate(J)
        A[i,c] = "$v"
        i < length(D) && (c -= D[i])
    end

    # Print out the transposed matrix
    for k = 1:b
        println(join(transpose(A)[k,:]))
    end
end

Javascript (ES6), 360 331 316 302 bytes
Here's my fourth attempt:
s=>{r=[],c=s[m=w=n=0];for(i in s)(i?(d=s[++i])>c?++n:c>d?--n:n:n)<m&&m--,n>w&&w++,c=d;for(i=0,n=w*2;i<(w-m)*2+1;r[i++]=[...' '.repeat(l=s.length*2-1)]);for(i=0;i<l;i++)i%2?(A=s[C=(i-1)/2])<(B=s[C+1])?r[--n,n--][i]='/':A>B?r[++n,n++][i]='\\':r[n][i]='-':r[n][i]=s[i/2];return r.map(x=>x.join``).join`
`}

Not as short as some of the others, but I'm satisfied with it for now.
Oh, so you want to test it? Alright, here you go:

z=s=>{r=[],c=s[m=w=n=0];for(i in s)(i?(d=s[++i])>c?++n:c>d?--n:n:n)<m&&m--,n>w&&w++,c=d;for(i=0,n=w*2;i<(w-m)*2+1;r[i++]=[...' '.repeat(l=s.length*2-1)]);for(i=0;i<l;i++)i%2?(A=s[C=(i-1)/2])<(B=s[C+1])?r[--n,n--][i]='/':A>B?r[++n,n++][i]='\\':r[n][i]='-':r[n][i]=s[i/2];return r.map(x=>x.join``).join('
')};

input=document.getElementById("input");
p=document.getElementById("a");
input.addEventListener("keydown", function(){
  setTimeout(function(){p.innerHTML = "
"+z(input.value)+"
";},10);
})
<form>Type or paste your text here: <input type="text" id="input"/></form>

Output:

Have fun!
Updates:
Update 1: Golfed off 29 bytes with a variety of typical techniques.
Update 2: Golfed off 15 more bytes by building the string horizontally from the start, as opposed to building an array of the vertical strings and switching them around, which is what it did before.
Update 3: Saved 14 more bytes.
More golfiness coming soon!

You can save a byte by replacing '\n' with a template string like this

@UndefinedFunction Yeah, I've used that trick before, but forgot to put it in last night. Thanks for the reminder!

Your for loops can be squished a lot.  Don't waste a whole block of required code with i++.  Instead, run most of your for code in there.  Also, you don't need braces around single lines of code.

It also seems like the only way you use l is to calculate s.length*2-1 and you do that twice.  Why not store that value instead?

However, it looks like a requirement is to print the string to the screen, and you haven't fulfilled that.  Consider using \n instead of
 and putting to console or alert.

@NotthatCharles Thanks for the tips! I'd just tried out the modified algorithm and not bothered to golf it much more yet. The
 is just in there so it shows up in the HTML version; if you look closely, I use a template string instead in the actual entry. Also, it's not a requirement: "Print (or return)..."

You can save 2 more characters by declaring all the iteration variables separately in that m=w=n=0 block.  You need to add extra variables for the other iterations.  So, e.g., f=j=m=w=n=0... and then replace the is as needed.  Then you can drop the i=0 in the later for loops.  You may find you save space without using an for in loop at the beginning, too.

Python, 393 bytes
def z(n,h=[]):
 for j in range(len(n)):h.append(sum(cmp(ord(n[i]),ord(n[i+1]))for i in range(j)))
 h=[j-min(h)for j in h]
 for y in range(max(h)*2+2):
  s=""
  for x in range(len(n)):
   if h[x]*2==y:s+=n[x]
   else:s+=" "
   if x==len(n)-1:continue
   c=" "
   if h[x]<h[x+1]and h[x]*2==y-1:c="\\"
   if h[x]>h[x+1]and h[x]*2==y+1:c="/"
   if h[x]==h[x+1]and h[x]*2==y:c="-"
   s+=c
  print s

Run as:
z("Zigzag")

JavaScript (ES6), 202
Using template strings. Indentation spaces and newlines not counted, except the last newline inside backticks that is significant and counted.
Usual note: test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go)

f=z=>
  [...z].map(c=>
    (d=0,x=w+c,p&&(
      c
p?(d=-1,g='/ ',r?r-=2:o=[v,v,...o]):x='-'+c,
      o=o.map((o,i)=>o+(i-r?i-r+d?b:g:x),v+=b)
    ),p=c)
  ,v=w=' ',o=[z[p=r=0]],b=w+w)&&o.join`
`

Ungolfed=z=>
(
  v=' ',o=[z[0]],r=0,p='',
  [...z].map(c=>{
    if (p) {
      if (c
o+(i==r ? ' '+c : i==r-1 ? '\\ ' : '  '))
      } else if (c > p) {
        if (r == 0)
          o = [v,v,...o]
        else
          r -= 2
        o = o.map((o,i)=>o+(i==r ? ' '+c : i==r+1 ? '/ ' : '  '))
      } else {
        o = o.map((o,i)=>o+(i==r ? '-'+c : '  '))
      }
      v += '  '
    }
    p = c
  }),
  o.join`\n`
)

out=x=>O.innerHTML+=x+'\n'

test = [
"Programming Puzzles & Code Golf",
"-\\//-- \\ //- ",
"3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"]

test.forEach(t=>out(t+"\n"+f(t)))

CJam, 79 bytes
l__0=\+2ew::-:g_0\{+_}%);_$0=fm2f*_$W=)S*:E;]z{~\_)"/-\\"=2$@-E\@t@@E\@t}%(;zN*

Try it online
This builds the output column by column, and transposes the result at the end to get the output row by row. This was quite painful overall.
Explanation:
l__   Get input and create a couple of copies.
0=\+  Prepend copy of first letter, since the following code works only with
      at least two letters.
2ew   Make list with pairs of letters.
::-   Calculate differences between pairs...
:g    ... and the sign of the differences.
_0\   Prepare for calculating partial sums of signs by copying list and
      pushing start value 0.
{     Loop for calculating partial sums.
  +_    Add value to sum, and copy for next iteration.
}%    End of loop for partial sums. We got a list of all positions now.
);    Pop off extra copy of last value.
_$0=  Get smallest value.
fm    Subtract smallest value to get 0-based positions for letters.
2f*   Multiply them by 2, since the offsets between letters are 2.
_$W=  Get largest position.
)     Increment by 1 to get height of result.
S*    Build an empty column.
:E;   Store it in variable E.
]     We got the input string, list of relative offsets, and list of
      absolute positions now. Wrap these 3 lists...
z     ... and transpose to get triplets of [letter offset position].
{     Loop over triplets.
  ~     Unwrap triplet.
  \     Swap offset to front.
  _)    Copy and increment so that offset is in range 0-2.
  "/-\\"  List of connection characters ordered by offset.
  =     Pick out connection character for offset.
  2$@   Get position and copy of offset to top.
  -     Subtract to get position of connection character.
  E     Empty column.
  \@    Shuffle position and character back to top. Yes, this is awkward.
  t     Place connection character in empty line. Done with first column.
  @@    Shuffle letter and position to top.
  E     Empty column.
  \@    Stack shuffling again to get things in the right order.
  t     Place letter in empty line. Done with second column.
}%    End of main loop for triplets.
(;    Pop off first column, which is an extra connector.
z     Transpose the whole thing for output by row.
N*    Join with newlines.

Perl 5, 230 214
@A=split(//,pop);$y=$m=256;map{$c=ord$_;$d=$c<=>$p;$t=$d>0?'/':$d<0?'\\':'-';$B[$x++][$y-=$d]=$t;$B[$x++][$y-=$d]=$_;$m=$y,if$m>$y;$M=$y,if$M<$y;$p=$c}@A;for$j($m..$M){for$i(1..$x){$s.=$B[$i][$j]||$"}$s.=$/}print$s

Test
$ perl zigzag.pl "zigge zagge hoi hoi hoi"
z
 \
  i
   \
    g-g
       \
        e   z   g-g       o       o       o
         \ / \ /   \     / \     / \     / \
              a     e   h   i   h   i   h   i
                     \ /     \ /     \ /

$

Ruby, 158
Saved 6 bytes thanks to histocrat.  Thanks!
->s,*i{i[x=n=k=(4*m=s=~/$/).times{i<<'  '*m}/2][j=0]=l=s[/./]
$'.chars{|c|i[k-=d=c<=>l][j+1]=%w{- / \\}[d]
i[k-=d][j+=2]=l=c
n,x=[x,n,k].minmax}
puts i[n..x]}

You can set i to an empty array using ->s,*i{. And if you replace s[0] with s[/./], I think you can replace s[1..-1] with $'.

@histocrat Great! Thanks!  I thought you needed parens for multi-param lambda declarations, but apparently that's only JS.

K, 86
{-1@+((d#\:" "),'1_,/("\\-/"1+e),'x)@\:!|/d:(|/b)+-:b:1_+\,/2#'e:{(x>0)-x<0}@-':6h$x;}

.
k){-1@+((d#\:" "),'1_,/("\\-/"1+e),'x)@\:!|/d:(|/b)+-:b:1_+\,/2#'e:{(x>0)-x<0}@-':6h$x;} "Programming Puzzles & Code Golf"
                                                        o
                                                       / \
  r                         z-z               o   e   G   l
 / \                       /   \             / \ / \ /     \
P   o   r   m-m   n       u     l   s   &   C   d           f
     \ / \ /   \ / \     /       \ / \ / \ /
      g   a     i   g   P         e
                     \ /

Ungolfed:
f:{
    dir:{(x>0)-x<0}-':[*a;a:"i"$x];          //directional moves (-1, 0, 1)
    chars:1_,/("\\-/"1+dir),'x;              //array of input string combined with directional indicators
    depths:(|/b)+-:b:1_+\,/2#'dir;           //depth for each char, normalised to start at 0
    -1@+((depths#\:" "),'chars)@\:!|/depths; //Pad each character by the calculated depths, extend each string to a uniform length and transpose
    }

Python with Numpy: 218 bytes
It is worth it to waste 19 bytes for importing numpy.
Golfed:
from numpy import*
z=zip
r=raw_input()
s=sign(diff(map(ord,r[0]+r)))
c=cumsum(s)
p=2*(max(c)-c)+1
for L in z(*[c.rjust(i).ljust(max(p))for _ in z(z(p+s,array(list('-/\\'))[s]),z(p,r))for i,c in _][1:]):print''.join(L)

Ungolfed:
from numpy import *

letters = raw_input()
#letters = 'Programming Puzzles & Code Golf'
s = sign(diff(map(ord, letters[0] + letters)))
c = cumsum(s)
lines = array(list('-/\\'))[s]

letter_heights = 2 * (max(c) - c) + 1
line_heights = letter_heights + s

columns = [symbol.rjust(height).ljust(max(letter_heights))
    for pair in zip(                    # interleave two lists of (height, symbol) pairs...
        zip(line_heights,   lines),
        zip(letter_heights, letters)
    )
    for height, symbol in pair          # ... and flatten.
][1:]                                   # leave dummy '-' out
for row in zip(*columns):
    print ''.join(row)

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


text:
Corrupted linked list
Suppose you are given a pointer to the head of a singly linked list. Normally each node in the list has a pointer to the next element, and the last node's pointer is Null. Unfortunately the list might have been corrupted so that some node's pointer leads back to an earlier node in the list.
How can I design an algorithm to detect whether the linked list is corrupted or not keeping in mind that run time is O(n).

Welcome to PPCG! The Q&A format may suggest otherwise, but this site is for programming contest. Unless you're willing to shape your question into a contest with an objective winning criterion, this is not the site for you.

See: https://en.wikipedia.org/wiki/Cycle_detection#Algorithms

please guide me what is the correct forum...i am a novice...

@Konad23 stackoverflow


text:
Interpreted Interpreter
Duplicate? I knew somebody must've done this before.

Programming a programming language in itself is something that has interested me since I knew what a programming language was. So I thought I'd create a Code Golf challenge for you.
Challenge
Create an interpreter for a given programming language, programmed entirely in itself. The interpreter should be able to run any valid program in that language, including itself.
Inputs:
The program can take it's input as a file passed as a parameter (e.g. python myfile.py) or as lines from stdin (cat myfile.py | python).
Outputs:
Whatever an interpreter would normally output, on the correct streams (stdout, stderr etc.)
Specifications

The code needs to be written in an interpretable language, and serve as an interpreter for its own language.
It can't use an eval() function to interpret code.
It must run any valid program in that language. If the language allows external modules (or includes), it must be able to read those modules.
This task is code golf. The submission with the least characters that is correct wins. In case of a tie, the solution that was submitted first wins.

Loophole remover:

Yes, if you can interpret Java, Bytecode or HQ9++ in themselves, go ahead!
In JavaScript / ES, using HTML tags such as <script> is not allowed.

Our default scoring method is bytes, not characters, because scoring in character will likely get you answers like this. You are free to choose characters over bytes if you really want to, but I thought I'd let you know about the consequences. ;)

Seems like this might be a better popularity contest than code golf- there are many extremely degenerate non-general esolangs which have simple solutions to this problem and more interesting languages have no chance of competing.

Oh well, this contest is over. Loopholes should be closed not opened.

@MartinBüttner I meant bytes! But there's no point editing now, even though the duplicate refers to an old and inactive challenge.

is tcl interp create valid?

Nothing, 0 chars
The source code is an empty file. It does nothing, like any Nothing program, therefore it is the correct execution of every such program.

Nothing doesn't satisfy our definition of programming language.

@Dennis the OP seems to explicitly accept such languages (e.g. HQ9++)

In that case, nothing beats Nothing.

@aditsu That was a joke, as there is no way to create an interpreter of HQ9++ in itself. But this is accepted.

JavaScript ES6, 44 bytes/chars
s=>document.write(`<${t='script>'}${s}</`+t)

Defines a function, taking the code string as a parameter.
How it works:
This function simply takes the code, wraps it in <script> tags, and writes it into the page. It doesn't use the eval function at all - the browser simply runs the code when the new <script> element is inserted into the page.
Tested in the FireFox console on the about:blank page as follows:
(s=>document.write(`<${t='script>'}${s}</`+t))("alert('hi')")

Yes, this is probably a loophole and as such I don't really expect to win. (It's impossible to beat the Nothing answer, anyway...)
If anything, hopefully it shows how it is possible to evaluate code in javascript without the use of the eval function.

This is a loophole. I'll add it to the Loophole remover.


text:
Dead code elimination
Dead code sits there doing nothing, staring at us knowing it will never be executed... but today we can take revenge.
Specification
The input will be a multiline string.
Each line may either be an assignment or an expression .
Assignment
An assignment is of the form <name> = number where name is a sequence of letters, underscores and numbers, but not starting with a number.
Variables may be assigned any number of times.
Expression
An expression is of the form <var_name OR number> <operation> <var_name OR number> ...
An expression may be any combination of:

Variables already defined
Basic arithmetic operators +-*/
Numbers (integers)

Expected output
You should output the string with redundant assignments, assignments that are never used by any of the expressions following it, removed. Please note that assignments can also be made redundant if an additional assignment to the same variable is performed before an expression using the variable is executed.
Test cases
in
a = 10
a * 3

out
a = 10
a * 3

in
foo = 8
2 - 1
a = 18

out
2 - 1

in
a = 10
a = 8
b = 4
ab = 72
b / 6
b + 1

out
b = 4
b / 6
b + 1

in
a = 1
a = 2
a + 1

out
a = 2
a + 1

in
FooBar1 = 0
Fuz__ = 8
Fuz__ / 1

out
Fuz__ = 8
Fuz__ / 1

in
a = 1
a + 1
a = 2
a + 1

out
a = 1
a + 1
a = 2
a + 1

in
a = 1
1 / 5 * 8 + 4

out
1 / 5 * 8 + 4

in
a = 1
a + 1
a = 1
a + 1

out
a = 1
a + 1
a = 1
a + 1

in
a = 7
5 / a

out
a = 7
5 / a

Should you add this particularly difficult case:a = 1; a + 1; a = 1; a + 1;? Where the second a  = 1 can be discarded only because a was previously set to the same value (1).

@flodel No, no need to look at values

@flodel testcase incorporated

You should add a test case where a variable is used in an expression, but not as the first element of the expression. Especially important is as the last member of the expression.

@isaacg no dead code, the var may be anywhere, testcase added

PHP - 197 bytes
The function works by analysing each line, in the reverse order and one after the other, and maintaining an array of the used variables.

If there is an equal character = in the line, it's an assignment.

It the variable is used, the assignment is useful, and the line is printed, but the variable isn't considered used any more.
Otherwise, do nothing.

Otherwise, the line is an expression. We split the line after each space, and add each symbol to the list of used variables. Numbers (1, 2, …) and operators (+, -, …) will be added too, but since they aren't valid variables names, it's not a problem. The line is then of course printed.

function($c){$u=[];foreach(array_reverse(split('
',$c))as$l){if($p=strpos($l,'=')){if(!isset($u[$x=substr($l,0,$p-1)]))continue;
unset($u[$x]);}else$u+=array_flip(split(' ',$l));$f="
$l$f";}echo$f;}

Here is the ungolfed version:
function removeDeadCode($code)
{
    $usedVariables = [];
    $finalCode = '';

    foreach (array_reverse(explode("\n", $code)) as $line)
    {
        if ($equalPosition = strpos($line, '='))
        {
            $variable = substr($line, 0, $equalPosition - 1);
            if (isset($usedVariables[$variable]))
            {
                $finalCode = "\n" . $line . $finalCode;
                unset($usedVariables[$variable]);
            }
        }
        else
        {
            $usedVariables += array_flip(explode(' ', $line));
            $finalCode = "\n" . $line . $finalCode;
        }
    }

    echo $finalCode;
}

Retina, 45 bytes
m`^(\w+) =.*\n(?=((?!\b\1\b)[^!])*(^\1 =|\Z))
<empty>

For counting purposes, each line goes in a separate file (where <empty> is an empty file) and \n should be replaced with an actual line feed (0x0A).
This assumes that the string will always end with a line feed.
As this regex doesn't use any .NET-specific features, you can test it on regex101.
The idea is fairly simple: remove all assignments from which we can find (searching forward) another assignment to the same variable or the end of the string without passing another use of the variable.

Pyth, 40 bytes
eMf|!}K\=eT&Jf}+dhceTK++dYdPT!}KeJ_.__.z

Seems kinda long. Maybe I can save one or two bytes tomorrow.
Try it online: Demonstration or Test Suite
Explanation:
_.__.z gives all postfixes of the input lines in reversed order. E.g. the input FooBar1 = 0; Fuz__ = 8; Fuz__ / 1 gives the list:
[['Fuz__ / 1', 'Fuz__ = 8', 'FooBar1 = 0'],
 ['Fuz__ / 1', 'Fuz__ = 8']
 ['Fuz__ / 1']]

Then I filter for list elements T, in which = doesn't is in the last element of T (expression) or (assignment) the last element in T, which contains the variable name, is an expression. Afterwards print the last element of each of the remaining elements on a separate line.
eMf|!}K\=eT&Jf}+dhceTK++dYdPT!}KeJ_.__.z
                                      .z  all input lines
                                     _    reverse order
                                   ._     all prefixes
                                  _       reverse order
  f                                       filter for elements T, which satisfy:
      K\=                                   K = '='
    !}K  eT                                 '=' is not in T[-1]
   |                                        or
             f             PT                 filter for elements Y in T[:-1],
                                              which satisfy:
                 hceTK                          extract variable name of T[-1]
                                                with an additional space at the end
               +d                               and at the beginning
              }       ++dYd                     ^ in space+Y+space
            J                                 assign these list to J
           &                                  J not empty and
                             !KeJ             '=' is not in J[-1]
eM                                        take the last element of each and print

Aww it's so cute... .__.

This code fails on http://pyth.herokuapp.com/?code=eMf%7C!%7DK%5C%3DeT%26Jf!xYhceTKPT!%7DKeJ_.__.z&input=a+%3D+1%0A2+%2B+a&debug=0&input_size=6

@isaacg Fixed .

Python 2, 270 267 bytes
import sys,re
d={}
s=list(enumerate(sys.stdin))
for n,l in s:
 try:v,_=l.split('=');v=v.strip();d[v]=d.get(v,[])+[[0,n]]
 except:
  for v in re.findall('[a-zA-Z_]\w*',l):d[v][-1][0]+=1
print''.join(l for n,l in s if n not in[n for x in d.values()for c,n in x if c==0])

Indentation is:
1. Space
2. Tab
Saved 3 bytes thanks to @Kamehameha!

The space after print in print ''.join and in in in [n can be removed.

Also, you can use this trick by using a tab instead of the double space after except line and saving one byte.

CJam, 49 bytes
LqN/W%{_'=#_){(<:V1$\e=_{\Va-\}&}{;S/+1}?},\;W%N*

Try it online
The approach here is that a list of unassigned variables is maintained while processing the input lines back to front:

If the line is an expression, all variables in the expression are added to the list. Actually, in the implementation, all tokens are added to the list, since it saves code and having numbers and operators in the list does not do any harm.
If the line is an assignment, it tests if the assigned variable name is in the list. If it is, the assignment is accepted, and the variable name removed from the list. Otherwise, the assignment is skipped.

Explanation :
L     Start with empty list.
qN/   Get input and split at newlines.
W%    Reverse to process lines back to front.
{     Start of filter block.
  _     Copy line.
  '=#   Find equal sign.
  _     Copy position of equal sign, will use original later to extract
        variable name from assignment.
  )     Increment to produce truthy/falsy value (-1 from find means not found).
  {     Start if-block that processes assignments.
    (<    Slice off everything but variable name.
    :V    Save in variable V for later re-use.
    1$\   Place copy of unassigned variable list and new variable name at
          top of stack.
    e=    Count occurrences. This tells us if variable name was in list.
    _     Copy the condition value because it will also be used as the
          overall filter result.
    {     Start of block that removes variable name from list.
      \V    Bring list to top, and push variable name.
      a-    Remove the variable name from list.
      \     Swap to get variable list to bottom of stack for next iteration,
            and filter result to top.
    }&    End of conditional block to remove variable name.
  }     End of if-block for assignment.
  {     Start of else-block for expression.
    ;     Pop result of find operation.
    S/    Split expression at spaces.
    +     Concatenate the new variables with the existing ones in the list.
    1     Filter result, expressions are always accepted.
  }?    End of if for assignment vs. expression.
},    End of filter.
\;    Get rid of variable list at bottom of stack.
W%    Reverse order of filtered result, since we worked back to front.
N*    Join with newlines.

JavaScript (ES6) 164 177
Using template strings, all newlines are signifcant and counted.
Test running the snippet in FireFox (required for ES6 compatibility including arrow functions)

f=s=>(k=>{s=s.split`
`,s.map((t,n)=>(r=t.match(/\w+/g)).map(v=>k[v]=f,~t.search`=`?k[s[k[v=r[0]]]=r[0]=0,v]=n:0))
for(v in k)s[k[v]]=0})([])||s.filter(r=>r).join`
`

ungolfed=s=>
{
  k={} // list line defining variables, by name, until used
  s=s.split`\n`
  s.forEach((t,n)=>
  {
    r=t.match(/\w+/g); // list variables in the line, operators are lost
    if (t.search`=` >= 0) // if it's an assignment
    {
      v=r[0] // new variable
      s[k[v]]=r[0]=0 // kill previous definition if not used
      k[v]=n
    }
    r.forEach(v=>k[v]='') // for each used variable, forget its definition line
  })
  for(v in k)s[k[v]]=0; // kill all remaining unused definitions
  return s.filter(r=>r).join`\n`
}

// TEST
out=x=>O.innerHTML+=x+'\n';

;[['a = 10\na * 3', 'a = 10\na * 3']
 ,['foo = 8\n2 - 1\na = 18','2 - 1']
 ,['a = 10\na = 8\nb = 4\nab = 72\nb / 6\nb + 1','b = 4\nb / 6\nb + 1']
 ,['a = 1\na = 2\na + 1','a = 2\na + 1']
 ,['FooBar1 = 0\nFuz__ = 8\nFuz__ / 1','Fuz__ = 8\nFuz__ / 1']
 ,['a = 1\na + 1\na = 2\na + 1','a = 1\na + 1\na = 2\na + 1']
 ,['a = 1\na + a\na = 2', 'a = 1\na + a']
 ,['a = 1\n1 / 5 * 8 + 4', '1 / 5 * 8 + 4']
 ,['a = 1\na + a\na = 2', 'a = 1\na + a']
 ,['a = 1\na + 1\na = 1\na + 1', 'a = 1\na + 1\na = 1\na + 1']
 ,['a = 7\n5 / a', 'a = 7\n5 / a']
]
.forEach(([i,k])=>(r=f(i),
  out('Test '+(r==k?'OK':'Fail')+'\nInput:  '+i.replace(/\n/g,',')
      +'\nResult: '+r.replace(/\n/g,',')
      +'\nCheck:  '+k.replace(/\n/g,',')+'\n')
));
Note: newlines trasformed to commas to save space in output

Hey, that's not 164 bytes!

@Cyphase line 1:20 + 1 newline, line 2;92 + 1 newline, line 3:48 + 1 newline, line 4:1. 21+93+49+1 => 164. The ungolfed part is for explanation only. The TEST part is ... uhm just guess ...

I know. I was just kidding. Sorry :).

R 144
Q=R=c()
for(L in rev(scan(,"",,,"\n"))){W=strsplit(L," ")[[1]]
if("="%in%W)if(W[1]%in%R)R=R[R!=W[1]]else next else R=c(R,W)
Q=c(L,Q)}write(Q,"")

where

L is a line from the input (starting from the last one)
W are the symbols (variables, operators, numbers) in a line
R is a vector of symbols that will be printed. It includes variables  whose assignment is needed.
Q is the vector of lines in the output

You can replace scan(what="",sep="\n") with scan(,"",sep="\n"). You may also be able to replace the named sep argument with its positional equivalent but I can't recall where the commas would go for that.

... saving 6. Very nice. Thank you Alex!

JavaScript ES6, 79 75 118 bytes
s=>s.split`
`.filter((l,i,a)=>(q=l.split`=`)[1]?!~(a.slice(i+1)+0).search(q[0]+'=')&&~s.search(q[0]+'[^=]'):1).join`
`

Tell me if this doesn't work for a case. Any ideas for golfing are welcome.

Explanation
s=>          // Function with argument "s"
  s.split`   // Splits each line
  `
  .filter(   // Filters through each line,
    (item,index,array)=>
      (q=l.split`=`)[1]? // If there is something after the equal sign
        !~ // XOR (~) will  essentially make -1, 0. NOT (!) will make 0, 1, vice-versa
         (a.slice(i+1)+0) // Gets following lines
         .search`^${z=q[0]}=` // Checks if following lines have the same variable name and then =
        && // AND...
         ~s.search(z+'[^=]') // Check if there is an expression with the variable
        :1) // If there is no equal sign, return 1 (true)
  .join` // Join everything back, seperated by newlines
  `

Tested on Safari Nightly. Firefox friendly version:
s=>s.split`
`.filter((l,i,a)=>(q=l.split`=`)[1]?!~(a.slice(i+1)+0).search(`^${z=q[0]}=`)&&~s.search(z+'[^=]'):1).join`
`

You can drop in in babeljs to get an ES5 version.

@Blackhole I've got that fixed.

@edc65 according to examples the separator is a newline though. Input is also in a strict format with spaces, etc.

@edc65 Are you sure? Try wrapping the function in parenthesis and run it like that. It works for me (Safari Nightly).

Maybe I'm too obstinate but I still feel it's too simple to work good in every case. I made it run without errors in Firefox adding brackets in the search call (still way shorter than mine). And tried "a = 1\na + a\na = 2". And it fails...

Thx for adding my suggestion to your answer. -1 because it's still bugged

@edc65 I think I posted the wrong version. I've updated it but I'll rewrite it and iron out the bugs

Haskell, 187 bytes
Use d.
import Data.List
f=filter
(!)=map
b((v,e,w):t)=e||or((\(_,p,_)->p)!take 1(f(\(x,_,y)->v==x||v`elem`y)t))
d=unlines.(\l->snd!f fst(zip(b!tails(((\(v:o:w)->(v,o/="=",w)).words)!l))l)).lines


text:
Shapeshifting boxes
I define four box styles:
+-----+   ooooooo    ^^^^^   *******
|  1  |   o  2  o   <  3  >  *  4  *
|     |   o     o   <     >  *     *
+-----+   ooooooo    vvvvv   *******

Write a program or function that given an integer and a string will find one of the above boxes inside the string and change its style into the box style requested by the user. For example:
1
This is a test document.
It ********* has
no *purpose* other than
dem*onstrat*ion.
   *********

Becomes:
This is a test document.
It +-------+ has
no |purpose| other than
dem|onstrat|ion.
   +-------+

You may assume that the input contains exactly one valid box that's at least 3x3. Your code must ignore incomplete/incorrect boxes:
ooooooooooooooooooooooooooooooooo
o This is not a box. o This is. o
ooooooooooo ooooo ooooooooooooooo

      ^^^^     ######
     <NOPE>    #NOPE#
      vVVv     ######

Shortest code in bytes wins.

Just to be clear, in the last example, the box with the 2 capital Vs is invalid, but if those were to be made lowercase v's, would the box still be valid? Also, if there are multiple boxes, we only need to change 1, correct?

@Vioz- Correct, the box with the capital Vs is only invalid because of the mismatched capitalization. You may assume that there will never be two or more valid boxes - there will always be exactly one valid box in the input.

Does style 3 require spaces in the corners?

@Pietu1998 Yes.

It took a moment to figure out why I was getting an odd output from my "find the box" code... your example of what is/isn't a box at the end has two valid boxes in it: o This is. o, and o This is no (with lines of o above and below, of course).

@GlenO I apologize - fixed.

No problems - it was just confusing me a bit in terms of my code's output, and I suspected it might catch other people out, too.

Julia, 995 818 713 613 bytes
g=(s,n)->(w=map;f=t->(t[z=end];for i=1:z-2,j=eachmatch(r"([*o]|(\+)|(\ ))(?(2)-|(?(3)\^|\1))+\1",t[i],1>0),k=i+2:z N=j.match;N[M=end];p=N[1];J=j.offset;u=w(i->i[[J:J+M-1]∩[1:end]],t);try p%3<1?for l=matchall(r"^([*o])\1+\1",u[k]),q=3:endof(l) w(r->r[[1,q]],u[i:k])⊆["$p$p"]&&return(i,k,J,J+q-1)end:u[k]==replace(N,"^","v")&&w(r->r[[1,M]],u[i+1:k-1])⊆[p<33?"<>":"||"]&&return(i,k,J,M+J-1)end;end);o=ones(5)';T=split(s,'\n');(i,j,k,l)=f(T);u=w(collect,T);(a,u[i][r=k+1:l-1],u[j][r],b,c)=41+[2 4 4 83 83;70o;-9 53 77 19 21;o][n,:];u[i][I]=u[j][I=[k,l]]=a;w(e->(e[k]=b;e[l]=c),u[i+1:j-1]);join(w(join,u),'\n'));

Ungolfed with explanation:
function g(s,n)
  # First, we define function f(t), which finds the box
  function f(t)
    # determine the number of rows of text
    z=length(t)
    # Get an iterator of all of the matches to iterate over
    # Regex handles all four box styles
    temp=i->eachmatch(r"([*o]|(\+)|(\ ))(?(2)-|(?(3)\^|\1))+\1",t[i],1>0)
    # Iterate over rows up to third-last one (i)...
    # and over any possible box-tops on each of those rows (j)...
    # and all possible box-bottom rows for each possible box-top (k)
    for i=1:z-2,j=temp(i),k=i+2:z
      # N holds the matched box-top
      N=j.match
      # M stores the length of the match
      M=length(N)
      # p holds the first letter of the match, the corner character.
      p=N[1]
      # J holds the position of the first character of the match in row i
      J=j.offset
      # The intersection here allows truncation of each row to only those
      # parts that lie within the valid range of the box-top
      u=map(i->i[[J:J+M-1]∩[1:end]],t)
      # A try block is being used to skip if a BoundsError is encountered
      # this BoundsError will occur if a box cannot be formed due to
      # a row not being long enough to form both sides or to form bottom
      try
        # This distinguishes between simple boxes (types 2 and 4)
        # from fancy boxes (types 1 and 3), as code differs between them
        if p%3<1 # "then" for simple boxes
          # loop over l either doesn't run (if bottom won't form a match
          # from position 1 within u) or holds the unique match
          # then loop over q looks at all possible bottom-lengths
          for l=matchall(r"^([*o])\1+\1",u[k]),q=3:endof(l)
            # If box sides are found to match top and bottom...
            if map(r->r[[1,q]],u[i:k])⊆["$p$p"]
              # return the coordinates of the box
              return(i,k,J,J+q-1)
            end
          end
        else # "else" for fancy boxes
          # If the bottom matches the top (replace fixes for type 3)...
          if u[k]==replace(N,"^","v")
            # ... and the edges are also there...
            if map(r->r[[1,M]],u[i+1:k-1])⊆[p<33?"<>":"||"]
              # return the coordinates
              return(i,k,J,M+J-1)
            end
          end
        end
      end
    end
  end
  # That defines function f(t), now for the replacement part of the code
  # Input s is a single string with newlines, split into separate strings
  T=split(s,'\n')
  # Find the coordinates of the box using f(T)
  (i,j,k,l)=f(T)
  # u holds the same strings, but stored as char arrays
  u=map(collect,T)
  # Here, we have the appropriate replacement characters for each type
  # with n determining which character from each array is taken
  # Variable names are used here to make it clearer
  corners =  ['+';'o';' ';'*'][n]
  topedge =  ['-';'o';'^';'*'][n]
  bottomedge=['-';'o';'v';'*'][n]
  leftedge = ['|';'o';'<';'*'][n]
  rightedge= ['|';'o';'>';'*'][n]
  # Assign the appropriate characters in the appropriate places
  u[i][[k,l]]=corners
  u[j][[k,l]]=corners
  u[i][k+1:l-1]=topedge
  u[j][k+1:l-1]=bottomedge
  # Iteration is required here because it's an array of arrays
  for e=i+1:j-1
    u[e][k]=leftedge
    u[e][l]=rightedge
  end
  # All that's left to do is recombine to form a single string again
  # we join each internal char array into single-line strings...
  # then join the strings together with a newline delimiter, and return
  return join(map(join,u),'\n')
end

Contrary to how I first approached it, this code will only work correctly for "valid" type numbers - 1, 2, 3, or 4. It is split into two parts - a box-finder, and a box-replacer. The box-finder code, function f(t), uses regex to locate tops and, for the simpler boxes (types 2 and 4), bottoms.
The first regex is the simplest way I could find to find the box-tops. Here's the logic of it:
r"([*o]|(\+)|(\ ))(?(2)-|(?(3)\^|\1))+\1"
  ([*o]|(\+)|(\ ))                        < This finds the first corner
        ( 2) ( 3)                         . if a + or space, conditionals
  (    1         )                        . kick in, so they're captured
                                          . separately
                  (?(2)-|           )     < If a +, top edge must be
                                          . at least one -
                         (?(3)\^|\1)      < Otherwise, if a space, top
                                          . edge must be at least one ^,
                                          . otherwise, repeat the corner
                                     +    < Allows more than one top-edge
                                          . character
                                      \1  < finish with the same corner
                                          . char found at the start

The code is used like this:
julia> s="""This is a test document.
       It************* has
       no *purpose* other than
       dem*onstrat*ion.
        ************o""";

julia> print(s)
This is a test document.
It************* has
no *purpose* other than
dem*onstrat*ion.
 ************o
julia> print(g(s,1))
This is a test document.
It*+-------+*** has
no |purpose| other than
dem|onstrat|ion.
 **+-------+*o

Printing is not included in the function, as the output format isn't specified - I just return the string, you can print it afterwards as seen above.


text:
Stop, stand there where you are!
Challenge
Write a function which takes one parameter: an integer t. Your function has to stop your program for t seconds before continuing, similar to time.sleep(t) in Python and WAIT t in BBC BASIC.
You must not use any built in waiting functions or any built in functions for executing code after a certain time, and your program must resume after t seconds.
For testing your function, there is tolerance of 0.1 seconds more or less than the given t on your own machine: variances between computers are fine.
If your answer is challenged by anyone, you must provide photographic (screenshotted) proof that your function works correctly for t=1, t=5 and t=25. You may also provide the details of your computer so people can try to replicate it on their own machine.
Your program should and will be run on a computer whose clock speed is 1.6 GHz or higher.
Winning
The shortest program wins.
Bounty
A bounty will go out to the shortest program which stops the program without using a loop checking how much time has elapsed. If you are in the running for this bounty, add a footnote saying that your answer is for the bounty.
Leaderboard

/* Configuration */

var QUESTION_ID = 55293; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 30525;

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var patt = new RegExp(/[Bb]ounty/);
    var res = patt.test(body);
    var bountyyn = "no";

    if (res) {
      bountyyn = "yes";
    }

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
        bounty: bountyyn
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link)
                   .replace("{{BOUNTY}}", a.bounty);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 400px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size	Bounty?

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	{{BOUNTY}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

What if our programming language of choice (cough cough) only supports getting the time to 1-second accuracy?

@Doorknob Well the input is an integer, so that's fine

But what about the rule "For testing your function, there is tolerance of 0.1 seconds more or less than the given t on your own machine: variances between computers are fine."?

@Doorknob perhaps you can measure execution time outside of your program, e.g. debug output and look at the time stamps of DebugView.

Is the title and the BBC BASIC example a reference to the tv show Sherlock or am I reading too much into this?

@Fatalize Nope, not at all :)

Well at least it made you realize that your title was inexact ;)

@Fatalize Exactly :D

@Justin Only if you don't use Timer.schedule

@BetaDecay Nice song! :-)

@LuisMendo Thank you :D

@BetaDecay Thanks for the edit!

@LuisMendo Oh, uh no problem :)

x86_64 machine code, 10 bytes
Hexdump of the code:
48 69 c9 ca fc 59 38 e2 fe c3

Source code (can be assembled by ml64 of Visual Studio):
    TITLE   heh

PUBLIC  mywait
_TEXT   SEGMENT
mywait  PROC
    imul rcx, 945421514
myloop:
    loop myloop
    ret
mywait  ENDP
_TEXT   ENDS
END

Performs an empty loop, starting from the specified value down to 0. I chose the multiplier 945421514 empirically by trial and error, until my test program output satisfactory results.
Test program (waits 10 times for each of the durations 1, 5 and 25 seconds):
#include <stdio.h>
#include <time.h>

extern "C" void mywait(int);

int main()
{
    int durations[] = {1, 5, 25};
    for (int duration: durations)
    {
        for (int i = 0; i < 10; ++i)
        {
            clock_t before = clock();
            mywait(duration);
            clock_t after = clock();
            printf("%f\n", (after - before) / (double)CLOCKS_PER_SEC);
        }
    }
    getchar(); // now take a screenshot
}

The result:
1.003000
1.000000
1.004000
1.006000
1.005000
0.998000
0.995000
1.000000
1.005000
1.004000
4.999000
5.003000
5.035000
5.010000
4.992000
5.003000
5.003000
5.019000
5.026000
4.989000
25.041000
24.993000
25.049000
24.988000
25.038000
24.948000
25.007000
25.014000
25.053000
25.021000

I ran this program on a Windows computer that has nothing else to do. If it runs some applications, the waiting times are more erratic.
The CPU speed is 3.9 GHz. It seems that this code is barely good enough for current PC technology - if the clock frequency is about 8.8 GHz, the multiplier will not fit into a signed 32-bit int.

P.S. As this answer doesn't check how much time has passed, it is a candidate for the bounty.

This is cool :D

3900 GHz ? Woah ! Maybe MHz ?

@WayToDoor Fixed! Also added some fun info related to that.

If I understand your approach correctly: if the computer is devoting only half processor time to the program, the waiting times would be double?

@LuisMendo Yes, and it's never exactly half, so waiting times would be very inexact.

Although I'm loosing the opportunity to receive bonus for my answer, I think fair play is important and I advice you mark your answer as the program does not test how much time has elapsed

@anatolyg I'm not sure it really answers the challenge then? "Stop your program for t seconds before continuing"

@LuisMendo Depends on how you want to interpret the rules. It seems that your interpretation is "... in any conditions" while my interpretation is "... in any favourable conditions". Here in PPCG, we are pretty much used to make strong assumptions (e.g. using the default-int rule in C), which are absolutely unacceptable in modern software. In addition, OP's intent seems to be that solutions depending on CPU speed are OK: "...on your own machine: variances between computers are fine..."

The source is 142 bytes, so that's what this answer should be scored as.

@PeterTaylor 142 bytes in assembly language; much less in machine code. These are different languages; in my opinion machine code is more fun (however, assembly language would be better in a [restricted-source] challenge). The problem with machine code is that it's non-ASCII, and I think it's not a big problem. A related issue is discussed here; should I (or you) start a discussion on machine code there?

Basically I'm saying the same thing as the comment to the answer you link to.

The right tool for the job.

Bash, 29 25 24 23 19 bytes
w()(ping -t$1 1.2)

Accuracy test (time) where $1 = 1 second:
real    0m1.012s
user    0m0.001s
sys     0m0.002s

Thanks Dennis for shaving the byte count down to 19 from 23!
EDIT: I've changed the IP to avoid ping on Linux pinging 0.0.0.0, which is the loopback device.

How this works
ping has a default timeout of 1 second, so, when contacting an IP address which does not exist, ping can't continue until either the time out has passed, or it has got a reply from the IP.
-t tells ping to try $1 number of times on this fake IP address, forcing ping to take $1 seconds to complete the ping.

It's eligible for the bounty! No loop!

Golfed: w()(ping -t$1 0.0) (We must have different pings; mine requires -w$1 and gets a reply from localhost.)

Right, then it must only work on OS X with no /dev/lo

Change 0.0 to 1.2 on Linux

On OS X, for w 10, I get 10.02 sec real using time.

w()(ping -w$1 1.2) works like a charm.

This is clever :D

Matlab, 33 bytes
function f(t)
tic;while toc<t,end

Or you can also use this in Octave: try it online
Matlab, 31 bytes
As suggested by @flawr, it can be done with an anonymous function (it should be assigned a name in order to use it):
@(t)eval('tic;while toc<t,end')

Example:
>> f=@(t)eval('tic;while toc<t,end');
>> tic, f(2), toc
Elapsed time is 2.000323 seconds.

Tic ... Toc ... Tic ... Toc

If an unassigned function handle is ok too, you could also use @(t)eval('tic;while toc<t,end')

@flawr Wow! very nice trick, using eval to pack several statements in an anonymous function. Thanks!

Yes, that is sometimes a usefull trick, but you still cannot asign values to variables even within eval. I am still working on a way to abuse function handles for recursive functions=) PS: You do not necessarily have to assign a name to the function handle, sometimes you can also pass the handle directly as an argument to another function, e.g. for bsxfun.

+1, but the anonymous function version does not work in Octave (v 3.8.1). It fails to recognize t variable inside eval.

@pawel.boczarski Thanks! Corrected

Java, 63 62 bytes
t->{for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;);}

Nothing surprising - just grabs the number of nanoseconds since 1/1/1970 multiple times and checks if a second has passed.
Saved 1 byte thanks to Ypnypn and aditsu.

Yay! A Java program below 100 bytes ;D

@BetaDecay Except it's not actually a program.

Didn't somebody mention you can shorten it with a for? for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;);

What's with the t->?

@Luminous It's a lambda expression, commonly used in Java 8.

Java has lambda? Java is becoming more like Python :D

Batch, 27 Bytes
set /a c=%1+1
ping -n %c% 0

A popular batch trick, since batch didn't have a sleep function.
No loop, so bounty eligible

Golf: set/ac=%1+1 saves 2 bytes.

JavaScript ES6, 50 45 40 bytes
n=>{for(g=Date.now,z=g();z+n*1e3>g(););}

this uses self-executing functions, not sure why +new Date isn't working.

Usage
I've tested this with Safari Nightly but it will also work on Firefox. Tested with:
(
  n=>{for(g=Date.now,z=g();z+n*1e3>g(););}
)(1); // 1 is the delay is seconds
console.log( 'foo' );

You can run it by either surrounding it with parenthesis:
( n=>{for(g=Date.now,z=g();z+n*1e3>g(););} )(5)

Or by naming it:
const wait=n=>{for(g=Date.now,z=g();z+n*1e3>g(););}
wait(5)

Explanation
Here's the main logic behind the program:
function (n) {
    var start = Date.now();   // Save start time (ms)
    while (                   // while is synchronous, it'll block the code execution until it has finished
           start + (n * 1000) // This is the end time (start + delay)
            > Date.now()      // When the current time is 1 ms past the target end time, stop. resuming the code execution
          );
}

The version I'm using uses the same logic:
n=>{ // Function with argument n, { is required if the functions is not just an expression
   for(           // For will also block code execution
                  // This first part is used to define variables
      g=Date.now, // Add an alias for Date.now as "g"
      z=g()       // get current time and store in z
      ;           // Next part, condition
      z + n*1e3   // Target end time, ( start + delay (converted to seconds) ) 1e3 is 1000 but in big e notation
      ;           // Is required for a valid for loop
   );
}

Commodore 64 BASIC, 19 16 bytes
1000 FORI=1TO930*N:NEXT:RETURN

With a call N=<number-of-secods>:GOSUB1000.
However, I cannot provide enough accuracy. Because C64 had about 1 MHz CPU speed, I remember it was good enough to make an empty FOR-NEXT loop 1000 times so that it was about 1 second.
In fact there were two main versions of the machine: PAL 0.985 MHz and NTSC 1.023 MHz (all data from C64 Wikipedia Page). As I had NTSC version, it was required to run loop about 930 times.
Tests with the following program (N seconds, provided by user in INPUT):
10 INPUT N
20 PRINT TI$
30 GOSUB 1000
40 PRINT TI$
50 END
1000 FOR I=1 TO 930*N:NEXT I:RETURN

where TI$ is a system variable containing string (hhmmss format) with time elapsed from last reset (1 second accuracy, however also depending on CPU speed, so this is not quite relevant, because it's the same clock).

Screenshot made with online C64 emulator http://codeazur.com.br/stuff/fc64_final/.
This program (line 1000 only) occupies 16 19 bytes in memory, as tested with PRINT FRE(0)+65535 both before typing the code (38908 bytes) and after (38893 38889 bytes). PRINT FRE(0) returns free memory for BASIC program (it's a negative value and constant 65535 should be added, but in fact it does not matter).
Because this program does not test the time elapsed in a loop, it qualifies for a bounty.

I remember I did perform a test how TI$ variable is accurate and it was about 1 second per ca. 2 hours difference with the reference clock (outside C64), so the accuracy is enough. What I am unsure is the value 950, however, would it be any other value <1000 (which I am sure), it's still the same amount of bytes

I think the J variable should somehow be a part of the real code, not a part of the testing program - so it would wait for N seconds, not just 1 second. I don't know how to integrate it into BASIC's syntax though.

@anatolyg Hm, you are right, it should be something like 1000 FOR I=1 TO N:FOR I=1 TO 950:NEXT I:NEXTJ:RETURN with a call eg. 200 N=5:GOSUB 1000. Also I've noticed the OP required a function. I will try to fix it

@anatolyg I have corrected, it uses GOSUB-RETURN statement, as there are no functions in BASIC

@Voitcus Not even DEF FN like in BBC BASIC?

@BetaDecay Yes, there is DEF FN, however, it's only mathematical function. It does not allow to have any statements within. I think GOSUB is the only equivalent for the function that does not return value only.

JavaScript, 68 54 51 42
I think no screenshot is needed. But I suspect you could golf this even more...
New version: I now finally managed to avoid new and using Date twice:
f=t=>{for(x=(d=Date.now)();d()<x+t*1e3;);}

Older versions:
f=t=>{for(x=new Date();(new Date()|0)<x|0+t*1e3;);}

f=t=>{x=(new Date())|0;while((new Date()|0)<x+t*1e3);}

f=t=>{x=new Date().getSeconds();while(new Date().getSeconds()<x+t);}

No screenshot is needed now :) Only if someone challenges this program

CJam, 15
{e3es+{_es>}g;}

This is a block that can be executed or stored into a variable (thus becoming a named function). Dennis and Mr Consensus agree that counting only the block is acceptable :)
Explanation:
e3       multiply the argument by 1000 (to get milliseconds)
es       get the current timestamp in milliseconds
+        add the values, obtaining the stopping time
{…}g     do…while
  _      duplicate the stopping time
  es>    check if we reached that time yet (loop condition)
;        discard the stopping time

Try it online

Consensus on Meta is that functions do not have to be named, so I'd argue that a block left on the stack is just as usable as a lambda.

Julia, 33 20 bytes
t->watch_file(".",t)

Only works in Julia v0.4 due to changes in the function signature of watch_file. Defines an anonymous function with a single parameter t that (ab)uses the timeout parameter in the watch_file function.
This is a candidate for the bounty!
Demonstration using the Julia REPL:
julia> f=t->watch_file(".",t)
(anonymous function)

julia> @elapsed f(1)
1.002134983

julia> @elapsed f(5)
5.006161965

julia> @elapsed f(25)
25.026096192

Previous answer (33 bytes), also working in Julia stable
t->(b=time();while b+t>time()end)

PHP, 171 177 84 79 65 64 62 bytes
<?php function a($i){for($f=microtime,$e=$f(1)+$i;$f(1)<$e;);}

Usage:

Call the function like so:

php -d error_reporting=0 -r "require 'script.php'; a(5);echo 'Hello, World!';"

Where 5 is the time in seconds the programm should wait before it echoes "Hello, World!".

Explanation:

At first the function gets the current time in milliseconds. Then the function does a loop until the current Time is smaller then the first time + the input.
Afterwards "Hello World!" gets echo'ed.

Log:

Saved 113 bytes thanks to Voitcus

Saved 2 bytes thanks to axiac

I would change while($t<$i) (one byte less). Also because if something goes wrong and PHP process would be delayed, it will not go to an endless loop. Also, why not use microtime(true)? This removes all this list() staff. I would do this like function a($i){$e=microtime(true)+$i*1e6;while(microtime(true)<$e);} (not tested). Also you could change true to 1. Probably you could use $u+.0 instead of (float)$u.

@Voitcus microtime(1) should be documented somewhere ... Thanks for the help!

It is - see manual, $get_as_float parameter. Also remove $t, $s - you don't need them (see my code)

@Voitcus I think the "*1e6" is not right

1e6 = 1000000 one million. echo 1e6; works. But yes - getting as float is number of seconds, so $e=microtime(1)+$i; would be enough

A working fiddle for you

You can save 2 more bytes (3 bytes on PHP 7): https://3v4l.org/fU11Y

More two bytes if change <?php to <?

Windows CMD, 22 bytes
ping -w 1000 -n %1 1.1

This uses no loop (label and goto) so this qualifies for the bounty
It sends t pings to to 1.0.0.1 (invalid) and waits for a responce for 1000 ms

R, 48 bytes
f=function(t){a={g=Sys.time}();while(g()<a+t){}}

Demonstration:
t0 <- Sys.time();f(1); Sys.time() - t0
## Time difference of 1.000272 secs

t0 <- Sys.time();f(5); Sys.time() - t0
## Time difference of 5.011189 secs

t0 <- Sys.time();f(25); Sys.time() - t0
## Time difference of 25.00848 secs

I don't think you need to include the f= in the byte count, function snippets are fine.

PHP, 39 bytes
function a($a){while($i++<.4583e8*$a);}

(Note that I can actually get this shorter if a full program is required by taking advantage of arguments passed on command line. Down to 35)
<?php while($i++<.4583e8*$argv[1]);

Program used for testing:
<?php function a($a){while($i++<.4583e8*$a);}

record(1);
record(5);
record(25);

function record($t)
{
    $time = microtime_float();
    a($t);
    echo microtime_float() - $time."\n";
}

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

Results:
JamesWebster:Documents jameswebster$ php A.php
1.0093479156494
4.9945771694183
24.971961975098

Though I qualify for the bounty, I'm hardly in the running with some of the other entries!

Yep, your byte count is fine

TI-BASIC (84+SE), 21 bytes
Input method: T:prgmT. This is the closest equivalent of a function in TI-BASIC. Program:
For(A,1,841Ans
End

All accuracy is gained via trial-and-error; timing it with a stopwatch works for all of the given test cases to within a twentieth of a second.
Device information:
RAM FREE   23312
ARC FREE  889802

 TI-84 Plus Silver Edition
          2.55MP
PROD #: 0A-3-02-37
ID: 0A3DC-C3469-FFE8

W00T eligible for a bounty!

Did you know: the speed of your calculator's For( loops depends on how many letter variables exist? More variables clog up the VAT and can take up to 20% or so of your time. System variables (e.g. n, Xmin) are immune.

@ThomasKwa Huh! Interesting. I'll recalibrate with a clean calculator when I have the time to transfer files.

JavaScript ES6, 40 bytes
t=>{for(t=(d=Date.now)()+t*1e3;d()<t;);}

Tested with the following:
elapsed=(f,t,b=(d=Date.now)())=>(f(t),console.log(d()-b+"ms elapsed")) // accepts func, delay
STOP=t=>{for(t=(d=Date.now)()+t*1e3;d()<t;);}
elapsed(STOP,1)  // prints 1000ms elapsed
elapsed(STOP,5)  // prints 5000ms elapsed
elapsed(STOP,25) // prints 25000ms elapsed

Can you explain what elapsed(STOP, t) does? What are STOP and elapsed?

elapsed measures the time it took the first argument to run, in this case, STOP, which in turn is just the first code snippet. The second arg to elapsed is the arg passed to STOP.

Python, 57 bytes
import time
b=time.time
def y(i):
 x=b()
 while x+i>b():x

Call function y()

PureBasic, 92 bytes
Procedure z(t)
t=t*1e3+ElapsedMilliseconds()
While t>ElapsedMilliseconds():Wend
EndProcedure

It's the shortest I can think of. I suspect this will be the longest here as well...
To test:
OpenConsole()
i=Val(Input())
s=ElapsedMilliseconds()
z(i)
PrintN(Str(ElapsedMilliseconds()-s))
Input()

PowerShell, 75 bytes
Long, descriptive procedure calls. Yay for clarity in a language. :)
function w{param($i);$n=(Get-Date).AddSeconds($i);while($n-gt(Get-Date)){}}

Called within a program with something like
Get-Date
w(15)
Get-Date

Alternatively, if we're allowed external programs to be called instead, we can get down to 59 Bytes with the following:
$n=(Get-Date).AddSeconds($args[0]);while($n-lt(Get-Date)){}

This would be called within a program as follows (presuming the above to be saved as "wait-function.ps1" and saved in the same folder):
Get-Date
& ((Split-Path $MyInvocation.InvocationName) + "\wait-function.ps1 15")
Get-Date

What we save in writing the function/program is more than clobbered by the excess needed to actually execute it, though. Le sigh.

Python, 66 bytes
Note, my implementation neither calls an inbuilt time function, nor using scheduling feature.
def S(t):
 try:__import__("Queue").Queue().get(1,t)
 except:pass

And yes, it is eligible for bounty.

Nope, this invalid: You must not use any built in waiting functions or any built in functions for executing code after a certain time

@BetaDecay: As per my understanding, Queue().get is not a  "built in functions for executing code after a certain time". Please explain why this would qualify as one.

Many other answers have code that uses timeouts for other things, so this should be fine too.

Pyth, 19 bytes
Late entry but after finding .d0 in the docs last night I decided to give it a go.
DCNK.d0W<-.d0KNJ1))

Defines a function which loops until the time elapsed is N seconds.
Try it here.

Nice. I got DCNJ+.dZN#Ig.dZJB)), which is also 19 bytes.

Hassium, 55 Bytes
func w(t){p=time().second;while((p+t)>time().second)0;}

Run and see expanded: http://HassiumLang.com/Hassium/index.php?code=9f4e2bdb292b14b150fba63677a11a79

Just checking, when was this language first created?

August 9th 2015

RProgN 2, 13 bytes
°°°)*™+]³]™>:

Explained
°°°)*™+]³]™>:
°°°             # Push 3 tens to the stack.
   )*           # Get the product of the entire stack, including the implicit input. This is the shortest way to multiply the input by 1000.
     ™+         # Add it to the current time in miliseconds.
       ]        # Duplicate it to use as a (throwaway) conditional.
        ³   :   # Create a function using the next 3 concepts, and while the top of the stack is truthy, execute it.
         ]      # Duplicate the target time
          ™>    # Is it larger than the current time?

The bounty specifically says "without using a loop checking how much time has elapsed", which this does not do. This sets a target time, and keeps checking if it's passed that target time, thus it's eligible for the bounty.
Try it online!

Tcl, 53 bytes
proc W t {while "\[clock mil]-[clock mil]<$t*1e3" {}}

Try it online!
Explained
Command clock milliseconds can be reduced to clock mil, with escaped 1st bracket, it'll be interpreted at each loop, and w/o just once.
As it measures milliseconds, we need to multpily by 1000 or 1e3 which saves 1 Byte.

C# (Visual C# Interactive Compiler) + /u:System.Threading, 36 bytes
x=>new SemaphoreSlim(0).Wait(x*1000)

Try it online!
Creates a semaphore with no capacity and tries to get it for the specified number of seconds.
I realize I am "wait"ing on something here. To me this seems more like the ping/timeout solution as opposed to Thread.Sleep. The code tries to get a resource that it cannot get and stops trying after a limit.
===
Below is a variation that starts a Task with an infinite loop, then waits for it to complete with a timeout. All required namespaces are included by default, but the solution is a few bytes longer than the one above.
C# (Visual C# Interactive Compiler), 40 bytes
x=>Task.Run(()=>{for(;;);}).Wait(x*1000)

Try it online!

Vyxal, 9 bytes
kṡ+{:kṡ>|

Try it Online!
For accuracy, use the offline interpreter, dowloadable via the link in the header.
kṡ        # Push current epoch, in seconds
  +       # Added to input
   {    | # Until
     kṡ   # Current epoch
    :  >  # Is greater than this
   {    | # Loop

SmileBASIC, 20 bytes
INPUT T
DIALOG"",,,T

Opens a dialog box that closes automatically after T seconds.
I'm not sure if this counts as a "built in waiting function", but I think this is just as valid as using ping.
An alternative 37-byte program which definitely isn't cheating:
INPUT T
FADE.,T*60WHILE FADECHK()WEND

Causes the screen fade color to change to 0 (alpha=0,red=0,green=0,blue=0) (no effect) gradually over T seconds, then waits for that animation to finish.

05AB1E, 22 bytes
žcžb60*+[Džcžb60*+αIQ#

Try it online.
NOTE: Depending on how many microseconds in the current second have already passed, the tolerance might be slightly larger than 0.1 sec. But since almost halve the answers have similar issues, I figured it's allowed.
Explanation:
05AB1E doesn't have any builtins for the current time. It does however have a builtin for the current year/month/day/hours/minutes/seconds/microseconds as separated builtins. Since only using seconds can potentially wrap around from 59 to 0 causing issues, I need both the minutes and seconds, making the code even longer than most answers in non-codegolfing languages unfortunately.
žc                # Push the current seconds
  žb              # Push the current minutes
    60*           # Multiply it by 60
       +          # Add them together
[                 # Start an infinite loop:
 D                #  Duplicate the initial (minutes*60 + seconds) from before the loop
  žcžb60*+        #  Push the current (minutes*60 + seconds) again
          α       #  And take the absolute difference between the two
           IQ     #  And if this is equal to the input:
             #    #   Stop the infinite loop

QB64, 31 bytes
Infinite loop until the time has elapsed
t=TIMER:DO:LOOP UNTIL t-TIMER>n


text:
Solve a game of Accordion
Accordion is a solitaire card game I recently came across where nearly every layout is solvable, but incredibly hard.  You can play it here.
Rules
52 face cards are placed face-up in a random order.  Each turn, you replace a card with a later card, where the two cards:

Share a suit or number and
Are at a distance of 1 (adjacent) or 3 (two cards in between).

The game is won when there is only 1 card remaining.  You can assume that each input is solvable.  The replaced card must always precede the replacing card.
Example
As an example, consider the following layout:
2H,2S,1S,2D  (H: Hearts, S: Spades, D: Diamonds)

There are 3 possible moves here:

Replace the 2H with the adjacent 2S, so we end up with 2S,1S,2D
Replace the 2S with the adjacent 1S, so we end up with 2H,1S,2D
Replace the 2H with the 2D (at a distance of 3), so we end up with 2D,2S,1S

Of those 3 moves, only the last one has the possibility of winning (You win by replacing 2D <- 2S, then 2S <- 1S).
Input/Output
Your job is to write an Accordion solver.  You are passed a list of cards, and you need to return a list of moves to solve the game.
You are passed a list of cards as a comma-delimited string, where each card is passed as an integer representing their numeric value, then a character representing their suit.
You must return a list of replacements as a comma-delimited string, where each replacement is in the format Card <- Card (following the card format described above).  The first card in each pair is the card being replaced.
Test cases:
5H,1C,12S,9C,9H,2C,12C,11H,10C,13S,3D,8H,1H,12H,4S,1D,7H,1S,13D,13C,7D,12D,6H,10H,4H,8S,3H,5D,2D,11C,10S,7S,4C,2H,3C,11S,13H,3S,6C,6S,4D,11D,8D,8C,6D,5C,7C,5S,9D,10D,2S,9S
5H,9C,11H,7S,7D,12D,6H,10S,3H,4D,12C,2S,3C,5C,7H,6S,1H,8S,2H,11S,4C,10D,12H,9H,2D,4H,6C,13H,11C,2C,10H,8C,1S,11D,3S,12S,7C,5D,13S,8D,4S,6D,13C,3D,8H,13D,1D,9D,9S,1C,5S,10C
7H,11C,8C,7S,10D,13H,4S,10C,4D,2C,4H,13D,3C,2H,12C,6C,9H,4C,12H,11H,9S,5H,8S,13S,8H,6D,2S,5D,11D,10S,1H,2D,5C,1C,1S,5S,3H,6S,7C,11S,9C,6H,8D,12S,1D,13C,9D,12D,3D,7D,10H,3S

While this competition is a code-golf, I am particularly interested in time-efficient solutions, and am likely to reward ingenious solutions with bounties.  That said, solutions that take astronomical amounts of time are still acceptable (I'd recommend testing with a smaller deck, such as a 16-card, 4 suit deck).

Do your rules mention that the moves can only be made in one direction?

Yes.  "The replaced card must always precede the replacing card"

Every card on the table has on average about 0.25 + 0.25 = 0.5 legal moves. Therefore the search space is about 52! * 0.5 = 4E67. The challenge as written (with code golf tag) can only be interpreted as being required to search this entire space and report any solution (or "none" if exhausted), which leaves little room for ingenuity and requires astronomical timescales. I suggest you make this a code challenge, considering success rate and time, and either reduce the influence of code length on the score or eliminate it altogether.

Counting the number of possible game states instead of paths I get a smaller number: around 4^52 = 2E30. Still, this is too large to search exhaustively

@steveverrill I have a golfable Python program that solves the test cases in about 2 seconds. I believe this shouldn't be too bad as a code-golf if the program is required to terminate in a reasonable about of time.

@Pietu1998 Can your program be mathematically demonstrated to be capable of solving all possible test cases? If not, then by my interpretation of the current rules it's an invalid (but interesting) entry. They suspected that Rubik's cube could always be solved in 20 moves once they had analysed all symmetrical positions. But it wasn't proved until decades later, when all positions were exhaustively searched. If the requirement is to solve the test cases that should be stated, but it would make the question vulnerable to hardcoding. With that approach, a wider set of test cases would help

An alternative for exhaustive searches (which is what the current rules appear to require) would be to use a reduced deck of 16 cards, giving a search space of 4^16 = 2^32, which can be fully searched in a few minutes.

@steveverrill Well, my program just does a depth-first search through all possibilities. I assume that'd mean a trivial test case might take 1000 years.

@steveverrill There are unsolvable accordion games. For example KC QD JH TS 9C 8D 7H 6S 5C 4D 3H 2S AC
KD QH JS TC 9D 8H 7S 6C 5D 4H 3S 2C AD
KH QS JC TD 9H 8S 7C 6D 5H 4S 3C 2D AH
KS QC JD TH 9S 8C 7D 6H 5S 4C 3D 2H AS. But the question assumes a solvable input.

@orlp indeed CDHS repeated 13 times is not solvable. The question does not currently state that the input will be solvable, nor is there any bound on how difficult it might be to solve. That's why I think this question as it stands is too broad, unless someone can come up with a decent mathematical analysis. I like the question though. (As an example of the issue I am trying to highlight, consider that there are implementations of quicksort which work great on random input, but run at a snail's pace when fed an already sorted input.)

@steveverrill The question does state that: " You can assume that each input is solvable. " And for fun: https://github.com/orlp/pdqsort .

Orlp: Oops, I missed that. Given that @Pietu1998 says he has found a reasonable average time complexity (which is an important discovery), maybe the question is  OK as it is, despite the fact that the worst case time complexity may be astronomical.

@steveverrill Well, my solution is astronomically slow without memoization, but by adding a memoizer it's rather quick.

@Pietu1998 and therein lies the problem. I assume the memorizer is costing you bytes, so you should submit the version without the memorizer as the golfed version, but then it becomes impossible to test on a 52 card deck. Codegolf doesn't work well as a scoring system on problems with large search spaces.

@steveverrill Well, I could submit both versions. The memoizer [sic] does not change the behavior of the program, so I believe I can still claim the byte count of the golfed program while testing with the memoizer.

I'm ok with astronomical runtimes for those wanting to be code-golf competitive.  However, people are certainly able (and encouraged) to post answers that aren't competitive, and are about run-time.

Furthermore, if you are wanting to test a code-golf solution, a 52-card deck is not needed.  A 16-card (4 suit) deck should provide short runtimes, and verify correctness.

@NathanMerrill With that clarification, I've retracted my close vote, and upvoted the question. I suggest you edit those points into the question. Note that according to my analysis, 16 cards in worst case might still take several minutes.

Python 3, 274 272 271 bytes
2 bytes saved thanks to @orlp.
def g(p):
 q=lambda a:[[i,a]for i in range(len(p)-a)if p[i][:-1]==p[i+a][:-1]or p[i][-1]in p[i+a]]
 for n in q(1)+q(3):
  s=sum(n);c=p[:s]+p[s+1:];c[n[0]]=p[s]
  if g(c):return p[n[0]]+' <- '+p[s]+','+g(c)
 return' 'if len(p)<2else[]
print(g(input().split(','))[:-2]or'')

This is extremely slow. However, you can try it with a memoize. This has a few extra list-tuple conversions, but is otherwise equivalent.
import functools
@functools.lru_cache(maxsize=None)
def g(p):
 q=lambda a:[[i,a]for i in range(len(p)-a)if p[i][:-1]==p[i+a][:-1]or p[i][-1]in p[i+a]]
 for n in q(1)+q(3):
  s=sum(n);c=list(p[:s]+p[s+1:]);c[n[0]]=p[s]
  if g(tuple(c)):return p[n[0]]+' <- '+p[s]+','+g(tuple(c))
 return' 'if len(p)<2else[]
print(g(tuple(input().split(',')))[:-2]or'')

Even this one is astronomically slow with certain inputs.
The code uses strings, not numbers, so it also supports notation like KH instead of 13H.
Example:
$ python accordion.py
5H,9C,11H,7S,7D,12D,6H,10S,3H,4D,12C,2S,3C,5C,7H,6S,1H,8S,2H,11S,4C,10D,12H,9H,2D,4H,6C,13H,11C,2C,10H,8C,1S,11D,3S,12S,7C,5D,13S,8D,4S,6D,13C,3D,8H,13D,1D,9D,9S,1C,5S,10C
7S <- 7D,7D <- 12D,3C <- 5C,12H <- 9H,11C <- 2C,3S <- 12S,13D <- 1D,1D <- 9D,9D <- 9S,2S <- 6S,7H <- 1H,6S <- 8S,1H <- 2H,8S <- 11S,2H <- 9H,10D <- 2D,9H <- 4H,4H <- 4C,5C <- 4C,4D <- 4C,4C <- 12C,10S <- 11S,11H <- 11S,6H <- 3H,12D <- 2D,12C <- 2C,2C <- 6C,6C <- 8C,12S <- 13S,5D <- 6D,6D <- 8D,8D <- 3D,4S <- 9S,13S <- 9S,11D <- 3D,7C <- 1C,1S <- 1C,1C <- 13C,8C <- 13C,13C <- 13H,13H <- 10H,2D <- 3D,3D <- 3H,3H <- 8H,8H <- 10H,11S <- 5S,5H <- 10H,5S <- 9S,10H <- 10C,10C <- 9C,9C <- 9S

Use functools.lru_cache instead of writing your own.

@orlp I would, but as list is unhashable it doesn't work.

Then use tuples.

@orlp OK, but that would require changes to the code (e.g. str.split returns list). I'd prefer the two programs to be functionally equivalent.

You could do h=lambda p:lru_cache(None)(g)(''.join(p)).

@orlp That becomes another problem with c[n[0]]=p[s]. I'll just go with these changes and standard lru_cache

h=lambda p:lru_cache(None)(lambda q:g(list(q)))(tuple(p))

Let us continue this discussion in chat.

The step 1S <- 11D appears in your example solution, which is invalid. Also, I think your solution more generally has the issue that it always attempts the first possible move, and this sometimes produces no solution when one in fact exists.

@isaacg Thanks, there was an in leftover from some previous golfing + undo-redo. I believe it'll always give a solution, it's a depth-first search that tries all moves.

@Pietu1998 Right, I see it now.