text:
ASCII art square affine fractals
Write the smallest program you can to create affine fractals. You may use any method you feel like that generates the same results as the rules below. You don't have to use any ideas from the suggested methods!
Your program will take two inputs, the first to define the pattern in the format 074 made of three digits from 0 to 7. The second input will define the size, 3 will be 8x8, 4 will be 16x16 and so on (2^n). Your program must output the correct result for all sizes from 0 (1x1) to at least 5 (32x32). If it produces any output for higher numbers it must be correct, i.e. it must produce the correct output up to a certain size but produce no output above that size if it would be wrong. You may assume a maximum size of 15 (32768x32768) as that is already an insane size for ASCII art (1GB)!
An 8x8 pattern will look something like below (rule 160). The left-most digit will be for block A, the middle digit (no rude thoughts please!) for block B and the right-most digit for block C. To construct the fractal, shrink it by a half in both dimensions, and apply the rotation/mirroring rule for the block. To shrink the pattern divide it evenly into 2x2 areas. There will either be 3 visible characters or none in each area. If there are visible characters place a character in the appropriate place in the smaller block, otherwise place a space. Rules 0-3 are not mirrored, rules 4-7 are mirrored. Rules 0 and 4 are not rotated, 1 and 5 are rotated 90 degrees clockwise, 2 and 6 are rotated 180 degrees, 3 and 7 are rotated 270 degrees clockwise. Stitch the three blocks together in the order shown, A in the top-left corner, B bottom-left and C bottom-right.
 AAA
AA A
AA
A
BBB CC
B BBC
  BBCCC
   B CCC

Shrunk, rotated and mirrored by rule number:
 0       1       2       3       4       5       6       7
----    ----    ----    ----    ----    ----    ----    ----
AA       BAA    CCB        C    C        BCC    AAB       AA
A       BB A     CBB      CC    CC      BBC     A BB       A
BBC     CC         A    A BB    BB A    A         CC     CBB
 BCC    C         AA    AAB      BAA    AA         C    CCB

Rules:

Not mirrored, Rotated 90 degrees clockwise
Not mirrored, Rotated 180 degrees clockwise
Not mirrored, Rotated 270 degrees clockwise
Mirrored but not rotated
Mirrored then Rotated 90 degrees clockwise
Mirrored then Rotated 180 degrees clockwise
Mirrored then Rotated 270 degrees clockwise
Rule 0: Not mirrored, Not rotated

The mirroring is always done first and is done diagonally through the blank corner e.g. rule 0 vs rule 4:
 0       4
----    ----
AA /    C  /
A /     CC/
BBC     BB A
/BCC    /BAA

Only rules 1, 6 and 0 are used in the above pattern, in that order. After the transformations have been applied and the blocks stitched together it will look like the below except I have spaced each block from each other by one space. Your code will not have this extra space in it. If you compare it to the "parent" image you will see that it has visible characters in the same positions.
 BAA
BB A
CC
C

AAB  AA
A BB A
  CC BBC
   C  BCC

Another way to generate the image without shrinking is as follows: Start with one character:
X

Apply the transformations for each of the three blocks (none since it's only one character) and stitch the blocks together:
X
XX

Apply the transformations for each of the three blocks again:
1
--
XX
X

6     0
--    --
XX    X
 X    XX

Stitch them together:
XX
X
XXX
 XXX

Apply the transformations for each of the three blocks again:
 1
----
 XXX
XX X
XX
X

 6       0
----    ----
XXX     XX
X XX    X
  XX    XXX
   X     XXX

Stitch them together:
 XXX
XX X
XX
X
XXX XX
X XXX
  XXXXX
   X XXX

You may use any printable character or characters (0x21 - 0x7E) for the visible part of the pattern but only the space character (0x20) for the blanks. Trailing spaces are allowed but there must be no blanks outside the entire square (i.e. for an 8x8 square there can be no characters past column 8).
There are 512 different rules, but some of them produce the same pattern. As a side note, any pattern containing only 0 and 4 will produce the Sierpinski triangle (8 different rules).
You may optionally post your favourite pattern and the rule that generates it. If you do, make sure the size is at least 3 (8x8) to distinguish it from similar rules.

@trichoplax You can start with a completely filled square or a square with only 1 visible character in it. Either way, repeating the rules n times, where n is the input size, will guarantee the same results. However, you don't have to generate the pattern this way, only generate the same pattern as doing it this way.

@trichoplax I appreciate your input. The way I see things is not necessarily the way other people see things and I don't know I'm making it hard for them!

+1 Thank you, you've made the explanation much clearer! In the future, I would recommend you run things through our sandbox so that people can get a clearer picture of what you're asking ahead of time. I will be working on this challenge shortly :)

Yeah everyone sees things differently. Happy to give feedback - a good question is worth clarifying. It reads well now.

@BrainSteel Thank you, will do! I've been around on SE for many years but I'm still relatively new to PCG!

CJam, 63 57 54 52 bytes
0aarari*{\f{\~7"W%z"a*3"Wf%"t<s~}({__Ser+}%\~.++}/N*

How it works:
The basic idea is that you run a loop, the second input number of times. In each loop, starting from a single array of array containing 0 ([[0]]), we build the fractal for the next step using the three rules, fill the empty quadrant and prepare the quadrants for the next loop.
0aa                           e# Starting condition, equivalent to a single A
   ra                         e# Read the rule string and wrap it in an array
     ri*                      e# Repeat the rule array, second input number of times
        { ...  }/             e# Loop for each rule in the rule array
                              e# In each loop, we will have the current fractal and
                              e# then the rule on stack
\f{\~7"W%z"a*3"Wf%"t<s~}
\f{                    }      e# Move the rule on top of stack and for each of the rule
                              e# character, run this loop on the current fractal
   \~                         e# Move the rule char on top and convert to int by face value
     7"W%z"a*3"Wf%"t          e# This is the array which has the logic to perform the rules
                              e# ["W%z" "W%z" "W%z" "Wf%" "W%z" "W%z" "W%z"]
                    <s        e# Based on the rule number value, take that many first items
                              e# from the above array and do a toString on the array
                              e# For rule 0 through 7, you will get the following strings:
                              e# 0: "", 1: "W%z", 2: "W%zW%z", 3: "W%zW%zW%z",
                              e# 4: "W%zW%zW%zWf%", 5: "W%zW%zW%zWf%W%z",
                              e# 6: "W%zW%zW%zWf%W%zW%z", 7: "W%zW%zW%zWf%W%zW%zW%z"
                              e# This works because each W%z will rotate the block of
                              e# fractal 90 degrees in clockwise direction.
                              e# For rule 4, where we need to mirror diagonally, we first
                              e# rotate it 279 degrees clock wise and then reverse each row
                              e# of the block. The rest of the rules after 4 take that
                              e# mirroring as base and rotate 90 degrees additionally
                      ~       e# Simply evaluate the string to apply the rule.
\f{ ... }                     e# After this for each loop, we get 3 copies of the fractal
                              e# block before the for loop. Each copy gets each one of the
                              e# three rule gets applied.
         ({      }%           e# We take out the first part corresponding to the 1st
                              e# quadrant and run each row through this loop to fill the
                              e# second quadrant with spaces
           __Ser              e# Take a copy of the row and replace everything in the
                              e# copy with spaces
                +             e# Append it to the original row
                   \~         e# Bring the last two quadrant array on top and unwrap it
                     .+       e# Append corresponding rows from the 4th quadrant to 3rd
                       +      e# Append the rows from lower half to the upper half
                              e# Now we have a full block ready to be run through
                              e# the next iteration which will double its size
                          N*  e# Finally, we join the rows of final fractal block with
                              e# newlines and automatically print the result

Try it online here

Very pretty! It produces too few printable characters if the pattern starts with 0 and James Bond has a license to kill. 007: IndexOutOfBoundsException

@CJDennis There are a bug with leading zeros. Fixed now.

Well done! The output looks perfect now!

APL (Dyalog Classic), 47 bytes
⊃(⊂⍪⍕#){,/⍪⌿↑1 ¯2↑¨⊂⍺{⍉∘⊖⍣⍺⌽⍉⍣(⍺>3)⌽⍵}¨⍵}⍣⎕⍨⍎¨⍞

Try it online!


text:
Generalised Array Riffle
A simple golf to start the week! You're given three arrays: the base array B, the value array V and the index array I. You should produce another array where the values from V are inserted into B at the indices specified by I. Here is an example:
Base:    [5, 1, 4, 1, 3]
Values:  [0, 0, 7]
Indices: [5, 0, 3]

The indices point at the following positions in the base array:
[ 5, 1, 4, 1, 3 ]
 ^        ^    ^
 0        3    5

So inserting the corresponding elements from the value array, the result should be:
[0, 5, 1, 4, 7, 1, 3, 0]

Rules
You may write a program or function, taking input via STDIN (or closest alternative), command-line arguments or function arguments and output the result via STDOUT (or closest alternative), function return value, or by modifying the array given as the B parameter.
If your submission is a function, I and V can be modified in any way, as well as B if it isn't used for output.
You may make the following assumptions about the input:

All elements of the base and value array will be non-negative integers.
The value array will have at most one more element than the base array.
The value array and index array will have the same number of elements.
The index array will not contain repeated indices, and all indices will be in range.
The base and value arrays may contain repeated elements.
Any or all of the arrays may be empty.
You must not assume that the indices are given in any particular order.
You may receive input and produce output in any convenient, unambiguous string or list format. You may also choose to receive the three arrays in a different order.
You may choose between 0-based and 1-based indexing.

This is code golf, so the shortest answer (in bytes) wins.
Test Cases
Given in the format B V I => Result for 0-based indexing. If you're using 1-based indexing, increment the elements of the third array by 1.
[] [] [] => []
[] [1] [0] => [1]
[1,2] [] [] => [1,2]
[1,2] [3] [0] => [3,1,2]
[1,2] [3] [1] => [1,3,2]
[1,2] [3] [2] => [1,2,3]
[0,0,0] [1,1,1,1] [0,1,2,3] => [1,0,1,0,1,0,1]
[5,1,4,1,3] [0,0,7] [5,0,3] => [0,5,1,4,7,1,3,0]
[1,2,3,4] [4,3,2,1] [4,0,3,1] => [3,1,1,2,3,2,4,4]

Let me know if you come across other interesting edge cases, and I'll add them.
Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

var QUESTION_ID=50369;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

How do you feel about NULL for an empty array for languages where an empty array is NULL?

@AlexA. If it's a common / the representation of the empty array in said language(s), I'm fine with that.

A simple golf? That's the most difficult thing I did in CJam all week. :P

Pyth, 14 bytes
s.icFPQmedSCtQ

Demonstration.
This program takes the inputs as a 3-tuple of lists in the order Base, Indices, Values.
Explanation on the example [5, 1, 4, 1, 3], [5, 0, 3], [0, 0, 7]:

Take the input: implicit, Q is the input.
Make the index, value pairs: CtQ = [(5, 0), (0, 0), (3, 7)]
Sort the pairs into increasing index order: SCtQ = [(0, 0), (3, 7), (5, 0)]
Take the value out of each pair: medSCtQ = [0, 7, 0]
Split the base list at the location of the indicies: cFPQ = [[], [5, 1, 4], [1, 3], []]
Interleave 3 and 4: .icFPQmedSCtQ = [[], 0, [5, 1, 4], 7, [1, 3], 0, []]
Combine into one list: s.icFPQmedSCtQ = [0, 5, 1, 4, 7, 1, 3, 0]

Damn. Since when do we have an interleave method? Just wanted to post  ssC,cFPQamedSCtQ].

@Jakube isaac sneakily committed it in 6 days ago.

@Jakube Since https://github.com/isaacg1/pyth/commit/8e46faaee719503dbbb2048832b7b13cf5637457

@Jakube since Pyth can grow to solve any problem. That's the problem with golfing languages. Esoteric languages exist for the sake of esoteric languages; as they are designed *afterwards.

@sentiao To be fair, the host language (Python) has had interleaving under a different name for a while.

Python 2, 54
lambda B,*X:map(B.insert,*zip(*sorted(zip(*X))[::-1]))

Takes input as B,I,V. Modifies the input B when called (thanks to Martin Büttner for reminding me this is possible).
Uses map to call B.insert on each index/element pair. To avoid the issue of the list indices shifting as elements are inserted, sorts the pairs in decreasing order of index by an ugly zip/sort/unzip. If not for the shifting issue, we could just do map(B.insert,*X).
Old method (65):
B,V,I=input()
for i,v in sorted(zip(I,V))[::-1]:B[i:i]=v,
print B

Haskell, 62 bytes
import Data.List
f b v i=map snd$sort$zip[0.5,1.5..]b++zip i v

Usage example: f [5,1,4,1,3] [0,0,7] [5,0,3] -> [0,5,1,4,7,1,3,0].
How it works: augment the base list with "and-a-half" indices starting at 0.5 (e.g. [(0.5,5),(1.5,1),(2.5,4),(3.5,1),(4.5,3)]) and concatenate it with the index-value pairs. Sort and discard the index.
Remark: don't know if I'm cheating here. From a mathematical point of view it's fine, but a programmer might argue that the list of indices [5,0,3] is not a list of Integers as requested, but a list of Fractionals (to be exact, the type is polymorphic, but must belong to the Fractional class, e.g. Float or Double).

K, 22 21 bytes
{,//+(y@<z;(z@<z)_ x)}

We define a 3 argument function {…} with the implicit variables x, y and z representing the starting list, the value list and the index list, respectively. The "cut" operator (_) is used to split the starting list apart at the sorted list of given indices ((z@<z)). We interleave values (after sorting them correspondingly) with the split up chunks of the original array by forming a list ((a;b)), taking its transpose (+) and flattening the result (,//).
Usage example:
  f:{,//+(y@<z;(z@<z)_ x)}
{,//+(y@<z;(z@<z)_ x)}

  f[1 2 3 4;4 3 2 1;4 0 3 1]
3 1 1 2 3 2 4 4

  f[5 1 4 1 3;0 0 7;5 0 3]
0 5 1 4 7 1 3 0

Spaces around the underscore are necessary because K allows underscores in identifiers. K5 removes this potential ambiguity. If we could count on the indices coming in ascending order and underscores were not valid identifiers, we could use the much nicer 13 byte program:
{,//+(y;z_x)}

(sigh.)
edit:
{,//+(y@<z;(z@<z)_ x)} / before
{,//+(y@<z;z[<z]_ x)}  / after

Breaks symmetry, but we can save a byte by using bracket-indexing ([…]) instead of the infix @ indexing operator. Usually this makes programs longer, but in this case we needed parens anyway to sort z before performing the cut.

Ruby, 60 59 53 bytes
->a,b,c{c.zip(b).sort.reverse.map{|i,v|a.insert i,v}}

And the ungolfed version
def riffle(array, values, indices)
    indices.zip(values).sort.reverse.each do |index, value|
        array.insert(index, value)
    end
end

You can shorten this by making it a unnamed function instead: ->a,b,c{...}. Also chances are insert doesn't need parentheses.

@MartinBüttner I did know about the unnamed function with the lambda, but I didn't feel that was in the spirit of the challenge (which usually asks for a named function). Thanks for spotting the parens, though.

Unless the challenge specifically asks for a named function, unnamed functions are always acceptable. And I didn't ask for a named function (I never do ;)).

CJam, 34 23 18 bytes
{.\2/\ee+{0=}$1f=}

My first CJam submission. Advices are welcome, I'm sure there is a lot to golf.
16 bytes saved with the help of @MartinBüttner and @Dennis.
Function expecting input on the stack in order B V I (I is the topmost).
Example usage:
[5 1 4 1 3] [0 0 7] [5 0 3] {.\2/\ee+{0=}$1f=}~

Method:

pair the array's ith element with i+0.5
pair insert values with insert positions
merge the resulting two arrays
sort array based on position elements
keep value elements

That floating point approach is very clever and (sadly) better than mine. You can get down to 19 bytes with q~.5fm.\2/\ee+$1f=p and to 18 bytes by using an anonymous function: {.5fm.\2/\ee+$1f=}

Same idea without the floating-point trick: {.\2/\ee+{0=}$1f=} (still 18 bytes)

@Dennis Thanks, I couldn't find the get array element operator for 1f=. I will leave it as a full program though.

Your call. Do you mind me asking why you're opposed to posting a function?

@Dennis I just started CJam and wasn't sure how to use the functions. Now I figured it out so I changed the answer to that.

Pyth, 17 bytes
ssC,cFPQamedSCtQ]

@isaacg beat my solution already. But since I had my documentation finished, I'm just gonna post it anyways.
This takes the input in the format B, I, V. You can try it here: Demonstration or Test Suite
Explanation:
I'm using the example B = [5,1,4,1,3], I = [5,0,3], V = [0,0,7] from the OP.
                    implicit: Q = input()
      PQ            all elements but last of Q   => [[5,1,4,1,3], [5,0,3]]
    cF              split B it the indices in I  => [[], [5,1,4], [1,3], []]

              tQ    all elements but first of Q  => [[5,0,3], [0,0,7]]
             C      zip                          => [(5,0), (0,0), (3,7)]
            S       sort                         => [(0,0), (3,7), (5,0)]
         med        extract the end of each pair => [0,7,0]
        a       ]   append an empty list         => [0,7,0,[]]

   ,                create a pair => ([[], [5,1,4], [1,3], []], [0,7,0,[]])
  C                 zip           => [([],0), ([5,1,4],7), ([1,3],0), ([],[])]
 s                  sum           => ([],0,[5,1,4],7,[1,3],0,[],[])
s                   sum           => [0,5,1,4,7,1,3,0]

JavaScript (ES6), 75
A function with 3 array parameters, returnning an array. Weirdly, this function modifies its i parameter (as kindly allowed by OP)
Test running the snippet, Firefox only as usual.

f=(b,v,i,j=0)=>b.concat(v).map(p=>(p=i.indexOf(j))<0?b[j++]:(i[p]=-1,v[p]))

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

test=[
{ b:[], v:[], i:[], k:[] },
{ b:[], v:[1], i:[0], k:[1] },
{ b:[1,2], v:[], i:[], k:[1,2] },
{ b:[1,2], v:[3], i:[0], k:[3,1,2] },
{ b:[1,2], v:[3], i:[1], k:[1,3,2] },
{ b:[1,2], v:[3], i:[2], k:[1,2,3] },
{ b:[0,0,0], v:[1,1,1,1], i:[0,1,2,3], k:[1,0,1,0,1,0,1] },
{ b:[5,1,4,1,3], v:[0,0,7], i:[5,0,3], k:[0,5,1,4,7,1,3,0] },
{ b:[1,2,3,4], v:[4,3,2,1], i:[4,0,3,1], k:[3,1,1,2,3,2,4,4] }
];

test.forEach(x=>{
  r = f(x.b,x.v,x.i.slice(0)) // pass a copy of i, as the function will alter it
  ok = ''+r==''+x.k
  s='Test ' + (ok?'OK':'FAIL')
  +'\n B ['+x.b
  +']\n V ['+x.v
  +']\n I ['+x.i
  +']\n Result ['+r
  +']\n Check  ['+x.k
  +']\n'
  out(s)

})

Out of curiosity, what about the code makes it specific to Firefox? Is it because it's ES6?

@AlexA.it's because it's ES6, yes. Particularly the fat arrow function is not implemented even in developer version of Chrome (AFAIK)

Indeed, not even the Canary build of Chrome supports it.

Mathematica, 52 51 bytes
Last/@(Tr@#2->#&~MapIndexed~#⋃Thread[#3+.5->#2])&

Example:
In[1]:= f = Last/@(Tr@#2->#&~MapIndexed~#⋃Thread[#3+.5->#2])&;

In[2]:= f[{5, 1, 4, 1, 3}, {0, 0, 7}, {5, 0, 3}]

Out[2]= {0, 5, 1, 4, 7, 1, 3, 0}

Explanation:
Using the example above.

Tr@#2->#&~MapIndexed~# => {1 -> 5, 2 -> 1, 3 -> 4, 4 -> 1, 5 -> 3}
Thread[#3+.5->#2] => {5.5 -> 0, 0.5 -> 0, 3.5 -> 7}
Then take the (sorted) union of these two lists. (=> {0.5 -> 0, 1 -> 5, 2 -> 1, 3 -> 4, 3.5 -> 7, 4 -> 1, 5 -> 3, 5.5 -> 0})
And then take the last element of each pair. (=> {0, 5, 1, 4, 7, 1, 3, 0})

CJam, 30 29 bytes
q~.\2/$z~0@+2ew@f{\~@<>}.\e_p

This is tooo long. I feel like this is not a golfing language submission :|
Try it online here

R, 75 bytes
function(b,v,i){n=b;j=0;for(g in v)n=append(n,g,i[j<-j+1]+sum(i<i[j])-1);n}

This creates an unnamed function. To call it, give it a name, e.g. f=function.... Note that the arrays must be 1-indexed because that's just how R rolls.
Ungolfed + explanation:
f <- function(b, v, i) {
    # Initialize the output vector to b
    n <- b

    # Initialize an index over the indices
    j <- 0

    # Loop over the values to insert
    for(g in v) {
        # Get the index of the next given insertion index
        j <- j + 1

        # Insert g into n.
        # The position at which to insert the value is determined by
        # adding the number of indices less than the current one and
        # subtracting 1. The subtraction is because we're using the
        # `after` argument in the `append` function.

        n <- append(n, g, i[j] + sum(i  f(c(), c(), c())
[1] NULL

> f(c(0, 0, 0), c(1, 1, 1, 1), c(1, 2, 3, 4))
[1] 1 0 1 0 1 0 1

> f(c(5, 1, 4, 1, 3), c(0, 0, 7), c(6, 1, 4))
[1] 0 5 1 4 7 1 3 0

Suggestions are welcome as always!

CJam, 19 bytes
l~_,)N*q~.{t}~.\N-p

This is a full program that the reads the arrays B, I and V (one per line, in that order) from STDIN.
Try it online in the CJam interpreter.
How it works
l~    e# Evaluate the first line of input.
_,)   e# Compute the array length and add 1.
N*    e# Push a string of that many linefeeds.
q~    e# Evaluate the remaining input.
.{t}~ e# Vectorized array set: for each index in the array from line 2, replace the
      e# LF at that index by the corresponding element of the array from line 3.
.\    e# Interleave the two arrays on the stack.
N-    e# Remove the linefeeds.
p     e# Print.

CJam, 20 bytes
{Qa+@@.{a2$2$=+t}e_}

This is an anonymous function that pops B, V and I (top to bottom) from the stack and leaves a single array on the stack in return.
Try it online in the CJam interpreter.
How it works
Qa+      e# Append [[]] to B.
@@       e# Rotate V and I on top of B.
.{       e# For each v in V and the corresponding i in I:
   a     e#     Push [v].
   2$2$= e#     Retrieve b := B[i].
   +     e#     Append to push [v b].
         e#     The stack now consists of: B i [v b]
   t     e#     Set B[i] := [v b].
}        e#
e_       e# Flatten B.

Ruby, 48 bytes
I think this complies with the rules, but please check.
->b,v,i{l=-1;i.map{|j|b[j]=[v[l+=1],b[j]]};b*?:}

Unnamed function taking the three arrays as input. Outputs a string that can be parsed unambiguously into an array of numbers with the ruby expression x.split(/:+/).map(&:to_i).
Test cases on ideone.
I could save 3 more bytes, but the output format [1,2,[nil,5]] is stretching the rules a bit too mych imo, although it is unambiguous.

I think the current format is okay. Nested arrays with interleaving nil values are a bit of stretch. But in either case this isn't winning the contest, so I'm not really worried about it either way.

R, 60
As an unnamed function that takes b, v and i
function(b,v,i){e=c(NA,rbind(b,NA));e[i*2+1]=v;e[!is.na(e)]}

Expands b with NAs
Fills the gaps where required with v
Returns the vector without NAs
> f=function(b,v,i){e=c(NA,rbind(b,NA));e[i*2+1]=v;e[!is.na(e)]}
> f(c(), c(), c())
logical(0)
> f(c(0, 0, 0), c(1, 1, 1, 1), c(0, 1, 2, 3))
[1] 1 0 1 0 1 0 1
> f(c(5, 1, 4, 1, 3), c(0, 0, 7), c(5, 0, 3))
[1] 0 5 1 4 7 1 3 0

Java, 253, 226, 219, 209
not exactly a winner, but oh well.
Assuming that B, V, and I are not null.
v (lowercase v) is the length of the Values/Indicies arrays.
R is the returned array.
r is the length of the returned array.
x, y, and i are all temporary ints.
int[]f(int[]B,int[]V,int[]I){int v=V.length,r=B.length+v,x,y,i;int[]R=java.utils.Arrays.copyOf(B,r);for(x=0;x<v;x++){i=I[x];for(y=0;y<x;y++)if(I[x]>I[y])i++;for(y=r-2;y>=i;y--)R[y+1]=R[y];R[i]=V[x];}return R;}

expanded:
int[]f( int[] B, int[] V, int[] I ) {
    int v = V.length, //length of Values
        r = B.length + v, //length of the result
        x, y, i; //temps
        int[] R = java.utils.Arrays.copyOf( B, r );
        for( x = 0; x < v; x++ ) {
        i = I[x];
        for( y = 0; y < x; y++ )
            if( I[x] > I[y] )
                i++;
        for( y = r - 2; y >= i; y-- )
            R[y+1] = R[y];
        R[i] = V[x];
    }
    return R;
}

APL, 22 bytes
{(∊⌽2↑⍵)[⍋(2⊃⍵),⍳≢⊃⍵]}

In ⎕IO←0 to match the test cases.
It's a standard algorithm: the index vector of the first argument is appended to the given indexes (3rd argument). ⍋ computes the permutation that would sort the indexes in ascending order. Since APL's sorting algorithm is stable by definition, the permutation computed puts the element of the catenation of the second and first argument in the right place.
For instance:
    {(∊⌽2↑⍵)[⍋(2⊃⍵),⍳≢⊃⍵]}(5 1 4 1 3)(0 0 7)(5 0 3)
0 5 1 4 7 1 3 0

source: Stack Exchange

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

sort: votes


text:
Extract a string from a given string
You are given a string and two characters. You have to print the string between these characters from the string.
Input
Input will first contain a string (not empty or null). In the next line, there will be two characters separated by a space.
Challenge
Return the string between the two characters
Example
Hello! What's your name?
! ?

should result in the output:
" What's your name"

Rules

The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to ~(tilde) (character codes 0x20 to 0x7E, inclusive). See ASCII table for reference.
You must take input from the stdin( or closest alternative ).
The output should be surrounded with quotes(").
You can write a full program, or a function which takes input, and outputs the final string
The two characters will only contain ASCII characters in range (space) to ~(tilde) (character codes 0x20 to 0x7E, inclusive). See ASCII table for reference.
There is no guarantee that both the characters will be in the string.
If any of the characters is not found in the string, print "null".
If any of the characters is found more than one times (unless both the characters are same) in a string, print "null".
If both the characters are the same character, print the string "null".

Test Cases
1)
code
> <                       --> "null"

2)
What's what?
' '                       --> "null"

3)
abcdefghijklmnopqrstuvwxyz
n k                       --> "lm"

4)
Testing...
e T                       --> ""

5)
Last test-case
  -                       --> "test"

Scoring
This is code golf, so the shortest submission (in bytes) wins.

Can the characters occur in the opposite order in the string? If so, that could use a test case.

What if the substring contains a "? Should we just surround it with another pair of quotes and not care about that?

@MartinBüttner , Yes. See edited test case 3. Thanks for reminding me about that

@user23013 , Yes. Example input: one"two-three \n" - output: "two" (\n is a newline)

What I meant was input one"two-three \nn -. So the output should be "e"two"?

@user23013 , Yes.

What should be the output for It's 5 o'clock \n' '? Should it be "s 5 o" or "null"?

@Jakube , Read the last point of the rules. Output = "null"

@CoolGuy What's the reason for case 4?

@Tim , No particular reason. I just wanted another case that outputs an empty string.

Ahh okay :) Yeah, it works on mine, phew!

Missing test case: aba\na c (my first submission failed that one).

I'm not a fan of the fiddly details about the markers not appearing or appearing multiple times. I think the problem would be more enjoyable to solve with stronger guarantees on the inputs.

@xnor , You mean that, characters will be present in the string, it will not be the same etc?

My solution outputs a backslash-escaped quote for strings that contain them. Is this acceptable?

Why does 1 fail?

@KyleKanos There are two < and >: If any of the characters is found more than one times in a string, print "null".

@CoolGuy Yes, exactly.

CJam, 34 33 32 bytes
'"l_l2%&2*2>NerN/0"null"t_,3=='"

Try it online in the CJam interpreter.
Idea

Remove the second character from line 2.
Form a string consisting of a single copy of all characters that both lines have in common.
Repeat the resulting string twice and discard its first two characters.
This results in a two-character string (if the characters from line 2 are different and both occur in line 1) or an empty string.
Replace the characters of the resulting string in line 1 by linefeeds.
Split line 1 at linefeeds.
The resulting array's second element will be the desired string if the array contains exactly three chunks.
Replace the first element of the array with the string null.
Retrieve the second element of the array if its length is 3 and the first otherwise.
Prepend and append a double quote.

Code
'"       e# Push a double quote.
l_       e# Read one line from STDIN. Push a copy.
l2%      e# Read one line from STDIN. Only keep characters at odd indexes.
&        e# Intersect both strings.
2*2>     e# Repeat the intersection twice and discard the first two characters.
Ner      e# Replace the characters of the resulting string with linefeeds.
N/       e# Split the result at linefeeds.
0"null"t e# Replace the first element of the resulting array with "null".
_,3=     e# Push 1 if the length of the array is 3 and 0 otherwise.
=        e# Retrieve the corresponding element from the array.
'"       e# Push a double quote.

Python 3, 149 bytes
s,i=input(),input();a,b=s.find(i[0]),s.find(i[2]);print('"'+('null',[s[a+1:b],s[b+1:a]][b-1)]+'"')

Ungolfed Version:
string, chars = input(), input()
a, b = string.find(chars[0]), string.find(chars[2])

    if string.count(chars[0]) == string.count(chars[2]) == 1 and a!=b and a*b>-1:
        if b<a:
            print('"' + string[b+1:a] + '"')
        else:
            print('"' + string[a+1:b] + '"')
else:
    print('"null"')

This is my first answer here, so tips and criticism are much appreciated.

CJam, 38 bytes
l:Tl2%f#_W-$2,=2,@f#$~T<>1>"null"?'"_o

Too long...
Explanation
l:T             e# Read a line and store in T.
l2%             e# Read the two characters into a list.
f#              e# Find each character in the list of two characters.
_W-             e# Copy and remove not found results.
$2,=            e# Sort and check if the result is exactly [0 1].
                e# If true:
2,@f#           e# Find 0 and 1 in the original results.
$               e# Sort.
~T<>            e# Get a slice of T between the two positions (left-closed).
1>              e# Remove the first character.
                e# If false:
"null"          e# The string "null".
?               e# End if.
'"_o            e# Append a quote and output another quote at the beginning.

Pyth, 37 36 34 bytes
p?"null"njT9m/zd{J%2wt:z.uSmxzdJNN

Thanks to @isaacg for the two bytes save.
Try it online: Pyth Compiler/Executor
Explanation:
                                     implicit: z = first input line
                    w                second input line
                  %2                 only use every 2nd char
                 J                   and store in J
                {J                   set(J), gets rid of duplicates
            m/zd                     count the number of appearances of each char
        njT1                         != [1, 1] ([1,1] is 10 in base 9)
 ?      njT1m/zd{J%2w                ... if [1,1] != number of appearances else ...
  "null"                               string "null"
                           mxzdJ     find the index for each char
                          S          sort the indices
                      :z.u           take the substring of z using these indices
                     t               remove the first char

p                               NN  print '"' + ... + '"'

*2]1 is shorter than [1 1), and - ... 1 is shorter still.

@isaacg -...1 don't work, since I also need to check that there are exactly two numbers.

I just thought of a 3 character way to make [1 1): jT9.

Ruby, 108 95 94
->s,f,l{a,b=[f,l].map{|u|(f==l||s.count(u)>1)&&abort('"null"');s.index u}.minmax;p s[a+1...b]}

And for the ungolfed version
def between(string, first, last)
    left, right = [first, last].map do |substring|
        abort('"null"') if first == last || string.count(substring) != 1
        string.index(substring)
    end.minmax
    p string[left + 1 ... right]
end

Why can't I see any output when I run your code here?

@CoolGuy It is an unnamed function, so you need to call it like this ->s,f,l{begin a,b=[f,l].map{|u|raise if f==l||s.count(u)>1;s.index u}.minmax;p s[a+1...b];rescue;p'null'end}["test",?>,?<] The [...] at the end is what calls the function.

@blutorange , Ok. That sort-of worked, but how do I test the last test case?

@CoolGuy Use normally quoted strings: ->s,f,l{begin a,b=[f,l].map{|u|raise if f==l||s.count(u)>1;s.index u}.minmax;p s[a+1...b];rescue;p'null'end}["Last test-case"," ","-"]

Instead of raising an error with raise, you can replace raise with an undefined variable such as _ or y. This raises a NameError. Also, I think you could save a few more bytes without an explicit rescue: ->s,f,l{a,b=[f,l].map{|u|(f==l||s.count(u)!=1)&&p('null')&&exit;s.index u}.minmax;p s[a+1...b]}

@blutorange Cool ideas, I made the changes.

You're welcome. Didn't know about abort, so I've learned sth. new too. By the way, your byte count seems to be 94, not 95. If you're looking at the bytesize of a *.rb file, keep in mind you don't need the final newline some editors add upon saving. Here's a bytecounter.

TypeScript's Type System, 160 bytes
//@ts-ignore
type F<S,U,Y=any,O={[K in U]:S extends`${Y}${K}${infer X}${Exclude<U,K>}${Y}`?S extends`${Y}${K}${Y}${K}${Y}`?0&1:X:0&1}[U]>=O extends 0&1?"null":O

Try it at the TypeScript playground!
This is a generic type F taking the string as the first type parameter S and the characters as a union type U.
If the input was two distinct characters that were guaranteed only to each appear once in the string, this would be 59 bytes:
type F<S,A,B>=S extends`${any}${A}${infer X}${B}${any}`?X:0

My original solution was around 150 bytes before I realized that the program had to check for the characters in either order, adding many bytes. I came up with the following solution at 161 bytes:
//@ts-ignore
type F<S,A,B,Y=any,Z="null">=S extends`${Y}${`${A}${infer X}${B}`|`${B}${infer X}${A}`}${Y}`?S extends{[K in A|B]:`${Y}${K}${Y}${K}${Y}`}[A|B]?Z:X:Z

...but then I thought of the current solution and it ended up exactly 1 byte shorter.
Explanation coming soon.

golflua, 132 bytes
L=I.r()I,J=I.r():m("(.) (.)")i=L:f(I)j=L:f(J)K,c=L:g(I,'')_,b=K:g(J,'')?i>j i,j=j,i$w((i==j|c+b!=2)&'"null"'|'"'..L:s(i+1,j-1)..'"')

Pretty ugly answer. The input bit is a bit rough (and requires two lines, first with the string & second with the slice characters
). Finding the locations of the flags is straight-forward, but just too long to compete with other answers. Output is pretty easy. An
equivalent Lua program would be
Line1 = io.read()
Line2 = io.read()
I,J = Line2:match("(.) (.)")     -- boobs return the char flags
i = Line1:find(I)                -- find location of flags
j = Line1:find(J)
K,c = Line1:gsub(I,'')           -- replace flag w/ empty & store in K
_,b = K:gsub(J,'')               -- taking K ensures single flags fail
if i > j then i,j=j,i end        -- ensure we start low to high
if i==j or not (c+b == 2) then   -- if i & j are the same or not 2 counts, fail
   print('"null"')
else                             -- print the string otherwise
   print('"'..Line1:sub(i+1,j-1)..'"')
end

Is there any online compiler which I can test the golfed version?

I don't believe there's an online version, but the source code is available. It is a 1:1 mapping of Lua (not an interpretation or translation to Lua), so the Lua code can be tested at ideone.

C, 192 bytes
f(){char b[101],c,d,*p,*t;scanf("%[^\n]%*c%c%*c%c",b,&c,&d);p=strchr(b,c);t=strchr(b,d);c==d||!p||!t||strchr(p+1,c)||strchr(t+1,d)?puts("\"null\""):printf("\"%s\"",p<t?(*t=0,p+1):(*p=0,t+1));}

Ungolfed code:
f()
{
    char b[101],c,d,*p,*t; //Variables

    scanf("%[^\n]%*c%c%*c%c",b,&c,&d); //Scan input

    p=strchr(b,c);
    t=strchr(b,d); //Find occurrence of characters

    c==d         ||  //If both characters are the same
    !p           ||  //If no occurrence of first character found
    !t           ||  //If no occurrence of second character found
    strchr(p+1,c)||  //If two occurrence of first character found
    strchr(t+1,d) ?  //If two occurrence of second character found
    puts("\"null\"") //Print "null"
                  :  //else
    printf("\"%s\"",p<t?(*t=0,p+1):(*p=0,t+1)); //print the string
}

Test it here

Python 3, 172 bytes
x=input()
a=input()
a,b=a[0],a[2]
if(a!=b)&(x.count(b)==x.count(a)==1):
 if x.index(a)>x.index(b):q=a;a=b;b=q
 print('"'+x.split(a)[1].split(b)[0]+'"')
else:print('"null"')

Second line can be shortened to “a,_,b=a” because unpacking!

Also q=a;a=b;b=q is equivalent to a,b=b,a

Javascript (ES6), 125 123 bytes
Idea stolen heavily from @edc65's solution.

[a,,b]=(p=prompt)(s=p()),[,c,d,e,,f]=s.split(RegExp('(['+(a+b).replace(/\W/g,'\\$&')+'])'))
p('"'+(!e||f||c==e?null:d)+'"')

I mostly like [a,,b]=, I'll use it next time. As regexs are a hassle, here is a regex free solution: [a,,b]=(P=prompt)(s=P()), P((s=s.split(a)).length==2& (s=[].concat(...s.map(s=>s.split(b)))).length==3 ?``"${s[1]}"``:null)

(the last string is templated, difficult to put in a comment)

Python, 161 bytes
import re,sys
s,p=sys.stdin
m=re.match('[^%s]*([%s])([^%s]*)([%s])[^%s]*$'%((p[0]+p[2],)*5),s)
if m:g=m.group
print'"null"'if not m or g(1)==g(3)else'"'+g(2)+'"'

The solution mostly just uses a regular expression to extract the string. To accommodate that the letters could match in either direction, the start and end of the matched part allows either letter. Checking that the letters that actually matched to be different excludes the same letter being matched twice, as well as the two letters in the input being the same.
This is my first attempt at using Python for an answer here. So feedback on possible improvements is very welcome. I particularly have a feeling that there must be a way to make the condition in the print statement shorter.

Python 3, 155 bytes
s,n,a,b=[input(),'null']+list(input())[::2];q,w=[s.find(a),s.find(b)];print('"'+{0>1:n,0<1:s[min(q,w)+1:max(q,w)],a==b:n}[s.count(a)==s.count(b)==1]+'"')

Try it online

Vyxal, 164 bitsv2, 20.5 bytes
"`(.*)`wYḂ"ṠẎf:₃[h|`¨β

Try it Online!
Bitstring:
00110000111000011110010000000100111011101000001101101000101001101101100110001100010100001110111101111111011010011000110000000101010010101011001110001001000110010001

Hello to all the people answering this as a result of me bumping it to the front page :p
Explained
"`(.*)`wYḂ"ṠẎf:₃[h|`¨β
"                       # Pair the two characters into a list
 `(.*)`                 # Push the string "(.*)", representing a capturing group of any number of characters. The `()` is so that only the .* is returned in a regex match
       wY               # Create a list of [first char, ^, second char]
         Ḃ"             # And wrap it in a list with its reverse
           Ṡ            # Summate each list, giving two regexes: "<first char>(.*)<second char>", "<second char>(.*)<first char>"
            Ẏf          # Get all regex matches of both regexes and flatten into a single list
              :₃[       # If the length is 1 (i.e. there was only one match, meaning the characters aren't the same and there's a unique span):
                 h      #   Print the span
                  |`¨β  #   Otherwise, print "null"

Created with the help of Luminespire.

APL(NARS), 50 chars
{1 1≢↑+/⍵=⊂a←∪1↓1⌽⍺:'"null"'⋄1⌽'""',⍵[↑../⍸⍵∊a]∼a}

the use. For result not sure 100%
  '4 5' {1 1≢↑+/⍵=⊂a←∪1↓1⌽⍺:'"null"'⋄1⌽'""',⍵[↑../⍸⍵∊a]∼a} 'aifdji5ijj4'
"ijj"

Perl, 65
#!perl -p0
$.*=s/\Q$1/
/g while s/ ?(.)\z//;/
(.*)
/;$_=$.-1?null:"\"$1\""

This requires there is no newline character at in the second line of the input.

Nice job. This seems to be missing the double quotes though.

@Dennis, fixed. I misunderstood the example.

It's still missing the quotes for the null case.

Kotlin, 238 bytes
"\""+v[0].let{s->v[1].let{val(a,b)=it.split("").drop(1).let{c->c[0] to c[2]};if(s.count{""+it==a}!=1||s.count{""+it==b}!=1||a==b)"null" else{val(c,d)= s.indexOf(a) to s.indexOf(b);s.substring((if(c<=d)c else d)+1,if(c<=d)d else c)}}}+"\""

Formatted version:
"\"" + v[0].let { s ->
    v[1].let {
        val (a, b) = it.split("")
            .drop(1)
            .let { c -> c[0] to c[2] } // get first and third char that we are looking fir
        if (s.count { "" + it == a } != 1 || s.count { "" + it == b } != 1 || a == b) { // check if there 0 or more times the character of the first or second char. also check if both are equal
            "null"
        } else {
            val (c, d) = s.indexOf(a) to s.indexOf(b) // fetch indices of thise two chars
            s.substring((if (c <= d) c else d) + 1, if (c <= d) d else c) // build a substring considering the reverse looking
        }
    }
} + "\""

Try it online!

Scala 3, 192 187 bytes
Saved 5 bytes thanks to @ceilingcat

Golfed version. Attempt This Online!
(s,c)=>{val(a,b)=(s.indexOf(c(0)),s.indexOf(c(2)));if(List(c(0),c(2)).forall(x=>s.count(_==x)==1)&a!=b&a*b> -1)"\""+(if (b -1) {
      if (b < a) {
        "\"" + string.substring(b + 1, a) + "\""
      } else {
        "\"" + string.substring(a + 1, b) + "\""
      }
    } else {
      "\"null\""
    }
  }

  def main(args: Array[String]): Unit = {
    val string = scala.io.StdIn.readLine()
    val chars = scala.io.StdIn.readLine()
    println(findSubstring(string, chars))
  }
}

187 bytes

all_licenses: 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/


text:
CodeGolf - Ignore the noise #1
Instructions
Barry is a not so good backend developer in charge of a small API that should give you information about purchases made in a client's shop. However, he hasn't done a great job and your boss tells you to fix it client-side instead. Ideally you should receive comma-separated values such as 927,2,45,90 which correspond to something like item_id,item_amount,unit_price,total
In this first puzzle we only care about item_id and item_amount but we need the other fields in place to present the problem. Barry sometimes gets things mixed up and returns noise as part of the output, he also gets the order wrong, returning noise, noise, unit_price, total, item_id, item_amount.
Your Task
You need to store in a map (or similar structure) the pairs of item_id and item_amount regardless of whether Barry returns them correctly or not and print each element in a new line in the least number of characters possible. (Storing is not mandatory, we just care about the output)
Sample input (mixed correct and messy formats)
103,2,50,100
106,1,900,900
459,40,150,300,67,2
4,20,30,6000

In other words input will be either a,b,x,x or x,x,x,x,a,b where what we care about is a & b. You need to provide code assuming we have a variable called G (or any other name) with all the lines of csv.
Sample output
103,2
106,1
67,2 //This one was messy
4,20

Tolerance
There is a certain margin for tolerance when it comes to the answer. Answers in similar formats but adhering to the correct values, will also be accepted. Formats like [a,b],(a,b) or {a,b} are valid, but a,b is preferred.

Although the first puzzle had mixed acceptance due to the fact that it
  was easy and fast to solve, I also felt that some people liked that
  too. So I'm going to continue making quickgolfs for now

Will input be always of the format x,x,x,x and x,x,x,x,x,x where x denotes a number?

Yes, input will follow one of those two formats, let me clarify

Do we need to submit a program or a function or something else? Also, where all can inputs be taken from?

Input will be available from a variable in your code G if possible, or similar depending on your language.

Updated requirements to include the valid formats

What about an output like ["103" "2"]? Would that be considered valid?

Sure, you are removing the noise and getting the values, I don't see why not

[tag:quick-golf] is essentially a difficulty tag. Consensus seems to be that we don't want those, so I'm removing that tag for now. If you want difficulty tags to be re-evaluated, please make a meta post for it. But that would be a massive retagging effort, which I think should happen in a coordinated manner, rather than individual users creating arbitrary new tags for it.

I'll just stick to adding it in the title, if that's ok

I have a solution here, but it is too long(97 bytes). :(

If our language has variables, do we have to assume the input is stored in one? My code would be shorter if I just read from STDIN. The Perl solution is doing this as well.

I dont mind reading from STDIN or equivalent input, whatever is shortest

@CoolGuy There is no such thing. You're not supposed to beat Pyth with C (because you're never going to). The joy is in beating other submissions in the same language or languages of similar verbosity. If there was already a 50 byte C submission I could understand not posting (although even then, I might post it if the approach is different and interesting). But since there isn't, please do post your answer. You're fairly close to JavaScript and Python, so it's definitely not excessively long for C.

@MartinBüttner , Ok. I posted it.

Pyth, 10 bytes
FNG<.<N4 2

Try it online: Pyth Compiler/Executor
(The first 4 chars =G.Q reads all the data and stores it in G)
Explanation
FNG              for row N in G:
    .<N4            cyclic leftshift by 4
   <     2          print the first two elements

beautiful, I'm starting to like Pyth already

@JuanCortés: This might be a good resource if you're looking to get started with Pyth.

Python 3, 123 76 72 62 bytes
I'm a newcomer, gotta start somewhere...
 for l in G:
  d=l.rstrip().split(',');x=[0,4][len(d)>5];print(d[x:x+2])

With xnor's and DLosc's suggestions (62 bytes):
for l in G:d=l.rstrip().split(',');print(d[4*(len(d)>5):][:2])

Welcome to Programming Puzzles and Code Golf! Since this is a [tag:code-golf] competition, you'll want to make your code as short as possible. One thing you could do is decrease the amount of space used for indents; a single space suffices in Python. This post lists tips for golfing in Python and may be a good reference.

@Alex, thanks - I was trying to figure out what the exact rules are, I was hoping I could ignore some whitespace, but I guess not.

Nope, newlines and spaces both factor into your character count.

In fact, in this case, you don't even need the newline and indent.  Block statements like for can be all on the same line in Python, as long as there isn't another block statement in the body.

A good start. You can put everything on the same line as the for to avoid indents. The conditional [0,4][...] can be shortened to 4*(...), using the fact that bools equal 0/1. Also, if you write d[x:x+2] as d[x:][:2], though one character longer, lets you avoid saving the expression for x to a variable.

@xnor Thanks, is there an etiquette for making updates based on others' suggestions?

@monguin Usually people just update the code, and sometimes say "thanks to [username] for golfing help" or whatever

Perl, 24
perl -pe's/(\d+,){4}|,\d+,\d+$//'

Example:
perl -pe's/(\d+,){4}|,\d+,\d+$//' <in
103,2
106,1
67,2
4,20

This would be 20 bytes in Retina. ;)

Sed, 32 bytes
s/,/=/4
s/.*=//
s/,/:/2
s/:.*//

This deletes everything up to the 4th comma if there is one.
Then it deletes everything from the 2nd comma (which may have previously been 6th).
And I even managed to right-justify!

Any chance of seeing a demo?

I'm not sure what you want from a demo - I ran your supplied test input and got the required output.

Javascript, 44 bytes
Assuming input in variable G.
Edit: I just realized, this looks a lot like nutki's perl solution.
alert(G.replace(/(\d+,){4}|,\d+,\d+$/gm,''))

Snippet Demo:

function run(){
    G = input.value;
    /* start solution */
    alert(G.replace(/(\d+,){4}|,\d+,\d+$/gm,''))
    /* end solution */
}
<textarea id="input" cols="25" rows="6">103,2,50,100
106,1,900,900
459,40,150,300,67,2
4,20,30,6000</textarea><br />
<button id="run" onclick="run();">Run</button>

Scala, 68 bytes
G.map(_.split(",")).map(x=>println((x++x).slice(4,6).mkString(",")))

-- MrBones
Scala, 46 70 bytes
Edit: Print out the result
for{l<-G;r=l.split(",");x=(r++r).slice(4,6).mkString(",")}{println(x)}

Demo

1 byte less, by using map instead G.map{k=>val x=k.split(",");println((x++x).slice(4,6).mkString(","))}

another byte saved by dropping the binding: G.map(_.split(",")).map(x=>println((x++x).slice(4,6).mkString(",")))

CJam, 18 15 14 bytes
r{',/4m<2<pr}h

Try it online in the CJam interpreter.
How it works
r      e# Read a whitespace separated token from STDIN.
{      e# Do-while loop:
  ',/  e#    Split at commas.
  4m<  e#    Rotate the resulting array 4 units to the left.
  2<   e#    Discard everything but the first 2 elements.
  p    e#    Print the array.
  r    e#    Read a whitespace separated token from STDIN.
}h     e# If the token is a nonempty string, repeat the loop.

Javascript, 117 112 99 95 84 76 71 bytes
for(r of G.split('\n'))s=r.split(','),console.log(s[t=s[4]?4:0],s[t+1])

JS Fiddle

Please post a fiddle, or demo

You can remove two b by replacing ; with , in the loop body and therefore removing the braces { and }

@JuanCortés - thanks, didn't know that.  What's the theory behind that?

If no braces are added the body of the loop will be the first expression after the closing parenthesis. An expression ends with a semicolon. Separating expressions with commas makes them sort of like an expression group if you may, ending the expression after them

@JuanCortés -  makes sense, thanks!

Using for of you can save 3 bytes. It works in any modern browser. for(r of q=G.split('\n'))s=r.split(','),console.log(s[t=s[4]?4:0],s[t+1])

@edc65 codegolf is happy to eschew IE then ... nice.

From what I see in Chrome and Firefox, the q= part is not necessary: for(r of G.split... works.

@DocMax - thanks, forgot to remove that when changing it to for..of

POSIX shell, 30 bytes
Assuming POSIX sed and cut are present:
sed 's/.*/&,&/'|cut -d, -f5,6

Duplicates the line, leaving the data of interest ready to be extracted from fields 5 and 6.

Pip, 12 + 1 = 13 bytes
Uses the -l flag, which gives the output as space-separated lists of numbers on each line.*
_@[4 5]Mg^',

Explanation:

The list of numbers is expected in g. Since g is normally initialized from the command-line arguments, you can also put the input there for the same results.
^', splits (each string in) the list on commas.
M maps a function to each element in the result.
_@[4 5] defines a lambda function. The argument to the function is represented by _; @[4 5] returns a list of its 4th and 5th elements. If the list has six elements, these will be the last two. If it has four, the indices wrap around, and so the result is the first two. (E.g. "abcd"@4 == "abcd"@0 == "a".)
We now have a list of lists, like [[103 2] [106 1] [67 2]], which is auto-printed at the end of the program. The -l flag joins each sub-list on space and then the whole thing on newline, so the result is as follows:

C:\>pip.py -le "_@[4 5]Mg^'," 103,2,50,100 106,1,900,900 459,40,150,300,67,2
103 2
106 1
67 2

* Currently. I may change this behavior, but I'm still planning to have some flag that does the same thing.

Perl, 37
@c=/(\d+,\d+)/g;$_=@c>2?$c[2]:$c[0]

35 characters +2 for -p and -l. I'm not sure if there is an approach in Perl that would beat @nutki's solution, but I figured I'd post this idea I had anyway.
Run with:
cat input.txt | perl -ple'@c=/(\d+,\d+)/g;$_=@c>2?$c[2]:$c[0]'

bash, 54
while IFS=, read {a..f};do echo ${e:-$a},${f:-$b};done

C, 95 bytes
f(a,b,c,d){scanf("%d,%d,%*d,%*d,%d,%d",&a,&b,&c,&d)>2?printf("%d,%d",c,d):printf("%d,%d",a,b);}

The code is simple. Here is the ungolfed version:
f(a,b,c,d){                                    //Four int variables
    scanf("%d,%d,%*d,%*d,%d,%d",&a,&b,&c,&d)>2 //Scan input
        ?                                      //If scanf returned a value > 2
        printf("%d,%d",c,d)                    //Print last two values
        :                                      //else
        printf("%d,%d",a,b);                   //Print first two values
}

Test it here

Ruby, 53
G.each_line{|x|g=x.split',';p[g[4]||g[0],g[5]||g[1]]}

or is good.


text:
Stripping off extra spaces from a string
You are given a string. Output the string with one space per words.
Challenge
Input will be a string (not null or empty), surrounded with quotes(") sent via the stdin. Remove leading and trailing spaces from it. Also, if there are more than one space between two words (or symbols or whatever), trim it to just one space. Output the modified string with the quotes.
Rules

The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to ~(tilde) (character codes 0x20 to 0x7E, inclusive) except ",i.e, the string will not contain quotes(") and other characters outside the range specified above. See ASCII table for reference.
You must take input from the stdin( or closest alternative ).
The output must contain quotes(").
You can write a full program, or a function which takes input (from stdin), and outputs the final string

Test Cases
"this  is  a    string   "         --> "this is a string"

"  blah blah    blah "             --> "blah blah blah"

"abcdefg"                          --> "abcdefg"

"           "                      --> ""

"12 34  ~5 6   (7, 8) - 9 -  "     --> "12 34 ~5 6 (7, 8) - 9 -"

Scoring
This is code golf, so the shortest submission (in bytes) wins.

You say must take input from stdin, and later you say ...or a function which takes input, and outputs the final string. Does this mean the function must take input from stdin as well?

@blutorange , Yes. Edited to clarify it.

"   "aa"   " --> ""aa"" (are quotes valid inside the input string?)

@edc65 , Good point. The answer to that is no. Edited to clarify it.

Please see MickeyT's comment on my answer. Is what he proposes valid? In R, returned results are implicitly printed, but in my answer I've explicitly printed to stdout.

@AlexA. , The output needs to be seen in the stdout. It doesn't matter if it is implicitly or explicitly printed.

Some answers are processing string including the double quotes: "   this  ", others process a once double quoted string which reaches the code with the double quotes already stripped off:   this  . This way the answers and the languages'/authors' efficiencies are not really comparable. @CoolGuy, could you firmly clarify the requirement on this?

@manatwork , I don't know. Do many answers take advantage of it? If so, I think it is better to leave both ways permitted.

@CoolGuy, yeah, now that we already have 20 answers, is indeed a bit late to impose a restriction. Though in my opinion this way the challenge is ruined. :(

CJam, 7 bytes
q~S%S*p

Code Explanation
CJam has reserved all capital letters as inbuilt variables. So S has a value of a space here.
q~          e# Read the input (using q) and evaluate (~) to get the string
  S%        e# Split on running lengths (%) of space
    S*      e# Join (*) the splitted parts by single space
      p     e# Print the stringified form (p) of the string.

This removes the trailing and leading spaces as well
Try it online here

///: 18 characters
/  / //" /"// "/"/

Sample run:
(Using faubiguy's interpreter from his Perl answer for Interpret /// (pronounced 'slashes').)
bash-4.3$ ( echo -n '/  / //" /"// "/"/'; echo '"   foo  *  bar   "'; ) | slashes.pl
"foo * bar"

Haven't I seen this program somewhere before?

Technically you're not taking input though. ;) There's this language but reading input is still quite a pain I think.

Perl, 22
(20 bytes of code, plus 2 command line switches)
s/ +/ /g;s/" | "/"/g

Needs to be run with the -np switch so that $_ is automatically filled via stdin and printed to stdout. I'm going to assume this adds 2 to the byte count.

same solution: sed -E 's/ +/ /g;s/" | "/"/g'

The same thing is 12 bytes in Retina. :)

-p implies -n, so you only have to take a +1 penalty here (assuming you don't just switch to a different language, like the other commenters suggest).

Bash, 36 32 bytes
As a function, a program, or just in a pipe:
xargs|xargs|xargs -i echo '"{}"'

Explanation
The first xargs strips the quotation marks.
The second xargs trims the left side and replaces multiple adjacent spaces in the middle of the string with one space by taking each "word" and separating each with a space.
The xargs -i echo '"{}"' trims the right side and rewraps the resulting string in double quotes.

Wow! That is tricky. Unfortunately not handles test case 4, but still impressing.

Yeah, this code meets the fourth test case and is shorter.

Can you do something like this? x=xargs;$x|$x|$x -i echo '"{}"'

@Cyoce: You could indeed do that to save one byte at the cost of losing pipe functionality.  Still not as short as this solution and still doesn't satisfy the fourth test case.

Ruby, 31 29 25 23 Bytes
p$*[0].strip.squeeze' '

Code Explanation:

p outputs string within double quotes to STDOUT (There's more to it though...)
$* is an array of STDIN inputs, $*[0] takes the first one
strip removes starting and ending spaces
squeeze ' ' replaces >1 space characters with a single space

Test Cases:

You can replace ARGV with $* saving two bytes. gsub /\s+/, ' ' can be replaced with squeeze ' ' for another 4 bytes

@DickieBoy, thank you for $*, I didn't know that. But we can't replace gsub /\s+/, ' ' with squeeze because they are not the same.

What do you mean by "are not the same"? The outputs are the same.

Well, they aren't. gsub /\s+/, ' ' replaces >1 'space characters' with a single space character, on the other hand squeeze replaces any character >1 with a single one.

Example: "yellow  moon".squeeze #=> "yelow mon"

squeeze ' ' will only squeeze spaces. "yellow moon".squeeze "l" => "yelow moon"

Your inputs are wrong, they should contain the surrounding double quotes: ./codegolf.rb '"this  is  a    string   "'. The quotes as you have them in your sample run are stripped off by the shell, so they never reach Ruby.

@DickieBoy Oh nice. Thanks!

@manatwork Are you sure that's what OP meant? I can update code, it would be shorter for that. The challenge says "Input will be a string (not null or empty), surrounded with quotes(") sent via the stdin." and the first rule says "the string will not contain quotes(")"

Personally I am. And some of other answerers too. But as I see, neither you are alone with your interpretation…  A clarification from the question owner would be welcome. By the way, both the space between p and its parameter and squeeze and its parameter are unnecessary.

@manatwork Fuck! I didn't know that was possible! Thank you so much!

Pyth, 17 15 11 10 bytes
(thanks to Ypnypn and FryAmTheEggman)
pjd-cQdkNN

Could probably be golfed more.
If the output can use ' instead of " then I only need 8 bytes:
`jd-cQdk

You can use N instead of \"

Welcome to Pyth, Tylio. The second program could be shorterned by the use of d.

@isaacg haven't I already used d for everything it can be used for?

@Tyilo I think you made an edit at about the same time I commented. It's all good now.

You can use p to save a few bytes on string concatenation instead of many +es. pjd-cQdkNN

Oh, I also happened upon this: pjdcQ)NN. It turns out the no-argument version of c (hence closing it with a ) ) automatically strips out excess spaces.

JavaScript (ES6), 49 52 58
Edit 6 bytes shorter, thanks to @Optimizer
Edit 2 -3, thanks to @nderscore
Input/output via popup. Using template string to cut 1 byte in string concatenation.
Run snippet to test in Firefox.

alert(`"${prompt().match(/[^ "]+/g).join(" ")}"`)

alert(\"${eval(prompt()).match(/\S+/g).join(" ")}"`)`   - 52

@Optimizer thx. Note,  that just works after the last clarification about the quotes: eval('"  "  "') would crash.

When I tested the fourth test case (using chrome), no popup (which shows the result) is seen. Why?

@CoolGuy maybe because Chrome does not run ES6? I never test ES6 with Chrome. Anyway I tried it now in my Chrome (42.0.2311.152) and works for me.

-3: alert(\"${prompt().match(/[^ "]+/g).join(" ")}"`)`

@CoolGuy If you are using the console with chrome make sure to not have the devtools in a separate window. since chrome blocks all prompts that don't come from the currently active tab.

" " " " - is that a valid input?

@Qwertiy the string will not contain quotes(") so, no, it's not

Haskell, 31 25 bytes
fmap(unwords.words)readLn

words splits the string into a list of strings with spaces as delimiters and unwords joins the list of strings with a single spaces in-between. The quotes " are stripped of and put back by Haskell's read and show (implicitly via the REPL) functions on strings.
Outputting by the function itself is three bytes longer, i.e. 28 bytes:
print.unwords.words=<<readLn

Edit: @Mauris pointed to the readLn function, which saved some bytes.

I'm getting Parse error: naked expression at top level when I tested both the codes here

@CoolGuy: rextester.com expects whole programs, not functions, so try main=interact$show.unwords.words.read. There's an online REPL at the frontage of http://haskell.org (requires cookies enabled) where you can try fmap(unwords.words.read)getLine.

fmap(unwords.words)readLn and print.unwords.words=<<readLn are a bit shorter.

@Mauris: thanks for pointing to readLn.

Python2, 37
Reduced by 1 byte thanks to @ygramul.
print'"%s"'%' '.join(input().split())

Original version:
print'"'+' '.join(input().split())+'"'

Test cases:

I really wanted to use print" ".join(raw_input().split()), but it would have a trailing space inside the last quotation mark if there were spaces after the last word...

You can shave off an extra byte using % formatting:
print'"%s"'%' '.join(input().split())

R, 45 bytes
cat('"',gsub(" +"," ",readline()),'"',sep="")

The readline() function reads from STDIN, automatically stripping any leading and trailing whitespace. Excess space between words is removed using gsub(). Finally, double quotes are prepended and appended and the result is printed to STDOUT.
Examples:
> cat('"',gsub(" +"," ",readline()),'"',sep="")
    This   is     a   string
"This is a string"

> cat('"',gsub(" +"," ",readline()),'"',sep="")
12 34  ~5 6   (7, 8) - 9 -
"12 34 ~5 6 (7, 8) - 9 -"

Not sure if it complies totally with the rules, but the cat may not be totally required, just the gsub.  The output from that is [1] "This is a string"

@MickyT: Thanks for the suggestion. My interpretation based on the OP's comment (first on the post) was that it had to be printed to stdout. I'll ask for clarification.

Ahhh ... didn't see that comment or requirement

05AB1E, 9 bytes
#õKðý'".ø

Try it online!

#         | Split on spaces.
 õK       | Remove empty Strings.
   ðý     | Join with spaces.
     '".ø | Surround with quotes.

Java 8, 40 bytes
s->'"'+s.replaceAll(" +"," ").trim()+'"'

Explanation:
Try it here.
s->                        // Method with String as parameter and return-type
  '"'                      //  Return a leading quote
  +s.replaceAll(" +",      //  + Replace all occurrences of multiple spaces in the input
                     " ")  //    with a single space
    .trim()                //    and remove all leading and trailing spaces
  +'"'                     //  + a trailing quote

Mathematica, 75 bytes
a=" ";b=a...;Print[InputString[]~StringReplace~{b~~"\""~~b->"\"",a..->a}]

KDB(Q), 28 bytes
" "sv except[;enlist""]" "vs

Explanation
                       " "vs    / cut string by space
      except[;enlist""]         / clear empty strings
" "sv                           / join back with space

Test
q)" "sv except[;enlist""]" "vs"12 34  ~5 6   (7, 8) - 9 -  "
"12 34 ~5 6 (7, 8) - 9 -"

Japt -Q, 10 4 bytes
¸f ¸

Try it

Powershell, 40 bytes
"`"$(($args-Replace' +'," ").trim())`""

Pretty straight forward and not very impressive.
Explanation
Take input parameter via (predfined) args-variable, replace all multiple spaces with one, trim leading and trailing spaces using trim()-method, add quotes. Powershell will print strings to console as default behavior.

Octave, 44 bytes
@(x)[34 strjoin(regexp(x,'\S+','match')) 34]

Try it online!

Tcl, 69 bytes
puts [string map {{ "} \" {" } \"} [regsub -all \ + [gets stdin] \ ]]

Try it online!

Tcl, 79 bytes
puts \"[string trim [regsub -all \ + [string range [gets stdin] 1 end-1] \ ]]\"

Try it online!

@KevinCruijssen Fixed. unfortunately, at the expense of many bytes. Tks for telling me.

Jq 1.5, 42 bytes
split(" ")|map(select(length>0))|join(" ")

Sample Run
$ jq -M 'split(" ")|map(select(length>0))|join(" ")' < data
"this is a string"
"blah blah blah"
"abcdefg"
""
"12 34 ~5 6 (7, 8) - 9 -"

$ echo -n 'split(" ")|map(select(length>0))|join(" ")' | wc -c
  42

Try it online

I caught the output issue earlier (see edit 5) but didn't notice the input issue.  The command is fixed now.  Thanks!

Perl 5, 17 bytes
16 bytes of code + 1 for -p
s/ *("| ) */$1/g

Try it online!

Zsh, 15 bytes
<<<\"${(Qz)1}\"

Try it online!
Input string contains embedded quotes. Remove the Q for 14 bytes if the input string does not contain embedded quotes, as is done in some of the other answers here.
Parameter expansion flags: Q dequotes, then z splits into words as the shell does. The words are then implicitly joined by spaces.

GolfScript, 8 bytes
' '%' '*

Try it online!
Explanation
The logic is quite simple:
' '%     # Split on spaces, remove empty results
    ' '* # Join on spaces

K (ngn/k), 21 18 16 15 bytes
" "/(~#:')_" "\

Try it online!

" "\ split (implicit) input on spaces
(~#:')_ drop empty strings
" "/ join remaining items with spaces

Fortran, 113 bytes
Try it Online!
character(99)S;read(*,'(A)')S;S='"'//trim(adjustl(S))//'"'
do i=1,99;if(S(i:i+1)>'  ')call fput(S(i:i));enddo;end

Per wikibooks, "It should be remembered that Fortran is designed for scientific computing and is probably not a good choice for writing a new word processor."
Fortran doesn't have a regex concept either. This just makes string challenges more interesting!
In this solution, we trim the string S, then iterate over it. Print each character unless it's a space followed by another space.
Previously: 127 bytes, 147 bytes

Other ideas failed! print* always prints a leading space and a new line. Writing to a new string (avoiding formatting directives) is annoying because gfortran fills it with garbage! Sigh

...but fput is awesome.

Nim, 72 bytes
import strutils
echo'"',stdin.readAll[1..^2].splitWhitespace.join" ",'"'

Try it online!
Ignoring the IO restrictions as many answers do, 58 bytes:
import strutils
echo stdin.readAll.splitWhitespace.join" "

Try it online!

C (gcc), 82 bytes
char*s=&s+9;main(t){for(gets(s);*s;s++)*s>32|(s[1]>32&&s[2]&&t)&&putchar(*s,--t);}

Try it online!

ARBLE, 26 bytes
join(explode(s,"%S+")," ")

explode groups by non-spaces, and then join re-concatenates them.
Try it online!

Thunno 2, 4 bytes
OðjṘ

Try it online!
Explanation
OðjṘ  # Implicit input
      # Implicit eval to
      # remove the quotes
O     # Split on spaces
 ðj   # Join on spaces
   Ṙ  # Repr (surround
      # by quotes)
      # Implicit output

golfua, 42 bytes
L=I.r():g('%s*\"%s*','"'):g('%s+',' ')w(L)

Simple pattern matching replacement: find any double quotes (\") surrounded by 0 or more spaces (%s*) & return the single quote, then replace all 1 or more spaces (%s+) with a single space.
A Lua equivalent would be
Line = io.read()
NoSpaceQuotes = Line:gsub('%s*\"%s*', '"')
NoExtraSpaces = NoSpaceQuotes:gsub('%s+', ' ')
print(NoExtraSpaces)

Cobra - 68
As an anonymous function:
do
    print'"[(for s in Console.readLine.split where''<s).join(' ')]"'

Objective-C 215
-(NSString*)q:(NSString*)s{NSArray*a=[s componentsSeparatedByString:@" "];NSMutableString*m=[NSMutableString new];for(NSString*w in a){if(w.length){[m appendFormat:@"%@ ",w];}}return[m substringToIndex:m.length-1];}

Uncompressed version:
-(NSString*)q:(NSString*)s{
    NSArray *a=[s componentsSeparatedByString:@" "];
    NSMutableString *m=[NSMutableString new];
    for (NSString *w in a) {
        if (w.length) {
            [m appendFormat:@"%@ ",w];
        }
    }
    return[m substringToIndex:m.length-1];
}

Bash ,14 bytes
read f;echo $f       # assume f="this  is  a    string   "

What about assuming “   foo   *   bar   ” or anything else with a wildcard character?

Python2, 28 Bytes
lambda s:" ".join(s.split())

Explanation
lambda s

Anonymous function which takes as input s.
s.split()

Returns a list of the words (which are separated by arbitrary strings of whitespace characters) of the string s.
" ".join(...)

Joins list back into a string, with each word separated by a space (" ").

This seems to give incorrect results regarding leading and trailing spaces. Note that the challenge state you should take the input with the double-quotes, and also output them with double-quotes. I also had this wrong at first, until I re-read the challenge.

k4, 23 bytes
" "/:x@&~~#:'x:" "\:0:0

                    0:0  / read from stdin
             x:" "\:     / split string on spaces and assign to x
        ~~#:'            / boolean true where string len>0, bool false otherwise
     x@&                 / x at indices where true
" "/:                    / join with spaces

Wren, 56 bytes
Wait. The replace only does it once? Now I have to use the split-join combo.
Fn.new{|x|x.trim().split(" ").where{|i|i!=""}.join(" ")}

Try it online!
Explanation
Fn.new{|x|                                             } // New anonymous function with the operand x
          x.trim()                                       // Trim out whitespace from both sides of the string
                  .split(" ")                            // Split the string into space-separated chunks
                             .where{|i|i!=""}            // Keep all of those that aren't the null string (due to two consecutive spaces)
                                             .join(" ")  // Join the replaced list together

Husk, 5 bytes
sJ' w

Try it online!
Fully ascii!
Explanation
sJ' w
    w split into words
 J'   join with spaces
s     add quotes

Python 3, 37 bytes
print("%r"%' '.join(input().split()))

Based of user12205's python2 answer. I've replaced the %s with a %r so that single quotes are printed around the string automatically.
Try it online!

Factor, 23 bytes
[ [ 32 = ] " "compact ]

Try it online!
Factor has a combinator called compact that does this. From the documentation:

Generate a new sequence where all runs of elements for which the predicate returns true are replaced by a single instance of elt. Runs at the beginning or end of the sequence for which the predicate returns true are removed.

Alice, 31 bytes
/ot!h';$ !Q'w!/
@Mq!"~K'.% >]]\

Try it online!
Mt!h~;' %Qw]!]' !.$K'"!qo@  Flattened, without flow characters
M                           Read an argument, push it on the stack
 t!h~;                      Remove the leading and trailing quote, write one of them on the tape
      '                     Adds a space on the stack
        %                   Pop the space, pop the argument, split the argument by space and push all of them words on the stack
         Q                  Reverse the stack
          w      .$K        While the stack is not empty
           ]                Go to the end of the tape
            !]              Pop a word from the stack, write to the tape, go to the end of the tape
              ' !           Add a space on the stack
                    '"!     Write a quote on the tape, overwriting the last space
                       q    Concatenate the content of the tape, word and spaces, push the result on the stack
                        o   Pop, output the concatenated result
                         @  Bye


text:
ASCII Art of the Day #2 - Flow Snakes
A Flow Snake, also known as a Gosper curve, is a fractal curve, growing exponentially in size with each order/iteration of a simple process. Below are the details about the construction and a few examples for various orders:
Order 1 Flow Snake:
____
\__ \
__/

Order 2 Flow Snake:
      ____
 ____ \__ \
 \__ \__/ / __
 __/ ____ \ \ \
/ __ \__ \ \/
\ \ \__/ / __
 \/ ____ \/ /
    \__ \__/
    __/

Order 3 Flow Snake:
                 ____
            ____ \__ \
            \__ \__/ / __
            __/ ____ \ \ \    ____
           / __ \__ \ \/ / __ \__ \
      ____ \ \ \__/ / __ \/ / __/ / __
 ____ \__ \ \/ ____ \/ / __/ / __ \ \ \
 \__ \__/ / __ \__ \__/ / __ \ \ \ \/
 __/ ____ \ \ \__/ ____ \ \ \ \/ / __
/ __ \__ \ \/ ____ \__ \ \/ / __ \/ /
\ \ \__/ / __ \__ \__/ / __ \ \ \__/
 \/ ____ \/ / __/ ____ \ \ \ \/ ____
    \__ \__/ / __ \__ \ \/ / __ \__ \
    __/ ____ \ \ \__/ / __ \/ / __/ / __
   / __ \__ \ \/ ____ \/ / __/ / __ \/ /
   \/ / __/ / __ \__ \__/ / __ \/ / __/
   __/ / __ \ \ \__/ ____ \ \ \__/ / __
  / __ \ \ \ \/ ____ \__ \ \/ ____ \/ /
  \ \ \ \/ / __ \__ \__/ / __ \__ \__/
   \/ / __ \/ / __/ ____ \ \ \__/
      \ \ \__/ / __ \__ \ \/
       \/      \ \ \__/ / __
                \/ ____ \/ /
                   \__ \__/
                   __/

Construction
Consider the order 1 Flow Snake to be built of a path containing 7 edges and 8 vertices (labelled below. Enlarged for feasibility):
4____5____6
 \         \
 3\____2   7\
       /
0____1/

Now for each next order, you simply replace the edges with a rotated version of this original order 1 pattern. Use the following 3 rules for replacing the edges:
1 For a horizontal edge, replace it with the original shape as is:
________
\       \
 \____   \
     /
____/

2 For a / edge (12 in the above construction), replace it with the following rotated version:
 /
/   ____
\  /   /
 \/   /
     /
____/

3 For a \ edge (34and 67 above), replace it with the following rotated version:
 /
/   ____
\   \   \
 \   \   \
  \  /
   \/

So for example, order 2 with vertices from order 1 labelled will look like
            ________
            \       \
  ________   \____   \6
  \       \      /   /
   \____   \5___/   /   ____
       /            \   \   \
  4___/   ________   \   \   \7
 /        \       \   \  /
/   ____   \____   \2  \/
\   \   \      /   /
 \   \   \3___/   /   ____
  \  /            \  /   /
   \/   ________   \/   /
        \       \      /
         \____   \1___/
             /
        0___/

Now for any higher order, you simply break up the current level into edges of lengths 1 /, 1 \ or 2 _ and repeat the process. Do note that even after replacing, the common vertices between any two consecutive edges are still coinciding.
Challenge

You have to write a function of a full program that receives a single integer N via STDIN/ARGV/function argument or the closest equivalent and prints the order N Flow Snake on STDOUT.
The input integer is always greater than 0.
There should not be any leading spaces which are not part of the pattern.
There should be either no trailing spaces or enough trailing spaces to pad the pattern to fill the minimum bounding rectangle completely.
Trailing newline is optional.

Fun Facts

Flow Snakes is a word play of Snow Flakes, which this pattern resembles for order 2 and above
The Flow and Snakes actually play a part in the pattern as the pattern is made up of a single path flowing throughout.
If you notice carefully, the order 2 (and higher as well) pattern comprises of rotations of order 1 pattern pivoted on the common vertex of the current and the previous edge.
There is a Non ASCII variant of Flow Snakes which can be found here and at several other locations.

This is code-golf so shortest code in bytes win!

Leaderboard
The first post of the series generates a leaderboard.
To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If I understand correctly, the shapes 1,2,3 are enlarged 2x, so the bottom row in 2 should be made of 4 undescores, not 3.

@edc65 The shapes in the examples are perfectly sized. If you are talking about the Construction part, yes, that is enlarged and there are 3 underscores so that the edge number takes up the 4th's place

But there is no edge numbers in shape 2 (in construction part, yes). The bottom of shape 2 should be equal to the bottom of shape 1.

@edc65 Oh, there!. Fixed!

I read the title as "Snow Flakes" and didn't even notice the real title until you called attention to the difference.

Concerning trailing spaces, and specifically "enough trailing spaces to pad the pattern in a perfect square," was this intended to be "a bounding rectangle"? (the pattern is not square). If square was intended does it matter on which side (top or bottom) the padding is?

@KSab Fixed. How does it sound now ?

@Optimizer The pedant in me wants 'minimum bounding rectangle', though I think the meaning is pretty clear either way ;)

@AndersKaseorg Input is always greater than 0. Mentioned in the Challenge section too.

CJam, 144 bytes
0_]0a{{_[0X3Y0_5]f+W@#%~}%}ri*{_[YXW0WW]3/If=WI6%2>#f*.+}fI]2ew{$_0=\1f=~-
"__1a /L \2,"S/=(@\+\~.+}%_2f<_:.e>\:.e<:M.-:)~S*a*\{M.-~3$3$=\tt}/zN*

Newline added to avoid scrolling. Try it online
The program works in several steps:

The initial fractal (order 1) is encoded as a sequence of 7 angles (conceptually, multiples of 60°) representing the direction of movement
The fractal is "applied" to a horizontal segment (order 0 fractal) N times to generate all the "movements" in the order N fractal
Starting from [0 0], the movements are translated into a sequence of points with [x y] coordinates
Each segment (pair of points) is converted to 1 or 2 [x y c] triplets, representing the character c at coordinates x, y
The bounding rectangle is determined, the coordinates are adjusted and a matrix of spaces is generated
For each triplet, the character c is placed at position x, y in the matrix, and the final matrix is adjusted for output

This answer is long enough to benefit from byte encoding: http://goo.gl/D1tMoc

@Dennis I'm not sure I'm done golfing it... and why did you put it in a block?

I'm not really sure... Your answer is quite impressive. I spent an entirely day trying to get this right.

@Dennis Thanks; btw, do you think it's generally ok to use non-printable/control characters? I usually try to avoid them

If I can avoid them without increasing the byte count, I do. But shorter is shorter. :P In cases like this one where I compress the code itself rather than some string or array, I usually include both versions in the answer.

Python 2, 428 411 388 bytes
This one was pretty tricky. The patterns don't retain their ratios after each step meaning its very difficult to procedurally produce an image from its predecessor. What this code does, though its pretty unreadable after some intense math golfing, is actually draw the line from start to finish using the recursively defined D function.
The size was also an issue, and I ended up just starting in the middle of a 5*3**n sided square and cropping things afterward, though if I can think of better way to calculate the size I might change it.
n=input();s=5*3**n
r=[s*[" "]for i in[0]*s]
def D(n,x,y,t=0):
 if n<1:
    x-=t%2<1;y+=t%3>1;r[y][x]='_/\\'[t/2]
    if t<2:r[y][x+2*t-1]='_'
    return[-1,2,0,1,0,1][t]+x,y-(2<t<5)
 for c in[int(i)^t%2for i in"424050035512124224003"[t/2::3]][::(t^1)-t]:x,y=D(n-1,x,y,c)
 return x,y
D(n,s/2,s/2)
S=[''.join(c).rstrip()for c in r]
for l in[c[min(c.find('\\')%s for c in S):]for c in S if c]:print l

Wow, this is awesome. Wanna give a shot at AAoD #1 ?

r=[s*[" "]for i in range(s)] -> r=[[" "]*s]*s] will shave a few bytes

@sirpercival unfortunately that won't work because of how * repeats mutable objects.

oh, right, i forgot

You can save some bytes by inlining l, switching print'\n'.join() to printing inside a for loop, using return[...][t]+x,, and removing the parentheses from (t%2). Also, you could use min(c.find('\\')%s for c in S) if you change the name of the list S so it doesn't overwrite the initial value of s.

@grc Ah yes, the order of operations of bitwise operators was something I had forgotten about. Also very clever using find like that.

@sirpercival while I might not be able to do that, I did realize that I don't need a whole range if I'm not using i at all.

JavaScript (ES6), 356 362 370
That's a difficult one ...
Each shape is stored as a path. There are 6 basic building blocks (3 + 3 backward)

0 diagonal up left to bottom right (4 backward)
1 diagonal bottom left to up right (5 backward)
2 horizontal left to right (6 backward)

For each one, there is a replacing step to be applied when increasing order:

0 --> 0645001 (backward 4 --> 5441024)
1 --> 2116501 (backward 5 --> 5412556)
2 --> 2160224 (backward 6 --> 0664256)

values prefilled in theh array, even if the elements 4..6 can be obtained from 0..2 using
;[...h[n]].reverse().map(x=>x^4).join('')

To obtain the shape for the given order, the path is built in the p variable applying the substitutions repeatedly. Then the main loop iterates on the p variable and draw the shape inside the g[] array, where each element is a row.
Starting at position (0,0), each index can become negative (y index at high orders). I avoid negative y indexes shifting all the g array whenever I find a negative y value. I don't care if the x index becomes negative, as in JS negative indexes are allowed, just a little more difficult to manage.
In the last step, I scan the main array using .map, but for each row I need to use an explicit for(;;) loop using the b variable that holds the least x index reached (that will be < 0).
In the console.log version there is a handy leading newline, that can be easily made a trailing newline swapping 2 rows, as in the snippet version.
f=o=>{
  g=[],x=y=b=0,
  h='064500192116501921602249954410249541255690664256'.split(9);
  for(p=h[2];--o;)p=p.replace(/./g,c=>h[c]);
  for(t of p)
    z='\\/_'[s=t&3],
    d=s-(s<1),
    t>3&&(x-=d,y+=s<2),
    y<0&&(y++,g=[,...g]),r=g[y]=g[y]||[],
    s?s>1?r[x]=r[x+1]=z:r[x]=z:r[x-1]=z,
    t<3&&(x+=d,y-=s<2),
    x
  {
    o+='\n';
    for(x=b;x<r.length;)o+=r[x++]||' '
  },o='');
  console.log(o)
}

Handy snippet to test (in Firefox) :

f=o=>{
  g=[],x=y=b=0,
  h='064500192116501921602249954410249541255690664256'.split(9);
  for(p=h[2];--o;)p=p.replace(/./g,c=>h[c]);
  for(t of p)
    z='\\/_'[s=t&3],
    d=s-(s<1),
    t>3&&(x-=d,y+=s<2),
    y<0&&(y++,g=[,...g]),r=g[y]=g[y]||[],
    s?s>1?r[x]=r[x+1]=z:r[x]=z:r[x-1]=z,
    t<3&&(x+=d,y-=s<2),
    x
  {
    for(x=b;x<r.length;)o+=r[x++]||' ';
    o+='\n'
  },o='');
  return o
}

// TEST

fs=9;
O.style.fontSize=fs+'px'

function zoom(d) {
  d += fs;
  if (d > 1 && d < 40)
    fs=d, O.style.fontSize=d+'px'
}
#O {
  font-size: 9px;
  line-height: 1em;
}
<input id=I value=3><button onclick='O.innerHTML=f(I.value)'>-></button>
<button onclick="zoom(2)">Zoom +</button><button onclick="zoom(-2)">Zoom -</button>

Haskell, 265 bytes
(?)=div
(%)=mod
t[a,b]=[3*a+b,2*b-a]
_#[0,0]=0
0#_=3
n#p=[352,6497,2466,-1]!!((n-1)#t[(s+3)?7|s<-p])?(4^p!!0%7)%4
0&_=0
n&p=(n-1)&t p+maximum(abs<$>sum p:p)
n!b=n&[1,-b]
f n=putStr$unlines[["__ \\/   "!!(2*n#t[a?2,-b]+a%2)|a<-[b-n!2+1..b+n!2+0^n?3]]|b<-[-n!0..n!0]]

(Note: on GHC before 7.10, you will need to add import Control.Applicative or replace abs<$> with map abs$.)
Run online at Ideone.com
f n :: Int -> IO () draws the level n flowsnake. The drawing is computed in bitmap order rather than along the curve, which allows the algorithm to run in O(n) space (that is, logarithmic in the drawing size).  Nearly half of my bytes are spent computing which rectangle to draw!

I logged in and it works now! Nice!

It turns out this previously didn’t run on Ideone.com because I was assuming 64-bit Int. Fixed now (sacrificing 2 bytes).

Its okay as the login thing only needed my email id for confirmation ..

Perl, 334 316 309
$_=2;eval's/./(map{($_,"\1"x7^reverse)}2003140,2034225,4351440)[$&]/ge;'x($s=<>);
s/2|3/$&$&/g;$x=$y=3**$s-1;s!.!'$r{'.qw($y--,$x++ ++$y,--$x $y,$x++ $y,--$x
$y--,--$x ++$y,$x++)[$&]."}=$&+1"!eeg;y!1-6!//__\\!,s/^$x//,s/ *$/
/,print for
grep{/^ */;$x&=$&;$'}map{/^/;$x=join'',map$r{$',$_}||$",@f}@f=0..3**$s*2

Parameter taken on the standard input.
Test me.

Haskell, 469 419 390 385 365 bytes
the function f::Int->IO() takes an integer as input and print the flow snake
e 0=[0,0];e 5=[5,5];e x=[x]
f n=putStr.t$e=<<g n[0]
k=map$(53-).fromEnum
g 0=id
g n=g(n-1).(=<<)(k.(words"5402553 5440124 1334253 2031224 1345110 2003510"!!))
x=s$k"444666555666"
y=s$k"564645554545"
r l=[minimum l..maximum l]
s _[]=[];s w(x:y)=w!!(x+6):map(+w!!x)(s w y)
t w=unlines[["_/\\\\/_ "!!(last$6:[z|(c,d,z)<-zip3(x w)(y w)w,c==i&&d==j])|i<-r.x$w]|j<-r.y$w]

This produces 2× enlarged figures. I think the question is asking for the smaller figures at the top, and only used 2× enlarged figures to explain how the flowsnake is constructed.

You are right. I corrected it

You could use $ in the definition of k, and replace (!!)a with (a!!) which can get rid from some parentheses. Other than that, you seem to know lots of tricks by yourself. Nice

Python 2, 523 502 475 473 467 450 437 bytes
l=[0]
for _ in l*input():l=sum([map(int,'004545112323312312531204045045050445212331'[t::6])for t in l],[])
p=[]
x=y=q=w=Q=W=0
for t in l:T=t|4==5;c=t in{2,4};C=t<3;q=min(q,x);Q=max(Q,x+C);w=min(w,y);W=max(W,y);a=C*2-1;a*=2-(t%3!=0);b=(1-T&c,-1)[T&1-c];x+=(a,0)[C];y+=(0,b)[c];p+=[(x,y)];x+=(0,a)[C];y+=(b,0)[c]
s=[[' ']*(Q-q)for _ in[0]*(W-w+1)]
for t,(x,y)in zip(l,p):x-=q;s[y-w][x:x+1+(t%3<1)]='_/\_'[t%3::3]
for S in s:print''.join(S)

Pffft, costed me a like 3 hours, but was fun to do!
The idea is to split the task in multiple steps:

Calculate all the edges (encoded as 0-5) in order of appearence (so from the beginning of the snake to the end)
Calculate the position for each of the edges (and save the min and max values for x and y)
Build the strings it consists of (and use the min values to offset, so that we don't get negative indices)
Print the strings

Here is the code in ungolfed form:
# The input
n = int(input())

# The idea:
# Use a series of types (_, /, \, %), and positions (x, y)
# Forwards:   0: __  1: /  2: \
# Backwards:  3: __  4: /  5: \

# The parts
pieces = [
    "0135002",
    "0113451",
    "4221502",
    "5332043",
    "4210443",
    "5324551"
]
# The final types list
types = [0]
for _ in range(n):
    old = types
    types = []
    for t in old:
        types.extend(map(int,pieces[t]))

# Calculate the list of positions (and store the mins and max')
pos = []
top = False
x = 0
y = 0
minX = 0
minY = 0
maxX = 0
maxY = 0
for t in types:
    # Calculate dx
    dx = 1 if t < 3 else -1
    if t%3==0:
        dx *= 2         # If it's an underscore, double the horizontal size
    # Calculate dy
    top = t in {1, 5}
    dy = 0
    if top and t in {0, 3, 1, 5}:
        dy = -1
    if not top and t in {2, 4}:
        dy = 1
    # If backwards, add dx before adding the position to the list
    if t>2:
        x += dx
    # If top to bottom, add dy before adding the position to the list
    if t in {2,4}:
        y += dy
    # Add the current position to the list
    pos += [(x, y)]
    # In the normal cases (going forward and up) modify the x and y after changing the position
    if t<3:
        x += dx
    if t not in {2, 4}:
        y += dy
    # Store the max and min vars
    minX = min(minX, x)
    maxX = max(maxX, x + (t<3)) # For forward chars, add one to the length (we never end with __'s)
    minY = min(minY, y)
    maxY = max(maxY, y)

# Create the string (a grid of charachters)
s = [[' '] * (maxX - minX) for _ in range(maxY - minY + 1)]
for k, (x, y) in enumerate(pos):
    x -= minX
    y -= minY
    t = types[k]
    char = '/'
    if t % 3 == 0:
        char = '__'
    if t % 3 == 2:
        char = '\\'
    s[y][x : x + len(char)] = char

# Print the string
for printString in s:
    print("".join(printString))

Edit: I changed the language to python 2, to be compatible with my answer for #3 (and it also saves 6 more bytes)

Nice job; one simple improvement you could make would be changing l.extend(x) to l+=x. Also you can probably use http://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python/407#407 instead of the .split() you use (I did something similar in my answer)

@KSab Thanks, I feel really stupid now for using extend

C, 479 474 468 427 bytes
There's no beating the Perl and Haskell guys I guess, but since there's no C submission here yet:
#define C char
C *q="053400121154012150223433102343124450553245";X,Y,K,L,M,N,i,c,x,y,o;F(C*p,
int l,C d){if(d){l*=7;C s[l];for(i=0;i<l;i++)s[i]=q[(p[i/7]%8)*7+i%7];return F
(s,l,d-1);}x=0;y=0;o=32;while(l--){c=*p++%8;for(i=!(c%3)+1;i--;) {K=x<K?x:K;L=
y<L?y:L;M=x>M?x:M;N=y>N?y:N;y+=c&&c<3;x-=c%5>1;if(x==X&y==Y)o="_\\/"[c%3];y-=c
>3;x+=c%5<2;}}return X<M?o:10;}main(l){F(q,7,l);for(Y=L;Y<N;Y++)for(X=K;X<=M;X
++)putchar(F(q,7,l));}

To save space on a atoi() call, the number of arguments passed to the program is used for the level.
The program runs in O(n^3) or worse; first the path is calculated once to find the min/max coordinates, then for each (x,y) pair it is calculated once to find the character on that specific location. Terribly slow, but saves on memory administration.
Example run at http://codepad.org/ZGc648Xi

Use X,Y,K,L,M,N,i,j,c; instead of int X,Y,K,L,M,N,i,j,c; and main(l) instead of void main(int l)

Yeah, thanks, I already shaved off those and a bit more, I'll put up a new version.

The output in the latest version seems to be trimmed and a bit off on the ends.

I uploaded the wrong blob, this one should be fine.

Pari/GP, 395
Looping over x,y character positions and calculating what char to print.  Moderate attempts at minimizing, scored with whitespace and comments stripped.
k=3;
{
  S = quadgen(-12);  \\ sqrt(-3)
  w = (1 + S)/2;     \\ sixth root of unity
  b = 2 + w;         \\ base

  \\ base b low digit position under 2*Re+4*Im mod 7 index
  P = [0, w^2, 1, w, w^4, w^3, w^5];
  \\ rotation state table
  T = 7*[0,0,1,0,0,1,2, 1,2,1,0,1,1,2, 2,2,2,0,0,1,2];
  C = ["_","_",  " ","\\",  "/"," "];

  \\ extents
  X = 2*sum(i=0,k-1, vecmax(real(b^i*P)));
  Y = 2*sum(i=0,k-1, vecmax(imag(b^i*P)));

  for(y = -Y, Y,
     for(x = -X+!!k, X+(k<3),  \\ adjusted when endpoint is X limit
        z = (x- (o = (x+y)%2) - y*S)/2;
        v = vector(k,i,
                   z = (z - P[ d = (2*real(z) + 4*imag(z)) % 7 + 1 ])/b;
                   d);
        print1( C[if(z,3,
                     r = 0;
                     forstep(i=#v,1, -1, r = T[r+v[i]];);
                     r%5 + o + 1)]) );  \\ r=0,7,14 mod 5 is 0,2,4
     print())
}

Each char is the first or second of a hexagon cell.  A cell location is a complex number z split into base b=2+w with digits 0, 1, w^2, ..., w^5, where w=e^(2pi/6) sixth root of unity.  Those digits are kept just as a distinguishing 1 to 7 then taken high to low through a state table for net rotation.  This is in the style of flowsnake code by Ed Shouten (xytoi) but only for net rotation, not making digits into an "N" index along the path.  The extents are relative to an origin 0 at the centre of the shape.  As long as the limit is not an endpoint these are the middle of a 2-character hexagon and only 1 of those chars is needed.  But when the snake start and/or end are the X limit 2 chars are needed, which is k=0 start and k<3 end.  Pari has "quads" like sqrt(-3) builtin but the same can be done with real and imaginary parts separately.

This does not quite satisfy the rules regarding leading and trailing whitespace.

Thanks, I amended.  Your haskell beat me by an hour to an x,y loop did it.  Should've posted before waiting to see if further inspiration would come :-).

Now an end of the snake is cut off for k = 0, 1, 2. (The math is irritating that way—I had to deal with it too.)

Ah dear, when the endpoint is the x maximum.  Hmm.