The "IT DOESN'T WORK!" thread

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
mrbaggins
Posts: 1611
Joined: Tue Jan 15, 2008 3:23 am UTC
Location: Wagga, Australia

Re: The "IT DOESN'T WORK!" thread

Postby mrbaggins » Mon Sep 07, 2009 11:11 pm UTC

Not returning a value, and the the alert("foo") line returns a 0 from the ok button, whereas without it there's nothing to return?

What's the error?
Why is it that 4chan is either infinitely awesome, infinitely bad, or "lolwut", but never any intermediary level?

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Berengal » Tue Sep 08, 2009 3:45 am UTC

The error was that while the form was submitted the reloaded page didn't reflect this for some reason. With the alert, however, it did (same with confirm, the page was loaded asynchronously before any button were pushed). In IE nothing worked, probably because it delayed submitting/reloading until after I had dismissed the dialoge. I tried various other things of getting this to work, but only the dialogs seemed to work. I ended up doing something else having the same end result but looking somewhat uglier.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Re: The "IT DOESN'T WORK!" thread

Postby Pesto » Thu Sep 10, 2009 9:27 pm UTC

JFC, QA found a bug that we can't reproduce on any of our dev boxes. It's the most bizarre thing, too. I put in a fix for it, which worked one time, then stopped working.

WTF?

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Wed Sep 16, 2009 11:18 pm UTC

I've spent two days trying to track down a bug in my code. I just found it now. Apparently, 1000 Megs is not equal to 10 Gigs. :oops:

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Thu Sep 17, 2009 2:10 am UTC

Yeah, I've had bugs like that... I spent a few hours tracking down one where I'd claimed that 8 * 8 == 256...

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby You, sir, name? » Wed Sep 23, 2009 12:16 pm UTC

Pesto wrote:JFC, QA found a bug that we can't reproduce on any of our dev boxes. It's the most bizarre thing, too. I put in a fix for it, which worked one time, then stopped working.

WTF?


When all else fails, PEBKAC is the only reasonable explanation.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Re: The "IT DOESN'T WORK!" thread

Postby Pesto » Wed Sep 23, 2009 5:46 pm UTC

You, sir, name? wrote:
Pesto wrote:JFC, QA found a bug that we can't reproduce on any of our dev boxes. It's the most bizarre thing, too. I put in a fix for it, which worked one time, then stopped working.

WTF?


When all else fails, PEBKAC is the only reasonable explanation.

Not this time. There was a difference in environments. Our production boxes use PHP acceleration software that we don't use on our dev boxes. It turned out to be a rather obscure bug in the acceleration software that we had to code around.

slightlydead
Posts: 115
Joined: Wed Sep 23, 2009 10:52 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby slightlydead » Wed Sep 23, 2009 11:03 pm UTC

This is my 2nd year taking java. I'm doing a hw assignment for linkedlists and after doing most of the programming, I've found out that my iterator method doesn't work like it should. Great, zero credit and 20+wasted hours. Anyone know where to buy good razors and/or ropes? OR razor wire rope?

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby You, sir, name? » Wed Sep 23, 2009 11:11 pm UTC

slightlydead wrote:This is my 2nd year taking java. I'm doing a hw assignment for linkedlists and after doing most of the programming, I've found out that my iterator method doesn't work like it should. Great, zero credit and 20+wasted hours. Anyone know where to buy good razors and/or ropes? OR razor wire rope?


What can I say? Unit testing is your friend.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
mrbaggins
Posts: 1611
Joined: Tue Jan 15, 2008 3:23 am UTC
Location: Wagga, Australia

Re: The "IT DOESN'T WORK!" thread

Postby mrbaggins » Thu Sep 24, 2009 7:57 am UTC

Not trying to be offensive, but... It took 20 hours to work out how to write a linked list iterator?

Even if it did, you should know most of it now, and so can knock it together real quick.
Why is it that 4chan is either infinitely awesome, infinitely bad, or "lolwut", but never any intermediary level?

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Re: The "IT DOESN'T WORK!" thread

Postby Pesto » Fri Sep 25, 2009 12:17 am UTC

I don't think that's what he was saying. He spent 20 hours on his homework assignment, and one small simple part that shouldn't have caused him any problems brought the whole thing crashing down.

Okay, time for my own rant.

I'm writing these API calls for our softwear, and I'm using a class that my superior wrote. There are bugs in the underlying class, but because QA is testing my API call, which uses the buggy spaghetti class, the bug fixes come back on me. Grr.

0xBADFEED
Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby 0xBADFEED » Fri Sep 25, 2009 12:50 am UTC

Pesto wrote:I'm writing these API calls for our softwear...

I'm picturing like space-sweatpants.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Re: The "IT DOESN'T WORK!" thread

Postby Pesto » Fri Sep 25, 2009 12:56 am UTC

Hm. My brain doesn't seem to be working, either.

User avatar
mrbaggins
Posts: 1611
Joined: Tue Jan 15, 2008 3:23 am UTC
Location: Wagga, Australia

Re: The "IT DOESN'T WORK!" thread

Postby mrbaggins » Fri Sep 25, 2009 6:49 am UTC

Indeed... comprehension fail.
Why is it that 4chan is either infinitely awesome, infinitely bad, or "lolwut", but never any intermediary level?

User avatar
Cosmologicon
Posts: 1806
Joined: Sat Nov 25, 2006 9:47 am UTC
Location: Cambridge MA USA
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Cosmologicon » Wed Sep 30, 2009 5:11 pm UTC

I'm a little confused on closures, and how they appear in Python. A lot of sites seem to use "closure" to mean "anonymous function" but they're not necessarily the same thing, right? Am I right in understanding that f1 below is not a closure (with respect to x), but f2 is a closure?

Code: Select all

>>> x = 1
>>> f1 = lambda: x
>>> f1()
1
>>> x = 2
>>> f1()
2

Code: Select all

>>> x = 1
>>> f2 = (lambda z: (lambda: z))(x)
>>> f2()
1
>>> x = 2
>>> f2()
1

And if that's right, is there a better way to form a closure than that ugly nested syntax?

User avatar
Xanthir
My HERO!!!
Posts: 5410
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Xanthir » Wed Sep 30, 2009 5:21 pm UTC

No, the former is a closure (unless I'm using the terms wrong as well). A closure is an anonymous function that *closes over* any free variables in its vicinity. In Lisp we have lexical closures (any variables that are in-scope at the point in the text where the closure is defined), but other languages may have dynamic closures (any variables that are in-scope at the point in text where the closure is called).

Both f1 and f2 are closing over the x variable. Whether or not it accepts additional bound variables (like f2) doesn't have any bearing.

Edit: It looks like f2 may be trying to fake a lexical closure, while f1 is a dynamic closure.

Edit2: No, f2 *is* a lexical closure. It's closing over the variable z that is present at the time it is defined, but will ignore any variables named z elsewhere. It only cares about what's in-scope when it's defined. f1 is still not a lexical closure.

Since I think most people *mean* lexical closure when they say "closure", you're probably right in saying that f1 is not a closure.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Berengal » Wed Sep 30, 2009 7:57 pm UTC

At least according to wikipedia, "a closure is a first-class function with free variables that are bound by the lexical environment." So f1 is not a closure, because even though x is a free variable, it's not bound to the value of x, rather it's an invisible function call to read the value of the global x variable.

The terms kind of fall appart in the presence of mutable values. In mathematics (and functional programming), adding 2 to 3 doesn't make 3 = 5.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Thu Oct 01, 2009 12:23 am UTC

Well, however it works, and whatever the definition is, there's only one major difference between a closure and a function that references a global variable - the global variable can't fall out of scope. As I understand it, and particularly in the context of not-functional programming, a closure basically boils down to any function that refers to a variable from an enclosing scope, such that if the variable falls out of scope, but the function doesn't, then the function can still refer to that variable.

Of course, a global variable never will fall out of scope. Similarly, I wouldn't describe this as a closure:

Code: Select all

def f1(x):
  def f2():
    print(x)
  f2()
f1(5)
But this is a closure:

Code: Select all

def f1(x):
  def f2():
    print(x)
  return f2
f1(5)()
Even though the definition of f2 is identical... just how it's used is different, it's called from a place where the variable x has fallen out of scope and, in a language that didn't support closures, wouldn't exist any more.

Since a function that refers to a global can't be called from a place where the global is out of scope, it can't be used as a closure.

But if I'm using the term wrong, and f2 would be called a closure in my first example, then a function that uses a global should probably be called a closure too, 'cause the actual behavior is the same.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
Cosmologicon
Posts: 1806
Joined: Sat Nov 25, 2006 9:47 am UTC
Location: Cambridge MA USA
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Cosmologicon » Thu Oct 01, 2009 12:30 am UTC

This seems more nuanced than I thought. I think I understand what everyone is saying. But when a job interviewer asks me what a closure is, should I explain all these details?

User avatar
Xanthir
My HERO!!!
Posts: 5410
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Xanthir » Thu Oct 01, 2009 1:26 am UTC

phlip: Your first one is a closure, it's just an internal closure that nothing else has access to. In your second example f1 *returns* a closure.

cosmo: Just assume the interviewer means lexical closures. You'll almost certainly be right.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Berengal » Thu Oct 01, 2009 6:42 am UTC

Closures are functions with bound free variables. They're also damned neat things. I <3 closures.

And continuations, which when combined with closures can give you free exception handling and automatic cleanup of resources at whatever point you're done with them. Damn, functional programming has such a small and simple foundation, yet all these awesome things fall out when you shake it a bit.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
The Smithmeister
Posts: 11
Joined: Thu Aug 20, 2009 10:20 am UTC
Location: UK

Re: The "IT DOESN'T WORK!" thread

Postby The Smithmeister » Tue Oct 06, 2009 7:50 pm UTC

Ok, I've decided to teach myself a programming language, and a friend recommended Python. So, I'm reading a few of the 'Python for Beginners' tutorials, and I found this site http://www.freenetpages.co.uk/hp/alan.gauld/ which appears to be pretty good. Some of the way through it it gives an example of a program that prints a list of all the times tables from 2 to 12, and a bit later it shows an edit to this which allows the user to pick which times table they want instead of it just printing all of them. I thought that i could change this to allow the user to either press enter at the end to exit the program or press space to run it again.

I thought that i would need to define the times table section as a function, so I've managed (i think) to do that. I'm completely stuck on how to phrase the last section though. Would anyone have any idea how to do this (i'm sure it's fairly simple.)

Here is my code

Code: Select all

resp = raw_input("What's your name?")
print """Hi, %s, nice to meet you.
Here is a list of any times table you want.""" % resp
print '---------------'
multiplier = int(raw_input("Which times table do you want? Pick a number "))
####We have to define 'multipler' before defining 'ttable'.
def ttable(multiplier): #defines a function
    'Calculates the first 12 numbers of the x times table'
    for n in range(1,13):
        print "%d x %d = %d" % (n, multiplier, n * multiplier)
ttable(multiplier)
print '---------------'
final = raw_input("Press ENTER to quit.")

User avatar
mrbaggins
Posts: 1611
Joined: Tue Jan 15, 2008 3:23 am UTC
Location: Wagga, Australia

Re: The "IT DOESN'T WORK!" thread

Postby mrbaggins » Wed Oct 07, 2009 12:17 am UTC

I'm guessing it quits regardless?

Functions don't HAVE to be part of this, but they can be.
When you write functions, don't have them in the place they run at (May as well just be code), move them to the end or start of the program. What happens is the line

Code: Select all

ttable(multiplier)
substitutes the entire function into that spot (Not quite, but that's a cheap and effective explanation), and then the code looks prettier, especially if you call it multiple times in one section.


So I'd ditch the function lines

Code: Select all

def ttable(multiplier): #defines a function
&
ttable(multiplier)
because you're really only calling the function once. Then you can go over the input code and the printing code as one big section.

Now, as to making it go back over the code again...
Because you could in theory go around and around this section of code an infinite number of times, you'll need some sort of control structure that loops around it, until the specific action you want (Press the enter button) occurs.

You won't need to ask the name over and over, so the start of the loop can come under that. The end of the loop would be at or after the "Press ENTER to exit".

Because you want to run through the times table code at least once, you will want to check if they press enter at the END of the loop.

To check if they press enter, it's the same as asking if they didn't type anything before pressing it. So you'll need to check if the input is empty or not. If it's empty, they just pushed enter. Else, if it's not, then they didn't and you need to loop.

The relevant page on your tutorial site is the loops page and the branches page
NB These links will break his frames because he wrote the page silly.
Why is it that 4chan is either infinitely awesome, infinitely bad, or "lolwut", but never any intermediary level?

User avatar
The Smithmeister
Posts: 11
Joined: Thu Aug 20, 2009 10:20 am UTC
Location: UK

Re: The "IT DOESN'T WORK!" thread

Postby The Smithmeister » Wed Oct 07, 2009 6:32 am UTC

mrbaggins wrote:Because you want to run through the times table code at least once, you will want to check if they press enter at the END of the loop.

To check if they press enter, it's the same as asking if they didn't type anything before pressing it. So you'll need to check if the input is empty or not. If it's empty, they just pushed enter. Else, if it's not, then they didn't and you need to loop.


I'm not quite sure i understand you here. Would you mean something like this?

Code: Select all

multiplier = int(raw_input("Which times table do you want? Pick a number "))
if multiplier == "":
    raw_input("Press ENTER to quit.")
else:
    for n in range(1,13):
        print "%d x %d = %d" % (n, multiplier, n * multiplier)
    print '---------------'

because this doesn't seem to work. (If i have missed something obvious however, sorry.)

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Wed Oct 07, 2009 6:39 am UTC

You still need a loop of some kind... you read in a value, and print out a table, and then you're at the bottom of the program, so it finishes. You need some kind of looping structure around the whole thing so that it'll go back up the top and ask for your next multiplier. Have you learned about "while" loops yet?

Also: multiplier will never equal "", because it's always going to be an int... you're reading the input, converting it to an int, then checking if it's "". You need to read the input, check if it's "", then convert it to an int.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
mrbaggins
Posts: 1611
Joined: Tue Jan 15, 2008 3:23 am UTC
Location: Wagga, Australia

Re: The "IT DOESN'T WORK!" thread

Postby mrbaggins » Wed Oct 07, 2009 7:19 am UTC

You really should read the two pages I linked you too thoroughly. The loops one is very important. Especially, as phlip said, the while loops section.

In the end though, you want something like this. Mind you, this is NOT code. It's pseudocode, a useful tool for planning what you want to do.


Code: Select all

Get the persons name
Print out "Hi there" + name
Get a number from the user
START OF LOOP (If we're not finished)
    From 1 to 12
        Print out current number times the users number
    Ask user to enter another number, or just press enter to quit
    If they just hit enter
        Then we're finished
    Else
        Get a new number and go back to START OF LOOP


The next step is to start making this look like real code. Try to do it without looking below.

Spoiler:
NB: I've never really used python much and dislike it, so the parts I'm putting in might be slightly wrong, but the idea is right. Also, NEVER comment like this. I'm just doing it to explain every line for you and show how it matches the pseudocode above.

Code: Select all

finished = false                                                      #We've barely started, how can we be finished? :P
name = raw_input("What's your name?")                                 #Get the persons name
print """Hi there %s!""" % name                                       #Print out "Hi there" + name
multiplier = int(raw_input("What number do you want to multiply?")    #Get a number from the user
while (finished == false)                                             #START OF LOOP (if we're not finished)
    for n in range(1,13):                                             #    From 1 to 12
        print "%d x %d = %d" % (n, multiplier, n*multiplier)          #        Print out times table
    input = raw_input("Enter another number, or nothing to quit")     #    Ask for another number of nothing to exit
    if raw_input == ""                                                #    If they just hit enter
        finished = true                                               #        Then we're finished
    else                                                              #    Else,
        multiplier = int(input)                                       #        get a new number and go back to START OF LOOP


You'll notice I added one line. The "Finished" variable is called a flag. Basically, a flag is something that gets checked to see if it's changed. In this case, we check to see if 'finished = true'. If it is, the while loop won't run again (cos we're finished).


Hope this helps.
Why is it that 4chan is either infinitely awesome, infinitely bad, or "lolwut", but never any intermediary level?

User avatar
The Smithmeister
Posts: 11
Joined: Thu Aug 20, 2009 10:20 am UTC
Location: UK

Re: The "IT DOESN'T WORK!" thread

Postby The Smithmeister » Wed Oct 07, 2009 3:28 pm UTC

Ahh I see what i was missing now. Thank you very much both of you. I managed to get it to work without looking at what you had written mrbaggins. :)

User avatar
DieJay
Posts: 93
Joined: Tue Jun 30, 2009 4:45 pm UTC
Location: here be dragons
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby DieJay » Wed Oct 07, 2009 11:21 pm UTC

Hey there guys, maybe you could help me out on this one;

Let's say I got a binary file with 100 random characters. Now I want to go to a specific position in the file and replace a handful of characters by another. The file must not be recreated or appended to (to keep its size intact). The program is made in C++. How am I supposed to do that?

Here's the best I could come up with. The problem is that it overwrites the file before making the "changes";

Code: Select all

char buffer[10];
strcat(buffer,"abcdefghij");
ofstream myFile ("test2.dat", ios::binary);
if (myFile)
{
    myFile.seekp(5);
    myFile.write(buffer,10);
    myFile.close();
}


Also, this is made with the fstream library. Is it possible to do it with stdio.h?
Proud Duct-Tape Programmer since 2000.
"More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity."
-W.A. Wulf

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Berengal » Wed Oct 07, 2009 11:41 pm UTC

If it was me I'd just mmap the file and treat it as a byte array.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
Briareos
Posts: 1940
Joined: Thu Jul 12, 2007 12:40 pm UTC
Location: Town of the Big House

Re: The "IT DOESN'T WORK!" thread

Postby Briareos » Thu Oct 08, 2009 12:04 am UTC

Berengal, your single post inspired me to (finally) carefully read the man page for mmap, and write a little program that prints out the first 100 bytes of a file. It was cool, and I have no idea why I did it.
Sandry wrote:Bless you, Briareos.

Blriaraisghaasghoasufdpt.
Oregonaut wrote:Briareos is my new bestest friend.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: The "IT DOESN'T WORK!" thread

Postby headprogrammingczar » Thu Oct 08, 2009 12:30 am UTC

I am getting a strange issue trying to add achievements to a mod on Steam. Long story short, the "base game" for the mod (Source SDK Base) is loading its own (out of date) version of steam_api.dll, so when I try to run the game, it loads steam_api.dll, then when it loads client.dll, it tries to use steam_api.dll, can't find stuff it needs, and flips out. Unfortunately, pretty much everything I know about dlls is in this post, so I am stymied.
Last edited by headprogrammingczar on Thu Oct 08, 2009 12:45 am UTC, edited 1 time in total.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Thu Oct 08, 2009 12:33 am UTC

DieJay wrote:

Code: Select all

char buffer[10];
strcat(buffer,"abcdefghij");

... eww, no. First, why not just use an initialiser? Second, that will only work if buffer[0] == '\0', which isn't guaranteed, or even likely. Third, you're putting 11 things in a 10-element array.

As for doing in-place overwrites with stdio:

Code: Select all

FILE *fp = fopen("test2.dat", "rb+");
fseek(fp, 5, SEEK_SET);
fwrite("abcdefghij", 1, 10, fp);
fclose(fp);
(Plus relevent error handling, of course.)

The '+' in the mode string means to open for read/write. You still have to specify a reading or writing flag, though... but the only difference between "r+" and "a+" is where it's initially seeked to... either the start or the end, respectively. "w+" still blanks the file, but you can write stuff, then seek backwards and read it in again (good for temporary files).

But yeah, mmap would be easier.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
DieJay
Posts: 93
Joined: Tue Jun 30, 2009 4:45 pm UTC
Location: here be dragons
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby DieJay » Thu Oct 08, 2009 1:33 am UTC

phlip wrote:... eww, no. First, why not just use an initialiser? Second, that will only work if buffer[0] == '\0', which isn't guaranteed, or even likely. Third, you're putting 11 things in a 10-element array. [...] But yeah, mmap would be easier.


Yeah, it's been a while since I coded in c++, I forgot most of my pointers and strings theory. :oops: That's what I get for being a php maniac.

The program isn't actually made to handle alphanumerical data, just plain bytes, so it shouldn't be a problem, I probably won't use the string library at all. And I just copied the relevant code, hence why there's no explicit initialization.

Anyway, I didn't think of using rb+ as the mode, and of course, it works perfectly! I think I'll stick with that, thanks a lot 8)

Edit: Maybe I'll get shunned for asking, but what's mmap?...
Proud Duct-Tape Programmer since 2000.
"More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity."
-W.A. Wulf

Agent_Irons
Posts: 213
Joined: Wed Sep 10, 2008 3:54 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Agent_Irons » Wed Oct 14, 2009 8:25 am UTC

Lisp problem! Solved!
Spoiler:
I'm getting weirdness with my Erastosthenes Sieve (apostrophe?). I'm attempting to return a list of primes.

Code: Select all

(defun primedo (maxprime)
(let  ((primes (loop for i from 2 to maxprime collecting i)))
(do (
     (currentprime 2 (elt primes numprimes))
     (numprimes 1 (1+ numprimes)))
     ((> currentprime maxprime))
   (do
      ((trem (* currentprime currentprime) (+ trem currentprime)))
      ((> trem maxprime))
      (setf primes (remove trem primes))))
 primes))

That's the part that is not working. If I understand return values properly, my let expires, returning the last statement in the body of the let: (primes). The let is the last form in the body of primedo, and should be the return value of that. However, (primedo 200) throws an error about index 46 being out of range.


In the happy way of things, I realized that my first do stepform returned an error if primes had fewer than numprimes in it. This happened every time, unless the bounds were changed. Unhappily, this made every list of primes contain maxprime at the end. With a call to butlast, all was well. It now finds all primes less than maxprime, not less than or equal.

RFC?

Edit: I was swayed by the tutorial's elegant fibonacci bodiless do loops. This whole program is awful and kludgy. I have much to learn about The Lisp Way.
Last edited by Agent_Irons on Wed Oct 14, 2009 3:59 pm UTC, edited 1 time in total.

User avatar
Xanthir
My HERO!!!
Posts: 5410
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Xanthir » Wed Oct 14, 2009 2:29 pm UTC

Only comment I can make is that DO *blows*, and you shouldn't ever use it. LOOP is *much* more readable and easier to use for every single application that you could possibly use DO for.

Also, I recommend creating a RANGE function for when you want a bit list of numbers, so you don't have to create those trivial little inline LOOPs. Makes things clearer. I offer up my own:

Code: Select all

(defmacro range (from clause to &key (by 1))
  "Returns a list of numbers.  You must specify one (and only one) termination
    keyword: upto, below, downto, above, or length."
  (let ((x (gensym)))
    `(loop for ,x from ,from by ,by ,clause ,to collect ,x)))

Use as (range 2 :to maxprime).
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
Josephine
Posts: 2142
Joined: Wed Apr 08, 2009 5:53 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Josephine » Tue Oct 20, 2009 6:44 pm UTC

I'm a bit of a noob at this. This probably has a bunch of errors. Can someone here help me find them? (Python)

Code: Select all

def ispalindrome(x)
    y = len(x)/2
    z = 1
        for palindrome =< 0
        n = 0
        m = -1
        if x[n] = x[m]
            n = n + 1
            m = m - 1
            z = z + 1
        elif z = y
            return x + " is a palindrome."
       
            palindrome = 0
            print x + " entered was not a palindrome."


   

Belial wrote:Listen, what I'm saying is that he committed a felony with a zoo animal.

User avatar
Cosmologicon
Posts: 1806
Joined: Sat Nov 25, 2006 9:47 am UTC
Location: Cambridge MA USA
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Cosmologicon » Tue Oct 20, 2009 6:58 pm UTC

Without even knowing your algorithm, I recognize some obvious errors. If you use a "for", you need to have an "in", that says what sequence the loop variable iterates through. You probably want a "while". Your "=" in your if/elif statements should probably be "==". Your "=<" should probably be "<=", or maybe ">="? You need a colon at the end of lines starting with "def", "for", "if", and "elif". You also have some code within a block after a return statement. This code is unreachable.

If you still have trouble, try writing a slightly simpler function, like one that finds the sum of the elements of a sequence. See if you can get that much to work first.

User avatar
Josephine
Posts: 2142
Joined: Wed Apr 08, 2009 5:53 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Josephine » Tue Oct 20, 2009 9:24 pm UTC

Well, I found a much better way of doing that. But it still hits a problem.

Code: Select all

def palindrome(s):
    for i in range (len(s)/2):
        if s[1] != s[-(i+1)]:
            print "no"
        else print "yes"
       
   
Belial wrote:Listen, what I'm saying is that he committed a felony with a zoo animal.

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Tue Oct 20, 2009 10:56 pm UTC

You have "s[1]" where I think you mean "s[i]". Also, the "else" should be "else:", and it would be better if the print was on the next line.

Also, look at what you're telling it to do: you're looping through the characters, and checking (correctly) if they match their mirror-image in the string. But then for each pair, you're printing "yes" or "no", based on whether or not they match. Like, if you fed in "abccxa", you'd get "yes no yes". What you want is to say "no" if any pair doesn't match, or "yes" if all the pairs match.

Finally, you might want to try using "return True" and "return False" instead of print statements, so that you can re-use the function later in other things.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
RoadieRich
The Black Hand
Posts: 1037
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Behind you

Re: The "IT DOESN'T WORK!" thread

Postby RoadieRich » Thu Oct 22, 2009 5:03 pm UTC

nbonaparte wrote:Well, I found a much better way of doing that. But it still hits a problem.

Code: Select all

def palindrome(s):
    for i in range (len(s)/2):
        if s[1] != s[-(i+1)]:
            print "no"
        else print "yes"
       
   

What is the definition of a palindrome?
google: define palindrome wrote:a word or phrase that reads the same backward as forward


There is a function that returns an iterator over a reversed sequence. It's called reversed(). Because it returns an iterator, you need to turn it back into a string. This is one of the few things that annoy me about python, that the str function doesn't operate the same as list. So, you need to use "".join to turn it into a usable string:

Code: Select all

def palindrome_p(word):
    return "".join(reversed(word)) == word


Takes the word, reverses it (which returns an iterator), and joins the iterator back into a string. It then compares it to the original string. If they are the same, the word is a palindrome (as from the initial definition, above). The hard work is done by c-code, and will probably be faster than any hand-rolled function. It also shows quite clearly what is going on, so when you come back to the code in a couple of years, it won't take you long to figure out what the code does.

(the _p is a throw-over from my lisp-learnings: it stands for predicate, and indicates that the function returns a boolean. You might prefer to use, for example 'is' as a prefix: def isPalindrome(word):...)

Another way, using a wider range of the stdlib, is to use itertools.imap(), operator.eq(), and all(): all() loops through an iterable, and returns False when it hits the first non-true value, or True is it reaches the end. itertools.imap returns an iterator that takes each element of one or more sequences in order, and passes them to a function; it is a more efficient version of map of you don't want to create the whole list, but is going away in python 3. operator.eq takes two arguments, a and b, and returns True if a==b, or False otherwise. Linking them together with one function we've already seen, we get:

Code: Select all

def palindrome_p(s):
    return all(itertools.imap(operator.eq, s, reversed(s)))

Finally, there's a more pythonic way (imho) of reversing a string (or any sequence), that doesn't need all the messing about with "".join: str[::-1]. Also, allowing

Code: Select all

def palindrome_p(s):
    return s == s[::-1]

You could also combine that with itertools.imap(operator.eq, ...), as in the above example, and you could improve the slices to only iterate over half the sequence, but that would only obfuscate what is now easily readable code.

Finally, I would add docstrings to all of the functions, describing WHAT, not HOW. palindrome_p will always check that a string is palindromic, but whether it will use izip, a for loop, or string slices might change depending on fashion, processing time, and function availability:

Code: Select all

def palindrome_p(s):
    '''Tests whether a string is palindromic.'''
    return s == s[::-1]


And there we have it. Three lines of easily readable, probably more efficient, commented code, down from five with no comments.

Now to check the running time, using the 540 word palindrome from http://www.fun-with-words.com/palin_panama.html (abbreviated here for readability):

Code: Select all

>>> Timer("""
... palindrome(p)
... ""","""
... p = 'amanaplan...nalpanama'
... def palindrome(s):
...     for i in range(len(s)/2):
...         if s[i] != s[-i]:
...             return False
...     return True... """).repeat()
[13.819100141525269, 13.887668132781982, 14.350332975387573]
>>> Timer("""
... palindrome(p)
... ""","""
... p = 'amanaplan...nalpanama'
... def palindrome(s):
...     '''Tests whether a string is palindromic.'''
...     return s == s[::-1]
... """).repeat()
[4.9705159664154053, 4.9484109878540039, 4.9572808742523193]


I don't think you can argue with that.

Parsing the palindrome:
Spoiler:

Code: Select all

>>> p = '''A man, a plan, a caret, a ban, a myriad, a sum, a lac, a liar, a hoop, a pint, a catalpa, a gas, an oil, a bird, a yell, a vat, a caw, a pax, a wag, a tax, a nay, a ram, a cap, a yam, a gay, a tsar, a wall, a car, a luger, a ward, a bin, a woman, a vassal, a wolf, a tuna, a nit, a pall, a fret, a watt, a bay, a daub, a tan, a cab, a datum, a gall, a hat, a fag, a zap, a say, a jaw, a lay, a wet, a gallop, a tug, a trot, a trap, a tram, a torr, a caper, a top, a tonk, a toll, a ball, a fair, a sax, a minim, a tenor, a bass, a passer, a capital, a rut, an amen, a ted, a cabal, a tang, a sun, an ass, a maw, a sag, a jam, a dam, a sub, a salt, an axon, a sail, an ad, a wadi, a radian, a room, a rood, a rip, a tad, a pariah, a revel, a reel, a reed, a pool, a plug, a pin, a peek, a parabola, a dog, a pat, a cud, a nu, a fan, a pal, a rum, a nod, an eta, a lag, an eel, a batik, a mug, a mot, a nap, a maxim, a mood, a leek, a grub, a gob, a gel, a drab, a citadel, a total, a cedar, a tap, a gag, a rat, a manor, a bar, a gal, a cola, a pap, a yaw, a tab, a raj, a gab, a nag, a pagan, a bag, a jar, a bat, a way, a papa, a local, a gar, a baron, a mat, a rag, a gap, a tar, a decal, a tot, a led, a tic, a bard, a leg, a bog, a burg, a keel, a doom, a mix, a map, an atom, a gum, a kit, a baleen, a gala, a ten, a don, a mural, a pan, a faun, a ducat, a pagoda, a lob, a rap, a keep, a nip, a gulp, a loop, a deer, a leer, a lever, a hair, a pad, a tapir, a door, a moor, an aid, a raid, a wad, an alias, an ox, an atlas, a bus, a madam, a jag, a saw, a mass, an anus, a gnat, a lab, a cadet, an em, a natural, a tip, a caress, a pass, a baronet, a minimax, a sari, a fall, a ballot, a knot, a pot, a rep, a carrot, a mart, a part, a tort, a gut, a poll, a gateway, a law, a jay, a sap, a zag, a fat, a hall, a gamut, a dab, a can, a tabu, a day, a batt, a waterfall, a patina, a nut, a flow, a lass, a van, a mow, a nib, a draw, a regular, a call, a war, a stay, a gam, a yap, a cam, a ray, an ax, a tag, a wax, a paw, a cat, a valley, a drib, a lion, a saga, a plat, a catnip, a pooh, a rail, a calamus, a dairyman, a bater, a canal – Panama'''
>>> for c in " ,\xe2\x80\x93":
...    p = p.replace(c, "")
...
>>> p
'amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoilabirdayellavatacawapaxawagataxanayaramacapayamagayatsarawallacaralugerawardabinawomanavassalawolfatunaanitapallafretawattabayadaubatanacabadatumagallahatafagazapasayajawalayawetagallopatugatrotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenorabassapasseracapitalarutanamenatedacabalatangasunanassamawasagajamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatadapariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanuafanapalarumanodanetaalaganeelabatikamugamotanapamaximamoodaleekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabaragalacolaapapayawatabarajagabanagapaganabagajarabatawayapapaalocalagarabaronamataragagapataradecalatotaledaticabardalegabogaburgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamuralapanafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeraleverahairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadamajagasawamassananusagnatalabacadetanemanaturalatipacaressapassabaronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatortagutapollagatewayalawajayasapazagafatahallagamutadabacanatabuadayabattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacallawarastayagamayapacamarayanaxatagawaxapawacatavalleyadribalionasagaaplatacatnipapooharailacalamusadairymanabateracanalpanama'

This was then copy-and pasted into the functions, as I've yet to get timeit.Timer to work correctly with out-of scope definitions.
73, de KE8BSL loc EN26.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 7 guests