<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bugs On Steroids</title>
	<atom:link href="http://blog.e-svet.si/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.e-svet.si</link>
	<description>Not Another Programming Blog</description>
	<lastBuildDate>Wed, 26 Feb 2014 14:15:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.6</generator>
		<item>
		<title>Sharing data and customizing dialogs in Android</title>
		<link>http://blog.e-svet.si/2013/12/sharing-data-and-customizing-dialogs-in-android/</link>
		<comments>http://blog.e-svet.si/2013/12/sharing-data-and-customizing-dialogs-in-android/#comments</comments>
		<pubDate>Thu, 05 Dec 2013 17:35:38 +0000</pubDate>
		<dc:creator>Luka Murn</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=198</guid>
		<description><![CDATA[A while ago, I was asked to take over an Android project that was outsourced by an indie freelancer. Despite me having no previous experience with Android programming, I was quite shocked when I received the source code. It&#8217;s probably the most unorganized and unstructured piece of code I have ever seen. The whole structure ...<a class="post-readmore" href="http://blog.e-svet.si/2013/12/sharing-data-and-customizing-dialogs-in-android/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>A while ago, I was asked to take over an Android project that was outsourced by an indie freelancer. Despite me having no previous experience with Android programming, I was quite shocked when I received the source code. It&#8217;s probably the most unorganized and unstructured piece of code I have ever seen. The whole structure more resembled a C project than a Java project.</p>
<p>I&#8217;ve heard from some of my colleagues that it&#8217;s quite hard to maintain a lightweight class structure in Android because of the Activity classes. Nonetheless, seeing this code I saw so many beginner mistakes that I just can&#8217;t let it go unnoticed. I&#8217;m quite sure that if I asked the code author what a MVC is, he wouldn&#8217;t have a clue. Anyway, seeing so many errors I decided I&#8217;d point out some of them in hope that somebody less experienced than me (which might not be a lot of people, since I&#8217;m an active programmer for just&#8230; 6 years?) finds something useful.</p>
<h1>1. Sharing data</h1>
<p>Our application is basically a workflow of consecutive steps, each represented by its own Activity. They, however, all operate (edit, read) on the same data. My predecessor solved this problem by creating public variables in the main Activity, and then referencing them from all the other activities. I didn&#8217;t particularly like that, so I wrote my own solution. As long as the application lives on Android (even if it&#8217;s pushed into the background, paused etc.), a single Application class will exist. That&#8217;s the object we need to store our custom data in (as long as we don&#8217;t want to use the database, which is really overkill for many smaller apps)! I created my own Application class that looks like this:</p>
<h2>MyApplication.java</h2>
<pre class="brush: java; title: ; notranslate">
public class MyApplication extends Application {

    private SharedData sharedData;

    /**
     * Called when the application is started.
     */
    @Override
    public void onCreate() {
        super.onCreate();

        // Initialize a new instance of shared data,
        // only once per application lifetime
        this.sharedData = new SharedData();
    }

    /**
     * Get the shared data.
     * @return The shared data.
     */
    public SharedData getSharedData() {
        return this.sharedData;
    }
}
</pre>
<p><strong>SharedData</strong> is simply an object holding various variables &amp; structures that are needed throughout the application. To ease the things a little bit, I also created a base Activity class from which I extend all my application activities:</p>
<h2>MyActivity.java</h2>
<pre class="brush: java; title: ; notranslate">
public class MyActivity extends Activity {

    private SharedPreferences sharedPreferences;

    /**
     * Get the application-wide shared data.
     * @return The shared data object instance.
     */
    protected final SharedData getSharedData() {
        return ((MyApplication)getApplication()).getSharedData();
    }

    /**
     * Get the application-wide shared preferences.
     * @return The shared preferences object.
     */
    protected final SharedPreferences getPreferences() {
        if (this.sharedPreferences == null) {
            try {
                this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
            } catch (Exception e) {
                this.sharedPreferences = null;
            }
        }

        return this.sharedPreferences;
    }
}
</pre>
<p>What that means is that whenever I need to access the shared data from any activity, I simply call the <strong>this.getSharedData()</strong> to retrieve or update it. I also added a function that kind of shortens the retrieval of the local preferences.</p>
<h1>2. Separation of dialogs</h1>
<p>Since our application uses quite many dialogs that are mostly just customized dialogs made from <strong>DialogBuilder</strong> factory, I still hated seeing all of them hard-coded inside individual activities. Since couple of activities use same dialogs, there was also some code duplication which is never hood. Solution? Isolate dialogs into individual classes:</p>
<h2>MyDialog.java</h2>
<pre class="brush: java; title: ; notranslate">
public class MyDialogFragment extends DialogFragment {

    // region EVENTS INTERFACE
    /**
     * An interface, used to contain abstract method definitions which are fired on specific events from the dialog and
     * should be overriden in the calling Activity class.
     */
    public interface MyDialogEvents {
        public abstract void onSubmit(String someDataToPass);
        public abstract void onCancel();
    }
    // endregion

    // region STATIC INITIALIZATION
    /**
     * Initializes a new instance of MyDialogFragment.
     * @param dialogData1 the dialog data 1.
     * @param dialogData2 the dialog data 2.
     * @param target the target events interface.
     * @return the dialog fragment.
     */
    public static MyDialogFragment newInstance(
        ArrayList dialogData1,
        boolean dialogData2,
        final MyDialogEvents target) {
        MyDialogFragment fragment;
        Bundle args;

        fragment = new MyDialogFragment();
        args = new Bundle();
        args.putStringArrayList(&quot;dialogData1&quot;, dialogData1);
        args.putBoolean(&quot;dialogData2&quot;, dialogData2);
        fragment.setArguments(args);
        fragment.setTarget(target);
        return fragment;
    }
    // endregion

    // region FIELDS
    private MyDialogEvents target;
    // endregion

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Builder builder;
        Dialog dialog;
        ArrayList dialogData1;
        boolean dialogData2;

        // Retrieve parameters from the bundle
        dialogData1 = this.getArguments().getStringArrayList(&quot;dialogData1&quot;);
        dialogData2 = this.getArguments().getBoolean(&quot;dialogData2&quot;);

        builder = new Builder(this.getActivity());
        builder.setTitle(getResources().getString(R.string.title_string));

        // Add custom controls to dialog

        // Add OK &amp; Cancel buttons
        builder.setNegativeButton(getResources().getString(R.string.dialog_negative_default),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                    target.onCancel();
                }
            });
        builder.setPositiveButton(getResources().getString(R.string.dialog_positive_default),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                String dataToPass;

                // Read the data from the controls, do validation if needed

                // Fire the event
                target.onSubmit(dataToPass);
            }
        });

        dialog = builder.show();
        return dialog;
    }

    /**
     * Sets the target.
     * @param target the target interface.
     */
    public void setTarget(MyDialogEvents target) {
        this.target = target;
    }
}
</pre>
<p>Since you usually want to do some stuff after dialog is validated/confirmed/cancelled, I exposed an interface with those specific events that the user must implement in the calling code. As I&#8217;m writing this code I realized I could move the abstract method definitions into the DialogFragment class itself, and replace the static initialization with the one in the DialogFragment constructor. But oh well, this works perfectly as well. If you want to prevent the dialog from closing when the user clicks the positive/negative button, see <a href="http://stackoverflow.com/questions/2620444/how-to-prevent-a-dialog-from-closing-when-a-button-is-clicked" target="_blank">this</a> StackOverflow entry (answer #31). To open the given dialog, the simple following code is needed in the calling Activity:</p>
<pre class="brush: java; title: ; notranslate">
MyDialogFragment dialogFragment;

dialogFragment = MyDialogFragment.newInstance(passedData1, passedData2, new MyDialogEvents() {
    @Override
    public void onSubmit(String someDataToPass) {
        // Do something with data after dialog submission
    }

    @Override
    public void onCancel() {
        // Do nothing on cancel
    }
});

dialogFragment.show(getFragmentManager(), TAG + &quot;_MyDialogFragment&quot;);
</pre>
<p>Considering I spent almost 3 whole weeks to refactor the beast, there were many more modifications &amp; improvements, but I&#8217;m too lazy to list them all at once <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . So for now that&#8217;s it folks!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/12/sharing-data-and-customizing-dialogs-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object Oriented Programming In PHP Part Three – Constructor &amp; Destructor</title>
		<link>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-three-constructor-destructor/</link>
		<comments>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-three-constructor-destructor/#comments</comments>
		<pubDate>Sun, 15 Sep 2013 09:39:00 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=162</guid>
		<description><![CDATA[PHP offers many &#8220;special&#8221; methods called magic methods. Today I will write about two of them. This is the third part of the Object Oriented Programming in PHP series and, if you haven&#8217;t already, I suggest you first read part one and two. The methods we will take a look at today are called constructor ...<a class="post-readmore" href="http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-three-constructor-destructor/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>PHP offers many &#8220;special&#8221; methods called magic methods. Today I will write about two of them. This is the third part of the Object Oriented Programming in PHP series and, if you haven&#8217;t already, I suggest you first <a href="http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/" title="Object Oriented Programming In PHP Part One – Basics">read part one</a> and <a href="http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/" title="Object Oriented Programming In PHP Part Two – Methods And Visibility">two</a>. The methods we will take a look at today are called constructor and destructor.<span id="more-162"></span></p>
<p><a href="http://www.php.net/manual/en/language.oop5.magic.php" title="PHP magic methods" target="_blank">All magic methods</a> names start with two underscores. To implement constructor and destructor we have to override __construct() and __destruct() methods. The method __construct is invoked when we create an object and __destruct when all references on an object are removed or an object is explicitly destroyed.</p>
<pre class="brush: php; title: ; notranslate">
class MilitaryBaracks {
 
  // note that construct methods starts with two underscores
  public function __construct() {
    // this code executes when object is created
    echo &quot;Soldier &quot; . $this-&gt;name . &quot; was created.&quot;;
  }

  // ... rest of the class code
  
  public function __destruct() {
    // this code executes when object is destroyed
    echo &quot;Destroying solider with name &quot; . $this-&gt;name;
  }
}
</pre>
<p>We use constructor in cases, when we want to execute some piece of code when object is instantiated. For instance, set values to properties for which we want to be sure they are set. In case of a class which takes care of connecting to database, we would want to be sure that we have all data required for establishing connection. We could use destructor to close the connection. In practice, constructor is much more often used than destructor because PHP closes resources it uses when script finishes execution. Anyway, <a href="http://stackoverflow.com/questions/3566155/php-destructors" title="Uses of PHP __destruct() method" target="_blank">this stackoverflow link</a> offers few examples of uses of destruct method in open source code.</p>
<p>For the sake of clarity, let&#8217;s build upon our MilitaryBaracks example. We want to be sure that every soldier has name and weapon.</p>
<pre class="brush: php; title: ; notranslate">
class MilitaryBaracks {
 
  // name doesn't have default value no more
  private $_name;
  // so doesn't weapon
  private $_weapon;
 
  private $_ammunition = 10;
 
  // instead, we make sure that values are passed when object is created
  public function __construct($name, $weapon) {
    $this-&gt;_name = $name;
    $this-&gt;_weapon = $orozje;
  }

  // we want that soldier is able to switch weapon
  // so we create getter method to access weapon variable value
  public function getWeapon() {
    return $this-&gt;_weapon;
  }
 
  // and set method to switch weapon
  public function setWeapon($weapon) {
    $this-&gt;_weapon = $weapon;
    return $this;
  }
 
  // name can't be changed, so we create only getter method
  public function getName() {
    return $this-&gt;_name;
  }
 
  //...
}
</pre>
<p>Ookay, let&#8217;s print out a few lines:</p>
<pre class="brush: php; title: ; notranslate">
// this is wrong because of missing arguments
$soldier = new MilitaryBaracks();
// the right way
$soldier = new MilitaryBaracks('Mougli', 'rifle');
 
echo $soldier-&gt;getname() . &quot; has weapon &quot; . $soldier-&gt;getWeapon() . &quot;.&lt;br&gt;&quot;;
 
$soldier-&gt;setWeapon('gun');

echo $soldier-&gt;getName() . &quot; has weapon &quot; . $soldier-&gt;getWeapon() . &quot;.&quot;; 
</pre>
<p>And we get:</p>
<div style="border: 1px solid #c9c9c9; padding: 10px; background-color: #f7f7f7;">
Warning: Missing argument 1 for MilitaryBaracks::__construct(), called in C:\Programi\Wamp\www\script.php on line 41 and defined in C:\Programi\Wamp\www\script.php on line 13</p>
<p>Warning: Missing argument 2 for MilitaryBaracks::__construct(), called in C:\Programi\Wamp\www\script.php on line 41 and defined in C:\Programi\Wamp\www\script.php on line 13</p>
<p>Notice: Undefined variable: name in C:\Programi\Wamp\www\script.php on line 14</p>
<p>Notice: Undefined variable: weapon in C:\Programi\Wamp\www\script.php on line 15</p>
<p>Mougli has weapon rifle.<br />
Mougli has weapon gun.
</p></div>
<p>This way our object are easier to instantiate and set, since we do everything in one line. Beside that, now we can be pretty sure that our objects have all needed properties set, as PHP throws a warning if we leave out an argument when instantiating new object. Our code and classes needs to be organized in a way that other programmers can easily understand its meaning and structure. The predictability is important &#8220;guide&#8221; of OOP.</p>
<p>Even though I previously announced a blog post about inheritance I saved it for next time. I intended to present constructor and inheritance in this post, but it would be too long and I want to keep series short and simple. For that reason I cover it in the next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-three-constructor-destructor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Yet another custom Google Picasa API gallery</title>
		<link>http://blog.e-svet.si/2013/09/yet-another-custom-google-picasa-api-gallery/</link>
		<comments>http://blog.e-svet.si/2013/09/yet-another-custom-google-picasa-api-gallery/#comments</comments>
		<pubDate>Fri, 13 Sep 2013 06:06:36 +0000</pubDate>
		<dc:creator>Luka Murn</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Picasa Web Albums Data API]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=60</guid>
		<description><![CDATA[As thousands of other people, I store my photos on the Picasa Web Albums from Google. Why did I choose Google in the first place? Well, the Picasa Web Albums had this easy way to upload pictures via Picasa application, and the first versions of the albums were just complex enough to sort pictures and ...<a class="post-readmore" href="http://blog.e-svet.si/2013/09/yet-another-custom-google-picasa-api-gallery/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>As thousands of other people, I store my photos on the Picasa Web Albums from Google. Why did I choose Google in the first place? Well, the Picasa Web Albums had this easy way to upload pictures via Picasa application, and the first versions of the albums were just complex enough to sort pictures and organize them into sub-albums, yet still simple enough to be easy to operate with. Besides, it was one of the few album providers with a lot of free space as long as you had your Gmail account (and who doesn&#8217;t have one of those&#8230;).</p>
<p>After a couple of years of usage, I sadly found some things that buggered me. The inability to create a nested structure (you can only have ona layer of organization), and the somewhat outdated look &amp; feel made me look again for alternatives, but when you have so many pictures at one provider already, it&#8217;s hard to move. The final nail in the coffin, however, was the merger of Picasa Web Albums and Google+. The galleries in G+, while certainly aesthetically appealing, were (at least in the first version of G+) incredibly bandwidth-hungry, and even required some insane hardware to play really smoothly. Besides, since I don&#8217;t use G+ much, I didn&#8217;t like the merger as my album was now directly tied to my G+ profile.</p>
<p>That&#8217;s when I decided I&#8217;ll implement my own gallery on my own server. Luckily, Google did (as many other things) the whole Picasa thing properly &#8211; the API to Picasa Web Albums is quite powerful and lets you customize the display of your galleries, while still retaining the ease of uploading images via Picasa, and preserving your old albums.</p>
<p>I will not walk you through the whole process of making the custom gallery, but instead, show you how I implemented it, and how I have tailored it to my needs. One thing I&#8217;d like to point out that I didn&#8217;t implement, as I don&#8217;t have a need for it, but is certainly doable &#8211; you can implement a multi-layer organization of your albums with the help of captions. Google lets you caption each image, and if you organize this caption into a nested structure, let&#8217;s say <strong>&#8220;subalbum1|subalbum2|subalbum3||caption&#8221;</strong>, you can create an &#8220;artificial&#8221; nested structure of your own!</p>
<p>Ookay, enough with the chatting. Let&#8217;s get to the code! <a href="https://developers.google.com/picasa-web/">Google Picasa Web Albums Data API</a> offers libraries for many popular web languages. As I only needed a relatively simple gallery, I picked PHP as the language.</p>
<p>First, let&#8217;s check the contents of my <strong>conf.php</strong> file.</p>
<h2>conf.php</h2>
<pre class="brush: php; title: ; notranslate">

&lt;?php
// ======================================
// CONFIGURATION FILE FOR PICASA GALLERY
// ======================================

// The Picasa service username
$userId = '&lt;your_google_id&gt;';

// Maximum thumbnail size (can be 32, 48, 64, 72, 144, 160). Cropped (c) or uncropped (u).
$thumbSize = '160c';

// Maximum image size can be 94, 110, 128, 200, 220, 288, 320, 400, 512, 576, 640,
// 720, 800, 912, 1024, 1152, 1280, 1440, 1600. These images are available as only uncropped(u) sizes.

$imgSize = '1280u';

// An array containing the albums that should not be shown (even though they are public!)
$hideAlbums = array('Scrapbook Photos', 'Warhammer army sale', 'Profile Photos');

</pre>
<p>As you can see from the config file, it&#8217;s pretty straightforward &#8211; first 3 options are needed to connect to Google Picasa Albums API, and to initialize parameters. The last option is my own; I have certain albums (I&#8217;m looking at you, Scrapbook Photos &amp; Profile Photos) that I don&#8217;t want to display under my gallery, as they&#8217;re default Google-created un-erasable albums that serve only G+.</p>
<h2>index.php</h2>
<pre class="brush: php; title: ; notranslate">

&lt;?php
// Include the config file
include &quot;./conf.php&quot;;

// Load the albums
$file = file_get_contents('https://picasaweb.google.com/data/feed/api/user/' . $userId . '?kind=album&amp;access=public&amp;thumbsize=' . $thumbSize);
$xml = new SimpleXMLElement($file);
$xml-&gt;registerXPathNamespace('gphoto', 'http://schemas.google.com/photos/2007');
$xml-&gt;registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;title&gt;zluftan.si ← Gallery&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;./style.css&quot; /&gt;
&lt;link rel=&quot;icon&quot; type=&quot;image/ico&quot; href=&quot;./favicon.ico&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:400,200&quot;&gt;
&lt;script src=&quot;jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

 &lt;!-- HEADER --&gt;
 &lt;?php echo file_get_contents('./header.html'); ?&gt;

 &lt;!-- BREADCRUMBS --&gt;
 &lt;div id=&quot;breadcrumbs&quot;&gt;
 &lt;ul&gt;
 &lt;li class=&quot;home&quot;&gt;&lt;i&gt;&lt;/i&gt;&lt;a href=&quot;./index.php&quot;&gt;&amp;#160;&lt;/a&gt;&lt;/li&gt;
 &lt;li&gt;&lt;i&gt;&lt;/i&gt;&lt;span&gt;Gallery&lt;/span&gt;&lt;/li&gt;
 &lt;/ul&gt;
 &lt;/div&gt;

&lt;!-- ALBUMS HOLDER --&gt;
 &lt;div class=&quot;albums&quot;&gt;
 &lt;?php
 foreach ($xml-&gt;entry as $feed) {
     // Skip the explicitly hidden albums
     if (in_array($feed-&gt;title, $hideAlbums)) {
         continue;
 }

 $group = $feed-&gt;xpath('./media:group/media:thumbnail');
 $a = $group[0]-&gt;attributes(); // We need thumbnail path
 $id = $feed-&gt;xpath('./gphoto:id'); // And album id for our thumbnail

 $summary = $feed-&gt;summary != '' ? $feed-&gt;summary : 'This album does not have any description.';
 if (strlen($summary) &gt; 228) {
     $summary = substr($summary, 0, 228) . '...';
 }
 $title = $feed-&gt;title;
 if (strlen($title) &gt; 47) {
     $title = substr($title, 0, 47) . '...';
 }

 echo '&lt;div class=&quot;album&quot;&gt;';
 echo '&lt;a href=&quot;./album.php?id=' . $id[0] . '&quot;&gt;'
 echo '&lt;img src=&quot;' . $a[0] . '&quot; alt=&quot;' . $feed-&gt;title . '&quot; title=&quot;' . $feed-&gt;title . '&quot; ref=&quot;' . $id[0] . '&quot; /&gt;&lt;/a&gt;';
 echo '&lt;div&gt;';
 echo '&lt;a href=&quot;./album.php?id=' . $id[0] . '&quot;&gt;&lt;h2&gt;' . $title . '&lt;/h2&gt;&lt;/a&gt;';
 echo '&lt;p&gt;' . $summary . '&lt;/p&gt;';
 echo '&lt;/div&gt;';
 echo '&lt;/div&gt;';
 }
 ?&gt;
 &lt;/div&gt;

 &lt;!-- FOOTER --&gt;
 &lt;?php echo str_replace('$YEAR', date(&quot;Y&quot;), file_get_contents('./footer.html')); ?&gt;

&lt;/body&gt;
&lt;/html&gt;

</pre>
<p>My albums are structured in the default Picasa 2-layer hierarchy; I decided I&#8217;ll have a main page, containing all my albums, and when clicking individual album, you&#8217;ll be redirected to a page dedicated and showing all the images from the selected album. Retrieving your album information is as simple as calling the php function <strong>file_get_contents(PICASA_URL) </strong>with correct parameters, and you can retrieve everything, from information about all albums, individual images from single album, etc.</p>
<p>You then simply parse the retrieved file (which is in XML format) and pull specific information you need from it. In my instance, I select the thumbnail image location, description name, and unique album id for each of the albums, and display them on the page. I then construct the links for each individual album by simply calling my &#8220;album display&#8221; .php page, while giving the unique album id as a GET parameter.</p>
<p>My individual album page is a bit unique. I have a lot of short, daily trips, and I didn&#8217;t want to create an individual album for each daily excursion, so I merged all the &#8220;daily&#8221; excursions into albums called &#8220;Summer 2012&#8243;, &#8220;Winter 2012&#8243;, etc. Inside those albums, however, I still want to retain structure of individual events. When using Picasa, I decided to prepend a header to all the captions from a single excursion, so inside those &#8220;general&#8221; albums, I have captions structured like this: <strong>&lt;dd&gt;.&lt;mm&gt;.&lt;yyyy&gt; &#8211; &lt;trip_title&gt;: &lt;actual image caption&gt;</strong>. Of course, this only holds true for albums called &#8220;Winter 2012&#8243; etc. To retain this &#8220;legacy&#8221; structure, there&#8217;s a lot of ugly mess in my .php code, but I hope it gives you an idea how you can implement a nested gallery structure for your albums I mentioned above. Let&#8217;s check <strong>album.php</strong>.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// Include the config file
include &quot;./conf.php&quot;;

// Retrieve the album id from the parameters
$albumId = $_GET[&quot;id&quot;];
if (empty($albumId)) {
	die;
}

// Load the contents of the specified album
$file = file_get_contents('https://picasaweb.google.com/data/feed/api/user/' . $userId . '/albumid/' . $albumId . '?kind=photo&amp;access=public&amp;thumbsize=' . $thumbSize .'&amp;imgmax=' . $imgSize);
$xml = new SimpleXMLElement($file);
$xml-&gt;registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');

// Check if special image description handling is required
$useSubAlbums = false;
if ($xml-&gt;title == 'Earlier stuff' ||
    preg_match('/^Summer (19|20)\\d{2}$/', trim($xml-&gt;title)) == 1 ||
    preg_match('/^Winter (19|20)\\d{2}\/(19|20)\\d{2}$/', trim($xml-&gt;title)) == 1) {
	$useSubAlbums = true;
}

// If we have sub albums, find all of them and save them into an ordered array, they should already be ordered (in Picasa)!
if ($useSubAlbums == true) {
	$subAlbums = array();
	foreach ($xml-&gt;entry as $feed) {
		$description = $feed-&gt;xpath('./media:group/media:description'); // Retrieve image description

		if (str_word_count($description[0]) &lt;= 0) {
			continue;
		}

		// This works whether the image has the &quot;sub-description&quot; or not =)
		$res = explode(':', $description[0]);
		$title = $res[0];

		if (array_key_exists($title, $subAlbums) == true) {
			$subAlbums[$title][] = $feed;
		} else {
			$tmp = array($feed);
			$subAlbums[$title] = $tmp;
		}
	}
} else {
	$subAlbums = array(&quot;tmp&quot; =&gt; $xml-&gt;entry);
}
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;title&gt;&lt;?php echo $xml-&gt;title; ?&gt;&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;./style.css&quot; /&gt;
&lt;link rel=&quot;icon&quot; type=&quot;image/ico&quot; href=&quot;./favicon.ico&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:400,200&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;lightbox/css/lightbox.css&quot; /&gt;
&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;lightbox/js/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;lightbox/js/lightbox-2.6.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;!-- HEADER --&gt;
	&lt;?php echo file_get_contents('./header.html'); ?&gt;

	&lt;!-- BREADCRUMBS --&gt;
	&lt;div id=&quot;breadcrumbs&quot;&gt;
		&lt;ul&gt;
			&lt;li class=&quot;home&quot;&gt;&lt;i&gt;&lt;/i&gt;&lt;a href=&quot;./index.php&quot;&gt;&amp;#160;&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;i&gt;&lt;/i&gt;&lt;a href=&quot;./index.php&quot;&gt;Gallery&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;i&gt;&lt;/i&gt;&lt;span&gt;&lt;?php echo $xml-&gt;title; ?&gt;&lt;/span&gt;&lt;/li&gt;
		&lt;/ul&gt;
	&lt;/div&gt;

	&lt;!-- IMAGES --&gt;
	&lt;?php
	if ($useSubAlbums == true) {
		echo '&lt;div class=&quot;subalbums_container&quot;&gt;';
	}

	foreach ($subAlbums as $albumTitle =&gt; $images) {
		if ($useSubAlbums == true) {
			$res = explode(' - ', $albumTitle);
			$trimmedAlbumTitle = $res[1];
			echo '&lt;div class=&quot;subalbum&quot;&gt;';
			echo '&lt;h2&gt;' . $trimmedAlbumTitle . '&lt;/h2&gt;';
		}

		// Show pictures
		echo '&lt;div class=&quot;images' . ($useSubAlbums == true ? '2' : '') . '&quot;&gt;';
		foreach ($images as $feed) {
			$group = $feed-&gt;xpath('./media:group/media:thumbnail'); // Let's find thumbnail tag
			$a = $group[0]-&gt;attributes(); // Now we need to get attributes of thumbnail tag, so we can extract the thumb link

			// Descriptions are tough nut
			$caption = 'Detail';
			$description = $feed-&gt;xpath('./media:group/media:description'); // Retrieve image description
			if (str_word_count($description[0]) &gt; 0) {
				if ($useSubAlbums == true) {
					if (strpos($description[0], ':')) {
						$res = explode(': ', $description[0]);
						$caption = $res[1];
					}
				} else {
					$caption = $description[0];
				}
			}

			$b = $feed-&gt;content-&gt;attributes(); // Now we convert &quot;content&quot; attributes into array

			echo '&lt;div class=&quot;image&quot;&gt;';
                        echo '&lt;a href=&quot;' . $b['src'] . '&quot; title=&quot;' . $caption . '&quot; data-lightbox=&quot;' . $albumTitle . '&quot;&gt;';
                        echo '&lt;img src=&quot;' . $a['url'] . '&quot; alt=&quot;' . $feed-&gt;title . '&quot; width=&quot;' . $a['width'] . '&quot; height=&quot;' . $a['height'] . '&quot;/&gt;';
                        echo '&lt;/a&gt;&lt;/div&gt;';
		}
		echo '&lt;/div&gt;';

		if ($useSubAlbums == true) {
			echo '&lt;/div&gt;';
		}
	}

	if ($useSubAlbums == true) {
		echo '&lt;/div&gt;';
	}
	?&gt;

	&lt;!-- FOOTER --&gt;
	&lt;?php echo str_replace('$YEAR', date(&quot;Y&quot;), file_get_contents('./footer.html')); ?&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>As you can see, I have special handling when it comes to sub-album structure. Nonetheless, the image info of the album is really easy to retrieve! I decided to use Lightbox for display of full-size images, and in case of sub-albums, I give each of the sub-album images its own <strong>data-lightbox</strong> attribute, so you have images corresponding to the same sub-album grouped together as a Lightbox album.</p>
<p>And that&#8217;s it! Header &amp; footer are just .html files for displaying header/footer. For some shameless self promotion, <a href="http://gallery.zluftan.si/">visit the gallery</a> (mind you, I&#8217;m still waiting for the designer to make it a bit nicer).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/09/yet-another-custom-google-picasa-api-gallery/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Drawing chart dynamically with Python and Matplotlib</title>
		<link>http://blog.e-svet.si/2013/09/drawing-chart-dynamically-with-python-and-matplotlib/</link>
		<comments>http://blog.e-svet.si/2013/09/drawing-chart-dynamically-with-python-and-matplotlib/#comments</comments>
		<pubDate>Tue, 10 Sep 2013 15:19:23 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Matplotlib]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=130</guid>
		<description><![CDATA[A while back my friend asked me if I could make him a dynamic chart for his thesis presentation. At first I didn&#8217;t know which tool I should use, but then a classmate suggested me to try matplot lib. As it turned out, it is quite easy to draw fancy dynamic chart with it &#8230; ...<a class="post-readmore" href="http://blog.e-svet.si/2013/09/drawing-chart-dynamically-with-python-and-matplotlib/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>A while back my friend asked me if I could make him a dynamic chart for his thesis presentation. At first I didn&#8217;t know which tool I should use, but then a classmate suggested me to try matplot lib. As it turned out, it is quite easy to draw fancy dynamic chart with it &#8230; Here is demo of final chart:<br />
<span id="more-130"></span></p>
<p><center><br />
<div style="width: 300px; max-width: 100%;"><!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->
<video class="wp-video-shortcode" id="video-130-1" width="300" height="240" preload="metadata" controls="controls"><source type="video/mp4" src="http://blog.e-svet.si/wp-content/uploads/2013/09/Cas.mp4" /><a href="http://blog.e-svet.si/wp-content/uploads/2013/09/Cas.mp4">http://blog.e-svet.si/wp-content/uploads/2013/09/Cas.mp4</a></video></div><br />
</center></p>
<p>First you need to install matplotlib. <a href="http://matplotlib.org/users/installing.html" title="Matplotlib installation instructions" target="_blank">Here</a> you can find instructions on how to do that.</p>
<p>Now, let take a look at how to plot that chart <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . First I needed to read data from .csv file into an array. Matplotlib takes in data in form of numpy array.</p>
<pre class="brush: python; title: ; notranslate">
print &quot;Read data ...&quot;
lines = [line.strip() for line in open('data.csv')]

time = []
vol = []
for i, x in enumerate(lines):
    t, v = x.split(',')
    time.append(t)
    vol.append(v)

final = []
final.append(time[:650])
final.append(vol[:650])

# create numpy array
data = np.array(final)
</pre>
<p>All you have to do now is configure matplotlib.pyplot to draw chart the way you want.</p>
<pre class="brush: python; title: ; notranslate">
fig1 = plt.figure()
plt.xlim(0, 70) # limit on X axis (modify to fit your data)
plt.ylim(0, 150) # limit on Y axis (modify to fit your data
plt.xlabel('Time')
plt.ylabel('Volume')
plt.title('The volume as a function of time')
</pre>
<p>Before we take a look at the interesting part, I would like to point out the following line</p>
<pre class="brush: python; title: ; notranslate">
l, = plt.plot([], [], 'r-')
</pre>
<p>Normally we pass data to plot function as array of points ([X], [Y]), but in the case of dynamic chart, we pass it empty arrays because we draw points dynamically. The third argument is string which determines how the points are drawn. First char means color, second char the representation of a point. &#8220;-&#8221; means line, but you can choose whatever char you want. <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot" title="Matplotlib plot function" target="_blank">Here</a> you can read more about plot function.</p>
<p>Ok, so far we haven&#8217;t seen anything special. Now let&#8217;s take a look at the part that does the magic. Matplotlib offers a <a href="http://matplotlib.org/api/animation_api.html#matplotlib.animation.FuncAnimation" title="matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs)" target="_blank">FuncAnimation</a> function to support animation of a chart. Animation is achieved by FuncAnimation repeatedly calling a function func. </p>
<pre class="brush: python; title: ; notranslate">
def update_line(num, data, line):
    line.set_data(data[0, :num], data[1,:num])
    return lines

line_ani = animation.FuncAnimation(fig1, update_line, 5000, fargs=(data, l), interval=50, blit=True, repeat=False)

print &quot;Starting drawing chart...&quot;
plt.show()
</pre>
<p>As you can see, we pass the function update_line to FuncAnimation and arguments to update_line which takes 3 arguments. The num argument represents sequence number, which we don&#8217;t need to pass explicitly. Each iteration we draw points from 0 to num, which animates our chart. So, that all, if your goal is to draw only lines for one type of data. But what if you want to have 2 different data types for Y axis? Let&#8217;s take a look how you can implement that. First you have to define two sets of data and two different axis:</p>
<pre class="brush: python; title: ; notranslate">
print &quot;Prepare data and chart...&quot;
data = np.array(final)
data2 = np.array(final2)

fig = plt.figure()
# add subplot to chart
ax = fig.add_subplot(111)
# first line is red
l, = ax.plot([], [], 'r-', label=&quot;Volume&quot;)

# define second axis
ax2 = ax.twinx()

#and set line color to blue
k, = ax2.plot([], [], 'b-', label=&quot;Temperature&quot;)

ax.legend([l,k], [l.get_label(), k.get_label()], loc=0)

plt.title('Volume and temperature in function with time.')
ax.set_xlabel(&quot;Time [seconds]&quot;)
ax.set_ylabel(&quot;Volume [liter]&quot;)
ax.set_ylim(0,150)
ax.set_xlim(0, 70)
ax2.set_ylabel(&quot;Temperature [Degrees celsius]&quot;)
ax2.set_ylim(0, 45)
ax2.set_xlim(0, 70)
</pre>
<p>I believe the above code shouldn&#8217;t give you trouble, because there were just some minor changes made. The main difference is that we add a subplot to the plot and set data to its ax. We define its color and label just like before. Then we specify second ax and repeat&#8230; </p>
<p>OK, we are almost there. The last thing we need to do is to modify our update_line function in a way that it accepts four parameters and pass them in FuncAnimation&#8217;s fargs argument.</p>
<pre class="brush: python; title: ; notranslate">
def update_line(num, data, line, data2, line2):
    line.set_data(data[0, :num], data[1,:num])
    line2.set_data(data2[0, :num], data2[1, :num])
    return line, line2

# pass all data in fargs argument
line_ani = animation.FuncAnimation(fig, update_line, 5000, fargs=(data, l, data2, k), interval=50, blit=True, repeat=False)
</pre>
<p>And that is it. <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Just in case if you have any problem with putting it all together, here is the full source</p>
<pre class="brush: python; title: ; notranslate">
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def update_line(num, data, line, data2, line2):
    line.set_data(data[0, :num], data[1,:num])
    line2.set_data(data2[0, :num], data2[1, :num])
    return line, line2

print &quot;Read data ...&quot;
lines = [line.strip() for line in open('data.csv')]
linesTemp = [line.strip() for line in open('cas_temp_ok.csv')]

pressure = []
time = []
for i, x in enumerate(lines):
    line = x.split(',')
    pressure.append(line[1])
    time.append(line[0])


temp = []
for i, x in enumerate(linesTemp):
    line = x.split(',')
    temp.append(line[1])



final = []
final.append(time)
final.append(pressure)

final2 = []
final2.append(time)
final2.append(temp)


print &quot;Prepare data and chart...&quot;
data = np.array(final)
data2 = np.array(final2)

fig = plt.figure()
# add subplot to chart
ax = fig.add_subplot(111)
# first line is red
l, = ax.plot([], [], 'r-', label=&quot;Volume&quot;)

# define second axis
ax2 = ax.twinx()

#and set line color to blue
k, = ax2.plot([], [], 'b-', label=&quot;Temperature&quot;)

ax.legend([l,k], [l.get_label(), k.get_label()], loc=0)

ax.set_xlabel(&quot;Time [seconds]&quot;)
ax.set_ylabel(&quot;Volume [liter]&quot;)
ax.set_ylim(0,150)
ax.set_xlim(0, 70)
ax2.set_ylabel(&quot;Temperature [Degrees celsius]&quot;)
ax2.set_ylim(0, 45)
ax2.set_xlim(0, 70)
plt.title('Volume and temperature in function with time.')

line_ani = animation.FuncAnimation(fig, update_line, 5000, fargs=(data, l, data2, k), interval=50, blit=True, repeat=False)
print &quot;Starting drawing chart...&quot;
plt.show()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/09/drawing-chart-dynamically-with-python-and-matplotlib/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
<enclosure url="http://blog.e-svet.si/wp-content/uploads/2013/09/Cas.mp4" length="1913220" type="video/mp4" />
		</item>
		<item>
		<title>Object Oriented Programming In PHP Part Two – Methods And Visibility</title>
		<link>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/</link>
		<comments>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/#comments</comments>
		<pubDate>Sun, 08 Sep 2013 09:26:30 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=94</guid>
		<description><![CDATA[In part one of Object Oriented Programming in PHP series I introduced fundamental terms of OOP (class, object and property). Today I will continue with explaining visibility keywords and methods. The methods differ from the functions in that they are declared in the class. They support different types of visibility just like properties do. Visibility ...<a class="post-readmore" href="http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>In part one of <a href="http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/" title="Object Oriented Programming In PHP Part One – Basics">Object Oriented Programming in PHP</a> series I introduced fundamental terms of OOP (class, object and property). Today I will continue with explaining visibility keywords and methods. <span id="more-94"></span></p>
<p>The methods differ from the functions in that they are declared in the class.</p>
<pre class="brush: php; title: ; notranslate">
public function myMethod() {
 
}
</pre>
<p>They support different types of visibility just like properties do. Visibility keywords are: <b><i>public, protected and private</b></i>. These keywords define from where we can access the method. Public methods can be accessed from anywhere while private methods can only be accessed in the same class they are defined in. There is also protected keyword, but we will take a closer look at it a bit later. First, let&#8217;s just take a look at the example of using public and private keywords.</p>
<pre class="brush: php; title: ; notranslate">
class MilitaryBaracks {
 
  //properties that we can access anywhere
  public $name = 'Mougli';
  public $weapon = 'rifle';
 
  //properties that we can access in this class only
  //in practice we usually prepend _ to the private methods for the clarity
  private $_ammunition = 10;
 
  //because we are inside the class, which defines property $_ammunition, we can access that property
  public function getAmmunition() {
    return $this-&gt;_ammunition;
  }
 
  public function shoot() {
    //keyword this means that we refer to property of an instance of class -&gt; an object
    //if soldier has any ammunition left, shoot and subtract one bullet
    if($this-&gt;_ammunition &gt; 0) {
      $this-&gt;_ammunition = $this-&gt;_ammunition - 1;
       
      return true;
    }
    return false;
  }
}
</pre>
<p>Let&#8217;s take a look at the above code in more detail. I&#8217;ve added a private property $_ammunition and methods getAmmunition() and shoot(). Because we cannot access a private property, we need to create a public method, which returns its value (getAmmunition()). Method shoot() reduces a number of bullets left each time it is called.</p>
<p>It is a common practice to prepend _ to the private properties. This helps to quickly differentiate private properties from public. Maybe all this is confusing, so let me clear it up a bit with an example. Let&#8217;s see what happens if I try to change and print out both properties.</p>
<pre class="brush: php; title: ; notranslate">
// we instantiate an object of type MilitaryBaracks
$soldier = new MilitaryBaracks();
 
// and print out its name (its property)
echo $soldier-&gt;name;
echo &quot;&lt;br&gt;&quot;;
// we change its name to &quot;Matic&quot;
$soldier-&gt;name = 'Matic';
echo $soldier-&gt;name;
echo &quot;&lt;br&gt;&quot;;
echo $soldier-&gt;_ammunition;
</pre>
<p>This is what we get:</p>
<div style="border: 1px solid #c9c9c9; padding: 10px; background-color: #f7f7f7;">
Mougli</p>
<p>Matic</p>
<p>Fatal error: Cannot access private property MilitaryBaracks::$_ammunition in C:\Programi\Wamp\www\script.php on line 42
</p></div>
<p>As you see we can access and modify public properties values just like variables, but we cannot do that with private ones. This is a mechanism to protect properties which values shouldn&#8217;t be changed from outside the class. But sometimes (actually quite often) we want to access the private properties from outside of class scope. In that case we create a public method like we did in our case. That way we can enforce the rules &#8211; what someone can do with that property. In our case we want to allow just reading so we created a getAmmunition() method.</p>
<pre class="brush: php; title: ; notranslate">
$soldier = new MilitaryBaracks();
echo &quot;Soldier has &quot; . $soldier-&gt;getAmmunition() . &quot; bullets.&quot;;
echo &quot;Soldier shoots.&quot;;
$soldier-&gt;shoot();
echo &quot;Soldier has &quot; . $soldier-&gt;getAmmunition() . &quot; bullets.&quot;;
</pre>
<div style="border: 1px solid #c9c9c9; padding: 10px; background-color: #f7f7f7;">
Soldier has 10 bullets.<br />
Soldier shoots.<br />
Soldier has 9 bullets.
</div>
<p>What does keyword <b><i>$this</b></i> means? With the use of $this keyword a class knows it&#8217;s operating on <b><i>this</b></i> object. For simplicity try changing word $this with &#8220;current object instance&#8221;.</p>
<p>When I was learning about OOP I was asking myself why would I set a method or property to private, if that just makes things more complicated. You have to write more code, because you have to write an additional method to access the property. Here is the answer. The thing with OOP is that we want to limit the access to class properties and methods as much as possible. This way me try to make code more clear and harder to use in a wrong way.</p>
<p>That is not so obvious in my case, because the example is to simple. But I hope it will become more clear in an upcoming posts, where we will roll up our sleeves and get to some more serious programming <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p>In next post of this series we will cover one of the most important but also more complex topic of object oriented programming, that is <b><i>inheritance</b></i>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>My Top 10 Favorite Eclipse Shortcuts</title>
		<link>http://blog.e-svet.si/2013/09/my-top-10-favorite-eclipse-shortcuts/</link>
		<comments>http://blog.e-svet.si/2013/09/my-top-10-favorite-eclipse-shortcuts/#comments</comments>
		<pubDate>Thu, 05 Sep 2013 15:25:55 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[eclipse]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=74</guid>
		<description><![CDATA[When I first started programming I didn&#8217;t realize how important role a good IDE plays. Initially, I just used notepad for a while. Although, I did write only few lines long scripts. After a while I switched to &#8220;professional&#8221; IDE, but I never tried to explore all of the options it was offering. I was ...<a class="post-readmore" href="http://blog.e-svet.si/2013/09/my-top-10-favorite-eclipse-shortcuts/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>When I first started programming I didn&#8217;t realize how important role a good IDE plays. Initially, I just used notepad for a while. <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Although, I did write only few lines long scripts. After a while I switched to &#8220;professional&#8221; IDE, but I never tried to explore all of the options it was offering. I was perfectly happy with code completion and code coloring. Oh, and I used a shortcut for commenting a line <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  And I was satisfied until I saw a colleague using all sorts of shortcuts. One of them was to generate getters and setters for class properties, which was the task I really hated, but always had to write all by myself. Well, enough of small talk, lets take a look at my top 10 choices &#8230;<span id="more-74"></span></p>
<h2>Shortcuts:</h2>
<ul>
<li>
<h3>1. Code Completion &#8211; Ctrl + Space</h3>
<p> Well, since the very beginning and up to now, this is indubitably my favorite shortcut and probably the most used by developers all over the world.</li>
<li>
<h3>2. Quickly Move Trough Text and Quickly Select Text &#8211; Ctrl + Arrow Left/Right and Ctrl + Shift + Arrow Left/Right</h3>
<p> Not exactly Eclipse shortcut, I don&#8217;t even know what its official name is, but I use it all the time to quickly move through words.</li>
<li>
<h3>3. Delete Line &#8211; Ctrl + d</h3>
<p> Deletes whole line or selected lines. Comes in very handy <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li>
<h3>4. Quick Fix &#8211; Ctrl + 1</h3>
<p> This combination offers tips to fix the compilation error. Very useful so you don&#8217;t have to move mouse cursor to that small sign at the beginning of the line.</li>
<li>
<h3>5. Open Type &#8211; Ctrl + T and Open Resource Ctrl + R</h3>
<p>Supports wildcards for searching through files.</li>
<li>
<h3>6. Generate Source Code &#8211; Shift + Alt + S</h3>
<p>            This shortcut opens a menu, which provides us with various different possible pieces of code Eclipse can generate for us. Some of the combinations are:</p>
<ul>
<li><strong>Create constructor using fields</strong> &#8211; Shift + Alt + S O</li>
<li><strong>Create constructors from superclass</strong> &#8211;  Shift + Alt + S C</li>
<li><strong>Generate getters and setters</strong> &#8211;  Shift + Alt + S R</li>
<li><strong>Override/implement methods</strong> &#8211;  Shift + Alt + S C</li>
</ul>
</li>
<li>
<h3>7. Move To Next/Previus Error &#8211; Ctrl + . and Ctrl + ,</h3>
<p> &#8211; This way one can quickly jump from one error/warning to another. The only problem with this shortcut is, that you can&#8217;t configure it in a way, that it would skip warnings. Or at least I wasn&#8217;t able to <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li>
<h3>Jump To Point Of Last Edit &#8211; Ctrl + Q</h3>
<p> &#8211; Jump to position in a file (even if you are in different tab), where you edited it the last time.</li>
<li>
<h3>Show Outline of Class &#8211; Ctrl + O</h3>
<p> &#8211; Offers a great way to quickly search for a method in a class or check out its methods.</li>
<li>
<h3>Show All Shortcuts &#8211; Ctrl + Shift + L</h3>
<p> &#8211; This one comes in handy <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  With this shortcut you can quickly find a combination you can&#8217;t remember at the moment <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</li>
</ul>
<p>Well, these are my favorites, but I use others as well. I would definitely put shortcuts like <em>format file, indent all lines, organize imports etc</em> , but I configured Eclipse to do these things on file save. That way is even faster and more effortless than using shortcuts <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . I hope I inspired someone to let the tool take care of tedious tasks like generating getters and setters and use extra time to be more productive &#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/09/my-top-10-favorite-eclipse-shortcuts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android class not found exception</title>
		<link>http://blog.e-svet.si/2013/09/android-class-not-found-exception/</link>
		<comments>http://blog.e-svet.si/2013/09/android-class-not-found-exception/#comments</comments>
		<pubDate>Wed, 04 Sep 2013 14:57:03 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Ant]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=54</guid>
		<description><![CDATA[Currently I am working on some Android project at work. Because the application we are developing communicates with server, we decided to pack common entities in .jar. That way our projects (server and android client) can share it and we avoid unnecessary code duplication. It is much easier to make changes as well as we ...<a class="post-readmore" href="http://blog.e-svet.si/2013/09/android-class-not-found-exception/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>Currently I am working on some Android project at work. Because the application we are developing communicates with server, we decided to pack common entities in .jar. That way our projects (server and android client) can share it and we avoid unnecessary code duplication. It is much easier to make changes as well as we don&#8217;t need to apply changes on different places in our code&#8230;<span id="more-54"></span></p>
<p>In our standard Java EE applications we use <a title="Apache Ant" href="http://ant.apache.org/" target="_blank">Apache Ant</a> for building project and deploying it to server. So I created a task which packed common classes into jar and copied it into libs folder in our android project. Now I was able to use common classes. I refactored some code and started Android project to test it. But build failed with <b>Class not found exception</b> &#8230; I checked again, all needed files were in jar, jar was in libs folder, classes were included in &#8220;private libraries&#8221; &#8230; After a bit of googleing I discovered that this might be because files were compiled with java 1.7, which Android doesn&#8217;t support, instead of 1.6. I was surprised, because I knew I set my java to 1.6 in eclipse workspace. Then I remembered that Apache Ant uses its own JRE. After changing JRE for Ant, everything worked fine <img src='http://blog.e-svet.si/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Here are short instructions on how to change ANT&#8217;s JRE:</p>
<p>First, right click on ANT task you want to run:<br />
<center><br />
<a href="http://blog.e-svet.si/wp-content/uploads/2013/09/ant_configure.png"><img class="size-medium wp-image-70 aligncenter" alt="ant_configure" src="http://blog.e-svet.si/wp-content/uploads/2013/09/ant_configure-300x217.png" width="300" height="217" /></a><br />
</center><br />
A new window will open. Select JRE tab and here you can set which JRE you want to use.<br />
<center><br />
<a href="http://blog.e-svet.si/wp-content/uploads/2013/09/change_jre.png"><img class="alignnone size-medium wp-image-71" alt="change_jre" src="http://blog.e-svet.si/wp-content/uploads/2013/09/change_jre-300x249.png" width="300" height="249" /></a><br />
</center></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/09/android-class-not-found-exception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object Oriented Programming In PHP Part One &#8211; Basics</title>
		<link>http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/</link>
		<comments>http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/#comments</comments>
		<pubDate>Sat, 24 Aug 2013 13:07:40 +0000</pubDate>
		<dc:creator>Matic Balantič</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=21</guid>
		<description><![CDATA[Usually, when people visit some website, they quickly form an opinion about it. They either like it, or they don&#8217;t. They find it well structured/organized, neat &#8230; or give up in search for a contact form &#8230; But nobody knows how good is the code, that is running the site &#8230; I believe that when ...<a class="post-readmore" href="http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>Usually, when people visit some website, they quickly form an opinion about it. They either like it, or they don&#8217;t. They find it well structured/organized, neat &#8230; or give up in search for a contact form &#8230; But nobody knows how good is the code, that is running the site &#8230;<span id="more-21"></span> I believe that when programming in PHP, one of the biggest steps towards writing clean and reusable code, is writing object oriented code. That is why I will dedicate a series of blog posts to this topic.</p>
<p>In the first part of this series I will try to lay out the most basic terms as simple as possible. I will describe what is an object, class and a property.</p>
<h2>Class</h2>
<p>Personally I see a class as some kind of a frame, with which help we generate objects. I would say that the best comparison is the one with a computer game e.g. old strategic game &#8211; Age Of Empires. Each building, that we create has a special task. Let&#8217;s say it generates soldiers. So, we create a class MilitaryBarack (a building in the game) and that class generates objects (soldiers in the game).</p>
<p>We create a class with a reserved word <strong>class ClassName and brackets {}.</strong></p>
<pre class="brush: php; title: ; notranslate">
class MilitaryBarack 
{
}
</pre>
<p>Even though this piece of code is perfectly legit, it is pretty useless, because it doesn&#8217;t do anything. We will fix that later.</p>
<h2>Object</h2>
<p>As I mentioned before, class generates, or more accurately, instantiates an object. But what is an object? Let me return back to game comparison. MilitaryBracket generates an object, a soldier, which has certain properties. In programming terms we say that an object is an instance of a class. We instantiate it with the use of a reserved word <strong>new</strong> plus the ClassName.</p>
<pre class="brush: php; title: ; notranslate">
$soldier1 = new MilitaryBaracks();
$soldier2 = new MilitaryBaracks();
</pre>
<p>When we create new instance of an object, it gets a unique identity. We can print object id and all of its properties with very useful function <b>var_dump();</b>.</p>
<pre class="brush: php; title: ; notranslate">
var_dump($soldier1);
var_dump($soldier2);
</pre>
<p>If we open that in browser, we will see the output</p>
<pre class="brush: php; title: ; notranslate">
object(MilitaryBaracks)[1] // note the object id in square brackets. Object has no properties yet.

object(MilitaryBaracks)[2]
</pre>
<h2>Properties</h2>
<p>All of this code is still quite useless. To make it more useful, we will add it some properties. Property of an object can contain different types of data. In our case, we could use a soldier&#8217;s name and a type of weapon he carries. To assign properties to an object, we have to declare it in its class. PHP offers three types of properties: <i>public, protected and private</i>. I will write more about the meaning of this words in next posts. For now it is enough to know, that they exist. We declare property with one of these reserved words plus a variable.</p>
<pre class="brush: php; title: ; notranslate">
// class
class MilitaryBaracks {
  // and its properties with defined default values
  public $name = 'Mougli';  
  public $weapon = 'rifle';
}
</pre>
<p>As you se, we defined two properties to MilitaryBaracks class. If we now instantiate and print a new object, we can see all values it holds. To access the property value we use an arrow (->).</p>
<pre class="brush: php; title: ; notranslate">
$soldier = new MilitaryBaracks();
echo &quot;Soldier &quot; . $soldier-&gt;name . &quot; carries a &quot; . $soldier-&gt;weapon;
</pre>
<p>These is were I stop for today. In <a href="http://blog.e-svet.si/2013/09/object-oriented-programming-in-php-part-two-methods-and-visibility/" title="Object Oriented Programming In PHP Part Two – Methods And Visibility">part 2</a> of these series I will write about methods and visibility.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/08/object-oriented-programming-in-php-part-one-basics/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Closing the browser window from Wicket</title>
		<link>http://blog.e-svet.si/2013/05/closing-the-browser-window-from-wicket/</link>
		<comments>http://blog.e-svet.si/2013/05/closing-the-browser-window-from-wicket/#comments</comments>
		<pubDate>Wed, 29 May 2013 21:05:32 +0000</pubDate>
		<dc:creator>Luka Murn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Apache Wicket]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://blog.e-svet.si/?p=17</guid>
		<description><![CDATA[On the project I was working on I stumbled upon a problem that when a user makes a certain action, the browser window needs to close. The internet is full of solutions for closing the browser window via JavaScript. This StackOverflow topic offers a great script example how to achieve the closing of the browser ...<a class="post-readmore" href="http://blog.e-svet.si/2013/05/closing-the-browser-window-from-wicket/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>On the project I was working on I stumbled upon a problem that when a user makes a certain action, the browser window needs to close. The internet is full of solutions for closing the browser window via JavaScript. <a href="http://stackoverflow.com/questions/57854/how-can-i-close-a-browser-window-without-receiving-the-do-you-want-to-close-thiadly">This StackOverflow topic</a> offers a great script example how to achieve the closing of the browser using simple JavaScript:</p>
<pre class="brush: java; title: ; notranslate">
function closeWindows() {
    var browserName = navigator.appName;
    var browserVer = parseInt(navigator.appVersion);
    //alert(browserName + &quot; : &quot;+browserVer);

    //document.getElementById(&quot;flashContent&quot;).innerHTML = &quot;&lt;br&gt;&amp;nbsp;&lt;font face='Arial' color='blue' size='2'&gt;&lt;b&gt; You have been logged out of the Game. Please Close Your Browser Window.&lt;/b&gt;&lt;/font&gt;&quot;;

    if(browserName == &quot;Microsoft Internet Explorer&quot;){
        var ie7 = (document.all &amp;&amp; !window.opera &amp;&amp; window.XMLHttpRequest) ? true : false;  
        if (ie7)
        {  
          //This method is required to close a window without any prompt for IE7 &amp; greater versions.
          window.open('','_parent','');
          window.close();
        }
       else
        {
          //This method is required to close a window without any prompt for IE6
          this.focus();
          self.opener = this;
          self.close();
        }
   }else{  
       //For NON-IE Browsers except Firefox which doesnt support Auto Close
       try{
           this.focus();
           self.opener = this;
           self.close();
       }
       catch(e){

       }

       try{
           window.open('','_self','');
           window.close();
       }
       catch(e){

       }
   }
}
</pre>
<p>Sadly, Firefox happens to be the exception here, as you cannot close it from the JavaScript. For other browsers, this script should work. Alright, but how do we hook this JavaScript to Wicket? First, we (obviously) have to include the .js file that contains the above script into our page. In Wicket 1.5, we then actually have multiple options for calling this JavaScript from code. Let&#8217;s say we have the following class:</p>
<pre class="brush: java; title: ; notranslate">
public class CloseWindowPage extends WebPage implements IHeaderContributor {

    private AjaxLink&amp;lt;Void&amp;gt; link1;
    private AjaxLink&amp;lt;Void&amp;gt; link2;

    private boolean closeWindow = false;

    @Override
    public void renderHead(IHeaderResponse response) {
        if (this.closeWindow)
            // This JS is executed after the page is completely loaded
            response.renderOnLoadJavaScript(&quot;closeWindows();&quot;);
    }

    public CloseWindowPage(PageParameters parameters) {
        super(parameters);

        if (!parameters.get(&quot;close&quot;).isEmpty())
            this.closeWindow = true;

        link1 = new AjaxLink&amp;lt;Void&amp;gt;(&quot;link1&quot;) {
            @Override
            public void onClick(AjaxRequestTarget target) {}
        };
        link1.add(new AttributeAppender(&quot;onclick&quot;, &quot;closeWindows();&quot;);
        add(link1);

        link2 = new AjaxLink&amp;lt;Void&amp;gt;(&quot;link2&quot;) {
            @Override
            public void onClick(AjaxRequestTarget target) {
                // Do some stuff...

                // Redirect to this page, set the parameters
                PageParameters params = new PageParameters();
                params.add(&quot;close&quot;, &quot;true&quot;);
                setResponsePage(CloseWindowPage.class, params);
            }
        };
        add(link2);
    }
}
</pre>
<p>I added two links to our sample page. The first option to call this JS function is not really much of a Wicket solution &#8211; basically, you create a HTML link (or a button), and set its <em>onclick</em> attribute to call our JavaScript function, like this:</p>
<pre class="brush: java; title: ; notranslate">&amp;lt;a href=&quot;#&quot; onclick=&quot;closeWindows();&quot; wicket:id=&quot;link1&quot;&amp;gt;Click me&amp;lt;/a&amp;gt;
</pre>
<p>To set the attribute of the element from Wicket, we use the <em>AttributeAppender</em> class, but in essence, it does the same as you would write the event handler in HTML. <em>link1</em> is an example of such behavior. My case, however, was different; when a user clicks a button/link in our application, the Wicket must do some background work, before the browser should close. In this case, the <em>AttributeAppender</em> will not work. We solve this problem by using the <em>renderHead</em> overriden method, and depending on the page parameter, we inject the JavaScript code calling our funcion into the <em>body onload</em> attribute. All we are left to do is to implement a link, override its <em>onClick</em> method, do the work we need and finally redirect to the same page, using the page parameter. This behavior is demonstrated by the <em>link2</em> component. I hope I offered some insight and threw an idea or two out there. Now to wait for Firefox to enable the window closing action&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.e-svet.si/2013/05/closing-the-browser-window-from-wicket/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
