Skip to main content

Posts

Showing posts from March 12, 2012

Why does Java allow control characters in its identifiers?

The Mystery In exploring precisely which characters were permitted in Java identifiers, I have stumbled upon something so extremely curious that it seems nearly certain to be a bug. I’d expected to find that Java identifiers conformed to the requirement that they start with characters that have the Unicode property ID_Start and are followed by those with the property ID_Continue , with an exception granted for leading underscores and for dollar signs. That did not prove to be the case, and what I found is at extreme variance with that or any other idea of a normal identifier that I have heard of. Short Demo Consider the following demonstration proving that an ASCII ESC character (octal 033) is permitted in Java identifiers: $ perl -le 'print qq(public class escape { public static void main(String argv[]) { String var_\033 = "i am escape: \033"; System.out.println(var_\033); }})' > escape.java $ javac escape.java $ java escape | cat -v i am escape: ^[

Obsolete Java Optimization Tips

There are number of performance tips made obsolete by Java compiler and especially Profile-guided optimization . For example, these platform-provided optimizations can drastically (according to sources) reduces the cost of virtual function calls. VM is also capable of method inlining, loop unrolling etc. What are other performance optimization techniques you came around still being applied but are actually made obsolete by optimization mechanisms found in more modern JVMs?

What is the rationale behind this code block in java?

What is the rationale behind making this kind of code valid in java? Does it exist for some particular reason or is it just a byproduct of other Java language design decisions? Can't you just use the consructor to achieve the same effect? class Student { { System.out.println("Called when Student class is instantiated."); } }

Why isn"t LinkedList.Clear() O(1)

I was assuming LinkedList.Clear() was O(1) on a project I'm working on, as I used a LinkedList to drain a BlockingQueue in my consumer that needs high throughput, clearing and reusing the LinkedList afterwards. Turns out that assumption was wrong, as the (OpenJDK) code does this: Entry<E> e = header.next; while (e != header) { Entry<E> next = e.next; e.next = e.previous = null; e.element = null; e = next; } This was a bit surprising, are there any good reason LinkedList.Clear couldn't simply "forget" its header.next and header.previous member ?

Playframework vs Ruby On Rails

Yet another LanguageX vs LanguageY question.... Currently I have a bunch of apps built on playframework . For the most part I love it. Moving from PHP a few years ago was almost a religious experience -- an actual functional orm, much less boiler plate code, stuff just worked, etc. I still have a website running on a a shared hosting service thats built with PHP+ CodeIgniter . Recently I've been adding some features to this site and have been thinking about porting it to either Ruby on Rails or Playframework. So far though, nothing about rails has really blown me away. It seems like it has pretty much the same featureset as playframework. I like ruby's terseness, and things like blocks, but again for the most part there's been nothing about the language itself that has made me go "oh wow this is 1000x better than java/php/c/whatever!" In fact, some parts actually kind of rub me the wrong way -- I prefer strongly-typed languages for example. My questio

apache commons equals/hashcode builder

I'm curious to know, what people here think about using org.apache.commons.lang.builder EqualsBuilder/HashCodeBuilder for implementing the equals/hashcode? Would it be a better practice than writing your own? Does it play well with Hibernate? What's your opinion?

Why reading a volatile and writing to a field member is not scalable in Java?

Observe the following program written in Java (complete runnable version follows, but the important part of the program is in the snippet a little bit further below): import java.util.ArrayList; /** A not easy to explain benchmark. */ class MultiVolatileJavaExperiment { public static void main(String[] args) { (new MultiVolatileJavaExperiment()).mainMethod(args); } int size = Integer.parseInt(System.getProperty("size")); int par = Integer.parseInt(System.getProperty("par")); public void mainMethod(String[] args) { int times = 0; if (args.length == 0) times = 1; else times = Integer.parseInt(args[0]); ArrayList < Long > measurements = new ArrayList < Long > (); for (int i = 0; i < times; i++) { long start = System.currentTimeMillis(); run(); long end = System.currentTimeMillis(); long time = (end - start); System.out.printl

Compiler complains about "missing return statement&rdquo; even though it is impossible to reach condition where return statement would be missing

In the following method, the compiler complains about a missing return statement even though there is only a single path through the method, and it contains a return statement. Suppressing the error requires another return statement. public int foo() { if (true) { return 5; } } Given that the Java compiler can recognize infinite loops , why doesn't it handle this situation as well? The linked question hints, but doesn't provide details for this specific case.

App Engine - Intermittent 500 errors on /_ah/openid_verify

I'm getting intermittent errors when logging into my app with the Google openid. The link they are sent to is http://www.example.com/_ah/login_redir?claimid=www.google.com/accounts/o8/id&continue=http://www.example.com/login2?returl%253Dhttp%25253A%25252F%25252Fwww.example.com%25252Ftest-list-8 . Then when they grant access to my app, sometimes there is a 500 error on the url: http://www.example.com/_ah/openid_verify?continue=http://www.example.com/login2?returl%3Dhttp%253A%252F%252Fwww.example.com%252Ftest-list-8%2523additem&gx.rp_st=AEp4C1sATcZr10BWADPx0hXZOeG49Vdr6GjYqvx83JXTTXjEFdqS8KaHIfZD3wmwTNl-wu8r7DMwoQMvWLpqgoV8RtAUigMMjw&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&openid.response_nonce=2011-12-06T20%3A00%3A53ZGU1ZOot7AJ4DGg&openid.return_to=http%3A%2F%2Fwww.example.com%2F_ah%2Fopenid_verify%3Fcontinue%3Dhttp%3A%2F%2Fwww.example.com%2Flogin2%

Why does java wait so long to run the garbage collector?

I am building a Java web app, using the Play! Framework . I'm hosting it on playapps.net . I have been puzzling for a while over the provided graphs of memory consumption. Here is a sample: The graph comes from a period of consistent but nominal activity. I did nothing to trigger the falloff in memory, so I presume this occurred because the garbage collector ran as it has almost reached its allowable memory consumption. My questions: Is it fair for me to assume that my application does not have a memory leak, as it appears that all the memory is correctly reclaimed by the garbage collector when it does run? (from the title) Why is java waiting until the last possible second to run the garbage collector? I am seeing significant performance degradation as the memory consumption grows to the top fourth of the graph. If my assertions above are correct, then how can I go about fixing this issue? The other posts I have read on SO seem opposed to calls to System.gc()

Any good interview questions to ask prospective Junior java developers? [closed]

Does anyone have a good interview question to ask prospective junior java developers? They will have a two year minimum experience requirement. The questions will be on a written test and they will have five to ten minutes to answer each question. Limit to one interview question per response for voting purposes please.

Getting A File"s Mime Type In Java

I was just wondering how most people fetch a mime type from a file in Java? So far I've tried two utils: JMimeMagic & Mime-Util. The first gave me memory exceptions, the second doesn't close its streams off properly. I was just wondering if anyone else had a method/library that they used and worked correctly?

Size of a byte in memory - Java

I have heard mixed opinions over the amount of memory that a byte takes up in a java program. I am aware you can store no more than +127 in a java byte, and the documentation says that a byte is only 8 bits but here I am told that it actually takes up the same amount of memory as an int, and therefore is just a Type that helps in code comprehension and not efficiency. Can anyone clear this up, and would this be an implementation specific issue?

what is JMS good for?

I'm looking for (simple) examples of problems for which JMS is a good solution, and also reasons why JMS is a good solution in these cases. In the past I've simply used the database as a means of passing messages from A to B when the message cannot necessarily be processed by B immediately. A hypothetical example of such a system is where all newly registered users should be sent a welcome e-mail within 24 hours of registration. For the sake of argument, assume the DB does not record the time when each user registered, but instead a reference (foreign key) to each new user is stored in the pending_email table. The e-mail sender job runs once every 24 hours, sends an e-mail to all the users in this table, then deletes all the pending_email records. This seems like the kind of problem for which JMS should be used, but it's not clear to me what benefit JMS would have over the approach I've described. One advantage of the DB approach is that the messages are persisten

Animating a custom property of CALayer subclass

I have a CALayer subclass, MyLayer, that has a NSInteger property called myInt. I'd really like to animate this property via CABasicAnimation, but it seems CABasicAnimation only works on so-called "animatable" properties (bounds, position, etc). Is there something I can override to make my custom myInt property animatable?

Method Overloading. Can you overuse it?

What's better practice when defining several methods that return the same shape of data with different filters? Explicit method names or overloaded methods? For example. If I have some Products and I'm pulling from a database explicit way: public List<Product> GetProduct(int productId) { // return a List } public List<Product> GetProductByCategory(Category category) { // return a List } public List<Product> GetProductByName(string Name ) { // return a List } overloaded way: public List<Product> GetProducts() { // return a List of all products } public List<Product> GetProducts(Category category) { // return a List by Category } public List<Product> GetProducts(string searchString ) { // return a List by search string } I realize you may get into a problem with similar signatures , but if you're passing objects instead of base types (string, int, char, DateTime, etc) this will be less of an issue. So... i

How to embed iPhone-Wax into app

I have just learnt about iPhone-Wax (thanks to SO). Now the documentation is rather sparse for what I am trying to do. I want to embed it into an Objective-C app. I don't want it to be the main app. Has anyone done it and how can I achieve it? I would like to use it in the same way LuaObjectiveCBridge is used.

Program received signal: “0”. Data Formatters temporarily unavailable

I'm working on an iPad app that downloads a CSV file from the web and parses the file into a NSMutableArray. (I'm using the code from http://www.macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data suggested in another post). When I run in the simulator, everything works perfectly, but when I run on the device, I get the following error: Program received signal: “0”. Data Formatters temporarily unavailable, will re-try after a 'continue'. (Unknown error loading shared library "/Developer/usr/lib/libXcodeDebuggerSupport.dylib") (gdb) Does anyone know why this would pop up? Google isn't helping me here... :( Thanks!

What is the relationship between UIView"s setNeedsLayout, layoutIfNeeded and layoutSubviews?

Can anyone give a definitive explanation on the relationship between UIView's setNeedsLayout, layoutIfNeeded and layoutSubviews methods? And an example implementation where all three would be used. Thanks. What gets me confused is that if I send my custom view a setNeedsLayout message the very next thing it invokes after this method is layoutSubviews, skipping right over layoutIfNeeded. From the docs I would expect the flow to be setNeedsLayout > causes layoutIfNeeded to be called > causes layoutSubviews to be called.

UIButton of type UIButtonTypeCustom will not display Title (iPhone)

I must have overlooked something completely obvious?? but my button displays its image and size correctly, but I simply can't get the Title to show up. I did a really simple test, the Title does not even show up when I do this: CGRect frameBtn = CGRectMake(160.0f, 150.0f, 144.0f, 42.0f); UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setImage:[UIImage imageNamed:@"left_halfscreen_button.png"] forState:UIControlStateNormal]; [button setTitle:@"Hello" forState:UIControlStateNormal]; [button setFrame:frameBtn]; NSLog(@"Title:%@", [button currentTitle]); //prints "Title:Hello [self addSubview:button]; I have a factory class that generates custom buttons for me and I thought I messed some detail up there, so I moved the above code directly into my UIView, the title is still blank. Is this a bug or am I simply missing something right in front of my eyes. Thank you for the extra set of eyes:

Reset push notification settings for app

I am developing an app with push notifications. To check all possible ways of user interaction, I'd like to test my app when a user declines to have push notifications enabled for my app during the first start. The dialog (initiated by registerForRemoteNotificationTypes ), however, appears only once per app. How do I reset the iPhone OS's memory of my app. Deleting the app and reinstalling doesn't help.

Alternative solutions for in-house iPhone enterprise app distribution

A client has asked us to develop a proprietary in-house app for managing their back-end systems. However, we are a small development company and I'm certain that their company does not have >500 employees. Are there any alternative, yet similar, solutions to distributing this app to their company without going through the iPhone enterprise program? (just to clarify: obviously, we would like to go through the official enterprise program but seeing how the company doesn't have >500 employees, this isn't possible). UPDATE (27/09): It appears Apple have removed the 500 employee limit for the enterprise distribution See here . So this will probably be our route now (which is helpful because the app is approaching completion). I'll update this as we go through the process if anyone would like me to, so that others may get an idea of what the actual process is like.

Play local notification default sound when displaying UIAlertView?

I'm writing a reminders app for iPhone that displays reminders using local notifications. If a reminder goes off while the application is running, the local notification isn't displayed. Instead, the didReceiveLocalNotification method is called in my app delegate, and I mimic the local notification dialog by displaying a UIAlertView with the reminder text. When local notifications are displayed outside of the app, the device vibrates and the sound specified by UILocalNotificationDefaultSoundName is played. Again, I'd like to mimic this in the app when displaying the UIAlertView . I can vibrate the device by calling AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) , but I can't figure out how to play the local notification default sound. There's no equivalent SystemSoundID constant, and I'm not sure what the path would be. tl;dr I'd like to play the local notification default sound when displaying a UIAlertView. Any ideas?

iPhone iOS 4.0 Camera FigCreateCGImageFromJPEG returned -1

Since I updated to 4.0, when I take a photo with my App using UIImagePickerController I get the following error output: * ERROR: FigCreateCGImageFromJPEG returned -1. Input (null) was 711733 bytes. I still get the image returned and can continue as normal, but does any body know what and why I get this error. I also get the following warnings that could be related: Using two-stage rotation animation. To use the smoother single-stage animation, this >application must remove two-stage method implementations. Using two-stage rotation animation is not supported when rotating more than one view >controller or view controllers not the window delegate Any information would be of great help. Thanks in advance.

NSThread vs. NSOperationQueue vs. ??? on the iPhone

Currently I'm using NSThread to cache images in another thread. [NSThread detachNewThreadSelector:@selector(cacheImage:) toTarget:self withObject:image]; Alternately: [self performSelectorInBackground:@selector(cacheImage:) withObject:image]; Alternately, I can use an NSOperationQueue NSInvocationOperation *invOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(cacheImage:) object:image]; NSOperationQueue *opQueue = [[NSOperationQueue alloc] init]; [opQueue addOperation:invOperation]; Is there any reason to switch away from NSThread ? GCD is a 4th option when it's released for the iPhone, but unless there's a significant performance gain, I'd rather stick with methods that work in most platforms. Based on @Jon-Eric's advice, I went with an NSOperationQueue / NSOperation subclass solution. It works very well. The NSOperation class is flexible enough that you can use it with invocations, blocks or custom subclasses, dependi

iphone webkit css animations cause flicker

This is the iphone site: http://www.thevisionairegroup.com/projects/accessorizer/site/ After you click "play now" you'll get to a game. The guns will scroll in. You can scroll the purse and accessories up and down. You can see that when you let go they snap into place. Just as that snap happens, there's a flicker that occurs. The only webkit animations I'm using are: '-webkit-transition': 'none' '-webkit-transition': 'all 0.2s ease-out' '-webkit-transform': 'translate(XXpx, XXpx)' I choose either the first or second transition based on whether or not I want it to animate, and the transform is the only way I move things around. The biggest issue though is when you click "Match items", then click "Play again". You'll see as the guns animate in, the entire background of the accessories/purses goes white. Can someone please radiate me with some insight asto why this is happening??

Asihttprequest 61 errors [closed]

it should be a simple problem. im using the ASIhttprequest in many project but sins 1 week each new project i'm trying to add the ASIhttprequest classes i got the following 61 error before using classes just when i'm trying to import them. Build finjan of project finjan with configuration Debug Ld build/Debug-iphonesimulator/finjan.app/finjan normal i386 cd /Users/Apple/Desktop/application/finjan setenv MACOSX_DEPLOYMENT_TARGET 10.5 setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.3.sdk -L/Users/Apple/Desktop/application/finjan/build/Debug-iphonesimulator -F/Users/Apple/Desktop/application/finjan/build/Debug-iphonesimulator -filelist /Users/Apple/Desktop/application/finjan/build/finjan.build/Debug-iphonesimulator/finj

iPhone: Create a reusable component (control) that has some Interface Builder pieces and some code

I want to create a reusable component (a custom control) for the iPhone. It consists of several standard controls prearranged on a View, and then some associated code. My goals are: I want to be able to use Interface Builder to lay out the subviews in my custom control; I want to somehow package the whole thing up so that I can then fairly easily drag and drop the resulting custom component into other Views, without having to manually rewire a bunch of outlets and so on. (A little manual rewiring is fine, I just don't want to do tons and tons of it.) Let me be more concrete, and tell you specifically what my control is supposed to do. In my app, I sometimes need to hit a web service to validate data that the user has entered. While waiting for a reply from the web service, I want to display a spinner (an activity indicator). If the web services replies with a success code, I want to display a "success" checkmark. If the web service replies with an error code,

HTML5 inline video on iPhone vs iPad/Browser

I've created an HTML5 video player (very simple) that works perfectly on the iPad and the browser. However, when I open it on the iPhone, I only get a play button which, when pressed, opens the native video player on a new window, on top of all my stuff. That means I lose access to my custom controls and time tracking (written in Javascript), since the video is now running isolated. Is there any way to override Apple's control of HTML5 video on the iphone and get it working like on the ipad? Cheers

UIDocumentInteractionController adding custom actions to menu (eg email, save to photos)

I've started using UIDocumentInteractionController for a new app but I'm wondering how to add additional actions to the action menu that you get on the preview screen? It seems that the menu only lists apps that have registered for a given url type plus I'm seeing PRINT showing up on iOS4.2. I would like to add send by email and save to photos but don't see a way of extending this menu. I can code the actions I want OK, it's just adding them into the menu that seems impossible? Am I missing something obvious?

What causes (and how can I fix) this odd Core Location error?

ERROR,Generic,Time,320195751.128,Function,"void CLClientHandleRegistrationTimerExpiry(__CFRunLoopTimer*, void*)",Registration timer expired, but client is still registering! There are only a few mentions of this problem that I was able to dig up in the wider Internet, and nobody has useful info. Here's the context: I have an app that monitors the device's location via CLLocationManager's startUpdatingLocation method. It starts monitoring, runs for a little while, then this message pops up in the debug output. From that point forward, no more location updates are delivered. This error is killing the location functionality of the app, and I'm at a loss as to what may be causing it. It even has an exclamation point at the end, which means it's clearly an exciting error. Update: Though I never found a solution to the problem, or figured out why it happens in the first place, I've also lost the ability to reproduce it. This seems to have h

How do I replace weak references when using ARC and targeting iOS 4.0?

I've begun developing my first iOS app with Xcode 4.2, and was targeting iOS 5.0 with a "utility application" template (the one that comes with a FlipsideViewController). I read that since ARC is a compile-time feature, it should be compatible with iOS 4 as well, so I attempted to target my app to 4.3, and try compiling it. When I do so, I get this error: FlipsideViewController.m: error: Automatic Reference Counting Issue: The current deployment target does not support automated __weak references It is referencing this line: @synthesize delegate = _delegate; That variable is declared as: @property (weak, nonatomic) IBOutlet id <FlipsideViewControllerDelegate> delegate; I understand that "weak references" are not supported in iOS 4, but I don't really understand why I would want to use a weak reference to begin with, nor can I figure out how I would rewrite things to avoid using it, while still taking advantage of ARC (after all, it's su

How to prevent iPhone 3GS from filtering low frequencies ( < 150Hz )

I'm developing a bass guitar pitch detection app on iphone 3GS. I found I can't get sound data lower than 150Hz with RemoteIO. However bass guitar may generate tones lower than 50hz. According to the report "iPhone 4 Headset Input Frequency Response", http://blog.faberacoustical.com/2010/iphone/iphone-4-audio-and-frequency-response-limitations/ There is a sharp drop-off below 150 Hz. Here shows how I setup the AudioUnit. // set audio unit { // create AudioUnit { AudioComponentDescription desc; desc.componentType = kAudioUnitType_Output; desc.componentSubType = kAudioUnitSubType_RemoteIO; desc.componentManufacturer = kAudioUnitManufacturer_Apple; desc.componentFlags = 0; desc.componentFlagsMask = 0; AudioComponent comp = AudioComponentFindNext(NULL, &desc); OSAssert(AudioComponentInstanceNew(comp, &m_AudioUnit)); } //enable input on the remote I/O unit (output is default enable

Linker Error in Xcode 4.2 Developer Preview

d /Users/yariksmirnov/Library/Developer/Xcode/DerivedData/Goozzy-cugjuvvsrzjqwvfiicxtykbqagux/Build/Products/Debug-iphonesimulator/Goozzy.app/Goozzy normal i386 cd /Users/yariksmirnov/Desktop/Goozy/branches/new setenv MACOSX_DEPLOYMENT_TARGET 10.6 setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk -L/Users/yariksmirnov/Library/Developer/Xcode/DerivedData/Goozzy-cugjuvvsrzjqwvfiicxtykbqagux/Build/Products/Debug-iphonesimulator -F/Users/yariksmirnov/Library/Developer/Xcode/DerivedData/Goozzy-cugjuvvsrzjqwvfiicxtykbqagux/Build/Products/Debug-iphonesimulator -filelist /Users/yariksmirnov/Library/Developer/Xcode/DerivedData/Goozzy-cugjuvvsrzjqwvfiicxtykbqagux/Build/Intermediates/Goozzy.build/Debug-iphonesimulator/Goozzy.build/O

When does an associated object get released?

I'm attaching object B via associative reference to object A. Object B observes some properties of object A through KVO. The problem is that object B seems to be deallocated after object A, meaning its too late to remove itself as a KVO observer of object A. I know this because I'm getting NSKVODeallocateBreak exceptions, followed by EXEC_BAD_ACCESS crashes in object B's dealloc. Does anyone know why object B is deallocated after object A with OBJC_ASSOCIATION_RETAIN? Do associated objects get released after deallocation? Do they get autoreleased? Does anyone know of a way to alter this behavior? I'm trying to add some things to a class through categories, so I can't override any existing methods (including dealloc), and I don't particularly want to mess with swizzling. I need some way to de-associate and release object B before object A gets deallocated. EDIT - Here is the code I'm trying to get working. If the associated objects were released

iOS UIImagePickerController result image orientation after upload

I am testing my iPhone application on an iOS 3.1.3 iPhone. I am selecting/capturing an image using a UIImagePickerController : UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera]; [imagePicker setDelegate:self]; [self.navigationController presentModalViewController:imagePicker animated:YES]; [imagePicker release]; - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { self.image = [info objectForKey:UIImagePickerControllerOriginalImage]; imageView.image = self.image; [self.navigationController dismissModalViewControllerAnimated:YES]; submitButton.enabled = YES; } I then at some point send it to my web server using the ASI classes: ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://example.com/myscript.php"]]; [request setDelegate:self]; [request setStringEnc

Where is set the active build configuration in Xcode 4

I have 3 configurations in my project (Debug, Distribution_AdHoc and Distribution_AppStore). In Xcode 3 we had a list to choose device, version, configuration and target before build and run. Now with Xcode 4 we only have the device kind and version in this list. This bring my two questions: So where is defined the configuration used ? Is that the configuration defined in "Project > Info > Command-line builds use: Debug" ? And now the "Project" menu is replaced by "Product" So where can we create (or duplicate and edit) a Configuration ? Thank you.