Ryan Rampersad
Thoughts, opinions, ideas and now links
  • About
  • Podcast
  • Links

Archives

Parse error: syntax error, unexpected T_AS

I was doing some PHP work after a long hiatus. You get used to one language and when you back to another, you just forget things sometimes. I received an unexpected T_AS.

Parse error: syntax error, unexpected T_AS, expecting ‘;’ in /homepages/224/d19925234/htdocs/kdelli/working/index.php on line 18

The error is so descriptive! Well, more so than others, actually. When do you use the keyword as? In loop declarations! See my code.

if ( $query == "places" ) {
    $output = "";
    for ($locations as $key => $l) {
        $output .= $l . "\r\n";
    }    
}

What could be wrong? Take a look at the for loop declaration. Notice anything odd about it? I didn’t either, at first. The as looks right, I took out $key => but there was no difference. I realized, since I was coming from Java, that for each loops aren’t just for loops in PHP. They are literally foreach loops.

I corrected the error simply by changing for to foreach.

POST 405 (Method Not Allowed)

I was attempting to XHR a simple plain text file. MooTools sets the default request method to post. On my local testing development machine, it wasn’t a problem, but out in the wild on my 1and1 server, apparently post cannot be used to get a text file. I recived this error from the console.

POST http://ifupdown.com/app/manifest/m.txt 405 (Method Not Allowed)

I searched for the error of course but there were shockingly few results. I reasoned though that it had something to do with using post to get a non-server interacting document. I overrode my request object in MooTools to use get.

var r = new Request({url: "manifest/m.txt"});
// ... onComplete, onError, other goodies
r.post(); // won't work on 1and1 for some reason
r.get(); // will work perfectly

And with that, I uploaded it back to the server and it was error free! 1and1 blocks post-requests to regular text files, so just watch out for it. Requesting via post a PHP file is just fine though. Oh, the mysteries.

Fatal error: Out of memory – WordPress Update

Today I was attempting to update from WordPress 3.1 to 3.1.1. I run my blog on 1and1 and since it is shared hosting, I have limited memory to work with. I tried updating and was given this wonderful error.

Fatal error: Out of memory (allocated 29622272) (tried to allocate 3096504 bytes) in /homepages/27/d20110405/htdoc/blog1/wp-includes/class-http.php on line 1426

This is a memory related issue but it has nothing to do with the download itself. To fix my particular problem, all I had to do was turn my plugins off. There are lots of solutions for this but WordPress should have a method to turn off all plugins at once.

I turned my fourteen plugins off and then tried the update again. I was greeted with successful update message.

Downloading update from http://wordpress.org/wordpress-3.1.1.zip…
Unpacking the update…
Verifying the unpacked files…
Installing the latest version…
Upgrading database…
WordPress updated successfully

If your WordPress update fails due to not having enough memory, try disabling your plugins.

Bad dynamic forwarding specification – Terminal

When making a SOCKS tunnel through the the terminal, sometimes the port might be skipped when you’re in a hurry.

ryan@ryan-laptop:~$ ssh -D ryan@234.241.124.24
Bad dynamic forwarding specification 'ryan@234.241.124.24'

Again, this is probably a silly error. I forgot to specify the port and ssh thought my host connection that server address was the port itself. The fix is easy.

ryan@ryan-laptop:~$ ssh -D 9988 ryan@234.241.124.24

Just add the port and it should work. Missing obvious things is so easy to do when you haven’t had your coffee.

Symfony Error SQLSTATE[HY000]

I recently reinstalled my server and of course that means I needed to recreate my databases. I thought the obvious command, symfony doctrine:build-db would do it for me but I was wrong! It returned this horrible error.

ryan@ryan-desktop:~/www/mr_app$ ./symfony doctrine:build-db
>> doctrine Creating “dev” environment “doctrine” database
>> doctrine SQLSTATE[HY000]: General error: 1…EATE DATABASE mr_app”

I knew that the database was in fact live – I just made it via phpmyadmin. So that aside, I wasn’t what the problem was. A quick google led me to an old post on the symfony forums.

Since I already had all my models built, I didn’t have to do it again. So the following code was enough to fix the database problem.
./symfony doctrine:build --sql
./symfony doctrine:insert-sql

I also had some additional fixture data I waded injected into my database, so I ran that too with ./symfony doctrine:data-load

For me that’s all there was too the SQLSTATE[HY000] error, but I think the problem will vary. It seems like a common enough error.

PHP & JSON – Fatal error: Cannot use object of type stdClass as array

When working with JSON and PHP, things can get a bit tricky. One such situation might be decoding JSON data, which probably occurs more often than not in a web application.

A view of the fatal error in chrome's resource inspect through an ajax request

Fatal Error ...

I came across this fatal php error:

Fatal error: Cannot use object of type stdClass as array…

The cause was a json_decode call that I thought was entirely innocent.

Apparently, some genious thought it was a great idea to make the return value of the json_decode function be an object. It turns out that you have to explicitly state that you want an array.

$raw = json_decode($json); // bad way
echo( $raw["somekey"] ); // fatal error ...

$better = json_decode($json, true);
echo( $raw["somekey"] ); // no error!

According to the PHP.net documentation on json_decode, you need to set the second assoc argument to true so that PHP will return arrays.

That’s all there is to this silly error.

missing argument 1 when calling function mutator.call

I’ve been doing some hefty MooTools development lately, and I ran into a odd ball error in that endeavor. I put it aside for a while, ignoring it while I worked on other code. Eventuallly, I had to face it though, so here are my remarks in that journey.

First, the error in question is formally given in Firefox/Firebug as follows:

missing argument 1 when calling function mutator.call
value = mutator.call(this, value);
mootoo…e-nc.js (line 1226)

(more…)

CakePHP Model Joins

I had to join two models together in order to search them properly. In this special case, it was pagination. I was browsing the cookbook for anything that could help and I did in fact find joining tables.

I was doing something kind of bizarre and probably bad practice, but with CakePHP, there are no practices. Anyway, my original index() method looked something like this (where I wanted to paginate a table):

public function index() {
    $this->paginate = array("limit" => 10,
             "order" => array("Problem.created" => "desc"));
    $problems = $this->paginate("Problem");
    $this->set("problems", $problems);
};

This particular App deals with Math problems, if you’re wondering. Anyway, I wanted to make it so that these tables could display only the problems from particular group sets. Since that was a fancy hasAndBelongsToMany table, the joining method mentioned in the link was the only viable solution.

Using an if and an empty check with a named url-parameter, I adapted my paginator’s configuration on-demand:

public function index() {
    // ... same code as before
    
    if ( !empty($this->params["named"]["group"]) ) {
        $groupID = $this->params["named"]["group"];
        $this->paginate["joins"] = array("table" => "groups_problems",
                    "alias" => "Group",
                    "type" => "inner",
                    "conditions" => array("Group.id = " .$groupID));
    }

    // ... same code as before
}

This looks like it will work, according the examples they give in the cookbook. But nothing’s really that simple. When running the code above, loads of scary errors pop out of the oven.

Undefined offset: 0 [CORE/cake/libs/model/datasources/dbo_source.php, line 1403]
Undefined offset: 1 [CORE/cake/libs/model/datasources/dbo_source.php, line 1403]
Undefined offset: 2 [CORE/cake/libs/model/datasources/dbo_source.php, line 1403]
Undefined offset: 3 [CORE/cake/libs/model/datasources/dbo_source.php, line 1403]
Array to string conversion [CORE/cake/libs/model/datasources/dbo_source.php, line 1415]
SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘groups_problems Group inner Array WHERE 1 = 1′ at line 1 [CORE/cake/libs/model/datasources/dbo_source.php, line 635]
Query: SELECT COUNT(*) AS `count` FROM `problems` AS `Problem` groups_problems Group inner Array WHERE 1 = 1
… and it continues …

Frightening, isn’t it? I wasn’t sure by looking at my code and the examples as to the cause. So I did the next best thing; looked at the line in the dbo_source.php that was causing the errors. The easiest to pick out was line 1415, the Array to String conversion.

Once there, I noticed, 'joins' => implode(' ', $query['joins']), was the insidious code being executed. It was expecting an array of arrays! Who knew? After this realization, the fix was easy. I simply wrapped my entire join array in another array.

public function index() {
    // ... same code as before
    
    if ( !empty($this->params["named"]["group"]) ) {
        $groupID = $this->params["named"]["group"];
        $this->paginate["joins"] = array(array(/*... all the same configuration here ... */));
    }

    // ... same code as before
}

That fixed all of the error messages in one fell swoop. CakePHP often gets me with the errors and the fickle nature of the methods requiring very particular arguments when nobody knows what they are supposed to be.

Happy baking.

This post was written with CakePHP 1.2 in mind. Also, sorry for the source code mess. These source plugins just do not deliver justice.

CakePHP 1.3 Helper $text truncate error

Today I was using one of CakePHP’s helper methods, $text->truncate. It gave me these errors and I can’t say I was pleased about it. It reminded me that sometimes, functions aren’t a piece of cake.

Warning (2): array_merge() [function.array-merge]: Argument #2 is not an array [CORE/cake/libs/view/helpers/text.php, line 184]
Warning (2): extract() [function.extract]: First argument should be an array [CORE/cake/libs/view/helpers/text.php, line 185]
Notice (8): Undefined variable: html [CORE/cake/libs/view/helpers/text.php, line 187]

I also used it in the same view a little later. It gave errors down there as well.

Notice (8): Undefined variable: ending [CORE/cake/libs/view/helpers/text.php, line 238]
Notice (8): Undefined variable: exact [CORE/cake/libs/view/helpers/text.php, line 241]
Notice (8): Undefined variable: html [CORE/cake/libs/view/helpers/text.php, line 244]
Notice (8): Undefined variable: ending [CORE/cake/libs/view/helpers/text.php, line 258]
Notice (8): Undefined variable: html [CORE/cake/libs/view/helpers/text.php, line 260]

I wasn’t sure what was going on, so I went into the CakePHP source code to check it out. Traveling to cake/libs/view/helpers/text.php, I found the truncate method. Check out the code for it.

function truncate($text, $length = 100, $options = array()) {
  $default = array(
    'ending' => '...', 'exact' => true, 'html' => false
  );
  $options = array_merge($default, $options);
  extract($options);
// continues
}

This code is expecting only two real arguments. The third is a magic options array. Apparently nobody has thought about updateing the CakePHP book. Of if they have made updates, forget to tell people by putting a huge notice somewhere. The documentation explains the new arguments quite well, actually.

To fix those errors, I simply didn’t use any extra arguments, as I was satisfied by the defaults. But I could easily specify some other options.

__( $text->truncate($problem["Task"]["description"], 75) ); 
// other options 
__( $text->truncate($problem["Task"]["description"], 75, array("ending" => ". . .", "exact" => false, "considerHtml" => true)) ); 

My favorite feature about this is the exact option. It doesn’t chop up words, which is great.

This post is written with Cake 1.3 in mind. This may or may not apply to earlier versions.

CakePHP – 1and1 – 500 Internal Server Error

I recently deployed a CakePHP application to a 1and1 server. I was presented with a wonderful 500 Internal Server Error. That only means one thing: a .htaccess was messed up somewhere.

There were many places that pointed me in the right direction to fix this problem. It was definitely an annoying hitch. Seriously, there’s that many people with this problem. (So 1and1, want to help out here and make some changes? Maybe, just maybe, provide an customer error.log?)

Anyway, there is a pretty simple way to do this, since I did it this way too.

RewriteEngine on
RewriteBase /
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]

I simply added a RewriteBase / to every single .htaccess, the one in the root folder, then one inside app and inside webroot.

1and1 has a reputation for making things complicated, but this wasn’t so bad.

Invalid Object Initialization

Firebug will scream and shout about Invalid Object Initialization if you mess just a little something up. Firebug does this a lot. It is an unhelpful error because Firebug will direct you to the first line of your object, not where the problem is.

Firebug gave me this, more or less. That wasn’t helpful. (Why did Firebug get full, anyway?)

Firebug’s log limit has been reached. 0 entries not shown. Preferences invalid object initializer[Break on this error]

Let’s say you have some code, and it looks like this.

 var TranslationStrings = {
  onAdd: "Do you want to add this?",
  onDelete, "Do you want to delete this?"
 };

If you don’t notice the mistake in the object, Firebug will. It’s just a little something. It is a comma.

The onDelete, "Do...." should have a colon between the key-value pair. Not a comma, those go after a pair. It should be formed like so, onDelete: "Do...".

So remember, watch out for those javascript object literals with commas and colons.

Read a Text File in Java, In Eclipse

Our favorite development tool, Eclipse, makes it slightly confusing to read files properly inside of a Java program.

To start with, I make a file as anyone would, just a quick right click in the Project Tree, then New and finally to File as in a blank file.

Making A New Blank Text File

Making A New Blank Text File

The File Is input.txt

The File Is input.txt

One would assume that a non-java would exist in the top-level directory of the project instead of binsrc. However, something fishy happens though. If you try, inside your program, to reference your new file, you might try, input.txt. Does that work? No.

So here’s the scary error you get when you try to run a basic program, just reading a file into an array line-by-line.

Exception in thread “main” java.io.FileNotFoundException: input.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:106)
at java.util.Scanner.(Scanner.java:621)
at InputTesting.main(FileNerd_Ryan.java:16)

Good people at StackOverflow leave us the answer.

Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.

So, basically, if you have a file called input.txt, you can actually find in-program via src/input.txt. Why does Eclipse not make this path-reality more clear?

Happy Coding.

illegal character /160

I encountered this error today from copying and pasting a code snippet that was from one of our PDF textbooks.

illegal character /160

After making sure that our brackets matched, methods weren’t variables, variables weren’t methods, we didn’t know what was going on. Everything looked good and clean. So we decided to do the unthinkable: we retyped all of the code. This is of course a last ditch effort to salvage our project. So after retyping, reading over again and again, we compiled and our code ran! So the problem? What was that mysterious /160 character?

It is a harmless space. Don’t believe me? Just checkout this list. If you look for 160, you’ll be greeted by a space. So why did it cause the error? It’s not a normal space even though it’s harmless. It’s a special HTML-non-breaking space, you know, the {and-sign}NBSP kind?

The solution to this error is to simply retype the code that you encountered it in. Be wary of textbooks that supply code, they are often formatted in such a way that is unfit for Java to handle.

Happy coding.

java.util.Scanner [delimiters=\p{java Whitespace}+]

My computer science teacher encountered this strange string while working with another student one day after class. The assignment was using Scanner and stepping through a string by delimiter.

java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][ source closed = false ][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q∞\E]

Doesn’t that looks like a scary mess? Actually, it’s not so bad, it’s not even an error!

The Scanner class in Java has a toString method which allows it to be printed. The (so-called) documentation for the toString method states:

Returns the string representation of this Scanner. The string representation of a Scanner contains information that may be useful for debugging. The exact format is unspecified.

So when you use a Scanner and then subsequently print it out, it will spit out a representation of that Scanner at the that time, because on each step through a string, the Scanner changes slightly, based on weather certain things are true.

import java.util.*;
public class QuickTest {

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner("Four score and seven years ago our fathers brought forth on this continent, " +
				"a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.");
		
		System.out.println(scanner);
		// returns the following
		
		/*
		 * java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false]
		 * 1[skipped=false][group separator=\,][decimal separator=\.]
		 * [positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q∞\E]
		 * */
		
	}
}

That’s all there is too this kind of message in Java, nothing too major, just silly.

VirtualBox Guest Additions in Ubuntu 9.10

Ubuntu 9.10 came out just a few days ago. I was eager to try it but at the moment, I don’t have a spare computer. However, since my current computer has enough horse power to spare, I thought I’d throw Ubuntu in a Virtual Machine, specifically, VirtualBox.

Installation was a breeze. Installing the Guest Additions to make the resolution changeable and have seemless mouse-movement between Windows and Ubuntu didn’t quite work. I tried to run the VBoxLinuxAdditions-x86.run by double clicking on it and selecting run from the subsequent dialog but it return this error:

ryan@ryan-desktop:/cdrom$ ./VBoxLinuxAdditions-x86.run
Verifying archive integrity… All good.
Uncompressing VirtualBox 3.0.8 Guest Additions for Linux installation……………………………………………………………………………………………………………………………………………………………………………………………………..
VirtualBox 3.0.8 Guest Additions installation
This program must be run with administrator privileges. Aborting

So I figured that I’d have to use the command line to do this. So here’s what I did.

  1. Went to Applications, Accessories and finally to Terminal to open the command line up.
  2. Executed cd /
  3. Executed cd cdrom
  4. Executed sudo ./VBoxLinuxAdditions-x86.run

That final step, with the sudo is the key step. It may prompt you to enter your password because you need special administrative permissions.

Once you run that, it should work, it’ll install and then say you have to restart.

Enjoy!

These instructions are obviously intended for the non-server edition of Ubuntu. Additionally, these instructions will work exactly the same on newer versions of Ubuntu, such as Lucid Lynx 10.04.
Next>

© 2013 Ryan Rampersad.