Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Monday, November 7, 2011

Vala compile error: cannot infer generic type argument for type parameter `GLib.Thread.create.T'

Today I tried to work with Vala and threads.
Turned out that documentation, even the official sources, is still sketchy and young.
E.g. I tried to build the following, taken from here:
void* thread_func()
{
    stdout.printf("Thread running.\n");
    return null;
}

int main(string[] args)
{
    if (!Thread.supported())
    {
        stderr.printf("Cannot run without threads.\n");
        return 1;
    }

    try
    {
        Thread.create(thread_func, false);
    }
    catch (ThreadError exc)
    {
        return 1;
    }  

    return 0;
}
It will give up compiling with the following error:
$ valac --thread main.vala
 main.vala:19.9-19.21: error:
 cannot infer generic type argument
  for type parameter `GLib.Thread.create.T'
        Thread.create(thread_func, false);
        ^^^^^^^^^^^^^
 Compilation failed: 1 error(s), 0 warning(s) 
The compiler does complain about an actual lack in my code. Infact the declaration of "Thread.create()" is:
Thread<T> create<T>(ThreadFunc<T> func, bool joinable)
The culprit is the generic type "T" to be passed to the create method.

But the type of what I need to provide?
Thread.create<?>(thread_func, false)
It's the return type of the thread function "thread_func" passed as the first parameter to the create method.
Hence I need to call it this way instead:
Thread.create<void*>(thread_func, false)
In the case thread_func had returned bool:
Thread.create<bool>(thread_func, false)
And so on.

Here's the incomplete documentation for the create method that led me to the initial impasse.
Here is where I found the solution (thanks to Abderrahim Kitouni) instead.
Yeah, a bit of Googling helped me as well.

Friday, September 30, 2011

Suppress "unused parameter" warnings

Here's a way to suppress the annoying "unused parameter" warning given by the following code:
void aFunction(int unusedParameter)
{
    // Do something but ignore the 'unusedParameter'
}

I use this define:
#define CHECKED_UNUSED(x) (void)x

And then I surround unused parameter with it, right after the opening bracket of the function (so I can easy find and modify the parameter if I start using it):
#define CHECKED_UNUSED(x) (void)x

void aFunction(int unusedParameter)
{
    CHECKED_UNUSED(unusedParameter);
}


I looked at the generated assembly before and after and it didn't change:
                  aFunction(int):
00000000004007d4:   push %rbp
00000000004007d5:   mov %rsp,%rbp
00000000004007d8:   mov %edi,-0x4(%rbp)
15                }
00000000004007db:   pop %rbp
00000000004007dc:   retq
18                {


Disclaimer: use it only after you carefully checked that you really not need to use that parameter.
Unused parameters (and all the warnings in general) could really lead to a bug (or simple misunderstandings) in your code.

Friday, September 2, 2011

Bug after updating to ruby 1.9.2 on Arch Linux

If you ever encountered the following error in your ArchLinux box:
$ gem install <your_gem_name_here>
/usr/lib/ruby/site_ruby/1.9.1/rubygems/source_index.rb:62:in `installed_spec_directories':
  undefined method `path' for Gem:Module (NoMethodError)
from /usr/lib/ruby/site_ruby/1.9.1/rubygems/source_index.rb:52:in `from_installed_gems'
from /usr/lib/ruby/site_ruby/1.9.1/rubygems.rb:914:in `source_index'
from /usr/lib/ruby/site_ruby/1.9.1/rubygems/gem_path_searcher.rb:83:in `init_gemspecs'
from /usr/lib/ruby/site_ruby/1.9.1/rubygems/gem_path_searcher.rb:13:in `initialize'
from /usr/lib/ruby/site_ruby/1.9.1/rubygems.rb:873:in `new'
from /usr/lib/ruby/site_ruby/1.9.1/rubygems.rb:873:in `searcher'
from /usr/lib/ruby/site_ruby/1.9.1/rubygems.rb:495:in `find_files'
from /usr/lib/ruby/site_ruby/1.9.1/rubygems.rb:1034:in `load_plugins'
from /usr/lib/ruby/site_ruby/1.9.1/rubygems/gem_runner.rb:84:in `<top (required)>'
from <internal:lib/rubygems/custom_require>:29:in `require'
from <internal:lib/rubygems/custom_require>:29:in `require'
from /usr/bin/gem:9:in `<main>'
You can use these commands to solve the issue:
$ sudo pacman -U /var/cache/pacman/pkg/ruby-1.9.1_p429-1-x86_64.pkg.tar.xz
[or equivalent 1.9.1 version]
$ sudo gem update --system
$ sudo pacman -S ruby

[to return to the new ruby (1.9.2 in my case)]

Thursday, February 3, 2011

[SOLVED] Kernel 2.6.37 : No temperature info for CPU

After the update to kernel 2.6.37 on my Arch-powered notebook I found my AWN temperature applet was showing GPU data only and no sensors could be detected for the CPU.

I solved by installing lm_sensors and modprobe-ing coretemp module.

Just in case someone is stuck on it, too.

Sunday, October 31, 2010

SOLVED: Avant-Window-Navigator Stacks Applets not working under Python 3

So, all of a sudden my AWN Stacks applet stop working... right after the switch to Python 3 (blame on you Arch Linux!!!).

BUT!

... I traced the issue back to its origin so there is a way (as of today quite a dirty one) to solve it:

$ gedit /usr/share/avant-window-navigator/applets/stacks/stacks_applet.py
(You may need to sudo it)

Find line 271, comment it and change it to:
pixbuf = IconFactory().scale_to_bounded(pixbuf, 1 * size)
(or to pixbuf = IconFactory().scale_to_bounded(pixbuf, size) if you're not a Captain Obvious fan)

Save and exit.

Restart AWN.

Done.

I'm on a Phacochoerus africanus.

Friday, July 30, 2010

git update-to

Reading this very useful GIT guide I thought of a possible addition to my GIT aliases set.
On my archlinux box git update-to origin mybranch is currently an alias for git pull --rebase origin mybranch.
It pulls with rebase instead of merge, thus avoiding many unnecessary commits in your history.
NB: It rebases to the branch the command is issued in!

Command to save the alias in your ".gitconfig":
git config --global alias.update-to pull --rebase

Final notes:
When rebasing fails with conflicts is often a good idea to simply merge (with "git pull origin master", for example): no "history-uncluttering" is this much valuable when conflicts-resolving steps in...

Friday, July 16, 2010

GIT Tip: Delete a Remote Branch

In GIT, when you're done with a remote branch you can*:
git push origin :mybranchname
Source: http://progit.org/book/ch3-5.html

* "can" doesn't mean "must" or "have to", you know...

Friday, September 11, 2009

MySQL foreign keys (MySQL Error Nr. 1005)

12-09-2009 - 12:00
UPDATE:
Well, it seems to me that this topic deserves some more attention, so I'm going to investigate it thoroughly.
From this page I found that:
a table [...] must have indexes on the referenced keys. If these are not satisfied [read: "if they are not present for those keys"], MySQL returns error number 1005 and refers to error 150 in the error message.

More in detail, in the rest of the update I'm assuming the following command (as it is reported on the same page I linked above) as reference:
[CONSTRAINT [symbol]] FOREIGN KEY
 [index_name] (index_col_name, ...)
 REFERENCES tbl_name (index_col_name,...)
 [ON DELETE reference_option]
 [ON UPDATE reference_option]

@Dhruva Sagar: I think you were talking about this one:
If the CONSTRAINT symbol clause is given, the symbol value must be unique in the database. If the clause is not given, InnoDB creates the name automatically.

@payal: Check this (same page as above...):
InnoDB supports foreign key references within a table. In these cases, “child table records” really refers to dependent records within the same table.

Furthermore I suggest using the following command to check when errors occur: SHOW ENGINE INNODB STATUS, which displays a detailed explanation of the most recent foreign key error in the server.
I'm trying to replicate this error today; I'll drop you the results as soon as I can.


----------------- old updates -----------------

27-08-2007 - 10:08 (OLD UPDATE!!!)

UPDATE:
It seems the problem is caused by the "ON UPDATE" and "ON DELETE" clauses: they have to be set to the same policy, i.e. you have to write "ADD CONSTRAINT 'new_fk_constraint' FOREIGN KEY 'new_fk_constraint' ('fieldA1') REFERENCES 'tableB' ('fieldB2') ON DELETE RESTRICT ON UPDATE RESTRICT" or "ON DELETE UPDATE ON UPDATE UPDATE", while "ON DELETE SET NULL ON UPDATE RESTRICT" won't work.
Indexes are not the cause of the problem: when you create a foreign key an index for the field involved on the foreign key is automatically created by the MySQL environment, so you don't need to manually create it before adding the foreign key (read: "Bull-Shit at 09:41, Good-Shit at 10:08").

27-08-2007 - 09:41 (OLD UPDATE!!!)
If you want to place a foreign key from field 1 on table A to field 2 on table B, first of all you need to create an index for the field 1 on table A.
If you don't create the index before attempting to create the foreign key you are likely to be stopped by the error "MySQL Error Nr. 1005- Can't create table...".

I experienced this situation while using InnoDB.

Monday, August 31, 2009

How to save an XML file in Java and Eclipse

One problem I faced today was saving the content of an XML document (org.w3c.dom.Document) to a newly created file.
The file I was outputting to was an Eclipse abstraction (precisely org.eclipse.core.resources.IFile) of a regular one and the method offered by this IFile for setting its contents is "IFile.setContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor)".
I needed to bridge the gap between that org.w3c.dom.Document and the InputStream required by "IFile.setContents()", and here's the way I did it:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

try
{
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();

transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

PrintWriter writer =
new PrintWriter(outputStream);

transformer.transform(new DOMSource(document),
new XMLWriter(writer).toXMLResult());

writer.flush();
}
catch (TransformerConfigurationException exc)
{
// DEBUG
exc.printStackTrace();
}
catch (TransformerException exc)
{
// DEBUG
exc.printStackTrace();
}
InputStream source = new ByteArrayInputStream(outputStream.toByteArray());

The main classes being used here are from package "javax.xml.transform", with the method "Transformer.transform(javax.xml.transform.dom.Source source, Result result)" basically taking care of all the stuff.

I'm going to package this one into a library called "LifeSavingUtilities"...

Monday, February 23, 2009

Installing CubicTest

Have you ever been in need of an advanced testing tool that makes it easy to:
  • Test your web-applications by interacting with them as an human user would do
  • Let you define test-steps by drawing simple flow-chart-like diagrams
  • Auto-draw the test-steps by recording your actions from the browser window
  • Automatically re-execute so-recorded texts against a web-browser
Well, this kind of tool really exists: it's CubicTest and in the last days it really lived up to its promises.

In just one day I wrote a complete test-plan and linked each one of the tests planned to a testcase created with CubicTest.
And not only I "wrote" the tests by simply recording my activities inside the browser, but I also left CubicTest the task of executing them automatically, presenting me with the exact step where the failures occurred.

This way I obtained a "real" test-plan, consisting of human-readable, auto-generated and repeatable acceptance-tests.
Something I could easily bundle into an Eclipse application that could be used by my customers when they will try out my project.

Here's how to install CubicTest:
  1. Download and install Eclipse at http://download.eclipse.org
  2. Add the following update site to Eclipse: http://boss.bekk.no/cubictest/update/ (or download it from http://boss.bekk.no/cubictest/download.html)
  3. Select the CubicTest plugins and install them
  4. When asked whether to apply the changes or restart click "Apply Changes" and then manually shut-down Eclipse
  5. Open the eclipse.ini configuration file (/path/to/eclipse/eclipse.ini or C:\Program Files\Eclipse\eclipse.ini) and add the following line:
  6. On Linux: -DfirefoxDefaultPath=/path/to/firefox_installation/<firefox_executable>
    On Windows: -DfirefoxDefaultPath=C:\path\to\firefox_installation\firefox.exe
  7. Start Eclipse
  8. Follow the tutorials provided by the CubicTest Team and start using it

Let me know if you like this tool (by clicking the title of this post and leaving me a comment).

Wednesday, November 5, 2008

One more reason

I'm still asking myself why people insist on using MySQL.
Today another near-buggy behavior for this DBMS.
Just try to call a MySQL function name and then leave a space between it and the open parenthesis:
"Function FUNCTION_NAME doesn't exist on DB_NAME"
...
Seriously man... migrate to PostgreSQL and leave the old and stupid things behind.

Monday, August 4, 2008

MySQL vs Ubuntu 8.04: Default settings really annoy me!

By default Ubuntu 8.04 sets MySQL to listen to local connections only.
This really is an annoying and stupid thing I found in the server (!) version of Ubuntu Hardy Heron.

Here the solution.

Here some thoughts of mine:
  • Does a server mantainer need Ubuntu to prevent him from using MySQL for the purpose it has been meant?
  • Does someone still use all-in-one machines, equipped with DBMS, appserver, webserver and whatever else (maybe someone like this still exists...)?
I have to admit it: the only OS I saw doing stupid things like this one is... Windows.

Sunday, August 3, 2008

Tunneling Desktop Environments via SSH

Xorovo "Shared Knowledge" Program


Sometimes working with SSH using the terminal isn't enough. These times SSH could be used to tunnel a graphical interface from the remote machine to the one we are using.


Requires:

Server machine: Linux, Gnome OR KDE OR any other desktop environment running on a X server

Client machine: any X-server-powered OS (Linux works with X by default, but also Windows machines could be equipped with some sort of X server), SSH client installed



Procedure: Starting simple graphical applications

First of all start the console and type:
ssh -X username@remotehostname -p port

providing the right username, remote host name (or remote host IP) and the right port.

After providing the password you are logged in the remote machine.
You can start any application of the remote machine, e.g. you can do:
gedit &

and Gedit will be started on the remote host and displayed on our X server.


Procedure: Starting a desktop environment

First of all start the console and type:
whereis xterm

Remind the path returned by the command and type:
xinit path/to/xterm -- :1

This command opens a new X session (on the display "1").
This session contains an xterm terminal.

In the xterm terminal type:
ssh -X username@remotehostname -p port

providing the right username, remote host name (or remote host IP) and the right port.

After providing the password you are logged in the remote machine.
You can start any application of the remote machine, but the useful thing is you can also start an entire desktop environment:

gnome-session (if you want to start Gnome)
startkde (if you want to start KDE)
startxfce4 (if you want to start XFCE4)

Wednesday, July 16, 2008

Programmers' Golden Rule

  • Let w be your typical work day,
  • Let a b is a bug discovered at m minutes before w is finished,
  • Then, iff m <= 60, the following holds:
(1)  b must be ignored for the following m - 1 minutes
and taken care of at w + 1

This is the same as saying that a good restful night is determinant to solve even the most fearful bug.

And it's also equivalent to saying that ignoring (1) is the best way to introduce more bugs and confusion instead of actually resolving the initial bug.

Trust me.

Wednesday, July 2, 2008

A great river always starts up as a little spring

Every time I come to read a sentence similar to "new search algorithm will annihilate Google" or something like "X researchers teamed to find the anti-Google technology", well, I always feel the same:
Those pretty heated boys are likely to be first misunderstood, secondarily praised as the new Leonardo Da Vinci of the search-engines market, then beaten up by some quite obvious objections and finally forgotten in no time.

And, 'til now, they proved me right every time.

The reason is pretty simple: this kind of claims may be absolutely correct and these people really found something interesting and new, but they also found the worst possible way of promoting and marketing their idea: going against Google.

Why going against a Mountain with your new car is really a bad idea should be quite obvious, but let me offer some not-always-cited additional reasons:

People do really like Google

This assertion may seem incorrect but the incredible success of the Mountain View giant would never be so explosive without that appeal they have (it's like that other one Apple has too).


Google simply works

And, you may throw a wild goat (or whatever you usually throw at blasphem prophets) at me, their algorithm works damn well.


Today Google is perceived as
THE search-engine

And this one doesn't really need further explanations...


Right by now 
Google isn't only search

Just look at their on-line office suite, GMail, YouTube, AdSense, AdWords, Maps, Android and so on.
All the services Google offer contribute to the appeal we told before and increase the number of data they can reach with their search algorithm.


So, why do you insist on promoting your ideas as alternative to Google?!?
Just be smart: promote them as complimentary to it or, best of all, do not even cite Google when describing your "completely-new-and-mighty-algorithm".

I think someday, by doing so, your ideas could become a Mountain.
Or a great river, if you like it better.

Tuesday, April 1, 2008

Open- o Closed-Source pari sono

Il supporto all'editing tramite documenti Master in OpenOffice è a dir poco imbarazzante: nella migliore delle ipotesi non funziona, nella peggiore... pure.
Insomma a dirla tutta o è spaventosamente buggato o non è stato proprio implementato...

Sul versante Closed-Source le cose non cambiano: Word 2003 è proprio buggato... dal SP1 in poi!
Infatti prima che applicassi il SP1 e il SP2 tutto funzionava meglio (non "bene" si noti... "meglio" o "meno peggio").
E figuratevi se le cose le hanno aggiustate con Office 2007... si vede lontano un miglio che non è altro che un Office 2003 con una diversa interfaccia grafica...

Ora mi sto chiedendo: solo io quando scrivo del software lo testo approfonditamente per evitare simili figure di £$%*# ?!?

Consiglio: se dovete realizzare layout complessi o, almeno, professionali non usate ne l'uno ne l'altro.
Basta elaborare il testo dove volete voi (anche BloccoNote va bene) e poi usare per l'impaginazione i programmi che sono specificatamente pensati per fare impaginazione (sembra ovvio, ma non sempre lo è).

Consiglio Scribus e, se proprio volete fare il botto, InDesign. Punto.

Wednesday, February 13, 2008

Overcome fear

Have you ever wondered about importing the Voice XML Schema (see http://www.w3.org/TR/voicexml21/) into an Eclipse EMF model? Well, I have, and the result was a bunch of really annoying errors that came out after about 3 minutes of CPU intense work.

Errors I wasn't prepared to. Just for being sure of what my eyes saw I validated the VXML XSD file (using XSV)... no errors found... mmmmhhh...

What to do next? Two options:
  • find why the Eclipse XML parser (I suspect it is Xerces) isn't working and fix it (I can only imagine the divine punishment I deserved by only thinking of it...) or try to adjust the XML Schema to avoid the errors (if you wanna give it a try I warn you that XML Schema is very hard not only to write but just to understand);
  • google the web to find a Good Samaritan who already solved this

You know? Only one person can solve this. His name is Tim Myer and I want to thank him for his really helpful post. Thank you Tim!

And you folks, whatareyouwaitingfor?!?! Go check Tim's post to make out of this dreadful situation and easily overcome your fear!

Wednesday, December 19, 2007

Istruzioni di installazione per PyGridware (su Ubuntu)

Andrea tempo fa mi ha gentilmente fornito un utile tutorial per l'installazione di un toolkit per il Grid-Computing con Python (su Ubuntu!!!).
Credo sarà di gradimento a molti.

Notare 3 cose:
  • il tutorial è interamente realizzato da Andrea
  • me lo ha fatto avere da un bel po; ergo Andre: mi incenso il capo e scusami per la lunga attesa
  • se doveste avere domande o commenti sarà mia premura mettervi in contatto con Andrea (ve l'ho detto: è lui l'autore del tutorial!)

Sunday, September 9, 2007

Enabling VT capabilities in VirtualBox 1.5

Today I dramatically increased the speed at which VirtualBox runs my Windows XP virtual machine.
I'm not saying that yesterday VirtualBox performances were not satisfactory: even without VT options enabled Innotek did a very good job for the new release of their software.
But (!) , if you really want to boost the speed at which your virtual machines are emulated up, well, you essentially need 3 ingredients:
  1. A VT-capable CPU (my Intel Core Duo T2300 is VT-enabled)
  2. VirtualBox 1.5
  3. me
Let's go:
  1. First of all check whether your CPU supports VT (or AMD-V, if you are using an AMD CPU): see this page for a list of VT enabled CPUs and this one for the AMD ones, or check Intel and AMD websites for more info. [Psssst: I'll explain you a method to check if VT is enabled by using the command line in a Ubuntu environment; all you have to do is to use these instructions more /proc/cpuinfo | grep vmx (or more /proc/cpuinfo | grep svm if you are an AMD-powered guy) and check whether the command returns some text or not. If at least one line of text is displayed you are ready to proceed with the next step]
  2. Install VirtualBox and open the preferences window (File > Preferences...). Now, in the right-side pane locate the "Extended Features" section and enable the check-box named "Enable VT-x/AMD-V".
  3. That's all: I noticed a very impressive performance improvement in my Ubuntu-box.
I also enabled "Seamless integration" ("'host key' + L" inside your virtual machine), a new feature in VirtualBox 1.5, and you can see the results in this gallery: