compare datetime and timespan value - timespan

I want to compare datetime value and timespan value for the reason of non-negative value checking ..
my code is here:
TimeSpan lateaftertime = new TimeSpan();
lateaftertime = Convert.ToDateTime(intime) - lateafter;
string latetime = lateaftertime.Hours + ":" + lateaftertime.Minutes;
if ((lateafter < lateaftertime))
{
Session["late"] = "00:00";
}
else
{
Session["late"] = latetime;
}
suppose late after returns negative value means the session["late"] have the value 00:00 otherwise the session maintain the difference value
please help me. i was trouble this..

Your question is pretty unclear, but it sounds like you really want:
if (lateaftertime < TimeSpan.Zero)
{
Session["late"] = "00:00";
}
else
{
Session["late] = latetime;
}
or more concisely:
Session["late"] = lateaftertime < TimeSpan.Zero ? "00:00" : latetime;
It's possible you want > rather than < here - it's hard to tell what you're trying to achieve. Sample data would make it clearer. You should also rename your variables to be more conventional, e.g. lateAfterTime instead of lateafterime

Related

trying to figure out why a for each statement worked with an if statement, but throws an exception when i switch it to a for loop

Sorry in advance, as I have only been working with C# for about a month with limited history in VB years ago. It's a Mail merge kind of loop that I am trying to create for work to make their life easier. I have the dates figured out. I have a NumUpDown control setting the int myInt, and a formCount int starting at 0.
The code worked fine when I used if(formCount==0), when I switched it to
for(formCount=0;formCount<myInt;formCount++)
it now throws a
"System.NullReferenceException: 'Object reference not set to an
instance of an object.'"
I know there is probably another way to do what I am working on which is to just add sequential dates to forms a month at a time. I have the dates stored in an array myDate[31].
I am using the numUpDwn(min 1 max 31) to get myInt so we can select how many days in the month, or only print a couple days if we need to replace pages, so we can print anywhere from 1 to 31 pages.
With the if statement it would create the first page from the template (.dotx) to doc(var) copy the contents of doc to doc2 and add a new page to receive the next content paste.
I am sure this is a silly question, that someone will have a simple answer too. The loop is supposed to open the template, add the date, copy to doc2. close the original, and restart until it reached the number of pages/dates selected. Thanks for any help, this is the last section I need to finish and I am stumped. Oh, and I used the != because it was skipping the merge field, but with only 1 field not equal to anything worked.
private void BtnPrint_Click(object sender, EventArgs e)
{
var app = new Microsoft.Office.Interop.Word.Application();
var doc = new Microsoft.Office.Interop.Word.Document();
var doc2 = new Microsoft.Office.Interop.Word.Document();
//app.Visible = true;
doc = null;
doc2.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
doc2.PageSetup.TopMargin = app.InchesToPoints(0.6f);
doc2.PageSetup.BottomMargin = app.InchesToPoints(0.17f);
doc2.PageSetup.LeftMargin = app.InchesToPoints(0.5f);
doc2.PageSetup.RightMargin = app.InchesToPoints(0.5f);
String fileSave;
fileSave = ("OTSU" + "_" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
int formCount;
//formCount = 0;
var filepath = System.Windows.Forms.Application.StartupPath + outfile;
doc = app.Documents.Add(filepath);
doc2.Activate();
//OBJECT OF MISSING "NULL VALUE"
Object oMissing = System.Reflection.Missing.Value;
for (formCount = 0; formCount<myInt;formCount++)
{
doc.Activate();
foreach (Microsoft.Office.Interop.Word.Field field in doc.Fields)
{
Range rngFieldCode = field.Code;
String fieldText = rngFieldCode.Text;
// ONLY GETTING THE MAILMERGE FIELDS
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11);
// GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dotx FILE
fieldName = fieldName.Trim();
if (fieldName != "M_2nd__3rd")
{
field.Select();
app.Selection.TypeText(myDate[formCount].ToShortDateString());
}
formCount++;
Microsoft.Office.Interop.Word.Range dRange = doc.Content;
dRange.Copy();
doc2.Range(doc2.Content.End - 1, doc2.Content.End - 1).PasteSpecial(DataType: Microsoft.Office.Interop.Word.WdPasteOptions.wdKeepSourceFormatting);
doc2.Range(doc2.Content.End - 1, doc2.Content.End - 1).InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);
Clipboard.Clear();
doc.Close(WdSaveOptions.wdDoNotSaveChanges);
}
}
}
doc2.SaveAs2("OTSU" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
app.Documents.Open("OTSU" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
doc.Close(WdSaveOptions.wdDoNotSaveChanges);
doc2.Close(WdSaveOptions.wdDoNotSaveChanges);
I haven’t run your code, but as far as I can see, this code would probably fail even without the formcount loop in the situation where you have more than one MERGEFIELD field because you close doc As soon as you have processed such a field, and yet the foreach loop is processing each Field in doc.Fields.
Even if that foreach loop terminates gracefully, in the next iteration of the formCount loop you are using doc.Activate(), but doc has closed so that will fail.
So I suggest that the main thing to do is consider which documents need to be open at which point for the process to work.
Some observations (not necessarily to do with your primary question)
where is myInt set?
is having a formCount++ loop and using formCount++ within the loop for every MERGEFIELD in doc Really your intention?
you might be better off testing field.Type() when filtering MAILMERGE fields rather than matching the text, at least if such fields can be set up by end users
when you process collections in Word and you are either adding or deleting members of the collection, you sometimes have to consider using a loop that starts with last member of the collection and works back towards the beginning. Not sure you need to do that in this case but since you may be “deleting” when you do your field.Select then Typetext, please bear that in mind
It may seem like a complication when you are mainly trying to sketch out the logic of your loops, but I generally find it very helpful to start using try...catch...finally blocks sooner rather than later during development.
I did find a solution for now. Since there is only one MERGFIELD, instead of trying to open doc, insert date, copy to new doc2, close doc, repeat I found I can open, insert date, copy to new doc2, undo edit on doc and repeat. At least it works for now, and I can get back to the books and learn some more while I map out the big project I have planned. I am sure I will be on here a bit with more questions. Without #slightly-snarky asking the questions he did, I wouldn't have thought of this so I have to give them credit for the answer. I did have to put the doc.Undo(); at the top of the loop and it will only work with one field. But its a start.
private void BtnPrint_Click(object sender, EventArgs e)
{
var app = new Microsoft.Office.Interop.Word.Application();
String fileSave;
fileSave = ("OTSU" + "_" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
int formCount;
formCount = 0;
var filepath = System.Windows.Forms.Application.StartupPath + outfile;
var doc = new Microsoft.Office.Interop.Word.Document();
doc = app.Documents.Add(filepath);
app.Visible = true;
doc.Activate();
var doc2 = new Microsoft.Office.Interop.Word.Document();
doc2.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
doc2.PageSetup.TopMargin = app.InchesToPoints(0.6f);
doc2.PageSetup.BottomMargin = app.InchesToPoints(0.17f);
doc2.PageSetup.LeftMargin = app.InchesToPoints(0.5f);
doc2.PageSetup.RightMargin = app.InchesToPoints(0.5f);
doc2.Activate();
//OBJECT OF MISSING "NULL VALUE"
Object oMissing = System.Reflection.Missing.Value;
for (formCount = 0; formCount < myInt; formCount++)
{
doc.Undo();
foreach (Microsoft.Office.Interop.Word.Field field in doc.Fields)
{
Range rngFieldCode = field.Code;
String fieldText = rngFieldCode.Text;
// ONLY GETTING THE MAILMERGE FIELDS
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11);
// GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dotx FILE
fieldName = fieldName.Trim();
if (fieldName != "M_2nd__3rd")
{
field.Select();
app.Selection.TypeText(myDate[formCount].ToShortDateString());
}
Microsoft.Office.Interop.Word.Range dRange = doc.Content;
dRange.Copy();
doc2.Range(doc2.Content.End - 1, doc2.Content.End - 1).PasteSpecial(DataType: Microsoft.Office.Interop.Word.WdPasteOptions.wdKeepSourceFormatting);
doc2.Range(doc2.Content.End - 1, doc2.Content.End - 1).InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);
Clipboard.Clear();
}
}
}
doc2.SaveAs2("OTSU" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
doc.Close(WdSaveOptions.wdDoNotSaveChanges);
doc2.Close(WdSaveOptions.wdDoNotSaveChanges);
app.Documents.Open("OTSU" + myDate[0].Month + "_" + myDate[0].Year + ".docx");
}
}
}

Writing code Javascript and other languages

What is the general consenses, in this case i will be using JavaScript as an example:
Which one is more clear and correct A or B.. ? Please explain why, it might help others with their own coding style
A) Assign value to variable then check variable, then return value
...
mm = fecha.getMonth().length;
if (mm<=1)
{
return '0' + mm;
}
...
B) Check value directly then return value
...
if (fecha.getMonth().length<=1)
{
return '0'+ fecha.getMonth().length;
}
...
If you just want to condition the value and not using it later
if (fecha.getMonth().length<=1){
...
}
No need to create another variable which name could be used later and would lead to an error
let month = fecha.getMonth();
if( month.length<=1 ){
...
}
...
let month = document.querySelector('input#month').value; // Error 'month' has already been declared
...
If you have to check the value and furthermore use it
mm = fecha.getMonth().length;
if (mm<=1)
return mm;
}
Keeps the code clean when there are cases like this
aType = document.querySelector('A').children[0].classList[0].split('-')[1]
if(aType != 'relative'){
return document.querySelectorAll(aType)[1];
}
Which otherwise it would look like this
if(document.querySelector('A').children[0].classList[0].split('-')[1] != 'relative'){
return document.querySelectorAll(document.querySelector('A').children[0].classList[0].split('-')[1])[1];
}

Android: Connecting buttons to the java file through a for loop

I'm trying to create a chess game for Android and would like to avoid having to declare every button when they are all named so similarly. I tried to generate all of the A + Num button using this for loop.
int RowNum ;
for (RowNum = 1; RowNum < 8; RowNum++) {
String Position = "A" + RowNum;
Button Position = (Button)findViewById(R.id.Position);
}
But I have an error: Variable 'Position' is already defined in the scope.
I would really appreciate if someone could explain to me the best way to go about doing this.
Thanks in advance.
R.Id.A1, R.id.A2, etc. are identifiers and each of them is mapped to a single integer during compilation of R class. Thus, you cannot manipulate the 'R.id.sth' as a string because it will not compile properly.
A way to solve that is search for the string in resources dynamically with a code like this:
Button[] buttons=new Button[8];
for(int RowNum=0; RowNum<8; RowNum++) {
String buttonID = "A"+(RowNum+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[RowNum] = ((Button) findViewById(resID));
}
Alternatively, to avoid the time overhead of dynamic search you can add a resource array:
int[] butIds = {R.id.A1, R.id.A2,...};
Button[] buttons= new Button[8];
for(int RowNum=0; RowNum<8, RowNum++) {
buttons[RowNum]= ((Button) findViewById(butIds[RowNum]));
}
You can even store the resource array in XML form and retrieve it as a TypedArray.
You called your String and Button object both Position. Give them different names, e.g.
for (int RowNum = 1; RowNum < 8; RowNum++) {
String currentPosition = "A" + RowNum;
//Why doesn this not use the Position (now 'currentPosition' variable)?
Button currentButton = (Button)findViewById(R.id.Position);
}
Semantically I still don't get that piece of code because Position is not used within the argument of findViewById, to which you pass a static variable R.id.Position.

Subtract Dates in Reducer

The input to reducer is as follows
key: 12
List<values> :
1,2,3,2013-12-23 10:21:44
1,2,3,2013-12-23 10:21:59
1,2,3,2013-12-23 10:22:07
The output needed is as follows:
1,2,3,2013-12-23 10:21:44,15
1,2,3,2013-12-23 10:21:59,8
1,2,3,2013-12-23 10:22:07,0
Please note last column is 10:21:59 minus 10:21:44. Date(next) - Date(current)
I tried loading into memory and subtracting but it is causing java heap memory issue. Your help is highly appreciated. data size for this key is huge > 1 GB and not able to fit into main memory.
Perhaps something along the lines of this pseudocode in your reduce() method:
long lastDate = 0;
V lastValue = null;
for (V value : values) {
currentDate = parseDateIntoMillis(value);
if (lastValue != null) {
context.write(key, lastValue.toString() + "," + (currentDate - lastDate));
}
lastDate = currentDate;
lastValue = value;
}
context.write(key, lastValue.toString() + "," + 0);
Obviously there will be tidying up to do but the general idea is fairly simple.
Note that because of your requirement to include the date of the next value as part of the current value calculation, the iteration through the values skips the first write, hence the additional write after the loop to ensure all values are accounted for.
If you have any questions feel free to ask away.
you can do by following code
reduce (LongWritable key, Iterable<String> Values, context){
Date currentDate = null;
LongWritable diff = new LongWritable();
for (String value : values) {
Date nextDate = new Date(value.toString().split(",")[3]);
if (currentDate != null) {
diff.set(Math.abs(nextDate.getTime()-currentDate.getTime())/1000)
context.write(key, diff);
}
currentDate = nextDate;
}
}

How to convert LINQ nvarchar to double

I'm trying to sort a column, but the value is stored as nvarchar in the database, how can I convert it to a double so it sorts here? I tried to do Convert.ToDouble(t.PressureChange), but it didn't work...
if (column == "PressureChange")
{
if (sortDirection == "ascending")
testResults = testResults.OrderBy(t => t.PressureChange);
else
testResults = testResults.OrderByDescending(t => t.PressureChange);
}
You could try
if (column == "PressureChange")
{
if (sortDirection == "ascending")
{
testResults = testResults.OrderBy(t => double.Parse(t.PressureChange));
}
else
{
testResults = testResults.OrderByDescending
(t => double.Parse(t.PressureChange));
}
}
... but it depends whether that method is supported by LINQ to SQL. To be honest, it sounds like you've got bigger problems in terms of your design: if you're trying to store a double value in the database, you shouldn't be using a varchar field to start with. Fix your schema if you possibly can.
EDIT: Note that based on the information on this page about LINQ to SQL and Convert.* it looks like Convert.ToDouble should work, so please give us more information about what happened when you tried it.
Rather use TryParse to avoid exceptions. In this code I used 0.0 as a default value if it could not parse the string.
double temp = 0.0;
if (column == "PressureChange")
{
if (sortDirection == "ascending")
testResults = testResults.OrderBy(t => (double.TryParse(t.PressureChange.toString(), out temp) ? temp : 0.0)).ToList();
else
testResults = testResults.OrderByDescending(t => (double.TryParse(t.PressureChange.toString(), out temp) ? temp : 0.0)).ToList();
}
I have not tested it but you can use an extension method like this:
public class StringRealComparer : IComparer<string>
{
public int Compare(string s1, string s2)
{
double d1;
double d2;
double.tryParse(s1, out d1);
double.TryParse(s2, out d2);
return double.Compare(d1, d2);
}
}

Resources