I have just few days to show a demo about a Music Player in WPF and i have a trouble that i can not work out right now .
I need know how change a location folder meantime the Music Player is running ,i have 3 location folder:
D/: Morning;
D/: Afternoon;
D/: Night;
in each folder there are songs of different genre.
This music player will be used everyday from the 8am to 10pm with no stop ,so when run the application in morning(8am) it will download automatically the folder"Morning" but when the timeOfDay is Midday it will change location folder and so pass in the folder"Afternoon"(about 6p would pass to the folder "Night") and at the point i get stuck i don't know how work out this step,i don't know how organise my code to make the Music Player change location folder and download new songs in automatic way.
Please do you have some idea to illuminate my mind and go on to finish this Demo?
Sorry for my confusion;
Thanks a lot
Honsa has the right idea, but this is a slightly cleaner implementation:
public static string GetFolderForTime(DateTime time)
{
if (time.Hour > 8 && time.Hour < 10)
return #"D:\Morning\";
if (time.Hour > 10 && time.Hour < 18)
return #"D:\Afternoon\";
return #"D:\Night\";
}
That way you can pass in a time different from the current one if you need to, although normally you would use DateTime.Now.
Also, note that the name of the function describes what it does.
static public string GetWorkingFolder()
{
if(System.DateTime.Now.Hour > 1 && System.DateTime.Now.Hour < 12)
return #"D:\Morning";
else if (System.DateTime.Now.Hour > 11 && System.DateTime.Now.Hour < 18)
return #"D:\Afternoon";
else
return #"D:\Evening";
}
would return a differential string dependant on the current pc time (which can of course change) this could then be parsed into a directory or directly used in whatever load method is picking up the various 'tunes'
Try this. Every time a song ends, before it loads a new one, simply call a function that does this:
// The string returned is the path
public string TimeOfDay()
{
// How you define
if(System.DateTime.Now.Hour >= 8 && System.DateTime.Now.Hour < 10)
return #"D:\Morning\";
else if(System.DateTime.Now.Hour >= 10 && System.DateTime.Now.Hour < 18)
return #"D:\Afternoon\";
else
return #"D:\Night\";
}
If the path returned is differen than the one you already have, then you change, and play songs from the new path.
Related
Got into a problem and i can't seem to find the issue. I am currently making a war based game where players are able to buy certain buildings and place them wherever they want. When they choose the spot they like it starts building. After specific time passes it finishes building and it appears in the spot.
THE PROBLEM: I can't figure out how to give the building time to buildings if there are more than one of them building. I tried arrays, but it came to nothing.
THE CODE: The code is kind of hard to read. But if it helps, here you go:
public void BuyBuilding(string whichBuilding)
{
if (whichBuilding == "CIV")
{
if (CIVQUANT < MaxCivQuant && decidedNotToBuy == false && howManyAreBuilding < 4)
{
if (ELEM.Money >= 10000) //IF ENOUGH MONEY
{
howManyAreBuilding++;
whichBuildBought[howManyAreBuilding] = whichBuilding;
}
^ Here i made a method that activates whenever a player presses a button, it checks which building it is "CIV" is one of them, i removes 10k from the player's currency (Not shown here for now)and adds a "CIV" value to a whichBuildBought string array. Then we go to update where the game is checking if any building was bought:
private void Update()
{
if (boughtBuildingS == true && whichBuildBought[howManyAreBuilding] == "CIV")
{
ElapsedTimeCalculator(howManyAreBuilding);
if (elapsedTime[howManyAreBuilding] == time.OnDayChanged)
{
elapsedTime[howManyAreBuilding] = 0;
boughtBuildingTime[howManyAreBuilding] = 0;
ElapsedTimeCalculatorPassed = false;
howManyAreBuilding--;
}
}
^ Here i activate an ElapsedTimeCalculator method shown below, Time.OnDayChanged is a day counter, i use it to check if the day the player bought the building matches the day it's supposed to finish building by giving boughtBuildingTime specific array value a current day value and then giving elapsedTime array that value plus how many days its supposed to be building. In the update method if the elapsedTime of that specific building in the array is done it just finished building and some extra things happen that i just removed for now.
public void ElapsedTimeCalculator(int i)
{
if (ElapsedTimeCalculatorPassed == false && whichBuildBought[i] == "CIV")
{
boughtBuildingTime[i] = time.OnDayChanged;
elapsedTime[i] = boughtBuildingTime[i] + 20;
ElapsedTimeCalculatorPassed = true;
}
Thanks in advance for helping! Would really appreciate it.
Inside a string array -"files", 10 file paths are stored.
For example, I show 2 of them,
[0] C:\\Users\\17\\Documents\\FS\\D\\mdN_2903.dat
[1] C:\\Users\\17\\Documents\\FS\\D\\mdNBP_29032.dat
I want to validate using their filename (before the numbering & extension .dat) as well the number of files counted in c#.net
I tried to use it like this, but it didn't passed even though the files are present
if(Array.Exists(files,e => e.Contains("mdN_") && e.Contains("mdNBP_") && e.count()==10)) { // All 10 files are present }
Is there any other way to implement this in c#, please explain?
Without testing it. If your file array always has 2 has mdN and mdNBP and the same order with up to 10 files, you can do something like this:
if (files[0].Contains("mdN") && files[1].Contains("mdNBP") && files.Length == 10)
{
Console.WriteLine("all good");
}
You can also use linq just example, it can be done differnt ways, here the order does not matter, it just check if you files contian the mentioned values:
if (files.Any(e => e.Contains("mdN") && e.Contains("mdNBP") && files.Length == 10))
{
Console.WriteLine("all good");
}
If you have more files, then you can for loop the file array and check against a list of what it should contain.
I have been googling for two days now, but can't figure this out and it seems to be basic.
Within the void OnTick(), I would like to create a variable int a;. Lets say it starts out with no value int a;, then I test condition if a is NULL or || equals 1 like this if (a == NULL || a == 1) which should always return true the first time the if statement runs due to NULL. I then assign a value to the variable a = 0;, so now a should equal 0.
This should trigger the else if(a == 0) the next time OnTick() is called, at this point I assign a = 1; resulting in the if being triggered next time round, etc and infinitum, constantly checking and assigning values switching between 0 and 1.
void OnTick()
int a;
if (PositionsTotal() < 1)
{
if(a == NULL || a == 1)
{
a = 0;
}
else if(a == 0)
{
a = 1;
}
}
I do not know what is going on, but during Testing in Strategy tester, I am getting a long string of numbers which switches between negatives and positives always with the same number -123456789 or 123456789, always 9 digits long.
Or during Debugging from Meta Editor. A random positive 3 digit number which never changes!
So far I have had both 303 and 597.
Beyond frustrating and most likely answered somewhere else.
Just not sure how to phrase the search term.
Thanks for you help.
I think the problem is that you declare your variable a inside the method OnTick, so it starts with an arbitrary value every time you call this method. Try declaring it outside this method.
I am trying to find the schedule variance of all the projects in my Microsoft Project Server. I am using CSOM and C# to access the server, and I do get some details of the projects.
The schedule variation would require Actual Start/ End, Baseline Start/End dates. When I included the start and end date in project query to load to the project context like :
projContext.Load(pubProj, d=> d.StartDate, d=>d.FinishDate, d=>d.Name,
d=>d.CustomFields, d=>d.Description, d=>d.Id,d=>d.Owner,
d=>d.PercentComplete, d=>d.LastPublishedDate, d=>d.ApprovedEnd,
d=>d.ApprovedStart);
I do see that the start and end dates are populating, but the start date varies from what I see in the Project Information on the UI. Also I could not figure out how to get the baseline dates which we would see in the Tracking view of projects.
Please can someone help me here ?
Just figured out that the baseline dates are not properties of the project and is picked from the first main task in the project. So as soon as you have a baseline start and end date on the first task the project baseline dates are reflected in the tracking view .
if (pubProj.Tasks != null && pubProj.Tasks.Count > 0)
{
tempProj.BaseEndDate = pubProj.Tasks[0].BaselineFinish;
tempProj.BaseStartDate = pubProj.Tasks[0].BaselineStart;
tempProj.BaselineDuration = (pubProj.Tasks[0].BaselineDuration != null && pubProj.Tasks[0].BaselineDuration.Length > 2) ? Convert.ToInt16(Convert.ToDecimal(pubProj.Tasks[0].BaselineDuration.Remove(pubProj.Tasks[0].BaselineDuration.Length - 1))) : 0;
tempProj.FinishVariance = (pubProj.Tasks[0].FinishVariance != null && pubProj.Tasks[0].FinishVariance.Length > 2) ? Convert.ToInt16(Convert.ToDouble(pubProj.Tasks[0].FinishVariance.Remove(pubProj.Tasks[0].FinishVariance.Length - 1))) : 0;
}
else
{
tempProj.BaselineDuration = 0;
tempProj.FinishVariance = 0;
}
Edit:
Steps:
Start at target day.
Then move backwards until no events are carried over from another day.
From there, start counting hours, and keep track of carried over hours.
Day cannot last more than ActualDayLength()
Then, once you know that, work your way back to target and then calculate actual occupied hours.
I have tasks that are put on a calendar:
Now let me give this some context:
Each day 'lasts' 7.5 hours here. But I work with a variable called DayHours (which right now is 7.5). (DayHours is also used in Locked Time which Ill describe below).
The goal of this calendar is to schedule 7.5 hour work days for employees.
What I need, is an algorithm that can correctly tell me how many hours are actually occupied in a day.
This seems simple, but is actually quite recursive.
First, a couple of notes. You will notice Case manager, at 14 hours, could be done in 2 days of 7.5 hours with 1 hour left over. It is stretched to 3 days because 1. Schedule, is 5 hours long, and 2. cannot start until the predecessor tasks of the day are complete.
There is also the concept of Locked Time.
In purple is Locked Time. This is a 10 hour block of locked time.
This means, on the 12th, I can only do (7.5 - 7.5) hours of work, and Monday, only (7.5 - 2.5) aswell.
I already have a function to calculate an actual day's available hours to account for this:
public decimal GetActualDayLength(DateTime day, Schedule s)
{
var e = Schedules.GetAllWithElement();
var t = Timeless(day);
var locked = from p in e
where p.EmployeID == s.EmployeID &&
((p.DateTo.Value.Date) >= t &&
Timeless(p.DateFrom.Value) <= t) &&
p.IsLocked
select p;
decimal hrs = 0.0M;
foreach (var c in locked)
{
if (c.Hours.Value <= DaysManager.GetDayHours())
hrs += c.Hours.Value;
else if (Timeless(c.DateTo.Value) != t)
hrs += DaysManager.GetDayHours();
else
{
if (c.Hours.Value % DaysManager.GetDayHours() > 0)
hrs += c.Hours.Value % DaysManager.GetDayHours();
else
hrs += DaysManager.GetDayHours();
}
}
return DaysManager.GetDayHours() - hrs;
}
There is also the concept of carry hours.
Here is an example:
Now let us take Thursday the 18th (The 18th has 1. Case):
To find the number of hours this day has for that employee, we need to first look at the tasks that start, end, or fall within that day.
I don't know how many hours I can do on the 18th because the task ending that day might have had carry hours.
So I go look at Perform unit test's start day. I cant figure that out either because NWDM finishes that day and it might have carry hours.
So now I go evaluate NWDM. Ahh, this one has nothing ending that day, so I know Schedule will take 5 / 7.5 hours available.
So I keep going, adding 7.5 hours each day that I pass.
Then I get to NWDM's last day.
Up until then, I worked 5 + 7.5 + 7.5 + 7.5 hours on it,
So I put in 27.5 hours, so I'll put in (30 - 27.5 = 2.5h) on the 22nd to finish it. So I have 5 hours left to work on Perform Unit Tests.
This means that I will need 1.5h to finish it. Now Case is 1 hour long.
Had case been 7.5 - 1.5 or more, we say the day is full and return DayHours.
Therefore, we are done. The return value is 1.5 + 1 = 2.5.
The function should look a bit like this one:
public decimal GetHours(IEnumerable<Schedule> s, DateTime today)
{
DateTime t = Timeless(today);
decimal hrs = 0;
foreach (Schedule c in s)
{
if (c.Hours.Value <= DaysManager.GetDayHours())
hrs += c.Hours.Value;
else if (Timeless(c.DateTo.Value) != t)
hrs += DaysManager.GetDayHours();
else
{
if (c.Hours.Value % DaysManager.GetDayHours() > 0)
hrs += c.Hours.Value % DaysManager.GetDayHours();
else
hrs += DaysManager.GetDayHours();
}
}
return hrs;
}
To get the events that start, end, or fall within a given day, I use:
public IEnumerable<Schedule> GetAllToday(DateTime date, int employeeID, Schedule current)
{
DateTime t = Timeless(date);
int sid = current == null ? -1 : current.ScheduleID;
var e = Schedules.GetAllWithElement();
return from p in e
where (((Timeless(p.DateTo.Value) >= t &&
Timeless(p.DateFrom.Value) <= t &&
p.EmployeID == employeeID) &&
(p.IsLocked || (Timeless(p.DateFrom.Value) < t &&
(sid == -1 ? true : Timeless(p.DateFrom.Value) < current.DateFrom.Value)) ||
bumpedList.Any(d => d.ScheduleID == p.ScheduleID)) &&
p.ScheduleID != sid) ||
((Timeless(p.DateTo.Value) >= t &&
(Timeless(p.DateFrom.Value) == t || (Timeless(p.DateFrom.Value) < t &&
(sid == -1 ? true : Timeless(p.DateFrom.Value) > current.DateFrom.Value))) &&
p.EmployeID == employeeID) &&
!p.IsLocked &&
!bumpedList.Any(d => d.ScheduleID == p.ScheduleID) &&
p.ScheduleID != sid)) &&
p.ScheduleID != sid
select p;
}
The Schedule has the following relevant fields:
DateFrom
DateTo
Hours
EmployeeID
The Schedule looks something like:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Schedule")]
public partial class Schedule : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _ScheduleID;
private System.Nullable<System.DateTime> _DateFrom;
private System.Nullable<decimal> _Hours;
private System.Nullable<int> _EmployeID;
private System.Nullable<int> _RecurringID;
private System.Nullable<int> _Priority;
private System.Nullable<System.DateTime> _DateTo;
private bool _IsLocked;
private System.Nullable<int> _BumpPriority;
private EntitySet<Case> _Cases;
private EntitySet<Project> _Projects;
private EntitySet<Task> _Tasks;
private EntitySet<Task> _Tasks1;
private EntityRef<Employee> _Employee;
private EntityRef<Recurring> _Recurring;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnScheduleIDChanging(int value);
partial void OnScheduleIDChanged();
partial void OnDateFromChanging(System.Nullable<System.DateTime> value);
partial void OnDateFromChanged();
partial void OnHoursChanging(System.Nullable<decimal> value);
partial void OnHoursChanged();
partial void OnEmployeIDChanging(System.Nullable<int> value);
partial void OnEmployeIDChanged();
partial void OnRecurringIDChanging(System.Nullable<int> value);
partial void OnRecurringIDChanged();
partial void OnPriorityChanging(System.Nullable<int> value);
partial void OnPriorityChanged();
partial void OnDateToChanging(System.Nullable<System.DateTime> value);
partial void OnDateToChanged();
partial void OnIsLockedChanging(bool value);
partial void OnIsLockedChanged();
partial void OnBumpPriorityChanging(System.Nullable<int> value);
partial void OnBumpPriorityChanged();
#endregion
public Schedule()
{
this._Cases = new EntitySet<Case>(new Action<Case>(this.attach_Cases), new Action<Case>(this.detach_Cases));
this._Projects = new EntitySet<Project>(new Action<Project>(this.attach_Projects), new Action<Project>(this.detach_Projects));
this._Tasks = new EntitySet<Task>(new Action<Task>(this.attach_Tasks), new Action<Task>(this.detach_Tasks));
this._Tasks1 = new EntitySet<Task>(new Action<Task>(this.attach_Tasks1), new Action<Task>(this.detach_Tasks1));
this._Employee = default(EntityRef<Employee>);
this._Recurring = default(EntityRef<Recurring>);
OnCreated();
}
}
Could anyone help me with developing an algorithm that can do this?
Even though you question is very complex and not very clearly explained, I'll try to answer it. Or more precisely hint you how you should decompose and solve it (or how I would solved it).
What I need, is an algorithm that can correctly tell me how many hours are actually occupied in a day.
At first I do not see the real problem in case you have DateTo value available for Schedule. Unless it equals to DateFrom + Hours. In such case it does not reflect the real DateTo but somewhat irrelevant value instead.
I will presume any Schedule is defined by starting time DateFrom and duration Hours. DateTo is calculated value and efficiently computing is the real core of the problem.
So I think this function getting available hours in any time range is pretty straightforward. Speaking in pseudo-code:
TimeSpan GetAvailableTime(DateRange range)
var tasks = FindIntersectingTasks(range)
' now the algorithm which finds available hours on given collection
' of tasks
' firstly - we need to determine relevant ranges which intersect
' with given range
var occupiedRanges = New List<DateRange>(tasks.Count)
for each task in tasks
var intersection = range.Intersect(
new DateRange(task.DateFrom, task.DateTo)
)
if Not intersection.IsEmpty
occupiedRanges.Add(intersection)
end
end
' secondly - sort ranges by start so we can easily merge them
ranges.Sort(range => range.DateFrom)
var mergedOccupiedRanges = new List(DateRange)
' thirdly - merge ranges so that we have collection with
' non-overlaping ranges (and also sorted)
for each occupiedRange in occupiedRanges
' range may merge only it there is non-empty intersection
if occupiedRange.CanMerge(mergedOccupiedRanges.Last)
var mergedRange = range.Merge(mergedOccupiedRanges.Last)
mergedOccupiedRanges.RemoveLast()
mergedOccupiedRanges.Add(mergedRange)
end
end
' fourthly - it is simple now to determine available/occupied hours
var timeAvailable = range.Duration
for each mergedRange in mergedOccupiedRanges
timeAvailable -= mergedRange.Duration
end
return timeAvailable
end
IEnumerable<Schedule> FindIntersectingTasks(DateRange range)
return From schedule In allEvents
Where schedule.DateFrom <= range.To
And schedule.DateTo >= range.From
end
You may need some adjustments as the DateTime expects normal 24-hour days.
Like such:
create a list of days with free time.
for each item in the list, add the maximum amount of time available to your task.
If the time needed for your project reaches 0, stop adding blocks.
This does not answer the exact question, but I would suggest simplifying your logic by extending your classes (objects) with some helper methods, e.g. methods/properties that return lists of days occupied.
If you cannot access these classes (i.e. they are not from your code base) - then create new classes and map to those.
Also - the .NET DateTime class has some very useful properties and enums like "DayOfWeek" and "TimeOfDay" that might be useful for you.