14

Each of your if blocks does the same thing, but with different inputs. if sun == 1: first_sunday = np.busday_offset(start, 0, roll='forward', weekmask='Sun') last_sunday = np.busday_offset(end, 0, roll='preceding', weekmask='Sun') sun_count = np.busday_count(first_sunday, last_sunday, weekmask='Sun') + 1 for i in trange(...


9

Without seeing the rest of your code it's difficult to say how this is used, but I think your function has conflated logic and formatting, and formatting is being done too soon. You should hold onto real date information right up until the edges of your program when that's possible. The following demonstrates one way of keeping dates and moving them to the ...


9

Your DayOnWeek object is mutable, allowing you to set the .day_number property. For such a simple object is not a good idea. An immutable object is better. There are exactly 7 days of the week. For a one-of-seven choice, the go-to data-storage structure is an Enum. For example: from enum import Enum class DayOfWeek(Enum): Sunday = 1 Monday = 2 ...


8

Overall, it looks fine. I probably would've written it a little differently, and I'll explain the differences. import datetime def get_current_quarters(): """A function that returns an array with all the actual year quarters """ current_year = datetime.date.today().year quarter_values = ["31/03/","30/06/...


8

It's great that you're thinking about classes, but you've misapplied them. This is a very simple problem that does not call for object-oriented code. The calendar module already has the name sequence, so you really only need a validation loop and a small output routine: from calendar import day_name def request_day_number() -> int: while True: ...


6

datetime.date has a .replace() method that returns a copy with some values changed. This can be used to get the date 18 years ago. end_date = date.today() start_date = end_date.replace(year=end_date.year - 18) datetime.date.toordinal returns an integer corresponding to the date. The ordinals for the start and stop date can be used in random.randint() to ...


6

Interesting start to what seems a very useful utility. Future improvements could include console calendar-style formatting for much easier reading, or a desktop or web UI. Your YYYY,MM,DD format is unusual. A slight adjustment to use hyphens instead of commas will bring it in line with ISO 8601 which will be more familiar, I think, to users. Or if you don't ...


5

Use clock's native resolution everywhere If you cast time points and durations to something with a different resolution than that of clock, you risk losing precision. So for all internal state of your classes, I would definitely store everything as clock::duration and clock::time_point types. You might consider keeping the template parameter to ensure the ...


5

public LocalDateTime parseDate(String dateString) { Your formatting choices are partly odd, if in doubt, stick to the IDE default formatting (or the formatting of the project. checkArgument(!Strings.isNullOrEmpty(dateString), "Date [" + dateString + "] is empty of NULL!"); Split it into two checks, one for null and one for empty, ...


5

To me it looks fine, other than it makes me scroll the code to read it. On this ground I agree with Sam, that line ought to be shortened. To do so I would use the fact that you don't need to convert mysql format dates to compare them remove excessive bracing use De Morgan's law to invert the condition and get this function dates_in_range( string $...


5

The main issue I see with the code is the repetitive if/elses at the bottom. Repetitive code is annoying to write, takes some time to read, and is often a bit more likely to have bugs than DRY code. To identify the parking fee, I'd make an array of ranges and their associated fees, then find the appropriate range: const getCost = (totalHoursParked) => { ...


4

I think the answer to your question will depend largely on the operating environment of your Python program. The actual language (Python) is not really relevant here, as it does nothing special in this regard. File management is the responsibility of the OS, and Python, like most programming languages only provides an interface to the underlying OS APIs. ...


4

You seem to ignore two facts. The client clock can be out of sync with the server clock. The transport of the request from client to server takes more then zero time. Both these cases mean that no matter how hard you try on the client side, there is always a chance that the server will evaluate the token as expired during its processing. What you should ...


4

The first two things I noticed when looking at your code were: 1: It's unclear why you use a function expression, with const, for the main function, and then use function declarations, with function, for the other functions? 2: Obviously there's a lot of repetition in your code. The string 'Your parking fee is' is repeated ten times. That is not very DRY. ...


4

The function seems okay. In Javascript one could use the method Array.every(), but as this StackOverflow question illustrates there isn't really an equivalent method or functional approach in PHP that will stop the loop as soon as one element does not meet the requirement. You might consider adhering to the PSR PHP Coding standards - especially PSR 12. PSR-...


4

"A mess" is the first thing that comes to my mind. Why don't you just use a loop over the various formats? If you want to introduce a special guard (like the string length), create a parser objcet, which implements an appropriate check. Something along the lines of interface DateParser { boolean isApplicable(String in); LocalDateTime parse(...


4

upggift1.cc Please don't do this: using namespace std; We have namespaces for good reason, and it's a bad habit to throw away their benefits like that. Date d1; bool create_date_again = true; int temp_date[3]; char garbage; This looks like something written by a (quite old) C programmer. Prefer to declare variables where they can be initialised, rather ...


4

As you will be able to see from your provided sample input, your code does not produce the intended result. Here is a minimal example: dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-05'), 2) stride = (dates[1] - dates[0]) result = np.arange(np.datetime64(dates[0]), np.datetime64(dates[-1] + stride)) print(dates) # > ['2018-02-01' ...


4

Modern Python has so many conveniences for creating simple data objects (namedtuple, dataclass, and the excellent attrs library), that it's usually a mistake to structure your internal data using ordinary dicts, lists, or tuples. These simple data objects not only clean up the code from a readability perspective (as shown in multiple places below) but also ...


4

There's some issues: when a new instance of your class is initialised, it has a state that's not supported by the rest of the code (i.e. a _day_number of 0, with no matching name) The name DayOnWeek isn't very descriptive, why not just Weekday? Why not implement the category property as a property that decides the category based on the value of _day_number ...


4

modular: use if __name__ == "__main__" guard to execute code, to allow imports use functions to encapsulate the logic and prevent unnecessary globals use class(es) to encapsulate the state - use constants as globals or class variables - the whole # Starting variables block consider naming the file __main__.py and adding a setup.py thus after ...


3

If the goal is to compute a date 10,000 days from now, I would strongly recommend using the std::chrono facilities. If you do, the code would be only a few lines long: #include <iostream> #include <iomanip> #include <ctime> #include <chrono> int main() { using namespace std::chrono; auto later{system_clock::to_time_t(...


3

It isn't completely clear what type the inputs would have from the question, since they just say "timestamp," but the simplest form of timestamp is Unix style timestamp you get from Date.now(). It's just the number of milliseconds since January 1 1970 00:00:00, and the timezone is always UTC. It's usually what programs should operate on, because it ...


3

There are a few small niceties that you can add. long = pd.DataFrame(columns={'bene_id', 'day','date'}) cols_to_order = ['bene_id', 'day','date'] should reuse the list: cols_to_order = ['bene_id', 'day','date'] long = pd.DataFrame(columns=set(cols_to_order)) This: cols_to_order + (long.columns.drop(cols_to_order).tolist()) can drop the outer parens, since ...


3

Welcome to Code Review! As I already mentioned in comments, epoch values can be treated as normal numerals, without having to involve momentjs or other external libraries. In js, you can get current epoch value in milliseconds accuracy using Date.now(). The value in token is with seconds accuracy. It is only a factor of 1000. Rewrite /** The token object ...


3

I think it is slow because your periods_breakdown is gigantic, and to fill each cell you have to compute its value. But what you compute is whether each individual visit overlapped with each other visit, which is overkill. If what you want is to know when there is two visits (or more) overlapping, but don't need to know which specific ones, you can simply ...


3

Missing error checks t = time(NULL); if (t == -1) handle_error_gracefully(); tmorig = localtime(&t); if (tmorig == NULL) handle_error_gracefully(); Simplify Value check not needed. // if ((errno == ERANGE && (n == LONG_MAX || n == LONG_MIN)) || (n > INT_MAX || n < 0)) if ((errno == ERANGE) || (n > INT_MAX || n < 0)) goto error; ...


2

I know this is a part of an exercise, but it feels like a lot of wheel reinventing where you can leverage builtin Python capabilities for date validation: from datetime import date >>> date(2020, 2, 29) # leap year date works datetime.date(2020, 2, 29) >>> date(2002, 2, 29) # non-leap year will raise ValueError ValueError: day is out of ...


2

I suggest some minor improvements in the regular expression: make sure that the same separator is used between day and month and between month and year with a backreference (?P=sep), replace numbered capture groups with named, and make non-needed groups, if there wer any, non-capturing with ?:. Consequently, finditer and groupdict are used, and the day is ...


2

I would suggest moving this method into the TimeSpan class. Let a TimeSpan tell you about its overlaps. Don't interrogate it for internal details and then figure it out for yourself. Private helper methods will make the compareTo calls more readable. Assorted other thoughts: A checked exception is probably not right here. I'd suggest preferring ...


Only top voted, non community-wiki answers of a minimum length are eligible