Arraylist auto complete in eclipse - eclipse

Im using eclipse and recently my auto complete for arraylist changed for some reason.
after typing: ArrayList <String> myArrayList = new, it usually auto completes the line to: ArrayList<String> myArrayList = new ArrayList<>();, but now when I do it, it auto completes to: ArrayList<String> myArrayList = new ArrayList();(Without the <>).
Does anyone know how to fix it? is it something in eclipse I need to change? or something in the jdk/something like that?
Thanks.
Edit - for some reason it doesn't display the full code, I did define the type of the arraylist to String, so that is not the problem.
Image
Image

ArrayList<> (<> is called Diamond), is valid when the compiled can "infer" this type.
Consider this
ArrayList<String> a = new ArrayList<>();
Here this "diamond" is known to be String.
But when you do a raw ArrayList, the compiler will NOT TYPE CHECK, this can cause serious bugs and crashes in big applications. Generics are meant to reduce bugs.
See
The diamond
Why use Generics?

Try initializing your ArrayList in your constructor (or as a class variable):
ArrayList myArrayList = new ArrayList()
When you need to add to this array list just use myArrayList.add()

Related

In Katalon Studio, How to retrieve the values using the javascript executor. document.getElementsByTagName('input')[29].value

enter image description here
I tried below code but not works.
a = WebUI.executeJavaScript('document.getElementsByTagName("input")[29].value', null)
Thread.sleep(5000)
System.out.println(a)
There is so much wrong with this question that I don't even know where to begin...
What are you trying to accomplish by using JavaScript (this is a testing code smell, for 99% of testing cases) to fetch a value ?
Why not do the following:
create a TestObject, preferably in the Object Repository, that points to the object in question.
give that Test Object the locator. This is, by default, some xpath.
In your case, give it xpath
(//input)[29]
. However, I advise you come up with a more meaningful selector for it (for example, select it by some class, data-* attribute, name) that is easier to maintain
use the built-in Keyword for getting attribute, like this:
WebUI.getAttribute(findTestObject('[whateverYourTestObjectNameIs]'), 'value')
this is just good code design, but write this to some Custom Keyword for this util:
// import statements here. Ctrl + Shift + O on your keyboard to bring those in
public final class GeneralWebUIUtils {
public static final String Value = "value";
public static final String GetValue(TestObject to) {
return WebUI.getAttribute(to, this.Value);
}
}
Also, why are you pausing runtime by some hard-coded time amount? That is a testing code smell. Stop it!
What exactly are you waiting on? Use the WebUI keywords for this thing you are waiting on, and if none of those suffice, hmu and I may have the wait method you're looking for ....
Oh, and looking at that image you linked, it looks like you solved your own question.

How to make copy of array's elements in the dart

Getting wired issue like main array has been changed if changed value of another array. I think issue is about copying same address, not sure but just thinking of it. I have tried from last 3 hours but unable to get rid from it.
Look at below illustration to get better idea.
List<page> _pageList;
List<page> _orderList = [];
_pageList = _apiResponse.result as List<page>;
_orderList.add(_pageList[0].element);
_orderList[0].title = "XYZ"
//--> Here if I change the `_orderList[0].title` then it also change the `title` inside "_pageList"
How can we prevent the changes in main array?
I got same issue in my one of the project. What I have done is, use json to encode and decode object that help you to make copy of the object so that will not be affected to the main List.
After 3rd line of your code, make changes like below
Elements copyObject = Elements.fromJson(_pageList[0].element.toJson());
// First of all you have to convert your object to the Map and and map to original object like above
_orderList.add(copyObject);
Hope that will help you.
You can use a getter function to create a copy of your list and use that instead of
altering your actual list.
example:
List<Page> get orderList{
return [..._orderList];
}
Lists in Dart store references for complex types, so this is intended behaviour.
From your code:
_orderList.add(_pageList[0].element);
_orderList[0] and _pageList[0].element point to the same reference (if they are non-primitive).
There is no general copy() or clone() method in dart, as far as i know. So you need to copy the object yourself, if you want a separate instance. (see this question)

ScalaTest: Issues with Singleton Object re-initialization

I am testing a parser I have written in Scala using ScalaTest. The parser handles one file at a time and it has a singleton object like following:
class Parser{...}
object Resolver {...}
The test case I have written is somewhat like this
describe("Syntax:") {
val dir = new File("tests\\syntax");
val files = dir.listFiles.filter(
f => """.*\.chalice$""".r.findFirstIn(f.getName).isDefined);
for(inputFile <- files) {
val parser = new Parser();
val c = Resolver.getClass.getConstructor();
c.setAccessible(true);
c.newInstance();
val iserror = errortest(inputFile)
val result = invokeparser(parser,inputFile.getAbsolutePath) //local method
it(inputFile.getName + (if (iserror)" ERR" else " NOERR") ){
if (!iserror) result should be (ResolverSuccess())
else if(result.isInstanceOf[ResolverError]) assert(true)
}
}
}
Now at each iteration the side effects of previous iterations inside the singleton object Resolver are not cleaned up.
Is there any way to specify to scalatest module to re-initialize the singleton objects?
Update: Using Daniel's suggestion, I have updated the code, also added more details.
Update: Apparently it is the Parser which is doing something fishy. At subsequent calls it doesn't discard the previous AST. strange. since this is off topic, I would dig more and probably use a separate thread for the discussion, thanks all for answering
Final Update: The issue was with a singleton object other than Resolver, it was in some other file so I had somehow missed it. I was able to solve this using Daniel Spiewak's reply. It is dirty way to do things but its also the only thing, given my circumstances and also given the fact I am writing a test code, which is not going into production use.
According to the language spec, no, there is no way to recreate singleton objects. However, it is possible to reflectively invoke the constructor of a singleton, which overwrites the internal MODULE$ field which contains the actual singleton value:
object Test
Test.hashCode // => e.g. 779942019
val c = Test.getClass.getConstructor()
c.setAccessible(true)
c.newInstance()
Test.hashCode // => e.g. 1806030550
Now that I've shared the evil secret with you, let me caution you never, ever to do this. I would try very very hard to adjust the code, rather than playing sneaky tricks like this one. However, if things are as you say, and you really do have no other option, this is at least something.
ScalaTest has several ways to let you reinitialize things between tests. However, this particular question is tough to answer without knowing more. The main question would be, what does it take to reinitialize the singleton object? If the singleton object can't be reinitialized without instantiating a new singleton object, then you'd need to make sure each test loaded the singleton object anew, which would require using custom class loaders. I find it hard to believe someone would design something that way, though. Can you update your question with more details like that? I'll take a look again later and see if the extra details makes the answer more obvious.
ScalaTest has a runpath that loads classes anew for each run, but not a testpath. So you'll have to roll your own. The real problem here is that someone has designed this in a way that it is not easily tested. I would look at loading Resolver and Parser with a URLClassLoader inside each test. That way you'd get a new Resolver each test.
You'll need to take Parser & Resolver off of the classpath and off of the runpath. Put them into a directory of their own. Then create a URLClassLoader for each test that points to that directory. Then call findClass("Parser") on that class loader to get it. I'm assuming Parser refers to Resolver, and in that case the JVM will go back to the class loader that loaded Parser to get Resolver, which is your URLClassLoader. Do a newInstance on the Parser to get the instance. That should solve your problem, because you'll get a new Resolver singleton object for each test.
No answer, but I do have a simple example of where you might want to reset the singleton object in order to test the singleton construction in multiple, potential situations. Consider something stupid like the following code. You may want to write tests that validates that an exception is thrown when the environment isn't setup correctly and also write a test validates that an exception does not occur when the environment is not setup correctly. I know, I know everyone says, "Provide a default when the environment isn't setup correctly." but I DO NOT want to do this; it would cause issues because there would be no notification that you're using the wrong system.
object RequiredProperties extends Enumeration {
type RequiredProperties = String
private def getRequiredEnvProp(propName: String) = {
sys.env.get(propName) match {
case None => throw new RuntimeException(s"$propName is required but not found in the environment.")
case Some(x) => x
}
}
val ENVIRONMENT: String = getRequiredEnvProp("ENVIRONMENT")
}
Usage:
Init(RequiredProperties.ENVIRONMENT)
If I provided a default then the user would never know that it wasn't set and defaulted to the dev environment. Or something along these lines.

How to get interpolated message in NHibernate.Validator

I'm trying to integrate NHibernate.Validator with ASP.NET MVC client side validations, and the only problem I found is that I simply can't convert the non-interpolated message to a human-readable one. I thought this would be an easy task, but turned out to be the hardest part of the client-side validation. The main problem is that because it's not server-side, I actually only need the validation attributes that are being used, and I don't actually have an instance or anything else at hand.
Here are some excerpts from what I've been already trying:
// Get the the default Message Interpolator from the Engine
IMessageInterpolator interp = _engine.Interpolator;
if (interp == null)
{
// It is null?? Oh, try to create a new one
interp = new NHibernate.Validator.Interpolator.DefaultMessageInterpolator();
}
// We need an instance of the object that needs to be validated, se we have to create one
object instance = Activator.CreateInstance(Metadata.ContainerType);
// we enumerate all attributes of the property. For example we have found a PatternAttribute
var a = attr as PatternAttribute;
// it seems that the default message interpolator doesn't work, unless initialized
if (interp is NHibernate.Validator.Interpolator.DefaultMessageInterpolator)
{
(interp as NHibernate.Validator.Interpolator.DefaultMessageInterpolator).Initialize(a);
}
// but even after it is initialized the following will throw a NullReferenceException, although all of the parameters are specified, and they are not null (except for the properties of the instance, which are all null, but this can't be changed)
var message = interp.Interpolate(new InterpolationInfo(Metadata.ContainerType, instance, PropertyName, a, interp, a.Message));
I know that the above is a fairly complex code for a seemingly simple question, but I'm still stuck without solution. Is there any way to get the interpolated string out of NHValidator?
Ok, so I know this is an old question, but I stumbled across this when trying to do the same thing, and it helped me get started - so I thought I would provide an answer.
I think the code in the question was on the right track but there are a couple of problems. The interpolator was not completely initialised with the ResourceManager and Culture details, and it doesn't seem to allow for the fact that you can only have one DefaultMessageInterpolator per validation attribute. Also, you don't need an instance of the object you are validating to get an interpolated message.
In the code in the question, where you are initialising the interpolator with the attribute value, you also need to initialise the interpolator with details of the ResourceManager to be used.
This can be done using the overloaded Initialize method on DefaultMessageInterpolator which has the following signature:
public void Initialize(ResourceManager messageBundle,
ResourceManager defaultMessageBundle,
CultureInfo culture)
The first parameter is a user-defined ResourceManager in case you want to use your own resource file for error messages, you can pass a null if you just want to use the default ResouceManager, the second parameter is the default ResourceManager - you can pass
new ResourceManager(
NHibernate.Validator.Cfg.Environment.BaseNameOfMessageResource,
Assembly.GetExecutingAssembly());
for this, the last parameter is the culture to use, (NHibernate.Validator comes with resource files with validation messages in several languages) - if you pass a null in to this it will just use CultureInfo.CurrentCulture
Lastly, you can only have one DefaultMessageInterpolator per attribute, so you will need to create a new DefaultMessageInterpolator for each validation attribute. You could make use of the DefaultMessageInterpolatorAggregator to handle this, or just roll your own.
I hope this helps someone.
Thanks for your help all--I'd upvote if I could. I just wanted to add that in addition to the first Initialize call on the DefaultMessageInterpolator that Stank illustrates, I also had to make a second different Initialize call to fully initialize it (I was getting some Null Reference Exceptions using only the first call). My code is as follows:
string interpolatedMessage = "";
DefaultMessageInterpolator interpolator = new DefaultMessageInterpolator();
interpolator.Initialize(null,
new ResourceManager(
NHibernate.Validator.Cfg.Environment.BaseNameOfMessageResource,
Assembly.Load("NHibernate.Validator")),
CultureInfo.CurrentCulture);
interpolator.Initialize(attribute as Attribute);
if (attribute is IValidator && attribute is IRuleArgs)
{
IValidator validator = attribute as IValidator;
IRuleArgs ruleArgs = attribute as IRuleArgs;
InterpolationInfo interpolationInfo = new InterpolationInfo(
validatableType,
null,
propertyName,
validator,
interpolator,
ruleArgs.Message);
interpolatedMessage = interpolator.Interpolate(interpolationInfo);
}

Odd problem with ListBox.DataSource

I'm writing a Windows application and using a Listbox control. I'm developing with Visual Studio C# 2008 Express Edition.
I've got a data object that looks something like this
public class RootObject
{
public List<SubObject> MySubObjects{ get; set;}
}
I've got a ListBox on my form, and also a property "MyRootObject" which, obviously, holds a RootObject. When the control is initialized, I set:
_listBox.DataSource = MyRootObject.MySubObjects;
Now, when the form loads, I debug and see that the DataSource is being set correctly. But nothing is displayed. I've overridden SubObject's ToString() method and it's not even being called. I tried setting _listBox.DisplayMember to a property of SubObject just to see if there was some problem there, but still nothing. I tried calling _listBox.Update() and _listBox.Refresh() after setting the DataSource, but still no love. The DataSource has all the data... it's just refusing to display it.
So while debugging, I wondered WTF and I decided to just do
_listBox.DataSource = new List<SubObject>{ new SubObject(), new SubObject() };
Sure enough, this worked, and I see two things listed in my listbox.
So then, really curious, I decided to try copying the list of objects and putting that in the listbox, like so:
_listBox.DataSource = MyRootObject.MySubObjects.ToArray();
This works! And it's a workaround to my problem for now... but a very annoying one. Does anyone know why I need to basically copy the list of objects like this to get it to work, rather than just setting the _listBox.DataSource = MyRootObject.MySubObjects; ? Again, the DataSource has all the right data either way after setting it... it's just when it's copied data, it actually displays, and when it's not, it's not displayed.
((CurrencyManager)_listBox.BindingContext[_listBox.DataSource]).Refresh();
Sux0r I know, but this works.
(originally found answer here)
Off the top of my head, this is because the ListBox.DataSource property must contain something that implements the IList interface. Your generic List<SubObject> does not implement IList; it implements IList<T> (in the System.Collections.Generic namespace). Array objects, on the other hand do inherit from IList, so handing the data in via that kind of object works.
You could try pulling an Enumerator (which also implements IList) out of your List<SubObject> object and plug that in. If it works, then the issue I've described is your problem. If it doesn't, then I'm talking out of my hat.
If this is indeed the issue, I am surprised that shoving in an unsupported object doesn't throw an exception.
so far that i know, whenever you want to set a collection to a
[ComboBox,ListBox].DataSource
you have to set the DisplayMember and ValueMember. DisplayMember and ValueMember are filled with the property name of the Class in the collection that is assigned to the listbox/combobox. Ex.
//Populate the data
RootObject root = new RootObject();
root.MySubObjects.Add(new SubObject("1", "data 1"));
root.MySubObjects.Add(new SubObject("2", "data 2"));
//Assign data to the data source
_listBox.DisplayMember = "DisplayProperty";
_listBox.ValueMember = "ValueProperty";
_listBox.DataSource = root.MySubObjects;
root.MySubObjects returns List of SubObject, and SubObject has to have properties called DisplayProperty and ValueProperty, ex.
public class RootObject
{
public List<SubObject> MySubObjects { get; set; }
}
public class SubObject
{
public string ValueProperty { get; set; }
public string DisplayProperty { get; set; }
}
I think you have to call Bind method after assigning to the list box data source
something like _listBox.DataSource.bind()
and you will have your listbox disappeared
you could try and use a BindingSource
( http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx )
inbetween the Listbox and your collection. Bindingsources handles a bunch of stuff and also includes Suspend/ResumeBinding properies that can be useful when updating the list
you could also try out wpf as its databinding is far superior to that of winforms :) but maybe thats not possible in your case
I believe you need to call _listbox.DataBind(); after assigning the datasource.
However, I've never used a property as a datasource before, I've only used methods. Have you tried changing your property to a method to see if that's the problem?
You could try
_listBox.DataSource = new BindingList<SubObject> (MyRootObject.MySubObjects);
instead. BindingList implements some more interfaces than List, which are essential for DataBinding.
I have a special rule for problems like this that I always try to remember before wasting an entire day hammering on it (believe me, I've spent many days hammering!). The rule is: when system behavior is really strange, the underlying cause must be very stupid. As intelligent programmers, we have a tendancy to search for esoteric causes or bugs in framework code to explain our problems. Sometimes the answer is that we were in a hurry and made a careless mistake that we haven't yet caught.
To quote Sherlock Holmes, "when you've removed the impossible, then whatever remains, no matter how improbable, must be the truth". In this case, the improbable truth is that the MySubObjects property of MyRoot object is null.