Directories and Environment

Note: The import statements are repeated for every code sample just to show you what modules you need. In real operation, of course, the modules need only be imported once.

Check whether a file/directory exists:

import os
print("File /tmp/test2 exists? " + str(os.path.exists("/tmp/test2")==False))

Get the path to the current file (with the help of the magic variable __file__)

import os
os.path.abspath(__file__)

Determine directory of a file (similar to dirname Bash command):

import os
directory = os.path.dirname("/tmp/test/testfile.txt")
print(directory) # yields /tmp/test

Copy a directory recursively (contents of “/tmp/test1/”  to “/tmp/test2″):

import shutil
shutil.copytree("/tmp/test1", "/tmp/test2")

Remove a directory recursively:

import shutil
shutil.rmtree("/tmp/test2")
# The above call will produce an error if the directory exists, the following command ignores errors:
shutil.rmtree("/tmp/test2", ignore_errors = True)

Export the following mapping to the environmentCSX_HOME=/home/user/citeseerx:

import os
os.environ["CSX_HOME"]="/home/user/citeseerx"
print(os.environ["CSX_HOME"])

Change the current working directory (CWD) temporarily and then return to the original working directory:

import os
old_directory=os.getcwd()
# Switch to new working directory
os.chdir("/tmp")
# do something, e.g.
print(os.getcwd()) # yields /tmp
# And switch back to the original wd
os.chdir(old_directory)

Create a directory  (cf. mkdir -p):

os.makedirs("/tmp/newdir")
os.makedirs("/tmp/newdir", <tt>0744</tt>) # with unix-like permissions (r:4, w:2, x:1)

Files

Write a raw string to the file /tmp/testfile.txt:

open("/tmp/testfile.txt", 'w').write("Hello World, this is my file contentn")
# verify content e.g. with Bash command: cat /tmp/testfile.txt

Read file to string:

content = open("/tmp/testfile.txt", 'r').read()
print(content) # yields "Hello World, this is my file content" for the previous example

Copy file to directory:

import shutil
shutil.copy("/tmp/testfile1.txt", "/tmp/testdir")

Renaming a file:

import os
os.rename("a.txt", "b.txt")

Process Management

Exit with a certain exit code (here: 1):

import sys
sys.exit(1)

Start a subprocess (e.g. a Bash script):

import subprocess
subprocess.call("/bin/ls") # will list the files in the current directory

Links

What is Reblogging?

  • …mechanism which allows users to repost the content of another user’s post with an indication that the content originates from another user.
  • Invented in an R&D project at Eyebeam Art and Technology Center (before 2005) and made public as open source software.
  • First used/adapted by Tumblr (2007), aftwards by Twitter (2008, “Retweet”) and Facebook (“Share”/Re-Sharing)
  • Reblogs may be seen as a virtual currency, where somebody who reblogs your content increases your virtual account (Wikipedia – Attention Economy, Wikipedia – Whuffie).
  • Source: Wikipedia – Reblogging

What is Pingback?

  • … method to notify authors when their content is cited on another platform, i.e., author A writes an article, author B cites the URL to this article and author A gets notified.
  • Supported by blog plattforms (e.g. WordPress) and some Content Management Systems (e.g. Drupal, Joomla)
  • Related: Trackback, Refback, Linkback
  • Source: Wikipedia – Pingback

The following code showcases how we can instantiate collections inside application context files in Spring. I suppose we want to use a class DummyContainer as a bean and we instantiate the following collection type properties of this class (assume the appropriate setters are given). The class MyBean is defined elsewhere and its actual properties do not matter here. We use two instances of the class in order to demonstrate reference values and inplace bean definitions:

  • java.util.List<Object> aList;
    • Content:  [“Hello World”, new Double(1.3), new MyBean(), new MyBean()]
    • XML element: <list/>
  • java.util.Map<String, Object> aMap;
    • Content: [[“Item 1”, “Hello World”],[“Item 2”, new Double(1.3)],[“Item 3”, new MyBean()],[“Item 4”, new MyBean()]]
    • XML element: <map/> and <entry/>
  • java.util.Properties properties;
    • Content: [[“Prop 1”, “Value 1”]]
    • XML element: <props/> and <prop/>
  • java.util.Set<Object> aSet;
    • Content: [“Hello World”, new Float(1.3), new MyBean(), new MyBean()]
    • XML element: <set/>

This is how the context  file looks like:

<beans>
  <bean id="myBean" class="MyBean"/>
&nbsp; <bean id="dummyContainer" class="DummyContainer">
    <property name="aList">
      <list>
        <value>"Hello World"</value>
        <value>1.3</value>
        <ref id="myBean"/>
        <bean class="MyBean/>
      </list>
    </property>
    <property name="aMap">
      <map>
        <entry key="Item 1" value="Hello World"/>
        <entry key="Item 2" value="1.3"/>
        <entry key="Item 3" value-ref="myBean"/>
        <entry key="Item 4"><bean class="MyBean/></entry>
      </map>
    </property>
    <property name="properties">
      <props>
        <prop key="Prop 1">Value 1</prop>
      </props>
    </property>
    <property name="aSet">
      <set>
        <value>"Hello World"</value>
        <value>1.3</value>
        <ref id="myBean"/>
        <bean class="MyBean/>
      </set>
    </property>
  </bean>
</beans>

Links

  • Spring 3.1.x Reference – Section 4.4.2.4 Collections
  • mkyong‘s summary of the collection elements (actually nicer than my entry here :-))

Grundlagen-Videos (YouTube)

Blogs und Webseiten

Projekte

When moving a legacy project from Ant to Maven, I needed to change the default source (default: src/[main|test]/java) and resources (default: src/[main|test]/resources) directories in Maven. These settings may be configured in the <build> element of the project’s pom.xml.

  • <sourceDirectory> the directory where the sources of your application are stored
  • <testSourceDirectory> the directory where the sources of your test cases are stored
  • <resources> the resources of your main application
  • <testResources> the resources needed only by your test cases

The relevant part of the pom.xml in Maven 2.1.x and above looks like this (with default values):

<project>
  <!--[...]-->
  <build>
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirect
    <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>    
    <resources>
      <resource>
        <directory>${project.basedir}/src/main/resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>${project.basedir}/src/test/resources</directory>
      </testResource>
    </testResources>
    <!--[...]-->
  </build>
  <!--[...]-->
</project>

Links

The Eclipse IDE offers to perform certain actions each time you save Java source code. These so-called Save Actions can be found here:

Window -> Preferences -> Java/Editor/Save Actions

The following is a list of my personal favorites:

  • Format Source Code
    Make sure you protect your comments from being formatted. Else the Eclipse formatter may be quite frustrating. Shortcut Ctrl + Shift + F.
  • Organize Imports
    In most cases this feature allows you to save time when refactoring the code. May also be performed manually using Ctrl + Shift + O.
  • Add ‘this’ qualifier to unqualified field accesses/Add ‘this’ qualifier to unqualified method accesses
    If you always qualify class members with the this qualifier, you can easily review, e.g. how difficult it may be to refactor out a method. In the rare case that you open your Java sources in a text editor, you may immediately recognize what variables are class members and what methods are static/non-static.
  • Convert control statement bodies to block except for single return or throw statement
    Often, I am tempted to not wrap one-line blocks below if/else with braces. But it is possible that you will need to add a second line and if you are in a hurry, you will not recognize that the second line is indeed outside the scope of the if/else.
  • Add final modifier to private fields/method parameters/local variables
    To my opinion, the final qualifier is a valuable means to make the code more expressive in terms of “what will not change from here on”. Unfortunately, there is nothing like the const keyword in C++ available for Java.
  • Add missing ‘@Override’ annotations
    Similar to the argumentation for final.

Links

The social network SchülerVZ which is targeted at young students is going down on April 30, 2013. I wanted to save some of my friends’ photos and searched the web for some appropriate tool.

I tried the Bilderdownload v2 from svz-styles.com and a Fotoalbum Download für StudiVZ, SchuelerVZ & MeinVZ 1.09 from userscripts.org both  of which did not work for me. So I needed to create a solution on my own.

Custom-Made Approach

The following description is only tested with the Altes SchülerVZ  theme. When I took a look at the HTML code around photos (<div class=”photo”>), I recognized that it is not possible to right-click a photo in Firefox and select Save Image As… because the context menu has been disabled:

<img id="photoDetailBig" oncontextmenu="return false;" 
alt="" src="http://img-a5.pe.imagevz.net/[...].jpg" 
onload="imageWrapperResizer();">[...]</img>

While it is perfectly reasonable that the SchülerVZ guys want to protect their users’ personal rights, in the current circumstances, I personally find it legitimate to circumvent this restriction. Disclaimer: You are responsible for your doings. Ask your friends first, if you may download their photos.

Preparations: Install GreaseMonkey

For Firefox there exists a nice add-on called Greasemonkey which allows you to execute arbitrary JavaScript code on sites of your choice. The add-on can be downloaded from the official Firefox add-on site. (Click here for immediate installation).

Installing the Userscript

After the  installation of Greasemonkey is complete, you still need the script which unlocks the context menu for photos. I uploaded the script to userscripts.org. If the automatic installation does not work for you, you may manually install the script:

  1. Select Tools -> Greasemonkey -> New User Script…
  2. Set the name to Enable SchülerVZ Photo Download (Altes schülerVZ theme)
  3. Set the namespace to http://userscripts.org/scripts/show/165246
  4. Set the includes to http://www.schuelervz.net/Photos/View/*
  5. Confirm with OK.
  6. Copy the whole code into the editor which pops up and save it.

When you now open up a photo, you will be able to open the context menu and save the image.

Links

You can delete a remote branch topic_branch located in the repository origin using the git push command:

git push origin :topic_branch

The semantics is that you push an empty reference (before the colon) to the remote branch and therewith delete it.

Links

It may happen that you create a local branch and forget to make it track a remote branch. We can make up for this by using the –set-upstream-to option of the git branch command. Say we are currently on branch issue123 and we want to make this branch track origin‘s issue123 branch.

For Git versions >=1.8

git fetch # may be necessary in order to get origin/issue123
git branch --set-upstream-to=origin/issue123 issue123

For Git versions <= 1.7

Mind the switched order of arguments. This command will also work in later Git versions:

git branch --set-upstream issue123 origin/issue123

 Links

When I update a Maven project in Eclipse Juno (m2eclipse version 1.2.0) I sometimes get back an error message reporting:

“Updating Maven Project”. Unsupported IClasspathEntry kind=4

There are some strategies on how to solve this. The most successful in my case is to perform the following steps:

  1. Disable the Maven Nature of the project by Right-clicking the project and selecting Maven -> Disable Maven Nature
  2. Fire up a terminal in the projects directory and run mvn eclipse:clean  (Important: the project still needs to be open in Eclipse!)
  3. Re-enable the Maven Nature of your project by Right-clicking the project and selecting Configure -> Convert to Maven Project

If you now update the project again (Right-click on project -> Maven -> Update Project), everything should run smoothly. If not, you may find additional hints in the stackoverflow question where I drew this solution from.

Alternative

Another successful solution to this problem is to open up the .classpath file of your project and remove all entries with attribute kind=”var”.

Links