Category Archives: Programming

Check if object is in (multidimensional) array?

Python:

>>> arr = [[1,3],[2,4]]
>>> 2 in [x[0] for x in arr]
True
>>> 3 in [x[0] for x in arr]
False

PHP:

$arr = [[1,3],[2,4]];
var_dump(in_array(1, array_map(function($x){return $x[0];},$arr), true));
var_dump(in_array(3, array_map(function($x){return $x[0];},$arr), true));

Gives

bool(true)
bool(false)

Adding true for “strict mode”, to prevent false positives (1 == true, 0 == false)

Java:

int[][] arr = {{1,3},{2,4}};
System.out.println(Arrays.stream(arr).map(x -> x[0]).collect(Collectors.toList()).contains(1));
System.out.println(Arrays.stream(arr).map(x -> x[0]).collect(Collectors.toList()).contains(3));

Gives

true
false

Converting arrays to/from strings

Found myself using these functions in various prints to interfaces and whatnot, so here’s the elegant ways of creating comma-separated strings. The added bonus is that this method allows for separation of data in for-loops. Early on I’d usually add a separation manually in each step of the loop and finish by removing the extra separation at the end.

Python:

string = ",".join(['1','2','3','4'])
array = string.split(",")

PHP:

echo($str = implode(",", [1,2,3,4,5]));
var_dump(explode(",",$str));

Java:

With Apache Commons:

StringUtils.join(new String[]{"1","2","3"}, ',');

In Android:

TextUtils.join(new String[]{"1","2","3"}, ',');

Without requires a bit of setup with StringBuilder and a for-loop, unless you use JDK8:

String[] array = {"1", "2", "3", "4", "5"};
System.out.println(String.join(",",array));

Check out the new StringJoiner class for some interesting helper functions.

Basic API: Redirecting URLs

In the thetvdb.com-example we can see that the URL is formed as if that XML-file is stored in the data/series/267440/all/ subdirectory. This is not the case, much like it isn’t the case that all the articles in WordPress are stored in their own directories. Instead the server is most likely using a redirect mechanism using the .htaccess-file.

In our new basic API we’ll do the same thing. By placing a .htaccess-file in the “mediainfo/api” directory on our server we can tell the web server how to handle requests in that subdirectory. In this case the file will look like this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ../apihandler.php?path=$1&%{QUERY_STRING} [L]

The RewriteCond-lines tell us that if the requested filename is not a file (!-f) or a directory (!-d) we will redirect the request to ^(.*)$ ../apihandler.php?path=$1&%{QUERY_STRING} [L]. The $1 will contain the excess path, in this case “search/a movie title”, and the QUERY_STRING is the standard GET-variables (may in fact not be necessary, verify)

This is the first step in creating an API that looks clean. By splitting the path and removing the forward slash we can handle requests differently based on the fake directories being requested.

Designing a REST API from scratch

A REST API is “an architectural style consisting of a coordinated set of architectural constraints applied to components, connectors, and data elements, within a distributed hypermedia system”. It’s often used to share information using either a JSON or XML format, as seen in this example over at thetvdb.com.

Writing a small API from scratch requires a few things. First we need to figure out how to format the URL, then we have to create a PHP script that posts information (usually from a database) formatted in either XML or JSON. This script needs to accept part of the URL as a parameter, not unlike the traditional use of the $_GET variable. These basic tasks are good to start out with, and should result in a decent first attempt at an API. In followup-articles I’ll write about my experiences with the three topics.

Building a media info scraper and MKV tagger

XBMC uses scrapers to look up information about movies and TV-shows online in order for the media center to show more interesting information about the files in the library. Take the following image for example:

Detailed movie information provided by themoviedb.org via XBMC's scraper
Detailed movie information provided by themoviedb.org via XBMC’s scraper

Without the scraper you would only see the file name, and even that would probably look weird (MakeMKV saves files full of underscores for instance). So by downloading metadata from the internets you get a more professional-looking library, and you can even start browsing through your media using that metadata (listing all action movies and so on).

In music files you generally add all this info to the ID3-tag, and can even see that metadata in Windows Explorer. The same support doesn’t exist for movie files. MP4 uses the “XMP” system for metadata, and MKV uses some weird xml-specification that they haven’t even bothered completing yet. XBMC’s scraper doesn’t save any of the downloaded information to the files in any way either, meaning the data can’t really be seen anywhere else.

As a small project aimed at teaching myself some Python I’ve decided to code a scraper for both themoviedb.org and thetvdb.com. Here I get to learn how to best handle both JSON and XML, and how to handle web requests. I then plan on making a tagger-tool that tags an MKV-file with the downloaded metadata. This teaches me how to best use other programs within Python, and how to build XML-files.

The goal is to add metadata to MKV-files, but without media players that can actually read said metadata there won’t be much of a point to the aforementioned project. Therefore I plan on looking into possible ways of having XBMC “scrape” metadata from the files, and adding that functionality via an addon or by modifying the source code.

Here’s a link to the project’s home on Github. For my own benefit I will follow up with minor articles detailing design choices, interesting Python-tricks and so on.

Creating symbolic links by drag and drop in Windows

This is a work in progress, stuff in red are things I’ll elaborate on later

Sync apps like Dropbox work by having a folder on the computer that synchronizes with the cloud. However it is also possible to synchronize files outside this folder by using symbolic or hard links. Links are kind of like more advanced shortcuts that lets you link to content in other areas of the computer. For instance, syncing settings in some application on multiple computers can be done by linking them together via a dropbox-folder.

Creating links usually works by opening the command line and using the “mklink”-command. However it would be nice to be able to do the same thing by right clicking and dragging files as well. In this little project we figure out how to do that by means of “shell extensions”. The DLL-file we create in this project is available on Github, and some simple bash-scripts makes (un)installing easy.

The following post is basically just me rambling on about the things I did and learned (to force myself to rethink the steps). It might not even be educational, and I’ll add all the most relevant links at the bottom.

dragdropsymbol

Continue reading Creating symbolic links by drag and drop in Windows

Java generics and interfaces (A* example)

As part of a project where I’m building a simulator I wanted a pathfinding algorithm and looked around for an A*-library in Java. I found a few that I didn’t like the look of and decided to just make my own library. Luckily the algorithm is simple enough to basically copy-paste from the pseudocode found on Wikipedia, and it was during the rewrite I decided to really look into generics for the first time.

Below is an example of generics (note that the methods returns “T“, and not an int or string. Basically, if we send a specific object that implements AStarNode to these methods, we get an object of the same type back.

public interface AStarNode {
    public <T extends AStarNode> Collection<T> getNeighbours();
    public <T extends AStarNode> double getDistance(T node);
}

Continue reading Java generics and interfaces (A* example)