Recent Entries 10
- pattern moderate 112d agotimeleft utilityThis utility tells you how much time is left until the time you set before. Setting time: ``` > timeleft set '2017/04/25;15:00:00' ``` Using utility: ``` > timeleft 2 days, 10 hours, 40 minutes, 25 seconds remaining... ``` Code: ``` #include // strcmp #include // fopen, fclose, fprintf, fscanf, sscanf #include // time, mktime #define TIME_PATH "time.txt" static void printRemainingTime(time_t t) { const char *s = "%d days, %d hours, %d minutes, %d seconds remaining...\n"; int days = t / 86400; t -= days * 86400; int hours = t / 3600; t -= hours * 3600; int minutes = t / 60; t -= minutes * 60; int seconds = t; fprintf(stdout, s, days, hours, minutes, seconds); } int main(int argc, char **argv) { int status = 0; if (argc = ref) fprintf(stdout, "It's over!\n"); else printRemainingTime(ref - now); } fclose(f); } } else if (argc == 3 && strcmp(argv[1], "set") == 0) { int Y, M, D, h, m, s; if (sscanf(argv[2], "%d/%d/%d;%d:%d:%d", &Y,&M,&D,&h,&m,&s) != 6) { fprintf(stderr, "Invalid time format\n"); } else if (Y >= 2038) { fprintf(stderr, "Do not plan too far ahead!\n"); } else { struct tm t = { s, m, h, D, M - 1, Y - 1900, -1, -1, -1 }; time_t ut = mktime(&t); if (ut < 0) { fprintf(stderr, "Parsing/range error\n"); status = 1; } else { FILE *f = fopen(TIME_PATH, "w"); if (!f) { fprintf(stderr, "Failed to save time\n"); status = 1; } else { fprintf(f, "%ld", (long) ut); fclose(f); } } } } else { fprintf(stderr, "Usage: "); if (argv[0]) fprintf(stderr, "%s ", argv[0]); fprintf(stderr, "[set YYYY/MM/DD;hh:mm:ss]\n"); } return status; } ```
- pattern minor 112d agoPrint the name of dayHow can I improve this code? It takes a number in the range of [1,7] and prints its corresponding day. ``` #include "stdafx.h" #include // std::cout #include // std::vector #include using std::cin; using std::cout; using std::vector; using std::string; int main() { vector name_day = { "Saturday" ,"Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" }; int n ; cout > n; if (!cin) //If input is wrong. { // reset failbit cin.clear(); cin.ignore(std::numeric_limits::max(), '\n'); } //If the condition is not satisfied . else { for (int i = 0; i <= 6; i++) { if (n-1 == i) { cout << name_day[i] << "\n" << "-----------------------" << "\n";; flag = false; } }//end of for } if (flag) { cout << "Bad Entery !." << "\n" << "-----------------------" << "\n"; } }//end of while system("pause"); } ```
- pattern minor 112d agoCalculate working days and excluding specific dates (Holidays)I read some questions/answers related to functions in C# to calculate the working days; some use an extended code to achieve that. I have a data table with more than 50,000 rows and I required an effective method to calculate this information. I created the following extension in C# that return a number of days (`Integer`), between two dates; excluding dates (Based on a list of `DateTime`) ``` /// Get working days between two dates (Excluding a list of dates - Holidays) /// Current date time /// Finish date time /// List of dates to exclude (Holidays) public static int fwGetWorkingDays(this DateTime dtmCurrent, DateTime dtmFinishDate, List lstExcludedDates) { Func workDay = currentDate => ( currentDate.DayOfWeek == DayOfWeek.Saturday || currentDate.DayOfWeek == DayOfWeek.Sunday || lstExcludedDates.Exists(evalDate => evalDate.Date.Equals(currentDate.Date)) ); return Enumerable.Range(0, 1 + (dtmFinishDate - dtmCurrent).Days).Count(intDay => workDay(dtmCurrent.AddDays(intDay))); } ``` Does there exists some way to improve this method.
- pattern minor 112d agoLeap year check in Haskell, using pattern matching or bind operatorOne of the first Haskell puzzles on http://exercism.io/ is to implement a leap year check. I've done this twice. Using pattern matching: ``` isLeapYear :: Integer -> Bool isLeapYear year | year `mod` 400 == 0 = True | year `mod` 100 == 0 = False | year `mod` 4 == 0 = True | otherwise = False ``` Using the bind operator `>>=`: ``` isLeapYear :: Integer -> Bool isLeapYear year = head $ [(400, True), (100, False), (4, True), (1, False)] >>= check year where check y (interval, isLeap) = [isLeap | y `mod` interval == 0] ``` I'd like to know which implementation is “better“ / more idiomatic in Haskell. I am unsure whether I might have misused a t0o powerful concept in the second try, and the first try might just be more readable.
- pattern minor 112d agoSimple elapsed time counterI've written a simple JavaScript function based off some existing code that takes a specific UNIX time string (in the snippet: `1491685200`). It shows an alert if the specified time is still in the future. When that date has passed, it shows the elapsed days, hours and minutes whenever the function is called in-page. I'm don't have much JavaScript object experience so it works just fine as-is, but I think it can be optimized further before I migrate my other stuff over to ES6. ``` function ElapsedTime () { var nTotalDiff = Math.round((new Date()).getTime() / 1000) - 1491685200; if (nTotalDiff >= 0) { var oDiff = {}; oDiff.days = Math.floor(nTotalDiff / 86400); nTotalDiff -= oDiff.days * 86400; oDiff.hours = Math.floor(nTotalDiff / 3600); nTotalDiff -= oDiff.hours * 3600; oDiff.minutes = Math.floor(nTotalDiff / 60); nTotalDiff -= oDiff.minutes * 60; oDiff.seconds = Math.floor(nTotalDiff); return oDiff; } else { alert('nTotalDiff still not >=0, so must be before the specified date'); } } function TimePassed() { oDiff = ElapsedTime(); if(oDiff) { alert(oDiff.days + 'd ' + oDiff.hours + 'h ' + oDiff.minutes + 'm '); } } // document.getElementById('counter').addEventListener('click', TimePassed, false); ```
- pattern minor 112d agoPython library for calculating next and previous time of the cron-like scheduled taskI needed a task system that would let me define a cron-like rule in the database, and be able to find the next and the previous time when the task was and is supposed to happen. I am running a web application, so ways like run a scheduled and check for every minute, or other ways around does not work for me, so I had to come up with an algorithm. It also should support more complicated jobs, like: Example 1: Task runs every Tuesday at 3:00pm, find the previous execution time Example 2: next presidential election day in the USA (which is, "the Tuesday next after the first Monday in the month of November"), find the next execution time (November, 3, 2020). This was not trivial. Here is the result: Github page with tests, documentation and more examples Here is the example of how to find the next presidential election day (with a bit of cheating, because we find the first Monday of November and take the next day after it). ``` from scheduledtask import ScheduledTask # Finding the next presidential election day in the USA task = ScheduledTask(minutes=[0], hours=[0], days_of_week=[0], days_of_week_num=[0], months=[11], years=range(1848, 9999, 4)) print(task.get_next_time() + timedelta(days=1)) print(task.get_previous_time() + timedelta(days=1)) ``` The algorithm supports multiple strategies (using days_of_month and days_of_week together is not supported). You can define every term (minutes, hours, days, days_of_week, days_of_week_num, weeks, months, years) as a list of values, range (supports step), or None (which is like a star * in cron). So, here is how the algorithm works in a nutshell: - Takes the highest term (years) - Figures the next year that matches the rule - If it does, it switches to the next term (month), tries to find the next matching value. If the value is found, it switches to the next term (days), if there is no possible values, it switches back to the year, finds the next possible year that matches the rule, and
- pattern minor 112d agoFinding consecutive days in an array of datesThe problem: How to get the largest number of consecutive days from an array of unknown number of Date objects, by taking into account days only like 4th of April, 5th of April and so on. Example input data: ``` let calendar = Calendar.current let x1 = Date() let x2 = calendar.date(byAdding: .day, value: 1, to: x1)! let x3 = calendar.date(byAdding: .day, value: 1, to: x2)! let x4 = calendar.date(byAdding: .day, value: 1, to: x3)! let x5 = calendar.date(byAdding: .day, value: 1, to: x4)! let x6 = calendar.date(byAdding: .day, value: 1, to: x5)! let x7 = calendar.date(byAdding: .hour, value: 1, to: x4)! let x8 = calendar.date(byAdding: .hour, value: 2, to: x4)! let x9 = calendar.date(byAdding: .hour, value: 3, to: x2)! let x10 = calendar.date(byAdding: .hour, value: 4, to: x2)! var dates = [Date]() dates.append(x1) dates.append(x5) dates.append(x2) dates.append(x3) dates.append(x4) dates.append(x6) dates.append(x7) dates.append(x8) dates.append(x9) dates.append(x10) ``` Expected result from the sample data: 6 consecutive days How this solution could be improved? Solution: ``` dates.sort(by: = aDayInSeconds && nextDate.timeIntervalSince(date) < twoDaysInSeconds { dateIndex += 1 nextDateIndex += 1 consecutiveDaysCount += 1 } else { break } } while (i < newDates.count - 1) print(consecutiveDaysCount) ```
- snippet minor 112d agoCreate and open a file to take lecture notes depending on day and timeI am just wondering what, if any, more elegant ways might exist to write a script to accomplish the task that the script below accomplishes. The script works, so I don't need it to be debugged, but I want to learn more. Other commands to be used, other ways of structuring it, etc. I have taken it through shellcheck. Yesterday I decided to try my hand at a shell script that would create and open a file to take notes for each of my classes in the folder designated for notes from that class. It was pretty satisfying to do; I started with basically no knowledge and over the course of an hour or two I went from a script that would prompt me to enter the class and the desired file title (`read Class read Title if [[ $Class = "X]] then touch /path/"$Title".docx` etc) to something that would just create the file in the right place based on the time/date the command is invoked, since the title is always today's date anyhow. Again, it works. I just know that there must be more ways to skin this cat and I was wondering what those might be. The version below has been revised once after input from some good samaritans. Also, FWIW, this is running on OS X Sierra. ``` #!/bin/bash read date hour day month <<< $(date +"%-d %-H %a %B") if [[ $hour -lt 11 && $day = "Tue" ]] || [[ $hour -lt 11 && $day = "Thu" ]]; then dir="/path/to/first" elif [[ $hour -gt 12 && $hour -lt 15 && $day = "Tue" ]] || [[ $hour -gt 12 && $hour -lt 15 && $day = "Thu" ]]; then dir="path/to/second" elif [[ $hour -ge 16 && $hour -le 17 && $day = "Wed" ]]; then dir="/path/to/third/" else echo "I am of no use to you right now" exit 1 fi file="$dir/$month $date".docx touch "$file" open "$file" killall Terminal ```
- pattern minor 112d agoMatching a time interval using regexWhat I needed to do was check whether a given string matches a certain pattern. The pattern is this: ``` 00:00:00,000 --> 00:00:00,000 ``` Things to keep in mind: The 0s can be numbers from 0 to 9. The pattern must be alone in a single line; the line has to only consist of the pattern. I came up with this: ``` "^(\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d) --> (\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d)" ``` I tested it a few times and strings that respect the pattern return `true`, the ones that don't, return `false`, as they should. Here's a test case: ``` import java.util.regex.Pattern; public class TestCaseRegex { public static void main(String[] args) { //will return true String testOne = "00:01:23,846 --> 00:01:26,212"; //will return false, there's a letter where a number should be String testTwo = "00:01:23,84a --> 00:01:21,221"; //will return true String testThree = "00:05:54,846 --> 00:01:16,450"; //will return false. The string doesn't match the format. String testFour = "00:05:54,6 --> 00:0116,450"; System.out.println(patternMatch(testOne)); System.out.println(patternMatch(testTwo)); System.out.println(patternMatch(testThree)); System.out.println(patternMatch(testFour)); } public static boolean patternMatch(String str) { Pattern p = Pattern.compile("^(\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d) " + "--> (\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d)"); return p.matcher(str).matches(); } } ``` As I'm very new to regex, I'm wondering if this is the most efficient/correct way to accomplish this.
- pattern minor 112d agoSimple calendar in PHPI made a simple calendar in PHP 7.0, could anyone help with simplification? Any advice appreciated. It works, but I totally believe it can be improved. I am a beginner. ``` " selected = "selected"> = 2000; $year--) { $years .= $year . " "; } return $years; } $years = explode (" ", getYear()); foreach ($years as $number => $chose_year) { ?> " selected = "selected" selected ='selected'> "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); foreach($months as $number2 => $chose_month) { ?> " selected = "selected"> Mon TueWedThuFriSatSun "; } else if ($i != 1) echo "\n"; echo ""; if (($chosen_year == date('Y')) and ($chosen_month == date('n')) and date('j') == $array_of_days[$i]) { echo '' .$array_of_days[$i]. ''; } else { echo $array_of_days[$i]; } if (($i % 7 == 0) || ($i == $lastDay)) { $DayToBrake = $i; echo ""; } $i++; } echo "\n"; ?> '." Is"." ".$months[$m]." ". date('Y').'';} ?> ```