# Question
Title: Make your language *mostly* unusable! (Cops' thread)
*Inspired by this comment...*

*Thanks to users Step Hen, Wheat-Wizard, and Dennis for helping my solidify the specification of this challenge before posting it!*

*This is the Cops' thread. For the Robbers' thread, go here*

---

In this challenge, you are tasked with running some code that makes it so that your language no longer satisfies our criteria of being a programming language. In that challenge, that means making it so that the language can no longer...

* Take numerical input and output
* Add two numbers together
* Test if a certain number is a prime or not.

This is a challenge, where there are two different challenges with two different objectives: the *Cops* will try to write some code that makes the language *mostly* unusable, and the *robbers* will try to find the hidden workaround that allows the cops to recover their language.

As a cop, you must write two snippets of code:

1. One that makes your language mostly unusable, e.g. by removing built-in functions for taking input/output and numerical operations. The more features you remove, the better. This code is **not** allowed to crash or exit. It should be possible to add code to the end of this snippet, and that code *will get evaluated*. And...
2. ...a snippet of code that takes two non-negative integers as input, adds them together, and outputs their sum. This snippet must still correctly function even after running the first snippet. When the two snippets are combined together, they must form a full program that adds two numbers, or define a function that adds two numbers. Ideally, this snippet should rely upon very obscure behavior, so as to be more difficult to find.

You may choose any standard method of input and output. However, you must reveal exactly which format (input and output) you are using. A robber cannot crack your answer unless they use the same format as you.

After writing both of these snippets, you must post the first one as an answer, without revealing the second one. Your answer should contain all of the following information:

* The *first* snippet (obviously not the second).
* Language (including minor version, since most submissions will probably rely on strange edge-cases)
* IO format, including whether it's a function or full program. Robbers *must* use the same format for their crack to be valid.
* Any strange edge cases required for your answer to work. For example, *only runs on linux*, or *requires an Internet connection*. Obviously, this is slightly subjective, but if a cop has some extreme edge case that prevents it from being cracked, and then only reveals this after being safe, I consider this poor sportsmanship. A potential robber should have all information necessary to crack your answer *before* it is cracked.

You do not need to reveal your byte count until your answer is safe.

Here's an example. For the first snippet, you could submit the following Python 3 program:

> # Python 3
>
> ```
> print=None
>
> ```
>
> Takes input from STDIN and output to STDOUT

And then as your second snippet, you could write:

```
import sys
a,b=int(input()),int(input())
sys.stdout.write(a+b)

```

This is valid because it will take two numbers as input, and output their sum even if you join the two snippets together, e.g.

```
print=None
import sys
a,b=int(input()),int(input())
sys.stdout.write(a+b)

```

However, this will be extremely easy for a robber to find a solution to. Since this would be very easy to crack, you could attempt to patch this particular approach like so:

```
import sys
sys.stdout=None
print=None

```

However, even this has a very easy workaround:

```
del print
a,b=int(input()),int(input())
print(a+b)

```

As a cop, your goal is to make the hidden workaround as obscure as possible, to prevent the robbers from finding it.

The *robbers* will look at one of your answers, and attempt to crack it. They may crack it by writing *any* valid snippet that could work as snippet 2 (adding two numbers together after the language is made mostly unusable). This does *not* have to be the same snippet as you originally intended. If a robber cracks your answer, they will leave a comment on your answer, and then you should edit it to indicate that it has been cracked. If your post is cracked, you should edit your answer to show the solution (snippet 2) that you originally intended. This isn't a *rule per se*, just a friendly suggestion to keep the game fun. You do not have to.

If an answer remains uncracked for one whole week, you can edit in your second snippet, and indicate that your answer is now *safe*. If you do not edit it after the week is up, other users can still crack it until you do. If you do not reveal your second snippet, you cannot claim points for your answer, or call it safe.

The winner of the cops' thread is the shortest safe answer *including both snippets*, counted in bytes, and this answer *will* be accepted after sufficient time has passed. You do *not* need to reveal your byte count until your answer is safe, since byte count is irrelevant to your score until your answer is safe. In the event that sufficient time has passed and no answers remain uncracked, the winner will be the answer that remained uncracked for the longest period of time.

Have fun!

# Rule clarifications

* The first snippet must run correctly *without taking any input*. It may output whatever you like, and this output will be ignored - as long as after the snippet is done, the second snippet runs correctly.
* The second snippet *must actually be executed* for your answer to be valid. This means an answer like

```
import sys
sys.exit()

```

is not valid because it doesn't break the language. It simply quits. Similarly, entering an infinite loop is not valid, since the second snippet will never be executed.
* After being safe, your score is the byte count *of both snippets*.
* This goes back to *Please reveal any strange edge cases required for your answer to work*... Your submission must contain enough information *before* being revealed to be reproducible *after* being revealed. This means that if your answer becomes safe, and then you edit in: *Here's my answer. Oh ya, BTW this only works if you run it on Solaris, joke's on you!* your answer is invalid and will be deleted and not considered eligible for winning.
* The second snippet is allowed to crash after outputting the sum - as long as the output is still correct (for example, if you choose to output to STDERR, and then you get a bunch of crash information, this is invalid).
* You may not edit your code after submitting an answer.
* You may not rely on cryptographic functions like encryption, hash functions, CSPRNGs etc.

### Snippet to find uncracked submissions:

```
<script>site='meta.codegolf';postID=5686;isAnswer=false;QUESTION_ID=133174;</script><script src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='//api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```

# Answer
# Gforth 0.7.3 (TIO), 231 bytes \[SAFE\]

This code redefines as useless some necessary output methods, as well as addition and something crucial for declaring functions. Good luck!

```
: . ;
: dec. ;
: u. ;
: .r ;
: u.r ;
: d. ;
: ud. ;
: d.r ;
: ud.r ;
: emit ;
: type ;
: + postpone 2drop ;
: ; + + + postpone exit reveal postpone [ ;

```

Input will be two signed integers taken from the top of the stack as function parameters. Output to STDOUT.

So you should fix the damage done, and define a function that takes the top two values from the stack and prints the result as an integer (not a float) to STDOUT without additional output (no trailing space).

Here's a template, if your goal function is named `f`.

### Solution:

> **79 bytes**
> I actually removed the `immediate` keyword from the end of the redefinition of `;`, so it was necessary for an answer to include it at the start. The function I defined is mostly equivalent to the internal definition of `.`, but it doesn't print the space at the end, and the addition is performed first, by moving the numbers to the floating point stack and back.
> `immediate : f s>f s>f f+ f>d swap over dabs <<# #s rot sign #> (type) #>> 0 0 ;`
> **Try it online**
> 2 votes

# Answer
# Haskell, cracked by Christian Sievers

```
import Prelude(getLine,print)
a=a

```

Full program, reading two integers (including negative ones) from stdin and writing to stdout.

I've just disabled the Prelude so almost nothing is in scope, and then added a definition; further imports are syntactically invalid. I gave you `getLine` and `print` though.

---

Edited to add my original solution. Christian's crack was different, but exploits the same basic features (you can get a surprising amount of computation done by accessing functions that have syntactic sugar, even when you can't call anything builtin directly or even name the types involved).

```
import Prelude(getLine,print)
a=a
(x:l)!0=x
(x:l)!n=l!d[0..n]
d[x,y]=x
d(x:l)=d l
x^y=[x..]!y
x+y=f[0..y](x^y)(-((-x)^(-y)))
f[]x y=y
f _ x y=x
f.g= \x->f(g x)
f&0= \x->x
f&n=f.(f&d[0..n])
x*y=((+x)&y)0
x%[]=x
x%('-':s)= -(x%s)
x%(c:s)=x*10+i c%s
i c=l['1'..c]
l[]=0
l(x:s)=1+l s
main=do
 x<-getLine
 y<-getLine
 print((0%x)+(0%y))

```

Which probably isn't super-golfed anyway, but here it is more readibly:

```
import Prelude(getLine,print)
a=a

-- List indexing
(x : _) !! 0 = x
(_ : xs) !! n = xs !! (sndLast [0..n])

-- sndLast [0..n] lets us decrement a positive integer
sndLast [x, _] = x
sndLast (_ : xs) = sndLast xs

-- Pseudo-addition: right-operator must be non-negative
x +~ y = [x..] !! y

-- Generalised addition by sign-flipping if y is negative
x + y = switch [0..y] (x +~ y) (-((-x) +~ (-y)))
  where switch [] _ empty = empty   -- [0..y] is null if y is negative
        switch _ nonempty _ = nonempty

f . g = \x -> f (g x)

-- compose a function with itself N times
composeN f 0 = \x -> x
composeN f n = f . (composeN f (sndLast [0..n]))

-- multiplication is chained addition
x * y = composeN (+x) y 0

strToNat acc [] = acc
strToNat acc ('-' : cs) = -(strToNat acc cs)
strToNat acc (c : cs) = strToNat (acc * 10 + charToDigit c) cs

charToDigit c = length ['1'..c]

length [] = 0
length (_ : xs) = 1 + length xs

main = do
  x <- getLine
  y <- getLine
  print (strToNat 0 x + strToNat 0 y)

```
> 21 votes

# Answer
# Python 2, Cracked

*Implements addition as a named function*

```
import sys
c="".join(open(__file__).read().split('\n')[4:])
if set(c)-set(' &)(,.:[]a`cdfijmonrt~')or"import"in c:sys.setrecursionlimit(1)
f=lambda\

```

Try it online!

## What does this do?

For the purposes of helping you out a bit I'll explain what this does. This code opens the source file and checks if the remainder of the code fits the following criteria:

* Does not contain the string `import`
* Is made solely of the characters  `&)(,.:[]a`cdfijmonrt~`

If it fails either criterion the recursion limit is set to `1` meaning that any code you write will hit the recursion limit.

There are no tricks here, I have written a solution that uses only these characters and no imports, I'm not doing anything subversive, but I will say that I think this will be pretty hard to crack.

To save you some time here is a short list of useful things you cannot do with this restriction

* `+` well duh,
* `eval`/`exec` Wasn't going to let you get away with that
* Numbers, They might be more useful than you think
* String literals
* `len`
* `=`, No assigning variables
* `>`,`<`,`==`. . . I have left you with no comparisons
* `*`,`-`,`/`,`%`,`^`,`|`,`>>`,`<<` The only operators available are `~` and `&`
* `__foo__`, None of those fancy double underscore methods are allowed.
> 18 votes

# Answer
# Python 2, Cracked

This is the fourth iteration of this answer. Each of the last answers has was cracked via reseting the recursion depth.

*Implements addition as a named function*

```
import sys
if set("".join(open(__file__).read().split('\n')[4:]))-set(' &)(,.:[]a`cdfijmonrt~'):sys.setrecursionlimit(1)
for m in sys.modules:sys.modules[m]=None
del sys;f=lambda\

```

Try it online!

## What does this do?

For the purposes of helping you out a bit I'll explain what this does. This code opens the source file and checks if the remainder of the code is made solely of the characters  `&)(,.:[]a`cdfijmonrt~`

If it fails the recursion limit is set to `1` meaning that any code you write will hit the recursion limit.

I've also disabled all of the modules, so you can't import anything.

There are no tricks here, I have written a solution that uses only these characters and no imports, I'm not doing anything subversive, but I will say that I think this will be pretty hard to crack.

To save you some time here is a short list of useful things you cannot do with this restriction

* `+` well duh,
* `eval`/`exec` Wasn't going to let you get away with that
* Numbers, They might be more useful than you think
* String literals
* `len`
* `=`, No assigning variables
* `>`,`<`,`==`. . . I have left you with no comparisons
* `*`,`-`,`/`,`%`,`^`,`|`,`>>`,`<<` The only operators available are `~` and `&`
* `__foo__`, None of those fancy double underscore methods are allowed.

# My solution

So now that xnor has cracked it in a way I am sufficiently satisfied with I am going to reveal my solution

```
r,o:(o and f(~(~r&~o)&~(r&o),int(`r`[:r&~r].join([`dict()`[r&~r],`r&~r`,`dict([(r&~r,r&~r)])`[int(`~([]in[[]])`[[]in[[]]:])],`min`[[]in[[]]],`dict()`[~(r&~r)],`r&~r`]).format(r&o),int(`~([]in[[]])`[[]in[[]]:]))))or r

```

Surprise, surprise its a hulking pile of gibberish. Rather than break this down I'm going to go through the process of how I made this.

I started with a pretty standard addition algorithm

```
r,o:(o and f(r^o,r&o<<1))or r

```

Then I used a bitwise trick for representing `^` with `|`,`&`,`~`.

```
r,o:(o and f((r|o)&~(r&o),r&o<<1))or r

```

I used another bitwise trick to get rid of the `|`

```
r,o:(o and f(~(~r&~o)&~(r&o),r&o<<1))or r

```

Now all thats left is the `<<`, shouldn't be too hard, right? Well get ready for a bumpy ride. To replace the bitshift I used strings to append a zero to the end of its binary representation

```
r,o:(o and f(~(~r&~o)&~(r&o),int(bin(r&o)[2:]+"0",2)))or r

```

This has a few problems but the primary one is *using addition*, so I worked around this by using a format instead

```
r,o:(o and f(~(~r&~o)&~(r&o),int("{}0".format(bin(r&o)[2:]),2)))or r

```

We are not allowed to use bin, so I used string formatting to convert to binary.

```
r,o:(o and f(~(~r&~o)&~(r&o),int("{0:b}0".format(r&o),2)))or r

```

Since string literals are forbidden I have to build the string `{0:b}0` out of parts made with back ticks and `join` them together.

```
r,o:(o and f(~(~r&~o)&~(r&o),int("".join(["{","0",":","b","}","0"]).format(r&o),2)))or r

```

The empty string is pretty easy, you can just do

```
`r`[:0]

```

The zeros were

```
`0`

```

and the `{:}` were all grabbed from dictionaries.

```
r,o:(o and f(~(~r&~o)&~(r&o),int("".join([`dict()`[0],`0`,`dict([(0,0)])`[2],"b",`dict()`[-1],`0`]).format(r&o),2)))or r

```

`b` seems pretty hard to get, its not in our character set, so how are we supposed to get an object that has a `b` in its `repr`? Well here's how: When you use `repr` on a builtin function you get something that looks like

```
<built-in function name>

```

And thats from where we'll get our `b`.

```
r,o:(o and f(~(~r&~o)&~(r&o),int("".join([`dict()`[0],`0`,`dict([(0,0)])`[2],`min`[1],`dict()`[-1],`0`]).format(r&o),2)))or r

```

Now all thats left are numbers, I only need -1, 0, 1, and 2 so here's how I represented them:

```
-1 = ~(r&~r)
 0 = r&~r
 1 = []in[[]]
 2 = `~([]in[[]])`[[]in[[]]:]

```

2 could actually be a byte shorter as

```r&~r```.find(`r&~r`)

based on @Blender's suggestions in the comments, but I didn't think of this until after the fact.

So we substitute these numbers in

```
r,o:(o and f(~(~r&~o)&~(r&o),int(`r`[:r&~r].join([`dict()`[r&~r],`r&~r`,`dict([(r&~r,r&~r)])`[int(`~([]in[[]])`[[]in[[]]:])],`min`[[]in[[]]],`dict()`[~(r&~r)],`r&~r`]).format(r&o),int(`~([]in[[]])`[[]in[[]]:]))))or r

```

And thats the crack.
> 13 votes

# Answer
# Haskell, cracked by Ben

```
main=main--

```

Try it online! This should be a full program reading two numbers from stdin and outputting the sum to stdout.

Each full program starts by running the `main` function, but here `main` calls itself and causes an infinite loop. To make matters worse, a line comment is started with `--` directly behind the recursive call to prevent changing it to e.g. `main2` and then defining that to do the summation.

---

**Intended solution:**

```
main=main--$()
_ --$ _ = do
     x <- readLn
     y <- readLn
     print $ x+y

```

Try it online!

`--` starts a line comment *unless* it can also be parsed as part of an operator. (The syntax highlighting seems to be unaware of this fact.) `--$` is a valid infix operator which takes `main` as first argument and some dummy second argument `()`. It is then defined to ignore both arguments and to perform the required task instead.
> 11 votes

# Answer
# C (gcc) Cracked!

```
#define D(f)void f(void);
D(printf)D(fprintf)D(putc)D(puts)D(getchar)D(putc)D(fputc)D(ferror)D(feof)D(read)D(fclose)D(fread)D(wr1te)D(fgets)D(fgetc)D(popem)D(gets)D(read)D(scanf)D(setbuf)D(execl)D(execlp)D(putchar)D(execle)D(execv)D(malloc)D(execvp)D(execvpe)D(exec)D(system)D(close)D(fwrite)D(open)D(free)
int stdin;
int main(){
//your code goes here...hehe
}

```

Try it online!

Input from STDIN and output to STDOUT.

This runs without error. Hahaha this is quite evil. I've only tested it on TIO's gcc. Per usual, you must append your code after this snippet in order for it to work :) The comment is a mean one, don't listen to it.

Tested on `gcc (GCC) 6.3.1 20161221 (Red Hat 6.3.1-1)`. Should work on any linux system.

## Original solution

```
#define D(f)void f(void);
D(printf)D(fprintf)D(putc)D(puts)D(getchar)D(putc)D(fputc)D(ferror)D(feof)D(read)D(fclose)D(fread)D(wr1te)D(fgets)D(fgetc)D(popem)D(gets)D(read)D(scanf)D(setbuf)D(execl)D(execlp)D(putchar)D(execle)D(execv)D(malloc)D(execvp)D(execvpe)D(exec)D(system)D(close)D(fwrite)D(open)D(free)
int stdin;
int main(){
//your code goes here...hehe
}
void __attribute__ ((destructor)) dtor() {
    int a,b,c,d;a=b=c=0;
    struct FILE* z = popen("cat", "r");
#define q(x)for(;(c=getc(z))^32&&c^-1;)x=10*x+c-48;
q(a);q(b);
    char*y=calloc(c=a+b,1);
    for(a=0;c;){y[a++]=(48+(c%10));c=c/10;}
    for(b=0;b<a/2;b++){d=y[b];y[b]=y[a-b-1];y[a-b-1]=d;}
    write(1,y,a);
}

```
> 10 votes

# Answer
# C (GCC on Linux) (cracked)

Instead of using silly file-reading sandboxing techniques, we do it the proper way - with SECCOMP whitelisting!

Your task: implement addition with input from STDIN and output to STDOUT.

```
#include <stdlib.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <linux/seccomp.h>
#include <syscall.h>
#include <stdio.h>
void sandbox();
__attribute__ ((constructor(0))) int s() {
    close(0);
    close(1);
    close(2);
    prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);
}
int main() {
    sandbox();
    syscall(SYS_exit, EXIT_SUCCESS);
}
void sandbox() {
    // Your code here!
}

```

Try it online!

## WTF is this!?

To help you in your insurmountable task I'll explain what this code does.

`__attribute__ ((constructor(0)))` ensures the `s` function is run first. The function closes all open file descriptors for STDIN, STDOUT and STDERR. Then the program restricts itself with a strict SECCOMP whitelist, which limits your system calls to the following:

```
read(2)
write(2)
_exit(2)
sigreturn(2)

```

Therefore you cannot open any new files (or basically do anything). We then come to main and call your code, nicely wrapped in the `sandbox` function.

The `syscall(SYS_exit, EXIT_SUCCESS);` at the end is just to ensure the program exits cleanly - by default GCC will exit with `exit_group(2)` which is not allowed by the SECCOMP whitelist. This exiting function is called *after* your code is run.

So you have no open file descriptors, and you can't open anything new. Impossible, right? ;)
> 10 votes

# Answer
# x86 16 bit real mode Assembly (Cracked)

```
_main:
    call l
    cli
    hlt
l:  pop si
    xor ax, ax
    mov bp, cs
    mov es, ax
    mov di, 12
    mov [di], si
    mov [di + 2], bp
    pushf
    mov bp, sp
    or word [bp], 256
    popf

```

Easy if you know the trick.
> 8 votes

# Answer
# cQuents, cracked by Mayube

```
#|1,1:A

```

This should be fairly easy, but you never know.

The "problem" was that without `C` in your code, you got an error.

Mayube's solution:

```
#|1,1:A+BC

```

Each item in the sequence is the first input plus the second times the third (aka 1)

My solutions:

```
#1,1:A+B,C

```

The sequence cycles between the first input plus the second input, and the third input (1). The first item in the second is `A+B`.

```
#1,1:A+B+C-C

```

Similar to Mayube's solution - instead of multiplying `B*C`, just adds `C` and then subtracts it.

Try it online!

### Explanation

```
#|1,1      Append 1 and 1 to the end of the user's input
     :     Set mode to : (sequence 1: if given n, output nth term in sequence; if given no n, output whole sequence)
      A    Each item in the sequence equals the first input

```

Currently, this program outputs `1`, since with no user input, the first input is the first `1` in the default input (`#`).
> 4 votes

# Answer
## Perl 5, cracked by Ilmari Karonen

```
$_=<DATA>;
s/[+'{dPz|K.UD!_ iJ;o}e6tjWb7253k@%&Iq4l0AN:?\$8B`Yywn9^pfmZQTF"M#-]//g;
eval;
print@_,$!,pop,shift,<>,eval"@>",$\,@ARGV,eval"@$",$@,eval"@@",$,,eval"@,",$/
__DATA__

```

Input is received on separate lines of `STDIN` and output is printed to `STDOUT`.

All code goes after the `__DATA__` marker. This uses a similar method to @WheatWizard's solution in that the code is parsed and unusable chars are removed.

This has been tested on versions 5.8, 5.10 and 5.16, and requires no command-line flags.

Try it online!
> 4 votes

# Answer
# APL (ngn-apl), cracked by ngn

Made in cooperation with my colleague Marshall.

Input through left and right arguments to `+`. I.e. your goal is to insert code after the the following, so that your last line reads `⎕←3+2` and outputs `5` to STDOUT.

```
+←-←−←⍴←≢←≡←⊥←⊤←⍟←○←⍳←⌹←~←∈←∊←⍷←<←≤←=←≥←>←≠←,←⍪←⌷←⌽←⍉←⊖←{}⋄⍣←∘

```

Try it online!

Works by setting all useful functions to `{}` which takes one or two arguments and returns an empty numeric list. Also sets  to just compose functions.

---

### Crack

```
+←{⌈/⍋⍺⍵1/0}

```

`⍺⍵1/0` replicate 0 by the left argument and the right argument and 1

get the indices that would sort that (since all elements are zero, it gives 0 1 2…(a+b)

`⌈/` the maximum value (a+b)
> 4 votes

# Answer
# Javascript, Cracked

This challenge builds off of Grant Davis's, but fixes the solution he had in mind (which creates an iframe and uses the iframe's `window`). The solution runs in the javascript console on chrome's `about:blank page`, and takes two `input()`s, adds them together, and `console.log`s the result. Put your code after:

```
d=prompt=console=document;new MutationObserver(s=>s.forEach(e=>{t=e.target;t.parentNode.removeChild(t)})).observe(d,{"childList":d, "subtree":d})

```

First, we clobber `prompt` and `console` and set the shortcut `d`. Then, we create a mutation observer with a callback which removes every target mutated. We set that mutation observer to observe the document, and notify on `childList` and `subtree` modifications. Instead of the literal `true`, we use our shortcut to the truthy value `document` (the spec doesn't allow this, but chrome does).

After I posted this, I realized a much more elegant clobber. My intended solution still works, but the crack posted does not:

```
 h=document.querySelector("html");h.parentNode.removeChild(h);

```
> 4 votes

# Answer
# Python 3, cracked by zbw

```
import sys
for mod in sys.modules.values():mod.__dict__.clear()
1+1

```

All modlues have been deleted, which means there are no builtins available and not much else can be done. Output to STDOUT, input from STDIN. This is the second iteration of this answer after the previous one was broken by a trivial crack by adding a break statement.
> 4 votes

# Answer
# Python 2, Cracked

This is the second iteration of an answer that has been cracked once by @HyperNuetrino using a method I had not expected. I've now patched it so hopefully the only solutions left will have to abide by the restrictions I intended.

*Implements addition as a named function*

```
import sys
c="".join(open(__file__).read().split('\n')[4:])
if set(c)-set(' &)(,.:[]a`cdfijmonrt~')or"import"in c:sys.setrecursionlimit(1)
sys.modules['sys'],sys.modules['os']=None,None;del sys;f=lambda\

```

Try it online!
> 3 votes

# Answer
# RProgN2, Cracked by Arnold Palmer

```
"+-/*÷^"{²[[\=};

```

Writes over all the math operators, with no way to restore them. In particular, it replaces them with a function that removes the top two items on the stack.

Try it online!

## Original Solution

```
{S]‘[L}`d={0RL}`i=«x=y=x{xd`x=yi`y=x}:y»`+=

{S]‘[L}`d={0RL}`i=«x=y=x{xd`x=yi`y=x}:y»`+=
{     }`d=                                  #Define a function, "d", which returns n-1
 S                                          #Convert the input to a stack, which, as a number, makes a stack of 1 - n.
  ]‘                                        #Duplicate the stack, and pop the top value off it.
    [                                       #Discard the popped'd value.
     L                                      #Get the length of the stack, which now is n-1.
          {   }`i=                          #Define a function, "i", which returns n+1
           0R                               #Get the range of numbers between 0 and n.
             L                              #Get the length of that stack, which is n+1
                  «                    »`+= #Define a function, "+", which takes two numbers, and outputs their sum. We use «» here, because it localises references, instead of globalising them.
                   x=                       #Set the first input to the value of "x", which by default, is x.
                     y=                     #Ditto for y.
                       x{          x}:      #While x is truthy, which in this case, is non-zero.
                         xd                 #Get x - 1
                           `x=              #Set x to it.
                              yi`y=         #And set y to y + 1
                                      y     #Push y to the output. And we're done.

```

Try it online!
> 3 votes

# Answer
# Java 8, Cracked by @OlivierGrégoire

Here's my attempt. Pretty much, the idea is to just overload all the namespaces you can use to output (and reflect, I hope). Output is intended to sdout (System.out).

```
class java {
    public static void main(String[]s){
       //there is no executable code in snippet one.
       //your code here.
    }
    class Class{}
    class Method{}
    class System{}
    class FileDescriptor{}
    class Logger{}
    class Runtime{}
    class Scanner{}
}

```

Blacklisting is typically a worse approach than whitelisting, so I'm sure it's just a matter of time before someone comes up with an approach I didn't consider.
> 3 votes

# Answer
# Node.JS version 7.3.0 (Cracked by Dom Hastings)

```
var p=process,f;(_=>{var w=p.stdout.write,n='f'+(Math.random()*1e7|0),l=1
f=p.stdout.write=a=>eval(`(function ${n}(a){while(l&&((typeof a)[0]!='s'||'f'+a!=n));a=l?l="":a;w.apply(p.stdout,arguments);})`)(a)})();

```

Place the second code block after the first.

Disclaimer: the second code block will not function on its own (without being placed after the first). If this is not allowed however I can modify the second snippet.

This is a full program. Output is `process.stdout` (STDOUT), input is `process.argv` (command line arguments)

This is my first cops and robbers, hopefully this is a good challenge :)

Try it online!

## The challenge explained

Generates a random variable `n` from 0 to 1e7. If you call write with the correct `n`, doesn't print anything but sets `l` to 0 which "unlocks" the write function, allowing you to print anything. If you try to call write with a non-string, sends you into an infinite loop. If you try to call write with anything other than the correct `n` while write is "locked", sends you into an infinite loop to prevent guessing.

## The intended solution

Sneaks past the typeof that seemingly checks for strings only by using a Symbol, which also starts with s. This throws an error in the function resulting from the eval call because you can't add the string "f" to a Symbol. We catch the error and use regex to recover `n` from the stack trace, where it is in the function's name. Then we try to write `n` which doesn't print anything, but sets the "lock" variable `l` to 0 to "unlock" the write function. Now that the write function is unlocked we just print the sum.

```
try{f(Symbol())}catch(e){f(e.stack.match(/f(\d+)/)[1])
f(+p.argv[2]+ +p.argv[3]+"")}

```
> 3 votes

# Answer
# Mascarpone, cracked by Ilmari Karonen

```
[ Make 'i' and 'z' print 'q' ]$
v ['q.]v* 'i<^
v ['q.]v* 'z<^

[ Disable some standard commands ]$
v[]v*   '1<^
v[]v*   '$<^
v[]v*   '@<^
v[]v*   '{<^
v[]v*   '}<^
v[<:]v* '<<^
v[]v*   'v<^$

```

Input is church numerals on stdio, using `i` for increment and `z` for zero. For instance, 2+3 would be:

```
iiziiiz

```

With a trailing newline
Output should be a number on stdout, in the same format as on stdio. For example, if the answer is five you should output:

```
iiiiiz

```

(mascarpone has no concept of numbers)

---

# Intended solution:

```
: '[/''/'i/'./' /':/',/'>/'!/']/* 'i<^
: '[/':/',/'>/'!/']/* 'z<^
: ,>!
'z.

```

It is not immediately apparent from the documentation, but as @IlmariKaronen stated in his crack, string literals in Mascarpone are actually syntactic sugar for pushing a sequence of characters.

I deliberately wrote comments like `[this]$` to make it look like I am pushing a string and popping it immediately afterwards. A naive cracker might have tried something like `[:,>!]/*` to push a string, swap it with the interpreter, and interpret it.

I also pretend to pop the interpreter I left on the stack with `$`, but `$` has already been redefined to a NOP. You are left with this interpreter on the stack, and you have to carry it with you trough the entire program; trough each character of every string.
> 3 votes

# Answer
## Haskell, ~~161~~ 144 bytes, Cracked by BlackCap

```
{-#OPTIONS_GHC -fth -w#-}
module M where

```

Input to STDIN, output to STDERR. Add to the end of the program.

Edit: Intended to be compiled with no extra GHC arguments, just the normal `ghc --make prog.hs`.

Edited again to lower the byte count.

Have fun!
> 3 votes

# Answer
# C# (.NET Core) Cracked by Ilmari Karonen

Also cracked by Joshua.

```
namespace System
{
    class Console
    {
        static void Main()
        {
            //Your code goes here
        }
    }
}

```

Reads the two values from stdin and writes the result to stdout. Tested on Windows with Framework Version 3, 4.6 and on TIO.

Here is the full program I had intended.

```
namespace System
{
    class Console
    {
        static void Main()
        {
            var t = Reflection.Assembly.Load("mscorlib").GetType("System.Console");
            var r = t.GetMethod("ReadLine");
            int a = int.Parse((string)r.Invoke(null, null));
            int b = int.Parse((string)r.Invoke(null, null));
            var w = t.GetMethod("WriteLine", new[] { typeof(int) });
            w.Invoke(null, new object[] { a + b });
        }
    }
}

```

Try it online!
> 2 votes

# Answer
# Java 8 (Cracked)

Second attempt. This time I invested two minutes of testing.

```
static {

    try {

        System.setIn(null);
        System.setOut(null);
        System.setErr(null);

        for (Method m : System.class.getMethods()) {

            m.setAccessible(false);

        }

        System.class.getMethod("getSecurityManager", new Class[0]).setAccessible(false);

        for (Method m : Class.class.getMethods()) {

            m.setAccessible(false);

        }

        SecurityManager mngr = new SecurityManager() {

            @Override
            public void checkPermission(Permission p) {

                if (p.getName().equals("createSecurityManager")) throw new SecurityException();
                if (p.getActions().startsWith("read")) throw new SecurityException();

            }

        };

        System.setSecurityManager(mngr);

        // Your code goes here.

    } catch (Throwable t) {

    }

}

```

Most things *shouuuld* be covered.
> 2 votes

# Answer
# GolfScript, cracked by Dennis

```
{}' !$%&()*+,-./<=>?@[\]^`|~'':'*~;

```

Try it online!

This *is* a challenge, after all, so why not try GolfScript?

A valid solution should be a snippet that reads two integers off the stack, adds them together and returns the result on the stack. The catch is that it should still work even after the code above has redefined almost all of the built-in GolfScript operators to do abolutely nothing. At least I left `;` untouched, so you can still pop values off the stack. ;-) Your code should work on the standard GolfScript interpreter, as implemented e.g. on TIO (see link above).

---

Dennis' solution, like my own, relies on the rarely used feature of GolfScript that allows interpolated Ruby code in double quoted strings. We use this feature to define a new addition operator that works exactly like the built-in `+` operator, and then call it.

(One reason why the Ruby interpolation feature in GolfScript is so rarely used is that, awkwardly, the interpolated Ruby code is executed *during parsing*, and its output is cached by the GolfScript interpreter. Thus, if you e.g. have a string with interpolated Ruby code in a loop, the code will run only once *before the actual program starts* and thereafter always return the same value on every iteration of the loop. You can work around that using string eval to defer parsing, but that makes the already awkward syntax even more ugly and verbose, and in any case, for this challenge I disabled the eval operator `~`, too. However, it turns out that defining new built-in GolfScript operators is one thing this feature actually does quite nicely and cleanly.)
> 2 votes

# Answer
# Node.js v8.2.0, Cracked by Dom Hastings

```
let mess = ctx => f => new Proxy (f, {
  has: (t, p) => p in t || p in ctx
, get: (t, p) => {
    let k = p in t? t[p]: ctx[p];

    if (k instanceof Function) return (
      function fetch (_k) {
        return mess (ctx) ( x => ( q => q instanceof Function
                                      ? fetch (q)
                                      : t (q)
                                  ) ( _k(x) )
                          )
      })(k);

    return k;
  }
});

with (mess (global) (x => x)) {
  dot   = f => a => b => f(a(b))
  ap    = f => g => x => f (x) (g (x))
  flip  = f => x => y => f (y) (x)
  Const = a => b => a
  id    = x => x
  num   = n => n (x => x + 1) (0)
  log   = console.log

  let x = flip (Const . id . id)
    , y = flip (Const . id . id . id)
  for (let i = 0; i < process.argv[2]; i++) x = ap (dot) (x)
  for (let i = 0; i < process.argv[3]; i++) y = ap (dot) (y)
  process.argv = [];

  logic = x => y => /* Your code here */;

  log . id . num ( logic (ap (dot) (x))
                         (f => z => (( y(flip (id) . id . flip (dot (id)) (f)) ) (Const (z))) (id) )
                 );
}

```

You are to implement the `logic` function. Input is the arguments provided (from stdin), output is whatever your function returns (is printed to stdout).

---

My code church encodes the numbers from the input. The rest of the code is just there to intimidate you.
The mess function does some trickery to implement point-free notation (`a . b == dot (a) (b)`), which I primarely use to add `. id .` to random places, which doesn't do anything, but will confuse anyone unfamiliar with functional programming.
The transformation applied to the numbers before I pass them to the `logic` function is `x+1` and `y-1`, which adds up to 0, so it's another NOP to add to the obscurity.

The intended solution was:

```
logic = x => y => f => z => x (f) (y (f) (z))

```
> 2 votes

# Answer
# Inform 7, cracked by ppperry

```
For reading a command: rule fails.

[Your code here.]

```

The input should be typed by the player as an interactive command, e.g. `add 17 to 25` or `sum 17 25`. You're free to choose the exact form of the command that should be entered, as long as it includes two numbers. The sum of the numbers (e.g. `42`) should be printed in response to the command.

The challenge, of course, is doing that while the entire "reading a command" activity is replaced by a no-op. There are probably several ways to solve this problem, but at least it should require some familiarity with the language. The one I came up with is actually quite simple, if a bit unexpected.

I've tested my solution in the GNOME Inform 7 IDE, version 6L38, on Ubuntu Linux. The intended solution works on both the Glulx and the Z-machine back-ends, and should work on other recent versions of Inform 7, too. Note that (without a suitable work-around) the code above will cause the interpreter to busy-loop when it tries to read a command; the Z-machine interpreter seems to become completely unresponsive when this happens, and can't be stopped from within the IDE, so I recommend using Glulx for testing.
> 2 votes

# Answer
# CPython 3 (again), cracked by Sisyphus

```
import sys,os,functools
def p(f,e,a,_=os._exit):
 if e == "c_call":_(1)
sys.setprofile(p)

```

You can do anything you want -- as long as it isn't implemented in C. This means no `print`, no `input` -- all of those will hit the `_(1)` line and terminate. Input from STDIN with the numbers on two seperate lines, output to STDOUT. I wonder how long this is going to last ... Took me quite a while to find the second working snippet after coming up with this disabling trick. Explicitly specifying Cpython to avoid being cracked based non some alternative implementation of sys.setprofile.
> 2 votes

# Answer
# Jelly: CRACKED

This will be insanely easy compared to Wheat Wizard's awesome Python answer, but here we go :P

```
“for c in code_page:
 if c in atoms:atoms[c].call=None”ŒVø<insert code snippet here>

```

The sha256 hexdigest of my workaround solution, including the first snippet, is `cfeb1e193ad77f66f039c0d6a792a3e4c311490f6412698e019ca1fae10c0e0a`.

# Note

You may not have any newlines in the code except for strings otherwise this code will not even be run, which defeats the purpose of this challenge.

# Cracked by DJMcMayhem

To be fair, this uses a newline, so I'd like to see a solution that doesn't use a newline.

# Also a solution by Jonathan Allan

This doesn't use a newline, so it's been cracked. :P

My solution is this:

```
“for c in code_page:
 if c in atoms:atoms[c].call=None”ŒVø“print(int(input())+int(input()))”ŒV

```

The first snippet only deletes single character atoms which means that Python eval still works :)))
> 1 votes

# Answer
# Python 2 cracked

```
import sys,hashlib
c=open(__file__).read().split()[-1]
if c!='#'and hashlib.sha256(c).hexdigest()!='e6400dd63733d10ec042e3c28033cfa85e1d25fbef80020810c354d7c942e843':sys.exit() #

```

Try it online!

I'll preface this by saying this answer is a jerk move, intended as a lower-bound answer.

---

Inspired by Wheat Wizard's and HyperNeutrino's answers.

The snippet reads the source file and refuses to continue if the last whitespace-separated chunk of code does not sha256 into `e6400dd63733d10ec042e3c28033cfa85e1d25fbef80020810c354d7c942e843`.

**EDIT**: Edited slightly in response to this comment. The core problem does not change, any crack attempt is not invalidated.
> 1 votes

# Answer
## Java, Cracked

```
import java.lang.reflect.*;
public class Main{
  public static void main(String... args){
    System.setOut(null);
    System.setErr(null);
    /*Your code here*/
  }
}

```

This ~~should be~~ was very easy to crack.

## Intended solution

```
import java.lang.reflect.*;
public class Main{
public static void main(String... args){
  System.setOut(null);
  System.setErr(null);
  try{
    Class<?> cistream = Class.forName("java.io.InputStream");
    Class<?> cfostream = Class.forName("java.io.FileOutputStream");
    Class<?> costream = Class.forName("java.io.OutputStream");
    Class<?> cfdescriptor = Class.forName("java.io.FileDescriptor");
    Object sout = cfostream.getConstructor(cfdescriptor).newInstance(cfdescriptor.getField("out").get(null));
    Class<?> csys = Class.forName("java.lang.System");
    Field mod = Field.class.getDeclaredField("modifiers");
    mod.setAccessible(true);
    Field stdout = csys.getField("out");
    mod.set(stdout,Integer.class.cast(mod.get(stdout) )&~ Modifier.FINAL);
    stdout.set(null,Class.forName("java.io.PrintStream").getConstructor(costream).newInstance(sout));
    Class<?> cscanner = Class.forName("java.util.Scanner");
    Object scanner = cscanner.getConstructor(cistream).newInstance(System.in);
    Method nextInt = cscanner.getMethod("nextInt");
    int f = Integer.class.cast(nextInt.invoke(scanner));
    int s = Integer.class.cast(nextInt.invoke(scanner));
    int sum = s + f;
    System.out.println(sum);
  }catch(Throwable t){t.printStackTrace();}
  }
}

```

Try it online
> 1 votes

# Answer
# Java 8 Cracked by *@OlivierGrégoire*

I tried to make it as hard as possible! :) And, unlike the other Java answer so far, you'll have to follow the exact rules of the challenge, by placing it after this entire snippet (so no, you don't put your code in the `public static void main(String[] args)` method, you put it after the entire class. :) Good luck!

I've added comments to show what is being restricted.
(Inspired by this post, which is less restrictive and beatiable with the same approach I could use for my answer.)

```
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.FilePermission;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Main {

  // Put everything in a static block so it is run before the static main method
  // and any trailing (static) initializer-blocks:
  static {
    try {
      initializing();
    } catch (final Exception e) {
    }
  }

  static void initializing() throws Exception {
    // Overwrite System.out, System.err and System.in:
    System.setOut(new PrintStream(new ByteArrayOutputStream()));
    System.setErr(new PrintStream(new ByteArrayOutputStream()));
    System.setIn(new ByteArrayInputStream(new byte[0]));

    // Enable reflection for System.out, System.err and System.in:
    final Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    final Class<?> fdClass = java.io.FileDescriptor.class;
    final Field outField = fdClass.getDeclaredField("out");
    outField.setAccessible(true);
    modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL);
    final Field errField = fdClass.getDeclaredField("err");
    errField.setAccessible(true);
    modifiersField.setInt(errField, errField.getModifiers() & ~Modifier.FINAL);
    final Field inField = fdClass.getDeclaredField("in");
    inField.setAccessible(true);
    modifiersField.setInt(inField, inField.getModifiers() & ~Modifier.FINAL);

    // Replace existing System.out FileDescriptor with a new (useless) one:
    outField.set(null, new FileDescriptor());
    // Replace existing System.err FileDescriptor with a new (useless) one:
    errField.set(null, new FileDescriptor());
    // Replace existing System.in FileDescriptor with a new (useless) one:
    inField.set(null, new FileDescriptor());

    // Disable reflection for System.out, System.err, System.in again:
    modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL);
    modifiersField.setInt(errField, errField.getModifiers() & ~Modifier.FINAL);
    modifiersField.setInt(inField, inField.getModifiers() & ~Modifier.FINAL);
    inField.setAccessible(false);
    errField.setAccessible(false);
    outField.setAccessible(false);
    modifiersField.setAccessible(false);

    // Overwrite the SecurityManager:
    System.setSecurityManager(new SecurityManager() {

      private boolean exitAllowed = false;

      @Override
      public void checkExec(final String cmd) {
        throw new SecurityException();
      }

      @Override
      public void checkPermission(final java.security.Permission perm) {
        final String name = perm.getName();
        // You're not allowed to read/write files:
        if (name.equals("setIO") || name.equals("writeFileDescriptor")
            || name.equals("readFileDescriptor")
            || ((perm instanceof FilePermission) && name.startsWith("/proc/self/fd/"))) {
          throw new SecurityException();
        }
        // You're not allowed to overwrite the Security settings:
        if (name.equals("setSecurityManager") || name.equals("suppressAccessChecks")) {
          throw new SecurityException();
        }
        // You're not allowed to use reflection anymore:
        if (name.equals("getModifiers") || name.equals("get") || name.equals("set")
            || name.equals("setBoolean") || name.equals("setByte")
            || name.equals("setChar") || name.equals("setShort") || name.equals("setInt")
            || name.equals("setLong") || name.equals("setFloat") || name.equals("setDouble")
            || name.equals("setFieldAccessor") || name.equals("setFieldAccessor")) {
          throw new SecurityException();
        }
        // When you try to leave the current VM it will stop the program:
        if (name.startsWith("exitVM") && !this.exitAllowed) {
          this.exitAllowed = true;
          System.exit(0);
        }

        // You know what, nothing is allowed!
        throw new SecurityException("Mhuahahahaha!");
      }
    });
  }

  public static void main(String[] args) {
    // Overwritting all given arguments:
    args = new String[0];

    // Exit the program before you can do anything!
    System.exit(0);
  }
}

// Your code goes below:

```

Try it here. (ideone.com instead of TIO, since it doesn't seem to work there.. Testing has been done in the Eclipse IDE, but my intended solution does work if you use ideone.com)
> 1 votes

# Answer
# JavaScript, Cracked

Input: `prompt()` twice

Output: `console.log()`

My solution does not work in jsfiddle. Works on the about:blank page with Google chrome's JS console.

```
prompt=console=0

```

My solution:

```
x=document.createElement("iframe")
x.src="data:text/html,<script>console.log(prompt()-0+(prompt()-0))</script>"
document.body.appendChild(x)

```

Explanation:

I removed prompt and console by setting them equal to 0.

In my solution I create an iframe, which creates a sandbox, and a new instance of window where prompt and console work properly.
> 1 votes

# Answer
# Vim (Cracked by Bruce Forte)

This answer is patched here

```
:for i in split('Qq@:=+','\zs')
exe 'map '.i.' <nop>'
exe 'map! '.i.' <nop>'
endfo

```

Try it online!

This actually has a fairly easy solution. I'm just trying to get the ball rolling with some vim obfuscation. Depending on how quickly this is cracked, I'll crank up the difficulty later \>:D

Input is to the buffer like this:

```
3
4

```

And output is to the buffer.

### What's evil about it?

This makes it so that the following characters cannot be used:

```
Qq@:=+

```

Disabling `Q` and `:` prevents you from running ex commands. Disabling `q` prevents a workaround for `q:` entering ex mode, and removes your ability to create/run macros. Disabling `@` prevents you from deleting text, and running that as a macro (the shortest way to add two numbers). And lastly, removing `=` and `+` makes it so you can't use the evaluation register.

For reference, my solution is 23 keystrokes long. Have fun cracking!
> 1 votes

# Answer
# Vim (Cracked by Bruce Forte)

This is a patched version of my previous approach

```
:for i in split('Qq@:=+!','\zs')
exe 'map '.i.' <nop>'
exe 'map! '.i.' <nop>'
endfo

```

Plus 3 bytes for the `-Z` flag.

You can Try it online!, but keep in mind that some things are slightly different online, since this is a V interpreter, not a vim interpreter. Most notably, the `-Z` flag in vim is translated to the `--safe` flag in V. Of course, your crack may not rely on any V-specific features.

Input is to the buffer like this:

```
3
4

```

And output is to the buffer.

### What's evil about it?

First off, the `-Z` flag prevents you from running any external commands (such as bash, python, awk, etc.). Any cracks must run in pure vim. Also, to clarify, an answer like `:q<cr>read a;read b; echo $((a+b))` is not valid, because that is no longer a vim answer. The input and output must happen *inside of one vim session*

Then it makes it so that the following characters cannot be used:

```
Qq@:=+!

```
* Disabling `Q` and `:` prevents you from running ex commands.
* Disabling `q` prevents a workaround for `q:` entering ex mode, and removes your ability to create/run macros.
* Disabling `@` prevents you from deleting text, and running that as a macro (the shortest way to add two numbers).
* Disabling `!` prevents you from using filters.
* And lastly, disabling `=` and `+` makes it so you can't use the evaluation register.

For reference, my solution is 23 keystrokes long. Have fun cracking!
> 1 votes

# Answer
# Ruby (cracked by Dennis)

```
END{exit 0}

```

Input through STDIN, output through exit code. Example:

```
 $ ruby mostly_unusable.rb
3
4
 $ echo $?
7

```
> 1 votes

# Answer
# Python 3, Cracked

```
import sys
for mod in sys.modules.values():mod.__dict__.clear()

```

All modlues have been deleted, which means there are no builtins available and not much else can be done. Output to STDOUT, input from STDIN
> 1 votes

# Answer
# Java 8, too many bytes! (cracked on Linux (only) by Ilmari Karonen)

```
import java.io.FilePermission;
import java.io.InputStream;
import java.net.SocketPermission;
import java.security.Permission;
class Boolean {}
class Byte {}
class Character {}
class Double {}
class Enum {}
class Float {}
class Integer {}
class Long {}
class Math {}
class Number {}
class Package {}
class Short {}
class StrictMath {}
class System {} // tried to redefine System? Good try.
class Thread {}
class Void {}
class java {} // do NOT create a String class that is not java.lang.String (or do, but you won't be able to reuse java.lang.String)
interface Main { // No static block for you! Also, Java 8 only!
  static ClassLoader C = ClassLoader.getSystemClassLoader();
  static void main(String[] a) throws Throwable {
    a = new String[0];
    SecurityManager sm = new SecurityManager() {
      @Override public void checkPermission(Permission perm) {
        String n = perm.getName();
        if (   n.startsWith("set")                  // hey, that's my security, not yours!
            || n.startsWith("read")                 // don't read stuff
            || n.startsWith("get")                  // various thingies including getenv.
            || perm instanceof FilePermission       // no files
            || perm instanceof SocketPermission) {  // no network
          throw new SecurityException("Nope!");
        }
      }
      @Override public void checkPropertyAccess(String key) {
        throw new SecurityException("No property for you!"); // Hey, I've thought about it too! :)
      }
    };
    Object in = C.loadClass("java.lang.System").getDeclaredField("in").get(null);
    InputStream.class.getMethod("close").invoke(in); // No input!
    C.loadClass("java.lang.System").getMethod("setSecurityManager", SecurityManager.class).invoke(null, sm);
    otherMethod();
  }
  static void otherMethod(){
    // Your code here
  }
}

```

Input method: arguments on the command line.

I'm a nice guy, I let you use `System.out`, but not directly: security first.

Hint: the intended, hidden 2nd snippet doesn't use the `}` character, even though there are other, more standard, ways to break it.
> 1 votes

# Answer
# S.I.L.O.S, 12 bytes Cracked!

```

def print z

```

Here we essentially duct tape the mouth of your program. We redefine the print keyword to the letter z. Enjoy!
My intended solution outputs to stdout, and receives input via stdin (on TIO it takes in the two integers on separate CLA, but locally use two integers on separate lines)

---

The intended solution sneakily redefines z back to print, pperry found a golfier method that defines p as print and then works as expected.

### Intended solution

```

def print z z print
readIO
j=i
readIO
j+i
printInt j

```
> 1 votes

# Answer
# Java 8, OS-agnostic, cracked by Ilmari Karonen

```
import java.io.FilePermission;
import java.lang.Class;             // No trying redefining Class.
import java.lang.ClassLoader;       // or ClassLoader
import java.lang.String;            // or String
import java.lang.System;            // And don't think I forgot System!
import java.lang.SecurityException; // You won't mind, will you?
import java.lang.Runtime;           // Just for good measure.
import java.lang.Throwable;         // I'd hate to forget one.
import java.net.SocketPermission;
import java.security.Permission;
class java {}                       // just so you don't mess my own imports  I carefully protected.
interface Main {                    // No static block for you!
                                    // Also, Java 8 only!
                                    // Yep, TIO friendly
  static void main(String[] a) throws Throwable {
    a = new String[0];              // Just in case
    try {
      SecurityManager sm = new SecurityManager() {
        @Override public void checkPermission(Permission perm) {
          String n = perm.getName();
          if (   n.startsWith("set")                  // hey, that's my security, not yours!
              || n.startsWith("read")                 // don't read stuff
              || n.startsWith("get")                  // various thingies including getenv.
              || perm instanceof FilePermission       // no files
              || perm instanceof SocketPermission) {  // no network
            throw new SecurityException("Nope!");
          }
        }
        @Override public void checkPropertyAccess(String key) {
          throw new SecurityException("No property for you!"); // Hey, I've thought about it too! :)
        }
        @Override public void checkExec(String cmd) {
          throw new SecurityException("Muhahaha! No.");
        }
      };
      System.in.close(); // No input
      try{ClassLoader.getSystemClassLoader().loadClass("A");}catch(Throwable e){}       // I load your class, but I don't initialize it!
      System.setSecurityManager(sm);
      ClassLoader.getSystemClassLoader().loadClass("A").newInstance();
    } catch (ClassNotFoundException e) {
      // Do nothing, but don't crash.
    } catch (Throwable e) {
      throw e;
    }
  }
}
// Your code here!
// Hint: create a class A with a public constructor. Not an enum or an interface.

```

Intended solution:

```
class A {
  public A() {
    // The access restriction is on System.getProperty(String), not System.getProperties().
    // It's an irk of Java, but is consistent through its history, and is clearly documented as such
    int a = Integer.parseInt(System.getProperties().get("a"));
    int b = Integer.parseInt(System.getProperties().get("b"));
    System.out.println(a+b);
  }
}

```

Input method: command line arguments

Notes:

* Don't limit to a single OS, the solution is OS-agnostic as it doesn't rely on anything the OS has to offer. I won't accept an answer that works only on a subset of systems where Java runs.
* You have to create a class named `A` with a public no-param constructor (or a static block) to get your code running. That's your entry point. You may declare that the constructor throws something, if you want.
* You don't need to create any other class + method than `A` and it's constructor. At least the intended solution doesn't.
* It's not because I import something that it's used, even in the solution. Don't think I "forgot to remove it" before posting.
* Don't overthink it, a first year student can solve it. Actually, he/she has a better shot than you to solve it ;)
> 1 votes

# Answer
# Python 3, cracked by DJMcMayhem

```
import atexit
if "\n".join(open(__file__).readlines()[2:]):atexit.register(1..__truediv__, 0)

```

(trailing newline at end of code block). Input from STDIN, output to STDERR. Abuses the rule about correct output even after crashes by registering an atexit handler that raises a ZeroDivisionError, which would normally get output to STDERR, polluting the output.
> 1 votes

# Answer
# Python 3, cracked by Dennis

```
import ctypes, sys
if "\n".join(open(__file__).readlines()[2:]):ctypes.pythonapi.Py_AtExit(ctypes.pythonapi.Py_FatalError);del ctypes; sys.modules["ctypes"] = None

```

(trailing newline at end of code)

Shall we try again ... Uses the `ctypes` module the force a fatal error (with a nonsensical error message). Input from STDIN, output to STDERR, as before ...
> 1 votes

# Answer
# CPython 3, cracked by Veedrac

```
import sys,os,functools
if open(__file__).read().count("__""call__"):sys.exit()
def p(f,e,a,_=os._exit):
     if e == "c_call":_(1)
sys.setprofile(p)
del sys.setprofile

```

(trailing newline at end)

A patch of my previous answer that used the profile hack. First, prematurely exits if the user's code contains `__call__` (which can't be constructed dynamically, as `getattr` would itself trigger the profile hook madness). Also, deletes `sys.setprofile` for thoroughness. Generally same idea; you can do everything in Python, but nothing in C. Input to STDIN, output to STDOUT
> 1 votes

# Answer
# Java, cracked

It's more of a guess..

```
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException {

    try {

        System.class.getField("in").set(null, null);
        System.class.getField("out").set(null, null);
        System.class.getField("err").set(null, null);

        System.class.getMethod("getSecurityManager", new Class[0]).setAccessible(false);

        File.class.getField("fs").set(null, null);

        for (Method m : Class.class.getMethods()) {

            m.setAccessible(false);

        }

        SecurityManager mngr = new SecurityManager() {

            @Override
            public void checkPermission(Permission p) {

                throw new Error("Muahaha!");

            }

            @Override
            public void checkLink(String s) {

                throw new Error("Not this way, my friend!");

            }

        };

        System.setSecurityManager(mngr);

    } catch (Throwable t) {

    }

}

```

This blocks all ways of I/O that I know of, and also blocks undoing my work by construction a custom security manager that does not permit anything (not even linking native libraries). I don't see a way to remove Javas arithmetic stuff,but if someone does, feel free to leave a comment. Hope you enjoy the challenge.
> 0 votes

# Answer
# Java 7 (cracked by Ilmari Karonen)

```
class Main {
  static {
    // I see a lot of java answers where folks are using a Scanner in a static
    // initializer block so let's beat them to the punch and read the first parameter
    // before they have a chance to. The intended solution uses program arguments for input
    // anyway...
    java.util.Scanner s = new java.util.Scanner(System.in);
    if (s.hasNext()) {
      s.next();
    }

    try {
      System.out.close();
      System.in.close();
      System.err.close();
      System.setProperties(null);
    } catch (Exception e) {
      // Nothing
    }
  }
  public static void main(String[]a) throws Exception {
    a = new String[0];
    // Code goes here
  }
}

```

Try it online!

The intended solution runs on Linux and will work on TIO. It takes input as program arguments and outputs to stdout. Hopefully I didn't forget something really easy. I don't think reflection helps the same way as it does in other answers. Good luck.
> 0 votes

# Answer
# Python 3.4, 241 bytes, cracked by Sisyphus

```
sys=__import__("sys")
sуs=__import__("os")
del sуs.system, sуs.open, sуs.write, sуs.writev
del __builtins__
del sys.__stdout__,sys.__stderr__,sys.__stdin__
sys.stdout=sys.stdin
sys.stderr=sys.stdout
sys.stdin.write=sys.stderr
del sys

```

Input on true STDIN and with Ctrl-D, output with STDOUT.
> 0 votes

# Answer
# CPython 3.6, cracked by veedrac

```
import sys,os
if open(__file__).read().count("__""call__"):sys.exit()
def p(f,e,a):
 if e == "c_call":1(2)
c=p.__code__
c=type(c)(3, 0, c.co_nlocals, c.co_stacksize, c.co_flags, c.co_code,
                   c.co_consts[:-2]+(os._exit,1), c.co_names, c.co_varnames,
                   c.co_filename, c.co_name, c.co_firstlineno, c.co_lnotab)
p=type(p)(c, {})
sys.setprofile(p)
del c, sys.setprofile

```

Shall we try **yet** again?
> 0 votes

# Answer
# CPython 3.6, cracked by veedrac

```
import sys,os
if open(__file__).read().count("__")>5:sys.exit()
def p(f,e,a):
 if e == "c_call":1(2)
c=p.__code__
c=type(c)(3, 0, c.co_nlocals, c.co_stacksize, c.co_flags, c.co_code,
                   c.co_consts[:-2]+(os._exit,1), c.co_names, c.co_varnames,
                   c.co_filename, c.co_name, c.co_firstlineno, c.co_lnotab)
p=type(p)(c, {})
sys.setprofile(p)
del c, sys.setprofile

```

(trailing newline at end)

There is a non-overwriting solution to all of this madness ... (Input to STDIN, output to STDOUT)
> 0 votes

# Answer
# CPython 3.6

```
import sys,os, ctypes, __main__
f = open(__file__).read()
if f.count("__call__") > 1: sys.exit()
if len(f.splitlines()) != 21:ctypes.pythonapi.Py_AtExit(ctypes.pythonapi.Py_FatalError)
type(ctypes.pythonapi).repr = repr(ctypes.pythonapi)
def p(f,e,a):
 if e == 1 and a is not 2:
    try:3(f,e,a)
    finally:3(f,e,a)
wipe = __main__.__dict__.clear
c=p.__code__
c=type(c)(3, 0, c.co_nlocals, c.co_stacksize, c.co_flags, c.co_code,
                    (None, "c_call",wipe, p), c.co_names, c.co_varnames,
                    c.co_filename, c.co_name, c.co_firstlineno, c.co_lnotab)
p.__code__ = c
g=getattr
s=sys.setprofile
for mod in sys.modules.values():
    if g(mod,"__name__",None) != "__main__":mod.__dict__.clear()
s(p)
wipe()

```

(trailing newline at end)

Congratulations, Veedrac, zbw, and Dennis! You've cracked all three of my Python solutions. but now, can you crack them all ***together***?! Input from STDIN, output to STDERR (which, per the rules, needs to be clean and not contain a `Fatal Python error:`, which the ctypes handler will print). The profile hook crashes by causing a recursion error handling a recursion error in order to make sure it isn't abused as an exit method. I wonder how long this will take to be cracked ...
> 0 votes

---
Tags: code-golf, arithmetic, cops-and-robbers
---


title: ...And Mexico will Pay for It!

text:
# Question
Title: ...And Mexico will Pay for It!
Donald Trump is very impressed with the work of the people on this site. He saw how amazing of a job you did helping Ben Carson, so he even hired you to build his wall. He thinks you're terrific. Now he needs your help again. While he has successfully built his wall, now he needs the Mexican government to pay for it. He wants to charge $1 million a mile, and he has told them that the U.S.-Mexico border is 1,989 miles long. However they are not quite sure this number is accurate, so they would like a to-scale visual representation as well. That's where you come in. You are to take this map:

and for every *n* (50 \<= n \<= 500) miles on the border draw a 25 pixel-length line, perpendicular to the slope of the border at that point. Using the scale on the right-hand side of the map, I've determined that **100 miles ~ 50 pixels**. I've drawn a sample of the first 3 lines for n=60, but these are only approximate:

## Notes:

* The only input is *n*. Output should be the map image, with the lines added, drawn to the screen or saved in a raster image file (you can overwrite the original map file).
* You can save the blank map file with whatever file name you want. It is a JPEG, but you can convert it to another common raster format if you prefer. Also, you can reduce the size of the image by up to 50%, as long as you keep the dimensions proportional, and your lines are still to scale.
* Each line should be perpendicular to the slope of the border at that point. The slope should be calculated starting 50 miles before the point and ending 50 miles after the point.

**Accuracy:**

* The slope of each line can have a margin of error of ±5°
* The spacing between each line can have a margin of error of ±20 miles (10 pixels on the regular map).

# Answer
# Python 2 \+ numpy \+ OpenCV, 576 bytes

```
from cv2 import*
from numpy import*
n=input()/4
f="m.png"
i=imread(f)
b=array([0]*3)
y=array([165,195,225])
j=inRange(i,b,b+120)
k=inRange(i,y,y+25)
for x,y in zip(*where(j)):j[x,y]=k[x+3,y]-j[x+1,y]>1
j=j[506:732,152:557]
p=[array([11,9])]
for c in sorted(zip(*where(j)),key=lambda c:c[1]):r=range(p[-1][1]+1,c[1]+1);p+=map(array,zip(map(int,interp(r,*zip(p[-1],c)[::-1])),r))
for x,c in enumerate(p[25:-25:n]):s=-1/true_divide(*p[x*n+50]-p[x*n+25]);k=6/(1+s**2)**.5;line(i,*map(tuple,[(c+[int(k*s)+506,int(k)+152])[::-1],(c-[int(k*s)-506,int(k)-152])[::-1],b]))
imwrite(f,i)

```

This program is almost entirely ungolfed, and there are aspects of it that are somewhat inaccurate at the moment, but at least it works for the most part. Additionally, there is a *little* bit of hardcoding, but it's only for an approximate window enclosing the border and the coordinate of the first pixel on the border (the latter of which I will actually most likely remove later).

The image used by the program is halved in area (i.e. 1120 x 865), and so the length of lines drawn and the distance between lines is smaller.
> 7 votes

---
Tags: code-golf, graphical-output, image-processing
---


title: How Cloudy Is It?

text:
# Question
Title: How Cloudy Is It?
## Challenge

Given an image of the sky, you must output the cloud cover in oktas. The image supplied will be an image file (the type is up to you) and the output should be to STDOUT.

## Oktas

In meteorology, an okta is a unit of measurement used to describe the amount of cloud cover at any given location such as a weather station. Sky conditions are estimated in terms of how many eighths of the sky are covered in cloud, ranging from 0 oktas (completely clear sky) through to 8 oktas (completely overcast).

The sky will always be a picture from around midday (so, blue sky, not red/night sky).

The colour of a cloud will always be a colour which follows the following pattern:

```
#ABCDEF

```

Where `AB >= C0`, `CD >= C0` and `EF >= C0`.

Or, in RGB:

```
(A, B, C)

```

Where `A >= 192`, `B >= 192` and `C >= 192`.

Here are the percentage coverages related to the oktas:

```
0%    - 0 oktas
12.5% - 1 okta
25%   - 2 oktas
37.5% - 3 oktas
50%   - 4 oktas
62.5% - 5 oktas
75%   - 6 oktas
87.5% - 7 oktas
100%  - 8 oktas

```

The percentages are the percentage of the image which is cloud.

If you the percentage cloud of your image is not a multiple of 12.5, you should round to the nearest.

## Output

The output should just be the okta number (you don't have to say the unit).

## Examples

***1 okta*** (18.030743615677714% cloud)

***0 oktas*** (0.0% cloud)

***3 oktas*** (42.66319444444445% cloud)

(source: hswstatic.com)

***1 okta*** (12.000401814778645% cloud)

**Python code used to calculate numbers**

## Winning

Shortest code in bytes wins.

# Answer
# MATL, ~~18~~ 17 bytes

```
Yi191>3&A1eYm8*Yo

```

Example runs with the four provided images (sorry about preview quality; click for full resolution):

Or remove the last four characters to see the results without rounding:

### Explanation

```
Yi     % Implicitly input filename or URL. Read image. Gives an M×N×3 array
191>   % Does each entry exceed 191?
3&A    % True for 3rd-dim "lines" that only contain true. Gives an M×N matrix
1e     % Linearize (flatten) into a 1×L row vector, with L = M*N
Ym     % Mean of vector
8*     % Multiply by 8
Yo     % Round. Implicitly display

```
> 11 votes

# Answer
# Python 2, ~~114~~ ~~110~~ 98 bytes

-4 bytes thanks to TheLethalCoder
-12 bytes thanks to Ruud

```
import PIL.Image as P
i=P.open(input()).getdata()
print round(8.*sum(min(x)>191for x in i)/len(i))

```

Try it online!
> 10 votes

# Answer
# Java (OpenJDK 8), 204 bytes

```
i->{int x=0,y=0,t=0,w=i.getWidth(),h=i.getHeight();for(;x<w;)for(y=0;y<h;){java.awt.Color c=new java.awt.Color(i.getRGB(x++,y++));if(c.getRed()>191&&c.getBlue()>191&&c.getGreen()>191)t++;}return 8*t/w/h;}

```

Try it online! I always forget that TIO outputs STDERR to the debug tab.. Maybe it could like highlight red in case of an error?
> 7 votes

# Answer
# C#, ~~150~~ 146 bytes

```
b=>{int t=0,c=0,w=0,h;for(;w<b.Width;++w)for(h=0;h<b.Height;++t){var p=b.GetPixel(w,h++);if(p.R>191&p.G>191&p.B>191)c++;}return(int)(c/(t+0d)*8);}

```

*Saved 4 bytes thanks to @Ian H.*

Full/Formatted version:

```
using System.Drawing;

namespace System
{
    class P
    {
        static void Main()
        {
            Func<Bitmap, int> f = b =>
            {
                int t = 0, c = 0, w = 0, h;
                for (; w < b.Width; ++w)
                    for (h = 0; h < b.Height; ++t)
                    {
                        var p = b.GetPixel(w, h++);

                        if (p.R > 191 & p.G > 191 & p.B > 191)
                            c++;
                    }

                return (int)(c / (t + 0d) * 8);
            };

            string[] testCases =
            {
                @"Appearance_of_sky_for_weather_forecast,_Dhaka,_Bangladesh.JPG",
                @"spanish-sky.jpeg",
                @"why-is-sky-blue-1.jpg",
            };

            foreach (string testCase in testCases)
            {
                using (Bitmap bitmap = new Bitmap(testCase))
                {
                    Console.WriteLine(f(bitmap));
                }
            }

            Console.ReadLine();
        }
    }
}

```
> 7 votes

# Answer
# PowerShell, 200 bytes

```
$a=New-Object System.Drawing.Bitmap $args[0]
0..($a.Height-1)|%{$h=$_;0..($a.Width-1)|%{$i+=(("$($a.GetPixel($_,$h)|select R,G,B)"|iex)['R','G','B']-ge192).count-eq3}}
[int]($i/($a.Height*$a.Width)*8)

```

Gets input `$args[0]` as the full image file-path, constructs a `New` `Bitmap` object into `$a`. This is just the internal object name; it supports JPG, PNG, etc.

We then double-loop through the `.height` and then the `.width` of the image, touching each `pixel`. We pull out the `R,G,B` values and then select those that are `-g`reaterthanor`e`qual to `192` and make sure that `count` is `3` (i.e., all of them are white-ish). That Boolean result is added into our accumulator `$i`.

We then divide out to get the percentage, multiply it by `8` to get the number of oktas, and then `[int]` to get just an integer output. *(Note that this performs Banker's Rounding -- if that's not allowed it'll be several more bytes to change the rounding method.)*
> 4 votes

# Answer
# x86 Machine Code, 34 bytes

```
51
31 D2
AD
F7 D0
25 C0 C0 C0 00
75 01
42
E2 F3
C1 E2 03
DB 04 24
52
DB 04 24
DE F1
DB 1C 24
58
5A
C3

```

These bytes of code define a function that takes a bitmap input and returns an integer value indicating its oktas. As in C, arrays (like bitmaps) are represented as a pointer to the first element and a size/length. Thus, this function takes two parameters: the total number of pixels in the bitmap (rows × columns) and a pointer to the bitmap itself.

This code uses a custom register-based calling convention, where the bitmap pointer is passed in the `ESI` register and the bitmap size is passed in the `ECX` register. The result (oktas) is, per usual, returned in `EAX`.

As already stated above, the input is taken as a bitmap. Specifically, a 32-bpp format is used, in a little-endian format, but the alpha channel (highest-order byte) is ignored. This simplifies a lot of things, allowing us to simply iterate through each pixel and check its 32-bit RGB color value. A clever optimization is also used here. Instead of isolating each color component and checking whether it is \>= 192, we just mask the entire 32-bit value by 0xC0C0C0 and test whether the result is \>= 0xC0C0C0. This will evaluate to true for all "cloud" colors, and false for all "sky" (non-cloud) colors. Well, *I* thought it was clever! :-) It certainly saves a large number of bytes.

Therefore, in order to test this code, you will need to convert the input images to 32-bpp bitmaps. You cannot use Windows Paint for this, because it supports maximum of 24 bits-per-pixel. However, there are a number of other software solutions that can do it, such as Adobe Photoshop. I used this free tool, which converts a PNG to a 32-bpp BMP on Windows, meaning that you need only convert from JPEG to PNG (which Paint can do).

Other assumptions that I posit are eminently reasonable:

* The bitmap is assumed to have a size greater than 0 (*i.e.*, it is assumed to contain at least one pixel). This is reasonable because, when they sky is null, we have bigger problems than meteorology.
* The direction flag (`DF`) is assumed to be clear so that we will iterate correctly through the bitmap using the `LODSD` instruction. This is the same assumption made by most x86 calling conventions, so it seems fair. If you don't like it, add 1 byte to the count for a `CLD` instruction.
* The rounding mode for the x87 FPU is assumed to be set to round-to-nearest-even. This ensures that we get the correct behavior when we convert the number of oktas from a floating-point temporary to the final integer result, as verified by test case #4. This assumption is reasonable because this is the default state for the FPU *and* it is required to be maintained even in C code (where truncation is the default rounding behavior, forcing compilers that wish to be standards-compliant to generate inefficient code that changes the rounding mode, does the conversion, and then changes the rounding mode back).

**Ungolfed assembly mnemonics:**

```
; int ComputeOktas(void*    bmpBits  /* ESI */,
;                  uint32_t bmpSize  /* ECX */);
   push  ecx                  ; save size on stack
   xor   edx, edx             ; EDX = 0 (cloudy pixel counter)

CheckPixels:
   lodsd                      ; EAX = DS:[ESI]; ESI += 4
   not   eax
   and   eax, 0x00C0C0C0
   jnz   NotCloudy
   inc   edx
NotCloudy:
   loop  CheckPixels          ; ECX -= 1; loop if ECX > 0

   shl    edx, 3              ; counter *= 8
   fild   DWORD PTR [esp]     ; load original size from stack
   push   edx
   fild   DWORD PTR [esp]     ; load counter from stack
   fdivrp st(1), st(0)        ; ST(0) = counter*8 / size
   fistp  DWORD PTR [esp]     ; convert to integer, rounding to nearest even
   pop    eax                 ; load result
   pop    edx
   ret

```

Surely you haven't made it all this way down and are still wondering how the code works? :-)
Well, it's pretty simple. We just iterate through the bitmap one 32-bit value at a time, checking to see if that pixel RGB value is "cloudy" or "not cloudy". If it's cloudy, we increment our pre-zeroed counter. At the end, we compute: cloudy pixelstotal pixels × 8
(which is equivalent to: cloudy pixelstotal pixels ÷ 0.125).

I can't include a TIO link for this because of the need for input images. I can, however, provide you with the harness I used to test this on Windows:

```
#include <stdio.h>
#include <assert.h>
#include <Windows.h>

int main()
{
   // Load bitmap as a DIB section under Windows, ensuring device-neutrality
   // and providing us direct access to its bits.
   HBITMAP hBitmap = (HBITMAP)LoadImage(NULL,
                                        TEXT("C:\\...\\test1.bmp"),
                                        IMAGE_BITMAP,
                                        0, 0,
                                        LR_LOADFROMFILE  | LR_CREATEDIBSECTION);
   assert(hBitmap != NULL);

   // Get the bitmap's bits and attributes.
   DIBSECTION dib;
   GetObject(hBitmap, sizeof(dib), &dib);
   assert(dib.dsBm.bmBitsPixel == 32);
   uint32_t cx = dib.dsBm.bmWidth;
   uint32_t cy = abs(dib.dsBm.bmHeight);
   uint32_t sz = cx * cy;
   assert(sz > 0);

   int oktas = ComputeOktas(sz, dib.dsBm.bmBits);

   printf("%d\n", oktas);

   return 0;
}

```

Be careful with this, though! As defined above, `ComputeOktas` uses a custom calling convention, which a C compiler will not respect. You need to add code at the top of the assembly language procedure to load values from the stack into the expected registers, *e.g.*:

```
mov  ecx, DWORD PTR [bmpSize]
mov  esi, DWORD PTR [bmpBits]

```
> 4 votes

# Answer
# C#, 313 bytes

```
namespace System.Drawing.Imaging{b=>{unsafe{int t=0,c=0,y=0,x,w=b.Width,h=b.Height;var d=b.LockBits(new Rectangle(0,0,w,h),(ImageLockMode)1,(PixelFormat)137224);for(;y<h;++y){var r=(byte*)d.Scan0+y*d.Stride;for(x=0;x<w*3;++t)if(r[x++]>191&r[x++]>191&r[x++]>191)c++;}b.UnlockBits(d);return(int)(c/(t+0d)/0.125);}}}

```

Obviously longer than my other answer but this one uses `LockBits` and `unsafe` code to directly access the image in memory; as such it is incredibly quick. I could probably remove the call to `UnlockBits` but it's more correct with it there.

Full/Formatted version:

```
namespace System.Drawing.Imaging
{
    class P
    {
        static void Main()
        {
            Func<Bitmap, int> f = b =>
            {
                unsafe
                {
                    int t = 0, c = 0, y = 0, x, w = b.Width, h = b.Height;

                    var d = b.LockBits(new Rectangle(0, 0, w, h), (ImageLockMode)1, (PixelFormat)137224);
                    for (; y < h; ++y)
                    {
                        var r = (byte*)d.Scan0 + y * d.Stride;

                        for (x = 0; x < w * 3; ++t)
                            if (r[x++] > 191 & r[x++] > 191 & r[x++] > 191)
                                c++;
                    }
                    b.UnlockBits(d);

                    return (int)(c / (t + 0d) / 0.125);
                }
            };

            string[] testCases =
            {
                @"Appearance_of_sky_for_weather_forecast,_Dhaka,_Bangladesh.JPG",
                @"spanish-sky.jpeg",
                @"why-is-sky-blue-1.jpg",
            };

            foreach (string testCase in testCases)
            {
                using (Bitmap bitmap = new Bitmap(testCase))
                {
                    Console.WriteLine(f(bitmap));
                }
            }

            Console.ReadLine();
        }
    }
}

```
> 3 votes

# Answer
# JavaScript, ~~83~~ 77 bytes

-6 bytes by *ETHproductions*

```
f=i=>(z=a=b=0,i.map(e=>{z=e<192||z;(++b%4)||((z||(a+=64))&&(z=0))}),a/b+1>>1)

```

## Inputs

Picture #1

Picture #2

Picture #3

Picture #4

## Demo

```
f=i=>(z=a=b=0,i.map(e=>{z=e<192||z;(++b%4)||((z||(a+=64))&&(z=0))}),a/b+1>>1)

window.onload = function(){
 var input = document.getElementById('input');
 input.addEventListener('change', handleFiles);
}
function handleFiles(e){
 var canvas = document.getElementById('canvas')
 var ctx = canvas.getContext('2d');
 var img = new Image;
 img.onload = function(){
  canvas.height = img.height
  canvas.width = img.width
  ctx.drawImage(img, 0,0);
  data = ctx.getImageData(0,0,canvas.width,canvas.height).data;
  console.log(f(data))//invoke f, send imageData as input
 }
 img.src = URL.createObjectURL(e.target.files[0]);
}
```

```
<input type="file" id="input"/><br>
<canvas id="canvas" style="max-width:400px"/>
```
> 3 votes

# Answer
# C (POSIX), 103 bytes

Assumes input as BMP file on stdin.

```
b,c,i,m=0xc0c0c0;main(){lseek(0,54,0);for(;read(0,&b,3);c+=(b&m)==m,i++);printf("%d",(i+16*c)/(2*i));}

```
> 3 votes

# Answer
# dc, 74 bytes

```
???*sa?[1+]ss[r1+r]st[?191<s]su0ddsd[0luxluxlux3=t1+dla>r]dsrxr8*la2/+la/p

```

Input is taken as a P3 ppm file, with all whitespace as newlines. Output is to STDOUT.

Try it online!
> 2 votes

# Answer
# Mathematica 89 bytes

The following binarizes the picture and determines the fraction of clouds, i.e. white pixels. Then it determines how many times .125 fits into the result. It returns the floor of that value.

```
o@i_:=⌊8Tr@Flatten[ImageData@MorphologicalBinarize[i,.932],1]/Times@@ImageDimensions@i⌋

```
> 2 votes

# Answer
# JavaScript (ES6), 218 bytes

```
(a,c=document.createElement`canvas`,w=c.width=a.width,h=c.height=a.height,x=c.getContext`2d`)=>x.drawImage(a,0,0)||x.getImageData(0,0,w,h).data.reduce((o,_,i,d)=>o+(i%4|d[i++]<192|d[i++]<192|d[i]<192?0:1),0)/w/h*8+.5|0

```

Takes an `Image` object as input, which can be created from an `<image>` element.

Test it out here on CodePen!

## Alternative

If input can be taken as flat array of RGBA values, with dimensions: **82 bytes**

```
(d,w,h)=>d.reduce((o,_,i)=>o+(i%4|d[i++]<192|d[i++]<192|d[i]<192?0:1),0)/w/h*8+.5|0

```

This input format is very similar to what this answer on meta suggests.
> 2 votes

---
Tags: code-golf, image-processing
---


title: Staircase writing

text:
# Question
Title: Staircase writing
Write a program or a function that will output a given string in a staircase fashion, writing each part of a word that starts with a vowel one line below the previous part.

For example:

```
Input: Programming Puzzles and Code Golf

Output: Pr          P           C    G
          ogr        uzzl   and  od   olf
             amm         es        e
                ing

```

# Input

A string containing nothing but letters and spaces.

The string can be passed via `STDIN` or function arguments or anything equivalent.

Letters can be lowercase or uppercase.

Inputs are always assumed to follow those rules, you don't need to check for incorrect inputs.

# Output

Each time a vowel (that is, `a`, `e`, `i`, `o`, `u` or `y`) is encountered in a word, you must output the rest of the word on the next line (the encountered vowel included), at the correct horizontal position. This rule is recursive, which means that if there are n vowels in the word, it will be written on n+1 lines.

* The vowel should be written at the beginning of the next line, and not at the end of the previous line when one is encountered.
* Each word starts on the first line, and should thus be formatted independently from other words. Two words are separated by a space.
* If a word starts with a vowel, you have to write it starting on the second line.

# Test cases

* Input: `Programming Puzzles and Code Golf`

Output:

```
Pr          P           C    G
  ogr        uzzl   and  od   olf
     amm         es        e
        ing

```
* Input: `The quick brown fox jumps over the lazy dog`

Output:

```
Th  q     br    f   j          th  l    d
  e  u      own  ox  umps ov     e  az   og
      ick                   er        y

```
* Input: `aeiouy`

Output:

```

a
 e
  i
   o
    u
     y

```
* Input: `YEAh UppErcAsE VOwEls`

Output:

```
               V
Y    Upp        Ow
 E      Erc       Els
  Ah       As
             E

```
* Input: `If you only knew the power of the Dark Side`

Output:

```
            kn   th  p        th  D    S
If y   onl    ew   e  ow   of   e  ark  id
    o     y             er                e
     u

```

# Scoring

This is , so the shortest code wins.

# Answer
# Retina, ~~50~~ ~~44~~ ~~34~~ ~~(+10)~~ ~~32~~ 30 bytes

Thanks to Dennis for saving 14 bytes by using actual control characters.

```
i`[aeiouy]
<VT>$0#
+`#(\S*)
$1<ESC>[A

```

Based on this answer, I'm using ANSI escape codes to move the terminal cursor vertically. The `<ESC>` should be replaced with the control character 0x1B, and `<VT>` with the vertical tab `0x0B`. For simpler testing, you can also replace `<ESC>` with `\e`, `<VT>` with `\v` and feed the output through `printf`.

For counting purposes, each line goes in a separate file. However, for convenience it's simpler to just paste the code into a single file and invoke Retina with the `-s` option.

The first replacement surrounds each vowel in `\v...#`, where the `\v` shifts the cursor downward and the `#` is a marker for the second step. The `i`` is Retina's notation for case-insensitive matching.

The second step then repeatedly (`+``) removes a `#` from a word and puts a `e\[A` at the end of the word which shifts the cursor upward. This stops once the string stops changing, i.e. when there are no more `#` markers in the string.
> 18 votes

# Answer
# CJam, ~~39~~ 36 bytes

```
0000000: 6c 7b 5f 65 6c 22 61 65 69 6f 75 79 22  l{_el"aeiouy"
000000d: 26 7b 22 1b 5b 41 22 27 0b 6f 5c 7d 26  &{".[A"'.o\}&
000001a: 5f 53 26 7b 5d 7d 26 6f 7d 2f           _S&{]}&o}/

```

The above is a reversible xxd dump, since the source code contains the unprintable character VT (code point 0x0b) and ESC (code point 0x1b).

Like this answer, it uses vertical tabs and ANSI escape sequences.

This requires a supporting video text terminal, which includes most non-Windows terminal emulators.

### Test run

Before executing the actual code, we'll disable the prompt and clear the screen.

```
$ PS1save="$PS1"
$ unset PS1
$ clear

```

This makes sure the output is shown properly.

```
echo -n Programming Puzzles and Code Golf | cjam <(xxd -ps -r <<< 6c7b5f656c226165696f757922267b221b5b4122270b6f5c7d265f53267b5d7d266f7d2f)
Pr          P           C    G
  ogr        uzzl   and  od   olf
     amm         es        e
        ing

```

To restore the prompt, execute this:

```
PS1="$PS1save"

```

### How it works

We insert a vertical tab before each vowel to move the cursor down and sufficient copies of the byte sequence **1b 5b 41** (`"\e[A"`) after each space to move the cursor back to the first row.

```
l           e# Read a line from STDIN.
{           e# For each character C:
  _el       e#   Push lowercase(C).
  "aeiouy"& e#   Intersect with "aeiouy".
  {         e#   If the intersection is non-empty:
    ".[A"   e#     Push "\e[A" (will be printed later).
    '.o     e#     Print "\v".
    \       e#     Swap "\e[A" with C.
  }&        e#
  _S&       e#   Intersect C with " ".
  {         e#   If the intersection is non-empty:
    ]       e#     Wrap the entire stack in an array.
  }&
  o         e#   Print C or the entire stack.
}/          e#

```
> 8 votes

# Answer
# Java, 428 bytes

```
void s(String s){int l=s.length(),m=0;char[][]c=new char[l][];for(int i=0;i<c.length;java.util.Arrays.fill(c[i++],' '))c[i]=new char[l];String v="aeiouyAEIOUY";String[]a=s.split(" ");for(int r=0,p=0;r<a.length;r++){String u=a[r]+" ";int o=v.indexOf(u.charAt(0))>=0?1:0,x=p;for(;x<u.length()-1+p;o+=v.indexOf(u.charAt(x++-~-p))>=0?1:0)c[o][x]=u.charAt(x-p);p+=u.length();m=m<o?o:m;}for(int i=0;i<=m;i++)System.out.println(c[i]);}

```

I know, it's horrible. There's probably some chars that can be shaved of, but I'm too lazy to do that.
> 5 votes

# Answer
# C, ~~200~~ 190 bytes

```
i,j,k,l,M;f(char*s){M=strlen(s)+1;char t[M*M];for(;i<M*M;++i)t[i]=(i+1)%M?32:10;for(i=0;i<M-1;++i)k=(strspn(s+i,"aeiouyAEIOUY")?++j:s[i]==32?j=0:j)*M+i,l<k?l=k:0,t[k]=s[i];t[l+1]=0;puts(t);}

```

### Ungolfed:

```
i,j,k,l,M;
f(char *s){
    M = strlen(s)+1;
    char t[M*M];
    for(; i<M*M; ++i) t[i] = (i+1)%M ? 32 : 10;
    for(i=0; i<M-1; ++i)
        k = (strspn(s+i,"aeiouyAEIOUY") ? ++j : s[i]==32 ? j=0 : j) * M + i,
        l<k ? l=k : 0,
        t[k] = s[i];
    t[l+1]=0;
    puts(t);
}

```

It allocates a rectangular buffer (actually square), fills it with spaces and newlines, then traverses the given string. At the end it adds a null character to prevent trailing newlines.

Technically it's not a function since it contains globals; in fact it can't be called more than once (`j` and `l` must be 0 at the start). To comply, `i,j,k,l,M;` could be moved to `int i,j=0,k,l=0,M;` at the start of the function.
> 4 votes

# Answer
# CJam, 47

Yeah, it's a bit long, but it's not "cheating" with ANSI codes :)

```
q_{_S&!\el"aeiouy"-!U+*:U}%_0|$])\zff{~@-S@?}N*

```

Try it online

The idea is to calculate a line number for each character (starting at 0, incrementing at vowels and jumping back to 0 at space), and then for each line, repeat the string but replace the characters that have a different line number with a space.
> 4 votes

# Answer
# Perl, 31 bytes

```
0000000: 24 5c 3d 22 1b 5b 41 22 78 20 73 2f 5b 61  $\=".[A"x s/[a
000000e: 65 69 6f 75 79 5d 2f 0b 24 26 2f 67 69     eiouy]/.$&/gi

```

The above is a reversible xxd dump, since the source code contains the unprintable character VT (code point 0x0b) and ESC (code point 0x1b).

The code is 27 bytes long and requires the switches `040p` (4 bytes).

The program requires a video text terminal that supports vertical tabs and ANSI escape sequences, which includes most non-Windows terminal emulators.

### Test run

Before executing the actual code, we'll disable the prompt and clear the screen.

```
$ PS1save="$PS1"
$ unset PS1
$ clear

```

This makes sure the output is shown properly.

```
echo -n Programming Puzzles and Code Golf | perl -040pe "$(xxd -ps -r <<< 245c3d221b5b41227820732f5b6165696f75795d2f0b24262f6769)"
Pr          P           C    G
  ogr        uzzl   and  od   olf
     amm         es        e
        ing

```

To restore the prompt, execute this:

```
PS1="$PS1save"

```

### How it works

* `perl -040p` automatically reads the input as space-separated tokens (`-040`), saves each token in `$_` (`-p`) and executes the program.
* `s/[aeiouy]/.$&/gi` performs a global, case-insensitive search in `$_` for vowels and replaces each vowel by the control character VT (moves the cursor down), followed by the vowel itself.
* `s` returns the number of replacements it made, so `$\=".[A"x s...` saves multiple copies of the byte sequence **1b 5b 41** (moves the cursor up) in `$\`, one for each vowel.
* At the end of the program, Perl automatically prints `"$_$\"`, because of the `-p` switch.
> 4 votes

# Answer
# K, ~~81~~ ~~72~~ ~~70~~ 66 bytes

Well, it's a start:

```
`0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/{+\{12>"aeiouyAEIOUY"?x}'x}'(0,&~{"  "?x}'x)_ x}

```

Usage Examples:

```
  `0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/{+\{12>"aeiouyAEIOUY"?x}'x}'(0,&~{"  "?x}'x)_ x} "Programming Puzzles and Code Golf"
Pr          P           C    G
  ogr        uzzl   and  od   olf
     amm         es        e
        ing
  `0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/{+\{12>"aeiouyAEIOUY"?x}'x}'(0,&~{"  "?x}'x)_ x} "YEAh UppErcAsE VOwEls"
               V
Y    Upp        Ow
 E      Erc       Els
  Ah       As
             E

```

## Edit 1:

Better. Made some surface level improvements:

```
`0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/{+\{12>"aeiouyAEIOUY"?x}'x}'(0,&~{"  "?x}'x)_ x}
`0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/(+\12>?["aeiouyAEIOUY"]')'_[0,&" "=x]x}

```

Notably, I inverted the arguments for `?` when I perform the vowel search and thus eliminated the need for a lambda, did the same inversion with `_` where I split words on whitespace, and I realized that `~{" "?x}'x` is a really silly, overcomplicated way of saying `" "=x`.

## Edit 2:

Another surface level tweak- negate `s` before applying it to the lambda, saving parens inside:

```
`0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/(+\12>?["aeiouyAEIOUY"]')'_[0,&" "=x]x}
`0:{+{z!y,x#" "}[|/s].'x,'-s:,/(+\12>?["aeiouyAEIOUY"]')'_[0,&" "=x]x}

```

## Edit 3:

OK, let's take a different approach to calculating the offset for each character. Instead of splitting the sequence at spaces and calculating a running sum (`+\`) of the positions of vowels, we can operate on the whole input string in one pass, multiplying the running sum by 0 whenever we encounter a space. I need the negation of this sequence, so I can subtract instead of adding as I scan and use number-of-distinct (`#?`) instead of max (`|/`) when I calculate the amount of vertical padding.

```
`0:{+{z!y,x#" "}[|/s].'x,'-s:,/(+\12>?["aeiouyAEIOUY"]')'_[0,&" "=x]x}
`0:{+{z!y,x#" "}[#?s].'x,'s:1_0{(~" "=y)*x-12>"aeiouyAEIOUY"?y}\x}

```

That saves another 4 characters. Phew!
> 3 votes

# Answer
# Ruby: ~~135~~ ~~131~~ ~~124~~ ~~115~~ 112 characters

```
a=[]
y=l=0
gets.split(r=/(?=[aeiouy ])/i).map{|w|w=~r&&y+=1
w<?A&&y=0
a[y]='%*s%s'%[-l,a[y],w]
l+=w.size}
puts a

```

Sample run:

```
bash-4.3$ ruby staircase.rb <<< 'Programming Puzzles and Code Golf'
Pr          P           C    G
  ogr        uzzl   and  od   olf
     amm         es        e
        ing

```
> 2 votes

# Answer
# GNU Sed, 151 + 1

(+1 as it needs the `-r` flag)

```
s/^/ /;h;s/[aoeuiy]/_/ig;:a;s/_[^ _]/__/;ta;y/_/ /;g;:x;:b;s/ [^ aoeuiy]/  /i;tb;h;s/([^ ])[aoeuiy]/\1_/ig;:c;s/_[^ _]/__/;tc;y/_/ /;g;s/ [^ ]/  /ig;tx

```

I thought that sed would be the tool for this job, but found it surprisingly hard.

### Readable version:

```
#!/bin/sed -rf

# make sure the string starts with a space
s/^/ /
h

# print leading consonants, if any
s/[aoeuiy]/_/ig
:a
s/_[^ _]/__/
ta
y/_/ /
p
g

:x
# strip the consonants just printed
:b
s/ [^ aoeuiy]/  /i
tb
h

s/([^ ])[aoeuiy]/\1_/ig
:c
s/_[^ _]/__/
tc
y/_/ /
p
g
# remove leading vowel of each word
s/ [^ ]/  /ig
tx

```
> 2 votes

# Answer
# C, 192 bytes

```
f(char*s){int l=0,r=1,v,c;for(;r;l=1){v=l;r=0;char*p;for(p=s;*p;++p){c=*p;if(c==' ')v=l,putchar(c);else if((strchr("aoeuiyAOEUIY",c)?--v:v)<0)r=1,putchar(' ');else*p=' ',putchar(c);}puts(p);}}

```

This iterates through the string, blanking characters as it prints them. It repeats until there are no non-space characters left to print. It's portable C, making no assumptions about character encoding.

### Readable version

```
f(char *s) {
    int l=0,       /* true if we've done the first line (no vowels) */
        r=1,       /* true if characters remain in buffer */
        v,         /* how many vowels to print from current word */
        c;         /* current character value */
    for (l=0; r; l=1) {
        v = l;
        r = 0;
        char *p;
        for (p=s;*p;++p) {
            c=*p;
            if (c==' ') {       /* a space - reset vowel counter */
                v=l;
                putchar(c);
            } else if ((strchr("aoeuiyAOEUIY",c)?--v:v)<0) {
                /* vowel conter exceeded - print a space */
                putchar(' ');
                r=1;
            } else {
                /* print it, and obliterate it from next line of output */
                putchar(c);
                *p=' ';
            }
        }
        puts(p); /* p points at the NUL, so this just prints a newline */
    }
}

```
> 2 votes

# Answer
# Python 2, ~~145~~ 142 Bytes

Probably isn't as competitive as some other methods, but I thought this was a cool way of using regex.

```
import re;s=I=input()[::-1]+" ";i=0
while s.strip()or i<2:s=re.sub("(?!([^aeiouy ]*[aeiouy]){%s}[^aeiouy]* )."%i," ",I,0,2)[::-1];print s;i+=1

```

The regex `(?!([^aeiouy ]*[aeiouy]){N}[^aeiouy]* ).` matches any single character *not* within the N-th group of letters from the end of a word. Since it counts from the end of the world I reverse the string before and afterward, and I also have to add a space at the end, but after that it becomes a simple matter of using `re.sub` to replace every instance of these characters with a space. It does this for every value of N until the string is empty.
> 2 votes

# Answer
# Python 3, 265 207 202 185 177 characters

```
i=input()
w,e=i.split(" "),lambda:[[" "]*len(i)]
o,x=e(),0
for p in w:
    y=0
    for c in p:
        if c in"AEIOUYaeiouy":o+=e();y+=1
        o[y][x],x=c,x+1
    x+=1
for l in o:print("".join(l))

```

This is terrible and I'm not proud. I know this can be made shorter, but I thought I'd post anyway.

Inspired by the C version, it creates a list which is then filled while traversing the input string.
> 2 votes

# Answer
# Octave, 132 129 characters

```
p=1;x=[];y=input(0);for j=1:numel(y);if regexpi(y(j),'[aeiouy]');p+=1;elseif y(j)==" ";p=1;end;x(p,j)=y(j);end;x(x==0)=32;char(x)

```

### Test

**Input:** `"YEAh UppErcAsE VOwEls"`

**Output:**

```
               V
Y    Upp        Ow
 E      Erc       Els
  Ah       As
             E

```
> 1 votes

# Answer
# Gema: ~~53~~ 48 characters

```
/[aeiouyAEIOUY]/=@append{u;^[[A}^K$1
 = $u@set{u;}

```

Note that `^[` (x1b) and `^K` (x0b) are single characters. (In the below sample run I use their copy-paste friendly `\e` and `\v` equivalents, in case you want to try it out.)

Sample run:

```
bash-4.3$ gema '/[aeiouyAEIOUY]/=@append{u;\e[A}\v$1; = $u@set{u;}' <<< 'Programming Puzzles and Code Golf'
Pr          P           C    G
  ogr        uzzl   and  od   olf
     amm         es        e
        ing

```
> 1 votes

# Answer
# Jelly, 42 bytes

```
Ḳµe€Øyœṗ⁸⁶ṁ$;¥\z⁶Zµ€µḷ/⁶ṁW⁸;ḣ®µ€L€Ṁ©$¡ZK€Y

```

Try it online!

Why Jelly, why? :-(
> 1 votes

---
Tags: code-golf, string
---