text:
Quixels - Quantum Pixels
Introduction
A quixel is a quantum pixel. Similar to a classical pixel, it is represented with 3 integer values (Red, Green, Blue). However, quixels are in a super position of these 3 states instead of a combination. This super position only lasts until the quixel is observed at which point it collapses to one of three classical pixels; RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255).
Specification

Representation

Each quixel is represented as an array of 3 integers between 0 and 255, r, g and b respectively.

Super Positions

Each quixel is in a super position between the Red, Blue and Green states represented by R, G and B respectively.

Observation

When each quixel is observed it collapses into one of the three states. The probability of each classical state is R = (r + 1) / (r + g + b +3), G = (g + 1) / (r + g + b + 3) and B = (b + 1) / (r + g + b + 3). This way each classical state always as a non-zero probability of showing up.

Input

The function or program should take a image of quixels. How it does this is flexible. A filename, using a multi-dimensional array, etc are all acceptable.

Output

The function or program should produce an image of classical pixels. The data structure for this produced image is also flexible. Note that all of the pixels should be one of these three: RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255)
The output should not be deterministic; these are quantum pixels! The same input should result in different outputs.
If your language has no way of generating a random number, you can take random bytes as input

Scoring

This is code-golf so fewest bytes win.

Images
Mona Lisa by Leonardo da Vinci

Starry Night by Vincent van Gogh

Persistence of Memory by Salvador Dali

Teddy Roosevelt VS. Bigfoot by SharpWriter

Can the image filename / URL be an input argument?

@LuisMendo Yes, you can read from a file (or URL)

My question is, can the name of that file / URL be an input? As opposed to hard-coded. So it wouldn't be included in the byte count

@LuisMendo Sorry. Yes, that is what I meant

That JPEG image of the Mona Lisa is causing 16x16 prominent visual artefacts on the output images.

Where the hell is Lena when you need her?

@wizzwizz4 Actually it isn't. It is the downsized preview that has artefacts. Click an image to view it full-sized. I suspect it is the particular width of only that image that gives the effect.

@Adám Oh, my bad. Thanks for correcting me.

You'll get better (visual) results if your quantum space was RGBK, where K=255*3-R-G-B, then make your quantum pixels be any one of the 4.  (If K is selected, display (0,0,0).  Extend your RGB equations in the obvious way, changing 3s to 4s, adding K when you would add R+G+B, etc).  A blur after doing this should reconstruct a pretty decent noisy copy of the original.  (K stands for black or key, in case you wondered)

If using a deterministic language (i.e. output = func(input)), is is alright if the input consists of the image followed by an infinite stream of random bytes? Some esolangs don't have a built-in RNG. Or are deterministic languages not allowed?

@TLW If your language has no way of generating a random number, you can take random bytes as input

@Yakk Have you tried it? Pure red (255,0,0) would give K=2×255, so a pure red picture would become two thirds black pixels and one third red. I.e. it would become very much darker.

@Adám You are right.  The proper K is harder to calculate. Treating channels as values from 0 to 1 and ignoring the "+1 per channel" in the quantum equation as tiny, the average total pixel value ("brightness") after is (R^2 + B^2 + G^2)/(R+G+B), while before it was (R+G+B).  To repair this we need to dim it by a factor of (R+G+B) / ( (R^2 + B^2 + G^2)/(R+G+B) ) = (R+G+B)^2/(R^2 + B^2 + G^2).  Then scale that by (R+G+B).  Sigh.

Dyalog APL, 23 21 19 bytes
Takes table of (R, G, B) triplets.
Inspired by miles' algorithm
Returns table of indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}. Horribly wasteful.
(?∘≢⊃⊢)¨(⊂⍳3)/¨⍨1+⊢

(
 ?∘≢ random index
 ⊃ selects
 ⊢ from
)¨ each of
(
 ⊂ the entire
 ⍳3 first three indices
)/¨⍨ replicated by each of
1+⊢ the incremented triplets
TryAPL!

Old version
Returns table of 0-based indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}
{+/(?0)≥+\(1+⍵)÷3++/⍵}¨

{...}¨ for each quixel in the table, find the:
 +/ the sum of (i.e. count of truths of)
 (?0)≥ a random 0 < number < 1 being greater than or equal to
 +\ the cumulative sum of
 (1+⍵)÷ the incremented RGB values divided by
 3+ three plus
 +/⍵ the sum of the quixel
Note: Dyalog APL lets you chose between the Lehmer linear congruential generator, the Mersenne Twister, and the Operating System's RNG¹ ².
For example, the image:
┌──────────┬──────────┬───────────┬───────────┬─────────┐
│52 241 198│148 111 45│197 165 180│9 137 120  │46 62 75 │
├──────────┼──────────┼───────────┼───────────┼─────────┤
│81 218 104│0 0 255   │0 255 0    │181 202 116│122 89 76│
├──────────┼──────────┼───────────┼───────────┼─────────┤
│181 61 34 │84 7 27   │233 220 249│39 184 160 │255 0 0  │
└──────────┴──────────┴───────────┴───────────┴─────────┘

can give
┌─┬─┬─┬─┬─┐
│1│0│2│2│1│
├─┼─┼─┼─┼─┤
│2│2│1│1│2│
├─┼─┼─┼─┼─┤
│0│2│1│2│0│
└─┴─┴─┴─┴─┘

Notice how the three "pure" quixels collapsed to their respective colors.
TryAPL online!

Mathematica, 53 bytes
RandomChoice[255#+1->IdentityMatrix@3]&~ImageApply~#&

Anonymous function. Takes a Mathematica Image as input and returns an Image as output. Note that the input image must have an RGB color space.

How does it work?

@GreenAsJade <...>~ImageApply~# applies a function over all pixels in the image, and RandomChoice[255#+1->IdentityMatrix@3] uses some weighted RNG to produce a row of the 3×3 identity matrix (i.e. {1, 0, 0}, {0, 1, 0}, or {0, 0, 1}) which corresponds to red, green, or blue.

C#, 366 243 bytes
Huge thanks to @TheLethalCoder for golfing this!
var r=new Random();c=>{double t=c.R+c.G+c.B+3,x=(c.R+1)/t,d=r.NextDouble();return d<=x?Color.Red:d<=x+(c.G+1)/t?Color.Lime:Color.Blue;};b=>{for(int x=0,y;x<b.Width;x++)for(y=0;y<b.Height;y++)b.SetPixel(x,y,g(b.GetPixel(x,y)));return b;};

Basic idea:
using System;
using System.Drawing;
static Random r = new Random();

static Image f(Bitmap a) {
    for (int x = 0; x < a.Width; x++) {
        for (int y = 0; y < a.Height; y++) {
            a.SetPixel(x, y, g(a.GetPixel(x, y)));
        }
    }
    return a;
}

static Color g(Color c) {
    int a = c.R;
    int g = c.G;
    double t = a + g + c.B + 3;
    var x = (a + 1) / t;
    var y = x + (g + 1) / t;
    var d = r.NextDouble();
    return d <= x ? Color.Red : d <= y ? Color.Lime : Color.Blue;
}

Examples:
Mona Lisa

Starry Night

Persistence of Memory

Teddy Roosevelt VS. Bigfoot

Here's an updated imgur album with a few more examples, to show that this is nondeterministic.

Color.Lime is the pure green color. For future reference, here's the known color table.

Heres a golfed version for 237 bytes: var r=new Random();c=>{double t=c.R+c.G+c.B+3,x=(c.R+1)/t,d=r.NextDouble();return d<=x?Color.Red:d<=x+(c.G+1)/t?Color.Lime:Color.Blue;};b=>{for(int x=0,y;x<b.Width;x++)for(y=0;y<b.Height;y++)b.SetPixel(x,y,g(b.GetPixel(x,y)));return b;}; And there are still improvements that can be made

Its actually 237 bytes the extra bytes are invisible characters that are added in the code comment I believe

Pyth - 11 10 bytes
Takes RGB 2d bitmap and outputs bitmap with indexed 3-bit color.
mLOs.emkbk

That level of nesting is hurting my head.
Try it online here.

Python 2, 172 166 162 bytes
The second and third indent levels are a raw tab and a raw tab plus a space, respectively; this plays really badly with Markdown, so the tabs have been replaced by two spaces.
from random import*
i=input()
E=enumerate
for a,y in E(i):
 for b,x in E(y):
  t=sum(x)+3.;n=random()
  for j,u in E(x):
   n-=-~u/t
   if n<0:i[a][b]=j;break
print i

Uses a similar input/output format to Adám's APL answer. Input is a 2D array of RGB tuples; output is a 2D array of 0, 1, or 2, representing red, green, and blue respectively. For example:
$ echo "[[(181,61,34),(39,184,160),(255,0,0)],[(84,7,27),(123,97,5),(12,24,88)]]" | python quixel.py
[[2, 2, 0], [0, 0, 0]]

Below is my older Python 3 answer using PIL.
Python 3 + PIL, 271 250 245 243 bytes
import random as a,PIL.Image as q
i=q.open(input())
w,h=i.size
for k in range(w*h):
 m=k//h,k%h;c=i.getpixel(m);t=sum(c)+3;n=a.random()
 for j,u in enumerate(c):
  n-=-~u/t
  if n<0:z=[0]*3;z[j]=255;i.putpixel(m,tuple(z));break
i.save('o.png')

Iterates over every pixel and applies the quixel function to it. Takes the filename as input and saves its output in o.png.
Here are some results:
$ echo mona-lisa.jpg | python quixel.py

$ echo starry-night.jpg | python quixel.py

$ echo persistence-of-memory.jpg | python quixel.py

$ echo roosevelt-vs-bigfoot.jpg | python quixel.py

@Doddy Probably because it's a PRNG and not a cryptographically secure RNG.

@someonewithpc Oh actually, I wrote that question when viewing on my phone, where the last image has a regular grid-like pattern on it, but now, viewing on a computer, it is the first image with this effect.

@Doddy Oh, yeah! Try pressing on the image on your phone: the effects will toggle! I guess it is about image sampling...

@Doddy Maybe delete your first question, so we don't think you're asking about the dense flag red stripes...

J, 20 18 17 bytes
(>:({~?@#)@##\)"1

The image is input as an array with dimensions h x w x 3 representing the RGB values as integers in the range 0 - 255. The output is a table with dimensions h x w where 1 is an rgb value of (255, 0, 0), 2 is (0, 255, 0), and 3 is (0, 0, 255).
Explanation
The ()"1 represents that this  verb is to be applied to each array of rank 1 in the input, meaning that it will apply to each pixel.
>:({~?@#)@##\  Input: array [R G B]
>:             Increment each, gets [R+1, G+1, B+1]
           #\  Gets the length of each prefix of [R G B], forms [1 2 3]
          #    Make a new array with R+1 copies of 1, G+1 copies of 2,
               and B+1 copies of 3
  (     )@     Operate on that array
       #         Get the length of the array of copies, will be R+G+B+3
     ?@          Generate a random integer in the range [0, R+G+B+3)
   {~            Select the value at that index from the array of copies and return

Your Mona Lisa has a different colour scheme to the others. Are you sure it works right?

@wizzwizz4 Thanks, when displaying the image, I had the rgb pixels in reverse order.

R, 58 bytes
mapply(function(r,g,b)rmultinom(1,1,c(r+1,g+1,b+1)),r,g,b)

Input consists of three numeric vectors held in r, g and b respectively.
We don't need to normalise the probabilities to sum to one, that happens automatically in rmultinom.
Output is of the form
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    0    0    0    0    0    0    0    0     0
[2,]    0    0    0    1    0    0    1    1    1     0
[3,]    1    1    1    0    1    1    0    0    0     1

Where there is a single 1 in each column. The 1 is in the first row for "R" pixels, the second row for "G" and the third row for "B".

Jelly, 8 7 bytes
Jx‘Xµ€€

The input is a 3d list with dimensions h x w x 3. The output is a 2d list with dimensions h x w where 1 represents the rgb value (255, 0, 0), 2 is (0, 255, 0), and 3 is (0, 0, 255).
The sample input below is the top-left 4 x 4 region of the Mona Lisa image.
Try it online!
Explanation
Jx‘Xµ€€  Input: The 3d list of rgb pixels
    µ    Begin a monadic chain (Will operate on each pixel, input: [R, G, B])
J          Enumerate indices to get [1, 2, 3]
  ‘        Increment each to get [R+1, G+1, B+1]
 x         Make R+1 copies of 1, G+1 copies of 2, B+1 copies of 3
   X       Select a random value from that list of copies and return
     €€  Apply that monadic chain for each list inside each list

Python 3, 119 bytes
Where m is the input taken as a 2-d array of pixels where each pixel is a list of the form [r,g,b]. At each pixel's position, returns 0,1,2 to represent (250,0,0), (0,250,0), and (0,0,250) respectively.
import random
lambda m:[map(lambda x:x.index(sum((((i+1)*[i])for i in x),[])[random.randint(0,sum(x)+2)]),i)for i in m]

I don't believe you are allowed to take input as a variable (when writing a full program in a language that supports normal IO). I think you have to use input or make this a function and take m as a parameter.


text:
The Squiggly Sequence
All credits to Adnan for coming up with this challenge.
My last challenge, before I go on break.
Task
Given positive integer n, if n is odd, repeat / that many times; if n is even, repeat \ that many times.
(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)
Specs

Any reasonable input/output format.
Standard loopholes apply.

Testcases
n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\

Javascript, 22 bytes
n=>"\\/"[n%2].repeat(n)

Defines an anonymous function.
If only * repeated strings in Javascript. sighs

Finally you have found the right operator

@LeakyNun What are you talking about?

You were using the ternary operator to choose the character, no?

@LeakyNun Initially, yes, but if you look at chat, I also posted this about a minute later.

Oh, I didn't notice; my fault.

Your slashes are switched around.

@Scepheo Thanks for pointing that out!

sorry for the ignorance (new here, and reading up a lot of code-golf questions).. How would one test this snippet?

@Jordumus You could either assign the function to a variable: f=n=>..., you could directly call it: (n=>...)(5). (Or if you are using the Node.js REPL, then you could use this._, which stands for the last thing entered)

Python, 20 bytes
lambda n:'\/'[n%2]*n

Great, simple and elegant ^_^

05AB1E/2sable, 15 11 9 8 bytes
DÈ„/\sè×

-2 bytes thanks to Leaky Nun
-1 byte thanks to Emigna
Try it online! in 05AB1E
or in 2sable

ftfy

It says sè×

"/\" can be „/\

You can remove the leading D for -1 byte in both languages, since input is implicit. You can also save an additional byte in 05AB1E (legacy) by changing È„/\ to „\/, since indexing is modular. (PS: in the new version of 05AB1E it's even 1 byte less by removing the s, but there is already an answer for that.)

Perl, 20 bytes
Includes +1 for -p
Run with input on STDIN:
squigly.pl <<< 6

squigly.pl
#!/usr/bin/perl -p
$_=$_%2x$_;y;01;\\/

It might just be my version of Perl (I'm still on 5.10) but this throws an error unless I add an extra ; to the end. I think it's because it you're using the semi-colon as a separator for y and you need one more to finish the statement (and would need two if you had more lines of code after this)

@theLambGoat Are you sure you are using the -p option ? I use ; in the transliterate exactly because -p has an implicit ; at the end of the code so I can save 1 more byte. This has worked since at least perl 5.6 (probably as long as the -p option existed in fact)

@theLambGoat Mm, I found an old redhat with perl 5.10 where indeed it does not work. Either this is a redhat patch or it indeed did not work for around 5.10 (I'm sure it worked in older perls and it also works in newer perls)

I'm running on SUSE Enterprise Server 11 so it's not just a redhat thing. But I think as long as it works in some versions, it should still be a valid answer. (I also just checked in 5.08, the only other version I have access to at the moment and it doesn't work there either)

Also 20 bytes: $_=qw{\ /}[$_%2]x$_ but far less interesting than this one!

That trick with the ; added by -p is quite awsome, well done.

J, 10 bytes
#'\/'{~2|]

This is a six-train verb, consisting of:
# ('\/' {~ 2 | ])

This is a hook between # and ('\/' {~ 2 | ]); a hook (f g) y expands to y f (g y), so this expands to y # (... y), which, for single-characters, yields a list of y characters.
The second part is a 5-train, consisting of:
'\/' {~ 2 | ]

This evaluates to two forks:
'\/' {~ (2 | ])

The inner fork, 2 | ], is modulus two. The outer fork, therefore, is:
'\/' {~ mod2

Which takes ({~) the mod2 index (mod2) from the string /.
Then, using the hook from above:
y # (apt char)

This yields what we want, and we are done.

Retina, 21
.+
$*/
T`/`\\`^(..)+$

Try it online (First line added to allow multiple testcases to be run).

PHP, 38 bytes
for(;$i++<$a=$argv[1];)echo'\/'[$a%2];

(variant 38 bytes)
while($i++<$a=$argv[1])echo'\/'[$a%2];

(variant 38 bytes)
<?=str_pad('',$a=$argv[1],'\/'[$a%2]);

(variant 40 bytes)
<?=str_repeat('\/'[($a=$argv[1])%2],$a);

C#, 42 bytes
string f(int n)=>new string("\\/"[n%2],n);

Selects the correct character, then creates a new string consisting of that character repeated n times.

C, 40 bytes
i;f(n){for(i=n;i--;)putchar(n%2?47:92);}

Try it on Ideone

putchar(92-n%2*45) is the same length.

Jelly, 5 bytes
ị⁾/\x

Try it online! or Verify all testcases.
ị⁾/\x

ị⁾/\    modular-indexing into the string "/\"
    x   repeat

Although I suspect this challenge may have something to do with it existing, it's worth noting that Ø^ is a byte shorter than ⁾/\ .

Haskell, 25 bytes
f n=cycle"\\/"!!n<$[1..n]

-1 byte thanks to Damien with cycle.

f n=cycle"\\/"!!n<$[1..n]

@Damien Wow, how did I forget cycle.

I don't know. But I'm glad to have had the opportunity to "beat" you once :)

Mathematica, 34 32 28 bytes
If[OddQ@#,"/","\\"]~Table~#&

Anonymous function. Takes an integer as input and returns a list of characters as output.

You can use ~Table~#.

I think it was added in 10.2.

Also, I think you can ditch the <>"" and return a list of characters.

@MartinEnder They must have also added ~Do~Infinity and such in 10.2+ as well...

Mathematica, 29 bytes
"\\"["/"][[#~Mod~2]]~Table~#&

Cruelly exploits the fact that [[1]] returns the first argument of a function while [[0]] returns the function (head) itself, applied to the strangely valid function named "\\" which is being "evaluated" at "/".

It's slightly less weird when you consider that something of the form a[b] is just a generic expression with head a (index 0) and element b (index 1), and functions are just special kinds of expression (actually, it would be more correct to say that functions aren't expressions at all, but are simply rules for transforming expressions which usually have form f[x...]). :)

I've seen many languages abused on this site, but I think this is the first abuse of Mathematica that I've seen. Good job!

Powershell, 30 27 bytes
Update:
param($n)('\','/')[$n%2]*$n

Switching to param, thanks to timmyd.

"$("\/"[$args[0]%2])"*$args[0]

or slightly more readable
("\","/")[$args[0]%2]*$args[0]

Test:
> 1..10 | % { ./run.ps1 $_ }
/
\\
///
\\\\
/////
\\\\\\
///////
\\\\\\\\
/////////
\\\\\\\\\\

Welcome to PPCG! Nice to see another PowerShell user around here. You can shave a few bytes by taking input as param($n) instead of $args, like follows for 27 bytes -- param($n)('\','/')[$n%2]*$n

><> (Fish), 30 Bytes
:2%?'/'o1-:?!;30.
30.  >'\'50p

First time using this language, but I think I at least saved a little room by conditionally using the / as either part of the output or a mirror to redirect flow. Probably still horribly inefficient though, I feel like it could probably be cut down a little more at the very least.
Input is the initial stack, output is stdout
Try it online!

Welcome to Programming Puzzles & Code Golf!

@Dennis Thanks! I appreciate the welcome.

Ruby, 15 bytes
->n{'\/'[n%2]*n}

See it on eval.in: https://eval.in/632030

Fourier, 27 bytes
92~SI~N%2{1}{47~S}N(Sai^~i)

Try it online!

Dyalog APL, 11 bytes
Requires ⎕IO←0 which is default on many systems.
⊢⍴'\/'⊃⍨2|⊢

⊢ the argument
⍴ reshapes (repeats)
'\/'⊃⍨ the string "/" selected by
2|⊢ the division remainder when the argument is divided by two
TryAPL online!

Cool! Very similar to J.

@ConorO'Brien Yes, the only difference is that 2-trains in J are hooks, while they are atops in Dyalog, so an explicit left tine is needed.

Ah, I was wondering why the argument was there.

Finally an APL answer with all characters rendered correctly for me!

@Cyoce Yeah, I wish we could specify (and embed) fonts on SE.

Brachylog, 15 bytes
:2%:"\/"rm:?jbw

Try it online!
Explanation
:2%                Input mod 2…
   :"\/"rm         …is the index of the element in string "\/",…
          :?j      …element that we juxtapose Input times to itself…
             bw    …and print to STDOUT after removing one slash/backslash

Java 11, 68 65 29 bytes
n->(n%2<1?"\\":"/").repeat(n)

-3 bytes saved thanks to @user902383 and @SeanBean
-36 bytes switching from Java 7 to Java 11+
Try it online.
Explanation:
n->                     // Method with integer parameter and String return-type
  (n%2<1?               //  If `n` is even:
         "\\"           //   Use String "\"
        :               //  Else (`n` is odd):
         "/")           //   Use String "/" instead
             .repeat(n) //  Repeat it `n` amount of times

Hi Kevin. Why not a Lambda Expression?

@Vale Hi Vale. Because I'm an old-fashion Java 7 programmer. :) If you have a Java 8 or 9 answer that is slightly different than my answer, feel free to post it.

@Vale (he's odd like that :P)

@KevinCruijssen I must admit I'm slowly switching too, so I'll post it as soon as I make it work! It doesn't help that the projects I'm following right now are all in Java 7 as well. I can't wait to transition completely. If anybody would like to intervene for the both of us, please do.

i think if you change x=-1;++x<i to x=0;x++<i you can reduce by one byte

Also you can replace "\\"  : "/" with 92:'/' ;)

CJam, 9 bytes
ri_"\/"=*

Try it online!
Explanation
ri     e# Read input and convert to integer N.
_      e# Duplicate N.
"\/"=  e# Use N as cyclic index into "\/", giving '\ for even and '/ for odd inputs.
*      e# Repeat N times.

T-SQL 50 bytes
Of course no STDIN here, so let's assume a hardcoded INT variable like this: DECLARE @ INT then the solution is:
PRINT IIF(@%2=0,REPLICATE('\',@),REPLICATE('/',@))

Pip, 8 bytes
"\/"@aXa

Straightforward. Uses modular indexing to select the character and string repetition to multiply it. Try it online!

This question presents an interesting comparison between Pip, Pyth, and Jelly, the latter two each having scored 5 bytes. All three languages have implicit output, with single-char operators for modular indexing and string repetition, and no requirement to escape backslashes in strings. There are two key differences, though:

Under certain circumstances, Pyth and Jelly need only one delimiter to define a string;
Pyth and Jelly have syntax such that the input doesn't need to be explicitly represented in the code (though for very different reasons, as Maltysen explained to me).

Neither one of these features is likely to show up in Pip1 (I don't like the aesthetics of unbalanced delimiters, and point-free syntax or implicit operands seem like they would be too alien to my infix expression parser), but I'm okay with playing third fiddle. Even though "readability" is extremely relative when golfing, I'd argue that those three extra bytes make the Pip program a lot easier to understand at a glance--and in my book, that's a worthwhile tradeoff.
1 Although, single-character strings in Pip use a single ' delimiter, inspired by CJam and by quoting in Lisp.

I'm not sure that readability is a plus, in code golf?   Not at the cost of bytes !

@GreenAsJade I expect a lot of people feel the same. I would just make one distinction: code golf != golflang design. Now you may well argue that the same principle (shorter is always better) applies to language design too. I'm just saying that for me, usability and even aesthetics are considerations.

Pro tip for making a golfing language: don't use infix

@Cyoce http://chat.stackexchange.com/transcript/message/31933195

pyth doesn't have implicit point free syntax. it works pretty much the same way it does in python, making it readable yet short. your comment about the unbalanced delimiters on the other hand is pretty true

Julia, 20 bytes
!x="$("/\\"[x%2])"^x

R, 47 46 bytes
n=scan();cat(rep(c("\\","/")[n%%2+1],n),sep="")

In R, you have to escape backslashes. the argument sep also has to be fully specified since it comes after .... Thus annoyingly few opportunities to save chars :(
Thanks to bouncyball for golfing away a byte.

Save one byte by using indexing: n=scan();cat(rep(c('\\','/')[n%%2+1],n),sep='')

Psithurism, 11 bytes
*(%2?"/:"\)

This is a language I'm still developing, but I'm going to start posting answers here to get a feeling of what kind of built-in functions might be useful to have. (This one has taught me I really need some way to index into arrays/strings lol.)
explained:
*(        # implicitly multiply the input by
  %2      # implicitly take input mod 2
    ? "/  # / if truthy (1)
    : "\  # \ if falsy (0)
)

Curious about Psithurism?
Github: https://github.com/AroLeaf/psithurism/
Docs (soon™): https://psithurism.leaf.moe/

I don't think it's non-competing since we dropped the rule that languages have to be older than the challenge.

@TheThonnu oh that's nice, thanks! I do assume that implementing a feature to improve your score is still non-competing?

If you make the feature just for that challenge, yeah it's non-competing, but if you make a feature which generally improves the language, and improves your score as a side effect, then that's fine.

@TheThonnu alright, thanks for clarifying

So for your example adding indexing would be fine in my opinion, because it's a useful feature for many challenges. Related loophole on Meta if you want more info.

Also, related Meta post about answering in newer languages.

Actually, 10 bytes
Golfing suggestions welcome. Try it online!
;'\'/2(%I*

How it works
       Implicit input of n
;      Duplicate n
'\'/   The strings "/" and "\"
2(%    n mod 2
I      If n mod 2, then "/", else "\"
*      Multiply by n. Implicit print at the end.

><>, 15 + 3 = 18 bytes
\/:l2-),:2%0go:

+3 bytes for the -v flag to initialise the stack with the input. Try it online!
 ><> is a toroidal 2D language, so the following runs in a loop:
\/          Mirrors that reflect the instruction pointer. Since the code is
            one row high, the reflection wraps and the IP ends up moving in the
            same direction anyway, so these are no-ops.

:l2-)       Push (input > length of stack - 1) - note that the actual subtraction
            is by 2 to account for the fact that we duplicated an element with :

,           Divide the input by the above. If (input == length of stack - 1),
            then the program errors out due to division by 0. Otherwise, the
            input is unchanged.

:2%0g       Push the char at (input % 2, 0), which will be one of the two slashes
            at the beginning of the code

o           Output this char

:           Duplicate the input, increasing the length of the stack by 1

Pyth, 5 bytes
*@"\/

Test suite.
Modular-indexing into the string \/ and then repeat.

You're FGITW'ing your own challenge?

@xnor it isn't exactly my challenge.

Perl 6, 16 bytes
{<\ />[$_%2]x$_}

Usage:
for 1..6 {
  say $_, {<\ />[$_%2]x$_}( $_ )
}

1/
2\\
3///
4\\\\
5/////
6\\\\\\

SpecBAS - 28 bytes
1 INPUT n: ?"\/"(ODD(n)+1)*n

ODD returns 1 if number is odd, then uses that as an index to print the correct character n number of times. Have to add 1 as SpecBAS strings start at character 1.

Python 3, 43 Bytes
n=int(input())
a='\\'*n
if n%2:a='/'*n
print(a)

In python the \ symbol is also used as an operator when inside a string (e.g: \n means newline) so \\ has to be used to get the backslash symbol.
This code works by assuming the input (n) is odd, and then checks if it is even. If so, then it redefines the variable a (the output) before displaying it.
This is shorter than using an if-else statement by 5 bytes as it does the checking after defining the variable, meaning that the else command is not needed.

You could save bytes by changing to Python2, since int(input()) could be changed to input() and print wouldn't need parentheses. Also, there's an unnecessary whitespace in n%2: .

Also, you may hook the character from a string (selecting n%2-th) character, but that would end up being the same answer as @xnor has. It's a nice trick for the future!

Indeed, '\/'[n%2]*n is pretty much as short as it can be.

Thanks for the tips, I'll bear them in mind for next time

Java 8, 56 bytes
(i,j)->{for(j=i;j-->0;)System.out.print(i%2<1?92:'/');};

I'd like to thank @Kevin Cruijssen in advanced for golfing my answer further.
Ungolfed Test Program
public static void main(String[] args) {
    BiConsumer<Integer, Integer> consumer = (i, j) -> {
        for (j = i; j-- > 0;) {
            System.out.print(i % 2 < 1 ? 92 : '/');
        }
    };

    consumer.accept(5, 0);
    consumer.accept(1, 0);
    consumer.accept(8, 0);
}

Bash + coreutils, 29 28 bytes
yes $1_45r2%*92+P|sed $1q|dc

Previous answer, easier to understand:
yes $[92-$1%2*45]P|sed $1q|dc

In the new script I just transferred the calculation of the ASCII code from bash to dc entirely.

@LeakyNun I was used with the Bash and pure Bash terms until I started here. I updated my answer.

PHP, 63 52 bytes
Version 1 - 63 bytes
$i=$argv[1];$x=($i%2?"/":"\\");echo sprintf("%'".$x.$i."s",$x);

Version 2 - 52 bytes
Thanks to manatwork for saving 11 bytes
$i=$argv[1];$x=$i%2?"/":"\\";printf("%'$x{$i}s",$x);

Run with php -f squiggle.php <number>
https://repl.it/DFdi/2 (remember to change the input on repl)

No need for parenthesis around the ternary expression. Why using sprintf() to return a value just to echo it and not directly printf() it? And is shorter to use variable expansion than concatenating the format string: "%'$x{$i}s".

@manatwork thanks for the great tips! I've modified my answer.

Husk, 6 bytes
R¹!"/¦

Try it online!
-4 bytes from Zgarb.
¦ is an alias for \ in a string.
Husk, 10 bytes
*⁰;!⁰"/\\"

Try it online!
Explanation
*⁰;!⁰"/\\"
   !⁰"/\\" get element at index n in string "/\" (wraps around)
  ;        create singleton list from it
*⁰         repeat list n times

Japt, 7 bytes
çUg"\\/

Try it

Forth (gforth), 55 bytes
: b 1- dup for dup 2 mod if 92 else 47 then emit next ;

Try it online!
called as <number> b.

05AB1E, 7 5 bytes
-2 bytes thanks to @Neil.
„\/è×

Try it online!
     è   # 0-based index...
         # implicit input...
     è   # implicit mod 2 in...
 „\/     # "\/"
      ×  # repeat implicit input times
         # implicit output

è is a) modular, so you don't need É, and b) commutative, so you don't need s.

Vyxal, 31 bits1, 3.875 bytes
‛\/iẋ

Try it Online!
'\/    # string literal "\\/"
   i   # modular index
    ẋ  # repeat

Vyxal, 8 bytes
?£₂k/i¥ẋ

Try it Online!

5 bytes because of implicit input or 4.75 bytes in Vycoder

TypeScript's Type System, No Ignore, 541 311 155 148 140 118 bytes
Based off of a previous even/odd answer
type E<N>=N extends`11${infer R}`?R extends""?"/":E<R>:"\\"
type X<A,B=A>=B extends`1${infer R}`?`${E<A>}${X<A,R>}`:""

X takes in a repeated 1 N times to represent the number N, for example X<"11111"> represents 5 passed to the X function.
TypeScript Playground && Tests

Drastic improvements by Jacob via even/odd, input simplification, and joining together types

175 bytes https://tsplay.dev/WPgoKm

I do want to make sure I didn't mess it up - was that 175 bytes of improvement or 175 bytes total? (If it was total, it seems I couldn't do the minification right - I was only able to shave off 230 bytes by minifying your solution - the extra improvements came from dropping the unneeded conditional on Join and simplifying infer _ to any)

175 total - the part after the blank line is footer, which shouldn't be counted, unless you still want to take input in decimal. But then I'm sure there's a shorter way of converting decimal to unary, I didn't attempt to golf that section. Good idea with the ${any} -- I didn't think of that.

Oh right! Thanks, I'll edit the solution with that input instead.

148 bytes (I think you copy-pasted from the wrong link I posted earlier) https://tsplay.dev/Nll1XN

Even further, (didn't see this before) you can use &string instead of N extends string to coerce the type to be stringified: https://tsplay.dev/wR0o1m

(Golf stackexchange reccomended for us to continue this discussion in chat).

Uiua, 11 bytes
▽∶?@/@\\◿2.

Try it!
▽∶?@/@\\◿2.
          .  # duplicate
        ◿2   # modulo two
  ?@/@\\     # choose slash depending on result
▽∶           # repeat it input times

Tried all sorts of ideas only to get a tie or 1 longer :/

@Bubbler Wow, that's a lot of ideas!

Rust, 210 190 Bytes
fn main(){let x:usize=std::env::args().nth(1).unwrap().parse::<usize>().unwrap();let l:&str=match x%2{0=>"\\",1=>"/",_=>"",};println!("{}",std::iter::repeat(l).take(x).collect::<String>());}

Ungolfed:
fn main() {
    let x : usize = std::env::args().nth(1)
                                    .unwrap()
                                    .parse::<usize>()
                                    .unwrap();
    let l : &str = match x % 2 {
        0 => "\\",
        1 => "/",
        _ => "",
    };
    println!("{}", std::iter::repeat(l).take(x)
                                       .collect::<String>());
}

I don't usually golf (so I bet this isn't a great score, at least for Rust), but I figured this would be good Rust practice. This compiles into an executable run as squiggly.exe x where x is the number of times to repeat the character.

Cut off 20 bytes by realizing that direct referencing (std::env::args(), std::iter::repeat(l)) is more effective than use clauses

S.I.L.O.S, 55 bytes
readIO
c=i
c%2
c*45
c-92
c|
lbla
printChar c
i-1
if i a

Try it online!
Port of this answer in C.

awk, 26 bytes
NF=$1,$1=OFS=$1%2?"/":"\\"

$1 is the input and then part of the output
NF is the number of fields
OFS is the output field separator
It prints if the expression before the comma is truthy.

Lua (33 44 Bytes)
Never tried golfing with Lua before.
Shortest program I could come up with:
n=io.read()print(({'\\','/'})[n%2+1]:rep(n))

Your code should handle either input or parameter.

Forth, 58 54 bytes
Leaves n%2 as junk on the stack. Output is sent to stdout. 47 is /, and 92 is \. Computes y=92-45*x, where x is n%2 and emits (outputs) the character with that codepoint.
: f dup 2 mod swap 0 DO dup 92 swap 45 * - emit LOOP ;

Try it online

PL-SQL (Oracle), 530 characters
DECLARE
-- Enter your input here, here example is taken as 3 ---
  n number := 3 ;
  k varchar2(20);
BEGIN
     -- Checking the input number for odd --
     if mod(n,2)=1 then
     for j in 1..n loop
      k := k||'/';
      end loop;
      DBMS_OUTPUT.PUT_line (n||' '||k);
     end if;

     -- Checking the input number for even --
         if mod(n,2)=0 then
         for j in 1..n loop
         k := k||'\';
          end loop;
          DBMS_OUTPUT.PUT_line (n||' '||k);
         end if;
END;

Language name?.

Welcome to PPCG! Please put what language this is and the length in bytes at the top of your post. Also, remove as many extraneous characters as possible, including whitespace. Posters must make a serious effort to golf (shorten) their code for [code-golf] questions.

Haskell, 32 bytes
f n=replicate n$"\\/"!!(mod n 2)

replicate n x can be replaced by [1..n]>>[x] or x<$[1..n] (with GHC 7.10). You can find other haskell tricks here: http://codegolf.stackexchange.com/questions/19255/tips-for-golfing-in-haskell

RETURN, 21 bytes
[$2÷%'/'\2øø4ø2␂{␋},]

Try it here.
Anonymous lambda. Usage:
5[$2÷%'/'\2øø4ø2␂{␋},]!

Explanation
[                    ]  [lambda]%
 $2÷%                   [copy input and mod 2]%
     '/'\2øø            [choose either / or \ depending on input mod 2]%
            4ø          [get input again]%
              2␂{      [copy the /\ char and the input into a new stack]%
                  ␋},   [repeat the stack by the input and output the stack]%

Bash, 63 bytes
q(){ seq -s0 0 $1|cut -c-$1|tr 0-9 $(($1%2))|sed 'y/10/\/\\/';}

Weird. If you know the tr command, then why used sed for the 2nd transliteration?

Move your code outside of the function and drop the q(){} part. Also, you can drop both tr and sed conversions by doing something like this: c=(\\ /);seq -s${c[$1%2]} 0 $1|tr -d [0-9]. For an even shorter way see my answer

x86-16 machine code, PC DOS, 18 bytes
Binary:
00000000: a082 002c 30a8 0191 b85c 0a74 02b0 2fcd  ...,0....\.t../.
00000010: 10c3                                     ..

Listing:
A0 0082     MOV  AL, BYTE PTR[82H]  ; first char of command line into AL
2C 30       SUB  AL, '0'            ; ASCII convert input char
A8 01       TEST AL, 1              ; set ZF if even
91          XCHG AX, CX             ; CL = number of times to repeat
B8 0A5C     MOV  AX, 0A5CH          ; AL = '\', AH = 0AH (BIOS write char)
74 02       JZ   WRITE              ; if even, write with a '\'
B0 2F       MOV  AL, '/'            ; otherwise change to a '/'
        WRITE:
CD 10       INT  10H                ; write AL to console CX number of times
C3          RET                     ; return to DOS

Standalone PC DOS executable (COM) program.  Input n on command line (note: this is limited to single digit values).

Acc!!, 90 bytes
N
Count i while _%60-10 {
_*10+_%60*50-2880+N
}
_/60
Count j while _-j {
Write 92-_%2*45
}

Try it online!
With comments
# Read a line of stdin, convert it to a decimal number, and store it in the accumulator
N
Count i while _%60-10 {
    _*10+_%60*50-2880+N
}
_/60
# Loop that many times
Count j while _-j {
    # Output \ if accumulator mod 2 is 0, or / if it is 1
    Write 92-_%2*45
}

Acc!! is a really fun language!

MAWP, 38 bytes
%@!!2P2WA{~[67W5M;1A].}~[99W25W1MM;1A]

Made using Dion's modulus function from here.
Try it!

Pyth, 5 bytes
*@"\/

Try it online!
*@"\/
@("\/", Q) * Q  // After implicit input is read and re-structured to appear more readable.
@("\/", Q)      // Get element at index Q(input)
@("\/", Q) * Q  // Repeat Q times.

Arturo, 31 bytes
$->n->repeat(0=n%2)?->{\}->"/"n

or
$->n[s:[{\}"/"]repeat s\[n%2]n]

Try it

Scala, 56 bytes
Golfed version. Try it online!
def c(i:Int)=for(_<-1 to i){print(if(i%2<1)"\\"else"/")}

Ungolfed version. Try it online!
object M {
  implicit class IntExtensions(val i: Int) extends AnyVal {
    def times[T](f: => T): Unit = {
      for (_ <- 1 to i) {
        f
      }
    }
  }
  //def c(i:Int)=print(Iterator.fill(i)(if(i%2<1)"\\"else"/").mkString)
  //def c(i:Int)=Iterator.fill(i)(if(i%2<1)"\\"else"/").foreach(print)
  def c(i: Int) = i.times { print(if (i % 2 < 1) "\\" else "/") }
  def main(args: Array[String]): Unit = {
    for (i <- 0 until 10) {
      c(i)
      println()
    }
  }
}

Rust, 28 bytes
|n|[r"\","/"][n%2].repeat(n)

Attempt This Online!

R, 32 bytes
\(n)intToUtf8(rep(92-45*n%%2,n))

Attempt This Online!

Thunno 2, 5 bytes
`\/i×

Explanation
`\/i×  # Implicit input
`\/    # Two character string "\\/"
   i   # Modularly index in
    ×  # Repeat input times
       # Implicit output

Screenshot

Regenerate, 22 bytes
(/{1/($~1%2)}|\\){$~1}

Attempt This Online!
Explanation
(/{1/($~1%2)}|\\){$~1}
 /                      Match a forward slash
  {         }           repeated this many times:
   1/(     )             Invert:
      $~1                 Command-line argument
         %2               mod 2
                         (For odd arguments, this gives one forward slash; for even
                         arguments, it fails due to division by zero)
             |          If the previous alternative failed,
              \\        match a backslash instead
(               ){$~1}  Repeat the above (command-line argument) times

Ly, 17 bytes
'\'/n:2%Isp[,lo];

Try it online!
I tried a couple variations and this one was the shortest.  It's uses the eveness/oddness of the number to pick the character from a list on the stack, then stashes it away before looping "N" times and printing the saved character.  The stack ends up with junk on it so it explicitly exits to avoid printing it.  That proved shorter than cleaning the stack.
'\'/               - push "\/" onto the stack
    n:             - get number "N" from STDIN and duplicate
      2%           - get 0|1 depending on whether it's even or odd
        I          - copy top "\" or one-down "/" entry from stack
         sp        - stash the char and delete
           [,  ]   - loop "N" times
             lo    - load char to print, print it
                ;  - exit to avoid printing junk on the stack

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:
Write an xkcd feed bot
The new xkcd feed bot room gave me an idea for a simple challenge.
Your code will have to monitor the xkcd website and output all the new comics to the user.
Specs

When first run it should just sit around waiting.
Then, when randall posts a new comic, within a minute, it should display the new comic in any of our usual standards for images (display, save, etc.)
If the comic is interactive and not a simple image, then print out the string "interactive comic".
This does not include the comics which are an image inside a link, those still have to be displayed normally.
After displaying the image, it should go back to waiting around for the next update.
Your program cannot access any sites except http://xkcd.com

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

Link to the feed bot room: https://chat.stackexchange.com/rooms/44753/xkcd

"If the comic is interactive and not a simple image" then how do we know? At present this seems underspecified.

A decent strategy would be to only check during the two to three hours around midnight eastern US time on M/W/F, but that would miss those comics he occasionally posts on other days (like April Fools and those week-long series he did in the past).

@PeterTaylor If it's a single image, there will be a permalink to the image on the page. If not, there won't be. You could also test to see if the main content pane contains an  tag.

@PeterTaylor there will be an image tag in the correct position, not an iframe or whatever else he uses

Are we allowed to use RSS feed libraries such as feedparser?

PowerShell v2+ & Default Browser, 215 217 bytes
$l=date;for(){if(($x=([xml](iwr xkcd.com/rss.xml)).rss.channel.item[0]).pubdate-ge$l){if(($y=$x.description)-match'img src'){saps ($y-replace'<img src="'-replace'" .*')}else{echo "interactive comic"}}$l=date}

WARNING: Running this as-is will likely make Randall very mad at you, due to the high frequency of calls to the RSS feed ... so, y'know, don't do that. (See below for an alternate version that can be used in a one-off manner)
Sets the $last time we displayed a comic to the result of Get-Date. Then, enter an infinite for loop.
Each iteration, we iwr (alias for Invoke-WebRequest) the RSS feed for the site. That's parsed as [xml] (yes, PowerShell can cast as XML), and the .rss.channel.item[0] thereof (i.e., the newest) is stored in $x. If the .pubDate is -ge$l (i.e., newer than the last comic we showed), we have a new comic to display.
So, we first check the .description field (saved in $y), to see if it matches img src. If so, we parse out the img from $y, and feed that to saps (alias for Start-Process). Since it's a URI, this relies on Windows' default behavior for "executing" a URI, that is, it opens the default browser to that location. (If this is too cheaty, let me know and we can iwr down the actual image and save it.)
Otherwise, we echo out that we've got an interactive comic.
In either case, we update our $l date to "now" since we just displayed a comic.
Saved 7 bytes thanks to Matt for reminding me that http:// can be implied

"Safe" version that executes just once and displays the latest comic
$l=(date).AddDays(-3);if(($x=([xml](iwr http://xkcd.com/rss.xml)).rss.channel.item[0]).pubdate-ge$l){if(($y=$x.description)-match'img src'){saps ($y-replace'<img src="'-replace'" .*')}else{echo "interactive comic"}}

You can run this one safely to see how the logic works. It'll only execute once and only display the latest comic.

Why did you use echo here? echo "interactive comic"? Or am I not seeing the nested parentheses and you are capturing data somewhere else? Also iwr xkcd.com/rss.xml seems to work

@Matt When doing testing locally, I was getting inconsistent results without an explicit echo -- sometimes the output wouldn't update until the next time the XML updated, and then two "interactive comic"s would be output simultaneously. -- Thanks for the golf on http://, I keep forgetting that can be implied.

I'd like to point out that you could probably DDoS xkcd with this.

@Mathime I don't know if it'd reach DDoS levels, but it would definitely be a Bad Thing™, hence my disclaimer.

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


text:
End the tabs versus space war
End the tabs versus space war
So, there has been a great deal of debate of whether to use tabs or spaces to indent/format code. Can you help the university settle the dispute, by going to an incredibly crazy unique method of formatting.

Your job is to write a full program or function which expands all tabs into four spaces. And then replaces a run of n leading spaces with "/(n - two stars here)/". You will receive input over multiple lines in any reasonable format (single string array of strings for each new line. Columnar array etc.)

Sample input shamelessly stolen. Note that since tabs get automagically expanded to four spaces on SE I represent it as the "^" character, but you must handle tabs (codepoint 0x09) as well. All "^" characters represent a tabulation.
Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
    Not zero so multiply by 256 again to get 65536
    [>++++<-]>[<++++++++>-]<[>++++++++<-]
    +>[>
        # Print "32"
        ++++++++++[>+++++<-]>+.-.[-]<
    <[-]<->] <[>>
        # Print "16"
        +++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
    # Print "8"
    ++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
^this is preceded by a tab
^^two tabs
^^^three tabs etcetera!

Sample output
Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
/**/Not zero so multiply by 256 again to get 65536
/**/[>++++<-]>[<++++++++>-]<[>++++++++<-]
/**/+>[>
/******/# Print "32"
/******/++++++++++[>+++++<-]>+.-.[-]<
/**/<[-]<->] <[>>
/******/# Print "16"
/******/+++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
/**/# Print "8"
/**/++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
/**/this is preceded by a tab
/******/two tabs
/**********/three tabs etcetera!

Because the university needs space to download both Vim and Emacs, you are allowed very little storage for your code. Therefore this is code-golf and the shortest code wins. You may assume that input is well formed and lines with less than four spaces (after replacement of tabs) may result in undefined behavior.
Disclaimer
This "excellent" formatting strategy came courtesy of Geobits, and is reproduced with his permission. No programmers were harmed during the production of this challenge.

Will tabs only occur at the start of lines (i.e. as indentation)? Can lines have mixed indentation (tabs + spaces)?

Someone please submit an answer written in Whitespace.

Should we consider lines starting with /*, or can that be assumed as not a "well formed input"? A C++ source file would have been a better test, because its multiline comment /*   */ would possibly break some answers that replace first and last of the leading spaces with an /, and then proceed to fill spaces with *.

I'm guessing we can't assume the number of spaces is a multiple of four, right?

@someonewithpc no you may not

@sesvounara this formatting implementation need not result in compilable code.

The war has ended: https://medium.com/@hoffa/400-000-github-repositories-1-billion-files-14-terabytes-of-code-spaces-or-tabs-7cfe0b5dd7fd#.pmnalkp87 (Unless you're programming in C, apparently.)

@RohanJhunjhunwala Imagine this C++ line: [4 spaces]int c; /*  */. According to your spec it should be transformed to /**/int c;/*  */, but wrong solutions when searching the regex /*  to fill spaces with asterisks between // might end up doing: /**/int c;/****/. Is this considered a wrong output?

@seshoumara yes that is incorrect output

@RohanJhunjhunwala So now I ask my first question again, since it wasn't about compilable code. Imagine the same /*  */ C++ code, but this time at the beginning of the line. According to your spec it should be left as is. Here the trap is, and spotted wrong answers already, that a regex like say /\** / used to fill those spaces between // with asterisks would turn the line into /***/. I've seen this conversion as well /*//*/. I assume both are incorrect.

Could the "multiple line" also mean "a string separated by \n"?

@Rohan, please can you add a test-case for /*  */->/*  */ (i.e. no change for a line beginning with /*), and for     /*  */->/**//*  */?  Thanks.  Also for  a and   b (i.e. indentation less than 3 chars).

@Vale yes that is correct

@Toby you may assume that there will either be no indentation or more than four lines

@seshoumara both are incorrect

V, 21, 20 bytes
Íô/
Î^hr/hv0r*r/

Try it online!
This is literally just a direct port of my vim answer. The notable differences:

The Í command (Global substitute) automatically fills in the /g flag, which saves two bytes
ô is identical to \t
Î Is a mnemonic for :%norm, and it also fills in the necessary space between :%norm and the set of keystrokes.
The trailing carriage return at the end is implicitly added.

Vim, 37, 34, 33, 32 bytes
:%s/\t/    /g|%norm ^hr/hv0r*r/

Try it online!
Note that this requires a trailing carriage return (enter) in vim, although not in the online interpreter.
This uses the V interpreter because it's backwards compatible. A very straightforward solution.
Here's a gif that lets you see the solution happen in real time. This uses a slightly older version, and I added some extra keystrokes to make it run slower so you can see what happens:

And here is the explanation of how it works:
:%s/\t/    /g           "Replace every tab with 4 spaces
|                       "AND
%norm                   "On every line:
      ^                 "  Move to the first non-whitespace char
       h                "  Move one character to the left. If there is none, the command will end here.
         r/             "  Replace it with a slash
           h            "  Move to the left
            v0          "  Visually select everything until the first column
              r*        "  Replace this selection with asterisks
                r/      "  Replace the first character with a slash

I was gonna +1 for using g but then you edited to not use g :/ +1 anyway :D

@downgoat Haha, thanks! I'm actually much prouder of the version without :g because it abuses a lesser known feature: the norm command gets cancelled if ^F<space> fails. So :%norm ^F<space>foo is essentially the same thing as :g/^ /norm foo fun Vim hacks. :D

huh, I thought ^F was used to postition the screen. does it have different behavior inside norm?

@downgoat Haha, no it's ^F, not <C-f> Silly Vim key notation. In this case it's ^, jump to first non-whitespace char, and F<space> Which is find the first space behind the cursor.

ohhh, that makes so much more sense now >_>

I think you could use :retab (haven't tested it though).

@Loovjo Yeah, I had thought the same thing, but you have to :set expandtab for that to work, so it's actually one byte longer: :se et<cr>:ret 4<cr>

@DJMcMayhem Oh, right, didn't think of that

Perl, 41 bytes
s,␉,    ,g;s,^  ( +),/@{[$1=~y| |*|r]}/,

Run with the -p flag, like so:
perl -pe 's,␉,    ,g;s,^  ( +),/@{[$1=~y| |*|r]}/,'
#     ↑   └───────────────────┬───────────────────┘
#     1 byte               40 bytes

Replace ␉ by a tab (in Bash, try typing Control-V Tab.)

The way perl replaced that backreference on the spot, I wish sed had that too.

Cheddar, 60 57 56 bytes
Saved 3 bytes thanks to @Conor O'Brien
@.sub(/\t/g," "*4).sub(/^ +/gm,i->"/"+"*"*(i.len-2)+"/")

I wish Cheddar had better string formatting.
Try it online!
Explanation
This is a function. @ is a represents functionized property (e.g. ruby's &:) letting you do things like: `ar.map(@.head(-1))
@                      // Input
 .sub( /\t/g, " "*4)   // Replace tabs with four spaces
 .sub(
   /^ +/gm,            // Regex matches leading spaces
   i ->                // i is the matched leading spaces
     "/"+              // The / at the beginning
     "*"*(i.len-2)+    // Repeat *s i-2 times
     "/"                // The / at the end
 )

If you aren't familiar with regex the:
/^ +/gm

this basically matched one or more (+) spaces () at the beginning (^) of every (g) line (m).

do literal tabs work in cheddar regexes? also, /^ +/ suffices as a regex, since we can assume that the leading spaces will be at least 4 in length.

@ConorO'Brien I believe they do but I haven't tested

The tabs are supposed to be replaced before the transformation.

@ConorO'Brien oh >_> I had it that way originally and then I changed it

Mathematica, 97 bytes
a=StringReplace;a[a[#,"\t"->"    "],StartOfLine~~b:" "..:>"/"<>Table["*",StringLength@b-2]<>"/"]&

Anonymous function. Takes a string as input and returns a string as output.

Python 3, 124 bytes
Uses good ol' regex.
import re
lambda I:re.sub('^\s*(?m)',lambda m:'/'+'*'*len(m.group()[:-2])+'/',re.sub('\t+',lambda g:' '*4*len(g.group()),I))

Ideone it!

Java  210 207 bytes
This is the reference solution which implements it naively.
void a(String[]a){for(String s:a){s=s.replaceAll("\t", "    ");String x,y="";int j,i=s.length()-(x=s.replaceAll("^\\s+", "")).length();if(i>3){y="/";for(j=0;j++<i-1;)y+="*";y+="/";}System.out.println(y+x);}}

Vim: 37 bytes, Cheddar: 65 bytes, JavaScript: 75 bytes, then there's Java at 210 bytes :P why am I not surprised

Very concise code in java :P

You can change the last for-loop to save 1 byte: for(int j=0;++j<i-1;). Also, you can remove the int  before j, and put it after the already present int: int i=s.length()-(x=s.replaceAll("^\\s+", "")).length(),j;

can't it be a lambda to shave bytes using (a)->{...}?

At least it's still readable and doesn't need further comments :o)

@bunyaclovem it could but I'll leave it a fully qualified function for ease of use

All suggestions implemented. Could someone test it out. I'm on mobile

JavaScript ES6, 75 bytes
s=>s.replace(/\t/g,"    ").replace(/^ +/gm,k=>`/${"*".repeat(k.length-2)}/`)

Replace \t with a literal tab in your code.

Java, 185 184 167 152 bytes
S->S.map(s->{s=s.replace("\t","    ");String t=s.replaceAll("^ +","");int n=s.length()-t.length();if(n>3){s="/";for(;n-->2;)s+="*";s+="/"+t;}return s;})

Given the very loose definition of string array given in the initial post, I've used Stream<String> which allows for some consequent byte savings.
I used different techniques than the RI to achieve the same goal. The algorithm itself is rather the same.
Testing and ungolfed:
import java.util.Arrays;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {
    StringStreamTransformer sst = lines -> lines.map(line -> {
      line = line.replace("\t","    ");
      String trimmed = line.replaceAll("^ +", "");
      int startingSpaces = line.length() - trimmed.length();
      if (startingSpaces > 3) {
        line = "/";
        for(;startingSpaces > 2; startingSpaces--) {
          line += "*";
        }
        line += "/" + trimmed;
      }
      return line;
    });

    Stream<String> lines = Arrays.stream(new String[]{
      "lots of spaces and tabs after\t\t    \t\t         \t\t\t\t\t",
      "no space",
      " 1 space",
      "  2 spaces",
      "   3 spaces",
      "    4 spaces",
      "     5 spaces",
      "      6 spaces",
      "       7 spaces",
      "        8 spaces",
      "\t1 tab",
      "\t\t2 tabs",
      "\t\t\t3 tabs"
    });
    sst.map(lines).map(s -> s.replace(" ", ".").replace("\t","-")).forEach(System.out::println);

  }
}

Python, 125 111 bytes
lambda s:'\n'.join(('/'+(len(L.replace('\t',' '*4))-len(L.strip())-2)*'*'+'/'+L.strip(),L)[L[0]>' ']for L in s)

https://repl.it/DGyh/2

Retina, 25 bytes
The \t should be replaced with an actual tab character (0x09).
\t
4$*
%`^  ( +)
/$.1$**/

Try it online!
Explanation
\t
4$*

Replace each tab with four spaces.
%`^  ( +)
/$.1$**/

Transform each line separately (%) by matching 2+N spaces at the beginning of the line and replacing it with /.../ where ... is N copies of *.

SED (56 + 1 for -r) 57
s/⇥/    /g;tr;:r;s,^ ( *) ,/\1/,;T;:l;s,^(/\**) ,\1*,;tl

Where ⇥ is a tab
1. replaces tabs with spaces.
2. replaces the first and last leading space with /.
3. replaces the first space after / and 0+ *s with a * until there isn't a match.

Since sed is specified, no single quotes are needed around the code, same with removing -r'' from your other sed answers, because you can consider the script as being stored in a source file that you run with -f. Any extra flags used like n or r should be counted as one byte each. Thus here, you save 2 bytes.

That's what I thought, but I want sure. Thanks.

The ; after the t command is not necessary either. As for the code itself, you need an ^ at the beginning of the third s command, otherwise an input like this "3 / 5" is turned into "3 /*5". In the first s command you actually have a tab there, but it's not correctly shown and misleading, so either use \t or specify after, that char was a tab.

@seshoumara Thanks, I'm trying to post from my phone... It's not the easiest thing to do.

I think I've spent more time editing this answer than all the others combined. Thanks for the help!

Upvoted you, can't press proportional to your edit work :) Only 1 byte down in the end, but errors were solved as well. I'm a sed fan, so I go through many posts using it and I can be a tough customer.

Can you confirm that this doesn't change a line that already begins with /*?  It looks like you need a Tend after that first replacement.

@TobySpeight You're right. I'll fix it as soon as i can

@TobySpeight Fixed. I Should have tested this better...

GNU sed, 66 64 + 1(r flag) = 65 bytes
Edit: 1 byte less thanks to Riley's suggestion.
s/\t/    /g
s,^ ( *) ,/\1\n,
:
s,^(/\**) ( *\n),\1*\2,
t
s,\n,/,

Run: sed -rf formatter.sed input_file
The reason for separating with a \n the leading spaces from the rest of the text on that line, is because otherwise a C++ line starting with a comment like this /*   */ would be turn into /*****/ by a simpler line 4 like s,^(/\**) ,\1*, or even s,^(/\**) ( */),\1*\2,. Since sed executes the script for each input line, no \n is introduced in the pattern space on reading.

You can save a byte by not putting in the closing / until you replace the \n. That saves you having to match it in line 4.

@Riley Good catch. Updated the code.

You can save another by replacing \twith a tab character.

@Riley That is true, but since it won't be printed as a tab here, I'm in doubt. I will keep this in mind for future sed answers with byte counts more competitive.

Ruby, 52 47 + 1 (p flag) = 48 bytes
Edit: saved whole 5 bytes, thanks to Value Ink
ruby -pe 'gsub ?\t," "*4;sub(/^ +/){?/+?**($&.size-2)+?/}'

Can you use the p flag to take advantage of the fact that (g)sub modifies $_ and thus changes the printed value? ruby -pe 'gsub ?\t," "*4;sub(/^ +/){?/+?**($&.size-2)+?/}'

Thanks, I didn't know (g)sub without bang can modify $_ here.

The university should consider allowing a bit more space for programs in Emacs Lisp (or default to tabify and untabify alone), as they get even more verbose than Java. It should also pay close attention to students (or teachers) whose identation size is smaller than four or who happen to code in some non-C-like language.
The following solution has 206 bytes
(lambda (b e)(let((tab-width 4))(untabify b e)(goto-char b)(while(re-search-forward"^ +"e t)(replace-match(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2)))))))))

Assuming that tab-width needs not to be explicitly set, we can save 20 of them.
(lambda(b e)(untabify b e)(goto-char b)(while(re-search-forward"^ +"e t)(replace-match(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2))))))))

And ungolfed version would look like this
(defun end-tab-war (beg end)
  (let ((tab-width 4))
    (untabify beg end)
    (goto-char beg)
    (while (re-search-forward "^ +" end t)
      (replace-match
       (format
        "/%s/"
        (apply 'concat
               (mapcar (lambda(x) "*")
                       (number-sequence 1
                                        (- (length (match-string 0))
                                           2)))))))))

We first untabify the region before jumping to its start. Then, while we see whitespace at the beginning of a line, we replace it with a comment that is as long as said whitespace. To be exact, the comment to be inserted is constructed by
 (format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2)))))

which itself takes up 97 bytes. A shorter solution to copy some string n times is highly appreciated.


text:
Subtract the next numbers
Description
Subtract the next P numbers from a N number. The next number of N is N + 1.
Look at the examples to get what I mean.
Examples:
Input: N=2,P=3
Calculate: n - (n+1) - (n+2) - (n+3)     //Ending with 3, because P=3
Calculate: 2 -  2+1  -  2+2  - 2+3       //Replacing N with 2 from Input
Calculate: 2 -  3    -  4    - 5
Output: -10

Input: N=100,P=5
Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5)
Calculate: 100-  101 -  102  -  103  -  104  - 105
Output: -415

Input: N=42,P=0
Calculate: n
Calculate: 42
Output: 42

Input: N=0,P=3
Calculate: n - (n+1) - (n+2) - (n+3)
Calculate: 0 -  1    -  2    -  3
Output: -6

Input: N=0,P=0
Calulate: n
Calculate: 0
Output: 0

Input:
N: Integer, positive, negative or 0
P: Integer, positive or 0, not negative
Output:
Integer or String, leading 0 allowed, trailing newline allowed
Rules:

No loopholes
This is code-golf, so shortest code in bytes wins
Input and Output must be as described

The essential challenge here is calculating triangle numbers.

There's more to this than just triangular numbers; the start point is arbitrary as well as the number of subtractions, which may be zero.

Also, for triangular numbers it's possible that doing the actual sum is shorter than using the closed form, whereas you can't just compute arbitrary polygonal numbers by summing a range from 0 to N. (I'd agree with the close vote if the other challenge just asked for triangular numbers.)

for the Input: N=0,P=3 example, your expansion has some extraneous double-negatives

@JDL, the part which is "more than just triangle numbers" is a simple multiplication: N * (P-1). That's virtually the definition of trivial.

why are there double minuses for N=0,P=3? Typo, right?

@MartinEnder, someone on meta found an even closer duplicate.

05AB1E, 5 3 bytes
Saved 2 bytes thanks to Adnan
Ý+Æ

Explanation
Takes P then N as input.
       # implicit input, ex 5, 100
Ý      # range(0,X): [0,1,2,3,4,5]
 +     # add: [100,101,102,103,104,105]
  Æ    # reduced subtraction: 100-101-102-103-104-105

Ahhh, I almost wanted to post my solution haha. Also, for three bytes: Ý+Æ :).

It only switches the input (P goes first)

@Adnan: I didn't even know 05AB1E had Ý... I thought only 1-based range existed.

In which character encoding is that only 3 Bytes? ;-)

@yankee: CP-1252

Python 2, 26 24 23 bytes
-2 bytes thanks to @Adnan (replace p*(p+1)/2 with p*-~p/2)
-1 byte thanks to @MartinEnder (replace -p*-~p/2 with +p*~p/2
lambda n,p:n-p*n+p*~p/2

Tests are on ideone

CJam, 8 bytes
{),f+:-}

Test suite.
Too bad that the closed form solution is longer. :|
Explanation
),  e# Get range [0 1 ... P].
f+  e# Add N to each value to get [N N+1 ... N+P].
:-  e# Fold subtraction over the list, computing N - (N+1) - (N+2) - ... - (N+P).

Haskell, 21 bytes
a#b=foldl1(-)[a..a+b]

Javascript (ES6), 20 19 18 bytes
n=>p=>n+p*(~p/2-n)

Saved 1 byte by currying, as suggested by Zwei
Saved 1 byte thanks to user81655
Test

let f =
n=>p=>n+p*(~p/2-n)

console.log(f(2)(3))
console.log(f(100)(5))
console.log(f(42)(0))
console.log(f(0)(3))
console.log(f(0)(0))

You can save a byte by currying the function. n=>p=>... and calling the function with f(n)(p)

(n,p)=>n-p*(++p/2+n) will also works in C#.

n-p*(++p/2+n) is equivalent to n+p*(~p/2-n).

Haskell, 19 18 bytes
n#p=n+sum[-n-p..n]

Previous 19 bytes solutions
n#p=n-n*p-(p*p+p)/2
n#p=n-sum[n+1..n+p]

Jelly, 4 bytes
r+_/

Try it online!
How it works
r+_/  Main link. Arguments: n, p

 +    Yield n+p.
r     Range; yield [n, ..., n+p].
  _/  Reduce by subtraction.

C#, 21 20 bytes
Edit: Saved one byte thanks to TheLethalCoder
N=>P=>N-P++*(N+P/2);

Try it online!
Full source, including test cases:
using System;

namespace substract
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,int>>s=N=>P=>N-P++*(N+P/2);
            Console.WriteLine(s(2)(3));     //-10
            Console.WriteLine(s(100)(5));   //-415
            Console.WriteLine(s(42)(0));    //42
            Console.WriteLine(s(0)(3));     //-6
            Console.WriteLine(s(0)(0));     //0

        }
    }
}

use currying N=>P=> instead of (N,P)=> to save 1 byte

Perl, 23 22 bytes
Includes +1 for -p
Give n and p (in that order) on separate lines of STDIN:
subtract.pl
2
3
^D

subtract.pl:
#!/usr/bin/perl -p
$_-=eval"+2+\$_++"x<>

(using '' quotes to save the \ invokes a 2 byte penalty because it can't be combined with -e)
Same idea and length:
#!/usr/bin/perl -p
$_+=eval"-1-++\$_"x<>

Surprisingly doing the actual calculation is shorter than using the direct formula (these $'s really hurt for arithmetic)

C++, 54 51 bytes
  [](int N,int P){int F=N;while(P--)F-=++N;return F;}

[](int N,int P){int F;for(F=N;P;F-=++N,P--);return F;}
Test:
#include <iostream>
int main(void)
{
    int N, P;
    std::cin >> N >> P;
    auto f = [](int N,int P){int F=N;while(P--)F-=++N;return F;};
    std::cout << f(N,P) << std::endl;
    return 0;
}

Welcome to PPCG! Unfortunately, all submissions need to be programs or callable functions, whereas this is just a snippet that assumes the input to be stored in pre-defined variables and stores the output in another.

@MartinEnder I have changed to C++ with  lambda. Is it acceptable?

Yes, lambdas are fine. :)

You can do this in C with 40 bytes f;g(n,p){f=n;while(p--)f-=++n;return f;} using your algorithm

@cleblanc Thanks for tip - global variable and declaration without an explicit type are really useful. What a pity that C99 standard removed implicit int

Mathematica, 15 bytes
#2-##-#(#+1)/2&

An unnamed function that receives P and n as its parameters in that order.
Uses the closed form solution n - n*p - p(p+1)/2.

Pyke, 6 bytes
m+mhs-

Try it here!
m+     -    map(range(input_2), +input_1)
  mh   -   map(^, +1)
    s  -  sum(^)
     - - input_1 - ^

Brachylog, 19 17 bytes
hHyL,?+y:Lx+$_:H+

Explanation
hH                  Input = [H, whatever]
 HyL,               L = [0, …, H]
     ?+             Sum the two elements in the Input
       y            Yield the range from 0 to the result of the sum
        :Lx         Remove all elements of L from that range
           +        Sum the remaining elements
            $_      Negate the result
              :H+   Add H

MATL, 5 bytes
:y+s-

Inputs are P and then N.
Try it at MATL Online!
Explanation
:     % Take P implicitly. Range [1 2 ... P]
      %     Stack: [1 2 ... P]
y     % Take N implicitly at the bottom of the stack, and push another copy
      %     Stack: N, [1 2 ... P], N
+     % Add the top two arrays in the stack , element-wise
      %     Stack: N, [N+1 N+2 ... N+P]
s     % Sum of array
      %     Stack: N, N+1+N+2+...+N+P
-     % Subtract the top two numbers
      %     Stack: N-(N+1+N+2+...+N+P)
      % Implicitly display

Forth, 36 bytes
Simple computation of n - (p*n + (p^2+p) / 2)
: f 2dup dup dup * + 2/ -rot * + - ;

Try it online

Fourier, 34 bytes
I~No~OI~P>0{1}{@P+N(N^~NO-N~ON)Oo}

Try it online!

Batch, 30 bytes
@cmd/cset/a%1-(%1*2+%2+1)*%2/2

Takes n and p as command-line parameters and prints the result without a trailing newline.

S.I.L.O.S, 80 bytes
GOTO b
lbla
n+1
m-n
i-1
GOTO d
lblb
readIO
n=i
m=n
readIO
lbld
if i a
printInt m

Try it online with test cases:
2,3
100,5
42,0
0,3
0,0

R, 17 14 bytes
N-N*P-sum(0:P)

Thanks to billywob for golfing away 3 bytes. Previous answer:
N-sum(N+if(P)1:P)

Note that 1:0 expands to the vector (1,0) so we need the if(P) condition (or to use seq_len, but that is more bytes). Without the condition, we would get the wrong output if P=0.
If P is zero, then the sum expands to sum(N+NULL), then to sum(numeric(0)), which is zero.

Not sure if this qualifies as a full program because it requires N and P to be already defined. Either way using n-n*p-sum(0:p) would be shorter anyways :)

My interpretation of the problem is that N and P are already defined (other answers seem to take this line as well). Golfing point taken though.

Unless specified otherwise submissions need to be full programs or callable functions not just snippets. Which other answers make the assumption that the variables are already defined?

I'm not a javascript expert, but it looks like the javascript solution is taking the variables as already defined. That could be my own misunderstanding though. Since N and P were named as such in the problem, I took that as "specified otherwise". If not, then we need a wrapper function(N,P){...} or N=scan();P=scan();...

@JDL the javascript entry doesn't take predefined variabled

does an R expression qualify as a "function-like construct"? Note that in R, an expression is its own class, can be evaluated directly, and is distinct from a snippet.

taking the variables as already defined, javascript would be 12 bytes n+p*(~p/2-n)

Java, 67, 63 bytes
Golfed:
int x(int n,int p){return-((p%2<1)?p*p/2+p:p/2*(p+2)+1)+n-p*n;}

Ungolfed:
int x(int n, int p)
{
    return -((p%2<1) ? p*p/2+p : p/2 * (p+2) + 1) + n - p*n;
}

Basically I did some math on the formula. The n - p*n part takes care of the all n's in the formula. Then I used a super fun property of summing together linearly increasing set of integers (arithmetic series): I used the sum of first and last integer and then multiply it by set.length / 2 (I also check for the parity and handle it appropriately).
Try it: https://ideone.com/DEd85A

You can remove the space between int n,int p to save a byte. Also, you can change the p%2==0 to p%2<1 to save another byte. -- I wasn't aware you had already posted a Java answer when I posted my shorter variant with for-loop. I like your mathematical formula, though, so +1 from me. :)

Great formula! Using p%2>0 and switching the order in the ternary you can save a character.

Oh and also p/2 *(p+2) is equal to p*p/2+p

Hehe great improvements :) actually this formula comes from a funny anecdote :)
@KevinCruijssen nice answer, definitely better than mine :) +1

Java 7, 43 40 bytes
int c(int n,int p){return n-p*n+p*~p/2;}

Java 8, 19 bytes
(n,p)->n-p*n+p*~p/2

Shamelessly stolen from @JonathanAllan's amazing Python 2 formula.
Original answer (61 60 bytes):
int c(int n,int p){int r=n,i=1;for(;i<p;r-=n+++i);return r;}

Ungolfed & test cases:
Try it here.
class M{
  static int c(int n, int p){
    return n - p*n + p*~p / 2;
  }

  public static void main(String[] a){
    System.out.println(c(2, 3));
    System.out.println(c(100, 5));
    System.out.println(c(42, 0));
    System.out.println(c(0, 3));
    System.out.println(c(0, 0));
  }
}

Output:
-10
-415
42
-6
0

What about this requires Java 7?

@mbomb007 int c(int n,int p){...}. If it would have been Java 8 (or 9) it could have been (n,p)->n-p*n+p*~p/2 (19 bytes)

Then do that to save those bytes.

PHP, 33 Bytes
$n-=$n*$p+array_sum(range(0,$p));

I think you need to use <?php or short <? for PHP-Code. Please edit your answer.

http://php.net/manual/de/features.commandline.usage.php not from the command line

Sorry, forget what said. I have seen many answers with this, and therefore thought, that there is a rule for that, which is not the case. There should be one, to avoid discussions like this one.

Jelly, 7 bytes
RS+×_×-

Arguments are P, N
Test it on TryItOnline
How?
RS+×_×-  - takes two arguments: P, N
R        - range(P): [1,2,3, ... ,P]
 S       - sum: 1+2+3+ ... +P
   ×     - multiply: P*N
  +      - add: 1+2+3+ ... +P + P*N
    _    - subtract: 1+2+3+ ... +P + P*N - N
      -  - -1
     ×   - multiply: (1+2+3+ ... +P + P*N - N)*-1
                   = -1-2-3- ... -P - P*N + N
                   = N - (N+1) - (N+2) - (N+3) - ... - (N+P)

Pyth - 6 bytes
-F}Q+E

Test Suite.

Labyrinth, 15 bytes
?:?:}*-{:)*#/-!

or
??:}`)*{:)*#/-!

Uses the closed form solution n - n*P - P*(P+1)/2.

php, 38 bytes
<?=$argv[1]*(1-$a=$argv[2])-$a++*$a/2;

Burlesque, 12 bytes
perz?+{.-}r[

Try it online!
pe     #Read input as P, N
rz     #Range (0,N)
?+     #Add P to each
{.-}r[ #Reduce via subtraction

Vyxal, 4 bytes
+ṡƒ-

Try it Online!
Port of Jelly answer.
How?
+ṡƒ-
+ṡ   # Inclusive range [a, a + b]
  ƒ- # Reduce by subtraction

TI-Basic, 17 bytes
Prompt N,P
N-NP-.5(P²+P

Alternatives:
Prompt N,P
N-P(P/2+.5+N

Prompt N,P
N-NP-.5P(P+1

Prompt N,P
N-.5P(2N+P+1

Pyth, 11 bytes
Ms+Gm_+GdSH

A function g that takes input of n and p via argument and prints the result. It can be called in the form gn p.
Try it online
How it works
Ms+Gm_+GdSH  Function g. Inputs: G, H
M            g=lambda G,H:
         SH   1-indexed range, yielding [1, 2, 3, ..., H]
    m_+Gd     Map lambda d:-(G+d) over the above, yielding [-(G+1), -(G+2), -(G+3),
              ..., -(G+H)]
  +G          Add G to the above, yielding [G, -(G+1), -(G+2), -(G+3), ..., -(G+H)]
 s            Reduce on addition with base case 0, yielding G-(G+1)-(G+2)-(G+3)...
              -(G+H)
              Implicitly print

C89, 38, 35, 33 bytes
h(n,p,r)int*r;{*r=n-p++*(n+p/2);}

Test it on Coliru.

Maple, 19 bytes
n-sum(i,i=n+1..n+p)

Usage:
> f:=(n,p)->n-sum(i,i=n+1..n+p);
> f(2, 3);
  -10
> f(100,5);
  -415
> f(42,0);
  42

Perl 6, 21 bytes
{$^n-[+] $n^..$n+$^p}

Explanation:
# bare block lambda with two placeholder parameters ｢$n｣ and ｢$p｣
{
  $^n -
      # reduce using ｢&infix:<+>｣
      [+]
          # a Range that excludes ｢$n｣ and has ｢$p｣ values after it
          $n ^.. ($n + $^p)
}

Java 8, 25 bytes
(n,p)->n-(p*n+p*(p+1)/2);

Ungolfed test program
public static void main(String[] args) {

    BiFunction<Integer, Integer, Integer> f = (n, p) -> n - (p * n + p * (p + 1) / 2);
    System.out.println(f.apply(100, 5));
}

Scala, 41 bytes
def?(n:Int,p:Int)=n-(1 to p).map{n+_}.sum

Testing code:
println(?(2,3))
println(?(100,5))
println(?(42,0))
println(?(0,3))
println(?(0,0))

// Output
-10
-415
42
-6
0

Clojure/Clojurescript, 30 bytes
#(reduce -(range %(+ 1 % %2)))

The straightforward approach is shorter than the mathematically clever ones.

Julia: 17-18 bytes (13 as program with terminal inputs)
As per suggestion in comments that "function or program" form is needed:

as function: 17 characters, 18 bytes if you count ∘ as multibyte
n∘r=2n-sum(n:n+r)

usage: 5∘3 outputs -16
as program, passed initial parameters from terminal: 13 bytes:
2n-sum(n:n+r)

usage: julia -E 'n,r=5,3;include("codegolf.jl")'

Nice solution, but all submissions need to be callable functions or full programs not just snippets. I think the shortest fix would be to define it as a binary operator by prepending n\r=.

Thanks, I edited to that effect. \   is a bad choice because it needs to be explicitly imported, although I suppose this is the kind of thing that could fall under a gray area. (but if I were allowed to do that, I might as well say Σ(n:n+r) where Σ is an alias for sum :p ). An "initialise and call" from the terminal feels like a bit of a cheat, but again it's a gray area, since other submissions do this without problem since it's considered the only way to call the program.

Excel, 20 bytes
Subtract the next B1 integers from A1:
=A1-B1*(A1+(B1+1)/2)

GolfScript, 11 bytes
Formula stolen elsewhere...
~1$1$)2/+*-

Try it online!
Explanation
This just boils down to
A-B*(A+(B+1)/2)

Converted to postfix.
GolfScript, 15 bytes
~),{1$+}%{-}*\;

Try it online!
Explanation
~               # Evaluate the input
 ),             # Generate inclusive range
   {1$+}%       # Add each item by the other input
         {-}*   # Reduce by difference
             \; # Discard the extra other input

Keg, -hr, 8 6 bytes
+ɧ^∑$-

Try it online!
No formula, just a for loop!

W d,  6 4 bytes
Surprised to see that it's not short at all. (Although it at least ties with Jelly...)
7▄i←

Explanation
Uncompressed:
+.@-R
+     % Generate b+a
 .    % Generate range(a,b+a)
  @-R % Reduce via subtraction

Japt, 5 bytes
ôV r-

Try it
ôV r-     :Implicit input of integers U=N & V=P
ôV        :Range [U,U+V]
   r-     :Reduce by subtraction

Demsos, 20 bytes
f(n,p)=n-p(p/2+.5+n)

Other 20-byters:
f(n,p)=n-pn-p(p+1)/2
f(n,p)=n-pp/2-.5p-np
f(n,p)=n-.5p(2n+p+1)
f(n,p)=n-pn-.5pp-.5p

Try it on Desmos!
With the sum function, it's 27 bytes:
f(n,p)=n-∑_{x=n+1}^{n+p}x

K (ngn/k), 10 bytes
{-/x+!y+1}

Try it online!
Quick.

Python 3, 43 bytes
lambda n,p:n-sum([n+i+1 for i in range(p)])

Try it online!
Explanation:
lambda n,p:                                  # Lambda header
                 [n+i+1 for i in range(p)]   # Next P numbers
             sum(                          ) # Sum each number
           n-                                # Subtract from N for final result

My initial answer was 46 bytes, then i shaved off 2 bytes by changing the comprehension, then 1 more byte was shaved off by turning -s into +s and vice versa.

I think you can remove the brackets

Ly, 14 bytes
n0ns-0Rl0I*-&+

Try it online!
This relies on the fact that for X=starting number and Y=iterator, the answer is:
X - (X*Y) - sum([1..Y])
It uses the R command to generate the range of negative numbers.
n              - read starting number onto the stack
 0n            - push "0", read iteration count onto the stack
   s           - save iteration count
    -          - convert to negative number
     0         - push "0" to set ending number
      R        - generate a range of negative numbers
       l       - load the iterator count
        0I     - copy the starting number
          *    - multiple to get base number common to all decrements
           -   - convert to negative (relies on "0" from range)
            &+ - sum the stack, answer prints automatically

APL (Dyalog Unicode), 12 bytes
⊣-(+/(⍳⊢)+⊣)

Try it online!

⊣-1⊥+∘⍳ uses 1⊥ to sum and rearranges (⍳⊢)+⊣ to +∘⍳

@rak1507 at first I thought {⍺-+/⍺+⍳⍵}, but yours seems smaller


text:
The world is like a Mirror: smile and it'll sɯıןǝ qɐɔʞ
Input:
A string only containing the following characters:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! (space at the end) and two special characters (_ and |)
Output:
Mirror the text based on the position(s) of the _ and |.
_ mirrors horizontally and | mirrors vertically.
Mirroring process

The first _ indicates the start of the mirroring of that substring, the second _ the end.
If just one _ is present, you can continue on until the end of the string.
If more then two _ are present, the same process repeats.
There can only be one | in the string, and this reversed the first substring and removes the second substring.

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! (space at the end) will be converted to ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ (space at the end) when it is mirrored by _ (click the link for the unicode values - requires unicode v8.0+).
Example input 1: _Will I be mirrored?!
Output 1: Mıll I qǝ ɯıɹɹoɹǝp¿¡
Example input 2: Wi_ll I be mi_rrored?!
Output 2: Will I qǝ ɯırrored?!

When it is mirrored by | we simply reverse the substring from 0 to index-of-|.
Example input 1: Will I be mirror|ed?!
Output 1: Will I be mirrorrorrim eb I lliW
Both mirrors (_ and |) can be present in the string.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:
_Will I be mirrored?!                          ->   Mıll I qǝ ɯıɹɹoɹǝp¿¡
Wi_ll I be mi_rrored?!                         ->   Will I qǝ ɯırrored?!
Will I be mirror|ed?!                          ->   Will I be mirrorrorrim eb I lliW
This_ is a test_ cont_aining bo|t_h mirrors.   ->   This ıs ɐ ʇǝsʇ contɐıuıuɓ qooq ɓuıuıɐtnoc ʇsǝʇ ɐ sı sihT
0_1_2_3_4_5|_6_7_8_9                           ->   0⇂2Ɛ4ϛϛ4Ɛ2⇂0

feature request -- Change the title to "The world is like a Mirror: smile and it'll sɯıןǝ qɐɔʞ" ;-)

@TimmyD ᗡouǝ ;)

@TimmyD In my country mirrors work like this: "smile ɘlimƨ", not "smile sɯıןǝ" :)  The title should be "The world is like a Mirror: smile and it'll ɘlimƨ back"

In the first line you should probably mention that spaces can appear in the input, too.

Pyth - 174 bytes
Can prolly save with base compression or something cuz of unicode(this is only 119 chars)
u?qH\_&=hZG+G@@c2K+s+rB;1UT".?! ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ "ZxKH?}\|zs_Bhcz\|zk

Test Suite.

JavaScript (ES6), 308 bytes
s=>s[r='replace'](/_.*?(_|$)/g,m=>m[r](/./g,c=>'| ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡'['| abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?!B'.indexOf(c)]||''))[r](/(.*)\|.*/,(m,t)=>t+[...t].reverse().join``)

Test

var solution =

s=>
  s[r='replace'](/_.*?(_|$)/g,m=>
    m[r](/./g,c=>
      '| ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡'
        ['| abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?!B'
          .indexOf(c)]||''
    )
  )
  [r](/(.*)\|.*/,(m,t)=>t+[...t].reverse().join``)

var testCases = [
  '_Will I be mirrored?!',
  'Wi_ll I be mi_rrored?!',
  'Will I be mirror|ed?!',
  'This_ is a test_ cont_aining bo|t_h mirrors.',
  '0_1_2_3_4_5|_6_7_8_9'
];
tests.textContent = testCases.map((c) => c + '   =>   ' + solution(c)).join('\n');
<input type="text" oninput="result.textContent=solution(this.value)" value="This_ is a test_ cont_aining bo|t_h mirrors." />

PERL 243
242 + 1 for -p
$h=(split'\|',$_)[0];$_=$h.reverse$h if($_=~/\|/);for$b(split'_',$_){$b=~y/A-Za-z0-9.?!/ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡/ if($f);$\.=$b;$f=!$f;}$_='';

Ungolfed:
$reverse = (split('\|', $_))[0];
$_ = $reverse . reverse($reverse) if($_=~/\|/);

for $block (split '_', $_) {
    $block =~ y/A-Za-z0-9.?!/ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡/ if($flip);
    $\.=$block;
    $flip=!$flip;
}
$_='';

Example:
$ perl -p mirror.pl <<<'Will I be mirror|ed?!'
Will I be mirrorrorrim eb I lliW

I'm 99% sure this works, but most of the upsidedown characters don't display correctly on my system. I tested it by using a different range of character, e.g. .?! -> %^& instead of .?! -> ˙¿¡.

R, 362 362 342 339 bytes
Edit 1: I found a bug in my original (failed if there were no _ in input), fixed it, golfed some more, and I'm back at 362 where I started!
Edit 2: Golfed away 20 byes by replacing "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! " with paste(c(letters,LETTERS,0:9,".?! "),collapse="")
Edit 3: Removing some extra whitespace shaves off another 3 bytes.
p=strsplit
l=length
i=p(readline(),"_")[[1]]
if(l(i)-1)i[v]=chartr(paste(c(letters,LETTERS,0:9,".?! "),collapse=""),"ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ",i[v<-seq(2,l(i),2)])
i=unlist(p(i,""))
if(l(b<-which(i=="|")-1))i[1:b+b]=rev(i[1:b])
cat(i,sep="")

Explained:
p=strsplit               # Aliases for common functions
l=length
i=p(readline(),"_")[[1]] # Read input, split by _s. Now every even-indexed substring is one that we must
                         # mirror vertically. (R indexes from 1.)
if(l(i)-1)               # If there are any _s,
  i[v]=chartr("paste(c(letters,LETTERS,0:9,".?! "),collapse=""),
  "ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ",
  i[v<-seq(2, l(i), 2)]
)                 # Flip the characters in the vertically-mirrored substrings
i=unlist(p(i,"")) # Split each substring into a single character object
if(l(b<-which(i=="|")-1)) # If there is a |,
  i[1:b+b]=rev(i[1:b])    # insert the reversed characters at the end of the list
cat(i,sep="")             # Print output

Javascript (ES5), 344 340 bytes
function mirror(a){d=[];~a.indexOf("|")&&(a=a.split("|")[0]+a.split("|")[0].split("").reverse().join(""));for(var c=!1,b=0;b<a.length;++b)"_"==a[b]&&(c=!c),d[b]=c?"zʎxʍʌnʇsɹbdouɯlʞɾᴉɥɓɟǝpɔqɐZ⅄XMΛ∩⊥SᴚΌԀONW⅂⋊ſIH⅁ℲƎᗡƆᗺⱯ068ㄥ95߈Ɛᘔ⇂˙¿¡ "["zyxwvutsrqponmlkijhgfedcbaZYXWVUTSRQPNOMLKIJHGFEDCBA0987654321.?! ".indexOf(a[b])]:a[b];return d.join("")}

Ungolfed:
function mirror_u(s){return "zʎxʍʌnʇsɹbdouɯlʞɾᴉɥɓɟǝpɔqɐZ⅄XMΛ∩⊥SᴚΌԀONW⅂⋊ſIH⅁ℲƎᗡƆᗺⱯ068ㄥ95߈Ɛᘔ⇂˙¿¡ "["zyxwvutsrqponmlkijhgfedcbaZYXWVUTSRQPNOMLKIJHGFEDCBA0987654321.?! ".indexOf(s)]};

function mirror(str){var b=[];
if(~str.indexOf("|"))str=str.split("|")[0]+str.split("|")[0].split("").reverse().join("");
    var is_mirrored=false;
    for(var i=0;i<str.length;++i){
        if(str[i]=="_")is_mirrored=!is_mirrored;
        if(is_mirrored){b[i]=mirror_u(str[i])}else{b[i]=str[i]};
    }
    return b.join("");
}

EDIT: Longer working code, that is mirrored | by character 341.
function mirror(a){d=[];~a.indexOf("|")&&(a=a.split("|")[0]+a.split("|")[0].split("").reverse().join(""));for(var c=!1,b=0;b<a.length;++b)"_"==a[b]&&(c=!c),d[b]=c?"zʎxʍʌnʇsɹbdouɯlʞɾᴉɥɓɟǝpɔqɐZ⅄XMΛ∩⊥SᴚΌԀONW⅂⋊ſIH⅁ℲƎᗡƆᗺⱯ068ㄥ95߈Ɛᘔ⇂˙¿¡ "["zyxwvutsrqponmlkijhgfedcbaZYXWVUTSRQPNOMLKIJHGFEDCBA0987654321.?! ".indexOf(a[b])]:a[b];return d.join("")}//})""(nioj.d nruter;]b[a:])]b[a(fOxedni." !?.1234567890ABCDEFGHJIKLMONPQRSTUVWXYZabcdefghjiklmnopqrstuvwxyz"[" ¡¿˙⇂ᘔƐ߈59ㄥ860ⱯᗺƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Zɐqɔpǝɟɓɥᴉɾʞlɯuodbɹsʇnʌʍxʎz"?c=]b[d,)c!=c(&&]b[a=="_")b++;htgnel.a<b;0=b,1!=c rav(rof;))""(nioj.)(esrever.)""(tilps.]0[)"|"(tilps.a+]0[)"|"(tilps.a=a(&&)"|"(fOxedni.a~;][=d{)a(rorrim noitcnuf

The `` character takes up two UTF-16 code units, but you don't seem to be taking this into account. Does the W in the first test case come out correctly?

The characters are all UTF-8. All test cases give the correct output.

Oh, it seems you're using code point U+15FA for the upside-down B. The one in the challenge is code point U+10412.

I used the characters from the linked wikipedia page, I just copied them into my editor.

Retina, 176 bytes
\|.+
:$`
O$^`:|(?!^)\G.

:

T`w.?!`_0⇂ᘔƐ߈ϛ9ㄥ86∀:ƆᗡƎℲ⅁\HIſ⋊⅂WN\OԀΌᴚS⊥∩ΛMX⅄Zɐqɔ\pǝɟɓɥıɾʞ\lɯu\o\dbɹsʇnʌʍxʎz˙¿¡`_[^_]*_?
:

Try it online! (The first line enables a linefeed-separated test suite.)

Java 7, 504 502 bytes
import java.util.*;String c(String s){Map m=new HashMap();int i=0,j;while(i<67)m.put("abcdefghijklmnopqrstuvwxyzABBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! ".charAt(i),"ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ".charAt(i++));String q=s.split("\\|")[0],z[]=(q+(s.equals(q)?"":new StringBuffer(q).reverse()+"")).split("_"),r="";for(i=-1;++i<z.length;){q="";for(char c:z[i].toCharArray())q+=m.get(c);r+=i%2<1?z[i]:q;}return r;}

Of course I'll have to answer my own challenge again. And.. it's long.. xD
Ungolfed & test cases:
Try it here.
import java.util.*;
class M{
  static String c(String s){
    Map m = new HashMap();
    int i = 0,
        j;
    while(i < 67){
      m.put("abcdefghijklmnopqrstuvwxyzABBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! ".charAt(i),
          "ɐqɔpǝɟɓɥıɾʞlɯuodbɹsʇnʌʍxʎz∀ƆᗡƎℲ⅁HIſ⋊⅂WNOԀΌᴚS⊥∩ΛMX⅄Z0⇂ᘔƐ߈ϛ9ㄥ86˙¿¡ ".charAt(i++));
    }
    String q = s.split("\\|")[0],
           z[] = (q + (s.equals(q)
                        ? ""
                        : new StringBuffer(q).reverse() + "")
                 ).split("_"),
           r = "";
    for(i = -1; ++i < z.length;){
      q = "";
      for(char c : z[i].toCharArray()){
        q += m.get(c);
      }
      r += i%2 < 1
            ? z[i]
            : q;
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("_Will I be mirrored?!"));
    System.out.println(c("Wi_ll I be mi_rrored?!"));
    System.out.println(c("Will I be mirror|ed?!"));
    System.out.println(c("This_ is a test_ cont_aining bo|t_h mirrors."));
    System.out.println(c("0_1_2_3_4_5|_6_7_8_9"));
  }
}

Output:
Mıll I qǝ ɯıɹɹoɹǝp¿¡
Will I qǝ ɯırrored?!
Will I be mirrorrorrim eb I lliW
This ıs ɐ ʇǝsʇ contɐıuıuɓ qooq ɓuıuıɐtnoc ʇsǝʇ ɐ sı sihT
0⇂2Ɛ4ϛϛ4Ɛ2⇂0

Suggest dropping the j variable.


text:
Convert string to number
Task
The task is to convert a string to a number. It must accept the string via stdin and output the number via stdout.
You convert a string to a number by replacing each letter of the string by its index (mind that you don't need to replace it with the index, that's just an example. You are allowed to replace it with anything you like, as long as the output is decodable) in the following list (you don't need to convert any other characters):
Characters: abcdefghijklmnopqrstuvwxyz1234567890 (the input will only either be lowercase letters, or/and a number).
Additionally, you must make the output decodable, so if you have output 0 for input a, and somebody inputs bl, then the output will be something like 111. This is not decodable since the program might interpret it as bbb or lb or bl. You might make it decodable by making sure the the number that each character outputs always has a length of 2. Any other way of making sure your output is decodable is allowed, but you must explain how one would decode the output in your answer.
Standard loopholes are not allowed. This is code golf, so shortest code wins!
EDIT: By decodable, just to clarify, I mean that you can convert the output back into the input. Your program doesn't need to feature decoding features, only encoding.
Examples
Input    Output
a        00
ab       0001
1        26

Welcome to PPCG! This is not a bad challenge, especially as your first, but I suggest using the Sandbox to get feedback on your future challenges before you post them.

You much convert a string to a number by replacing each letter of the string by its index (mind that you don't need to replace it with the index, that's just an example. You are allowed to replace it with anything you like, as long as the output is decodable) What exactly does that mean? Are we suppose to replace each letter of the string by its index or not?

You don't need to, no. Anything that is decodable works.

"It must accept the string via stdin and output the number via stdout." Any reason for this restriction?  Commonly any I/O methods appropriate to the given language is acceptable, which would include e.g. command-line args in many cases.

what's stopping us just doing base36 conversion?

Can the input be empty?

@muddyfish I think the fact that a string prepended with zeros returns the same output as the string - e.g. int("abc",36) == int("0abc",36)

Pyth, 1 byte
C

Try it here!
Converts a string to a number
Decode with the following Python code:
def decode(x):
    rest, char = divmod(x, 256)
    if rest < 256: return chr(rest)+chr(char)
    return decode(rest)+chr(char)

This basically base-256 converts the string.

It doesn't appear to be against the rules

I'm not complaining :)

The decoding (as presented here) doesn't work for smaller inputs -- for example, input "hi" yields 26729, but input 26729 yields 桩

It's still probably possible to decode - pyth just seems to have a bug?

@muddyfish I think the problem is that if the integer is in the UTF-8 range, C converts to the character with that code point. Since the maximum UTF-8 code point is 1114111, any encoding that results in an integer less than or equal that number may fail upon decoding. I came up with jkm-d38CM for encoding and sCMm+d38sMcz2 for decoding, using the same idea as the PowerShell answer.

@muddyfish TheBikingViking has it right. Encoding with C should be fine, you just need a more-explicit base-256-to-string decoding algorithm than simply C.

I'm not going to count this as correct because "ab" gets 24930, but 24930 gets 慢.

@Okx it is possible to decode those values, it just won't work with that function - if you want, I could write something that decodes it

@muddyfish alright, but alternatively you can edit your answer to explain how you would decode it.

@Okx that good?

C 69 61 52 62 Bytes
i;char v[99];main(){gets(v);while(v[i])printf("%.3d",v[i++]);}

Now taking input from stdin, each character code is 3 digits.
a.exe thisisatest
116104105115105115097116101115116

I think you have to take the input through stdin, not through input arguments.

How does the output look for input of 1? I think it will be 49 i.e. only 2 chars long, which makes decoding harder

Good point I should output 3 digits for each character

I think you can do some as 2 chars and others as 3. If it starts with 1 (d-z) it'll be 3 chars, otherwise it's 2 chars (0-9,a-c).

Ruby, 97 37 44 bytes
lambda{|s|s.chars.map{|c|c.upcase.ord}.join}

Take the ordinal of each character in s converted to uppercase (to ensure 2 chars per number for ordinals)

PowerShell v2+, 42 32 bytes
-join([char[]]$args[0]|%{$_-38})

Takes input $args[0], treats it as a char-array, sends it into a loop, and each loop cast the char as an int (implicit) minus 38. Those are all encapsulated in parens and -joined into one string. That string is left on the pipeline and printing is implicit.
The lowest ASCII point of abcdefghijklmnopqrstuvwxyz0123456789 is 0, with 48. The highest is z with 122. By subtracting 38 from each code point, we're guaranteed distinct two-digit number for each input character.
Examples
PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'ab'
5960

PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'ppcg'
74746165

PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'error404'
6376767376141014

PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'abcdefghijklmnopqrstuvwxyz0123456789'
596061626364656667686970717273747576777879808182838410111213141516171819

Interesting. I was expecting an answer similar to this.

Bash + coreutils, 20
od -vbAn|tr -d ' \n'

The index of each character in the ASCII table is given in octal by od, which ensures each octal number for each input character is exactly 3 digits long (padded with leading zeros as necessary).  tr removes the whitespace.
Decoding would be performed by grouping output into groups of 3 digits and then conversion from octal back to ASCII.

S.I.L.O.S, 63 60 55 bytes
loadLine
b=256
lbla
c=get b
printIntNoLine c
b+1
if c a

Prints ASCII value.
Try it online!

Python 3, 86 bytes
I appear to have misunderstood what the question allows... Either way, this exactly matches the test cases given.
print(''.join('%02d'%'abcdefghijklmnopqrstuvwxyz0123456789'.index(i)for i in input()))

Ideone it!

GS2, 1 byte
Byte 14, which, in CP437, is ♫.
Try it online!
Decoding is possible: get all matches of the regex (1..|..) and map them from decimal ASCII code points to ASCII characters.

Surely 1?.. would be a golfier regex?

Decoding isn't possible, because 'e0' gets 10148. Attempting to decode that can lead to a number of solutions (10 & 148 or 101 & 48).

Character 10 (a newline) is not in abcdefghijklmnopqrstuvwxyz1234567890.