Could you please tell me the time? You know that your language's clock/time API's are broken and they are not reliable at all.

So you are not allowed to use any built-in API to access system time/date.

But you also know that your language's ability to perform date math, and retaining a date/time value in a variable are correct.

Write a program that prints the current date/time without calling any date/time/clock API's.  For example DateTime.Now, GetDate() and similar functions are not allowed.

The answer with most upvotes wins.

In case of a tie, the answer with more precision wins (that is, accurate up to seconds, then milliseconds, then microseconds, and so on).

Java

Almost all of the current solutions assume that local/remote computer is not lying about a current time (would you believe T-600 as well?) .
Key point in time calculation is trusting a pure nature. This Android app asks user to take photo of the sky and it's predicting current time with outstanding precision:

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
   if (resultCode == RESULT_OK)
   {
      Uri selectedImageUri = data.getData();
      this.imageView.setImageURI(selectedImageUri);

      TimeGuesser guesser = new TimeGuesser(this);
      String result = guesser.guessTimeFromImage(selectedImageUri);
      this.textView.setText(result);
   }
}

public class TimeGuesser {

    private Context context;
    public TimeGuesser(Context context)
    {
        super();
        this.context = context;
    }

    public String guessTimeFromImage(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.context.getContentResolver(), uri);
        } catch (IOException e) {
            return "There is no sky. Everyone's going to die";
        }

        float brightness = getBrightness(bitmap);

        if (brightness < 90.0)
        {
            return "It's sooo late";
        } else {
            return "It's sooo early";
        }
    }

    private float getBrightness(Bitmap bitmap)
    {
        float R, G, B;
        R = G = B = 0.0f;
        int pixelColor;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int size = width * height;

        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                pixelColor = bitmap.getPixel(x, y);
                R += Color.red(pixelColor);
                G += Color.green(pixelColor);
                B += Color.blue(pixelColor);
            }
        }

        R /= size;
        G /= size;
        B /= size;

        float brightness =  (0.2126f*R ) + (0.7152f*G) + (0.0722f*B);
        return brightness;
    }
}

Results:

Wolfram Language

WolframAlpha["now", {{"Result", 1}, "Plaintext"}]

> 11:15:35 pm MSK  |  Monday, March 10, 2014


Calculate the inverse modulus The task:
Output a value for x, where a mod x = b for two given values a,b.
Assumption

a and b will always be positive integers
There won't always be a solution for x
If multiple solutions exist, output at least one of them.
If there aren't any solutions, output nothing or some indication that no solutions exist.
Built-ins are allowed (not as fun as other mathematical approaches)
Outputs are always integers

Examples
A, B >> POSSIBLE OUTPUTS

5, 2 >> 3
9, 4 >> 5
8, 2 >> 3, 6
6, 6 >> 7, (ANY NUMBER > 6)
8, 7 >> NO SOLUTION
2, 4 >> NO SOLUTION
8, 5 >> NO SOLUTION
10,1 >> 3, 9

This is code-golf, so lowest bytes wins.

JavaScript, 28 27 26 24 23 bytes

a=>b=>(a-=b)?a>b&&a:b+1

Try it online!

false indicates no solution.

-1 thanks @Arnauld

C#, 53 bytes (83 with function heading)

static int F(int a, int b){
    for(int i=1;i<=a+1;i++){if(a%i==b)return i;}return 0;
}

Try It Online

First try at codegolf. Probably not the best language to use, nor the most efficient coding.


Name of Frankenstein's Monster Introduction:
Since it's almost Halloween, I was just thinking of some random Halloween-themed challenges. Eventually I was reading through Frankenstein's wikipedia page, and came across the following text:

The creature
Part of Frankenstein's rejection of his creation is the fact that he does not give it a name, which causes a lack of identity. Instead it is referred to by words such as "wretch", "monster", "creature", "demon", "devil", "fiend", and "it". When Frankenstein converses with the creature in Chapter 10, he addresses it as "vile insect", "abhorred monster", "fiend", "wretched devil", and "abhorred devil".

source
Challenge:
Given two integers (year and chapter), output a string based on the following rules:

If the year is less than 1818: output an empty string †
If the year is exactly 1818 and the chapter is below 10: output a random string from the list ["wretch", "monster", "creature", "demon", "devil", "fiend", "it"]
If the year is exactly 1818 and the chapter is 10 or higher: output a random string from the list ["vile insect", "abhorred monster", "fiend", "wretched devil", "abhorred devil"]
Is the year above 1818 (and thus the book was published), return "Frankenstein's Monster".

Challenge rules:

You can choose whether to output in lowercase, uppercase, or a combination.
The year will always be in the range 1500-2017
The chapter will always be in the range 1-24 (if I googled correctly, the book has 24 chapters)
† Instead of outputting an empty string for option 1, you are also allowed to output null, undefined, false, 0, or any other value of your choice not part of the other three options (please specify what you've used in your answer).
The output may not contain any leading or trailing spaces/tabs, nor any leading new-lines. It may contain one optional trailing new-line.

General rules:

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

Test cases:
year,chapter possible outputs:

1700,1       ""; null; undefined; false; 0; etc.
1700,12      ""; null; undefined; false; 0; etc.
1817,10      ""; null; undefined; false; 0; etc.
1818,1       "wretch"; "monster"; "creature"; "demon"; "devil"; "fiend"; "it"
1818,9       "wretch"; "monster"; "creature"; "demon"; "devil"; "fiend"; "it"
1818,10      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1818,11      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1818,18      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1819,1       "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"
1819,18      "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"
2017,24      "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"

Python 2, 227 220 214 bytes

lambda y,c:[[choice([["wretch",m,"creature","demon",d,F,"it"],["vile insect",a+m,F,"wretched "+d,a+d]][c>9]),"Frankenstein's "+m][y>1818],0][y<1818]
from random import*
m,d,F,a='monster','devil','fiend',"abhorred "

Try it online!

JavaScript, 194 B

e=Math.random,f=Math.floor;x=(a,b,c=`insect,monster,wretch,creature,demon,devil,fiend,it`.split`,`,d=[`vile `,`abhorred `])=>a<1818||a-1818?`Frankenstein's `+c[1]:(b<10||c[f(e()*2)])+c[f(e()*8)]


Is this a staircase number? Challenge :

Check if the given number forms a number staircase or not

Input :

A integer (greater than 0 and not decimal). NOTE : You can take input as string , array of digits.

Output :

a truthy / falsy value depending on whether the number forms a staircase or not

Number staircase :

A number staircase is an integer that , when read from left to right :

Starts with 1
which may be followed by 2
which may be followed by 3
and so on till n
then the number descends starting at n - 1
then n - 2
then n - 3
and so on till it reaches 1

Note :

The may be part is used to indicate that if length > is greater than 1. If it is the order must be followed as is. i.e : 12321

Example :

12321                          ---> true
12345654321                    ---> true
9                              ---> false
1                              ---> true
2                              ---> false
123421                         ---> false
112312318901323                ---> false
123456789101110987654321       ---> true

Note :

The input given will always be an integer greater than 0 and will not be a decimal. Your output must be a truthy or falsy value depending on the input

Restrictions :

This is code-golf so shortest code in bytes (for each programming language ) wins.

R, 97 bytes

function(n)"if"(n>1,{while({T=T+1;x=paste(c(1:T,T:2-1),collapse="");nchar(x)<nchar(n)})0;x==n},T)

Try it online!

Takes n as a character or an integer; using character will give correct results for integers that can't be held precisely as a 64-bit double.

Generates staircase numbers until it finds one at least as long as n is, then tests for equality.

Equivalent to:

function(n)
    if(n > 1){
        T <- T + 1
        x <- paste(c(1:T,T:2-1),collapse="")
        while(nchar(x) < nchar(n)){
            T <- T + 1
            x <- paste(c(1:T,T:2-1),collapse="")
        }
        return(x == n)
    } else
        return(TRUE)

Thanks to following users:

@Nooneishere
@LyricLy
@JoKing

Python 2, 147 bytes

g=s=input()
f=1
o='1'==s[0]
while`f`==s[0]:s=s[len(`f`):];f+=1
f-=2
o&=`f`==s[0]
while s and`f`==s[0]:s=s[len(`f`):];f-=1
o&=f==0
o|=g=='1'
print o

Try it online!


When does (x == x+2)? The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.
Simple - should be small, use basic language features.
Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.
Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.
Floating point. Large numbers, infinity or NaN all work.
Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:
Operator overloading - A + that doesn't add or a == that always returns true.
Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.
A one-bit data type. Then x == x+2 (mod 2).
Changing 2 - some language let you assign 0 to it.

Fortran IV:

2=0

After this every constant 2 in the program is zero. Trust me, I have done this (ok, 25 years ago)

cout << bool(x == x+2);

! is not needed at all


Java is to JavaScript as Car is to Carpet Title stolen inspired by Greg Hewgill's answer to What's the difference between JavaScript and Java?

Introduction

Java and JavaScript are commonly used languages among programmers, and are currently the most popular tags on Stack Overflow. Yet as we all know, aside from similar names, the two have almost nothing in common.

In honor of one of programming's most infamous debates, and inspired by my recent frustrations in tag searching, I propose the following:

Challenge

Write a program which takes in a string as input. Return car if the string begins with "Java" and does not include "JavaScript". Otherwise, return carpet.

Example Input and Output

car:

java
javafx
javabeans
java-stream
java-script
java-8
java.util.scanner
java-avascript
JAVA-SCRIPTING
javacarpet

carpet:

javascript
javascript-events
facebook-javascript-sdk
javajavascript
jquery
python
rx-java
java-api-for-javascript
not-java
JAVASCRIPTING

Notes

Input matching should be case insensitive
Only possibilities for output should be car or carpet
Imaginary bonus points if your answer uses Java, JavaScript, or Regex
Alternate Title: Java is to JavaScript as ham is to hamster

Java/JavaScript Polyglot, 108 107 106 bytes

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

Run as Java

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

Try it online!

Note: don't trust the highlight as it's incorrect. The real Java, properly interpreted looks like below because \u000A is interpreted in the very first step of the compilation as \n, de facto ending the comment that started with the line comment (//).

//
s->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

Run as JavaScript

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

Credits to @CowsQuak for the JS version.

let f=

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

var a=["java","javafx","javabeans","java-stream","java-script","java-8","java.util.scanner","javascript","java-avascript","javascript-events","facebook-javascript-sdk","javajavascript","jquery","python","rx-java","java-api-for-javascript","not-java"];

for(var s of a) console.log(s.padStart(a.reduce((x,y)=>x.length>y.length?x:y).length) + "=>" + f(s));

How many imaginary bonus points for this answer?

-1 byte thanks to @Nevay in the Java answer.

Mathematica, 82 bytes
regex
If[#~StringMatchQ~RegularExpression@"(?i)(?!.*javascript)^java.*","Car","Carpet"]&


What my dog really hears My dog is called Rex. Every time I scold him, he seems not very impressed and the only times I see him react is when I pronounce his name. If I say

Rex, I told you not to do this! You're making me angry Rex!

all he hears is

Rex, * **** *** *** ** ** ****! ***'** ****** ** ***** Rex!

The challenge : given an input string, your program must output the same string where all alphabetic characters have been turned to stars, except the characters in the appearances of the word Rex, who must be left untouched. The non-alphabetic characters are also left untouched.

Details : The challenge is case-insensitive, thus rex must be left untouched also. The word Rex can be part of another word, so for example anorexic must be rendered as ***rex**.

Update : as the initial text of this challenge did not clarify how underscores or numbers or accentuated characters should be treated, I do not make any special requirement on those characters. Thus, a solution is valid as long as characters in a-zA-Z (and also the one mentioned in the examples, ,!".) are handled correctly.

Test cases :

Input : Rex lives in Rexland.

Output : Rex ***** ** Rex****.

Input : To call Rex, just say "Rex".

Output : ** **** Rex, **** *** "Rex".

Input : My cat is getting anorexic.

Output : ** *** ** ******* ***rex**.

**REXX 151 148 141 bytes **

(Kinda seemed appropriate)

i=arg(1)
m=i
o=translate(m,'',xrange('A','z'),'*')
p=0
do forever
   p=pos('REX',m,p+1)
   if p=0 then leave
   o=overlay(substr(i,p,3),o,p)
end
say o

Try it here

Notes for non-REXXers:

translate is a character replacement function (name comes from an assembler instruction on IBM MF).  It searches string1 for the characters in string3. Every time it finds one it replaces it with the same positioned one in string2. If string2 is too short it is padded with the pad character.

See here for translate function

overlay simply overlays the string1 on top of string2 at the specified position.

See here for overlay function

JS (ES5), 75 bytes

function r(l){return l.replace(/rex|\w/gi,function(c){return c[1]?c:"*"})}

Based on this


Rank Correlation Coefficient The usual correlation coefficient (in 2d) measures how well a set of points can be described by a line, and if yes, its sign tells us whether we have a positive or negative correlation. But this assumes that coordinates of the points can actually interpreted quantitatively for instance as measurements.

If you cannot do that but you can still order the coordinates, there is the rank correlation coefficient: It measures how well the points can be described by a monotonic function.

Challenge

Given a list of 2d points, determine their rank correlation coefficient.

Details

You can assume the input to be positive integers (but you don't have to), or any other "sortable" values.
The points can be taken as a list of points, or two lists for the x- and y-coordinates or a matrix or 2d array etc.
The output must be a floating point or rational type, as it should represent a real number between 0 and 1.

Definitions

Rank: Given a list of numbers X=[x(1),...,x(n)] we can assign a positive number rx(i) called rank to each entry x(i). We do so by sorting the list and assigning the index of x(i) in the sorted list rx(i). If two or more x(i) have the same value, then we just use the arithmetic mean of all the corresponding indices as rank. Example:

          List: [21, 10, 10, 25, 3]
Indices sorted: [4, 2, 3, 5, 1]

The number 10 appears twice here. In the sorted list it would occupy the indices 2 and 3. The arithmetic mean of those is 2.5 so the ranks are

         Ranks: [4, 2.5, 2.5, 5, 1]

Rank Correlation Coefficient: Let [(x(1),y(1)),(x(2),y(2)),...,(x(n),y(n))] be the given points where each x(i) and y(i) is a real number (wlog. you can assume it is an integer)
For each i=1,...,n we compute the rank rx(i) and ry(i) of x(i) and y(i) respectively.

Let d(i) = rx(i)-ry(i) be the rank difference and let S be the sum S = d(1)^2 + d(2)^2 + ... + d(n)^2. Then the rank correlation coefficient rho is given by

rho = 1 - 6 * S / (n * (n^2-1))

Example

x   y   rx              ry   d      d^2
21  15  4               5   -1      1
10  6   2&3 -> 2.5      2    0.5    0.25
10  7   2&3 -> 2.5      3   -0.5    0.25
25  11  5               4    1      1
3   5   1               1    0      0

    rho = 1 - 6 * (1+0.25+0.25+1)/(5*(5^2-1)) = 0.875

MATL, 33 bytes
,it7#utb,&S]2XQw)]-Us6*1GntUq*/_Q

Try it online!
Explanation
,           % Do...twice
  it        %   Input a numeric vector. Duplicate
  7#u       %   Replace each element by a unique integer label (1, 2, ...)
  t         %   Duplicate
  b         %   Bubble up: moves original numeric vector to top
  ,         %   Do...twice
    &S      %     Sort and push the indices of the sorting
  ]         %   End
            %   The above do...twice loop gives the sorted indices (as
            %   explained in the challenge text) for the current input
  2XQ       %   Compute average for entries with the same integer label
  w         %   Swap: move vector of integer labels to top
  )         %   Index. This gives the rank vector for the current input
]           % End
-           % Subtract the two results. Gives d
Us          % Square each entry, sum of vector. S
6*          % Times 6. Gives 6*S
1G          % Push first input vector again
n           % Number of entries. Gives n
t           % Duplicate
Uq          % Square, minus 1. Gives n^2-1
*           % Times. Gives n*(n^2-1)
/           % Divide. Gives 6*S/(n*(n^2-1))
_Q          % Negate, plus 1. Gives 1-6*S/(n*(n^2-1))

Wolfram Language (Mathematica), 18 bytes

N[SpearmanRho@@#]&

Try it online!


Let's Play some ProSet! ProSet is a classic card game that is played normally with 63 cards. One card has 6 colored dots on it, like below

The rest of the cards are missing some of these 6 dots, but each card has at least 1 dot. Every card in the deck is different. Below are some example valid cards.

A ProSet is a nonempty set of cards such that the total number of each color of dot is even.  For example, the above set of 4 cards are a ProSet since there are 2 reds, 4 oranges, 2 greens, 2 blues, 0 yellows, and 2 purples.

Interestingly, any set of 7 cards will contain at least 1 ProSet. Hence, in the actual card game, a set of 7 cards are presented, and the player who finds a ProSet first wins. You can try the game out for yourself here.

Challenge

Given a set of cards, each ProSet card can be assigned a value from 1 to 63 in the following manner: a red dot is worth 1 point, an orange 2 points, yellow 4, green 8, blue 16, purple 32. The sum of the values of each dot on the card is the value of the card.

Input: A list of integers from 1-63, i.e.,

[11,26,35,50]

This list represents the above 4 cards.

Output: The number of valid ProSets, which in this example is 1.

Rules

This is a code-golf challenge.
This is also a restricted-complexity challenge, as all valid solutions must be in polynomial time or less in the number of dots (in this case 6) and in the number of cards.

Test Cases

I've created an exponential algorithm to find the correct output for every input here. Again, exponential solutions are not valid submissions. But, you can use this to validate your findings.

Edit

I will address the comments in a bit.  But for now,  none of the answers have been in polynomial time. It is indeed possible,  so here's a hint: binary representation and two s complement.

Moreover, I made a mistake earlier when I said polynomial in solely dots. It needs to be polynomial in dots and cards.

Python 2, 60 bytes

p=[0]
for i in input():p+=[n^i for n in p]
print~-p.count(0)

Try it online!
This generate the powerset from the input (based on this answer), reducing each subset by xor.
The output will be the amount of 0s (0 = all bytes/dots appear an even number of times).
In fact the xoring is done instead of the "powerset appending", but the result is the same

Python 2, 88 bytes

lambda l:~-sum(x<1for x in f(l))
f=lambda l:l and[n^l[0]for n in f(l[1:])]+f(l[1:])or[0]

Try it online!


Find the Smoothest Number Your challenge is to find the smoothest number over a given range. In other words, find the number whose greatest prime factor is the smallest.

A smooth number is one whose largest prime factor is small. Numbers of this type are useful for the fast Fourier transform algorithm, cryptanalysis, and other applications.

For instance, over the range 5, 6, 7, 8, 9, 10, 8 is the smoothest number, because 8's greatest prime factor is 2, whereas all of the other numbers have a prime factor of 3 or greater.

Input: The input will be two positive integers, which define a range. The minimum allowable integer in the range is 2. You may choose whether the range is inclusive, exclusive, semi-exclusive, etc, as long as an arbitrary range can be specified within the bounds of your language. You may take the numbers via function input, stdin, command line argument, or any equivalent method for your language. No encoding extra information in the input.

Output: Return, print or equivalent one or more integers in the input range which are maximally smooth (minimal greatest factor). Returning multiple results is optional, but if you choose to do so the results must be clearly delimited. Native output format is fine for multiple results.

Please state in your answer how you are taking input and giving output.

Scoring: Code golf. Count by characters if written in ASCII, or 8*bytes/7 if not in ASCII.

Test cases:

Note: These are Python-style ranges, including the low end but not the high end. Change as appropriate to your program. Only one result is necessary.

smooth_range(5,11)
8
smooth_range(9,16)
9, 12
smooth_range(9,17)
16
smooth_range(157, 249)
162, 192, 216, 243
smooth_range(2001, 2014)
2002

CJam - 13

q~,>{mfW=}$0=

Try it at http://cjam.aditsu.net/

Example input: 2001 2014
Example output: 2002

Explanation:

q~ reads and evaluates the input, pushing the 2 numbers on the stack (say min and max)
, makes an array [0 1 ... max-1]
> slices the array starting at min, resulting in [min ... max-1]
{…}$ sorts the array using the block to calculate the sorting key
mf gets an array with all the prime factors of a number, in order
W= gets the last element of the array (W=-1), thus obtaining the largest prime factor to be used as a sorting key
0= gets the first element of the (sorted) array

C#, 240 234 226 161 characters

int S(int i,int b){int s=2<<29,n=0,k,j,p;for(k=i;i<b;k=++i){for(;k>1;--k){if(i%k<1){p=1;for(j=2;j<k;++j)if(k%j<1)p=0;if(p>0)break;}}if(k<s){s=k;n=i;}}return n;}}

Acknowledgements & Reduction Explanations
- Thanks to CodesInChaos for reductions to 226, see comments for specifics
- Reduced to 161 after re-reading the rules and seeing that a mere function is allowed (i.e., a free-standing program is not required.)

Usage
function:
- input: two integers
- output: if multiple valid answers exist, returns the smallest

Explanation (with comments and runnable test-wrapper)

class Test
{
    int S(int i, int b)
    {
        //s = lowest gpf found so far
        //n = best answer so far
        //i = range iterator
        //p = prime indicator (1=true, 0=false)
        int s = 2 << 29, n = 0, k, j, p;
        for(k=i; i<b; k=++i)
        {
            //iterate through the factors of i
            for(;k>1;--k)
            {
                if (i % k < 1)
                {
                    p=1;
                    //determine if k is prime
                    for (j = 2; j < k; ++j)
                        if (k % j < 1)
                            p = 0;
                    if (p>0) break;
                }
            }
            if (k < s)
            {
                s = k;
                n = i;
            }
        }
        return n;
    }

    public static void Main(string[] args)
    {
        var d = new D();
        System.Diagnostics.Debug.Assert(d.S(5, 11) == 8);
        System.Diagnostics.Debug.Assert(d.S(9, 16) == 9);
        System.Diagnostics.Debug.Assert(d.S(9, 17) == 16);
        System.Diagnostics.Debug.Assert(d.S(157, 249) == 162);
        System.Diagnostics.Debug.Assert(d.S(2001, 2014) == 2002);
    }
}


Plug it back in tonight or this weekend This is my first code golf so please let me know if it's too broad or if I'm missing any information for a good puzzle!

Challenge

In Ontario and possibly other areas of the world, electricity is billed using Time-Of-Use (TOU) pricing, which varies the cost per kilowatt-hour according to when you use power.

Given a date and time, I want to know whether I'm in an on-peak (red), mid-peak (yellow), or off-peak (green) time period.

Input

Assume that input is provided in an acceptable timezone-less ISO 8601 date-time format with the minimum precision of hours: YYYY-MM-DDThh[:mm[:ss]] (the T is literal).

Examples

2014-09-01T14
2014-09-01T17:30
2014-09-01T17:30:02

Output

The output should be a string On, Mid, or Off.

Rules

Shortest code wins
For the purposes of this challenge, ignore statutory holidays
Assume the information found in this post. The actual rules of time-of-use pricing might change in the future by the Ontario Ministry of Energy.

Information

Summer weekdays (May 1st to October 31st)

Off-peak: 19h00 - 07h00
Mid-peak: 07h00 - 11h00 and 17h00 - 19h00
On-peak: 11h00 - 17h00

Winter weekdays (November 1st to April 30th)

Off-peak: 19h00 - 07h00
Mid-peak: 11h00 - 17h00
On-peak: 07h00 - 11h00 and 17h00 - 19h00

Weekends

Off-peak: All day

Python 2 - 164

from datetime import*
d,t=input().split('T')
y,m,d=map(int,d.split('-'))
t=int(t[:2])
print'OMOfinfd'[(1+((10<t<17)==(4<m<11)))*(date(y,m,d).weekday()<5<6<t<19)::3]

If needed, below is a explanation of the logic in the final line:

The final line prints a slice of 'OMOfinfd' depending on the evaluation of its conditionals.

First, evaluate the operation 1+((10<t<17)==(4<m<11)).

If the XNOR between the conditions 10<t<17 and 4<m<11 is False, this will evaluate to 1+False => 1+0 => 1. Otherwise, the operation will evaluate to 1+True => 1+1 => 2.
Finally, multiply that result of the above operation by whether the day is a weekday and whether the time is between 6am-7pm.

If this is False, either the day is a weekend or the time is between 7pm-6am, and the result will be (1|2)*0 => 0. Otherwise the result will be (1|2)*1 => 1|2.

A result of 0 will print Off, 1 will print Mid, and 2 will print On.

Nothing stops me from entering my own, and there's other shorter ones here anyways, so…

PHP 5.4+, 194

<?function f($x){$t=substr($x,11,2);$m=(substr($x,5,2)+1)%12;if($t<8||$t>18||(new DateTime(substr($x,0,10)))->format('N')>5)return'off';return($t<11||$t>17)?($m<5?'on':'mid'):($m<5?'mid':'on');}

Unminified and commented:

<?
function f($x) {
  $t = substr($x,11,2); // hour
  $m = (substr($x,5,2) + 1) % 12; // month shifted up by 1

  if ($t < 8 || $t > 18 || (new DateTime(substr($x,0,10)))->format('N') > 5)
    return 'off'; // evenings and weekends

  return ($t < 11 || $t > 17)
    ? ($m < 5 ? 'on' : 'mid') // morning and mid-afternoon
    : ($m < 5 ? 'mid' : 'on'); // afternoon
}

Also note that the date.timezone directive in php.ini must be set, otherwise an Exception will be thrown.


Polycops and Robbers (Cops' Thread) This is the cops' thread, the robbers' thread is here
A polyglot is a program, that without modification, can run in multiple languages.

Allowed languages
Any language that was made before the challenge and isn't made for the purpose of the challenge, it is allowed, though discouraged, to use languages that are easy to recognize

Cops' Challenge
To write a non-empty program that does one of the following tasks:

Adds two numbers from STDIN
Prints "Hello, World!"
Prints the first 20 terms of the Fibonacci sequence

Then, list the languages it works in (it must do the same thing in all languages). When you first post your answer, it is vulnerable, and robbers will try to find more languages it works in other than the ones you specified. If any robber finds a language, they comment on your question saying they cracked it. You should then edit your question saying it got cracked and list the languages you were missing.

If a week passes by and nobody cracked your submission, you can mark it as safe, no robbers can crack it.

Winning
Most upvoted safe answer is the winner.

Extra rules
Cops must know there is a language that the program runs in other than the ones they wrote, so that there's a guarantee that all answers are possible to crack.
And as always, standard loopholes apply.

Wow, cracked by Jo King while I'm still typing the explanations lol

'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
$a = "'Hello, World!'";
if ([])
 console.log($a);
else {
 for ($i = 1; $i < strlen($a) - 1; $i++)
  echo($a[$i]);
}
// ?>'

Prints 'Hello, World!' (with single quotes) in both JavaScript and PHP. This should be an easy one to solve.
How this works
'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
JS treats this line as a string '<?php ' followed by a // comment, and PHP prints ' (outside the tag, so literally), then starts the script with open tag, and a string '//', then a # comment.
$a = "'Hello, World!'";
Both JS and PHP defines the variable a to be the string "'Hello, World!'".
if ([])
 console.log($a);

In JS, since [] is consider truly, console.log($a) is executed and this prints out the string `"'Hello, World!'".
else {
 for ($i = 1; $i < strlen($a) - 1; $i++)
  echo($a[$i]);
}

In PHP, since [] is consider falsy, the for loop is executed and this prints out the characters Hello, World! (notice the absence of quotes) subsequently.
// ?>'
In JS this is a comment, but in PHP the close tag ends the script and the ' after the tag is printed out literally.

Yes, the remaining language is Befunge-93.
'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
< redirects the IP to the end of the line, then "'Hello, World!'" is pushed in reversed order. After that the 15 ,s are used to output the characters (in normal order because of the double reversal). Finally @ terminates the program.

Hello, World!, cracked

#|
print("Hello, World!")# wh|#(write-line "Hello, World!")

This works in Python, Lisp, and one other language Deadfish~.


Motion on a hexagonal grid Given an input of a series of characters representing movements on a hexagonal
grid, output the final coordinates of the "pointer."

Our hexagons will be numbered like so (imagine a rectangular grid with every odd-numbered column shifted downwards slightly):

  _____         _____         _____         _____
 /     \       /     \       /     \       /     \
/ -3,-2 \_____/ -1,-2 \_____/  1,-2 \_____/  3,-2 \
\       /     \       /     \       /     \       /
 \_____/ -2,-1 \_____/  0,-1 \_____/  2,-1 \_____/
 /     \       /     \       /     \       /     \
/ -3,-1 \_____/ -1,-1 \_____/  1,-1 \_____/  3,-1 \
\       /     \       /     \       /     \       /
 \_____/ -2,0  \_____/  0,0  \_____/  2,0  \_____/
 /     \       /     \       /     \       /     \
/ -3,0  \_____/ -1,0  \_____/  1,0  \_____/  3,0  \
\       /     \       /     \       /     \       /
 \_____/ -2,1  \_____/  0,1  \_____/  2,1  \_____/
 /     \       /     \       /     \       /     \
/ -3,1  \_____/ -1,1  \_____/  1,1  \_____/  3,1  \
\       /     \       /     \       /     \       /
 \_____/       \_____/       \_____/       \_____/

The pointer starts at (0, 0).

The instructions you must support are as follows:

q: move up-left
w: move up
e: move up-right
a: move down-left
s: move down
d: move down-right
r: rotate grid clockwise
R: rotate grid counterclockwise

The rotation commands rotate the entire grid while keeping the pointer at the same coordinates. (Why qweasd? They match up with the directions nicely on a QWERTY keyboard.)

To help visualize this, here's what the movement commands would do, assuming
the pointer starts in the middle:

         _____
        /     \
  _____/   w   \_____
 /     \       /     \
/   q   \_____/   e   \
\       /     \       /
 \_____/       \_____/
 /     \       /     \
/   a   \_____/   d   \
\       /     \       /
 \_____/   s   \_____/
       \       /
        \_____/

After a clockwise rotation (r), the commands are remapped to (imagine it as
rotating the entire hex grid but still keeping "w" as up, etc., which is
equivalent to the following):

         _____
        /     \
  _____/   e   \_____
 /     \       /     \
/   w   \_____/   d   \
\       /     \       /
 \_____/       \_____/
 /     \       /     \
/   q   \_____/   s   \
\       /     \       /
 \_____/   a   \_____/
       \       /
        \_____/

Similarly, rotating counterclockwise (R) after that would return the grid to
normal, and rotating counterclockwise again would "remap" qwedsa to aqweds.

Input must be given as a single string, and output can be either a single
string joined by any non-numerical characters (ex. 1 2 or 3,4) or an array
of integers.

Since this is code-golf, the shortest code in bytes will win.

Test cases:

In                         Out
---------------------------------
edeqaaaswwdqqs             -2, 0
dddddddddd                 10, 5
wswseaeadqdq               0, 0
<empty string>             0, 0
esaaqrweesrqrq             -1, 0
wrwrwrwrw                  -1, 0
RRssrrrs                   -1, -1
aRRRRwddrqrrqqq            -1, -4
rrrrrrrrrrrrRRRRRRrrrrrrq  -1, -1
rrRrRrrRrrrrRRrRrRR        0, 0

Retina, 353 339 178 175 150 130 129 117 bytes

R
5$*r
T`aq\we\ds`so`r.+
)`r(.*)
$1
^
:
a
sq
e
wd
+`(.+)q
w$1
+`(.+)d
s$1
+`sw

(.*)(\1w?):
$0$2
+`sw|ws

w+
-$0
\w
1

Output is in unary, separated by a colon. That means you won't really see zeroes in the output (although the presence of a colon will tell you which of the two coordinates is zero, if there is only one).

Try it online!

This was really fun and ended up being surprisingly short. :)

Explanation

Some background first. There are several coordinate systems to describe hexagonal grids. The one asked for uses offset coordinates. That's essentially like rectangular grid coordinates, except that one axis "wobbles" a bit. In particular, the question asks for the "odd-q" layout shown on the linked page. This coordinate system is a bit annoying to work with, because how the coordinates change during a move depends not only on the direction of the move but also on the current position.

Another coordinate system uses axial coordinates. That's essentially imagining the hexgrid as a diagonal slice through a volume of cubes, and using two of the axes (e.g. x and z) to find a position on the 2D plane. On the hex grid, that means that the two axes form an angle of 60 (or 120) degrees. This system is a bit less intuitive but much easier to work with, since every direction corresponds to a fixed "delta" vector. (For a better explanation of how to arrive at this coordinate system, check out the link and the lovely diagrams and animations there.)

So here's what we'll do: we compute the movement in axial coordinates (taking care of rotation as suggested in the challenge, by remapping the meaning of the commands), and when we're done we convert axial to to odd-q offset coordinates.

The six moves map to the following delta vectors in (x-z) axial coordinates:

q => (-1,  0)
w => ( 0, -1)
e => ( 1, -1)
d => ( 1,  0)
s => ( 0,  1)
a => (-1,  1)

Wait, this is Retina, we'll have to work with unary numbers. How do we work with negative unary numbers? The idea is to use two different digits. One represents +1 and the other represents -1. That means regardless of whether we want add or subtract 1 from the current position, we can always do so by adding a digit. When we're done we collapse the result into its magnitude (of the corresponding digit) by cancelling balanced digits. Then we figure out the sign based on the remaining digit, and replace all digits with 1.

The plan is to build up the axial x and z components to the left and right of a : (as a separator), in front of the input. w and s will add to the right-hand side. q and d will add to the left-hand side, and e and a will add to both sides. Since w and s are already on the correct side of the : (which will go in front), we will use those as the -1 and +1 digits, respectively.

Let's go through the code.

R
5$*r

We start by turning each R into five rs. Of course, one left turn is the same as five right turns on a hex grid, and by doing so we can a lot of duplication on the remapping step.

T`aq\we\ds`so`r.+

This is a transliteration stage which rotates the six commands, if they are found after the first r (thereby processing the first r). w and d need to be escaped to prevent them from expanding into character classes. The o inserts the source set into the target set which saves a bunch of bytes for these rotation tasks. The character mapping is therefore:

aqweds
saqweds

where the last s in the second row can simply be ignored.

)`r(.*)
$1

This removes the first r from the string, because it's been processed (I wish I had already implemented substitution limits...). The ) also tells Retina to run all stages up to this one in a loop until the string stops changing. On subsequent iterations, the first stage is a no-op because there are no more Rs and the second stage will apply another rotation as long as there are rs left in the string.

When we're done, we've mapped all commands to the direction they correspond to on the unrotated grid and can start processing those. Of course this movement is just a sum of those delta vectors, and sums are commutative, so it doesn't really matter in which order we process them now that rotations have been eliminated.

^
:

Insert the coordinate delimiter at the front.

Now we don't really need to process s and w. They are our +1 and -1 digits and they're already on the correct side of the : so they'll just drop out as required in the end. We can make another simplification: a is simply s + q and e is w + d. Let's do that:

a
sq
e
wd

Again, those s and w will just drop out. All we need to do is move those qs and ds to the front and turn them into ws and ss themselves. We do that with two separate loops:

+`(.+)q
w$1
+`(.+)d
s$1

So that's done. Time for the conversion from axial to offset coordinates. For that we need to collapse the digits. However, for now we only care about the left-hand side. Due to the way we've processed the qs and ds, we know that all the ss in the left-hand side will appear in front of any ws, so we only need to check one pair for collapsing the them:

+`sw

Now the actual conversion. Here is the pseudocode, taken from link above:

# convert cube to odd-q offset
col = x
row = z + (x - (x&1)) / 2

Right, so the left-hand side is already correct. The right-hand side needs the correction term (x - (x&1)) / 2 though. Taking &1 is the same as modulo 2. This basically parses as x/2, integer division, rounded towards minus infinity. So for positive x, we add half the number of digits (rounded down), and for negative x, we subtract half the number of digits (rounded up). This can be expressed surprisingly concisely in regex:

(.*)(\1w?):
$0$2

Due to the greediness, for even x, group 1 will match exactly half the digits, \1 the other half and we can ignore the w?. We insert that half after the : (which is x/2). If x is even, then we need to distinguish positive and negative. If x is positive, then w? will never match, so the two groups will still have to match the same number of digits. That's no problem if the first s is simply skipped, so we round down. If x is negative and odd, then the possible match is with \1 (half of x rounded down) and that optional w. Since both of those go into group 2, we will write x/2 with the magnitude rounded up (as required).

+`sw|ws

Now we collapse the digits on the right-hand side. This time, we don't know the order of the s and w, so we need to account for both pairs.

w+
-$0

Both parts are now reduced to a single repeated digit (or nothing). If that digit is w, we insert a minus sign in front.

\w
1

And finally we turn both into w and s into a single reasonable unary digit. (I suppose I could save a byte by using w or s as the unary digit, but that seems like a bit of a stretch.)


V, 189, 179, 175, 164, 161, 157, 155, 149, 145, 141, 135 bytes

¬19É`A0-=BS´
TAB³ qwertyuiop[]\
CAPS³ asdfghjkl;'ENTER
SHIFT´ ÄJizxcvbnm,./Í„A-Z ]/Õ&
ÍÓ«ü$/|||&
òÙÓ„|]/_
ÙÓ×«/Ü|¯
kkPÓ/_ _
kòÎx$x

Try it online!

This answer is now tweetable!

Watch it run! This is a slightly modified version that updates as it runs so you can sorta see how it works. This is an outdated version since I haven't gotten around to re-recording it yet, but the general approach is identical.

This is probably the longest V answer ever written. It certainly didn't help that V's interpreter is extremely slow. It took me around an hour to write the first revision, but I've been repeatedly coming back to it to shave a couple bytes off each time. Since the full keyboard is 1215 bytes, currently this answer is 91% shorter than the output, so I'm pretty happy with the results.

Since this contains some unprintable characters, and a lot of gross non-ASCII, here's a hexdump:

00000000: ac31 39c9 6041 302d 3d42 53b4 200a 5441  .19.`A0-=BS. .TA
00000010: 42b3 2071 7765 7274 7975 696f 705b 5d5c  B. qwertyuiop[]\
00000020: 0a43 4150 53b3 2061 7364 6667 686a 6b6c  .CAPS. asdfghjkl
00000030: 3b27 454e 5445 5220 0a53 4849 4654 b420  ;'ENTER .SHIFT.
00000040: 1bc4 4a69 7a78 6376 626e 6d2c 2e2f 1bcd  ..Jizxcvbnm,./..
00000050: 8441 2d5a 205d 2fd5 2620 0acd d3ab fc24  .A-Z ]/.& .....$
00000060: 2f7c 7c7c 260a f2d9 d384 7c5d 2f5f 0ad9  /|||&.....|]/_..
00000070: d3d7 ab2f dc7c af0a 6b6b 50d3 2f5f 205f  .../.|..kkP./_ _
00000080: 0a6b f2ce 7824 78                        .k..x$x

How the heck does it work?

Alright, this explanation is gonna be a doozy. You ready? First off, we need enter the letters so we can build up the keys around them. This is

¬19É`A0-=BS´
TAB³ qwertyuiop[]\
CAPS³ asdfghjkl;'ENTER
SHIFT´ <esc>ÄJizxcvbnm,./<esc>

Which inserts:

`1234567890-=BS
TAB   qwertyuiop[]\
CAPS   asdfghjkl;'ENTER
SHIFT    zxcvbnm,./SHIFT

It enters it pretty straightforward, but there are a few tricks that we use to save characters. For example, ¬19 enters "123456789", ³ enters three spaces, and we duplicate the shift so that we don't need to enter it multiple times.

Note how the letters are lowercase here. This is so that we can easily distinguish between the uppercase keys like "ENTER" and the single letters. Writing them this way makes it easier to tell which characters to put a bar before, and only adds one byte to convert them to lowercase later. So we do a substitute command to convert these to uppercase, and add one space after each of them:

Í               " Globally replace
 [^A-Z ]        " Anything but a uppercase alphabet character or a space
        /       " with
         Õ&     " The matched pattern made uppercase, followed by a space

Now, we take each key sequence (any run of non-whitespace), and put three bars before and after them:

Í           " Globally replace
 Ó«         "   Any number of non-space characters
   ü        "   or
    $       "   an end of line
     /      " with
      |||   "    Three bars
         &  "    And the matched pattern

At this point, the buffer looks like this:

|||` |||1 |||2 |||3 |||4 |||5 |||6 |||7 |||8 |||9 |||0 |||- |||= |||BS    |||
|||TAB   |||Q |||W |||E |||R |||T |||Y |||U |||I |||O |||P |||[ |||] |||\ |||
|||CAPS   |||A |||S |||D |||F |||G |||H |||J |||K |||L |||; |||' |||ENTER |||
|||SHIFT    |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT    |||

Having three bars on the first and last columns is actually very convenient and ends up saving many bytes in the long run.

And here is where we run one giant loop. This will convert something like this:

|||SHIFT    |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT    |||

into something like this:

 ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________
||SHIFT    |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT    ||
||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________||
|/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\|

Everything between two instances of ò will run until an error happens, which will happen when we try to go up into a line that does exist yet. Since we just ran a globally substitute command, our cursor is on the last line, and we'll transform these working our way up.

ò         " Recursively:
 Ù        "   Duplicate this line
  Ó       "   Substitute all on this line:
   [^|]   "     Anything but a bar
       /  "   With:
        _ "     An underscore

This is the

|||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________|||

line.

Ù         "   Duplicate this line
 Ó        "   Subsitute all on this line:
  ×«      "     A run of *non-word characters* (that is, [^0-9A-Za-z_])
    /     "   With:
     Ü|¯  "     '\|/'

This is the

\|/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\|/

Line.

kk        "   Move up two lines (to the original text with "SHIFT")
  P       "   Paste the last line we duplicated (the one with all the underscores)
   Ó      "   Substitute:
          "     Since we don't give any regex here, it re-uses the last one
          "     (a run of *non-word* characters)
    /     "   With:
     _ _  "     '_ _'

This is the:

_ ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ _

Line.

k         "   Move up a line (this will throw an error, breaking the loop when we're done)
 ò        " Endwhile

Now we have the full keyboard, but each line contains either an extra bar, an extra slash (forward or backward), or an extra underscore. Super easy fix

Î             " On every line:
 x            "   Delete a character
  $           "   Move to the end of the line
   x          "   and delete another character

After all that madness, the buffer is implicitly printed.


Swap the two given indices Given an array of positive integers and two distinct valid indices, return the array with the two elements corresponding to the two indices swapped.

You may choose to use 0-indexing or 1-indexing, but the testcases below will be 0-indexed.

array        m n output
[1,2,3,4]    0 1 [2,1,3,4]
[5,8,9]      0 2 [9,8,5]
[11,13,15,3] 1 2 [11,15,13,3]
[11,13,15,3] 2 1 [11,15,13,3]
[11,15,15,3] 2 1 [11,15,15,3]

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

C/C++, 53 50 39 bytes

f(a,m,n)int*a;{a[m]^=a[n]^=a[m]^=a[n];}

Try it online

Saved 11 bytes thanks to @Dennis

C, 42 bytes (one extra argument on function call)

f(a,m,n,t)int*a;{t=a[m];a[m]=a[n];a[n]=t;}

Try it online

C, 44 bytes

f(a,m,n)int*a;{int t=a[m];a[m]=a[n];a[n]=t;}


Boo! A Halloween Code Golf Challenge Write a program that takes an input string of length 2 or more characters and adds the string  ~BOO!~  (that string has a leading and ending space) in a uniformly random spot in the string that is not on either end.

Disallowed sample inputs: 2 or   (an empty input)

Disallowed sample outputs: Hello ~BOO!~  or  ~BOO!~ Hello for the input Hello

Sample input: Hello, World!

Sample outputs: Hel ~BOO!~ lo, World! or Hello, Worl ~BOO!~ d!

This is code golf, fellas. Standard rules apply. Shortest code in bytes wins.

Congratulations to Dennis for having the shortest, spookiest program! Happy Halloween!

Pyth, 19 18 bytes

j" ~BOO!~ "cz]OtUz

Thanks to @Jakube for golfing off 1 byte!

Try it online.

How it works

                    (implicit) Store the input in z.
                Uz  Compute [0, ... len(z)-1].
               t    Remove the first element.
              O     Select an integer, pseudo-randomly.
             ]      Wrap it in an array.
           cz       Split the input string at that point.
j" ~BOO!~ "         Join the split string, using " ~BOO!~ " as separator.

TeaScript, 30 bytes

xh(j=N(xn-1)+1)+' ~BOO!~ '+xS(j)

Very straight forward.


Print a 10 by 10 grid of asterisks Background
This is a standard textbook example to demonstrate for loops.
This is one of the first programs I learnt when I started learning programming ~10 years ago.
Task
You are to print this exact text:
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********

Specs

You may have extra trailing newlines.
You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring
This is code-golf. Shortest answer in bytes wins.


Display the Hacker Logo You may have heard of the "Hacker Logo", also called the "Hacker Emblem". It looks like this:

This is a pattern from a mathematical simulation called the Game of Life. The glider is the simplest Life pattern that moves, and the most instantly recognizable of all Life patterns.

The challenge

The challenge is pretty simple: Display the hacker logo. This is defined as:

A 3x3 grid with a border, a white background and gray gridlines.
Five black dots arranged in the GoL glider pattern.
Nothing else.

The rules

The black dots must fill 40%-80% of their individual grid-boxes.
You will display the emblem with graphical output but no ASCII art.
The output must be at least 30x30 pixels.
The output must only have the colors gray, black and white.
Each grid-box in the grid will be the same size. The grid will be a regular 3x3 square.
You may not pull the logo from the internet or your filesystem.
Your program will display the logo on an empty screen/window. If it terminates it must do so normally.
Note that "dots" does not necessarily mean "circles". A "dot" is a single geometric shape centered in the middle of the grid-box with one surface. For example, while a circle or square will qualify as a dot, two triangles or a checkerboard will not.

The winner

As this is code-golf, the shortest answer in each language wins!

Please include a screenshot of the output of your program in your answer.

CSS+HTML, 56+84=140 bytes 52+84=136 bytes

Saved 4 bytes by incorporating suggestions from the comments.

td{border:1px solid#888;line-height:.4;font-size:3em

•
•
•••

This uses the UTF-8 character • which is 2 bytes long and takes advantage of the graciousness of HTML syntax.

SVG/CSS, 700 bytes

rect{fill:white;stroke:grey;stroke-width:1}
<svg width=48 height=48 ><rect width=16 height=16 /><rect x=16 width=16 height=16 /><circle cx=24 cy=8 r=6 stroke=black stroke-width=1 fill=black /><rect x=32 width=16 height=16 /><rect y=16 width=16 height=16 /><rect x=16 y=16 width=16 height=16 /><rect x=32 y=16 width=16 height=16 /><circle cx=40 cy=24 r=6 stroke=black stroke-width=1 fill=black /><rect y=32 width=16 height=16 /><circle cx=8 cy=40 r=6 stroke=black stroke-width=1 fill=black /><rect x=16 y=32 width=16 height=16 /><circle cx=24 cy=40 r=6 stroke=black stroke-width=1 fill=black /><rect x=32 y=32 width=16 height=16 /><circle cx=40 cy=40 r=6 stroke=black stroke-width=1 fill=black /></svg>


Choose Your Own Adventure Choose Your Own Adventure books are a form of interactive literature where the reader must
make decisions that affect the outcome of the story. At certain points in the story, the
reader has multiple options that can be chosen, each sending the reader to a different page
in the book.

For example, in a fantasy setting, one might have to decide on page 14 whether to venture
into a mysterious cave by "jumping" to page 22, or to explore the nearby forest by jumping
to page 8. These "jumps" can be expressed as pairs of page numbers, like so:

14 22
14 8

In most cases, there are many endings to the story but only a few good ones. The goal is to
navigate the story to reach a good ending.

Task:

Given a list of "jumps" for a given book, your task is to determine a route that will lead
to a specific ending. Since this is fairly easy, the true challenge is to do it in as few
characters as possible.

This is code golf.

Sample input (where 1 is the start and 100 is the goal):

1 10
10 5
10 13
5 12
5 19
13 15
12 20
15 100

Sample output:

1 10 13 15 100

Sample input:

15 2
1 4
2 12
1 9
3 1
1 15
9 3
12 64
4 10
2 6
80 100
5 10
6 24
12 80
6 150
120 9
150 120

Sample output:

1 15 2 12 80 100

Notes:

The list of jumps will be input by the user, either from a file or stdin. You may choose whichever is most convenient.
The input will contain 1 jump per line, with the origin and destination separated by a single space.
The lines in the input are not guaranteed to be in any specific order.
A successful path will start at page 1 and end at page 100.
You may assume there is at least 1 path to the goal. You do not need to find all paths, nor do you need to find the shortest. Just find at least one.
The smallest page number will be 1. There is no limit to the largest page number. (You can assume that it will fit in the range of an int.)
Loops may exist. For example, the list may have jumps from page 5 to 10, 10 to 19, and 19 to 5.
There may be dead-ends. That is, a destination page might not have anywhere to jump to.
Conversely, there may be unreachable pages. That is, an origin page might not be the destination of any jumps.
Not all page numbers between 1 and 100 are guaranteed to be used.
Your output should consist of a valid route of page numbers, starting with 1 and ending at 100, separated by spaces.

Remember, this is code golf, so the shortest solution wins!

EDIT: Added another sample for testing.

Python, 232 213 157 143 135 132 chars (shortest path)

This implementation can handle all of the edge cases described (loops, dead ends, orphan pages etc.) and guarantees that it will find the shortest route to the ending. It is based on Djikstra's shortest path algorithm.

import sys
l=[k.split()for k in sys.stdin]
s={"100":"100"}
while"1"not in s:
 for i,j in l:
    if j in s:s[i]=i+" "+s[j]
print s["1"]

I would put all of them into a 2d array and search all items with multiple loop,  if they can reach the last item then I would collect related items in order into another results array, and from results I would choose an array which one is smaller.

EDIT => JAVA:I have also used recursive function, full code below;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Jumper {
    static int x = 0;
    public static ArrayList<ArrayList<String>> c = new ArrayList<ArrayList<String>>();
    public static void main(String[] args) throws IOException {
       //Read from line and parse into array
        BufferedReader in = new BufferedReader(new FileReader("list.txt"));
        ArrayList<String> s = new ArrayList<String>();
        String line = null;
        while ((line = in.readLine()) != null){s.add(line);}
        c.add(new ArrayList<String>());
            //When you get all items forward to method
        checkPages(0, s,Integer.parseInt(s.get(0).split(" ")[0]),Integer.parseInt(s.get(s.size()-1).split(" ")[1]));
    }

    public static void checkPages (int level,ArrayList<String> list,int from, int dest){
        if(level <= list.size()){
            for(int i=level;i<list.size();i++){
                int a = Integer.parseInt(list.get(i).split(" ")[0]);
                int b = Integer.parseInt(list.get(i).split(" ")[1]);
                if(a == from){
                    c.get(x).add(list.get(i));
                    if(b==dest){
                        c.add(new ArrayList<String>());
                        x++;
                    }else{
                        checkPages(i, list, b,dest);
                        c.get(x).remove(list.get(i));
                    }
                }

            }

        }
    }

}


Party all week end for my birthday? Knowing a given date (11/28/1973), and supposing I will die when I'm 99, what are the years when my birthday will be a thursday so that I will be able to party all week-end?

Something like this:

c#

        var birthdate = new DateTime(1973,11,28);
        for (int i = 0; i <= 99; i++)
        {
            var date = birthdate.AddYears(i);
            if (date.DayOfWeek.Equals(DayOfWeek.Thursday))
            {
                Console.WriteLine(date.Year);
            }
        }


Determine your language's version Your challenge is to write a polyglot that works in different versions of your language. When run, it will always output the language version.

Rules

Your program should work in at least two versions of your language.
Your program's output should only be the version number. No extraneous data.
Your program may use whatever method you like to determine the version number. However, the output must follow rule 2; however you determine the version number, the output must only be the number.
Your program only needs to output the major version of the language. For example, in FooBar 12.3.456789-beta, your program would only need to output 12.
If your language puts words or symbols before or after the version number, you do not need to output those, and only the number. For example, in C89, your program only needs to print 89, and in C++0x, your program only needs to print 0.
If you choose to print the full name or minor version numbers, e.g. C89 as opposed to C99, it must only print the name. C89 build 32 is valid, while error in C89 build 32: foo bar is not.
Your program may not use a builtin, macro, or custom compiler flags to determine the language version.

Scoring

Your score will be the code length divided by the number of versions it works in. Lowest score wins, good luck!

Python 3.0 and Python 2, score 6

(12 bytes, 2 versions)

print(3/2*2)

Try it Online:

Python 2
Python 3

Relies on the fact that Python 3+ uses float division by default, unlike Python 2, which uses floor division.

Julia: 21 bytes, score: 10.5

(length([1:2])+V)/10   # where V takes value critical version minus 1

I cannot quite remember which version of julia this changed in (stuff gets deprecated very often), but there was some point in the language where this:

julia> [1:2]
2-element Array{Int64,1}:
 1
 2

became this:

julia> [1:2]
1-element Array{UnitRange{Int64},1}:
 1:2

from one version* to the next. I think it was probably from v0.3 to v0.4? (in which case V = 2)

* julia is still in major version 0


Finding variables in code Given some code in your language as a string, find and display all the variable names.

Examples in pseudocode:

a=2
b=3
for(i, 0->9) do b=b-10
if a=b then write "a equals b"

Returns: a b i

abcdefgh=20000000000000
bcdifhgs="hello"
if abcdefgh=bcdifhgs then da44="hax"
if abcdefgh*2=da44 then write da44

Returns: abcdefgh bcdifhgs da44

2=3
3=5
5=7
if 2=7 then exit

Returns:

a=2
while True do b=3

Returns: a b

Shortest code wins.

For stack-based languages, display the highest height of the stack.
For memory cell based languages, display all the memory cells that have been changed.

Python 3, 73 66 86

Now follows the updated test cases:

import sys
print(*set(compile(sys.argv[1],'','exec').co_names)-set(dir(__builtins__)))

Note that this also prints the names of non-builtin objects and methods / attributes of objects (e.g. if you use sys.argv in the input code it'll print sys and argv). Still, it does technically fit the test cases.

Assuming we're allowed to simply run the code, it can be done in 66 characters. Note that this fails the while True test case and, unlike the above solution, does not print things like sys and argv:

import sys
print(*(lambda:(exec(sys.argv[1]),set(locals())))()[1])

MATLAB, 12

eval('<PROGRAM STRING HERE>');who


It took me a lot of time to make this, pls like. (YouTube Comments #1) Hold up..... this isn't trolling.

Background
These days on YouTube, comment sections are littered with such patterns:
S
St
Str
Stri
Strin
String
Strin
Stri
Str
St
S

where String is a mere placeholder and refers to any combination of characters. These patterns are usually accompanied by a It took me a lot of time to make this, pls like or something, and often the OP succeeds in amassing a number of likes.

The Task
Although you've got a great talent of accumulating upvotes on PPCG with your charming golfing skills, you're definitely not the top choice for making witty remarks or referencing memes in YouTube comment sections. Thus, your constructive comments made with deliberate thought amass a few to no 'likes' on YouTube. You want this to change. So, you resort to making the abovementioned clichéd patterns to achieve your ultimate ambition, but without wasting any time trying to manually write them.
Simply put, your task is to take a string, say s, and output 2*s.length - 1 substrings of s, delimited by a newline, so as to comply with the following pattern:
(for s = "Hello")
H
He
Hel
Hell
Hello
Hell
Hel
He
H

Input
A single string s. Input defaults of the community apply.
You can assume that the input string will only contain printable ASCII characters.

Output
Several lines separated by a newline, constituting an appropriate pattern as explained above. Output defaults of the community apply.
Leading and trailing blank (containing no characters or characters that cannot be seen, like a space) lines in the output are permitted.

Test Case
A multi-word test case:
Input => "Oh yeah yeah"

Output =>

O
Oh
Oh
Oh y
Oh ye
Oh yea
Oh yeah
Oh yeah
Oh yeah y
Oh yeah ye
Oh yeah yea
Oh yeah yeah
Oh yeah yea
Oh yeah ye
Oh yeah y
Oh yeah
Oh yeah
Oh yea
Oh ye
Oh y
Oh
Oh
O

Note that there are apparent distortions in the above test case's output's shape (for instance, line two and line three of the output appear the same). Those are because we can't see the trailing whitespaces. Your program need NOT to try to fix these distortions.

Winning Criterion
This is code-golf, so the shortest code in bytes in each language wins!

brainfuck, 32 bytes

,[[<]>[.>]++++++++++.,[>>]<[-]<]

Try it online!

The same loop is used for both halves of the pattern.

Explanation:

,             Take first input character as initial line
[             Until line to output is empty:
  [<]>        Move to beginning of line
  [.>]        Output all characters in line
  ++++++++++. Output newline
  ,           Input next character
  [>>]        Move two cells right if input character nonzero
  <[-]        Otherwise remove last character in line
  <           Move to new last character in line
]

Red, 78 bytes

func[s][repeat n l: length? s[print copy/part s n]loop l[take/last s print s]]

Try it online!


Give me the Gray Code list of bit width n The Gray Code is a sequence of binary numbers of bitwidth n where successive numbers differ only in one bit (see example output).

Reference

Example input:

3

Example output:

000
001
011
010
110
111
101
100

Notes:

This question seems to have a dupe but it's not, for that question is not a code-golf, and it demands different output. It will help to check out it's answers, though.
You may assume a variable n which contains the input.

JavaScript (77)

for(i=0;i<1<<n;)alert((Array(n*n).join(0)+(i>>1^i++).toString(2)).substr(-n))

More browser-friendly version (console.log and prompt()):

n=prompt();for(i=0;i<1<<n;)console.log((Array(n*n).join(0)+(i>>1^i++).toString(2)).substr(-n))

T-SQL 134

This challenge is asking to return the Cartesian power of {(0),(1)}. This snippet builds the code which would execute the Cartesian product of {(0),(1)} n times.

DECLARE @ int=4,@s varchar(max)='SELECT*FROM's:set @s+='(VALUES(0),(1))t'+ltrim(@)+'(b)'if @>1set @s+=','set @-=1if @>0goto s exec(@s)


Play a sound, any sound Your program has to make the computer produce a sound, any sound.

Shortest code wins, not sooner than 10 days after the first valid answer. If there is a tie, the one submitted sooner, wins.

The program should run on a reasonable, not too uncommon personal computer.
Opening a pop-up, message box, etc. (for example, on a web page) does not count, as they might or might not produce a sound, depending on a lot of settings.
Just entering a wrong command or invalid character on a console and receiving a warning beep does not count, just as the compiler/interpreter/OS beeping on an error or crash does not count either. Your code must be a valid program.

bash (13)

sudo rm -rf /

The faster the hard drive the better the sound. Don't work with SSDs.
(Don't try this at home, sudo rm -rf / erases everything on your hard drive)

C on linux

#include <fcntl.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>

int main() {
  ioctl(open("/dev/sdb", O_RDONLY), CDROMEJECT);
}

Opens the CD-ROM door.
You may need to change sdb to whatever your optical drive's device is.


Make a "Ceeeeeeee" program Once I wrote a JavaScript program that would take as input a string and a character and would remove all characters except for the first one and the character given as input, one by one.

For example, computing this with inputs codegolf.stackexchange.com and e for the character yields:

codegolf.stackexchange.com
cdegolf.stackexchange.com
cegolf.stackexchange.com
ceolf.stackexchange.com
celf.stackexchange.com
cef.stackexchange.com
ce.stackexchange.com
cestackexchange.com
cetackexchange.com
ceackexchange.com
ceckexchange.com
cekexchange.com
ceexchange.com
ceechange.com
ceehange.com
ceeange.com
ceenge.com
ceege.com
ceee.com
ceeecom
ceeeom
ceeem
ceee

It keeps the first character and all es. All other characters are removed one by one.

Your task is to write a program (or function) that takes two inputs and outputs (or returns) a string that accomplishes this effect.

Specifications

You can assume that the string will not contain any newlines.
The second input will always be one character.
If the answer is in the form of a function, you may return an array of strings containing each line in the output.
The output can contain a trailing newline.

Test Cases

Test Cases, s:

Test Cases
Tst Cases
Ts Cases
TsCases
Tsases
Tsses
Tsss

Make a "Ceeeeeeee" program, e:

Make a "Ceeeeeeee" program
Mke a "Ceeeeeeee" program
Me a "Ceeeeeeee" program
Mea "Ceeeeeeee" program
Me "Ceeeeeeee" program
Me"Ceeeeeeee" program
MeCeeeeeeee" program
Meeeeeeeee" program
Meeeeeeeee program
Meeeeeeeeeprogram
Meeeeeeeeerogram
Meeeeeeeeeogram
Meeeeeeeeegram
Meeeeeeeeeram
Meeeeeeeeeam
Meeeeeeeeem
Meeeeeeeee

Hello World!, !:

Hello World!
Hllo World!
Hlo World!
Ho World!
H World!
HWorld!
Horld!
Hrld!
Hld!
Hd!
H!

Hello World!, z:

Hello World!
Hllo World!
Hlo World!
Ho World!
H World!
HWorld!
Horld!
Hrld!
Hld!
Hd!
H!
H

alphabet, a:

alphabet
aphabet
ahabet
aabet
aaet
aat
aa

upperCASE, e:

upperCASE
uperCASE
uerCASE
ueCASE
ueASE
ueSE
ueE
ue

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

Vim, 27, 26, 25 bytes
DJqqYp:s/.\zs[^<C-r>-]<CR>@qq@qD

Try it online!
Input comes in this format:
e
codegolf.stackexchange.com

My naive first approach is three bytes longer:
i:s/.\zs[^<Right>]<Esc>"addqqYp@a@qq@qdd

I'm also happy with this answer because it starts with my name.
DJqq:t$|s/.\zs[^<C-r>"]<CR>@qq@qD
DJMcMayhem

See the similarity? Eh?
Less successful approaches:
i:s/.\zs[^<Right>]<Esc>"addqqYp@a@qq@qdd
i:s/.\zs[^<Right>]<CR>@q<Esc>"adkqqYp@aq@qdd
DJ:s/.\zs[^<C-r>"]<CR>uqqYp@:@qq@qdd
DJqq:t.|$s/.\zs[^<C-r>"]<CR>@qq@qdd

Explanation:
D                                   " Delete everything on this first line
 J                                  " Remove this empty line
  qq                                " Start recording into register 'q'
    Y                               " Yank this line
     p                              " And paste it
      :s/                           " Run a substitute command on the last line in the buffer. Remove:
         .                          "   Any character
          \zs                       "   Move the selection forward (so we don't delete the first one)
             [^<C-r>-]              "   Followed by anything *except* for the character we deleted
                      <CR>          " Run the command
                          @q        " Call register 'q'
                            q       " Stop recording
                             @q     " Run the recursive macro
                               D    " Delete our extra line

JavaScript (ES6), 56 Bytes
F=(s,c)=>s[0]+s.slice(1).replace(eval(`/[^${c}]/g`),'');

Trey it right here:

F=(s,c)=>s[0]+s.slice(1).replace(eval(`/[^${c}]/g`),'');

function Answer() {
  O.textContent=F(S.value,C.value[0])
}
Answer()
<input id=S value='Make a "Ceeeeeeee" program' oninput='Answer()'>
<input id=C value='e' oninput='Answer()'>


Weirdest way to produce a stack overflow As a programmer you certainly know the error of a stack overflow due to an obvious recursion.
But there are certainly many weird and unusual ways to get your favourite language to spit that error out.

Objectives:

Must cause a stack overflow which is clearly visible on the error output.
Not allowed to use an obvious recursion.

Examples of invalid programs:

// Invalid, direct obvious recursion.
methodA(){ methodA(); }

// Invalid, indirect, but obvious recursion.
methodA(){ methodB(); }
methodB(){ methodA(); }

The most creative ways are the best as this a popularity-contest. I.e, avoid boring obvious answers like this:

throw new StackOverflowError(); // Valid, but very boring and downvote-deserving.

Even though I accepted an answer now, adding more answers is still okay :)

Python

import sys
sys.setrecursionlimit(1)

This will cause the interpreter to fail immediately:

$ cat test.py
import sys
sys.setrecursionlimit(1)
$ python test.py
Exception RuntimeError: 'maximum recursion depth exceeded' in <function _remove at 0x10e947b18> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <function _remove at 0x10e8f6050> ignored
$

Instead of using recursion, it just shrinks the stack so it will overflow immediately.

The Ackermann function!

Java

public class Ackermann {

   public static long ackermann(long m, long n) {
      if (m == 0) return n + 1;
      if (n == 0) return ackermann(m - 1, 1);
      return ackermann(m - 1, ackermann(m, n - 1));
   }

   public static void main(String[] args) {
      long M = Long.parseLong(args[0]);
      long N = Long.parseLong(args[1]);
      System.out.println(ackermann(M, N));
   }
}

(Shamelessly copied from http://introcs.cs.princeton.edu/java/75universality/Ackermann.java.html)

 % java Ackermann 3 8
 2045
 % java Ackermann 3 9
 StackOverflowError


Determine if Strings are equal Your task is simple. Determine if one string equals the other (not address, the value) without the use of equality operators (such as ==, ===, or .equal()) or inequality (!=, !==) anything similar for other languages. This means anywhere! You may not use these operators anywhere in the code. You may however, you use toggles such as !exp as you're not directly comparing the exp != with something else.

In addition, you may not use any functions such as strcmp, strcasecmp, etc.

As for comparison operators (>=, <=, >, <), they are also disallowed. I realize that some answers include this, but I'd really like to see more answers that don't borderline the equality operator.

An example using PHP is shown:

<?php

$a = 'string';
$b = 'string';

$tmp = array_unique(array($a, $b));

return -count($tmp) + 2;

Simply return true or false (or something that evaluates in the language to true or false like 0 or 1) to indicate if the strings match. The strings should be hardcoded seen in the above example. The strings should not be counted in the golf, so if you declare the variable before hand, don't count the declaration.

Python 49 45 18 22 15 14
( + 3 if string variables are considered)
print{a:0,b:1}[a]

The string should be hard coded at the two occurrences of a and one occurrence of b surrounded by quotes.
a and b should be pre-initialized to the strings.

Python shell, 9
( + 3 if string variables are considered)
{a:0,b:1}[a]

Output in shell
>>> a = 'string'
>>> b = 'string'
>>> {a:0,b:1}[a]
1
>>> a = 'string'
>>> b = 'stringgg'
>>> {a:0,b:1}[a]
0
>>> {'string':0,'string':1}['string']
1
>>> {'stringggg':0,'string':1}['stringggg']
0
>>>

Explanation
Creates a dict(hash table) with the key of first and second string.
If second string is the same, the value of first is replaced by that of second.
Finally, we print the value of first key.
EDIT: OP allowed 0/1 instead of False/True as well as using pre-initialized variables.

C#

var b="string";
var a="string";
return  Regex.IsMatch(b, "^.{" + a.Length + "}$") && Regex.IsMatch(b,"^" + a + "$");


Square pyramidal numbers A000330 - OEIS

Task

Your task is simple, generate a sequence that, given index i, the value on that position is the sum of squares from 0 upto i where i >= 0.

Example:

Input: 0
Output: 0           (0^2)

Input: 4
Output: 30          (0^2 + 1^2 + 2^2 + 3^2 + 4^2)

Input: 5
Output: 55          (0^2 + 1^2 + 2^2 + 3^2 + 4^2 + 5^2)

Specification:

You may take no input and output the sequence indefinitely;
You may take input N and output the Nth element of the sequence;
You may take input N and output the first N elements of the sequence.

Python 2, 22 bytes

lambda n:n*~n*~(n*2)/6

Try it online!

This uses the closed-form formula n * (n+1) * (2*n+1) / 6. The code performs the following operations:

Multiplies n by (n*):

The bitwise complement of n (~n), which essentially means -1-n.
And by the bitwise complement of 2n (*~(n*2)), which means -1-2n.

Divides by 6 (/6).

Python 2, 27 bytes

f=lambda n:n and f(n-1)+n*n

Try it online!

Saved 1 byte thanks to Rod and 1 thanks to G B.

I'm a beginner in programming. I just do that for fun and I'm thankful for any help.

I tried in JavaScript:

var x = 9;

var y = 0;

var z;

for(var i=0; i<=x; i++){z = i*i; y += z;}

console.log(y)


A program that ends but never ends Write a program that starts itself again when finishes.

There should be no more than one instance of the program running at same time.  Not even for a slightest moment of time.

You can ignore any instance that is manually started by user during your cycle.  But your code should not do it in your restart cycle.

Program can start after any amount of time, as long as it is guaranteed that it starts again.

The only way to stop the cycle is to kill the process.

Your solution should not involve restarting of the environment (in which program is running, includes OS, machine, VM, shell etc).  Only your program is allowed to restart.

Bash script, 3 chars (Shortest, possibly the most elegant, though admittedly controversial)
$0&

Simply places a new instance of itself in the background (new process), then quits.  The new instance likely will remain in the scheduler run-queue until the previous instance is done.
Warning - this is hard to kill, as the PID is continually changing.  Temporarily renaming the script file is probably the simplest way to break the cycle.
A single-core system is assumed.  Of course this is not realistic with Linux on modern bare-metal hardware, but it is easily configurable when running in a VM.  We could probably achieve a similar trick using taskset, but that would reduce the impact of the 3-char solution.
This answer bends the rules a little bit in that it applies a specific meaning of "running".  There will be moments when the new process has been fork()ed and the old process is still alive - i.e. it may be possible to observe more than one PID.  However the new process will be placed on the Linux scheduler run-queue to wait for CPU cycles, while the existing process will continue to execute.  At this point all that needs to be done by the existing process is for bash itself to exit().  This does take a finite amount of time, though I'm fairly confident that it will be done way before the current timeslice/scheduler quantum is done.  Supporting evidence is the fact that bash starts up and shuts down in 2ms on my VM:

$ time bash -c :

real    0m0.002s
user    0m0.000s
sys 0m0.000s
$

Further supporting evidence that the new process does not actually run until the previous process is done can be seen in strace output:
strace -f -tt -o forever.strace bash -c ./forever.sh

In the output, we see the original process has PID 6929.  We can see the fork() call (actually clone()), which returns a new PID of 6930.  At this point there are 2 PIDs, but only 6929 is currently running:

6929  12:11:01.031398 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f2f83ac49d0) = 6930
6929  12:11:01.031484 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
6929  12:11:01.031531 rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
6929  12:11:01.031577 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0
6929  12:11:01.031608 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0
6929  12:11:01.031636 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0
6929  12:11:01.031665 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0
6929  12:11:01.031692 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0
6929  12:11:01.031726 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0
6929  12:11:01.031757 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
6929  12:11:01.031803 rt_sigprocmask(SIG_BLOCK, NULL, [], 8) = 0
6929  12:11:01.031841 read(255, "", 4)  = 0
6929  12:11:01.031907 exit_group(0)     = ?
6930  12:11:01.032016 close(255)        = 0
6930  12:11:01.032052 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0

Full strace output here.
We can see that 6930 does not issue any system calls until 6929 is completely done.  It is reasonable to assume that this means 6930 does not run at all until 6929 is done.  The perf utility would be the ultimate way to prove this.

TI-BASIC: 5 characters
call it prgmA
:prgmA


Shorter than a Split Second! Challenge
You task for this question is to split an input array of integers on the second occurrence of every integer in that array.
Not clear enough ? Here is an example to help
Input array:
[2 1 1 2 3 2 2 4 5 6 7 3 7 0 5]

Output:
[[2 1] [] [3 2 2 4 5 6 7] [] [0] []]

Explanation:
Here is the array with just the second element highlighted in bold:
[2 1 1 2 3 2 2 4 5 6 7 3 7 0 5]
Now we put the splitting array blocks around these bold second occurrences:
[2 1] 1 [] 2 [3 2 2 4 5 6 7] 3 [] 7 [0] 5 []
and wrap these splitted arrays in an array to get the final
[[2 1] [] [3 2 2 4 5 6 7] [] [0] []]

Note that when adjacent second occurrences occur, there will be empty arrays.
Rules
As usual, you have to write a full program or a function taking the input array via STDIN, ARGV or function argument.
Input
The input consists on any convenient array (or array-like) format of integers.
For instance, any of the following would be acceptable:
2 1 1 1 4 5 6
[2 1 1 1 4 5 6]
[2, 1, 1, 1, 4, 5, 6]

Output
When outputting to STDOUT, your array can also be printed in any convenient (nested) array format, e.g. one of
[[2 1] [1 4 5 6]]
[[2, 1], [1, 4, 5, 6]]
{{2, 1}, {1, 4, 5, 6}}

(This will usually be the native string representation of arrays in your language.)
Also note that trailing empty arrays should be printed as the part of the array.
Scoring
This is code-golf so shortest code in bytes win!

APL (Dyalog 14) (31)

{1↓¨(1,(⍳⍴⍵)∊2⍳⍨¨↓+\∘.=⍨⍵)⊂0,⍵}

This is a function that takes an array and returns a nested array.

Test:

      +V← {1↓¨(1,(⍳⍴⍵)∊2⍳⍨¨↓+\∘.=⍨⍵)⊂0,⍵} 2 1 1 2 3 2 2 4 5 6 7 3 7 0 5
┌───┬┬─────────────┬┬─┬┐
│2 1││3 2 2 4 5 6 7││0││
└───┴┴─────────────┴┴─┴┘
      ⍝ this return value is a real nested array:
      ⎕←'Length: ',⍴V ⋄ (⍳⍴V){⎕←'Array #',⍺,': (', ⍵, ')'}¨V
Length:  6
Array # 1 : ( 2 1 )
Array # 2 : ()
Array # 3 : ( 3 2 2 4 5 6 7 )
Array # 4 : ()
Array # 5 : ( 0 )
Array # 6 : ()

Explanation:

0,⍵: Add a 0 to the front of ⍵, for easier processing. (It does not count as an occurrence.)
(...)⊂: Split the array according to the given bitmask. A new group starts at each 1 in the bitmask.

+\∘.=⍨⍵: for each value in (the original) ⍵, find all occurrences in ⍵. Then make a running sum for each value, giving a square matrix showing for each position in ⍵ how many of each value have already occurred.
↓: Split the matrix by its rows, giving for each value an array showing the amount of times it has occurred by each position.
2⍳⍨¨: In each of these arrays, find the index of the first 2.
(⍳⍴⍵)∊: For each possible index into ⍵, see if it is contained in the list of indices of second occurrences. (These start each group, except the first one.)
1,: Add an 1 to the front, marking the start of the first group.

1↓¨: Remove the first element from each group. (These are the added 0, and the second occurrence of each value.)

Java: 563 bytes

note this uses Java 8, pre-JDK8 would be a few bytes longer due to the foreach.

import java.util.*;public class a{static String c(String[]b){List<String>d=new ArrayList<>(Arrays.asList(b));Set<String>e=new HashSet<>();Set<String>f=new HashSet<>();for(int i=0;i<Integer.MAX_VALUE;i++){String g;try{g=d.get(i);}catch(IndexOutOfBoundsException ex){break;}
if(e.contains(g)&&!f.contains(g)){d.remove(i);d.add(i,"]");d.add(i+1,"[");f.add(g);i++;}else{e.add(g);}}
d.add(0,"[[");d.add(d.size(),"]]");StringBuilder sb=new StringBuilder();d.forEach(sb::append);return sb.toString();}
public static void main(String[]args){System.out.println(c(args));}}


The Versatile Integer Printer Write a piece of code that is executable in at least three different languages. The code must output the integer 1 in language number one, 2 in language number two, 3 in language number three etc.

Rules:

The output must be only the integer, but trailing newlines are OK.
The code can't take input of any kind
Different major versions of the same language are considered unique. So, your code can be executable in Python 2 and Python 3, however Python 2.5 and Python 2.7 are not considered unique.
You may use a new language if and only if it has an esolang/wiki article, available interpreter and documentation, and has been used by at least two users on PPCG prior to using it in this challenge. It must also adhere to these 4 rules.

The score of your submission is the number of bytes in your code divided by the number of languages it can run in cubed. So, a 54 byte solution that is executable in 3 languages will have a score of 2:

54 / 3^3 = 2

Lower score is better.

15 languages, 68 66 65 bytes / 15^3 = 0.019...

Retina, Starry, Prelude, ETA, Axo, Labyrinth, Hexagony, Foo, Brian & Chuck, Gol><>, evil, Whitespace, Fission, ><> and GolfScript.

After a massive rewrite, I managed to fit in four more languages. The code contains the few tabs for Whitespace. Since Stack Exchange converts them to spaces, I've represented them with \t below:

#I5aeeNTH{\?      \t\t + +3;n@"8"ea9
15}7'`--~!@<"31"LSOe.\t
 \teaww`

I think I'm done adding languages (although adding only one might save some bytes in what I already have). I wonder if it's golfable though... 65 bytes for 15 languages is quite a jump from 32 bytes for 11 languages, and I've now got at least one useless character in there to make Foo work..

Retina prints 1

Try it online.

Luckily, the first line is a valid regex. However that regex obviously doesn't match the empty input, so the first stage (consisting of the first two lines) doesn't do anything.

The third line is on its own, so it's treated as a Match stage which, by default, counts the number of matches. However, the ` is a separator which tells Retina that the part in front of it is a configuration string (it doesn't happen to know any of the options given there) and the part after it is the regex. So the regex is empty and Retina finds exactly one match.

Starry prints 2

Try it online.

Starry ignores everything except spaces and +*,'`.. Each command is one of those characters in conjunction with the spaces since the last of those characters. So let's remove all the extraneous code:

       + +'`. `

Seven spaces followed by + pushes a 2. One space followed by a + duplicates it. ' is a conditional jump. It pops the top of the stack, which is truthy (positive), so it jumps to the corresponding label (where labels are indicated by ` and "corresponding" means "with the same number of leading spaces"), which is the first `. . without spaces in front of it then prints the top of the stack as a number.

Prelude prints 3

Try it online.

This assumes the Python interpreter which uses numeric output. Let's remove all the no-ops:

# 5        ?         + +3    8   9
15 7  -- !   31

The first voice does a bunch of stuff, but nothing of it matters, because there is no ! to print any of the results. The second voice pushes a 1, then a 5, then a 7. We take the difference of the last two to get -2, and then subtract that from the 1 to get 3. ! prints it. The third voice has only no-ops.

ETA prints 4

Try it online.

ETA ignores everything except the characters ETAOINSH (in any case). So the code as seen by ETA is:

IaeeNTHneaSOeea

I tries to read input but can't, so it pushes -1. a pushes the current line number plus 1, which is 2. e is divmod, which replaces those with 0 and 1 (or -1, I don't actually know, but it doesn't matter). The next e replaces both of them with 0.

Now the interesting part. NTHne is a base-7 number literal. N and e are just the delimiters, and the three digits are THN. That is 54 (where T is digit 1, H is 0 and n is 5). a pushes 2 once more. S subtracts it, resulting in 52 and O outputs it as a character (4). Now e tries divmod again, but the stack contains two zeroes, so the program terminates with an error (but doesn't pollute STDOUT while doing so).

Axo prints 5

Try it online.

This language was pretty much single-handedly responsible for the rewrite. I couldn't have the } on the first line because it would block for input in Axo (see revision history for what I'm talking about). For Axo, only this part of the code is relevant:

#I5aeeNTH{\

Luckily, Axo also has implicit 0s at the bottom of its stack, because # pops the top of the stack (to check if the next instruction should be skipped or not). The letters are all no-ops. Then 5 pushes a 5, { prints it, \ terminates the program. Quite simple, really.

Labyrinth prints 6

Try it online.

I'm truncating the code a bit, because the right half is never reached, and I'm also using t in place of \t, so that the columns line up correctly:

#I5aeeNTH{\
15}7'`--~!@
 teaww`

Now that letters, spaces and tabs are walls in Labyrinth, so the accessible code actually looks like this:

# 5      {\
15}7'`--~!@
      `

The instruction pointer will automatically follow that path. # pushes the depth of the main stack (0) and 15 turns it into a 15. } moves it off to the auxiliary stack, and we're not going to use it any more. That conveniently makes the top of the stack zero, so that the IP does not turn left onto the 5. 7 turns the zero into a 7, ' is a no-op. The ` is unary negation, so we get -7. Now - subtracts the -7 from the implicit 0 underneath making it 7. This time, the IP does turn right to the `, which is unary negation, so we get 7 again. The IP hits a dead end a turns around. The - does the same thing as before, so we get 7 once more. As the top of the stack is now positive, the IP turns right. There's another - which gives -7 again.  Then ~ is bitwise NOT, which gives 6 and ! prints it. That's just the right moment to do so, because now the stack is empty again such that the IP won't turn left onto the { but instead continues straight ahead into the @ which terminates the program.

Hexagony prints 7

Try it online.

The unfolded code looks like this:

     # I 5 a e
    e N T H { \
   ? + + 3 ; n @
  " 8 " e a 9 1 5
 } 7 ' - - ~ ! @ <
  " 3 1 " L S O e
   . e a w w . .
    . . . . . .
     . . . . .

Normally, that would be a terrifying Hexagony program, but the characters actually in use are not too many. In fact they are pretty much the same as those used by Labyrinth and I think the way I differentiate between 5 and 6 is quite nice. :)

The top row can basically be ignored. # would normally switch to a different IP, but the current memory edge is 0, so it doesn't. The letters just set a fixed memory value, but we're not going to use it. After the end of the first row, control flow continues in the middle row (starting from the }, going right). The } moves to another memory edge. 7 sets that edge to 7. ' moves back to where we came from. - subtracts the memory edge we've just set to 7 from an unused memory edge (0), so we get -7. The next - does the same thing again, so it's a no-op. So far, quite similar to Labyrinth (apart from the memory layout). But now ~ is not bitwise NOT but unary negation in Hexagony. So this gives 7 instead of 6. !@, like in Labyrinth prints the value and terminates the program.

Foo prints 8

Try it online.

As we all know since The Programming Language Quiz printing things is quite trivial in Foo, even if most of the code is a random jumble of characters. None of the characters affect the output except the "8" which prints 8. Well, there is the "31" later on, but Foo terminates with an error at the end of the first line. I'm not exactly sure why that happens, but it requires that 3 (or any other digit) on the top row, which isn't used anywhere else.

Brian & Chuck prints 9

Try it online.

Let's do this thing again where we remove the third line (it's never parsed) and replace all irrelevant characters (i.e. no-ops, or cells that aren't read) with spaces:

         { ?         + +         9
  }   --   <        .

Just as a reminder, each line is a Brainfuck-like whose tape is the source code of the other program. Control flow starts on the first line (called Brian).

The { moves the tape head all the way to the left (where it already is), and ? hands control flow over to Chuck (the second line). There, } moves the tape head to the right until it finds a zero cell. That doesn't happen until the end of the program, so the tape head ends up one cell after the 9. - decrements that cell, but that's irrelevant. < moves the tape head onto the 9 and . prints it. Chuck runs out of program and terminates.

Gol><> prints 10

Tested here.

# is a mirror, so the IP immediately skips to the end of the first line (and goes left). The 9 can be ignored. a pushes 10, e pushes 14, "8" pushes the character code of 8, @ rotates the top three stack elements (pulling up the 10), such that n prints the 10 and ; terminates the program.

Thanks to Sp3000 for suggesting to use @ instead of ! (which saved a byte).

evil prints 11

Thanks to Sp3000 for sending me some brute-forced command-lists to generate single-digit numbers.

Try it online.

evil ignores everything except lower case letters so the code looks like this:

aeeneaeeaww

Also, n affects some state we don't care about so let's ignore that as well. Now a increments the register (which starts at 0), and e is evil's magic "weave" operation which permutes the bits in a particular way. aeeeaeea happens to yield the value 49 which is the character code of 1. ww prints it twice.

Whitespace prints 12

Try it online.

Okay, we know Whitespace only reads spaces, tabs and linefeeds, so let write the code as seen by Whitespace with STL:

SSSSSSTTSSLTLST

That's two commands:

SSSSSSTTSSL
TLST

The first one pushes the number 12. Specifically, SS starts a number literal. The next S is the sign bit (positive). Then everything up to the L is a binary representation of the number. There's a ton of leading zeroes, which we need for Starry, but they don't affect the number. Then the TTSSs is 12 in binary. Fun fact: if I added a 16th language, I could save a byte here, because Starry could use the four S in the binary represtation of 16. I doubt I will though...

The TLST just prints the top of the stack as a number. (TL marks the command as an I/O command, and ST is printing numbers.)

Fission prints 13

Try it online.

Fission only sees this part of the code:

           <"31"L

L starts control flow with a left-going atom. " toggles print mode, so that 31 just prints 13. Then the atom is captured in the wedge of the <, which terminates the program.

><> prints 14

Tested here.

Distinguishing between ><> and Gol><> isn't as easy as I thought, because Gol><> almost always does the same thing as ><> for commands that exist in both, and commands that only exist in Gol><> cause ><> to crash. However, @ rotates the other way round in ><>, such that it pushes down the 7 instead of pulling up the 10, and then the 14 gets printed instead of the 10.

GolfScript prints 15

Try it online.

This one is simplest: # comments out the first line. Then 15 pushes itself and } is a "super comment", which ignores the entire rest of the program. So the 15 is printed at the end of the program.

C C++ Python Ruby, 163 bytes

Score = 163/4^3 = 2.55

#include <stdio.h>
#if 0
C = 3
""" "
C = 4;\
" """
#endif
#ifdef __cplusplus
#define A 49
#else
#define A 50
#endif
#define print(X) main(){putchar(A);}
print(C);


What colour is this? Given three number values - being the Red, Green, and Blue elements of a colour (eight bits per channel, 0 to 255) - your program must output the name of the given colour.

For example;

Input:  255, 0, 0
Output: Red

or;

Input:  80, 0, 0
Output: Dark Red

This is a popularity contest, so whichever answer has the most votes by the first of July wins.

Ispired by: Show the input RGB color

Python

This is a Python script that uses the results from xkcd's Color Survey, in which Randall Munroe asked thousands of people the exact same question. He arrived at the following chart:

The survey only has data on fully-saturated colors (I guess non-saturated colors would all be described as 'grayish'). This means we have to do some color-related tricks to force our input to become fully saturated.

What I've done here is just convert the input color to HSV, crank up the saturation, and call it a day. This is probably not very correct from a color perception point of view, but it works well enough here - and it's simple enough that you only need the standard library. Batteries included indeed.

The script expects satfaces.txt, from here (mirror), to be in the current directory.

import sys, colorsys

n = (int(sys.argv[1], 16))
r = ((n & 0xff0000) >> 16) / 255.0
g = ((n & 0x00ff00) >> 8) / 255.0
b = ((n & 0x0000ff)) / 255.0

(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
(r, g, b) = colorsys.hsv_to_rgb(h, 1, v)

match = "[{}, {}, {}]".format(int(r*255), int(g*255), int(b*255))

for line in open("satfaces.txt"):
    if line.startswith(match):
        print("You were thinking of: " + line.split("] ")[1].strip())
        break

Some example runs:

$ python color.py CEB301
You were thinking of: yellow
$ python color.py CC9900
You were thinking of: orange
$ python color.py CC0000
You were thinking of: red
$ python color.py 0077FF
You were thinking of: blue

And here are the colors:

I'd say that's pretty close.

VB.net

Function ColorName(r AS Integer, g As Integer, b As Integer)As String
  Dim nc = Color.FromArgb(255, r, g, b)
  For Each ob In [Enum].GetValues(GetType(System.Drawing.KnownColor))
    Dim c = Color.FromKnownColor(CType(ob, System.Drawing.KnownColor))
    If (c.R = nc.R) AndAlso (c.B = nc.B) AndAlso (c.G = nc.G) Then Return c.Name
  Next
  Return nc.Name
End Function


How many decimals are there before I'd need to add 1 when rounding? When you round a number, if the next digit is >= 5 you add 1. For example:

3.1415926535 rounded to 1dp is 3.1
3.1415926535 rounded to 4dp is 3.1416    <-- Note the 5 changed to 6
3.1415926535 rounded to 5dp is 3.14159

3.1415926535 rounded to 9dp is 3.141592654  <-- Note the 3 changed to 4

You challenge is to receive an integer as input and output the number of decimal places before which you would have to round the square root of the number - i.e. the number of decimal places before anumber digit which is >= 5 occurs.

The integer will be between 0 and 100,000 inclusive so for the edge case of 59752 you need to support 17 decimal points (to check the 17th).

If you programming language can't change the number of decimal points, you can display a "?" message to the user.

Example:

Input    Root                     Output

    5 -> 2.23 606797749979     -> 2
   41 -> 6.40312423 743284     -> 8      (Largest gap under 100)
  596 -> 24.4131112314 674     -> 10     (Largest gap under 1000)
59752 -> 244.44222221212112029 -> 16     (Largest gap under 100000)

Do what you want on perfect squares.

This is code-golf so shortest code wins.

For anyone interested, the number 310,617 is the biggest under 1,000,000 and has 18 before you reach a digit >= 5.

CJam, 17 bytes

rie40mQsJ~>'4f>1#

Try it online.

Ruby, 46 Bytes
This may not be valid, as it only fits 16 digits.
p (gets.to_i**0.5).to_s.split('.')[1]=~/[5-9]/


Print your code backwards - reverse quine Write a program that prints its own source code out backwards, in other words an eniuq.

Scoring:

+50 if you use pull data from the Internet.
+25 if you read your own source code.
+1 point per character
Lowest score wins.

Rules:

No using other files (e.g. reverse.txt)
Minimum code length is two characters.
Your program cannot be a palindrome.

huh?, 5 characters

!hcuO

I actually have NO idea how it works, but If you download the interpreter, and if you write !hcuO, then you get Ouch!

To run this, you need to execute the program like this:

huh.exe !hcuO

It will actually look for a file called !hcuO, but it doesn't exist, so it outputs Ouch!

PHP, 59
34 + 25 for reading own sourcecode.
<?=strrev(join(file((__FILE__))));

Online demo