<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users611</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/611" rel="self"/>
  <title>Chris Jester-Young</title>
  <updated>Sun Oct 17 16:29:40 -0700 2010</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor538200</id>
    <published>2010-10-17T16:29:40-07:00</published>
    <title>[Lisp] On Generalised composition</title>
    <content type="html">&lt;p&gt;Just for fun, I decided to make a pure define-only version, just to be slightly easier on the eyes. :-P Not really a serious entry compared to the above, but you get to see defines nested 4 deep!&lt;/p&gt;

&lt;pre&gt;## Generalised composition, define-only [scheme]
(define (compose . fns)
  (define (make-chain fn chain)
    (define (call-chain . args)
      (define (call) (apply fn args))
      (call-with-values call chain))
    call-chain)
  (reduce make-chain values fns))
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/836-generalised-compose/refactors/538200" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor156039</id>
    <published>2009-04-30T21:40:43-07:00</published>
    <title>[C] On argv iteration</title>
    <content type="html">&lt;p&gt;Your method is mostly good, but, it will fail if your argc is 0 (i.e., argv[0] is null, and other elements after it are invalid). On some operating systems (e.g., Linux), if you call execve with an empty argument array (without even the program name as the 0th argument), this will in fact cause the above-mentioned condition.&lt;/p&gt;

&lt;p&gt;Mind you, I once sent a patch to Boost.Program_options because it didn't catch the argc == 0 case either, so I guess it's not a corner case that many people think about. :-)&lt;/p&gt;

&lt;pre&gt;int
main(int argc, char **argv)
{
    while (--argc &amp;gt;= 0)
        printf(&amp;quot;%s\n&amp;quot;, *++argv);
    return 0;
}
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/853-argv-iteration/refactors/156039" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor155580</id>
    <published>2009-04-23T01:18:28-07:00</published>
    <title>[Java] On Stats</title>
    <content type="html">&lt;p&gt;Seriously, a better solution is to make an enum type containing all the keys (HP, STR, etc), then look each attribute up using an EnumMap.&lt;/p&gt;

&lt;pre&gt;import java.util.EnumMap;
import java.util.Map;

public class Stats {
    public enum Type {
        HP, STR, MAG, SPEED, SKILL, DEF, RES, LUCK, WEIGHT, MOV;
    }

    private Map&amp;lt;Type, Integer&amp;gt; attrs = new EnumMap&amp;lt;Type, Integer&amp;gt;(Type.class);

    public int getStat(Type type) {
        if (attrs.containsKey(type))
            return attrs.get(type);
        throw new IllegalArgumentException(type);
    }

    public int getStat(String type) {
        return getStat(Type.valueOf(type.toUpperCase()));
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/840-stats/refactors/155580" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor155579</id>
    <published>2009-04-23T01:14:32-07:00</published>
    <title>[Java] On Stats</title>
    <content type="html">&lt;p&gt;Use reflection! :-P&lt;/p&gt;

&lt;pre&gt;public int getStat(String stat) {
    try {
        Field field = Stats.class.getField(stat.toUpperCase());
        return field.getInt(this);
    } catch (NoSuchFieldException exc) {
        throw new IllegalArgumentException(exc);
    } catch (IllegalAccessException exc) {
        throw new IllegalArgumentException(exc);
    }
}
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/840-stats/refactors/155579" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor155517</id>
    <published>2009-04-22T05:07:17-07:00</published>
    <title>[Lisp] On Generalised composition</title>
    <content type="html">&lt;p&gt;zbigniew from freenode #scheme suggests that &amp;quot;fold&amp;quot; be replaced with &amp;quot;reduce&amp;quot;; this would then strip out the (redundant) &amp;quot;values&amp;quot; call at the start of the function chain. Thanks!&lt;/p&gt;

&lt;pre&gt;## Generalised composition [scheme]
(define (compose . fns)
  (define (make-chain fn chain)
    (lambda args
      (call-with-values (lambda () (apply fn args)) chain)))
  (reduce make-chain values fns))
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/836-generalised-compose/refactors/155517" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code836</id>
    <published>2009-04-22T04:24:55-07:00</published>
    <updated>2011-07-10T12:49:37-07:00</updated>
    <title>[Lisp] Generalised composition</title>
    <content type="html">&lt;p&gt;Most people have worked with a simple kind of function composition: one that is essentially (lambda (f g) (lambda (x) (f (g x)))). SRFI 41 (&lt;a href="http://srfi.schemers.org/srfi-41/srfi-41.html" target="_blank"&gt;http://srfi.schemers.org/srfi-41/srfi-41.html&lt;/a&gt;) describes a more general composition, that takes an arbitrary number of functions, and that allows each function to return multiple values. Here's my version of the same idea, but using &amp;quot;reduce&amp;quot; from SRFI 1 (&lt;a href="http://srfi.schemers.org/srfi-1/srfi-1.html" target="_blank"&gt;http://srfi.schemers.org/srfi-1/srfi-1.html&lt;/a&gt;), which I think is much cleaner from a functional programming point of view. Feel free to refactor this to make it even more functional. :-)&lt;/p&gt;

&lt;p&gt;(Original version used &amp;quot;fold&amp;quot;; thanks to zbigniew on freenode #scheme for suggesting to use &amp;quot;reduce&amp;quot;, to remove the redundant &amp;quot;values&amp;quot; call; plus, as Riastradh points out, that makes it tail-recursive also.)&lt;/p&gt;

&lt;pre&gt;## Generalised composition [scheme]
(define (compose . fns)
  (define (make-chain fn chain)
    (lambda args
      (call-with-values (lambda () (apply fn args)) chain)))
  (reduce make-chain values fns))
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/836-generalised-compose" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code566</id>
    <published>2008-10-28T11:32:59-07:00</published>
    <updated>2008-10-28T12:44:46-07:00</updated>
    <title>[C] Writing characters to stdout at a specified rate</title>
    <content type="html">&lt;p&gt;See &lt;a href="http://stackoverflow.com/questions/242697/do-stdout-output-with-specific-speed" target="_blank"&gt;http://stackoverflow.com/questions/242697/do-stdout-output-with-specific-speed&lt;/a&gt; for context. The OP has asked me to post my code somewhere public so people can play with it, so here it is. :-)&lt;/p&gt;

&lt;p&gt;My use of sleeptill is designed to get around the problem of &amp;quot;time slippage&amp;quot;, where, because the time to write and do various other calculations is not necessarily trivial, using a simple constant quantity to nanosleep could cause the time to keep drifting out.&lt;/p&gt;

&lt;pre&gt;#include &amp;lt;math.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;time.h&amp;gt;
#include &amp;lt;unistd.h&amp;gt;

int
sleeptill(const struct timespec *when)
{
    struct timespec now, diff;

    clock_gettime(CLOCK_REALTIME, &amp;amp;now);
    diff.tv_sec = when-&amp;gt;tv_sec - now.tv_sec;
    diff.tv_nsec = when-&amp;gt;tv_nsec - now.tv_nsec;
    while (diff.tv_nsec &amp;lt; 0) {
        diff.tv_nsec += 1000000000;
        --diff.tv_sec;
    }
    if (diff.tv_sec &amp;lt; 0)
        return 0;
    return nanosleep(&amp;amp;diff, 0);
}

int
main(int argc, char **argv)
{
    double rate = 0.0;
    char *endp;
    struct timespec start;
    double offset;

    if (argc &amp;gt;= 2) {
        rate = strtod(argv[1], &amp;amp;endp);
        if (endp == argv[1] || *endp)
            rate = 0.0;
        else
            rate = 1 / rate;

        if (!argv[2])
            argv[2] = &amp;quot;.&amp;quot;;
    }

    if (!rate) {
        fprintf(stderr, &amp;quot;usage: %s rate [char]\n&amp;quot;, argv[0]);
        return 1;
    }

    clock_gettime(CLOCK_REALTIME, &amp;amp;start);
    offset = start.tv_nsec / 1000000000.0;

    while (1) {
        struct timespec till = start;
        double frac;
        double whole;

        frac = modf(offset += rate, &amp;amp;whole);
        till.tv_sec += whole;
        till.tv_nsec = frac * 1000000000.0;
        sleeptill(&amp;amp;till);
        write(STDOUT_FILENO, argv[2], 1);
    }
}
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/566-writing-characters-to-stdout-at-a-specified-rate" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor16135</id>
    <published>2008-08-31T22:34:10-07:00</published>
    <title>[C] On Fastest way to get value of pi</title>
    <content type="html">&lt;p&gt;@evilteach: Thanks for that. My question was going for the fastest double-precision method applicable, however, your approach of going for more precision is nice too.&lt;/p&gt;

&lt;p&gt;I noticed that your final answer has a sqrt in it. Do you have an arbitrary-precision sqrt function? Does Erlang provide one, or would you have to do an iterative approximation by hand?&lt;/p&gt;

&lt;p&gt;I've taken the liberty of taking your code and marking it as Erlang, so that the syntax highlighting works better for it. Hope you don't mind! :-)&lt;/p&gt;

&lt;pre&gt;## evilteach's code formatted as Erlang [erlang]
%
%   A simple test program to calculate pi, using an easy, slow converging formula
%

-module(pi).
-export([main/0]).

% The formual we use
% pi^2 = 6*(1/(1^2) + 1/(2^2) + 1/(3^2) ...)




% When we reach the 0th term, we are done.
pi_engine(0, Sum) -&amp;gt; 
    io:format(&amp;quot;~20w ~30.25f ~n&amp;quot;, [0, Sum]),
    io:format(&amp;quot;The value of Pi is about ~30.25f ~n&amp;quot;, [math:sqrt(Sum * 6)]);

% Calculate the Nth term
pi_engine(N, Sum) when N &amp;gt; 0 -&amp;gt; 
    %io:format(&amp;quot;~20w ~30.25f ~n&amp;quot;, [N, Sum]),
    pi_engine(N - 1, Sum + (1 / (N * N)));

pi_engine(N, _Sum) when N &amp;lt; 0 -&amp;gt;
    io:format(&amp;quot;A negative number of terms does not make sense~w ~n&amp;quot;, [N]).


% provide an interface into the engine, as we must pass the sum along in order to 
% be able to accumulate the running total
pi(TermsToCalculate) -&amp;gt; 
    InitialValue = 0.0,
    pi_engine(TermsToCalculate, InitialValue).


main() -&amp;gt;
    io:format(&amp;quot;main begins ~n&amp;quot;, []),

    
    % Decide how many terms should be used for this run
    TermsToCalculate = 100000,
    
    % Perform the calculation, and display the result
    pi(TermsToCalculate),

    io:format(&amp;quot;main ends ~n&amp;quot;, []).
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/405-fastest-way-to-get-value-of-pi/refactors/16135" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code455</id>
    <published>2008-08-22T01:19:59-07:00</published>
    <updated>2008-08-22T01:20:33-07:00</updated>
    <title>[Perl] Bencode decoder</title>
    <content type="html">&lt;p&gt;The BitTorrent .torrent file format uses Bencode, so this program allows you to unpack .torrent files into something more intelligible. Note that the hashes are in binary, so be sure to escape the output before writing it to your terminal!&lt;/p&gt;

&lt;pre&gt;## Bdecode.pm
#!/usr/bin/perl -w
package Bdecode;
use strict;
use Carp;

our %bdecode_funcs = (
    list =&amp;gt; sub {return [bdecode_list($_[0])]},
    dict =&amp;gt; sub {return {bdecode_list($_[0])}},
    int =&amp;gt; sub {return 0 + $_[1]},
    string =&amp;gt; sub {return substr ${$_[0]}, 0, $_[1], ''},
);

# on return, contains unparsed text
sub bdecode(\$) {
    my ($str) = @_;
    my $key =
        $$str =~ /^l/ ? 'list' :
        $$str =~ /^d/ ? 'dict' :
        $$str =~ /^i(0|-?[1-9]\d*)e/ ? 'int' :
        $$str =~ /^(0|[1-9]\d*):/ ? 'string' :
        undef;
    $key or croak 'invalid sequence';
    $$str =~ s///;
    return $bdecode_funcs{$key}-&amp;gt;($str, $+);
}

sub bdecode_list($) {
    my ($str) = @_;
    my @result;
    push @result, bdecode($$str) while $$str !~ /^e/;
    $$str =~ s///;
    return @result;
}

1;
## bdecode
#!/usr/bin/perl -w0777
use strict;
use Bdecode;
use Data::Dumper;

my $input = &amp;lt;STDIN&amp;gt;;
my $obj = Bdecode::bdecode($input);
push @ARGV, '' unless @ARGV;
for my $path (@ARGV) {
    my $cur = $obj;
    for my $item (split '/', $path) {
        my ($name, @indices) = split /:/, $item;
        $name =~ s/%([[:xdigit:]]{2})/chr hex $1/eg;
        $cur = $cur-&amp;gt;{$name} if length $name;
        $cur = $cur-&amp;gt;[$_] for @indices;
    }
    my $dumper = new Data::Dumper([$cur], [$path]);
    print $dumper-&amp;gt;Dump;
}
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/455-bencode-decoder" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code405</id>
    <published>2008-07-30T03:50:29-07:00</published>
    <updated>2010-11-05T03:02:26-07:00</updated>
    <title>[C] Fastest way to get value of pi</title>
    <content type="html">&lt;p&gt;Solutions welcome in any language. :-) I'm looking for the fastest way to obtain the value of pi, as a personal challenge. More specifically I'm using ways that don't involve using #defined constants like M_PI, or hardcoding the number in.&lt;/p&gt;

&lt;p&gt;The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable; I've included it as a baseline to compare the other versions against. In my tests, with builtins, the 4 * atan(1) version is fastest on GCC 4.2, because it auto-folds the atan(1) into a constant. With -fno-builtin specified, the atan2(0, -1) version is fastest.&lt;/p&gt;

&lt;p&gt;Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too, because the optimisations are different), I've also tried switching the order of the tests around. The atan2(0, -1) version still comes out top every time, though.&lt;/p&gt;

&lt;p&gt;I'm keen to hear what results you have, as well as improvements to the testing process. :-)&lt;/p&gt;

&lt;p&gt;ETA: I noticed that the inline assembly was treated as a constant and hoisted out of the loop. Thus, I've included the fldpi in a separate file, so that it gets treated like a function call. As a bonus, now the frame setup times get counted too, just like all the other function calls.&lt;/p&gt;

&lt;pre&gt;## pitimes.c
#include &amp;lt;math.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;time.h&amp;gt;

#define ITERS 10000000
#define TESTWITH(x) {                                                       \
    diff = 0.0;                                                             \
    time1 = clock();                                                        \
    for (i = 0; i &amp;lt; ITERS; ++i)                                             \
        diff += (x) - M_PI;                                                 \
    time2 = clock();                                                        \
    printf(&amp;quot;%s\t=&amp;gt; %e, time =&amp;gt; %f\n&amp;quot;, #x, diff, diffclock(time2, time1));   \
}

static inline double
diffclock(clock_t time1, clock_t time0)
{
    return (double) (time1 - time0) / CLOCKS_PER_SEC;
}

int
main()
{
    int i;
    clock_t time1, time2;
    double diff;

    /* Warmup. The atan2 case catches GCC's atan folding (which would
     * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin
     * is not used. */
    TESTWITH(4 * atan(1))
    TESTWITH(4 * atan2(1, 1))

#if defined(__GNUC__) &amp;amp;&amp;amp; (defined(__i386__) || defined(__amd64__))
    extern double fldpi();
    TESTWITH(fldpi())
#endif

    /* Actual tests start here. */
    TESTWITH(atan2(0, -1))
    TESTWITH(acos(-1))
    TESTWITH(2 * asin(1))
    TESTWITH(4 * atan2(1, 1))
    TESTWITH(4 * atan(1))

    return 0;
}
## fldpi.c
double
fldpi()
{
    double pi;
    asm(&amp;quot;fldpi&amp;quot; : &amp;quot;=t&amp;quot; (pi));
    return pi;
}
## build.sh [shell-unix-generic]
#!/bin/sh
gcc -O3 -Wall -c           -m32 -o fldpi-32.o fldpi.c
gcc -O3 -Wall -c           -m64 -o fldpi-64.o fldpi.c

gcc -O3 -Wall -ffast-math  -m32 -o pitimes1-32 pitimes.c fldpi-32.o
gcc -O3 -Wall              -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -ffast-math  -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall              -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/405-fastest-way-to-get-value-of-pi" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13275</id>
    <published>2008-07-18T01:45:34-07:00</published>
    <title>[C#] On I hate to do this, but...</title>
    <content type="html">&lt;p&gt;@Wolfbyte: Haha, nice. Very enterprisey, probably suitable for the next OMGWTF contest. :-P (That's &lt;a href="http://omg.thedailywtf.com/" target="_blank"&gt;http://omg.thedailywtf.com/&lt;/a&gt; for the lurkers.)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/102-i-hate-to-do-this-but/refactors/13275" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13205</id>
    <published>2008-07-16T10:20:26-07:00</published>
    <title>[C#] On I hate to do this, but...</title>
    <content type="html">&lt;p&gt;Implementation in Perl. :-P&lt;/p&gt;

&lt;p&gt;(Le sigh, some people just have no sense of humour. Marking my submission as spam? You've got to be kidding me, it's a valid FizzBuzz program after all.)&lt;/p&gt;

&lt;pre&gt;## FizzBuzz in Perl [perl]
my %fbmap = (3 =&amp;gt; 'Fizz', 5 =&amp;gt; 'Buzz');
my $fizzbuzz = sub {
    my $num = $_;
    join('', map {$num % $_ ? '' : $fbmap{$_}} keys %fbmap) || $num;
};

print &amp;quot;@{[map &amp;amp;$fizzbuzz, 1..100]}\n&amp;quot;;
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/102-i-hate-to-do-this-but/refactors/13205" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13103</id>
    <published>2008-07-14T21:50:58-07:00</published>
    <title>[PHP] On Adding seconds to a MySQL timestamp</title>
    <content type="html">&lt;p&gt;My fixes below are really tiny things:
&lt;br /&gt;1. Using a bracket expression for matching single characters, rather than using full-blown branches.
&lt;br /&gt;2. Using single quotes where double quotes are unnecessary.
&lt;br /&gt;3. Not doing case-insensitive matching where it doesn't make a difference at all.
&lt;br /&gt;4. Not updating $seconds, but rather passing $seconds + $_amount as an argument to mktime.
&lt;br /&gt;5. Spelling ``list'' correctly in the destructuring assignment. :-P&lt;/p&gt;

&lt;pre&gt;&amp;lt;?php
function addSecondsToTimestamp ($_timestamp, $_amount) {
    list($year, $month, $day, $hours, $minutes, $seconds) = preg_split('/[- :]/', $_timestamp);
    return date('Y-m-d H:i:s', mktime($hours, $minutes, $seconds + $_amount, $month, $day, $year));
}
?&amp;gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/363-adding-seconds-to-a-mysql-timestamp/refactors/13103" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13087</id>
    <published>2008-07-14T11:52:12-07:00</published>
    <title>[C#] On Balance HTML Tags</title>
    <content type="html">&lt;p&gt;@Konrad: on your suggestion of using a Stack, it's impossible to iterate through the stack (looking for the opening tag) without popping all the items in between. If we _do_ find the opening tag, then yes, we do want to pop all the items in between (adding them to the discard list), but if we don't find it, we are supposed to keep the opening tag stack intact, and just place the closing tag in the discard list. RemoveAt is O(1) if the back element is being removed (see the .NET Framework reference source if you want to verify), which Corbin's code does, consistently.&lt;/p&gt;

&lt;p&gt;WRT string searching (this is more a diversion of curiosity than anything else): I'm given to believe that there are some optimised string-searching algorithms out there. The ones I've heard of (Knuth-Morris-Pratt and Boyer-Moore) require pre-studying of the &#226;&#8364;&#339;needle&#226;&#8364;&#157;, and thus isn't suitable for the current application. However, I've also chanced to look at a few different strstr() implementations, to see how they do their stuff:&lt;/p&gt;

&lt;p&gt;1. Find first character of the needle in the haystack (using strchr() or equivalent), then (if found) use the result as a starting point to compare the rest of the needle (using memcmp() or equivalent). If comparison fails, advance the pointer and start again. This approach is used in: String.indexOf() in OpenJDK, strstr() in BSD libc, std::basic_string::find in {GNU libstdc++, STLport, and Microsoft's C++ library}, and (from what I can gather) String.IndexOf() in .NET Framework.&lt;/p&gt;

&lt;p&gt;2. Find the first two characters of the needle in the haystack (using a custom-written loop), then (if found) use the result as a starting point to compare the rest of the needle (again, using a custom-written loop). This approach is used in: strstr() in Microsoft's libc, strstr() in procmail, and strstr() in GNU libc (which uses the procmail implementation).&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/360-balance-html-tags/refactors/13087" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13086</id>
    <published>2008-07-14T10:45:58-07:00</published>
    <title>[C#] On Balance HTML Tags</title>
    <content type="html">&lt;p&gt;Hats off to Corbin for an excellent implementation. I would add a few suggestions: &lt;/p&gt;

&lt;p&gt;1. Because &amp;lt;li&amp;gt;, &amp;lt;p&amp;gt;, and the like are put on the ignore list, people who type in &#226;&#8364;&#339;correct XHTML&#226;&#8364;&#157; with closer tags are going to get those stripped off. This is not strictly a problem, however for people writing lots of list items and/or paragraphs, this search-back through the ignore list is O(n&#194;&#178;) on the number of such closer tags. Although malicious users are going to be able to cause this O(n&#194;&#178;) case no matter what, it'd be nice for the more typical XHTML case to actually not impose that sort of performance penalty. I'll post a possible solution once I come up with one, it's just a thought I have at the moment.&lt;/p&gt;

&lt;p&gt;2. I would suggest downcasing all the incoming tags like Jeff's version does, just to reduce the amount of case-insensitive comparisons that have to be done. If this is not done, then the ignoredtags.Contains() test has to be modified to be a case-insensitive one, too, in order for &amp;lt;P&amp;gt;, &amp;lt;LI&amp;gt;, and the like to work correctly.&lt;/p&gt;

&lt;p&gt;3. (This applies to Jeff's version too.) For consistency, &amp;lt;hr /&amp;gt; should get added to the no-closer-needed list.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/360-balance-html-tags/refactors/13086" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor12752</id>
    <published>2008-07-08T11:36:19-07:00</published>
    <title>[Bash] On store string from terminal into file w/timestamp</title>
    <content type="html">&lt;p&gt;Here's a one-liner (excluding the shell-bang line) for your enjoyment. :-) The main thing is the use of &amp;quot;$*&amp;quot;, which joins all arguments into a single string. The use of printf means you don't have to use &amp;quot;echo -e&amp;quot;, which can help readability.&lt;/p&gt;

&lt;pre&gt;#!/bin/bash
printf '%s\t%s\n' &amp;quot;$(date)&amp;quot; &amp;quot;$*&amp;quot; &amp;gt;&amp;gt; ~/progress/progress.txt&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/354-store-string-from-terminal-into-file-w-timestamp/refactors/12752" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor12167</id>
    <published>2008-06-30T00:08:38-07:00</published>
    <title>[Ruby] On Tracking error in numbers</title>
    <content type="html">&lt;p&gt;I don't know whether your specific problem domain can be solved using interval arithmetic, but if so, a search for &amp;quot;ruby interval arithmetic&amp;quot; came up with &lt;a href="http://intervals.rubyforge.org/" target="_blank"&gt;http://intervals.rubyforge.org/&lt;/a&gt;. Hope it helps. :-)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/342-tracking-error-in-numbers/refactors/12167" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor12162</id>
    <published>2008-06-29T22:23:32-07:00</published>
    <title>[JavaScript] On countdown timer (minutes &amp; seconds) javascript</title>
    <content type="html">&lt;p&gt;@Ryan: Yes, it seems backwards to me---why would a &amp;quot;prototype&amp;quot; function refer to a specific instance of _TDisplay? Is it meant to model the singleton pattern? A not-so-singleton approach would be to assign the closure to &amp;quot;TDisplay.tick&amp;quot;, not &amp;quot;_TDisplay.prototype.tick&amp;quot;. (I can understand the use of &amp;quot;TDisplay._tick.call(TDisplay)&amp;quot;, because the callback from &amp;quot;setInterval&amp;quot; loses the &amp;quot;this&amp;quot; reference.)&lt;/p&gt;

&lt;p&gt;Of course, a not-so-singleton approach would also assign the &amp;quot;tick&amp;quot; property in the constructor, rather than assigning the &amp;quot;tick&amp;quot; property in &amp;quot;global&amp;quot; code. :-) Something like the code box below.&lt;/p&gt;

&lt;p&gt;(ETA: My original version didn't take into account that the &amp;quot;this&amp;quot; reference might not be saved as part of the closure's environment. This will sort that out. Also, calling self._tick() will automatically set the &amp;quot;this&amp;quot; reference correctly, no need to use call().)&lt;/p&gt;

&lt;pre&gt;function _TDisplay() {
    var self = this;
    this.tick = function () {
        self._tick();
    };
}&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/302-countdown-timer-minutes-seconds-javascript/refactors/12162" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor12126</id>
    <published>2008-06-29T09:33:16-07:00</published>
    <title>[Lisp] On Group-by</title>
    <content type="html">&lt;p&gt;The function can be made even shorter by using the cut functionality in SRFI 26. :-)&lt;/p&gt;

&lt;pre&gt;## Even more succinct, with SRFI 1 and SRFI 26 [scheme]
(define (group-by x n)
  (unfold
    (lambda (l) (&amp;lt;= (length l) n))
    (cut take &amp;lt;&amp;gt; n)
    (cut drop &amp;lt;&amp;gt; n) 
    x
    list))&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/193-group-by/refactors/12126" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor11775</id>
    <published>2008-06-25T17:36:50-07:00</published>
    <title>[Lisp] On Group-by</title>
    <content type="html">&lt;p&gt;Here is a demonstration of the kinds of madness one can get up to in the name of &amp;quot;performance&amp;quot;. Of course, I personally prefer the shorter, simpler, and clearer code listed in my previous submission.&lt;/p&gt;

&lt;p&gt;This implementation uses a variant of &amp;quot;split-at!&amp;quot; (returning the results as a dotted pair instead of multiple values, as well as allowing the list to be shorter than the split point). It's faster in two ways: for long lists, because there are no calls to &amp;quot;length&amp;quot;; and for large group size, because the use of &amp;quot;split-at!&amp;quot; (or variant) means only one traversal, rather than one for each of &amp;quot;take&amp;quot; and &amp;quot;drop&amp;quot;. Oh, and it also mutates the incoming list, to avoid making any copies.&lt;/p&gt;

&lt;pre&gt;## This way lies madness [scheme]
(define (split-at-or-earlier! x i)
  (let 
      ((dummy (cons #f x)))
    (let loop
        ((cur dummy) (rem i))
      (if
        (or (zero? rem) (null? (cdr cur)))
        (let 
            ((tail (cdr cur)))
          (set-cdr! cur '())
          (cons (cdr dummy) tail))
        (loop (cdr cur) (- rem 1))))))

(define (group-by x n)
  (let
      ((split! 
        (lambda (l) 
          (split-at-or-earlier! l n))))
    (unfold
      (lambda (p) (null? (car p)))
      car
      (lambda (p) (split! (cdr p)))
      (split! x))))
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/193-group-by/refactors/11775" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor11658</id>
    <published>2008-06-25T01:22:30-07:00</published>
    <title>[C#] On Sanitize HTML</title>
    <content type="html">&lt;p&gt;@Mike: That sounds like a good idea. However, not being a .NET person myself, I can't help but think: surely there is a way to make a reverse iterator from a collection, and be able to use the &amp;quot;for (Type x in foo)&amp;quot;-type loop. e.g., rbegin/rend in the C++ STL, or descendingIterator in the Java Collections Framework. (I've had a cursory look at the .NET Framework documentation and couldn't find anything suitable....)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/333-sanitize-html/refactors/11658" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor11655</id>
    <published>2008-06-25T00:50:42-07:00</published>
    <title>[C#] On Sanitize HTML</title>
    <content type="html">&lt;p&gt;@Rob, @mmp1: (Re use of a DOM)&lt;/p&gt;

&lt;p&gt;Technically, using a DOM is possible. Just not the HTML DOM. You write out a restricted DTD, containing only the elements and attributes you want (start with the XHTML DTD, and strip it down) and ask the XML processing system to validate against that. The restricted DTD can use a root tag of, say, rhtml (&amp;quot;restricted&amp;quot; HTML), and you wrap &amp;lt;rhtml&amp;gt;...&amp;lt;/rhtml&amp;gt; around the string to validate. Then, strip off inappropriate URI schemes (i.e., anything but http/https for images, or http/https/ftp for links) via the DOM, write the tree back out to a string, strip off the rhtml tags, and you're done.&lt;/p&gt;

&lt;p&gt;But, that is a lot of work. Also, it rejects any invalid input, rather than just stripping it off or escaping it, which is what Jeff was going for.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/333-sanitize-html/refactors/11655" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor11653</id>
    <published>2008-06-25T00:41:19-07:00</published>
    <title>[C#] On Sanitize HTML</title>
    <content type="html">&lt;p&gt;@Stefan: The result of cleaning is &amp;lt;p&amp;gt; for the version of the code Jeff last posted. It matches the first-pass regex twice: &amp;lt;p&amp;gt;, and &amp;lt;. The second-pass regex accepts the &amp;lt;p&amp;gt;, but rejects the &amp;lt;.&lt;/p&gt;

&lt;p&gt;Also, there are cases where linking to images is actually quite appropriate, such as showing screenshots. Also, because not every site bans image links, you would have to guard against people putting image links on those sites that point to your webapp anyway. So, your webapp must have the kinds of defences mentioned in my earlier post, no matter what.&lt;/p&gt;

&lt;p&gt;i.e., the server can only &amp;quot;automatically react&amp;quot; for POST requests, and only if the timestamp/hash thing checks out. (Referring to that last post, LiveJournal has even more defences than that...I will have to post a summary of it sometime, once I look at the code further.)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/333-sanitize-html/refactors/11653" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor11584</id>
    <published>2008-06-23T10:59:22-07:00</published>
    <title>[Lisp] On Group-by</title>
    <content type="html">&lt;p&gt;Here's a very cheap answer that uses SRFI 1. :-P&lt;/p&gt;

&lt;p&gt;About the predicate ensuring that the list has more than n elements left:&lt;/p&gt;

&lt;p&gt;1. The &amp;quot;take&amp;quot;/&amp;quot;drop&amp;quot; functions fail if there aren't at least n elements in the list being processed. Unfortunately, all the &amp;quot;length&amp;quot; calls do not make the code particularly fast, especially if the list is long.&lt;/p&gt;

&lt;p&gt;2. It's safe to change the (&amp;lt;= (length l) n) into (&amp;lt; (length l) n), so that the loop continues one last time when (length l) is n. However, the tail-generator code would then append an empty list, which is outside the spec. Solving it in that case would require complicating the tail generator, and I was going for simplest answer here.&lt;/p&gt;

&lt;p&gt;I'll see if I can code up a faster version. But meanwhile, here's a very concise version. :-)&lt;/p&gt;

&lt;pre&gt;## SRFI 1-based implementation [scheme]
;; To activate SRFI 1:
;; MzScheme 372: (require (lib &amp;quot;1.ss&amp;quot; &amp;quot;srfi&amp;quot;))
;; MzScheme 4.0: (require srfi/1)
;; Guile: (use-modules (srfi srfi-1))

(define (group-by x n)
  (unfold
    (lambda (l) (&amp;lt;= (length l) n))
    (lambda (l) (take l n))
    (lambda (l) (drop l n))
    x
    list))
&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/193-group-by/refactors/11584" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor11578</id>
    <published>2008-06-23T09:18:31-07:00</published>
    <title>[Java] On Simple interpreter</title>
    <content type="html">&lt;p&gt;I don't have a code refactoring for you at the moment, however, it looks like you're trying to do your own language parsing, which is not easy to do by hand. A much easier way to do parsing is to use a parser generator, such as JavaCC (&lt;a href="https://javacc.dev.java.net/" target="_blank"&gt;https://javacc.dev.java.net/&lt;/a&gt;), to make a parser for you.&lt;/p&gt;

&lt;p&gt;Given the amount of time you have (surely) spent on it, I would suggest spending just a little more time on how to turn your language into a grammar that JavaCC can use. The JavaCC site has extensive documentation on how you can write this grammar. All the best!&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Chris Jester-Young</name>
      <email>cky944@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/337-simple-interpreter/refactors/11578" rel="alternate"/>
  </entry>
</feed>

