JasonHippy 739 Practically a Master Poster

I've just done a bit of digging around on python.org and found this:
http://bugs.python.org/issue1524

Looks like I'm not the first person to come up with this workaround....See the post made by daniel.weyh on the 25th June 2008.

Jas.

JasonHippy 739 Practically a Master Poster

It took a bit of playing around, but think I've found a workaround for this....

I noticed in the docs for os.system() (Yes I RTFM!) it mentions that the subprocess.call() should be used instead.
So I had a go with subprocess.call() but I soon ran into very similar problems, it still didn't like the spaces in the path.

After a bit of playing around and using a bit of lateral thinking I decided to try using subprocess.call() to call 'cmd.exe' passing it the path to a program in 'Program Files' as a parameter.

Now, I don't have winamp installed on my pc, so I decided to try and fire up Audacity using the following code:

import subprocess

subprocess.call(r'C:\WINDOWS\system32\cmd.exe /C "C:\Program Files\Audacity\audacity.exe"')

And you know what?? It bloody works!

After that, I decided to try using os.system in exactly the same way (use it to fire up cmd.exe with the path to Audacity as a parameter):

import os

os.system(r'C:\WINDOWS\system32\cmd.exe /C "C:\Program Files\Audacity\audacity.exe"')

Guess what??
That worked too!

Woot woot! :)

You'll get a little cmd window that will pop-up alongside whatever program you fire up, but it will disappear when you close the program down again.

So, all you need to do is copy one of the bits of code posted above and then replace my path to Audacity with the path to your installation of Winamp!

Hope that solves your problem.
Cheers for now,
Jas.

pysup commented: cool.. Thanks +1
JasonHippy 739 Practically a Master Poster

Awesome I like it just one question why does the line below have datetime twice?

d = datetime.datetime.strptime(userIn, "%d/%m/%y")

It's the only way I could access the strptime function.
The first datetime refers to the datetime package, the second refers to the datetime class.

In my import I could have used something like:

import datetime as dt

This gives the datetime package an alias (dt). So to call the strptime function I'd need to use:

dt.datetime.strptime(userInput, pattern)

So my strptime function call breaks into the following parts:
packageName.className.function(parameter1, parameter2)
or:
datetime.datetime.strptime(userInput, "%d/%m/%y")

Hope that clarifies things for you!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Firstly 'input' is a reserved word in python, it's used to get input from the user, (rather like raw_input!). So that's why this line of code fails to do anything:

input = raw_input("Type Date dd/mm/year: ")

Change your variable 'input' to something like 'userInput' or just anything that isn't a reserved word and you will get your prompt!

Secondly...No I don't think that strptime will work used like that! if your users enter anything other than yy-mm-dd, it will bomb out with an error!
But if you use a try: except: block inside a loop, you should be able to get the user to repeatedly enter the date until the format is correct!

Check this out:

import datetime
def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date dd/mm/yy: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d = datetime.datetime.strptime(userIn, "%d/%m/%y")
            isValid=True
        except:
            print "Doh, try again!\n"
    return d

#test the function
print ObtainDate()

I've not done any exception handling code for a while, but there should be a way of outputting to the user the reason that the exception occurred.

I'll leave that up to you to look up!

Cheers for now,
Jas

JasonHippy 739 Practically a Master Poster

OK, I started working on this when I saw your original post. But since I started, you made your second post. So I've modified it a little to give the line numbers; but I've not got it to output the character position yet!

I've done the search using the re module (regular expressions).

Here's the code I've got so far...It only works if all lines in birthday.txt end with a newline! Otherwise the last line gets a character removed by my code!

Anyway, this is what I've got so far: (not quite the same as yours but it kinda does the job!)

import string
import re

def find():
    # read both text files in their entirety...
    piDigits = open("pidigits.txt").readlines()
    birthdays = open("birthday.txt").readlines()

    # iterate through the dates
    for date in birthdays:
        wasFound=False

        # build a search string
        # need to strip out the newlines...
        # ensure each line in birthday.txt ends with a newline
        # otherwise the last birthday will have the last digit removed!
        searchString=""
        for idx in range(0, len(date)-1):
            searchString+=date[idx]

        # as long as we have exactly 6 chars in the search string
        # we can continue!
        if len(searchString)==6:
            print "\n\nSearching for", searchString, ":"
            # iterate through the piDigits and use the re module
            # (Regular expressions) to see if the birthday is found
            count=0
            for line in piDigits:
                count+=1
                result = re.search(searchString, line)
                if result: # if found, set flag and output.
                    wasFound=True
                    print "The birthday", searchString, "was found at line ", count …
JasonHippy 739 Practically a Master Poster

The description of your problem is at best vague and at worst confusing...Being able to see the code that's actually causing you the problem would help!
So if you could post some code it would help us to help you! (Just don't forget the code tags!)


Also, regarding your question about void main vs int main....Well that particular issue has been discussed numerous times here on Daniweb.
Take a look at:
http://www.daniweb.com/forums/thread109415.html
or:
http://www.daniweb.com/forums/thread78955.html

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

What about replacing the backslashes with forward slashes?
So wherever there was a single backslash, replace it with a forward slash. That should also fix your problem!

I know typically in Windows, filepaths look like this:
C:\SomeDirectory\SomeFile.ext

But in C++ forward slashes are also acceptable for file paths..
c:/SomeDirectory/SomeFile.ext

The obvious reason for using forward slashes is to avoid the problems with backslashes in C/C++ strings.

A backslash in a C/C++ string is an escape sequence for special characters like '\n'. Double backslashes '\\' is the escape sequence used to put a single backslash into a string!

So instead of replacing the single backslashes with doubles; replace them with forward slashes and you can circumvent the entire problem.. I use forward slashes all the time in file paths and have never experienced any problems!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Here's something I just knocked up in a few minutes....This isn't exactly what you're doing, but it should give you a few ideas to use in your game.

My variant uses one tower. The player starts with 50 blocks in their tower.
The computer will then draw random cards (valued from 1-10) and will then add or remove blocks from the players tower until the maximum or minimum number of blocks has been reached.
Odd numbered cards remove blocks, even numbers add blocks. Cards are worth 5,10,15,20 or 25 blocks.

I'm not sure how au fait you are with python, so I've used some pretty simple code and commented it heavily....

Without further ado, here's the listing:

import random

# set up our maximum and minimum number of blocks
MAXBLOCKS=100
MINBLOCKS=0

# set up the initial number of blocks in the tower
userBlocks=50

# count how many cards are dealt in the game
dealCount=0

# some instructions:
print "The aim is to get 100 or more blocks in your tower."
print "The computer will randomly select a card for you (1-10)."
print "The value of the card will affect your towers height."
print "Even numbers add blocks, odd numbers remove blocks."
print "Cards are worth the following:"
print " Card value    -    Block Value"
print "================================"
print "    1,2        -     +/- 05"
print "    3,4        -     +/- 10"
print "    5,6        -     +/- 15"
print "    7,8        -     +/- 20"
print "    9,10       - …
JasonHippy 739 Practically a Master Poster

Hi folks
I have just completed my first programme with help from yourselves.
I cant understand why the code , if x ==1 or 2, wouldn't work in my programme below

# Convert C to F or F to C and return with result

select = True
while select:
    x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n'))   
    if x == 1 or x == 2:
        select = False
    else:
        print 'Only options are 1 or 2'            

#Convert C to F
if x == 1:
    def Tc_to_Tf ():        
        Tc = input ("What is the Celsius Temperature ?   " )
        Tf = 9.0/5.0 * Tc + 32
        return Tf
    Tf = Tc_to_Tf ()
    #.2f instructs Python that placeholder holds float number with 2decimal places. 
    print 'The temperature is %.2f Degrees Fahrenheit' %(Tf, )
        
#Convert F to C
if x == 2:
    def Tf_to_Tc ():
        Tf = input ("What is the Fahrenheit Temperature ?   " )
        Tc = (5.0/9.0)*(Tf - 32)
        return Tc
    Tc = Tf_to_Tc ()
    print 'The temperature is %.2f Degrees Celsius' %(Tc, )

Many thanks in anticipation. I included the whole programme as I would value any comments on my methods.
Graham

I can't see a problem with the code you've posted!

However if you were using this before:

if x==1 or 2:

Then as gerard has said, the if statement would always evaluate to True...

for example if the user entered '4' as their first choice, …

sneekula commented: great explanation +8
JasonHippy 739 Practically a Master Poster

This block of code looks like it's presenting the problem:

elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    elderly.moveup()
                if event.key == pygame.K_DOWN:
                    elderly.movedown()
                if event.key == pygame.K_RIGHT:
                    elderly.moveright()
                if event.key == pygame.K.LEFT:
                    elderly.moveleft()
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
                    elderly.movepos = [0,0]
                    elderly.state = "still"

If you take another look at your Elderly class, it doesn't have any methods defined called moveright(), moveleft(), moveup(), or movedown(), or properties called movepos or state for that matter either!

So you'll need to define them in your Elderly class.
e.g.
inside your definition of Elderly you need to define the moveup function (and the other missing functions like this):

def moveup():
            #TODO: add code to move your elder upwards

        def movedown():
            #TODO: add code to move your elder downwards

            # etc etc.....

You should also add and initialise the missing properties (movepos and state) in the __init__ function for the Elderly class!

Give that a go and let us know how you get on!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Looking at your original post again, if it's just a case of removing the stuff after the decimal point and then adding your commas in the appropriate place, i'd probably do the following:

If you're perfoming your calculations using ordinary floating point arithmetic:
1. perform your calculations
2. convert your results to int (thereby removing the decimal digits)
3. convert to string
4. parse through the string and add commas.

steps 2 & 3 above could be done in one line:

strVal = str(int(calculatedVal))

If you used the Decimal class to perform your calculations, and your results are already in strings then:
1. Perform your calculations
2. Use split, as mentioned by djidjadji (but don't cast the first part to an int keep it as a string!)
3. parse through the resultant string and add your commas.

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

If all you want to do is remove the floating point digits you could do this:

floatValue=3.141
integerValue = int(floatValue)
print "The integer equivalent of", floatValue, "is", integerValue

Note: The above code is python 2.x syntax. For python 3.x change the print statement to:

print("The integer equivalent of", floatValue, "is", integerValue)

All this does is create a new integer based on the value of the floatValue. Anything after the decimal point is discarded in the integerValue.

Alternatively, because python variables can hold any data-type, there's nothing stopping you from doing this:

value=3.141
print "The initial value is:", value
value = int(value)
print "The value is now:", value

Again, if you're using python 3.x, you'll need to alter the print statements.

All the above code segment does is converts the float value into an integer. So initially value holds a float, but line 3 changes it to an int. Again, anything after the decimal point is simply discarded.

Another alternative is rounding using math.floor() or math.ceil().
math.floor will round down to the nearest whole number and math.ceil will round up to the nearest whole number.
Using floor or ceil will allow your values to remain as floats.

import math

value=3.1412
print "Value is:", value
print "math.ceil() rounds value up to: ", math.ceil(value)
print "math.floor() rounds value down to:", math.floor(value)

Again, this was 2.x syntax, alter the print statements if you're using 3.x.

The thing to bear in mind with all of …

JasonHippy 739 Practically a Master Poster

Your indentation goes a bit off from line 26 onwards (but that is more of an aesthetic thing which affects the readability of your code, it doesn't affect the code in any other way..The compiler doesn't care about whitespace or readability of code..As long as the syntax is correct the compiler is happy!)

Also your switch statement is incorrect. You need to move your cout and cin statements outside the switch statement. As it stands they'll only get called if the user enters something other than S or R.

Once you've moved those out of the switch, you'll also need to add an opening brace under your 2nd 'for' loop (don't forget to add a closing brace further down!). You should declare your 2nd for loop as Ancient Dragon has suggested.

In other words, your 2nd for loop should look like this:

for (int j = 0; j < nrAttend; ++j)
    {
    	switch (vote)
    	{
        	case 'S':
        		votesForS++; 
			break;
        	case 'R':
        		votesForR++; 
			break;
        	default:
        		votesForO++;
     	}   
     	cout << "Next: For whom do you vote? ";
     	cin >> vote;
    }

TECHNICAL NOTE: In Ancient Dragons code (and in my code above), we've used the prefix increment operator (++j) instead of the postfix operator (j++) in the increment section of the for loop. This is an old C/C++ optimisation trick.

All you need to know is that the prefix operator is a teeny tiny bit quicker than the postfix operator (I could explain further, but I can't …

JasonHippy 739 Practically a Master Poster

I have this piece of code

// some function
int px;
void SomeFunction( void *dummy )
{
	...

	RECT rect;
	GetWindowRect(hWnd, &rect);
	px = ((rect.right - rect.left) / 2) - 60;

	...

	// Terminate thread
	_endthread();
}

And my problem is px doesn't get assigned.. it stays 0.. although in the debugger I can see all the values inside rect..
please help me

What about if you change px from int to long? Does that give you any differemt results?
The thing to take note of here is that px is currently declared as an int. Whereas rect.right and rect.left are both LONG/long variables.

Therefore if the result of your calculation is less than 1.0 (e.g. something like 0.43455664), then because px is an int, the calculated value will be truncated to 0.
Whereas if you alter px to be long, you'll get the actual calculated value (in my example 0.4345564).

I could be wrong, but that looks like the most obvious explanation to me!

oh, hang on.....Looking at that code, another thing strikes me as odd....
px is declared outside of the function, but used inside it..
That's probably your problem right there!
The px used in the function and the px outside of the function might not be the same variable, they might have different scope.
If you could post some more code, we might be able to determine whether or not this is the case!

Cheers for …

Salem commented: Two px's in scope could easily explain it +36
JasonHippy 739 Practically a Master Poster

OK, well the error messages say it all...
For starters you need to uncomment the definition of RAND_MAX which is the cause of your error.

Secondly, as Salem has pointed out, you need to include stdlib.h, which will get rid of the warnings about rand and srand.

Finally line 116:

i = (randomperc() * (high - low + 1)) + low;

The variable 'i' has been declared as a long, as have the variables 'high' and 'low'. The randomperc function returns a double, which is the cause of the final warning, basically it's telling you that the double will automatically be converted to long and that it could result in a loss of precision (due to the inherent floating point issues.)
Being a warning, you could just ignore it, but it could be worth explicitly casting the value returned by randomperc to long.
i.e.

i = ( ((long)randomperc()) * (high - low + 1)) + low;

Which will stop the warning from occurring.

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

This concept seems really strange to me...
You've created a class called Mp3 and a class derived from Mp3 called Frame, but the Mp3 class has members which are instances of Frames???

I could be wrong, but I don't think it's possible to do that in C++. In all my years, I've certainly never seen or heard of it being done before!

This sounds like a paradox kinda like the chicken and egg scenario... Which came first, Mp3 or Frame? Mp3 is a class which uses Frame, and Frame is derived from Mp3 (where Mp3 is a class which uses Frame, which is derived from Mp3, which uses Frame.....etc ad nauseum.). It all seems a little incestuous and ultimately unnecessary!

You could declare two classes Mp3 and Frame and you could get Mp3 to use instances of Frame in it. But I don't think that there's any need to derive Frame from Mp3.

Personally, I think you need to rethink your design!
Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Quick background: I'm working on Project Euler and made a palindrome checker. I needed to convert integers to strings. itoa() kept giving random values (9 gave 9 or 90, etc...), so I decided to make my own, and ran into a problem. I have fixed it, but could somebody explain what caused the problem and why the fix works?

Broken Code: The below code creates a stringstream inputs the number then puts that into a string and then into a char. The problem is it would chop the last number off when returning the char. (The buffer holds the 99800 value but the receiving variable numaschar = strItoA(num); becomes 9980.)

char* strItoA(int number)
{
   std::ostringstream sin;
   sin << number;
   std::string val = sin.str();

  size_t length;
  char buffer[val.size()+1]; //add one for the zero terminator
  length=val.copy(buffer,val.length(),0); //do the transfer and grab the last position
  buffer[length]='\0'; //zero terminate!!
  return buffer;
}

The Fix:

char* buffer; //moved outside of function and given reference

char* strItoA(int number)
{
//Same...

  buffer = new char [val.size()+1]; //added to keep buffer dynamic
//char buffer[val.size()+1]; //removed
//Same...
}

Thanks. :)

Looking briefly at the first block of code, I think it's because the char buffer is declared inside your function and only has scope inside your function. So as soon as your function returns, the object referenced by the returned value has been invalidated as it is out of scope. In which case you're lucky to have anything sensible at all in the return value. That or perhaps you were overwriting …

JasonHippy 739 Practically a Master Poster

What have you got so far?

JasonHippy 739 Practically a Master Poster

.ttf files are basically just fonts.

In order to be able to use them, what you need to do is install the font on your system and then you should be able to use the font in any application that uses system fonts to display text, be they office/openoffice applications or desktop publishing/graphics applications (word, photoshop, flash..whatever!)

To install the font on windows XP (and probably almost any other version of windows), you can do either it via the control panel...by selecting the fonts link and then follow the instructions for installing your .ttf file.

Alternatively, via windows explorer, open two instances of windows explorer, in the first window, navigate to wherever your new .ttf file is. In the other explorer window, navigate into the system fonts directory, (typically C:\WINDOWS\Fonts\).

Now you have two options, you can either:
Copy the .ttf file in the first window and paste it into the 2nd window.
OR:
drag the .ttf file from the first window to the 2nd window.

Whatever of these actions you choose, the outcome will be more or less the same. The .ttf file will be moved/copied into the system fonts directory and windows will automatically register it as a system font.

Next fire up an application and you can select the font from the list of fonts.
i.e. open a word processor like word and click on the font drop-down list and you should be able to see the …

JasonHippy 739 Practically a Master Poster

OK,
After this line:

label = Tkinter.Label(pg4_group.interior(), image=photo)

try adding the following:

label.photo = photo

This will create an instance of your image in the label, preventing it from being garbage collected (Which is what I suspect is going on!).


Next, after your call to label.place, add the following:

label.pack()

Your final file should look something like this:

from tkFileDialog import *
import Image, ImageTk,Pmw, Tkinter

class Demo:
    def __init__(self, parent):
        notebook = Pmw.NoteBook(parent)
        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        page_4 = notebook.add('About')
        pg4_group = Pmw.Group(page_4, tag_text = 'Picture')
        pg4_group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        image = Image.open("pic.JPG")
        photo = ImageTk.PhotoImage(image)
        label = Tkinter.Label(pg4_group.interior(),image=photo)
        label.photo = photo #prevent photo from being garbage collected
        label.place(x=0,y=0,width=image.size[0],height=image.size[1])
        label.pack() # display the image
        
if __name__ == '__main__':
    root = Tkinter.Tk()
    Pmw.initialise(root)
    widget = Demo(root)
    root.mainloop()

Now your image should appear and your problems should be solved!

Cheers for now,
Jas.

P.S. See the following link for more details on the Tkinter.Label widget:
http://effbot.org/tkinterbook/label.htm

bumsfeld commented: nice help! +7
JasonHippy 739 Practically a Master Poster

Assuming this is a wireless connection you're having this problem on, I had similar problems with one of my machines issuing the media disconnected message a while ago when trying to connect to a wireless network. It always used to work, but one day I started to get these media disconnected errors..

My router was allowing my machine to connect to the network, so I assumed that everything was OK. But I couldn't access anything on the network (other machines, the internet etc.). Whenever I did an ipconfig /renew I kept getting the media disconnected message.

After much unsuccessful puzzling and googling, I was about to give up. But then I decided to completely remove the wireless connection from my list of connections and try connecting again.
So I disconnected from the network, removed the network from my list of networks to auto connect to and then selected the wireless network in the list of available wireless networks.
I then manually entered my WEP key to connect to the network and........

The connection to the network succeeded..."OK" I thought, "but that doesn't prove anything, it said I was connected before!"

However, a quick ipconfig /renew showed that everything was indeed hunky dory. IP addresses were all valid and correct and most importantly no media disconnected messages. Suddenly the internet was working and I could access the rest of the network....

So what had happened??
Well, in my case it looks like the …

JasonHippy 739 Practically a Master Poster

I concur with Raja!

If you open up the movie clip containing the images and the scroll bar (the instance of library object "scroll 3" called "ins_revistas").
Take a look at the movie-clips containing pictures 1-12 at frame 1 and pictures 13-24 in frame 2, you'll see that both clips have instance names of: "ins_revistas_de_1-12" and "ins_revistas_de_13-24".

Now if you look at the movieclip containing pictures 25-27 at frame 3, you can see that there is no instance name.
Give the clip an instance name of "ins_revistas_de_25-27" and that should resolve your problem!

Nice Job Raja!

Jas.

JasonHippy 739 Practically a Master Poster

In my opinion nothing beats the full flash suite.

You need all the little perks like the timeline and everything.

Going slightly off-topic from the OP:
The timeline can be handy for quick and dirty stuff, but personally I prefer not to use it as far as possible. Especially since the advent of AS3/Flex!

If I ever need to use the timeline (which is rare!), it's about the only time I'll fire up one of the Flash IDE's. Other than that it's Flashdevelop (on windows) or the Flex SDK (on Linux) all the way!

Thinking back to my previous job back in the days of AS2, having to debug all of those nasty third party .fla's with hundreds of layers containing nested movieclips and actionscript buried here, there and everywhere.....ugh! {shivers} Not a pretty time!

Coming from a C++ background, I much prefer dealing with classes and scripting everything myself.

As I've said, the timeline can be a handy tool from time to time. But from what I've seen, even in professional production code; it is frequently overused and/or abused, resulting in horrific, mind meltingly convoluted spaghetti-like sources. So personally, I'm more than happy to leave the timeline behind!

But that's just me! heh heh! ;)

JasonHippy 739 Practically a Master Poster

I'm not aware of any linux software that deals with flash, certainly nothing that will open .fla's. There are some attempts to make a linux port of Flashdevelop (a free Windows/.NET based IDE for the Flex 3 SDK), but I don't think they've got very far with it yet.

As Vishesh has already said, you could try using Wine to run one of the flash IDE's. Flash mx2004 will probably work well under wine, flash 8 might also work, but I have serious doubts that CS3 or CS4 will work properly.
The windows version of Flashdevelop might also run under wine.

Another usually overlooked alternative is the Adobe Flex3 SDK, which can be used to create flash content in Linux using pure AS3 or AS3 and mxml.

The flex3 SDK ships with some multi-platform command line tools, the bin folder of the SDK contains binaries for windows, mac and linux. To get it, all you need to do is download it from Adobe and unzip it somewhere on your system. And that's it, you're ready to start developing flash in Linux!

The only pre-requisites are that you need to have java installed on your Linux system...But that's not really a stretch, if your machine doesn't have Java, open up your package manager and download and install it from your linux distros repository.

To use the SDK in linux, you simply use a text editor like gEdit, vi or emacs to create your mxml and/or …

JasonHippy 739 Practically a Master Poster

This one was pretty straightforward...

Take a look at divisions.xml

If you look at the entry for "Eyesite" you can see that the "[CDATA[" tag at the start of the line hasn't been closed properly at the end.
The line currently ends with:

in an effective manner.</Option>

The end of this line of xml should read:

in an effective manner.]]></Option>

That will solve your extra space issue for this file....

In answer to your scrollbar question, the scrollbar appears to have been created by the original author of this .swf, created entirely from scratch. So it's not a standard flash UI scrollbar component.

Cheers for now,
Jas.

sandra21 commented: completely solved my problem +1
JasonHippy 739 Practically a Master Poster

That's really odd!

What class/classes are your buttons derived from?

It sounds as if addEventListener is not a valid property of your button class...I'm not sure what's going on there!

JasonHippy 739 Practically a Master Poster

In answer to this question:
Take a look at the actionscript on the scroll bar instance at frame 30 on layer 52..
The actionscript says:

onClipEvent (construct)
{
    _targetInstanceName = "txt5";
    horizontal = false;
}

Something struck me as odd while looking at this. The scrollbar in question has an instance name of txt5...Which seems very odd...The scrollbar is targeting itself?? That's not right!

From looking at the other instances of the scrollbar in other frames of the .fla, the other scrollbar instances have no instance name and their _targetInstanceName properties seem to refer to the instance names of the textboxes in the frames.

With this in mind, looking at the instance name of the textbox at frame 30 (layer 54) the instance name of the textbox is "detail_txt5".

So you have two options to fix this...
At frame 30 you can either:
1. Change the text box instance name to "txt5" and remove the scrollbars instance name.
OR
2. Alter the actionscript on the scrollbar to:

onClipEvent (construct)
{
    _targetInstanceName = "detail_txt5";
    horizontal = false;
}

Either way, that will solve your problem and the scrollbar will work.

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Believe it or not, I think it's your gotoAndStop() calls in your click handlers that are causing the error.

If memory serves correctly, when you use addEventListener to attach an event handler function to an instance of an object of any class, I think the code in the handler function refers to the attached object. So the handler has the objects scope rather than global scope.

In other words, your gotoAndStop() calls are trying to make your buttons gotoAndStop at the specified frame rather than making the parent movieclip stop at the specified frame in the timeline.

Now, you've said that you're using your own custom button class. I know if it was me, I'd derive from Sprite, so I'm assuming you've done the same....
If this is the case, then you should be informed that gotoAndStop is not a property of the Sprite class. Which is most likely why you're getting the error you mentioned! A Sprite is basically a MovieClip without a timeline, so there is no need for things like stop(), play(), gotoAndStop() or gotoAndPlay().

If your buttons are derived from MovieClip, it could be because your button clip doesn't have thirty-something frames!

So how do you get around it and access the timeline of the parent clip?
Well, I know that in traditional timeline based flash programming (in AS1/AS2) you'd use _parent to refer to the parent clip.
So to access the main timeline from your button instance …

JasonHippy 739 Practically a Master Poster

i tried this, result is different but not as expected either.

byte = abc.B_ABC_Function02(hex(p2), hex(p3))

Do you need to convert the returned value to hex perhaps??
i.e.

byte = hex( abc.B_ABC_Function02(hex(p2), hex(p3)) )

The above code should set the value of byte to be a hexadecimal representation of the value returned by your abc.B_ABC_Function02() call.
Does that give you the expected result?
Jas.

JasonHippy 739 Practically a Master Poster

If you're using the windows version of Python3.0 and for some reason you haven't got the shortcuts to idle (i.e. the installer failed to create them, you accidentally deleted them or you used a source package rather than the installer) you can create them manually by right-clicking on your desktop and selecting new->shortcut.
Next, navigate to idle.pyw and select OK and the shortcut will be created...

On a typical windows python install, you'll find idle in the following directory:
C:\python30\lib\idlelib\idle.pyw

If you're on *nix, you'll have to either download and install the idle-python3.0 package with your OS's package manager or via the command line (see shadwicks post for ubuntu cmd line example!)

Cheers for now,
Jas.

p.s. If you used a source package and/or you can't find idle.pyw, try downloading the windows installer and install it that way instead!

JasonHippy 739 Practically a Master Poster

I'm not sure what's causing the problem, but it also occurs in IE7!

I usually use firefox, but I took a peek at the site in IE7 (nice site BTW!) and had exactly the same problem you described in IE8.

The page flashed up and then disappeared and IE showed an error saying that it couldn't load the page..refreshing didn't work..going back/forwards and entering the URL manually didn't work either.

I deleted my cache and reloaded the page and lo and behold it worked...

The only difference I had in IE7 was that afterwards I could refresh the page and navigate away and return to it with no problem. So it only happened the first time for me!

Viewing the source, everything looks more or less ok..I can't see anything obvious in there!
Perhaps it's a bug in IE. It may be worth having a look on the Microsoft site to see if it's a known issue and if there are any workarounds...

Alternatively, perhaps put a front page/intro on your site (one of those 'click here to enter' kinda deals) with a disclaimer stating that the site is best viewed using ANYTHING other than IE, or perhaps more something more constructive like instructing IE users to delete their cache if the site fails to load for them!

Other than that, I'm pretty much out of ideas!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

From what I can see it looks like it's because you are calling newName.ShowModal() twice in your code.
In the first call to DoModal in your if statement, a dialog is created and if the user presses ok and has entered some text the dialog is destroyed and your while loop breaks out.
If the user presses ok after entering no text, the dialog is destroyed, your while loop reiterates and the first call to ShowModal is called again. OK so far, I assume this is the behaviour you want.

But if the user closes the initial text box with cancel, your code drops to the elif statement where DoModal is called a second time, creating a 2nd dialog.. In the 2nd call, whether the dialog returns via ok or cancel it will be destroyed.
So it is the call to DoModal in the elif that is the problem!

What you need to do is alter your code so that you're making one call to DoModal and then see what value was returned..
So I'm guessing you'd need to do something like this:

def OnNewButton(self,event):
        error=1
        while error==1:
            newName = wx.TextEntryDialog(self, 'Question?:','Title')
            newName.SetValue("")
            retVal = newName.ShowModal()
            if retVal == wx.ID_OK:
                if len(newName.GetValue().strip())!=0:
                    error=0
                    self.Destroy()
            elif retval == wx.ID_CANCEL:
                error=0
            newName.Destroy()

Hope that solves your problem!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster


I personally feel that for you the best way to return your doubles is with a struct.

I second that motion!
That would be preferable to the method I put forward.

I just wasn't sure how familiar the OP was with structs, pointers and arrays. So I went with the simplest example passing each value separately....

Although looking my post now, why I posted the entire body of the function instead of just posting a more compact example is beyond me! heh heh ;)

Good solution Sky!

JasonHippy 739 Practically a Master Poster

As the other guys have suggested, there are several ways around the problem.
The error you're getting is because your F_Ite() function does not return a value.

A function can only return one value, the only way of returning several values would be to either create all of the variables you want returned outside of your function and pass them into your function as pointers or references, or pass them as an array of pointers.
You could then change the return type of the function to void as the function will manipulate the contents of the pointers, so it won't need to return anything.

Or you could get your function to return an array of pointers.

I'm not sure how au-fait you are with the idea of pointers and arrays, so for now I'll go with the idea of creating the values outside of the function and passing them individually as pointers.
Here's what the code would look like:

#include<iostream>
#include<cmath>

// pass values into your function
void F_Ite(double *a, double *b, double *c, double *d, double *Fc, double *Fd)
{ //Main Function Start
	// you could initialise your variables here, or outside of the function.
	// I've gone for the latter, but whatever floats your boat!

	for(int k=1;k<(NI-1);k++)
	{ //Main 'for' Loop Start
		std::cout <<"\n";
		system("pause");
		std::cout <<"\n";
		std::cout <<"At The "<<k+1<<" Iteration :\n";

		if(Fc[k]<Fd[k])
		{ //Outer 'if' Start
			a[k+1]=a[k];
			std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << …
JasonHippy 739 Practically a Master Poster

Hi, guys
I've a little problem, again. Before closing the thread I just wanted to ask. As you might have seen from the code, I'm reading array from the file. I want my flash to be resized depending on the array size read from a file.

I don't know whether I'm using correct word to explain what I want.
I want every square to be 100x100 always, and depending on the array size I want my flash size to resized. For instance if array is 5x5, then I want flash animation to be 500x500, if array size is 100x100, my flash will be 10000x10000. It's ok if there will be scrollbars. Is there a way to achieve this?
Thanks again.

Sorry dude, I haven't had a chance to puzzle over this properly yet!

My initial thoughts are that you'll probably have to restructure your code a little. All of the code for loading your text file and drawing and animating your arrows should probaly be moved out of Main and into a class of it's own (ArrowAnimation.as??).

Then you can set the size of the Main.swf [500X500] and add an instance of your animation to the stage inside Main.
This way your arrow animation should appear at full-size. But as you've already mentioned, it may not fit inside the visible area of the main frame (depending on the amount of data in the data file).

Bearing this in mind:
After …

JasonHippy 739 Practically a Master Poster

Ok, I think I see the problem. It's not related to publish settings or erroneous code, its a security issue...

I downloaded your code to my desktop and unzipped it to a directory called ide. I then loaded Main.as into FlashDevelop and pressed Ctrl-F8 to build the .swf.
The swf built successfully and ran ok in a standalone player in the FlashDevelop IDE...Lots of squares with different sized arrows pointing in different directions and moving around..OK good so far.

I knocked up a quick and dirty HTML page to embed the swf and opened the page with Firefox and I got a blank blue .swf...Not so good!

I then opened up the directory containing the swf on my desktop and tried to run the swf in a standalone instance of Flash player (flash player 10) and got the following error message:

SecurityError: Error #2148: SWF file file:///C|/Documents%20and%20Settings/Jason/Desktop/ide/Main.swf cannot access local resource file:///C|/Documents%20and%20Settings/Jason/Desktop/ide/data.txt. Only local-with-filesystem and trusted local SWF files may access local resources.
at flash.net::URLStream/load()
at flash.net::URLLoader/load()
at Main/::readMatrix()
at Main$iinit()

This is a pretty straightforward thing to get around, what you need to do is inform flashplayer that your .swf is a trusted file and that you give explicit permission for it to access the local file-system.
"How do I do that??" I hear you cry "Do I need to sign a permission slip for its teacher?"

Well, to do this the following simple steps are …

NeoKyrgyz commented: As always best and correct answer. Thanks again. +1
JasonHippy 739 Practically a Master Poster

To better diagnose the problem it would be worth trying to run the .swf directly from the desktop in a standalone version of flash player, instead of via a browser plugin.
To do this, navigate to your .swfs directory on the hard drive and double click on it and the standalone player should load and run the file!

If it doesn't work properly in the standalone player, then it is most likely that your actionscript for loading the text file is incorrect.
In which case, it would be an idea to upload some code so we can see what's going on.

However, if it works properly in the standalone player, then it could be a problem with your publish settings...Unfortunately I'm on my wifes laptop at the moment, so I don't have Flashdevelop handy and can't give any suggestions on what to try.

For now, try running your swf in a standalone instance of flashplayer and let us know how you get on!

All the best.
J.

JasonHippy 739 Practically a Master Poster

Excellent, not begging or having a go or anything, but any chance you can mark this as solved??

J.

JasonHippy 739 Practically a Master Poster

looks ok to me...{using firefox..}

Could be a browser related thing...
What browser are you experiencing the problems on?
What kind of help do you need?


p.s. one thing I did think was that the site intro was a little long-winded and slow...Having the 'Enter site' link appear at the bottom throughout the intro might be an idea, as some people won't like being forced to sit through the entire intro before being able to enter the site!

JasonHippy 739 Practically a Master Poster

Hi, I am using Flash 8 with Actionscript 2.0. I am unable to stop my Flash Videos from playing as soon as the page loads. Tried everything...please help, Thank You

Have you tried setting the autoPlay parameter of the FLV playback component to false? That should solve the problem...

To do this:
Open up your .fla, select the instance of the FLV playback component on the stage and then open up the 'component inspector' panel. (by selecting 'Window->component inspector' from the top menu or by pressing Alt+F7)

In the parameters tab of component inspector, right at the top of the list is a parameter called autoPlay, which is set to 'true' by default...Set this to 'false' and that should stop the video from auto-playing when the page loads..The user will then have to manually start the vid by pressing play on the FLV playback components controls.

Note:The above steps will only work if your FLV component has been manually added to the stage (i.e. you dragged and dropped an instance of it onto the stage from the component panel).

If you are dynamically adding your FLV player instance onto the stage via actionscript instead, then you'll need to do the following:
Wherever you're attaching the new instance of the FLV playback component, be sure to add the following line of AS to set the autoPlay property:
{FLV player instance name}.autoPlay=false;

So if you used actionscript to attach an instance of an FLV …

JasonHippy 739 Practically a Master Poster

I can't see anything obvious...

The only thing I can think of that you could try is perhaps removing your variables from the flash movies URL..
i.e. change the following lines:

<param name="movie" value="flash/arcs.swf?testing=test" />

to

<param name="movie" value="flash/arcs.swf" />

and

<object type="application/x-shockwave-flash" data="flash/arcs.swf?testing=test" width="380" height="130">

to

<object type="application/x-shockwave-flash" data="flash/arcs.swf" width="380" height="130">

Then, where you have your <param name> tags try adding the following line....

<param name="flashvars" value="Testing=Test" />

Note: It looks to me like you'll need to put two copies of the above line in your code. One under the first line you edited and another a couple of lines below the second edited line! (because it's in the middle of your !IE thing!)

It's the only method I've ever used to pass variables into flash, so it should work....Let me know how you get on!
I've never used the old querystring method of passing params before, so I don't know much about it!

Addendum:
If memory serves, using flashvars makes the parameters available to the root of the movie, so your getqry method will probably be redundant as you won't be using querystring any more!

I know that the flashvars thing isn't the most secure way of sending parameters to a flash file, the only other method I am aware of which I used once (but too long ago for me to remember the specifics of) is FSCommand which I think is more secure...

Cheers …

JasonHippy 739 Practically a Master Poster

>it's probably because you aren't freeing the block
>of memory you're allocating in your call to malloc
No, it's probably not. Even if the process doesn't release allocated memory when it terminates, all you're likely to get is leaked memory, not a segmentation fault.

>memcpy(&pData, &t, sizeof(t));
>memcpy(&a, &pData, sizeof(t));
pData is already a pointer. Remove the address-of operator and watch it magically begin working:

memcpy(pData, &t, sizeof(t));
memcpy(&a, pData, sizeof(t));

Doh, good point....I stand corrected madam... {hangs head in shame}
I didn't spot the unnecessary usage of &..Although now you mention it, it's glaringly obvious! {kicking self}

He he, ne'er mind....Can't win 'em all...Unless your names Narue that is! heh heh ;)

JasonHippy 739 Practically a Master Poster

Hello to everyone,

I am having this problem with the following code:

typedef struct test
{
	int  i;
	char c[50];
} testStruct;

int main()
{
	char *pData;
	testStruct t;

	t.i = 5;
	strcpy_s(t.c, 50*sizeof(char), "hello");

	pData = (char *)malloc(sizeof(t));
	memcpy(&pData, &t, sizeof(t));
	
	testStruct a;
	memcpy(&a, &pData, sizeof(t));

	cout << a.i << ' ' << a.c << endl;

	system("PAUSE");
	return (0);
}

The problem occurs with the variable "pData", the moment the program returns.

Could someone, please, indicate to me what the problem to the above source code is?

Thanks a lot,
Erroneous Seth

If the problem is occurring when the program exits, it's probably because you aren't freeing the block of memory you're allocating in your call to malloc......It's one of the golden rules of C and C++ that you should free any resources that get allocated, either by using free() (if using the old C style allocations methods, like malloc ) or delete (if using the 'new' keyword to allocate memory).

So at some point before you return, try putting the following line in:

free(pData);

That should hopefully solve the problem!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

My last post wasn't entirely successful. But using Flashdevelop and the latest version of the flex 3 SDK (both of which are FREE downloads, so google 'em and download 'em....Highly recommended!) I've knocked something together in AS3 which works pretty much as you wanted it to.....

First I knocked a little AS3 class together draw an arrow shape (derived from Sprite, a new AS3 class which is basically a MovieClip without a timeline...All animation is done through adding and removing event listeners....)
Anyway, without further ado here's Arrow.as:

/**
* Draws an arrow shape
* @author Jason Trunks
* @version 0.1
*/

package 
{
	import flash.display.Sprite;
	
	[SWF(backgroundColor="0xffffff", width="800", height="600", frameRate="25")]
	public class Arrow extends Sprite  
	{
		public function Arrow()
		{
			init();
		}
		
		public function init():void
		{
			graphics.lineStyle(1,0,1);
			graphics.beginFill(0xffff00);
			graphics.moveTo(-50,-25);
			graphics.lineTo(0,-25);
			graphics.lineTo(0,-50);
			graphics.lineTo(50,0);
			graphics.lineTo(0,50);
			graphics.lineTo(0,25);
			graphics.lineTo(-50,25);
			graphics.lineTo(-50,-25);
			graphics.endFill();
		}
	}
	
}

Then I knocked this little class together, which draws and animates 10 instances of the Arrow class and animates them in a circular um... well in a circle....so this isCircularArrow.as:

package 
{
	import flash.display.Sprite;
	import Arrow;
	import flash.events.Event;
	/**
	 * Draws a number of arrows onto the stage, arranged in a circle and animates them...
	 * @author Jason Trunks
	 */
	[SWF(backgroundColor="0xffffff", width="275", height="250", frameRate="25")]
	public class CircularArrows extends Sprite 
	{
		private var arrows:Array = new Array();
		private var angles:Array = new Array();
		
		private const numArrows:Number = 10;
		private var angleDifference:Number = (2 * Math.PI) / numArrows;
		
		private const radX:Number = 100;
		private const radY:Number = 70; …
NeoKyrgyz commented: Really Helped +1
JasonHippy 739 Practically a Master Poster

OK, I've not had time to look into this too far, and it's been a while since I've done any AS2...But here goes.

To be able to dynamically use movieclips in your actionscript you first need to ensure that the clip has the appropriate linkage settings.
After creating your GFX/movieclip, locate it in the library, right click on it and select "linkage..." ensure that the "export for actionscript" and "Export in first frame" items are checked.
In the identifier field of the dialog, put in the name you want to use to refer to your clip in your actionscript (by default it will have the same name as the asset in the library)

For this example, I created a simple graphic of an arrow on the stage, converted it into a movieclip called mArrow (which automatically bungs it into the library) and then deleted the movieclip from the stage (but keeping it in the library!).

Then in the linkage dialog, I've checked the relevant boxes and left it's name as the default (mArrow). So any time I want to add an instance of the arrow to the stage I can do so using attachMovie(mArrow, "instance_name_mc", getNextHighestDepth()); .

Ok, so that's the first part out of the way, now we have an asset which we can dynamically add to the stage, now for the code part of it.

In the first frame of the main movieclip I've put the following actionscript which should create …

JasonHippy 739 Practically a Master Poster

Aha, yes sorry...I was in a bit of a rush on Saturday....I'd started replying to the thread and then my other half started harassing me 'cause she wanted me to drive her into town...In my haste, I misread the original post..Yes I see now..
I guess I should've cancelled my reply and waited until I had time to look at it properly!

Yes, the OP either needed to do this:

a* aa = new a();

aa->GetAttribute() = Id;

or as you've posted:

a aa;

aa.GetAttribute() = Id;

I stand corrected!

J.

JasonHippy 739 Practically a Master Poster

The line:

aa.getAttribute() = Id;

Is where you're going wrong here....
The assignment operator assigns the left hand operand the value of the right operand.

So you are trying to assign the value of id to the value of the getAttribute function....Which is nonsense.

What you really want is this:

Id = aa->getAttribute();

What this does is assign the value returned by aa.getAttribute() to Id.

That should solve your problem..

Jas.

JasonHippy 739 Practically a Master Poster

Ah, I see niek_e snuck in there with the answer while I was writing my last post!

JasonHippy 739 Practically a Master Poster

In windows, by including shlobj.h you can use a call to determine the path to the users desktop using the following:

// This variable will store the path to the users desktop
LPSTR desktopPath = new CHAR(MAX_PATH);

// this function call will populate the variable above with the path to 
// the users desktop....
SHGetSpecialFolderPath(0, desktopPath, CSIDL_DESKTOPDIRECTORY, 0);

I've not done any programming for unix/linux (yet!), so I don't know anything about the various API's/libraries involved, but I'm sure there will be some equivalent functionality somewhere in the *nix codebase to do this. If anybody knows what it is, then that will be the most likely solution to this thread!

Hope this is in some way useful.
Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Hi, I have a question with ofstream, is there anyway to ask the user for a file name, then create the file, and write to it?
Like:

string file;
cout << "Enter filename:";
getline(cin, file);
ofstream ofile;
ofile.open(file);
ofile << (stuff....);
ofile.close;

...except that doesn't work properly.:S
Thanks for any help.

Assuming you're using a std::string to hold your filename, I think you just need to convert it to a c style string in your call to ofile.open....
i.e.

ofile.open(file.c_str());

Hope this is of some help,
Jas.