Match with multiple conditions in $OR - regex

In MongoDB I have 2 conditions
First condition:
"\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}";
Second condition:
"\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}";
I need to OR condition on this statement so what I did is:
matchquery = matchquery + "\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}"+["%OR:"]+"\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}";
but of course that did not work. How can I achieve this?

Use the Or Operator & create it like this :
var condition1 =
"\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}";
var condition2 = "\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}";
var matchquery = "{ \"$or\" : [ " + condition1 + "," + condition2 +" ]}"

Use the $or operator. You essentially want to create a query which has the form
var matchquery = {
'$or': [
{ 'userfullname': { '$regex': \filtertext\, '$options': 'i' } },
{ 'email': { '$regex': \filtertext\, '$options': 'i' } }
]
}
If filtertext is a variable then you can use RegExp constructor which creates a regular expression object for matching text with a pattern. For example:
var filtertext = "foo";
var rgx = new RegExp(filtertext, "i");
var matchquery = {
"$or": [
{ "userfullname": rgx },
{ "email": rgx }
]
};
To stringify the query, you could try:
var filtertext = "foo";
var rgx = new RegExp(filtertext, "i");
var matchquery = '{ "$or":[{ "userfullname": {"$regex": '+ rgx.toString() +'} },{ "email":{ "$regex": '+ rgx.toString() + '} }] } }';

Related

Google Chart google.visualization.arrayToDataTable: How can I pass a formatted string

I have created the following string in PHP
["Month", "Points", {role: "style"}, "Goal", {role: "annotation"}],
["JAN", 3, "#4a7dae", 6.5, ""],
["FEB", 2, "#4a7dae", 6.5, ""],
["MAR", 3, "#4a7dae", 6.5, ""],
["APR", 1, "#4a7dae", 6.5, ""],
["MAY", 2, "#4a7dae", 6.5, ""],
["JUN", 1, "#4a7dae", 6.5, "Goal (6.5)"]
and want the same to use in Google Chart data
The above string I have grabbed in a JavaScript variable (str_data) and tried like this
var data = google.visualization.arrayToDataTable([str_data]);
but getting the following error:
jsapi_compiled_default_module.js:23 Uncaught (in promise) Error: First row is not an array.
at gvjs_rba (jsapi_compiled_default_module.js:23)
at Object.gvjs_Tl [as arrayToDataTable] (jsapi_compiled_default_module.js:25)
at prev_year_chart_callback_function (evd-all.js?ver=1.0:212)
UPDATE (PHP code)
The following code runs inside a loop and creates one row at a time.
$model_str = '["Month", "Points", {role: "style"}, "Goal", {role: "annotation"}],';
if ( $row_index === count( $assoc_array ) - 1 ) {
$model_str .= '["' . $unix_month_start_formatted . '", ' . $assoc_array[ $key ] . ', "#4a7dae", ' . $prior_season_goal_point . ', "Goal (' . $prior_season_goal_point . ')"],';
} else {
$model_str .= '["' . $unix_month_start_formatted . '", ' . $assoc_array[ $key ] . ', "#4a7dae", ' . $prior_season_goal_point . ', ""],';
}
instead of trying to pass json as a string
build the json in php, then pass the encoded json as a string
// create column headings
$model_str = [];
$columns = [];
$columns[] = "Month";
$columns[] = "Points";
$columns[] = ["role" => "style"];
$columns[] = "Goal";
$columns[] = ["role" => "annotation"];
$model_str[] = $columns;
// create rows
$row = [];
if ( $row_index === count( $assoc_array ) - 1 ) {
$row[] = $unix_month_start_formatted;
$row[] = $assoc_array[$key];
$row[] = "#4a7dae";
$row[] = $prior_season_goal_point;
$row[] = "Goal (" . $prior_season_goal_point . ")";
} else {
$row[] = $unix_month_start_formatted;
$row[] = $assoc_array[$key];
$row[] = "#4a7dae";
$row[] = $prior_season_goal_point;
$row[] = "";
}
$model_str[] = $row;
// return json
echo json_encode($model_str);
then, assuming you're using ajax to get the data, set the type to json...
$.ajax({
url: '...',
dataType: 'json'
}).done(...

Regex - Replace input and output as decimals only? [duplicate]

Anyone have a regex to strip lat/long from a string? such as:
ID: 39.825 -86.88333
To match one value
-?\d+\.\d+
For both values:
(-?\d+\.\d+)\ (-?\d+\.\d+)
And if the string always has this form:
"ID: 39.825 -86.88333".match(/^ID:\ (-?\d+\.\d+)\ (-?\d+\.\d+)$/)
var latlong = 'ID: 39.825 -86.88333';
var point = latlong.match( /-?\d+\.\d+/g );
//result: point = ['39.825', '-86.88333'];
function parseLatLong(str) {
var exp = /ID:\s([-+]?\d+\.\d+)\s+([-+]?\d+\.\d+)/;
return { lat: str.replace(exp, "$1"), long: str.replace(exp, "$2") };
}
function doSomething() {
var res = parseLatLong("ID: 39.825 -86.88333");
alert('Latitude is ' + res.lat + ", Longitude is " + res.long);
}

OnClick event on Custom legends Chart.js / Angular 5

I'm working on a project using Angular 5 and Chart.js.
I needed to create custom legends into my charts so I follow this git issue to help me a bit: Github Issue Chart.js.
It was very helpful and It worked as expected only with pure javascript, but trying to reply the example into Angular 5 App just doesn't work, it throws me this.updateDataset() is not a function.
Here is a snippet of what I'm currently doing into the options object of Chart.js library:
legendCallback: (chart) => {
const legendHtml = [];
legendHtml.push('<table>');
legendHtml.push('<tr>');
for (let i=0; i<chart.data.datasets.length; i++) {
const color = chart.data.datasets[i].borderColor;
const legendId = 'linear-d'+i;
legendHtml.push(
'<td onclick="this.updateDataset(event,' + '\'' + chart.legend.legendItems[i].datasetIndex + '\'' + ', ' + '\'' + legendId + '\'' + ')">' +
'<div id="'+legendId+'-square" style="background-color:' + color +'; border: 2px solid ' + color +'; width: 15px; height: 15px;"></div>' +
'</td>'
);
if (chart.data.datasets[i].label) {
legendHtml.push('<td id="'+legendId+'-text" style="cursor: default; font-size: 12px;" onclick="this.updateDataset(event,' + '\'' + chart.legend.legendItems[i].datasetIndex + '\'' + ', ' + '\'' + legendId + '\'' + ')">' + chart.data.datasets[i].label + '</td>');
}
}
legendHtml.push('</tr>');
legendHtml.push('</table>');
return legendHtml.join("");
},
So the important part is this one '<td onclick="this.updateDataset(event,' + '\'' + chart.legend.legendItems[i].datasetIndex + '\'' + ', ' + '\'' + legendId + '\'' + ')">' where the onclick is trying to call this.updateDataset().
How should I call the function updateDataset() into the onclick event of the element or how should I declare the function so I could access to it from the onclick event.
It's not a neat solution but it's the only one I found so far.
Instead of using the onclick event I added an eventListener after adding the new legend. Then you need to do minor changes to the updateDataset() function.
The legendCallback should look something like this:
legendCallback: (chart) => {
var legendHtml = [];
legendHtml.push('<table>');
legendHtml.push('<tr>');
for (var i=0; i<chart.data.datasets.length; i++) {
legendHtml.push('<td><div class="chart-legend" style="background-color:' + chart.data.datasets[i].backgroundColor + '"></div></td>');
if (chart.data.datasets[i].label) {
legendHtml.push('<td class="chart-legend-label-text" id="' + chart.id + '_' + chart.legend.legendItems[i].datasetIndex + '">' + chart.data.datasets[i].label + '</td>');
}
}
legendHtml.push('</tr>');
legendHtml.push('</table>');
return legendHtml.join("");
},
And then add the listener and the updateDataset() function after the declaration of the Chart:
document.getElementById("customLegend" + this.chartId).innerHTML = myChart.generateLegend();
var legenTags = document.getElementsByClassName("chart-legend-label-text");
var updateDataset = function(e) {
var id = e.currentTarget.id;
var index = id.split('_')[1];
var chartId= id.split('_')[0];
if (myChart.id == chartId) {
var meta = myChart.getDatasetMeta(index);
// See controller.isDatasetVisible comment
meta.hidden = meta.hidden === null? !myChart.data.datasets[index].hidden : null;
// We hid a dataset ... rerender the chart
myChart.update();
}
}
for (var i = 0; i < legenTags.length; i++) {
legenTags[i].addEventListener('click', updateDataset, false);
}
I hope it helps.
If anyone has a better solution please share.

Google Visualization : How do I perform check/uncheck with google visualization table associated checkbox?

Problem:
I am unable to perform the check and uncheck action with google visualization table associated checkbox. The checkboxes are generated dynamically based on the query value.(0/1)
Code:
function drawQuestions(queryResponse, table_container_id) {
if (queryResponse.isError()) {
alert('Error in query: ' + queryResponseData.getMessage() + ' ' + queryResponseData.getDetailedMessage());
return;
}
var questionBankResponse = queryResponse.getDataTable();
if (questionBankResponse.getNumberOfRows() === 0) {
alert('Empty rows in query: ' + );
return;
}
var questionDataTable = new google.visualization.DataTable();
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
var questionDataTableRow = new Array();
var rowCounter;
var questionHeader = questionBankResponse.getValue(0, 0);
for (rowCounter = 0; rowCounter < questionBankResponse.getNumberOfRows() ; rowCounter++) {
var count = 0 * 1;
var chbQuestion;
var questionId = questionBankResponse.getValue(rowCounter, 2);
var questionName = questionBankResponse.getValue(rowCounter, 3);
var answerValue = questionBankResponse.getValue(rowCounter, 4);
var answerOthers = questionBankResponse.getValue(rowCounter, 5);
if (answerValue === null)
answerValue = 0;
if (answerValue.toString() === "1") {
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\" checked=\"true\" />";
}
else {
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\" />";
}
if (isNaN(answerOthers))
txtAnswerOthers = "<input type=\"text\"" + "size=\"100\" id=\"" + questionId + "\"" + " value='" + answerOthers + "' name='" + answerOthers + "' />";
else
txtAnswerOthers = null;
questionDataTableRow[count++] = chbQuestion;
questionDataTableRow[count++] = questionName;
questionDataTableRow[count++] = txtAnswerOthers;
questionDataTable.addRow(questionDataTableRow);
}
for (rowCounter = 0; rowCounter < questionDataTable.getNumberOfRows() ; rowCounter++) {
questionDataTable.setProperty(rowCounter, 0, "style", "width:30px");
questionDataTable.setProperty(rowCounter, 1, "style", "width:100%");
}
var tableObject = new google.visualization.Table(document.getElementById(table_container_id));
tableObject.draw(questionDataTable, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
Issue: Checkbox state has not been changed before and after the click.
Referred: Previous answer reference
Finally, I developed a solution for this. Here it is.
First, draw the table using google visualization API then draw the checkbox using HTML dom.
function handleQuestionsSqlQueryResponse(dataQueryQuestionsResponse) {
if (dataQueryQuestionsResponse.isError()) {
alert('Error in query: ' + dataQueryQuestionsResponse.getMessage() + ' ' + dataQueryQuestionsResponse.getDetailedMessage());
return;
}
var dtQuestions = dataQueryQuestionsResponse.getDataTable();
var intNoOfRows = dtQuestions.getNumberOfRows();
for (intRowCounter = 0; intRowCounter < intNoOfRows ; intRowCounter++) {
var tblQuestions = new google.visualization.DataTable();
tblQuestions.addColumn('string', '');
tblQuestions.addColumn('string', '');
var arrQuestions = new Array();
var strQuestionSection = dtQuestions.getValue(intRowCounter, 0);
var strQuestionDetails = dtQuestions.getValue(intRowCounter, 1);
if (strQuestionSection !== null && strQuestionDetails !== null) {
arrQuestions = strQuestionDetails.split(";");
for (var intRowIterator = 0; intRowIterator < arrQuestions.length; intRowIterator++) {
var intCount = 0 * 1;
var tblQuestionsRow = new Array();
var strQuestionNo = arrQuestions[intRowIterator].split("|")[0];
var strQuestionName = arrQuestions[intRowIterator].split("|")[1];
tblQuestionsRow[intCount++] = strQuestionName;
if (strQuestionName === "Other / Unknown? Please Describe:") {
tblQuestionsRow[intCount++] = "<input type=\"text\"" + "size=\"30\" id=\"" + strQuestionNo + "Others" + "\"" + " value='' name='" + strQuestionNo + "' disabled />";
} else {
tblQuestionsRow[intCount++] = null;
}
tblQuestions.addRow(tblQuestionsRow);
}
var tableObject = new google.visualization.Table(document.getElementById(strQuestionSection));
tableObject.draw(tblQuestions, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
}
}
for (intRowCounter = 0; intRowCounter < intNoOfRows ; intRowCounter++) {
var intQuestionValue = 0;
var strQuestionSection = dtQuestions.getValue(intRowCounter, 0);
var strQuestionDetails = dtQuestions.getValue(intRowCounter, 1);
var tblContainer = document.getElementById(strQuestionSection);
var tblReference = tblContainer.getElementsByTagName('TBODY')[0];
arrQuestions = strQuestionDetails.split(";");
for (var intRowIterator = 0; intRowIterator < arrQuestions.length; intRowIterator++) {
var tblRow = tblReference.rows[intRowIterator];
var tblCheckBox = tblRow.insertCell(0);
var strQuestionNo = arrQuestions[intRowIterator].split("|")[0];
if (strQuestionNo !== null) {
tblCheckBox.innerHTML = "<input type=\"checkbox\"" + " id=\"" + strQuestionNo + "\" name=\"" + strQuestionNo + "\" value=\"" +
intQuestionValue + "\" onchange=\"doCheckOrUnCheck('" + strQuestionNo + "');\" />";
}
}
}
}

javascript regular expression to replace string

I have unspecified number of html inputs:
<input id="ageInput" />
<input id="nameInput" />
...
and having the following string which is built based on inputs:
s = "{ 'age': '{ageInput}', 'name': '{nameInput}'}"
how could I use regular expression to replace the above string to reflect the current inputs values like this:
s = "{ 'age': " + $('#ageInput').val() + ", 'name': " + $('#nameInput').val() + " }"
Answering your original question, use replace method of string , which accepts function as parameter:
s = s.replace(/\{([^{}]+)\}/g, function (match, g1) {
return $("#" + g1).val()
})
But I would rather use JSON.stringify:
var s = "{ 'age': '{ageInput}', 'name': '{nameInput}'}"
, controlMap = JSON.parse(s)
, data = {}
for(var i in controlMap) {
data[i] = $(controlMap[i]).val()
}
var str = JSON.stringify(data)