Is is possible to do #Unique() inside Java in XPages? - xpages

When I want a unique key for documents I'm partial to using #Unique(). I like that it's based on username and time.
Is there a way to get that from inside a Java bean?
If not, what's the best way to get a unique number in Java that would not repeat?
Thanks

This is what I use whenever I need a unique number:
String controlNumber = UUID.randomUUID().toString();

Yes you can. When you get a handle to Session call evaluate. You can evaluate any formula expressions with this method.
String ID = (String)session.evaluate("#Unique").elementAt(0);

Russell's answer is correct. But if you need a shorter unique key, you can also try this alternative:
public static String getUnique() {
String CHARLIST = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
long number=System.currentTimeMillis();
int base=CHARLIST.length();
String result="";
while (number > 0){
result = CHARLIST.charAt((int)(number%base))+result;
number = number/base;
}
return result;
}
This is basically converts the number of milliseconds from 1970 to 62-base number. You can even shorten this by getting time since 2012/12/31 or so.

What about this:
public String getUnique() {
try {
return (String) getCurrentSession().evaluate("#Unique").elementAt(0);
} catch (NotesException e) {
return "";
}
}
// retrieve handle to a Notes-Domino object in the bean class
public static Session getCurrentSession() {
FacesContext context = FacesContext.getCurrentInstance();
return (Session) context.getApplication().getVariableResolver()
.resolveVariable(context, "session");
}
It will return a familiar Unique string. Unfortunately with the signature of your server, not the current username when it runs in a browser. I the client it will work as intended.

The following is the LotusScript code I developed a long time ago as part of my .DominoFramework to reproduce the behavior of #Unique(). You should be able to convert this to Java to get a set of values similar to what you are used to.
Function unique() As String
Dim Index As Integer
Try:
On Error GoTo Catch
Randomize
Unique = ""
For Index% = 1 To 4
Unique$ = Unique$ + Chr$(CInt(Rnd(Index%)*26)+65)
Next Index%
Unique$ = Unique$ + "-"
For Index% = 6 To 11
Unique$ = Unique$ + Chr$(CInt(Rnd(Index%)*26)+65)
Next Index%
Exit Function
Catch:
Stop
DominoException.throw Me, Nothing
Exit Function
End Function

Related

Making sure every Alphabet is in a string (Kotlin)

So I have a question where I am checking if a string has every letter of the alphabet in it. I was able to check if there is alphabet in the string, but I'm not sure how to check if there is EVERY alphabet in said string. Here's the code
fun isPangram (pangram: Array<String>) : String {
var panString : String
var outcome = ""
for (i in pangram.indices){
panString = pangram[i]
if (panString.matches(".^*[a-z].*".toRegex())){
outcome = outcome.plus('1')
}
else {outcome = outcome.plus('0')}
}
return outcome
}
Any ideas are welcomed Thanks.
I think it would be easier to check if all members of the alphabet range are in each string than to use Regex:
fun isPangram(pangram: Array<String>): String =
pangram.joinToString("") { inputString ->
when {
('a'..'z').all { it in inputString.lowercase() } -> "1"
else -> "0"
}
}
Hi this is how you can make with regular expression
Kotlin Syntax
fun isStrinfContainsAllAlphabeta( input: String) {
return input.lowercase()
.replace("[^a-z]".toRegex(), "")
.replace("(.)(?=.*\\1)".toRegex(), "")
.length == 26;
}
In java:
public static boolean isStrinfContainsAllAlphabeta(String input) {
return input.toLowerCase()
.replace("[^a-z]", "")
.replace("(.)(?=.*\\1)", "")
.length() == 26;
}
the function takes only one string. The first "replaceAll" removes all the non-alphabet characters, The second one removes the duplicated character, then you check how many characters remained.
Just to bounce off Tenfour04's solution, if you write two functions (one for the pangram check, one for processing the array) I feel like you can make it a little more readable, since they're really two separate tasks. (This is partly an excuse to show you some Kotlin tricks!)
val String.isPangram get() = ('a'..'z').all { this.contains(it, ignoreCase = true) }
fun checkPangrams(strings: Array<String>) =
strings.joinToString("") { if (it.isPangram) "1" else "0" }
You could use an extension function instead of an extension property (so it.isPangram()), or just a plain function with a parameter (isPangram(it)), but you can write stuff that almost reads like English, if you want!

Linq to split/analyse substrings

I have got a List of strings like:
String1
String1.String2
String1.String2.String3
Other1
Other1.Other2
Test1
Stuff1.Stuff1
Text1.Text2.Text3
Folder1.Folder2.FolderA
Folder1.Folder2.FolderB
Folder1.Folder2.FolderB.FolderC
Now I would like to group this into:
String1.String2.String3
Other1.Other2
Test1
Stuff1.Stuff1
Text1.Text2.Text3
Folder1.Folder2.FolderA
Folder1.Folder2.FolderB.FolderC
If
"String1" is in the next item "String1.String2" I will ignore the first one
and if the second item is in the third I will only take the third "String1.String2.String3"
and so on (n items). The string is structured like a node/path and could be split by a dot.
As you can see for the Folder example Folder2 has got two different Subfolder items so I would need both strings.
Do you know how to handle this with Linq? I would prefer VB.Net but C# is also ok.
Regards Athu
Dim r = input.Where(Function(e, i) i = input.Count - 1 OrElse Not input(i + 1).StartsWith(e + ".")).ToList()
Condition within Where method checks if element is last from input or is not followed by element, that contains current one.
That solution uses the fact, that input is List(Of String), so Count and input(i+1) are available on O(1) time.
LINQ isn't really the correct approach here, because you need to access more than one item at a time.
I would go with something like this:
public static IEnumerable<string> Filter(this IEnumerable<string> source)
{
string previous = null;
foreach(var current in source)
{
if(previous != null && !current.Contains(previous))
yield return previous;
previous = current;
}
yield return previous;
}
Usage:
var result = strings.Filter();
Pretty simple one. Try this:
var lst = new List<string> { /*...*/ };
var sorted =
from item in lst
where lst.Last() == item || !lst[lst.IndexOf(item) + 1].Contains(item)
select item;
the following simple line can do the trick, I'm not sure about the performance cost through
List<string> someStuff = new List<string>();
//Code to the strings here, code not added for brewity
IEnumerable<string> result = someStuff.Where(s => someStuff.Count(x => x.StartsWith(s)) == 1);

Binary search of an ArrayList object method to retrieve a string will not identify if strings are identical?

The program in it's entirety sorts an ArrayList of Student objects by integers highest average, last name, and also has the option to perform a search. My program works flawlessly except for my binary search, for which I can absolutely not determine the cause of failure. I have printed all the information as it comes up.
Here is the student class with the method that references the Student's first and last name (String).
public String getFirstName (){
return firstname;
}
public String getLastName(){
return lastname;
}
In addition, here is the code for the binary search. Yes, I know Collections has a method for this exact purpose, but for my class I need to write up the search myself.
private static void searchStudent(ArrayList<Student> a){
Scanner reader = new Scanner(System.in);
System.out.print("Please enter search term: ");
String term = reader.next();
//System.out.println(term + " " + term.length());
System.out.println("---SEARCH RESULTS:---");
for (int i = 0; i < a.size(); i++){
String fName = (a.get(i).getFirstName());
String lName = (a.get(i).getLastName());
//System.out.println(fName + " " + fName.length());
//System.out.println(lName + " " + lName.length());
if (term == fName){
System.out.println(a.get(i));
} else if (term == lName){
System.out.println(a.get(i));
}
}
}
In Java, you need to use .equals() to compare strings. E.g. instead of this:
if (term == fName){
you need to do this:
if (term.equals(fName)){
Otherwise, you are comparing references only.
Btw, this is not a binary search, it's a linear search. You can see one implementation of binary search e.g. here:
http://leepoint.net/notes-java/algorithms/searching/binarysearch.html
though to compare strings you would use .compareTo / .compareToIgnoreCase methods on the String class instead of < / > operators.

Finding sub-strings in Java 6

I looked through the String API in Java 6 and I did not find any method for computing how many times a specific sub-string appears within a given String.
For example, I would like to know how many times "is" or "not" appears in the string "noisxxnotyynotxisi".
I can do the long way with a loop, but I would like to know whether there is a simpler way.
Thanks.
Edit: I'm using Java 6.
org.apache.commons.lang.StringUtils.countMatches method could be preferred.
Without using an external library, you can use String.indexOf(String str, int fromIndex); in a loop.
Update This example fully works.
/**
* #author The Elite Gentleman
* #since 31 March 2011
*
*/
public class Test {
private static final String STR = "noisxxnotyynotxisi";
public static int count(String str) {
int count = 0;
int index = -1;
//if (STR.lastIndexOf(str) == -1) {
// return count;
//}
while ((index = STR.indexOf(str, index + 1)) != -1) {
count++;
}
return count;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Test.count("is"));
System.out.println(Test.count("no"));
}
}
You can do this, but a loop would be faster.
String text = "noisxxnotyynotxisinono";
String search = "no";
int count = text.split(search,-1).length-1;
System.out.println(Arrays.toString(text.split(search,-1)));
System.out.println("count= " + count);
prints
[, isxx, tyy, txisi, , ]
count= 5
As you can see this is correct if the text starts or ends with the search value. The -1 argument stops it removing trailing seperators.
You can use a loop with indexOf() which is more efficient, but not as simple.
BTW: Java 5.0 has been EOL since Aug 2007. Perhaps its is time to look at Java 6. (though the docs are very similar)

Comparing sentences (strings) in AS3

I'm building a short quiz where the user needs to input the meaning of an acronym.
This means I need to compare a long string (usually a sentence) typed in by the user with an acronym.
I have a feeling I'm not doing it right. For my testing I'm copy-pasting the correct answer to make sure the spelling is correct however I keep getting the feedback that the answer is incorrect.
My question is, am I comparing correctly?
Here's my code:
var arrQuestions:Array = [["LOL","Laughing Out Loud"], ["OMG", "Oh My God"], ["BTW", "By The Way"]];
var i:Number=0;
function setup():void {
quiztext_txt.text = arrQuestions[i][0];
trace(quiztext_txt.text);
trace(arrQuestions[i][1]);
check_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}//End of Setup()
setup();
function clickHandler(event:MouseEvent):void {
var givenString:String;
var inputString:String;
inputString = userinput_txt.text;
givenString = arrQuestions[i][1];
if (inputString == givenString) {
feedback_txt.text = "Correct!";
} else {
feedback_txt.text = "Wrong!";
}
}
Is there any whitespace before/after the user input? Is the value of i changing in between?
else
{
//what does it trace?
trace("given answer: " + inputString + "\ncorrect answer: " + givenString);
feedback_txt.text = "Wrong!";
}
try clearing the text field in your setup function like so:
function setup():void
{
userinput_txt.text = "";
quiztext_txt.text = arrQuestions[i][0];
trace(quiztext_txt.text);
trace(arrQuestions[i][1]);
check_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}//End of Setup()
For any kind of string matching I would strongly recommend looking into regular expressions (RegExp). In the regular expression written below I am matching each word, then I say [ ]+ which means "at least one or more spaces", then at the end of the expression I use /gi to say that the expression is case insensitive. In the code above if I type the phrase in lowercase its not going to match, a quick fix for this would be to use this if(inputString.toLowerCase() == givenString.toLowerCase()) which would catch this. Heres the regexp example:
// testString could easily equal myTextField.text
var testString:String = "lauGHing OuT loUD";
// you could store each one in an array, as you were before
var regEx:RegExp = /laughing[ ]+out[ ]+loud/gi
trace( regEx.test( testString ) ); //returns true,test() returns a Boolean
Hope this helps.

Resources