The website has moved

Note: the website moved to www.keenformatics.com. You're being redirected.

Showing posts with label How To. Show all posts
Showing posts with label How To. Show all posts

Friday, April 7, 2017

How to generate documentation with Sphinx

Sphinx is a documentation generator that can help building great docs for our projects in a very short time. In this tutorial I will show how to use it to build docs starting from pre-existing Python docstrings.

Installing and configuring Sphinx

NOTE: If you are developing your Python package using virtualenv, I recommend installing Sphinx directly inside your virtual environment (see explanation at the end of the article).

In order to start working with Sphinx, we need to install it first. Unsurprisingly, this is as easy as:

pip install sphinx

We can now proceed and generate all the files that will be used by Sphinx to build our documentation. From terminal:

sphinx-quickstart

At this point the script will ask us to specify more details about our configuration. Here are some of the basic customizations we will be asked about:

  • Root path for the documentation: I usually choose docs/, to keep documentation separate from the rest of the project;
  • Separate source and build directories: choosing y will create two separate folders (build/ and source/) for our docs. I think this is the best choice if we want to keep everything in order;
  • Project name;
  • Author name(s);
  • Project version: I highly suggest to take a look at Semantic Versioning to choose the most suitable version at this stage;
  • Create Makefile?: choosing y will make things a bit easier later.

Sphinx ships with some extremely useful extensions that will make your life much easier. It is therefore important to choose the right ones for your needs. I usually use autodoc, todo, viewcode and githubpages. Note that these preferences can also be added to the conf.py file later.

In order to be quicker, we could also specify all of the above preferences in one command as follows:

sphinx-quickstart --sep -p 'Project Name' -a 'Author Name' -v '0.1.0' --makefile --ext-autodoc --ext-todo --ext-viewcode --ext-githubpages docs/

You should now see a structure like the following for your docs folder:

docs
├── Makefile
├── build
└── source
    ├── _static
    ├── _templates
    ├── conf.py
    └── index.rst

Building the docs

We can now proceed and let Sphinx build all the HTML files for our docs.

NOTE: HTML is not the only available format. You can use LaTeX, text, XML, and many others (see sphinx-build buildername options).

In order to do so, we will use the make command that we asked for during the configuration step above. Place yourself within the docs/ folder and issue the following command:

make html

NOTE: if you do not want to change directory, you can also use make -C docs/ html, where -C specifies the directory inside of which you want to issue the command.

At this point your build should have succeeded and your HTML files should be in docs/build/html. You can therefore open index.html in your browser and start taking a look around at your brand new docs. It won’t be long until you realize that something is missing!


Generating documentation from docstrings

What we did so far was to simply generate a sort of scaffolding for our documentation. However, we never explicitly told Sphinx to use our docstrings to automatically populate our docs! This is exactly what the sphinx-apidoc command does. From terminal:

sphinx-apidoc <path-to-project-package> -o docs/source -f -M

The above command uses the following options (you can omit them if you want):

  • -f, --force: overwrite all files generated by Sphinx;
  • -M: put module documentation before submodule documentation.

Customizing conf.py

Several customizations can be done to our docs to make them look shiny. The main place where magic happens is the conf.py file within our documentation folder. I will now share a few tricks that could help improving your documentation.


Hiding full module names


The vanilla configuration will produce an output where classes and methods described by the docs are nested inside their module name. However, all these entities will be prepended with their full namespace. For example:

module.long.full.name module

Your module description

class module.long.full.name.MyClass

As you can see, the full module name (module.long.full.name) is prepended to both the module (above) and the class (below). Since the class belongs to the module, we could reasonably prefer to hide the full module name and just keep the class name (MyClass) instead. In order to do so, we can add the following line to our conf.py configuration file:

# Do not prepend names to object names
add_module_names = False

We subsequently have to re-run the sphinx-apidoc and make commands as above to rebuild the HTML output files.


Changing Sphinx docs theme


Sphinx ships with several builtin themes that we can choose from. Additionally, we can also choose a customized theme (or create our own). In my case, I often go for the Sphinx ReadTheDocs theme. If you want to use it as well, install the sphinx_rtd_theme package:

pip install sphinx_rtd_theme

then add the following lines to your conf.py:

# Use ReadTheDocs theme
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

We can now run again the sphinx-apidoc and make commands as seen above.


More


Many other customizations can be used to improve our documentation. Please make sure to read the Sphinx build configuration file docs if you want to achieve the best results for your project.


Notes

Why installing Sphinx inside virtualenv?


The make command that we use calls sphinx-build, which in turn uses the default Python interpreter. This means that if we install Sphinx inside the virtual environment, sphinx-build will correctly call the Python version in use for our project. Why is it important? The project needs to be installed in order to be found by Sphinx; since we probably installed it using pip install -e, Sphinx will only be able to find it with regards to the Python version used by our current virtualenv.


Sources

Thursday, October 20, 2016

How To Override Sublime Text Packages Shortcuts and Preferences

I recently began using a Sublime Text 3 package that automatically generates inline YARD documentation for my Ruby code (Yardgen). The only problem with this package is that the key bindings it provides are overriding other Sublime Text shortcuts that I want to keep.

Since this plugin is packed in a zip file, it is not possible to simply edit one of its keymap files (see Package Control - Customizing Packages). At the same time, unpacking the original zipped file and creating a new zip file would not work.

Following are the steps that you need in order to solve this problem and, more generally, to override Sublime Text 3 packed packages preferences.

NOTE: If your package is overriding some default binding you wanted to keep, but you do not know the command it was binded to, please refer to my previous post.

The steps!

Install your package (Yardgen, in my case) using the Package Manager or any other method you prefer.

Your zipped package file should be now placed within the folder ~/.config/sublime-text-3/Installed Packages/<your-package>.sublime-package.

Check the content of the package by unzipping it (just make sure to keep the original zipped file).

In my case I want to edit one of the default Yardgen keybindings. Key bindings for Linux are usually stored in the Default (Linux).sublime-keymap file within the Yardgen package archive. This is the file content:

[
  { "keys": ["ctrl+enter"], "command": "yard_gen"},
]

We now have to create a folder named Yardgen inside ~/.config/sublime-text-3/Packages. We can then place inside it our new key bindings file that will override the default package behaviour:

cd ~/.config/sublime-text-3/Packages
mkdir Yardgen
gedit "Default (Linux).sublime-keymap"

Now copy the following json content in Default (Linux).sublime-keymap:

[
  { "keys": ["ctrl+alt+shift+enter"], "command": "yard_gen"},
]

As you can see, we just associated the yard_gen command to a different key sequence. You can obviously choose the one that best suits your needs.

At the moment, the yard_gen command is binded to two different key sequences: the default one, still present in the original package, and the new one we just defined. In my case, I’m not ok with this. Yardgen key bindings have in fact overridden the default CTRL + Enter behaviour, and I want to have it back.

If you too want to restore the default binding, you just need to figure out which command it was originally associated with and then explicitly add its binding to the Key Bindings preference file. For more details, please refer to my other post: How To Find out Sublime Text Key Binding Commands.


References

Tuesday, October 18, 2016

How To Find out Sublime Text Key Binding Commands

I just happened to download an awesome package for Sublime Text. Unluckily, this package uses a keyboard shortcut that overwrites a default binding I really need (the CTRL + Enter command that adds a line below the current line). I therefore want to restore the normal ST behaviour and, in order to do that, I need to figure out which command was originally called when using that shortcut.

If a new package is overwriting some default binding you want to keep, but you do not know the command it was binded to, please keep reading.

NOTE: In order to make these steps work, you need to temporarily uninstall the package that is currently overwriting your key binding.


The Steps


Open Sublime Text console. To do so, you can either click on View > Show Console or use the CTRL + ` shortcut.

We can now activate the console log to show every command we run. Give the following command in the Sublime Text console:

sublime.log_commands(True)

Now press (in the appropriate context) the key sequence that you want to analyze. For example, if you want to find out the command associated with CTRL + Enter, press that sequence of keys while editing a file. In this case you will see something like the following appear in your console:

command: run_macro_file {"file": "res://Packages/Default/Add Line.sublime-macro"}

That is the command we are looking for. We can now deactivate the command logging feature before we proceed:

sublime.log_commands(False)

If you need to overwrite some package key bindings and restore the old ones, you can simply bind your old key sequence to that command. In the CTRL + Enter case, add this entry to your Default (Linux).sublime-keymap json file (Preferences > Key Bindings):

{ "keys": ["ctrl+enter"],
  "command": "run_macro_file",
  "args": {
    "file": "res://Packages/Default/Add Line.sublime-macro"
  }
}

If you also want to keep your new package shortcuts, binding them to a different key binding, please refer to How To Override Sublime Text Packages Shortcuts and Preferences.


References

Thursday, February 18, 2016

How To Make Terminator Behave Like Guake (Ubuntu)

Terminator is a tool to arrange multiple terminals in a single window, structured on a customizable grid.

When I started using Terminator on Ubuntu, I missed two key features that I had with Guake: an hide/show shortcut, and the possibility to hide its icon from the alt-tab list of running applications.

Hide/Show Terminator like Guake

This solution has been proposed on StackOverflow (see references). I will just copy the code with its attributions and some minor changes.

  • Install xdotool and wmctrl:

    sudo apt-get install xdotool wmctrl
  • Create a file /usr/bin/launch_focus_min.sh.

  • Add the following content to the file:

    #!/bin/bash
    #
    # This script does this:
    # launch an app if it isn't launched yet,
    # focus the app if it is launched but not focused,
    # minimize the app if it is focused.
    #
    # by desgua - 2012/04/29
    # modified by olds22 - 2012/09/16
    #  - customized to accept a parameter
    #  - made special exception to get it working with terminator
    
    # First let's check if the needed tools are installed:
    tool1=$(which xdotool)
    tool2=$(which wmctrl)
    
    if [ -z $tool1 ]; then
      echo "Xdotool is needed, do you want to install it now? [Y/n]"
      read a
      if [[ $a == "Y" || $a == "y" || $a = "" ]]; then
        sudo apt-get install xdotool
      else
        echo "Exiting then..."
        exit 1
      fi
    fi
    
    if [ -z $tool2 ]; then
      echo "Wmctrl is needed, do you want to install it now? [Y/n]"
      read a
      if [[ $a == "Y" || $a == "y" || $a = "" ]]; then
        sudo apt-get install wmctrl
      else
        echo "Exiting then..."
        exit 1
      fi
    fi
    
    
    # check if we're trying to use an app that needs a special process name
    # (because it runs multiple processes and/or under a different name)
    app=$1
    if [[ $app == terminator ]]; then
      process_name=usr/bin/terminator
    else
      process_name=$app
    fi
    
    # Check if the app is running (in this case $process_name)
    
    #pid=$(pidof $process_name) # pidof didn't work for terminator
    pid=$(pgrep -f $process_name)
    
    # If it isn't launched, then launch
    
    if [ -z $pid ]; then
      $app
    
    else
    
      # If it is launched then check if it is focused
    
      foc=$(xdotool getactivewindow getwindowpid)
    
      if [[ $pid == $foc ]]; then
    
        # if it is focused, then minimize
        xdotool getactivewindow windowminimize
      else
        # if it isn't focused then get focus
        wmctrl -x -R $app
      fi
    fi
    
    exit 0
    
  • Make the script executable:

    sudo chmod +x /usr/bin/launch_focus_min.sh
  • Assign the script to a keyboard shortcut. You can do it on Ubuntu using the Keyboard settings:

    Keyboard > Shortcuts > Customized Shortcuts

    From there, you can now add the following custom command:

    /usr/bin/launch_focus_min.sh terminator

    Note that the **launch_focus_min.sh** script can be also used with applications other than **terminator**.

Hide Terminator icon from Alt-Tab menu

  • Download CompizConfig Settings Manager and the compiz-plugins-extra package

    sudo apt-get install compizconfig-settings-manager compiz-plugins-extra
  • Open CompizConfig Settings Manager.

  • Click on Manage Windows.

  • Tick the box next to Window Rules to enable them.

  • Click on Window Rules.

  • Fill in the Skip Taskbar and Skip Pager fields with the following:

    (name=terminator) & class=Terminator

    Note - Here is the meaning of the two fields we filled:

    Skip taskbar These windows will not show up on the task bar (the list of buttons you click on to switch between open windows).
    Skip pager These windows will not show up on the desktop pager (the applet you click on to switch to desktops/workspaces/viewports).

Terminator should now disappear from the Alt-Tab menu.


References

Monday, November 4, 2013

How To show Eclipse menu in Ubuntu 13.10 Saucy Salamander

Note: The following solution also applies to Aptana Studio.

The almost new Eclipse Kepler IDE has been released with a new exciting bug for those who use Ubuntu 13.10 (Saucy Salamander).

If you're among those lucky developers, when you'll open your IDE you'll find that Eclipse upper menu is pretty useless, since clicking on menu entries nothing will happen: no submenus will show up as you expected.

So, what to do if Eclipse menu doesn't show up in Ubuntu 13.10? The best solution at the moment (until someone decides to fix this bug) is the following.




N.B.: This method takes for granted that you already created your eclipse.desktop file. If you didn't create it and you don't want to do that at the moment, you can simply run eclipse by console with this command:

$ UBUNTU_MENUPROXY= eclipse
where "eclipse" is the path to your eclipse executable. But this is just the fast way to run eclipse once. If you don't want to remember this command and use it every time you have to run Eclipse, follow the rest of this guide.

Steps!
  1. Open your eclipse.desktop file:
    sudo gedit /usr/share/applications/eclipse.desktop
    or
    sudo gedit ~/.local/share/applications/eclipse.desktop
    (Depending on your configuration.)
  2. Copy these lines in it:
    [Desktop Entry]
    Type=Application
    Name=Eclipse
    Icon=eclipse
    Exec=env UBUNTU_MENUPROXY= eclipse
    Terminal=false
    Categories=Development;IDE;Java;
    
  3. Save the file.

Yes, that's it. Did you expect something harder? Comment complaining is welcome.

If you found this post useful, please share it!

References

Monday, August 26, 2013

How To create a global InitBinder in Spring with @ControllerAdvice

Date formatting could be an annoying problem when dealing with your views. I wrote an article about it when I was facing Json problems (see How To format dates in Json within Spring 3) but, as you may know, even if you don't need to use Json in your views, you'll probably have to face some troubles with date formats.

Sometimes you can avoid all your problems simply using the specific JSTL fmt in your jsp (see references). But what to do if you can't use JSTL in your jsp, or if a simple JSTL won't solve your problems?

Someone suggests to inject an InitBinder in your controller. What an InitBinder does is to grab your data from web request parameters and bind it to your JavaBean objects. So this could be a good solution if you have to deal with different kinds of data inputs in different controllers. But what if you have to always deal, for example, with dates? You could write a specific InitBinder for each of your controllers, but this is not a good procedure if you want to maximize your code efficiency by an accurate modularization (and this should be your aim, since you're using MVC paradigm).

What I suggest you to do is to create something like a single global InitBinder, which will be activated everytime your application needs it, without any controller restriction. There's a really simple way to do so, using Spring @ControllerAdvice annotation. A class annotated with @ControllerAdvice is a class that assists every controller, and it's easily autodetected through Spring classpath scanning.

If this is your case, and you want to create an InitBinder which manages your dates parsing them in (for example) dd/MM/yyyy format, here's what you can do.

The steps!
  1. Create a DateEditor class like this:
    public class DateEditor extends PropertyEditorSupport {
     
     public void setAsText(String value) {
            try {
                setValue(new SimpleDateFormat("dd/MM/yyyy").parse(value));
            } catch(ParseException e) {
                setValue(null);
            }
        }
    
        public String getAsText() {
         String s = "";
         if (getValue() != null) {
       s = new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
      }
         return s;
        }
    
  2. Create a class annotated with @ControllerAdvice (I called it GlobalBindingInitializer):
    @ControllerAdvice
    public class GlobalBindingInitializer {
     
     /* Initialize a global InitBinder for dates instead of cloning its code in every Controller */
     
     @InitBinder
     public void binder(WebDataBinder binder) {
      binder.registerCustomEditor(Date.class, new DateEditor());
     }
    }
    
  3. In your Spring MVC configuration file (for example webmvc-config.xml) add the lines that allow Spring to scan the package in which you created your GlobalBindingInitializer class. For example, if you created GlobalBindingInitializer in the org.example.common package:
    <context:component-scan base-package="org.example.common" />
    

There's nothing else to do for your InitBinder date formatter to work. Remember that @ControllerAdvice is an extremely helpful annotation even when you have to handle exceptions, or if you want to create a global accessible @ModelAttribute for your application.

References

Monday, August 19, 2013

How To display trailing zeros in Json within Spring 3 and Jackson

This post could be simply read as a revisitation of the one in which I explained How To format dates in Json within Spring 3. But since the problem to solve is different, I think it could be useful to write a new guide about it, even if the mechanics are quite the same.

I recently discovered that managing prices with floats is a bad idea, so I decided to change all of my "float price" variables to a more efficient BigDecimal type. I know, the use of BigDecimals is controversial too, but it presently fits my needs, so I decided to use them in my web application.

Anyway, prices types are not what I'm going to talk about now. What I discovered when I tried to put my values in a table obtained via Json, is that Json automatically trims out trailing zeros after the decimal mark. This means that if you have to display a price like 1.20 dollars, you'll probably display 1.2 instead.

So, what I needed was something that would have been able to pick up my BigDecimal from the model, format it in a string including trailing zeros, and pass it to my jsp as Json. All of this, using Spring and Jackson, a Java library for processing JSON.

I assume you've got a jsp (i.e. itemslist.jsp), a controller class (i.e. ItemController.java) and a simple java class for the objects you want to manage in your Json call (e.g. Item.java). Plus, you should have enabled Spring annotation based configuration (see the reference links at the bottom of this post).

The steps!
  1. Create a PriceJsonSerializer class (you can change the name depending on your needs) that extends JsonSerializer. Like this:
    public class PriceJsonSerializer extends JsonSerializer<BigDecimal> {
    
      @Override
      public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) 
        throws IOException, JsonProcessingException {
          jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
      }
    }
    

    As you can see, the serialize method writes in a String format the BigDecimal, ensuring that it's scaled in order to display two digits after the decimal mark (you can customize this behaviour changing the setScale parameter "2" to a higher or lower number).

    As you can see, the serialize method sets up the format you want to use for your BigDecimal, writing it in a String format.

    Important: this means that your object will reach the jsp in a String format. So if you want to perform client-side arithmetics calculations on your values (e.g., in javascript) you'll have to parse them back to a number format. For example, if you have two values a = 2 and b = 3 in your jsp, writing a + b will perform an append procedure between strings, not a sum, giving you 32 instead of 5!

  2. In Item.java class, insert the @JsonSerialize annotation above the date getters:
    @JsonSerialize(using=PriceJsonSerializer.class)
    public BigDecimal getPrice() {
     return price;
    }
    
    @JsonSerialize(using=PriceJsonSerializer.class)
    public void setPrice(BigDecimal price) {
     this.price = price;
    }
    

I hope this works for you as it does for me. If not, comment and we'll try to figure out a proper solution. Well, your comments are welcome in any way :)

References

Monday, August 12, 2013

How To Solve JSON infinite recursion Stackoverflow
(with Spring and Jackson annotations)

Infinite recursion picture

Coding in Spring 3 with JPA and Jackson is supposed to semplify your life, sparing you from writing thousand lines of code. Sometimes, though, you'll notice that all these annotations hide the real core of your application, preventing you to really understand what your code is doing (and what it is supposed to do).
This means that if you want to develop a good java application or website, you need to carefully read the docs or (more realistically) you need to understand how to read your error logs and combine them with a well-written search engine query.

This is what I had to do when I first met the problem I'm about to write about.



The problem.

I was getting a wrong JSON response while using a many-to-many relationship, that caused my application to enter in an infinite loop giving as output an infinite recursion Stackoverflow error.

Here is part of what I found in my Eclipse console:

Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain: [here is the loop]) with root cause
java.lang.StackOverflowError
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:567)
 at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:143)
 at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:118)
 at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:24)
 at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:180)
 at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:544)
 at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:551)
 ...

and so on.

Since I was using Datatables jQuery plugin, I also had this output in my browser window:

DataTables warning (table id = 'products'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.

What I noticed is that the same database query, without JSON, was working well. So the problem (as the console in fact said) was with Jackson and Json serialization. As the docs state (see references), bi-directional references for ORM-managed beans (iBatis, Hibernate) would cause serialization to failure since they are cyclic dependencies. Since Jackson 1.6, this problem has been solved by the introduction of two new annotations: @JsonManagedReference and @JsonBackReference (and see the end of this post to give a look at the @JsonIdentityInfo annotation).

How does serialization work? (The solution in theory)
In computer science, in the context of data storage and transmission, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and resurrected later in the same or another computer environment.

For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the annoying infinite recursive loop that causes our stackoverflow error.

So, Jackson takes the forward part of the reference, for example an attribute of a java class (i.e. List<Role> roles in User class), and converts it in a json-like storage format; this is the so-called marshalling process.
Then, Jackson looks for the back part of the reference (i.e. List<User> users in Role class) and leaves it as it is, not serializing it. This part of the relationship will be re-constructed during the deserialization (unmarshalling) of the forward reference.

The solution in practice.

It's very simple. Assuming that your database query already works without JSON, all you have to do is this:

  1. Add the @JsonManagedReference In the forward part of the relationship (i.e. User.java class):
    @Entity
    public class User implements java.io.Serializable{
     
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private long id;
     
     @Column(name="name")
     private String name;
    
     @ManyToMany
     @JoinTable(name="users_roles",joinColumns=@JoinColumn(name = "user_fk"),
     inverseJoinColumns=@JoinColumn(name = "role_fk"))
     @JsonManagedReference
     private Set<Role> roles = new HashSet<Role>();
    
    ...
    
  2. Add the @JsonBackReference In the back part of the relationship (i.e. Role.java class):
    @Entity
    public class Role implements java.io.Serializable {
    
     @Id 
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;
    
     @ManyToMany(mappedBy="roles")
     @JsonBackReference
     private Set<User> users = new HashSet<User>();
    
    ...
    

The work is done. If you take a look at your firebug logs, you'll notice that the infinite recursive loop has disappeared.


Edit (02/09/2013)

Another useful annotation you could check is @JsonIdentityInfo: using it, everytime Jackson serializes your object, it will add an ID (or another attribute of your choose) to it, so that it won't entirely "scan" it again everytime. This can be useful when you've got a chain loop between more interrelated objects (for example: Order -> OrderLine -> User -> Order and over again).

In this case you've got to be careful, since you could need to read your object's attributes more than once (for example in a products list with more products that share the same seller), and this annotation prevents you to do so. I suggest to always take a look at firebug logs to check the Json response and see what's going on in your code.


References

Monday, August 5, 2013

How To format dates in Json within Spring 3


After I managed to fix the Datatables jQuery plugin, finally squeezing my "Movie" class into the awesome table I prepared in my jsp, I found out that the dates in the columns were absolutely unintelligible: they were not properly formatted, and so they were showing up as a Long useless number.
My DataTables implementation uses Json to call the informations with which I'll fill the table's columns and rows. So, what I needed was something like a "real-time date formatter" for Json, something that would have been able to pick up my Date object from the model, format it in a comprehensible string format, and pass it to my DataTables plugin as Json.
If this is your situation at the moment, you'll probabily find this guide useful, since it's not very long and not very complicated. Well, it's not complicated at all, actually.

I assume you've got a jsp (i.e. movielist.jsp), a controller class (i.e. MovieController.java) and a simple java class for the objects you want to manage in your Json call (e.g. Movie.java). Oh, you should also have enabled Spring annotation based configuration (see the reference links at the bottom of this post). So...

The steps!


1. Create a DateJsonSerializer class that extends JsonSerializer. Like this:
public class DateJsonSerializer extends JsonSerializer<date> {
 
 @Override
 public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) 
   throws IOException, JsonProcessingException {
     DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
     jgen.writeString(formatter.format(value));
 }
}

As you can see, the serialize method sets up the format you want to use for your date strings.

2. In Movie.java class, insert the @JsonSerialize annotation above the date getters:

@JsonSerialize(using=DateJsonSerializer.class)
public Date getDate_in() {
 return date_in;
}
public void setDate_in(Date date_in) {
 this.date_in = date_in;
}

That's it. Yes, your work should already be done.
If you find something not working, please comment and I'll try to figure out a proper solution.

REFERENCE LINKS:
Spring docs - Annotation type JsonSerialize
Sakae Nakajima - Spring 3 Enable Annotation based Configuration

Tuesday, July 30, 2013

How To create a customized "Access Denied" landing page
with Spring 3 and Tiles 3

https://apps.cs50.net/img/error403.gif
Your new site finally needs the last thouch.
You're wasting your time walking back and forth in your room trying to think about what to do to improve it: suddenly, you remember that time when you first saw a customized landing page for that (otherwise) annoying 403 error.
Now the question is: how the hell can I do that?

And here's the answer!


(Yes, that was an absolutely boring post introduction, but I'm not a writer. Not yet, at least.)



The steps!

1) In security-config.xml

<security:access-denied-handler error-page="/accessdenied">

2) In webmvc-config.xml

<mvc:view-controller path="/accessdenied" view-name="common.accessdenied">
</mvc:view-controller>

3) In tiles-defs.xml (your tiles definitions file) define the tile for your landing page

    <definition extends="template" name="errors.denied">
        <put-attribute name="content" value="/WEB-INF/views/denied.jsp">
    </put-attribute></definition>

Obviously, change the paths consequently to your denied.jsp location.
You're done!

Now, you just have to customize the jsp in order to show the contents you want.
I suggest you to take a look at the 404 github pages: they're awesome.

Saturday, June 15, 2013

How to solve Dell laptops fan issues in Ubuntu

When I finally bought my new Dell Inspiron laptop, I decided to take a look at the brand new Windows 8 OEM installation which I (forcedly) paid for. About 20 seconds later, I was installing the latest Ubuntu distribution. I didn't knew what I would have found, but I was happy as well.
How to solve Dell laptops fan issues in Ubuntu
Sarah Klockars-Clauser for openphoto.net


One of the main problems I faced has been that of the incredibly loud fan noise which came from my new laptop, so I began my online quest until I found i8kutils, a (partial) solution to my problem. I'm saying "partial" because we shouldn't confuse the cause and the effect: i8kutils won't solve your overheating issues, but it will help you to configure your fans in order to overwrite their exasperated and irritating default behaviour. But be warned: if your fans are running it's probably because they're trying to manage your overheating problems for you, so don't set i8kutils just to make your fans definitively shut up (unless you know what you're doing).


The steps!

1) First of all, let's download and install i8kutils. Open your terminal and write:
sudo apt-get install i8kutils
2) Now you've got to add i8k to your modules. Open the modules file:
sudo gedit /etc/modules
and add the string "i8k" (without quotes) to the file. Save and exit.

3) Create an i8k.conf file
sudo vim /etc/modprobe.d/i8k.conf
and fill it with this code:
options i8k force=1

Note: Some older guides will tell you to create a /modprobe.d/options file. The "options" file isn't used anymore on Ubuntu. What does matter is that you create a file with a .conf extension (the filename isn't important, but I decided to name it i8k.conf for clarity). So beware of older i8kmon configuration guides.

4) Now restart your computer, or run this code to make i8k run:
sudo modprobe i8k force=1
5) We will now create a i8kmon.conf file which will tell the i8kmon utility how to behave.
sudo gedit /etc/i8kmon.conf
Paste the following code in it:
# Run as daemon, override with --daemon option
set config(daemon)      0

# Automatic fan control, override with --auto option
set config(auto)        1

# Report status on stdout, override with --verbose option
set config(verbose) 1

# Status check timeout (seconds), override with --timeout option
set config(timeout) 20

# Temperature thresholds: {fan_speeds low_ac high_ac low_batt high_batt}
set config(0)   {{-1 0}  -1  40  -1  40}
set config(1)   {{-1 1}  30  60  30  60}
set config(2)   {{-1 2}  53  128  53  128}

# For computer with 2 fans, use a variant of this instead:
# Temperature thresholds: {fan_speeds low_ac high_ac low_batt high_batt}
# set config(0) {{-1 0}  -1  52  -1  65}
# set config(1) {{-1 1}  41  66  55  75}
# set config(2) {{-1 1}  55  80  65  85}
# set config(3) {{-1 2}  70 128  75 128}

# end of file

This has been edited to match my Dell Inspiron 15r 5521 fan configuration (and I hope I did it well). If you want more informations take a look at the documentation on Ubuntu Manuals: http://manpages.ubuntu.com/manpages/gutsy/man1/i8kmon.1.html

6) Now you should be able to run i8kmon from your terminal and see if (and how) it's working. Simply run:
i8kmon

Finished!

But wait...what if you want i8kmon to automatically start at boot? I'll simply copy-paste what's been written in the official documentation:
Under Debian GNU/Linux it is possible to start the daemon automatically by creating an /etc/default/i8kmon configfile containing the line "set config(daemon) 1". Note the the /etc/default/i8kmon configfile is not installed by the i8kutils package because the program is designed to be run by normal users. If you want to use it as daemon you must create the config file yourself. In this case, the --nouserconfig option can sometimes also help by limiting it to sourcing /etc/i8kmon (and not ~/.i8kmon).
Doubts: I wonder why I don't have the ~/.i8kmon file on my system, while the docs refer to it.
If you take a look in your /usr/bin/i8k you'll find that ~/.i8kmon is considered as a user configuration, while /etc/i8kmon.conf (the file we edited before) is treated as a system configuration.
If something in your configuration goes wrong (e.g. if you can't make your temperature limits work) it would be worthwhile checking if you've got this ~/.i8kmon file on your system and try to edit it, because it could be perfidiously overwriting your system configuration. If you discover something about it, please let me know.

I hope this article has been useful to you. If so, please click here and there on social buttons to make it more visible. If not, I'm waiting for your constructive comments ;)

Monday, May 27, 2013

How To build your TeX file using LaTeX on Sublime Text


How To build your TeX file using LaTeX on Sublime Text
LaTeX and Sublime Text
Sublime Text 2 (the 3rd release is about to come) is one of the smarter and most elegant editors on the scene nowadays. It comes with a lot of interesting functions, and it can easily be enriched with plugins using its awesome Package Control function.

While I was writing my thesis about Kurt Gödel I discovered LaTeX, an incredible markup language which I felt in love with; it passed just a short time before I desired to use it with Sublime Text, but when I installed the LatexTools package via Package Control I had to face a little problem in order to make it work.

First of all: I think you already installed TexLive (a LaTeX distribution with many LaTeX tools) but if you did not, you can do so by typing this in your terminal:

sudo apt-get install texlive

Now you can try (as I did) to build your .tex file in Sublime Text by pressing Ctrl+B. Unfortunately, all I got at this point was this error message:

COULD NOT COMPILE!
Attempted command:latexmk -cd -e $pdflatex = 'pdflatex %O -interaction=nonstopmode -synctex=1 %S' -f -pdf <your-tex-file-path>


Read carefully these lines: what Sublime Text is trying to tell you is that it needs the latexmk package to build your file, and you didn't previously install it.
If you're encountering the same problem, the solution is trivial: you just have to install the latexmk package. Write this you your terminal:

sudo apt-get install latexmk

Now try again: you'll find that Sublime is now correctly building your tex file.

Saturday, May 25, 2013

How To access phpMyAdmin page

Here's the case: you installed Xampp (or Lampp, as it was called until some months ago), you made it run, but now you can't access your phpMyAdmin page because you get this error message:

New Xampp Security concept
Access to the requested object is only available from the local network.
This setting can be configured in the file "httpd-xampp.conf".

So, as the message says, let's open the file:
/opt/lampp/etc/extra/httpd-xampp.conf
(its path may vary depending on your system and installation).

Now edit the lines under this comment:
# since XAMPP 1.4.3
So that they look like these:
# since XAMPP 1.4.3
<Directory "/opt/lampp/phpmyadmin">
AllowOverride AuthConfig Limit
Order allow,deny
Require all granted
Allow from all
</Directory>
Now restart your Xampp and you're done!