I am trying to print all the column values from a table based on a parameter. If the paramter matches then all the column values should be printed. This is not happening in my code below.
public class DynamicTableHandling extends DriverFactory {
static String company = "ABB India Ltd.";
public static void main(String[] args) {
init_driver("chrome");
driver.get("https://money.rediff.com/sectors/bse/power");
extractTableValues(company);
}
public static void extractTableValues(String company) {
//print all the column values from the table when the company name provided has matched//
List<WebElement> tableRow = driver.findElements(By.xpath("//table[#class='dataTable']/tbody/tr"));
for (int row = 0; row < tableRow.size(); row++) {
WebElement colData = tableRow.get(row);
List<WebElement> tableCol = colData.findElements(By.tagName("td"));
for (int col = 0; col < tableCol.size(); col++) {
String result = tableCol.get(col).getText();
if (company.equals(result.trim())) {
System.out.print(result + " | ");
break;
}
}
}
}
}
Output -- ABB India Ltd. |
The current method that you've extractTableValues has a complexity of O(n^2). You can significantly optimize to have a O(n) by making a dynamic xpath.
Your effective code:
public static void extractTableValues(String company) {
List<WebElement> tds = driver.findElements(By.xpath("//a[contains(.,'"+company+"')]//ancestor::tr//td"));
for (WebElement td : tds) {
System.out.println(td.getAttribute("innerText"));
}
}
Output:
ABB India Ltd.
A
2090.10
2084.35
+5.75
+0.28
Or Using Java 1.8:
public static void extractTableValues(String company) {
List<WebElement> tds = driver.findElements(By.xpath("//a[contains(.,'"+company+"')]//ancestor::tr//td"));
tds.stream().forEach(td -> {System.out.println(td.getText());});
}
Related
Suppose two Items 8 and 4 are there in the list. So the Sum I should get is 12. But I am getting result as 84 and not 12. I am a beginner So I don't have an idea what wrong I am doing here.
private void getCreditEntries() {
final String shift = kvName.getText().toString();
final String leaveType = selectLeaveType.getSelectedItem().toString();
final String employeeCode = empCode.getText().toString();
final String calendarYear = selectYear.getText().toString();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("LeaveDetails").child(shift)
.child("Credit").child(employeeCode).child(calendarYear);
DatabaseReference dbRef = reference.child(leaveType);
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<>();
if (!dataSnapshot.exists()) {
creditEntryLayout.setVisibility(View.GONE);
} else {
creditEntryLayout.setVisibility(View.VISIBLE);
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
LeaveCreditData data = snapshot.getValue(LeaveCreditData.class);
list.add(data);
}
rvCreditEntry.setHasFixedSize(true);
rvCreditEntry.setLayoutManager(new LinearLayoutManager(LeaveDetails.this));
rvCreditEntry.setItemAnimator(new DefaultItemAnimator());
leaveCreditAdapter = new LeaveCreditAdapter(list, LeaveDetails.this);
rvCreditEntry.setAdapter(leaveCreditAdapter);
int total = 0;
for(int i = 0; i < list.size(); i++){
total = Integer.parseInt(total + list.get(i).getTotalLeaveCredit());
creditSum.setText(String.valueOf( total));
//Suppose two Items 8 and 4 are there in the list
// So the Sum I should get is 12.
// But I am getting result as 84 and not 12
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(LeaveDetails.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
I simply edited the code as below and achieved what I wanted.
int total = 0;
for(int i = 0; i < list.size(); i++){
total += Integer.parseInt(list.get(i).getTotalLeaveCredit());
creditSum.setText(String.valueOf( total));
}
I have an ArrayList that has numbers in it in a form of Strings, that are taken from a WebElement List (Copied into it).
I have 2 of these and I would like to compare between them, But because they have some "," and "." in these numbers I have difficulty to do that.
I have tried to look into similar questions such as
How can I remove punctuation from input text in Java?
But have failed to implement it on my arrayList.
The lists in the code can be easily located as :
/ / ***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
and
***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
public static void WatchlistInstrumentsList(WebDriver driver, boolean finalstatus) throws InterruptedException
{
List<Integer> memoryOfSelectedi = new ArrayList<Integer>(); // Remembering the 'Clock = Green' instruments
int size = 2;
int forCounter1=0;
for (int i = 1; i < size ; i++) {
forCounter1=i;
// The selector of "Last" price = Streamer
listOfLastPrice1= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
// ***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
ArrayList<String> listCopyLastPrice1 = new ArrayList<String>();
for (WebElement element : listOfLastPrice1) {
listCopyLastPrice1.add(element.getText());
}
System.out.println("Number of Open stocks out of the list is: " +memoryOfSelectedi.size());
WatchlistCheckSocket(driver, listCopyLastPrice1, memoryOfSelectedi,listOfLastPrice1, forCounter1) ;
finalstatus = true;
}
public static void WatchlistCheckSocket(WebDriver driver,List listCopyLastPrice1,
List<Integer> memoryOfSelectedi, List<WebElement> listOfLastPrice1, int forCounter1) throws InterruptedException
{
// ******** CHANGE LATTER TO 180000 ******///
Thread.sleep(60000);
List<WebElement> listOfLastPrice2=null;
int size = 2;
int forCounter2;
for (int z = 0; z < size ; z++) {
listOfLastPrice2= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
size = listOfLastPrice2.size();
String NewPrice = listOfLastPrice2.get(z).getText();
System.out.println("Last Price is: " +listOfLastPrice2.get(z).getText());
}
// LIST #2 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS ///
// Put all Values of WebElement listOfLastPrice2 List, into a String array list //
ArrayList<String> listCopyLastPrice2 = new ArrayList<String>();
for (WebElement element : listOfLastPrice2) {
listCopyLastPrice2.add(element.getText());
}
// ****** COMPARE GREEN INSTRUMENTS, LIST1_Price VS LIST2_Price ****//
int sizeList=0;
while (sizeList<memoryOfSelectedi.size())
{
if (listCopyLastPrice1.get(memoryOfSelectedi.get(sizeList)) != listOfLastPrice2.get(memoryOfSelectedi.get(sizeList)).getText())
{
System.out.println("First price was: " +listCopyLastPrice1.get(memoryOfSelectedi.get(sizeList)));
System.out.println("Second price was: " +listCopyLastPrice2.get(memoryOfSelectedi.get(sizeList)));
}
sizeList++;
}}}
If I'll modify my list's syntax to that, would this help?
listCopyLastPrice2.add(element.getText().replaceAll("[^A-Za-z0-9]", ""));
I am trying to run the below code, to find the common friends between two persons. The input is as follows
A : B C D
B : A C D E
C : A B D E
D : A B C E
E : B C D
I am not able to get any output in the output file and there is no exception.
Please find my code below,
public class Friend {
public static class Mapperfriend extends Mapper<Object, Text, Text, Text>{
private Text vendor = new Text();
#Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer tokenizer = new StringTokenizer(value.toString(), "\n");
String line = null;
String[] lineArray = null;
String[] friendArray = null;
String[] tempArray = null;
while(tokenizer.hasMoreTokens()){
line = tokenizer.nextToken();
lineArray = line.split(":");
friendArray = lineArray[1].split(" ");
tempArray = new String[2];
for(int i = 0; i < friendArray.length; i++){
tempArray[0] = friendArray[i];
tempArray[1] = lineArray[0];
Arrays.sort(tempArray);
context.write(new Text(tempArray[0] + " " + tempArray[1]), new Text(lineArray[1]));
}
}
}}
public static class ReducerFriend extends Reducer<Text,Text,Text,Text>{
#Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
Text[] texts = new Text[2];
int index = 0;
for(Text val: values)
{
texts[index++] = new Text(val);
}
String[] list1 = texts[0].toString().split(" ");
String[] list2 = texts[1].toString().split(" ");
List<String> list = new LinkedList<String>();
for(String friend1 : list1){
for(String friend2 : list2){
if(friend1.equals(friend2)){
list.add(friend1);
}
}
}
StringBuffer sb = new StringBuffer();
for(int i = 0; i < list.size(); i++){
sb.append(list.get(i));
if(i != list.size() - 1)
sb.append(" ");
}
context.write(key, new Text(sb.toString()));
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Friends");
job.setJarByClass(Friend.class);
job.setMapperClass(Mapperfriend.class);
job.setReducerClass(ReducerFriend.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
The mapper class emitted the entire key from first. Instead of picking up the array. When removed that it works fine.
I want to do a query like that : "banana apple cherry" on a "fruit" field.
All the fruits in the desserts needs to be in the query, but not all the fruits in the query needs to be in the desserts..
Here's an example..
NAME FRUIT
Dessert1 banana apple OK (we got banana and apple in the query)
Dessert2 cherry apple banana OK(the order doesn't matter)
Dessert3 cherry apple banana melon NO (melon is missing in the query)
public class ArrayStringFieldBridge implements TwoWayFieldBridge{
#Override
public Object get(String name, Document document) {
IndexableField[] fields = document.getFields(name);
String[] values = new String[fields.length];
for (int i=0; i<fields.length; i++) {
values[i] = fields[i].stringValue();
}
return values;
}
#Override
public String objectToString(Object value) {
return StringUtils.join((String[])value, " ");
}
#Override
public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
String newString = StringUtils.join((String[])value, " ");
Field field = new Field(name, newString, luceneOptions.getStore(), luceneOptions.getIndex(), luceneOptions.getTermVector());
field.setBoost(luceneOptions.getBoost());
document.add(field);
}
}
#Indexed
#AnalyzerDef(name = "customanalyzer",
tokenizer = #TokenizerDef(factory = StandardTokenizerFactory.class))
public class Dessert {
#Analyzer(definition="customanalyzer")
#Field(name = "equipment", index=Index.YES, analyze = Analyze.YES, store=Store.YES)
#FieldBridge(impl=ArrayStringFieldBridge.class)
public String[] fruits = new String[]{};
}
Even if you are not using hibernate-search, every suggestions about the theory to handle that would be great... Thank you
Step 1 : Fire lucene query "fruit:banana OR fruit:apple OR fruit:cherry"
Step 2 : Gather all matched dessert documents
Step 3 : Post process your match dessert document with query
convert match document to array of terms matchDocArr : {banana, apple}
convert query terms to array - queryArr : {banana, apple, cherry}
iterate over matchDocArr and make sure each term of matchDocArr is found in queryArr by array, if NOT (melon use case) knockout this matched document
Here is an example function which needs to be called for every matched doc
public static boolean isDocInterested(String query, String matchDoc)
{
List<String> matchDocArr = new ArrayList<String>();
matchDocArr = Arrays.asList(matchDoc.split(" "));
List<String> queryArr = new ArrayList<String>();
queryArr = Arrays.asList(query.split(" "));
int matchCounter = 0;
for(int i=0; i<matchDocArr.size(); i++)
{
if (queryArr.contains(matchDocArr.get(i)))
matchCounter++;
}
if (matchCounter == matchDocArr.size())
return true;
return false;
}
if function returns TRUE we are interested in doc/dessert, if it returns FALSE ignore this doc/dessert.
of course this function can be written in many different ways but I think you get the point.
I am a beginner and I am trying to understand what is static, private, public. Please see the following example written by me. It works, but I have very big doubts whether this is a correct way of defining variables and methods. Thanks in advance!
import java.util.Scanner;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Biorhytm {
private static String nameOne;
private static String nameTwo;
private static String dobOneIn;
private static String dobTwoIn;
private static Date dobOne;
private static Date dobTwo;
static int diff;
public static Date getDobOne() {
return dobOne;
}
public static void setDobOne(Date dobOne) {
Biorhytm.dobOne = dobOne;
}
public static Date getDobTwo() {
return dobTwo;
}
public static void setDobTwo(Date dobTwo) {
Biorhytm.dobTwo = dobTwo;
}
public static String getDobOneIn() {
return dobOneIn;
}
public static void setDobOneIn(String dobOneIn) {
Biorhytm.dobOneIn = dobOneIn;
}
public static String getDobTwoIn() {
return dobTwoIn;
}
public static void setDobTwoIn(String dobTwoIn) {
Biorhytm.dobTwoIn = dobTwoIn;
}
public static String getNameOne() {
return nameOne;
}
public static void setNameOne(String nameOne) {
Biorhytm.nameOne = nameOne;
}
public static String getNameTwo() {
return nameTwo;
}
public static void setNameTwo(String nameTwo) {
Biorhytm.nameTwo = nameTwo;
}
public static int diffCalc() {
return diff = Math.abs((int)((getDobOne().getTime() - getDobTwo().getTime()) / (24 * 60 * 60 * 1000)));
}
public static void main(String[] args) {
float physicalBio;
float emotionalBio;
float intellectualBio;
boolean validEntry;
Scanner input = new Scanner(System.in);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("EEEE, MMMM d, yyyy", java.util.Locale.US);
System.out.println("Enter name of first person!");
setNameOne(input.nextLine());
if (getNameOne().equals("")) {
setNameOne("first person");
}
System.out.println("Enter name of second person!");
setNameTwo(input.nextLine());
if (getNameTwo().equals("")) {
setNameTwo("second person");
}
do {
try {
System.out.println("Enter date of birth of " + getNameOne() + "! (MM/DD/YYYY)");
setDobOneIn(input.nextLine());
setDobOne(format.parse(getDobOneIn()));
validEntry = true;
}
catch (ParseException e) {
validEntry = false;
}
} while (!validEntry);
do {
try {
System.out.println("Enter date of birth of " + getNameTwo() + "! (MM/DD/YYYY)");
setDobTwoIn(input.nextLine());
setDobTwo(format.parse(getDobTwoIn()));
validEntry = true;
}
catch (ParseException e) {
validEntry = false;
}
} while (!validEntry);
System.out.println();
System.out.println("DOB of " + getNameOne() + ": " + format2.format(getDobOne()) + ".");
System.out.println("DOB of " + getNameTwo() + ": " + format2.format(getDobTwo()) + ".");
System.out.println("Difference between DOBs (days): " + diffCalc() + ".");
physicalBio = diffCalc() % 23;
emotionalBio = diffCalc() % 28;
intellectualBio = diffCalc() % 33;
physicalBio /= 23;
emotionalBio /= 28;
intellectualBio /= 33;
if (physicalBio > 0.5) {
physicalBio = 1 - physicalBio;
}
if (emotionalBio > 0.5) {
emotionalBio = 1 - emotionalBio;
}
if (intellectualBio > 0.5) {
intellectualBio = 1 - intellectualBio;
}
physicalBio = 100 - (physicalBio * 100);
emotionalBio = 100 - (emotionalBio * 100);
intellectualBio = 100 - (intellectualBio * 100);
System.out.println("Physical compatibility: " + java.lang.Math.round(physicalBio) + " %.");
System.out.println("Emotional compatibility: " + java.lang.Math.round(emotionalBio) + " %.");
System.out.println("Intellectual compatibility: " + java.lang.Math.round(intellectualBio) + " %.");
}
}
You'd rather have your Biorhythm class be something representing the data about a single person. So you'd create two instances of it (call them "one" and "two", say) and make them non-static. It would have instance variables, not static variables, representing name and date of birth.
class Biorhythm {
private Date dob;
private String name;
Biorhythm(String name, Date dob) {
this.name = name;
this.dob = dob;
}
public String getName() {
return name;
}
public Date getDob() {
return dob;
}
}
public static void main(String[] args) {
Date onedob = /* implementation omitted */
Biorhythm one = new Biorhythm("maxval", onedob);
System.out.println("one: name=" + one.getName() + " date=" + one.getDob());
/* and so forth */
}
You don't really have a need for setXXX() methods because these values aren't probably going to change in your program.
Now create two instances of this class in your main() method. I'll leave the implementation of the calculation methods as an exercise for the time being, since there would be several decent designs for implementing them (in terms of the object-oriented question you asked).
First let me explain what these keywords are-
private,default,protected.public are ACCESS SPECIFIERS.
public-as the word says ,can be accessed everywhere and all members can be public.
protected-can be accessed outside the package in case of inheritance.
default-access able within the package and all members can be default.
private-scope lies within the class,cant be inherited.
And remember these can be used with variables,methods,even classes.
static-can be used when there is no need to invoke methods or access variables with objects.
static members doesn't belong to object and initialised at the time of loading a class.
for ex:
class Converter{
public static long convert(long val){
return val;
}
class User{
long value=Converter.convert(500);//calling convert with class name}