Programming

Etsy API Fail – Well, Ok maybe not.

I’m working on a new project which uses Etsy’s API. As far as APIs go, theirs is pretty neutered. There’s no user authentication whatsoever so the only data you can get from it is what’s available to the general public. Since you can’t authenticate, you certainly can’t write any data, so things like allowing users to add Etsy items to their favorites aren’t possible.

Working with their API I found another “quirk.” If you try to getUserDetails on a username which doesn’t exist it won’t return null or false or an empty object. Instead, it responds with HTTP status code 404.

Wait, what?

This means I have no way of differentiating between an error in my URI and a simple case of a defunct username. In fact, this behavior is contrary to what Etsy’s own documentation suggests. Their sample code dies on any status besides 200, which makes sense although you’d probably want to handle the error more gracefully. Now I have to look up the status code and try to guess whether I got the 404 because of a malformed URI or because the username was wrong. That will make debugging super fun!

404 is an HTTP error. A correctly formed API query with a null result should not return a 404. Argh. In english terms, a 404 means “I don’t have the information you’re looking for.”

You could argue that Etsy simply doesn’t have the userinfo for that user, because it doesn’t exist, and therefore 404 is appropriate. But that’s a cop out. Etsy DOES know that user’s info: it’s empty. If I’m querying a database of all known users, and getting back a subset of said users based on my input, Etsy’s response should be “there aren’t any matching users” not “I don’t have that information.” A 204 error would be more appropriate.

Edit: Apparently this is becoming a common thing.  Although I haven’t seen it with any other APIs I’ve worked with. And let me state for the record that just because other people do it doesn’t make me think it’s any less of a dumb idea.

Edit again: Someone who is less sleep deprived than myself pointed out that the body of the 404 responses does contain useful information, which I had missed earlier. So in this case I will concede to being wrong, although I am still not a fan of this approach because it means my script relies on the exact English wording of their error messages. Carry on.

Programming

Most Useful CS Classes?

One thing that’s clear about my quest for higher education is that I’m going to need some undergraduate level classes to fill in the holes of my self-taught education. I’ve been looking through course catalogs for various programs to get an idea of what I’m missing, but it’s hard to tell what would be valuable and what’s just filler.

For folks who got viagra online without prescription an undergraduate degree in computer science, what classes / topics did you actually find useful? I know I need to brush up on my math, I haven’t done anything resembling a proof in about a decade. Most of the programming I’ve done has been for the web. Lots of figuring out when to access and how to store various bits of data, but not much recursion. I’m used to speed being a factor of how often you hit the database, not how you’re manipulating the data.

I’ve found a community college locally where I can pick up some classes on the cheap, including one called “Language Independent Design Tools” which covers problem solving techniques, modular design, how to perform a proper trace, subroutines, etc. It could be either really useful or entirely too general, it’s hard to tell from the course description. It requires “Intro to C#” as a co requisite, which sounds like a lot of “this is a variable, this is a function.” Bleh.

Speaking of classes!

I’m teaching Intro to PHP at NYC Resistor in December. It covers the basics of the language, and doesn’t require any previous programming experience. Working knowledge of HTML is a big help, but not strictly required. You can sign up online, the class is taught at the NYCR Hackerspace in Brooklyn.

I’m thinking of teaching the GD image class again, because it’s fun to draw graphs and calculate resizing, shifts, etc. But the last one wasn’t very well attended so I’m not sure.

Programming

Android: Hello Circle

Note: This article is really old. It is here for posterity only. You should really find a more current tutorial.

I’ve been a little frustrated by the lack of Android tutorials. I got a Hello world going, and found that most of the few tutorials I could find were WAY more complicated than what I want to start with. GPS, map overlays, to-do lists, etc, which is great and all but I want to start simple and work up from that. So I set out to build “Hello Circle,” a program which drew a dot on the screen wherever you touched it. After about 12 hours of beating my head against Eclipse, the Android SDK, and the frequently incorrect Android documentation I got it working. So here’s a tutorial.

Setting up the environment I’m going to assume you already successfully completed the Hello World tutorial. Which means you’ve got yourself an IDE (probably Eclipse), the Android SDK, and the ADK (Android Development Kit) which is a plugin for Eclipse to help keep things in order. If  you haven’t done that yet follow these instructions and pray everything works as planned. I’ll see you in a few hours. Create a project just like you did for Hello World. Creating the ViewGroup In order for anything to display on the screen you need to create a view. In the Hello World tutorial you created a TextView. We’re going to use the XML setup for creating our view, and rather than creating a TextView we’re going to use a FrameLayout, which is acutlaly a view group. Open up /res/layout/main.xml and plop in this fine code (obliterating anything that may be there):



This, when it’s called in our code, will create a FrameLayout view with an id of “main view,” a width/height that fills the screen, and a neon green background. The hex color code for the background includes the alpha channel (the first to FFs). Setting the contentView to our XML Head over to your main class and call setContentView on your layout. Your code should look something vaguely like this:

import android.app.Activity;
import android.os.Bundle;

public class RoboTown extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
}

If you run your code at this point you should get a big green background which does nothing. Hooray! Creating the Ball class Now we want to create a circle. Actually we want to create a lot of circles. So the first step is to create a new class called Ball. Right click on your project’s main class in the Package Explorer (on the left) and click New > Class. Give it the name Ball and click Finish. Our ball is actually going to be another view. What? Yeah. It’s a view. All of our Ball views will eventually go into our FrameLayout, but we’ll worry about that later. So first, modify your Ball class so that it extends View, since it’s a new type of View, and while you’re at it go ahead and import some of the things we’ll need for drawing:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

public class Ball extends View {

}

In order to draw a ball we need a handful of things: a Canvas to draw them on, x and y coordinates to place the center of the ball, the radius, and Paint to give it color. So we’ll start by establishing those (I hid the imports for the sake of clarity, you should leave yours there):

public class Ball extends View {
    private final float x;
    private final float y;
    private final int r;
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}

In the last line we create a new Paint object, creatively called mPaint. A Paint contains information like colors, text sizes, etc, which affect the appearance of the drawing. So far we haven’t assigned any of those things to the Paint, we’ve just created it. Now we need to write the Ball constructor, which is the method to be called whenever we create a new ball:

    private final int r;
    private final Paint mPaint = new    Paint(Paint.ANTI_ALIAS_FLAG);

    public Ball(Context context, float x, float y, int r) {
        super(context);
        mPaint.setColor(0xFFFF0000);
        this.x = x;
        this.y = y;
        this.r = r;
    }
}

Our constructor takes a Context, x, y, and radius r. We pass these arguments in when we instantiate the object and assign them to the object properties. And lastly, the method which actually draws the circle, onDraw:

public Ball(Context context, float x, float y, int r) {
    super(context);
    mPaint.setColor(0xFFFF0000);
    this.x = x;
    this.y = y;
    this.r = r;
}

 @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawCircle(x, y, r, mPaint);
}

Ok, our Ball class is done. Save it and head back over to the main class. Drawing a Ball on the screen At this point we haven’t actually drawn anything. We’ve just created Ball which we *could* draw if we so desired. In order to draw it on the screen we first have to get a hold of our FrameLayout. Since we created it via XML we’ll need to find it again using findViewById():

  setContentView(R.layout.main);

   FrameLayout main = (FrameLayout) findViewById(R.id.main_view);

Now we can use the addView method to attach a new Ball to our main view:

    FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
    main.addView(new Ball(this,50,50,25));

Run your code now and, if all goes well, you’ll have a circle with a radius of 25 pixels in the upper left corner of the screen. Yay! Take some time to play around with Paint options, positioning, etc with the various methods outlined in the documentation. Now all we have to do is add a touch listener to react when the screen is touched. Which is thankfully pretty easy. We’re going to create a new touch listener and attach it to our main view all in one fell swoop:

main.addView(new Ball(this,50,50,25));

main.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {

    }
});

The onTouch() method is a callback function which will be hit whenever you touch the screen. Android will send it a View (v) and a MotionEvent (e). We already know what a view is, and a MotionEvent is an object containing information about the touch. All we care about are the X and Y coordinates, which are accessible via the getX() and getY() methods.

main.addView(new Ball(this,50,50,25));

main.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        float x = e.getX();
	float y = e.getY();
    }
});

The last thing we have to do before we can start drawing is to cast the view we were sent as a FrameLayout, so we can use the addView() method with it. Then we can instantiate a new Ball at the coordinates sent in the Motion Event:

main.addView(new Ball(this,50,50,25));

main.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        float x = e.getX();
	float y = e.getY();
        FrameLayout flView = (FrameLayout) v;
	flView.addView(new Ball(getParent(), x,y,25));
    }
});

The getParent() call sets the context for the Ball to the main Activity. I only vaguely understand why it has to be done this way. So now, the moment of truth! You should have all the code you need to run the app in your emulator or even on a real phone. Touching the screen will place a dot where you touched. Amazing! Hopefully you now have enough of an idea of how all this stuff plays together that you can forge your way to making something vaguely useful (which this isn’t).

Programming

Adam Mayer explains pointers to art students

I don’t have a background in CS. In fact I got my degree in Crafts. Yes, you can get a degree in Crafts. And I have one.

Most of my programming skills are self-taught, which is fine most of the time but occasionally gets me into trouble. Recently I learned about pointers the hard way, and to help clarify things my friend Adam broke it down into art school terms for me. It was so hilarious (and helpful) that I’m reposting it here.

You’re telling me you went through art school without once discussing referers and referents? WHAT KIND OF PUNK-ASS ART SCHOOL DID YOU GO TO? Let me break it down to you in art-school terms, then:

In python, you can think of all variables as pointers. All they do is point to objects. When you say:
>> constructivism = 6
You can think of this as creating an “integer object” with a value of 6. Constructivism is not itself 6 (which is to say, constructivism is not “6” in the way that brutalist materialism might be “6”). Instead, constructivism is a variable which points to this newly created
integer object with a value of 6. If you were to say:
>> constructivism = []
or
>> constructivism = Socket()
then you’ll be creating an new empty list object, or a new socket object, and then constructivism will point to that instead.

That’s all pretty simple. Then there’s this:
>> futurism = constructivism
Now, constructivism is already a pointer to something else. Futurism, however, will not point to constructivism itself: instead it will point to whatever constructivism points too, much like in 1991 Saatchi did not point at Damien Hirst, but whatever Damien Hirst was pointing at at the time; in this instance a dead shark. Note that while Damien Hirst went on to point at other things, Saatchi is still pointing at the dead shark. So:
>> hirst = Shark( dead=True )
Hirst is now pointing at a dead shark.
>> saatchi = hirst
Saatchi is now pointing at the same dead shark. Now,
>> hirst = Skull( bling=True )
Hirst is now pointing at a blinged-out skull, but Saatchi is still stuck on the shark.

When two variables are pointing at the same thing, they both see any changes made to that thing over time. So, for example, look at the following code:

>> # note that hirst does not make the shark himself, but calls a constructor
>> hirst = Shark( dead=True )
>> saatchi = hirst
>> print hirst.living
False

Both Hirst and Saatchi are referring to the same dead shark. But, later:

>> # Saatchi uses his money to bring the shark back to life
>> saatchi.ressurect()
>> print saatchi.living
True
>> print hirst.living
True

However, let’s move on:
>> hirst = Skull() # Hirst has moved on to other dumb shit
>> # What doth life?
>> print hirst.living
AttributeError: Skull has no attribute 'living'

… because hirst now points to a skull, and not the shark.

I could go on, but I’m impatient to see what google ads start popping up for this thread.

-a
(Actually, you probably really need to hear about scoping, but I’ll do that in terms of objectification and the male gaze.)

Programming, SDXF Documentation

Python library for generating DXF files

I’ve gotten a little frustrated with the limitations of using Processing to generate PDFs for laser cutting. Primarily, there’s no support for “hairline” thickness lines, which add an extra step to getting things ready to lase, and there’s no way to separate lines into different layers so it can be hard to work with the file later if you want to raster etch some lines and vector cut others.

Adam suggested looking into a DXF library someone had written for Python. Indeed, there is a very nice library. Unfortunately the original documentation for it seems to have gone missing.

I’ve started documenting the library, it’s called SDXF and is pretty thorough. I don’t know Python, or DXF, but so I’m picking up both as I go along.

Programming

Mysql_Awesome_Query

Hm it’s been a while since I’ve posted, been busy with a lot of boring, non-hacking stuff. Travesty! But here’s something vaguely interesting:

Often when I’m writing a bunch of PHP I want to be able to see the MySQL queries its generating. Usually I just comment out the mysql_query() and replace it with an echo. But sometimes that’s annoying, or I want to check multiple queries at once and don’t feel like switching them back and forth all the time.

I wrote a quick function called mysql_awesome_query(), which will either execute or echo a query depending on whether it’s a SELECT, INSERT, UPDATE, or DELETE/DROP.

//1 is run, 0 is echo sql
$flags = array(
'S'=>1,
'I'=>1,
'U'=>1,
'D'=>1
);


function mysql_awesome_query($sql){
$flags = $GLOBALS['flags'];

if($flags[$sql[0]]==1){
$result = mysql_query($sql);
if(mysql_error()){
return mysql_error();
} else {
return $result;
}
} else {
echo $sql;
return false;
}
}

The $flags global variable is an array of settings for which types of queries to execute, based on the first letter of the query string. MySQL conveniently doesn't have a lot of overlap there.
When mysql_awesome_query() is executed it checks the first letter of the query and if the corresponding array value is 1, it executes it and returns either a result or a mysql error. If it's 0, it simply echos the query so you can review it.

I'm sure there are more elegant ways to do this, but this was quick and dirty and works for my purposes.