Unable to locate element using ID and Css selector methods - selenium-webdriver

//
// United States
copy selector = #ddlCountries
Select drpCountries = new Select(driver.findElement(By.id("ddlCountries")));
drpCountries.selectByValue("999");
I keep getting this error no such element: Unable to locate element: {"method":"id","selector":"ddlCountries"}

Call using SelectOptionInList("ddlCountries","999");
public IWebDriver SelectOptionInList(string elementID, string optionValue)
{
SelectElement ElementSelect = new SelectElement(driver.FindElement(By.Id(elementID)));
IList<IWebElement> ElementList = ElementSelect.Options;
int ElementCount = ElementList.Count;
for (int i = 0; i < ElementCount; i++)
{
string elementText = ElementList.ElementAt(i).Text;
if (elementText.Equals(optionValue))
{
ElementList.ElementAt(i).Click();
Console.WriteLine("Option " + optionValue + "Clicked");
return driver;
}
else if(elementText.Contains(optionValue))
{
ElementList.ElementAt(i).Click();
Console.WriteLine("Option " + optionValue + "Clicked");
return driver;
}
else
{
Console.WriteLine("Option " + optionValue + " Not Found Under Element with ID: " + elementID);
}
}
return driver;
}

Related

Why does this image rendering benchmark crash on IOS but not in the simulator?

I tried to get a grasp of image rendering performance and created some code which draws full screen images using mutable images and PNGs.
The code runs fine in the simulator but on an iPhone SE it crashes after 50 seconds or short before a million images.
Is it a bug or is there another explanation since it doesn't crash in the simulator and I cannot see a memory leak in jvisualvm?
Here is the code:
public class FormMeasureImage extends Form implements Painter {
abstract class Wallpaper implements Painter {
private Component componentParent;
public Wallpaper(Component aComponentParent) {
componentParent = aComponentParent;
}
public void paint(Graphics aGraphics, Rectangle aRectangle) {
aGraphics.drawImage(
getImage(new Dimension(componentParent.getWidth(), componentParent.getHeight())),
0,
0);
}
public abstract Image getImage(Dimension aDimension);
}
class WallpaperTiledIcons extends Wallpaper {
private Image image;
private Dimension dimension;
public WallpaperTiledIcons(Component aComponentParent) {
super(aComponentParent);
}
public Image getImage(Dimension aDimension) {
if ((null == image || !dimension.equals(aDimension)) && null != aDimension) {
dimension = new Dimension(aDimension);
Label labelPattern = new Label("1234567890");
Style styleLabelPattern = labelPattern.getAllStyles();
styleLabelPattern.setBorder(Border.createEmpty());
styleLabelPattern.setMargin(0, 0, 0, 0);
// byte[] bytes = new byte[4];
// Arrays.fill(bytes, Style.UNIT_TYPE_PIXELS);
// styleLabelPattern.setPaddingUnit(bytes);
styleLabelPattern.setPadding(0, 0, 0, 1);
Dimension preferredSizeLabelPattern = labelPattern.getPreferredSize();
labelPattern.setSize(preferredSizeLabelPattern);
Image imagePattern = Image.createImage(
preferredSizeLabelPattern.getWidth(),
preferredSizeLabelPattern.getHeight(),
0x00000000);
Graphics graphicsImagePattern = imagePattern.getGraphics();
graphicsImagePattern.setAlpha(255);
labelPattern.paint(graphicsImagePattern);
image = Image.createImage(
aDimension.getWidth(),
aDimension.getHeight(),
0xff606060);
Graphics graphics = image.getGraphics();
if (graphics.isAntiAliasingSupported()) {
graphics.setAntiAliased(true);
}
int canvasWidth = preferredSizeLabelPattern.getWidth(), canvasHeight = preferredSizeLabelPattern.getHeight();
int[] clip = graphics.getClip();
Rectangle rectangleClip = new Rectangle(clip[0], clip[1], clip[2], clip[3]);
int columns = (rectangleClip.getX() + rectangleClip.getWidth()) / canvasWidth + 1;
int rows = (rectangleClip.getY() + rectangleClip.getHeight()) / canvasHeight + 1;
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
int x = canvasWidth * column;
int y = canvasHeight * row;
Rectangle rectangle = new Rectangle(x, y, canvasWidth, canvasHeight);
if (!rectangleClip.intersects(rectangle)) {
continue;
}
graphics.drawImage(imagePattern, x, y);
}
}
}
return image;
}
}
abstract class Stage {
long millisTotal;
long tally;
TextArea textArea;
public Stage(String aName) {
textArea = new TextArea();
textArea.setEditable(false);
getContentPane().add(textArea);
stages.add(this);
}
abstract void perform();
abstract boolean isPainted();
}
private Wallpaper wallpaper;
private List<Stage> stages = new ArrayList<>();
private Iterator<Stage> iteratorStages;
private Image imageEncoded;
public FormMeasureImage() {
super("FormMeasureImage", new BoxLayout(BoxLayout.Y_AXIS));
setScrollableX(false);
setScrollableY(true);
Style styleForm = getAllStyles();
styleForm.setBgTransparency(255);
styleForm.setBgPainter(this);
TextArea textArea = new TextArea();
textArea.setEditable(false);
textArea.setText("Measuring image throughput.");
add(textArea);
}
#Override
public void paint(Graphics aGraphics, Rectangle aRectangle) {
if (null == iteratorStages) {
new Stage("create") {
void perform() {
long millisBefore = System.currentTimeMillis();
wallpaper = new WallpaperTiledIcons(FormMeasureImage.this);
wallpaper.getImage(aRectangle.getSize());
millisTotal += System.currentTimeMillis() - millisBefore;
tally++;
textArea.setText("create: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return false;
}
};
new Stage("mutable") {
void perform() {
long millisBefore = System.currentTimeMillis();
for (int index = 0; index < 1000; index++) {
wallpaper.paint(aGraphics, aRectangle);
tally++;
}
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("mutable: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return true;
}
};
new Stage("encoding") {
void perform() {
long millisBefore = System.currentTimeMillis();
try {
millisBefore = System.currentTimeMillis();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.getImageIO().save(wallpaper.getImage(null), byteArrayOutputStream, ImageIO.FORMAT_PNG, 1);
byteArrayOutputStream.close();
imageEncoded = Image.createImage(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
tally++;
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("encoding: " + millisTotal + " / " + tally);
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
millisTotal += System.currentTimeMillis() - millisBefore;
tally++;
textArea.setText("encoding: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return false;
}
};
new Stage("encoded") {
void perform() {
long millisBefore = System.currentTimeMillis();
for (int index = 0; index < 1000; index++) {
aGraphics.drawImage(
imageEncoded,
0,
0);
tally++;
}
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("encoded: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return true;
}
};
iteratorStages = stages.iterator();
}
while (!perform().isPainted()) {;}
}
private Stage perform() {
if (!iteratorStages.hasNext()) {
iteratorStages = stages.iterator();
}
Stage stage = iteratorStages.next();
stage.perform();
return stage;
}
}
It seems that the test case included an EDT violation of decoding off the EDT. This can work for some cases but because of the heavy usage it crashes.
Making UI code threadsafe is a difficult task which is doubly so cross platforms.

Comma separated string split by length but keeping the comma separation?

I have a string like this "105321,102305,321506,0321561,3215658" and i need to split this string by the comma (,) and with a specific length, so if the length of each string part is 15, the splited array must be like:
105321,102305
321506,0321561
3215658
I try several ways but i can't find the right approach to do this
The code that i have gives me an error of index out of range:
private static List<string> SplitThis(char charToSplit, string text, int maxSplit)
{
List<string> output = new List<string>();
string[] firstSplit = text.Split(charToSplit);
for(int i = 0; i < firstSplit.Length; i++)
{
string part = firstSplit[i];
if(output.Any() && output[i].Length + part.Length >= maxSplit)
{
output.Add(part);
}
else
{
if(!output.Any())
output.Add(part);
else
output[i] += "," + part;
}
}
return output;
}
Edit: i must say that the comma , must be a part of the amount of the maxSplit variable.
This one would be concise, yet not really performant
private static Pattern P = Pattern.compile("(.{1,15})(,|$)");
private static String[] split(String string) {
Matcher m = P.matcher(string);
List<String> splits = new ArrayList<String>();
while (m.find()) {
splits.add(m.group(1));
}
return splits.toArray(new String[0]);
}
The regular expression in P matches (.{1,15})(,|$):
a sequence of 1 to 15 characters = .{1,15}
followed by , or line ending
the parentheses allow grouping, the content of the first group is what you are interested in
static void Main(string[] args)
{
string originalString = "105321,102305,321506,0321561,3215658";
string[] commaSplit = originalString.Split(',');
string tempString = string.Empty;
List<string> result = new List<string>();
for (int i = 0; i < commaSplit.Length; i++ )
{
if ((tempString.Length + commaSplit[i].Length) > 15)
{
result.Add(tempString);
tempString = string.Empty;
}
if (tempString.Length > 0)
{
tempString += ',' + commaSplit[i];
}
else
{
tempString += commaSplit[i];
}
if (i == commaSplit.Length - 1 && tempString != string.Empty)
{
result.Add(tempString);
}
}
foreach (var s in result)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
This may not be the best solution but it works ;)
what about this?
private static List<string> SplitThis(char charToSplit, string text, int maxSplit)
{
List<string> output = new List<string>();
string[] firstSplit = text.Split(charToSplit);
int i = 0;
while (i < firstSplit.Length)
{
string part = firstSplit[i];
while (part.Length < maxSplit)
{
if (part.Length < maxSplit && i + 1 < firstSplit.Length)
{
if ((part + "," + firstSplit[i + 1]).Length < maxSplit)
{
part += "," + firstSplit[i + 1];
i++;
}
else
{
output.Add(part);
i++;
break;
}
}
else
{
output.Add(part);
i++;
break;
}
}
}
return output;
}

Flash unidentified property

For some reason unknown to me it thinks my array pressed keys is not defined. The error is : "Access of undefined property pressedKeys." But the array works fine in my onKeyDown and Up functions.. Any ideas?
Here is the code:
addEventListener(Event.ENTER_FRAME, onEnterFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
var Entities:Array = new Array();
var PressedKeys:Array = new Array();
//Create player ...more code
function onEnterFrame(event:Event):void
{
updateVel();
//...
}
function updateVel()
{
if (pressedKeys[37]) //getting error here
{
// left
player.velX -= player.speed;
}
else if (pressedKeys[65])
{
player.velX -= player.speed;
}
if (pressedKeys[38])
{
// up
player.velY -= player.speed;
}
else if (pressedKeys[87])
{
player.velY -= player.speed;
}
//more code...
}
function onKeyDown(event:KeyboardEvent):void
{
PressedKeys[event.keyCode] = true; //works fine here
trace("Keycode: " + event.keyCode + " is: " + PressedKeys[event.keyCode]);
}
function onKeyUp(event:KeyboardEvent):void
{
PressedKeys[event.keyCode] = false;
trace("Keycode: " + event.keyCode + " is: " + PressedKeys[event.keyCode]);
}
function rand(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
You need to use PressedKeys not pressedKeys - notice the upper/lower case.

How do i get Object index in an array

I have seen many threads about this but my problem doesn't solved. This may be a simple way but i have no idea...
I'm trying to get Objects indices in an array like so :
var test:Array = new Array();
for (var row:Number = 0; row < 2; row++) {
test[row] = [];
for (var column:Number = 0; column < 3; column++) {
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
addChild(test[row][column]);
}
}
function objClicked(evt:MouseEvent):void {
// Here must return Object index in array
}
P.S :
I can get items index in int array, but i don't know about objects.
Any ideas would be appreciated.
Edit :
ballShape.as
package {
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.MouseEvent;
import fl.motion.Color;
public class ballShape extends Sprite {
private var shapeId:uint;
private var currentPosition:uint;
private var arrayPosition:uint;
private var color:Number;
public function ballShape(Id:uint, currPos:uint, arrPos:uint) {
setId(Id);
setArrayPos(arrPos);
setCurrentPos(currPos);
//trace("Array : " + arrPos);
//trace("Curr : " + currPos);
if (arrPos == 0) {
var posX:uint = 60;
} else {
var posX:uint = (arrPos + 1) * 60;
}
if (currPos == 0) {
var posY:uint = 42;
} else {
var posY:uint = (currPos + 1) * 42;
}
if (arrPos == 0) {
color = 0xFF0000;
} else {
color = 0x00FF00;
}
graphics.beginFill(color, 1.0);
graphics.drawCircle(posX, posY, 20);
graphics.endFill();
this.addEventListener(MouseEvent.CLICK, Clicked);
}
public function setId(Id:uint):void {
shapeId = Id;
}
public function getId():uint {
return shapeId;
}
public function Clicked(evt:MouseEvent):void {
//return getId();
trace("Ball id is " + getId());
trace("Array id is " + getArrayPos());
trace("PositionInArray id is " + getCurrentPos());
//return arrayPosition;
}
public function setCurrentPos(Pos:uint):void {
currentPosition = Pos;
}
public function getCurrentPos():uint {
return currentPosition;
trace(currentPosition);
}
public function setArrayPos(arrayPos:uint):void {
arrayPosition = arrayPos;
}
public function getArrayPos():uint {
return arrayPosition;
trace(arrayPosition);
}
public function addBead(arrayId, currPos):void {
}
}
}
I would suggest adding row and column as public variables in your ballShape class.
That way you can get them like this:
function objClicked(evt:MouseEvent):void {
trace(ballShape(evt.target).getCurrentPos(), ballShape(evt.target).getArrayPos());
}
Maybe turn this two lines around:
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
to be :
test[row][column] = new ballShape(column, column, row);
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
Try something like:
protected function objClicked(e:MouseEvent):void {
for (var row: int=0; row < test.length; row++) {
var column:int = (test[row] as Array).indexOf(e.currentTarget);//use currentTarget so you don't try to match on internal Interactive Objects!
if (column>-1) {
trace(row, column);
return;//or break, if you need to do something else below this loop
}
}
}

How to replace words with span tag using jsoup?

Assume I have the following html:
<html>
<head>
</head>
<body>
<div id="wrapper" >
<div class="s2">I am going <a title="some title" href="">by flying</a>
<p>mr tt</p>
</div>
</div>
</body>
</html>
Any words in the text nodes that are equal to or greater than 4 characters for example the word 'going' is replaced with html content (not text) <span>going<span> in the original html without changing anything else.
If I try do something like element.html(replacement), the problem is if lets the current element is <div class="s2"> it will also wipe off <a title="some title"
In this case you must traverse your document as suggested by this answer. Here's a way of doing it using Jsoup APIs:
NodeTraversor and NodeVisitor allow you to traverse the DOM
Node.replaceWith(...) allows for replacing a node in the DOM
Here's the code:
public class JsoupReplacer {
public static void main(String[] args) {
so6527876();
}
public static void so6527876() {
String html =
"<html>" +
"<head>" +
"</head>" +
"<body>" +
" <div id=\"wrapper\" >" +
" <div class=\"s2\">I am going <a title=\"some title\" href=\"\">by flying</a>" +
" <p>mr tt</p>" +
" </div> " +
" </div>" +
"</body> " +
"</html>";
Document doc = Jsoup.parse(html);
final List<TextNode> nodesToChange = new ArrayList<TextNode>();
NodeTraversor nd = new NodeTraversor(new NodeVisitor() {
#Override
public void tail(Node node, int depth) {
if (node instanceof TextNode) {
TextNode textNode = (TextNode) node;
String text = textNode.getWholeText();
String[] words = text.trim().split(" ");
for (String word : words) {
if (word.length() > 4) {
nodesToChange.add(textNode);
break;
}
}
}
}
#Override
public void head(Node node, int depth) {
}
});
nd.traverse(doc.body());
for (TextNode textNode : nodesToChange) {
Node newNode = buildElementForText(textNode);
textNode.replaceWith(newNode);
}
System.out.println("result: ");
System.out.println();
System.out.println(doc);
}
private static Node buildElementForText(TextNode textNode) {
String text = textNode.getWholeText();
String[] words = text.trim().split(" ");
Set<String> longWords = new HashSet<String>();
for (String word : words) {
if (word.length() > 4) {
longWords.add(word);
}
}
String newText = text;
for (String longWord : longWords) {
newText = newText.replaceAll(longWord,
"<span>" + longWord + "</span>");
}
return new DataNode(newText, textNode.baseUri());
}
}
I think you need to traverse the tree. The result of text() on an Element will be all of the Element's text including text within child elements. Hopefully something like the following code will be helpful to you:
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
public class ScreenScrape {
public static void main(String[] args) throws IOException {
String content = FileUtils.readFileToString(new File("test.html"));
Document doc = Jsoup.parse(content);
Element body = doc.body();
//System.out.println(body.toString());
StringBuilder sb = new StringBuilder();
traverse(body, sb);
System.out.println(sb.toString());
}
private static void traverse(Node n, StringBuilder sb) {
if (n instanceof Element) {
sb.append('<');
sb.append(n.nodeName());
if (n.attributes().size() > 0) {
sb.append(n.attributes().toString());
}
sb.append('>');
}
if (n instanceof TextNode) {
TextNode tn = (TextNode) n;
if (!tn.isBlank()) {
sb.append(spanifyText(tn.text()));
}
}
for (Node c : n.childNodes()) {
traverse(c, sb);
}
if (n instanceof Element) {
sb.append("</");
sb.append(n.nodeName());
sb.append('>');
}
}
private static String spanifyText(String text){
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(text);
String token;
while (st.hasMoreTokens()) {
token = st.nextToken();
if(token.length() > 3){
sb.append("<span>");
sb.append(token);
sb.append("</span>");
} else {
sb.append(token);
}
sb.append(' ');
}
return sb.substring(0, sb.length() - 1).toString();
}
}
UPDATE
Using Jonathan's new Jsoup List element.textNode() method and combining it with MarcoS's suggested NodeTraversor/NodeVisitor technique I came up with (although I am modifying the tree whilst traversing it - probably a bad idea):
Document doc = Jsoup.parse(content);
Element body = doc.body();
NodeTraversor nd = new NodeTraversor(new NodeVisitor() {
#Override
public void tail(Node node, int depth) {
if (node instanceof Element) {
boolean foundLongWord;
Element elem = (Element) node;
Element span;
String token;
StringTokenizer st;
ArrayList<Node> changedNodes;
Node currentNode;
for (TextNode tn : elem.textNodes()) {
foundLongWord = Boolean.FALSE;
changedNodes = new ArrayList<Node>();
st = new StringTokenizer(tn.text());
while (st.hasMoreTokens()) {
token = st.nextToken();
if (token.length() > 3) {
foundLongWord = Boolean.TRUE;
span = new Element(Tag.valueOf("span"), elem.baseUri());
span.appendText(token);
changedNodes.add(span);
} else {
changedNodes.add(new TextNode(token + " ", elem.baseUri()));
}
}
if (foundLongWord) {
currentNode = changedNodes.remove(0);
tn.replaceWith(currentNode);
for (Node n : changedNodes) {
currentNode.after(n);
currentNode = n;
}
}
}
}
}
#Override
public void head(Node node, int depth) {
}
});
nd.traverse(body);
System.out.println(body.toString());
I am replacing word hello with hello(span tag)
Document doc = Jsoup.parse(content);
Element test = doc.body();
Elements elemenets = test.getAllElements();
for(int i =0 ;i <elemenets .size();i++){
String elementText = elemenets .get(i).text();
if(elementText.contains("hello"))
elemenets .get(i).html(l.get(i).text().replaceAll("hello","<span style=\"color:blue\">hello</span>"));
}

Resources