Invalid Date whilst using Moment() and Linq - linq

I am having a problem where I have a 12 month period but beginning from zero index and its causing me to have an invalid date. Below is a picture of both my date array and chart js. Basically, because the months are zero indexed, they are out by one
and the below is the Linq query I am using, if anyone can help me fix this that would be great
var solicitor = _db.Records
.Where(j => j.Requestor == "Solicitor" && EF.Functions.DateDiffMonth(j.Request_Date, DateTime.Now) == 0 && EF.Functions.DateDiffMonth(j.Request_Date, DateTime.Now) <= 12)
.GroupBy(g => new { g.Request_Date.Value.Year, g.Request_Date.Value.Month }).OrderBy(d => d.Key.Year).ThenBy(d => d.Key.Month)
.Select(group => new
{
Dates = group.Key,
Count = group.Count()
});
var solicitorCount = solicitor.Select(n => n.Count).ToArray();
var date = solicitor.Select(n => n.Dates).ToArray();
and the code inside my chart js to format as moment
let newArr = []
for (let i = 0; i < simpleData[0].date.length; i++) {
var calDate = moment(simpleData[0].date[i]).format('MMM YYYY');
console.log(calDate)
newArr.push(calDate)
}

You can change your code like this:
let newArr = []
for (let i = 0; i < simpleData[0].date.length; i++) {
data[i].month -= 1;
var calDate = moment(simpleData[0].date[i]).format('MMM YYYY');
console.log(calDate)
newArr.push(calDate)
}
newArr result:

Related

Linq to entity with dynamically growing where clause

I am trying to fetch data from an entity based on some criteria. The WHERE clause will have any number of 'OR' conditions. How can I acheive this?
var skill = skillset.split(";"); //array can have any number of items
var EmployeeList1 = EmployeeList
.Where(x => x.Primary1.ToUpper().Contains(skill[0])
|| x.Primary2.ToUpper().Contains(skill[0])
|| x.Primary1.ToUpper().Contains(skill[1])
|| x.Primary2.ToUpper().Contains(skill[1]))
.ToList();
return EmpMapper.Mapper.Map<List<EmployeeModel>>(EmployeeList1);
I need to build an expression for where clause with 'n' number of 'OR' conditions. I tried using predicate, but got exception(Index was outside the bounds of the array.).
var predicate = PredicateBuilder.New<ResourceEntity>(true);
for (int i = 0; i < skill.Count(); i++)
{
predicate= predicate.Or(p => p.Primary1.Contains(skill[i]));
}
You have to copy for variable into local variable:
var predicate = PredicateBuilder.New<ResourceEntity>(true);
for (int i = 0; i < skill.Length; i++)
{
var s = skill[i];
predicate = predicate.Or(p => p.Primary1.ToUpper().Contains(s));
predicate = predicate.Or(p => p.Primary2.ToUpper().Contains(s));
}

InDesign Text Modification Script Skips Content

This InDesign Javascript iterates over textStyleRanges and converts text with a few specific appliedFont's and later assigns a new appliedFont:-
var textStyleRanges = [];
for (var j = app.activeDocument.stories.length-1; j >= 0 ; j--)
for (var k = app.activeDocument.stories.item(j).textStyleRanges.length-1; k >= 0; k--)
textStyleRanges.push(app.activeDocument.stories.item(j).textStyleRanges.item(k));
for (var i = textStyleRanges.length-1; i >= 0; i--) {
var myText = textStyleRanges[i];
var converted = C2Unic(myText.contents, myText.appliedFont.fontFamily);
if (myText.contents != converted)
myText.contents = converted;
if (myText.appliedFont.fontFamily == 'Chanakya'
|| myText.appliedFont.fontFamily == 'DevLys 010'
|| myText.appliedFont.fontFamily == 'Walkman-Chanakya-905') {
myText.appliedFont = app.fonts.item("Utsaah");
myText.composer="Adobe World-Ready Paragraph Composer";
}
}
But there are always some ranges where this doesn't happen. I tried iterating in the forward direction OR in the backward direction OR putting the elements in an array before conversion OR updating the appliedFont in the same iteration OR updating it a different one. Some ranges are still not converted completely.
I am doing this to convert the Devanagari text encoded in glyph based non-Unicode encoding to Unicode. Some of this involves repositioning vowel signs etc and changing the code to work with find/replace mechanism may be possible but is a lot of rework.
What is happening?
See also: http://cssdk.s3-website-us-east-1.amazonaws.com/sdk/1.0/docs/WebHelp/app_notes/indesign_text_frames.htm#Finding_and_changing_text
Sample here: https://www.dropbox.com/sh/7y10i6cyx5m5k3c/AAB74PXtavO5_0dD4_6sNn8ka?dl=0
This is untested since I'm not able to test against your document, but try using getElements() like below:
var doc = app.activeDocument;
var stories = doc.stories;
var textStyleRanges = stories.everyItem().textStyleRanges.everyItem().getElements();
for (var i = textStyleRanges.length-1; i >= 0; i--) {
var myText = textStyleRanges[i];
var converted = C2Unic(myText.contents, myText.appliedFont.fontFamily);
if (myText.contents != converted)
myText.contents = converted;
if (myText.appliedFont.fontFamily == 'Chanakya'
|| myText.appliedFont.fontFamily == 'DevLys 010'
|| myText.appliedFont.fontFamily == 'Walkman-Chanakya-905') {
myText.appliedFont = app.fonts.item("Utsaah");
myText.composer="Adobe World-Ready Paragraph Composer";
}
}
A valid approach is to use hyperlink text sources as they stick to the genuine text object. Then you can edit those source texts even if they were actually moved elsewhere in the flow.
//Main routine
var main = function() {
//VARS
var doc = app.properties.activeDocument,
fgp = app.findGrepPreferences.properties,
cgp = app.changeGrepPreferences.properties,
fcgo = app.findChangeGrepOptions.properties,
text, str,
found = [], srcs = [], n = 0;
//Exit if no documents
if ( !doc ) return;
app.findChangeGrepOptions = app.findGrepPreferences = app.changeGrepPreferences = null;
//Settings props
app.findChangeGrepOptions.properties = {
includeHiddenLayers:true,
includeLockedLayersForFind:true,
includeLockedStoriesForFind:true,
includeMasterPages:true,
}
app.findGrepPreferences.properties = {
findWhat:"\\w",
}
//Finding text instances
found = doc.findGrep();
n = found.length;
//Looping through instances and adding hyperlink text sources
//That's all we do at this stage
while ( n-- ) {
srcs.push ( doc.hyperlinkTextSources.add(found[n] ) );
}
//Then we edit the stored hyperlinks text sources 's texts objects contents
n = srcs.length;
while ( n-- ) {
text = srcs[n].sourceText;
str = text.contents;
text.contents = str+str+str+str;
}
//Eventually we remove the added hyperlinks text sources
n = srcs.length;
while ( n-- ) srcs[n].remove();
//And reset initial properties
app.findGrepPreferences.properties = fgp;
app.changeGrepPreferences.properties = cgp;
app.findChangeGrepOptions.properties =fcgo;
}
//Running script in a easily cancelable mode
var u;
app.doScript ( "main()",u,u,UndoModes.ENTIRE_SCRIPT, "The Script" );

Calculating Total Job Experience

I need to calculate the total job experience as year value. Users add experiences with starting and ending dates to their resumes, just like Linkedin. But there is no any certain pattern. For instance;
A user may have a resume like that;
Experience 2
08.2012 - 01.2015
Experience 1
01.2011 - 01.2013
The user started their second experience while the first hasn't finished yet. So resumes may have many overlapping experiences. Overlapping also may occur between more than 2. So I need to consider many cases.
I tried to visualise the experience and year relationship for you.
I just need to develop an algorithm covering all the cases for this issue.
Sort by start date
start at the beginning and accumulate overlapping experiences (i.e. treat as one)
e.g. (Jan 2012, Jan 2015), (Jan 2014, Dec 2016) overlap, so we treat it as a single experience
This "super experience" begins at the start of the first, and ends at the end of the last; (Jan 2012, Dec 2016)
This is assuming that there can be gaps in experience, so we don't want to treat the entire history as one long "super experience"
I just did this
Sort the experiences by Begin Date.
Use 2 variables, that represent the begin of work and the end called Begin
and End.
If end and begin are empty it means that is the first date, we filled with the first experience, and we calculate the month count between the begin and end of this experience and and then this months count add to our months accumulator.
if the end and begin date of next experience is not between our begin and end variables, we calculate the months count from the experience and then add it to our accumulator.
If the begin date of next experience is between our begin and end variables, we calculate the months count between our end date as begin and the experience end date as end, and then that difference add to our months accumulator.
as you can see every time we set our new end if the experience end is greater than ours.
at the end we get the months, if you divide by 12 you get the years exactly you can round it if you want
NOTE: I Mapped the experiences, if not have End it means that is equivalent to NOW
you can see all the code below
function monthDiff(d1, d2) {
var m = (d1.getFullYear() - d2.getFullYear()) * 12 +
(d1.getMonth() - d2.getMonth());
if (d1.getDate() < d2.getDate()) --m;
return m;
}
function dateCheck(from, to, check) {
var fDate, lDate, cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if (cDate <= lDate && cDate >= fDate) {
return true;
}
return false;
}
function calculateYearsOfExperience(experiences) {
if (!experiences) return 0;
let months = 0;
let now = new Date();
let sorted = experiences
.sort((a, b) => {
return new Date(a.begin) - new Date(b.begin);
})
.map(experience => {
if (!experience.end) experience.end = now;
return { begin: experience.begin, end: experience.end };
});
let begin;
let end;
for (var i in sorted) {
let dif = 0;
if (!end && !begin) {
dif = monthDiff(sorted[i].begin, sorted[i].end);
begin = sorted[i].begin;
end = sorted[i].end;
} else if (
!dateCheck(begin, end, sorted[i].begin) &&
!dateCheck(begin, end, sorted[i].end)
) {
dif = monthDiff(sorted[i].begin, sorted[i].end);
end = sorted[i].end;
} else if (dateCheck(begin, end, sorted[i].begin)) {
dif = monthDiff(end, sorted[i].end);
end = sorted[i].end;
}
months += dif;
}
return months / 12;
}
experiences = [
# (start date, end date),
(date(2012, 8, 1), date(2015, 1, 30)),
(date(2011, 1, 1), date(2013, 1, 30))
]
print(sum((end_date - start_date).days/365 for start_date, end_date in experiences))
Create an array full of 0. Element range: Start would be the very first hire date, last would be current date / last working date. For every year you have 12 elements that can be 0/1. After filling in the array count the elements that have the value 1. If you need to take into account the overlapping then ignore the 0/1 part and give +1 for every month worked.
This is c# code, but you'll get the steps in algorithm. It returns total number of months which you can convert into year and month format.
var sortedList = expList
.OrderBy(a => a.start_year)
.ThenBy(a => a.start_month)
.ThenBy(a => a.end_year)
.ThenBy(a => a.end_month)
.ToList();
int totalMonths = 0;
int totalDays = 0;
DateTime? prevEndDate = null;
foreach (var exp in sortedList)
{
if(exp.start_month != null && exp.start_year != null)
{
var startDate = new DateTime((int)exp.start_year, (int)exp.start_month, 1);
var endDate = (bool)exp.is_present ?
DateTime.Now :
new DateTime((int)exp.end_year, (int)exp.end_month, 1);
if (prevEndDate != null && prevEndDate > startDate)
{
startDate = (DateTime)prevEndDate;
}
var timespan = endDate.Subtract(startDate);
var tempdate = DateTime.MinValue + timespan;
totalMonths = totalMonths + (tempdate.Year - 1) * 12 + tempdate.Month - 1;
totalDays = totalDays + tempdate.Day - 1;
prevEndDate = endDate;
}
}
if (totalDays > 0)
{
totalMonths = totalMonths + 1;
}
public static function YearCalculation($id=null) {
if($id=="")
$employee_id=#Auth::guard('web_employee')->user()->id;
else
$employee_id=$id;
$employee_exp = Experience::where('employee_id',$employee_id)->orderBy("experience_from","ASC")->get();
//print_r($employee_exp ); exit;
$years = 0;
$months = 0;
$days = 0;
$sum=0;
$lastfromdate=0;
$last_endDate=0;
if(#$employee_exp!=null){
foreach(#$employee_exp as $experience){
$fdate = #$experience->experience_from;
if($experience->is_current==0){
$tdate = #$experience->experience_to;
}else{
$tdate = date("Y-m-d");
}
if($last_endDate != date("Y-m-d") ){
if( $fdate < $last_endDate ){
$start_date1 = strtotime($last_endDate);
$end_date1 = strtotime($tdate);
$interval1 = ($end_date1 - $start_date1)/60/60/24;
$sum +=$interval1;
}
else{
$start_date2 = strtotime($fdate);
$end_date2 = strtotime($tdate);
$interval2 = ($end_date2 - $start_date2)/60/60/24;
$sum +=$interval2;
}
if($last_endDate < $tdate){
$last_endDate=$tdate;
}
}
}
$years = ($sum / 365) ;
$years = floor($years);
$month = ($sum % 365) / 30.4166;
$month = floor($month);
$days = ($sum % 365) % 30.4166;
//$total=date_diff(0,$tmstamp);
//$total_year=$years.' years, ' .$month.' months and '.$days.($days==1?' day':' days');
$total_year=($years==0?'':($years==1?$years.' year':$years.' years and ')) .($month==0?'':($month==1?$month.($days>1?'+':'').' month':$month.($days>1?'+':'').' months'));
return $total_year;
}
}

running total by linq : place results in paged List

I try to place results of below link in a paged list:
LINQ to SQL and a running total on ordered results
I change the code slightly :
var userDocs = db.Docs.AsQueryable();
Int64 running_total = 0;
var moeen = userDocs.ToList()
.OrderBy(a => a.DocDate)
.Select(a =>
{
running_total += 1;
return new MoeenViewModel
{
Doc = a,
remain = running_total
};
}
);
return View(moeen.ToPagedList(1, 15));
but 'remain' results don't start with 1. it start with 8 for example if 'Docs' records count is 7
Why ??? !!!
if I return View(moeen) results is Ok
I find problem
var userDocs = db.Docs.AsQueryable();
Int64 running_total = 0;
var moeen = userDocs.ToList()
.OrderBy(a => a.DocDate)
.Select(a =>
{
running_total += 1;
return new MoeenViewModel
{
Doc = a,
remain = running_total
};
}
);
moeen = moeen.ToList();
return View(moeen.ToPagedList(1, 15));
before list moeen by .ToList(), every use of moeen cause to side effect on running_total.
See this :
http://www.blackwasp.co.uk/LinqRunningTotal.aspx
if you change the value of the variable that has been closed over before executing the query, the results will be affected.

Replace certain cell values in a column

Disclaimer: I am Newb. I understand scripting a little, but writing it is a pain for me, mostly with loops and arrays, hence the following.
I am attempting to pull all of the data from a specific column (in this case H [8]), check each cell's value in that column and if it is a y, change it to Yes; if it's n, change it to No; if it's empty, leave it alone and move onto the next cell.
Here's what I have so far. As usual, I believe I'm pretty close, but I can't set the value of the active cell and I can't see where I'm messing it up. At one point I actually changed ever value to Yes in the column (so thankful for undo in these cases).
Example of Sheet:
..... COL-H
r1... [service] <-- header
r2... y
r3... y
r4... n
r5... _ <-- empty
r6... y
Intent: Change all y's to Yes and all n's to No (skip blank cells).
What I've tried so far:
Function attempt 1
function Thing1() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
var lrow = ss.getLastRow();
var rng = ss.getRange(2, 8, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == "y") {
data[i][0] == "Yes";
}
}
}
Function attempt 2
function Thing2() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
var lrow = ss.getLastRow();
var rng = ss.getRange(2, 8, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == "n") {
data.setValue("No");
} else if (data[i][0] == "y") {
data.setValue("Yes");
}
}
}
Usage:
Once I'm done here, I want to modify the function so that I can target any column and change one value to another (I already have a method for that, but I need to be able to set the value). It would be like so: =replace(sheet, col, orig_value, new_value). I will post it as well below.
Thanks in advance for the help.
Completed Code for searching and replacing within a column
function replace(sheet, col, origV1, newV1, origV2, newV2) {
// What is the name of the sheet and numeric value of the column you want to search?
var sheet = Browser.inputBox('Enter the target sheet name:');
var col = Browser.inputBox('Enter the numeric value of the column you\'re searching thru');
// Add old and new targets to change (Instance 1):
var origV1 = Browser.inputBox('[Instance 1:] What old value do you want to replace?');
var newV1 = Browser.inputBox('[Instance 1:] What new value is replacing the old?');
// Optional - Add old and new targets to change (Instance 2):
var origV2 = Browser.inputBox('[Instance 2:] What old value do you want to replace?');
var newV2 = Browser.inputBox('[Instance 2:] What new value is replacing the old?');
// Code to search and replace data within the column
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
var lrow = ss.getLastRow();
var rng = ss.getRange(2, col, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == origV1) {
data[i][0] = newV1;
} else if (data[i][0] == origV2) {
data[i][0] = newV2;
}
}
rng.setValues(data);
}
Hope this helps someone out there. Thanks Again #ScampMichael!
The array named data was created from the values in the range and is independent of the spreadsheet after it is created so changing an element in the array does not affect the spreadsheet. You must modify the array and then put the whole array back where it came from.
for (var i=0; i < data.length; i++) {
if (data[i][0] == "n") {
data[i][0] = "No";
} else if (data[i][0] == "y") {
data[i][0] = "Yes";
}
}
rng.setValues(data); // replace old data with new
}

Resources