Build a dynamic string to filter a rest call - reactjs

I'm trying to build a dynamic string but I'm facing a problem, so I kindly ask help to the community.
A have a string to build a rest call filter, but I'm lost with the and's
This query only works if only one filter condition is provided, but I have to provide as AND
var query;
var queryDefault = "IsLastForLevelAndParticipant eq 1";
this.state.participantFirstName
? query += "substringof('" + this.state.participantFirstName + "',Participant/FirstName)"
: queryDefault
this.state.participantLastName
? query += "substringof('" + this.state.participantLastName + "',Participant/LastName)"
: queryDefault
So let´s see.
If I start building this and only one filter is provided I'll have a plus and
var query;
var queryDefault = "IsLastForLevelAndParticipant eq 1";
this.state.participantFirstName
? query += "substringof('" + this.state.participantFirstName + "',Participant/FirstName) and "
: queryDefault
this.state.participantLastName
? query += "substringof('" + this.state.participantLastName + "',Participant/LastName)"
: queryDefault
query += " and " + queryDefault
I have 12 filters and I must know how many have values in order to provide the and clause
This is my state
//Filters Certificates
startEmission: string;
endEmission: string;
startValidity: string;
endValidity: string;
participantFirstName: string;
participantLastName: string;
paticipantCertNumber: string;
selectYesNo: string;
selectLevel: string;
Any help is a bonus.

Add all possible filters to an array, filter the falsy values and finally join all items with " and ".
var query = [
queryDefault,
this.state.participantFirstName && "substringof('" + this.state.participantFirstName + "',Participant/FirstName)"
this.state.participantLastName && "substringof('" + this.state.participantLastName + "',Participant/LastName)"
]
.filter(item => !!item)
.join(" and ");
BTW. are you using OData? the structure of the filter looks familiar. If you do, I would recommend you to use this library: https://github.com/techniq/odata-query#readme

Since I'm using datetime also, here it is the final solution
var queryDefault = "IsLastForLevelAndParticipant eq 1";
var query = [
queryDefault,
this.state.startEmission && "(Date1 ge datetime'" + moment.utc(this.state.startEmission).toISOString() + "') and (Date1 le datetime'"
+ moment.utc(this.state.endEmission).toISOString() + "')",
this.state.startValidity && "(Validto ge datetime'" + moment.utc(this.state.startValidity).toISOString() + "') and (Validto le datetime'"
+ moment.utc(this.state.endValidity).toISOString() + "')",
this.state.participantFirstName && "(substringof('" + this.state.participantFirstName + "',Participant/FirstName))",
this.state.participantLastName && "(substringof('" + this.state.participantLastName + "',Participant/LastName))",
this.state.selectYesNo && "IsPrinted eq " + this.state.selectYesNo,
this.state.selectLevel && "Level/Title eq '" + this.state.selectLevel + "'"
]
.filter(filter => !! filter)
.join(" and ");
var q = JSON.stringify(query).substring(1).slice(0, -1);
console.log(JSON.stringify(query));

Related

SOQL Group by IN Salesforce

String query = 'SELECT id,CreatedById,Product.Id,POCGrades__c ,fm_pocname__c,product.Name ,Visit.placeId, fm_poccode__c, createdby.LastName,Visit.LastModifiedDate, createddate, ActualBooleanValue'
+ ' FROM retailvisitkpi'
+ ' WHERE createddate = last_month and '
+ ' ( Product.Id = \'01t5j000003tszWAAQ\''
+ ' OR Product.Id = \'01t5j000003tszWAAQ\''
+ ' OR Product.Id = \'01t5j000003tt5nAAA\''
+ ' OR Product.Id = \'01t5j000003tsznAAA\''
+ ' OR Product.Id = \'01t5j000003tt1zAAA\''
+ ' OR Product.Id = \'01t5j000003tt7AAAQ\''
+ ' )';
I am having trouble to removes duplicate records based on Visit.placeID, can anybody help me out with soql
Just use hashmaps with the resulting query?
Map<String, retailvisitkpi__c> mapOfItems = new Map<String, retailvisitkpi__c>();
That will remove all the duplicates based on the Visit Place ID

fnDrawCallback how to loop through each row

How do i loop through the enitre datset within the in datatables method?
"fnFooterCallback": function (nFoot, aData, iStart, iEnd, aiDisplay) {
$(aData).each(function (index) {
$(".it").append("<div class='mapdata' id='" + nFoot + "B' title='" + aData[index][14] + "|" + aData[index][15] + "' >");
});
},
The above works if the pagination is removed. But if iDisplayLength is set to 25 for example then it only goes through 25 records, not all 100 etc.
"fnFooterCallback": function (nFoot, aData, iStart, iEnd, aiDisplay) {
$(aData).each(function (index) {
$(".it").append("<div class='mapdata' id='" + nFoot + "B' title='" + aData[index][14] + "|" + aData[index][15] + "' data-id='true' data-id2='" + aData[index][1] + "' data-isapprove='" + aData[index][12] + "' ><div class='gTab1'><div class='info'><div class='maptitle'>" + aData[index][1] + "</div><div class='location'></div></div></div ></div >");
});
},
The above did it

Issue looping through an array response

I was writing an API using the kat.cr API and the IMDB api too in nodejs, I didn't use json.stringify cuz I didn't know about it at the time of writing haha XD, anyway, the problem is that when I loop through the code in 46 through 50, the response remains the same here's an example,
here is the json generated,
{
"MovieList": [{
"title": "Jurassic World",
"imdb": "tt0369610",
"poster_med": "http://ia.media-imdb.com/images/M/MV5BMTQ5MTE0MTk3Nl5BMl5BanBnXkFtZTgwMjczMzk2NTE#._V1_SX300.jpg",
"poster_big": "http://ia.media-imdb.com/images/M/MV5BMTQ5MTE0MTk3Nl5BMl5BanBnXkFtZTgwMjczMzk2NTE#._V1_SX300.jpg",
"genres": ["Action, Adventure, Sci-Fi"],
"items": [{
"torrent_magnet": "magnet:?xt=urn:btih:9D8BB2F07BC40BE4EA8EDAB7F7EB9C70A8AB2892&dn=maze+runner+the+scorch+trials+2015+hc+720p+hdrip+x264+shaanig&tr=udp%3A%2F%2Ftracker.publicbt.com%2Fannounce&tr=udp%3A%2F%2Fopen.demonii.com%3A1337",
"torrent_seeds": "1262",
"torrent_peers": "1306",
"id": "9D8BB2F07BC40BE4EA8EDAB7F7EB9C70A8AB2892"
}]
}, {
"title": "San Andreas",
"imdb": "tt2126355",
"poster_med": "http://ia.media-imdb.com/images/M/MV5BNjI4MTgyOTAxOV5BMl5BanBnXkFtZTgwMjQwOTA4NTE#._V1_SX300.jpg",
"poster_big": "http://ia.media-imdb.com/images/M/MV5BNjI4MTgyOTAxOV5BMl5BanBnXkFtZTgwMjQwOTA4NTE#._V1_SX300.jpg",
"genres": ["Action, Drama, Thriller"],
"items": [{
"torrent_magnet": "magnet:?xt=urn:btih:9D8BB2F07BC40BE4EA8EDAB7F7EB9C70A8AB2892&dn=maze+runner+the+scorch+trials+2015+hc+720p+hdrip+x264+shaanig&tr=udp%3A%2F%2Ftracker.publicbt.com%2Fannounce&tr=udp%3A%2F%2Fopen.demonii.com%3A1337",
"torrent_seeds": "1262",
"torrent_peers": "1306",
"id": "9D8BB2F07BC40BE4EA8EDAB7F7EB9C70A8AB2892"
}]
}]
}
Here is the crawler code :
var kat = require('kat-api');
var IMDb = require('imdb-scraper');
var movieTitle = require('movie-title');
var nameToImdb = require("name-to-imdb");
var movie = require('node-movie');
var fs = require('fs');
var util = require('util');
var log_file = fs.createWriteStream(__dirname + '/main.json', {
flags: 'w'
});
var log_stdout = process.stdout;
var config = '720p 2015'; //This is the line that should be changed if needed!
console.log = function(d) { //
log_file.write(util.format(d) + '\n');
log_stdout.write(util.format(d) + '\n');
};
var kat = require('kat-api');
kat.search({
query: config,
category: 'movies',
language: 'en'
}).then(function(response) {
var quotes = '"';
var startingOfJson = "{" + quotes + "MovieList" + quotes + ":" + "[";
var endingOfJson = "}";
var itemStart = quotes + "items" + quotes + ":" + "[{";
var itemEnd = "}]";
console.log(startingOfJson);
for (i = 0; i <= 20; i++) {
var titleForEverything = movieTitle(response.results[i].title);
movie(titleForEverything, function(err, data) {
console.log("{");
console.log(quotes + "title" + quotes + ":" + quotes + data.Title + quotes + ",");
console.log(quotes + "imdb" + quotes + ":" + quotes + data.imdbID + quotes + ",");
console.log(quotes + "poster_med" + quotes + ":" + quotes + data.Poster + quotes + ",");
console.log(quotes + "poster_big" + quotes + ":" + quotes + data.Poster + quotes + ",");
var genres = quotes + "genres" + quotes + ":" + "[" + quotes + data.Genre + quotes + "]" + ",";
console.log(genres);
console.log(itemStart);
console.log(quotes + "torrent_magnet" + quotes + ":" + quotes + response.results[i].magnet + quotes + ",");
console.log(quotes + "torrent_seeds" + quotes + ":" + quotes + response.results[i].seeds + quotes + ",");
console.log(quotes + "torrent_peers" + quotes + ":" + quotes + response.results[i].peers + quotes + ",");
console.log(quotes + "id" + quotes + ":" + quotes + response.results[i].hash + quotes);
console.log(itemEnd);
if (i == 20) {
console.log("}");
} else {
console.log("},")
}
});
}
}).catch(function(error) {
console.log('an error occured' + error);
});
console.log("]}");
and you can see that the magnet, seeds, hash and peers remain the same for all the results generated! How can I fix this and why does this happen? Thank you! :D
You're committing the classic error of a function inside a loop closing over the loop index i; when the function is executed, i will already have its final value. The easiest way to fix this is with for (let i.

How to add extra column to protractor-html-screenshot-reporter like duration for each "it" block

I am trying to add an extra column to the HTML report. Like duration of each "it" block. I tried this inside jsonparser.js file.
phssr.makeHTMLPage = function(tableHtml, reporterOptions){
var styleTag = phssr.makeHardCodedStyleTag(reporterOptions);
var scrpTag = phssr.makeScriptTag();
var staticHTMLContentprefix = "<html><head><meta charset='utf-8'/>";
//Add title if it was in config setup
if (typeof (reporterOptions.docTitle) !== 'undefined' && _.isString(reporterOptions.docTitle) ){
staticHTMLContentprefix += "<title>" + reporterOptions.docTitle + "</title>";
} else {
staticHTMLContentprefix += "<title></title>";
}
staticHTMLContentprefix += styleTag + scrpTag + " </head><body>";
staticHTMLContentprefix += "<h1>" + reporterOptions.docHeader + "</h1><table class='header'>";
staticHTMLContentprefix += "<tr><th class='desc-col'>Description</th><th class='status-col'>Passed</th>";
staticHTMLContentprefix += "<th class='browser-col'>Browser</th>";
staticHTMLContentprefix += "<th class='os-col'>OS</th><th class='msg-col'>Message</th>";
staticHTMLContentprefix += "<th class='msg-col'>Duration</th>";
staticHTMLContentprefix += "<th class='img-col'>Screenshot</th></tr></table>";
var staticHTMLContentpostfix = "</body></html>";
var htmlComplete = staticHTMLContentprefix + tableHtml + staticHTMLContentpostfix;
return htmlComplete;
}
phssr.getTimestamp = function (date) {
function pad(n) { return n < 10 ? '0' + n : n; }
var currentDate = date !== undefined ? date : new Date(),
month = currentDate.getMonth() + 1,
day = currentDate.getDate();
return (currentDate.getFullYear() + "-" + pad(month) + "-" + pad(day) + " " + pad(currentDate.getHours()) + ":" + pad(currentDate.getMinutes()) + ":" + pad(currentDate.getSeconds()));
}
var sTime = new Date();
var startTime = phssr.getTimestamp(sTime);
console.log("sTime***********************",startTime);
var passCount=0, failCount=0, loopCount=0;
function generateHTML(data){
var eTime = new Date();
var endTime = phssr.getTimestamp(eTime);
console.log("eTime***********************",endTime);
var diffTime = (eTime-sTime)/1000;
console.log("dTime***********************",diffTime);
data.passed? passCount++: failCount++;
var str = '<table><tr>';
str += '<td class="desc-col">' + data.desc + '</td>';
var bgColor = data.passed? 'green': 'red';
str += '<td class="status-col" style="color:#fff;background-color: '+ bgColor+'">' + data.passed + '</td>';
str += '<td class="browser-col">' + data.browser.name+ ':' +data.browser.version + '</td>';
str += '<td class="os-col">' + data.os + '</td>';
var stackTraceInfo = data.passed? '': '<br/><a onclick="showTrace(event)" href="#trace-modal'+loopCount+'">View Stack Trace Info</a><br/> <div id="#trace-modal'+loopCount+'" class="traceinfo"><div>X' + data.trace + '</div></div>';
str += '<td class="msg-col">' + data.message+ stackTraceInfo+ '</td>';
str += '<td class="msg-col">' + diffTime + '</td>';
if(!(reporterOptions.takeScreenShotsOnlyForFailedSpecs && data.passed)) {
str += '<td class="img-col">View </td>';
}
else{
str += '<td class="img-col"></td>';
}
str += '</tr></table>';
loopCount++;
return str;
}
I can see the extra column in the report. The problem was it is not showing the correct time. In the console it is printing like this
sTime*********************** 2015-08-28 13:26:44
Using the selenium server at http://localhost:4444/wd/hub
.eTime*********************** 2015-08-28 13:26:48
dTime*********************** 3.312
.eTime*********************** 2015-08-28 13:26:52
dTime*********************** 7.984
eTime*********************** 2015-08-28 13:26:52
dTime*********************** 7.984
.
Finished in 12.123 seconds
3 tests, 3 assertions, 0 failures
eTime*********************** 2015-08-28 13:26:57
dTime*********************** 12.325
eTime*********************** 2015-08-28 13:26:57
dTime*********************** 12.325
eTime*********************** 2015-08-28 13:26:57
dTime*********************** 12.325
here, I don't know why it is executing two times. In the report it is showing 12.325 for all blocks. I don't know where I am doing wrong. please help me.
Tests:
describe('Title', function() {
it('TESTCASE-1 : Should have a title', function() {
expect(browser.getTitle()).toContain('Test');
});
it('TESTCASE-2 : Should accept a valid email address and password', function() {
element(by.id('email')).sendKeys('*********');
element(by.id('password')).sendKeys('*********');
element(by.css('.btn')).click();
expect(browser.getCurrentUrl()).toEqual('*********/app/#/home');
});
it('TESTCASE-4: Dashboard Selection.....', function(){
var menubutton = element.all(by.css('.btn')).get(0);
menubutton.click();
expect(browser.getCurrentUrl()).toEqual('*************************/students/1');
});
});

Reading calendar folder in a date range using JACOB

hi guys is it possible on JACOB on reading only CALENDAR folder with a date range and let me get the subject. If yes please give a sample code for reference. Thanks a lot
This code has two filters
1) first only by date range - start and end date
2) filter by subject = "test"
If you need only date, you can omit second filter.
How to: Filter Recurring Appointments and Search for a String in the Subject
Dispatch namespace = outlokAx.getProperty("Session").toDispatch();
Dispatch calendarFolder = Dispatch.call(namespace, "GetDefaultFolder", new Integer(9)).toDispatch();
Dispatch calItems = Dispatch.get(calendarFolder, "items").toDispatch();
String customFilter = "#SQL=\"urn:schemas:calendar:dtstart\" > '" + DateUtility.dateToUtcString(startDate) + "' and \"urn:schemas:calendar:dtend\" = '" + DateUtility.dateToUtcString(endDate) + "'" ;
String customFindFilter = "#SQL=\"urn:schemas:httpmail:subject\" like '" + "test" + "'" ;
Dispatch restrictedItems = Dispatch.call(calItems, "Restrict", new Variant(customFilter)).toDispatch(); //Works only with dates
Dispatch.call(calItems, "Sort", "[Start]");
Dispatch.put(restrictedItems, "IncludeRecurrences", "False");
int numberOfMatchingItems = 0;
Dispatch lastitemFound = null;
if (restrictedItems != null && restrictedItems.m_pDispatch > 0) {
Dispatch findItem = Dispatch.call(restrictedItems, "Find", customFindFilter).toDispatch(); // Find Works with other attributes
while (findItem != null && findItem.m_pDispatch > 0) {
numberOfMatchingItems++;
lastitemFound = findItem;
findItem = Dispatch.call(restrictedItems, "FindNext").toDispatch();
Variant start = Dispatch.get(findItem, "Start");
Variant end = Dispatch.get(findItem, "End");
Variant subject = Dispatch.get(findItem, "Subject");
System.out.println("# Outlook event fetched: " + subject + " start: '" + start + "' end '" + end + "'");
}
}

Resources