Modulo:Demografia: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
Moroboshi (discussione | contributi)
r
Moroboshi (discussione | contributi)
refactoring
Riga 1:
local mWikidata = require('Modulo:Wikidata/sandbox')
 
local p = {}
Riga 10:
end
 
local function max_pop(data)
-- =============================================================
-- Funzioni copiate da Modulo:Wikidata
-- =============================================================
 
-- Messaggi di errore
local i18n = {
["errors"] = {
["entityid-param-not-provided"] = "Parametro ''entityid'' non fornito",
["property-param-not-provided"] = "Parametro ''property'' non fornito",
["qualifier-param-not-provided"] = "Parametro ''qualifier'' non fornito",
["value-param-not-provided"] = "Parametro ''valore'' da ricercare non fornito",
["entity-not-found"] = "Entità non trovata",
["unknown-claim-type"] = "Tipo asserzione sconosciuta",
["unknown-snak-type"] = "Tipo di snak sconosciuto",
["unknown-datavalue-type"] = "Tipo di dato sconosciuto",
["unknown-entity-type"] = "Tipo di entità sconosciuta"
},
["somevalue"] = "''valore sconosciuto''",
["novalue"] = "''nessun valore''"
}
 
-------------------------------------------------------------------------------
-- Formatters
-------------------------------------------------------------------------------
 
local function errhandler(msg)
local cat = mw.title.getCurrentTitle().namespace == 0 and errorCategory or ''
return string.format('<span class="error">%s</span>%s', msg, cat)
end
 
local function formatExtLink(url)
local protocols = { ftp = true, http = true, https = true }
 
local success, uri = pcall(function() return mw.uri.new(url) end)
if success and uri.protocol and protocols[uri.protocol] then
local dest = tostring(uri)
return string.format('[%s %s]', dest, dest:gsub(uri.protocol .. '://', ''))
else
return url
end
end
 
local function formatEntityId(entityId)
local label = mw.wikibase.label(entityId)
local link = mw.wikibase.sitelink(entityId)
if link then
if label then
return '[[' .. link .. '|' .. label .. ']]'
else
return '[[' .. link .. ']]'
end
else
return label or ''
end
end
 
local function formatTime(value, args)
local year, month, day
local ret = ''
year, month, day = value.time:match('(%d+)%-(%d%d)%-(%d%d).+')
if value.precision == 9 then
ret = tonumber(year)
elseif value.precision == 10 then
ret = mw.getLanguage('it'):formatDate('F Y', tonumber(year) .. '-' .. month)
elseif value.precision == 11 then
ret = mw.getLanguage('it'):formatDate('j F Y', tonumber(year) .. '-' .. month .. '-' .. day)
ret = ret:gsub('^1%s', '1º ')
end
if value.precision >= 9 and value.precision <= 11 then
ret = ret .. (value.time:sub(1, 1) == '-' and ' a.C.' or '')
end
 
return ret
end
 
local function formatGlobecoordinate(value, args)
local ret
if args.formatting == 'latitude' then
ret = value.latitude
elseif args.formatting == 'longitude' then
ret = value.longitude
else
ret = value.latitude .. ', ' .. value.longitude
end
return ret
end
 
local function formatFromPattern(str, args)
local pattern = args.pattern
pattern = mw.ustring.gsub(pattern, '\\{', '{')
pattern = mw.ustring.gsub(pattern, '\\}', '}')
return mw.getCurrentFrame():preprocess(mw.message.newRawMessage(pattern, str):plain())
end
 
local function getEntityIdFromValue(value)
local prefix = ''
if value['entity-type'] == 'item' then
prefix = 'Q'
elseif value['entity-type'] == 'property' then
prefix = 'P'
else
error(i18n.errors['unknown-entity-type'])
end
return prefix .. value['numeric-id']
end
 
local function formatDatavalue(datavalue, args)
local ret
 
--Default formatters
if datavalue.type == 'wikibase-entityid' then
if args.formatting == 'raw' then
ret = getEntityIdFromValue(datavalue.value)
else
ret = formatEntityId(getEntityIdFromValue(datavalue.value))
end
elseif datavalue.type == 'string' then
ret = datavalue.value
if args.formatting == 'extlink' then
ret = formatExtLink(ret)
end
elseif datavalue.type == 'monolingualtext' then
ret = datavalue.value.text
elseif datavalue.type == 'time' then
if args.formatting == 'raw' then
ret = datavalue.value.time
else
ret = formatTime(datavalue.value, args)
end
elseif datavalue.type == 'globecoordinate' then
ret = formatGlobecoordinate(datavalue.value, args)
elseif datavalue.type == 'quantity' then
ret = tonumber(datavalue.value.amount)
else
error(i18n.errors['unknown-datavalue-type'])
end
 
return ret
end
 
local function formatSnak(snak, args)
if snak.snaktype == 'somevalue' then
return i18n['somevalue']
elseif snak.snaktype == 'novalue' then
return i18n['novalue']
elseif snak.snaktype == 'value' then
return formatDatavalue(snak.datavalue, args)
else
error(i18n.errors['unknown-snak-type'])
end
end
 
-- =============================================================
-- Fine Funzioni copiate da Modulo:Wikidata
-- =============================================================
local function max_array(array)
local max = 0
for _,pd in ipairs(arraydata) do
if pd.population > max then max = pd.population end
end
return max
Riga 177 ⟶ 21:
-- Eventuali valori non numerici sono ignorati
local function read_array(args)
local yearsraw_data = {}
if args.anni and args.popolazione then
local populations = {}
if local years = mw.text.split(args.anni, then",")
local listpopulations = mw.text.split(string.gsub(args.annipopolazione, "%s", ""), ",")
forif _,s#years in== ipairs(list)#populations dothen
years[#years+1]for i = tonumber(s)1, or#years 0do
raw_data[i] = {year=string.gsub(years[i], "%s", "") , population = tonumber(populations[i]) or 0 }
end
if args.popolazione then
local list = mw.text.split(string.gsub(args.popolazione, "%s", ""), ",")
for _,s in ipairs(list) do
populations[#populations+1] = tonumber(s) or 0
end
end
end
else -- vecchio metodo di inserimento
if #raw_data == 0 then -- vecchio metodo di inserimento
for i=1,20 do
local index = tonumber(i)
local year = tonumber(args['a' .. index])
if year then
yearsraw_data[#yearsraw_data+1] = { year = year, population = tonumber(args['p' .. index]) or 0 }
populations[#populations+1] = tonumber(args['p' .. index]) or 0
end
end
end
return years, populationsraw_data
end
 
local function comp_year(a1d1, a2d2)
return a1[1]d1.year < a2[1]d2.year
end
 
 
local function get_wikidata(from)
local P585claims = mWikidata._getClaims({'P1082', 'P585', from=from, rank='normal'})
if not(claims) or #claims==0 then return nil end
local P1082 = 'P1082'
local entity = mw.wikibase.getEntityObject(from)
local claims
if entity.claims and entity.claims.P1082 and #entity.claims.P1082 > 0 then
claims = entity.claims.P1082
else
return nil
end
--if true then return mw.text.jsonEncode(claims[1],mw.text.JSON_PRETTY) end
local raw_data = {}
for _,claim in ipairs(claims) do
raw_data[#raw_data+1] = { year=mWikidata._formatQualifiers(claim, 'P585', {}),
if claim.qualifiers and claim.qualifiers.P585 and (claim.rank == 'preferred' or claim.rank == 'normal') then
population=tonumber(mWikidata._formatStatement(claim, {})) or 0 }
--if true then return claim end
raw_data[#raw_data+1] = { formatSnak(claim.qualifiers.P585[1] , {}), formatSnak(claim.mainsnak, {}) }
end
end
table.sort(raw_data, comp_year)
localreturn years = {}raw_data
local populations = {}
for i,data in ipairs(raw_data) do
years[i], populations[i] = data[1], data[2]
end
return years, populations
end
 
 
local function default_table(popmax, n)
Riga 260 ⟶ 84:
 
function p._demografia(args)
local years,populationsraw_data = read_array(args)
local from_wikidata = false
if #yearsraw_data == 0 then
years,populationsraw_data = get_wikidata(args.from)
from_wikidata = true
-- if true then return mw.text.jsonEncode(raw_data, mw.text.JSON_PRETTY) end
end
--if true#raw_data == 0 then return mw.text.jsonEncode(years)'' end
local popmax = max_pop(raw_data)
if #years == 0 then return '' end
local popmax = max_array(populations)
local is_thousand = false
if from_wikidata and popmax >= 900000 then
popmax = popmax / 1000
for indexi,populationdata in ipairs(populationsraw_data) do
populationsraw_data[indexi].population = raw_data[i].population / 1000
is_thousand = true
end
end
-- calcolo default per la popolazione
local default = default_table(popmax, #populationsraw_data)
-- generazione del grafico
local graph = {}
Riga 290 ⟶ 114:
dump(graph, 'BackgroundColors = canvas:sfondo\n')
dump(graph, 'BarData=\n')
for _,yeardata in ipairs(yearsraw_data) do
dump(graph, string.format(' bar: %d text:%d\n', data.year, data.year))
end
dump(graph, '\n')
dump(graph, 'PlotData=\n color:barra width:20 align:left\n\n')
for i =1_,#yearsdata in ipairs(raw_data) do
dump(graph, string.format(' bar:%d from:0 till:%d\n', years[i]data.year, populations[i]data.population))
end
dump(graph, '\n')
local lang = mw.language.new('it')
dump(graph, 'PlotData=\n')
for i=1_,#yearsdata in ipairs(raw_data) do
local p_formatted = lang:formatNum(math.floor(tonumber(populations[i])data.population + 0,5) )
dump(graph, string.format(' bar: %d at: %d fontsize:S text: %s shift:(-10,5)|n.d. shift:(-8,5)\n',
years[i]data.year, populations[i]data.population, p_formatted))
end
dump(graph, '\n')