How to solve the "String" in "for each" loop - string

My task is to open multiple files after a button clicked, and read all those selected files.
I have found an example of foreach function in c#, but I would like to write it in C++. How should I actually to convert that?
It shows the error that System::String, cannot use this type here without top level '^'.
I'm still new with that. Does anyone can give suggestion?
Thank you very much.
Below is my written codes
Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Title = "open captured file";
openFileDialog1->Filter = "CP files (*.cp)|*.cp|All files (*.*)|*.*|txt files (*.txt)|*.txt";
openFileDialog1->FilterIndex = 2;
//openFileDialog1->RestoreDirectory = true;
openFileDialog1->Multiselect = true;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
**for each (String line in openFileDialog1->FileName)**
System::Diagnostics::Debug::WriteLine("{0}",line);
myStream->Close();
}

Depending on the Container type returned, there is a std::for_each defined in <algorithm>-header.
The function Looks like this:
#include <algorithm>
std::for_each(InputIterator first, InputIterator last, Function fn);
You need to provide two iterators, one for the beginning of the Container and one for the end of the iterator. As a third Argument you can provide a function (function-object) and operate on the current argument.
See here for further reference.
As I got it from MSDN, the property SafeFileNames returns an array<String^>.
System::Array provides a static method called Array::ForEach. You would need to call it like
System::Action<T> myAction; // You will Need to provide a function here to be used on every filename.
System::Array::ForEach(openFileDialog1->SafeFileNames, myAction);
This comes closest to foreach from C#.
Look here for System::Array::ForEach and here for OpenFileDialog::SafeFileNames.

Related

Is it possible to get the name of variable in Groovy?

I would like to know if it is possible to retrieve the name of a variable.
For example if I have a method:
def printSomething(def something){
//instead of having the literal String something, I want to be able to use the name of the variable that was passed
println('something is: ' + something)
}
If I call this method as follows:
def ordinary = 58
printSomething(ordinary)
I want to get:
ordinary is 58
On the other hand if I call this method like this:
def extraOrdinary = 67
printSomething(extraOrdinary)
I want to get:
extraOrdinary is 67
Edit
I need the variable name because I have this snippet of code which runs before each TestSuite in Katalon Studio, basically it gives you the flexibility of passing GlobalVariables using a katalon.features file. The idea is from: kazurayam/KatalonPropertiesDemo
#BeforeTestSuite
def sampleBeforeTestSuite(TestSuiteContext testSuiteContext) {
KatalonProperties props = new KatalonProperties()
// get appropriate value for GlobalVariable.hostname loaded from katalon.properties files
WebUI.comment(">>> GlobalVariable.G_Url default value: \'${GlobalVariable.G_Url}\'");
//gets the internal value of GlobalVariable.G_Url, if it's empty then use the one from katalon.features file
String preferedHostname = props.getProperty('GlobalVariable.G_Url')
if (preferedHostname != null) {
GlobalVariable.G_Url = preferedHostname;
WebUI.comment(">>> GlobalVariable.G_Url new value: \'${preferedHostname}\'");
} else {
WebUI.comment(">>> GlobalVariable.G_Url stays unchanged");
}
//doing the same for other variables is a lot of duplicate code
}
Now this only handles 1 variable value, if I do this for say 20 variables, that is a lot of duplicate code, so I wanted to create a helper function:
def setProperty(KatalonProperties props, GlobalVariable var){
WebUI.comment(">>> " + var.getName()" + default value: \'${var}\'");
//gets the internal value of var, if it's null then use the one from katalon.features file
GlobalVariable preferedVar = props.getProperty(var.getName())
if (preferedVar != null) {
var = preferedVar;
WebUI.comment(">>> " + var.getName() + " new value: \'${preferedVar}\'");
} else {
WebUI.comment(">>> " + var.getName() + " stays unchanged");
}
}
Here I just put var.getName() to explain what I am looking for, that is just a method I assume.
Yes, this is possible with ASTTransformations or with Macros (Groovy 2.5+).
I currently don't have a proper dev environment, but here are some pointers:
Not that both options are not trivial, are not what I would recommend a Groovy novice and you'll have to do some research. If I remember correctly either option requires a separate build/project from your calling code to work reliable. Also either of them might give you obscure and hard to debug compile time errors, for example when your code expects a variable as parameter but a literal or a method call is passed. So: there be dragons. That being said: I have worked a lot with these things and they can be really fun ;)
Groovy Documentation for Macros
If you are on Groovy 2.5+ you can use Macros. For your use-case take a look at the #Macro methods section. Your Method will have two parameters: MacroContext macroContext, MethodCallExpression callExpression the latter being the interesting one. The MethodCallExpression has the getArguments()-Methods, which allows you to access the Abstract Syntax Tree Nodes that where passed to the method as parameter. In your case that should be a VariableExpression which has the getName() method to give you the name that you're looking for.
Developing AST transformations
This is the more complicated version. You'll still get to the same VariableExpression as with the Macro-Method, but it'll be tedious to get there as you'll have to identify the correct MethodCallExpression yourself. You start from a ClassNode and work your way to the VariableExpression yourself. I would recommend to use a local transformation and create an Annotation. But identifying the correct MethodCallExpression is not trivial.
no. it's not possible.
however think about using map as a parameter and passing name and value of the property:
def printSomething(Map m){
println m
}
printSomething(ordinary:58)
printSomething(extraOrdinary:67)
printSomething(ordinary:11,extraOrdinary:22)
this will output
[ordinary:58]
[extraOrdinary:67]
[ordinary:11, extraOrdinary:22]

Can't locate object method "say_hello" via package "1"

I just started to learn Perl. When I moved to object orientation I am getting an error like
Can't locate object method "say_hello" via package "1" (perhaps you forgot to load "1"?) at ./main.pl line 8.
I googled a lot for a solution. Got some similar issues like this. My understanding is it's not a general issue.
Here is my class
# MyModule.pm
package MyModule;
use strict;
use warnings;
sub new {
print "calling constructor\n";
}
sub say_hello {
print "Hello from MyModule\n";
}
1;
Here is my test script
# main.pl
#!/usr/bin/perl -w
use strict;
use warnings;
use MyModule;
my $myObj = new MyModule();
$myObj->say_hello();
The code is working perfectly if remove last line from main.pl
Your constructor new needs to return a blessed reference to the data structure you are using to contain the object's information. You have no relevant data here, but you still need to return something
bless associates the data with a specific package. In this case, your object should be blessed into MyModule, so that perl knows to look for MyModule::say_hello when it sees a method call like $myObj->say_hello()
Your current constructor returns the value returned by the print statement, which is 1 if it succeeded, as it almost certainly does. That is why you see the "1" in the error message
Can't locate object method "say_hello" via package "1" (perhaps you forgot to load "1"?) at ./main.pl line 8.
The most common container for an object's data is a hash, so you need to change new to this
sub new {
print "calling constructor\n";
my $self = { };
bless $self, 'MyModule';
return $self;
}
and then your program will work as it should. It creates an anonymous hash and assigns it to the $self variable, then blesses and returns it
Note that this can be made much more concise:
Without a return statement, a subroutine will return the value of the most recently executed statement
By default, bless will bless the data into the current package
There is no need to store the reference in a variable before blessing it
So the same effect may be achieved by writing
sub new {
print "calling constructor\n";
bless { };
}
Note also that your call
my $myObj = new MyModule()
is less than ideal. It is called indirect object notation and can be ambiguous. It is better to always use a direct method reference, such as
my $myObj = MyModule->new()
so as to disambiguate the call
You're not creating a new object, and thus $myObj is just the return code of the "print" statement (or 1).
You need to bless something and return it.
sub new {
my ( $class ) = #_;
print "Calling Constructor\n";
my $self = {};
bless $self, $class;
return $self;
}
That way $myObj will actually be an object, not just a return code :)

Why does my variable say it is unassigned when it is assigned?

I'm am helping convert VB code to C#. In the C# code, I have an error saying that one of my variables is unassigned. When I right click (in Visual Studios 2013) and click on Go to Definition it brings me to its declaration where it is clearly being assigned to null. I have even tried assigning it to something else besides null.
Here is the declaration and it being set to null:
DataSet set5 = new DataSet();
set5 = null;
Here is where it is being called and where I get the error:
try
{
wires.grdInser.DataSource = set5.Tables[0];//Being called here
} catch (Exception exception92)
{
ProjectData.SetProjectError(exception92);
Exception exception46 = exception92;
ProjectData.ClearProjectError();
}
There is a bunch of code in-between these two pieces of code, but I don't think the scope the variable is being called in is an issue since the "Go to Definition" takes me directly to the definition. Could the issue be because it is inside a try/catch statement? Any help would be greatly appreciated.
Try this instead, just to get rid of the error, then you can figure out what you need to do from there:
DataSet set5 = new DataSet();
DataTable x = new DataTable();
set5.Tables.Add(x);
Get rid of the set5 = null statement.
Now your other function should be able to see Tables[0].

Is there a way to change the text of checked/unchecked MCheckBox states?

How would I go about changing the default MCheckBox state text (currently I/0) to, for example, YES/NO or ON/OFF?
Mr. Daniel Kurka is the author for all the widget classes in MGWT. If the look & feel is not
fulfilling our requirement, We can edit those classes and rewrite them according to our requirement.Because they are open source. I done this on many classes like CellList,FormListEntry and MCheckBox. code for ON/OFF instead of I/O
public MyOwnCheckBox(CheckBoxCss css) {
this.css = css;
css.ensureInjected();
setElement(DOM.createDiv());
addStyleName(css.checkBox());
onDiv = DOM.createDiv();
onDiv.setClassName(css.on());
onDiv.setInnerText("ON");
getElement().appendChild(onDiv);
middleDiv = DOM.createDiv();
middleDiv.setClassName(css.middle());
Element middleContent = DOM.createDiv();
middleContent.setClassName(css.content());
middleDiv.appendChild(middleContent);
getElement().appendChild(middleDiv);
offDiv = DOM.createDiv();
offDiv.setClassName(css.off());
offDiv.setInnerText("OFF");
getElement().appendChild(offDiv);
addTouchHandler(new TouchHandlerImplementation());
setValue(true, false);
}
Write a new class like MyOwnCheckBox.just copy the code in MCheckBox and paste in your class MyOwnCheckBox, find and replace the MCheckBox with MyOwnCheckBox in the code(change constructor's name). do the following changes.
onDiv.setInnerText("ON");
offDiv.setInnerText("OFF");
and finally create object to MyOwnCheckBox rather MCheckBox, it'll shows MCheckBox with ON/OFF.
Right now there is no way to do that, but there is no real reasons that checkbox does not implement HasText other than we might need to update the css so that big text will not break the layout.
If you think mgwt should implement this go and vote for this issue: http://code.google.com/p/mgwt/issues/detail?id=171
Well, an easy way to accomplish the same thing, without creating a new class that mimics MCheckBox, is to do something like the code below:
CheckBoxCss css = MGWTStyle.getTheme().getMGWTClientBundle().getCheckBoxCss();
String offClass = css.off();
String onClass = css.on();
NodeList<Node> checkBoxElems;
mIsSingleSkuBox = new MCheckBox(css);
checkBoxElems = mIsSingleSkuBox.getElement().getChildNodes();
for( int i = 0; i < checkBoxElems.getLength(); i++ )
{
Element openElem = (Element) checkBoxElems.getItem(i);
String className = openElem.getClassName();
if( className.equals( offClass))
{
openElem.setInnerText("No" );
}
else if( className.equals( onClass))
{
openElem.setInnerText("Yes" );
}
}
It will probably have space problems with anything longer than 3 characters, but it works consistently with "Yes" and "No" for me.

How to get groovy to evaluate ${sth} when stored in string?

I'm getting a text which contains ${somethingElse} inside, but it's just a normal String.
I've got a class:
class Whatever {
def somethingElse = 5
void action(String sth) {
def test = []
test.testing = sth
assert test.testing == 5
}
}
Is it possible with groovy?
EDIT:
my scenario is: load xml file, which contains nodes with values pointing to some other values in my application. So let's say I've got shell.setVariable("current", myClass). And now, in my xml I want to be able to put ${current.someField} as a value.
The trouble is, that the value from xml is a string and I can't evaluate it easily.
I can't predict how these "values" will be created by user, I just give them ability to use few classes.
I cannot convert it when the xml file is loaded, it has to be "on demand", since I use it in specific cases and I want them to be able to use values at that moment in time, and not when xml file is loaded.
Any tips?
One thing you could do is:
class Whatever {
def somethingElse = 5
void action( String sth ) {
def result = new groovy.text.GStringTemplateEngine().with {
createTemplate( sth ).make( this.properties ).toString()
}
assert result == "Number 5"
}
}
// Pass it a String
new Whatever().action( 'Number ${somethingElse}' )
At first, what we did, was used this format in xml:
normalText#codeToExecuteOrEvaluate#normalText
and used replace closure to regexp and groovyShell.evaluate() the code.
Insane. It took a lot of time and a lot of memory.
In the end we changed the format to the original one and crated scripts for each string we wanted to be able to evaluate:
Script script = shell.parse("\""+stringToParse+"\"")
where
stringToParse = "Hello world # ${System.currentTimeMillis()}!!"
Then we were able to call script.run() as many times as we wanted and everything performed well.
It actually still does.

Resources