Difficulty making some sentences run randomly when I press the button - java

My app was built in Java, but I decided to migrate to Kotlin because it is a more current language...
The app consists of displaying some sentences at random, and for that purpose, I used the code below, but I'm having trouble converting it to Kotlin. Someone who understands more than I could help me with this? To make the app work normally, I just need to be able to translate this code.
PS.: The attributes "frases", "frasesst" and "numerosAleatorios", are in accordance with the names I gave in the project's source code.
Random random = new Random(); //gerar números aleatórios
int numerosAleatorios = random.nextInt(frasesst.length); //rodar as frases aleatóriamente quando apertar o botão
frases.setText(frasesst[numerosAleatorios]);

Kotlin version of the code is:
val numerosAleatorios = frasesst.random()
frases.setText(frasesst[numerosAleatorios])
Or you can directly use it like this without using a variable :
frases.setText(frasesst[frasesst.random()])
You can use Kotlin collections directly so you don't need this:
Random random = new Random()

Related

Why does my MCreate Java Minecraft mod not compile?

Whenever I try to run the mod, it tells me there's something wrong with the mod elements (The weapons and armor in particular), and that they do not compile correctly. This is the line of code it says was wrong (I didn't write it). new ItemStack(, (int)(1)) It says the comma is illegal. Please help me.
In Java (such as lot of other languages), this is not a valid syntax.
You should do something like:
new ItemStack(Material.MY_ITEM); // create item with default amount (1)
new ItemStack(Material.MY_ITEM, 2); // create item with 2 as amount
Also, you don't need the (int) part. You are trying to cast an int as int...

How to select random value from iOS picker wheel using Selenium

I am performing my automation in real IOS device.
In one of the aspect I have to automate a picker wheel
xpath:
//UIAApplication[1]/UIAWindow[1]/UIAPopover[1]/UIAPicker[1]/UIAPickerWheel[1]
I would like to select a random value from picker. I can able to do the by sending static value using SendKeys. Instead of the I want to select a random value.
Can I please know how can I do that using java??
Two ways to do this :
Randomise the UIAPickerWheel[1] index while you are using the x-path to access the elements.
You can put all possible static values into an ArrayList and use a random element from amongst them to input using the sendKeys() in way some-what like this :
ArrayList<String> list = new ArrayList<String>();
list.add("value1");
list.add("value2"); // so on for all your values
Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));
element.sendKeys(random);
Not sure if anyone would still need this. But just in case this could help somebody out there...
Here's an adaptation of the code in Nexial Automation:
val index = RandomUtils.nextInt(0, 7)
// index = 3
val picker = driver.findElement(By.xpath("//XCUIElementTypePickerWheel"))
val currentPickedValue = picker.getAttribute("value")
val pickerId = picker.id
// if picker already has selection, we'll swipe to top of the dropdown first
if (StringUtils.isNotBlank(currentPickedValue))
driver.executeScript(
scriptScript,
mapOf<String, Any>("element" to pickerId, "direction" to "down", "velocity" to 250))
// magic number 25 (per dropdown option)
val scrollAmount = 25.0 / picker.size.height
for (i in 0 until index)
driver.executeScript(
scriptSelectPickerValue,
mapOf<String, Any>("element" to pickerId, "order" to "next", "offset" to scrollAmount))
The code is written in Kotlin. If you know Java/JavaScript/C#, then the above should be reasonably comprehensible.
The magic number is derived via some online research and trial-and-error. Seems to work fine so far.
I randomized index as an integer between 0 to 7. Feel free to change index to something else.
This code has only been tested on XCUITest driver.
Consider moving your view interaction methods to Appium iOS Gestures which does pretty much the same as you did in your script but 'from the box'
Pickerwheel gesture

No Viable Alternative to Input '\\n" Python Error

I am working on a large scale project that involves giving a python script a first name and getting back a result as to what kind of gender it belongs to. My current program is written in Java and using Jython to interact with a Python script called "sex machine." It works great in most cases and I've tested it with smaller groups of users. However, when I attempt to test it with a large group of users the program gets about halfway in and then gives me the following error:
"Exception in thread "main" SyntaxError: No viable alternative to input '\\n'", ('<string>', 1, 22, "result = d.get_gender('Christinewazonek'')\n")
I am more accustomed to Java and have limited knowledge of Python so at the moment I don't know how to solve this problem. I tried to trim the string that I'm giving the get_gender method but that didn't help any. I am not sure what the numbers 1, 22 even mean.
Like I said since I'm using Jython my code would be the following:
static PythonInterpreter interp = new PythonInterpreter();
interp.exec("import sys, os.path");
interp.exec("sys.path.append('/Users/myname/Desktop/')");
interp.exec("import sexmachine.detector as gender");
interp.exec("d = gender.Detector()");
interp.exec("result = d.get_gender('"+WordUtils.capitalize(name).trim()
+"')");
PyObject gendAnswer = interp.get("result");
And this is pretty much the extent of Jython/Python interaction in my Java code. If someone sees something that's wrong or not right I would certainly appreciate if you could help me. As this is a large project it takes time to run the whole program again only to run into the same issue, so because of this I really need to fix this problem.
I don't know if it helps but this is what I did and it works for me.
public static void main(String[] args){
PythonInterpreter pI = new PythonInterpreter();
pI.exec("x = 3");
PyObject result = pI.get("x");
System.out.println(result);
}
Not sure if you sorted this out, but have an extra apostrophe on
d.get_gender('Christinewazonek'')
Just like in Java, everything you open you need to close, and in this case you opened a string containing )\n") which was not closed.
Depending on the interpreter you are using, this can be flagged easily. Perhaps you might try different interpreter.

Enumerate Possible Matches of Regular Expression in Java

I want to enumerate all the possible values of a finite regular expression in Java for testing purposes.
For some context, I have a regular expression that I'm using to match allowable color values in words. Here's a shortened version of it as an example:
(white|black)|((light|dark) )?(red|green|blue|gray)
I wanted to create a unit test that would enumerate all these values and pass each of them to my utility class which produces a Color object from these, that way if I change the regular expression, my unit tests will fail if an error occurs (i.e. the new color value is unsupported).
I know enumeration is possible, of course (see this question), but is there an existing library for Java which will enumerate all the possible matches for a regex?
Edit: I've implemented a library that does this. See my answer below for links.
You are right, didn't find such a tool online as well
but you can try Xeger from google
it can create a random matching string from a regexp, and with some code tweaking might do what you want.
generation a random match:
String regex = "[ab]{4,6}c";
Xeger generator = new Xeger(regex);
String result = generator.generate();
assert result.matches(regex);
Xeger code is very simple, it consists of 2 files which contain 5 methods between them..
it uses dk.brics.automaton to conver the regex to an automaton, then goes over the automaton transitions making random choices in every node.
the main function is generate:
private void generate(StringBuilder builder, State state) {
List<Transition> transitions = state.getSortedTransitions(true);
if (transitions.size() == 0) {
assert state.isAccept();
return;
}
int nroptions = state.isAccept() ? transitions.size() : transitions.size() - 1;
int option = XegerUtils.getRandomInt(0, nroptions, random);
if (state.isAccept() && option == 0) { // 0 is considered stop
return;
}
// Moving on to next transition
Transition transition = transitions.get(option - (state.isAccept() ? 1 : 0));
appendChoice(builder, transition);
generate(builder, transition.getDest());
}
you can see that in order to change it so you get all possible matches, you need to iterate over all possible combinations in every possible node (like incrementing a multi digit counter)
you will need a hash to prevent loops, but that shouldn't take more than 5 senconds to code..
i would also suggest first checking that the regex is actually finate, by checking that it doesn't have *,+ and other symbols that make this action impossible (just to make this a complete tool for reuse)...
For future browsers coming to this question, I wrote a library that uses dk.brics.automaton using a similar approach to Xeger from the accepted answer and published it. You can find it:
On GitHub
On the project site
In Maven Central
To add it as a dependency:
Maven
<dependency>
<groupId>com.navigamez</groupId>
<artifactId>greex</artifactId>
<version>1.0</version>
</dependency>
Gradle
compile 'com.navigamez:greex:1.0'
Sample Code
Using this question as an example:
GreexGenerator generator = new GreexGenerator("(white|black)|((light|dark) )?(red|green|blue|gray)");
List<String> matches = generator.generateAll();
System.out.println(matches.size()); // "14"

reading data from Matlab into Java

I'm trying to read a matrix produced in Matlab into a 2D array in java.
I've been using jmatio so far for writing from java to a .mat file (successfully), but now can't manage to go the other way around.
I've managed to import a matrix into an MLArray object using this code:
matfilereader = new MatFileReader("filename.mat");
MLArray j = matfilereader.getMLArray("dataname");
But other than getting its string representation I couldn't manage to access the data itself. I found no example for this or documentation on the library itself, and I actually wrote a function to parse the intire string into a double[][] array but that's only good if the matrix is smaller than 1000 items...
Would be grateful for any experience or tips,
thanks,
Amir
matfilereader.getMLArray has several subclasses to access different kinds of data in MLArray object.
To represent double array you can cast MLArray to MLDouble:
MLDouble j = (MLDouble)matfilereader.getMLArray("dataname");
I'm not familiar with that tool, but it's pretty old. Try saving to an older version of *.mat file and see if your results change. That is, add either the '-v7.0' or '-v6' flag when you save you r*.mat file.
Example code:
save filename var1 var2 -v7.0
or
save filename var1 var2 -v6

Categories

Resources