User:Haxit/Kiloseconds

From ArchWiki
Revision as of 22:38, 23 June 2009 by Mr.Elendig (Talk | contribs) (Python Ncurses: curses.wrapper() instead of the 'manual' terminal setup/restoring)

Jump to: navigation, search

The kiloseconds project is a very sophisticated and exquisite, ego-boosting and mind-blowing (albeit perhaps a bit over-engineered) project which aims to provide its audience with the time in kiloseconds, since we cannot live without it.

Bash

echo "It's $((($(date +%s) - $(date +%s -d $(date +%x)))/1000)) kiloseconds."

Bash (fixed invalid date bug ;)

echo "It's $((($(date +%s) - $(date +%s -d $(LC_ALL="C" date +%x)))/1000)) kiloseconds."

C

#include <stdio.h>
#include <time.h>

int main()
{
     struct tm *t;
     time_t now;
     float ks;
     time(&now);
     t=localtime(&now);
     ks=(t->tm_hour*3600 + t->tm_min*60 + t->tm_sec);
     printf("it is %.2f kiloseconds\n",ks/1000);
     return 0;
}

C++

#include <iostream>
using namespace std;

int main()
{
    time_t now;
    time(&now);
    struct tm *t = localtime(&now);
    float ks = (t->tm_hour*3600 + t->tm_min*60 + t->tm_sec);
    cout << "it is " << ks/1000 << " kiloseconds" << endl;
    return 0;
}

Clojure

(import '(java.util Calendar))

(defn kiloseconds
  "Current time in kiloseconds."
  []
  (let [calendar (Calendar/getInstance)
        hours (. calendar (get Calendar/HOUR_OF_DAY))
        minutes (. calendar (get Calendar/MINUTE))
        seconds (. calendar (get Calendar/SECOND))
        kiloseconds (/ (+ (* hours 3600) (* minutes 60) seconds) 1000)]
    (println (str "Kiloseconds: " (float kiloseconds)))))

;; call it                                                                      
(kiloseconds)

Delphi

program Kiloseconds;

{$APPTYPE CONSOLE}

uses
SysUtils;

var
h,m,s,ms: word;
begin
DecodeTime(now, h, m, s, ms);
Writeln('It is ' + FloatToStrF( (h*3600 + m*60 + s) / 1000, ffNumber, 7, 2) + ' kiloseconds.');
end.

Eiffel

class
	APPLICATION

inherit
	ARGUMENTS

create
	make

feature {NONE} -- Initialization

	make
			-- Run application.
		local
			time: TIME
			kilo_seconds: INTEGER
		do
			create time.make_now
			kilo_seconds := ((time.hour * 3600 + time.minute * 60 + time.second) / 1000).floor
			io.put_integer (kilo_seconds)
			io.new_line
		end

end

Emacs Lisp

(require 'cl)

(defun ks-from-time (seconds minutes hours)
  (/ (+ seconds (* minutes 60) (* hours 3600))1000.0))

(defun ks-time ()
  (interactive)
  (message "It's %.3f ks" (apply 'ks-from-time (subseq (decode-time) 0 3))))

(defun erc-cmd-KS ()
  (erc-send-message
   (format "It's %.3f ks" (apply 'ks-from-time (subseq (decode-time) 0 3)))))

Erlang

-module(kiloseconds).
-export([kilotime/0]).
kilotime() ->
{Hour,Minutes,Seconds} = erlang:time(),
io:format("It is ~w kiloseconds ~n", [(Hour * 3600 + Minutes * 60 + Seconds)/1000]).

Factor

USING: accessors calendar kernel math prettyprint ;
IN: kiloseconds

: kiloseconds ( -- n )
    now [ hour>> 3600 * ] [ minute>> 60 * ]
    [ second>> ] tri + + 1000 /i ;

: main ( -- )
    kiloseconds . ;

MAIN: main

Haskell

import Data.Time

diffTimeToKiloSeconds diffTime = (fromRational $ toRational diffTime) / 1000
secondsSinceMidnight = timeOfDayToTime . localTimeOfDay . zonedTimeToLocalTime
kiloSecondsSinceMidnight = diffTimeToKiloSeconds . secondsSinceMidnight

main = do localTime <- getZonedTime
          putStrLn $ "It's "
                     ++ show (kiloSecondsSinceMidnight localTime)
                     ++ " kiloseconds"

A version with fixed-width decimal output:

import Data.Time

getS = timeOfDayToTime . localTimeOfDay . zonedTimeToLocalTime
getKS s = (fromRational $ toRational s) / 1000
formatKS n ks = let (b,a) = properFraction ks
                    c     = round $ a * 10^n
               in show(b) ++ "." ++ show(c)
ks = formatKS 2 . getKS . getS

main = do
  c <- getZonedTime
  putStrLn ("Current time: " ++ (ks c) ++ " kiloseconds")

What about printf "%.2f" value?

Java

import java.util.GregorianCalendar;

public class Kiloseconds {

	public static void main(String[] args) {
		
		GregorianCalendar calendar = new GregorianCalendar();
		int hours, minutes, seconds, kiloseconds;
		
		hours = calendar.get(GregorianCalendar.HOUR_OF_DAY);
		minutes = calendar.get(GregorianCalendar.MINUTE);
		seconds = calendar.get(GregorianCalendar.SECOND);
		kiloseconds = (hours*3600 + minutes*60 + seconds) / 1000;
		System.out.println(kiloseconds + "\n");

	}

}

Javascript

ourDate = new Date();
metricTime =  (ourDate.getHours() * 3600 + ourDate.getMinutes() * 60 + ourDate.getSeconds());
document.write("It is: " + metricTime / 1000 + " kiloseconds.");

Lisp

(multiple-value-bind (seconds minutes hours)
   (get-decoded-time)
 (print (/ (+ seconds
              (* minutes 60)
              (* hours 3600))
           1000.0)))

LOLCODE (LOLPython)

LOLPython here

IN MAI time GIMME localtime LIKE NOW
TODAYS CAN HAZ NOW THING

KILOSECONDS CAN HAZ EASTERBUNNY
PILE CAN HAZ CHEEZBURGER

KILOSECONDS GETZ ANOTHR 3600 OF THOSE TODAYS OWN tm_hour
KILOSECONDS GETZ ANOTHR 60 OF THOSE TODAYS OWN tm_min
KILOSECONDS GETZ ANOTHR PILE OF THOSE TODAYS OWN tm_sec

VISIBLE "OMG IT'S" AND KILOSECONDS SMASHES INTO 1000.0 AND "KILOSECONDS"

Lua

This version displays the time once

print("It is ", (os.date("%H")*3600 + os.date("%M")*60 + os.date("%S"))/1000, " kiloseconds")

Time is updated once per second

while true do
  io.write("\rIt is ", (os.date("%H")*3600 + os.date("%M")*60 + os.date("%S"))/1000, " kiloseconds")
  io.stdout:flush()
  os.execute("sleep 0.7")
end

Mathematica

Drop[DateList[],3].{3600,60,1}/1000

MatLab

function ks = kiloseconds();
% make a clock
c = clock;
% get hour
hour = c(4);
% get minutes 
min = c(5);
% get seconds
sec = c(6);
ks = (hour * (min*60) * sec)/ 1000;

Perl

#!/usr/bin/perl
($s,$m,$h) = localtime();
printf "Current time: %.3f kiloseconds", ($h*3600+$m*60+$s)/1000;

PHP

<?php
$t = localtime(time(), true);
$ks = $t['tm_hour']*3600 + $t['tm_min']*60 + $t['tm_sec'];
fwrite(STDOUT, "It's " . $ks/1000 . " kiloseconds\n");
?>

PLT Scheme

(let* ([date-struct (seconds->date (current-seconds))]
       [seconds (date-second date-struct)]
       [minutes (date-minute date-struct)]
       [hours (date-hour date-struct)])
 (display (/ (+ seconds
                (* minutes 60)
                (* hours 3600))
             1000.0)))

Prolog (SWI-Prolog)

#!/usr/bin/env swipl -g kiloseconds -s
kiloseconds :- 
    get_time(T), 
    stamp_date_time(T,date(_,_,_,H,M,S,_,_,_),'local'), 
    format('It is: ~f kiloseconds.~n',[(H*3600+M*60+S)/1000]).

Python

import time
tm = time.localtime()
print (tm.tm_hour*3600+tm.tm_min*60+tm.tm_sec)/1000.0, "kiloseconds"

Python Ncurses

Very messy, second version, kinda ugly. You have been warned

#!/usr/bin/env python

import curses
import traceback
import time

DIGIT_WIDTH = 5
DIGIT_HEIGHT = 5
DIGIT_SPACING = 2
POINT_SPACING = 0
POINT_WIDTH = 5

'''
_0_0_._0_0_0_
'''

width = 5*DIGIT_SPACING + 5*DIGIT_WIDTH + 2*POINT_SPACING + POINT_WIDTH
height = 2*DIGIT_SPACING + DIGIT_HEIGHT


# numbers, list of coords in (y,x)

digits = [
    [
        "#####",
        "#   #",
        "#   #",
        "#   #",
        "#####"
        ],
    [
        "  #",
        " ##",
        "  #",
        "  #",
        " ###",
        ],
    [
        "#####",
        "    #",
        "#####",
        "#",
        "#####",
        ],
    [
        "#####",
        "    #",
        " ####",
        "    #",
        "#####",
        ],
    [
        "#   #",
        "#   #",
        "#####",
        "    #",
        "    #",
        ],
    [
        "#####",
        "#",
        "#####",
        "    #",
        "#####",
        ],
    [
        "#####",
        "#",
        "#####",
        "#   #",
        "#####",
        ],
    [
        "#####",
        "    #",
        "    #",
        "    #",
        "    #",
        ],
    [
        "#####",
        "#   #",
        "#####",
        "#   #",
        "#####",
        ],
    [
        "#####",
        "#   #",
        "#####",
        "    #",
        "    #",
        ],
    [
        "",
        "",
        "",
        " ###",
        " ###",
        ],
    ]

def draw_digit(win, digit, y, x):
    sections = digits[digit]
    position = 0
    for section in sections:
        win.addstr(position+y, x, section)
        position += 1

def draw_time(win, digits):
    x_pos = DIGIT_SPACING
    y_pos = 1
    digits.insert(2, 10) #add in the point
    for d in digits:
        draw_digit(win, d, y_pos, x_pos)
        x_pos += (DIGIT_SPACING + DIGIT_WIDTH)

def tick(win):
    tm = time.localtime()
    t = ks = tm.tm_hour*3600 + tm.tm_min*60 + tm.tm_sec
    a = ks/10000; ks -= a*10000
    b = ks/1000; ks -= b*1000
    c = ks/100; ks -= c*100
    d = ks/10; ks -= d*10
    e = ks
    draw_time(win, [a,b,c,d,e])
    return t

def main(screen):
    draw_time(screen, [0,1,2,1,2])
    t = None
    screen.hline(0,0,curses.ACS_BULLET, width)
    while True:
        screen.clear()
        newtime = tick(screen)
        if t != newtime:
            screen.refresh()
        t = newtime
        time.sleep(0.5)

if __name__ == '__main__':
    curses.wrapper(main)

Ruby

puts((Time.now.sec + Time.now.min*60 + Time.now.hour*3600) / 1000.0)

Scala

Could be done shorter, but this demonstrates some nice Scala features.

import java.util.Calendar

object Kilosecond {
    private implicit def enrichCalendar(c: Calendar) = new CalendarWrapper(c)

    def main(args: Array[String]) = {
        val c = Calendar.getInstance

        println("Kiloseconds: " + c.kiloseconds)
    }

    private class CalendarWrapper(c: Calendar) {
        def kiloseconds = {
            val hours = c.get(Calendar.HOUR_OF_DAY)
            val minutes = c.get(Calendar.MINUTE)
            val seconds = c.get(Calendar.SECOND)

            (hours * 3600 + minutes * 60 + seconds) / 1000.0
        }
    }
}

Smalltalk

'It is ', (Time now asSeconds/1000.000) printString, ' kiloseconds'

TCL

puts "It's [expr [clock format [clock seconds] -format {(%k*3600+%M.0*60+%S.0)/1000}]] kiloseconds"

Weechat Plugin

Requires weechat version 0.3.0+

kiloseconds.py

IRSSI Plugin

#!/usr/bin/perl

use vars qw($VERSION %IRSSI);
use Irssi;
use strict;
$VERSION = '0.10';
%IRSSI = (
   authors	=> 'Ben Duffield',
   contact	=> 'jebavarde AT gmail DOT com',
   name	=> 'kiloseconds',
   description	=> 'Reports the time in kiloseconds',
   license	=> 'GPL',
   url		=> 'http://wiki.archlinux.org/index.php/Kiloseconds',
   changed	=> 'no idea',
); 
 

sub cmd_kiloseconds {
    my ($data, $server, $witem) = @_;
    my $output;
    my $ks;
    my $s;
    my $m; 
    my $h;

    ($s,$m,$h) = localtime();
    $ks = ($h*3600+$m*60+$s)/1000; 

    $output = sprintf("Current time: %.3f  kiloseconds", $ks);
 

    if ($output) {
	if ($witem && ($witem->{type} eq "CHANNEL" || $witem->{type} eq "QUERY")) {
	    $witem->command("MSG ".$witem->{name}." $output");
	}
	else {
	    Irssi::print("This is not a channel/query window :b");
	}
    }
}

Irssi::command_bind('kiloseconds', 'cmd_kiloseconds');

Oracle SQL

select ((to_char(sysdate,'HH')*60*60)+(to_char(sysdate,'MM')*60)+(to_char(sysdate,'SS')))/1000 
as "Kiloseconds" from dual