Loading code from a TXT file on Action Script 3.0 - actionscript-3

Is there a way to load external code from a .txt file on action script 3? I'd like to put some addChild() codes inside a .txt file to execute on Flash then, for example:
file.txt content
addChild(mc1);
addChild(mc2);
My application does something like this:
fileContents = URLRequest(file.txt);
Now, fileContents has 2 lines of codes I wanna run on Flash, how to run these?
Thanks

You need a function that re-creates the txt files's code dynamically inside AS3.
(1) Extract the code lines into some array of Strings.
(2) Make a function to extract each line into parts.
(eg: extract the command addChild and parameter mc1).
(3) Make a function run_Code where you use the command and parameter.
Example code without array, just a string value, for simplicity...
var myStr = "addChild(mc1);"; //# you read this value from txt file
//# extract using length ( substr )
var myCmd = myStr.substr( 0, myStr.indexOf( "(" ) ); //extract "addChild" (eg: from start until first bracket)
//# extract using positions ( substring )
var myParam = myStr.substring( myStr.indexOf("(") +1 , myStr.indexOf(")") );
trace( "Command is: " + myCmd + " ... Param is: " + myParam );
run_Code( myCmd, myParam );
function run_Code ( in_command:String , in_param:String ) :void
{
//# handle possible commands
if ( in_command == "addChild" ) { stage.addChild( this[ in_param ] ); }
}

Related

SSIS Script howto append text to end of each row in flat file?

I currently have a flat file with around 1million rows.
I need to add a text string to the end of each row in the file.
I've been trying to adapt the following code but not having any success :-
public void Main()
{
// TODO: Add your code here
var lines = System.IO.File.ReadAllLines(#"E:\SSISSource\Source\Source.txt");
foreach (string item in lines)
{
var str = item.Replace("\n", "~20221214\n");
var subitems = str.Split('\n');
foreach (var subitem in subitems)
{
// write the data back to the file
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
I can't seem to get the code to recognise the carriage return "\n" & am not sure howto write the row back to the file to replace the existing rather than add a new row. Or is the above code sending me down a rabbit hole & there is an easier method ??
Many thanks for any pointers &/or assistance.
Read all lines is likely getting rid of the \n in each record. So your replace won't work.
Simply append your string and use #billinKC's solution otherwise.
BONUS:
I think DateTime.Now.ToString("yyyyMMdd"); is what you are trying to append to each line
Thanks #billinKC & #KeithL
KeithL you were correct in that the \n was stripped off. So I used a slightly amended version of #billinKC's code to get what I wanted :-
string origFile = #"E:\SSISSource\Source\Sourcetxt";
string fixedFile = #"E:\SSISSource\Source\Source.fixed.txt";
// Make a blank file
System.IO.File.WriteAllText(fixedFile, "");
var lines = System.IO.File.ReadAllLines(#"E:\SSISSource\Source\Source.txt");
foreach (string item in lines)
{
var str = item + "~20221214\n";
System.IO.File.AppendAllText(fixedFile, str);
}
As an aside KeithL - thanks for the DateTime code however the text that I am appending is obtained from a header row in the source file which is being read into a variable in an earlier step.
I read your code as
For each line in the file, replace the existing newline character with ~20221214 newline
At that point, the value of str is what you need, just write that! Instead, you split based on the new line which gets you an array of values which could be fine but why do the extra operations?
string origFile = #"E:\SSISSource\Source\Sourcetxt";
string fixedFile = #"E:\SSISSource\Source\Source.fixed.txt";
// Make a blank file
System.IO.File.WriteAllText(fixedFile, "");
var lines = System.IO.File.ReadAllLines(#"E:\SSISSource\Source\Source.txt");
foreach (string item in lines)
{
var str = item.Replace("\n", "~20221214\n");
System.IO.File.AppendAllText(fixedFile, str);
}
Something like this ought to be what you're looking for.

google apps script: get the name of the function that is currently running

I'm trying to get google apps script to log the current function that is running. I have something similar in python like so:
code_obj = sys._getframe(1).f_code
file = os.path.basename(code_obj.co_filename).split('.')[0]
Def = code_obj.co_name
line = str(sys._getframe(1).f_lineno)
try:
Class = get_class_from_frame(sys._getframe(1)).__name__
except:
Class = ''
return "--> " + file + "." + Class + "()." + Def + "()." + line + " --> " + now() + '\n'
Anybody know how to get the name of the current running function?
As in plain JavaScript, you can retrieve current function via arguments.callee, and then retrieve Function's property name:
callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function.
function myFunctionName() {
const functionName = arguments.callee.name;
// ...
}
Important note:
Since ES5, arguments.callee is forbidden in strict mode. This can cause an error in cases where the script is using strict mode behind the scenes (see, for example, this):
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
I've noticed this happening, for example, when using default parameters or rest parameters.
Unfortunately, there's not an easy alternative to arguments.callee:
How to get function name in strict mode [proper way]
Get current function name in strict mode
There's a nice way to get all function names and lines called in google-apps-script using:
(new Error()).stack
Please try:
function test() {
console.log(f_(100));
}
function f_(n) {
console.log(stack2lines_((new Error()).stack))
return n + 1;
}
function stack2lines_(stack) {
var re1 = new RegExp('at ([^ ]+) \\(Code\\:(\\d+).*', 'gm');
var re2 = new RegExp('\\{.*\\}', 'gm');
var result = stack
.replace(re1, '{"$1": $2}')
.match(re2);
return result;
}
The result:
[ '{"f_": 6}', '{"test": 2}' ]
Source:
https://script.google.com/u/0/home/projects/1BbaDeja4ObWMwbVnhCJ29FHsNfQm-SfAPYvpqobh2B96TA5449GnGnHc/edit

Actionscript While loop & addChild problems

Hi I'm trying to make a powers calculator that displays every line calculated by the while loop in my actionscript3 code. When I run the program, the flash file only displays the last loop, can anyone help to make it work without using trace? I need it to display in the flash program. Here is my code:
private function evalue(event:MouseEvent = null):void
{
maMiseEnForme.font="Arial";
maMiseEnForme.size=14;
maMiseEnForme.bold=true;
maMiseEnForme.color=0x000000;
monMessage.x=270;
monMessage.y=375;
monMessage.autoSize=TextFieldAutoSiz...
monMessage.border=true;
monMessage.defaultTextFormat=maMiseE...
var base:uint;
var reponse:uint;
var puissanceCount:int=1;
var puissance:uint;
var reponseText:String;
base = uint(boiteBase.text);
puissance = uint(boitePuissance.text);
while (puissanceCount <= puissance)
{
reponse = Math.pow(base,puissanceCount);
reponseText=(base + "^" + puissanceCount + "=" + reponse + "\n");
monMessage.text=reponseText;
addChild(monMessage);
puissanceCount++
}
}
}
}
I have attached a picture of what appears in the .swf window:
P.S: I'm a newbie to flash.
Thanks in advance.
You can use "+=" parameter instead of "=" parameter to update a string variable by "adding string to it" instead of "refreshing it everytime", then you can show text after your while loop finished. You don't need to addChild(nonMessage) in everyloop, just move it after your while{} loop. SO: You just need "monMessage.text+=reponseText;" instead of "monMessage.text=reponseText;" and move your "addChild()" to next to your while loop.

Saving text box input to XML or txt file in HTML

I'm working on a HTML page project where I have 2 text boxes and basically I want to save the input data that the user put in the text boxes. What we did in my C# class was that we saved all input into a XML file so I'm assuming there is a similar way? Either to a XML or some other file that can store text?
Anyone that knows a solution?
I recommend the following php script
<?php
// check that form was submitted
// (you'll need to change these indices to match your form field names)
if( !empty( $_POST['firstname'] ) && !empty( $_POST['lastname'] ) ){
// remove html tags from submission
// (since you don't want them)
$firstname = strip_tags( $_POST['firstname'] );
$lastname = strip_tags( $_POST['lastname'] );
// create the date
// (you can change the format as desired)
$date = date( 'Y-m-d' );
// create an array that holds your info
$record = array( $firstname,$lastname,$date );
// save the record to your .txt file (I still recommend JSON)
$json = json_encode( $record );
$file = '/_server_/path/to/yourfile.txt';
file_put_contents( $json,$file );
}

Extracting "filename" from full path in actionscript 3

Does AS3 have a built in class / function to extract "filename" from a complete path. e.g. I wish to extract "filename.doc" from full path "C:\Documents and Settings\All Users\Desktop\filename.doc"
For Air, you can try using File Class to extract file name
var file:File=new File("path_string");
//path_string example "C:\\Windows\\myfile.txt"
var filename:String = file.name;
First you want to find the last occurrence of / or \ in the path, do that using this:
var fSlash: int = fullPath.lastIndexOf("/");
var bSlash: int = fullPath.lastIndexOf("\\"); // reason for the double slash is just to escape the slash so it doesn't escape the quote!!!
var slashIndex: int = fSlash > bSlash ? fSlash : bSlash;
That will give you the index in the string that is right BEFORE that last slash. So then to return the portion of the string after that, you add one to the index (moving it past the last slash) and return the remainder of the string
var docName: String = fullPath.substr(slashIndex + 1);
To do this as a simple to use function, do this:
function getFileName(fullPath: String) : String
{
var fSlash: int = fullPath.lastIndexOf("/");
var bSlash: int = fullPath.lastIndexOf("\\"); // reason for the double slash is just to escape the slash so it doesn't escape the quote!!!
var slashIndex: int = fSlash > bSlash ? fSlash : bSlash;
return fullPath.substr(slashIndex + 1);
}
var fName: String = getFileName(myFullPath);
Couldn't you just do something basic like:
string filename = filename.substring(filename.lastIndexOf("\\") + 1)
I know it's not a single function call, but it should work just the same.
Edited based on #Bryan Grezeszak's comment.
Apparently you can use the File class, or more specifically, the File.separator static member if you're working with AIR. It should return "/" or "\", which you can plug in to #cmptrgeekken's suggestion.
Try this:
var file_ :File = new File("C:/Usea_/Dtop/sinim (1).jpg"); // or url variable ... whatever//
file_ = file_.parent;
trace(file_.url);
You can use something like this to do the job :
var tmpArray:Array<String>;
var fileName:String;
tmpArray = fullFilePath.split("\");
fileName = tmpArray.pop();
You have to take care if you are using Unix file system ("/") or Windows file system ("\").