Multiple API calls simultaneously in marionetteJS - api

I use forcast api to get weather data. In marionette I use model to define API rulRoot as
var weatherApi = Backbone.Model.extend({
defaults:{
lat:"",
lng:"",
timeStamp:"",
units:"",
response:""
},
urlRoot: function(){
return '/api/web/forecast?lat='+ this.get("lat") + '&long=' + this.get("lng") +'&time=' + this.get("timeStamp") + '&units='+this.get("units");
}
});
Then I instantiate as
weatherApiGddObj = new weatherApiInstance();
I used this object to fetch api call response. Now want I want is to make multiple api call simultaneously like from today to next 30 days, So If I do one after another then It'll take lot of time to get all response. How do I do this with marionette?

It would be good to have a method that allows you to grab data for the range of days in one request. But according to your conditions I'd do it like this:
var date, startDate = someTimestamp, day = 86400,
endDate = startDate + day * 30, promises=[];
for(date = startDate; date < endDate; date += day){
weatherApiGddObj.set('timestamp', date);
promises.push(weatherApiGddObj.fetch());
}
$.when.apply($,promises).done(function(){
var data = Array.slice.call(arguments);
console.log(data);
});
I suggest you to read about Deferred Object

Related

Kotlin: How to detect 'date change'?

I will use Timer() to execute function by 5 minutes in Kotlin.
And when I execute function by 5m, if a day passed,I want count var to be 0.
So my idea was
declare two vars
var todayDate = LocalDate.now() // 2019-09-23
var todayCount:Int = 0
After that I will check this vars in 5 minutes by using Timer()
Then todayDate value differs from previous todayDate, then I can detect date change.
However, I don't know how to compare current todayDate and previous todayDate.
Any idea? or is there any other way to know day change?
For your specific question about comparing dates you can use the isEqual() method on your LocalDate instance (docs). Something like the following would likely do what you want:
// initial state
var todayDate = LocalDate.now()
var todayCount = 0
// in each timer iteration:
val now = LocalDate.now()
if (!todayDate.isEqual(now)) {
// it's a new day
todayCount = 0
todayDate = now
} else {
// it's the same day
++todayCount
}
However if you're talking about Android and using its Timer class, you need to be aware that that runs on a background thread and you will need to persist your todayDate and todayCount values somewhere (which could be app preferences, your app DB, etc.).

JS - How to implement the YTD (Year To Date) logic in order to do Date selection

I am trying to implement a method for a Date selection in vue-chartjs. Here is the function that i have used in the methods life cycle hook:
DateSelect(event) {
const period = event.target.value
let minValue = new Date(Math.max(...this.date) * 1000)
const axisXMin = new Date(Math.min(...this.date) * 1000)
switch (period) {
case '1m':
minValue.setMonth(minValue.getMonth() - 1)
break
case '3m':
minValue.setMonth(minValue.getMonth() - 3)
break
case 'ytd':
minValue.setFullYear(minValue.getFullYear() - minValue.getMonth()) //Here I want to implement the YTD Logic.
break
default:
minValue = axisXMin
}
const data = this.data.filter(el => {
return el.x >= minValue
})
this.GraphOutput(data) // this is vue-chartjs function.
}
Here the logic '1m' and '3m' works absolutely fine, as they display the previous 1month's and 3month's chart to the user when the respective button is clicked.
I want to know how to implement the YTD (Year to Date) Logic in the function that i have used above. Please do help me.
As far I understand you may need a full year of data in the graph. So that you need to set the minimum value as below:
case 'ytd':
minValue.setYear(minValue.getFullYear() - 1);
break

Best way to get current web visitor timezone in asp.net core Razor Pages [duplicate]

I am building an application in MVC3 and when a user comes into my site I want to know that user's timezone. I want to know how to do this in c# not in javaScript?
As has been mentioned, you need your client to tell your ASP.Net server details about which timezone they're in.
Here's an example.
I have an Angular controller, which loads a list of records from my SQL Server database in JSON format. The problem is, the DateTime values in these records are in the UTC timezone, and I want to show the user the date/times in their local timezone.
I determine the user's timezone (in minutes) using the JavaScript "getTimezoneOffset()" function, then append this value to the URL of the JSON service I'm trying to call:
$scope.loadSomeDatabaseRecords = function () {
var d = new Date()
var timezoneOffset = d.getTimezoneOffset();
return $http({
url: '/JSON/LoadSomeJSONRecords.aspx?timezoneOffset=' + timezoneOffset,
method: 'GET',
async: true,
cache: false,
headers: { 'Accept': 'application/json', 'Pragma': 'no-cache' }
}).success(function (data) {
$scope.listScheduleLog = data.Results;
});
}
In my ASP.Net code, I extract the timezoneOffset parameter...
int timezoneOffset = 0;
string timezoneStr = Request["timezoneOffset"];
if (!string.IsNullOrEmpty(timezoneStr))
int.TryParse(timezoneStr, out timezoneOffset);
LoadDatabaseRecords(timezoneOffset);
... and pass it to my function which loads the records from the database.
It's a bit messy as I want to call my C# FromUTCData function on each record from the database, but LINQ to SQL can't combine raw SQL with C# functions.
The solution is to read in the records first, then iterate through them, applying the timezone offset to the DateTime fields in each record.
public var LoadDatabaseRecords(int timezoneOffset)
{
MyDatabaseDataContext dc = new MyDatabaseDataContext();
List<MyDatabaseRecords> ListOfRecords = dc.MyDatabaseRecords.ToList();
var results = (from OneRecord in ListOfRecords
select new
{
ID = OneRecord.Log_ID,
Message = OneRecord.Log_Message,
StartTime = FromUTCData(OneRecord.Log_Start_Time, timezoneOffset),
EndTime = FromUTCData(OneRecord.Log_End_Time, timezoneOffset)
}).ToList();
return results;
}
public static DateTime? FromUTCData(DateTime? dt, int timezoneOffset)
{
// Convert a DateTime (which might be null) from UTC timezone
// into the user's timezone.
if (dt == null)
return null;
DateTime newDate = dt.Value - new TimeSpan(timezoneOffset / 60, timezoneOffset % 60, 0);
return newDate;
}
It works nicely though, and this code is really useful when writing a web service to display date/times to users in different parts of the world.
Right now, I'm writing this article at 11am Zurich time, but if you were reading it in Los Angeles, you'd see that I edited it at 2am (your local time). Using code like this, you can get your webpages to show date times that make sense to international users of your website.
Phew.
Hope this helps.
This isn't possible server side unless you assume it via the users ip address or get the user to set it in some form of a profile. You could get the clients time via javascript.
See here for the javacript solution: Getting the client's timezone in JavaScript
You will need to use both client-side and server-side technologies.
On the client side:
(pick one)
This works in most modern browsers:
Intl.DateTimeFormat().resolvedOptions().timeZone
There is also jsTimeZoneDetect's jstz.determine(), or Moment-Timezone's moment.tz.guess() function for older browsers, thought these libraries are generally only used in older applications.
The result from either will be an IANA time zone identifier, such as America/New_York. Send that result to the server by any means you like.
On the server side:
(pick one)
Using TimeZoneInfo (on. NET 6+ on any OS, or older on non-Windows systems only):
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
Using TimeZoneConverter (on any OS):
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("America/New_York");
Using NodaTime (on any OS):
DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/New_York"];
I got the same issue , Unfortunately there is no way for the server to know the client timezone .
If you want you can send client timezone as header while making ajax call .
In-case if you want more info on adding the header this post may help how to add header to request : How can I add a custom HTTP header to ajax request with js or jQuery?
new Date().getTimezoneOffset();//gets the timezone offset
If you don't want to add header every time , you can think of setting a cookie since cookie is sent with all httpRequest you can process the cookie to get client timezone on server side . But i don't prefer adding cookies , for the same reason they sent with all http requests.
Thanks.
For Dot Net version 3.5 and higher you can use :
TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
but for Dot Net lower than version 3.5 you can handle it manually via this way :
first, get Offset from the client and store it in the cookie
function setTimezoneCookie(){
var timezone_cookie = "timezoneoffset";
// if the timezone cookie does not exist create one.
if (!$.cookie(timezone_cookie)) {
// check if the browser supports cookie
var test_cookie = 'test cookie';
$.cookie(test_cookie, true);
// browser supports cookie
if ($.cookie(test_cookie)) {
// delete the test cookie
$.cookie(test_cookie, null);
// create a new cookie
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
// re-load the page
location.reload();
}
}
// if the current timezone and the one stored in cookie are different
// then store the new timezone in the cookie and refresh the page.
else {
var storedOffset = parseInt($.cookie(timezone_cookie));
var currentOffset = new Date().getTimezoneOffset();
// user may have changed the timezone
if (storedOffset !== currentOffset) {
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
location.reload();
}
}
}
after that you can use a cookie in backend code like that :
public static string ToClientTime(this DateTime dt)
{
// read the value from session
var timeOffSet = HttpContext.Current.Session["timezoneoffset"];
if (timeOffSet != null)
{
var offset = int.Parse(timeOffSet.ToString());
dt = dt.AddMinutes(-1 * offset);
return dt.ToString();
}
// if there is no offset in session return the datetime in server timezone
return dt.ToLocalTime().ToString();
}
I know the user asked about a non-javascript solution, but I wanted to post a javascript solution that I came up with. I found some js libraries (jsTimezoneDetect, momentjs), but their output was an IANA code, which didn't seem to help me with getting a TimeZoneInfo object in C#. I borrowed ideas from jsTimezoneDetect. In javascript, I get the BaseUtcOffset and the first day of DST and send to server. The server then converts this to a TimeZoneInfo object.
Right now I don't care if the client Time Zone is chosen as "Pacific Time (US)" or "Baja California" for example, as either will create the correct time conversions (I think). If I find multiple matches, I currently just pick the first found TimeZoneInfo match.
I can then convert my UTC dates from the database to local time:
DateTime clientDate = TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZoneInfo);
Javascript
// Time zone. Sets two form values:
// tzBaseUtcOffset: minutes from UTC (non-DST)
// tzDstDayOffset: number of days from 1/1/2016 until first day of DST ; 0 = no DST
var form = document.forms[0];
var janOffset = -new Date(2016, 0, 1).getTimezoneOffset(); // Jan
var julOffset = -new Date(2016, 6, 1).getTimezoneOffset(); // Jul
var baseUtcOffset = Math.min(janOffset, julOffset); // non DST offset (winter offset)
form.elements["tzBaseUtcOffset"].value = baseUtcOffset;
// Find first day of DST (from 1/1/2016)
var dstDayOffset = 0;
if (janOffset != julOffset) {
var startDay = janOffset > baseUtcOffset ? 180 : 0; // if southern hemisphere, start 180 days into year
for (var day = startDay; day < 365; day++) if (-new Date(2016, 0, day + 1, 12).getTimezoneOffset() > baseUtcOffset) { dstDayOffset = day; break; } // noon
}
form.elements["tzDstDayOffset"].value = dstDayOffset;
C#
private TimeZoneInfo GetTimeZoneInfo(int baseUtcOffset, int dstDayOffset) {
// Converts client/browser data to TimeZoneInfo
// baseUtcOffset: minutes from UTC (non-DST)
// dstDayOffset: number of days from 1/1/2016 until first day of DST ; 0 = no DST
// Returns first zone info that matches input, or server zone if none found
List<TimeZoneInfo> zoneInfoArray = new List<TimeZoneInfo>(); // hold multiple matches
TimeSpan timeSpan = new TimeSpan(baseUtcOffset / 60, baseUtcOffset % 60, 0);
bool supportsDst = dstDayOffset != 0;
foreach (TimeZoneInfo zoneInfo in TimeZoneInfo.GetSystemTimeZones()) {
if (zoneInfo.BaseUtcOffset.Equals(timeSpan) && zoneInfo.SupportsDaylightSavingTime == supportsDst) {
if (!supportsDst) zoneInfoArray.Add(zoneInfo);
else {
// Has DST. Find first day of DST and test for match with sent value. Day = day offset into year
int foundDay = 0;
DateTime janDate = new DateTime(2016, 1, 1, 12, 0, 0); // noon
int startDay = zoneInfo.IsDaylightSavingTime(janDate) ? 180 : 0; // if southern hemsphere, start 180 days into year
for (int day = startDay; day < 365; day++) if (zoneInfo.IsDaylightSavingTime(janDate.AddDays(day))) { foundDay = day; break; }
if (foundDay == dstDayOffset) zoneInfoArray.Add(zoneInfo);
}
}
}
if (zoneInfoArray.Count == 0) return TimeZoneInfo.Local;
else return zoneInfoArray[0];
}
You can get this information from client to server (any web API call)
var timezoneOffset = new Date().getTimezoneOffset();
With the help of timezoneoffset details you can achieve the same. Here in my case i converted UTC DateTime to my client local datetime in Server side.
DateTime clientDateTime = DateTime.UtcNow - new TimeSpan(timezoneOffset / 60, timezoneOffset % 60, 0);
Click for code example
Take a look at this asp.net c# solution
TimeZoneInfo mytzone = TimeZoneInfo.Local;
System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_TIMEZONE"] ;

Siebel Business(E-script) Service Calculate Expiry Date

I have a requirement to create a business service function to calculate expiry date , 2 weeks from a date field in Siebel.
I have written the code in Java which is
public static Date checkexpiry(Date Datefield)
{
Calendar cal = Calendar.getInstance();
cal.setTime(Datefield);
cal.add(Calendar.DATE, -14);
Date twoWeeksToExpiry = cal.getTime();
System.out.println(twoWeeksToExpiry);
return twoWeeksToExpiry;
}
if current date is equal to twoWeeksToExpiry {do .....}
So how can I re-write this code on Siebel using a business service particularly E-script.
The whole idea is have an output Yes is its 2 weeks before a date field in Siebel.
This will later be used in a work flow.
OK so have started Migrating my Java coding skills to Siebel E-Script I came up with this.
function ExpiryNotification(Inputs,Outputs)
{
try
{
var expiryDate = Inputs.GetProperty("DateField");
var eDate= new Date(expiryDate);
var notificationdate = eDate-14;
var currentdate = Today();
if (currentdate==notificationdate){
Outputs.SetProperty("Notification", "Y")
}
else {
Outputs.SetProperty("Notification", "N")
}
catch(e)
{
TheApplication().RaiseErrorText(e.toString());
}
}
However I did not use the Business Service ..I used a calculated field on my Business Component.
The calculated Fields
1 twoWeeksToExpiry = Datefield-14
Notification = IIf (Today()==[twoWeeksToExpiry], "Y", "N")
So this solved the problem without scripting,
Will appreciate any suggestions on my scripting thou I didn't use it.

How can I use the Twitter Search API to return all tweets that match my search query, posted only within the last five seconds?

I would like to use the API to return all tweets that match my search query, but only tweets posted within the last five seconds.
With Twitter's Search API, I can use the since_id to grab all tweets from a specific ID. However, I can't really see a good way to find the tweet ID to begin from.
I'm also aware that you can use "since:" in the actual query to use a date, but you cannot enter a time.
Can someone with Twitter API experience offer me any advice? Thanks for reading and your time!
http://apiwiki.twitter.com/Search-API-Documentation
This sounds like something you can do on your end, as created_at is one of the fields returned in the result set. Just do your query, and only use the ones that are within the last 5 seconds.
<script type="text/javascript" charset="utf-8">
// JavaScript Document
$(document).ready(function(){
// start twitter API
$.getJSON('http://twitter.com/status/user_timeline/YOUR_NAME.json?count=10&callback=?', function(data){
$.each(data, function(index, item){
$('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '</p><p><strong>' + relative_time(item.created_at) + '</strong></p></div>');
});
});
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
}
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};// end twitter API
}); // ***** end functions *****
</script>
<div id="twitter">
Target Div
</div>
Are you trying to poll tweets in real time? Doesn't twitter have a limit on API req/hour. I think you'd hit that pretty fast.
Why don't you just make a call to the API every 5 seconds and grab the top 1 tweet.
Twitter API results are sorted by recent by default. Please see the following quote from twitter wiki :
Parameter to Twitter search API :
result_type: Optional. Specifies what type of search results you would prefer to receive.
* Valid values include:
o mixed: In a future release this will become the default value. Include both popular and real time results in the response.
o recent: The current default value. Return only the most recent results in the response.
o popular: Return only the most popular results in the response.
* Example: http://search.twitter.com/search.atom?q=Twitter&result_type=mixed
* Example: http://search.twitter.com/search.json?q=twitterapi&result_type=popular
* Example: http://search.twitter.com/search.atom?q=justin+bieber&result_type=recent
Please correct me if I am wrong anywhere.
Thanks and Regards,
Abhay Dandekar