text:
Meta radiation hardener
Background
On this site, we occasionally have questions requiring programs to be "radiation hardened"; this means that the program has to be able to survive the deletion of one or more bytes, no matter which bytes are deleted.
As is common for tasks that frequently get set in programming challenges, it's natural to want to make a language that's particularly good at these challenges. Given that the natural way to make this is to add some metadata that makes it possible to reverse corruption, it's actually not really a language that needs designing, but an encoding; the idea is to transform each input to a sequence of bytes, in such a way that even if the sequence is slightly irradiated, it's possible to extract the original input.
The task
Write two programs or functions, E (an encoder) and D (a decoder), such that:

E takes two arguments, a sequence of octets (which we'll call "input" in this specification) and a nonnegative integer "radiation", and outputs a sequence of octets "encoding";
D takes one argument, a sequence of octets ("encdng"), and outputs a sequence of octets "reconstruction";
If you run both E and D (with encdng, the input to D, chosen by deleting no more than radiation elements from encoding (not necessarily contiguously)), then reconstruction will be equal to input no matter which characters were deleted to form encdng.

Clarifications

If you submit functions, you don't have to call them E and D; you can choose whatever name is most suitable for your language.
An "octet" is basically an integer from 0 to 255 inclusive, which you can encode as an integer, a character, or whatever's appropriate for your language.
E and D must be entirely deterministic (i.e. giving them the same inputs will always produce the same output, where "inputs" is defined as input and radiation for E, or encdng for D). In particular, E may not communicate information to D via a side channel.
The deletions are performed by deleting one element of the sequence; think of opening the seuqence in an editor, placing the cursor at an arbitrary point, and pressing Backspace. If an element appears multiple times, it's possible that only one copy of the element will be deleted (i.e. other instances of the same octet won't be affected).
Although the score is only calculated on the basis of fairly short input, your program must work in theory for any input and radiation. In particular, it must work no matter which octets appear in input. (Sorry, people who would like the ability to use unprintable characters that they know won't appear in the input, but I need to ensure that the input's incompressible so that the challenge is about radiation hardening rather than compression.)
You can submit either one file that defines two functions; two files which each define a function or which are both full programs; or three files, two of which implement D and E respectively (either via being full programs or via defining a function), and the third which is a header file or library common to both D and E. Regardless of which form of submission you use, your programming language implementation must be able to understand both programs without further arguments like file locations (or else you must pay a byte penalty for invoking your implementation in an unusual way, as per our standard rules).

Victory condition
For each length and radiation, let f(length,radiation) be the total lengths of the encodings that correspond to all input with length length, and the given radiation. (That is, f(length,radiation) = suminput has length length length(E(input,radiation)).) Then let g(length,radiation) equal f(length,radiation) ÷ 256length. In other words, g is the average length of the encoded output, for a given length of input and a given radiation hardening requirement. (In theory you could calculate this by brute force, but it would likely take implausibly long to work out your score that way. I'm expecting most submissions will be able to make a mathematical argument as to what their score is. If you're not sure, post an approximate score and you or someone else can calculate it in more depth if another entry posts a similar score.)
Your score is equal to the sum of g(length,radiation) for all radiation in the range 0 to 9 inclusive, and all length in the range 0 to 99 inclusive, plus (mostly to avoid hardcoding, or to keep the competition going if someone discovers a mathematically perfect encoding; this is likely to be a minimal factor otherwise) the total number of bytes in your submission to the challenge (plus the standard penalties for things like requiring unusual interpreter flags or specific filenames). The winner is the entry with the lowest score (tiebroken by the first entry to submit).

May the decoder know the radiation parameter as well?

(or length, but I believe that knowing either should give you the other for most schemes)

@orlp: No, it only has the string. In a [tag:radiation-hardening] problem, the decoder (i.e. language) doesn't know the radiation rules used, so your decoder doesn't know them either; it has to deduce them from its input.

Based on this computerphile video I'd make a language that takes codels in 3-byte triplets: if they don't all match, something went wrong and we have enough information to figure out what the right value is. There's probably a way to do it with fewer bits but I don't have the brain to work out how at the moment.

How do you combine the header and the programs?

@CalculatorFeline: If you're using the three-file approach, via whatever mechanism your language supports for including header files (e.g. #include in C) or libraries (again in C, specifying the filename on the command line when building; note that that would incur a byte penalty).

What if my language does not support any mechanism for including header files?

@CalculatorFeline: Then use the 1-file or 2-file approach. The reason a range of possible approaches is given is to support a range of possible languages.

CJam, score ≤ 286,516 + 54 + 36 = 286,606
Encoder
{_{1\+_:e>)_0a+@@b0\{{)_256b_,\e`,-}g}*256b+\)e*}{*}?}

Try it online!
Decoder
{_{e`1f=(\256b{256b_,\e`,=},,\b1>}&}

Try it online!
Both of these take and return a list integers. The TIO links include conversion from/to strings for convenience. Note that these are incredibly inefficient for longer strings. If you want to try a few more characters, I recommend using characters with small character codes.
The basic idea for creating a radiation-hardened encoding involves two steps:

Find an encoding which never contains two consecutive identical octets.
Repeat each octet in the encoded string r + 1 times, where r is the radiation level.

This way, the radiation can't completely delete one run of identical characters, so that we can decode the string by taking one character from each run and then decoding step 1.
So the only interesting part is finding an encoding that never yields repeated octets. The basic idea is to use something like A043096 as a number system. That is, to encode an integer N, we simply count up in some base b, skipping all numbers with repeated octets. I believe the amount of numbers that can be represented in this way with up to d digits is the same as the amount of numbers that can be represented in bijective base b-1 (since, when you want to write such a number, you can choose between b-1 digit for each position without violating the constraint).
Of course, to obtain maximal compression we will use b = 256. To turn the input into an integer, we can use base conversion as well. If I wasn't lazy, I'd use a bijective base for the input, but for now I'm just prepending a 1 (to ensure there are no leading zeros) and then use the smallest possible base that such that all octets in the input are less than the base.
This base is then prepended to the encoding (so that the decoder knows which base to use) and separated from the remaining number by a 0-octet (this works because the remaining number will never start with a zero). As a minor optimisation, the empty string remains an empty string.
The reason I haven't computed an exact score above is that I'm only computing an upper bound for how long each input will be based on its length and its maximal octet. However, for these two parameters, there will often be two different output lengths, and I haven't bothered figuring out yet where the tipping point between them occurs. I've also used the length of usual base 255 instead of bijective base 255 to estimate that length, which is again slightly bigger than it needs to be. The exact Mathematica code I used for the computation is the following:
num[l_, 1] = 0;
num[l_, base_] := num[l, base] = base^l - Sum[num[l, b], {b, base - 1}]
Sum[
  num[l, b]*(r + 1)*(2 + IntegerLength[2*b^l - 1, 255])/256^l,
  {r, 0, 9}, {l, 1, 99}, {b, 2, 256}
]
N@%

num[l, b] should give the the number of strings of length l with maximum octet b-1 (except for b == 1, where I've hardcoded it to 0 because I'm always using at least base 2).

"Assuming that on average a string of length N cannot be encoded in less than (r+1)*N octets at radiation level r." I see no reason for this to be true. I wouldn't be surprised to see an encoding scheme existing which is O(N + r).

@orlp I'm not seeing how that would be possible, but I'm looking forward to being proven wrong. :)

Nice idea. I don't know CJam, but from your description, it sounds like you're prepending the base to the encoded data. If that's the case, is there a problem if there are characters deleted from the prepended data?  (That's the mistake I made that @Leo pointed out, that I had to fix in my solution.)

@MitchellSpector the base is prepended before repeating each character r+1 times. So the base is radiation safe as well.

That's good -- that's what I ended up doing in my solution as well. You just need to be sure that the decoder can decode the prepended data before knowing what the base is.

How does the encoder decide what base to use? (Why not just stick with 256 and avoid the issue?)

@MitchellSpector the base is for the decoder's output. It always treats the input as base 256.

@MitchellSpector sorry, misread your question. It uses the smallest possible base (maximum octet plus one)

bash + GNU utilities, score 294506 283468
Edit 1: Fixes a problem that @Leo noticed -- thank you!
Edit 2: Improved the encoding method for the radiation parameter, for a better score.
Encoder (97 bytes):
for((j=0;j<$1;j++)){ p+=p\;;}
(sed 's/\(.\)\1/\1a\1a/g'<<<$1;cat)|xxd -p -c1|sed ${p-;}|xxd -r -p

Decoder (121 bytes):
read n
n=`sed 's/\(.\)\1*/\1/g'<<<$n`
sed -r "s/( ..)\1{0,${n//a}}/\1/g"<<<' 0a '`xxd -p -c1`|sed 's/^ [^ ]*//'|xxd -r -p

For the encoder: Octet sequence passed as characters in stdin, radiation parameter r passed as an argument.
For the decoder: Input passed as characters in stdin.
For both: Output on stdout.
The encoder prepends to the input data the digits of r, with a character 'a' inserted between each pair of consecutive identical digits, followed by a single newline. It then copies all the input (starting with the prepended characters), replacing each character by r+1 copies of that character.
The decoder undoes this, going through each of the remaining characters x in its input, skipping up to r consecutive identical copies of x following x, and printing what remains.  The prepended data has no repeated characters, so it can be decoded before r is known.  At that point, r is known, and that value is needed to decode the rest of the data correctly.
You can check that this works even if the original input has repeated identical characters.

Score computation:
Suppose the input has length L and the radiation parameter is r (which is at most 9 for the scoring computation, so it fits in one digit and therefore has no consecutive repeated characters). The prepended data is 2 bytes (digit, newline), so the output is (r+1)(L+2) bytes for the encoded stream.
So g(L,r) = (r+1)(L+2).
It follows that the total score can be computed as

What if the dropped octet is the first one? The decoder wouldn't have an r to read

@Leo  Your're right. I'll look at fixing that tomorrow -- it's too late tonight. Thanks for spotting it.

@Leo I think it's fixable by including r+1 copies of each of the digits of r, followed by r+1 newlines. If that's correct, the score won't go up by very much.

Something like that should work. I think you should take some additional measures to make sure that it works properly with higher radiations (e.g. a radiation of 222), but fortunately the score is computed just over radiations 0-9, so it won't be affected much.
P.S. I was thinking of implementing this same encoding, that's why I spotted the error right away ;)

@Leo Yes, the fix works for all values for the radiation, even though the score only takes into account radiation values of at most 9.

Perl + Math::{ModInt, Polynomial, Prime::Util}, score ≤ 92819
$m=Math::Polynomial;sub l{($n,$b,$d)=@_;$n||$d||return;$n%$b,l($n/$b,$b,$d&&$d-1)}sub g{$p=$m->interpolate([grep ref$_[$_],0..$map{$p->evaluate($_)}0..$}sub p{prev_prime(128**$s)}sub e{($_,$r)=@_;length||return'';$s=$r+1;s/^[␀␁]/␁$&/;@l=map{mod($_,p$s)}l(Math::BigInt->from_bytes($_),p$s);$@l+$r>p($s)&&return e($_,$s);$a=0;join'',map{map{chr$_+$a}l($_->residue,128,$s,($a^=128))}g(@l)}sub d{@l=split/([␀-␡]+)/,$_[0];@l||return'';$s=vecmax map length,@l;@l=g map{length==$s&&mod($m->new(map{ord()%128}split//)->evaluate(128),p$s)}@l;$$_=$m->new(map{$_->residue}@l)->evaluate(p$s)->to_bytes;s/^␁//;$_}

Control pictures are used to represent the corresponding control character (e.g. ␀ is a literal NUL character). Don't worry much about trying to read the code; there's a more readable version below.
Run with -Mbigint -MMath::ModInt=mod -MMath::Polynomial -MNtheory=:all. -MMath::Bigint=lib,GMP is not necessary (and thus not included in the score), but if you add it before the other libraries it'll make the program run somewhat faster.
Score calculation
The algorithm here is somewhat improvable, but would be rather harder to write (due to Perl not having the appropriate libraries). Because of this, I made a couple of size/efficiency tradeoffs in the code, on the basis that given that bytes can be saved in the encoding, there's no point in trying to shave off every point from golfing.
The program consists of 600 bytes of code, plus 78 bytes of penalties for command-line options, giving a 678 point penalty. The rest of the score was calculated by running the program on the best-case and worst-case (in terms of output length) string for every length from 0 to 99 and every radiation level from 0 to 9; the average case is somewhere in between, and this gives bounds on the score. (It's not worth trying to calculate the exact value unless another entry comes in with a similar score.)
This therefore means that the score from encoding efficiency is in the range 91100 to 92141 inclusive, thus the final score is:
91100 + 600 + 78 = 91778 ≤ score ≤ 92819 = 92141 + 600 + 78
Less-golfed version, with comments and test code
This is the original program + newlines, indentation, and comments. (Actually, the golfed version was produced by removing newlines/indentation/comments from this version.)
use 5.010;                    # -M5.010; free
use Math::BigInt lib=>'GMP';  # not necessary, but makes things much faster
use bigint;                   # -Mbigint
use Math::ModInt 'mod';       # -MMath::ModInt=mod
use Math::Polynomial;         # -MMath::Polynomial
use ntheory ':all';           # -Mntheory=:all
use warnings;                 # for testing; clearly not necessary

### Start of program

$m=Math::Polynomial;          # store the module in a variable for golfiness

sub l{ # express a number $n in base $b with at least $d digits, LSdigit first
    # Note: we can't use a builtin for this because the builtins I'm aware of
    # assume that $b fits into an integer, which is not necessarily the case.
    ($n,$b,$d)=@_;
    $n||$d||return;
    $n%$b,l($n/$b,$b,$d&&$d-1)
}

sub g{ # replaces garbled blocks in the input with their actual values
    # The basic idea here is to interpolate a polynomial through all the blocks,
    # of the lowest possible degree. Unknown blocks then get the value that the
    # polynomial evaluates to. (This is a special case of Reed-Solomon coding.)
    # Clearly, if we have at least as many ungarbled blocks as we did original
    # elements, we'll get the same polynomial, thus we can always reconstruct
    # the input.
    # Note (because it's confusing): @_ is the input, $_ is the current element
    # in a loop, but @_ is written as $_ when using the [ or # operator (e.g.
    # $_[0] is the first element of @_.
    # We waste a few bytes of source for efficiency, storing the polynomial
    # in a variable rather than recalculating it each time.
    $p=$m->interpolate([grep ref$_[$_],0..$#_],[grep ref,@_]);
    # Then we just evaluate the polynomial for each element of the input.
    map{$p->evaluate($_)}0..$#_
}

sub p{ # determines maximum value of a block, given (radiation+1)
    # We split the input up into blocks. Each block has a prime number of
    # possibilities, and is stored using the top 7 bits of (radiation+1)
    # consecutive bytes of the output. Work out the largest possible prime that
    # satisfies this property.
    prev_prime(128**$s)
}

sub e{ # encoder; arguments: input (bytestring), radiation (integer)
    ($_,$r)=@_; # Read the arguments into variables, $_ and $r respectively
    length||return''; # special case for empty string
    $s=$r+1; # Also store radiation+1; we use it a lot
    # Ensure that the input doesn't start with NUL, via prepending SOH to it if
    # it starts with NUL or SOH. This means that it can be converted to a number
    # and back, roundtripping correctly.
    s/^[␀␁]/␁$&/; #/# <- unconfuse Stack Exchange's syntax highlighting
    # Convert the input to a bignum, then to digits in base p$s, to split it
    # into blocks.
    @l=map{mod($_,p$s)}l(Math::BigInt->from_bytes($_),p$s);
    # Encoding can reuse code from decoding; we append $r "garbled blocks" to
    # the blocks representing the input, and run the decoder, to figure out what
    # values they should have.
    $#l+=$r;
    # Our degarbling algorithm can only handle at most p$s blocks in total. If
    # that isn't the case, try a higher $r (which will cause a huge increase in
    # $b and a reduction in @l).
    @l+$r>p($s)&&return e($_,$s);
    # Convert each block to a sequence of $s digits in base 128, adding 128 to
    # alternating blocks; this way, deleting up to $r (i.e. less than $s) bytes
    # will preserve the boundaries between each block; then convert that to a
    # string
    $a=0; # we must initialize $a to make this function deterministic
    join'',map{map{chr$_+$a}l($_->residue,128,$s,($a^=128))}g(@l)
}

sub d{ # decoder: arguments; encdng (bytestring)
    # Reconstruct the original blocks by looking at their top bits
    @l=split/([␀-␡]+)/,$_[0];
    @l||return''; # special case for empty string
    # The length of the longest block is the radiation parameter plus 1 (i.e.
    # $s). Use that to reconstruct the value of $s.
    $s=vecmax map length,@l;
    # Convert each block to a number, or to undef if it has the wrong length.
    # Then work out the values for the undefs.
    @l=g map{
        # Convert blocks with the wrong length to undef.
        length==$s&&
            # Convert other blocks to numbers, via removing any +128 and then
            # using Math::Polynomial to convert the digit list to a number.
            mod($m->new(map{ord()%128}split// #/# <- fix syntax highlighting
            )->evaluate(128),p$s)
    }@l;
    # Remove the redundant elements at the end; now that they've reconstructed
    # the garbled elements they have no further use.
    $#l-=$s-1;
    # Convert @l to a single number (reversing the conversion into blocks.)
    $_=$m->new(map{$_->residue}@l)->evaluate(p$s)
        # Convert that number into a string.
        ->to_bytes;
    # Delete a leading SOH.
    s/^␁//;  #/# <- unconfuse Stack Exchange's syntax highlighting
    # Finally, return the string.
    $_
}

### Testing code
use Encode qw/encode decode/;

# Express a string using control pictures + IBM437, to make binary strings
# easier for a human to parse
sub format_string {
    ($_)=@_;
    $_ = decode("Latin-1", $_);
    s/[\0-\x1f]/chr (0x2400 + ord $&)/eag;
    s/\x7f/chr 0x2421/eag;
    s/[ -~\x80-\xff]/decode("IBM437",$&)/eag;
    encode("UTF-8","\x{ff62}$_\x{ff63}")
}

sub test {
    my ($string, $radiation, $samples) = @_;
    say "Input: ", format_string($string);
    my $encoding = e($string, $radiation);
    say "Encoding: ", format_string($encoding);
    say "Input length ", length($string), ", encoding length ", length($encoding), ", radiation $radiation";
    my $decoding = d($encoding);
    $decoding eq $string or die "Mistake in output!";
    say "Decoding: ", format_string($decoding), " from ",
        format_string($encoding);

    # Pseudo-randomly generate $samples radiation-damaged versions.
    srand 1;
    for my $i (1..$samples) {
        my $encdng = $encoding;
        for my $r (1..$radiation) {
            substr $encdng, int(rand(length $encdng)), 1, "";
        }
        my $newdecoding = d($encdng);
        say "Decoding: ", format_string($newdecoding), " from ",
            format_string($encdng);
        $newdecoding eq $string or die "Mistake in output!";
    }

    say "";
    length $encoding;
}

test "abcdefghijklm", 1, 10;
test "abcdefghijklm", 2, 10;
test "abcdefghijklm", 5, 10;
test "abcdefghijklm", 10, 10;
test "\0\0\0\0\0", 1, 10;
test "\5\4\3\2\1", 2, 10;
test "a", 10, 10;

my %minlength = ();
my %maxlength = ();

for my $length (0..99) {
    my ($min, $max) = ("", "");
    $length and ($min, $max) =
        ("\2" . "\0" x ($length - 1), "\1" . "\377" x ($length - 1));
    for my $radiation (0..9) {
        $minlength{"$length-$radiation"} = test $min, $radiation, 1;
        $maxlength{"$length-$radiation"} = test $max, $radiation, 1;
    }
}

say "Minimum score: ", vecsum values %minlength;
say "Maximum score: ", vecsum values %maxlength;

Algorithm
Simplifying the problem
The basic idea is to reduce this "deletion coding" problem (which is not a widely-explored one) into an erasure coding problem (a comprehensively explored area of mathematics). The idea behind erasure coding is that you're preparing data to be sent over an "erasure channel", a channel that sometimes replaces the characters it sends with a "garble" character that indicates a known position of an error. (In other words, it's always clear where corruption has occurred, although the original character is still unknown.) The idea behind that is pretty simple: we divide the input up into blocks of length (radiation + 1), and use seven out of the eight bits in each block for data, whilst the remaining bit (in this construction, the MSB) alternates between being set for an entire block, clear for the entire next block, set for the block after that, and so on. Because the blocks are longer than the radiation parameter, at least one character from each block survives into the output; so by taking runs of characters with the same MSB, we can work out which block each character belonged to. The number of blocks is also always greater than the radiation parameter, so we always have at least one undamaged block in the encdng; we thus know that all blocks that are longest or tied for longest are undamaged, allowing us to treat any shorter blocks as damaged (thus a garble). We can also deduce the radiation parameter like this (it's the length of an undamaged block, minus 1).
Erasure coding
As for the erasure coding part of the problem, this uses a simple special case of the Reed-Solomon construction. This is a systematic construction: the output (of the erasure coding algorithm) is equal to the input plus a number of extra blocks, equal to the radiation parameter. We can calculate the values needed for these blocks in a simple (and golfy!) way, via treating them as garbles, then running the decoding algorithm on them to "reconstruct" their value.
The actual idea behind the construction is also very simple: we fit a polynomial, of the minimum possible degree, to all the blocks in the encoding (with garbles interpolated from the other elements); if the polynomial is f, the first block is f(0), the second is f(1), and so on. It's clear that the degree of the polynomial will equal the number of blocks of input minus 1 (because we fit a polynomial to those first, then use it to construct the extra "check" blocks); and because d+1 points uniquely define a polynomial of degree d, garbling any number of blocks (up to the radiation parameter) will leave a number of undamaged blocks equal to the original input, which is enough information to reconstruct the same polynomial. (We then just have to evaluate the polynomial to ungarble a block.)
Base conversion
The final consideration left here is to do with the actual values taken by the blocks; if we do polynomial interpolation on the integers, the results may be rational numbers (rather than integers), much larger than the input values, or otherwise undesirable. As such, instead of using the integers, we use a finite field; in this program, the finite field used is the field of integers modulo p, where p is the largest prime less than 128radiation+1 (i.e. the largest prime for which we can fit a number of distinct values equal to that prime into the data part of a block). The big advantage of finite fields is that division (except by 0) is uniquely defined and will always produce a value within that field; thus, the interpolated values of the polynomials will fit into a block just the same way that the input values do.
In order to convert the input into a series of block data, then, we need to do base conversion: convert the input from base 256 into a number, then convert into base p (e.g. for a radiation parameter of 1, we have p = 16381). This was mostly held up by Perl's lack of base conversion routines (Math::Prime::Util has some, but they don't work for bignum bases, and some of the primes we work with here are incredibly large). As we're already using Math::Polynomial for polynomial interpolation, I was able to reuse it as a "convert from digit sequence" function (via viewing the digits as the coefficients of a polynomial and evaluating it), and this works for bignums just fine. Going the other way, though, I had to write the function myself. Luckily, it isn't too hard (or verbose) to write. Unfortunately, this base conversion means that the input is typically rendered unreadable. There's also an issue with leading zeroes; this program uses the simple (but not perfectly efficient) method of prepending a 1 octet to the program if it starts with a 0 or 1 octet (and reversing the translation when decoding), thus avoiding the issue altogether.
It should be noted that we can't have more than p blocks in the output (otherwise the indexes of two blocks would become equal, and yet possibly need to produce different outputs form the polynomial). This only happens when the input is extremely large. This program solves the issue in a very simple way: increasing radiation (which makes the blocks larger and p much larger, meaning we can fit much more data in, and which clearly leads to a correct result).
One other point worth making is that we encode the null string to itself, because the program as written would crash on it otherwise. It's also clearly the best possible encoding, and works no matter what the radiation parameter is.
Potential improvements
The main asymptotic inefficiency in this program is to do with the use of modulo-prime as the finite fields in question. Finite fields of size 2n exist (which is exactly what we'd want here, because the blocks' payload sizes are naturally a power of 128). Unfortunately, they're rather more complex than a simple modulo construction, meaning that Math::ModInt wouldn't cut it (and I couldn't find any libraries on CPAN for handling finite fields of non-prime sizes); I'd have to write an entire class with overloaded arithmetic for Math::Polynomial to be able to handle it, and at that point the byte cost might potentially overweigh the (very small) loss from using, e.g., 16381 rather than 16384.
Another advantage of using power-of-2 sizes is that the base conversion would become much easier. However, in either case, a better method of representing the length of the input would be useful; the "prepend a 1 in ambiguous cases" method is simple but wasteful. Bijective base conversion is one plausible approach here (the idea is that you have the base as a digit, and 0 as not a digit, so that each number corresponds to a single string).
Although the asymptotic performance of this encoding is very good (e.g. for an input of length 99 and a radiation parameter of 3, the encoding is always 128 bytes long, rather than the ~400 bytes that repetition-based approaches would get), its performance is less good on short inputs; the length of the encoding is always at least the square of the (radiation parameter + 1). So for very short inputs (length 1 to 8) at radiation 9, the length of the output is nonetheless 100. (At length 9, the length of the output is sometimes 100 and sometimes 110.) Repetition-based approaches clearly beat this erasure-coding-based approach on very small inputs; it might be worth changing between multiple algorithms based on the size of the input.
Finally, it doesn't really come up in the scoring, but with very high radiation parameters, using a bit of every byte (⅛ of the output size) to delimit blocks is wasteful; it would be cheaper to use delimiters between the blocks instead. Reconstructing the blocks from delimiters is rather harder than with the alternating-MSB approach, but I believe it to be possible, at least if the data is sufficiently long (with short data, it can be hard to deduce the radiation parameter from the output). That would be something to look at if aiming for an asymptotically ideal approach regardless of the parameters.
(And of course, there could be an entirely different algorithm that produces better results than this one!)


text:
Running Merge Conflict
When using a tool such as git to merge two files, a conflict could be detected and added to the result of the merge.
A merge of these two files:
my file:
Common line of code 1
Common line of code 2
my lines
Common line of code 3
Common line of code 4

their file:
Common line of code 1
Common line of code 2
their lines
Common line of code 3
Common line of code 4

would result in:
Common line of code 1
Common line of code 2
<<<<<<< Mine
my lines
=======
their lines
>>>>>>> Theirs
Common line of code 3
Common line of code 4

See Conflict Marker Lines
Resolving this conflict with Mine would create this file:
Common line of code 1
Common line of code 2
my lines
Common line of code 3
Common line of code 4

Resolving this conflict with Theirs would create this file:
Common line of code 1
Common line of code 2
their lines
Common line of code 3
Common line of code 4

The objective of this challenge is to write a source file that contains a conflict and still compiles/executes.
Write a source file which:

contains one valid, two-way, conflict marked by the proper patch conflict markers (<<<<<<<, =======, >>>>>>>) Mine and Theirs file descriptors after the markers are optional.
compiles/executes without errors/warnings if the markers remain a part of the source
compiles/executes without errors/warnings if the conflict is resolved by using mine
compiles/executes without errors/warnings if the conflict is resolved by using theirs
outputs "Hello Conflict" when compiling/executing the conflicted file
outputs "Hello Mine" when compiling/executing the mine version
outputs "Hello Theirs" when compiling/executing the theirs version

The markers should be located in the source file in such a way that kdiff3 recognizes the conflict.
Standard loopholes are forbidden.
The shortest code wins.
Score is the length of the conflicted source

Are function submissions allowed, or just full programs?

@Jakob - it must be possible to execute/run it. So if there is a REPL that can execute the function (or just the expression), sure.

Jelly, 51 bytes
<<<<<<<
“½&;»
“£<Ø»
=======

“8ẉI»
>>>>>>>
“¢5Ṛ»;2£

Try it online!
Explanation
The conflict markers here are positioned so that one of three lines becomes the second line of the program after the conflict is resolved; this will be a constant, named 2£. The second line of the original program encodes the string " Conflict" (in Jelly's compressed notation); the third line encodes the string " Mine" (this will become the second line if the conflict is resolved as mine); the sixth line encodes the string " Theirs" (and will become the second line if the conflict is resolved as theirs).
The main program is always the last line, no matter how many lines before it are deleted. It takes the compressed encoding of "Hello", and appends (;) the value of 2£ to it, thus producing the desired output.

JavaScript (ES6), 102 94 93 90 bytes
console.log('Hello',(a=`
<<<<<<<
Mine
=======
Theirs
>>>>>>>
Conflict`.split`
`)[6]||a[1])

If the conflict has been resolved, then there is no sixth line, so it prints the now first line instead. Edit: Saved 3 bytes thanks to @nderscore.

Creative use of regular expressions!

@ErnodeWeerd Oops, I just changed it...

:) no worries, I was happy to see it

-3 bytes: console.log('Hello',(a=\...`)[6]||a[1])`

Brachylog, 68 67 66 bytes
"Hello "wċ₂↰₁w∨"Conflict"w
<<<<<<<
"Mine"
=======
"Theirs"
>>>>>>>

Try it online!
Try the "Hello Mine" version here
Try the "Hello Theirs" version here
Explanation
Thankfully, <<<<<<<, ======= and >>>>>>> are all valid rule definitions in Brachylog. They respectively mean:

Input is less than an implicit varible, itself less than..., etc., itself less than the output.
All elements of the input are equal, and all elements of the input are equal, and..., and Input = Output
Same as the first but greater than instead.

If we remove conflicts, we end up with "Mine" or "Theirs" on the second line, which means they become predicate number 1. Calling that predicate with ↰₁ on the first line will unify its input and output with Mine / Theirs, which we then print with w.
If we call ↰₁ on the conflicted file, we end up calling <<<<<<<. We therefore call that predicate with a string as input (using ċ₂ - coerce to string). < will fail with a string as input. We then put a disjunction ∨"Conflict"w in the main predicate which states that if predicate 1 fails, then we print Conflict instead. ↰₁ with a string as input won't fail for the "Mine" or "Theirs" lines because they are strings.

PHP, 74 65 bytes
Note: uses IBM-850 encoding
Hello<?='
<<<<<<<
2:<?PU_~
=======
+;73"&_~
>>>>>>>
'^~ıÇ¼¡Ñ»¬áü;

Store to a file and run like this:
php -nf conflict.php

Explanation
Hello       # Print "Hello"
<?='        # Print result of expression
<<<<<<<     # String with merge conflict
2:<?PU_~
=======
+;73"&_~
>>>>>>>
'
^           # XOR that string with...
~ıÇ¼¡Ñ»¬áü; # ... this string, negated.

The binary XOR results in either of the following 3:
'
<<<<<<<
' ^ ~'ıÇ¼¡Ñ»¬áü'
==> ' Conflict'
--------------------------------------------------------------------------
'
2:<?PU_~' ^ ~'ıÇ¼¡Ñ»¬áü'
==> ' Mine' (right padded with nul bytes)
--------------------------------------------------------------------------
'
+;73"&_~' ^ ~'ıÇ¼¡Ñ»¬áü'
==> ' Theirs' (right padded with nul bytes)

Tweaks

Saved 9 bytes by using binary logic on strings

Someday PHP will have an ======= operator, and then this'll be a bit easier.

Pip, 61 bytes
"Hello ".("Conflict
<<<<<<<
Mine
=======
Theirs
>>>>>>>
"^n7)

Try it online!
Everything between "" is a string. We split the large string on newlines ("..."^n) and take the 7th element with cyclical indexing ((___7)). For the conflicted version, there are seven lines, so index 7 is equivalent to index 0 and we get Conflict. For the resolved versions, there are three lines, so index 7 is equivalent to index 1 and we get Mine/Theirs. Then concatenate "Hello " to the front and autoprint.

Very creative, I like the cyclical indexing.

Batch, 133 129 bytes
@set s=Theirs
@goto t
<<<<<<<
:t
@set s=Mine
@goto m
=======
:m
@set s=Conflict
@goto t
>>>>>>>
:t
:m
echo Hello %s%

Explanation: The goto statement goes to the next label it can find. In the case of the conflict, this just ends up skipping the conflict markers, and s gets its final value. In the case of resolving with Mine, the gotos have no effect, but the last set no longer exists, so the result is Mine. In the case of resolving with Theirs the inital goto bypasses the remaining set so the result is its initial value. Edit: Saved 4 bytes thanks to @DLosc.

Nice! Can you remove :c and do @goto t instead?

@DLosc Oh, so Batch goes to the next label, rather than the first? Neat!

I don't know--I haven't tested it. I might be completely wrong.

Python 2, 88 87 bytes
print 'Hello','''
<<<<<<<
Mine
=======
Theirs
>>>>>>>
Conflict'''.split('\n')[1::5][-1]

Prints the sixth or (now) first line as appropriate.

It doesn't print the "Hello " part...

@ErnodeWeerd Sorry, I'd made that mistake in my other answer too, and forgotten to fix this one.

Is there a space between Hello and whatever follows?

@ErnodeWeerd The Python 2 print statement always uses a space as separator (and a trailing newline; Python 3's print function allows you to choose the separator and terminator).

.COM opcode, 77 bytes
0000h: B4 09 BA 17 01 CD 21 BA 1F 01 80 3E 1F 01 3C 75 ; ......!....>..<u
0010h: 03 BA 44 01 CD 21 C3 48 65 6C 6C 6F 20 24 0A 3C ; ..D..!.Hello $.<
0020h: 3C 3C 3C 3C 3C 3C 0A 4D 69 6E 65 24 0A 3D 3D 3D ; <<<<<<.Mine$.===
0030h: 3D 3D 3D 3D 0A 54 68 65 69 72 24 0A 3E 3E 3E 3E ; ====.Their$.>>>>
0040h: 3E 3E 3E 0A 43 6F 6E 66 6C 69 63 74 24          ; >>>.Conflict$

        org 100h
        mov ah, 9
        mov dx, str1
        int 21H
        mov dx, str2
        cmp [str2], byte '<'
        jne $+5
        mov dx, str3
        int 21H
        ret

str1    db 'Hello $', 10
str2    db '<<<<<<<', 10
        db 'Mine$', 10
        db '=======', 10
        db 'Their$', 10
        db '>>>>>>>', 10
str3    db 'Conflict$'

If a space after <<<<<<< allowed, 75 bytes
0000h: B4 09 BA 0D 01 CD 21 BA 1E 01 CD 21 C3 48 65 6C ; ......!....!.Hel
0010h: 6C 6F 20 24 0A 3C 3C 3C 3C 3C 3C 3C 20 0A 43 6F ; lo $.<<<<<<< .Co
0020h: 6E 66 6C 69 63 74 24 4D 69 6E 65 24 0A 3D 3D 3D ; nflict$Mine$.===
0030h: 3D 3D 3D 3D 0A 2A 2A 2A 2A 2A 2A 2A 2A 54 68 65 ; ====.********The
0040h: 69 72 24 0A 3E 3E 3E 3E 3E 3E 3E                ; ir$.>>>>>>>

        org 100h
        mov ah, 9
        mov dx, str1
        int 21H
        mov dx, str2
        int 21H
        ret

str1    db 'Hello $', 10
        db '<<<<<<< ', 10
str2    db 'Conflict$'
        db 'Mine$', 10
        db '=======', 10
        db '********Their$', 10
        db '>>>>>>>'

Nice one! Would you be able to add the assembly version(s), I would enjoy being able to read the instructions :).  Yes, space appears to be allowed (the specs aren't as clear as I would like them to be)

Retina, 57 bytes

Hello
$
<<<<<<<
Mine
=======
Theirs
>>>>>>>
<+
Conflict
Try it online!
Try the "Mine" version
Try the "Theirs" version
Explanation of Conflict program
As is often the case with Retina, this program contains many replace stages.

Hello
Replace the empty/non-existent input with Hello .
$
<<<<<<<

Replace the end of the working string with <<<<<<<
Mine
=======

Replace Mine with =======. Since Mine doesn't appear anywhere in the working string, this does nothing.
Theirs
>>>>>>>

Replace Theirs with >>>>>>>. Same deal as with Mine; Theirs doesn't appear, so the replacement does nothing.
<+
Conflict

Replace a sequence of < with Conflict. We added <<<<<<< to the end of the string on the first replacement, so the working string becomes Hello Conflict, which is implicitly output at the end of the program.
Explanation of Mine/Theirs programs
When the conflict is resolved, the code will look like this:

Hello
$
Mine
<+
Conflict

Hello
Same as before, starting with the string Hello.
$
Mine

Now instead of appending <<<<<<< to Hello , we append Mine.
<+
Conflict

Next, we replace a sequence of < with Conflict. But there are no <s in the string, so nothing happens.
The working string, Hello Mine, is implicitly output. The "Theirs" program works the same way.

OIL, 88 80 77 bytes
4
2
Hello
10
Conflict
16
16
8
4
11
3
<<<<<<<
Mine
=======
Theirs
>>>>>>>
4
4

4 2 is printing line 2 (Hello), 10 tests whether line 0 (4) is identical with line 16 (the one that contains a 4 when the conflict exists) and jumps to either line 16 or line 8 depending on the result. If it existed, 4 4 prints line 4 (Conflict). If it didn't, 4 11 prints either Mine or Theirs, depending on what was merged, and 3 exits.

Java 145 Bytes
()->{String s = "Hello ";/*
<<<<<<<
*/s+="Mine";/*
=======
*/s+="Theirs";/*
>>>>>>>
*/if(s.length()>15)s="Hello Conflict";System.out.println(s);}

Java has no multiline strings so some Comment trickery was needed

What is the reason for the extra * on the third line? I would think that just */s+="Mine";/* would work.

leftover from when comment lines were separate lines to avoid identical lines(refactored before posting and forgot that), thx for that hint and 3 bytes

Bash, 76 bytes
Golfed
sed 's/^/Hello /;s/<\+/Conflict/;q'<<E
<<<<<<<
Mine
=======
Theirs
>>>>>>>
E

How it works
Uses here doc, to feed the source text to sed.
Sed will prepend the first line it read with "Hello ", replace the <<<<<<< string by "Conflict" and then quit (q).
Try It Online !

ES6 (Javascript), 83, 82 bytes
Golfed
alert("Hello "+((T=`\
<<<<<<<
Mine
=======
Theirs
>>>>>>>
`)[1]>"<"?T:"Conflict"))

Try It

alert("Hello "+((T=`\
<<<<<<<
Mine
=======
Theirs
>>>>>>>
`)[1]>"<"?T:"Conflict"))

alert("Hello "+((T=`\
Mine
`)[1]>"<"?T:"Conflict"))

alert("Hello "+((T=`\
Theirs
`)[1]>"<"?T:"Conflict"))

C (GCC), 110 bytes
Function submission.
f(){char*s[]={0,"Mine","Theirs","Conflict"};printf("Hello %s",s[/*
<<<<<<<
*/1/*
=======
*/+2/*
>>>>>>>
*/]);}

Approach inspired by masterX244's Java solution.
TIOs

mine
theirs
conflict

Nice one! Smart use of the multi-line comments.

Java 8, 108 bytes
This is a lambda accepting empty input and returning nothing.
n->System.out.print("Hello "+",Mine,Theirs,Conflict".split(",")[/*
<<<<<<<
*/1/*
=======
*/+2/*
>>>>>>>
*/])

Try It Online
Approach inspired by masterX244's Java solution.

Perl 5, 68 bytes
Updated after realising that the version with 6 of each delimiter works as intended, but with the actual 7 delimiters, it doesn't... Oops...
say"Hello ",q
<<<<<<<
!Mine!;0
=======
!Theirs!;0
>>>>>>>
&&Conflict

Try the conflict online!
Try mine online!
Try itheirs online!

source: Stack Exchange

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

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

sort: votes


text:
Google search result short summary
Intro
When you search in google, it always shows you a result with a sample text from the found webpage.
For example if you search for "Madonna greatest vinyl", google will show you one line link, and below a short excerpt from that found webpage:
Madonna Greatest Hits Records, LPs, Vinyl and CDs
Madonna - Greatest Hits Volume 2, Madonna, Greatest Hits ... vinyl Is Fully Restored To As Near New Condition As Possible. Shipping & Multiple Order D..
Task
Imagine yourself you work for google and you have to write a program/function which takes in:

a string containing many words (the webpage content)
list of searched words (at least 3)

and returns the shortest excerpt of given string (webpage) containing all searched words.
Example
Given this webpage content:

This document describes Session Initiation Protocol (SIP), an application-layer
 control (signaling) protocol for creating, modifying, and terminating
 sessions with one or more participants. These sessions include
 Internet telephone calls, multimedia distribution, and multimedia conferences.

and these searched words: calls, sessions, internet
the program should return: sessions include Internet telephone calls, as this is the shortest substring containing all 3 searched words. Note that one more substring contains these 3 words, it is "sessions with one or more participants. These sessions include Internet telephone calls", but it is longer, so it was discarded.
Rules

If the string is empty, return empty string
If all searched words are not found in given string, return empty string
Search is ignoring letters case
At least 3 words need to be specified for searching
The returned string may contain the searched words in different order than specified

Challenge
Write the fastest code. It's for google, right? Remember that repeatable strings comparison is very expensive.

Google doesn't always show a sample. Next time please post to the sandbox first.

This looks like it could be a good challenge, but you need to be more specific about the task, e.g. by defining possible inputs and outputs. Will there always be one text and three search words? Are the search words arbitrary strings? What should be returned if not all search words are present in the text?

So... what's the winning criteria?

I could maybe require to do it in one loop, but that would be a hint.

05AB1E, 13 bytes
Œévyl²l#åPiyq

Explanation:
Œé            # Get substrings sorted by shortest first
  vyl         # For each substring (in lowercase)...
     ²l#      # Split the searched text (in lowercase)on spaces
        åP    # Check if each word of the searched text is in the substring
          iyq # If so, print the substring and terminate the program

Try it online!
It will only work for one line of input.

It's very inefficient. Do you know how many substrings will it be if there are n words? I guess n!. And generating all of them will be time-consuming.

@FilipStachowiak This is [tag:code-golf], right? Not [tag:fastest-code]. I'm not entirely sure because there is no tag on your question for the winning criterion.

Actually I removed the code-golf tag when I understood its meaning. There are no special winning criteria for this task. I think it's interesting as-is.

@FilipStachowiak that's exactly why it's closed as unclear what you're asking. The rules of PPCG state that every challenge must have an objecting winning criterion.

Great! I'll figure sth out.

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


text:
Motorcycle gear checker!
Some of you may be familiar with the way that a motorcycle shifts. But for those who don't, It looks like this
6
5
4
3
2
N
1
Now I want to know what gear I am in after performing a few up and down shifts.
 The program should work from neutral.
Sample input:
V^^

Sample output:
2

As you can see I downshifted once from N to 1 and upshifted twice to 2nd gear.
This is a code golf. Shortest answer in bytes wins.
Note: The input can be any 2 characters. Can be U and D for up and down or whatever you want it has to be a string. You cannot shift beyond 1st or 6th gear. If you are in 6th and upshift again it will stay in 6th. Good luck!

Next time, please post your challenge to the sandbox to get feedback before posting it on main

@LliwTelracs oh, I am sorry I didn't know that! I will keep it in mind.

Can the input shifts be on separate lines?

@seshoumara the only two requirement are that is has to be a string and that you can only input 2 characters. So could use a newline as a character. but If you'd use it for another reason, I don't  really mind. it would be interesting to see what you have in mind. but give a short explaination as to why you've done it that way if you do. GL!

I meant using D and U, but put each one on separate lines because that's the natural way of parsing in sed.

@seshoumara Go for it. the preferred way would be a normal 1 line string but if its the natural way of parsing I think it should be allowed

It's a shame this doesn't account for the half-step shift between 1 and N.  It'd be neat to be able to not only go 2 N 1 N 2 3, but also go 2 1 N 2 3

I agree to @CortAmmon - there is a single shift between 1 and 2. It's half shift where the neutral is.

not all motorcycles shift like this. Most clutchless motorcycles shift in N-1-2-3-4 (or N-1-2-3 on some very ancient vehicles). They don't have gear 5 or 6 and use a round gear, i.e. when it's 4 then increasing the gear will make it wrap around to N.

@LưuVĩnhPhúc Ofcourse not every single motorcycle ever, but most modern motorcycles (and the one that I own) ;)

@Lifeless most modern motorcycles in my country are automatic clutch, and there are tens of millions of them. One of the top of the world. There are very few clutched motocycles compared to clutchless and scooteres

JavaScript (ES6), 49 48 47 46 bytes
Expects:

1 for down
7 for up

f=([c,...s],g=2)=>c?f(s,g-c&7||g):'1N'[--g]||g

Formatted and commented
f = (                   // f is a recursive function which takes:
  [c,                   // - c = next character in input string
      ...s],            // - s = remaining characters
  g = 2                 // - g = current gear, with default = neutral = 2
) =>                    //
  c ?                   // if there's still a character to process:
    f(                  //   do a recursive call with:
      s,                //     - the remaining characters
      g - c & 7 ||      //     - the updated gear if it is valid
      g                 //       or the previous gear if not
    )                   //
  :                     // else:
    '1N'[--g] ||        //   decrement g and output '1' for g = 0, 'N' for g = 1,
    g                   //   or simply the corresponding digit for other values

Gears are mapped as follows:
g MOD 8 = 0 1 2 3 4 5 6 7
          ---------------
gear    = X 1 N 2 3 4 5 6       (where 'X' is an invalid state)

Which allows us to easily check the validity of the current gear with:
(g & 7) != 0

Demo

f=([c,...s],g=2)=>c?f(s,g-c&7||g):'1N'[--g]||g

console.log(f(''))
console.log(f('1'))
console.log(f('11'))
console.log(f('17777'))
console.log(f('1777777771'))

05AB1E, 22 20 bytes
Îvy<+®‚Z5‚W}6LÀ'N¸ìè

Try it online!
Explanation
Î                      # push 0 (accumulator) and input
 v         }           # for each in input
  y<+                  # decrement current element and add to accumulator
     ®‚Z               # take maximum of current value and -1
        5‚W            # take minimum of current value and 5
            6L         # push the range [1 ... 6]
              À        # rotate left
               'N¸ì    # prepend the letter "N" producing the list [N, 2, 3, 4, 5, 6, 1]
                   è   # index into this list with the value produced by the loop

MATL, 32 28 23 bytes
5 bytes saved thanks to @Luis
'234561N'j!Uq[aA]&Ys0))

This solution uses '2' for up-shift and '0' for down-shift.
Try it at MATL Online
Explanation
'234561N'   % Push the string literal to the stack
j           % Grab the input as a string
!U          % Convert the input to a numeric array based on the characters.
q           % Subtract 1 to turn '2' into 1 and '0' into -1
[aA]        % Push the array [-1 5] to the stack
&Ys         % Compute the cumulative sum using the array [-1, 5] as
            % the upper and lower limits at each point
0)          % Get the last value from the cumulative sum
)           % Use this to index into the initial string literal.
            % Implicitly display the result

@Lifeless Updated with an explanation

Very nice! may i ask why the string is 234561N instead of 1n23456 or 65432n1? I also found a flaw! If you keep upshifting it should stay in 6th gear but it returns N

@Lifeless So we have to deal with invalid input?

I quote: "If you are in 6th and upshift again it will stay in 6th." So yes should. your program does deal with downshifting though. if i input VVVVVVVV it will return 1. but ^^^^^^^^ returns N unfortunately

@Lifeless Oh I see now, that was a late edit to the question. I will update.

@Lifeless Updated.

Nice! Didn't know about the limits trick in cumsum

@B.Mehta Me neither! Luis recommended it

@B.Mehta Also, feel free to join us over in the MATL chatroom!

Java 7, 106 105 103 bytes
char c(String s){int r=1;for(int c:s.toCharArray())r+=c<99?1:-1;return"1N23456".charAt(r<0?0:r>6?6:r);}

Explanation:
char c(String s){                // Method with String input and character return-type
  int r = 1;                     // Result-index (0-indexed and starting at 1)
  for(int c : s.toCharArray()){  // Loop over all characters in the input String
    r += c < 99 ?                //  If the current character is '^':
           1                     //   Raise the result-index by 1
         :                       //  If it is 'v' instead:
           -1;                   //   Decrease the result-index by 1
  }
  return "1N23456".charAt(       // Return the character based on the return-index:
           r < 0 ?               //  If the result-index is below 0
                  0              //   Use 0 instead
                 : r > 6 ?       //  Else-if the result-index is above 6
                          6      //   Use 6 instead
                         :       //  Else
                          r);    //   Use the result-index
}

Test code:
Try it here.
class M{
  static char c(String s){int r=1;for(int c:s.toCharArray())r+=c<99?1:-1;return"1N23456".charAt(r<0?0:r>6?6:r);}

  public static void main(String[] a){
    System.out.println(c("v^^"));
    System.out.println(c("^^^^^^^^"));
    System.out.println(c("vvvv^^^vvvv"));
    System.out.println(c("^v^v^v^v"));
  }
}

Output:
2
6
1
N

V, 20, 15 bytes
:sil!î¬61énÀxVp

Try it online!
Input is a string of h (up) and l (down) characters.
Thanks to @nmjcman for saving 5 bytes and teaching me about a vim feature I never knew about!
If we could assume the input never goes out of bounds, it would simply be 9 bytes:
¬61énÀxVp

But unfortunately that isn't allowed.
Explanation:
:sil!           " If the cursor goes out of bounds, ignore it and continue
     î          " Run the following keystrokes as V code, rather than vimscript:
      ¬61       "   Insert the string "654321". This will leave the cursor on the '1'
         én     "   Insert an 'n'
           À    "   Run the first arg as V code. This will move left and right a bunch of times
            x   "   Delete whatever character we ended up on
             V  "   Select this whole line,
              p "   And replace it with the character we just deleted

Also, Try it online! V compression.  That's cool.

Actually, I think that this doesn't work because going over or under the 1/6 breaks the macro :/

Why is the 9 byte answer not allowed?

@AlbertRenshaw It fails if you ever attempt to shift beyond 1st or 6th gear. For example Try it online! should output n, not 1.

Oh I see, I thought by input is always valid you meant non-shifting characters. Still a cool answer even if its invalid

Haskell, 59 53 51 Bytes
("1N23456"!!).foldl(\l c->max 0$min 6$l+read[c]-1)1

Uses 0 for down and 2 for up. Usage example:
(("1N23456"!!).foldl(\l c->max 0$min 6$l+read[c]-1)1) "0002"

Thanks to @xnor for taking off 6 bytes! Also, turns out I don't need a function name or parentheses so that's another 2 bytes.

If you take the input chars as 0 and 2, you can do read[c]-2.

Welcome to PPCG! Anonymous functions are fine too, so you don't need the g=.

@Laikoni I'd have to wrap it in parentheses, right? That wouldn't change the byte count so I thought I'd leave the g= because it's clearer

@user1472751 You don't need the parens.

JavaScript (ES6), 48 58 bytes
s=>"1N23456"[[1,...s].reduce((a,b)=>a?a<6?+b?a+1:a-1:6:0)]

Usage
Assign it to a function, and then call it. Input is a string containing a 1 for an upshift, and a 0 for a downshift.
f=s=>"1N23456"[[1,...s].reduce((a,b)=>a?a<6?+b?++a:a--:6:0)]
f("011")
-> "2"
f("0")
-> "1"
f("01")
-> "N"

f(0) returns 1 not N... and your code returns undef if you shift up from 6 or down from 1

Good catch. Fixed at cost of two bytes

Doesn't work input such as f("001") which should return N (gear down to 1, gear down staying at 1, gear up to N)

Not supposed to loop around. It should stay at 6 if upshifted from 6 and stay at 1 if downshifted from 1. Also, it still gives undef if you downshift from 1

PHP 7.1, 71 bytes
for(;$c=$argv[1][$i++];))$g=max(-1,min($g+=$c<=>X,5));echo N234561[$g];

shifts $g from -1 to 5, uses negative string offset for first gear.
Run with -nr, provide shifting string as command line argument.

Jelly, 17 14 bytes
1;r2ị$¥/CỊ¡o”N

Uses 6 for up and0 for down.
Try it online!
How it works
1;r2ị$¥/CỊ¡o”N  Main link. Argument: s (string of 6's and 0's)

1;              Prepend a 1 (integer) to the string/character array s.
       /        Reduce the result by the following dyadic link.
                Let's call the arguments x and y.
      ¥           Create a dyadic chain of 2 links:
  r                 Construct the range [x, ..., y] (increasing or decreasing).
                    y will be a character, but 'r' casts both argument to int.
                    This is intended for use with floats, but it works just as well
                    when the argument is a digit.
     $              Create a monadic chain of two links:
   2ị                 Take the second element of the constructed range.
                  When y = 6 > x, this gives x + 1.
                  When y = 0 < x, this gives x - 1.
                  When y = x, the range is a singleton array, so this gives x.
          ¡     Conditional application:
         Ị        If the previous result is insignificant (0 or 1):
        C           Subtract it from 1.
                This swaps 0 and 1 without affecting the other potential outcomes.
           o”N  Logical OR with 'N', replacing 0 with that character.

Ruby, 58 bytes
->s{a=1;s.chars{|b|a-=[a<=>0,a<=>6][b<=>?v]};"1N23456"[a]}

Expected input is 'v' for a downshift and '^' for upshift

Rebol, 96 93 bytes
f: func[s][g: next"1N23456"parse s[any["D"(g: back g)|"U"(unless tail? x: next g[g: x])]]g/1]

Ungolfed:
f: func [s] [
    g: next "1N23456"
    parse s [
        any [
              "D" (g: back g)
            | "U" (unless tail? x: next g [g: x])
        ]
    ]
    g/1
]

Example usage (in Rebol console):
>> print f "DUU"
2

>> print f "DDDUU"
2

>> print f "UUUUUUUUU"
6

>> print f "UUUUUUUUUD"
5

Processing JS (modified) 121 bytes
var g="1N23456",a="",c=0; for(var i=0;i<a.length;i++){if(a[i]==="d"&&c>0){c--;}else if(c<6&&a[i]==="u"){c++;}}println(g[c]);

Ungolfed
var g=[1,"N",2,3,4,5,6],a="",c=0;
for(var i=0;i<a.length;i++)
{if(a[i]==="d"&&c>0)
{
    c--;

}else if(c<6&&a[i]==="u")
{
    c++;

}

}
println(g[c]);

Try it online!
I went with PJs since I know it well. The only problem is the version I use is very strictly typed. I can't leave out brackets and lots of other tricks. It is pretty simple. The input should go into the variable a and it takes lowercase u d. The program loops until it hits the end of the string and every iteration it checks to see if it is a u or a d. If it is and it won't try and "shift" past where you can it shifts. At the end I print the results!

If your version allows ternary operators, you might be able to rewrite your ifs in a much more shorter fashion, I think.

The input should go into the variable a Using hard coded input is not a default input method, see here.

@Laikoni really? That is silly. I don't have any better way. If I have to redo this it will be ~100 bytes longer

Can't you simply wrap your code in a function? Eg. void f(String[] a){...} That's hardly 100 bytes.

@Laikoni In Khan Academy ProcessingJS, it is pure JS, and hence doesn't have String or void. But you're right, a function would be way shorter

@Laikoni input is not really supported. There is no way of getting input like that.

k, 25 bytes
"1N23456"@{6&0|x+y-92}/1,

It takes input as a string, and uses [ for downshift, and ] for upshift, because they're conveniently situated.
"1N23456"@                / the numbers 0 to 6 are used for the gears,
                          / this turns them into the correct number/letter
                       1, / prepend 1 because this is our initial gear
          {          }/   / fold the function through the list
                          / x is before, y is the next character
                 y-92     / subtract 92, which is between "[" and "]"
                          / "[" becomes -1 and "]" becomes 1
               x+         / add it to what we had before
           6&0|           / use max and min to set boundaries 6 and 0

Examples:
 shift:"1N23456"@{6&0|x+y-92}/1,
 shift"[]]"
"2"
 shift"]]]]]]]]"
"6"
 shift"[[[[]]][[[["
"1"
 shift"[][][][]"
"N"
 shift"[[[[[[[[]"
"N"
 shift"]]]]]]]]["
"5"

GNU sed, 89 87 + 1(r flag) = 88 bytes
Because sed has no integer types or arithmetic operations, the solution is arrived at by using regular expressions only.
s:$:65432Nx1:
:
/6x/!s:^U(.*)(.)x:\1x\2:
s:^D(.*)x(.):\1\2x:
t
s:U|D::
t
s:.*(.)x.*:\1:

It works by sliding the pointer x based on each input shift, left (for Up) or right (for Down), along a non-wrapping tape that contains only the cells 65432N1. The answer at the end is the value in the cell left of the pointer.
Example run: or Try it online!
sed -rf gear.sed <<< "UUUUUUD"
5

Explanation:
s:$:65432Nx1:              # assign initial tape and pointer
:                          # start loop
/6x/!s:^U(.*)(.)x:\1x\2:   # if shift 'U', slide `x` to left, but not past the edge
s:^D(.*)x(.):\1\2x:        # if shift 'D', slide `x` to right, -||-
t                          # repeat
s:U|D::                    # if a shift couldn't be applied, delete it "manually",
t                          # and jump to the start of the loop again
s:.*(.)x.*:\1:             # print value left of pointer `x` (answer)

Here is 76 bytes, but it outputs in unary.

@Riley Unary, of course! Well, your solution is different, so why not post it!

Yours gave me the inspiration for it. I figured I'd let you use it if you wanted.

@Riley Then I'll make a separate section with your version and credit you.

I'll just post my own :)

GNU sed, 76  73 bytes
Includes +1 for -r
s/$/1/
:
/1{6}/!s/^U(.*)/\11/
s/^D(.*)1/\1/
t
s/U|D//
t
s/^1$/N/
s/^$/1/

Output is in unary except neutral, which is still N (see this consensus).
Try it online!
This basically counts up and down in unary then converts 1 to N and 0 to 1.
s/$/1/               # add 1 to the end (the starting value)
:                    # loop start
/1{6}/!s/^U(.*)/\11/ # If the string starts with 'U' and doesn't have 6 ones, increment
s/^D(.*)1/\1/        # If the string starts with 'D' decrement (but not past 0)
t                    # if something changed loop back
s/U|D//              # if the U or D couldn't be applied, remove it.
t                    # if something changed loop back
s/^1$/N/             # replace 1 with N
s/^$/1/              # if "0", replace with 1

Your sed version can be shorter by 4 bytes I think, if you work with 1 as the starting value, as N, and nothing as 1.  s/$/1/;:;/1{6}/!s/^U(.*)/\11/;s/^D(.*)1/\1/;t;s/U|D//;t;s/^1$/N/;s/^$/1/

><>, 35 bytes
An enthusiastic piece of code that encourages you to drive above the speed limit.
Accepts any two inputs whose code modulo 3 are 0 and 2, for example 0 and 2.
For extra fishiness, I recommend the use of < and >.
1i:0(?;3%1-+:0(?0:6)?6:1go!
1N23456

Explanation :
1i:0(?;3%1-+:0(?0:6)?6:1go!
1                             # initial position
 i                            # read the next char
  :0(?;                       # copies it, test copy against 0, if lower stops (EOF detection)
       3%1-                   # map the char to -1 or 1
           +                  # add it to the position
            :0(?0             # if the new position is lower than 0, set to 0
                 :6)?6        # if the new position is greater than 6, set to 6
                      :1go    # output a character from line 1 at the position
                          !   # loops and skip the position initialisation

You can try it here !

CJam, 24 22 bytes
"1N23456"1q{~0e>6e<}/=

Uses ( for down and ) for up.
Try it online!
Explanation
"1N23456"               e# Push the string containing all gears
         1              e# Push 1, the initial index
          q             e# Push the input
           {            e# For each character in the input
            ~           e#   Eval that character. ( is decrement and ) is increment.
             0e>        e#   Take the maximum of (0, index)
                6e<     e#   Take the minimum of (6, index)
                   }/   e# (end of block)
                     =  e# Take that index of the string

SpecBAS - 102
1 g=2: INPUT s$
2 FOR i=1 TO LEN s$
3 g+=(s$(i)="^" AND g<7)-(s$(i)="v" AND g>1)
4 NEXT i
5  ?"1N23456"(g)

Moves the index of the string depending on input and prints the relevant character.

Pyth, 32 bytes
J1VQ=JhtS[06+J-qNbqNd;?qJ1\N?JJ1

Uses space and newline for down and up.
Explanation
J1VQ=JhtS[06+J-qNbqNd;?qJ1\N?JJ1
J1                                 Initialize J to 1
  VQ                 ;             For each character in the input
            +J-qNbqNd              Increment or decrement J
      htS[06                       Get the middle sorted value of [0,6,J]
    =J                             Assign it to J
                      ?qJ1\N?JJ1   Change 1 to 'N' and 0 to 1

There's almost certainly a better way to do the incrementing and the output.

Batch, 144 bytes
@set/ps=
@set g=1
:l
@if %g% neq %s:~,1% set/ag+=%s:~,1%/3-1
@set s=%s:~1%
@if not "%s%"=="" goto l
@if %g%==1 (echo N)else cmd/cset/ag+!g

Takes input on STDIN, using 0 to go to a lower gear and 6 to go to a higher gear. These numbers were chosen to make it easy to ignore the current gear. Finally if the gear is 1 then N is printed otherwise 0 is converted to 1 and the gear is printed.

Javascript ES6 nonstrict, 136 120 chars
136 chars for V^
with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})f=s=>eval(s.replace(/(V)|./g,(m,v)=>`x${"-+"[+!v]}=1,`,y=1)+'"1N"[x]||x')

with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})
f=s=>eval(s.replace(/(V)|./g,(m,v)=>`x${"-+"[+!v]}=1,`,y=1)+'"1N"[x]||x')
console.log(f("V^^"))

120 chars for -+
with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})f=s=>eval(s.replace(/./g,m=>`x${m}=1,`,y=1)+'"1N"[x]||x')

with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})
f=s=>eval(s.replace(/./g,m=>`x${m}=1,`,y=1)+'"1N"[x]||x')
console.log(f("-++"))

Retina, 65 bytes
^
1 N23456
+(` (.)?(\w*6)u
$1 $2
)`(.)? (\w*6)d
 $1$2
.* (.).*
$1

Uses u and d for up and down.
Try it online!
Explanation
This program works by keeping 1N23456 behind the sequence of instructions. It keeps track of the current gear by having a space behind it. Then it takes one instruction at a time until there's no more.
^
1 N23456

Start by putting 1 N23456 before the input. The space before N indicates that N is the current gear.

+(` (.)?(\w*6)u
$1 $2
)`(.)? (\w*6)d
 $1$2

These are two replacement stages, grouped together, and run until they stop changing the string:
 (.)?(\w*6)u
$1 $2

The first one handles shifting the gear up. It will look for any number of gears after the space, followed by a 6, then followed by u (u indicates the instruction to gear shift up). If there were characters before the 6, it swaps the space with the character immediately after it, deletes the u, and leaves the rest of the string intact. Since the 6 is mandatory in the match, it will only swap the space with any character before the 6. It will never swap with the 6.
(.)? (\w*6)d
 $1$2

The second stage handles gear shifting down, and works similarly. It looks optionally for a character before the space, then some other gears after ending in 6, followed by d. It swaps the space with the character before it, deletes the d, and leaves the rest intact. If the space was at the start of the string, there was no match for a character before the space, so no swap occurs.

.* (.).*
$1

After neither of the above replacements can be done anymore, all gear shifts have been completed. The line is cleared of everything except the gear immediately after the space. This is the final gear.

Python 3, 67 63 bytes
k=1
for i in input():k+=[k<6,-(k>0)][i<'1']
print('1N23456'[k])

Pretty straightforward solution.
-4 bytes thanks to @ovs!

Perl 6, 144 bytes
my enum C <1 N 2 3 4 5 6>;my $n=prompt("");my $p=1;for split("",$n) ->$l {$l eq "u" && $p < 6 ?? ++$p !! 0;$l eq"d"&&$p>0 ?? --$p!!0};say C($p);

Works as it should, i believe. Improvements are welcome. First time using Perl for anything, but i loved the thought of the language, so i had to try.

Clojure, 74 bytes
#((vec "1N23456")(reduce(fn[c s](max 0(min 6((if(= s \^)inc dec)c))))1 %))

Folds over the shift string, maintaining an index as the accumulator. Each iteration it either increases or decreases the index, then clamps it to the range 0-6. Finally, a string holding the gears is indexed and returned.
Returns a Clojure character representing the current gear. Gear 1 is returned as \1, and gear 'N' is returned as \N.
Pre-golfed explanation. Follow the numbers, since it doesn't read well top-down.
; Expects ^ for shift-up, and V (or anything else) for shift down
; Returns a character representing the current gear
(defn shift [shift-str]
  ((vec "1N23456") ; 4. Then index the gear list with the calculated index, and return
   (reduce (fn [current-gear s] ; 1. Fold over the shift symbols
             (max 0 (min 6 ; 3. Clamp it to the range 0-6 so we don't overflow
                      ((if (= s \^) inc dec) ; 2. If the shift is up, increase, else decrease
                       current-gear))))
           1
           shift-str)))

Powershell, 112 87 85 bytes
$i=1;switch([char[]]$args[0]){'^'{if(5-gt$i){$i++}}'v'{if(1-le$i){$i--}}}'1N2345'[$i]
ungolfed
$i=1;                                # index which gear we are in
switch([char[]]$args[0]){            # loop over all elements using a switch
  '^'{if(5-gt$i){$i++}}             # if there is a ^ and we are not in sixth yet, shift up
  'v'{if(1-le$i){$i--}}             # if there is a v and we are not in first, shift down
}
'1N2345'[$i]                         # print the output

saved 25 bytes by reading the powershell codegolf tips
saved 2 bytes by flipping the gt/le operators


text:
Give everyone T-Shirts
You're in charge of distributing T-Shirts to everyone. Simple enough, right? But remember, there are different sizes of T-Shirts, and you have to keep that in mind...
Challenge Specifications
There are N T-Shirt sizes. There are K people. Each person may wear any T-Shirt that is larger than them, but they can only wear a T-Shirt that is D sizes down. You want to figure out what the optimal configuration is, based on the cost of the system. It is guaranteed that everyone will be able to get a T-Shirt, so you must give everyone a T-Shirt.
The cost is calculated as such:
Start from 0 and add up.
For every person who receives a T-Shirt, add |S1 - S2|, where the person is size S1 and they are receiving a T-Shirt of size S2.
Input Specifications
The input starts with the integers N, K, and D. You can choose to not input N or K if you want. These can be given in an array, one on each line, space separated, or pretty much anything you want, but they must be given in this order. You must specify how you want input.
Then, the next part of the input is N integers representing how many T-Shirts of each size there are. For example, with N := 3, [1, 4, 2] means that there is 1 size 1 T-Shirt, 4 size 2 T-Shirts, and 2 size 3 T-Shirt. It is guaranteed that the sum of these numbers equals K. This can be taken as an array, an array contained at the end of the first part of input, an array joined to the end of the first part of the input, one on each line, space separated, or some other one that does not put you at a clear advantage. Again, please specify how you want input.
Then, the next part of the input is K integers representing the individual size of each person. This order matters. This can be taken as an array, an array contained at the end of the first part of the input, etc.
You can also choose to start with size-0.
Output Specifications
Output must consist of K + 1 integers. The first K of these represents the size of T-Shirt given to each person, and the last integer is the overall cost. This can be outputted as an array, space-separated integers, one on each line, etc.
Test Cases
Input:
3 10 1
3 5 2
1 1 1 2 2 2 2 2 3 3

Output:
1 1 1 2 2 2 2 2 3 3 0

Explanation:
This one's an easy case; each person gets the size of T-Shirt matching them, so the overall cost is 0.
Input:
2 10 0
5 5
1 1 1 1 1 1 2 2 2 2

Output:
1 1 1 1 1 2 2 2 2 2 1 # Or 2 1 1 1 1 1 2 2 2 2, or similar outputs

Explanation:
There are 5 size-1 shirts, which are given to 5 of 6 size-1 people. There are 5 size-2 shirts, 4 of which are given to the 4 size-2 people. There is one more size-1 person and one more size-2 shirt, so this assignment is made at a cost of 1.
Input:
7 20 2
5 0 5 0 5 0 5
3 5 7 9 3 5 7 9 3 5 7 9 3 5 7 9 3 5 7 9

Output:
1 3 5 7 1 3 5 7 1 3 5 7 1 3 5 7 1 3 5 7 40

Explanation:
At first glance, it may make sense to assign everyone the size of T-Shirt they need. However, then we get 5 size-9 people and 5 size-1 T-Shirts, and people can only wear shirts down 2 sizes, so we assign everyone a T-Shirt 2 sizes down, at a cost of 40.
This test case is also in place to address the possible confusion that you can output the shirt sizes sorted. This is not always the case, as shown in this test case.
This is a code-golf challenge, so the shortest valid submission by March 14th (Pi Day) wins!

Can we assume that we always are able to give everyone a shirt?

It is guaranteed that everyone will be able to get a T-Shirt, so you must give everyone a T-Shirt. Yes.

Do we have to take the N and K parameters, even though they're just the lengths of the lines/arrays that follow? It may be necessary in a language like C in order to know how many elements to read from each array, but in languages where the sizes of arrays are known it's kinda awkward and redundant.

@smls I guess, you can choose to omit them. Since there are no answers yet, I'll change that in the specs. Thanks for pointing that out.

Is the last array (size of each person) always sorted in ascending order? If so, is there any case where simply outputting the sorted list of available T-Shirts isn't the correct answer?

@smls They're meant to be put in the same order as the people in the input. It is incorrect to output the sorted list if the people aren't sorted in ascending order. I'll add a test case later to clarify that.

k, 47 44 35 25 bytes
Stealing from the Perl6 solution, it matches the smallest shirt to the smallest person it can.
It turns out, D is also unnecessary! This takes advantage of that. It takes in two lists as arguments.
{x,+/%y*y:y-x:(1+&x)@<<y}

Try it online!
Try it in oK.
Explanation:
{                       } /function(x,y)
                     <<y  /grade up the grade up of the people
                          /  returns indices needed to rearrange a list of shirts
              (1+&x)      /expand the list into a list of shirts
            x:      @     /x = rearrange shirts by said indices
          y-              /S1 - S2
     %y*y:                /absolute value
   +/                     /total to get the score
 x,                       /prepend the list of rearranged shirts

Can you provide a link to an online test suite? I cannot get it to work. Thanks!

Unfortunately, it does not work in a publicly available interpreter (unless you send the creator an email and ask for a copy of the interpreter). However, I'm working on a shorter variant that does work in oK and it's almost finished!

Alright. That's good! I tried testing it with the available interpreter, but unfortunately it doesn't work, so I'm looking forward to seeing your improved version!

@AlexL. The newer version is up along with links to interpreters.

This appears to work for all test cases and some edge cases. Good job!

Does it not work for some edge cases?

Let us continue this discussion in chat.

Perl 6, 77 bytes
->$,\t,\p{flat(1..*Zxx t)[[p].&{@(.sort)=0..*;$_}].&{|$_,(p Z-$_)».abs.sum}}

Try it online!
Simply matches the n'th smallest T-Shirt to the person with the n'th smallest size.
I'm not absolutely sure if that is guaranteed to give the correct result for all possible inputs, but it works for the test-cases given in the task description.

Perl 6, 97 bytes
->\d,\t,\p{flat(1..*Zxx t).permutations.map({|$_,(p Z-$_)».&{$_>d??∞!!.abs}.sum}).min(*[*-1])}

Try it online!
Dumb brute-force solutions.
Takes around 15 minutes for the test-cases with 10 people, so the test-case with 20 people should only take, uh, millions of years... :D
(Memory usage should remain steady though, because permutations and map return lazy one-off sequences, and min also only needs to keep one element in memory.)

Both versions take three input arguments:

The number D.
The array for the T-Shirts.
The array for the people.

Can you provide a link to an online tester? Thanks.

@AlexL.: Added.

This appears to work for all test cases and a few additional edge cases I came up with. Good job!

Python 2, 121 119 115 106 bytes
def f(a,b):
 j=h=0
 for i in a:j+=1;exec"q=b.index(min(b));h+=abs(j-b[q]);b[q]=`j`;"*i
 print map(int,b),h

Try it Online!
Takes both lists, without N, K or D. Outputs a list of sizes, followed by the cost
Edit: I found a cool trick using exec that took off 9 bytes!

I thought D was necessary to allow people to wear smaller shirts, because there's always the possibility that the input is simply invalid...

@zgrep It is guaranteed that everyone will be able to get a T-Shirt, so you must give everyone a T-Shirt

@zgrep Yeah... I overlooked that this specification made D unnecessary, so a lot of of people exploited that... :D

Good job, this works for all cases I provided and some edge cases! +1!


text:
Mod the Floats!
3D-modeling software mainly uses UV Mapping to map textures onto a 3D object. The valid values for both U and V are usually located in an inclusive [0..1] range.
Challenge
You bought a new 3D-modeling software which is super-easy to use. However there is one issue with it: it adds or subtracts a random integer number from UV values. Your task is to create a program or a function that modifies an input value to get a float value in an inclusive [0..1] range.
The resulting float should have the same fractional part as the original, and be as close to the original as possible. Because both 0 and 1 are in the output range, any integers 0 or less should change to 0, and any integers 1 or greater should change to 1.
An example algorithm in JavaScript:
function modFloat(input) {
    while (input < 0 || input > 1) {
        if (input < 0) input += 1;
        if (input > 1) input -= 1;
    }
    return input;
}

Rules

Input is a single integer or float value. Any reasonable format is allowed as long as it is specified in your answer.
The output should be a decimal representation of a float value.
The output precision should be at least same decimal places as input.
Trailing zeros are allowed.
Be sure your code correctly chooses which of 0 or 1 to output for integer inputs.

Test cases
Input       | Output
------------+---------
         -4 | 0
         -1 | 0
          0 | 0
          1 | 1
          2 | 1
     1.0001 | 0.000100
 678.123456 | 0.123456
-678.123456 | 0.876544
        4.5 | 0.5

This is code-golf, so the shortest code in bytes wins!

Welcome to PPCG, nice first question

Do you intend for 1 to map to 1? Usually a half-open range is used. Based on your pseudocode, should I understand all integers >1 go to 1, and all integers <0 go to 0>

All %1 solutions fail if input is 1!

Actually, I like the 1->1 thing, it keeps the problem from being a trivial built-in for many languages.

they also fail for negative numbers

What is the largest size of number?

Can you confirm if the intent is that all numbers go to the closest equivalent value in [0,1] as your example code does? This would mean that positive integers go to 1 and non-positive integers go to 0.

@xnor 0 and 1 stand for texture edges, thus it is intended mapping.

@lolbas I'm going to edit the wording to make the clearer, as some people missed it at first

@xnor thanks in advance :)

What is the output when the input is 10 or -10?

@ChristopherPeart the largest size of number is whatever your language is fine to work with.

For any integer valid output can be either 0 or 1, since the random number could have been either of two adjacent integers.

@KritixiLithos 1 and 0 respectively.

Can I use sed for this? There are no data types in sed, the input would have to be a text stream.

@seshoumara any reasonable input format is allowed, so I'd say "Why not?".

Jelly, 6 bytes
%1o>0$

Try it online!
Jelly has no True or False, but uses 1 and 0 in their place.
%1o>0$ - Main link: float v
%1     - v mod 1
     $ - last two links as a monad
   >0  -     v greater than zero?
  o    - or - replace the 0 result of the mod with 1 when v is greater than 0.

Python, 20 bytes
lambda x:x%1or+(x>0)

Try it online!
Takes the input modulo 1, then handles the boundary case by converting outputs of 0 to 1 for positive inputs. A bool output would save two bytes.
lambda x:x%1or x>0

I think 1or is breaking the syntax highlighter. (I assume it's interpreted as 1 or)

@12Me21 Yes, and I haven't seen any highlighter that handles it correctly.

Mine does :) http://12Me21.github.io/syntax/link#1or

Brachylog, 14 11 bytes
Thanks to Fatalize for golfing 3 bytes.
∧≜:?+.≥0∧1≥

For a change, this answer doesn't use mod :)
Try it online!
Explanation
∧≜                Label an integer variable. This will start trying different
                  values for this variable, the ones closest to 0 first.
   :?+.           This variable summed to the input is equal to the output
      .≥0∧1≥      which is >= 0 and <= 1

This output 0 for positive integers when I tried it online.

@Neil corrected, thank you. I don't know why I missed it

You can save 3 bytes as such: ∧≜:?+.≥0∧1≥.

JavaScript (ES6), 19 bytes
n=>(n%1+1)%1||n>0|0

In JavaScript, n%x returns a negative number if n is negative, meaning that if we want to get the positive residue, we must add x if n is negative. (n%x+x)%x covers all cases:
n     n%1   n%1+1 (n%1+1)%1
0     0     1     0
1     0     1     0
2.4   0.4   1.4   0.4
-1    0     1     0
-2.4  -0.4  0.6   0.6

Another working solution at 20 bytes, which shows a bit more of a pattern:
n=>n%1+(n%1?n<0:n>0)

MATL, 9 bytes
1&\0>yg>+

Try it online! Or verify all test cases.
Explanation
Example with input 678.123456
1      % Push 1
       % STACK: 1
&\     % Implicit input. Divmod with 1
       % STACK: 0.123456, 678
0>     % Is it positive?
       % STACK: 0.123456, 1
y      % Duplicate from below
       % STACK: 0.123456, 1, 0.123456
g      % Convert to logical: nonzero becomes 1
       % STACK: 0.123456, 1, 1
>      % Greater than? This is true if fractional part of input was zero
       % and non-fractional part was positive
       % STACK: 0.123456, 0
+      % Add. Implicitly display
       % STACK: 0.123456

Javascript, 28 bytes
m=f=>f<0?m(f+1):f>1?m(f-1):f

Recursively decreases/increases the values by 1 until the result is in [0,1]

Welcome to PPCG, and nice answer!

Japt, 8 bytes
u1 ªUbV1

Test it online!
I think this is the first time I've ever used b...
Explanation
 u1 ªUbV1  // Implicit: U = input, V = 0
Uu1        // Take U%1, but add 1 if U is negative. This is equivalent to %1 in Python.
    ª      // If the result is falsy (0), instead take
     UbV1  //   U bound between 0 and 1.
           // This converts positive integers to 1, zero/negative integers to 0.
           // Implicit: output result of last expression

Mathematica, 20 bytes
#~Mod~1/. 0/;#>0->1&

Explanation
This is a rather unusual use of /; where I'm using it more like an && because the condition after it has nothing to do with the pattern it matches.
#~Mod~1...

Compute x % 1, which is correct for all cases except positive integers.
.../. 0/;...

Replace zeros in the previous expression if...
...#>0...

...the input is positive...
...->1...

with 1.

C 57 56 73 bytes
b;f(float n){b=n;printf("%f",((!(n-b)&&n<=0)?0:n<0?1.+n-b:(n-b)?n-b:1));}

@pinkfloydx33 Thanks for pointing out!

Ungolfed version:
f(float n)
{
  int b=n;
  printf("%f",( (!(n-b)&&n<=0)?0:n<0?1.+n-b:(n-b)?n-b:1) );
}

Try it online!

Can you do 1. instead of 1.0?

@KritixiLithos  I am not familiar with that notation but it seemed to work.

Must you call everything f? Also I don't think the parenthesis in (f<0) is necessary.

That can be simplified I think to not replicate the subtraction. But either way it doesn't work for f(1) (which should return 1)

@pinkfloydx33 thanks so much for pointing it out, that code was far from done.:) Fixed it, should run fine now!

49 bytes

PHP, 37 bytes
<?=($m=fmod($argn,1))+(!!$m^$argn>0);

Run with echo <number> | php -R '<code>'.
There are so many ways to do this ... this should be one of the shortest in PHP.
The fmod result is negative for negative floats and 0 for positive integers; those need adjustment: !!$m is true for floats, xoring with $n>0 results in false for positive float and negative int, true for negative float and positive int; + casts that to 1 or 0 - done.

SmileBASIC, 28 bytes
INPUT N?N-FLOOR(N)+(N<<0==N)

JavaScript (ES6), 19 bytes
n=>(n>0==!(n%=1))+n

Explanation: %1 doesn't give the correct results in all cases:
input       %1          output
-ve int     -0
-ve frac    -ve frac    +ve frac
0           0
+ve frac    +ve frac
+ve int     0           1

An extra 1 needs to be added in the cases that are wrong, which are those of a negative non-integer and a positive integer. This is what the expression (n>0==!(n%1)) calculates.

There are several other arrangements of this, but I haven't yet found one that's shorter...

><>, 26 bytes
:1%:?vr1(?v1n;
     >n;n0<

Try it online!
Because solutions in good golfing languages are almost always pretty instantly given, I decided to mix things up. First <>< answer!
Explanation
:1%:?vr1(?v1n;    Assume input i in stack
     >n;n0<

:                 Duplicate i (need it if i%1 != 0)
 1                Push 1
  %               Pop i and 1, push i%1
   :              Duplicate top of stack because  we need one for the if
    ?v            If i%1 != 0 ------------------------,
      r           Reverse stack so that i is TOS      |
       1(?v       If i > 0 (not < 1)                  |
           1n;      Print 1 and Exit                  |
                  Else                                |
        n0<         Print 0 and --,                   |
     >n           Print n <-------|-------------------'
       ;          Exit <----------'

Fun fact: the explanation is a valid <>< program!

Javascript, 41 28 bytes
n=>n-Math.floor(n)+(n<<0==n)

Math.floor() is so long...

n|0 is shorter than Math.floor (I think it works)

|0 is different than floor() for negative numbers.

Pyth, 7 bytes
|%Q1s<0

Explanation
|%Q1s<0
|%Q1s<0Q      Implicitly add input
 %Q1          Input mod 1
|             Short-circuting or
    s<0Q      1 if input is positive, 0 otherwise

If you don't mind using True and False as 1 and 0, you can drop the s for 6 bytes.

Perl 6, 15 bytes
{+($_%1||$_>0)}

Try it online!
Inspired by seshoumara's comment that mod 1 almost works.
EDIT: Ha, xnor's Python solution beat me to it.


text:
Anagram Quines (Cops' Thread)
This is a cops-and-robbers challenge the Robbers' Thread can be found here
Your challenge is to write a program that outputs an anagram of its source code but not the original source code itself.
For example the following Python program,
print`'print*2``'*2`

prints
'print*2``print*2``'

which has all of the same characters as its original source but in a different order.
Once you have found such a program, include the output of the program as an answer omitting the program that generates it.  As you might have guessed, robbers will seek to discover the program you have hidden, or any program that fits the specifications.  Your goal is to make the shortest program that the robbers cannot crack.
Rules

As with most cops-and-robbers challenges, if your answer remains uncracked for a week you may add the intended solution to your answer and mark it as Safe.  Once safe an answer cannot be cracked by robbers.

You do not need to include the language of the intended solution, however if you do not include the language robbers can crack it in any language predating the challenge, while if you specify the language they may only crack it in the one provided.

Standard rules for Quines apply.

My usual question: in a language where bytes don't correspond to characters, is the anagram at the byte or character level?

@ais523 it should be an anagram of the bytes.

Closely related

Do usual quine rules apply to robbers? Do they apply to cops?

@Dennis Yes. (I suppose an empty program wouldn't be bad but lets just say yes)

I suppose introducing randomness isn't allowed?

@Fatalize If it does not change the output it is fine but the output must be static.

If the program contains newline characters, does the output need to include those newlines?

Brain-Flak, 231 bytes Cracked by Wheat Wizard
}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{][][][][][][][)()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(

The original program uses the -A argument.
Here are the counts:
( -> 74
) -> 74
{ -> 34
} -> 34
[ -> 7
] -> 7

Cracked!

Python 2, 96 bytes, cracked by math_junkie
Output:
B97.off]xo) wnd[ri0'of{r1({r6-{r{rri) {r1(xo0'sjD;0'0'qhF=1({r{r2)4+}twnri2)wnlcof) yp) ) xomd2)

First time code golfing! Hope it's not too easy.

I have a miserable print(''),  chr() + '' so far

Cracked!

Unspecified langauge, 124 bytes,
In the theme of DJMcMayhem's answer this is the first 32 ASCII characters (aside from 0x00) printed four times each. Since none of these are visible, I have not included the actual code in my answer.
Here is the hexdump:
00000000: 0101 0101 0202 0202 0303 0303 0404 0404  ................
00000010: 0505 0505 0606 0606 0707 0707 0808 0808  ................
00000020: 0909 0909 0a0a 0a0a 0b0b 0b0b 0c0c 0c0c  ................
00000030: 0d0d 0d0d 0e0e 0e0e 0f0f 0f0f 1010 1010  ................
00000040: 1111 1111 1212 1212 1313 1313 1414 1414  ................
00000050: 1515 1515 1616 1616 1717 1717 1818 1818  ................
00000060: 1919 1919 1a1a 1a1a 1b1b 1b1b 1c1c 1c1c  ................
00000070: 1d1d 1d1d 1e1e 1e1e 1f1f 1f1f            ............

Here however is some Python that prints it (and a newline) if you would like:
print"".join(chr(x)*4for x in range(1,32))

V, 21 bytes (Safe!)

"&./124ipq|ÍÓÚîñòÿ

Note the leading newline.
Since this contains unprintables, here is a hexdump:
00000000: 0a16 1b22 262e 2f31 3234 6970 717c cdd3  ..."&./124ipq|..
00000010: daee f1f2 ff                             .....

To help people out some, here is a link to the Standard extensible V quine

Here is the original version:
ñi241"qp|Ó./ò&
ÚÍîÿ

Try it online!
The readable version is:
ñi<C-v>241<esc>"qp|Ó./ò&
ÚÍîÿ

The way this works is by embedding sort into the default extensible quine. As I was thinking about V-quines because of this answer, I realized that the standard extensible quine can be shortedn by three bytes, so this solution could have been:
ñiéÑ~"qp|Ó./ò&
ÚÍîÿ

Explanation:
ñi<C-v>241<esc>"qp  " Standard V-quine. Everything after this is recorded into register 'q'
                    " so we can do whatever we want without ruining it's "quine-ness"

|       " Go the first character on the line (I just realized now that this is pointless)
 Ó./ò&  " Put every character on a newline
Ú       " Sort every line
 Íî     " Join all lines together
   ÿ    " Necessary for V-quines

sniff I smell fresh regex

Pyth, 32 bytes, Cracked by math_junkie
J+J=JJ 1-2#pTN%"J+J=JJ 1-2#pTN%"

Original solution
J2#p+"J+J=JJ 1-2#pTN%"N=J-J1 %TJ

Try it online!
J2                               # Assign 2 to the variable J
  #                              # Infinite loop, break on error
    +"J+J=JJ 1-2#pTN%"N          # appending a '"' to the string 'J+J=JJ 1-2#pTN%'
   p                             # print the string above
                       =J-J1     # subtract 1 from J and assign back to J
                             %TJ # calculated 10%J, with a blank space before to supress output,
                                 # on the 3rd iteration this will be 10%0 that will generate an
                                 # erro and will break out the loop

Cracked!

CJam, 46 bytes, cracked by math_junkie
3658:93]93]]]95_959599c101101$::]]]]]]____ccee

Cracked!

Haskell, 107 bytes, Cracked by nimi
"$$$$'''''''',,----....::<<<<<<<<========>>>>[[[[[[[[]]]]]]]]aaddddddddddddiiiiiiiiiiiimmnnnnpprrtt||||||"

There is an additional trailing newline.

Original solution:

main=print$id=<<[[id|i<-"main=print$id=<<[[id|i<-,i==d]>>d:[d]|d<-['$'..'|']]",i==d]>>d:[d]|d<-['$'..'|']]

Try it online!
My main idea was to write a quine which sorts its own source code before outputting it without using a library sort function. Only after an initial cracking try by nimi it occurred to me that the program code could be manually sorted, hard coded into the program and then printed out while doubling each letter. However the limited available characters make this approach more cumbersome and nimi's successful crack is quite similar to my original program.
Explanation:
main=print$                                      -- full program which prints the following string
  id=<<[[id|i<-"...",i==d]>>d:[d]|d<-['$'..'|']]
                                 |d<-['$'..'|']  -- for each char d in "$%&'()*+,-./012 ... xyz{|"
        [id|i<-"...",i==d]                       -- build a list with as many elements as d is contained in the string
                          >>d:[d]                -- replicate the string "dd" as often as the previous list is long
  id=<<[                                       ] -- concatenate the resulting list of srings to one single string

@nimi Yes it's a full program. Isn't this a standard rule for quines?

Not sure. We had quines before that allowed functions. And even if full programs are standard,  the "program" in the challenge could be interpreted as overwriting the defaults and also allow functions.

@nimi I'm sorry the previous version was misleading. I had written it after having seen your first attempt and before noticing it wasn't valid according to the specs. I even published it and then quickly rolled back in the hope that nobody saw it, as you can see in the revision history. After seeing your fixed version, I rolled back to this version, without considering that description wasn't fitting any more.

I was not sure if you were referring to my answer that's why I deleted my comment. It is indeed possible to use a presorted string (replace ; with a NL): i[]d=[d,d];main=print$i[]=<<"$$  ... |||"-- and all the missing characters after the --. I found this version after my answer from the robbers thread and after you revealed your answer with the now changed explanation.

Unspecified language, 254 bytes Cracked by @Dennis!
I doubt this will win for brevity, but it'll be a pain to crack, so it's still worth making.
Due to a bug, the order of 0x0b, 0x0c, 0x0a got a little bit mixed up, but this is definitely the real output.
I figured I wouldn't specify the language just so I could see what different languages this is possible in. Since the output is mostly non-ASCII, here is a hexdump of the output:
00000000: 0102 0304 0506 0708 090b 0c0a 0e0f 1011  ................
00000010: 1213 1415 1617 1819 1a1b 1c1d 1e1f 2021  .............. !
00000020: 2223 2425 2627 2829 2a2b 2c2d 2e2f 3031  "#$%&'()*+,-./01
00000030: 3233 3435 3637 3839 3a3b 3c3d 3e3f 4041  23456789:;<=>?@A
00000040: 4243 4445 4647 4849 4a4b 4c4d 4e4f 5051  BCDEFGHIJKLMNOPQ
00000050: 5253 5455 5657 5859 5a5b 5c5d 5e5f 6061  RSTUVWXYZ[\]^_`a
00000060: 6263 6465 6667 6869 6a6b 6c6d 6e6f 7071  bcdefghijklmnopq
00000070: 7273 7475 7677 7879 7a7b 7c7d 7e7f 8081  rstuvwxyz{|}~...
00000080: 8283 8485 8687 8889 8a8b 8c8d 8e8f 9091  ................
00000090: 9293 9495 9697 9899 9a9b 9c9d 9e9f a0a1  ................
000000a0: a2a3 a4a5 a6a7 a8a9 aaab acad aeaf b0b1  ................
000000b0: b2b3 b4b5 b6b7 b8b9 babb bcbd bebf c0c1  ................
000000c0: c2c3 c4c5 c6c7 c8c9 cacb cccd cecf d0d1  ................
000000d0: d2d3 d4d5 d6d7 d8d9 dadb dcdd dedf e0e1  ................
000000e0: e2e3 e4e5 e6e7 e8e9 eaeb eced eeef f0f1  ................
000000f0: f2f3 f4f5 f6f7 f8f9 fafb fcfd feff       ..............

That is every single ASCII character except for 0x00 and 0x0D because they both caused strange behavior on TIO. Have fun cracking! >:D

The original code was in V.
Try it online
Hexdump:
00000000: ee02 0304 0506 0708 090b 0c0e 0f10 1112  ................
00000010: 1314 1516 1718 191a 1b1c 1d1e 1f20 2122  ............. !"
00000020: 2324 2526 2728 292a 2b2c 2d2e 2f30 3132  #$%&'()*+,-./012
00000030: 3334 3536 3738 393a 3b3c 3d3e 3f40 4142  3456789:;<=>?@AB
00000040: 4344 4546 4748 494a 4b4c 4d4e 4f50 5152  CDEFGHIJKLMNOPQR
00000050: 5455 5657 5859 5a5b 5c5d 5e5f 6061 6263  TUVWXYZ[\]^_`abc
00000060: 6465 6667 6869 6a6b 6c6d 6e6f 7071 7273  defghijklmnopqrs
00000070: 7475 7677 7879 7a7b 7c7d 7e7f 8081 8283  tuvwxyz{|}~.....
00000080: 8485 8687 8889 8a8b 8c8d 8e8f 9091 9293  ................
00000090: 9495 9697 9899 9a9b 9c9d 9e9f a0a1 a2a3  ................
000000a0: a4a5 a6a7 a8a9 aaab adae afb0 b1b2 b3b4  ................
000000b0: b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2 c3c4  ................
000000c0: c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2 d3d4  ................
000000d0: d5d6 d7d8 d9da dbdc ddde dfe0 e1e2 e3e4  ................
000000e0: e5e6 e7e8 e9ea ebec edef f0f1 f2f3 f4f5  ................
000000f0: f6f7 f8f9 fafb fcfd feff 0a53 ac01       ...........S..

Basically, everything up to the S just inserts garbage into the buffer. The 0xEE at the beginning is just to insure that everything after the newline doesn't happen in part of a loop or macro. Then, we do
¬<C-a>   "Insert every character in the range 0x01-0xFF

Cracked.

Octave, 91 bytes
a=['111111111123666667eeegggkkknnszEEGn};:;:'];
''''''''''(),,,,,-[[[]]]aaaddip;;=ds1010]);

Cracked!

Not quite... you get an extra '' at the end of the output

Should be good now

This is it. Well done!

PHP, 130 Bytes (Safe)
    $$$$$$''''(((((((()))))))),,22;;;;;;<<==??\\\\____aaccddeeeeeeeehhhhiiiillllmmoooooopppppppppprrrrrrrrssssssssttttttttttvvvvvv

Original Solution
I could not understand that it was not cracked
<?php $v=str_split(str_repeat('<?php\ $v=str_split(str_repeat(\'\',2));sort($v);echo\ implode($v);',2));sort($v);echo implode($v);

Guess, 43 bytes
{4"2)4q):)u(4o'{4t:q(e)(",(t22(u()o)?,?'2e

It was a tough call whether or not to share what language it was, but I think this option is better. Note that there's a trailing newline.

An answer is only safe if you add the intended solution to the answer. Until then, this answer is not safe.