Skip to content

Commit

Permalink
📝 Sundry updates per review
Browse files Browse the repository at this point in the history
  • Loading branch information
akrherz committed Dec 27, 2024
1 parent fde9377 commit db40e49
Show file tree
Hide file tree
Showing 30 changed files with 130 additions and 94 deletions.
2 changes: 1 addition & 1 deletion htdocs/AWOS/current.phtml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
<?php
<?php
header("Location: /ASOS/current.phtml");
1 change: 0 additions & 1 deletion htdocs/QC/offline.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ function networkOffline($network)
to a wide range of factors. Here is a listing of sites currently offline.
</p>
<table class="table table-striped">
<thead>
<tr>
Expand Down
1 change: 1 addition & 0 deletions htdocs/api/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
<li><a href="https://openweathermap.org/api">OpenWeatherMap</a></li>
<li><a href="https://pirateweather.net">Pirate Weather</a></li>
<li><a href="https://realearth.ssec.wisc.edu/doc/api.php">SSEC RealEarth API</a></li>
<li><a href="https://synopticdata.com/">Synoptic Data PBC</a></li>
<li><a href="https://www.tomorrow.io/weather-api/">Tomorrow.io</a></li>
<li><a href="https://xweather.com/docs">Vaisala Xweather</a></li>
<li><a href="https://www.visualcrossing.com/weather-api">Visual Crossing Weather</a></li>
Expand Down
46 changes: 25 additions & 21 deletions htdocs/js/iemss.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* global $, ol */
var htmlInterface = ['<div class="panel panel-default">',
const htmlInterface = ['<div class="panel panel-default">',
'<div class="panel-heading">',
'<a class="btn btn-default pull-right" href="/" id="iemss-metadata-link" target="_new">',
'<i class="fa fa-info"></i> Station Metadata</a>',
Expand Down Expand Up @@ -52,24 +52,28 @@ var htmlInterface = ['<div class="panel panel-default">',
'</div><!-- End of panel-body -->',
'</div><!-- End of panel -->'];

var map, selectedFeature, geojson, geojsonSource, network;
let map = null;
let selectedFeature = null;
let geojson = null;
let geojsonSource = null;
let network = null;

//http://www.lessanvaezi.com/filter-select-list-options/
jQuery.fn.filterByText = function (textbox, selectSingleMatch) {
return this.each(function () {
var select = this;
var options = [];
const select = this;
const options = [];
$(select).find('option').each(function () {
options.push({ value: $(this).val(), text: $(this).text() });
});
$(select).data('options', options);
$(textbox).bind('change keyup', function () {
const opts = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search, 'gi');
const search = $.trim($(this).val());
const regex = new RegExp(search, 'gi');

$.each(opts, (i) => {
var option = options[i];
const option = options[i];
if (option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
Expand All @@ -86,7 +90,7 @@ jQuery.fn.filterByText = function (textbox, selectSingleMatch) {

function sortListing(option) {
$("#stations_in").append($("#stations_in option").remove().sort(function (a, b) {
var at = $(a).text(), bt = $(b).text();
let at = $(a).text(), bt = $(b).text();
if (option == 'name') {
at = at.slice(at.indexOf(' ') + 1);
bt = bt.slice(bt.indexOf(' ') + 1);
Expand Down Expand Up @@ -128,8 +132,8 @@ $().ready(() => {
$("#iemss").append(htmlInterface.join(''));

network = $("#iemss").data("network");
var only_online = ($("#iemss").data("only-online") === 1);
var select_name = $("#iemss").attr("data-name");
const only_online = ($("#iemss").data("only-online") === 1);
const select_name = $("#iemss").attr("data-name");
if (select_name) {
$("#stations_out").attr("name", select_name);
}
Expand All @@ -147,7 +151,7 @@ $().ready(() => {
return !$('#stations_in option:selected').remove().appendTo('#stations_out');
});
$('#stations_addall').click(() => {
var ret = !$('#stations_in option').remove().appendTo('#stations_out');
const ret = !$('#stations_in option').remove().appendTo('#stations_out');
$('#stations_out option').prop('selected', true);
return ret;
});
Expand Down Expand Up @@ -203,7 +207,7 @@ $().ready(() => {
geojsonSource.on('change', () => {
if (geojsonSource.getState() == 'ready') {
$.each(geojsonSource.getFeatures(), (_index, feat) => {
var lbl = `[${feat.get('sid')}] ${feat.get('sname')}`;
let lbl = `[${feat.get('sid')}] ${feat.get('sname')}`;
if (network != 'TAF') {
lbl += ` ${feat.get('time_domain')}`;
}
Expand All @@ -224,14 +228,14 @@ $().ready(() => {
}
});

var $newdiv = $("<div>", { id: "popup", style: "width: 250px;" });
const $newdiv = $("<div>", { id: "popup", style: "width: 250px;" });
$("#map").append($newdiv);
var $newdiv2 = $("<div>", { id: "popover-content", style: "display: none;" });
const $newdiv2 = $("<div>", { id: "popover-content", style: "display: none;" });
$("#map").append($newdiv2);

var element = document.getElementById('popup');
const element = document.getElementById('popup');

var popup = new ol.Overlay({
const popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false
Expand All @@ -245,16 +249,16 @@ $().ready(() => {
});
// display popup on click
map.on('click', (evt) => {
var feature = map.forEachFeatureAtPixel(evt.pixel,
const feature = map.forEachFeatureAtPixel(evt.pixel,
(feat) => {
return feat;
});
if (feature) {
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
var sid = feature.get('sid');
const geometry = feature.getGeometry();
const coord = geometry.getCoordinates();
const sid = feature.get('sid');
popup.setPosition(coord);
var content = `<p><strong>SID: </strong>${sid}`
const content = `<p><strong>SID: </strong>${sid}`
+ `<br /><strong>Name:</strong> ${feature.get('sname')}`
+ `<br /><strong>Period:</strong> ${feature.get("time_domain")}</p>`;
$('#popover-content').html(content);
Expand Down
1 change: 1 addition & 0 deletions htdocs/request/dcp/fe.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ $network = isset($_GET['network']) ? xssafe($_GET["network"]) : 'IA_DCP';

$t = new MyView();
$t->iemss = True;
$t->iem_resource = "HADS";
define("IEM_APPID", 44);
$mesosite = iemdb('mesosite');

Expand Down
8 changes: 5 additions & 3 deletions pylib/iemweb/AWOS/metar_collective.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,24 @@
from io import StringIO

import pandas as pd
from pyiem.util import get_sqlalchemy_conn, utc
from pyiem.database import get_sqlalchemy_conn
from pyiem.util import utc
from pyiem.webutil import iemapp
from sqlalchemy import text


def add_output(sio):
"""Do as I say"""
with get_sqlalchemy_conn("iem") as conn:
df = pd.read_sql(
"""
text("""
select raw from current c JOIn stations t on (t.iemid = c.iemid)
WHERE t.network = 'IA_ASOS' and
valid > now() - '2 hours'::interval
and id not in ('CWI', 'FOD', 'SUX', 'MCW', 'MIW', 'IOW', 'AMW',
'DSM', 'LWD', 'DBQ', 'CID', 'DVN', 'EST', 'OTM', 'ALO', 'SPW',
'BRL') ORDER by id ASC
""",
"""),
conn,
)
sio.write("000 \r\r\n")
Expand Down
16 changes: 9 additions & 7 deletions pylib/iemweb/autoplot/scripts/p10.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,14 @@ def plotter(fdict):
s_slp, s_int, s_r, _, _ = stats.linregress(years, spring)
f_slp, f_int, f_r, _, _ = stats.linregress(years, fall)

(fig, ax) = figure_axes(apctx=ctx)
title = PDICT.get(direction, "").replace(
"Temperature", PDICT2.get(varname)
)
units = r"$^\circ$F" if not varname.startswith("snow") else "inch"
(fig, ax) = figure_axes(
title=ctx["_sname"], subtitle=f"{title} {threshold}{units}", apctx=ctx
)
ax.set_position([0.1, 0.1, 0.8, 0.7])
ax.bar(years, fall - spring, bottom=spring, ec="tan", fc="tan", zorder=1)
for _v in [fall, spring]:
avgv = int(np.average(_v))
Expand Down Expand Up @@ -232,12 +239,7 @@ def plotter(fdict):
)

ax.grid(True)
title = PDICT.get(direction, "").replace(
"Temperature", PDICT2.get(varname)
)
units = r"$^\circ$F" if not varname.startswith("snow") else "inch"
ax.set_title(f"{ctx['_sname']}\n{title} {threshold}{units}")
ax.legend(ncol=4, fontsize=14, labelspacing=2)
ax.legend(ncol=4, fontsize=14, labelspacing=2, loc=(0.1, 0.91))
ax.set_yticks((1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335))
ax.set_yticklabels(calendar.month_abbr[1:])
ax.set_ylim(min(spring) - 5, max(fall) + 30)
Expand Down
2 changes: 1 addition & 1 deletion pylib/iemweb/autoplot/scripts/p14.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def plotter(fdict):
year = ctx["year"]
jdaylimit = 367
if year == today.year:
jdaylimit = int(today.strftime("%j"))
jdaylimit = today.timetuple().tm_yday

endyear = int(datetime.now().year) + 1

Expand Down
5 changes: 2 additions & 3 deletions pylib/iemweb/autoplot/scripts/p28.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def add_ctx(ctx):
"""Get the plotting context"""
pgconn, cursor = get_dbconnc("coop")
station = ctx["station"]
dt = ctx["date"]
dt: date = ctx["date"]
opt = ctx["opt"]

cursor.execute(
Expand Down Expand Up @@ -123,8 +123,7 @@ def add_ctx(ctx):
ts = datetime.strptime(lastrow["valid"], "%Y-%m-%d")
dclass = f"{cat} on {ts:%-d %b %Y}"

_temp = dt.replace(year=2000)
_doy = int(_temp.strftime("%j"))
_doy = dt.replace(year=2000).timetuple().tm_yday
xticks = []
xticklabels = []
for i in range(-360, 1, 60):
Expand Down
4 changes: 2 additions & 2 deletions pylib/iemweb/autoplot/scripts/p30.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"""

import calendar
import datetime
from datetime import date

import numpy as np
import pandas as pd
Expand All @@ -24,7 +24,7 @@ def get_description():
"""Return a dict describing how to call this plotter"""
desc = {"description": __doc__, "data": True}
desc["defaults"] = {"_r": "96"}
today = datetime.date.today()
today = date.today()
desc["arguments"] = [
ARG_STATION,
dict(
Expand Down
6 changes: 3 additions & 3 deletions pylib/iemweb/autoplot/scripts/p31.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"""

import calendar
import datetime
from datetime import date, datetime

import pandas as pd
from pyiem.database import get_sqlalchemy_conn
Expand Down Expand Up @@ -79,7 +79,7 @@ def get_description():
dict(
type="year",
min=1893,
default=datetime.date.today().year,
default=date.today().year,
label="End Year for Plot:",
name="eyear",
),
Expand Down Expand Up @@ -272,7 +272,7 @@ def plotter(fdict):
multiplier = 1
if agg == "week":
multiplier = 7
sts = datetime.datetime(2012, 1, 1)
sts = datetime(2012, 1, 1)
xticks = []
for i in range(1, 13):
ts = sts.replace(month=i)
Expand Down
4 changes: 2 additions & 2 deletions pylib/iemweb/autoplot/scripts/p32.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
variable you selected for plotting.
"""

import datetime
from datetime import date

import matplotlib.colors as mpcolors
import matplotlib.dates as mdates
Expand Down Expand Up @@ -50,7 +50,7 @@ def get_description():
dict(
type="year",
name="year",
default=datetime.date.today().year,
default=date.today().year,
label="Year to Plot:",
),
dict(
Expand Down
4 changes: 2 additions & 2 deletions pylib/iemweb/autoplot/scripts/p34.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def plotter(fdict):
xticks = []
for i in range(1, 13):
ts = sts.replace(month=i)
xticks.append(int(ts.strftime("%j")))
xticks.append(ts.timetuple().tm_yday)

sdf = pd.DataFrame(streaks, columns=["period", "enddate"])
df = pd.DataFrame(
Expand All @@ -166,7 +166,7 @@ def plotter(fdict):
)
df["startdate"] = df["enddate"]
fig = figure(apctx=ctx)
ax = fig.add_axes([0.1, 0.1, 0.55, 0.8])
ax = fig.add_axes((0.1, 0.1, 0.55, 0.8))
ax.bar(np.arange(1, 367), maxperiod[1:], fc="b", ec="b")
ax.grid(True)
ax.set_ylabel("Consecutive Days")
Expand Down
10 changes: 5 additions & 5 deletions pylib/iemweb/autoplot/scripts/p35.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"""

import calendar
import datetime
from datetime import datetime, timedelta

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -86,25 +86,25 @@ def plotter(fdict):
conn,
params={
"station": station,
"hours": datetime.timedelta(hours=hours),
"hours": timedelta(hours=hours),
},
parse_dates="valid",
)
if obs.empty:
raise NoDataFound("No non-null data found")

sts = datetime.datetime(2012, 1, 1)
sts = datetime(2012, 1, 1)
xticks = []
for i in range(1, 13):
ts = sts.replace(month=i)
xticks.append(int(ts.strftime("%j")))
xticks.append(ts.timetuple().tm_yday)

# We want bins centered on zero
p99 = obs["delta"].abs().quantile(0.999)
bins = np.arange(0 - p99, p99, interval)

hist, xedges, yedges = np.histogram2d(
obs["week"].values, obs["delta"].values, [range(54), bins]
obs["week"].to_numpy(), obs["delta"].to_numpy(), [range(54), bins]
)
# create a dataframe from this 2d histogram
x, y = np.meshgrid(xedges[:-1], yedges[:-1])
Expand Down
14 changes: 7 additions & 7 deletions pylib/iemweb/autoplot/scripts/p39.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"""

import calendar
import datetime
from datetime import date, timedelta

import numpy as np
from pyiem.database import get_dbconnc
Expand All @@ -28,8 +28,8 @@
def get_description():
"""Return a dict describing how to call this plotter"""
desc = {"description": __doc__}
today = datetime.date.today()
lastmonth = (today.replace(day=1)) - datetime.timedelta(days=25)
today = date.today()
lastmonth = (today.replace(day=1)) - timedelta(days=25)
desc["arguments"] = [
ARG_STATION,
{
Expand Down Expand Up @@ -93,9 +93,9 @@ def plotter(fdict):
effective_date = ctx["date"]
year, month = compute_compare_month(ctx, cursor)

oldmonth = datetime.date(year, month, 1)
sts = datetime.date(effective_date.year, effective_date.month, 1)
ets = (sts + datetime.timedelta(days=35)).replace(day=1)
oldmonth = date(year, month, 1)
sts = date(effective_date.year, effective_date.month, 1)
ets = (sts + timedelta(days=35)).replace(day=1)
days = int((ets - sts).days)

# beat month
Expand Down Expand Up @@ -185,7 +185,7 @@ def plotter(fdict):
% (calendar.month_abbr[effective_date.month], effective_date.year, lv),
)
# For historical, we can additionally plot the month values
today = datetime.date.today().replace(day=1)
today = date.today().replace(day=1)
if effective_date < today:
ax.plot(
np.arange(1, days + 1),
Expand Down
Loading

0 comments on commit db40e49

Please sign in to comment.