9 my $dbh = DBI->connect("dbi:Pg:dbname=foosball;host=127.0.0.1", "foosball", "cleanrun", {AutoCommit => 0});
10 $dbh->{RaiseError} = 1;
16 return -round(-$x) if ($x < 0.0);
17 return POSIX::floor($x + 0.5);
20 sub find_single_rating {
21 my ($dbh, $username, $limit) = @_;
22 $limit = "" if (!defined($limit));
23 my ($age, $rating, $rd) = $dbh->selectrow_array('SELECT EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP-ratetime)), rating, rd FROM single_rating WHERE username=? '.$limit.' ORDER BY ratetime DESC LIMIT 1',
25 $rd = apply_aging($rd, $age / 86400.0);
27 if (!defined($rating)) {
32 return ($rating, $rd);
35 sub find_double_rating {
36 my ($dbh, $username, $limit) = @_;
37 $limit = "" if (!defined($limit));
38 my ($age, $rating, $rd) = $dbh->selectrow_array('SELECT EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP-ratetime)), rating, rd FROM double_rating WHERE username=? '.$limit.'ORDER BY ratetime DESC LIMIT 1',
40 $rd = apply_aging($rd, $age / 86400.0);
42 if (!defined($rating)) {
47 return ($rating, $rd);
50 sub create_user_if_not_exists {
51 my ($dbh, $username) = @_;
52 my $count = $dbh->selectrow_array('SELECT count(*) FROM users WHERE username=?',
54 return if ($count > 0);
55 $dbh->do('INSERT INTO users (username) VALUES (?)',
57 $dbh->do('INSERT INTO single_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,1500.0,350.0)',
59 $dbh->do('INSERT INTO double_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,1500.0,350.0)',
64 # c=8 => RD=50 moves to RD=350 over approx. five years
69 $rd = sqrt($rd*$rd + $c * $c * ($age / 86400.0));
70 $rd = 350.0 if ($rd > 350.0);
75 my ($rating1, $rd1, $rating2, $rd2, $score1, $score2) = @_;
76 my $result = `/srv/foosball.sesse.net/foosrank $rating1 $rd1 $rating2 $rd2 $score1 $score2`;
78 my ($newr1, $newrd1) = split / /, $result;
80 $newrd1 = 30.0 if ($newrd1 < 30.0);
82 return ($newr1, $newrd1);
85 sub calc_rating_double {
86 my ($rating1, $rd1, $rating2, $rd2, $rating3, $rd3, $rating4, $rd4, $score1, $score2) = @_;
87 my $result = `/srv/foosball.sesse.net/foosrank $rating1 $rd1 $rating2 $rd2 $rating3 $rd3 $rating4 $rd4 $score1 $score2`;
89 my ($newr1, $newrd1) = split / /, $result;
91 $newrd1 = 30.0 if ($newrd1 < 30.0);
93 return ($newr1, $newrd1);