Write a functioning bare-bones IRCd A bit of an unusual one, but hey, why not? :)

The objective: Write a functioning IRC daemon in your language of choice that provides barebones functionality, in as few characters as possible. As long as it fulfills the criteria below, it does not have to fully comply with the IRC RFCs (this would make the challenge significantly less fun), it just needs to work.

Requirements:

Clients must be able to connect on port 6667 and use it. At least irssi and XChat must be able to connect to it successfully with a default configuration.
Users must be able to specify their own nickname, change it while already connected, join channels, leave channels, and exit cleanly (ie. QUIT).
Channels should be created like normal - joining a channel with no users in it 'creates' it. They do not have to be persistent.
Users must be able to send both channel messages and private messages (ie. to other users).
The WHOIS command must be implemented, as well as PING/PONG, LIST, and NAMES (mostly in order to keep clients happy).

Restrictions:

You may not use any third-party libraries (that includes non-core evented I/O libraries). Only standard libraries that come with the platform you use, are permitted.
If your implementation includes explicit support for IRC in the standard library, you may not use that either. Standard-library network functionality is, of course, fine.
Your submission must be able to run independently. No being clever with mIRC scripting :)

Modes, kicks, etc. do not have to be implemented (unless required to make it work with the above clients). SSL isn't necessary either. Just the above barebones functionality, to keep the challenge short and fun.

More information on what IRC is here, RFCs are 1459 and 2812 (I can't link to them directly due to my lack of reputation).
Shortest functional and requirements-compliant submission wins!

C++ (partially golfed) 5655 (with CRLF counting for 1)
This compiles in VS 2013 (uses auto, lambdas and winsock)  It seemed to be working before I golfed it so unless I mucked it up it should still be ok.  One of the reasons it is so big is that the numeric replies I am returning include the text specified in the RFC - I don't know if that is necessary or not.  I tested it with KVirc because it runs portably (not allowed to install software on my PC!)  KVirc seems to work with my server but I don't know about other clients - I did what I thought the RFC said but a lot of it is underspecified so hopefully I understood it right.
The server handles DIE, KILL, NICK, USER, MODE, WHOIS, WHO, JOIN, PART, TOPIC, LIST, NAMES, PRIVMSG, USERS, PING, PONG and QUIT to varying degrees.  For most of them I return the required responses including doing most of the checks needed to return the specified error replies.  For some of them I cheat:

USERS always returns 446 "USERS has been disabled"
the channel MODE message always returns 477 "Channel doesn't support modes"
the user MODE message works properly but the flags are not used by the other commands

I figure it is only partially golfed because I am not very good at golfing so if you see something big please edit the answer and fix it.
Here is the golfed version
#include<time.h>
#include<map>
#include<list>
#include<vector>
#include<string>
#include<sstream>
#include<iostream>
#include<algorithm>
#include<winSock2.h>
#pragma comment(lib,"ws2_32.lib")
#define P m.p[0]
#define Q m.p[1]
#define E SOCKET_ERROR
#define I INVALID_SOCKET
#define T c_str()
#define H second
#define Y first
#define S string
#define W stringstream
#define G else
#define J G if
#define A auto
#define Z bool
#define B empty()
#define K return
#define N 513
#define X(n,x)if(x){r=n;goto f;};
#define U(x,i)for(A i=x.begin();i !=x.end();++i)
#define L(x)U(x,i)
#define V(x)for(A i=x.begin();i!=--x.end();++i)
#define M(x)FD_ZERO(&x);FD_SET(t.s,&x);L(l){FD_SET(i->s,&x);}
#define R(a,b,...){M v={a,b,{__VA_ARGS__}};w(d,v);}
#define F(x)}J(!_stricmp(m.c.T,x)){
using namespace std;struct C{S t;list<S>n;};struct M{S f;S c;vector<S>p;};struct D{SOCKET s;SOCKADDR_IN a;int m,l,i;char b[N];S n,u,h,r;time_t p,q;};map<S,C>c;list<D>l;void w(D d,M m);void x(D&t,S r,Z n){L(c)i->H.n.remove(t.n);L(l){A d=*i;if(d.n!=t.n)R(d.n,"QUIT",t.n,r)J(n)R("","ERROR","QUIT",r)}closesocket(t.s);t.s=I;}void w(D d,M m){S s=(!m.p.B?":"+m.f+" ":"")+m.c;V(m.p)s+=" "+*i;s+=" :"+*m.p.rbegin()+"\r\n";int c=0;do{int b=send(d.s,s.T+c,s.size()-c,0);if(b>0)c+=b;G x(d,"send error",0);}while(s.size()-c>0);}Z e(D&d,M m){A z=m.p.size();if(!_stricmp(m.c.T,"DIE")){K 1;F("KILL")if(z<1)R("","461",d.n,"USER","Not enough parameters")G{Z f=0;L(l)if(i->n==P){f=1;x((*i),P,1);}if(f==0)R("","401",d.n,P,"No such nick/channel")}F("NICK")if(z<1)R("","431",d.n,"No nickname given")G{Z f=0;L(l)if(i->n==P)f=1;if(f==1)R("","433",d.n,"Nickname is already in use")G d.n=P;}F("USER")if(z<4)R("","461",d.n,"USER","Not enough parameters")G{Z f=0;L(l)if(i->u==P)f=1;if(f==1)R("","462",d.n,"Unauthorized channel (already registered)")G{d.u=P;d.m=atoi(Q.T);d.h=m.p[2];d.r=m.p[3];R("","001",d.n,"Welcome to the Internet Relay Network "+d.n+"!"+d.u+"@"+d.h)}}F("MODE")if(z<1)R("","461",d.n,"MODE","Not enough parameters")J(P==d.n){if(z<2)R("","221",d.n,S("")+(d.m&2?"+w":"-w")+(d.m&3?"+i":"-i"))G{A x=(147-Q[1])/14;if(Q[0]=='+'){d.m|=1<<x;}G{d.m&=~(1<<x);}}}G R("","477",d.n,P,"Channel doesn't support modes")F("WHOIS")if(z<1)R("","431",d.n,"No nickname given")G{Z f=0;L(l)if(i->n==P){f=1;R("","311",d.n,(i->n,i->u,i->h,"*",i->r))}if(f==1)R("","318",d.n,P,"End of WHOIS")G R("","401",d.n,P,"No such nick/channel")}F("WHO")L(c[P].n)U(l,j)if(*i==j->n)R("","352",d.n,P,j->u,j->h,"*",j->n,"",j->r)R("","315",d.n,P,"End of WHO")F("JOIN")if(z<1)R("","461",d.n,"JOIN","Not enough parameters")J(P=="0")L(c){U(i->H.n,j)if(*j==d.n)R("","PART",i->Y,d.n)i->H.n.remove(d.n);}G{A&C=c[P];Z f=0;L(C.n)if(*i==d.n){f=1;}if(f==0){C.n.push_back(d.n);R(d.n,"JOIN",P)if(C.t.B)R("","331",d.n,P,"No topic is set")G R("","332",d.n,P,C.t)S q;L(C.n)q+=(q.B?"":" ")+*i;R("","353",d.n,"=",P,q)R("","366",d.n,P,"End of NAMES")}}F("PART")if(z<1)R("","461",d.n,"PART","Not enough parameters")G{Z f=0;A&C=c[P];L(C.n)if(*i==d.n)f=1;C.n.remove(d.n);if(f){if(z<2)m.p.push_back(d.n);R(d.n,"PART",P,Q)}G R("","442",d.n,P,"You're not on that channel")}F("TOPIC")if(z<1)R("","461",d.n,"TOPIC","Not enough parameters")G{A&C=c[P];if(z<2){C.t="";R("","331",d.n,P,"No topic is set")}G{C.t=Q;R("","332",d.n,P,C.t)}}F("LIST")if(z<1){L(c){W ss;ss<<i->H.n.size();R("","322",d.n,i->Y,ss.str(),i->H.t.B?"No topic is set":i->H.t)}R("","323",d.n,"End of LIST")}G{W ss;ss<<c[P].n.size();R("","322",d.n,P,ss.str(),c[P].t.B?"No topic is set":c[P].t)R("","323",d.n,"End of LIST")}F("NAMES")if(z<1){L(c){S q;U(i->H.n,j)q+=(q.B?"":" ")+*j;R("","353",d.n,"=",i->Y,q)}R("","366",d.n,"End of NAMES")}G{S q;L(c[P].n)q+=(q.B?"":" ")+*i;R("","353",d.n,"=",P,q)R("","366",d.n,P,"End of NAMES")}F("PRIVMSG")if(z<1)R("","411",d.n,"No recipient given(PRIVMSG)")J(z<2)R("","412",d.n,"No text to send")G{Z f=0;A from=d.n;L(c)if(i->Y==P){f=1;U(i->H.n,k)U(l,j)if(*k==j->n){A d=*j;R(from,"PRIVMSG",d.n,Q)}}if(f==0)L(l)if(i->n==P){f=1;A d=*i;R(from,"PRIVMSG",d.n,Q)}if(f==0)R("","401",d.n,P,"No such nick/channel")}F("USERS")R("","446",d.n,"USERS has been disabled")F("PING")R("","PONG",P,Q)F("PONG")d.p=time(NULL)+60;d.q=0;F("QUIT")if(!z)m.p.push_back(d.n);x(d,P,1);}G{R("","421",d.n,m.c,"Unknown command")}K 0;}M g(char*d){M m;char*n=d;while(*d!='\0'){if(m.c.B){if(*d==':'){for(;*d!='\0'&&*d!=' ';++d);*d='\0';m.f=n+1;n=++d;}for(;*d!='\0'&&*d!=' ';++d);*d='\0';m.c=n;n=++d;}J(*d==':'){for(;*d!='\0';++d);m.p.push_back(n+1);n=++d;}G{for(;*d!='\0'&&*d!=' ';++d);*d='\0';m.p.push_back(n);n=++d;}}K m;}int main(){int r;WSADATA u;SOCKADDR_IN la;la.sin_family=AF_INET;la.sin_port=htons(6667);la.sin_addr.s_addr=htonl(INADDR_ANY);timeval h;h.tv_sec=0;h.tv_usec=10000;fd_set rs,ws,es;D t;t.n="IRCd";X(1,(0!=WSAStartup(MAKEWORD(2,2),&u)))X(2,(I==(t.s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))))X(3,(E==bind(t.s,(SOCKADDR*)&la,sizeof(la))))X(4,(E==listen(t.s,SOMAXCONN)))while(1){M(rs)M(ws)M(es)X(5,(E==select(0,&rs,&ws,&es,&h)))X(6,(FD_ISSET(t.s,&es)))if(FD_ISSET(t.s,&rs)){D d={};d.l=sizeof(d.a);d.s=accept(t.s,(SOCKADDR*)&d.a,&d.l);X(7,(I==d.s))W s;s<<inet_ntoa(d.a.sin_addr)<<":"<<ntohs(d.a.sin_port);d.n=s.str();d.p=time(NULL)+60;d.q=0;l.push_back(d);}L(l){D&d=*i;if(d.p>0&&time(NULL)>d.p){R("","PING",d.n)d.p=0;d.q=time(NULL)+60;}if(d.q>0&&time(NULL)>d.q)x(d,"PONG",1);if(FD_ISSET(d.s,&es))x(d,"select except",0);if(FD_ISSET(d.s,&rs)){int b=recv(d.s,d.b+d.i,sizeof(d.b)-d.i-1>0,0);if(b>0)d.i+=b;G x(d,"recv error",0);char*y=d.b+d.i-2;if(!strcmp(y,"\r\n")){*y++='\0';*y='\0';M m=g(d.b);memset(d.b,0,N);d.i=0;if(d.p>0&&time(NULL)<d.p){d.p=time(NULL)+60;d.q=0;}if(e(d,m))X(0,1)}}}l.remove_if([](const D&d){K d.s==I;});}r=0;f:L(l)x(*i,"exit",0);x(t,"exit",0);WSACleanup();K r;}

Here is the mostly ungolfed version (still uses some macros):
#include <time.h>
#include <map>
#include <list>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <winSock2.h>
#pragma comment(lib, "ws2_32.lib")
#define READ_BUFFER_SIZE 513
#define EXIT_IF(n,x) if (x) { retval=n; goto finished; };
#define LOOPX(x,it) for (auto it = x.begin(); it != x.end(); ++it)
#define LOOP(x) LOOPX(x,it)
#define LOOP2(x) for (auto it = x.begin(); it != --x.end(); ++it)
#define MAKE_SET(x) FD_ZERO(&x); FD_SET(listener.socket, &x); LOOP(socket_list) { FD_SET(it->socket, &x); }
#define RESPOND(a, b, ...) { message response = {a, b, {__VA_ARGS__}}; tell(data, response); }
#define CASE(x) } else if (!_stricmp(msg.command.c_str(),x)) { std::cout << "Received " << x << " from " << data.nickname << std::endl;
struct channel { std::string topic;  std::list<std::string> nicknames; };
struct message { std::string prefix; std::string command; std::vector<std::string> params; };
struct socket_data { SOCKET socket; SOCKADDR_IN address; int mode,address_length,read_buffer_index; char read_buffer[READ_BUFFER_SIZE]; std::string nickname,username,servername,realname; time_t ping_timer,pong_timer; };
std::map<std::string,channel> channels;
std::list<socket_data> socket_list;
void tell(socket_data data, message msg);
void disconnect(socket_data& target, std::string reason, bool notify)
{
    LOOP(channels) it->second.nicknames.remove(target.nickname);
    LOOP(socket_list)
    {
        auto data = *it;
        if (data.nickname != target.nickname) RESPOND(data.nickname, "QUIT", target.nickname, reason)
        else if (notify) RESPOND("", "ERROR", "QUIT", reason)
    }
    closesocket(target.socket);
    target.socket = INVALID_SOCKET;
    std::cout << "Disconnected " << target.nickname << " reason=" << reason << std::endl;
}
void print(socket_data data, message msg, char *heading)
{
    std::cout << heading << ":\n  " << inet_ntoa(data.address.sin_addr) << ":" << ntohs(data.address.sin_port) << "\n";
    if (!msg.prefix.empty()) std::cout << "  Prefix=" << msg.prefix << "\n";
    std::cout << "  Command=" << msg.command;
    int count = 0; LOOP(msg.params) std::cout << "\n  Param[" << count++ << "]=" << *it;
    std::cout << std::endl;
}
void tell(socket_data data, message msg)
{
    print(data, msg, "Response");

    std::string str = (!msg.prefix.empty() ? ":" + msg.prefix + " " : "") + msg.command;
    LOOP2(msg.params) str += " " + *it;
    str += " :" + *msg.params.rbegin() + "\r\n";

    int start = 0;
    do
    {
        int bytes = send(data.socket, str.c_str() + start, str.size() - start, 0);
        if (bytes > 0) start += bytes; else disconnect(data, "send error", 0);
    }
    while (str.size() - start > 0);
}
bool process(socket_data &data, message msg)
{
    print(data, msg, "Request");

    auto size = msg.params.size();
    auto first = size<1 ? "" : msg.params[0], second = size<2 ? "" : msg.params[1];
    if (!_stricmp(msg.command.c_str(), "DIE")) { return true;
    // and now all the cases
    CASE("KILL")    if (size<1)
                        RESPOND("", "461", data.nickname, "USER", "Not enough parameters")
                    else
                    {
                        bool found = false;
                        LOOP(socket_list) if (it->nickname == first) { found = true; disconnect((*it), first, 1); }
                        if (found == false) RESPOND("", "401", data.nickname, first, "No such nick/channel")
                    }
    CASE("NICK")    if (size<1)
                        RESPOND("", "431", data.nickname, "No nickname given")
                    else
                    {
                        bool found = false;
                        LOOP(socket_list) if (it->nickname == first) found = true;
                        if (found == true) RESPOND("", "433", data.nickname, "Nickname is already in use")
                        else data.nickname = first;
                    }
    CASE("USER")    if (size<4)
                        RESPOND("", "461", data.nickname, "USER", "Not enough parameters")
                    else
                    {
                        bool found = false;
                        LOOP(socket_list) if (it->username == first) found = true;
                        if (found == true) RESPOND("", "462", data.nickname, "Unauthorized command (already registered)")
                        else
                        {
                            data.username = first; data.mode = atoi(second.c_str()); data.servername = msg.params[2];  data.realname = msg.params[3];
                            RESPOND("", "001", data.nickname, "Welcome to the Internet Relay Network " + data.nickname + "!" + data.username + "@" + data.servername)
                        }
                    }
    CASE("MODE")    if (size<1)
                        RESPOND("", "461", data.nickname, "MODE", "Not enough parameters")
                    else if (first == data.nickname)
                    {
                        if (size < 2)
                            RESPOND("", "221", data.nickname, std::string("") + (data.mode & 2 ? "+w" : "-w") + (data.mode & 3 ? "+i" : "-i"))
                        else
                        {
                            auto x = (147 - second[1]) / 14;
                            if (second[0] == '+')
                            {
                                data.mode |= 1 << x;
                                std::cout << "set " << first << " mode bit " << x << "w=2, i=3" << std::endl;
                            }
                            else
                            {
                                data.mode &= ~(1 << x);
                                std::cout << "clear " << first << " mode bit " << x << "w=2, i=3" << std::endl;
                            }
                        }
                    }
                    else
                        RESPOND("", "477", data.nickname, first, "Channel doesn't support modes")
    CASE("WHOIS")   if (size < 1)
                        RESPOND("", "431", data.nickname, "No nickname given")
                    else
                    {
                        bool found = false;
                        LOOP(socket_list) if (it->nickname == first) { found = true; RESPOND("", "311", data.nickname, (it->nickname, it->username, it->servername, "*", it->realname)) }
                        if (found == true) RESPOND("", "318", data.nickname, first, "End of WHOIS")
                        else RESPOND("", "401", data.nickname, first, "No such nick/channel")
                    }
    CASE("WHO")     LOOP(channels[first].nicknames) LOOPX(socket_list, dit) if (*it == dit->nickname)
                        RESPOND("", "352", data.nickname, first, dit->username, dit->servername, "*", dit->nickname, "", dit->realname)
                    RESPOND("", "315", data.nickname, first, "End of WHO")
    CASE("JOIN")    if (size < 1)
                        RESPOND("", "461", data.nickname, "JOIN", "Not enough parameters")
                    else if (first == "0")
                        LOOP(channels) { LOOPX(it->second.nicknames, dit) if (*dit == data.nickname) RESPOND("","PART", it->first, data.nickname) it->second.nicknames.remove(data.nickname); }
                    else
                    {
                        auto& channel = channels[first];
                        bool found = false;
                        LOOP(channel.nicknames) if (*it == data.nickname) { found = true; }
                        if (found == false)
                        {
                            channel.nicknames.push_back(data.nickname);
                            RESPOND(data.nickname, "JOIN", first)
                            if (channel.topic.empty()) RESPOND("", "331", data.nickname, first, "No topic is set")
                            else RESPOND("", "332", data.nickname, first, channel.topic)
                            std::string list; LOOP(channel.nicknames) list += (list.empty() ? "" : " ") + *it;
                            RESPOND("", "353", data.nickname, "=", first, list)
                            RESPOND("", "366", data.nickname, first, "End of NAMES")
                        }
                    }
    CASE("PART")    if (size < 1)
                        RESPOND("", "461", data.nickname, "PART", "Not enough parameters")
                    else
                    {
                        bool found = false;
                        auto &channel = channels[first];
                        LOOP(channel.nicknames) if (*it == data.nickname) found = true;
                        channel.nicknames.remove(data.nickname);
                        if (found)
                        {
                            if (size < 2) msg.params.push_back(data.nickname);
                            RESPOND(data.nickname, "PART", first, second)
                        }
                        else RESPOND("", "442", data.nickname, first, "You're not on that channel")
                    }
    CASE("TOPIC")   if (size < 1)
                        RESPOND("", "461", data.nickname, "TOPIC", "Not enough parameters")
                    else
                    {
                        auto& channel = channels[first];
                        if (size < 2) { channel.topic = ""; RESPOND("", "331", data.nickname, first, "No topic is set") }
                        else { channel.topic = second; RESPOND("", "332", data.nickname, first, channel.topic) }
                    }
    CASE("LIST")    if (size < 1)
                    {
                        LOOP(channels)
                        {
                            std::stringstream ss; ss << it->second.nicknames.size();
                            RESPOND("", "322", data.nickname, it->first, ss.str(), it->second.topic.empty() ? "No topic is set" : it->second.topic)
                        }
                        RESPOND("", "323", data.nickname, "End of LIST")
                    }
                    else
                    {
                        std::stringstream ss; ss << channels[first].nicknames.size();
                        RESPOND("", "322", data.nickname, first, ss.str(), channels[first].topic.empty() ? "No topic is set" : channels[first].topic)
                        RESPOND("", "323", data.nickname, "End of LIST")
                    }
    CASE("NAMES")   if (size < 1)
                    {
                        LOOP(channels)
                        {
                            std::string list; LOOPX(it->second.nicknames, dit) list += (list.empty() ? "" : " ") + *dit;
                            RESPOND("", "353", data.nickname, "=", it->first, list)
                        }
                        RESPOND("", "366", data.nickname, "End of NAMES")
                    }
                    else
                    {
                        std::string list; LOOP(channels[first].nicknames) list += (list.empty() ? "" : " ") + *it;
                        RESPOND("", "353", data.nickname, "=", first, list)
                        RESPOND("", "366", data.nickname, first, "End of NAMES")
                    }
    CASE("PRIVMSG") if (size < 1)
                        RESPOND("", "411", data.nickname, "No recipient given (PRIVMSG)")
                    else if (size < 2)
                        RESPOND("", "412", data.nickname, "No text to send")
                    else
                    {
                        bool found = false;
                        auto from = data.nickname;
                        LOOP(channels) if (it->first == first)
                        {
                            found = true;
                            LOOPX(it->second.nicknames, nit) LOOPX(socket_list, dit) if (*nit == dit->nickname) { auto data = *dit; RESPOND(from, "PRIVMSG", data.nickname, second) }
                        }
                        if (found == false)
                            LOOP(socket_list) if (it->nickname == first)
                            {
                                found = true;
                                auto data = *it; RESPOND(from, "PRIVMSG", data.nickname, second)
                            }
                        if (found == false)
                            RESPOND("", "401", data.nickname, first, "No such nick/channel")
                    }
    CASE("USERS")   RESPOND("", "446", data.nickname, "USERS has been disabled")
    CASE("PING")    RESPOND("", "PONG", first, second)
    CASE("PONG")    data.ping_timer = time(NULL) + 60; data.pong_timer = 0;
    CASE("QUIT")    if (!size) msg.params.push_back(data.nickname);
                    disconnect(data, first, 1);
    // end of the cases
    } else {
        std::cout << "Received invalid message from " << data.nickname << " msg=" << msg.command << std::endl;
        RESPOND("", "421", data.nickname, msg.command, "Unknown command")
    }
    return false;
}
message parse(char *data)
{
    message msg;
    char *pointer = data;
    while (*data != '\0')
    {
        if (msg.command.empty())
        {
            if (*data == ':')
            {
                for (; *data != '\0' && *data != ' '; ++data); *data = '\0';
                msg.prefix = pointer + 1;
                pointer = ++data;
            }
            for (; *data != '\0' && *data != ' '; ++data); *data = '\0';
            msg.command = pointer;
            pointer = ++data;
        }
        else if (*data == ':')
        {
            for (; *data != '\0'; ++data);
            msg.params.push_back(pointer+1);
            pointer = ++data;
        }
        else
        {
            for (; *data != '\0' && *data != ' '; ++data); *data = '\0';
            msg.params.push_back(pointer);
            pointer = ++data;
        }
    }
    return msg;
}
int main()
{
    int retval;
    WSADATA wsaData;
    SOCKADDR_IN listen_address; listen_address.sin_family = AF_INET; listen_address.sin_port = htons(6667); listen_address.sin_addr.s_addr = htonl(INADDR_ANY);
    timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 10000;
    fd_set socket_read_set, socket_write_set, socket_except_set;
    socket_data listener; listener.nickname = "IRCd";
    EXIT_IF(1, (0 != WSAStartup(MAKEWORD(2, 2), &wsaData)))
    EXIT_IF(2, (INVALID_SOCKET == (listener.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))))
    EXIT_IF(3, (SOCKET_ERROR == bind(listener.socket, (SOCKADDR *)&listen_address, sizeof(listen_address))))
    EXIT_IF(4, (SOCKET_ERROR == listen(listener.socket, SOMAXCONN)))
    while (1)
    {
        MAKE_SET(socket_read_set) MAKE_SET(socket_write_set) MAKE_SET(socket_except_set)
        EXIT_IF(5, (SOCKET_ERROR == select(0, &socket_read_set, &socket_write_set, &socket_except_set, &timeout)))
        EXIT_IF(6, (FD_ISSET(listener.socket, &socket_except_set)))
        if (FD_ISSET(listener.socket, &socket_read_set))
        {
            socket_data data = {}; // zero everything
            data.address_length = sizeof(data.address);
            data.socket = accept(listener.socket, (SOCKADDR *)&data.address, &data.address_length);
            EXIT_IF(7, (INVALID_SOCKET == data.socket))
            std::stringstream ss; ss << inet_ntoa(data.address.sin_addr) << ":" << ntohs(data.address.sin_port); data.nickname = ss.str();
            data.ping_timer = time(NULL)+60; data.pong_timer = 0;
            socket_list.push_back(data);
            std::cout  << "Connected " << data.nickname << " ping=" << data.ping_timer << std::endl;
        }
        LOOP(socket_list)
        {
            socket_data &data = *it;
            if (data.ping_timer > 0 && time(NULL) > data.ping_timer)
            {
                RESPOND("", "PING", data.nickname)
                data.ping_timer = 0; data.pong_timer = time(NULL) + 60;
                std::cout << "Sent PING to " << data.nickname << " pong=" << data.pong_timer << std::endl;
            }
            if (data.pong_timer > 0 && time(NULL) > data.pong_timer) disconnect(data, "PONG", 1);
            if (FD_ISSET(data.socket, &socket_except_set)) disconnect(data, "select except", 0);
            if (FD_ISSET(data.socket, &socket_read_set))
            {
                int bytes = recv(data.socket, data.read_buffer + data.read_buffer_index, sizeof(data.read_buffer) - data.read_buffer_index - 1 > 0, 0);
                if (bytes > 0) data.read_buffer_index += bytes; else disconnect(data, "recv error", 0);
                char *pointer = data.read_buffer + data.read_buffer_index - 2;
                if (!strcmp(pointer, "\r\n"))
                {
                    *pointer++ = '\0'; *pointer = '\0'; // remove the \r\n
                    message msg = parse(data.read_buffer);
                    memset(data.read_buffer, 0, READ_BUFFER_SIZE); data.read_buffer_index = 0;
                    if (data.ping_timer > 0 && time(NULL) < data.ping_timer)
                    {
                        data.ping_timer = time(NULL) + 60; data.pong_timer = 0;
                        std::cout << "Reset ping for " << data.nickname << " ping=" << data.ping_timer << std::endl;
                    }
                    if (process(data, msg)) EXIT_IF(0, true)
                }
            }
        }
        socket_list.remove_if([](const socket_data& data){ return data.socket == INVALID_SOCKET; });
    }
    retval = 0;
finished:
    LOOP(socket_list) disconnect(*it, "exit", 0);
    disconnect(listener, "exit", 0);
    WSACleanup();
    return retval;
}


Write a Program in Disguise The challenge is to create a program that solves any one of the HQ9+ problems while looking like another language.

Note: This is not a golf challenge.

Rules:

The program must perform one of the following tasks when run.

Print "Hello, World!"
Print its entire source.
Print the lyrics to "99 Bottles of Beer on the Wall" (as seen here).

At first glance the program should look like another language.

Grading

Working program that satisfies the rules. +3
Bonus points if the "other language" can be run (syntax valid). +1
Even more points if the "other language" can do something useful. +3
Lots of bonus points for the program being valid (and useful) in even more languages. +5 for each language over 2.

T-SQL

Print 'Hello, World!' -- she said.

Looks like English.


Garden architecture - ASCII style We have a square 10x10 meter garden outside our house. We want to plant grass and make a terrace. We have decided how to divide the garden, but we haven't decided the ratio between amount of grass vs terrace.

We need help visualizing it, and ASCII-art is clearly the best way to do so.

Challenge:

Take an integer in the inclusive range [0, 100] (or optionally decimal [0, 1]) representing how many percent of the garden should be terrace.

One square meter of terrace will be represented by either a dash - or a bar |. One square meter of grass will be represented by a hash mark #.

If the amount of terrace is less than or equal to 50%, then the garden should be covered with bars, starting in the bottom left corner, and fill vertically, then horizontally.
If the amount of terrace is more than 50% then we want the decking to be the other way (dashes instead of bars), and starting in the bottom left corner, and fill horizontally, then vertically.

Examples:

N = 25%
||########
||########
||########
||########
||########
|||#######
|||#######
|||#######
|||#######
|||#######

N = 75%
##########
##########
-----#####
----------
----------
----------
----------
----------
----------
----------

N = 47%
||||######
||||######
||||######
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####

N = 50%
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####

N = 51%
##########
##########
##########
##########
-#########
----------
----------
----------
----------
----------

N = 0%
##########
##########
##########
##########
##########
##########
##########
##########
##########
##########

N = 100%
----------
----------
----------
----------
----------
----------
----------
----------
----------
----------

This is code-golf so the shortest code in bytes win. Standard rules regarding I/O. This is ASCII-art, so the output should look like the examples above. I.e. outputting ["|", "|" ...] is not OK.

Explanations are encouraged as always :)

APL (Dyalog), 34 bytes

Anonymous prefix function expecting integer in range 0–100. Assumes ⎕IO (Index Origin) to be 0, which is default on many systems.

{'#-|'[⊖⍉⍣s⊢10 10⍴100↑⍵⍴1+s←50≥⍵]}

Try it online!

{…} lambda; ⍵ is argument:

 '#-|[…] index the string with the following array:

 50≥⍵ 1 if 50 is greater than or equal to argument, else 0

 s← store in s (for small)

 1+ increment

 ⍵⍴ cyclically reshape to argument-length

 100↑ take the first hundred of that, padding with zeros

 10 10⍴ reshape to ten rows and ten columns

 ⊢ yield that (separates s from 10 10)

 ⍉⍣s transpose if small

 ⊖ flip upside-down


Google's Hopping Bunny On December 4, 2017, the Google Doodle was a graphical programming game featuring a bunny. The later levels were nicely non-trivial and they seemed like a great candidate for an atomic-golf challenge.

Details

Game

There are four available moves: hop forward, turn left, turn right, and loop. Each of these moves is one token, corresponding to the fact that they are each one tile in the game.
The bunny can face four orthogonal directions (i.e. north, south, east, west).
The bunny can hop forward (move one square in the direction it's facing) and turn left or right.
Loops may have any number of other moves inside them, including other loops, and their iteration count is any positive integer (though the game technically allows an iteration count of 0).
The board is a set of grid-aligned squares and the bunny can hop between adjacent squares.
The bunny cannot hop into the void. Meaning that an attempt to hop off the board does nothing. (This was apparently a surprise for some people and a disappointment for others.)
Squares are either marked or unmarked. When the bunny is on a square, it becomes marked.
The level is complete when all squares are marked.
You may assume a solution exists.

Your code

Objective: given a board, find one or more shortest solutions.
Input is a list of square locations forming the board (distinguishing marked and unmarked squares) and output is a list of moves. Input and output format does not matter at all, so long as they are human-readable and understandable.
Winning criterion: sum of number of moves of shortest solutions found within one minute for each board. If your program does not find a solution for any particular board, your score for that board is (5 * number of squares).
Please do not hardcode solutions in any manner. Your code should be able to take any board as input, not just the ones given as examples below.

Examples

Solutions are hidden in spoilers to give you a chance to play the game first and attempt some of these yourself. Also, only one solution is provided below for each.

S is the bunny's starting square (facing east), # is an unmarked square, and O is a marked square. For moves, my notation is F = hop forward, L = turn left, R = turn right, and LOOP(<num>){<moves>} denotes a loop that iterates <num> times and does <moves> each time. If the loop can run any number of times beyond some minimum number, <num> may be omitted (i.e. infinity works).

Level 1:

S##

   F F

Level 2:

S##
  #
  #

   LOOP(2){F F R}

Level 3:

S##
# #
###

   LOOP{F F R}

Level 4:

###
# #
##S##
  # #
  ###

   LOOP{ F LOOP(7){F L} } (found by DJMcMayhem)

Level 5:

#####
# # #
##S##
# # #
#####

   LOOP(18){ LOOP(10){F R} L}
 Source: Reddit

Level 6:

 ###
#OOO#
#OSO#
#OOO#
 ###

   LOOP{ LOOP(3){F} L }

Huge boards: (shortest solutions currently unknown)

12x12:

S###########
############
############
############
############
############
############
############
############
############
############
############

Level 5 but way bigger:

#############
# # # # # # #
#############
# # # # # # #
#############
# # # # # # #
######S######
# # # # # # #
#############
# # # # # # #
#############
# # # # # # #
#############

More holey boards:

S##########
###########
## ## ## ##
###########
###########
## ## ## ##
###########
###########
## ## ## ##
###########
###########

and

S#########
##########
##  ##  ##
##  ##  ##
##########
##########
##  ##  ##
##  ##  ##
##########
##########

Finally, asymmetry can be a real pain in the butt:

#######
# ##  #
#######
###S###
# ##  #
# ##  #
#######

and

#########
# ##  ###
###S  ###
# #######
###    ##
#####   #
####  ###
#########
#########

Python 3, 67 tokens

import sys
import time

class Bunny():
    def __init__(self):
        self.direction = [0, 1]
        self.coords = [-1, -1]

    def setCoords(self, x, y):
        self.coords = [x, y]

    def rotate(self, dir):
        directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        if dir == 'L':
            self.direction = directions[(directions.index(self.direction) + 1) % 4]
        if dir == 'R':
            self.direction = directions[(directions.index(self.direction) - 1) % 4]

    def hop(self):
        self.coords = self.nextTile()

    # Returns where the bunny is about to jump to
    def nextTile(self):
        return [self.coords[0] + self.direction[0], self.coords[1] + self.direction[1]]

class BoardState():
    def __init__(self, map):
        self.unvisited = 0
        self.map = []

        self.bunny = Bunny()
        self.hopsLeft = 0

        for x, row in enumerate(map):
            newRow = []
            for y, char in enumerate(row):
                if char == '#':
                    newRow.append(1)
                    self.unvisited += 1

                elif char == 'S':
                    newRow.append(2)

                    if -1 in self.bunny.coords:
                        self.bunny.setCoords(x, y)
                    else:
                        print("Multiple starting points found", file=sys.stderr)
                        sys.exit(1)

                elif char == ' ':
                    newRow.append(0)

                elif char == 'O':
                    newRow.append(2)

                else:
                    print("Invalid char in input", file=sys.stderr)
                    sys.exit(1)

            self.map.append(newRow)

        if -1 in self.bunny.coords:
            print("No starting point defined", file=sys.stderr)
            sys.exit(1)

    def finished(self):
        return self.unvisited == 0

    def validCoords(self, x, y):
        return -1 < x < len(self.map) and -1 < y < len(self.map[0])

    def runCom(self, com):
        if self.finished():
            return

        if self.hopsLeft < self.unvisited:
            return

        if com == 'F':
            x, y = self.bunny.nextTile()
            if self.validCoords(x, y) and self.map[x][y] != 0:
                self.bunny.hop()
                self.hopsLeft -= 1

                if (self.map[x][y] == 1):
                    self.unvisited -= 1
                self.map[x][y] = 2

        else:
            self.bunny.rotate(com)

class loop():
    def __init__(self, loops, commands):
        self.loops = loops
        self.commands = [*commands]

    def __str__(self):
        return "loop({}, {})".format(self.loops, list(self.commands))

    def __repr__(self):
        return str(self)

def rejectRedundantCode(code):
    if isSnippetRedundant(code):
        return False

    if type(code[-1]) is str:
        if code[-1] in "LR":
            return False
    else:
        if len(code[-1].commands) == 1:
            print(code)
            if code[-1].commands[-1] in "LR":
                return False

    return True

def isSnippetRedundant(code):
    joined = "".join(str(com) for com in code)

    if any(redCode in joined for redCode in ["FFF", "RL", "LR", "RRR", "LLL"]):
        return True

    for com in code:
        if type(com) is not str:
            if len(com.commands) == 1:
                if com.loops == 2:
                    return True

                if type(com.commands[0]) is not str:
                    return True

                if com.commands[0] in "LR":
                    return True

            if len(com.commands) > 1 and len(set(com.commands)) == 1:
                return True

            if isSnippetRedundant(com.commands):
                return True

    for i in range(len(code)):
        if type(code[i]) is not str and len(code[i].commands) == 1:
            if i > 0 and code[i].commands[0] == code[i-1]:
                return True
            if i < len(code) - 1 and code[i].commands[0] == code[i+1]:
                return True

        if type(code[i]) is not str:
            if i > 0 and type(code[i-1]) is not str and code[i].commands == code[i-1].commands:
                return True
            if i < len(code) - 1 and type(code[i+1]) is not str and code[i].commands == code[i+1].commands:
                return True

            if len(code[i].commands) > 3 and all(type(com) is str for com in code[i].commands):
                return True

    return False

def flatten(code):
    flat = ""
    for com in code:
        if type(com) is str:
            flat += com
        else:
            flat += flatten(com.commands) * com.loops

    return flat

def newGen(n, topLevel = True):
    maxLoops = 9
    minLoops = 2
    if n < 1:
        yield []

    if n == 1:
        yield from [["F"], ["L"], ["R"]]

    elif n == 2:
        yield from [["F", "F"], ["F", "L"], ["F", "R"], ["L", "F"], ["R", "F"]]

    elif n == 3:
        for innerCode in newGen(n - 1, False):
            for loops in range(minLoops, maxLoops):
                if len(innerCode) != 1 and 0 < innerCode.count('F') < 2:
                    yield [loop(loops, innerCode)]

        for com in "FLR":
            for suffix in newGen(n - 2, False):
                for loops in range(minLoops, maxLoops):
                    if com not in suffix:
                        yield [loop(loops, [com])] + suffix

    else:
        for innerCode in newGen(n - 1, False):
            if topLevel:
                yield [loop(17, innerCode)]
            else:
                for loops in range(minLoops, maxLoops):
                    if len(innerCode) > 1:
                        yield [loop(loops, innerCode)]

        for com in "FLR":
            for innerCode in newGen(n - 2, False):
                for loops in range(minLoops, maxLoops):
                    yield [loop(loops, innerCode)] + [com]
                    yield [com] + [loop(loops, innerCode)]

def codeLen(code):
    l = 0
    for com in code:
        l += 1
        if type(com) is not str:
            l += codeLen(com.commands)

    return l

def test(code, board):
    state = BoardState(board)
    state.hopsLeft = flatten(code).count('F')

    for com in code:
        state.runCom(com)

    return state.finished()

def testAll():
    score = 0
    for i, board in enumerate(boards):
        print("\n\nTesting board {}:".format(i + 1))
        #print('\n'.join(board),'\n')
        start = time.time()

        found = False
        tested = set()

        for maxLen in range(1, 12):
            lenCount = 0
            for code in filter(rejectRedundantCode, newGen(maxLen)):
                testCode = flatten(code)
                if testCode in tested:
                    continue

                tested.add(testCode)

                lenCount += 1
                if test(testCode, board):
                    found = True

                    stop = time.time()
                    print("{} token solution found in {} seconds".format(maxLen, stop - start))
                    print(code)
                    score += maxLen
                    break

            if found:
                break

    print("Final Score: {}".format(score))

def testOne(board):
    start = time.time()
    found = False
    tested = set()
    dupes = 0

    for maxLen in range(1, 12):
        lenCount = 0
        for code in filter(rejectRedundantCode, newGen(maxLen)):
            testCode = flatten(code)
            if testCode in tested:
                dupes += 1
                continue

            tested.add(testCode)

            lenCount += 1
            if test(testCode, board):
                found = True
                print(code)
                print("{} dupes found".format(dupes))
                break

        if found:
            break

        print("Length:\t{}\t\tCombinations:\t{}".format(maxLen, lenCount))

    stop = time.time()
    print(stop - start)

#testAll()
testOne(input().split('\n'))

This program will test a single input board, but I find this test driver more useful. It will test every single board at the same time and print how long it took to find that solution. When I run that code on my machine (Intel i7-7700K quad core CPU @ 4.20 GHz, 16.0 GB RAM), I get the following output:

Testing board 1:
2 token solution found in 0.0 seconds
['F', 'F']

Testing board 2:
4 token solution found in 0.0025103092193603516 seconds
[loop(17, [loop(3, ['F']), 'R'])]

Testing board 3:
4 token solution found in 0.0010025501251220703 seconds
[loop(17, [loop(3, ['F']), 'L'])]

Testing board 4:
5 token solution found in 0.012532949447631836 seconds
[loop(17, ['F', loop(7, ['F', 'L'])])]

Testing board 5:
5 token solution found in 0.011022329330444336 seconds
[loop(17, ['F', loop(5, ['F', 'L'])])]

Testing board 6:
4 token solution found in 0.0015044212341308594 seconds
[loop(17, [loop(3, ['F']), 'L'])]

Testing board 7:
8 token solution found in 29.32585096359253 seconds
[loop(17, [loop(4, [loop(5, [loop(6, ['F']), 'L']), 'L']), 'F'])]

Testing board 8:
8 token solution found in 17.202533721923828 seconds
[loop(17, ['F', loop(7, [loop(5, [loop(4, ['F']), 'L']), 'F'])])]

Testing board 9:
6 token solution found in 0.10585856437683105 seconds
[loop(17, [loop(7, [loop(4, ['F']), 'L']), 'F'])]

Testing board 10:
6 token solution found in 0.12129759788513184 seconds
[loop(17, [loop(7, [loop(5, ['F']), 'L']), 'F'])]

Testing board 11:
7 token solution found in 4.331984758377075 seconds
[loop(17, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])]

Testing board 12:
8 token solution found in 58.620323181152344 seconds
[loop(17, [loop(3, ['F', loop(4, [loop(3, ['F']), 'R'])]), 'L'])]

Final Score: 67

This last test just barely squeaks in under the minute restriction.

Background

This was one of the most fun challenges I've ever answered! I had a blast pattern hunting and looking for heuristics to cut down on things.

Generally, here on PPCG I tend to answer relatively easy questions. I'm especially fond of the string tag because it's generally pretty well suited for my languages. One day, about two weeks ago, I was looking through my badges and I realized that I had never gotten the revival badge. So I looked through the unanswered tab to see if anything caught my eye, and I found this question. I decided that I would answer it no matter the cost. It ended up being a bit harder than I thought it would, but I finally got a brute-force answer that I can say I'm proud of. But this challenge is totally out of the norm for me since I don't usually spend more than an hour or so on a single answer. This answer took me a little over 2 weeks and at least 10+ of work to finally get to this stage, though I wasn't keeping careful track.

The first iteration was a pure brute force solution. I used the following code to generate all snippets up to length N:

def generateCodeLenN(n, maxLoopComs, maxLoops, allowRedundant = False):
    if n < 1:
        return []

    if n == 1:
        return [["F"], ["L"], ["R"]]

    results = []

    if 1:
        for com in "FLR":
            for suffix in generateCodeLenN(n - 1, maxLoopComs, maxLoops, allowRedundant):
                if allowRedundant or not isSnippetRedundant([com] + suffix):
                    results.append([com] + suffix)

    for loopCount in range(2, maxLoopComs):
        for loopComs in range(1, n):
            for innerCode in generateCodeLenN(loopComs, maxLoopComs, maxLoops - 1, allowRedundant):
                if not allowRedundant and isSnippetRedundant([loop(loopCount, innerCode)]):
                    continue

                for suffix in generateCodeLenN(n - loopComs - 1, maxLoopComs, maxLoops - 1, allowRedundant):
                    if not allowRedundant and isSnippetRedundant([loop(loopCount, innerCode)] + suffix):
                        continue

                    results.append([loop(loopCount, innerCode)] + suffix)

                if loopComs == n - 1:
                    results.append([loop(loopCount, innerCode)])

    return results

At this point, I was sure that testing every single possible answer would be way too slow, so I used isSnippetRedundant to filter out snippets that could be written with a shorter snippet. For example, I would refuse to yield the snippet ["F", "F", "F"] because the exact same effects could be achieved with [Loop(3, ["F"]), so if it we get to the point where we test length-3 snippets, we know that no length-3 snippet could solve the current board. This used a lot of good mnemonics, but ultimately was waaaay too slow. Testcase 12 took just over 3,000 seconds using this approach. This is clearly significantly too slow. But using this information and a bunch of computer cycles to brute force short solutions to every board, I could find a new pattern. I noticed that almost every solution found would generally look like something like the following:

[<com> loop(n, []) <com>]

nested several layers deep, with the single coms on each side being optional. This means that solutions like:

["F", "F", "R", "F", "F", "L", "R", "F", "L"]

would never appear. In fact, there was never a sequence of more than 3 non-loop tokens. One way to utilize this would be to filter out all of these and not bother to test them. But generating them was still taking a non-negligible amount of time, and filtering through the millions of snippets like this would barely cut time off. Instead I drastically rewrote the code-generator to only generate snippets following this pattern. In pseudo code, the new generator follows this general pattern:

def codeGen(n):
    if n == 1:
        yield each [<com>]

    if n == 2:
        yield each [<com>, <com>]

    if n == 3:
        yield each [loop(n, <com length 2>]
        yield each [loop(n, <com>), <com>]

    else:
        yield each [loop(n, <com length n-1>)]
        yield each [loop(n, <com length n-2>), <com>]
        yield each [<com>, loop(n, <com length n-2>)]

        # Removed later
        # yield each [<com>, loop(n, <com length n-3>), <com>]
        # yield each [<com>, <com>, loop(n, <com length n-3>)]
        # yield each [loop(n, <com length n-3>), <com>, <com>]

This cut the longest test case down to 140 seconds, which is a ridiculous improvement. But from here, there were still some things I needed to improve. I started more aggressively filtering out redundant/worthless code and checking to see if code has been tested before. This cut it down further, but it wasn't enough. In the end, the final piece that was missing was the loop counter. Through my highly advanced algorithm (read: random trial and error) I determined that the optimal range to allow loops to run in is [3-8]. But there's a huge improvement in there: If we know that [loop(8, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])] can't solve our board, then there's absolutely no way that [loop(3, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])] or any loop count from 3-7 could solve it. So rather than iterating through all the loop sizes from 3-8, we set the loop count on the outer loop to the max. This ends up cutting the search space down by a factor of maxLoop - minLoop, or 6 in this case.

This helped a lot, but ended up inflating the score. Certain solutions I had found earlier by brute force require larger loop numbers to run (for example, boards 4 and 6). So rather than setting the outer loop count to 8, we set the outer loop count to 17, a magical number also calculated by my highly advanced algorithm. We know we can do this because increasing the loop count of the outermost loop has no effect on the solution's validity. This step actually reduced our final score by 13. So not a trivial step.


Execute prints backwards Your task is to reverse the order in which some prints get executed.

Specs:
Your code will be in this form:

//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code

You will have to print (or echo, or write, or equivalent) those strings from the fourth to the first.

You decide which lines of your program must print the strings, but they must be adjacent;
Every line can contain only one print, and cannot exceed 60 bytes in length;
Since this is popularity-contest, be creative and avoid to write just a goto or a simple for(i){if(i=4)print"Line1";if(i=3)...}
The most upvoted answer in 2 weeks wins this.
Your output MUST be Line4 Line3 Line2 Line1 OR Line4Line3Line2Line1 OR Line4\nLine3\nLine2\nLine1(where \n is a newline), and it must be generated only by executing those prints backwards.

Happy coding!

UPDATE: Contest is over! Thank you all :)

Commodore 64 BASIC

40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"


Marching Squares Lookup Marching Squares is an algorithm from computer graphics, which is used to recover 2D isocontours from a grid of samples (see also, its big brother Marching Cubes for 3D settings). The idea is to process each cell of the grid independently, and determine the contours passing through that cell based on the values at its corners.

The first step in this process is to determine which edges are connected by contours, based on whether the corners are above or below the value of the contour. For simplicity, we'll only consider contours along the value 0, such that we're interested in whether the corners are positive or negative. There are 24 = 16 cases to distinguish:

Image Source: Wikipedia

The identification of white and black doesn't really matter here, but for definiteness say that white is positive and black is negative. We will ignore cases where one of the corners is exactly 0.

The saddle points (cases 5 and 10) provide a little extra difficulty: it's not clear which diagonals should be used by only looking at the corners. This can be resolved by finding the average of the four corners (i.e. an approximation of the centre value), and choosing the diagonals such that the contours separate the centre from the corners with the opposite sign. If the average is exactly 0, either case can be chosen.

Normally, these 16 cases are simply stored in a lookup table. This is great for efficiency, but of course, we'd prefer the code to be short around here. So your task is to perform this lookup step and print an ASCII representation of the case in as little code as possible.

The Challenge

You're given the values of the four corners (non-zero integers) in a fixed order of your choice. You should then generate the correct layout of the contours, correctly resolving the saddle point cases.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Input may be taken in any convenient string or list format.

The 16 cases will be represented in ASCII art using one of the following 5x5 blocks:

o---o  o---o  o---o
|   |  |   |  | | |
|   |  |---|  | | |
|   |  |   |  | | |
o---o  o---o  o---o

o---o  o---o  o---o  o---o
|/  |  |  \|  |   |  |   |
|   |  |   |  |   |  |   |
|   |  |   |  |\  |  |  /|
o---o  o---o  o---o  o---o

o---o  o---o
|/  |  |  \|
|   |  |   |
|  /|  |\  |
o---o  o---o

You must not print any leading or trailing whitespace, but you may print a single optional newline.

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

Test Cases

The test cases assume that input is given in order top-left, top-right, bottom-left, bottom-right. Test cases are presented in 9 groups, one corresponding to each of the 9 representations given above (in the same order, starting from the empty cell, ending with the two saddle points).

[1, 2, 1, 3]
[-9, -2, -2, -7]

[4, 5, -1, -2]
[-1, -2, 3, 4]

[7, -7, 7, -7]
[-5, 5, -5, 5]

[1, -6, -4, -1]
[-2, 3, 3, 4]

[-1, 6, -4, -1]
[2, -3, 3, 4]

[-1, -6, 4, -1]
[2, 3, -3, 4]

[-1, -6, -4, 1]
[2, 3, 3, -4]

[3, -8, -9, 2]
[-3, 8, 9, -2]

[8, -3, -2, 9]
[-8, 3, 2, -9]

Additionally, the following test cases may return either of the saddle points (your choice):

[1, -4, -2, 5]
[-1, 4, 2, -5]

Ruby, 201 180 176
This is an anonymous lambda function, to be called in the way shown in the ungolfed example.
This contains no variable s. In the ungolfed version a complex expression is assigned to s for clarity, before it is used. 4 bytes are saved in the golfed version by putting it inline. The only other difference between the versions is the whitespace and comments.
If it is acceptable to return the output as an array of five strings of five characters, instead of printing to stdout, one more byte can be saved.
->a{p=t=0
4.times{|i|t+=a[i]*=a[3];p+=a[i]>>9&1<<i}
q=p==6&&t>0?19:'@AC@P*10'[p].ord
puts c='o---o',(0..2).map{|i|b=p*i==3?'|---|':'|   |';b[q%4]='|/|\|/'[q%4+(i&2)];q/=4;b},c}

I'm happy with the parsing of the array, but I think there may be shorter ways to form the output.
All four elements of the input array are multiplied by the last element. This guarantees that the last element is positive, and reduces the number of cases from 16 down to 8. The elements are rightshifted 9 places, so that all positive numbers become 0 and all negative numbers become -1 (at least in the range of input given in the test cases.) They are then ANDed by 1<<array index to give a 3-bit binary number indicating the pattern (actually 4-bit, but as the last element is always positive, the 4th bit is always zero.)
This number from 0..7 is then fed to a (sigh) lookup table to determine which characters of each row are non-whitespace. It is at this stage that the two different displays for the saddle case are handled, with an alternative to the number in the lookup table being used if the total is positive (the question says to consider the "average", but as we are only interested in the sign, it doesn't matter if we consider the total instead.)
The way the display of output works is hopefully clear from the comments in the code.
ungolfed in test program
f=->a{p=t=0
  4.times{|i|                      #for each number in the input
    t+=a[i]*=a[3];                   #multiply each number by a[3]; totalize the sum in t
    p+=a[i]>>9&1<<i                  #shift right to find if negative; AND with 1<<i to build index number for pattern
  }                                #q is a 3-digit base 4 number indicating which character of each line is non-whitespace (if any).
  q=p==6&&t>0?19:'@AC@P*10'[p].ord #It's encoded in the magic string, except for the case of saddles with a positive total, which is encoded by the number 19.
  s=(0..2).map{|i|                 #build an array of 3 strings, indexes 0..2
    b=p*i==3?'|---|':'|   |';        #IF p is 3 and we are on row 1, the string is |---| for the horizontal line case. ELSE it is |   |.
    b[q%4]='|/|\|/'[q%4+(i&2)];      #The numbers in q indicate which character is to be modified. The characters in the string indicate the character to replace with.
    q/=4;                            #If q%4=0, the initial | is replaced by | (no change.) i&2 shifts the string index appropriately for the last row.
    b                                #divide q by 4, and terminate the loop with the expression b so that this is the object loaded into array s.
  }
puts c='o---o',s,c}                #print the array s, capped with "o---o" above and below.

[[1, 2, 1, 3],
[-9, -2, -2, -7],

[4, 5, -1, -2],
[-1, -2, 3, 4],

[7, -7, 7, -7],
[-5, 5, -5, 5],

[1, -6, -4, -1],
[-2, 3, 3, 4],

[-1, 6, -4, -1],
[2, -3, 3, 4],

[-1, -6, 4, -1],
[2, 3, -3, 4],

[-1, -6, -4, 1],
[2, 3, 3, -4],

[3, -8, -9, 2],
[-3, 8, 9, -2],

[8, -3, -2, 9],
[-8, 3, 2, -9],

[1, -4, -2, 5],
[-1, 4, 2, -5]].each{|k|f.call(k)}


Repeating pattern of empty lines Write the shortest program or function that takes some text as input, and outputs either it or an empty line in a repeating pattern:
some text
some text

some text
some text

some text
some text

...

This must continue indefinitely, or until some unpreventable limitation occurs (stack size, memory, etc.). It must be newline separated, and you can assume the inputted text is made up of non-newline printable ASCII characters. Note that it doesn't have to follow the pattern text-text-empty, and text-empty-text would be equally valid.
The ratio of text lines and empty lines will also be specified by input. There are various ways you can do this (though you only need to support one):

A fraction represented as a floating point number (this can represent the fraction which do OR do not have text in them, but it must be consistent)
A ratio of lines with text to lines without (represented as two integer inputs)
A fraction of lines which do OR do not have text in them (represented as an integer numerator and denominator)

Example:
Text: Hello, world!
Ratio: 2:3
Hello, world!
Hello, world!

Hello, world!
Hello, world!

...

Text: fraction
Fraction: 1/3
fraction

fraction

fraction

...

Text: decimal decimal decimal
Input: 0.6
decimal decimal decimal
decimal decimal decimal
decimal decimal decimal

decimal decimal decimal
decimal decimal decimal
decimal decimal decimal

...

Text: example with a different pattern
Fraction: 2/5
example with a different pattern

example with a different pattern

example with a different pattern

example with a different pattern

...

This is code golf, so the shortest answer in bytes, per language, wins.

Pip, 26 12 bytes
T0{LbPaLcPx}

-14 bytes after taking ratio as two arguments.
Explanation:
T0           Till 0 (infinite loop)
  {Lb        Loop b(second argument) number of times
     Pa      Print a(first argument) with newline
       Lc    Loop c(third argument) number of times
         Px} Print x(empty string) with newline

Try it online!


Battle of the Jimmys /o\ Jimmy has been receiving a lot of attention on this site recently and it has caused Jimmy to get a little stressed. The bodybuilder Jimmys /-o-\ started bad mouthing the OG / acrobat /o\ Jimmys saying they are way cooler because they are bigger. But of course the acrobat Jimmys thinks they are way cooler since after all they were the original.

This tension between Jimmys has resulted in somewhat of a Jimmy war, the acrobat Jimmys and the bodybuilder Jimmys are no longer at peace.

Objective

Given a string of acrobat and bodybuilder Jimmys, determine would would win the battle.

The input string will only contain bodybuilder Jimmys /-o-\, acrobat Jimmys /o\ and spaces
The bodybuilder Jimmys are stronger than acrobat Jimmys, so one bodybuilder Jimmy can take down 2 acrobat Jimmys BUT he will be taken down himself after the second Jimmy
/o\ /-o-\     ->  /-o-\

/o\ /o\ /-o-\ ->
The acrobat Jimmys are crafty and are good at surrounding the bodybuilder Jimmys, if 2 acrobat Jimmys surround a bodybuilder Jimmy, the bodybuilder Jimmy will be defeated with no damage to the acrobat Jimmys

/o\ /-o-\ /o\ -> /o\ /o\
The acrobat Jimmys are also faster than the bodybuilder Jimmys so their actions will occur before the bodybuilder Jimmys

/o\ /-o-\ /o\ /-o-\ -> /o\ /o\ /-o-\ ->

Notes

Whitespace between Jimmys will have no affect on the battle, but it can be expected in the input.
Whitespace in the output is acceptable and will be ignored as long as no Jimmys get cut in half
Whitespace will only be spaces, you can assume there will be no tabs or newlines
All Jimmys in the input will be whole, there will be no partial Jimmys /o
The battle will continue until only 1 type of Jimmy (or no Jimmys at all) remain
Both input and output should be in the form of a string
Jimmy actions will occur going left -> right across the field, but acrobat Jimmys have priority to bodybuilder Jimmy
Bodybuilder Jimmys will only go down to two Jimmys if it occurs on the same turn (see last example)

More Examples

/o\ /o\ /-o-\ /-o-\ /o\ /o\     // Input string

/-o-\ /o\ /o\                   // Leftmost bodybuilder took out left two acrobats

                                // Output will be whitespace

-----------------------------------

/o\ /o\ /-o-\ /o\ /-o-\ /o\ /o\  // Input string

/o\ /o\ /o\ /-o-\ /o\ /o\        // acrobat Jimmys got a surround

/o\ /o\ /o\ /o\ /o\              // acrobat Jimmys win

-----------------------------------

/o\ /o\ /-o-\ /o\ /-o-\ /-o-\ /o\ /o\   // Input string

/o\ /o\ /o\ /-o-\ /-o-\ /o\ /o\

/o\ /-o-\ /o\ /o\

/o\ /o\ /o\                             // acrobats win again

-----------------------------------

/o\ /o\ /-o-\ /o\ /-o-\ /-o-\ /o\ /-o-\  // Input string

/o\ /o\ /o\ /-o-\ /-o-\ /o\ /-o-\

/o\ /-o-\ /o\ /-o-\

/o\ /o\ /-o-\

                                        // Output is empty

-----------------------------------

/-o-\ /o\ /o\ /o\ /-o-\ /-o-\           // Input string

/o\ /-o-\ /-o-\

/-o-\ /-o-\                             // Bodybuilder Jimmys win

-----------------------------------

/o\ /-o-\ /-o-\ /o\ /o\ /o\            // Input string

/-o-\ /-o-\ /o\ /o\ /o\                // left most bb jimmy took out leftmost acrobat jimmy

/-o-\ /o\                              // right bb Jimmy took out left two acrobat Jimmys and himself

/-o-\                                  // leftmost jimmy took out a second jimmy but survives because it occurred on a different turn the the first jimmy he took out - bodybuilder Jimmys win

Standard rules apply,
This is code-golf so may the shortest answer win!

Retina 0.8.2, 82 bytes

+1`/-o-./o./o.|(/-o-.)/o.|(/o.(/o.)?)/-o-.(/o.)|/o./o./-o-.|/o.(/-o-.)
$1$2$4$5

Try it online! Link includes test suite. Explanation: The first stage simply deletes whitespace. (The footer spaces the remaining Jimmies back out out.) The second stage then repeatedly replaces the first available match with the captures until no more replacements can be made. The matches are as follows:

/-o-./o./o. Matches a bodybuilder next to two acrobats. There is no capture because this takes out the bodybuilder as well.
(/-o-.)/o. Matches a bodybuilder next to an acrobat. There's no second acrobat here, because it would have matched above, so the lone acrobat is taken out, while the bodybuilder survives.
(/o.(/o.)?)/-o-.(/o.) Matches a bodybuilder between two acrobats, with up to two acrobats to his left. The bodybuilder is taken out.
/o./o./-o-. Matches a bodybuilder with two acrobats to his left (but no acrobats to his right, as that would have already matched). All three are taken out.
/o.(/-o-.) Matches a bodybuilder with one acrobat to his left (but no acrobats to his right, as that would have already matched). The acrobat is taken out.


I programming puzzles, il code golf Background

The Italian definite article (corresponding to English the) has seven different forms: l', il, lo, gli, i, la, le. Which one to use depends on three variables:

Gender: masculine / feminine.
Number: singular / plural.
Initial letter of the subsequent word: vowel / consonant type A / consonant type B.

Vowel is any of these: aeiou.
Consonant type B is any of these cases: s- followed by another consonant, z-, gn-, pn-, ps-, x-, i- followed by vowel (this i acts as a semivowel).
Consonant type A is a consonant that is not type B.

The table shows the article form to be used in each of the twelve combinations of the three above variables. Note that the l' form is attached to the following word with a single quote and without a space.

The challenge

Input a word and one or two strings, numbers or Booleans indicating gender and number. (The initial letters will have to be obtained from the input word).

The input word will be a sequence of lowercase ASCII letters. Accented vowels will be replaced by their non-accented versions (for example, realtà will be input as realta).

The gender and number inputs can be separate numbers, Booleans or strings, or a combined number of string (for example, 1 for masculine singular, 2 for feminine singular, etc).

Any reasonable format and separator can be used, as long as it is specified in the answer.

Output the word preceded by the appropriate form of the article, with space or single quote as needed. The output should also be lowercase. Trailing or leading blank space is allowed.

Code golf, shortest wins.

Test cases

In the following I use the input letters m, f to specify gender, and s, p for number (this is just one possible input format).

Input               Output              Comment

macchina f s        la macchina         Initial letter is cons. A
zio m s             lo zio              Initial letter is cons. B
libri m p           i libri             Initial letter is cons. A
ieri m s            lo ieri             Initial letter is cons. B
aquile f p          le aquile           Initial letter is vowel
spagnoli m p        gli spagnoli        Initial letter is cons. B
golf m s            il golf             Initial letter is cons. A
ombra f s           l'ombra             Initial letter is vowel
impossibili m p     gli impossibili     Initial letter is vowel

Retina, 138 133 129 113 bytes

^.(s[^aeiou]|z|gn|pn|ps|x|i[aeiou])
B$&
^.[aeiou]
V$&
^\d.
A$&
V[02]
l'
A0
il
B0
lo
A1
i
.1
gli
.2
la
.3
le

Test suite.
(prepended %(G`\n to run all test-cases at once)

Input format: macchina f s becomes 2macchina instead.

0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural

Conversion table thanks to Kevin Lau.


Sums of 100 Rolls of Two Six Sided Dice Suppose you have two six-sided dice. Roll the pair 100 times, calculating the sum of each pair. Print out the number of times each sum occurred.
If a sum was never rolled, you must include a zero or some way to identify that that particular sum was never rolled.

Example Output:
[3, 3, 9, 11, 15, 15, 11, 15, 7, 8, 3]

The number of times a sum was rolled is represented in the sums index - 2

In this example, a sum of two was rolled 3 times ([2-2]), a sum of three 3 times ([3-2]), a sum of four 9 times ([4-2]), and so on. It does not matter the individual dice rolls to arrive at a sum (5 and 2 would be counted as the same sum as 6 and 1)

"Ugly" outputs are fine (loads of trailing zeros, extra output, strange ways of representing data, etc.) as long as you explain how the data should be read.

Jelly, 13 12 bytes

³Ḥ6ẋX€+2/ṢŒr

A niladic link. Output format is a list of lists of [value, count].

(Zero rolls means no such entry is present in the output - e.g. an output of[[6, 12], [7, 74], [8, 14]] would identify that only sums of six, seven and eight were rolled.)

Try it online!

How?

³Ḥ6ẋX€+2/ṢŒr - Main link: no arguments
³            - 100
 Ḥ           - double = 200
  6          - 6
   ẋ         - repeat -> [6,6,6...,6], length 200
    X€       - random integer from [1,z] for €ach (where z=6 every time)
       2/    - pairwise reduce with:
      +      -   addition (i.e. add up each two)
         Ṣ   - sort
          Œr - run-length encode (list of [value, length] for each run of equal values)


Is the program 32 or 64 bits? Assignment is simple to explain: write the shortest code you need to determine whether an executable binary program supplied as parameter is 32 or 64 bits.

If there is a different kind of bitness, you can also do for it, but is not mandatory.

What I really don't want is telling me you support other bitnesses and after I get 32 or 64 as a result.

Valid outputs for 32:

32
32bit
32bits
32 bit
32 bits

The same pattern for 64.

No accepted answer.

Jelly on Linux, 6 bytes

5ịO×32

Try it online!

Usage note: the question says "write the shortest code you need to determine whether an executable binary program supplied as parameter", and that's exactly what you need to do here; supply the entire executable binary program as the parameter. Not its filename, the program itself. (I hope you have a fairly understanding shell!) The TIO link uses the shortest known ELF program Linux will run, by Brian Raiter as the example program.

Linux uses ELF as its executable format. It turns out that the fifth byte of an ELF program specifies the processor bitwidth it's designed for: 0x01 for a 32-bit program, or 0x02 for a 64-bit program. So all we have to do is extract the byte in question (5ị), convert it from a character to a number (O), and multiply by 32 (×32).

There's probably a language that can use this exact algorithm more succinctly, but I wanted to post this answer to demonstrate the algorithm.


Maximizing output from minimal input Obviously, code golfing is all about making the most of the least code. Who really cares what the actual output is?

While we have had a challenge for highest input-to-output ratio, this is a call for most finite and deterministic output with given code lengths. Ironically, this challenge is then not code-golf.

Rules:

Write three independent snippets (not full programs/functions).
The snippets must be in the same language.
Score is total number of outputted bytes.
Outputs may be in the form of a result, STDOUT, etc.
The snippets may not cause any error.
The snippets may cause different forms of output.
Trailing newline characters are not counted.
The first snippet must be 1 byte or the minimum length that produces at least 1 byte of output.
The second snippet must be one byte longer than that.
The third snippet must be two bytes longer than the first.


Implement hyperexponentiation/tetration without the use of '^' The Challenge

Implement tetration (aka Power Tower or Hyperexponentiation) with the least amount of characters.

The Conditions

Don't use the 'power' operator or its equivalents (such as pow(x,y), x^y, x**y, etc.)
Input given as: x y (separated by a space)
x is exponentiated by itself y times.
Your method must be able to compute at least 4 3 (4 exponentiated by itself 3 times)

The Scoring

Lowest score wins: (# of characters)
Bonus deduction if you do not use the multiplication operator (-5 points).
No Speed/Memory requirements. Take as long as you want.

Examples

x, 0 -> 1

2, 2 -> 2^2 = 4

2, 4 -> 2^(2^(2^2)) = 65536

4, 3 -> 4^(4^4) = 4^256 = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096

Open to suggestions/alterations/questions

J, score is 7 (12 chars - 5 points for avoiding multiplication)
+/@$/@$~/@$~
usage:
   4 +/@$/@$~/@$~ 3
1.34078e154
t=.+/@$/@$~/@$~  NB. define a function
   4 t 3
1.34078e154
   2 t 2
4

Just few nested folds:

Using multiplication it would be */@$~/@$~
Using power it would be ^/@$~ where $~ creates array, / is a fold function.


Which languages are optimal for problems that require "reading" input while also writing to it like a stack When encountering a problem whose input is meant to be read sequentially, but you may also want to push back onto the input like a stack, which languages have the optimal boilerplates for doing so, and how?
For example, from Create a Boolean Calculator, we have a string like:
1AND0OR1XOR1

We want to "pop" 5 chars 1AND0, compute it to be 0, then "push" it back to form:
0OR1XOR1

Then, repeat until there's only 1 char left. In this case:
0

It's trivial to write while loops and such, but this seems common enough in codegolf problems that there must be canonical forms. I wasn't able to find a tips question specifically about this setup though, and going through each tips question by language was difficult.

The approach you're asking seems like reduce/left fold in general. Many languages have this, such as Python (reduce(f,seq) or functools.reduce(f,seq)), APL (f⍨/⌽seq), Jelly (f/seq), and Haskell (foldl f start seq).
As a Python example, let's assume we already have the input parsed as a list seq=[1, 'AND', 0, 'OR', 1, 'XOR', 1]. Then reduce(f,seq) is equivalent to
f(f(f(f(f(f(1, 'AND'), 0), 'OR'), 1), 'XOR'), 1)

The trouble here is that we need to take 3 arguments at a time. A way this could be done is by grouping most of the sequence into pairs seq2=[1, ['AND',0], ['OR',1], ['XOR',1]], so reduce(f,seq) would be equivalent to
f(f(f(1, ['AND',0]), ['OR',1]), ['XOR',1])

This could work well in Jelly because it has a builtin s that could help split into pairs (output looks funny strings are internally lists of chars).
However, a loop-based approach would work better in Python by assigning to a slice of an array:
seq=[1, 'AND', 0, 'OR', 1, 'XOR', 1]
while len(seq)>1:
  seq[1:3] = [f(*seq[1:3])]
print(seq[0])

This would output f(f(f(1, 'AND', 0), 'OR', 1), 'XOR', 1).
As @AdHocGarfHunter notes in the comments, recursion is a good idea too:
# (ungolfed)
def r(s):
  if len(s)>1:
    return r(f(*s[:3]) + s[3:])
  else:
    return s[0]

APL has little boilerplate for this: {1=⍴⍵:⊃⍵⋄∇(3↓⍵),f3↑⍵} (∇ is the recursion). Jelly does too, with 1 byte recursion.


On the Subject of Wire Sequences This challenge is from a game, Keep Talking And Nobody Explodes.
It's hard to say how this mechanism works. The engineering is pretty impressive, but there must have been an easier way to manage nine wires. — from the manual
Input
Exactly 9 "wires", each which is labeled 'A', 'B', or 'C', and is colored red, blue, or black.
Input format and type doesn't matter, as long as they uniquely identify the wires. In particular, the alphabets can be encoded arbitrarily, so can the colors.
Objective and Output
Output the indices of the wires that needs to be cut. The output format and type doesn't matter either, as long as they uniquely identify the wires to be cut.
Which wire to cut?
If the wire has color \$X\$ and it's the \$N\$th wire of that color that you have seen so far, look at the entry of color \$X\$ on row \$N\$ of the table. If and only if the wire's label is listed on that entry, it is to be cut.
$$
\begin{array}{c|ccc}
           & \text{Red} & \text{Blue} & \text{Black} \\ \hline
\text{1st} & \text{C} & \text{B} & \text{A, B, or C} \\
\text{2nd} & \text{B} & \text{A or C} & \text{A or C} \\
\text{3rd} & \text{A} & \text{B} & \text{B} \\
\text{4th} & \text{A or C} & \text{A} & \text{A or C} \\
\text{5th} & \text{B} & \text{B} & \text{B} \\
\text{6th} & \text{A or C} & \text{B or C} & \text{B or C} \\
\text{7th} & \text{A, B, or C} & \text{C} & \text{A or B} \\
\text{8th} & \text{A or B} & \text{A or C} & \text{C} \\
\text{9th} & \text{B} & \text{A} & \text{C}
\end{array}
$$
Example
Assuming the wires are 1-indexed, and given the following input:
Blue  C
Blue  C
Black C
Black B
Black A
Red   C
Blue  C
Black A
Black A

The 1st wire is the 1st blue wire, which is not connected to B, so leave it.
The 2nd wire is the 2nd blue wire, which is connected to A or C,  so cut it.
The 3rd wire is the 1st black wire, so cut it.
The 4th wire is the 2nd black wire, which is not connected to A nor C, so leave it.
The 5th wire is the 3rd black wire, which is not connected to B, so leave it.
The 6th wire is the 1st red wire, which is connected to C, so cut it.
The 7th wire is the 3rd blue wire, which is not connected to B, so leave it.
The 8th wire is the 4th black wire, which is connected to A or C, so cut it.
The 9th wire is the 5th black wire, which in not connected to B, so leave it.
So the output is [2,3,6,8].

JavaScript (ES6),  75 74  67 bytes
Expects a list of [color, label] pairs, using 0-2 for both. Returns a binary array describing which wires must be cut.
a=>a.map(([c,w])=>(m[c]/=8)>>w&1,m=[334844576,228136272,611931512])

Try it online!
63 bytes
We can save a few bytes by taking A=1, B=2, C=4 and returning a list of zero / non-zero values.
a=>a.map(([c,w])=>w&=m[c]/=8,m=[334844576,228136272,611931512])

Try it online!
How?
Each color is encoded as a bit mask describing the wire labels for the 1st to the 9th appearance.
 #     |  9   8   7   6   5   4   3   2   1  (0)
 Label | CBA CBA CBA CBA CBA CBA CBA CBA CBA ---
-------+-----------------------------------------
 Red   | 010 011 111 101 010 101 001 010 100 000 -> 334844576
 Blue  | 001 101 100 110 010 001 010 101 010 000 -> 228136272
 Black | 100 100 011 110 010 101 010 101 111 000 -> 611931512

Whenever a color appears, we right-shift the corresponding bit mask by 3 positions (by dividing it by 8) and we test the bit 0, 1 or 2 according to the label.


Make an ASCII bat fly around an ASCII moon Background

Here is a Halloween related challenge.

As you may have seen from my last challenge I quite like what I term as ascii art animations, that is not just draw a pattern but draw a pattern that progresses. This idea came to me after I was asked a couple of years ago to liven up a (rather dull) presentation by making random ascii bats fly across the screen on Halloween. Needless to say I duly obliged (I was being paid for it) but it made me think that there is more to life than random bats. Inspired by this I would like to propose this challenge.

Challenge

Make a bat fly around the moon.

Here is a bat:

^o^

Here is the moon:

     mmm
   mmmmmmm
  mmmmmmmmm
   mmmmmmm
     mmm

You must show every stage of the bats flight (see output).

Input

None

Output

      ^o^
      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm^o^
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm
    mmmmmmm^o^
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm^o^
    mmmmmmm
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm^o^
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm^o^

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm
      ^o^

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
   ^o^mmm

      mmm
    mmmmmmm
   mmmmmmmmm
 ^o^mmmmmmm
      mmm

      mmm
    mmmmmmm
^o^mmmmmmmmm
    mmmmmmm
      mmm

      mmm
 ^o^mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

   ^o^mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      ^o^
      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

Rules

No reading from external files or websites
You may submit a full program or a function
Extra spaces and/or newlines are fine by me
Standard loopholes banned as usual
The bat must finish back at the top of the moon
Please feel free to clear the screen between frames if you wish however this is not a requirement. Output as shown above is fine
As this is code golf, the winner will be the answer with the lowest byte count although any answer is welcome

Sample

Reference implementation in totally ungolfed Python 2 (620 bytes but just to prove that it can be done. May golf it later).

b='^o^'
m=['                     ',
'         mmm         ',
'       mmmmmmm       ',
'      mmmmmmmmm      ',
'       mmmmmmm       ',
'         mmm         ',
'                     ']
p=[(9,12),(12,15),(14,17),(15,18),(14,17),(12,15),(9,12),(6,9),(4,7),(3,6),(4,7),(6,9),(9,12)]
d=0
for z in range(7):
    x=map(str,m[z])
    c="".join(x[:p[z][0]]) + b + "".join(x[p[z][1]:])+"\n"
    print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:])
for z in range(6)[::-1]:
    x=map(str,m[z])
    c="".join(x[:p[z+6][0]]) + b + "".join(x[p[z+6][1]:])+"\n"
    print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:])

Result

Although @Jonathan obviously wins on byte count with Jelly, I am going to mark the Brainfuck answer from @Oyarsa as the accepted answer purely because I think that anyone who can actually do something like this in such a crazy language deserves +15 rep no matter how many bytes it takes. This is not because I have any problem with golfing languages. See my answer to a question regarding this on meta if you have any doubts. Many thanks and respect to all who contributed in whatever language.

05AB1E, 69 62 60 bytes

Saved 2 bytes thanks to Adnan.

3ð×…^o^)U13FNV0379730vð5y>;ï-y_+×N(Y-12%_Xè'my×NY-12%_y&XèJ,

Try it online!

Explanation

3ð×…^o^)U stores the list ["   ","^o^"] in X for later use.

13FNV loops over the 13 stages [0 .. 12] and stores the current iteration index in Y.

0379730v loops over the rows of each stage,
where N is the row index and y is the current number of m's.

We start by adding floor(5/(y+1))-(y==0) spaces to each row with ð5y>;ï-y_+×.

We then determine if there should be a bat or 3 spaces before the m's.
If (-N-Y)%12 == 0 is true we add a bat, else 3 spaces.
This expression (N(Y-12%_Xè) will place bats in stages 0,6-12.

Then we place y m's with 'my×.

Now we determine if there should be a bat or 3 spaces after the m's.
The code NY-12%_y&Xè will place a bat if ((N-Y)%12 == 0) and y!=0 is true, else 3 spaces.
This will place the bats on stages 1-5.

Finally we join the whole row into a string and print with a newline: J,.


Tips for golfing in Whispers Whispers is February 2021's Language of the Month, so what tips do you have for golfing in it? Tips do not have to be specific to code-golf, so long as they apply to other types of challenges on the site. Tips should be at least somewhat specific to Whispers (e.g. "remove ignored code" is not an answer). Please post one tip per answer.

Order is important
Swap lines that are referenced more frequently than other lines with less referenced lines that are referenced by a small digit number.
Example:
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> Input
>> #10
>> [10]
>> Output 11 12

The input is referenced twice and the line number is 10. If this line is moved up to line 1. Both 10s are replaced by 1s. In this example 2 bytes were saved.
> Input
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
>> #1
>> [1]
>> Output 11 12

Moving line 11 and 12 up saves another 2 bytes.
> Input
>> #1
>> [1]
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
>> Output 2 3

I wrote a script that takes a Whispers program as input and prints the optimized re-ordered program.
TIO | Github


Merry Golfmas, Everyone! It's Christmas everybody, and here's a code-golf challenge to celebrate. You need to make a program to print out a present. Specifically, the words "Merry Christmas". BUT, there is a catch: this program must only work if it is the 25th of December. If the code is run on any other day, then the program should crash.

This is Code-Golf, so the answer with the least amount of bytes wins.

Merry Christmas!

Pyke, 21 bytes
.dↄґ6C65h*325q/Al

Try it here!
     C65h*        -   multiply the day by the (current month + 1)
          325q    -  ^ == 325
    6         /   - 6 / ^
.dↄґ              -  load "merry christmas"
               Al - ^.capwords()

Or 18 bytes noncompetitive.
.dↄґ6Cs6Y1q/Al

Exactly the same except for this section:
Cs6Y1q
C      -    get_time()
 s6    -   add 1 week
   Y   -  get day of the year
    1q - ^ == 1

Try it here!


Two lasers between two mirrors What if we have a corridor comprised of two parallel mirrors?

|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |

Now, we shine a laser down it...

|  \       |
|   \      |
|    \     |
|     \    |
|      \   |
|       \  |
|        \ |
|         \|
|         /|
|        / |

Oh, look. It bounced, towards the end, there.

What if we draw two lasers BUT going in the opposite direction?

|  \    /  |
|   \  /   |
|    \/    |
|    /\    |
|   /  \   |
|  /    \  |
| /      \ |
|/        \|
|\        /|
| \      / |

Hmm, they didn't seem to meet, there. That's convenient. What happens if both lasers take up the same space?

|  \     / |
|   \   /  |
|    \ /   |
|     X    |
|    / \   |
|   /   \  |
|  /     \ |
| /       \|
|/        /|
|\       / |

I guess that was pretty obvious, huh?

Drawing these diagrams by hand is pretty laborious (trust me on this). Perhaps some code could do it for us?

Write some code to output two parallel mirrors, with two bouncing, intersecting lasers.
Input (all integers):

The width of the corridor
The length of the corridor
Starting position of the right-going laser (zero-indexed, must be less than width)
Starting position of the left-going laser (zero-indexed, must be less than width)

Process

If a laser is right going, it will be drawn one space to the right on the following line.
If a laser is left going, it will be drawn one space to the left on the following line.
If a laser can not take it's sideways step, it will change it's direction, but not it's position.
If both laser are at the same index, print an upper-case X at that index.

Output

A string with multiple lines
Each line starts and ends with a pipe character (|)
Right-going laser are denoted by a back slash (\)
Left-going laser are denoted by a forward slash (/)
The intersection of two lasers is denoted by an upper-case X.

Any language
I'd like to see TIO links
Attempt to fix it in the smallest number of bytes

Test cases

width: 6
length: 10
right-going: 1
left-going: 4

| \  / |
|  \/  |
|  /\  |
| /  \ |
|/    \|
|\    /|
| \  / |
|  \/  |
|  /\  |
| /  \ |

width: 6
length: 10
right-going: 0
left-going: 1

|\/    |
|/\    |
|\ \   |
| \ \  |
|  \ \ |
|   \ \|
|    \/|
|    /\|
|   / /|
|  / / |

width: 4
length: 10
right-going: 2
left-going: 0

|/ \ |
|\  \|
| \ /|
|  X |
| / \|
|/  /|
|\ / |
| X  |
|/ \ |
|\  \|

width: 20
length: 5
right-going: 5
left-going: 15

|     \         /    |
|      \       /     |
|       \     /      |
|        \   /       |
|         \ /        |

width: 5
length: 6
right-going: 2
left-going: 2

|  X  |
| / \ |
|/   \|
|\   /|
| \ / |
|  X  |

width: 1
length: 2
right-going: 0
left-going: 0

|X|
|X|

JavaScript (ES6), 149 bytes
Takes input in currying syntax (w)(h)([a,b]).

w=>h=>g=(p,d=[1,-1],s=Array(w).fill` `)=>h--?`|${p=p.map((x,i)=>~(k=d[i],s[x]='/X\\'[x-p[i^1]?k+1:1],x+=k)&&x<w?x:x+(d[i]=-k)),s.join``}|
`+g(p,d):''

Try it online!
Commented
w => h =>                  // w = width, h = height
  g = (                    // g = recursive function taking:
    p,                     //   p[] = array holding the point coordinates
    d = [1, -1],           //   d[] = directions
    s = Array(w).fill` `   //   s = array of w spaces (we can't use a string because it's
  ) =>                     //       immutable in JS)
    h-- ?                  // if we haven't reached the last row yet:
      `|${                 //   append the left pipe
      p = p.map((x, i) =>  //   for each x at position i in p[]:
        ~(k = d[i],        //     k = direction for this point
          s[x] = '/X\\'[   //     insert either '/', 'X' or '\' at position x in s
            x - p[i ^ 1] ? //     if p[0] != p[1]:
              k + 1        //       use the direction
            :              //     else:
              1            //       force 'X'
          ], x += k        //     add k to x
        ) &&               //     if the result is not equal to -1
        x < w ?            //     and is less than w:
          x                //       use the current value of x
        :                  //     else:
          x + (d[i] = -k)  //       change the direction and restore the initial value of x
      ),                   //   end of map()
      s.join``}|\n` +      //   join and append s; append the right bar and a linefeed
      g(p, d)              //   followed by the result of a recursive call
    :                      // else:
      ''                   //   stop recursion


Tips for golfing in Visual Basic This page is not for Visual Basic .NET Tips or VBA tips
Visual Basic (VB or VB6) is an object-oriented and event-driven dialect of basic that was developed and released by Microsoft in 1991. The last release of Visual Basic came as Visual Basic 6.0 in 1998, and the language was declared a legacy language in 2008. Visual Basic .NET replaced Visual Basic in 2002.
All answers on this site that are written in Visual Basic are assumed to be written for Visual Basic 6.0 unless otherwise stated.

Some helpful links

MSDN Visual Basic 6.0 Resource Center

Visual Basic Wiki

You may compile and execute Visual Basic code using Visual Studio Community.
There is no online resource for compiling VB code.

Use DefXXX statements when declaring multiple variables

The statement
DefDbl A-D

Defines all variables that start with A through D as being of the type Double, which means this can shorten cases such as
Dim A As Double
Dim B As Double
Dim C As Double
Dim D As Double

Similar commands exist for the following types
DefBool     ''  Boolean
DefByte     ''  byte
DefCur      ''  Currency
DefDate     ''  Date
DefDbl      ''  Double
DefDec      ''  Decimal
DefInt      ''  Integer
DefLng      ''  Long
DefObj      ''  Object
DefSng      ''  Single
DefStr      ''  String
DefVar      ''  Variant


Compress a sparse matrix Compress a sparse matrix using Compressed sparse row (CSR, CRS or Yale format).
These are all the same form of compression (ignore new Yale).
Input may be any 2d data structure (list of lists, etc): e.g
[[0 0 0 0],
 [5 8 0 0],
 [0 0 3 0],
 [0 6 0 0]]

And the output should be three 1d data structures (list etc), that denote the outputs A, IA and JA, for example
[5, 8, 3, 6]
[0, 0, 2, 3, 4]
[0, 1, 2, 1,]

The process is described by wikipedia:

The array A is of length NNZ and holds all the nonzero entries of M in
left-to-right top-to-bottom ("row-major") order.

The array IA is of length m + 1. It is defined by this recursive
definition:

IA[0] = 0
IA[i] = IA[i − 1] + (number of nonzero elements on the (i − 1)-th row in the original matrix)

Thus, the first m elements of IA store the index into A of the first
nonzero element in each row of M, and the last element IA[m] stores
NNZ, the number of elements in A, which can be also thought of as the
index in A of first element of a phantom row just beyond the end of
the matrix M. The values of the i-th row of the original matrix is
read from the elements A[IA[i]] to A[IA[i + 1] − 1] (inclusive on both
ends), i.e. from the start of one row to the last index just before
the start of the next.[5]

The third array, JA, contains the column index in M of each element of
A and hence is of length NNZ as well.

If your language doesn't support actual data structures, input and output may be text.
Test cases
Input 1:
[[0 0 0 0],
 [5 8 0 0],
 [0 0 3 0],
 [0 6 0 0]]

Output 1:
[ 5, 8, 3, 6 ]
[ 0, 0, 2, 3, 4 ]
[ 0, 1, 2, 1, ]

Input 2
[[10 20 0 0 0 0],
 [0 30 0 40 0 0],
 [0 0 50 60 70 0],
 [0 0 0 0 0 80]]

Output 2:
[ 10 20 30 40 50 60 70 80 ]
[  0  2  4  7  8 ]
[  0  1  1  3  2  3  4  5 ]

Input 3:
[[0 0 0],
 [0 0 0],
 [0 0 0]]

Output 3:
[ ]
[ 0 0 0 0 ]
[ ]

Input 4:
[[1 1 1],
 [1 1 1],
 [1 1 1]]

Output 4:
[ 1 1 1 1 1 1 1 1 1 ]
[ 0 3 6 9 ]
[ 0 1 2 0 1 2 0 1 2 ]

Input 5:
[[0 0 0 0],
 [5 -9 0 0],
 [0 0 0.3 0],
 [0 -400 0 0]]

Output 5:
[ 5, -9, 0.3, -400 ]
[ 0, 0, 2, 3, 4 ]
[ 0, 1, 2, 1, ]

Assume inputs may contain any real number, you need not consider mathematical symbols or exponential representation (e.g. 5,000 will never be entered as 5e3). You will not need to handle inf, -inf, NaN or any other 'pseudo-numbers'. You may output a different representation of the number (5,000 may be output as 5e3 if you so choose).
Scoring
This is a code-golf, fewest bytes wins.

MATL, 19 bytes

!3#f!Dx0Gg!XsYshDq!

Input uses ; as row separator.

Try it online! Or verify all test cases: 1, 2, 3, 4, 5.

Explanation

!     % Implicit input. Transpose
3#f   % 3-output version of find: it takes all nonzero values and pushes
      % their column indices, row indices, and values, as column vectors
!     % Transpose into a row vector
D     % Display (and pop) vector of values
x     % Delete vector of row values
0     % Push 0
G     % Push input
g     % Convert to logical: nonzeros become 1
!     % Transpose
Xs    % Sum of columns. Gives a row vector
Ys    % Cumulative sum
h     % Prepend the 0 that's below on the stack
D     % Display (and pop) that vector
q     % Subtract 1 from the vector of row indices
!     % Transpose into a row vector. Implicitly display


Can the maze be solved? Task

Print 0 if an n*m maze cannot be solved
Print 1 if an n*m maze can  be solved (in 1 or more ways)

(so I'm not asking for paths but if it's possible to solve!!!)
Example
Input array(2d):
[[0,0,0,0,0,0,1],[0,0,0,0,0,1,0],[0,0,0,0,1,0,0],[1,0,0,0,0,0,0]]

XXXXXXXXX
XS     XX
X     X X
X    X  X
XX     FX
XXXXXXXXX

0 = can pass through
1 = can not pass trough
[0][n] is the last block of the first line
[m][0] is the first block of the last line

Rule
The start position is 0,0 and the end position is n,m
You can only move horizontally and vertically
Shortest code wins

Dyalog APL, 27 characters
⊃⌽∨.∧⍨⍣≡1≥+/¨|∘.-⍨,(~×⍳∘⍴)⎕
⎕ evaluated input.  APL distinguishes between a matrix and a vector of vectors.  This program assumes that the input is a matrix.
(~×⍳∘⍴)A is a fork equivalent to (~A) × ⍳⍴A.  It's needed to avoid mentioning ⎕ twice or introducing a variable.
⍴A is the shape of A.  For a 4-by-7 matrix the shape is 4 7.
⍳ is the index generator.  ⍳4 is 1 2 3 4.  ⍳4 7 is the vectors (1 1)(1 2)...(4 7) arranged in a 4-by-7 matrix.
~A flips the bits of A.
× by multiplying ⍳⍴A by the flipped bits, we preserve the coordinates of all free cells and turn all walls into 0 0.
, ravels the matrix of coordinate pairs, i.e. linearizes it into a vector.  In this case the vector will consist of pairs.
∘.-⍨A or A∘.-A subtracts elements of A pairwise.  Note that here the elements of A are themselves pairs.
| absolute value
+/¨ sum each pair of absolute values.  This gives us the grid distances between every pair of cells in the maze, save for walls.
1≥ we are only intrested in neighbours at a distance no more than 1, this also excludes walls.  Now we have a graph's adjacency matrix.
∨.∧⍨⍣≡ Floyd--Warshall's transitive closure algorithm
(f⍣n)A (not used here) where n is an integer is the power operator.  It applies f to A n times: f f ... f A.
(f⍣g)A where g is a function, is the fixed point operator, a.k.a. "power limit".  It keeps on computing the series A, f A, f f A, ... until ((f⍣i)A) g ((f⍣(i+1))A) returns true for some i.  In this case we use match (≡) as g.
∨.∧⍨A or A∨.∧A is a step in Floyd's algorithm.  f.g is a generalisation of matrix multiplication (+.×), here we use conjunction (∧) and disjunction (∨) in place of + and ×.
⊃⌽  After ⍣≡ has applied the step enough times and reached a stable state, we must look up the top-right corner of the matrix to get the result, so we flip it (⌽) and take the first, top-left item (⊃).
Visualization of ⍣≡'s steps