text:
What would your reputation be without the rep cap?
In this challenge, you will calculate what your reputation would be, if the reputation cap didn't exist on PPCG.
Everyone can access the rawdata for reputation changes on the adress: codegolf.stackexchange.com/reputation.
The raw data follows a setup like this (these are the first few lines of my version of the page.
total votes: 2955
-- bonuses   (100)
 2     37663 (10)
-- 2014-09-11 rep +110  = 111
 2     41751 (10)
-- 2014-11-23 rep +10   = 121
 2     41751 (10)
 2     41751 (10)
-- 2014-11-24 rep +20   = 141

The first line is irrelevant for this challenge (it shows the total number of votes you have received on all your answers and questions).
The second line shows the "Association bonus". If you don't have the bonus then that line will not be there at all.
After these two (or one, if no bonus) lines, you'll have a list of reputation changes per question, along with a summary of all the rep gained/lost on each day. You'll also get a list of the total reputation you have at the end of that day. Only days where your reputation changed are shown in this list.
There are identifiers in the beginning of each line (except the daily summary lines). These represent the following potential reputation change reasons:
1 : Accept (+2 if you accept, +15 if your answer is accepted)
2 : Upvote (+5 for question, +10 for answer)
3 : Downvote (-1 if you downvote answer, -2 if you get downvoted)
4 : Offensive (-100)
8 : Give bounty
9 : Receive bounty
12: Spam (-100)
16: Approved edit (+2)

The missing numbers (5,6,7,10,11,13,14,15 don't affect reputation).

Your challenge is to calculate the reputation you would have, if it weren't for the reputation cap.

How you'll do this:
Save the content of codegolf.stackexchange.com/reputation as plain text locally, or some other place of your choosing (this is because you need to be logged in to access the information).
You may retrieve the data from the website directly if you prefer, although I assume that will be a lot longer.
Sum up all the positive and negative reputation changes. Votes that doesn't result in a reputation change (due to the rep cap) are shown like this
(notice the square brackets, instead of regular parentheses):
 2    106125 [0]
 2    106125 [0]
 3    106125 [-2]
 2    106088 [2]
 2    106125 [0]
 2    106088 [0]

You must include the rep you would have received if it wasn't for the cap.
Post number 106125 is a question, while 106088 is an answer.
As you can see, there's no way to tell the difference between the two using only the data given in the table. You must therefore access the website (codegolf.stackexchange.com) to check whether a post is a question or answer. You may also use the API for this.

Rules:

Everyone must be able to run your script so:

You must include all the different reputation change types, even if you haven't encountered it yourself.
The code must work even if you haven't received the Association bonus (the line won't be there if you haven't)
You may use non-free languages (Mathematica, MATLAB etc.), as long as others with a license can run the code.
You do not have to provide the raw-data, since everyone can test your code on their own version of the page (it will be interesting if you share the results though, but that's optional).

You may use the API or access the website directly. url-shorteners are not allowed.
If there are other ways to find the rep you would have without the rep cap then you can't use it. You have to use the data from the mentioned page.

Note that posts that are answers get a different extension to the url:
https://codegolf.stackexchange.com/questions/106088        // Answer: Notice the end of the url
https://codegolf.stackexchange.com/questions/106079/detect-ms-windows/106088#106088

https://codegolf.stackexchange.com/questions/106079/       // Question: Notice the end of the url
https://codegolf.stackexchange.com/questions/106079/detect-ms-windows

Output:
The output should be:
Rep w cap: 15440
Rep w/o cap: 16202

The format is optional, [15440,16202] is accepted. Rep w cap can be taken directly from the line: ** total rep 15440 :) near the bottom of the page.

This is code-golf so the shortest code in byte wins.

Related.

Rip me and my life

lol I've never hit the repcap before.

Just to clarify, your reputation with cap is the sum your total rep, and the reputation changes inside the square brackets?

Perl 5 (+ curl), 209 +1 (-n flag) = 210 bytes
if(/([0-9]+)\s*([0-9]+) \[([0-9]*)/){$_=`curl https://codegolf.stackexchange.com/a/$2`;@p=(2,5,-1);$p[15]=2;@s=(13,5,-1);$x=$1;$r+=($p[--$x]//-100)-$3;$r+=$s[$x]if/#/;};$t=$1 if/([0-9]+) :/;END{say$t,$",$r+$t}

Abuses the fact that the url for an answer has a # in it. Can add a -s flag after curl if you don't like stderr being flooded with progress bars. I would appreciate someone with a more varied reputation page testing it- I can't be sure I didn't miss anything.
Mine is 421 and would be 451, by the way.

I've never ever used Perl before, and I can't see where you get the rawdata from. Where do I put the rawdata if I want to test this? Note: I'm using Strawberry on Windows 10. I don't have Unix or OS X. And how would I call this?

@Stewie Griffin It reads the raw data from stdin. The code is a one-liner, and should be executed something like perl -nE 'code' < filename. You may have to do some different quoting and escaping of things on Windows, I'm not very familiar with the environment there.

Small optimisation: you can remove the https:// if you pass the -L flag to curl, allowing it to follow the 301 redirect

@Markasoftware That will follow the multiple redirects to the actual page, though, right? As it is, my code parses the 301 redirect from https://codegolf.stackexchange.com/a/$2 rather than the page itself.

I get Search pattern not terminated at -e line 1. when I try this. I simply paste the entire code using what you wrote in the comment (perl -nE ..), while having the file saved in the current working directory. Any idea why that might be?

@StewieGriffin It's probably an issue with characters that the shell is interpreting before perl gets a chance. On Linux you can avoid this surrounding the code with single quotes. I think it's double quotes on Windows? But in that case you should change the $" in the last term to ' ' to avoid conflict with the shell. You could also try putting it in a script with an extra line use feature qw(say); at the beginning and then running it like perl -n scriptname.pl < rawdata.txt.

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:
When life gives you lemons, make lemonade
Challenge
You will be given an input string, anywhere the word "Lemon" is found it should be converted to "Lemonade" but the a, d, and e must be borrowed from somewhere else in the sentence.

Example
Example Input:

I found a lemon when I was a kid

Example Output:

I foun a lemonade whn I was  kid

The Lemonade was created by stealing the following superscript letters from the original

I found a lemonade when I was a kid

This is just one possible output example, the "e", "d", and "a", could have been taken from anywhere (except for from the word lemon of course)

Comments
•If there are not enough e, a, or ds you must output what was do-able with the letters given. For example the input bdblemon would output bblemond
•The lemon text might not always be standalone (space on each side). For example you may have the word lemons somewhere in the input and the output should be lemonades
•The input may contain any number of lemons, even 0 lemons (in which case the output would be identical to the input)
•You can make your lemonade with uppercase and lowercase letters, for example leMon could become leMonade, and the ade borrowed can be any case (so it could also have become leMonADe).The case of the letter you borrowed must remain what it was when you borrowed it.(Example input -> output, he hAD lemOn -> h h lemOnADe)
•Does not have to be a full program, a function alone is fine.
•You may assume input will be only the CP437 Character Set

Code Golf
This is code-golf, so the lowest number of bytes wins!

Pseudo-TestCases
*Note: For any given input there might be multiple possible outputs so your program may not output exactly as these test cases do, this is more just so people can understand the logic:

Input: EpaD leMons
  Output: p LeMonaDEs
Input: hello world
  Output: hello world
Input: lemon lemon
  Output: lemon lemon
  *(The e, a, d letters should never be taken from another "Lemon")
Input: HE HAD lemonade
  Output: H H lemonADEade
Input: Do you like lemons? You hAd me at lemon!
  Output: o you lik lemonADes? You h m t lemonade!
Input: AE lemon
  Output:  lemonAE
Input: 55bad lemon
  Output: 55b lemonad

JavaScript (ES6), 159 157 155 162 bytes
Edit: +7 bytes to "output what was do-able with the letters given" rather than throwing out an error

A recursive function that returns the modified string.
f=(s,a=s.split(/(lemon)/i),n=(a.length-1)*1.5)=>n?f(n,a.map((s,i)=>i&1|!n||(a[i]=s.replace([/a/i,/e/i,/d/i][n%3],c=>(a[--n/3<<1|1]+=c,''))))&&a,n-(n==s)):a.join``

How it works
The expression s.split(/(lemon)/i) splits the input string on lemon but preserves the capture groups in the result.
For instance, "foo lemon bar LEMON baz".split(/(lemon)/i) will produce the array [ 'foo ', 'lemon', ' bar ', 'LEMON', ' baz' ].
We recursively iterate on this array, extracting the characters a, d and e or their uppercase counterparts from the entries located at an even position, and appending them to the entries located at an odd position.
Commented
f = (                                   // given:
  s,                                    //   s = input string or previous value of 'n'
  a = s.split(/(lemon)/i),              //   a = split array, as described above
  n = (a.length - 1) * 1.5              //   n = total number of characters to be found
) =>                                    //
  n ?                                   // if there's still at least one character to find:
    f(                                  //   do a recursive call with:
      n,                                //     1) the current value of 'n'
      a.map((s, i) =>                   //     2) an updated version of 'a', where
        i & 1 | !n || (                 //       for even positions:
          a[i] = s.replace(             //         we look for the next character
            [/a/i, /e/i, /d/i][n % 3],  //           'a', 'e' or 'd' (case insensitive)
            c => (                      //           append it to
              a[--n / 3 << 1 | 1] += c, //           one of the entries at an odd position
              ''                        //           and remove it from the original entry
            )                           //           end of replace() callback
          )                             //         end of replace()
        )                               //       end of position condition
      ) && a,                           //     end of map() -> yield the updated 'a'
      n -                               //     3) the updated value of 'n', skipping the
      (n == s)                          //        current character if not found at all
    )                                   //   end of recursive call
  :                                     // else:
    a.join``                            //   success: join 'a' and return it

Demo

f=(s,a=s.split(/(lemon)/i),n=(a.length-1)*1.5)=>n?f(n,a.map((s,i)=>i&1|!n||(a[i]=s.replace([/a/i,/e/i,/d/i][n%3],c=>(a[--n/3<<1|1]+=c,''))))&&a,n-(n==s)):a.join``

console.log(f("I found a lemon when I was a kid"))
console.log(f("I found a lemon when I was a kid. I found another lemon when I was older."))
console.log(f("bdblemon"))
console.log(f("he hAD lemOn"))

Throwing a recursion-error doesn't seem to comply to the first rule ("If there are not enough e, a, or ds you must output what was do-able with the letters given. For example the input bdblemon would output bblemond")?

@KevinCruijssen Hmm, you're right. I was almost certain that throwing an error was initially allowed. Was it an edit during the grace period of the initial post? (Either that or I dreamed it.) Anyway, I'll try to fix that. Thanks for noticing.

I looked back in the history before making my comment in case it was indeed edited out. You could be right it might have been edited in the first 5 minutes, but no idea how to check that. And no problem, your answer is still pretty impressive, so I'll +1 it in advance. I have no doubt you'll be able to fix the issue (hopefully without causing to much added bytes).

@KevinCruijssen That's fixed at the cost of 7 bytes for now.

@Arnauld Yes sorry I edited that out within the first 2 minutes of the post maybe haha, my apologies

@AlbertRenshaw No worries. At least, I'm not crazy. :-p

CJam, 130 bytes
LqY5m*{"lemon"_eu}%3/:z{~?}f%{_@\/_:,[{1$+}*]);@f{[\]}@+\1a*}/\{1
=}$0f=\1$,{"ade"{__C#)\Ceu#)|(\0+We\)@_N=@+N\t\}fC}fN0a/L*1a/\.{}

This is split across two lines for clarity; the newline is not counted.
Pseudocode:
FLAG_1 = object()
FLAG_2 = object()
lemon_instances = [] # CJam: L
input_chars = list(all_input()) # CJam: q
lemons = [
    "LEMON", "LEMOn", "LEMoN", "LEMon", "LEmON", "LEmOn", "LEmoN", "LEmon",
    "LeMON", "LeMOn", "LeMoN", "LeMon", "LemON", "LemOn", "LemoN", "Lemon",
    "lEMON", "lEMOn", "lEMoN", "lEMon", "lEmON", "lEmOn", "lEmoN", "lEmon",
    "leMON", "leMOn", "leMoN", "leMon", "lemON", "lemOn", "lemoN", "lemon"
] # CJam: Y5m*{"lemon"_eu}%3/:z{~?}f%
for i in lemons: # CJam: { ... }/
    temp = input_chars.split(i) # CJam: _@\/
    lengths = temp.map(len) # CJam: _:,
    # Here, accum turns an array like [1,2,3] into [1,3,6].
    indices = accum(lengths) # CJam: [{1$+}*]
    indices.pop() # CJam: );
    temp2 = zip(temp, indices) # CJam: @f{[\]}
    lemon_instances = temp2 + lemon_instances # CJam: @+
    input_chars = join_array(temp, FLAG_1) # CJam: 1a*
lemon_instances.sort(key=lambda x: x[1]) # CJam: {1=}$
lemon_instances = [i[0] for i in lemon_instances] # CJam: 0f=
for i in range(len(lemon_instances)): # CJam: \1$,{...}fN
    for c in "ade": # CJam: "ade"{...}fC
        # list_index returns -1 if not found
        lower = list_index(input_chars, c)+1 # CJam: __C#)
        upper = list_index(input_chars, upper(c))+1 # CJam: \Ceu#)
        char_index = (lower or upper) - 1 # CJam: |(
        input_chars.append(FLAG_2) # CJam: \0+
        # -1 refers to the last element in the list
        swap_list_elements(input_chars, char_index, -1) # CJam: e\
        extracted = input_chars.pop() # CJam: )
        lemon_instances[i] += extracted # CJam: @_N=@+N\t\
remove_all(input_chars, FLAG_2) # CJam: 0a/L*
temp1 = input_chars.split(FLAG_1) # CJam: 1a/
# interleave([1, 2, 3], ["a", "b"]) gives [1, "a", 2, "b", 3]
temp2 = interleave(temp1, lemon_instances) # CJam: \.{}
print("".join(temp2))

I'm saddened this doesn't have more upvotes, great answer imo

Retina, 303 bytes
i+`(?<!lemon)(a)(.*)(lemon)(?!a)
$2$3$1
i+`(lemon)(?!a)(.*)(?<!lemon)(a)
$1$3$2
i+(?<!lemona?)(d)(.*)(lemona?)(?![ad])
$2$3$1
i+`(lemona?)(?![ad])(.*)(?<!lemona?)(d)
$1$3$2
i+(?<!lemona?d?)(e)(?!(?<=le)mon)(.*)(lemona?d?)(?![ade])
$2$3$1
i+`(lemona?d?)(?![ade])(.*)(?<!lemona?d?)(e)(?!(?<=le)mon)
$1$3$2

Try it online!
Surely I'm doing something wrong here.

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


text:
May the first be with you
Write a program to replace all occurrences of "force" with "first" and all occurrences of "first" with "force", keeping the original case for all character positions:
"ForcefoRcefOrcE" -> "FirstfiRstfIrsT"
"FirstfiRstfIrsT" -> "ForcefoRcefOrcE"

The rest of the string must stay unchanged, and so running your program twice shall return the original string:
"thirst of forces" -> "thirst of firsts" -> "thirst of forces"

Your program should work on any initial string. So as a hint, you better avoid using magic characters as intermediate representation, because if you try a three pass replacement ("force" -> "zzzzz", "first" -> "force", "zzzzz" -> "first"), it will fail on strings containing "zzzzz".
You should support the full range of characters allowed in a definition of a String by your programming language (in most cases, it's Unicode). Example, using JSON-style representation for non-printable characters (\u + 4 digits):
"\u0000\u0001\u0002\u0003the Force of the firsT"
                     |
                     V
"\u0000\u0001\u0002\u0003the First of the forcE"

Atta boy. Remind people that the tag has the winning criterion'

Quite related

Can't you just ignore the leading f?

@Challenger5 No I don't think so since if the leading [Ff] isn't there then you must not replace the word.

@EriktheOutgolfer The OP hasn't replied to MartinEnder's comment. My submission assumes that context doesn't matter.

@Challenger5 I wasn't talking about that, but I don't think you can can replace "orce" -> "irst" instead of "force"->"first", since then you will be replacing things like "divorce" -> "divirst".

May May first be with you. (Commented on May 1st)

Shouldn't it be "May the fourth be with you"?

You should've waited 3 days...

@mbomb007 "fourth" and "force" do not have the same number of letters, making it incompatible for keeping same character case.

@Cœur You meant to ping wizzwizz4 instead, huh?

Retina, 33 bytes
iT`\OC\E\ocetsiTSI`Ro`first|force

Try it online!
Edit: Saved 5 bytes thanks to @MartinEnder for pointing out what Ro does.

Yep, was going to post once the OP replies to my comment. You can save a few bytes by reordering the first set so that the second one can be Ro.

@MartinEnder The documentation confused me by paying too much attention to R's effect on ranges; for instance I would never have realised that RE is equivalent to 86420 if you hadn't pointed it out.

thanks for letting me know. I'll try to make that clearer in the docs.

JavaScript (ES6), 93 88 bytes

f=
s=>s.replace(/force|first/gi,s=>s.replace(/./g,c=>s[s.search(c)^1]||c,s="oicsetOICSET"))
<textarea oninput=o.textContent=f(this.value)></textarea><pre id=o>

Edit: Saved 5 bytes by optimising the unchanged letter case.

Perl 5, 52 bytes
51 bytes of code + -p flag.
s%first|force%$&=~y/oceOCEistIST/istISToceOCE/r%eig

Try it online!
Nothing too crazy going on. Find the occurrences of force and first non-case-sensitive (s%force|first%%gi), and then transliterates the characters to convert one to the other.

PHP, 88 Bytes
Online Versions
<?=preg_replace_callback("#first|force#i",function($t){return$t[0]^first^force;},$argn);

PHP, 110 Bytes
<?=preg_replace_callback("#first|force#i",function($t){return strtr($t[0],iIsStToOcCeE,oOcCeEiIsStT);},$argn);

You could save a few bytes with $t[0]^first^force instead of strtr().

@user63956 Thank You for the learning effort

APL (Dyalog), 61 bytes
Requires ⎕IO←0 which is default on many systems. Can be four characters shorter using the Unicode symbol ⍠ instead of ⎕OPT .
(t←'force' 'first')⎕R{(m∊⎕A)c¨t⊃⍨~t⍳(c←819⌶)⊂m←⍵.Match}⎕OPT 1

Try it online!

Java 10, 318 310 284 279 277 271 256 bytes
String c(String s){var x=s.toLowerCase();int i=x.indexOf("force")+1,j=x.indexOf("first")+1,t=i>0&j>i|j<1?1:-1;var y=s.toCharArray();return-j<i?s.substring(0,i=t<0?j:i)+(y[i++]-=t*6)+y[i++]+(y[i++]+=t*16)+(y[i++]+=t*15)+c(s.length()>i?s.substring(i):""):s;}

-34 bytes thanks to @ceilingcat.
Try it online.
Explanation:
String c(String s){                     // Recursive method with String as both parameter and return-type
  var x=s.toLowerCase();                //  Temp String as lowercase of the input
  int i=x.indexOf("force")+1,           //  Index of "force" + 1 (becomes 0 if NOT present; >=1 if it is present)
      j=x.indexOf("first")+1,           //  Index of "first" + 1 (becomes 0 if NOT present; >=1 if it is present)
      t=i>0&j>i|j<1?1:-1;               //  Temp integer: -1 if "force" is found first; 1 if "first" is found first
  var y=s.toCharArray();                //  Convert the string to a character-array
  return-j<i?                           //  If either "force" or "first" is found:
    s.substring(0,i=t<0?j:i)            //   Return the substring before that (if any) + ('f' or 'F')
     +(y[i++]-=t*6)                     //   + 'i'↔'o' or 'I'↔'O'
     +y[i++]                            //   + 'r' or 'R'
     +(y[i++]+=t*16)                    //   + 's'↔'c' or 'S'↔'C'
     +(y[i++]+=t*15)                    //   + 't'↔'e' or 'T'↔'E'
     +c(s.length()>i?s.substring(i):"") //   + a recursive call for the rest of the input-String (if any)
   :                                    //  Else:
    s;}                                 //   Return the input-String as is

I appreciate that you provided a symmetric example c(c("..."))!

@ceilingcat Thanks! Your character-array approach also opened up a golf for 15 more bytes due to implicit casting. :)

CJam, 66 bytes
qY5m*_"force"{f{_eu}3/:z{~?}f%}:K~\"first"K.{[\]:P~@\/\f/P~@\f*\*}

Goes through every case variation of "first" and "force" and tries to split on it. If it can, it then joins it back with the reverse words.
Pseudocode:
input_chars = list(read_all_input()) # CJam: q
power = cartesian_power(2, 5) # CJam: Y4m*_
def case_variations(s): # CJam: {...}:K
    temp0 = [[i, j, upper(j)] for i, j in zip(power, s)] # CJam: f{_eu}3/
    temp1 = map(transpose, temp0) # CJam: :z
    ret = []
    for i in ret:
        for j in i: # CJam: {...}f%
            ret.append(j[1] if j[0] else j[2]) # CJam: ~?
    return ret
force_var = K("force") # CJam: "force"{...}:K~
first_var = K("first") # CJam: \"first"K
for force, first in zip(force_var, first_var): # CJam: .{...}
    current = [force, first] # CJam: [\]:P~
    input_chars = list_split(input_chars, force) # CJam: @\/
    input_chars = [list_split(i, first) for i in input_chars] # CJam: \f/
    input_chars = [list_join(i, force) for i in input_chars] # CJam: P~@\f*
    input_chars = list_split(input_chars, first) # CJam: \*

Surely the f is relevant to avoid changing thirst into thorce or divorce into divirst?

@Neil True, edited.

@Cœur Try it online!

Jelly, 37 36 bytes
Is there is a way to use a reduce across slices of length 5 instead?
®‘©ị“Ɓu“¡Ḣƭ»
Œlœṣ¢œṣ€¢j€¢j¢Œu⁸=ŒuT¤¦

Try it online!
How?
®‘©ị“Ɓu“¡Ḣƭ» - Link 1 helper that fetches the next word to use: no arguments
®            - recall value from register (initially zero)
 ‘           - increment
  ©          - place the result into the register
    “Ɓu“¡Ḣƭ» - literal dictionary compressed string list ["first","force"]
   ị         - index into (1-indexed and modular)
             - so this link first yields "first", then "force", then "first" and so on.

Œlœṣ¢œṣ€¢j€¢j¢Œu⁸=ŒuT¤¦ - Main link: list of characters, S
Œl                      - convert S to lower case
  œṣ                    - split on sublists equal to:
    ¢                   -   call the last link (1) as a nilad ("first")
     œṣ€                - split €ach on sublists equal to:
        ¢               -   call the last link (1) as a nilad ("force")
         j€             - join €ach with:
           ¢            -   call the last link (1) as a nilad ("first")
            j           - join with:
             ¢          -   call the last link (1) as a nilad ("force")
                      ¦ - apply a link to sparse indices:
              Œu        -   convert to upper case
                     ¤  -   nilad followed by link(s) as a nilad:
                ⁸       -     chain's left argument, S
                  Œu    -     convert to upper case
                 =      -     equal to S? (vectorises)
                    T   -     truthy indexes (indexes at which input is upper case)

Pyth and Jelly are equal :o

There must be a golfier way :D

Yes, and I just found it :D

Python 2, 171 bytes
I wanted to try to do this using built-ins, but it can't beat the messy method with all the splitting and zipping.
import re,string as g
def f(s):f="istISTECOeco";l=re.split("(first|force)",s,0,re.IGNORECASE);l[1::2]=[t.translate(g.maketrans(f,f[::-1]))for t in l[1::2]];print"".join(l)

I think it's pretty clear what I'm doing here. Split the string on instances of first and force (case-insensitive), replace those instances with versions translated using str.translate, and join it back into a string again.
Try it online!

Further golfing and switching to Python 3.8 brings it down to 113 bytes

@movatica yes that's a much smarter way to go about it

You can update your post accordingly :)

@movatica no thanks. that's your solution. post it yourself.

Python 2.7, 173 165 bytes
8 bytes saved by quintopia
This one got gross:
lambda S:`[(t[0],t[0].upper())[t[1]]for t in zip("".join("first".join(s.replace("first","force")for s in S.lower().split("force"))),[l.isupper() for l in S])]`[2::5]

Try it online
Breaking it down step by step:

S.lower().split("force"): take the string, unify to lowercase, split into substrings separated by "force"
s.replace("first","force")for s in <STEP 1>: Replace all "first"'s with "force"
_`.join("first".join(<STEP 2>)`[2::5]`_: replace all "force"'s with "first" by recombining the "force" delineated substrings with "first" and rejoin into single string (underscores added to get tick marks correct)
zip(<STEP 3>,[(2,1)[l.isupper()]for l in S]): zip each character of replaced phrase with case encoding of original string (2 for lowercase, 1 for uppercase)
_`[(t[0],t[0].upper())[t[1]==1]for t in <STEP 4>]`[2::5]`_: Restore original casing, converts list to string (underscores added to get tick marks correct)

You can save 8 bytes by encoding upper as True and lower as False: Try it online!

131 bytes

Flex (lexer), 72 bytes
%%
 #define x(a) yytext[a]^=
(?i:first|force) x(1)6;x(3)16;x(4)17;ECHO;

To compile and run:
flex first.l
gcc lex.yy.c -lfl # -ll on Macs, apparently
./a.out

first.l:3: EOF encountered inside an action (oh, nevermind: it requires a newline at the end)

ld: library not found for -lfl (oh never mind, command is gcc lex.yy.c -ll on macOS)

Tested and approved.

MATL, 47 bytes
5W:qB!"o['first';'force']@!32*-cZ}_Zt5M_6MoZt|c

Try it online!
This uses negative values as the intermediate step, and after the two passes it takes the absolute value.

Pyth, 36 35 bytes
K"first"srVjJ"force"mjKcdJcr0QKqVr1

Try it online!
Pyth is not especially good at string manipulations.

Yet, you were holding second place for 7 years. Now fourth place, behind Vyxal, 05AB1E and Retina.

C (clang), 201 183 226 214 bytes
Had some bugs...
Still needs to be golfed down quite a lot
(saved 12 thanks to ceilingcat)
char*s,*p,*q;main(i,v)char**v;{puts(s=v[1]);do{p=strcasestr(s,"first");q=strcasestr(s,"force");if(p&&(!q|p<q))p[1]+=6,p[3]-=16,p[4]-=15;else if(q)q[1]-=6,q[3]+=16,q[4]+=15;s=p&&(!q|p<q)?p:q;}while(s++);puts(v[1]);}

Try it online!

183 bytes

Python 3.8 (pre-release), 113 102 bytes
-11 bytes thanx to naffetS
lambda s:re.sub("(?i:first|force)",lambda m:m[0].translate(' tf Io RCE i  rceS TF  Os'*9),s)
import re

Try it online!
Inspired by quintopias answer.

102

Vyxal r, 21 20 19 18 bytes
⇩1∆o‛°⇩"JḂǓ"ƛ÷V;•F

Try it Online!
Neat. String compression helps here but honestly the hard part was figuring out how to set up the lists with minimal repetition.
-1 because I never actually use the register in my final answer
-1 by switching the last two elements to remove the duplication
-1 again for redoing how the lists are created
⇩1∆o‛°⇩"JḂǓ"ƛ÷V;•F
 1∆o                # "first"
    ‛°⇩             # "force"
⇩      "J           # pair the two and append the lowercase input
         Ḃ          # push ["force", "first", input] and its reverse
          Ǔ         # rotate the reverse so its in the order ["first", "force", input]
           "        # pair the two
            ƛ  ;    # map over each list
             ÷V     # replacement of first/force
                •F  # copy capitalization of input and remove the one identical to the input

Created with the help of Luminespire.

Here comes a new challenger! Good job.

This doesn't seem to handle inputs containing both first and force? here's a 21 that works

actually 19 by porting osabie

C# 273 bytes
string c(string s){var x=s.ToLower();int i=x.IndexOf("force")+1,j=x.IndexOf("first")+1,t=i>0&j>i?0:j>0?1:0;return i>0|j>0?s.Substring(0,t>0?(i=j):i)+(char)(s[i++]-(t>0?-6:6))+s[i++]+(char)(s[i++]+(t>0?-16:16))+(char)(s[i++]+(t>0?-15:15))+c(s.Length>i?s.Substring(i):""):s;}

Try it online!
Direct port of Kevin Cruijssen's Java answer, turns out when it comes to getting the char in a string at a given index, C# is much golfier than java (s[i++] instead of s.charAt(i++))

Japt, 41 bytes
r"first|force"_d"i1o s1c t1e"¸m²®+ZuÃq}'i

Try it online!
This would be considerably shorter if Japt had a sane transliterate function...
Alternate version:
r"first|force"_d"io sc te"¸®¬¸²Ã®+ZuÃq}'i

Try it online!

C#, 234 bytes
string a(string s){var l=s.ToLower();int f=l.IndexOf("first"),F=l.IndexOf("force"),m=f<F&f>-1?f:F>-1?F:f;return ++m>0?s.Substring(0,m)+(char)(s[m]^6)+s[m+1]+(char)(s[m+2]^16)+(char)(s[m+3]^17)+(s.Length-m>5?a(s.Substring(m+4)):""):s;}

Try it online!

Ruby, 55 bytes
gsub(/first|force/i){$&.tr(s="iIsStTEeCcOo",s.reverse)}

Try it online!

05AB1E, 21 20 bytes
„€Û‹›#`UVlY¡XY:Xý¹.Ï

Try it online!
I could not figure out a way of doing this shorter without using variables, so here we are.  I'm sure someone more versed with stack manipulation can figure it out
How?
„€Û‹›#`UVlY¡XY:Xý¹.Ï
„€Û‹›#`UV               X = "first" Y="force"
         l              Lower case the input
          Y¡            Split on "force"
            XY:         Replace "first" with "force"
               Xý       Join on "first"
                 ¹.Ï    Apply capitalization of input

Thanks, and good job on the split-replace-join. You're on second place after Vyxal currently.

Swift, 127 247 225 219 208 bytes
var b="force",c="first",a=b,d=a,x={(a=$0,d=$3,($1+"").lowercased().ranges(of:$2+"").map{a.replaceSubrange($0,with:zip(d,a[$0]).map{$1.isLowercase ?$0:.init($0.uppercased())})},a).3},f={x(x($0,$0,b,c),$0,c,b)}

Built and tested with Swift 5.9, so TIO is out of the window. Here's a JDoodle link instead.

The following explanation is outdated, and refers to this similar, yet slightly less complicated version:
let f={let b="force",c="first",s=$0+"",x={var a=$0+"",d=$2+""
s.lowercased().ranges(of:$1+"").map{a.replaceSubrange($0,with:zip(d,a[$0]).map{$1.isLowercase ?$0:.init($0.uppercased())})}
return a}
return x(x(s,b,c),c,b)}

The current revision isn't much different in principle; the major differences are:

Tuples are exploited to allow for one-line closures, which lets us use implicit return statements.
All declarations are merged into a single var statement.
The s variable is no longer used, and has been replaced with an extra parameter to x.
Empty strings used for type inference have been replaced with references to other strings; this saves a byte wherever it's used.

With whitespace restored:
let f = {
  let b = "force", c = "first", s = $0 + "", x = {
    var a = $0 + "", d = $2 + ""
    s.lowercased().ranges(of: $1 + "").map {
      a.replaceSubrange($0, with: zip(d, a[$0]).map {
        $1.isLowercase ? $0 : .init($0.uppercased())
      })
    }
    return a
  }
  return x(x(s, b, c), c, b)}

Explanation
There's a lot to follow here, so I'll try and step you through the least Swifty Swift code I've ever written. Knowledge of Swift's intricacies is invaluable in understanding this gibberish.

Fair warning: Most of the identifiers used here are completely arbitrary.

Line 1
let f = { /* ... */ }

Since function declarations are generally not small, I've opted for a closure instead, so that the compiler can infer the parameter and return types. Plus, this means we don't have any pesky argument labels to deal with.
Line 2
let b = "force", c = "first", s = $0 + "", x = { /* ... */ }

b and c are simply there to shave off a few bytes, since I use each of those strings twice.
s serves a dual purpose. It lets me use the closure parameter (the original string) inside of more closures, since implicit closure parameters can only be used one level deep; and concatenating "" to it lets the type checker know that it's a String, meaning I don't have to specify that directly.
x is simply another closure definition. It takes three parameters:

the string to replace characters in
the search string
the replacement string

Line 3
var a = $0 + "", d = $2 + ""

a is there so I have a mutable copy of the string to work with. I also use the trick I used with s above to help out the type checker.
d serves the same purpose as s above (except for it being used differently, of course).
Line 4
s.lowercased().ranges(of: $1 + "").map { /* ... */ }

This lowercases the original string (to effectively make the substring search case insensitive) before finding all ranges containing the search string ($1, with "" appended to assist the type checker). These ranges allow us to refer to discovered words in the string even after we start replacing them.
The call to map here serves the same purpose as a for-in loop, just with less bytes (and a warning since we don't use the result -- if you don't want a warning, replace map with forEach).
Line 5
a.replaceSubrange($0, with: zip(d, a[$0]).map { /* ... */ }

This line does the actual replacing. In this method call, $0 is one of the ranges containing a word we want to replace. a[$0] gets the actual contents of the string in that range.

replaceSubrange(_:with:) unfortunately does not have a non-mutating counterpart, which is why we declare a above as a var instead of a let.

The call to zip allows us to iterate over the original string and the replacement string simultaneously, allowing us to keep case unchanged. Speaking of which...
Line 6
$1.isLowercase ? $0 : .init($0.uppercased())

Here, $1 is a character from the original string, and $0 is the corresponding character from the replacement string.

If $1 is lowercase, we return $0 unchanged (since I hardcoded the replacement strings to be lowercase).
If $1 is uppercase (or if it isn't cased at all), we return the result of uppercasing $0 (if it isn't cased, this call does nothing).

We have to wrap the call to uppercased() in a call to Character.init(_:) since uppercased() on Character returns a String (blame Swift's Unicode support).

Line 9
return a

The only line of this program that actually makes sense.
Line 11
return x(x(s, b, c), c, b)

Remember: b == "force", and c == "first".

We call our closure with the original string first, telling it to replace "force" with "first".
We then call the closure again with the result, and replace "first" with "force".

We avoid replacing words we've already replaced by referencing the original, unmodified string when finding ranges.

Finally, we return the result of that and leave the miniature catastrophe that is the f closure.

But why, tho?
I've probably overcomplicated a good chunk of this program, but if we're being honest here, Swift was not designed with code golfing in mind. Still, that's what makes golfing fun in the first place!

I'd also specify that this is Swift 5 (since TIO is currently only supporting Swift 4).

C# (269 Bytes)
string s(string z){var u=z.ToUpper();var a=new[]{"FIRST","FORCE"};return String.Join("",u.Split(a,StringSplitOptions.None).Aggregate((c,n)=>c+(u.Substring(c.Length,5)==a[0]?a[1]:a[0])+n).Select((c,i)=>Char.IsLower(z[i])?Char.ToLower(c):c));}

yet another c# solution, only the second-smallest because I declared two variables and so can't use lambda syntax. oh well, I had fun. :)
explanation:

upshift the original string, then split on "FORCE" and "FIRST".
aggregate
the results and on every split, find the five-character substring that was used to split the original string using the length so far of the string being
aggregated. if it was "force" make it "first" and vice versa
select all the characters of the newly created all caps string and
check if the original string was lowercase at the same index. if yes, return lowercased character at that index in the new string, otherwise return the uppercase character


text:
Longest equal subsequences
Definitions

A subsequence may not be contiguous, e.g. [1, 1, 1] is a subsequence of [1, 2, 1, 2, 1].
An equal subsequence is a subsequence in which every element is equal.
The longest equal subsequence may not be unique, e.g. [1, 1] and [2, 2] are both longest equal subsequences of [2, 1, 1, 2].

Input
A non-empty list of positive integers in one of the format below:

as the native implementation of an array of positive integers in your language
as a string of newline-separated integers in decimal
as a string of newline-separated integers in unary
any other reasonable formats

Output
All of the longest equal subsequences in any order in one of the formats below:

as a 2D nested array in your language (if the input is an array)
as a flattened array with the equal elements being contiguous
any other reasonable format

Scoring
Although we are looking for something long, the code used should be as short as possible in terms of number of bytes, since this is code-golf
Testcases
Inputs:
[1, 2, 3]
[1, 2, 2, 1]
[1, 2, 3, 2, 1]
[1, 2, 1, 2, 3, 4, 1]

Outputs:
[[1], [2], [3]]
[[1, 1], [2, 2]]
[[1, 1], [2, 2]]
[[1, 1, 1]]

Note that for the outputs above, any order is valid.
A flattened array is also valid, as long as the equal elements are contiguous.

It would be simpler to talk of “most frequent elements” IMO: subsequences are used when the order is important, but here, every permutation of the input has the same set of allowed correct outputs.

@ShreevatsaR Sorry, I've edited the question.

Does a flat list work for output? E.g. 1 2 3, 1 1 2 2, 1 1 2 2, 1 1 1?

@ConorO'Brien saying yes would invalidate most of the answers here...

@LeakyNun As in, is it an acceptable alternative?

@ConorO'Brien yes.

Jelly, 5 bytes
ĠLÐṀị

Try it online!
How it works
ĠLÐṀị  Main link. Argument: A (array)

Ġ      Group; partition the indices of A by their corresponding values.
 LÐṀ   Select all index arrays with maximal length.
    ị  Unindex; retrieve the items of A at the specified indices.

I thought Jelly doesn't have a maximum quick...

It's technically a maximal quick, but yes, it does.

Pyth, 5 bytes
S.M/Q

Test suite
Explanation:
This is implicitly S.M/QZQ. .M is the maximal function, so .M/QZQ selects all elements where the value of /QZ, count the number of occurrences of the element in the input, is maximal. S then sorts the list so that identical elements are contiguous.

Brachylog, 7 bytes
⊇ᶠ=ˢlᵍh

Try it online!
Explanation
⊇ᶠ=ˢlᵍh
⊇ᶠ        Find all subsequences
  =ˢ      Keeping only those for which all elements are equal
    lᵍ    Group by length
      h   Take the first group

⊇'s natural order generates the longest subsequences first, so those are the ones that end up in the first group.

Oh hey, another Brachylogist.

Somehow you and me must have missed each other repeatedly in the Brachylog chat; I've been using it for months, and was surprised to learn that apparently someone else besides Fatalize was too.

bash, 66 bytes
sort|uniq -c|sort -rn|awk 'NR==1{a=$1}$1==a{for(i=a;i--;)print$2}'

This seems like it should be way shorter, but I can't figure out how.
sort                  # sort the input
|uniq -c              # group runs of identical lines and prefix with count
|sort -rn             # sort by count, with largest at top
|awk '                # pipe to awk...
  NR==1{a=$1}         # on the first line, set the variable "a" to field 1
  $1==a{              # on any line, if first field is a (max count)...
    for(i=a;i--;)     # a times...
    print$2           # print the second field
  }
'

Try it online!
Thanks to Leaky Nun for 3 bytes!

3 bytes off

Consider updating your explanation

Python 2, 68 63 bytes
lambda x:sorted(n for n in x if x.count(n)/max(map(x.count,x)))

Try it online!

Would like to see an answer in Python 3 :p

Porting this one is trivial: just replace print with return.

Oh, I thought Python 3 doesn't have map.

It's a bit different in 3 (returns a generator and truncates longer iterables if there are more than two arguments), but it's there.

I thought Python had a built-in for this

@BetaDecay Without an external library, I doubt it. And even then, verbose imports are oftentimes longer than rolling your own.

@BetaDecay The closest I know to a Python builtin for this is Counter: for example Counter([1, 2, 1, 2, 3, 4, 1]).most_common() returns [(1, 3), (2, 2), (3, 1), (4, 1)] and you could walk the list till the count decreases (here after just the first element). But that would be a lot more verbose, even after the import.

I have added another acceptable alternative which might help you golf off some bytes.

@LeakyNun Thanks for the heads-up.

@Dennis It's my responsibility.

Actually, 23 bytes
;╗⌠;╜ck⌡M;♂NM╗⌠N╜=⌡░♂FS

Try it online, or run all test cases!
Thanks to Leaky Nun for pointing out a one-byte improvement that really should've been obvious to me
-3 bytes from relaxed output format
Explanation:
;╗⌠;╜ck⌡M;♂NM╗⌠N╜=⌡░♂FS
;╗                        save a copy of the input to register 0
  ⌠;╜ck⌡M                 for each value in the input list:
   ;                        make a copy on the stack
    ╜c                      count the occurrences in the input list (from register 0)
      k                     make a list: [value, count]
         ;♂N             make a copy, take last value of each list in the 2D list
            M╗           store the maximum count in register 0
              ⌠N╜=⌡░     filter the other copy of the list of [value, count] lists:
               N╜=         take items where the count equals the maximum count
                    ♂FS  take first items (values) and sort them

Stacked, 55 52 43 bytes
sorted rle toarr:[1#]map MAX@K[1#K=]YES rld

Try it online!
Works by run-length encoding the input, sorting by occurrences, keeping occurances for which the number of occurrences is maximal, and run length decoding. Outputs through a flat list, as is acceptable by the challenge.

Mathematica, 42 31 25 bytes
Thanks @GregMartin for 5 bytes and @MartinEnder for another byte!
MaximalBy[Length]@*Gather

Explanation
MaximalBy[Length]@*Gather  (*                       {1, 2, 3, 2, 1}       *)
                   Gather  (* Gather same numbers:  {{1, 1}, {2, 2}, {3}} *)
                 @*        (* Function composition                        *)
MaximalBy[Length]          (* Find longest:         {{1, 1}, {2, 2}}      *)

You can save 5 bytes with Gather@#~MaximalBy~Length&.

@GregMartin and then MaximalBy[Length]@*Gather.

I have added another acceptable alternative which might help you golf off some bytes.

K (ngn/k), 18 bytes
{x{b=|/b:#'x}#.=x}

Try it online!

CJam, 22 bytes
{$e`z~\__:e>f=.*\]ze~}

This is an anonymous block (function) that takes the input from the top of the stack and repaces it with the output. The output is a flattened array withequal elements being contiguous.
Try it online!
Explanation
Consider input [10  20  30  20  10 ] as an example.
{      e# Begin block
       e#   STACK: [10 20 30 20 10]
  $    e#   Sort
       e#   STACK: [10 10 20 20 30]
  e`   e#   Run-length encoding
       e#   STACK: [[2 10] [2 20] [1 30]]
  z    e#   Zip
       e#   STACK: [[2 2 1] [10 20 30]]
  ~    e#   Dump array contents onto the stack
       e#   STACK: [2 2 1] [10 20 30]
  \    e#   Swap
       e#   STACK: [10 20 30] [2 2 1]
  __   e#   Duplicate twice
       e#   STACK: [10 20 30] [2 2 1] [2 2 1] [2 2 1]
  :e>  e#   Fold maximum over array. Gives the maximum of the array
       e#   STACK: [10 20 30] [2 2 1] [2 2 1] 2
  f=   e#   Map "is equal" with number (2) over the array ([2 2 1])
       e#   STACK: [10 20 30] [2 2 1] [1 1 0]
  .*   e#   Vectorized multiplication
       e#   STACK: [10 20 30] [2 2 0]
  \    e#   Swap
       e#   STACK: [2 2 0] [10 20 30]
  ]    e#   Pack into array
       e#   STACK: [[2 2 0] [10 20 30]]
  z    e#   Zip
       e#   STACK: [[2 10] [2 20] [0 30]]
  e~   e#   Run-length decoding
       e#   STACK: [10 10 20 20]
}      e# End block

Perl 5, 58 bytes
sub{sort grep$x{$_}>$m,grep{$/=$x{$_}++;$m=$/if$m<$/;1}@_}

Python 2, 138 bytes
lambda l:[[x[0]]*x[1] for x in next(__import__('itertools').groupby(__import__('collections').Counter(l).most_common(),lambda x:x[1]))[1]]

itertools is never the shortest :p

I have added another acceptable alternative which might help you golf off some bytes.

Octave, 47 bytes
[~,b,c]=mode(input(0));disp([repmat(c,1,b){:}])

Try it online!
Explanation
The second and third outputs of mode (obtained as [~,b,c]=mode(...)) respectively give the number of repetitions (b) and a column cell array (c) of the most repeated elements in the input (input(0)) . The cell array c is then repeated horizontally b times (repmat(c,1,b)), converted to a comma-separated list ({:}) and contatenated horizontally ([...]) to give a numeric matrix, which is displayed (disp(...)).

I have added another acceptable alternative which might help you golf off some bytes.

MATL, 10 bytes
3#XMg1bX"&

Try it online!
Explanation
Similar to my Octave answer. Consider input [10, 20, 30, 20, 10] as an example.
3#XM   % Three-output version of mode function. Gives the first mode, the
       % number of repetitions, and a cell array with all modes
       % STACK: 10, 2, {10; 20}
g      % Convert from cell array to matrix
       % STACK: 10, 2, [10; 20]
1      % Push 1
       % STACK: 10, 2, [10; 20], 1
b      % Bubble up in the stack
       % STACK: 10, [10; 20], 1, 2
X"     % Repeat those number of times vertically and horizontally
       % STACK: 10, [10, 10; 20, 20]
&      % Specify that implicit display will show only the top of the stack.
       % Since this is singleton cell array that contains a matrix, that
       % matrix is directly displayed

I have added another acceptable alternative which might help you golf off some bytes.

@LeakyNun Thanks for letting me know

It is my responsibility.

05AB1E, 8 5 bytes
Outputs a flat list in order
.M¹Ã{

Uses the 05AB1E encoding. Try it online!

I have added another acceptable alternative which might help you golf off some bytes.

@LeakyNun Thanks for the notification :)

Husk, 5 bytes
→kLk=

Try it online!

Japt -h, 4 bytes
ü üÊ

Try it
ü üÊ     :Implicit input of array
ü        :Group & sort by value
  üÊ     :Group & sort by length
         :Implicit output of last element

Hey, is there a way to wait for a certain amount of time, or run a block until condition in Japt?

Nibbles, 5 bytes (10 nibbles)
/=~=~$$,$@

/=~=~$$,$@
   =~       # group
     $      # the input
      $     # by its own values,
 =~         # now group each of these groups
       ,$   # by their lengths
            # (group of longest groups comes last),
/           # fold over this list-of-lists from right
         @  # always returning the second argument
            # (so this fold just returns the last item,
            # which is the list of the longest groups
            # of values)

JavaScript (ES6), 84 83 bytes
Returns a sorted flattened array.
a=>a.sort().filter((_,i)=>b[i]==Math.min(...b),b=a.map(i=>a.filter(j=>i-j).length))

Test cases

let f =

a=>a.sort().filter((_,i)=>b[i]==Math.min(...b),b=a.map(i=>a.filter(j=>i-j).length))

console.log(JSON.stringify(f([1, 2, 3])))
console.log(JSON.stringify(f([1, 2, 2, 1])))
console.log(JSON.stringify(f([1, 2, 3, 2, 1])))
console.log(JSON.stringify(f([1, 2, 1, 2, 3, 4, 1])))

I have added another acceptable alternative which might help you golf off some bytes.

@LeakyNun Thanks for the notification.

Clojure, 65 bytes
#(let[P partition-by C count](last(P C(sort-by C(P +(sort %))))))

Ungolfed:
(def f #(->> %
             (sort-by      identity)   ; sort so that identical values are one after another, same as sort
             (partition-by identity)   ; partition by identity (duh!)
             (sort-by      count)      ; sort by item count
             (partition-by count)      ; partition by item count
             last))                    ; get the last partition

C#, 145 Bytes
l=>{var t=Enumerable.Range(0,l.Max()+1).Select(i=>l.Count(a=>a==i));return t.Select((a,i)=>Enumerable.Repeat(i,a)).Where(d=>d.Count()==t.Max());}

This must be possible better as well, however I'm kind of stuck.
Explanation
l =>                                                   //Takes the list
{                                                      //...
    var t = Enumerable.Range(0, l.Max() + 1)           //Makes a range till the count, so that the items together with their indices are double defined (i.e. the items are 0,1,2,3... and the indices are the same)
                      .Select(i =>                     //Takes the items
                          l.Count(a => a == i));       //And replaces them with the count of themselves in the list (so the item has the index with its old value and the count as it's actual value)
    return t.Select((a, i) =>                          //Then it takes this list and selects the items together with the indices
        Enumerable.Repeat(i, a))                       //Repeats them as often as they appeared in the list
                  .Where(d => d.Count() == t.Max());   //And just keeps those which appear the maximum amount of times
};                                                     //...

Probably a totally different approach would be much shorter, so the C# challenge is still open :)

Ruby, 57 bytes
->a{a.reject{|i|a.map{|j|a.count j}.max>a.count(i)}.sort}

Try it online!

APL (Dyalog), 22 bytes
Requires ⎕ML←3 which is default on many systems.
Program: s/⍨(⌈/=⊢)≢¨s←⊂⍨(⍋⊃¨⊂)⎕
⎕ get numeric (evaluated) input
(…) tacit function
 ⍋ the indices of ascending items
 ⊃¨ each pick from
 ⊂ the entire array
⊂⍨ partition by cutting at its increases
s← store as s
≢¨ tally each
(…) tacit function
 ⌈/ the maximum (tally)
 = equals
 ⊢ the argument (the tallies)
s/⍨ filter s with that
Function: {s/⍨(⌈/=⊢)≢¨s←⊂⍨⍵[⍋⍵]}
{…} anonymous function where argument is ⍵
⍵[⍋⍵] sort (lit. index with indices of ascending items)
⊂⍨ partition by cutting at its increases
s← store as s
≢¨ tally each
(…) tacit function
 ⌈/ the maximum (tally)
 = equals
 ⊢ the argument (the tallies)
s/⍨ filter s with that
Try it online!

I have added another acceptable alternative which might help you golf off some bytes.

CJam, 24 bytes
{$e`_$W=0=\{0=1$=},e~\;}

I wanted to do this in 05ab1e, but I gave up :P
This is a block. Input and output are arrays on the stack.
Try it online!
Explanation:
{                      e# Stack:                | [1 2 3 2 1]
 $                     e# Sort:                 | [1 1 2 2 3]
  e`                   e# RLE encode:           | [[2 1] [2 2] [1 3]]
    _$W=               e# Copy elements:        | [[2 1] [2 2] [1 3]] [2 1]
       0=              e# First element:        | [[2 1] [2 2] [1 3]] 2
         \             e# Swap:                 | 2 [[2 1] [2 2] [1 3]]
          {0=1$=},     e# Filter where x[0]==2: | 2 [[2 1] [2 2]]
                  e~   e# RLE decode:           | 2 [1 1 2 2]
                    \; e# Delete back:          | [1 1 2 2]
                      }

This only works if the smallest integer belongs to the most common elements. You'll need $W= instead of the first 0=.

I have added another acceptable alternative which might help you golf off some bytes.

PHP, 69 Bytes
<?print_r(preg_grep("#".max($r=array_count_values($_GET))."#",$r));

Online Version
Output Format
key = value , value = count
Array
(
    [1] => 2
    [2] => 2
)

PHP, 96 Bytes
<?foreach($_GET as$v)$r[$m[]=count($l=preg_grep("#^{$v}$#",$_GET))][$v]=$l;print_r($r[max($m)]);

Online Version
Output Format
1D Key= value
2D Key = position in the input array for each value
Array
(
    [1] => Array
        (
            [0] => 1
            [4] => 1
        )

    [2] => Array
        (
            [1] => 2
            [3] => 2
        )

)

PHP, 97 Bytes
<?foreach($_GET as$v)$r[count($l=preg_grep("#^{$v}$#",$_GET))][$v]=$l;ksort($r);print_r(end($r));

I have added another acceptable alternative which might help you golf off some bytes.

Factor + math.combinatorics, 46 bytes
[ all-subsets [ all-eq? ] filter all-longest ]

Try it online!

all-subsets Get all the subsets of the input
[ all-eq? ] filter Get the ones where all the elements are the same
all-longest Get all the longest of these


text:
All the k-mers/n-grams
Intro
We have had histograms and counting, but not listing all of them.
Every year, Dyalog Ltd. holds a student competition. The challenge there is to write good APL code. This is a language agnostic code-golf edition of this year's sixth problem.
I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author.
Problem
The term k-mer typically refers to all the possible substrings of length k that are contained in a string. In computational genomics, k-mers refer to all the possible subsequences (of length k) from a read obtained through DNA Sequencing. Write a function/program that takes a string and k (the substring
length) and returns/outputs a vector of the k-mers of the original string.
Examples
[4,"ATCGAAGGTCGT"] → ["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]
k > string length? Return nothing/any empty result:
[4,"AC"] → [] or "" or [""]

Does the order of the output matter? When a substring occurs multiple times, should it be repeated in the output?

Can I return a string of the required substrings separated by newlines instead of an array of strings, like this?

May we also input and output the string as an array of characters (like ['A', 'T', 'C', 'G'] instead of "ATCG"?

Are Dyalog APL answers allowed in this PPCG challenge (because the challenge is also hosted by Dyalog)?

Is it acceptable to return an empty string for the empty result while returning an array of strings for the non-empty result?

@JonathanAllan Yes.

@feersum Order matters, and repetitions should be repeated. This is just like a sliding window.

@LeakyNun Yes, if that would be normal for your language.

@Adnan Yes, if that would be normal for your language.

@KritixiLithos Yes, because this is [tag:code-golf] while that challenge is for quality code.

Related (sliding window on a list)

Jelly, 1 byte
ṡ

Jelly has a single byte dyadic atom for this very operation
Try it online! (the footer splits the resulting list with newlines, to avoid a mushed representation being printed.)

Somehow the OP must have known...

@LeakyNun I actually didn't.

Octave, 28 bytes
@(N,s)s((1:N)+(0:nnz(s)-N)')

Try it online!
For k > string length works in Octave 4.2.1-windows but in tio (Octave 4.0.3) doesn't work.
Creates numeric indexes of consecutive elements and index the string by it.
s= "ATCGAAGGTCGT"
N = 4
idx = (1:N)+(0:nnz(s)-N)'
 =
    1    2    3    4
    2    3    4    5
    3    4    5    6
    4    5    6    7
    5    6    7    8
    6    7    8    9
    7    8    9   10
    8    9   10   11
    9   10   11   12

s(idx) =

ATCG
TCGA
CGAA
GAAG
AAGG
AGGT
GGTC
GTCG
TCGT

C (GCC on POSIX), 67 66 63 bytes
-3 bytes thanks to @LeakyNun!
f(i,s,j)char*s;{for(;j+i<=strlen(s);puts(""))write(1,s+j++,i);}

Try it online!

I don't think you need j=0.

@LeakyNun the function should be reusable. Try it online! vs Try it online!

Though if i do this...

You can replace j+i<=strlen(s) with just s[j+i]

05AB1E, 2 bytes
Code:
Œù

Explanation:
Œ      # Get all substrings of the input
 ù     # Only keep the substrings of length the second input

Uses the 05AB1E encoding.
Try it online!

Python 3,  47 45 42 bytes
-3 bytes thanks to ovs (use Python 3's unpacking to reuse a[n-1:] at the tail.)
f=lambda a,n:a[n-1:]and[a[:n],*f(a[1:],n)]

A recursive function taking the string, a, and the slice length, n, and returning a list of the slices or an empty string.
a[n-1:] takes a slice of the current string from the n-1th (0-indexed) element onward to test whether there are enough elements remaining (an empty string is falsey in Python) - this is shorter than the equivalent len(a)>=n.

If there are enough elements a list is constructed, [...], with the first n elements of the string, a[:n], and the unpacked result of calling the function again, *f(...), with a dequeued version of the current input (without the first element), a[1:].
If there are not enough elements the tail of the recursion is reached when a[n-1:] is returned (in this case an empty string).

Try it online!

45 for Python 2 or 3 with:
f=lambda a,n:a[n-1:]and[a[:n]]+f(a[1:],n)or[]

f=lambda a,n:a[n-1:]and[a[:n],*f(a[1:],n)] for 42 bytes (Python 3) TIO

@ovs, very nice, I've asked if this is acceptable (since they empty result is a string, while the non-empty result is a list).

Brachylog, 3 bytes
s₎ᶠ

Try it online!
Specs:

Input: ["ATCGAAGGTCGT",4]
Argument: Z
Output: Z = ["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]

How it works
s₎ᶠ
s    Output is a substring of first element of input,
 ₎   with length specified by second element of input.
  ᶠ  Find all solutions.

J, 2 bytes
,\

It is not a complete program, but a function with an operator.
Call it as such:
echo 4 ,\ 'ATCGAAGGTCGT'

Try it online!
How it works
The operator (called "conjunction") \ (named "infix") is used as such:

(x u\ y) applies verb u to successive parts of list y (called infixes).

The function (called "verb") u in this case is the function , which is a simple "append" function:

Creates an array containing the items of x followed by the items of y.

R, 65 61 bytes
-2 bytes thanks to MickyT
-2 bytes by changing the indexing
returns an anonymous function.
function(s,n,x=nchar(s))`if`(n>x,'',substring(s,x:n-n+1,n:x))

substring cycles through the indices (as opposed to substr which does not), and if the starting index is less than 1, it defaults to 1 instead, so it checks and returns the empty string.
x:n-n+1 is equivalent to 1:(x-n+1) since : takes precedence over sums/differences
Try it online!

you can save a couple of bytes with function(s,n,x=nchar(s))if(n>x,'',substring(s,1:(x-n+1),n:x))

@MickyT, thanks! I also noticed I could drop some bytes by changing the index computation

Mathematica, 21 bytes
##~StringPartition~1&

Anonymous function. Takes a string and a number (in that order) as input and returns a list of strings as output.

oK, 2 bytes
':

oK has a sliding window operator!

Clojure, 19 bytes
Well this is handy:
#(partition % 1 %2)

Examples:
(def f #(partition % 1 %2))
(println [(f 4 "ATCGAAGGTCGT")
          (f 4 "abc")])

[((A T C G) (T C G A) (C G A A) (G A A G) (A A G G) (A G G T) (G G T C) (G T C G) (T C G T))
 ()]

CJam, 4 bytes
{ew}

Anonymous block that expects the arguments on the stack and leaves the result on the stack after.
Try it online!
ew is a built-in that does exactly what is required.

I have only one thing to say: ew

Pyth, 2 bytes
.:

It is not a complete program, but a built-in function.
Call it as such:
.:"ATCGAAGGTCGT"4

Try it online!
Full program:
.:.*

Try it online!
(The .* is splat.)

While it doesn't really matter, .:F is a byte shorter for the full program.

Jellyfish, 7 bytes
p
_I
\i

Try it online!
How it works
In linear: p(\(I,i)), where p is print and \ gets the required substrings.
I is the raw first input while i is the evaluated second input.
In Jellyfish, every function and operator gets two arguments, one from the right, and one from the bottom. Here, the function p gets the argument from the output of _, which is required if we are to use the operator \ to get substrings.

Java (OpenJDK 8), 92 bytes
void f(String s,int n){for(int i=n;i<=s.length();)System.out.println(s.substring(i-n,i++));}

Try it online!

You can golf it by 3 bytes like this: String[]f(String s,int n){int i=0,t=s.length()-n+1;String[]r=new String[t];for(;i<t;r[i]=s.substring(i,n+i++));return r;}

@KevinCruijssen I changed my answer.

Retina, 41 38 bytes
.*$
$*
!&`(.)+(?=.*¶(?<-1>.)+(?(1)¶)$)

Try it online!
Takes the string and count on separate lines. The first two lines are used to convert the count from decimal to unary, so if unary input is acceptable then the byte count would be reduced to 34 31. Edit: Saved 3 bytes thanks to @FryAmTheEggman. Or, if you prefer, a 48-byte version that handles newlines in the string, although that does produce confusing output:
.*$
$*
!&`(\S|\s)+(?=[\S\s]*¶(?<-1>.)+(?(1)$.)$)

@KritixiLithos I don't see how your solution takes the count into account...

Oh, sorry I just had a brain fart >_<

This doesn't necessarily work if the string can contain a newline, so I think you can change (?!) to ¶.

Octave with Image Package, 29 bytes
@(s,n)[im2col(+s, [1 n])' '']

Try it online!
Explanation
The function im2col(m,b) takes a matrix m, extracts blocks of size b from it, and arranges them as columns. By default blocks are sliding (as opposed to distinct). Here the matrix m is a row vector of the ASCII codes of the input string s (this is done as +s, which is shorter than the standard double(s)), and the size b is [1 n] to obtain horizontally sliding blocks of n elements.
The result is transposed (using complex-conjugate transpose  ', which is shorter than transpose .') to turn the columns into rows, and then it is converted back to char ([... ''], which is shorter than the standard char(...)).

Python 2, 54 bytes
lambda x,n:map(''.join,zip(*[x[b:]for b in range(n)]))

Try it online!

C# 89 bytes
void a(string s,int n){for(int i=n;i<=s.Length;)Console.WriteLine(s.Substring(i++-n,n));}

Try it online!
Best method I could find in C# is basically the same as Java

Ruby, 48 46 bytes
->(s,k){0.upto(s.size-k).map{|i|s[i..i+k-1]}}

No particular tricks, just a stabby-lambda defining a function that pulls the required substring from each valid starting point.
Saved two bytes, since there doesn't seem to be a need to store the lambda.

V, 16 bytes
òÀ|ly0Ïp
"_xòkVp

Not terribly well golfed I'm afraid, struggling with "delete the string if k > len(str)".  Input is in the file, k is an argument.  Golfing before explanation
Try it online!

What happens if you do not try to handle the k > len(str) case?

Depending on the method I use (in this one in particular) it just leaves the string as is

Microsoft Sql Server, 199 bytes
create function dbo.f(@s nvarchar(max),@ int)returns table as return
with v as(select 2 p,left(@s,@)g where len(@s)>=@ union all
select p+1,substring(@s,p,@)from v where len(@s)>p-2+@)select g from v

Check it.

PowerShell, 70 bytes
$b={$c,$s=$args;[regex]::matches($s,"(?=(.{$c}))")|%{''+$_.groups[1]}}

Try it online!

Stacked, 7 bytes
infixes

Try it online!
Pretty standard. Without this builtin, it becomes 20 bytes:
{%x#'y-#+:>y#-#>x\#}

Which is:
{%x#'y-#+:>y#-#>x\#}
{%                 }   dyad; first arg: x, second arg: y
  x#'                  length of x (the array)
     y-                minus y (the skew)
       #+              plus 1
         :>            range [x, y]
           y#-         y minus 1
              #>       range from [[x, y], [x, y] + y]
                x\#    get indices from x

MATL, 3 bytes
YC!

Try it online!
Explanation
YC   % Sliding blocks of input string with input size, arranged as columns
!    % Transpose

Dyalog APL, 13 11 bytes
⊢,/⍨⊣⌊1+∘⍴⊢

It does exactly as intended now. Stupid errors.
Thanks to Adám for giving me the hint that there is an 11 byte solution, even though this isn't the one he was looking for.

… except when it doesn't.

There, it's fixed.

Good. Now golf it! (Hint: I can do it in 11.)

Well, now it works.

The third time's the charm. Still waiting for -2 bytes…

Would it be acceptable to switch the order of the operands?

Yes. I'm curious why you'd want to, though.

Never mind, I don't need it.

Does that work?

That is clever. Not the 11-byte solution I had in mind, but certainly more elegant.

Standard ML (mosml), 109 65 61 bytes
fun f(n,x)=if n>length(x)then[]else List.take(x,n)::f(n,tl x)

Takes a number and a character list (quite a common alternative to strings in the SML world). (Really works on all lists of course.)
Usage:
- f(3,explode("ABCDEFGH"));
> val it =
    [[#"A", #"B", #"C"], [#"B", #"C", #"D"], [#"C", #"D", #"E"],
     [#"D", #"E", #"F"], [#"E", #"F", #"G"], [#"F", #"G", #"H"]] :
  char list list
- f(7, explode("ABCD"));
> val it = [] : char list list

Changelog:

Right, there is a standard library.. (-44 bytes)
Change comparison and nil to [] as suggested (-4 bytes)

You can save a byte by changing if length(x)<n then to if n>length(x)then. However, as it is perfectly possible for SML to handle strings, I'm not sure it is allowed to require explode being already applied to the input string.

Also then nil else can be shortened to then[]else.

@Laikoni not sure either, but  ¯\(ツ)/¯

Using some other library functions I got a 68 byte version which deals with strings instead of char lists. Also your approach can be shortened to 54 bytes: fun f$n=if n>length$then[]else List.take($,n)::f(tl$)n.

Python 3, 49 bytes
f=lambda a,n:[a[i:i+n]for i in range(len(a)-n+1)]

Try it online!
A non-recursive solution, albeit not shorter.
Compatible with Python 2.

You can drop f=, saving two bytes, because you do not use f anywhere else. By default, functions that are just declared and not used can be left unnamed.

JavaScript (Firefox 30-57), 51 bytes
(s,n,t='')=>[for(c of s)if((t+=c)[n-1])t.slice(-n)]

64 bytes in ES6:
(s,n,t=s.slice(0,--n))=>[...s.slice(n)].map(c=>(t+=c).slice(~n))

PHP, 75 Bytes
Online Version
for([,$n,$s]=$argv;$i+$n-1<strlen($s);)$r[]=substr($s,$i++,$n);print_r($r);

80 Bytes without double values

for([,$n,$s]=$argv;$i+$n-1<strlen($s);)$r[$p=substr($s,$i++,$n)]=$p;print_r($r);

Haskell, 39 bytes
n#s|length s<n=[]|1<2=take n s:n#tail s

Usage example: 4 # "ABCDEF" -> ["ABCD","BCDE","CDEF"]. Try it online!
A simple recursion that keeps the first n chars of the input string an continues with the tail of the string as long as its length is not less than n.

Standard ML, 68 bytes
fun f$n=List.tabulate(size$ -n+1,fn m=>substring($,m,n))handle _=>[]

Try it online! Example usage: f "abcdef" 3 returns ["abc", "bcd", "cde", "def"].
Explanation:
For two bytes more we can replace the identifier $ by s to get better readable code:
fun f s n=List.tabulate(size s-n+1,fn m=>substring(s,m,n))handle _=>[]

The function takes a string s and an integer n as arguments. List.tabulate(m,g) takes an integer m and some function g and builds the list [g 0, g 1, ..., g(m-1)]. In this case, we give for m the size of the string s minus the n-gram length n (+1 to avoid off-by-one-errors). For each such m we return the substring of s at position m with length n.
In case of n > size s, an exception is thrown. handle _=>[] catches the exception and returns the empty list.

brainfuck, 52 bytes
[[>],+[<]>-]>[->]<[[<]>[.>]<[<]++++++++++.>[-]>[>],]

Try it online!
Takes K as the value on the starting cell and the string as input.

q/kdb+, 19 bytes
Solution:
{(0-x)_x#'next\[y]}

Example:
q){(0-x)_x#'next\[y]}[4;"ABCDEFGHIJ"]
"ABCD"
"BCDE"
"CDEF"
"DEFG"
"EFGH"
"FGHI"
"GHIJ"
q){(0-x)_x#'next\[y]}[4;"AC"]
q)

Explanation:
Use next and scan over the input string, then take the first 'x' (sliding window size), then drop off the extras from the end:
{(0-x)_x#'next\[y]} / the solution
{                 } / anonymous lambda with implicit args x and y
          next\[y]  / take 'next' element of y until exhausted
       x#'          / x take-each (take first x chars of each)
 (0-x)              / negate x
      _             / drop (negative drops from the end rather than front)

Japt, 2 bytes
Straightforward, built-in solution.
ãV

Try it


text:
Minus, Plus, Times, Exponentiation?
This is a CMC (chat mini challenge) that I posted in our chatroom, The Ninteenth Byte, a bit ago.
The Challenge
Given a positive integer x, depending on the last 2 bits of x, do the following:
x & 3 == 0: 0
x & 3 == 1: x + x
x & 3 == 2: x * x
x & 3 == 3: x ^ x (exponentiation)

Input/Output
Single Integer -> Single Integer

A trailing newline is permitted in the output. No other whitespace is permitted.
Testcases
input       output
    1            2
    2            4
    3           27
    4            0
    5           10
    6           36
    7       823543
    8            0
    9           18
   10          100
   11 285311670611
   12            0

This is a code-golf challenge, so the shortest code wins!

Shouldn't the 0 case be x + 2, seeing as how the others are x * 2, x ^ 2, and x ^^ 2 (tetration)? :P

What is the largest output we should support (regarding x ^ x)? 32-bit is already not enough for test case 11, and 64-bit is not enough for test case 19.

@KevinCruijssen I will say that you only have to handle cases where the input and output are in the scope of your language, as long as your program would theoretically work given infinite number size.

@HyperNeutrino Ok, in that case I've fixed my (Java 7) code (for +72 bytes.. xD)

Jelly, 8 bytes
ị“+×*_”v

Try it online!
How it works
Firstly, notice that x&3 is equivalent to x%4, where % is modulo. Then, since Jelly uses modular indexing (a[n] == a[n+len(a)]), so we don't even need to deal with that.
Then:

If x%4==0, return x_x (subtraction) (for consistency);
If x%4==1, return x+x;
If x%4==2, return x×x(multiplication);
If x%4==3, return x*x(exponentiation)

Note that Jelly uses 1-indexing, so the subtraction "_" is moved to the end.
ị“+×*_”v  example input: 10
ị“+×*_”   index 10 of the string “+×*_”, which gives "×"
       v  evaluate the above as a Jelly expression,
          with 10 as the argument, meaning "10×" is the
          expression evaluated. The dyad "×" takes the
          second argument from the only argument, effectively
          performing the function to itself.

@andrybak AFAIK Jelly has its own encoding - see here, but I do know that all of its characters are 1 byte.

"8 bytes". How should bytes be counted? This answer consists of eight characters, but at least in the encoding stackexchange serves this page, it takes up 15 bytes (counted using wc --bytes).

If the language interprets it in one encoding, it doesn't make sense to use another encoding for the byte count (imo)

@andrybak The code encoded in an encoding so that the browser shows it correctly is 15 bytes. The code in an encoding that Jelly understands it is 8 bytes. Look at https://github.com/DennisMitchell/jelly/wiki/Code-page if you want to know how it is encoded.

Python, 30 bytes
lambda x:[0,x+x,x*x,x**x][x%4]

Try it online!

Alternative version on python 2: 'lambda x:[0,2,x,x**x/x][x%4]*x'.

CJam, 12 bytes
ri__"-+*#"=~

Try it online!
Explanation
ri            e# Read an int from input (call it x).
  __          e# Duplicate x twice.
    "-+*#"    e# Push this string.
          =   e# Get the character from the string at index x (mod 4).
           ~  e# Eval that char, using the two copies of x from before.

Runs one of the following operations depending on x's value mod 4 (mod 4 is equivalent to AND 3).
0:  -  Subtraction
1:  +  Addition
2:  *  Multiplication
3:  #  Exponentiation

Mathematica 25 Bytes
0[2#,#*#,#^#][[#~Mod~4]]&

Saved 4 Bytes thanks to @MartinEnder

Ruby, 26 bytes
->x{x*[0,2,x,x**~-x][x%4]}

Try it online!

Pyth, 8 bytes
.v@"0y*^

Interpreter

Yes I have tested this and it works. And no, I can't use v instead of .v.

I thought the scope was local... I thought .v cannot access Q... Apparently I got outgolfed in Pyth. +1 for you.

@LeakyNun No it's v which has local scope, .v just evals an expression.

I have much to learn...

@LeakyNun You do have much to learn. Also, Pyth is almost as confusing as Jelly, so I forgive that :)

That's beautiful! That's absolutely amazing! I had no idea that was even possible. For style points, "0y*^ could be "-+*^.

@isaacg So you didn't implement .v, right? And I purposefully chose the former because I don't see any reason to do x-x instead of 0 or x+x instead of x*2.

Lol guys why are you acting like WOW WHOA WTF? I just don't get it at all...

@EriktheOutgolfer I implemented .v. I hadn't realized that when I implemented auto-variable introduction that it allow .v to handle this sort of case. Note for instance that this fails, because while .v autointroduces variables, it doesn't take input. The fact that Q had already been instantiated by the modular indexing is essential to making this work.

@isaacg Yeah I get it, it does indeed run in a local scope then.

PHP, 37 Bytes
<?=[0,2*$x=$argn,$x*$x,$x**$x][$x&3];

Online Version
PHP, 47 Bytes
<?=(bc.[sub,add,mul,pow][($x=$argn)&3])($x,$x);

Online Version
BC Math functions

Haskell, 28 27 bytes
f x=cycle[0,x+x,x*x,x^x]!!x

Try it online!
Edit: Thanks to @Ørjan Johansen for 1 byte.

Hm I'm very late, but you could shorten this a byte with cycle.

@ØrjanJohansen: better late than never. Thanks!

JavaScript, 24 bytes
a=>[0,a+a,a*a,a**a][a%4]

Try it online!

Java 7, 75 bytes
long c(int n){int x=n%4;return x<1?0:x<2?n+n:x<3?n*n:(long)Math.pow(n,n);}

Even though it is valid according to the rules, long is 64-bits, so it fails for the exponentiation test cases of 19^19 and above. To fix that we can use a BigDecimal approach:
148 146 bytes
import java.math.*;BigDecimal c(int n){int x=n%4;BigDecimal m=new BigDecimal(n);return x<1?m.subtract(m):x<2?m.add(m):x<3?m.multiply(m):m.pow(n);}

Explanation (of BigDecimal approach):
import java.math.*;                // Import required for BigDecimal
BigDecimal c(int n){               // Method with integer parameter and BigDecimal return-type
  int x=n%4;                       //  Input modulo-4
  BigDecimal m=new BigDecimal(n);  //  Convert input integer to BigDecimal
  return x<1?                      //  If the input mod-4 is 0:
    m.subtract(m)                  //   Return input - input (shorter than BigDecimal.ZERO)
   :x<2?                           //  Else if the input mod-4 is 1:
    m.add(m)                       //   Return input + input
   :x<3?                           //  Else if the input mod-4 is 2:
    m.multiply(m)                  //   Return input * input
   :                               //  Else:
    m.pow(n);                      //   Return input ^ input
}                                  // End of method

Test code:
Try it here.
import java.math.*;
class M{
  static BigDecimal c(int n){int x=n%4;BigDecimal m=new BigDecimal(n);return x<1?m.subtract(m):x<2?m.add(m):x<3?m.multiply(m):m.pow(n);}

  public static void main(String[] a){
    for (int i = 1; i <= 25; i++) {
      System.out.print(c(i) + "; ");
    }
  }
}

Output:
2; 4; 27; 0; 10; 36; 823543; 0; 18; 100; 285311670611; 0; 26; 196; 437893890380859375; 0; 34; 324; 1978419655660313589123979; 0; 42; 484; 20880467999847912034355032910567; 0; 50;

You don't need to fix the program this way :P The old answer would work if numbers had infinite size; the first program would have been valid under my specs. :P

@HyperNeutrino Then I specify that in the answer.. Ah well, Java won't win any code-golf challenges anyway. ;)

Yes, I would specify. And yes, it's Java, it's not going to win. :D

"And yes, it's Java, it's not going to win. :D" I'm used to it. :P Even my shortest Java answer ever of 8 bytes is way to long compared to the golfing answers. xD Although it was the first time I had beaten a Python answer with my Java answer, which has to count for something I guess. ;)

C, 63 or 62 bytes
#include<math.h>
f(x){return(int[]){0,x+x,x*x,pow(x,x)}[x&3];}

-1 byte if macros are allowed, assuming x is not an expression like 3+5 (since that'd mess up the precedence):
#include<math.h>
#define f(x)(int[]){0,x+x,x*x,pow(x,x)}[x&3]

@ceilingcat Right, forgot about that.

does not compile on MSVS2015; Intellisense said cast to incomplete array type "int[]" is not allowed Compiler said error C4576: a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax; ALSO! where is int f(int x)? code is actually at least 8 bytes longer; also it is very slow and inefficient, as it evaluates everytning - dont repeat it IRL)

@xakepp35 What? 1) it has to compile in a C compiler. Most (read: just about all but MSVC) C compilers support this (int[]) syntax for this situation. 2) f(x) is perfectly legal C89. I didn't specify the standard. 3) This is about code size, not efficiency. And 4) If you're going to be patronizing, at least use a real compiler and/or check your facts.

@Tim Čas Ah yes, rly sorry! I was trying to compile it as C++ code. That's my fault) It compiles and works great!

x86 Assembler, Intel syntax, 192 bytes
.data
f dw @q,@w,@e,@r
.code
mov ecx, eax
and ecx, 3
mov edx,dword ptr f[ecx*4]
call [edx]
ret
q:
xor eax,eax
ret
w:
add eax,eax
ret
e:
mul eax,eax
ret
r:
mov ecx,eax
t:
mul eax,eax
loop t
ret

Example pretends for fastest working speed. Is is a program or program part, which uses fastcall convention. It assumes input variable x in register eax, and returns result also in eax. Basic idea is stay away from using conditional jumps, as in some examples here. Also, it is not to evaluate everything (as in C example with arrays) but to use array of pointers to functons and make faster unconditional jumps (jmp/call) as an optimized "C language switch()-case.." analog. This technique could be also useful in kinds of finita automata - like processor emulators, executors and so on.
Upd: for x64 use "r" in register names, instead of "e" (e.g. rax instead of eax, rcx instead of ecx). Size will not be changed, and it will use 64-bit unsigned words.

Welcome to PPCG! The objective of this challenge is to make your code as short as possible. In this case, your code could easily be shortened a bunch by combining all those function declarations. You can also remove some whitespace.

@HyperNeutrino asm itself is kinda "long" language :) so i dont have an idea on how to make this shorter. any example-advices?

Eh, sorry, I must have copied my comment on your C answer into this post. I don't know how to program in ASM but could you potentially remove some whitespace?

@HyperNeutrino, sorry.. but seems no) it has to be longest code among others, i can just trunc windows crlf to linux format so 209->192 bytes, changes are not visible)

Aw. That's too bad. But nice submission regardless! :)

C#, 39 bytes
x=>new[]{0,2,x,Math.Pow(x,x-1)}[x&3]*x;

Explanation
Observe that:
(x-x, x+x, x*x, x^x) == (0, 2, x, x^(x-1)) * x
The solution creates an array, indexes into it and then multiplies the result by x:
x => new[] { 0, 2, x, Math.Pow(x,x-1) }[x&3] * x;

Alternative versions:
x=>new[]{0,x+x,x*x,Math.Pow(x,x)}[x%4];

(39B, all multiplication done in the array, x%4 replaces x&3)
x=>x%4<2?x%2*2*x:Math.Pow(x,x%4<3?2:x);

(39B, same as @MetaColon's answer but x%2*2*x replacing x*x%4<1?0:2)

PHP, 36 bytes
<?=[0,2,$x=$argn,$x**~-$x][$x&3]*$x;

dc, 27
I've never had the occasion to use arrays in dc before:
[+]1:r[*]2:r[^]3:r?dd4%;rxp

Try it online.

Oasis, 25 bytes
mn4%3Q*nkn4%2Q*nxn4%1Q*++

Try it online!
How it works
Notice that x&3 is equivalent to x%4, where % is modulo.
mn4%3Q*nkn4%2Q*nxn4%1Q*++  input is n
mn4%3Q*                    (n**n)*((n%4)==3)
       nkn4%2Q*            (n**2)*((n%4)==2)
               nxn4%1Q*    (n*2)*((n%4)==1)
                       +   add the above two
                        +  add the above two

Oasis is a stack-based language where every character is a command.

C#, 42 Bytes
x=>x%4<2?x*x%4<1?0:2:Math.Pow(x,x%4<3?2:x)

Actually it's normal C#, but as you can't run it as a whole program and you have to type it into the interactive, I guess you may call it C# interactive.
Explanation:
x => (x % 4) < 2     //If the bits are smaller than 2 (1 or 0)
? x *           //multiply x with
    (x % 4) < 1 //if the bits are 0
    ? 0         //0 (results in 0)
    : 2         //or else with 2 (results in 2*x or x+x)
: Math.Pow(x,   //otherwise power x by
    (x % 4) < 3 //if the bits are 2
    ? 2         //2 (results in x^2 or x*x)
    : x);       //or else x (results in x^x)

I can't tell wether it's the shortest variant, any suggestions are appreciated.

I don't think that's valid. You generally should submit a program or function. Snippets are not allowed by default.

@Cyoce It is a program. You just have to run it through the interactive, which will interpret the program.

When I run this in interactive, I get an error because x is not defined. That makes this a snippet, not a full program.

@Cyoce In the challenge it said, there'd be a variable x defined.

That's not what that means. "Given a positive integer x" means that you are being given x through a standard input method (i.e., function or program).

Just add x=> to the start of the submission and you're fine.

Also, you can call it C# instead of C# Interactive. Function submissions don't require any enclosing class or other boilerplate (except the function declaration, which you have included)

Cubix, 29 bytes
.;.O+@.UOI:4%!^s;((?u.^P;<^*;

Try it online!
Explanation will be added soon...

C, 115 bytes
#include<math.h>
#define D(K,L)K(x){return L;}
D(q,0)D(w,x+x)D(e,x*x)D(r,pow(x,x))(*g[])()={q,w,e,r};D(f,g[x%4](x))

Example is a function int f(int x)
It pretends for fastest working speed as it keeps CPU away from using conditional jumps. And this is only correct speed-optimisation way for this task. Also, it tries not to evaluate everything, as in array C example return(int[]){0,x+x,x*x,pow(x,x)}[x%4]; But but to wisely use array of pointers to functons, in order to make much faster unconditional jumps (jmp/call) with much faster address arithmetics, as an optimized version of "switch()-case..". This technique could be also useful in several kinds of finita automata - like processor emulators, executors, command stream parsers, and so on - where speed matters and code like switch(x%4) case(0):... case(1):...  is unsuitable because it produces multiple cmp/jnz instructions; and these are costly operations for CPU
Simpliest and shortest test program (in default conditions) for the case will be as follows:
D(main,f(x))

It will add just 12 bytes of payload and will total our size to 127 bytes;
But you should better tell the linker to use f function as an entry point, instead of main. That is the way, if we aim to get fastest possible working binary for this task from shortest code ;-) This happens because C library adds extra init/shutdown code before calling your main() function.
Code compiles on MSVS Community 2015 without any tricks and issues and produces correct results. I haven't tested it with gcc, but i'm sure it will work fine as well.

Welcome to PPCG! The objective of this challenge is to make your code as short as possible. In this case, your code could easily be shortened a bunch by combining all those function declarations. You can also remove some whitespace.

I like the idea of using pointers to functions

@RosLuP ye, but its almost twice longer than your 60 bytes version. but it  works much faster, it is worth its size.

@Hyper Neutrino Okay. I've compressed it more. Seems, this is final version! There are no bugs, all tests passed 8-)

@xakepp35 did you measure your is faster than my?

@RosLuP sure:D for 2147483648 iterations of i=f(i) runtime for your version is 6.98236s, function works with 307.558mhz frequency

@RosLuP And my version runs only for 3.908s runtime; 549.51mhz; So it is 1.78x faster; Man; Just read on how does branch predictor works; and what happens if prediction was wrong. All "if" are slow as hell!!! If you could avoid using conditional jumps - avoid using it! So, you use x%2? - what is that "?"? how do you think?) Hint - compile two versions and compare their disassembly code!

@Tim Čas and your version is slowest among us; 10.2782s runtime
208.935mhz; And also RosLuP has shorter version. So he won, both in approach and length; Upvoting his ver, as this is code golf for shortest code ;-)

I even thought about new computer architecture, where CPU is one chip, with multiple cores, only capable of handling all IFs and tnat kind of conditional execution in a simd like way (and without any ALU). And GPU(ALU) therefore will be a separate chip capable of just doing large scale simd-like maths. But seems to be too lazy and have lack of free milliards of dollars to implement this =)))

@xakepp35 "2147483648 iterations of i=f(i) runtime for your version is 6.98236s" for me is fast enough;  not are these the problems in slow code... The same jnz jump and loop I not find they slow dow the code too much. The real problem is the code is wrong because from input 11 return wrong results (if I remember well it return a wrong value without some warning to the user of the function)

@RosLup, it does not matter what is enough for you or me. We told about speed benchmarks and relative comparison., and bad programmer is a programmer that chooses 1.7x slower algorithm just because it is shorter/simplier. Whole PC world lags problems arose from tnat decision motivation. On other hand, you said "enough for you"/ I always leave place for situation, wrere i make mistake/misassumption. So maybe i am wrong.. Lets clear this out! What do you mean? Where exactly do you use current algorithm? And how do you consider is it "enough" or "not enough"? Have you tried some benchmarks?

@RosLup and for big numbers we could use int64 or even double types, or, even, we could use some kind of bigint (arbitary precision int arithmetics) libraries, if that is really required. but that was not the point.

Groovy, 26 bytes
{x->[0,x+x,x*x,x**x][x%4]}

Try it online!

Actually, 12 bytes
;;3&"-+*ⁿ"Eƒ

Try it online!
Explanation:
;;3&"-+*ⁿ"Eƒ
;;            two copies of input (so 3 total)
  3&          bitwise AND with 3
    "-+*ⁿ"E   index into this string
           ƒ  call the respective function

05AB1E, 10 bytes
Ð"-+*m"è.V

Uses the 05AB1E encoding. Try it online!

J, 14 bytes
4&|{0,+:,*:,^~

Try it online!

(4&|{-,+,*,^)~ works as well but it's the same byte count due to parens, although it's slightly more obvious what it does.

R, 47 42 bytes
x=scan();c(`-`,`+`,`*`,`^`)[[x%%4+1]](x,x)

Applies the function -, +, *, or ^ based on the modulus of x to x and x.
- is the only (somewhat) smart thing, since x-x is always 0.
R, 33 bytes
pryr::f(c(0,2*x,x^2,x^x)[x%%4+1])

Same method as other people use. Though it is shorter, I don't like it nearly as much.

TI-BASIC, 27, 23 bytes
:Prompt X          //Get input as X, 3 bytes
:{2X,X²,X^X,0      //Implicitly store the list {2X,X²,X^X,0} to Ans, 16 bytes
:Ans(remainder(X,4 //Compute X&3 (as X%4), get that element of the list, and implicitly print 8 bytes

TI-BASIC doesn't have bitwise operators, so I used the modulus operator (remainder() instead.

oK, 20 bytes
{*/(."-+*#"4!x).x,x}

Try it online!

C (gcc), 59 bytes
#include<math.h>
h(x){return x&2?pow(x,x&1?x:2):(x&1)*2*x;}

Test and results. It overflows at 11.
main()
{int i;
 for(i=0;i<20;++i)
       printf("%u %u\n", i, h(i));
}

0 0
1 2
2 4
3 27
4 0
5 10
6 36
7 823543
8 0
9 18
10 100
11 1843829075
12 0
13 26
14 196
15 1500973039
16 0
17 34
18 324
19 0

Ideone
Try it online!

Why someone  downvote this?

does not compile.int main(); int h(int x) please!

@xakepp35 here http://ideone.com/4eI270 it compile; if it is for arguments of function, in a old standard they are seen from compiler all as int...

In "tio" gcc compier not compile even this: #include <math.h>
#include <stdlib.h>
double h(int x){return x&2?pow((double)x,(double)(x&1?x:2)):(double)((x&1)2x);}; it says the linker not find the pow function (double pow(double, double) in math.h header)

The trick it is to add "-lm" [link math functions] to the line compiler is called

but its actually 68 bytes, ok?)

latest MSVS community dont compile without types

@xakepp35 "msvs" compiler has to have the option for compile ANSI or K&R C code... In filename.c  gcc and bcc compile it show only some warning for the name of functions library have no type declaration or equivalent...

Pure Bash, 35
a=(- + * **)
echo $[$1${a[$1%4]}$1]

Try it online.

Japt, 13 bytes
Ov"^+*p"gU +U

Try it online!
This uses the same method as the other eval answers, except the program -U just negates U, so we use ^ (bitwise XOR) instead.

Vim, 50 bytes
y$o^R"A-+*^^V^[0^R"lx0"_Dp^[0D@"kJ0"ad$:r!echo ^R"^R0|bc^<Enter>

Here, ^V represents a Ctrl+V, ^R represents Ctrl-R and ^[ represents the esc key
Works by first building up the expression and then letting bc evaluate it. Expects the input on the first line in an otherwise empty buffer.
Explanation:
y$o^R"                                                          Copies the input into register " and pastes it on the second line
      A-+*^^V^[0^R"lx0"_Dp                                      Enters that text after the input on the second line
                          ^[0D@"                                Executes the second line as a Vim command.
                                                                For example, if the input is 12, the second line would be 12A-+*^^[012lx0"_Dp, which means:
                                                                  12A-+*^^[           Insert the text -+*^ 12 times
                                                                           012lx0"_Dp Go 12 chars to the right and remove everything except for that.
                                                                If effect, this basically just selects the appropriate operation.
                                kJ0"ad$                         Put the operator after the number, cut it into register a
                                       :r!                      Execute the following shell command and put the result into the buffer:
                                          echo ^R"^R0|bc<Enter> The shell command "echo [contents of register a][contents of registers 0]|bc. As said above, register a contains the input and the operator, and register 0 contains the input. The <enter> then executes this command.

When I type ^V it just pastes what I have in my clipboard, instead of the number...

Try it online! Also, You can do D instead of d$

Pyth, 9 bytes
@[0yQ*QQ^

Test suite
Nothing fancy going on here, just calculate the four values, and select one with modular indexing.
@[0yQ*QQ^
@[0yQ*QQ^QQ)Q    Implicit variable introduction
@           Q    Modularly index into the following list
 [0        )     0
   yQ            Q*2
     *QQ         Q*Q
        ^QQ      Q^Q

Batch, 135 bytes
@set/an=%1*2^&6
@goto %n%
:6
@set n=1
@for /l %%i in (1,1,%1)do @set/an*=%1
@goto 0
:4
@set n=%1
:2
@set/an*=%1
:0
@echo %n%

I was hoping to create the exponentiation by building up and evaluating a string of the form [0+...+0, 2+...+2, x+...+x, x*...*x] depending on the last two bits of x but unfortunately the code to select the operation took too long to express because I couldn't use * as a for parameter, but I was at least able to use some fall-though trickery to golf away some bytes.

Retina, 87 bytes
.+
$*1;$&$*
;((1111)*)(1?)$
;$3$3
1(?=1.*;((1111)*111)$)
$1;
+`\G1(?=.*;(1*))|;1*$
$1
1

Try it online! (Link includes test suite.)
Explanation: The first two lines convert the input into unary and duplicate it (so we now have x;x). The next two lines look for an x&3 of either 0 or 1 and change x;x into x;0 or x;2 appropriately. The next two lines look for x&3==3 and change x;x into x;x;x;...;x;1;x (x xs). This means that we have either x;0, x;2, x;x, or x;...;x and it remains to multiply everything together and convert back to decimal. (The multiplication code is based on that in the Retina wiki but amended to handle multiplication by zero.)

vba, 101
Function x(f)
Select Case f Mod 4
Case 0:x=0
Case 1:x=f+f
Case 2:x=f*f
Case 3:x=f ^f
End Select
End Function

Dyvil, 24 Bytes
x=>[0,x+x,x*x,x**x][x&3]

Usage:
let f: int->int = x=>[0,x+x,x*x,x**x][x&3]
print f(10) // => 100

Explanation:
The code creates a lambda expression that takes and returns a 32-bit integer. The body stores the result of all calculations in an array and retrieves the result from the index given by the last 2 bits of x.

Swift, 105 68 67 bytes
Here is the body of the function:
i in let a=i%4;return [0,i+i,i*i,Int(pow(Double(i),Double(i)))][a]

Here is the full implementation:
import Foundation;var e:(Int)->Int={i in let a=i%4;return [0,i+i,i*i,Int(pow(Double(i),Double(i)))][a]}

Try it here

Axiom, 59 33 bytes
h(x)==[0,x+x,x*x,x^x].(1+x rem 4)

traslate in Axiom the answer of Mego... this is the old 59 bytes
h(x)==(x quo 2 rem 2=1=>(x rem 2=0=>x^2;x^x);(x rem 2)*2*x)

results
(24) -> for i in 0..30 repeat output [i,h(i)]
   [0,0]
   [1,2]
   [2,4]
   [3,27]
   [4,0]
   [5,10]
   [6,36]
   [7,823543]
   [8,0]
   [9,18]
   [10,100]
   [11,285311670611]
   [12,0]
   [13,26]
   [14,196]
   [15,437893890380859375]
   [16,0]
   [17,34]
   [18,324]
   [19,1978419655660313589123979]
   [20,0]
   [21,42]
   [22,484]
   [23,20880467999847912034355032910567]
   [24,0]
   [25,50]
   [26,676]
   [27,443426488243037769948249630619149892803]
   [28,0]

Pyth, 12 bytes
.vjd,+@"-+*^

Try it online!
How it works
Firstly, notice that x&3 is equivalent to x%4, where % is modulo. Then, since Pyth uses modular indexing (a[n] == a[n+len(a)]), so we don't even need to deal with that.
Then:

If x%4==0, return x-x (for consistency);
If x%4==1, return x+x;
If x%4==2, return x*x;
If x%4==3, return x^x.

.vjd,+@"-+*^  example input: 10
      @"-+*^  "-+*^"[10], which is "*"
     +        "*10"
    ,         ["*10","10"]
  jd          "*10 10"
.v            evaluate as Pyth expression
              (Pyth uses Polish notation)

More about Polish notation: Wikipedia (too bad if you are in Turkey).

Huh? This just seems too much to me. See my answer for details.


text:
Mortarboard Challenge
Challenge
Given a user's ID, determine how many times they have hit the repcap.
Specs
On a given day, let's a user has hit the repcap if they had reputation that wasn't gained due to the repcap. Essentially, on any given day, if the user's net reputation change as calculated without any cap was different from their actual observed reputation change, then they hit the repcap.
Input/Output
Input will be a single integer, the user's ID.
Output will be a single integer, indicating the number of days for which they had reputation that was "lost".
I/O can be in any reasonable format.
Test Cases
Feel free to add your own ID and stats here. The brackets indicate which user it is, but that isn't part of the output. Don't include it.
input -> output (username)
42649 -> 0 (HyperNeutrino)
41723 -> 7 (Fatalize)
46271 -> 0 (Riker) (This user has obtained 200 rep twice, but never over)

For the record, your criterion is different from that of the mortarboard badge. For that you just need 200 rep, even if you haven't got the rep cap at that point (the rules are a bit more complicated because not all rep changes count towards the badge).

@MartinEnder Yes. I decided to simplify it so people didn't have to count badge progress. Essentially, it counts if and only if the user didn't gain rep they otherwise would have.

This question is of interest to me because I happened to hit the rep cap a couple of times last month and I've already hit it again today. +1

Very related :)

@StewieGriffin I was inspired to write this challenge because of your challenge, in fact. :) :P

JS ES6, 360 bytes
f=(i,p=1,d=[])=>fetch(`https://api.stackexchange.com/2.2/users/${i}/reputation?site=codegolf&pagesize=100&page=${p}`).then(x=>x.json()).then(j=>(q=d.concat(j.items),j.has_more?f(i,p+1,q):(r=[],q.map(s=>(r[d=new Date(s.on_date*1000),i=d.getDate()+d.getMonth()*32+d.getYear()*365]?r[i]+=s.reputation_change:r[i]=s.reputation_change)),r.filter(x=>x>200).length)))

Call it like f(user id). Returns a promise that resolves with the number of days that rep was lost.
Ungolfed:
f=(i,p=1,d=[])=>fetch(`https://api.stackexchange.com/2.2/users/${i}/reputation?site=codegolf&pagesize=100&page=${p}&key=kAc8QIHB*IqJDUFcjEF1KA((`).then(x=>x.json()).then(j=>{
    return (q=d.concat(j.items),
    j.has_more?
        f(i,p+1,q)

        :(r=[],
            q.map(s=>(r[d=new Date(s.on_date*1000),
                i=d.getDate()+d.getMonth()*32+d.getYear()*365]?
                    r[i]+=s.reputation_change

                    :r[i]=s.reputation_change)),
            r.filter(x=>x>200).length
        )
    )
});