folder hierarchy in flash cs5.5 - flash-cs5

I'm trying to create a folder hierarchy in flash, the folders i have are
C:\uk\ac\uwe\webgames\math
in the math folder i have the following file called GameMath.as
package uk.ac.uwe.webgames.math{
public class GameMath {
// ------- Constructor -------
public function GameMath() {
}
// ------- Properties -------
const PI:Number = Math.PI;
// ------- Methods -------
public function areaOfCircle(radius:Number):Number {
var area:Number;
area = PI * radius * radius;
return area;
}
}
}
In the webgames folder i have a file called webgames_driver.fla
import uk.ac.uwe.webgames.math.GameMath;
import flash.text.TextField;
// Create a GameMath instance
var output:TextField = new TextField();
var aGameMathInstance:GameMath = new GameMath();
// you will need to create a dynamic textfield called
// output on the stage to display method return value
output.text=aGameMathInstance.areaOfCircle(5).toString();
addChild(output);
//trace(aGameMathInstance.areaOfCircle(1))
however i am getting the following errors
Scene 1, Layer 'Layer 1', Frame 1, Line 1 1172: Definition
uk.ac.uwe.webgames.math:GameMath could not be found.
Scene 1, Layer 'Layer 1', Frame 1, Line 1 1172: Definition
uk.ac.uwe.webgames.math:GameMath could not be found.
Scene 1, Layer 'Layer 1', Frame 1, Line 5 1046: Type was not found or
was not a compile-time constant: GameMath.
Scene 1, Layer 'Layer 1', Frame 1, Line 5 1180: Call to a possibly
undefined method GameMath.
Could anyone help coz i am just stuck, and i'm really new to flash

I'll put this in as basic and detailed terms as possible, not just for your benefit, but for anyone else reading this who isn't terribly experienced with custom classes. Better to get it all out there now and avoid confusion. (I know I wish some people had given me this level of detail on some of my early questions...)
The import code is for importing an .as class. As you know, the top of a class, you'd have code something like this (except from my own custom class, Trailcrest).
package trailcrest
{
public class sonus
{
Then, in my .fla or an .as file, I can use
import trailcrest.sonus;
I will mention that your .fla must be in the main directory that contains all the custom classes you want to import. My file layout is something like this (folders in parenthesis):
MyProject.fla
MyDocumentClass.as
(trailcrest)
sonus.as
Note that my package name corresponds with the folder structure, with the folder containing the .fla being assumed as the starting place by the code. If I wanted to use a package name like trailcrest.v1, the folders would have to be like this:
MyProject.fla
MyDocumentClass.as
(trailcrest)
(v1)
sonus.as
Then, I'd refer to my custom class using
import trailcrest.v1.sonus;
Note that MyProject.fla MUST be at the main directory of that folder structure. This is because Flash cannot search backwards through the folders, only forwards. So if I had a structure like...
(project)
MyProject.fla
MyDocumentClass.as
(trailcrest)
sonus.as
...then, the line of code...
import trailcrest.sonus;
...would search for the path "\project\trailcrest\sonus.as", which as you can see, doesn't exist. Flash isn't able to go to the parent folder of "\project\".
Your line of code...
import uk.ac.uwe.webgames.math.GameMath;
...is looking for the path "webgames\uk\ac\use\webgames\math\GameMath.as". (Remember, the code assumes the folder containing the .fla as the starting place, so the code is literally trying to go to "C:\uk\ac\uwe\webgames\uk\ac\use\webgames\math\GameMath.as")
To fix this, you'll need to change the package for GameMath.as:.
package math{
...and the import statement in your code:
import math.GameMath;
This will point everything to the literal path "C:\uk\ac\uwe\webgames\math\GameMath.as"
I hope this answers your question!

Related

QCheckbox issue [duplicate]

I am struggling to get this working.
I tried to transpose from a c++ post into python with no joy:
QMessageBox with a "Do not show this again" checkbox
my rough code goes like:
from PyQt5 import QtWidgets as qtw
...
mb = qtw.QMessageBox
cb = qtw.QCheckBox
# following 3 lines to get over runtime errors
# trying to pass the types it was asking for
# and surely messing up
mb.setCheckBox(mb(), cb())
cb.setText(cb(), "Don't show this message again")
cb.show(cb())
ret = mb.question(self,
'Close application',
'Do you really want to quit?',
mb.Yes | mb.No )
if ret == mb.No:
return
self.close()
the above executes with no errors but the checkbox ain't showing (the message box does).
consider that I am genetically stupid... and slow, very slow.
so please go easy on my learning curve
When trying to "port" code, it's important to know the basis of the source language and have a deeper knowledge of the target.
For instance, taking the first lines of your code and the referenced question:
QCheckBox *cb = new QCheckBox("Okay I understand");
The line above in C++ means that a new object (cb) of type QCheckBox is being created, and it's assigned the result of QCheckBox(...), which returns an instance of that class. To clarify how objects are declared, here's how a simple integer variable is created:
int mynumber = 10
This is because C++, like many languages, requires the object type for its declaration.
In Python, which is a dynamic typing language, this is not required (but it is possible since Python 3.6), but you still need to create the instance, and this is achieved by using the parentheses on the class (which results in calling it and causes both calling __new__ and then __init__). The first two lines of your code then should be:
mb = qtw.QMessageBox()
cb = qtw.QCheckBox()
Then, the problem is that you're calling the other methods with new instances of the above classes everytime.
An instance method (such as setCheckBox) is implicitly called with the instance as first argument, commonly known as self.
checkboxInstance = QCheckBox()
checkboxInstance.setText('My checkbox')
# is actually the result of:
QCheckBox.setText(checkboxInstance, 'My checkbox')
The last line means, more or less: call the setText function of the class QCheckBox, using the instance and the text as its arguments.
In fact, if QCheckBox was an actual python class, setText() would look like this:
class QCheckBox:
def setText(self, text):
self.text = text
When you did cb = qtw.QCheckBox you only created another reference to the class, and everytime you do cb() you create a new instance; the same happens for mb, since you created another reference to the message box class.
The following line:
mb.setCheckBox(mb(), cb())
is the same as:
QMessageBox.setCheckBox(QMessageBox(), QCheckBox())
Since you're creating new instances every time, the result is absolutely nothing: there's no reference to the new instances, and they will get immediately discarded ("garbage collected", aka, deleted) after that line is processed.
This is how the above should actually be done:
mb = qtw.QMessageBox()
cb = qtw.QCheckBox()
mb.setCheckBox(cb)
cb.setText("Don't show this message again")
Now, there's a fundamental flaw in your code: question() is a static method (actually, for Python, it's more of a class method). Static and class methods are functions that don't act on an instance, but only on/for a class. Static methods of QMessageBox like question or warning create a new instance of QMessageBox using the provided arguments, so everything you've done before on the instance you created is completely ignored.
These methods are convenience functions that allow simple creation of message boxes without the need to write too much code. Since those methods only allow customization based on their arguments (which don't include adding a check box), you obviously cannot use them, and you must code what they do "under the hood" explicitly.
Here is how the final code should look:
# create the dialog with a parent, which will make it *modal*
mb = qtw.QMessageBox(self)
mb.setWindowTitle('Close application')
mb.setText('Do you really want to quit?')
# you can set the text on a checkbox directly from its constructor
cb = qtw.QCheckBox("Don't show this message again")
mb.setCheckBox(cb)
mb.setStandardButtons(mb.Yes | mb.No)
ret = mb.exec_()
# call some function that stores the checkbox state
self.storeCloseWarning(cb.isChecked())
if ret == mb.No:
return
self.close()

Loading a class of unknown name in a dynamic location

Currently I am extracting files to the temp directory of the operating system. One of the files is a Python file containing a class which I need to get a handle of. The Python's file is known, but the name of the class inside the file is unknown. But it is safe to assume, that the there is only one single class, and that the class is a subclass of another.
I tried to work with importlib, but I am not able to get a handle of the class.
So far I tried:
# Assume
# module_name contains the name of the class and -> "MyClass"
# path_module contains the path to the python file -> "../Module.py"
spec = spec_from_file_location(module_name, path_module)
module = module_from_spec(spec)
for pair in inspect.getmembers(module):
print(f"{pair[1]} is class: {inspect.isclass(pair[1])}")
When I iterate over the members of the module, none of them get printed as a class.
My class in this case is called BasicModel and the Output on the console looks like this:
BasicModel is class: False
What is the correct approach to this?
Edit:
As the content of the file was requested, here you go:
class BasicModel(Sequential):
def __init__(self, class_count: int, input_shape: tuple):
Sequential.__init__(self)
self.add(Input(shape=input_shape))
self.add(Flatten())
self.add(Dense(128, activation=nn.relu))
self.add(Dense(128, activation=nn.relu))
self.add(Dense(class_count, activation=nn.softmax))
Use dir() to get the attributes of the file and inspect to check if the attribute is a class. If so, you can create an object.
Assuming that your file's path is /tmp/mysterious you can do this:
import importlib
import inspect
from pathlib import Path
import sys
path_pyfile = Path('/tmp/mysterious.py')
sys.path.append(str(path_pyfile.parent))
mysterious = importlib.import_module(path_pyfile.stem)
for name_local in dir(mysterious):
if inspect.isclass(getattr(mysterious, name_local)):
print(f'{name_local} is a class')
MysteriousClass = getattr(mysterious, name_local)
mysterious_object = MysteriousClass()

Error when importing Dictionary to another file

so i need to use a dictionary within another file but am getting an error when importing the file. my file is called "Final Chess Game.py" with the spaces.
here is how im calling it:
from Final Chess Game import pieces
"pieces" is my dict.
Im getting an error on "Chess" within the import, do i have to change the name of the file or is there any other way of calling the dictionary from the final chess game file?
It is simply bad practice to have spaces in your import. Python thinks that you are trying to import Final and reads a syntax error when you get to Chess. You should rename your file to something without spaces.
If you absolutely want to import that file:
Final_Chess_Game = __import__("Final Chess Game")
Now you can call functions from Final Chess Game through Final_Chess_Game.<functioname>
If your chessboard class looks like this:
class ChessBoard(tk.Frame):
def __init__(self, parent, rows=8, columns=8, size=70, color1="White", color2="lightgrey"):
self.rows = rows
self.columns = columns
self.size = size
self.color1 = color1
self.color2 = color2
self.pieces = {}
You cannot import a class variable without importing the whole class. You must import the whole chessboard. You can access the chessboard with:
Final_Chess_Game.ChessBoard
You cannot self.pieces without first creating an instance of the class. self.pieces is an instance variable, so each ChessBoard that you create has a .pieces variable.

class index differ error in weka

I want to do text classification with weka. I have a train and a test file (Persian language). first I load the train file and then choose "string to word vector" in preprocess. And because of choosing that, the class position goes to the start. For moving the class to its index (which is 2 in the files), I can go either to "Edit" part and right click on the class column and choose "attribute as class" or just in classify menu, choose (NOM)class. (unless most of the algorithms would be inactive). I run SMO and save the model. The problem is, after opening the test file, and click on "re-evaluate the model on current test set", this error occurs that, "...class index differ: 1!=2". I know it is because after opening the test file, again the class column goes to the start. For train part I solved the problem as I described above. But how can I solve it for the test part, too?
sample train file:
sample test file:
You should use the same transformation(s) on your testset before you use it to evaluate a trained model. When using the GUI, you could use the preprocessor view from the explorer, apply the same transformations by hand and than save the set to a new arff file. When you want to conduct a series of experiment, I suggest writing a routine that does your transformation for you.
That would look a little something like this:
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Remove;
import weka.filters.unsupervised.attribute.Reorder;
import weka.filters.unsupervised.attribute.NumericToNominal;
import java.io.File;
public class DataConverter
{
public static void Convert(String sourcepath,String destpath) throws Exception
{
CSVLoader loader = new CSVLoader();
loader.setSource(new File(sourcepath));
Instances data = loader.getDataSet();
Remove remove = new Remove();
remove.setOptions(weka.core.Utils.splitOptions("-R 1"));
remove.setInputFormat(data);
data = Filter.useFilter(data, remove);
Reorder reorder = new Reorder();
reorder.setOptions(weka.core.Utils.splitOptions("-R first-29,31-last,30"));
reorder.setInputFormat(data);
data = Filter.useFilter(data, reorder);
NumericToNominal ntn = new NumericToNominal();
ntn.setOptions(weka.core.Utils.splitOptions("-R first,last"));
ntn.setInputFormat(data);
data = Filter.useFilter(data, ntn);
// save ARFF
ArffSaver saver = new ArffSaver();
saver.setInstances(data);
saver.setFile(new File(destpath));
//saver.setDestination(new File(destpath));
saver.writeBatch();
}
public static void main(String args[]) throws Exception
{
File folder = new File("..\\..\\data\\output\\learning\\csv\\");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String target = listOfFiles[i].getName();
target = target.substring(0, target.lastIndexOf("."));
System.out.println("converting file " + (i + 1) + "/" + listOfFiles.length);
Convert("..\\..\\data\\output\\learning\\csv\\" + listOfFiles[i].getName(), "..\\..\\data\\output\\learning\\arff\\" + target + ".arff");
}
}
}
}
Also: The reorder filter can help you place your target class at the end of the file. It takes a new order of the old indices as arguments. In this case you could apply Reorder -R 2-last,1
First, I changed the files to vector based on 1000 most frequent words in train file and made a numeric arff file for the train and test file, then for both of them in the "classify" menu in "Test options" I chose "(Nom) class.

Create a self updating string based on files in a folder in Processing

Alright, so I was messing around with a simple fft visualization in Processing and thought it would be fun to have more than just one song playing every time. In the end I added 3 songs manually and on mouse click change between the songs randomly using a predefined string. I wanted to add the rest of my computers music, but every time I would want to add a new song to my sketch I would have to copy and paste it's name into the string in my sketch. Seems like a lot of unnecessary work
Is there a way to have processing scan a folder, recognize how many files are inside, and copy all of the file names into the string? I found a library called sDrop for processing 1.1 which lets you drag and drop files into the sketch directly. However, that doesn't seem to exist anymore in version 2+ of Processing.
Here is the simple version of my current working code to play the music:
import ddf.minim.spi.*;
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.ugens.*;
import ddf.minim.effects.*;
AudioPlayer player;
Minim minim;
String [] songs = {
"song1.mp3",
"song2.mp3",
"song3.mp3",
};
int index;
void setup() {
size(100, 100, P3D);
index = int(random(songs.length));
minim = new Minim(this);
player = minim.loadFile(songs[index]);
player.play();
}
void draw() {
}
void mouseClicked() {
index = int(random(songs.length));
player.pause();
player = minim.loadFile(songs[index]);
player.play();
}
If anyone has suggestions or could guide me towards a good tutorial that would be great. Thanks!
Assuming you're using this in Java mode, then you can use the Java API: https://docs.oracle.com/javase/8/docs/api/
The Java API contains a File class that contains several methods for reading the contents of a directory: https://docs.oracle.com/javase/8/docs/api/java/io/File.html
Something like this:
ArrayList<String> songs = new ArrayList<String>();
File directory = new File("path/to/song/directory/");
for(File f : directory.listFiles()){
if(!f.isDirectory()){
songs.add(f.getAbsolutePath());
}
}
Googling "java list files of directory" will yield you a ton of results.
Just to add to Kevin's Workman's answer:
Try to use File.separator instead of "/" or "\". It does the same thing, but it figures out the right based on the OS you're using for you, so you can move you sketch on other computers and still have it working.
Check out Daniel Shiffman's that comes with Processing in Examples > Topics > File IO > DirectoryList

Resources