Call methods with sililar names through a loop in geb - selenium

I'm new to Geb and fairly new in Java. I ask my self if its possible to call multiple methods through a loop. For example this part:
homePage.file1 = Content.Upload()
isDisplayed(homePage.clear1, true)
homePage.file2 = Content.Upload()
isDisplayed(homePage.clear2, true)
homePage.file3 = Content.Upload()
isDisplayed(homePage.clear3, true)
I had the idea to call this through a loop cause the names are very similar to each other. Only the numbers are different.
So I thought about something like this:
String[] elements = { "file1", "file2","file3"}
for( int i = 0; i <= elements.length - 1; i++){
homePage.elements[i] = Generator.fileUpload()
}
But this won't work. Is there any other way to get this to work?
Greetings

Think this is what you're trying to achieve?:
def elements = ["file1", "file2","file3"]
elements.each {
homePage."${it}" = Generator.fileUpload()
}

Related

creating new variable name instance using this[ ] in actionscript 3

I keep looking this over the internet but I think, as far as I have searched, nothing yet had been posted (if any, please give me some links). Is this a way to make an instance this way. When I tried, there's a compilation error, a syntax error ("expecting identifier before this"). I'm happy to receive help from you guys.
Here's my code.
var mc_Names:Array = [];
function createMovieClip(index:int):void{
var nameOfMc:String = "mc_" + index;
mc_Names[index] = nameOfMc;
var this[mc_Names[index]]:MovieClip = new MovieClip(); **// this is what I'm asking if it is possible**
this[mc_Names[index]].graphics.lineStyle(20,0x00FF00, 0.5);
this[mc_Names[index]].graphics.moveTo(square_mc.x,square_mc.y);
this[mc_Names[index]].graphics.lineTo(mc3.x, mc3.y);
this[mc_Names[index]].x = 0;
this[mc_Names[index]].y = 0;
addChildAt(this[mc_Names[index]], 0);
currentIndex++;
}
Or is there any way to make it more simple or another way of declaring variable instances through this[] to make a dynamic creation of those movieclip instances.
var index:int = 1;
var A:Array = new Array();
A[index] = "mc_1";
A[index] = new MovieClip();
A[index].graphics.lineStyle(20,0x00FF00, 0.5);
A[index].graphics.moveTo(0,0);
A[index].graphics.lineTo(100, 100);
A[index].x = 0;
A[index].y = 0;
addChildAt(A[index], 0);
//it is possible to do this way. Direct substitution... :D

zf2 validation form: How can I validate dependent fields?

I have 5 text form
$number1 = new Text('number-1');
$number2 = new Text('number-2');
$number3 = new Text('number-3');
....
with the relative filters
foreach(...)
$input = new Input($elementName);
$validator = new ValidatorChain();
$validator->addByName('Int')
->addByName('Between', array(
'min'=>0,
'max'=>$this->maxAllowedTicket,
'inclusive'=>true));
$filter = new FilterChain();
$filter->attachByName('Int');
$input->setValidatorChain($validator);
$input->setFilterChain($filter);
I would that only one of this 3 forms can contain a value different from 0.
There are then two possible errors.
TOO MANY NUMBERS
$data['number1'] = 5;
$data['number2'] = 5;
$data['number3'] = 0;
$data['number4'] = 5;
$data['number5'] = 0;
NO NUMBER
$data['number1'] = 0;
$data['number2'] = 0;
$data['number3'] = 0;
$data['number4'] = 0;
$data['number5'] = 0;
How can I validate this multiple fields at the same time ?
You need to write your own Validator class to do so. The isValid() method of your new validation class also receives the $context which includes the values of the whole form. This way you can validate the value of each field depending on the other fields.
namespace My\Validator;
use Zend\Validator\AbstractValidator;
class CustomValidator extends AbstractValidator
{
public function isValid($value, $context = null)
{
// put your logic here and call
// $this->error(); if required
}
}
Craft your own solution using the Callback validator.
Examples are here: http://packages.zendframework.com/docs/latest/manual/en/modules/zend.validator.set.html#callback

Lucene: how to preserve whitespaces etc when tokenizing stream?

I am trying to perform a "translation" of sorts of a stream of text. More specifically, I need to tokenize the input stream, look up every term in a specialized dictionary and output the corresponding "translation" of the token. However, i also want to preserve all the original whitespaces, stopwords etc from the input so that the output is formatted in the same way as the input instead of ended up being a stream of translations. So if my input is
Term1: Term2 Stopword! Term3
Term4
then I want the output to look like
Term1': Term2' Stopword! Term3'
Term4'
(where Termi' is translation of Termi) instead of simply
Term1' Term2' Term3' Term4'
Currently I am doing the following:
PatternAnalyzer pa = new PatternAnalyzer(Version.LUCENE_31,
PatternAnalyzer.WHITESPACE_PATTERN,
false,
WordlistLoader.getWordSet(new File(stopWordFilePath)));
TokenStream ts = pa.tokenStream(null, in);
CharTermAttribute charTermAttribute = ts.getAttribute(CharTermAttribute.class);
while (ts.incrementToken()) { // loop over tokens
String termIn = charTermAttribute.toString();
...
}
but this, of course, loses all the whitespaces etc. How can I modify this to be able to re-insert them into the output? thanks much!
============ UPDATE!
I tried splitting the original stream into "words" and "non-words". It seems to work fine. Not sure whether it's the most efficient way, though:
public ArrayList splitToWords(String sIn)
{
if (sIn == null || sIn.length() == 0) {
return null;
}
char[] c = sIn.toCharArray();
ArrayList<Token> list = new ArrayList<Token>();
int tokenStart = 0;
boolean curIsLetter = Character.isLetter(c[tokenStart]);
for (int pos = tokenStart + 1; pos < c.length; pos++) {
boolean newIsLetter = Character.isLetter(c[pos]);
if (newIsLetter == curIsLetter) {
continue;
}
TokenType type = TokenType.NONWORD;
if (curIsLetter == true)
{
type = TokenType.WORD;
}
list.add(new Token(new String(c, tokenStart, pos - tokenStart),type));
tokenStart = pos;
curIsLetter = newIsLetter;
}
TokenType type = TokenType.NONWORD;
if (curIsLetter == true)
{
type = TokenType.WORD;
}
list.add(new Token(new String(c, tokenStart, c.length - tokenStart),type));
return list;
}
Well it doesn't really lose whitespace, you still have your original text :)
So I think you should make use of OffsetAttribute, which contains startOffset() and endOffset() of each term into your original text. This is what lucene uses, for example, to highlight snippets of search results from the original text.
I wrote up a quick test (uses EnglishAnalyzer) to demonstrate:
The input is:
Just a test of some ideas. Let's see if it works.
The output is:
just a test of some idea. let see if it work.
// just for example purposes, not necessarily the most performant.
public void testString() throws Exception {
String input = "Just a test of some ideas. Let's see if it works.";
EnglishAnalyzer analyzer = new EnglishAnalyzer(Version.LUCENE_35);
StringBuilder output = new StringBuilder(input);
// in some cases, the analyzer will make terms longer or shorter.
// because of this we must track how much we have adjusted the text so far
// so that the offsets returned will still work for us via replace()
int delta = 0;
TokenStream ts = analyzer.tokenStream("bogus", new StringReader(input));
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
OffsetAttribute offsetAtt = ts.addAttribute(OffsetAttribute.class);
ts.reset();
while (ts.incrementToken()) {
String term = termAtt.toString();
int start = offsetAtt.startOffset();
int end = offsetAtt.endOffset();
output.replace(delta + start, delta + end, term);
delta += (term.length() - (end - start));
}
ts.close();
System.out.println(output.toString());
}

How do I mock this value using Rhino Mocks

Here is the method I'm trying to test:
public override void CalculateReductionOnYield()
{
log.LogEnter();
if (illus.RpFundStreams.Count <= 0)
{
throw new InvalidDataException("No regular premium fund streams which are required in order to calculate reduction on yield");
}
// Add the individual ReductionOnYield classes to the collection.)
foreach (RegularPremiumFundStream fs in illus.RpFundStreams)
{
foreach (int i in ReductionOnYieldMonths)
{
ReductionOnYield roy = new ReductionOnYield(i);
roy.FundStream = fs;
ReductionsOnYield.Add(roy);
}
foreach (ReductionOnYield redOnYield in ReductionsOnYield)
{
if (redOnYield.Month == 0 || illus.RegularPremiumInPlanCurrency == 0M)
{
redOnYield.Reduction = 0M;
}
else
{
double[] regPremiums = new double[redOnYield.Month + 1];
for (int i = 1; i <= redOnYield.Month; i++)
{
regPremiums[i - 1] = Convert.ToDouble(-1*redOnYield.FundStream.FundStreamMonths[i].ValRegularPremium);
}
regPremiums[redOnYield.Month] = Convert.ToDouble(redOnYield.FundStream.GetFundStreamValue(redOnYield.Month));
redOnYield.Reduction = Convert.ToDecimal(Math.Pow((1 + Financial.IRR(ref regPremiums, 0.001D)), 12) - 1);
}
}
}
How do I mock all the required classes to test the value of redOnYield.Reduction to make sure that it working properly?
e.g. how do I mock redOnYield.FundStream.GetFundStreamValue(redOnYield.Month) and redOnYield.FundStream.FundStreamMonths[i].ValRegularPremium ?
Is this a valid test? Or am I going about this the wrong way?
without more info on your objects its hard to say, but you want something like:
var fundStream = MockRepository.GenerateStub<TFundStream>();
fundStream.Stub(f => f.GetFundStreamValue(60)).Return(220000M);
var redOnYeild = MockRepository.GenerateStub<TRedOnYeild>();
redOnYeild.Stub(r => r.FundStream).Return(fundStream);
redOnYield is an object returned from iterating ReductionsOnYield. I don't see where this is coming from. If we assume it's a virtual property, then you'll want to create a collection of mock ReductionOnYield objects and stub out ReductionsOnYield to return your mocked collection (or, to make it easier to test, have CalculateReductionOnYield accept an IEnumerable and operate on that collection).
Once you get the ReductionsOnYield issue resolved, Andrew's response of stubbing out the properties will get you where you want to be. Of course, this assumes that FundStream is virtual (so it can be mocked/stubbed) as well as RegularPremiumFundStream's GetFundStreamValue and FundStreamMonths.

How do I print the list of registry keys in HKCU\Environment to SDTOUT using JScript (WSH)?

I want to iterate over the environment keys and print a list of these items.
You can access the user environment variables via the appropriate WshEnvironment collection; there's no need to mess with the registry:
var oShell = new ActiveXObject("WScript.Shell");
var oUserEnv = oShell.Environment("User");
var colVars = new Enumerator(oUserEnv);
for(; ! colVars.atEnd(); colVars.moveNext())
{
WScript.Echo(colVars.item());
}
This script will output the variable names along with values (non-expanded), e.g.:
TEMP=%USERPROFILE%\Local Settings\Temp
TMP=%USERPROFILE%\Local Settings\Temp
Path=%PATH%
PATHEXT=%PATHEXT%;.tcl
If you need the variable names only, you can extract them like this:
// ...
var strVarName;
for(; ! colVars.atEnd(); colVars.moveNext())
{
strVarName = colVars.item().split("=")[0];
WScript.Echo(strVarName);
}
Edit: To expand the variables, use the WshShell.ExpandEnvironmentStrings method; for example:
// ...
var arr, strVarName, strVarValue;
for(; ! colVars.atEnd(); colVars.moveNext())
{
arr = colVars.item().split("=");
strVarName = arr[0];
strVarValue = oShell.ExpandEnvironmentStrings(arr[1]);
WScript.Echo(strVarName + "=" + strVarValue);
}
When I tried the code given in the answer, I got an error on line 4. I believe it should be:
var colVars = new Enumerator(oUserEnv);