Skip to content

Tag: programming

Python, flatten a list

Surprisingly python doesn’t have a shortcut for flatten a list (more generally a list of lists of lists of…).

I made a simple implementation that doesn’t use recursion and tries to be written clearly.

I get a element from a “notflat” list (a list that can have another lists on it). If a element is not a list we store in our flat list. If the element is still a list we deal with him later. The flat list always have only elements that are not a list.
To preserve the original order we reverse the elements at the end.

OpenPixels: simple sprite sheet with Processing

/**
 * Openpixels example in Processing.
 * This simple example of how to get a sprite 
 * from a sprite sheet.
 */

PImage bg;
PImage sprite_sheet;
PImage player;

void setup() { 
  // load images
  bg = loadImage("kitchen.png");
  sprite_sheet = loadImage("guy.png");
  
  /* The sprite size is 32x49.
     Look guy.png, the "stand position" is at (36,102). */
  
  player = createImage(32, 49, ARGB);
  player.copy(sprite_sheet, 36, 102, 32, 49, 0, 0, 32, 49);

  // set screen size and background
  size(bg.width, bg.height);  
  background(bg);
  
  frameRate(30);
}

void draw() { 
  background(bg);
  image(player, 100, 50);
}

See more at OpenPixels.

Atiaia early releases

This was a project that me and Marco Diego created during our graduation for the Computer Graphics course. It is a ray tracing engine build from scratch in C. It was great exercise of experimentation on how implement object-oriented design patterns in ANSI C. Later Marco continued it in his master’s degree thesis implementing more features.

Parts of the sources were lost during a disk failure in the forge we hosted the project. I found some early releases and packed them here for future use. It can be useful for someone studying C or how to implement a ray tracer.

Download: atiaia_sources_by_2006.zip

Enjoy it.

ps: with this project we won the 1st place project of class and maximum grade. 😉

Android screen height and width

Context ctx = getContext();
Display display = ((WindowManager)ctx.getSystemService(ctx.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

Yes, there are easier ways to retrieve the screen width on Android but there are cases that this long code is the only solution. You may already have the Context. WindowManager or the Display and so it would be smaller, but this code is more general.

PHP: array, all elements but first

$bric = array("Brazil", "Russia", "India", "China"); 
$ric = $bric; // array copy
$br = array_shift($ric); // left shift at $ric. $br stores "Brazil" 
print_r($bric); // $bric remains the same
print_r($ric); // $ric lost "Brazil"

Output:

Array
(
    [0] => Brazil
    [1] => Russia
    [2] => India
    [3] => China
)
Array
(
    [0] => Russia
    [1] => India
    [2] => China
)

Reference: PHP array_shift at php.net.

Java: invoking a method by name


import java.lang.reflect.*;

public class Foo {
	public void bar(int param){
		System.out.println(param);
	}	

	public static void main(String args[]){
		Object f = new Foo();
		try {
			Method m = f.getClass().getMethod("bar", int.class);
			m.invoke(f, 42);
		} catch (Exception e){
			System.err.println(e);	
		}
	}

}

$ java Foo
42

calling commands in Java

I don’t like the approach of calling native shell commands in any language instead of using multi platform libraries, but here is a little prof of concept Java program to call native commands.

import java.io.*;
import java.util.*;
public class Exec {
   public static void main(String args[]) throws IOException {
      Process proc = Runtime.getRuntime().e xec(args);
      BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      String line;
      while ((line = br.readLine()) != null) {
         System.out.println(line);
      }
   }
}

Usage:

java Exec VALID_COMMAND

Example:

$ java Exec echo hello
hello

ps: I had to write “e xec” instead of exec because it was triggering some very strange security protection in the blog engine here. If you need to compile this code change that. =P Also there’s no error handling, you should pass a valid command when executing this code.

Iterating over a HashMap

Iterating over a HashMap using the enhanced loop (foreach) in Java is a good way to keep your code smaller, more legible and usually more semantically coherent.

import java.util.HashMap;
import java.util.Map;

class Foo {}

public class Main {
	
   public static void main(String args[]){
      Map mHash;
		
      mHash = new HashMap();
      mHash.put((byte)1, new Foo());
      mHash.put((byte)2, new Foo());
      mHash.put((byte)3, new Foo());
		
      for(Foo f: mHash.values()){
         System.out.println(f.toString());
      }
   }
}

Getting an Android app source

Getting the Android’s AlarmClock application source from official repositories:

git clone git://android.git.kernel.org/platform/packages/apps/AlarmClock.git

To get the head version for an old platform like the 1.4 (codename donut), choose the correspondent branch using -o or –origin:

git clone git://android.git.kernel.org/platform/packages/apps/AlarmClock.git --origin donut

Getting enviroment information on Android

This is a simple program I wrote called Who Am I that shows informations about the device which it is running. Which can be useful for developers and maybe advanced users.

Download:

  • WhoAmI.tar.bz2 – Eclipse project. It’s configured for Android platform 4 (1.6) but should work without problems in newer Android platform versions.
  • WhoAmI.apk – Application installation Android package.

Main Activity source code:

package net.silveiraneto.whoami;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.widget.EditText;

public class WhoAmI extends Activity {
    private EditText mEditor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.whoami);

        mEditor = (EditText) findViewById(R.id.editor);

        Object[][] properties = {
        	{"Build.BOARD", Build.BOARD},
        	{"Build.BRAND", Build.BRAND},
        	{"Build.CPU_ABI", Build.CPU_ABI},
        	{"Build.DEVICE", Build.DEVICE},
        	{"Build.DISPLAY", Build.DISPLAY},
        	{"Build.FINGERPRINT", Build.FINGERPRINT},
        	{"Build.HOST", Build.HOST},
        	{"Build.ID", Build.ID},
        	{"Build.MANUFACTURER", Build.MANUFACTURER},
        	{"Build.MODEL", Build.MODEL},
        	{"Build.PRODUCT", Build.PRODUCT},
        	{"Build.TAGS", Build.TAGS},
        	{"Build.TIME", Build.TIME},
        	{"Build.USER", Build.USER},
        };

        for(Object[] prop: properties) {
        	mEditor.append(String.format("%s: %s\n", prop[0], prop[1]));
        }
    }
}

And its Android Manifest: