Schema for opening hours MongoDB - mongodb

How would you store opening hours on a document, say a Library, in mongoDB, that's easily queryable with Mongoid? I've read this thread, but I'm not sure how it would be implemented with my needs.
I need to have the ability to add multiple opening and closing times per day since the Library should be able to close some hours during the day and then reopen.
I need to be able to add exceptions to these opening hours. For example; close monday on a specific date.
Please share some best practices and experiences on how one could do this the most flexible way.

Thank you, Yeggeps, for the list of requirements.
This is a revised answer based on your requirements. Of course there is no holy grail to schemae, but I would like to motivate my answer before revision (keeping a flat structure is easy to query and maintain) with some sample data + queries based on your requirement list. I reiterate, I am not saying this is the best solution, but it is a solution which is straightforward to query and easy to maintain (imho).
Code is a little quick and dirty, apologies. The data:
[
# library "lib1" open on wednesdays from 8:00 until 17:00
{"lib_id" => "lib1", "type" => "hours", "opening" => 800, "closing" => 1700, "day_of_week" => 3},
# library "lib1" open on wednesdays from 19:00 until 22:15
{"lib_id" => "lib1", "type" => "hours", "opening" => 1900, "closing" => 2215, "day_of_week" => 3},
{"lib_id" => "lib1", "type" => "hours", "opening" => 800, "closing" => 1700, "day_of_week" => 4},
{"lib_id" => "lib2", "type" => "hours", "opening" => 1100, "closing" => 1700, "day_of_week" => 3},
{"lib_id" => "lib2", "type" => "hours", "opening" => 1400, "closing" => 1700, "day_of_week" => 4},
{"lib_id" => "lib2", "type" => "hours", "opening" => 1900, "closing" => 2100, "day_of_week" => 4},
# library lib1 closed on wednesday december 7th 2011
{"lib_id" => "lib1", "type" => "closed_on", "reason" => "Rearranging the shelves", "closed_date" => Time.utc(2011, 12, 8)},
{"lib_id" => "lib2", "type" => "closed_on", "reason" => "We are closed for the holidays", "closed_date" => Time.utc(2011, 12, 7)}
].each do |schedule|
coll.save(schedule)
end
Show opening hours and exceptional dates separately:
# List all the library id's distinctly
coll.distinct("lib_id").each do |lib_id|
puts "\nLibrary #{lib_id} opening hours:\n--- "
# I need to be able to show the opening hours in correlation with the Library
# Find all the opening hour information for current library
coll.find({"lib_id" => lib_id, "type" => "hours"}).each do |schedule|
puts " #{Date::DAYNAMES[schedule["day_of_week"]]}s: #{schedule["opening"]} - #{schedule["closing"]}" if schedule["type"] == "hours"
end
# I need to show an indication if it's open or closed in correlation with the Library.
puts "This library will be closed on: "
# Find all the exceptions for current lib_id -- introduce a time-period restriction using Date.utc (...)
coll.find({"lib_id" => lib_id, "type" => "closed_on"}).each do |closed|
puts " #{closed["closed_date"].strftime("%a %B%e, %Y")}: #{closed["reason"]}"
end
end
Which libraries are open today?
# I need to be able to query on what's open right now or some time in the future with minute granularity
# here I'll also need to be able to exclude the Librarys that has added exceptions for the given time/day
puts "---"
qtime = (Time.now.hour * 100) + Time.now.min # minute granularity
qwday = Time.now.wday # this example only shows today
qclosed = Time.utc(Time.now.year, Time.now.mon, Time.now.mday)
# Query for all library ids which have opening times for this weekday, at this hour (+minutes)
coll.find({"opening" => {"$lte" => qtime}, "closing" => {"$gte" => qtime}, "day_of_week" => qwday}, {:fields => "lib_id"}).each do |lib|
# Check whether current library has an exception for this specific day
closed = coll.find_one({"lib_id" => lib["lib_id"], "closed_date" => qclosed})
if closed
# If an exception record was encountered, print the reason
puts "Library #{lib["lib_id"]} is normally open right now, but is now closed: '#{closed["reason"]}'"
else
# Else: the library is open
puts "Library #{lib["lib_id"]} is open right now! (#{Time.now.strftime("%a %B%e %Y, %H:%M")})"
end
end
Produces output as follows:
Library lib1 opening hours:
---
Wednesdays: 800 - 1700
Wednesdays: 1900 - 2215
Thursdays: 800 - 1700
This library will be closed on:
Thu December 8, 2011: Rearranging the shelves
Library lib2 opening hours:
---
Wednesdays: 1100 - 1700
Thursdays: 1400 - 1700
Thursdays: 1900 - 2100
This library will be closed on:
Wed December 7, 2011: We are closed for the holidays
---
Library lib1 is open right now! (Wed December 7 2011, 13:12)
Library lib2 is normally open right now, but is now closed: 'We are closed for the holidays'
Admittedly, the downside to my proposed solution is that it does not capture every requirement in one query.

It's difficult to provide a good solution without knowing the exact queries you'd like to run. For instance, if you're asking "what businesses are open now (5:32 PM, 5/11/2011)?" you'd want a different schema than if you were asking "when is business XYZ open next?"
In the first case, you'll want to be able to efficiently pose range queries on the current hour, minute, and day -- as well as negative queries on an exception list. Alternatively, you can handle exceptions in client code.
Last, what is the level of granularity needed? What is the smallest exception possible? Minutes? Hours? Days?
I'd post the above as a comment but I just created a user account. With additional information, I'll update this to provide an actual answer.

Related

How to extend a Indicator COT Data Line

Unfortunately, the commodity trade market is closed at the weekend. The new COT data will come on Saturday. The script therefore only shows the old data until Monday when the markets open again. But I would like to analyze the markets at the weekend. So how can I see the COT data in the indicator already at the weekend? I thought that it would be possible if we extend the indicator line by one point as an extension or as a forecast which are downloading the new data into the future without priceaction.
'qticker = syminfo.root == 'GE'
comm_lg = request.security(legacy_cot + '4', 'W', close)
comm_sh = request.security(legacy_cot + '5', 'W', close)
comm_net = comm_lg - comm_sh
plot(comm_net, color=color.new(color.red, 0), title='Commercials Net', style=plot.style_line, linewidth=2)`

Moodle eeror to write in database

I am running moodle on kubernetes with statefulsets of databases.
Moodle version : $version = 2018120303.14; // 20181203 = branching date YYYYMMDD - do not modify!
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
$release = '3.6.3+ (Build: 20190501)'; // Human-friendly version name
$branch = '36'; // This version's branch.
$maturity = MATURITY_STABLE; // This version's maturity level.
Error writing to database
Other information about this error
Debug info: Duplicate entry '1-12345678900' for key 'mdl_user_mneuse_uix'
INSERT INTO mdl_user (city,auth,policyagreed,idnumber,username,password,firstname,lastname,email,lang,confirmed,lastip,timecreated,timemodified,mnethostid) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
[array (
0 => '',
1 => 'wp2moodle',
2 => 1,
3 => '1584',
4 => '12345678900',
5 => 'a803bc70a48ce4568a9e85f7e1e30c58',
6 => 'Pedro',
7 => 'Marinelli',
8 => 'pedromarinelli#email.com',
9 => 'pt_br',
10 => 1,
11 => '177.192.193.143',
12 => 1537303059,
13 => 1537303059,
14 => '1',
)]
Error code: dmlwriteexception
Stack trace: line 489 of /lib/dml/moodle_database.php:
dml_write_exception thrown line 1329 of
/lib/dml/mysqli_native_moodle_database.php: call to
moodle_database->query_end() line 1375 of
/lib/dml/mysqli_native_moodle_database.php: call to
mysqli_native_moodle_database->insert_record_raw() line 232 of
/auth/wp2moodle/login.php: call to
mysqli_native_moodle_database->insert_record()
You are trying to add duplicate username into the database. Please check that, username your inserting has already existed.
Run this command which requires for moodle(3.1 and new version)
php admin/cli/mysql_collation.php --collation=utf8mb4_unicode_ci

Telerik Datetime picker- Time shows 30 minutes span

#Html.Telerik().DateTimePickerFor(model => model.DepartureTime).Value(Model.DepartureTime > DateTime.MinValue ? Model.DepartureTime : DateTime.Today).ClientEvents(events => events.OnChange("OnChangeDatePicker"))
In Telerik datetime picker, The Time is 30 minutes span. Like 9, 9.30, 10, 10.30 etc. Is there a way to select time For each minutes eg: 9.00, 9.01,9.02 etc..?
Here is the documentation for what you are looking for:
http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-datetimepicker-configuration.html#Interval
Basically you want to set the Interval configuration option to 1 such as.
#Html.Telerik().DateTimePickerFor(model => model.DepartureTime)
.Interval(1)
.Value(Model.DepartureTime > DateTime.MinValue ? Model.DepartureTime : DateTime.Today)
.ClientEvents(events => events.OnChange("OnChangeDatePicker"))
Now I havent tested this exact scenario but the documentation speaks for itself.
Cheers, Nico

perl Data::Dumper to extract key values

I have some perl code which I've written to get weather data/alerts from NOAA.
My code is pretty simple:
use Weather::NOAA::Alert;
use Data::Dumper;
$alert = Weather::NOAA::Alert->new(['TXC301']);
$events = $alert->get_events();
$alert->poll_events();
print Dumper($events);
# #url = (keys %{$VAR1->{'TXC301'}});
# $url = $VAR1->{'TXC301'};
$url = $events->{'TXC301'};
print "URL is $url\n";
# $expires= $events->{'TXC301'}->{$url}->{'expires'};
$expires= $events->{'TXC301'}->{'http://alerts.weather.gov/cap/wwacapget.php?x=TX12516CBE9400.FloodWarning.12516CC068C0TX.MAFFLWMAF.f21e7ce7cf8e930ab73a110c4d912576'}->{'expires'};
print "Expires: $expires\n";
The output:
$VAR1 = {
'TXC301' => {
'http://alerts.weather.gov/cap/wwacapget.php?x=TX12516CBE9400.FloodWarning.12516CC068C0TX.MAFFLWMAF.f21e7ce7cf8e930ab73a110c4d912576' => {
'certainty' => 'Likely',
'senderName' => 'NWS Midland-Odessa (Western Texas and Southeastern New Mexico)',
'urgency' => 'Expected',
'instruction' => 'A FLOOD WARNING MEANS THAT FLOODING IS IMMINENT OR HAS BEEN REPORTED.
STREAM RISES WILL BE SLOW AND FLASH FLOODING IS NOT EXPECTED.
HOWEVER... ALL INTERESTED PARTIES SHOULD TAKE NECESSARY PRECAUTIONS
IMMEDIATELY.
DO NOT DRIVE YOUR VEHICLE INTO AREAS WHERE THE WATER COVERS THE
ROADWAY. THE WATER DEPTH MAY BE TOO GREAT TO ALLOW YOUR CAR TO CROSS
SAFELY.',
'description' => 'THE NATIONAL WEATHER SERVICE IN MIDLAND HAS ISSUED A
FLOOD WARNING FOR...
SOUTHWESTERN LOVING COUNTY IN WEST TEXAS...
NORTHWESTERN WARD COUNTY IN WEST TEXAS...
NORTH CENTRAL REEVES COUNTY IN SOUTHWEST TEXAS...
UNTIL 300 PM CDT FRIDAY
AT 259 AM CDT...ROADS REMAIN CLOSED NEAR THE PECOS RIVER BETWEEN
RED BLUFF AND INTERSTATE 20 BECAUSE OF ELEVATED RIVER LEVELS DUE
TO RECENT RAINS. FLOODING WILL ALSO IMPACT THE CITY OF PECOS.',
'event' => 'Flood Warning',
'delete' => 0,
'category' => 'Met',
'severity' => 'Moderate',
'effective' => '2014-09-26T03:00:00-05:00',
'headline' => 'Flood Warning issued September 26 at 3:00AM CDT until September 26 at 3:00PM CDT by NWS Midland-Odessa',
'expires' => '2014-09-26T15:00:00-05:00'
}
}
};
URL is HASH(0x26384c0)
Expires: 2014-09-26T15:00:00-05:00
The TXC301 is a report identifier.
The output of the script will print all the values fetched from NOAA.
The goal is to store/return the 'expires' value.
I have lines commented out, which were attempts at achieving my goal.
The problem I'm having is getting the $url variable. I need this value in order to get my $expires value. The 2nd to last line in my code will correctly get the $expires value, but in order to do this I needed to hard code the URL into the line.
I'm trying to get the line directly above that (3rd to last) to work:
$expires= $events->{'TXC301'}->{$url}->{'expires'};
But this depends on the $url value to be stored.
I can't seem to figure out how to get the $url value.
My guesses:
#url = (keys %{$VAR1->{'TXC301'}});
$url = $VAR1->{'TXC301'};
$url = $events->{'TXC301'};
None of which work.
Any help would be great.
Thanks!
Regards,
Joseph Spenner
Given there is only one value for that level of hash ref, you could use values:
print +( values %{ $VAR1->{TXC301} } )[0]{expires}, "\n";
Outputs:
2014-09-26T15:00:00-05:00
Alternative to Data::Dumper
Also, on a separate issue, I would like to recommend the use of Data::Dump over the core library Data::Dumper.
The default settings and features for this alternative give superior output and enable one to analyze a data structure a lot quicker as demonstrated below:
$VAR1 = {
'TXC301' => {
'http://alerts.weather.gov/cap/wwacapget.php?x=TX12516CBE9400.FloodWarning.12516CC068C0TX.MAFFLWMAF.f21e7ce7cf8e930ab73a110c4d912576' => {
'certainty' => 'Likely',
'senderName' => 'NWS Midland-Odessa (Western Texas and Southeastern New Mexico)',
'urgency' => 'Expected',
'instruction' => 'A FLOOD WARNING MEANS THAT FLOODING IS IMMINENT OR HAS BEEN REPORTED.
STREAM RISES WILL BE SLOW AND FLASH FLOODING IS NOT EXPECTED.
HOWEVER... ALL INTERESTED PARTIES SHOULD TAKE NECESSARY PRECAUTIONS
IMMEDIATELY.
DO NOT DRIVE YOUR VEHICLE INTO AREAS WHERE THE WATER COVERS THE
ROADWAY. THE WATER DEPTH MAY BE TOO GREAT TO ALLOW YOUR CAR TO CROSS
SAFELY.',
'description' => 'THE NATIONAL WEATHER SERVICE IN MIDLAND HAS ISSUED A
FLOOD WARNING FOR...
SOUTHWESTERN LOVING COUNTY IN WEST TEXAS...
NORTHWESTERN WARD COUNTY IN WEST TEXAS...
NORTH CENTRAL REEVES COUNTY IN SOUTHWEST TEXAS...
UNTIL 300 PM CDT FRIDAY
AT 259 AM CDT...ROADS REMAIN CLOSED NEAR THE PECOS RIVER BETWEEN
RED BLUFF AND INTERSTATE 20 BECAUSE OF ELEVATED RIVER LEVELS DUE
TO RECENT RAINS. FLOODING WILL ALSO IMPACT THE CITY OF PECOS.',
'event' => 'Flood Warning',
'delete' => 0,
'category' => 'Met',
'severity' => 'Moderate',
'effective' => '2014-09-26T03:00:00-05:00',
'headline' => 'Flood Warning issued September 26 at 3:00AM CDT until September 26 at 3:00PM CDT by NWS Midland-Odessa',
'expires' => '2014-09-26T15:00:00-05:00'
}
}
};
use Data::Dump;
dd $VAR1;
Outputs:
{
TXC301 => {
"http://alerts.weather.gov/cap/wwacapget.php?x=TX12516CBE9400.FloodWarning.12516CC068C0TX.MAFFLWMAF.f21e7ce7cf8e930ab73a110c4d912576" => {
category => "Met",
certainty => "Likely",
delete => 0,
description => "THE NATIONAL WEATHER SERVICE IN MIDLAND HAS ISSUED A\n FLOOD WARNING FOR...\nSOUTHWESTERN LOVING COUNTY IN WEST TEXAS...\nNORTHWESTERN WARD COUNTY IN WEST TEXAS...\nNORTH CENTRAL REEVES COUNTY IN SOUTHWEST TEXAS...\n UNTIL 300 PM CDT FRIDAY\n AT 259 AM CDT...ROADS REMAIN CLOSED NEAR THE PECOS RIVER BETWEEN\nRED BLUFF AND INTERSTATE 20 BECAUSE OF ELEVATED RIVER LEVELS DUE\nTO RECENT RAINS. FLOODING WILL ALSO IMPACT THE CITY OF PECOS.",
effective => "2014-09-26T03:00:00-05:00",
event => "Flood Warning",
expires => "2014-09-26T15:00:00-05:00",
headline => "Flood Warning issued September 26 at 3:00AM CDT until September 26 at 3:00PM CDT by NWS Midland-Odessa",
instruction => "A FLOOD WARNING MEANS THAT FLOODING IS IMMINENT OR HAS BEEN REPORTED.\nSTREAM RISES WILL BE SLOW AND FLASH FLOODING IS NOT EXPECTED.\nHOWEVER... ALL INTERESTED PARTIES SHOULD TAKE NECESSARY PRECAUTIONS\nIMMEDIATELY.\nDO NOT DRIVE YOUR VEHICLE INTO AREAS WHERE THE WATER COVERS THE\nROADWAY. THE WATER DEPTH MAY BE TOO GREAT TO ALLOW YOUR CAR TO CROSS\nSAFELY.",
senderName => "NWS Midland-Odessa (Western Texas and Southeastern New Mexico)",
severity => "Moderate",
urgency => "Expected",
},
},
}
Ok, I was able to piece something together which worked:
use Weather::NOAA::Alert;
use Data::Dumper;
$alert = Weather::NOAA::Alert->new(['TXC301']);
$events = $alert->get_events();
$alert->poll_events();
Dumper($events);
print +( values %{ $events->{TXC301} } )[0]{expires}, "\n";
By changing $VAR1 to $events in the last line, I got rid of the error and got the exact output I needed.
Thanks for all the quick replies!
Regards,
Joseph Spenner

Perl Tk::Date - toggle by week

I am in the process of writing a GUI which will monitor if various measurements have been made on a weekly basis. I have written various other GUIs for updating measurements results each day onto a database. These GUIs use Tk::Date datewidget that allows me to toggle by days
my $datewidget = $f_filter->Date(-choices=>'today', -datefmt=>'%2d %2m %4y',
-fields=>'date', -varfmt=>'datehash',
-monthmenu=>1, -allarrows=>1,
-value=>'now', -command=>\&populate)->pack(-side=>'left');
This lets me use the up and down arrows to increment/decrement days, change months and year.
What I desire to do in the weekly GUI is have an up and down arrow that will toggle by week only. Eg this week would be 'Mon Nov 4 - Fri Nov 8', next week 'Mon Nov 11 to Fri Nov 15'
I would like to be able to go forwards and backwards several years.
Is there a simple way to do this in perl-Tk::Date or Date::Entry?
Tk::Date and Tk::DateEntry cannot do this out of the box. With Tk::Date, I can propose the following approach:
use -varfmt => 'unixtime' instead of datehash, because the latter does not work well with the ->configure(-value => ...) call used later
set -editable=>0 to remove all arrow buttons created by Tk::Date
create the inc/dec buttons yourself
and make the date calculations using DateTime (see the incweek subroutine here)
Something like the following could work:
use strict;
use Tk;
use Tk::Date;
my $mw = tkinit;
my $datewidget = $mw->Date(-choices=>'today', -datefmt=>'%2d %2m %4y',
-fields=>'date', -varfmt=>'unixtime',
-editable=>0,
-monthmenu=>1,
-value=>'now',
-command=>sub { warn "populate #_" })->pack(-side=>'left');
my $arrowframe = $mw->Frame->pack(-side => 'left');
{
no warnings 'once'; # because of INCBITMAP/DECBITMAP
$arrowframe->FireButton(-bitmap => $Tk::FireButton::INCBITMAP, -command => sub { incweek(+1) })->pack(-side => 'top');
$arrowframe->FireButton(-bitmap => $Tk::FireButton::DECBITMAP, -command => sub { incweek(-1) })->pack(-side => 'top');
}
MainLoop;
sub incweek {
my($inc) = #_;
use DateTime;
my $epoch = $datewidget->get;
my $dt = DateTime->from_epoch(epoch => $epoch);
$dt = $dt->add(weeks => $inc);
$datewidget->configure(-value => $dt->epoch);
}
__END__
Note that $datewidget->get returrns now the epoch time, but using DateTime you can easily convert this into y/m/d values.