During my current personal project I needed so do something I have never done before, try and store an object as a string.

If you have ever developed for Android then you know the annoying fact that Bundles can’t store Objects. In my project, I wanted to save an object for when your Activity/Fragment is restored (onSaveInstanceState). But, I didn’t want to have 20 lines of disgusting code that said

bundle.putString("thisArgument","thisValue");

and I didn’t want to hardcode each variable’s assignment. In case I wanted to change the structure of my Class later on, I didn’t want to have to change the hardcoding for the putting AND retrieval of the variables. Now all I have to do is change how my fragment reads in the JSON data.

I accomplished this with the following code:


public static String objectToJson(Object obj) throws IllegalAccessException, IllegalArgumentException{
    String json = obj.getClass().getName() + " {";

    Field[] fields = obj.getClass().getDeclaredFields();
    for(int i = 0; i < fields.length; i++){
        String before = i > 0 ? ", " : "";
        fields[i].setAccessible(true);
        json += before + fields[i].getName() + ":" + fields[i].get(obj);
    }
    json += "}";
    return json;
}

This code will return the Object’s variables with the following structure:

ClassName {
    variable1:value1,
    variable2:value2,
    variable3:value3
}

The value of each variable will be the String representation of the variable, so if this variable happens to be another Object, just override the toString() function with the data you want to store as the value.

 

So I was able to use this onSaveInstanceState function to store my Object for when the Fragment restores:

MyClass myObject;
public void onSaveInstanceState(Bundle savedState) {
    super.onSaveInstanceState(savedState);

    savedState.putString("MySavedObject",objectToJSON(myObject));
}

Then, later on in my onCreateView function (onCreate if it is an activity, but I am using a fragment) you just check for a savedInstance then restore the data accordingly, just use any JSON parsing library to help out with the parsing.


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //All the View creation code and stuff...

    if(savedInstanceState != null){
        String savedJSON = savedInstanceState.getString("MySavedObject");

        //Here you would parse the JSON and construct the object again (A lot of libraries for that, but it is a simple enough method)
    }
}

This method is NOT all encompassing, it still only works amazingly with String values and other values like integers or booleans (just use casting), but if you have custom classes it can also be useful because you have the ability to override the toString function and return maybe some JSON data that you can then use to reconstruct that Object too.

It works for what I want, and I think it looks a million times cleaner than dealing with tens of put methods.

 

If you guys wanted a super simple method that parses the JSON data for you straight out, here is what I made to work with this:

public static ArrayList<HashMap<String,String>> parseSimpleJSON(String json) {
    ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String,String>>();
    String[] objects = json.split("\\}");
    for(int i = 0, len = objects.length; i < len; i++){
        String obj = objects[i];
        String[] parts = obj.split("\\{");
        HashMap<String,String> variables = new HashMap<String,String>();
        for(String variable : parts[1].split(",")) {
            String[] variableData = variable.split(":");
            variables.put(variableData[0].trim(), variableData[1].trim());
        }
        data.add(variables);
    }

    return data;
}

And here is what my reconstruction looks like:

//get 0th because there is only one object in this JSON string
HashMap<String,String> data= Utils.parseSimpleJSON(savedJSON).get(0);
myObject = new Object(data.get("variable1"),data.get("variable2"),data.get("variable3"));

 

-Brandon

JSData is an open source project I just started. I felt like there weren’t enough good libraries for data-visualization in jQuery and Javascript.

JSData extends jQuery and uses HTML5 Canvas to draw out the data. It is 100% interactive and I plan on making it even more interactive, to the point where you can edit the data from the graph itself.

Even though this is in ultra alpha, I felt like releasing it to the community as a baby would be good for educational purposes if not for implementation purposes yet.

 

Anywho, you can find this project on my GitHub account or:

HERE

 

-Brandon

On a project I am currently working on I needed to handle collision detection. I don’t have enough appendages to help me count the amount of times I have implemented collision detection. But this time it was a little different, I wanted to check whether or not someone was hovering over a segment of a circle. So I started to brainstorm possible algorithms to handle this particular kind of collision detection.

When I first started off I was thinking about it way too hard and way too mathematically instead of logically. I was trying to figure out the equation of a circle segment and blah blah blah. But after a little while of scribbling into my tiny notebook I came across a rather easy way to detect collision detection for circle segments.

Step 1

Are we in the circle? If we aren’t in the circle then we aren’t going to be in the segment.

This is a super qualification to check for, lets just call dX and dY the coordinate relative to the center of the circle:

if (dX*dX + dY*dY) > radius*radius:
    return false;

This snippet of code checks the squared distance of the coordinate with the squared radius (no need to do a square root because a square is present on both sides of the equation and square roots are expensive computing-wise)

Step 2

What angle is our point at? If it lies within the angles of our segment then we are in the segment since we just found out that we are in fact inside of the circle.

Using some vector math, we know that the arctangent2(y,x) is equal to the angle that the vector is at relative to the x-axis. This means we can find out the angle from the x-axis that our coordinate is at. This can be done with this code:

fi= atan2(dY,dX);
return  fi >= alpha && fi <= beta;

Here we call alpha the starting angle and beta the ending angle of the segment.

Here is an image:

Segment Collision Detection

In this image P is the point that was clicked and the resulting line and arrow is it’s vector. 0 is the starting point (unit circle!). If you aren’t familiar with Greek letters: the fish looking guy is Alpha, the “b” looking thing is Beta, and the O with a line through it is Fi.

Complete Algorithm in Semi-Pseudocode/Python:

function inCircleSegment(dX,dY,radius,alpha,beta):
    if(dX*dX + dY*dY > radius) return false;
    fi = atan2(dY,dX);
    return fi >= alpha && fi <= beta;

ONE LINE! (Because why not?):

return (dX*dX + dY*dY > radius) && (atan2(dY,dX) >= alpha && atan2(dY,dX) <= beta);

Seriously, don’t use that version though. At least save atan2(dY,dX) as a variable!

 

This was a fun little algorithm to come up with, one that is a lot easier to derive once you get your mind out of math and back into logic!

-Brandon

I have been having some fun with Array construction lately. You can do some really fun, elegant things with JavaScript. Here are some fun and cool looking snippets that make some pretty useful/awesome Arrays using abstraction.


makeEmptyArray(size):

function makeEmptyArray(size){
   return Array(size).join(' ').split(" ");
}

Before we do some awesome stuff, we need arrays that don’t have undefined elements. We do this by making an array, then joining and splitting the array so that its elements are not undefined (Array(size) makes an array with all undefined elements, this won’t do if we want to map the array). You can picture it this way: imagine you have 5 boxes, but these 5 boxes are collapsed and still need to be constructed before you can start putting things in them, and that is exactly what this function does.


fillArray(size,filler):

function fillArray(size,filler){
   return makeEmptyArray(size).map(function(){ return filler; });
};

Here we have a simple function that fills in the empty array with some filler.


zeroes(size):

function zeroes(size){
   return fillArray(size,0);
}

This is just an example of a function that would be practical.


mapArray(size,mapFunc):

function mapArray(size,mapFunc){
   return makeEmptyArray(size).map(mapFunc);
}

Here is a really fun function that is also really simple in design. It allows you to make an extremely custom array with just a few lines of code.


range(start,end):

function range(start,end){
   return start>=end ? [] : mapArray(end-start, function(){ return start++; });
}

This small function will create an array from start to end with end being exclusive, and if there is a problem with the indexes it just returns an empty array.

In practice, range(0,7) would return [0,1,2,3,4,5,6].


grid(width,height):

function grid(width, height, gridFunc){
   return mapArray(height, function(){ return mapArray(width, gridFunc); });
}

Don’t you love abstraction? This function makes a grid with a width width and a height height using gridFunc as the manner of filling in the elements.

Using this, a simple line of code can fill in a grid of zeroes:

var zeroRectangle = grid(7,4,function(){ return 0 });

Identity Matrix

function identityMatrix(n){
   var i = 0;
   function gridFunc(value,index,array){
      var y = Math.floor((i++)/n);
      return index == y ? 1 : 0;
   };
   return grid(n,n,gridFunc);
}

I think this function shows just how powerful abstraction can be when it comes to arrays.


Here are all of the functions from this post in one code snippet.

All of the code:

function makeEmptyArray(size){
   return Array(size).join(' ').split(" ");
}

function mapArray(size,mapFunc){
   return makeEmptyArray(size).map(mapFunc);
}

function range(start,end){
   return start>=end ? [] : mapArray(end-start, function(){ return start++; });
}

function grid(width, height, gridFunc){
   return mapArray(height, function(){ return mapArray(width, gridFunc); });
}

function identityMatrix(n){
   var i = 0;
   function gridFunc(value,index,array){
      var y = Math.floor((i++)/n);
      return index == y ? 1 : 0;
   };
   return grid(n,n,gridFunc);
}

Isn’t abstraction fun?

-Brandon Layton

Link: https://github.com/proflayton/pyMediaManip

This was really just a challenge for myself. I wanted to see if I could interpret a .GIF file at the lowest level possible, its binary. This library is a work in progress that I have been unable to touch for a little bit, but it was a fun project I got started and hope to finish eventually.

Right now it works for all GIFs , even animated GIFs , excluding GIFs that have a data stream clear or local color tables. Those features have yet to be implemented.

I created a system for a client that allows for “targeting” similar to Fallout, where if your crosshairs are over the NPC then their name will pop up. I also created a system for fully customizable conversations that can be chained how ever you want and it also allows for scripts to be opened on certain replys (great for shopkeepers or something). The conversations is 100% customizable and allows for different textures, that is why my version is kind of odd looking because I am not a texture artist. All of this was done in C#.ImageImage

Follow

Get every new post delivered to your Inbox.