CakeTime relative time instead of absolute time - cakephp-2.0

How I can get relative time instead of absolute time by using CakeTime:timeAgoInWords ?
for example:
about one week ago
instead of
1 week, 2 days ago

Create you own method to handle that based on what you want. And you can implement a function int_to_words() like this
Something like:
function relativeTime($time){
$arrray = explode(" ",$time); // transform time in array of words
if(array[1] == "week,"){
if(array[2]) > 5){
return "Almost two weeks ago";
}
return "About one week ago";
}else if(array[1] == "weeks"){
$aux = array[0];
$number = int_to_words($aux);
return "About $number week ago";
}
// Read more about the possible CakeTime:timeAgoInWords results
// and continue to implement the other possibilities here...
}

Related

laravel Maximum execution time of 60 seconds exceeded --

hello guys so I am doing a laravel project ( new to laravel ).
i am supposed to to calculation from other tables and save the results in another OUTPUT table.
I have 8 calculation in total in each line and up to 3k lines to fill.
The problem that I get the ma execution time error 60 sec even if a change it in laravel and php.ini.
each function called is just calling a select where and sum I've decided to divide them for better org.
My question is is there a better way to process the data and minimize to exc time if you can help .
public function calcul($week)
{ $test = Output::where('week',$week)->Limit(1);
if($test->first()){
return self::afficher($week);
}
else{
DB::table('article')->orderBy('material')->chunk(100, function ($stocks){
foreach ($stocks as $stock) {
$id = $stock->material;
$safe_stock=self::safe_stock($id);
$past_need=self::PassedNeeds($id) - self::NeedsInTwoWeeks($id);
$two_week_need=self::NeedsInTwoWeeks($id);
$stock_=self::stock($id);
$bdl=self::bdl($id);
$sm=self::sm($id);
$package=self::package($id);
$store_1=self::store_1($id);
$store_2=self::store_2($id);
$store_3=self::store_3($id);
Output::create([
'material' => $id,'safe_stock'=>$safe_stock,'past_need'=>$past_need,'two_week_need'=>$two_week_need,
'stock'=>$stock_,'bdl'=>$bdl,'sm'=>$sm,'package'=>$package,
'store_1'=>$store_1,'store_2'=>$store_2,'store_3'=>$store_3
]);
}
});
return self::index();
}
}

Google Earth Engine - counts days of the longest dry period in a time period

I'm trying to map the max number of consecutive days with rain <1 mm in Google Earth Engine.
This is the link to the code
https://code.earthengine.google.com/22b5c20d2700a2ffb5989f892838ac58
First I reclassify the collection with 0 if rain <=1 and 1 if >1.
Then I run the code that should count the days of the longest dry period, but it is able to do so only if the dry period reach the end of the time period.
For instance if I am looking for the longest dry period in 4 days timestep i get the following series:
rain days 1 2 3 4 output
0,0,1,1 = 0 dry days
0,1,0,0 = 2 dry days
0 = rain<=1 and
1 = rain>1 (as per the first step)
Does anyone can help in solving this?
Thanks
I don't think you were far off in your code that you provided. To keep track of the dry spells you have to use .iterate(). I took a stab at your application in a little different way where instead of classifying the data before the iteration, I calculate which pixels are dry each day and carry over the accumulated days that a pixel is dry, otherwise it is set to zero:
// DATA
var collection = ee.ImageCollection("UCSB-CHG/CHIRPS/DAILY");
// Define time range
var startyear = 2000;
var endyear = 2017;
var startmonth = 1;
var endmonth = 12;
// Set date in ee date format
var startdate = ee.Date.fromYMD(startyear,startmonth,1);
var enddate = ee.Date.fromYMD(endyear,endmonth,31);
// Filter data
var datain_t = collection.filterDate(startdate, enddate)
.filter(ee.Filter.calendarRange(startmonth,endmonth, 'month'))
.select("precipitation").map(function(img){
return img.addBands(ee.Image.constant(0).uint8().rename('counter'));
})
.sort('system:time_start');
// // START
var dataset = datain_t
.filterDate("2016-08-01","2016-08-30")
.sort('system:time_start:');
print(dataset,"dataset");
var precipThresh = 1; // mm
function drySpells(img, list){
// get previous image
var prev = ee.Image(ee.List(list).get(-1));
// find areas gt precipitation threshold (gt==0, lt==1)
var dry = img.select('precipitation').lt(precipThresh);
// add previous day counter to today's counter
var accum = prev.select('counter').add(dry).rename('counter');
// create a result image for iteration
// precip < thresh will equal the accumulation of counters
// otherwise it will equal zero
var out = img.select('precipitation').addBands(
img.select('counter').where(dry.eq(1),accum)
).uint8();
return ee.List(list).add(out);
}
// create first image for iteration
var first = ee.List([ee.Image(dataset.first())]);
// apply dry speall iteration function
var maxDrySpell = ee.ImageCollection.fromImages(
dataset.iterate(drySpells,first)
).max(); // get the max value
// display results
Map.addLayer(maxDrySpell.select('counter'),{min:0,max:30,palette:'#9ecae1,#ffffff,#ffeda0,#feb24c,#f03b20'},'Max Dry Spells');
Here is the link to the code: https://code.earthengine.google.com/80b4c0f7e82a5f0da316af1d2a55dd59
Don't try to run this analysis for too long of a time period or Earth Engine will give an error. I hope this helps!

Incorrect day format returned from momentJS countdown

I used this simple script from: https://github.com/icambron/moment-countdown to make a simple countdown. The code below i'm using.
Used Code:
$interval(function(){
$scope.nextDate = moment().countdown($scope.nextDateGet,
countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS
);
$scope.daysCountdown = moment($scope.nextDate).format('dd');
$scope.hoursCountdown = moment($scope.nextDate).format('hh');
$scope.minutesCountdown = moment($scope.nextDate).format('mm');
$scope.secondsCountdown = moment($scope.nextDate).format('ss');
},1000,0);
This gives correct output
$scope.nextDate.toString();
But this contains one string with the remaining days,hours,minutes and seconds. So i decided i want to split this string into 4 strings by using this:
$scope.daysCountdown = moment($scope.nextDate).format('dd');
$scope.hoursCountdown = moment($scope.nextDate).format('hh');
$scope.minutesCountdown = moment($scope.nextDate).format('mm');
$scope.secondsCountdown = moment($scope.nextDate).format('ss');
Example for input
2016-10-15 10:00:00 // $scope.nextDateGet
Desired output is something like this:
0 // (days)
12 // (hours)
24 // (minutes)
30 // (seconds)
But i can't seem to format the remainings days, i get this output:
Fr // Shortcode for the day the item is scheduled => I need the remaining days in this case that would be 0. The other formatting is correct.
The following output was correct if remaining days was not 0:
$scope.daysCountdown = moment($scope.nextDate).format('D');
If remaining days was 0 it would set remaining days on 14 so this work around did the trick:
if(moment($scope.nextDate).isSame(moment(), 'day')){
$scope.daysCountdown = 0;
} else {
$scope.daysCountdown = moment($scope.nextDate).format('D');
}
Any suggestions to improve this code are always welcome.

angular filter on click by 'last week' data

Hi I am new in angular and making my first module. This article is very helpfull. I want to filter my data by lastweek records. I have already found days by current date and given date in mysql query, On button click I am just setting value like DisTopic=1 and this works fine.
May you please tell me how can I apply filter for a range like day>=1 && day<=7
I am using below:-
filter:{'topic': DisTopic,'attachment':attch, 'days':day}
Please help me.
Solution 1: with angular-filter module
As stated by other users, you could indeed do that with a custom filter. However, if you find yourself writing a lot of custom filters, I'll advise you have a look at angular-filter module. With this module you can do what you need with the pick filter :
<div ng-repeat="task in tasks | pick: 'days >= 1 && days <= 7'">{{task.name}}</div>
See demo fiddle
Solution 2: Custom filter with parameters
Template:
<div ng-repeat="task in tasks | dayFilter: 1 : 7">{{task.name}}</div>
Javascript:
app.filter('dayFilter', function() {
return function(input, startDay, endDay) {
var filterFunction = function (item) {
return item.days >= startDay && item.days <= endDay;
};
return input.filter(filterFunction);
};
});
See updated demo fiddle
Custom filter example, you can modify as per your need.
Controller
$scope.search = function (item) {
if ($scope.searchUser == null || $scope.searchUser.trim() == "")
return true;
if (item.FirstName.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1 || item.LastName.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1 || item.Role.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1) {
return true;
}
return false;
};
and than call it in your view
| filter:search
So, depending on your requirement, you can pass as many parameters and modify method in controller.
//Below code solve my problem.
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return Math.ceil((firstThursday - target) / 604800000) - 1; // 604800000 = 7 * 24 * 3600 * 1000
};

"Week of the year" Algorithm needs improvements

I have an algorithm which scans through data read from a .csv file(approx 3700 lines) and assess's which trading week of the year each entry is in by running a count++ for every Sunday of that year and assigning the count value as the trading week when the date falls within that week.
It's working but performance is lagging. It is the 3rd function running using Task.Factory.StartNew (I have also tried parallel.Invoke).
Results of timing tests.
before: 00:00:05.58
after: 00:00:23.27
UPDATE
Added break after each trading week is set. Time improved but still slow.
new time: 00:00:15.74
For our purposes the 1st week of the year is week 1(not 0) and is defined as from the first day of the year until the Sunday. If the first day of the year is a Sunday the length of week 1 is 1 day.
private void SetDefiniteWeeks()
{
string FileLoc = FilePath + Market + ".csv";
string[] Data = File.ReadAllLines(FileLoc);
var FileData = from D in Data
let DataSplit = D.Split(',')
select new
{
Date = DateTime.Parse(DataSplit[0]),
ClosingPrice = double.Parse(DataSplit[4])
};
//assign each date to it's relevant week
TradingWeek TW;
List<TradingWeek> tradingWeek = new List<TradingWeek>();
foreach (var pe in FileData)
{
// DateTime dt = pe.Date;
int Year = pe.Date.Year;
string End_of_Week = "Sunday";
int WeekCount = 0;
DateTime LoopDate_Begin = new DateTime(Year,1,1);
DateTime LoopDate_End = new DateTime(Year,12,31);
do
{
if (LoopDate_Begin.DayOfWeek.ToString() == End_of_Week)
{
WeekCount++;
if (LoopDate_Begin.DayOfYear > pe.Date.DayOfYear && LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7))
{
TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
break;
}
}
LoopDate_Begin = LoopDate_Begin.AddDays(1);
} while (LoopDate_Begin.Date.ToString() != LoopDate_End.Date.ToString());
}
}
Please help.
UPDATE
NEW TIME
00:00:06.686
A vast improvement. Thanks all for your help.
Revised code:
CalendarWeekRule cw = CalendarWeekRule.FirstDay;
var calendar = CultureInfo.CurrentCulture.Calendar;
var trad_Week = (from pe in FileData
select new TradingWeek
{
Date = pe.Date,
Week = (calendar.GetWeekOfYear(pe.Date, cw,DayOfWeek.Sunday))
}).ToList();
Im not sure if this is what you want but after reading the comments I got the feeling that this might work (?)
var calendar = CultureInfo.CurrentCulture.Calendar;
var tradingWeek = (from pe in FileData
select new TradingWeek
{
Date = pe.Date,
Week = calendar.GetWeekOfYear(pe.Date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
}).ToList();
Edit: Changed to CalendarWeekRule.FirstDay since it's (more?) what OP is looking for.
Three quick thoughts:
Why are you only adding one day each time and checking to see if it's Sunday. Surely once you have found your first Sunday you can add seven days to find the next one?
If you order your pes by DateTime before you start then you don't need to restart at the beginning of the year for each one, you can pick up where you left off.
As Nicolas says, break after adding the trading week. No need to go through the rest of the year after you already know what the answer is.
I guess you'll end up with something like this (may or may not actually work, but should be close enough)
TradingWeek TW;
List<TradingWeek> tradingWeek = new List<TradingWeek>();
string End_of_Week = "Sunday";
var orderedData = FileData.OrderBy(x => x.Date)
DateTime LoopDate_Begin = new DateTime(orderedData[0].Date.Year,1,1);
int WeekCount = 1;
while (LoopDate_Begin.DayOfWeek.ToString() != End_of_Week)
{
LoopDate_Begin = LoopDate_Begin.AddDays(1);
}
foreach (var pe in orderedData)
{
do
{
if (LoopDate_Begin.DayOfYear > pe.Date.DayOfYear && LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7))
{
TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
break;
}
WeekCount++;
LoopDate_Begin = LoopDate_Begin.AddDays(7);
} while (true); //need to be careful here
}
if I get you correctly, you don't need to look any further as soon as you've added your TradingWeek
So, you can
break;
after
tradingWeek.Add(TW);
You could then even leave out the
&& LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7)
condition since the first part is going to be true only once: for your desired interval.
You might even go for a loopless approach by dividing the number of days since your starting week by 7 - and doing some cleaning up work ;)
Can you get rid of your do loop altogether by calculating the Week Number directly? Something like the accepted answer here.
Following #nicolas78's response, something like this should work
int Year = pe.Date.Year;
DateTime Year_Begin = new DateTime(Year,1,1);
int Jan1DayOfWeek = Year_Begin.DayOfWeek;
foreach (var pe in FileData)
{
int WeekCount = (pe.Date.DayOfYear - Jan1DayOfWeek) % 7 + 1;
TradingWeek TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
}
Depending on how DayOfWeek and DayOfYear count, that is from 0 or 1, and how your mod operation work, you may need to tweak the WeekCount computation a bit.
There's a built-in feature to get the week of the year based on the date in .NET. An example is shown below, but it may need some tweaking to fit your business scenario:
System.Globalization.CultureInfo myCI = new System.Globalization.CultureInfo("en-US");
int week = myCI.Calendar.GetWeekOfYear(DateTime.Now.ToUniversalTime(), System.Globalization.CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Sunday);
You don't need to count at all - just do a quick calculation. This assumes that a partial week at the start of the year is week 1 and week 2 begins on the first Monday.
List<TradingWeek> tradingWeek = new List<TradingWeek>();
foreach (var pe in FileData)
{
var date = pe.Date;
while (date.DayOfWeek != DayOfWeek.Sunday)
date = date.AddDays(1);
var week = date.DayOfYear/7+1;
var TW = new TradingWeek {Week = week, Date = pe.Date};
tradingWeek.Add(TW);
}

Resources