Set minimum days difference between jquery ui datepickers - jquery-ui-datepicker

I have two date pickers that I use to select a date range. Here is the code for them:
$("#ContentPlaceHolder1_MySearchBox_txtOutDate").datepicker({
changeMonth: true,
numberOfMonths: 1,
dateFormat: 'dd-M-yy',
onClose: function (selectedDate) {
$("#ContentPlaceHolder1_MySearchBox_txtInDate").datepicker("option", "minDate", selectedDate);
DoPostBack();
},
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 99999999999999);
}, 0);
}
}).val();
$("#ContentPlaceHolder1_MySearchBox_txtInDate").datepicker({
changeMonth: true,
numberOfMonths: 1,
dateFormat: 'dd-M-yy',
onClose: function (selectedDate) {
$("#ContentPlaceHolder1_MySearchBox_txtOutDate").datepicker("option", "maxDate", selectedDate);
DoPostBack();
},
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 99999999999999);
}, 0);
}
}).val();
The code works fine when it comes to not allowing the InDate from being lower than the OutDate. But I need to set the minimum value for InDate to be at least 3 days after the OutDate. I tried using New Date(selectedDate) to add 3 days but it didn't work because "selectedDate" is a string of dd-MMM-YYYY format and it won't convert to date.
What is the simplest method to achieve what I am after?
Thanks

OK. I found a solution using the following functions:
function parseDate(input) {
var parts = input.split('-');
return new Date(parts[2], MonthNameToNumber(parts[1]) - 1, parts[0]);
}
function MonthNameToNumber(MonthName) {
switch(MonthName) {
case "Jan":
return 1;
break;
case "Feb":
return 2;
break;
case "Mar":
return 3;
break;
case "Apr":
return 4;
break;
case "May":
return 5;
break;
case "Jun":
return 6;
break;
case "Jul":
return 7;
break;
case "Aug":
return 8;
break;
case "Sep":
return 9;
break;
case "Oct":
return 10;
break;
case "Nov":
return 11;
break;
case "Dec":
return 12;
break;
default:
return 1;
}
}
And then changing:
$("#ContentPlaceHolder1_MySearchBox_txtInDate").datepicker("option", "minDate", selectedDate);
to
var OutDate = parseDate(selectedDate);
OutDate.setDate(OutDate.getDate() + 3);
$("#<%=txtInDate.ClientID%>").datepicker("option", "minDate", OutDate);
and
$("#ContentPlaceHolder1_MySearchBox_txtOutDate").datepicker("option", "maxDate", selectedDate);
to
var InDate = parseDate(selectedDate);
InDate.setDate(InDate.getDate() - 3);
$("#<%=txtOutDate.ClientID%>").datepicker("option", "maxDate", InDate);

Related

Flutter/Dart/Firestore - Group documents by day in an AnimtedList

How can I group messages between users by day? So far it just adds to the list and sorts it by day but I can't seem to add a gap between the messages that were sent in past days. The list is being displayed in an AnimatedList()
Code :
List<Message> _messages = [];
...
_initMessages() { // Being called in the initState
APIs().chats.messages(
chatID: widget.chat.chatID,
onEmpty: () {
if (mounted)
setState(() {
this._isLoading = false;
});
},
onAdded: (m) {
if (mounted)
setState(() {
if (m.type == 'Image') {
m.message = NetworkImage(m.message);
}
this._messages.add(m);
this._messages.sort((a, b) => a.createdAt.compareTo(b.createdAt));
if (mounted) this._listKey.currentState.insertItem(this._messages.length, duration: Duration(milliseconds: 500));
this._isLoading = false;
});
},
onModified: (m) {
int i = this._messages.indexWhere((message) => message.messageID == m.messageID);
if (mounted)
setState(() {
this._messages[i] = m;
this._messages.sort((a, b) => a.createdAt.compareTo(b.createdAt));
this._isLoading = false;
});
},
onRemoved: (m) {
int i = this._messages.indexWhere((message) => message.messageID == m.messageID);
if (mounted)
setState(() {
this._messages.removeAt(i);
this._messages.sort((a, b) => a.createdAt.compareTo(b.createdAt));
this._isLoading = false;
});
},
onFailure: (e) {
print(e);
});
}
It shows the messages in order but when I changed it to an AnimatedList it gives me an error:
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: 'package:flutter/src/widgets/animated_list.dart': Failed assertion: line 279 pos 12: 'itemIndex >= 0 && itemIndex <= _itemsCount': is not true.
Kinda a two-part question, group the documents by day and try to get it to work in an AnimatedList. The date is of the Firestore Timestamp type.

AWS Cognito: Custom Challenge with Retry

I am using Custom Challenge for MFA because i wanted to use Twilio instead of AMAZON SNS. i have successfully implemented it. It works fine but
When a user enters wrong OTP code. The user session is expired. means that he has to again provide phone number and request a OTP again. Whereas i want it to retry for atleast 3 time. before he need to request another OTP.
My Response verify trigger is as simple as below, is there something that we can do.
(event, context, callback) => {
if (event.request.privateChallengeParameters.answer == event.request.challengeAnswer) {
event.response.answerCorrect = true;
} else {
event.response.answerCorrect = false;
}
callback(null, event);
}
I acheived this by adding the answer as a variable into challengeMetaData - which so far as I can see is not returned to the client but is available on subsequent calls, I also have a variable named attempts to track how many times the user has entered an incorrect value.My code is below - I hope it helps
const AWS = require("aws-sdk");
exports.handler = (event, context, callback) => {
const session = event.request.session;
const currentSession = session ? session.length - 1 : 0
switch (event.triggerSource) {
case 'DefineAuthChallenge_Authentication':
console.log("DefineAuthChallenge_Authentication");
console.log(event);
if (session.length === 0) {
event.response = {
challengeName: 'CUSTOM_CHALLENGE',
failAuthentication: false,
issueTokens: false
};
}
else {
if (session[currentSession].challengeName === 'CUSTOM_CHALLENGE') {
if (session[currentSession].challengeResult === true) {
event.response.issueTokens = true;
event.response.failAuthentication = false;
}
else {
let metaData = JSON.parse(session[currentSession].challengeMetadata);
if (metaData.attempts <= 3) {
event.response = {
challengeName: 'CUSTOM_CHALLENGE',
failAuthentication: false,
issueTokens: false
};
}
else {
event.response.issueTokens = false;
event.response.failAuthentication = true;
}
}
}
}
console.log(event);
break;
case 'CreateAuthChallenge_Authentication':
if (event.request.challengeName === 'CUSTOM_CHALLENGE') {
console.log("CreateAuthChallenge_Authentication");
console.log(event);
if (session.length === 0) {
let answer = Math.random().toString(10).substr(2, 6);
//Your logic to send a message goes here
event.response.publicChallengeParameters = { challengeType: 'SMS_CODE' };
event.response.privateChallengeParameters = { answer: answer };
event.response.challengeMetadata = JSON.stringify({ '_sid': answer, 'challengeType': 'SMS_CODE', attempts: 1 });
}
else {
let metaData = JSON.parse(session[currentSession].challengeMetadata);
if (metaData.attempts <= 3) {
event.response.publicChallengeParameters = { challengeType: 'SMS_CODE', errorCode: 'NotAuthorizedException' };
event.response.privateChallengeParameters = { answer: metaData._sid };
event.response.challengeMetadata = JSON.stringify({ '_sid': metaData._sid, 'challengeType': 'SMS_CODE', attempts: metaData.attempts + 1 });
}
}
}
console.log(event);
break;
default:
console.log("VerifyAuthChallenge_Authentication");
console.log(event);
if (event.request.privateChallengeParameters.answer === event.request.challengeAnswer) {
event.response.answerCorrect = true;
}
else { event.response.answerCorrect = false; }
console.log(event);
break;
}
callback(null, event);
};

Ember Cli - Added Polyfill Internet Explorer Error Object Expected

I have a problem and I don't see someone who has this kind of problem with this.
Basically I made a helper to format a date, it has some syntax of EcmaScript like let, or expoorts.
Its working in all the browsers except INTERNET EXPLORER, so I though ok its time to configure Polyfill, so I read the documentation to configure it with ember-cli-babel and I am not able to see the results as expected.
I have an ember app, with ember cli
DEBUG: -------------------------------
DEBUG: Ember : 2.14.1
DEBUG: jQuery : 2.2.4
DEBUG: -------------------------------
I include POLYFILL in my broccoli file like this
ember-cli
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
'ember-cli-babel': {
includePolyfill: true
},
storeConfigInMeta: false,
minifyJS: {
enabled: false
},
minifyCSS: {
enabled: false
},
vendorFiles: {
'jquery.js': {
development: 'bower_components/jquery/dist/jquery.js',
production: false,
development: false
}
}
});
app.import('vendor/jquery.lumanetix.all.min.js');
return app.toTree();
};
I have a ember helper to format a date here it is:
import Ember from 'ember';
export function dateAuctionFormat(date/*, hash*/) {
let dateObj = new Date(date);
let monthName = getMonthName(dateObj.getUTCMonth());
let dayNumber = dateObj.getUTCDate();
dayNumber = dayNumber + formatDateNotation(dayNumber);
let dayName = getWeekDayName(dateObj.getDay());
let time = dateObj.toLocaleString('en-US', { hour: 'numeric', minute:'numeric', hour12: true });
return dayName + ' ' + dayNumber + ' ' + monthName + ' ' + time;
}
function getMonthName(date) {
let month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "Aug";
month[8] = "Sept";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
return month[date];
}
function getWeekDayName(date) {
let weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
return weekday[date];
}
function formatDateNotation(d) {
if (d > 3 && d < 21) {
return 'th';
}
switch (d % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
export default Ember.Helper.helper(dateAuctionFormat);
But when Internet Explorer 11 is rendering the site, I have an error in the debugger like this:
The error said Object Expected.
and you can see the error showing just after the line
export default App.extend({
// rootElement: '#listings-search'
});
So I don't know from where start, I try to modify a little bit, app.js, but no luck, also I tried to convert my ES6 code to ES5 with this converter:
https://babeljs.io/repl/
But of course it didn't work and also its not the idea.
I believe you need to add target to your targets config. You can use this list:
https://github.com/ai/browserslist#queries
This targets file is later used by Babel to determine which features are supported by browsers and this later affects transpiled JavaScript.

Objects from registerhelper in Handlebars.js / Browserify bundle not printing in Django app on some servers

I have a Django site that I'm deploying where I'm using Handlebars.js for templateing. I'm using Browserify to bundle the Javascript. I'm using registerhelper in Handlebars.js to iterate over some objects and print them in modals on click. A sample of this code is below.
I have my Django app deployed on a live dev server (Digital Ocean) and these text boxes are being populated without problem. When I pushed to the production server (university server) these text boxes are not getting populated. Otherwise the Django app is working fine on both live dev and production servers. There are no errors in the console.
The servers are similar but not totally the same. Both are running Ubuntu and Python 2.7 and have the same pip dependancies. We are using the same bundle.js from Browserify on both servers.
I don't know if this is a code problem or a dependency problem and it's driving me nuts because the deployment completely works on the live dev server. Any advice would be welcome.
Below is an example of my Handlebars code:
{{#countryListTitle attributes.works 'Projects'}}
<div class="row">
<div class="col-sm-12"><h3>Projects</h3></div>
{{#each attributes.works}}
{{#countryListContent attributes ../attributes.full_name 'Projects'}}
{{/countryListContent}}
{{/each}}
</div>
{{else}}
{{/countryListTitle}}
Below is an example of my related Javascript code:
registerHBHelpers: function(){
Handlebars.registerHelper('countryListTitle', function(works, needle, options) {
var yes = 0;
$.each(works, function(key, value) {
if (value.attributes.work_types[0].attributes.name == needle) {
yes = 1;
}
});
if(yes == 1) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Handlebars.registerHelper('countryListContent', function(attributes, full_name, type, options) {
var output = '';
var periodicals = '';
var publishers = '';
for(var i=0, l=attributes.work_types.length; i<l; i++) {
// add item name if the type is the type passed to the helper
if (attributes.work_types[i].attributes.name == type) {
output = output + '<div class="col-sm-12"><h4>' + attributes.title + '</h4></div>';
// add publication info if a publication
if (attributes.publicationinfo) {
var d = new Date(attributes.publicationinfo.date_published);
var month = d.getMonth() + 1; //Months are zero based
var year = d.getFullYear();
switch (month)
{
case 1:
month = 'January';
break;
case 2:
month = 'February';
break;
case 3:
month = 'March';
break;
case 4:
month = 'April';
break;
case 5:
month = 'May';
break;
case 6:
month = 'June';
break;
case 7:
month = 'July';
break;
case 8:
month = 'August';
break;
case 9:
month = 'September';
break;
case 10:
month = 'October';
break;
case 11:
month = 'November';
break;
case 12:
month = 'December';
break;
default:
month = '';
break;
}
if (attributes.publicationinfo.periodicals.length > 0) {
periodicals = attributes.publicationinfo.periodicals[0].trim() + ', ';
}
if (attributes.publicationinfo.publishers.length > 0) {
publishers = attributes.publicationinfo.publishers[0].trim() + ', ';
}
output = output + '<div class="col-sm-12"><p class="modal-fine-print">' + periodicals + publishers + 'Published ' + month + ' ' + year + '</p></div>';
// add buffer of no unordered lists will appear
if (attributes.topics.length === 0 && attributes.faculty.length === 0) {
output = output + '<div class="buffer"></div>';
}
}
if (attributes.faculty.length > 0) {
output = output + '<div class="col-sm-12"><p class="modal-list-first-element"><strong>Faculty</strong></p><p>';
for(var e=0, p=attributes.faculty.length; e<p; e++) {
if (attributes.faculty[e].attributes.home_page !== '') {
output = output + '' + attributes.faculty[e].attributes.full_name + '<br />';
} else {
output = output + '' + attributes.faculty[e].attributes.full_name + '<br />';
}
}
output = output + '</p></div>';
}
if (attributes.topics.length > 0) {
output = output + '<div class="col-sm-12"><p class="modal-list-first-element"><strong>Topics</strong></p><p>';
for(var h=0, m=attributes.topics.length; h<m; h++) {
output = output + attributes.topics[h].attributes.name + '<br />';
}
output = output + '</p></div>';
}
output = output + '<div class="buffer"></div>';
}
}
return new Handlebars.SafeString(output);
});
},
Lee
Figured this out - there was a change in an object name in the database. It was hard to debug, but simple problem in the end.

jQuery DatePicker calendar not returning correct month

I am soooo close here. I'm hoping a guru can help me with this last piece. I'm populating a jQuery DatePicker calendar with XML from an RSS feed. Upon clicking a highlighted date where there's an event, I'm creating a URL with a query string so I can display all the event for the clicked day. Everything is working... until I change the month by clicking previous or next month. My script will return the correct day, but is only returning the current month. For example, I navigate to May and click the 5th, my URL will be events.htm?month=june&day=5. Any ideas on why it will not return my selected month? Here's my code:
var data = $.ajax({
url: "news.xml",
type: "GET",
dataType: "xml",
async:false,
success: function(xml){
return xml;
}
} ).responseText;
$(document).ready(function() {
var events = getSelectedDates();
$("div.datepicker").datepicker({
beforeShowDay: function(date) {
var result = [true, '', null];
var matching = $.grep(events, function(event) {
return event.published.getDate() === date.getDate() && event.published.getMonth() === date.getMonth() && event.published.getFullYear() === date.getFullYear();
});
if (matching.length) {
result = [true, 'highlight', null];
}
return result;
},
onSelect: function(dateText) {
var date, selectedDate = new Date(dateText),
i = 0,
event = null;
while (i < events.length && !event) {
date = events[i].published;
if (selectedDate.getFullYear() === date.getFullYear() &&
selectedDate.getMonth() === date.getMonth() &&
selectedDate.getDate() === date.getDate()) {
event = events[i];
}
i++;
}
if (event) {
var eMonNum = event.published.getMonth();
var d = new Date();
var eMonNum = new Array();
eMonNum[0] = "january";
eMonNum[1] = "february";
eMonNum[2] = "march";
eMonNum[3] = "april";
eMonNum[4] = "may";
eMonNum[5] = "june";
eMonNum[6] = "july";
eMonNum[7] = "august";
eMonNum[8] = "september";
eMonNum[9] = "october";
eMonNum[10] = "november";
eMonNum[11] = "december";
var eMon = eMonNum[d.getMonth()];
var eDay = event.published.getDate();
window.location = "events.htm?month="+eMon+"&day="+eDay;
}
}
});
});
function getSelectedDates() {
return $(data).find('entry').map(function() {
return {
title: $('title', this).text(),
published: new Date($('published', this).text())
};
}).get();
}
Found the problem, when you copied this list from a resource, you forgot to replace the variables.
CHANGE (at the end of month list)
var eMon = eMonNum[d.getMonth()];
TO:
var eMon = eMonNum[event.published.getMonth()];
All I did was get rid of the bad variable and reassigned your month variable to the one you used for the day. You can also remove the declaration of the d variable, as you will not need it.
Best of luck!