Jump to content
Wikipedia The Free Encyclopedia

Module:Sandbox/Jts1882/Test

From Wikipedia, the free encyclopedia
Module documentationcreate purge
You might want to create a documentation page for this Scribunto module.
Editors can experiment in this module's sandbox (create | mirror) and testcases (create) pages.
Add categories to the /doc subpage. Subpages of this module.
 require('strict')
 localfn=require('Module:Formatnum')
 localmm=require('Module:Math')
 localp={}
 localpargs={}

 functionp.lighthouse(frame)
 localpage=frame.args['page']
 localqid=frame.args['qid']
 localproperty=frame.args['property']
 localtext=page..": instance of :"

 --local item = mw.wikibase.getEntity('P'..prop) --('P5354')
 ifpagethen
 qid=mw.wikibase.getEntityIdForTitle(page)
 text=page..': instance of :'
 elseifqidthen
 text=mw.wikibase.getLabel(qid)..' ('..qid..'): instance of :'
 else
 return"No page or qid given"
 end

 localstatements=mw.wikibase.getBestStatements(qid,'P31')-- get instance of
 forindex,statementinpairs(statements)do
 localinstanceOfId
 ifstatementandstatement.mainsnakandstatement.mainsnak.datavaluethen
 instanceOfId=statement.mainsnak.datavalue.value.id
 text=text..'\n:::'..instanceOfId..' ('..mw.wikibase.getLabel(instanceOfId)..') '

 --local item2 = mw.wikibase.getEntity(instanceOfId) -- returns full claims table [expensive,so just use best statements]
 --local statements2 = item2:getBestStatements( 'P279') 

 localinstanceOfStatements=mw.wikibase.getBestStatements(instanceOfId,'P279')

 text=text..'[subclass: '
 for_,instanceOfStatementinpairs(instanceOfStatements)do
 ifinstanceOfStatement.mainsnakandinstanceOfStatement.mainsnak.datavaluethen
 localsubclassId=instanceOfStatement.mainsnak.datavalue.value.id
 text=text..'\n:::::'..subclassId..' ('..mw.wikibase.getLabel(subclassId)..') '
 end
 end
 text=text..']; '
 end

 end

 returntext
 end
 functionp.testExpensive(frame,page,mode)

 localmode=frame.args['mode']
 ifnotmodethenmode="makeTitle"end

 localtitle
 localpage=frame.args['page']
 ifnotpagethenp.errormsg("Target page not found")end-- TODO check for page existence here

 ifmode=="new"then
 title=mw.title.new(page)-- , ns)
 else
 title=mw.title.makeTitle("Template",page)
 end
 ifnottitlethenreturnp.errormsg("Title object not created")end

 ifnottitle.existsthen
 return"Invalid page name = "..title.text.." (using mw.title."..mode..")"
 end

 return"Title = "..title.text.." (using mw.title."..mode..")"
 end

 functionp.getdomain(frame)
 localurl=frame.args[1]

 localdomain=string.match(url,"%/%/(.-)%/")
 localdomain2=mw.uri.new(url).host
 returndomain.."|"..domain2
 end

 functionp.getclade(frame)

 localpage=frame.args['page']
 ifnotpagethenp.errormsg("Target page not found")end-- TODO check for page existence here

 localtitle=mw.title.new(page)-- , ns)
 ifnottitlethenp.errormsg("Title not retrieved from page")end

 localcontent=title:getContent()

 localcladogram=p.matchClade(content)

 if1==2then
 returnframe:preprocess(p.matchClade(cladogram))
 else-- now do something with it
 returnp.parseCladogram(frame,cladogram)
 end

 end
 functionp.parseCladogram(frame,cladogram)

 localpattern='|1=(.+)[|}]'
 --local value = p.matchClade(cladogram, pattern)
 formatchincladogram:gmatch(pattern)do-- most inclusive
 ifmatch:find("^{{clade")then
 localvalue=p.matchClade(match)
 returnp.parseCladogram(frame,value)
 --return frame:preprocess(p.matchClade(match)) --found clade
 else
 return"no clade found"..match
 end
 return"no match found in match : "..match
 end

 --return frame:preprocess(value)
 return"no match found in cladogram: "..cladogram
 end
 functionp.matchClade(content,pattern)

 ifnotpatternthen
 pattern='{{clade.-}}'-- least inclusive (until first "}}")
 pattern='{{clade.+}}'-- most inclusive (until last "}}", e.g. the taxonbar close)
 end

 formatchincontent:gmatch(pattern)do-- most inclusive
 formatch2inmatch:gmatch('%b{}')do-- match paired brackets
 returnmatch2
 end
 end
 end



 functionp.getpage(frame)
 localpage=frame.args['page']
 localwrap=frame.args['wrap']
 ifnotpagethenp.errormsg("Target page not found")end-- TODO check for page existence here

 localtitle=mw.title.new(page)-- , ns)
 iftitlethen
 localcontent=title:getContent()

 ifwrapthen
 content='<'..wrap..'>'..tostring(content)..'</'..wrap..'>'
 end

 returncontent
 end

 end

 p.main=function(frame)-- called from template
 pargs=frame:getParent().args
 localoutput
 localpage=pargs['page']
 ifnotpagethenp.errormsg("Target page not found")end-- TODO check for page existence here

 localsection=pargs['section']orpargs['section1']orpargs[1]
 ifsectionthen
 output=p._section(frame,page,section)

 end

 locallabel=pargs['label']orpargs['label1']orpargs[1]
 iflabelthen
 output=p._label(frame,page,label)
 end

 localsubtree=pargs['subtree']orpargs['subtree1']orpargs[1]
 ifsubtreethen
 output=p._label(frame,page,subtree)
 end

 localwrap=pargs['wrap']
 ifwrapand(labelorsubtree)then
 locallabel1=labelorstring.lower(subtree)
 ifwrap~=""thenlabel1=wrapend
 output="{{clade |label1="..p.firstToUpper(label1).."|1="..output.."}}"
 end

 ifoutputthen
 returnframe:preprocess(output)
 end

 returnp.errormsg("No valid option for transclusion")
 end

 p.test=function(frame)

 --mw.title.makeTitle( namespace, title, fragment, interwiki )
 --mw.title.new( text, namespace )
 localpage="User:Jts1882/sandbox/test/Passeriformes"--"Atelopus andinus"
 localsection="Passeriformes"

 localns=1
 ifpage:find("^User")thenns=2end
 ifpage:find("^Template")thenns=10end-- TODO check number

 --mw.site.namespaces.User.id -- returns 2

 --TEST PAGE = User:Jts1882/sandbox 
 returnp._section(frame,page,"Passeroidea ","Corvida","Tyranni")


 end


 p.test_working_prototype=function(frame)

 --mw.title.makeTitle( namespace, title, fragment, interwiki )
 --mw.title.new( text, namespace )
 localpage="User:Jts1882/sandbox/test/Passeriformes"--"Atelopus andinus"

 localns=1
 ifpage:find("^User")thenns=2end
 ifpage:find("^Template")thenns=10end-- TODO check number

 --mw.site.namespaces.User.id -- returns 2

 --TEST PAGE = User:Jts1882/sandbox 

 localtitle=mw.title.new(page)-- , ns)
 iftitlethen
 localcontent=title:getContent()

 localpattern="<section begin=Passeriformes />(.+)<section end=Passeriformes />"
 pattern="{{#tag:section||begin=Test}}(.+){{#tag:section||end=Test}}"
 localvalue=string.match(content,pattern)
 ifvaluethen
 returnframe:preprocess(value)
 --return value
 else
 return"no match found"
 end

 returncontent
 end


 return"Hello"
 end
 --================================== exclude LABEL ================================================

 p.xlabel=function(frame,page,...)
 localpage=frame.args[1]--"User:Jts1882/sandbox/test/Passeriformes"
 locallabel=frame.args[1]orframe.args['label']orframe.args['label1']
 -- page , target tree, subtrees to exclude ...



 -- page, include clade, multple clades to exclude |
 returnp._xlabel(frame,page,frame.args[2],frame.args[3],frame.args[4],frame.args[5])



 end
 p._xlabel=function(frame,page,target,...)
 --	local page = "User:Jts1882/sandbox/test/Passeriformes"
 --	local label = frame.args[1] or frame.args['label']
 localargs={...}
 localoutput=""

 ifnotargs[1]thenreturnp.errormsg("Label name not provided")end

 localfullOutput=p._label(frame,page,target)
 --local fullOutput = p._section(frame, page, target) 

 output=fullOutput

 localtitle=mw.title.new(mw.text.trim(page))-- , ns) -- creates object if page doesn't exist (and valid page name)
 --TODO: could use mw.title.makeTitle(), but that needs ns
 iftitleandtitle.existsthen
 localcontent=title:getContent()

 fork,vinpairs(args)do
 localsection=mw.text.trim(v)
 localtargetType="label%d"
 localcladePrefix="%d"
 ifstring.upper(section)==sectionthen
 targetType="target%u"-- by convention subtrees must be uppercase
 cladePrefix="subclade%u"
 end

 -- label = [[ name ]] |n= {...}
 localpattern="("..targetType.."=[%s%p]*"..section.."[%s%p]*.-"..cladePrefix.."=.-)(%b{})"
 -- ^^ this .- skips section tags before clade
 -- ^^this .- skips |sublabel and styling following the label (but can return wrong clade when a subtree)


 --for value in string.gmatch( fullOutput , pattern ) do
 localvalue=string.match(fullOutput,pattern)


 ifvaluethen
 localtrimmedTree,matches=string.gsub(fullOutput,pattern,"%1".."replacement string")--replaces pattern with capture %1

 --output = output .. trimmedTree
 --output = output .. "<pre>" .. trimmedTree .. "</pre>"
 fullOutput=trimmedTree
 else
 output=output..p.errormsg("Failed to capture subclade with label "..section)
 end

 end


 else
 return'<span class="error">No page title found</span>'
 end

 ifoutput~=""then
 returnframe:preprocess(fullOutput)
 else
 return'<span class="error">Section for label not found</span>'
 end
 end


 --=============================== extract LABELS or SUBTREES=======================================
 p.label=function(frame,page,...)
 localpage=frame.args[1]--"User:Jts1882/sandbox/test/Passeriformes"
 locallabel=frame.args[1]orframe.args['label']orframe.args['label1']
 localwrap=frame.args['wrap']

 localoutput=p._label(frame,page,frame.args[2],frame.args[3],frame.args[4],frame.args[5])
 ifwrapthen
 locallabel1=string.lower(frame.args[2])
 ifwrap~=""thenlabel1=wrapend
 output="{{clade |label1="..p.firstToUpper(label1).."|1="..output.."}}"
 end
 returnframe:preprocess(output)
 end

 p._label=function(frame,page,...)
 --	local page = "User:Jts1882/sandbox/test/Passeriformes"
 --	local label = frame.args[1] or frame.args['label']
 localargs={...}
 localoutput=""

 ifnotargs[1]thenreturnp.errormsg("Label name not provided")end

 localtitle=mw.title.new(mw.text.trim(page))-- , ns) -- creates object if page doesn't exist (and valid page name)
 --TODO: could use mw.title.makeTitle(), but that needs ns
 iftitleandtitle.existsthen
 localcontent=title:getContent()
 localtargetType="label%d"
 localcladePrefix="%d"
 fork,vinpairs(args)do
 localsection=mw.text.trim(v)
 ifstring.upper(section)==sectionthen
 targetType="target%u"-- by convention subtrees must be uppercase
 cladePrefix="subclade%u"
 end

 -- label = [[ name ]] |n= {...}
 --local pattern = "label%d=[%s%p]*"..section .. "[%s%p]*%d=(%b{})"
 -- the .- skips section tags before clade
 --local pattern = "label%d=[%s%p]*"..section .. "[%s%p]*%d=.-(%b{})"
 -- this .- skips |sublabel and styling following the label (but can return wrong clade when a subtree)
 --local pattern = "label%d=[%s%p]*"..section .. ".-%d=.-(%b{})"
 localpattern=targetType.."=[%s%p]*"..section.."[%s%p]*.-"..cladePrefix.."=.-(%b{})"

 -- for subtrees (how to capture right )
 --local pattern = "[%u]=[%s%p]*"..section .. ".-%d=.-(%b{})"


 localvalue=string.match(content,pattern)



 ifvaluethen

 -- what if we have something like {FABIDS} "{%u}"
 localpattern="({%u-})"
 ifstring.find(value,pattern)then-- if a subtree that hasn't been substituted.
 --local i,j,target = string.find(value, pattern) -- only one subtree
 fortargetinstring.gmatch(value,pattern)do
 localsubtree=p._label(frame,page,target)
 ifsubtreethen
 value=string.gsub(value,target,subtree)
 end
 --return value 
 --value = value .. " (subtree needs transcluding)"
 end
 end
 --if (1==1) then return "Captured pattern=" .. (value or "no match") end 	

 section=string.lower(section)
 output=output..value
 --output = output .. "{{clade |label1=" .. p.firstToUpper(section) .. "|1=" .. value .. "}}"
 else
 output=output..p.errormsg("Failed to capture subclade with label "..section)
 end

 end


 else
 return'<span class="error">No page title found</span>'
 end

 ifoutput~=""then
 --return frame:preprocess(output)
 returnoutput-- preprocess in entry function
 else
 return'<span class="error">Section for label not found</span>'
 end
 end
 p.section=function(frame)
 -------------------------target page ---- sections
 returnframe:preprocess(p._section(frame,mw.text.trim(frame.args[1]),frame.args[2],frame.args[3],frame.args[4],frame.args[5]))
 end
 p._section=function(frame,page,...)
 localargs={...}
 localoutput=""
 localtitle=mw.title.new(page)-- , ns) -- creates object if page doesn't exist (and valid page name)
 --TODO: could use mw.title.makeTitle(), but that needs ns
 iftitleandtitle.existsthen
 localcontent=title:getContent()

 content=string.gsub(content,"%<%!%-%-.-%-%-%>","")-- strip out comments

 fork,vinpairs(args)do
 localsection=mw.text.trim(v)
 --[[ note: using the non-greedy - in (.-) to allow capture of several sections 
 			 this allows internal clade structures to be closed without capturing sisters clades
 			 e.g. see section Tyranni in User:Jts1882/sandbox/test/Passeriformes
 			]]
 localpattern="<section begin="..section.."[ ]*/>(.-)<section end="..section.."[ ]*/>"

 forvalueinstring.gmatch(content,pattern)do
 ifvaluethen
 ifframe.args.wraporframe:getParent().args.wrapthen
 locallabel1=frame.args.wraporframe:getParent().args.wrap
 iflabel1==""thenlabel1=sectionend
 value="{{clade |label1="..label1.."|1="..value.."}}"
 end
 output=output..value
 end

 end
 end


 else
 return'<span class="error">No page title found</span>'
 end

 ifoutput~=""then
 --return frame:preprocess(output)
 returnoutput-- leave preprocessing for entry function
 else
 return'<span class="error">Section not found</span>'
 end

 end

 p.xsection=function(frame)
 localpage=frame.args[1]--"User:Jts1882/sandbox/test/Passeriformes"
 locallabel=frame.args[1]orframe.args['label']orframe.args['label1']
 -- page , target tree, sections to exclude ...	
 returnframe:preprocess(p._xsection(frame,page,frame.args[2],frame.args[3],frame.args[4],frame.args[5]))
 end

 p._xsection=function(frame,page,target,...)
 localargs={...}
 localoutput=""
 localtitle=mw.title.new(page)-- , ns) -- creates object if page doesn't exist (and valid page name)
 --TODO: could use mw.title.makeTitle(), but that needs ns




 iftitleandtitle.existsthen
 localcontent=title:getContent()
 localfullOutput=p._section(frame,page,target)
 output=fullOutput


 fork,vinpairs(args)do
 localsection=mw.text.trim(v)
 --[[ note: using the non-greedy - in (.-) to allow capture of several sections 
 			 this allows internal clade structures to be closed without capturing sisters clades
 			 e.g. see section Tyranni in User:Jts1882/sandbox/test/Passeriformes
 			]]
 localpattern="(<section begin="..section.."[ ]*/>)(.-)(<section end="..section.."[ ]*/>)"

 localvalue=string.match(fullOutput,pattern)


 ifvaluethen
 localtrimmedTree,matches=string.gsub(fullOutput,pattern,"replacement string")--replaces pattern with capture %1

 output=output..trimmedTree
 output=output.."<pre>"..trimmedTree.."</pre>"
 fullOutput=trimmedTree
 else
 output=output..p.errormsg("Failed to capture subclade with label "..section)
 end

 end


 else
 return'<span class="error">No page title found</span>'
 end

 ifoutput~=""then
 --return frame:preprocess(output)
 returnoutput-- leave preprocessing for entry function
 else
 return'<span class="error">Section not found</span>'
 end

 end
 functionp.populations(frame)
 localargs=frame.args
 localpage="List of countries by population (United Nations)"
 localoutput=""
 localdata={}
 localtotal=0
 localtotalProjected=0
 localcount=0
 localtitle=mw.title.new(page)-- , ns) -- creates object if page doesn't exist (and valid page name)
 --TODO: could use mw.title.makeTitle(), but that needs ns
 iftitleandtitle.existsthen
 localcontent=title:getContent()

 localpattern="<section begin=date_1[ ]*/>(.-)<section end=date_1[ ]*/>"
 forvalueinstring.gmatch(content,pattern)do
 data['date']=value-- date of latest data 
 end
 localpattern="<section begin=date_0[ ]*/>(.-)<section end=date_0[ ]*/>"
 forvalueinstring.gmatch(content,pattern)do
 data['date2']=value-- date of previous data 
 data['date2']=mw.getContentLanguage():formatDate('j F Y',value)
 end
 data['today']=mw.getContentLanguage():formatDate('j F Y')-- today's date (for formatting see https://www.mediawiki.org/wiki/Help:Extension:ParserFunctions#.23time)

 localay=(frame:callParserFunction{name='#time',args={"U",data['today']}}
 -frame:callParserFunction{name='#time',args={"U",data['date2']}})
 /60/60/24/365.2425-- number of years since first date until today‬


 fork,vinpairs(args)do
 localcountry=mw.text.trim(v)

 -- get population data from section 
 localsection=country.."_1"
 localpattern="<section begin="..section.."[ ]*/>(.-)<section end="..section.."[ ]*/>"

 forvalueinstring.gmatch(content,pattern)do
 ifvaluethen
 count=count+1
 data[count]={}
 data[count]['country']=country
 data[count]['populationString']=frame:preprocess(value)
 localraw=string.gsub(data[count]['populationString'],",","")-- strip formatting from number string
 data[count]['populationNumber']=tonumber(raw)
 total=total+data[count]['populationNumber']

 localsection=country.."_0"
 localpattern2="<section begin="..section.."[ ]*/>(.-)<section end="..section.."[ ]*/>"
 forvalue2instring.gmatch(content,pattern2)do
 data[count]['populationString2']=frame:preprocess(value2)
 localraw=string.gsub(data[count]['populationString2'],",","")-- strip formatting from number string
 data[count]['populationNumber2']=tonumber(raw)
 data[count]['populationIncrement']=data[count]['populationNumber']-data[count]['populationNumber2']
 data[count]['populationGrowth']=data[count]['populationIncrement']/data[count]['populationNumber2']
 data[count]['populationDouble']=math.log(2)/math.log(1+data[count]['populationGrowth'])

 data[count]['populationProjected']=math.pow(data[count]['populationNumber2'],1-ay)
 *math.pow(data[count]['populationNumber'],ay)
 totalProjected=totalProjected+data[count]['populationProjected']
 end
 end
 end
 end

 localsort_function=function(a,b)
 if(tonumber(a.populationNumber)>tonumber(b.populationNumber))then-- primary sort on 'population' -> a before b
 returntrue
 end
 end
 localtest="test: "
 localnumber=5435.12345
 test=fn.formatNum(5435.12345,"en",0)
 --test= frame:expandTemplate{ title = "formatnum", args = { totalProjected ,"en",0 } }
 --test=frame:callParserFunction{ name = 'formatnum', args = { totalProjected, decs=2 } }

 table.sort(data,sort_function)

 locali=1
 -- output table
 output='{| class="wikitable sortable" style="text-align:right;" '
 ..'\n!rowspan=2|#'
 ..'\n!rowspan=2|Country'
 ..'\n!rowspan=2|Projected population<br/>('..data['today']..')'
 ..'\n!rowspan=2|Pct of total'
 ..'\n!rowspan=2|Population<br/>('..data['date']..')'
 --.. '\n!rowspan=2|Pct of total'
 ..'\n!rowspan=2|Previous Population<br/>('..data['date2']..')'
 ..'\n!colspan=2|Annual growth'
 ..'\n!rowspan=2|Doubling time<br/>(years)'
 ..'\n|-\n!Increment'
 ..'\n!Rate'
 while(data[i])do
 output=output..'\n|-\n|'..i
 output=output..'\n|style="text-align:left;" |'..frame:expandTemplate{title="flagcountry",args={data[i]['country']}}
 output=output..'\n| '..mm._precision_format(data[i]['populationProjected'],0)
 --output = output .. '\n| ' .. fn.formatNum(data[i]['populationProjected'],"en",0) 
 output=output..'\n| '..mm._precision_format(data[i]['populationProjected']/totalProjected*100,2).."%"-- projected
 output=output..'\n| '..data[i]['populationString']
 --output = output .. '\n| ' .. fn.formatNum(data[i]['populationNumber']/total*100,"en",2) .. "%"
 output=output..'\n| '..data[i]['populationString2']
 output=output..'\n| '..mm._precision_format(data[i]['populationIncrement'],0)
 output=output..'\n| '..mm._round(data[i]['populationGrowth']*100,2).."%"
 output=output..'\n| '..mm._round(data[i]['populationDouble'],0)
 i=i+1
 end

 output=output..'\n|-\n! !! Total'
 ..'\n! style="text-align:right;" |'..fn.formatNum(mm._round(totalProjected,0),"en",0)
 ..'\n! style="text-align:right;" | 100% '
 ..'\n! style="text-align:right;" |'..fn.formatNum(total,"en",0)
 --.. '\n! style="text-align:right;" | 100% '
 ..'\n! || || ||'-- ..test
 output=output..'\n|}'
 else
 return'<span class="error">No page title found</span>'
 end




 returnoutput
 end

 functionp.firstToUpper(str)
 return(str:gsub("^%l",string.upper))
 end
 p.errormsg=function(message)
 return'<span class="error">'..message..'</span>'
 end

 returnp

AltStyle によって変換されたページ (->オリジナル) /