Trying to move e2e code into a function with no success - protractor

The problem is due to promise resolution, I pass in an xPath for all elements to be searched along with a string to search for and I would like the element returned. Here is the code:
export class Library {
static findListItem(xPath: string, findItem: string): any {
let z = 0;
const allItemsXPath = xPath.split('[X]');
const itemXPath = xPath.split('X');
console.log(xPath + ' : ' + findItem);
const itemList = element.all(by.xpath(allItemsXPath[0] + allItemsXPath[1])).map(function (item) {
return item.getText();
});
itemList.then(function (itemText) {
console.log(itemText.length);
for (let k = 0; k < itemText.length; k++) {
itemFound = true;
console.log(itemText[k] + ' : ' + findItem);
if (itemText[k] === findItem) {
z = k + 1;
console.log('found ' + z);
}
}
}).then(() => {
console.log(itemXPath[0] + z + itemXPath[1]);
// element(by.xpath(itemXPath[0] + z + itemXPath[1])).click();
return element(by.xpath(itemXPath[0] + z + itemXPath[1]));
});
};
The commented line for clicking works. It can see the element and click on it. I would like to return the element to the caller who would then click.
If the return isn't in a .then section then the return happens too quickly and z = 0. The way it is now, nothing is returned.

Your function findListItem no return value, Add return before itemList.then
static findListItem(xPath: string, findItem: string): any {
...
return itemList.then(function (itemText) {
...
});
}
Library.findListItem(xxx, yyy).then(function(item){
return item.click();
})
I have a question on your below code which to find the matched item, you compare one char of itemText with a whole string findItem per iterate. Are you sure you can find the matched one with below code.
for (let k = 0; k < itemText.length; k++) {
itemFound = true;
console.log(itemText[k] + ' : ' + findItem);
if (itemText[k] === findItem) {
z = k + 1;
console.log('found ' + z);
}
}

Related

LootLocker - How to show local rank

In my game, I am able to show the GlobalRank, however, I would also like to show the position of a player in Ranking according to the global results.
So in the bottom line, there should be the local (on this device) results.
Basically, on the left bottom corner, I want to get the RANK from the LootLocker, but I am struggling to get the rank...
IEnumerator ShowScores()
{
yield return new WaitForSeconds(2);
LootLockerSDKManager.GetScoreList(ID, maxScores, (response) =>
{
if (response.success)
{
LootLockerLeaderboardMember[] scores = response.items;
for (int i = 0; i < scores.Length; i++)
{
playerNames[i].text = (scores[i].member_id +"");
playerScores[i].text = (scores[i].score +"");
playerRank[i].text = (scores[i].rank + "");
//Rank of the localPlayer
Rank.text = (scores["here_Should_Be_This_Player_ID"].rank + "");
LootLockerSDKManager.GetPlayerName
// Entries[i].text = (scores[i].rank + ". " + scores[i].score + ". " + scores[i].member_id);
}
if (scores.Length < maxScores)
{
for (int i = scores.Length; i < maxScores; i++)
{
// Entries[i].text = (i + 1).ToString() + ". none";
}
}
}
else
{
}
});
}
Fixed it with the LootLocker support team
Step 1 - load LootLocker and get the resonse
Step 2 - load the rank and get the resonse2
Step 3 - use the "Response2.rank from the LootLocker
Rank.text = (response2.rank + "");
string playerIdentifier = "PlayerNameRecordOnThisDevice";
LootLockerSDKManager.StartSession(playerIdentifier, (response) =>
{
if (response.success)
{
Debug.Log("session with LootLocker started");
}
else
{
Debug.Log("failed to start sessions" + response.Error);
}
LootLockerSDKManager.GetMemberRank(ID, playerIdentifier, (response2) =>
{
if (response2.statusCode == 200)
{
Debug.Log("GetMemberRank Successful");
}
else
{
Debug.Log("GetMemberRank failed: " + response2.Error);
}
Rank.text = (response2.rank + "");
});
}); ```

Firebase fetch inside for loop not working properly

In my project, I took data from the android accessibility stream in a headless background function turned them into an array and split them into chunks for firebase limits, and used a for loop to iterate over them and check in firebase. Sometimes this is not working, especially since I can see the associability service runner but showing data from a bit ago. I think this happens when the user is offline and tried to fetch data from firebase. Can you please have a look at this code and tell me what the issue is and How I should solve it?
N.B: I changed some variable names for privacy purposes. There are no issues with them.
FlutterAccessibilityService.accessStream.listen((event) {
if (event.capturedText != null &&
event.capturedText != "" &&
isCold) {
text = event.capturedText!.toLowerCase();
List textList = getArray(text);
final sharedItems = getSimilarArray(fbtag, textList, sensitivity);
final sharedLocalItems =
getSimilarLocalArray(fbtag, textList, sensitivity);
final sharedAbsItems = getAbsLocalArray(fbtag, textList);
final sharedItemWithLastEval =
getSimilarArray(lastEvaluatedText, textList, sensitivity);
if (text != lastEventText &&
(sharedItemWithLastEval.length == 0 ||
lastEvaluatedText[0] == "first")) {
print("called related content");
print("bg currant text: " +
text.toString() +
" sensitivity: " +
sensitivity.toString() +
" minimumAbsMatch: " +
minimumAbsMatch.toString() +
" shared local items: " +
sharedLocalItems.toString() +
" shared abs items: " +
sharedAbsItems.toString() +
" shared items: " +
sharedItems.toString() +
" last : " +
lastEventText +
" last eval text: " +
lastEvaluatedText.toString() +
" Cold: " +
isCold.toString());
print("captured text: " + text.toString());
//GetRelatedContent(fbtag, event.capturedText);
print(sharedItems);
if (sharedLocalItems.length >= accuracy &&
sharedAbsItems.length >= minimumAbsMatch) {
print("main called");
List result = [];
lastEvaluatedText = sharedItems;
List chunkedList = chunking(sharedItems);
for (int i = 0; i < chunkedList.length; i++) {
FirebaseFirestore.instance
.collection('Content')
.where('keyWords', arrayContainsAny: chunkedList[i])
.get()
.then((value) {
for (int i = 0; i < value.docs.length; i++) {
result.add(value.docs[i].data());
print("sep");
print("result: " + result.toString());
}
if (i == chunkedList.length - 1) {
if (result.isNotEmpty) {
print("final result: " +
result[HighestMatchingIndex(sharedItems, result)[0]]
.toString());
print('result length called' +
' result: ' +
result.toString());
if (HighestMatchingIndex(sharedItems, result)[1] >=
accuracy) {
print('overlay called');
isCold = false;
Timer(Duration(seconds: 60), () {
print("Cold down");
isCold = true;
});
var FinalResult = result[
HighestMatchingIndex(sharedItems, result)[0]];
if (FinalResult['availableCountry']
.contains(country) &&
FinalResult['availableR']
.contains(r)) {
print("all passed");
String l = FinalResult[r]
[country] ??
FinalResult[r]['EN'];
String o =
FinalResult[r]['origin'];
ShowAlert(l, o, r);
}
}
}
}
});
}
}
//
}
lastEventText = text;
}
});

Render lit / lit-html TemplateResult as string

In lit/lit-html/lit-element, a standard component is the TemplateResult (usually HTMLTemplateResult), created like:
function renderMe(msg) {
return html`<div>Hello ${msg}!</div>`;
}
and of course the power and efficiency of the library is that subsequent calls will reuse the same <div> Element and only replace the changed fragments.
For testing the renderMe() function above, however, it would be helpful to be able to see the return value as a standard string, like:
assert.equal(RENDER_AS_STRING(renderMe('kimiko')), '<div>Hello kimiko!</div>');
and fix any bugs in the function before testing how it renders into the browser itself.
Is there a function like RENDER_AS_STRING either in lit itself or in a testing library? I have searched and not found one.
The result of execution contains html strings and values that alternate:
We can combine them in the same order:
function renderMe(msg) {
return html`<div>Hello ${msg}!</div>`;
}
const getRenderString = (data) => {
const {strings, values} = data;
const v = [...values, ''] // + last emtpty part
return strings.reduce((acc,s, i) => acc + s + v[i], '')
}
console.log(getRenderString(renderMe('SO')))
You can test it in the playground
And the recursive version
import {html, css, LitElement} from 'lit';
function renderMe(msg) {
return html`<p>Hello ${msg}!</p>`;
}
function renderBlock(msg) {
return html`<div>${renderMe(msg)}</div>`;
}
const getRenderString = (data) => {
const {strings, values} = data;
const v = [...values, ''].map(e => typeof e === 'object' ? getRenderString(e) : e )
return strings.reduce((acc,s, i) => acc + s + v[i], '')
}
document.getElementById('output').textContent = getRenderString(renderBlock('SO'))
#Daniil Loban's answer works great if the arguments are strings, but if they might themselves be TemplateResults or arrays of TemplateResults (which are all allowed by spec), it needs a more complex answer:
export function template_as_string(data) {
const {strings, values} = data;
const value_list = [...values, '']; // + last empty part
let output = '';
for (let i = 0; i < strings.length; i++) {
let v = value_list[i];
if (v._$litType$ !== undefined) {
v = template_as_string(v); // embedded Template
} else if (v instanceof Array) {
// array of strings or templates.
let new_v = '';
for (const inner_v of [...v]) {
new_v += template_as_string(inner_v);
}
v = new_v;
}
output += strings[i] + v;
}
return output;
}

JavaScript - Hangman - Logic Issue

I'm trying to get my Hangman game to check if the letter is found in the word, but as of now it's checking if that letter is found in every character of the word. It won't allow me to guess again after the first guess.
setScreen("WelcomeScreen");
//variables
var WordArray = ["apple", "word", "quiz"];
var currentWord = "";
var wrongCounter = 0;
var bodyPartCounter = 0;
var Guess = "";
//Welcome Screen Code
onEvent("letsGoBtn", "click", function () {
setScreen("playingHangmanScreen");
generateWord();
setUpScreenElements();
});
function generateWord() {
currentWord = WordArray[randomNumber(0,2)];
console.log(currentWord);
}
function setUpScreenElements(){
for (var i = 0; i < currentWord.length; i++) {
showElement("letterArea" + [i]);
}
var showCorrectHint = "hintWord" + currentWord;
showElement(showCorrectHint);
console.log(showCorrectHint);
}
//Guessing Code
onEvent("submitBtn", "click", function () {
Guess = getText("guessInputTxt");
console.log("The guess for " + currentWord + " is: " + Guess);
checkGuess();
});
function checkGuess() {
for (var i = 0; i < currentWord.length; i++) {
if (Guess == currentWord.charAt([i])) {
setText("letterArea" + [i], Guess);
console.log("Correctly guessed letter is: " + currentWord.charAt([i]));
}
else {
wrongCounter++;
console.log("wrongCounter for " + currentWord + " is: " + wrongCounter);
if (wrongCounter == currentWord.length) {
bodyPartCounter++;
showElement("wrongGuessImg" + bodyPartCounter);
setText("livesLeftNumber", (6-bodyPartCounter));
}
if (bodyPartCounter === 6) {
setScreen("gameOverScreen");
}
}
}
resetGuessInput();
}
function resetGuessInput () {
setText("guessInputTxt", " ");
Guess = " ";
wrongCounter = 0;
}
//Game Over Screen and Play Again Button
onEvent("playAgainBtn", "click", function () {
hideElement("hintWord" + currentWord);
generateWord();
setUpScreenElements();
setScreen("playingHangmanScreen");
for (var i = 0; i <currentWord.length; i++) {
setText("letterArea" + [i], " ");
}
for (var j = 1; j < 7; j++) {
hideElement("wrongGuessImg" + [j]);
}
bodyPartCounter = 0;
wrongCounter = 0;
setText("livesLeftNumber", "6");
});
//Victory Screen
onEvent("goHomeBtn", "click", function() {
setScreen("WelcomeScreen");
});
I've attached the code, as well as, included the link to see the app in action.
Here's a link to the app
Thanks in advance!
The checkGuess function needs to first determine where the letter appears in the word (or not), and then update the board one time, instead of updating it for each character:
function checkGuess() {
var foundAtIndex = -1;
for (var i = 0; i < currentWord.length; i++) {
if (Guess == currentWord.charAt([i])) {
foundAtIndex = i;
break;
}
}
if (foundAtIndex >= 0) {
setText("letterArea" + [foundAtIndex], Guess);
// etc...
Luckily, Javascript provides a nice IndexOf function for strings, so you can remove the loop entirely and condense that first part into:
var foundAtIndex = currentWord.indexOf(Guess);

I want to fetch the values from AdvancedCriteria

I want to fetch the values from AdvancedCriteria
My Code is like this
Now how can I retrieve values from objects ?
How did you get the values from criteria?
AdvancedCriteria cr = filterBuilder.getCriteria();
JavaScriptObject jso = cr.getJsObj();
Map map = cr.getValues();
Set keys = map.keySet();
Iterator it = keys.iterator();
while( it.hasNext()){
String key = it.next().toString();
system.out.println("=> "+map.get(key));
}
Out put
=> AdvancedCriteria
=> and
=> [object Object]
To print advanced criteria with inner criterias and advanced criterias you can do something like this:
public void onClick(ClickEvent event) {
AdvancedCriteria crit = filterBuilder.getCriteria();
printCriteria(crit, 0);
}
public void printCriteria(AdvancedCriteria ac, int level) {
char[] indentArray = new char[level];
Arrays.fill(indentArray, '\t');
String indent = new String(indentArray);
OperatorId operator = ac.getOperator();
Criteria[] c = ac.getCriteria();
for (int i = 0; i < c.length; i++) {
if (c[i].isAdvanced()) {
System.out.println(indent + "(");
printCriteria(c[i].asAdvancedCriteria(), level + 1);
System.out.println(indent + ")");
} else {
System.out.println(indent +
c[i].getAttributeAsString("fieldName") + " " +
c[i].getAttributeAsString("operator") + " " +
c[i].getAttributeAsString("value"));
}
if ((i + 1) < c.length) {
System.out.println(indent + operator);
}
}