2011-12-20

bash: adding or subtracting days from a date

I had this problem at my workplace. As I crawled through the web I saw that this is a very common question and rookies are directed to a forum at www.unix.com where someone reimplemented the World (many calendar functions) in bash. His solution is a very long and complicated lib which is an overkill for this kind of tiny task we have at hand.

My solution

t_days=30            # I needed stuff from a this long period,
t_reftime=2011-11-14 # just before this date

# 1st: Translate the reference time to UNIX timestamp:
ts=`date --utc -d "$t_reftime" +%s`
# 2nd: Convert 30 days to seconds, subtract it from the above
# and add it to the UNIX epoch. Format as you like. I liked %Y-%m-%d
sdate=`date --utc -d "1970-01-01 $((ts-t_days*86400)) sec" +%Y-%m-%d`
# $sdate is now "2011-10-15"

2011-11-14

C++: Return type of assignment operator

I had a confusion about whether to return with constant reference or non-constant reference from operator=. It seemed clever and practical to return T const&, because of the following faulty reasoning:

T a,b;
a = b = T(100,200,"something");

The fully bracketed form of the second line is:

a = (b = T(100,200,"something"));

So if we return T const& from T::operator=(T const& rhs) it is sufficient for that purpose. And also when we accidentally write something silly like (a = b) = T(100,200,"something") it will help us by giving a compile error.

Reasoning for non-constant return

The nice argument is that there are useful cases when we do want to modify the result of an assignment, for example:

T a,b,c;
// ...
std::swap(a=b,c); // #1
(b=c).Transponate(); // #2
// ...

The strong argument is that many STL containers require their type parameter(s) to fulfill the Assignable[1] concept, which defines assignment operator to return non-constant reference.

2011-09-23

Ruby, oh my increment...

Quote from ruby-doc.org:

9. Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1. (An explanation for this language design by the author of Ruby can be found at http://www.ruby-talk.org/2710.)

And you are eager to know an explanation for that decision, and you click and you get:

The domain ruby-talk.org may be for sale. Click here for details.

I have been convinced as of now that Ruby is a really good programming language for university studies, but it is yet to become an applicable language in the industry. Will it ever reach that seriousness? It has been infant for a long time and haven't yet reached that level...

2011-08-04

Ruby true or false

The test

def true?(x)
    if x
        return "true"
    else
        return "false"
    end
end

tests = [false,true,0,1,nil,[],{},"","0","1","true","false"]

tests.each do |test|
    puts test.inspect+":\t "+true?(test)+" ("+test.class.to_s+")"
end

The results

false:   false (FalseClass)
true:    true (TrueClass)
0:       true (Fixnum)
1:       true (Fixnum)
nil:     false (NilClass)
[]:      true (Array)
{}:      true (Hash)
"":      true (String)
"0":     true (String)
"1":     true (String)
"true":  true (String)
"false":         true (String)

For later reference.

2011-08-02

Álmaid nője 1 perce halott / The woman of your dreams died a minute ago

English version follows


A mindenki.hu egy olyan szájt, ahol az emberek feltehetnek és megválaszolhatnak személyes preferenciákra vonatkozó kérdéseket, majd aztán megkereshetik hogy ki mennyire hasonlít hozzájuk vagy különbözik tőlük.

Volt ott egy kérdés: Lefeküdnél álmaid nőjével, úgy hogy már 1 perce halott?

  • A: persze, ha adódik egy alkalom, akkor nem szabad kihagyni.
  • B: ez undorító!!
  • C: lány vagyok
  • D: attól függ, hogyan halt meg

Az eredmények:

  • A: 2%
  • B: 52%
  • C: 33%
  • D: 11%

Ha ezek küzül az eredmények közül megnézzük a férfiakra vonatkozó részt:

  • A: 3%
  • D: 17%

Azaz a férfiak 20%-a [te mondod meg].


English version

The mindenki.hu is a site where people can raise and answer questions about personal preferences and then they can see who is similar and who is different to them.

There was a question: Would you "sleep" with the woman of your dreams if she were dead for 1 minute?

  • A: Of course. If an opportunity raises, it should not be missed.
  • B: This is disgusting.
  • C: I am a woman.
  • D: It depends on the way she died.

The results:

  • A: 2%
  • B: 52%
  • C: 33%
  • D: 11%

Taking the shocking results only on men:

  • A: 3%
  • D: 17%

So 20% of men are [you name it].

2011-05-18

Programming language inventor OR serial killer?

Kóder vagy sorozatgyilkos?

Can you tell a coder from a cannibal? Try to work out which of the following spent their time hacking computers and which preferred hacking away at corpses instead.

Killer Quiz

2011-05-04

The bad and ugly: Ruby strings

Ruby is a language like Java, everything is reference to object. An assignment does not produce copy of the value, but the copy of the reference. So if you have an a object, and you say b=a then you will have a b object reference pointing to the same place as a.

The naive approach of a string is that if I say a='x12345y'; b=a; b.sub!('234','---'); will result in an a which's value is 'x12345y' and a b which's value is 'x1---5y'.

The Java guys invented the immutable pattern which means that after a string is created it cannot be modified. The sensation of modification comes from the construction of new strings from old ones, like s = s.concat("TEST") where s.concat("TEST") creates a new string which's reference may or may not be stored back at s itself.

But Ruby has weird behavior:

original = '|123|123|123|123|'
s = original
s['123']='TEST'
print(s,"\n")
s = original
s.sub!('123','TEST')
print(s,"\n")
will output
|TEST|123|123|123|
|TEST|TEST|123|123|
You do not know enough - they say, There are immutable objects in ruby too!. I just have to call the freeze method and the object will be immutable. Let's try it.

original = '|123|123|123|123|'
original.freeze # <--- NEW GUY
s = original
s['123']='TEST'
print(s,"\n")
s = original
s.sub!('123','TEST')
print(s,"\n")
will output
stringtest.rb:4:in `[]=': can't modify frozen string (TypeError)
        from stringtest.rb:4

That is just plain wonderful. We are still on the same place: nowhere. What would be the solution? Nothing sane is available. You have to use s = String.new(original) instead of simple assignment. This is a terrible looking pain in the ass solution.

Who the hell knows where was my string declared at the first time? Who knows what will be broken if I change a string I got from somewhere? Who will find the real problem for an error message like File not found: 'TEST'?

2011-05-02

Unexpected behavior: pointer to constant

Preface: some words about correct 'const' syntax

The general rule is that the const keyword affects its immediate left neighbor. Sic! So the correct syntax for defining a pointer to a constant integer is int const * pInteger. The history proved that the traditional style is not sufficient, but is still maintained: If the const keyword is the leftmost in a type specification then it affects its immediate right neighbor.

Constants are to be disposed too

#include <iostream>
class A {
public:
        A(){ std::cout << "Risen #" << (idx=++counter) << std::endl; }
        ~A(){ std::cout << "Fallen #" << idx << std::endl; }
private:
        int idx;
        static int counter;
};
int A::counter = 0;

int main(){
        A const first;
        return 0;
}

will output (as expected)

Risen #1
Fallen #1

As we can observe, the destructor of the const-qualified first variable was called. That extrapolates that the const qualifier does not protect from calling the destructor on a pointer which is a weird looking thing for the first time.

The unexpected behavior

#include <iostream>
class A { /* same as the above */ };
int A::counter = 0;
void f(A const * pTest){ delete pTest; }

int main(){
        A *pFirst = new A, second;
        f(pFirst);
        A const third;
        return 0;
}

will compile flawlessly and will produce

Risen #1
Risen #2
Fallen #1
Risen #3
Fallen #3
Fallen #2

The bad idea

Let's make it impossible to call a delete on pointers to constants! Bad idea. The following example must be possible.

Vector2D const * pVector = new Vector2D(3,2);
// ...
delete pVector; // <--- This is it.

And the deletion of a pointed value must be delegable to functions. That's why the f() was able to delete its parameter.

One may feel unsafe at this moment, but it is not really a problem in the industry: almost nobody has the clue that it is even possible, and nobody wants to do that anyways, except when it is the main goal. But then it's not a trap.

2011-04-20

Az nem úgy van az

Történt egyszer valamikor 2005 tájékán, hogy Budapesten egy XI. kerületi kollégiumban, a 11 emeletes épületben a lift elromlott és egy fiatal srác bennragadt. Nyomta ő a csengőt, mint süket a csengőt, de a portás csak nem hallotta meg és nem intézkedett. Bicskájával hát kibütykölte a lift ajtajának zárószerkezetét, kinyitotta a liftajtót, majd kimászott. Lesétált a földszintre, hogy elmesélje hogyan járt, ha már a csengő nem működött vagy nem hallották. Addigra épp oda is ért a nagyon lassú léptekkel közlekedő mikulásra emlékeztető portásbácsi.

- Jó napot kívánok! A negyedik és az ötödik emelet között elakadt a lift.
- Ezt meg maga honnan tudja?
- Benne utaztam.
- És? - kérdezte a portás nagy kerek szemekkel.
- Kifeszítettem az ajtót és kimásztam.
- Az nem úgy van az hogy csak úgy kimászunk a liftből!*

2011-04-14

Symlinks under Windows, finally. Or not?

Symbolic links were introduced to Windows as of Windows Vista. Yipikaye! Or not?

D:\linktest>mklink fileLink file.txt
You do not have sufficient privilege to perform this operation.

Under Windows 7 you have to have administrator privileges to create one. So if you have a D:\home\yourname\projects\pets\WorldDominator and you want to access it as D:\home\yourname\WorldDominator then your friend is not the symbolic link, but the plain old Windows shortcut.

What about projects that want to be platform independent and wait for Windows to have support for symbolic links, so some routing code could be dropped? Some pain. Windows is the only mainstream operating system that does not have support for user managed symbolic links by default. It can be configured using secpol.msc by the administrator who may or may not care.

I wish I could understand the considerations behind this decision.

And finally, should the multi-platform projects use symbolic links or not?

2011-04-07

Courier New - follow up

Couri
erNew
|⇐⇒|
|||||

Rightwards (and leftwards) double arrow

I wrote to "FontsLive.com by Monotype Imaging" about the problem. They confirmed that the problem is in the font itself (not the softwares), but they cannot change the situation, because of licensing difficulties:

Hi Edvárd,

It appears to a bug (or a feature?) in Courier New and how it is rendered in various environments or applications.

Unfortunately since we distribute this font under license we cannot modify it.

So my suggestion would be to consider a different font, such as Consolas, another monospaced font.

Sincerely,
--- 8< ----

2011-03-18

Courier New - rightwards double arrow


<span style='font-family: courier new; font-size: 1.5em; line-height: 80%;'>
|something|&larr;|&rarr;|&lArr;|&rArr;|something|<br />
||||||||||||||||||||||||||||||||||<br />
</span>

|something|←|→|⇐|⇒|something|
||||||||||||||||||||||||||||||||||

The above example demonstrates that the monospace Courier New font is not monospace. You can use this text for testing Notepad, Mozilla Firefox 3.*, PuTTY. The rightwards double arrow is wider than it should be. Under IE8, and Firefox 4.* both double arrows are wider than they should be. (All tested under Win7)

Here I divide by z[AUTOSAVED]

Follow up

Courier New - follow up

2011-02-07

Dropbox (x)

One of my friends recommended me this simple utility. I like it and I think that the most impressive feature of it is that you can synchronize your documents between your computers. It can be also used for sharing some things with the public or with some other Dropbox users.

The figure

The idea is a basic one. You register at Dropbox.com and download a service application for your operating system (Windows, Linux, Mac and some mobile devices are supported) and select a newly created directory on your local computer.

Everything stored on the Dropbox server will be synchronized down to your computer's selected folder and when you change or add anything to that folder then it will be uploaded automatically and downloaded by your other computers. You can also access your files via the web interface.

You will get 2 GB of space for free and - of course - you can buy more up to 100 GB.

Dropbox vs Google Docs

It is better than Google Docs because you can share ANY KIND OF DOCUMENT that your computer can handle, not only a subset of them. However Google Docs has some advantages like simultaneous editing of texts and spreadsheets.

Dropbox vs revision control systems

It is not for that at all. There are a limited support for undeleting but that's all.

Internet Explorer vs favicons

The usage of favicon.ico in the root directory of the site was introduced by Internet Explorer 4.0. This icon must be a Windows Icon File (MIME: image/vnd.microsoft.icon). It is used to illustrate bookmark entries, desktop shortcuts, tabs (of tabbed browsing). Time is - again - frozen at Microsoft because...

jeffdav blog entry describes that this must be a Windows Icon File, otherwise Internet Explorer will not display this icon.

All other major web browsers support PNG, GIF and JPEG. Firefox and Opera also supports APNG, and Opera alone can use SVG. If an image type can be handled by a browser then there should not be any obstacle to display favicons of that kind.

2011, Internet Explorer: WINDOWS ICON FILE ONLY.

Good news: You can specify different favicon for each page like that:
<html>
	<head>
		<!-- some things -->
		<link rel="shortcut icon" href="path/something.ico" />
	</head>
	<body>
		<!-- some things -->
	</body>
</html>

PS: If you want to generate more anger inside yourself then you should check out http://animatedpng.com/ and follow the case of APNG support in web browsers. According to the 10 year long story of alpha transparency support in Internet Explorer there is no much hope.