Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

Ugg boots posted:

I don't think that the Java problem is the same x87 weirdness as PHP. Their algorithm is different (approximating toward the target from the other direction), and also it seems to work (not work) on 32-bit and 64-bit hardware.

Why do so many libraries and runtimes use the correction loop method to begin with?

Adbot
ADBOT LOVES YOU

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Plorkyeran posted:

The indentation is wrong, so no.

I didn't mean it was right, I meant it was aesthetically pleasing. Like if ee cummings were a programmer.

zootm
Aug 8, 2006

We used to be better friends.

Ugg boots posted:

I don't think that the Java problem is the same x87 weirdness as PHP. Their algorithm is different (approximating toward the target from the other direction), and also it seems to work (not work) on 32-bit and 64-bit hardware.
Good point. I think it would be best if I resolved to stick to the natural numbers henceforth, all of this stuff hurts my brain.

Otto Skorzeny posted:

Why do so many libraries and runtimes use the correction loop method to begin with?
I believe they're falsely assuming that the value will always converge, but with some subnormal numbers the result does not. It's common, I think, because it's the "standard" way of doing this (although I could be wrong about that). This blog article from the same guy as wrote about the Java one seems to have a pretty good explanation.

raminasi
Jan 25, 2005

a last drink with no ice
I misread that first for loop as for ( eof = 0; skip = 0; )
and it was my favorite for loop ever.

Surface
May 5, 2007
<3 boomstick

So now PHP, and Java (and therefore Clojure and others).

What other languages could be susceptible to this?

plushpuffin
Jan 10, 2003

Fratercula arctica

Nap Ghost

NotShadowStar posted:

I'm taking a numeric analysis course this semester, and the second chapter is literally all about floating point errors and bounds checking and how much this is going to gently caress you over and over until you get it right.

Then we have languages like PHP and Java, who were apparently too good to learn that crap.

The worst abuse/misunderstanding of floating point I've ever seen was someone who decided to implement a bit-flag vector (in C++), but they wanted a human-readable bit-flag vector. So, instead of 15, they would use the number 1111. Also, instead of using an integer, they figured a double would give them more space (it does, but just barely: ~16 decimal digits instead of ~10).

Then they decided to pack way more than 16 digits into the double, by using some whole digits and some fractional digits. They didn't realize that the double was going to drop any digits more than ~15 decimal places away from the most significant digit. This also made it really hard to do actual bitwise arithmetic on the number.

They could have just used a bitset in memory (which can initialize from and output to a string) and a varchar in the database, but they evidently thought that floats/doubles had arbitrary precision, and thus they could pack digits onto the end indefinitely. The code was 10+ years old, so maybe they didn't have access to STL's bitset at the time, but it wouldn't have taken more than an hour or two to write their own bitset class using a backing string or byte array or something.

Deep Dish Fuckfest
Sep 6, 2006

Advanced
Computer Touching


Toilet Rascal
I'm not sure if this is a coding horror or not:

code:
bool deletedSomething;
for (SomeIterator iterator = someList.begin(); iterator != someList.end(); deletedSomething ? iterator : ++iterator) {
	deletedSomething = false;

	[...]

	if(someCondition()) {
		iterator = someList.erase(iterator);
		deletedSomething = true;
	}

	[...]

}
On one hand, I wouldn't expect a ternary operator there. On the other hand, I kind of like it... It makes me feel dirty though.

pwd
May 1, 2009
I saw this today in actual use. Even if you're familiar with perl, it is probably somewhat confusing.

code:
use File::Spec;
my $fileExt = qr/\.txt$/;
my $dirhandle;

my $dir = File::Spec->curdir();
opendir($dirhandle, $dir) || die "Can't opendir $dir: $!";
my @files = grep { /$fileExt/ && (-f File::Spec->catfile($dir, $_)) }
readdir($dirhandle);
closedir($dirhandle);

print join("\n", @files) . "\n";
It just lists files matching "*.txt" in the current directory.

The same thing (in all the cases we care about) can also be accomplished in one line:
code:
my @files = glob("*.txt");
Looking at it again, I don't think "readdir" even does anything up there.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
Today's coding horror is courtesy of an applicant for a job at my company. The job's standard C#, and we start off with a phone interview where we make sure they at least know what an abstract class is and the like. We had someone come in today, and one of the questions we always ask them to code up in front of us is FizzBuzz. It's simple and any good developer will knock it out in under 5 minutes.

Today's applicant had to use MSDN to look up the syntax for a "for" loop, and then didn't know the modulus operator, so the solution looked (roughly) like this:

code:
for (int i=1;i<=100;i++) 
{ 
      decimal dec = i;
      if (dec/3 == i/3) 
      {
          ...
      }
}
That hurt my brain. It's actually pretty clever (and the solution ultimately worked!), but it's the bad kind of clever. The interview was more or less over right after needing to google the syntax for "for", anyway.

At the very least, being present for these interviews is making me feel like a superstar programmer.

evensevenone
May 12, 2001
Glass is a solid.
Apparently the real horror is your phone screening. Although, it sounds more like the person you were dealing was competent in some language, just not a C-style one.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

pwd posted:

I saw this today in actual use. Even if you're familiar with perl, it is probably somewhat confusing.

code:
use File::Spec;
# ...
It just lists files matching "*.txt" in the current directory.

The same thing (in all the cases we care about) can also be accomplished in one line:
code:
my @files = glob("*.txt");

I vaguely recall glob not being implemented correctly on non-Unix platforms a while ago. They fixed this along with a lot of other cross-platform behavior way back in 5.6. File::Spec is expressly designed for cross-platform operations. It's not the best code, but there's probably a clear method to the madness.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip
IIRC Path::Class is a more convenient wrapper around File::Spec stuff btw

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

YeOldeButchere posted:

I'm not sure if this is a coding horror or not:

code:
bool deletedSomething;
for (SomeIterator iterator = someList.begin(); iterator != someList.end(); deletedSomething ? iterator : ++iterator) {
	deletedSomething = false;

	[...]

	if(someCondition()) {
		iterator = someList.erase(iterator);
		deletedSomething = true;
	}

	[...]

}
On one hand, I wouldn't expect a ternary operator there. On the other hand, I kind of like it... It makes me feel dirty though.
The idiomatic way to do this is
code:
for (SomeIterator iterator = someList.begin(); iterator != someList.end(); ) {
	[...]

	if(someCondition()) {
		iterator = someList.erase(iterator);
	}
	else {
		++iterator;
	}

	[...]

}
(or just std::remove_if when applicable)

Beef
Jul 26, 2004
For loop is a coding horror in itself, I wouldn't fault anyone for looking it up to make sure.

NotShadowStar
Sep 20, 2000

Beef posted:

For loop is a coding horror in itself, I wouldn't fault anyone for looking it up to make sure.

I frequently gently caress it up, since it uses semicolons but the statement is in parentheses, so I always use commas. Bit of a logical disconnect there, can't think of another remotely used thing that uses semicolons in parentheses for C-like languages.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
At least for isn't as ugly as a switch block.

csammis
Aug 26, 2003

Mental Institution

NotShadowStar posted:

I'm taking a numeric analysis course this semester, and the second chapter is literally all about floating point errors and bounds checking and how much this is going to gently caress you over and over until you get it right.

Then we have languages like PHP and Java, who were apparently too good to learn that crap.

Just out of curiousity what book are you using?

BattleMaster
Aug 14, 2000

evensevenone posted:

ah, the simple joys of embedded coding.
code:
    
   TERMIO_Init();

   TIOS |= TIOS_IOS4_MASK; // enable output capture
   TSCR1 |= TSCR1_TEN_MASK; // enable timer module
   TCTL1 &= ~(TCTL1_OM4_MASK|TCTL1_OL4_MASK); // disconnects output pins from TIM
   TSCR2 |= (TSCR2_PR0_MASK|TSCR2_PR1_MASK|TSCR2_PR2_MASK);
   TSCR2 &= ~(TSCR2_TCRE_MASK|TSCR2_TOI_MASK);
      
   TC4 = TCNT+PERIOD;
   TFLG1=TFLG1_C4F_MASK;
   TIE |= TIE_C4I_MASK;   

Most of the code I write is for embedded systems, so (sadly) I don't really see anything too bad there.

ColdPie
Jun 9, 2006

NotShadowStar posted:

I frequently gently caress it up, since it uses semicolons but the statement is in parentheses, so I always use commas. Bit of a logical disconnect there, can't think of another remotely used thing that uses semicolons in parentheses for C-like languages.

Well, comma already has a valid meaning in that context so you have to pick something else.

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
Just came across this gem and thought of this thread;

php:
<?
foreach(array_keys($_POST) as $key){
    
    if($key == 'feature_button')
    {
        $feature_button = $_POST['feature_button'];
        
    }    
    if($key == 'feature_name')
    {
        $feature_name = $_POST['feature_name'];
        
    }
        
    if($key == 'feature_button2')
    {
        $feature_button2 = $_POST['feature_button2'];
        
    }    
    if($key == 'feature_name2')
    {
        $feature_name2 = $_POST['feature_name2'];
        
    }
    if($key == 'listing')
    {
        $listing = $_POST['listing'];
        
    }
}
?>
For a 30-something variables.

nielsm
Jun 1, 2009



Rewrite it with "variable variables" because PHP is an awesome language :eng99:

php:
<?
$keys = array("feature_button", "feature_name", "feature_button2");
foreach ($keys as $key) {
    if (isset($_POST[$key])) {
        $$key = $_POST[$key];
    }
}?>

Fehler
Dec 14, 2004

.
Still light years better than enabling register_globals...

Karanth
Dec 25, 2003
I need to finish Xenogears sometime, damn it.

nielsm posted:

Rewrite it with "variable variables" because PHP is an awesome language :eng99:

The best thing is when you come across a php programmer trying to learn another language and they ask how to do this.

$LANG can't do that? $LANG sucks. :smug:

Zhentar
Sep 28, 2003

Brilliant Master Genius
They should go for MUMPS then. It offers the much better named "indirection", which makes PHP's variable variables look extremely limited in comparison.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
Scheme offers similar features through judicious use of string->symbol.

G-Dub
Dec 28, 2004

The Gonz
I think to redress the balance of life someone should start a Coding Joys thread for downright clever code, beautifully simple code or LOC-busting refactoring.

Zombywuf
Mar 29, 2008



It just seemed so appropriate.

ironypolice
Oct 22, 2002

nielsm posted:

Rewrite it with "variable variables" because PHP is an awesome language :eng99:


This works for function names too -- Drupal is kind of built around it.

http://drupal.org/node/547518
http://api.drupal.org/api/drupal/includes--module.inc/group/hooks/7

baquerd
Jul 2, 2007

by FactsAreUseless

ironypolice posted:

This works for function names too -- Drupal is kind of built around it.

Not that the practice isn't a nightmarish hell to debug and maintain, but I often found it to be an intuitive approach to problems when I was first learning.

Karanth
Dec 25, 2003
I need to finish Xenogears sometime, damn it.

baquerd posted:

Not that the practice isn't a nightmarish hell to debug and maintain, but I often found it to be an intuitive approach to problems when I was first learning.

20 GOTO 10 is pretty intuitive to a total beginner too.

beuges
Jul 4, 2005
fluffy bunny butterfly broomstick
code:
        	boolean get_db_connection = true;
        	while (get_db_connection) 
        	{
        		if (oraobj.Connect(props.getURL(), props.getUser(), props.getPasswd())) 
        		{
        			db_cb = new databaseobj(oraobj, m_eventLog);
        			get_db_connection = false; // got connection
        			continue;
        		}
...

Sewer Adventure
Aug 25, 2004
code:
- (BOOL)addImagesFromAPI:(NSNumber *)aStyleID {
	
	// Request images
	NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://style.host.com/%@", aStyleID]];
	NSLog(@"url: %@",url);
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setValidatesSecureCertificate:NO];
	[request setUsername:@"foo"];
	[request setPassword:@"bar"];
	[request setDownloadCache:[ASIDownloadCache sharedCache]];
	[request startSynchronous];
	
	// If no error
	NSError *error = [request error];
	NSMutableArray *images = [NSMutableArray array];
	if (!error) {
		NSUInteger responseCode = [request responseStatusCode];
		if ( responseCode == 200 || responseCode == 0 ) {
			NSString *response = [request responseString];
			NSDictionary *reply = [response JSONValue];
			NSArray *exteriorImages = [reply objectForKey:@"exterior"];
			for ( NSDictionary *size in exteriorImages ) {
				if ( [size objectForKey:@"0640"] ) {
					for ( NSString *image in [size objectForKey:@"0640"] ) {
						NSString *urlForImage = [NSString stringWithFormat:@"http://image.host.com/%@",image];
						NSLog(@"Image url: %@ (%@)",urlForImage, [size objectForKey:@"0640"]);
						[images addObject:urlForImage];
					}
					break;
				}
			}
			if ( [images count] > 0 )
				[(SpinView*)[self view] addImagesFromURLs:images];
			else
				return NO;
		} else {
			return NO;
		}
	} else {
		return NO;
	}
	return YES;
}

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

baquerd posted:

Not that the practice isn't a nightmarish hell to debug and maintain, but I often found it to be an intuitive approach to problems when I was first learning.

The main argument against using it from a functionality perspective, as far as I can see, is that it doesn't let you do anything you can't already do with an associative array.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

Hammerite posted:

The main argument against using it from a functionality perspective, as far as I can see, is that it doesn't let you do anything you can't already do with an associative array.

That's a silly reason. Take that argument far enough and we'll all use assembler whose only instruction is subtract and branch if less than or equal to zero.

I haven't touched PHP in a solid decade so I don't know how this particular feature works but does it help make something clearer or easier to use?

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



pokeyman posted:

That's a silly reason. Take that argument far enough and we'll all use assembler whose only instruction is subtract and branch if less than or equal to zero.

I haven't touched PHP in a solid decade so I don't know how this particular feature works but does it help make something clearer or easier to use?

Easier than typing out every single mapping from REQUEST to local variables but less clear.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

pokeyman posted:

That's a silly reason. Take that argument far enough and we'll all use assembler whose only instruction is subtract and branch if less than or equal to zero.

Well ok, so what I should really have said was: it's like using an associative array, except with less control over what you're doing and much greater potential for hard-to-spot security problems.

Really I think you can compare "variable variables" : associative arrays, with global variables : local variables. If I write $$var then I could be referring to any variable. How do you know what the hell I'm doing? If I write $myarray[$parameter] then you know that line of code can only touch the contents of the associative array $myarray, which presumably is an appropriate thing for my code to be doing.

So pretend I said: it's like using an associative array, but with problems that wouldn't apply if you just used an associative array in the first place.

pokeyman posted:

I haven't touched PHP in a solid decade so I don't know how this particular feature works but does it help make something clearer or easier to use?

IMO no it doesn't, if anything it seems to me to obfuscate things, although like any technique I'm sure it gets more intuitive the more you do it.

spiritual bypass
Feb 19, 2008

Grimey Drawer
Maybe if you cut off four of your fingers with a table saw, sticking the fifth one in doesn't seem like a big deal anymore.

MononcQc
May 29, 2007

Munkeymon posted:

Easier than typing out every single mapping from REQUEST to local variables but less clear.

Also less safe and more annoying. REQUEST respects the GPC order (Get, Post, Cookies) by default. This implicit kind of thing makes it so someone can pass in arbitrary variables with any page call that is being made, overwrite what you had, etc. Or it could just be another dev who started using a POST value that you need in a GET and fantastic you now have conflicts.

Variable variables are dumb. Using variables for functions and classes is kind of okay (reminds of first class functions), if only the implementation wasn't so dumb (you pass a string around). Then 5.3 apparently got HoF and closures, so that's much better and kills the need for that kind of trick altogether.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



MononcQc posted:

Also less safe and more annoying. REQUEST respects the GPC order (Get, Post, Cookies) by default. This implicit kind of thing makes it so someone can pass in arbitrary variables with any page call that is being made, overwrite what you had, etc. Or it could just be another dev who started using a POST value that you need in a GET and fantastic you now have conflicts.

Variable variables are dumb. Using variables for functions and classes is kind of okay (reminds of first class functions), if only the implementation wasn't so dumb (you pass a string around). Then 5.3 apparently got HoF and closures, so that's much better and kills the need for that kind of trick altogether.

I was talking about the kind of thing posted above where it iterates over a pre-defined array and creates a local variable for anything it finds both in that array and in the magic array, not a hand-rolled register globals.

Adbot
ADBOT LOVES YOU

NotShadowStar
Sep 20, 2000

MononcQc posted:

Also less safe and more annoying. REQUEST respects the GPC order (Get, Post, Cookies) by default. This implicit kind of thing makes it so someone can pass in arbitrary variables with any page call that is being made, overwrite what you had, etc. Or it could just be another dev who started using a POST value that you need in a GET and fantastic you now have conflicts.

Variable variables are dumb. Using variables for functions and classes is kind of okay (reminds of first class functions), if only the implementation wasn't so dumb (you pass a string around). Then 5.3 apparently got HoF and closures, so that's much better and kills the need for that kind of trick altogether.

Considering there's too many (>1) installations still running PHP 4, requiring PHP 5.3+ features for a large project like Drupal is impossible. Wordpress does a similar trick for converting strings to function names for hooking into processes.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply