Alright people who know how to tell there computer what to do and how to get there... I bring you a challenge from the interweb.
THE 4K CODE CHALLENGE
Objective: To create the most productive/useful code that as source code is no larger than 4 kilobytes (4096 bytes). There is no restrictions as to what your code does, or what language it is used in.
Rules:
Gentlemen, START YOUR TEXTEDITORS
>>65
shorter:
#!/usr/bin/perl
$a.=(0..9,a..z,A..Z)[rand 62]for(0..9);
die$a
Time for some Perl golf!
#!/usr/bin/perl
die map{(0..9,a..z,A..Z)[rand 62]}(1..10)
Shows how much I know about perl after using it for years. I did not know what map was.
That's the best part about Perl - you NEVER STOP LEARNING IT.
>>68
You should learn a Lisp; there's probably other neat things you don't know, too.
>>70
some of us spend thousands on speech therapy to unlearn our lisps, you insensitive clod
>>71
slashdot memes? In my /code/?
>>73
in your code!
Not even close to 4K, I was just really bored this evening... Too lazy to add command line arguments, however.
import urllib, urllib2, re
def babelfish(langpair, text):
url="http://babelfish.altavista.com/tr?lp="+langpair+"&trtext="+urllib.quote(text.encode('utf-8'))
html = urllib2.urlopen(urllib2.Request(url,None,{'Accept-charset':'utf-8'})).read()
m = re.compile("white class.s..div.style.padding.10px..([^<]*)</div",re.U).search(html)
return m.groups()[0].decode('utf-8').replace(u'\n',u' ')
def log(f, num, text, encoding='utf-8'):
out = (unicode(num)+u': '+text+u"\r\n")
print out.strip().encode('ascii','replace')
f.write(out.encode(encoding))
f.flush()
def mutate(text, steps, langpairs, outfile):
t = unicode(text)
f = open(outfile,"wb")
n = 1
log(f, 0, t)
history = [t]
br = False
while not br:
for lp in langpairs:
t = babelfish(lp, t)
log(f, n, t)
if n==steps: break
n += 1
if t in history:
br = True
break
history.append(t)
if n==steps: break
if br: log(f, n, u"[loop found]")
f.close()
mutate("Hay guys what's going on in this thread?", 20, ['en_ja','ja_en'], "nonsense.txt")
opens a tab with w3m running in the first open konsole and switches to that tab, or starts konsole with w3m if no konsole is running.
first, create ~/.kde/share/apps/konsole/w3m.desktop with the following contents:
[Desktop Entry]
Encoding=UTF-8
Type=KonsoleApplication
Name=w3m
Comment=Web Browser
Exec=w3m -v
Cwd=
then, you can use this perl script:
#!/usr/bin/perl
my $kpid=`dcop|grep konsole`;
$kpid=~s/\n.*//g;
if($kpid eq "")
{
`konsole --type w3m`
}
my $w3msession=`dcop $kpid konsole newSession w3m`;
$w3msession=~s/\n.*//g;
`dcop $kpid konsole activateSession $w3msession`;
hmm, it's difficult for me.
there are many kind of programming language.
so, i don't know how kind do i chose.
r2_jane@yahoo.co.jp
The maximum post size is set too low. I get "Text field too long" even though my whole post is less than 4K.
>>78
Maximum comment size is to 4096 characters exactly. Break it up if you have to.
>>79
Why don't you set it higher, then? What was wrong with 9K?
#!/usr/bin/perl
use CGI;
use CGI::Carp qw(fatalsToBrowser);
my $query=new CGI;
my $task=$query->param("task");
my $text=$query->param("text");
do_post($text) if $text;
unless (-e "index.xhtml") {
build_main_page();
}
print "Status: 303 Go West\n",
"Location: index.xhtml\n",
"Content-type: application/xhtml+xml; charset=utf-8\n\n",
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n",
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd\">\n",
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n",
"<head><title>redirect</title></head><body>\n",
"<p><a href=\"index.xhtml\">go to index.xhtml</a></p></body></html>\n";
sub do_post($) {
$text=shift;
$text=~s/[\x00-\x08\x0b\x0c\x0e-\x1f]//g;
$text=~s/&/&/g;
$text=~s/\</</g;
$text=~s/\>/>/g;
$text=~s/"/"/g;
$text=~s/'/'/g;
$text=~s/,/,/g;
$text=~s/&(\#[0-9]+;)/&$1/g;
$text=~s/&(\#x[0-9a-f]+;)/&$1/gi;
$text=~s/&\#([0-9]+);/$1<=1114111?"&#$1;":""/ge;
$text=~s/&\#x([0-9a-f]+);/hex($1)<=1114111?"&#x$1;":""/gei;
if(length($text)>4096) {
too_long_error();
} else {
my $filename="data/".int(rand(20));
open POSTFILE,">$filename";
print POSTFILE $text;
close POSTFILE;
}
build_main_page();
}
sub too_long_error() {
print "Content-type: application/xhtml+xml; charset=utf-8\n\n",
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n",
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd\">\n",
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n",
"<head><title>error!</title></head>\n<body>\n",
"<p>your text is too long.</p></body></html>\n";
}
sub build_main_page() {
open MAINPAGE,">index.xhtml";
print MAINPAGE "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n",
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd\">\n",
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n",
"<head><title>a web 3.0 page</title></head>\n",
"<body>\n",
"<form action=\"web3.0.pl\" method=\"post\">\n",
"<p><textarea name=\"text\" cols=\"64\" rows=\"10\"></textarea><br/>\n",
"<input type=\"submit\" value=\"submit\" /></p></form>\n";
@posts=glob("data/*");
for(@posts) {
open POSTFILE,"<$_";
read POSTFILE,$text,4096;
close POSTFILE;
print MAINPAGE "<hr><p>$text</p>\n";
}
print MAINPAGE "</body>\n</html>\n";
close MAINPAGE;
}
>>81
oh, the my $task=$query->param("task");
line isn't needed anymore
>>81
Nice, but if you call it .xhtml it'll send as a content-type of application/xhtml+xml, which some browsers don't support. (I'm thinking of Lynx and w3m here, there might be another major browser that doesn't support that content type, but I'm drawing a blank).
>>83
w3m and lynx do support xhtml sent as application/xhtml+xml.
Just tested. Lynx 2.8.5.rel2 and w3m 0.5.1 both offer to save the file. Maybe your server isn't set up to actually send .xhtml as application/xhtml+xml?
>>85
http://web3.hollosite.com/
works in lynx 2.8.5rel.4 and w3m 0.5.1 for me...
http://img122.imageshack.us/my.php?image=lynx0ob.png
http://img118.imageshack.us/my.php?image=w3m5ju.png
>>86
Are you using FreeBSD? It looks like their w3m port has a patch to make this work. I didn't look at Lynx, but I figure either it has a similar patch or it was fixed between 2.8.5rel.2 and 2.8.5rel.4.
Someone should step up to maintain w3m and collect these fixes. Nobody is really maintaining it right now, it seems.
Speaking of XHTML, the <hr>
that script outputs is wrong.
> Speaking of XHTML, the <hr> that script outputs is wrong.
i thought i posted about that when i fixed it on web3.hollosite.com... for anyone who can't figure out how to fix it, just replace it with <hr/>
I've been learning Perl recently, and I made this small program to encrypt/decrypt text and files using one-time pads (more on one-time pads here, if there's interest: http://en.wikipedia.org/wiki/One-time_pad)
Don't expect this code to be very good, but I would love any constructive criticisim (or destructive, whatever)
#!/usr/bin/perl -w
use strict;
=pod
-g output-file num: generates keytext file of length num. makes file of length 1024
if num is omitted.
-e file-to-encrypt output-file a-keyfile : encrypts file-to-encrypt with a-keyfile. if
a-keyfile is omitted, script uses file 'keyfile'.
-d file-to-decrypt output-file a-keyfile : decrypts file-to-decrypt with a-keyfile. if
a-keyfile is omitted, script uses file 'keyfile'.
=cut
if (not @ARGV)
{
print "try supplying some arguments : )\nview the source for a guide.\n";
exit(0);
}
sub rand_char{
return chr(rand 255);
}
sub crypt($$$){
my($arg,$letter,$keyletter)=@_;
return
($arg eq "-e" )?chr(($letter+$keyletter)%255):
($arg eq "-d" )?chr(($letter-$keyletter)%255):
undef;
}
if($ARGV[0] eq '-ga' || $ARGV[0] eq '-g')
{
my $keytext='';
my $length=($ARGV[2])?$ARGV[2]:1024;
$keytext.=rand_char while $length--;
open KEYFILE, ">$ARGV[1]" or die "couldn't open $ARGV[1] for output: $!";
print KEYFILE $keytext;
}
wow, I already fucked that up. here's the bottom half of the code
if($ARGV[0] eq '-e'||$ARGV[0] eq '-ea'||$ARGV[0] eq '-d'||$ARGV[0] eq '-da')
{
open INPUT, "<$ARGV[1]" or die "couldn't open $ARGV[1] for input: $!";
open OUTPUT, ">$ARGV[2]" or die "couldn't open $ARGV[2] for output: $!";
open KEY, ($ARGV[3])?"<$ARGV[3]":"<keyfile";
my @input=split //, join("\n", <INPUT>);
my @key=split //, <KEY>;
foreach (@input)
{
my $letter=ord($_);
my $keyletter=ord(shift @key);
print OUTPUT &crypt($ARGV[0],$letter,$keyletter);
}
close INPUT;
close OUTPUT;
close KEY;
}
Your "one-time pad" is trivially breakable if you generate it like that. Seriously. It is far weaker than even DES. You need a file of real, cryptographic-strength random data, and that's non-trivial to generate.
Also, you're taking a layman's description of one-time pads too literally if you're using + and - to encrypt. Just use a proper XOR and you won't need separate encryption and decryption modes, either.
Also, my @input=split //, join("\n", <INPUT>);
is a bug. You want my @input=split //, join("", <INPUT>);
Cryptographically you're also missing a whole lot of important features, such as a check that you have enough pad to encrypt the whole data, and a method to make sure you never re-use any part of the pad.
.
None of you are expert programmers. I have read the SICP, I know the abstract bullshite. I believe I am the Sussman's love child. Not enough of you are using Lisp (Possibly none of you, I do not check lesser languages on lesser boards). If you all achieved satori, you could become expert programmers like me, and sometimes shaft the paying customers, but have a lot of fun.
I have one word for all of you; the forced indentation of code.
>>94
Fuck off back to /prog/, animal.
I am from /prog/
GREETINS folks ;]
I am from Prague too!
COMRADES, WE SHALL HAVE OUR REVENGE
[code]
#!/usr/bin/perl
use strict;
use warnings;
my $sleep = 2000+int(rand(1500)); #Some days are better for fishing than others
open(FISH, "fish.data") || die("Couldn't open fish.data $!");
my @fish = <FISH>;
my $fish = @fish;
close(FISH);
foreach my $typeOfFish (@fish) {
chomp $typeOfFish;
}
while (1) {
my $thisIsTheFloorGrid = int(rand(80)) +1;
my $typeOfFish = @fish[int(rand($fish))];
system("xmessage A $typeOfFish appears in grid $thisIsTheFloorGrid");
sleep $sleep+int(rand(800));
}
[/code]
http://www.dilbert.com/comics/dilbert/archive/dilbert-20070930.html
I am taking 100GET to tell >>99 to next time read the notice at the top of the board, there is no retarded BBCode here you idiot!
That's great. Carpet fishing.
>>100
Which is very unfortunate. I haven't been able to get my ``EXPERT BBCODE'' fix for a few days.
The averaging solution to Laplace's equation. More specifically, it's a 1000V and a -1000V wire near each other in a conducting pipe and I find the voltage in the pipe. While ago though, I've to look it up to see if that's right. Used symmetry to speed it up. You can change the shape and the wire's voltage and get rid of the symmetry. Graphs the result. It's in Matlab. Am I cool yet?
``
m=201;
n=201;
a = 0.5;
x = 0:1/200:a;
y = 0:1/200:a;
s = zeros(m,n);
[u1,u2] = meshgrid(y.^2,x.^2); % shape
out = find(u1+u2 >= a^2); % points outside the circle
e = 1;
while e<1000,
e = e + 1;
s = ([s(2,:) ; s(1:end-1,:)] ...
+ [s(2:end,:) ; zeros(1,n)] ...
+ [zeros(m,1) s(:,1:end-1)] ...
+ [s(:,2:end) zeros(m,1)])/4; % averaging
s(out) = 0; % outside pipe
s(1,5) = 10; % the 1000V wire
s(:,1) = 0; % y = 0
end
s1 = [flipud(s) ; s(2:end,:)];
s2 = [fliplr(-s1) s1(:,2:end)]; % symmetry across the y-axis
mesh(s2)
``
> what does anon think?Unlike Blum Blum Shub, the algorithm in its native form is not suitable for cryptography.
Monads in Javascript
// Monad stuff
function bindM(m ,k)
{
return function (s) {
tmp = m(s);
a = tmp[0]; s_ = tmp[1];
return k(a)(s_);
}
}
function thenM(m,k) { return bindM(m,function(_){return k;}); }
function returnM(v) { return function (s) { return [v,s]; } }
function evalS(m,s) { return m(s)[0]; }
function getS(s) { return [s,s]; }
function putS(s) { return function(_) { return [null,s]; } }
function doM(m) {
if (arguments.length == 1) return m;
else if (arguments.length % 2 && arguments.length >= 2) {
var rest = Array.prototype.slice.call(arguments).slice(2);
return arguments[1](m, doM.apply(this, rest));
}
else throw ("doM: Error: Arguments mismatch.");
}
function mapM(k,l) {
if (l.length > 0) return doM(
k(l[0])
, bindM
, function (item) { return doM(
mapM(k,l.slice(1))
, bindM
, function (rest) {
if (rest)
return returnM(item.concat(rest));
else
return returnM(item);
}
); }
);
else
return returnM(null);
}
// Parse stuff
function parse(parser, input) { return evalS(parser, input); }
function throwInt(msg,input) {
var e = new Error();
e.message = [msg,input];
e.name = 'PARSE_ERROR'; throw e;
}
/// Combinators
function choice_(m,k) {
return function (s) {
try {
return m(s);
}
catch (e) {
switch (e.name) {
case 'PARSE_ERROR':
if (e.message[1].length != s.length) throw e;
else return k(s);
break;
default:
throw e;
}
}
}
}
function try_(m) {
return function (s) {
try {
return m(s);
}
catch (e) {
switch (e.name) {
case 'PARSE_ERROR':
e.message[1] = s; // Pretend we haven't consumed input
throw e;
break;
default:
throw e;
}
}
}
}
var letter_ = doM(
getS
, bindM
, function (input) {
if (input.length == 0)
return throwInt("Unexpected end of input, expected letter",input);
if (input.match(/^[a-z]/i))
return doM( putS(input.slice(1)) ,thenM, returnM(input[0]) );
else
return throwInt("Expected letter ([a-zA-Z])",input);
}
);
function char_(c) {
return doM(
getS
, bindM
, function (input) {
if (input.length == 0)
return throwInt("Unexpected end of input, expected '" + c + "'",input);
if (input[0] == c)
return doM( putS(input.slice(1)) ,thenM, returnM(c) );
else
return throwInt("Expected character '" + c + "'",input);
}
);
}
function string_(str) {
return mapM(char_,str);
}
// Run a parser
function run(parser,string) {
print("Parse output:");
try {
print(parse(parser,string));
}
catch (e) {
switch (e.name) {
case 'PARSE_ERROR':
print("Parse failed: " + e.message[0] + ", input: " + e.message[1]);
break;
default:
throw e;
}
}
}
// Example parsers
// Parse some parentheses
function parens(s) {
return choice_( doM( char_('(')
, thenM
, parens
, thenM
, char_(')')
, thenM
, parens
)
, returnM(null)
)(s);
}
var testOr = choice_( string_("(a)")
, string_("(b)") );
var testOr1 = doM( char_('(')
, thenM
, choice_( char_('a') , char_('b') )
, thenM
, char_(')')
);
var testOr2 = choice_( try_( string_("(a)") )
, string_("(b)")
);
var testOr3 = choice_( doM( try_( string_("(a") )
, thenM
, char_(')')
, thenM
, returnM("(a)")
)
, string_("(b)")
);
function nesting(s) {
return choice_(
doM(
char_('(')
, thenM
, nesting
, bindM
, function (n) {
return doM(
char_(')')
, thenM
, nesting
, bindM
, function (m) {
return returnM(Math.max(n+1, m));
}
);
})
, returnM(0)
)(s);
}
>>108
Usage: var nestcount = run(nesting,"((()))");
//Coded by drwho
// Knight's Tour program where moves are base on on horizontal and vertical
// arrays and are accessed by a random number generator. This does only 64
// moves but can be increased. the 0 on the board is the night
// I didn't know how to get C to print out both characters and integers
// or else I would have made the knight k (%c didn't work and just displays
// weird shit). Question? I idle in #4-ch on synirc so come by
// http://en.wikipedia.org/wiki/Knight's_tour
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(int argc, char *argv[])
{
int j, currentrow, currentcolumn, lastmover, lastmovec, counta, moves, check;
static movenumber;
int horizontal[8]={2,1,-1,-2,-2,-1,1,2};
int vertical[8]={-1,-2,-2,-1,1,2,2,1};
int board[8][8]={
{2,3,4,4,4,4,3,2},
{3,4,6,6,6,6,4,3},
{4,6,8,8,8,8,6,4},
{4,6,8,8,8,8,6,4},
{4,6,8,8,8,8,6,4},
{4,6,8,8,8,8,6,4},
{3,4,6,6,6,6,4,3},
{2,3,4,4,4,4,3,2}
};
currentrow = 3;
currentcolumn = 3;
board[currentrow][currentcolumn] = 0;
moves = 0;
check = 0;
//time seed
srand ( time(NULL) );
for (counta = 1; counta < 65; counta++){
printf("Knights Round Program\n");
// random move number with time seed
movenumber = rand() % 8;
currentrow += horizontal[movenumber];
currentcolumn += vertical[movenumber];
if(currentrow > 8 || currentrow < 0 || currentcolumn > 8 || currentcolumn < 0){
currentrow = lastmover;
currentcolumn = lastmovec;
}
check = board[currentrow][currentcolumn];
if(check == 0){ board[lastmover][lastmovec]; }
else{board[currentrow][currentcolumn] = 0;}
// The Board
printf("\n");
for(j=0;j<8;j++){printf("%d", board[0][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[1][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[2][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[3][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[4][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[5][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[6][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[7][j]);}
printf("\n");
printf("Row: %d | Column: %d\n", currentrow, currentcolumn);
if(currentrow != lastmover && currentcolumn != lastmovec){moves++;}
lastmover = currentrow;
lastmovec = currentcolumn;
printf("Moves: %d\n", moves);
if(counta == 64){
printf("Knights Round Program\n");
printf("\n");
for(j=0;j<8;j++){printf("%d", board[0][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[1][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[2][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[3][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[4][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[5][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[6][j]);}
printf("\n");
for(j=0;j<8;j++){printf("%d", board[7][j]);}
printf("\n");
printf("Row: %d | Column: %d\n", currentrow, currentcolumn);
printf("Moves: %d\n", moves);
system("PAUSE");
return 0;
}
//Time Delay
sleep(1000);
system("cls");
}
}
//Coded by drwho
// Update: Thanks to a friend from 2600 I was able to shorten the code for the
// chess board. Now that is real hacking!
// Knight's Tour program where moves are base on on horizontal and vertical
// arrays and are accessed by a random number generator. This does only 64
// moves but can be increased. the 0 on the board is the night
// I didn't know how to get C to print out both characters and integers
// or else I would have made the knight k (%c didn't work and just displays
// weird shit). Question? I idle in #4-ch on synirc so come by
// http://en.wikipedia.org/wiki/Knight's_tour
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(int argc, char *argv[])
{
int j, i, currentrow, currentcolumn, lastmover, lastmovec, counta, moves, check;
static movenumber;
int horizontal[8]={2,1,-1,-2,-2,-1,1,2};
int vertical[8]={-1,-2,-2,-1,1,2,2,1};
int board[8][8]={
{2,3,4,4,4,4,3,2},
{3,4,6,6,6,6,4,3},
{4,6,8,8,8,8,6,4},
{4,6,8,8,8,8,6,4},
{4,6,8,8,8,8,6,4},
{4,6,8,8,8,8,6,4},
{3,4,6,6,6,6,4,3},
{2,3,4,4,4,4,3,2}
};
currentrow = 3;
currentcolumn = 3;
board[currentrow][currentcolumn] = 0;
moves = 0;
check = 0;
//time seed
srand ( time(NULL) );
for (counta = 1; counta < 65; counta++){
printf("Knights Round Program\n");
// random move number with time seed
movenumber = rand() % 8;
currentrow += horizontal[movenumber];
currentcolumn += vertical[movenumber];
if(currentrow > 8 || currentrow < 0 || currentcolumn > 8 || currentcolumn < 0){
currentrow = lastmover;
currentcolumn = lastmovec;
}
check = board[currentrow][currentcolumn];
if(check == 0){ board[lastmover][lastmovec]; }
else{board[currentrow][currentcolumn] = 0;}
// The Board
printf("\n");
for(i=0;i<8;i++) { for(j=0;j<8;j++){printf("%d", board[i][j]);} printf("\n"); }
printf("\n");
printf("Row: %d | Column: %d\n", currentrow, currentcolumn);
if(currentrow != lastmover && currentcolumn != lastmovec){moves++;}
lastmover = currentrow;
lastmovec = currentcolumn;
printf("Moves: %d\n", moves);
if(counta == 64){
printf("Knights Round Program\n");
printf("\n");
for(i=0;i<8;i++) { for(j=0;j<8;j++){printf("%d", board[i][j]);} printf("\n"); }
printf("\n");
printf("Row: %d | Column: %d\n", currentrow, currentcolumn);
printf("Moves: %d\n", moves);
system("PAUSE");
return 0;
}
//Time Delay
sleep(1000);
system("cls");
}
}
> #include <windows.h>
http://www.tilander.org/aurora/2008/01/include-windowsh.html
>>1
Why not just implement an interpreter for lisp or something. That's as useful as you can get because you can implement any other program in that.
ok I hav it giv me a sec XDD
[code]
mysqld > /dev/usr/in > out.py
out.py < in.tt > ee.ttt
dc -e "5 6 * + +" > ff.rrrr
cat ee.ttt ff.rrrr > src.c
gcc -Wall -O3 src.c -o exe
[/code]
ders my code XDD u need the /devusr/in file tho XDDD
>source code must be 4 kb
>not the resulting executable
lol cucks.