Archive for the 'Code' Category

#SCALA #NOTES Difference between list.foreach() and list.map()

Tuesday, June 11th, 2013
val l = List(1,2,3,4,5)
val lAfterForEach = l.foreach(x => x * 10)
val lAfterMap = l.map(x => x * 10)
println("Original List: " + l)
println("For each operates on each element, returns nothing:" + lAfterForEach)
println("Map is like foreach but returns new post-processed list: " + lAfterMap)

output:

Original List: List(1, 2, 3, 4, 5)
For each operates on each element, returns nothing:()
Map is like foreach but returns new post-processed list: List(10, 20, 30, 40, 50)

My Git Cheat-sheet

Tuesday, May 28th, 2013

I don’t know if it’s the crazy syntax, but for the life of me, I always need to come back to this cheat sheet, maybe you will too:

GIT CHEATSHEET

pull remote branch.

git fetch origin <branch-name>

push local branch to remote (with tracking)

git push origin -u <new-branch>

delete remote branch (who the fuck thought of this syntax?)

git push origin :<branch-name>   #deletes remotely
git branch -d <branch-name>      #deletes locally

clean untracked files (not folders)

git clean -f -x

synchronize with original repository on my forked repo

git checkout <branch I'm working on>
git pull <url of remote original repo> <remote branch, usually their master>

(it’s probably better to add the remote repo as another origin.)

How to avoid Android compilation/building issues – Setting up the Eclipse Buildpath correctly

Tuesday, May 21st, 2013

This post is the product of about 48 hours of not being able to work on what I was supposed to be working because I had to deal with build issues in Eclipse.

Hopefully If you follow these steps you will be able to solve some of the issues you may be facing right now with your build.

Some of these issues are:
- Class not found errors, even though your app was built and uploaded to your device.
- R.java not being compiled.
- *.aidl interfaces not generating .java files.

Screen Shot 2013-05-20 at 6.09.53 PM
1. Make sure your project’s compiler is set (as of the current android release) to be Java 1.6 compliant.

If you work on several java projects outside of Android, you may probably need to work with Java 1.7 compiler specs and by mistake you may have set it as the default for all projects.

This may cause a lot of stuff to break on your Android projects, including the generation of .java files out of .aidl files.

Make sure your Android project is using Java 1.6 (which is sadly all of what Android supports as of this writing)

2. Make sure the .jars you want to export are CHECKED in your Java Build Path > Order and Export settings

Screen Shot 2013-05-20 at 6.24.00 PM

After updating my Android SDK tools last friday, I wasted a whole day trying to figure out why on earth my application was giving me runtime Class Not Found errors on classes that exist inside android-support-v4.jar, even though I had all my jars placed on the proper standard “libs/” directory in my project.

The culprit was that the checkboxes along the .jars in my Order and Export tab were not checked.

3. Make sure your source folders are placed in the right order in your Java Build Path > Order and Export settings

Screen Shot 2013-05-21 at 12.13.46 PM

That right order for me has been:
1. My source folders at the top.
2. The “gen” folder right after the source folders.
3. My jars and Android dependencies at the the bottom.
4. Make sure “Android Dependencies” and “Android Private Libraries” are all the way at the bottom. I found out having them before the .jars causes issues when you want to attach source code to your .jars, eclipse will try to browse the .class inside the “Android Private Libraries” which does not allow for source code attachments, therefore not letting you see the source code you’ve attached on the build settings.

3. Make sure the .jar dependencies you need are saved inside the libs/ folder in your project.

That’s all I have for you.
Clean and Rebuild.

My First Raspberry PI Project: DIY ARM Video Game Console.

Thursday, April 4th, 2013

I got everything on amazon, didn’t pay for shipping (Prime member):

raspberry_pi_diy_game_console_nes_snes_sega_n64

So far I bought:
- Raspberry PI ($48)

- Raspberry PI case ($14)

- Power adapter ($2.25)

- SNES-like Controller with USB jack ($10.75)

- SanDisk SDHC 16GB class 6 (30mb/s) ($15)

I first intend to install Ubuntu ARM along with several video game console emulators for NES, SNES, SEGA, N64.

People at the Raspberry PI G+ Community have suggested instead to install arch linux and keep it light, I’ll go first for ubuntu since I know it well.

However I’m thinking that a more interesting option, given that it has an ARM processor is to install Android Jelly Bean on it and see if not only I can run game emulators on it, I’ll be running and testing FrostWire for Android on it.

Ever since I started developing FrostWire for Android I’ve thought that Android has everything in it to be a desktop operating system, maybe Raspberry PI’s will be the hardware I’ll use to prove my vision.

The idea is to end up with a nice tutorial on how to do this after I’m done so you can all do it. In the meantime I’ll keep posting updates.

java: How to get all the files inside a folder and its subfolders without recursion

Tuesday, March 19th, 2013

Most programmers will do this in a recursive fashion, but doing that is putting yourself at risk of hitting a stack overflow error, and it’s 20% slower (according to my tests). Here’s my first implementation of a method that will return just the files (cause I didn’t need the folders, you can always hack it to your needs). This is part of FrostWire for Android and FrostWire for Desktop, all the code is available under the GPL at our github repository.

/** Given a folder path it'll return all the files contained within it and it's subfolders
     * as a flat set of Files.
     * 
     * Non-recursive implementation, up to 20% faster in tests than recursive implementation. :) 
     * 
     * @author gubatron
     * @param folder
     * @param extensions If you only need certain files filtered by their extensions, use this string array (without the "."). or set to null if you want all files. e.g. ["txt","jpg"] if you only want text files and jpegs.
     * 
     * @return The set of files.
     */
    public static Collection<File> getAllFolderFiles(File folder, String[] extensions) {
        Set<File> results = new HashSet<File>();
        Stack<File> subFolders = new Stack<File>();
        File currentFolder = folder;
        while (currentFolder != null && currentFolder.isDirectory() && currentFolder.canRead()) {
            File[] fs = null;
            try {
                fs = currentFolder.listFiles();
            } catch (SecurityException e) {
            }
            
            if (fs != null && fs.length > 0) {
                for (File f : fs) {
                    if (!f.isDirectory()) {
                        if (extensions == null || FilenameUtils.isExtension(f.getName(), extensions)) {
                            results.add(f);
                        }
                    } else {
                        subFolders.push(f);
                    }
                }
            }
            
            if (!subFolders.isEmpty()) {
                currentFolder = subFolders.pop();
            } else {
                currentFolder = null;
            }
        }
        return results;
    }    

Here’s the FilenameUtils if you want the isExtension() implementation and it’s dependencies, you can always code your own there

jar dependencies if you plan to use the cling UPnP library in your android project

Tuesday, March 12th, 2013

This took me quite a while and lots of runtime errors, here are the minimum jars I needed to add to my project since now cling when used on android needs jetty, and damn jetty is broken into a thousand little jars for maximum modularity.

These are the one jars that I needed to not have any more runtime (class not found) errors

jetty-security-8.1.8.v20121106.jar
jetty-http-8.1.8.v20121106.jar
jetty-continuation-8.1.8.v20121106.jar
jetty-io-8.1.8.v20121106.jar
jetty-util-8.1.8.v20121106.jar
jetty-server-8.1.8.v20121106.jar
jetty-servlet-8.1.8.v20121106.jar
jetty-client-8.1.8.v20121106.jar
servlet-api-3.0.jar

How to enable adb logcat on Android 4 (debugging output)

Monday, March 4th, 2013

So you got a new Nexus or another Android running Android +4.2 and there’s no “Applications” menu entry in the settings menu.

No worries.

Go to the “About phone” entry at the bottom of settings, then scroll all the way down to the “Build number” menu entry.

Tap on it SEVEN times. (You’ll see funny “toast” messages come along)

When you go back to the main “Settings” menu, you will see a “{ } Developer options” entry.

Cheers

How to check if a Java Process is running on any local Virtual Machine programmatically

Wednesday, January 30th, 2013

Quick and dirty way to check if a Java Process is already running.
Useful if you need to run cronjobs periodically and you don’t know how long they might take, you can add this check at the beginning of your main, and it’ll look for all the local virtual machines that have a main class named like the “processName” string passed to it.

In other words, a quick and dirty programatic jps-like function you can add to your util toolset.

public static boolean isJavaProcessRunning(String processName) {
        boolean result = false;
        
        try {
            HostIdentifier hostIdentifier = new HostIdentifier("local://localhost");
            MonitoredHostProvider hostProvider = new MonitoredHostProvider(hostIdentifier);
            
            MonitoredHost monitoredHost;
            try {
                monitoredHost = MonitoredHost.getMonitoredHost(hostIdentifier);
            } catch (MonitorException e1) {
                e1.printStackTrace();
                return false;
            }
            
            
            Set<Integer> activeVms = (Set<Integer>) monitoredHost.activeVms();
            int thisProcessCount = 0;
            for (Integer activeVmId : activeVms) {
                try {
                    VmIdentifier vmIdentifier = new VmIdentifier("//" + String.valueOf(activeVmId) + "?mode=r");
                    MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmIdentifier);
                    if (monitoredVm != null) {
                        String mainClass = MonitoredVmUtil.mainClass(monitoredVm, true);
                        if (mainClass.toLowerCase().contains(processName.toLowerCase())) {
                            thisProcessCount++;
                            if (thisProcessCount > 1) {
                                result = true;
                                break;
                            }
                        }
                    }
                    
                } catch (MonitorException e) {
                    e.printStackTrace();
                }
            }
            
            
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (MonitorException e) {
            e.printStackTrace();
        }
        
        
        return result;
    }

Enjoy

[SOLVED] Kindle Fire HD not being detected by adb

Monday, November 26th, 2012

OSX Setup Modify your adb_usb.ini

Open the ~/.android/adb_usb.ini file for editing and add

0x1949
0x0006

Save the file.

Note: Make sure there is only one entry per line. If the file does not exist, create the file and make sure you have the required Android SDK prerequisites configured. Restart the ADB server and confirm your Kindle Fire is detected

Open a terminal shell and execute:

adb kill-server
adb start-server
adb devices

Locate Kindle Fire under the device list.

If your Kindle Fire is not being detected, you may need to reboot your computer or log out and log in for the changes to take effect.

Source: StackOverFlow

How to process thousands of WordPress posts without hitting or raising memory limits.

Tuesday, November 13th, 2012

So you need to write a script that processes all the posts in your wordpress database, you don’t need to use the stupid wordpress loop because you’re not writing web facing code, you might just need to fix some metadata on each one of the posts, but every time you iterate through your posts, no matter if you use the wordpress api, or even if you try to fetch the post IDs directly with MySQL and then call “wp_get_post($id)” after a few hundred posts your PHP interpreter dies when it uses all the memory you’ve given it.

You Google and every other clueless php-wordpress-noob that thinks himself of a programmer will give you the “Raise your PHP’s memory limit” or “Do it in parts” answer.

WTF is it with these noobs?

You a programmer used to real programming languages start to curse on the frustration of having to get dirty with this awful language and badly documented wordpress “API”. The noobs don’t understand that you might have to deal with tens of thousands of posts that couldn’t possibly fit in memory and you know…

is the solution to the problem is to free memory?

The WordPress geniuses created this WP Object cache which is used by default whenever you invoke “get_post()” or other functions. The bastards didn’t bother to mention it on the function documentations, nor they bothered to put a little note on how to disable it in case you didn’t need it. This is what happens when you get people that don’t think about all the possible uses of an API.

If you start iterating through a list of IDs, and you start invoking get_post($somePostId,’OBJECT’), and you start to print how much memory is available you will see how get_post() does keep the posts in memory, if you read get_post() and dig further you will see objects being cached in the in-memory WP Object Cache, a half-ass solution would be to invoke wp_cache_flush() every now and then:

  $post_ids_cursor = mysqli_query("select ID from wp_posts where post_status='publish' order by post_date desc");
  $n = 0;
  $last_memory_usage = memory_get_usage();

  while ($row = mysqli_fetch_row($post_ids_cursor)) {
    //this son of a bitch caches the post object.
    //nowhere on the WordPress documentation for the function it says so
    //http://codex.wordpress.org/Function_Reference/get_post
    $post = get_post($row[0],'OBJECT');

    $memory_usage = memory_get_usage();
    $delta_memory = $memory_usage - $last_memory_usage;
    $last_memory_usage = $memory_usage;
    
    echo "($n) " . $memory_usage . " ($delta_memory) \n";

    $n++;

    //flush php's cache every 100 posts, and let's see what happens.
    if ($n % 100 == 0) {
      wp_cache_flush();
      echo "Flush!\n";
    }
  }
//N post - Memory used - Delta memory used
(0) 30254136 (13984)  //start about 28.85MB
(1) 30262280 (8144) 
(2) 30269592 (7312) 
(3) 30277656 (8064) 
(4) 30285720 (8064) 
(5) 30293784 (8064) 
(6) 30301848 (8064) 
(7) 30309928 (8080) 
(8) 30318056 (8128) 
(9) 30326120 (8064) 
(10) 30334184 (8064) 
...
(93) 31054104 (8104) 
(94) 31062168 (8064) 
(95) 31070232 (8064) 
(96) 31078344 (8112) 
(97) 31086440 (8096) 
(98) 31094552 (8112) 
(99) 31102632 (8080) //already here at 29.66MB
Flush!
(100) 29816984 (-1285648) //bam we've freed 1.22MB with the flush call

However this solution is slow, WordPress will use and free unnecessary dynamic memory and it’ll check the cache with no luck every time you get a new object, which is the case of a linear scan like the one we have to do to batch process our posts.

Luckily someone in the wordpress team put a way to disable caching, so the real solution is…

To not use dynamic memory at all if you don’t need it

When you read the code of “wp_post_cache” every time $wp_object_cache->add() is invoked, that code always checks to see if caching has been suspended using a function called “wp_suspend_cache_addition()”

function add( $key, $data, $group = 'default', $expire = '' ) {
                if ( wp_suspend_cache_addition() )
                        return false;
...

This function can be used to turn off the freaking caching, this way you can iterate much faster through all your posts, every object fetched from the database will be kept in the stack of your loop and by not needing to flush or check the cache your processing will be much much faster.

This is how you turn it off:

  wp_suspend_cache_addition(true);

Hope this helped you process your posts in batch efficiently, leave a tip on the way out if I saved your ass.




  • Categories

  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • October 2012
  • September 2012
  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
  • March 2010
  • February 2010
  • January 2010
  • December 2009
  • October 2009
  • September 2009
  • July 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • September 2008
  • August 2008
  • July 2008
  • June 2008
  • May 2008
  • April 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007
  • February 2007
  • January 2007
  • December 2006
  • November 2006
  • October 2006
  • September 2006
  • August 2006
  • July 2006
  • June 2006
  • May 2006
  • April 2006
  • March 2006
  • February 2006
  • January 2006
  • December 2005
  • November 2005
  • October 2005
  • September 2005
  • August 2005
  • July 2005
  • June 2005
  • May 2005
  • April 2005
  • March 2005
  • February 2005
  • January 2005
  • December 2004
  • November 2004
  • October 2004