What are "watches" in IntelliJ and how to use them? - intellij-idea

When I debug an app, in the debug tool window there is a Watches window. I have read this manual over and over, but cannot find any practicle usage of Watches.
Somehow, I think this is a cool and useful tool and I lack from not using it.
Can someone explain when should I use it and give a few samples? Ideally, the description will be bound to a concrete (imaginary) situation so that I better apply it in my work.

This section allows you to define expressions which you'd like to see how they evolve/change with every step of your debug process, without manually inspecting all the available objects and their properties. Let's take the following simple sample which intentionally throws a NullPointerException (NPE):
public class WatchSample {
static class Student {
public static final int CREDITS_REQUIRED_FOR_GRADUATION = 10;
private String name;
private Integer credits;
public Student(String name, Integer credits) {
this.name = name;
this.credits = credits;
}
String getName() {
return name;
}
public boolean hasGraduated() {
return credits >= CREDITS_REQUIRED_FOR_GRADUATION;
}
public Integer getCredits() {
return credits;
}
}
public static void main(String[] args) throws Exception {
List<Student> students = simulateReadingFromDB();
for (Student student : students) {
if (student.hasGraduated()) {
System.out.println("Student [" + student.getName() + "] has graduated with [" + student.getCredits() + "] credits");
}
}
}
private static List<Student> simulateReadingFromDB() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("S1", 15));
students.add(new Student("S2", null)); // <- simulate some mistake
students.add(new Student("S3", 10));
return students;
}
}
At some point in time you may wonder how come you get a NPE and what needs fixing. So just set a breakpoint, add a few watches and carefully step through the lines. Eventually you'll end up with the troublemaker in sight:
Of course this is a basic example and should be taken as such. Within a regular app you'll probably have more complex scenarios and expressions you'd like to inspect, and this will make more sense, for example: if (((position > 0 && position < MAX) || (position < 0 && position > MIN) && (players(currentPlayer).isNotDead() && move.isAllowed()) && time.notUp())..... In this case you can evaluate the sub-expressions to see which one returns false
**Note**: You could also make the breakpoint conditional so that the program will pause only when that specific event occurs:

Related

In Linked list how to produce value

I would like to repeatedly enter a number that is added to a linked list.
But there's an error in the code at line x = new Node():
No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main).
Is there a way to fix my code?
static Node head;
static Node p;
static Node q;
static Node x;
class Node {
int data;
Node next;
public Node link;
// Constructor to create a new node
// Next is by default initialized
// as null
Node(int d) {
data = d;
next = null;
}
public Node() {
// TODO Auto-generated constructor stub
}
}
Two issues:
class Node should either be declared as static, or be moved to a separate file.
p = x should happen outside the else block, since it should get this value also when the if condition was true:
if(head == null) {
head = x;
} else {
p.link = x;
}
p = x;
Some remarks:
If you really want to use the Node constructor without arguments, then it is better to define explicitly what the new Node's properties should be:
public Node() {
data = 0;
next = null;
}
However, it would be better to not have this constructor signature at all, and only construct the object using the data as argument:
if(num != -999){
x = new Node(num);
...and now you don't need to do any of this any more:
x.data = num;
x.link = null;
The inner Node class is not static, meaning it belongs to a specific instance of the enclosing Main class. Since it doesn't refer to any instance methods this seems like it was not done intentionally. Make the class itself static (i.e., static class Node {) and you should be fine.
First, the class Node cannot be referenced from a static context. To fix this, make it static or move it to its own file. Second, the null pointer exception happens since you don't assign p in the special case where the list is empty.
Overall, I suggest that you clean up your class and use a more structured approach. Rename p to last to make it clear that this is a reference to the last element of the list. Move the functionality to add a node into its own method to make the code more readable. Use next in the Node class to point to the next node instead of link. Create an instance of the class where your head and last reference is defined and make them private. Use break inside the loop to only define the magic number (-999) once and exit the loop when it is entered.
The whole class could look like this:
public class CustomLinkedList {
private Node head = null;
private Node last = null;
static class Node {
int data;
Node next = null;
}
public void add(int num) {
Node x = new Node();
x.data = num;
if (this.head == null) {
this.head = x;
} else {
this.last.next = x;
}
this.last = x;
}
public static void main(String[] args) {
CustomLinkedList list = new CustomLinkedList();
int count = 0;
do {
try {
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number " + (++count) + ": ");
String strNum = dataIn.readLine();
int num = Integer.parseInt(strNum);
if (num != -999) {
list.add(num);
} else {
break; // exit loop
}
} catch (IOException e) {
System.out.print(e.getMessage());
}
} while (true);
}
}

How to pass data out from a method

I have a problem with a part of code in my Android application. I need to get the text saved in the tmp variable to see if it is null or not, but I'm not able to get the information from method onGlobalLayout. How can I do this? I'm not an expert, so I wish you could help me.
public void setText (){
int i = 0;
tmp = stringResponse;
//Log.i("TMP", " 1 " + tmp);
final PageTurnLayout flipper = (PageTurnLayout) findViewById(R.id.flipper);
while (i != 15){
final TextView tv = new TextView (this);
tv.setTextSize(20);
tv.setPadding(7, 5, 5, 0);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
tv.setText(tmp);
tmp = getInvisibleText(tv);
tmp2 = getVisibleText(tv);
tv.setText(tmp2);
}});
flipper.addView(tv);
i++;
}
}
Assuming tmp holds a string, try changing public void setText() to public String setText(), and at the bottom of the function use return(tmp);
Also, when you call the function, you will have to have a String variable(Ex. tmptext), and call the function by saying tmptext = setText();
This will return the value of tmp into the value of tmptext, and you can then use that value. I'm not sure why you have a function inside another, but you could (probably) have them separate, and just use recursion to call the functions.
Sorry if I missunderstood, it's been a while since I've done anything in Java.

C# How to define a variable as global within a (Step Defintion) class

below is an extract from a Step Definition class of my Specflow project.
In the first method public void WhenIExtractTheReferenceNumber() I can successfully extract the text from the application under test, and I have proved this using the Console.WriteLine();
I need to be able to use this text in other methods with in my class I.e. public void WhenIPrintNumber(); But I'm not sure how to do this!
I read about Get/Set but I could not get this working. So I'm thinking is it possible to make my var result global somehow, so that I can call it at anytime during the test?
namespace Application.Tests.StepDefinitions
{
[Binding]
public class AllSharedSteps
{
[When(#"I extract the reference number")]
public void WhenIExtractTheReferenceNumber()
{
Text textCaseReference = ActiveCase.CaseReferenceNumber;
Ranorex.Core.Element elem = textCaseReference;
var result = elem.GetAttributeValue("Text");
Console.WriteLine(result);
}
[When(#"I print number")]
public void WhenIPrintNumber()
{
Keyboard.Press(result);
}
}
}
Thanks in advance for any thoughts.
Here is the solution to my question. Now I can access my variable(s) from any methods within my class. I have also included code that I'm using to split my string and then use the first part of the string. In my case I need the numerical part of '12345 - some text':
namespace Application.Tests.StepDefinitions
{
[Binding]
public class AllSharedSteps
{
private string result;
public Array splitReference;
[When(#"I extract the case reference number")]
public void WhenIExtractTheCaseReferenceNumber()
{
Text textCaseReference = ActiveCase.CaseReferenceNumber;
Ranorex.Core.Element elem = textCaseReference;
result = elem.GetAttributeValue("Text").ToString();
splitReference = result.Split('-'); // example of string to be split '12345 - some text'
Console.WriteLine(splitReference.GetValue(0).ToString().Trim());
}
[When(#"I print number")]
public void WhenIPrintNumber()
{
Keyboard.Press(result); // prints full string
Keyboard.Press(splitReference.GetValue(0).ToString()); // prints first part of string i.e. in this case, a reference number
}
}
}
I hope this help somebody else :)

Java: change variable from outside while looping through a while queque

I am a Java Beginner and have a little question.
I have got 2 Classes:
the first one is a java formular, the important code is:
#Override
public void keyPressed(KeyEvent event) {
int key = event.getKeyCode();
if(key == 17) {
System.out.println("STRG");
if(roboter.running == true) {
roboter.running = false;
}
}
}
the second one is a class (called robot) which main part is the for loop:
public class Roboter {
public boolean running = false;
public void myFunction() {
for(...;...;...) {
for(...;...;...) {
if(!running)
break;
// DO SOMETHING IMPORTANT
}
}
}
Well, this doesn't work. I think it is because I can't change the value of running while my for loop. I have no idea how to slove this problem. Maybe there is an other solution? My aim is to stop the robots myFunction if an user press a key.I hope you can help me
I am sorry for my english, if you don't undestand me I will try to rewrite the question.
The class that handles the keyboard input should run in a separate Thread.

Mono.CSharp: how do I inject a value/entity *into* a script?

Just came across the latest build of Mono.CSharp and love the promise it offers.
Was able to get the following all worked out:
namespace XAct.Spikes.Duo
{
class Program
{
static void Main(string[] args)
{
CompilerSettings compilerSettings = new CompilerSettings();
compilerSettings.LoadDefaultReferences = true;
Report report = new Report(new Mono.CSharp.ConsoleReportPrinter());
Mono.CSharp.Evaluator e;
e= new Evaluator(compilerSettings, report);
//IMPORTANT:This has to be put before you include references to any assemblies
//our you;ll get a stream of errors:
e.Run("using System;");
//IMPORTANT:You have to reference the assemblies your code references...
//...including this one:
e.Run("using XAct.Spikes.Duo;");
//Go crazy -- although that takes time:
//foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
//{
// e.ReferenceAssembly(assembly);
//}
//More appropriate in most cases:
e.ReferenceAssembly((typeof(A).Assembly));
//Exception due to no semicolon
//e.Run("var a = 1+3");
//Doesn't set anything:
//e.Run("a = 1+3;");
//Works:
//e.ReferenceAssembly(typeof(A).Assembly);
e.Run("var a = 1+3;");
e.Run("A x = new A{Name=\"Joe\"};");
var a = e.Evaluate("a;");
var x = e.Evaluate("x;");
//Not extremely useful:
string check = e.GetVars();
//Note that you have to type it:
Console.WriteLine(((A) x).Name);
e = new Evaluator(compilerSettings, report);
var b = e.Evaluate("a;");
}
}
public class A
{
public string Name { get; set; }
}
}
And that was fun...can create a variable in the script's scope, and export the value.
There's just one last thing to figure out... how can I get a value in (eg, a domain entity that I want to apply a Rule script on), without using a static (am thinking of using this in a web app)?
I've seen the use compiled delegates -- but that was for the previous version of Mono.CSharp, and it doesn't seem to work any longer.
Anybody have a suggestion on how to do this with the current version?
Thanks very much.
References:
* Injecting a variable into the Mono.CSharp.Evaluator (runtime compiling a LINQ query from string)
* http://naveensrinivasan.com/tag/mono/
I know it's almost 9 years later, but I think I found a viable solution to inject local variables. It is using a static variable but can still be used by multiple evaluators without collision.
You can use a static Dictionary<string, object> which holds the reference to be injected. Let's say we are doing all this from within our class CsharpConsole:
public class CsharpConsole {
public static Dictionary<string, object> InjectionRepository {get; set; } = new Dictionary<string, object>();
}
The idea is to temporarily place the value in there with a GUID as key so there won't be any conflict between multiple evaluator instances. To inject do this:
public void InjectLocal(string name, object value, string type=null) {
var id = Guid.NewGuid().ToString();
InjectionRepository[id] = value;
type = type ?? value.GetType().FullName;
// note for generic or nested types value.GetType().FullName won't return a compilable type string, so you have to set the type parameter manually
var success = _evaluator.Run($"var {name} = ({type})MyNamespace.CsharpConsole.InjectionRepository[\"{id}\"];");
// clean it up to avoid memory leak
InjectionRepository.Remove(id);
}
Also for accessing local variables there is a workaround using Reflection so you can have a nice [] accessor with get and set:
public object this[string variable]
{
get
{
FieldInfo fieldInfo = typeof(Evaluator).GetField("fields", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
var fields = fieldInfo.GetValue(_evaluator) as Dictionary<string, Tuple<FieldSpec, FieldInfo>>;
if (fields != null)
{
if (fields.TryGetValue(variable, out var tuple) && tuple != null)
{
var value = tuple.Item2.GetValue(_evaluator);
return value;
}
}
}
return null;
}
set
{
InjectLocal(variable, value);
}
}
Using this trick, you can even inject delegates and functions that your evaluated code can call from within the script. For instance, I inject a print function which my code can call to ouput something to the gui console window:
public delegate void PrintFunc(params object[] o);
public void puts(params object[] o)
{
// call the OnPrint event to redirect the output to gui console
if (OnPrint!=null)
OnPrint(string.Join("", o.Select(x => (x ?? "null").ToString() + "\n").ToArray()));
}
This puts function can now be easily injected like this:
InjectLocal("puts", (PrintFunc)puts, "CsInterpreter2.PrintFunc");
And just be called from within your scripts:
puts(new object[] { "hello", "world!" });
Note, there is also a native function print but it directly writes to STDOUT and redirecting individual output from multiple console windows is not possible.