commit
stringlengths 40
40
| old_file
stringlengths 6
181
| new_file
stringlengths 6
181
| old_contents
stringlengths 448
7.17k
| new_contents
stringlengths 449
7.17k
| subject
stringlengths 0
450
| message
stringlengths 6
4.92k
| lang
stringclasses 1
value | license
stringclasses 12
values | repos
stringlengths 9
33.9k
|
---|---|---|---|---|---|---|---|---|---|
5e322bab4c49af9c498c5d2aec0ce716a311dc1f
|
OS/DiskOS/Programs/save.lua
|
OS/DiskOS/Programs/save.lua
|
local destination = select(1,...)
local flag = select(2,...) or ""
local ctype = select(3,...) or "gzip"
local clvl = tonumber(select(4,...) or "9")
local term = require("terminal")
local eapi = require("Editors")
if destination == "-?" then destination = nil end
if destination and destination ~= "@clip" and destination ~= "-?" then
destination = term.resolve(destination)
if destination:sub(-5,-1) ~= ".lk12" then destination = destination..".lk12" end
elseif destination ~= "@clip" and destination ~= "-?" then
destination = eapi.filePath
end
if not destination then
printUsage(
"save <file>","Saves the current loaded game",
"save <file> -c","Saves with compression",
"save","Saves on the last known file",
"save @clip","Saves into the clipboard",
"save <image> --sheet","Saves the spritesheet as external .lk12 image",
"save <filename> --code","Saves the code as a .lua file"
)
return
end
if destination ~= "@clip" and fs.exists(destination) and fs.isDirectory(destination) then color(8) print("Destination must not be a directory") return end
local sw, sh = screenSize()
if string.lower(flag) == "--sheet" then --Sheet export
local data = eapi.leditors[eapi.editors.sprite]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--code" then
local data = eapi.leditors[eapi.editors.code]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination:sub(1,-6)..".lua",data) end
color(11) print("Exported Lua code successfully")
return
end
eapi.filePath = destination
local data = eapi:export()
-- LK12;OSData;OSName;DataType;Version;Compression;CompressLevel;data"
local header = "LK12;OSData;DiskOS;DiskGame;V".._DiskVer..";"..sw.."x"..sh..";C:"
if string.lower(flag) == "-c" then
data = math.b64enc(math.compress(data, ctype, clvl))
header = header..ctype..";CLvl:"..tostring(clvl)..";"
else
header = header.."none;CLvl:0;"
end
if destination == "@clip" then
clipboard(header.."\n"..data)
else
fs.write(destination,header.."\n"..data)
end
color(11) print(destination == "@clip" and "Saved to clipboard successfully" or "Saved successfully")
|
local destination = select(1,...)
local flag = select(2,...) or ""
local ctype = select(3,...) or "gzip"
local clvl = tonumber(select(4,...) or "9")
local term = require("terminal")
local eapi = require("Editors")
local png = false
if destination and destination ~= "@clip" and destination ~= "-?" then
destination = term.resolve(destination)
if destination:sub(-4,-1) == ".png" then
png = true
elseif destination:sub(-5,-1) ~= ".lk12" then
destination = destination..".lk12"
end
elseif not destination then
destination = eapi.filePath
end
if (not destination) or destination == "-?" then
printUsage(
"save <file>","Saves the current loaded game",
"save <file>.png","Save in a png disk",
"save @clip","Saves into the clipboard",
"save <file> -c","Saves with compression",
"save <file> -b","Saves in binary format",
"save","Saves on the last known file",
"save <image> --sheet","Saves the spritesheet as external .lk12 image",
"save <filename> --code","Saves the code as a .lua file"
)
return
end
if destination ~= "@clip" and fs.exists(destination) and fs.isDirectory(destination) then color(8) print("Destination must not be a directory") return end
local sw, sh = screenSize()
if string.lower(flag) == "--sheet" then --Sheet export
local data = eapi.leditors[eapi.editors.sprite]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--code" then
local data = eapi.leditors[eapi.editors.code]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination:sub(1,-6)..".lua",data) end
color(11) print("Exported Lua code successfully")
return
end
eapi.filePath = destination
-- LK12;OSData;OSName;DataType;Version;Compression;CompressLevel;data"
local header, data, savedata = "LK12;OSData;DiskOS;DiskGame;V".._DiskVer..";"..sw.."x"..sh..";C:"
if string.lower(flag) == "-c" then
data = eapi:export()
data = math.b64enc(math.compress(data, ctype, clvl))
header = header..ctype..";CLvl:"..tostring(clvl)..";"
elseif string.lower(flag) == "-b" then
data = eapi:encode()
header = header.."binary;R:1;"
else
data = eapi:export()
header = header.."none;CLvl:0;"
end
if string.lower(flag) == "-b" then
savedata = header..data
else
savedata = header.."\n"..data
end
if destination == "@clip" then
clipboard(savedata)
else
fs.write(destination,savedata)
end
color(11) print(destination == "@clip" and "Saved to clipboard successfully" or "Saved successfully")
|
Added binary save support, and fixed -? argument.
|
Added binary save support, and fixed -? argument.
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
c70d9a4f1852aed7e851ae43842f19f3730d6417
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp",
translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"),
translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " ..
"members can automatically receive their network settings (<abbr title=" ..
"\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " ..
"System\">DNS</abbr>-server, ...)."))
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("Start")).rmempty = true
s:option(Value, "limit", translate("Limit")).rmempty = true
s:option(Value, "leasetime", translate("Leasetime")).rmempty = true
local dd = s:option(Flag, "dynamicdhcp", translate("dynamic"))
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("Name")).optional = true
ignore = s:option(Flag, "ignore",
translate("Ignore interface"),
translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " ..
"this interface"))
ignore.optional = true
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true
s:option(Flag, "force", translate("Force")).optional = true
s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp",
translate("DHCP"),
translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " ..
"members can automatically receive their network settings (<abbr title=" ..
"\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " ..
"System\">DNS</abbr>-server, ...)."))
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("Start")).rmempty = true
s:option(Value, "limit", translate("Limit")).rmempty = true
s:option(Value, "leasetime", translate("Leasetime")).rmempty = true
local dd = s:option(Flag, "dynamicdhcp",
translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"))
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("Name")).optional = true
ignore = s:option(Flag, "ignore",
translate("Ignore interface"),
translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " ..
"this interface"))
ignore.optional = true
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true
s:option(Flag, "force", translate("Force")).optional = true
s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
modules/admin-full: fix last commit
|
modules/admin-full: fix last commit
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5466 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
projectbismark/luci-bismark,8devices/carambola2-luci,Flexibity/luci,Flexibity/luci,zwhfly/openwrt-luci,stephank/luci,stephank/luci,Canaan-Creative/luci,ch3n2k/luci,saraedum/luci-packages-old,jschmidlapp/luci,projectbismark/luci-bismark,jschmidlapp/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,stephank/luci,saraedum/luci-packages-old,8devices/carambola2-luci,zwhfly/openwrt-luci,phi-psi/luci,gwlim/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Flexibity/luci,gwlim/luci,gwlim/luci,phi-psi/luci,projectbismark/luci-bismark,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,vhpham80/luci,gwlim/luci,yeewang/openwrt-luci,Canaan-Creative/luci,Flexibity/luci,phi-psi/luci,ThingMesh/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,ch3n2k/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,freifunk-gluon/luci,projectbismark/luci-bismark,ch3n2k/luci,gwlim/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,jschmidlapp/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,8devices/carambola2-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,stephank/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,phi-psi/luci,ThingMesh/openwrt-luci,ch3n2k/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,phi-psi/luci,yeewang/openwrt-luci,phi-psi/luci,jschmidlapp/luci,jschmidlapp/luci,zwhfly/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,vhpham80/luci,jschmidlapp/luci,Flexibity/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,Flexibity/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,8devices/carambola2-luci,projectbismark/luci-bismark,8devices/carambola2-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,Canaan-Creative/luci,freifunk-gluon/luci,vhpham80/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,ch3n2k/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,vhpham80/luci,stephank/luci
|
f8dbed9284ce653c0afe0fd5541ee8fdeefa5fe7
|
core/inputs-texlike.lua
|
core/inputs-texlike.lua
|
SILE.inputs.TeXlike = {}
local epnf = require( "epnf" )
local ID = lpeg.C( SILE.parserBits.letter * (SILE.parserBits.letter+SILE.parserBits.digit)^0 )
SILE.inputs.TeXlike.identifier = (ID + lpeg.P("-") + lpeg.P(":"))^1
SILE.inputs.TeXlike.parser = function (_ENV)
local _ = WS^0
local sep = lpeg.S(",;") * _
local quotedString = (P("\"") * C((1-lpeg.S("\""))^1) * P("\""))
local value = (quotedString + (1-lpeg.S(",;]"))^1 )
local myID = C( SILE.inputs.TeXlike.identifier + lpeg.P(1) ) / function (t) return t end
local pair = lpeg.Cg(myID * _ * "=" * _ * C(value)) * sep^-1 / function (...) local t= {...}; return t[1], t[#t] end
local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset)
local parameters = (P("[") * list * P("]")) ^-1 / function (a) return type(a)=="table" and a or {} end
local anything = C( (1-lpeg.S("\\{}%\r\n")) ^1)
local lineEndLineStartSpace = (lpeg.S(" ")^0 * lpeg.S("\r\n")^1 * lpeg.S(" ")^0)^-1
local comment = ((P("%") * (1-lpeg.S("\r\n"))^0 * lpeg.S("\r\n")^-1) /function () return "" end)
START "document"
document = V("stuff") * (-1 + E("Unexpected character at end of input"))
text = C( (1-lpeg.S("\\{}%")) ^1)
stuff = Cg(V"environment" +
comment +
V("text") + V"bracketed_stuff" + V"command")^0
bracketed_stuff = P"{" * V"stuff" * (P"}" + E("} expected"))
command =((P("\\")-P("\\begin")) * Cg(myID, "tag") * Cg(parameters,"attr") * V"bracketed_stuff"^0)-P("\\end{")
environment =
P("\\begin") * Cg(parameters, "attr") * P("{") * Cg(myID, "tag") * P("}")
* V("stuff")
* (P("\\end{") * (
Cmt(myID * Cb("tag"), function(s,i,a,b) return a==b end) +
E("Environment mismatch")
) * (P("}") * _) + E("Environment begun but never ended"))
end
local linecache = {}
local lno, col, lastpos
local function resetCache()
lno = 1
col = 1
lastpos = 0
linecache = { { lno = 1, pos = 1} }
end
local function getline( s, p )
start = 1
lno = 1
if p > lastpos then
lno = linecache[#linecache].lno
start = linecache[#linecache].pos + 1
col = 1
else
for j = 1,#linecache-1 do
if linecache[j+1].pos >= p then
lno = linecache[j].lno
col = p - linecache[j].pos
return lno,col
end
end
end
for i = start, p do
if string.sub( s, i, i ) == "\n" then
lno = lno + 1
col = 1
linecache[#linecache+1] = { pos = i, lno = lno }
lastpos = i
end
col = col + 1
end
return lno, col
end
local function massage_ast(t,doc)
-- Sort out pos
if type(t) == "string" then return t end
if t.pos then
t.line, t.col = getline(doc, t.pos)
end
if t.id == "document" then return massage_ast(t[1],doc) end
if t.id == "text" then return t[1] end
if t.id == "bracketed_stuff" then return massage_ast(t[1],doc) end
for k,v in ipairs(t) do
if v.id == "stuff" then
local val = massage_ast(v,doc)
SU.splice(t, k,k, val)
else
t[k] = massage_ast(v,doc)
end
end
return t
end
function SILE.inputs.TeXlike.process(doc)
local tree = SILE.inputs.TeXlike.docToTree(doc)
local root = SILE.documentState.documentClass == nil
if root then
if tree.tag == "document" then
SILE.inputs.common.init(doc, tree)
SILE.process(tree)
elseif pcall(function() assert(loadstring(doc))() end) then
else
SU.error("Input not recognized as Lua or SILE content")
end
end
if root and not SILE.preamble then
SILE.documentState.documentClass:finish()
end
end
local _parser
function SILE.inputs.TeXlike.rebuildParser()
_parser = epnf.define(SILE.inputs.TeXlike.parser)
end
SILE.inputs.TeXlike.rebuildParser()
function SILE.inputs.TeXlike.docToTree(doc)
local tree = epnf.parsestring(_parser, doc)
-- a document always consists of one stuff
tree = tree[1][1]
if tree.id == "text" then tree = {tree} end
if not tree then return end
resetCache()
tree = massage_ast(tree,doc)
return tree
end
SILE.inputs.TeXlike.order = 99
SILE.inputs.TeXlike.appropriate = function () return true end
|
SILE.inputs.TeXlike = {}
local epnf = require( "epnf" )
local ID = lpeg.C( SILE.parserBits.letter * (SILE.parserBits.letter+SILE.parserBits.digit)^0 )
SILE.inputs.TeXlike.identifier = (ID + lpeg.P("-") + lpeg.P(":"))^1
SILE.inputs.TeXlike.parser = function (_ENV)
local _ = WS^0
local sep = S(",;") * _
local quotedString = (P("\"") * C((1-S("\""))^1) * P("\""))
local value = (quotedString + (1-S(",;]"))^1 )
local myID = C( SILE.inputs.TeXlike.identifier + P(1) ) / function (t) return t end
local pair = Cg(myID * _ * "=" * _ * C(value)) * sep^-1 / function (...) local t= {...}; return t[1], t[#t] end
local list = Cf(Ct("") * pair^0, rawset)
local parameters = (P("[") * list * P("]")) ^-1 / function (a) return type(a)=="table" and a or {} end
local anything = C( (1-S("\\{}%\r\n")) ^1)
local lineEndLineStartSpace = (S(" ")^0 * S("\r\n")^1 * S(" ")^0)^-1
local comment = ((P("%") * (1-S("\r\n"))^0 * S("\r\n")^-1) /function () return "" end)
START "document"
document = V("stuff") * (-1 + E("Unexpected character at end of input"))
text = C( (1-S("\\{}%")) ^1)
stuff = Cg(V"environment" +
comment +
V("text") + V"bracketed_stuff" + V"command")^0
bracketed_stuff = P"{" * V"stuff" * (P"}" + E("} expected"))
command =((P("\\")-P("\\begin")) * Cg(myID, "tag") * Cg(parameters,"attr") * V"bracketed_stuff"^0)-P("\\end{")
environment =
P("\\begin") * Cg(parameters, "attr") * P("{") * Cg(myID, "tag") * P("}")
* V("stuff")
* (P("\\end{") * (
Cmt(myID * Cb("tag"), function(s,i,a,b) return a==b end) +
E("Environment mismatch")
) * (P("}") * _) + E("Environment begun but never ended"))
end
local linecache = {}
local lno, col, lastpos
local function resetCache()
lno = 1
col = 1
lastpos = 0
linecache = { { lno = 1, pos = 1} }
end
local function getline( s, p )
start = 1
lno = 1
if p > lastpos then
lno = linecache[#linecache].lno
start = linecache[#linecache].pos + 1
col = 1
else
for j = 1,#linecache-1 do
if linecache[j+1].pos >= p then
lno = linecache[j].lno
col = p - linecache[j].pos
return lno,col
end
end
end
for i = start, p do
if string.sub( s, i, i ) == "\n" then
lno = lno + 1
col = 1
linecache[#linecache+1] = { pos = i, lno = lno }
lastpos = i
end
col = col + 1
end
return lno, col
end
local function massage_ast(t,doc)
-- Sort out pos
if type(t) == "string" then return t end
if t.pos then
t.line, t.col = getline(doc, t.pos)
end
if t.id == "document" then return massage_ast(t[1],doc) end
if t.id == "text" then return t[1] end
if t.id == "bracketed_stuff" then return massage_ast(t[1],doc) end
for k,v in ipairs(t) do
if v.id == "stuff" then
local val = massage_ast(v,doc)
SU.splice(t, k,k, val)
else
t[k] = massage_ast(v,doc)
end
end
return t
end
function SILE.inputs.TeXlike.process(doc)
local tree = SILE.inputs.TeXlike.docToTree(doc)
local root = SILE.documentState.documentClass == nil
if root then
if tree.tag == "document" then
SILE.inputs.common.init(doc, tree)
SILE.process(tree)
elseif pcall(function() assert(loadstring(doc))() end) then
else
SU.error("Input not recognized as Lua or SILE content")
end
end
if root and not SILE.preamble then
SILE.documentState.documentClass:finish()
end
end
local _parser
function SILE.inputs.TeXlike.rebuildParser()
_parser = epnf.define(SILE.inputs.TeXlike.parser)
end
SILE.inputs.TeXlike.rebuildParser()
function SILE.inputs.TeXlike.docToTree(doc)
local tree = epnf.parsestring(_parser, doc)
-- a document always consists of one stuff
tree = tree[1][1]
if tree.id == "text" then tree = {tree} end
if not tree then return end
resetCache()
tree = massage_ast(tree,doc)
return tree
end
SILE.inputs.TeXlike.order = 99
SILE.inputs.TeXlike.appropriate = function () return true end
|
Drop (more consistently) LPEG prefix which is current scope anyway
|
Drop (more consistently) LPEG prefix which is current scope anyway
|
Lua
|
mit
|
alerque/sile,neofob/sile,alerque/sile,simoncozens/sile,alerque/sile,simoncozens/sile,simoncozens/sile,alerque/sile,simoncozens/sile,neofob/sile,neofob/sile,neofob/sile
|
0c20e3122dabeb2fdf8ea1631805fec7b533ffbe
|
overloadimpact/lua/lib/common/oimp.lua
|
overloadimpact/lua/lib/common/oimp.lua
|
oimp = {}
oimp.TOP_PAGE = "top"
oimp.start_time = util.time()
oimp.started = {}
oimp.tot_requests = 0
oimp.last_request = nil
oimp.scenario_name = nil -- to be set by oimp.top
oimp.top_pass_val = 1
-- oimp.top_pass_val can be set to 0 to indicate failure, but normally failure is done by:
--
-- oimp.done(0)
-- return
--
function oimp.should_log()
return client.get_id() == 1
end
function oimp.debug(msg)
if not oimp.should_log() then
return
end
if not oimp_config.LOG_DEBUG then
return
end
log.debug('DEBUG', msg)
end
function oimp.info(msg)
if not oimp.should_log() then
return
end
if not oimp_config.LOG_INFO then
return
end
log.info('INFO', msg)
end
function oimp.error(msg)
oimp.top_pass(0)
if not oimp.should_log() then
return
end
if not oimp_config.LOG_ERROR then
return
end
if oimp_config.ERRORS_AS_INFO then
log.info('ERROR', msg)
else
log.error('ERROR', msg)
end
end
-- we must only set pass metric once for each test, to get correct pass counts
oimp.top_pass_set_already = false
function oimp.top_pass(pass)
if oimp.top_pass_set_already then -- we must only set pass metric once for each test, to get correct pass counts
return
end
oimp.top_pass_set_already = true
if oimp_config.PRINT_TOP_PASS then
oimp.info("top_pass " .. pass)
end
oimp.metric('pass', pass)
oimp.metric(oimp.scenario_name .. '.pass', pass)
end
function oimp.profile(uri, trace)
local doit = math.random(1, oimp_config.PROFILE_EACH) == 1
if doit then
local timestamp = os.time()
uri = uri .. '&_x=' .. (trace or 'loadimpact')
oimp.debug('Profiling ' .. uri)
end
return uri
end
function oimp.metric(name, value)
if not oimp.should_log() then
return
end
result.custom_metric(oimp_config.METRICS_TAG .. "." .. name, value)
if oimp_config.LOG_METRICS then
log.info('METRIC', oimp_config.METRICS_TAG .. "." .. name, ':', value)
end
end
function oimp.log_response_metrics(res)
-- oimp.metric('status_code', res['status_code'])
-- oimp.metric('connect_time', 1000 * res['connect_time'])
-- oimp.metric('dns_lookup_time', 1000 * res['dns_lookup_time'])
-- oimp.metric('ssl_handshake_time', 1000 * res['ssl_handshake_time'])
-- oimp.metric('redirect_time', 1000 * res['redirect_time'])
-- oimp.metric('time_to_first_byte', 1000 * res['time_to_first_byte'])
-- oimp.metric('download_time', 1000 * res['download_time'])
end
-- Perform a positive test. It returns true if the value matches the correct one.
function oimp.pass(page, metric, value, correct)
if value == correct then
oimp.metric(page .. '.' .. metric .. '.pass', 1)
return true
else
local url_str = ""
if oimp.last_request.url then
url_str = " Url: " .. oimp.last_request.url .. "."
end
oimp.error('Value ' .. metric .. ' failed for page ' .. page .. '. Got ' .. tostring(value) .. ' instead of ' .. tostring(correct) .. '.' .. url_str .. ". Email: " .. email .. ". Client_id: " .. client_id)
oimp.metric(page .. '.' .. metric .. '.pass', 0)
return
end
end
-- Perform a negative test. It returns false if the value matches the failure one.
function oimp.fail(page, metric, value, failure)
if not page then -- if _page nil then use default top_page
page = oimp.TOP_PAGE
end
local _page = page .. '.' .. metric
if value == failure then
oimp.error('Value ' .. metric .. ' failed. Got ' .. tostring(value) .. '.')
oimp.metric(_page .. '.pass', 0)
return true
else
oimp.metric(_page .. '.pass', 1)
return
end
end
function oimp.check_status(page, res, expected)
return oimp.pass(page, 'status_code', res['status_code'], expected)
end
function oimp.before(page)
http.page_start(page)
local started = util.time() - oimp.start_time
oimp.started[page] = started
-- oimp.metric('request.before', 1000 * started)
-- oimp.metric(page .. '.before', 1000 * started)
end
function oimp.after(page, res)
http.page_end(page)
local started = oimp.started[page]
local stopped = util.time() - oimp.start_time
local duration = stopped - started
-- oimp.metric('request.after', 1000 * stopped)
-- oimp.metric(page .. '.after', 1000 * stopped)
oimp.metric('request.duration', 1000 * duration)
oimp.metric(page .. '.duration', 1000 * duration)
oimp.log_response_metrics(res)
oimp.started[page] = nil
end
function oimp.request(page, request, is_core_action)
local report_results = oimp.should_log()
request['response_body_bytes'] = request['response_body_bytes'] or oimp_config.RESPONSE_SIZE
request['report_results'] = report_results
oimp.tot_requests = oimp.tot_requests + 1
if is_core_action then
oimp.before("core_action") -- Needed to calculate actions/s for the central part of each test, excluding setup requests
end
oimp.before(page)
local res = http.request(request)
oimp.after(page, res)
if is_core_action then
oimp.after("core_action")
end
oimp.last_request = res
return res
end
function oimp.top(scenario)
oimp.scenario_name = "scenario_" .. scenario -- store global var
oimp.start(oimp.scenario_name)
http.page_start(oimp_config.METRICS_TAG .. "." .. oimp.scenario_name)
end
-- This function is called once, from oimp.top() on script start
function oimp.start(page)
oimp.before(oimp.PAGE_DOMAIN)
oimp.before(page)
end
function oimp.done(pass)
oimp.metric('total_requests', oimp.tot_requests)
local page = oimp.scenario_name
local started = oimp.started[page]
if started then
local stopped = util.time() - oimp.start_time
local duration = stopped - started
oimp.metric(page .. '.duration', 1000 * duration)
else
log.error('Started for page ' .. page .. ' was not found.')
end
http.page_end(oimp_config.METRICS_TAG .. "." .. page)
http.page_end(page)
http.page_end(oimp.PAGE_DOMAIN)
if pass ~= nil then
oimp.top_pass(pass)
end
end
function oimp.bottom(scenario)
oimp.pass(oimp.PAGE_DOMAIN, 'check', oimp.top_pass_val, 1)
oimp.done(oimp.top_pass_val)
end
|
oimp = {}
oimp.TOP_PAGE = "top"
oimp.start_time = util.time()
oimp.started = {}
oimp.tot_requests = 0
oimp.last_request = nil
oimp.scenario_name = nil -- to be set by oimp.top
oimp.top_pass_val = 1
-- oimp.top_pass_val can be set to 0 to indicate failure, but normally failure is done by:
--
-- oimp.done(0)
-- return
--
function oimp.should_log()
return client.get_id() == 1
end
function oimp.debug(msg)
if not oimp.should_log() then
return
end
if not oimp_config.LOG_DEBUG then
return
end
log.debug('DEBUG', msg)
end
function oimp.info(msg)
if not oimp.should_log() then
return
end
if not oimp_config.LOG_INFO then
return
end
log.info('INFO', msg)
end
function oimp.error(msg)
oimp.top_pass(0)
if not oimp.should_log() then
return
end
if not oimp_config.LOG_ERROR then
return
end
if oimp_config.ERRORS_AS_INFO then
log.info('ERROR', msg)
else
log.error('ERROR', msg)
end
end
-- we must only set pass metric once for each test, to get correct pass counts
oimp.top_pass_set_already = false
function oimp.top_pass(pass)
if oimp.top_pass_set_already then -- we must only set pass metric once for each test, to get correct pass counts
return
end
oimp.top_pass_set_already = true
if oimp_config.PRINT_TOP_PASS then
oimp.info("top_pass " .. pass)
end
oimp.metric('pass', pass)
oimp.metric(oimp.scenario_name .. '.pass', pass)
end
function oimp.profile(uri, trace)
local doit = math.random(1, oimp_config.PROFILE_EACH) == 1
if doit then
local timestamp = os.time()
uri = uri .. '&_x=' .. (trace or 'loadimpact')
oimp.debug('Profiling ' .. uri)
end
return uri
end
function oimp.metric(name, value)
if not oimp.should_log() then
return
end
result.custom_metric(oimp_config.METRICS_TAG .. "." .. name, value)
if oimp_config.LOG_METRICS then
log.info('METRIC', oimp_config.METRICS_TAG .. "." .. name, ':', value)
end
end
function oimp.log_response_metrics(res)
-- oimp.metric('status_code', res['status_code'])
-- oimp.metric('connect_time', 1000 * res['connect_time'])
-- oimp.metric('dns_lookup_time', 1000 * res['dns_lookup_time'])
-- oimp.metric('ssl_handshake_time', 1000 * res['ssl_handshake_time'])
-- oimp.metric('redirect_time', 1000 * res['redirect_time'])
-- oimp.metric('time_to_first_byte', 1000 * res['time_to_first_byte'])
-- oimp.metric('download_time', 1000 * res['download_time'])
end
-- Perform a positive test. It returns true if the value matches the correct one.
function oimp.pass(page, metric, value, correct)
if value == correct then
oimp.metric(page .. '.' .. metric .. '.pass', 1)
return true
else
local url_str = ""
if oimp.last_request.url then
url_str = " Url: " .. oimp.last_request.url .. "."
end
oimp.error('Value ' .. metric .. ' failed for page ' .. page .. '. Got ' .. tostring(value) .. ' instead of ' .. tostring(correct) .. '.' .. url_str .. ". Email: " .. email .. ". Client_id: " .. client_id)
oimp.metric(page .. '.' .. metric .. '.pass', 0)
return
end
end
-- Perform a negative test. It returns false if the value matches the failure one.
function oimp.fail(page, metric, value, failure)
if not page then -- if _page nil then use default top_page
page = oimp.TOP_PAGE
end
local _page = page .. '.' .. metric
if value == failure then
oimp.error('Value ' .. metric .. ' failed. Got ' .. tostring(value) .. '.')
oimp.metric(_page .. '.pass', 0)
return true
else
oimp.metric(_page .. '.pass', 1)
return
end
end
function oimp.check_status(page, res, expected)
return oimp.pass(page, 'status_code', res['status_code'], expected)
end
function oimp.before(page)
http.page_start(page)
local started = util.time() - oimp.start_time
oimp.started[page] = started
-- oimp.metric('request.before', 1000 * started)
-- oimp.metric(page .. '.before', 1000 * started)
end
function oimp.after(page, res)
http.page_end(page)
local started = oimp.started[page]
local stopped = util.time() - oimp.start_time
local duration = stopped - started
-- oimp.metric('request.after', 1000 * stopped)
-- oimp.metric(page .. '.after', 1000 * stopped)
oimp.metric('request.duration', 1000 * duration)
oimp.metric(page .. '.duration', 1000 * duration)
oimp.log_response_metrics(res)
oimp.started[page] = nil
end
function oimp.request(page, request, is_core_action)
local report_results = oimp.should_log()
request['response_body_bytes'] = request['response_body_bytes'] or oimp_config.RESPONSE_SIZE
request['report_results'] = report_results
oimp.tot_requests = oimp.tot_requests + 1
if is_core_action then
oimp.before("core_action") -- Needed to calculate actions/s for the central part of each test, excluding setup requests
end
oimp.before(page)
local res = http.request(request)
oimp.after(page, res)
if is_core_action then
oimp.after("core_action")
end
oimp.last_request = res
return res
end
function oimp.top(scenario)
oimp.scenario_name = "scenario_" .. scenario -- store global var
oimp.start(oimp.scenario_name)
foo = oimp_config.METRICS_TAG .. "." .. oimp.scenario_name
oimp.info("foo:" .. foo)
http.page_start(oimp_config.METRICS_TAG .. "." .. oimp.scenario_name)
end
-- This function is called once, from oimp.top() on script start
function oimp.start(page)
oimp.before(oimp.METRICS_TAG)
oimp.before(page)
end
function oimp.done(pass)
oimp.metric('total_requests', oimp.tot_requests)
local page = oimp.scenario_name
local started = oimp.started[page]
if started then
local stopped = util.time() - oimp.start_time
local duration = stopped - started
oimp.metric(page .. '.duration', 1000 * duration)
else
log.error('Started for page ' .. page .. ' was not found.')
end
http.page_end(oimp_config.METRICS_TAG .. "." .. page)
http.page_end(page)
http.page_end(oimp.METRICS_TAG)
if pass ~= nil then
oimp.top_pass(pass)
end
end
function oimp.bottom(scenario)
oimp.pass(oimp.METRICS_TAG, 'check', oimp.top_pass_val, 1)
oimp.done(oimp.top_pass_val)
end
|
fix variable renaming
|
fix variable renaming
|
Lua
|
mit
|
schibsted/overloadimpact,schibsted/overloadimpact,schibsted/overloadimpact
|
387cf83650b8e7698c7ca3ec97ff094653d0e249
|
OS/DiskOS/Libraries/parser/languages/lua.lua
|
OS/DiskOS/Libraries/parser/languages/lua.lua
|
local keywords = {
"and", "break", "do", "else", "elseif",
"end", "false", "for", "function", "if",
"in", "local", "nil", "not", "or",
"repeat", "return", "then", "true", "until", "while"
}
local api = getAPI()
local callbacks = {"_draw","_init","_keypressed","_keyreleased","_mousemoved","_mousepressed","_mousereleased","_textinput","_touchcontrol","_touchmoved","_touchpressed","_touchreleased","_update","_wheelmoved"}
local escapable = {"a", "b", "f", "n", "r", "t", "v", "\\", "\"", "'"}
-- Convert values to keys
for _, list in ipairs({keywords, api, callbacks, escapable}) do
for i, word in ipairs(list) do
list[word] = true
list[i] = nil
end
end
function startState()
return {
tokenizer = "base",
starter = ""
}
end
function token(stream, state)
local result = nil
if state.tokenizer == "base" then
char = stream:next()
-- Comment and multiline comment matching
if char == "-" and stream:eat('%-') then
if stream:match("%[%[") then
state.tokenizer = "multilineComment"
else
stream:skipToEnd()
result = "comment"
end
-- String matching
elseif char == "\"" or char == "'" then
state.starter = char
state.tokenizer = "string"
-- Decimal numbers
elseif char == '.' and stream:match('%d+') then
result = 'number'
-- Hex
elseif char == "0" and stream:eat("[xX]") then
stream:eatWhile("%x")
result = "number"
-- Ints and floats numbers
elseif char:find('%d') then
stream:eatWhile("%d")
stream:match("\\.%d+")
local nextChar = stream:peek() or "" -- TODO: Do this to hex and decimals too
if not nextChar:find("[%w_]") then
result = "number"
end
-- elseif operators[char] then
-- return 'operator'
-- Multiline string matching
elseif char == "[" and stream:eat("%[") then
state.tokenizer = "multilineString"
-- Keyword matching
elseif char:find('[%w_]') then
stream:eatWhile('[%w_]')
local word = stream:current()
if keywords[word] then
result = "keyword"
elseif api[word] then
result = "api"
elseif callbacks[word] then
result = "callback"
end
end
end
if state.tokenizer == "string" then
char = stream:next()
result = "string"
if char == "\\" then
escaped = stream:peek()
if escaped and escapable[escaped] then
stream:next()
result = "escape"
end
elseif char == state.starter then
state.starter = ""
stream:next()
state.tokenizer = "base"
--else
-- stream:skipToEnd()
else
if stream:eol() then state.tokenizer = "base" end
end
elseif state.tokenizer == "multilineString" then
char = stream:next()
result = "string"
if char == "\\" then
escaped = stream:peek()
if escaped and escapable[escaped] then
stream:next()
result = "escape"
end
elseif char == "]" and stream:eat("%]") then
stream:next()
state.tokenizer = "base"
end
elseif state.tokenizer == "multilineComment" then
if stream:skipTo("%]%]") then
stream:next()
state.tokenizer = "base"
else
stream:skipToEnd()
end
result = "comment"
end
return result
end
return {
startState = startState,
token = token
}
|
local keywords = {
"and", "break", "do", "else", "elseif",
"end", "false", "for", "function", "if",
"in", "local", "nil", "not", "or",
"repeat", "return", "then", "true", "until", "while"
}
local api = getAPI()
local callbacks = {"_draw","_init","_keypressed","_keyreleased","_mousemoved","_mousepressed","_mousereleased","_textinput","_touchcontrol","_touchmoved","_touchpressed","_touchreleased","_update","_wheelmoved"}
local escapable = {"a", "b", "f", "n", "r", "t", "v", "\\", "\"", "'"}
-- Convert values to keys
for _, list in ipairs({keywords, api, callbacks, escapable}) do
for i, word in ipairs(list) do
list[word] = true
list[i] = nil
end
end
function startState()
return {
tokenizer = "base",
starter = ""
}
end
function token(stream, state)
local result = nil
if state.tokenizer == "base" then
char = stream:next()
-- Comment and multiline comment matching
if char == "-" and stream:eat('%-') then
if stream:match("%[%[") then
state.tokenizer = "multilineComment"
else
stream:skipToEnd()
result = "comment"
end
-- String matching
elseif char == "\"" or char == "'" then
state.starter = char
state.tokenizer = "string"
-- Decimal numbers
elseif char == '.' and stream:match('%d+') then
result = 'number'
-- Hex
elseif char == "0" and stream:eat("[xX]") then
stream:eatWhile("%x")
result = "number"
-- Ints and floats numbers
elseif char:find('%d') then
stream:eatWhile("%d")
stream:match("\\.%d+")
local nextChar = stream:peek() or "" -- TODO: Do this to hex and decimals too
if not nextChar:find("[%w_]") then
result = "number"
end
-- elseif operators[char] then
-- return 'operator'
-- Multiline string matching
elseif char == "[" and stream:eat("%[") then
state.tokenizer = "multilineString"
-- Keyword matching
elseif char:find('[%w_]') then
stream:eatWhile('[%w_]')
local word = stream:current()
if keywords[word] then
result = "keyword"
elseif api[word] then
result = "api"
elseif callbacks[word] then
result = "callback"
end
end
end
if state.tokenizer == "string" then
char = stream:next()
result = "string"
if char == "\\" then
escaped = stream:peek()
if escaped and escapable[escaped] then
stream:next()
result = "escape"
end
elseif char == state.starter then
state.starter = ""
state.tokenizer = "base"
--else
-- stream:skipToEnd()
else
if stream:eol() then state.tokenizer = "base" end
end
elseif state.tokenizer == "multilineString" then
char = stream:next()
result = "string"
if char == "\\" then
escaped = stream:peek()
if escaped and escapable[escaped] then
stream:next()
result = "escape"
end
elseif char == "]" and stream:eat("%]") then
state.tokenizer = "base"
end
elseif state.tokenizer == "multilineComment" then
if stream:skipTo("%]%]") then
stream:next()
state.tokenizer = "base"
else
stream:skipToEnd()
end
result = "comment"
end
return result
end
return {
startState = startState,
token = token
}
|
Fix string syntax parsing
|
Fix string syntax parsing
The parser was consuming an extra character at the end of a string.
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
b4d202ec79f8fe3592f16b23c10d0b652c090847
|
source/scenes/mapEditor/mapEditor.lua
|
source/scenes/mapEditor/mapEditor.lua
|
-- TODO: clean this up
module(..., package.seeall)
-- import
local flower = flower
local layer = nil
local grid = nil
local mode = "default"
local width = 50
local height = 100
local lives = 20
local score = 0
-- TODO: Move this logic elsewhere for finding neighbors
local neighbors = {
hex = {
{
{x = 0, y = 2},
{x = 0, y = -2},
{x = 0, y = -1},
{x = 0, y = 1},
{x = 1, y = -1},
{x = 1, y = 1},
},
{
{x = 0, y = 2},
{x = 0, y = -2},
{x = 0, y = -1},
{x = 0, y = 1},
{x = -1, y = -1},
{x = -1, y = 1}
}
}
}
-- Return a list of offsets for the tiles neighbors
function getHexNeighbors(pos)
local parity = pos.y % 2 == 0 and 1 or 2
return neighbors.hex[parity]
end
function addTouchEventListeners(item)
item:addEventListener("touchDown", item_onTouchDown)
item:addEventListener("touchUp", item_onTouchUp)
item:addEventListener("touchMove", item_onTouchMove)
item:addEventListener("touchCancel", item_onTouchCancel)
end
function onCreate(e)
layer = flower.Layer()
layer:setTouchEnabled(true)
scene:addChild(layer)
buildGrid()
-- Build GUI from parent view
buildGUI(e.data.view)
-- Make the grid touchable
addTouchEventListeners(grid)
end
function buildGrid()
-- Create hex grid
grid = flower.MapImage("hex-tiles.png", width, height, 128, 112, 16)
grid:setShape(MOAIGridSpace.HEX_SHAPE)
grid:setLayer(layer)
grid:setRepeat(false, false)
grid:setPos(0,50)
end
function buildGUI(view)
local buttonSize = {flower.viewWidth/6, 39}
toggleButton = widget.Button {
size = buttonSize,
--pos = {flower.viewWidth - 100, 50},
text = "Toggle Mode",
parent = view,
onClick = function()--updateButton,
mode = mode == "default" and "pattern" or "default"
score = score + 10
statusUI:setText(updateStatus())
end,
}
clearButton = widget.Button {
size = buttonSize,
text = "Clear Grid",
parent = view,
onClick = function()
grid.grid:fill(5)
end,
}
saveButton = widget.Button {
size = buttonSize,
text = "Save Grid",
parent = view,
onClick = function()
-- TODO: implement
end,
enabled = false,
}
loadButton = widget.Button {
size = buttonSize,
text = "Load Grid",
parent = view,
onClick = function()
-- TODO: implement
end,
enabled = false,
}
statusUI = widget.TextBox {
size = {buttonSize[1], 50},
text = updateStatus(),
textSize = 10,
parent = view,
}
end
function updateStatus()
return "Lives: "..lives.."\nScore: "..score.."\nPaint Mode: "..mode
end
function rippleOut(pos, length)
local function ValidTile(pos)
return grid:getTile(pos.x, pos.y) ~= 3
end
--[[if not ValidTile(pos) then
return
end]]
local randomTile = math.random(1, 4)
local function UpdateTile(newX, newY)
grid:setTile(newX, newY, randomTile)
end
local visited = {}
local list = {}
table.insert(list, {position = pos, depth = 1})
local counter = 1
while #list > 0 and counter < length do
local currentNode = list[1]
table.remove(list, 1)
flower.Executors.callLaterTime(currentNode.depth / 20, UpdateTile, currentNode.position.x, currentNode.position.y)
local directions = getHexNeighbors(currentNode.position)
for i, dir in ipairs(directions) do
local newPos = {x = currentNode.position.x + dir.x, y = currentNode.position.y + dir.y}
local key = newPos.x + newPos.y * (width + 1)
if ValidTile(newPos) and not visited[key] then
visited[key] = true
table.insert(list, {position = newPos, depth = currentNode.depth + 1})
end
end
counter = counter + 1
end
end
function onStart(e)
end
function onStop(e)
end
function item_onTouchDown(e)
local prop = e.prop
if prop == nil or prop.touchDown and prop.touchIdx ~= e.idx then
return
end
-- Convert screen space into hex space
local x = e.wx
local y = e.wy
x, y = layer:wndToWorld(x, y)
x, y = prop:worldToModel(x, y)
local xCoord, yCoord = grid.grid:locToCoord(x, y)
rippleOut({x = xCoord, y = yCoord}, mode == "pattern" and 100 or 8)
prop.touchDown = true
prop.touchIdx = e.idx
prop.touchLastX = e.wx
prop.touchLastY = e.wy
end
function item_onTouchUp(e)
local prop = e.prop
if prop == nil or prop.touchDown and prop.touchIdx ~= e.idx then
return
end
prop.touchDown = false
prop.touchIdx = nil
prop.touchLastX = nil
prop.touchLastY = nil
end
function item_onTouchMove(e)
local prop = e.prop
if prop == nil or not prop.touchDown then
return
end
local moveX = e.wx - prop.touchLastX
local moveY = e.wy - prop.touchLastY
prop:addLoc(moveX, moveY, 0)
prop.touchLastX = e.wx
prop.touchLastY = e.wy
end
function item_onTouchCancel(e)
local prop = e.prop
if prop == nil or not prop.touchDown then
return
end
prop.touchDown = false
prop.touchIdx = nil
prop.touchLastX = nil
prop.touchLastY = nil
end
|
-- TODO: clean this up
module(..., package.seeall)
-- import
local flower = flower
local layer = nil
local grid = nil
local mode = "default"
local width = 50
local height = 100
local lives = 20
local score = 0
-- TODO: Move this logic elsewhere for finding neighbors
local neighbors = {
hex = {
{
{x = 0, y = 2},
{x = 0, y = -2},
{x = 0, y = -1},
{x = 0, y = 1},
{x = 1, y = -1},
{x = 1, y = 1},
},
{
{x = 0, y = 2},
{x = 0, y = -2},
{x = 0, y = -1},
{x = 0, y = 1},
{x = -1, y = -1},
{x = -1, y = 1}
}
}
}
-- Return a list of offsets for the tiles neighbors
function getHexNeighbors(pos)
local parity = pos.y % 2 == 0 and 1 or 2
return neighbors.hex[parity]
end
function addTouchEventListeners(item)
item:addEventListener("touchDown", item_onTouchDown)
item:addEventListener("touchUp", item_onTouchUp)
item:addEventListener("touchMove", item_onTouchMove)
item:addEventListener("touchCancel", item_onTouchCancel)
end
function onCreate(e)
layer = flower.Layer()
layer:setTouchEnabled(true)
scene:addChild(layer)
buildGrid()
-- Build GUI from parent view
buildGUI(e.data.view)
-- Make the grid touchable
addTouchEventListeners(grid)
end
function buildGrid()
-- Create hex grid
grid = flower.MapImage("hex-tiles.png", width, height, 128, 112, 16)
grid:setShape(MOAIGridSpace.HEX_SHAPE)
grid:setLayer(layer)
grid:setRepeat(false, false)
grid:setPos(0,50)
end
function buildGUI(view)
local buttonSize = {flower.viewWidth/6, 39}
toggleButton = widget.Button {
size = buttonSize,
--pos = {flower.viewWidth - 100, 50},
text = "Toggle Mode",
parent = view,
onClick = function()--updateButton,
mode = mode == "default" and "pattern" or "default"
score = score + 10
statusUI:setText(updateStatus())
end,
}
clearButton = widget.Button {
size = buttonSize,
text = "Clear Grid",
parent = view,
onClick = function()
grid.grid:fill(5)
end,
}
saveButton = widget.Button {
size = buttonSize,
text = "Save Grid",
parent = view,
onClick = function()
-- TODO: implement
end,
enabled = false,
}
loadButton = widget.Button {
size = buttonSize,
text = "Load Grid",
parent = view,
onClick = function()
-- TODO: implement
end,
enabled = false,
}
statusUI = widget.TextBox {
size = {buttonSize[1], 50},
text = updateStatus(),
textSize = 10,
parent = view,
}
end
function updateStatus()
return "Lives: "..lives.."\nScore: "..score.."\nPaint Mode: "..mode
end
function rippleOut(pos, length)
local function ValidTile(pos)
return pos.x >= 1 and pos.x <= width and
pos.y >= 1 and pos.y <= height and
grid:getTile(pos.x, pos.y) ~= 3
end
--[[if not ValidTile(pos) then
return
end]]
local randomTile = math.random(1, 4)
local function UpdateTile(newX, newY)
grid:setTile(newX, newY, randomTile)
end
local visited = {}
local list = {}
table.insert(list, {position = pos, depth = 1})
local counter = 1
while #list > 0 and counter < length do
local currentNode = list[1]
table.remove(list, 1)
flower.Executors.callLaterTime(currentNode.depth / 20, UpdateTile, currentNode.position.x, currentNode.position.y)
local directions = getHexNeighbors(currentNode.position)
for i, dir in ipairs(directions) do
local newPos = {x = currentNode.position.x + dir.x, y = currentNode.position.y + dir.y}
local key = newPos.x + newPos.y * (width + 1)
if ValidTile(newPos) and not visited[key] then
visited[key] = true
table.insert(list, {position = newPos, depth = currentNode.depth + 1})
end
end
counter = counter + 1
end
end
function onStart(e)
end
function onStop(e)
end
function item_onTouchDown(e)
local prop = e.prop
if prop == nil or prop.touchDown and prop.touchIdx ~= e.idx then
return
end
-- Convert screen space into hex space
local x = e.wx
local y = e.wy
x, y = layer:wndToWorld(x, y)
x, y = prop:worldToModel(x, y)
local xCoord, yCoord = grid.grid:locToCoord(x, y)
rippleOut({x = xCoord, y = yCoord}, mode == "pattern" and 100 or 8)
prop.touchDown = true
prop.touchIdx = e.idx
prop.touchLastX = e.wx
prop.touchLastY = e.wy
end
function item_onTouchUp(e)
local prop = e.prop
if prop == nil or prop.touchDown and prop.touchIdx ~= e.idx then
return
end
prop.touchDown = false
prop.touchIdx = nil
prop.touchLastX = nil
prop.touchLastY = nil
end
function item_onTouchMove(e)
local prop = e.prop
if prop == nil or not prop.touchDown then
return
end
local moveX = e.wx - prop.touchLastX
local moveY = e.wy - prop.touchLastY
prop:addLoc(moveX, moveY, 0)
prop.touchLastX = e.wx
prop.touchLastY = e.wy
end
function item_onTouchCancel(e)
local prop = e.prop
if prop == nil or not prop.touchDown then
return
end
prop.touchDown = false
prop.touchIdx = nil
prop.touchLastX = nil
prop.touchLastY = nil
end
|
Fixed accessing tiles outside of the hex grid.
|
Fixed accessing tiles outside of the hex grid.
|
Lua
|
mit
|
BryceMehring/Hexel
|
e3659747443021e53a71992710b28c12fb76adc4
|
xmake/rules/qt/xmake.lua
|
xmake/rules/qt/xmake.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: qt/wasm application
rule("qt._wasm_app")
add_deps("qt.env")
after_build(function (target)
local qt = target:data("qt")
local pluginsdir = qt and qt.pluginsdir
if pluginsdir then
local targetdir = target:targetdir()
local htmlfile = path.join(targetdir, target:basename() .. ".html")
os.vcp(path.join(pluginsdir, "platforms/wasm_shell.html"), htmlfile)
io.gsub(htmlfile, "@APPNAME@", target:name())
os.vcp(path.join(pluginsdir, "platforms/qtloader.js"), targetdir)
os.vcp(path.join(pluginsdir, "platforms/qtlogo.svg"), targetdir)
end
end)
-- define rule: qt static library
rule("qt.static")
add_deps("qt.qrc", "qt.ui", "qt.moc")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", "static")
end)
after_load(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
-- define rule: qt shared library
rule("qt.shared")
add_deps("qt.qrc", "qt.ui", "qt.moc")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", "shared")
end)
after_load(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
-- define rule: qt console
rule("qt.console")
add_deps("qt.qrc", "qt.ui", "qt.moc")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", "binary")
end)
after_load(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
-- define rule: qt widgetapp
rule("qt.widgetapp")
add_deps("qt.ui", "qt.moc", "qt._wasm_app")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", is_plat("android") and "shared" or "binary")
end)
after_load(function (target)
import("load")(target, {gui = true, frameworks = {"QtGui", "QtWidgets", "QtCore"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
-- define rule: qt static widgetapp
rule("qt.widgetapp_static")
add_deps("qt.ui", "qt.moc", "qt._wasm_app")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", is_plat("android") and "shared" or "binary")
end)
after_load(function (target)
local plugins = {}
if is_plat("macosx") then
plugins.QCocoaIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"qcocoa", "Qt5PrintSupport", "Qt5PlatformSupport", "cups"}}
elseif is_plat("windows") then
plugins.QWindowsIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"Qt5PrintSupport", "Qt5PlatformSupport", "qwindows"}}
elseif is_plat("wasm") then
plugins.QWasmIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"Qt5EventDispatcherSupport", "Qt5FontDatabaseSupport", "Qt5EglSupport", "qwasm"}}
end
import("load")(target, {gui = true, plugins = plugins, frameworks = {"QtGui", "QtWidgets", "QtCore"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
-- define rule: qt quickapp
rule("qt.quickapp")
add_deps("qt.qrc", "qt.moc", "qt._wasm_app")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", is_plat("android") and "shared" or "binary")
end)
after_load(function (target)
import("load")(target, {gui = true, frameworks = {"QtGui", "QtQuick", "QtQml", "QtCore", "QtNetwork"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
-- define rule: qt static quickapp
rule("qt.quickapp_static")
add_deps("qt.qrc", "qt.moc", "qt._wasm_app")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", is_plat("android") and "shared" or "binary")
end)
after_load(function (target)
local plugins = {}
if is_plat("macosx") then
plugins.QCocoaIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"qcocoa", "Qt5PrintSupport", "Qt5PlatformSupport", "Qt5Widgets", "cups"}}
elseif is_plat("windows") then
plugins.QWindowsIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"Qt5PrintSupport", "Qt5PlatformSupport", "Qt5Widgets", "qwindows"}}
elseif is_plat("wasm") then
plugins.QWasmIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"Qt5EventDispatcherSupport", "Qt5FontDatabaseSupport", "Qt5EglSupport", "qwasm"}}
end
import("load")(target, {gui = true, plugins = plugins, frameworks = {"QtGui", "QtQuick", "QtQml", "QtQmlModels", "QtCore", "QtNetwork"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
-- define rule: qt application (deprecated)
rule("qt.application")
add_deps("qt.quickapp", "qt.ui")
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: qt/wasm application
rule("qt._wasm_app")
add_deps("qt.env")
after_build(function (target)
local qt = target:data("qt")
local pluginsdir = qt and qt.pluginsdir
if pluginsdir then
local targetdir = target:targetdir()
local htmlfile = path.join(targetdir, target:basename() .. ".html")
if os.isfile(path.join(pluginsdir, "platforms/wasm_shell.html")) then
os.vcp(path.join(pluginsdir, "platforms/wasm_shell.html"), htmlfile)
io.gsub(htmlfile, "@APPNAME@", target:name())
os.vcp(path.join(pluginsdir, "platforms/qtloader.js"), targetdir)
os.vcp(path.join(pluginsdir, "platforms/qtlogo.svg"), targetdir)
end
end
end)
-- define rule: qt static library
rule("qt.static")
add_deps("qt.qrc", "qt.ui", "qt.moc")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", "static")
end)
after_load(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
-- define rule: qt shared library
rule("qt.shared")
add_deps("qt.qrc", "qt.ui", "qt.moc")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", "shared")
end)
after_load(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
-- define rule: qt console
rule("qt.console")
add_deps("qt.qrc", "qt.ui", "qt.moc")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", "binary")
end)
after_load(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
-- define rule: qt widgetapp
rule("qt.widgetapp")
add_deps("qt.ui", "qt.moc", "qt._wasm_app")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", is_plat("android") and "shared" or "binary")
end)
after_load(function (target)
import("load")(target, {gui = true, frameworks = {"QtGui", "QtWidgets", "QtCore"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
-- define rule: qt static widgetapp
rule("qt.widgetapp_static")
add_deps("qt.ui", "qt.moc", "qt._wasm_app")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", is_plat("android") and "shared" or "binary")
end)
after_load(function (target)
local plugins = {}
if is_plat("macosx") then
plugins.QCocoaIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"qcocoa", "Qt5PrintSupport", "Qt5PlatformSupport", "cups"}}
elseif is_plat("windows") then
plugins.QWindowsIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"Qt5PrintSupport", "Qt5PlatformSupport", "qwindows"}}
elseif is_plat("wasm") then
plugins.QWasmIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"Qt5EventDispatcherSupport", "Qt5FontDatabaseSupport", "Qt5EglSupport", "qwasm"}}
end
import("load")(target, {gui = true, plugins = plugins, frameworks = {"QtGui", "QtWidgets", "QtCore"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
-- define rule: qt quickapp
rule("qt.quickapp")
add_deps("qt.qrc", "qt.moc", "qt._wasm_app")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", is_plat("android") and "shared" or "binary")
end)
after_load(function (target)
import("load")(target, {gui = true, frameworks = {"QtGui", "QtQuick", "QtQml", "QtCore", "QtNetwork"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
-- define rule: qt static quickapp
rule("qt.quickapp_static")
add_deps("qt.qrc", "qt.moc", "qt._wasm_app")
-- we must set kind before target.on_load(), may we will use target in on_load()
before_load(function (target)
target:set("kind", is_plat("android") and "shared" or "binary")
end)
after_load(function (target)
local plugins = {}
if is_plat("macosx") then
plugins.QCocoaIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"qcocoa", "Qt5PrintSupport", "Qt5PlatformSupport", "Qt5Widgets", "cups"}}
elseif is_plat("windows") then
plugins.QWindowsIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"Qt5PrintSupport", "Qt5PlatformSupport", "Qt5Widgets", "qwindows"}}
elseif is_plat("wasm") then
plugins.QWasmIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"Qt5EventDispatcherSupport", "Qt5FontDatabaseSupport", "Qt5EglSupport", "qwasm"}}
end
import("load")(target, {gui = true, plugins = plugins, frameworks = {"QtGui", "QtQuick", "QtQml", "QtQmlModels", "QtCore", "QtNetwork"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
-- define rule: qt application (deprecated)
rule("qt.application")
add_deps("qt.quickapp", "qt.ui")
|
fix qt/wasm
|
fix qt/wasm
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
7d8af16ca00df92e0d67dfc506e67b8f77d286cd
|
premake5.lua
|
premake5.lua
|
---
-- Premake 5.x build configuration script
-- Use this script to configure the project with Premake5.
---
--
-- Remember my location; I will need it to locate sub-scripts later.
--
local corePath = _SCRIPT_DIR
--
-- Disable deprecation warnings for myself, so that older development
-- versions of Premake can be used to bootstrap new builds.
--
premake.api.deprecations "off"
--
-- Register supporting actions and options.
--
newaction {
trigger = "embed",
description = "Embed scripts in scripts.c; required before release builds",
execute = function ()
include (path.join(corePath, "scripts/embed.lua"))
end
}
newaction {
trigger = "package",
description = "Creates source and binary packages",
execute = function ()
include (path.join(corePath, "scripts/package.lua"))
end
}
newaction {
trigger = "test",
description = "Run the automated test suite",
execute = function ()
include (path.join(corePath, "scripts/test.lua"))
end
}
newoption {
trigger = "test",
description = "When testing, run only the specified suite or test"
}
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
newoption {
trigger = "no-curl",
description = "Disable Curl 3rd party lib"
}
newoption {
trigger = "no-zlib",
description = "Disable Zlib/Zip 3rd party lib"
}
newoption {
trigger = "no-bytecode",
description = "Don't embed bytecode, but instead use the stripped souce code."
}
--
-- Define the project. Put the release configuration first so it will be the
-- default when folks build using the makefile. That way they don't have to
-- worry about the /scripts argument and all that.
--
-- TODO: defaultConfiguration "Release"
--
solution "Premake5"
configurations { "Release", "Debug" }
location ( _OPTIONS["to"] )
configuration { "macosx", "gmake" }
buildoptions { "-mmacosx-version-min=10.4" }
linkoptions { "-mmacosx-version-min=10.4" }
project "Premake5"
targetname "premake5"
language "C"
kind "ConsoleApp"
flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" }
includedirs { "src/host/lua/src" }
-- optional 3rd party libraries
if not _OPTIONS["no-zlib"] then
includedirs { "contrib/zlib", "contrib/libzip" }
defines { "PREMAKE_COMPRESSION" }
links { "zip-lib", "zlib-lib" }
end
if not _OPTIONS["no-curl"] then
includedirs { "contrib/curl/include" }
defines { "CURL_STATICLIB", "PREMAKE_CURL" }
links { "curl-lib" }
end
files
{
"*.txt", "**.lua",
"src/**.h", "src/**.c",
}
excludes
{
"src/host/lua/src/lauxlib.c",
"src/host/lua/src/lua.c",
"src/host/lua/src/luac.c",
"src/host/lua/src/print.c",
"src/host/lua/**.lua",
"src/host/lua/etc/*.c"
}
configuration "Debug"
targetdir "bin/debug"
defines "_DEBUG"
flags { "Symbols" }
debugargs { "--scripts=" .. path.translate(os.getcwd()) .. " test"}
debugdir ( os.getcwd() )
configuration "Release"
targetdir "bin/release"
defines "NDEBUG"
flags { "OptimizeSize" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" }
configuration "vs2005"
defines {"_CRT_SECURE_NO_DEPRECATE" }
configuration "windows"
links { "ole32", "ws2_32" }
configuration "linux or bsd or hurd"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
linkoptions { "-rdynamic" }
configuration "linux or hurd"
links { "dl", "rt" }
configuration "linux"
if not _OPTIONS["no-curl"] and os.findlib("ssl") then
links { "ssl", "crypto" }
end
configuration "macosx"
defines { "LUA_USE_MACOSX" }
links { "CoreServices.framework" }
if not _OPTIONS["no-curl"] then
links { "Security.framework" }
end
configuration { "macosx", "gmake" }
toolset "clang"
configuration { "solaris" }
linkoptions { "-Wl,--export-dynamic" }
configuration "aix"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
-- optional 3rd party libraries
group "contrib"
if not _OPTIONS["no-zlib"] then
include "contrib/zlib"
include "contrib/libzip"
end
if not _OPTIONS["no-curl"] then
include "contrib/curl"
end
--
-- A more thorough cleanup.
--
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
|
---
-- Premake 5.x build configuration script
-- Use this script to configure the project with Premake5.
---
--
-- Remember my location; I will need it to locate sub-scripts later.
--
local corePath = _SCRIPT_DIR
--
-- Disable deprecation warnings for myself, so that older development
-- versions of Premake can be used to bootstrap new builds.
--
premake.api.deprecations "off"
--
-- Register supporting actions and options.
--
newaction {
trigger = "embed",
description = "Embed scripts in scripts.c; required before release builds",
execute = function ()
include (path.join(corePath, "scripts/embed.lua"))
end
}
newaction {
trigger = "package",
description = "Creates source and binary packages",
execute = function ()
include (path.join(corePath, "scripts/package.lua"))
end
}
newaction {
trigger = "test",
description = "Run the automated test suite",
execute = function ()
include (path.join(corePath, "scripts/test.lua"))
end
}
newoption {
trigger = "test",
description = "When testing, run only the specified suite or test"
}
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
newoption {
trigger = "no-curl",
description = "Disable Curl 3rd party lib"
}
newoption {
trigger = "no-zlib",
description = "Disable Zlib/Zip 3rd party lib"
}
newoption {
trigger = "no-bytecode",
description = "Don't embed bytecode, but instead use the stripped souce code."
}
--
-- Define the project. Put the release configuration first so it will be the
-- default when folks build using the makefile. That way they don't have to
-- worry about the /scripts argument and all that.
--
-- TODO: defaultConfiguration "Release"
--
solution "Premake5"
configurations { "Release", "Debug" }
location ( _OPTIONS["to"] )
configuration { "macosx", "gmake" }
buildoptions { "-mmacosx-version-min=10.4" }
linkoptions { "-mmacosx-version-min=10.4" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" }
project "Premake5"
targetname "premake5"
language "C"
kind "ConsoleApp"
flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" }
includedirs { "src/host/lua/src" }
-- optional 3rd party libraries
if not _OPTIONS["no-zlib"] then
includedirs { "contrib/zlib", "contrib/libzip" }
defines { "PREMAKE_COMPRESSION" }
links { "zip-lib", "zlib-lib" }
end
if not _OPTIONS["no-curl"] then
includedirs { "contrib/curl/include" }
defines { "CURL_STATICLIB", "PREMAKE_CURL" }
links { "curl-lib" }
end
files
{
"*.txt", "**.lua",
"src/**.h", "src/**.c",
}
excludes
{
"src/host/lua/src/lauxlib.c",
"src/host/lua/src/lua.c",
"src/host/lua/src/luac.c",
"src/host/lua/src/print.c",
"src/host/lua/**.lua",
"src/host/lua/etc/*.c"
}
configuration "Debug"
targetdir "bin/debug"
defines "_DEBUG"
flags { "Symbols" }
debugargs { "--scripts=" .. path.translate(os.getcwd()) .. " test"}
debugdir ( os.getcwd() )
configuration "Release"
targetdir "bin/release"
defines "NDEBUG"
flags { "OptimizeSize" }
configuration "vs2005"
defines {"_CRT_SECURE_NO_DEPRECATE" }
configuration "windows"
links { "ole32", "ws2_32" }
configuration "linux or bsd or hurd"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
linkoptions { "-rdynamic" }
configuration "linux or hurd"
links { "dl", "rt" }
configuration "linux"
if not _OPTIONS["no-curl"] and os.findlib("ssl") then
links { "ssl", "crypto" }
end
configuration "macosx"
defines { "LUA_USE_MACOSX" }
links { "CoreServices.framework" }
if not _OPTIONS["no-curl"] then
links { "Security.framework" }
end
configuration { "macosx", "gmake" }
toolset "clang"
configuration { "solaris" }
linkoptions { "-Wl,--export-dynamic" }
configuration "aix"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
-- optional 3rd party libraries
group "contrib"
if not _OPTIONS["no-zlib"] then
include "contrib/zlib"
include "contrib/libzip"
end
if not _OPTIONS["no-curl"] then
include "contrib/curl"
end
--
-- A more thorough cleanup.
--
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
|
Fix deprecated Posix function warnings
|
Fix deprecated Posix function warnings
|
Lua
|
bsd-3-clause
|
Blizzard/premake-core,noresources/premake-core,mandersan/premake-core,mandersan/premake-core,dcourtois/premake-core,soundsrc/premake-core,premake/premake-core,mendsley/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,CodeAnxiety/premake-core,TurkeyMan/premake-core,lizh06/premake-core,aleksijuvani/premake-core,jstewart-amd/premake-core,dcourtois/premake-core,resetnow/premake-core,premake/premake-core,dcourtois/premake-core,starkos/premake-core,mendsley/premake-core,jstewart-amd/premake-core,sleepingwit/premake-core,martin-traverse/premake-core,sleepingwit/premake-core,dcourtois/premake-core,starkos/premake-core,xriss/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,mendsley/premake-core,premake/premake-core,jstewart-amd/premake-core,LORgames/premake-core,xriss/premake-core,sleepingwit/premake-core,jstewart-amd/premake-core,noresources/premake-core,Zefiros-Software/premake-core,soundsrc/premake-core,premake/premake-core,martin-traverse/premake-core,premake/premake-core,starkos/premake-core,jstewart-amd/premake-core,Blizzard/premake-core,CodeAnxiety/premake-core,resetnow/premake-core,starkos/premake-core,noresources/premake-core,LORgames/premake-core,xriss/premake-core,mandersan/premake-core,noresources/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,lizh06/premake-core,Blizzard/premake-core,Blizzard/premake-core,tvandijck/premake-core,xriss/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,noresources/premake-core,LORgames/premake-core,lizh06/premake-core,TurkeyMan/premake-core,aleksijuvani/premake-core,LORgames/premake-core,xriss/premake-core,aleksijuvani/premake-core,bravnsgaard/premake-core,noresources/premake-core,Zefiros-Software/premake-core,resetnow/premake-core,TurkeyMan/premake-core,premake/premake-core,CodeAnxiety/premake-core,tvandijck/premake-core,dcourtois/premake-core,lizh06/premake-core,noresources/premake-core,aleksijuvani/premake-core,mandersan/premake-core,dcourtois/premake-core,premake/premake-core,martin-traverse/premake-core,TurkeyMan/premake-core,resetnow/premake-core,sleepingwit/premake-core,mendsley/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,starkos/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,bravnsgaard/premake-core,bravnsgaard/premake-core,starkos/premake-core,mandersan/premake-core,tvandijck/premake-core,starkos/premake-core,sleepingwit/premake-core,soundsrc/premake-core,bravnsgaard/premake-core,resetnow/premake-core,martin-traverse/premake-core,mendsley/premake-core,soundsrc/premake-core,soundsrc/premake-core,LORgames/premake-core
|
96e9f184f1731147474222e4cccb94f0d605f551
|
premake4.lua
|
premake4.lua
|
-- http://industriousone.com/scripting-reference
local action = _ACTION or ""
solution "island"
location (".project")
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
language "C"
targetdir ("bin")
kind "StaticLib"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "Debug"
targetdir ("bin")
defines { "DEBUG" }
flags { "Symbols"}
targetsuffix "-d"
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize"}
project "glfw"
includedirs { "3rdparty/glfw/include" }
files {
"3rdparty/glfw/include/GLFW/*.h",
"3rdparty/glfw/src/clipboard.c",
"3rdparty/glfw/src/context.c",
"3rdparty/glfw/src/gamma.c",
"3rdparty/glfw/src/init.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/joystick.c",
"3rdparty/glfw/src/monitor.c",
"3rdparty/glfw/src/time.c",
"3rdparty/glfw/src/window.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/input.c",
}
defines { "_GLFW_USE_OPENGL" }
configuration "windows"
defines { "_GLFW_WIN32", "_GLFW_WGL" }
files {
"3rdparty/glfw/src/win32*.c",
"3rdparty/glfw/src/wgl_context.c",
"3rdparty/glfw/src/winmm_joystick.c",
}
project "glew"
files {
"3rdparty/glew/GL/*.h",
"3rdparty/glew/*.c"
}
defines "GLEW_STATIC"
project "nanovg"
files { "3rdparty/nanovg/src/*" }
project "libuv"
includedirs { "3rdparty/libuv/include" }
files {
"3rdparty/libuv/include/*.h",
"3rdparty/libuv/src/*.c"
}
configuration "linux"
files {
"3rdparty/libuv/src/unix/*.c"
}
configuration "windows"
files {
"3rdparty/libuv/src/win/*.c"
}
project "lua"
os.copyfile("3rdparty/lua/src/luaconf.h.orig", "3rdparty/lua/src/luaconf.h")
includedirs { "3rdparty/lua/src" }
files {
"3rdparty/lua/src/*.h",
"3rdparty/lua/src/*.c"
}
excludes {
"3rdparty/lua/src/loadlib_rel.c",
"3rdparty/lua/src/lua.c",
"3rdparty/lua/src/luac.c",
"3rdparty/lua/src/print.c",
}
project "stb"
includedirs { "3rdparty/stb" }
files {
"3rdparty/stb/stb/*.h",
"3rdparty/stb/*.h",
"3rdparty/stb/*.c"
}
project "AntTweakBar"
language "C++"
includedirs {
"3rdparty/AntTweakBar/include",
"3rdparty/glew",
"3rdparty/glfw/include",
}
files {
"3rdparty/AntTweakBar/include/*.h",
"3rdparty/AntTweakBar/src/*",
}
project "blendish"
language "C++"
files {
"3rdparty/blendish/*.h",
"3rdparty/blendish/blendish_lib.cpp"
}
function create_example_project( example_path )
example_path = string.sub(example_path, string.len("examples/") + 1);
project (example_path)
kind "ConsoleApp"
files {
"examples/" .. example_path .. "/*.h",
"examples/" .. example_path .. "/*.lua",
"examples/" .. example_path .. "/*.c",
}
defines {
"GLEW_STATIC",
"NANOVG_GL3_IMPLEMENTATION",
}
includedirs {
"3rdparty",
"3rdparty/glfw/include",
"3rdparty/glew",
"3rdparty/nanovg/src",
"3rdparty/libuv/src",
"3rdparty/lua/src",
"3rdparty/stb",
"3rdparty/AntTweakBar/include",
"3rdparty/blendish",
"3rdparty/bass/include",
}
libdirs {
"bin",
}
configuration "Debug"
links {
"glfw-d",
"glew-d",
"nanovg-d",
"libuv-d",
"lua-d",
"stb-d",
"AntTweakBar-d",
"blendish-d",
}
configuration "Release"
links {
"glfw",
"glew",
"nanovg",
"libuv",
"lua",
"stb",
"AntTweakBar",
"blendish",
}
configuration "windows"
links {
"OpenGL32",
"3rdparty/bass/lib/windows/bass.lib",
}
end
local examples = os.matchdirs("examples/*")
for _, example in ipairs(examples) do
create_example_project(example)
end
|
-- http://industriousone.com/scripting-reference
local action = _ACTION or ""
solution "island"
location (".project")
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
language "C"
targetdir ("bin")
kind "StaticLib"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "Debug"
targetdir ("bin")
defines { "DEBUG" }
flags { "Symbols"}
targetsuffix "-d"
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize"}
project "glfw"
includedirs { "3rdparty/glfw/include" }
files {
"3rdparty/glfw/include/GLFW/*.h",
"3rdparty/glfw/src/clipboard.c",
"3rdparty/glfw/src/context.c",
"3rdparty/glfw/src/gamma.c",
"3rdparty/glfw/src/init.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/joystick.c",
"3rdparty/glfw/src/monitor.c",
"3rdparty/glfw/src/time.c",
"3rdparty/glfw/src/window.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/input.c",
}
defines { "_GLFW_USE_OPENGL" }
configuration "windows"
defines { "_GLFW_WIN32", "_GLFW_WGL" }
files {
"3rdparty/glfw/src/win32*.c",
"3rdparty/glfw/src/wgl_context.c",
"3rdparty/glfw/src/winmm_joystick.c",
}
project "glew"
files {
"3rdparty/glew/GL/*.h",
"3rdparty/glew/*.c"
}
defines "GLEW_STATIC"
project "nanovg"
files { "3rdparty/nanovg/src/*" }
project "libuv"
includedirs { "3rdparty/libuv/include" }
files {
"3rdparty/libuv/include/*.h",
"3rdparty/libuv/src/*.c"
}
configuration "linux"
files {
"3rdparty/libuv/src/unix/*.c"
}
configuration "windows"
files {
"3rdparty/libuv/src/win/*.c"
}
project "lua"
os.copyfile("3rdparty/lua/src/luaconf.h.orig", "3rdparty/lua/src/luaconf.h")
includedirs { "3rdparty/lua/src" }
files {
"3rdparty/lua/src/*.h",
"3rdparty/lua/src/*.c"
}
excludes {
"3rdparty/lua/src/loadlib_rel.c",
"3rdparty/lua/src/lua.c",
"3rdparty/lua/src/luac.c",
"3rdparty/lua/src/print.c",
}
project "stb"
includedirs { "3rdparty/stb" }
files {
"3rdparty/stb/stb/*.h",
"3rdparty/stb/*.h",
"3rdparty/stb/*.c"
}
project "AntTweakBar"
language "C++"
includedirs {
"3rdparty/AntTweakBar/include",
"3rdparty/glew",
"3rdparty/glfw/include",
}
files {
"3rdparty/AntTweakBar/include/*.h",
"3rdparty/AntTweakBar/src/*",
}
project "blendish"
language "C++"
files {
"3rdparty/blendish/*.h",
"3rdparty/blendish/blendish_lib.cpp"
}
function create_example_project( example_path )
example_path = string.sub(example_path, string.len("examples/") + 1);
project (example_path)
kind "ConsoleApp"
files {
"examples/" .. example_path .. "/*.h",
"examples/" .. example_path .. "/*.lua",
"examples/" .. example_path .. "/*.c",
}
defines {
"GLEW_STATIC",
"NANOVG_GL3_IMPLEMENTATION",
}
includedirs {
"3rdparty",
"3rdparty/glfw/include",
"3rdparty/glew",
"3rdparty/nanovg/src",
"3rdparty/libuv/src",
"3rdparty/lua/src",
"3rdparty/stb",
"3rdparty/AntTweakBar/include",
"3rdparty/blendish",
"3rdparty/bass/include",
}
libdirs {
"bin",
"3rdparty/bass/lib/windows",
}
configuration "Debug"
links {
"glfw-d",
"glew-d",
"nanovg-d",
"libuv-d",
"lua-d",
"stb-d",
"AntTweakBar-d",
"blendish-d",
}
configuration "Release"
links {
"glfw",
"glew",
"nanovg",
"libuv",
"lua",
"stb",
"AntTweakBar",
"blendish",
}
configuration "windows"
links {
"OpenGL32",
"bass",
}
end
local examples = os.matchdirs("examples/*")
for _, example in ipairs(examples) do
create_example_project(example)
end
|
windows/vs2013 link bugfix
|
windows/vs2013 link bugfix
|
Lua
|
mit
|
island-org/island,island-org/island
|
7a70df85f825fff52a77785173e91af0e4281025
|
premake4.lua
|
premake4.lua
|
solution "alloy"
configurations { "Debug", "Release" }
-- get data from shell
LLVM_OPTIONS = "--system-libs --libs "
LLVM_CONFIG = "core analysis executionengine jit interpreter native "
LLVM_CFLAGS = "$(" .. "llvm-config --cflags " .. LLVM_OPTIONS .. LLVM_CONFIG .. ")"
LLVM_LFLAGS = "$(" .. "llvm-config --ldflags " .. LLVM_OPTIONS .. LLVM_CONFIG .. ")"
-- common settings
defines { "_GNU_SOURCE", "__STDC_LIMIT_MACROS", "__STDC_CONSTANT_MACROS" }
buildoptions { LLVM_CFLAGS, "-pthread", "-xc" }
includedirs { "includes" }
links { "dl", "ncurses", "z" }
linkoptions { LLVM_LFLAGS, "-pthread", "-Wl,--as-needed -ltinfo" }
configuration "Debug"
flags { "Symbols", "ExtraWarnings", "FatalWarnings" }
configuration "Release"
buildoptions { "-march=native", "-O2" }
-- compiler
project "alloyc"
kind "ConsoleApp"
language "C++" -- because LLVM is a bitchling
files { "src/*.c", "src/*.h" }
|
solution "alloy"
configurations { "Debug", "Release" }
-- missing function
if not os.outputof then
function os.outputof(cmd)
local pipe = io.popen(cmd)
local result = pipe:read('*a')
pipe:close()
result = result:gsub ("\n", " ")
return result
end
end
-- get data from shell
LLVM_OPTIONS = "--system-libs --libs "
LLVM_CFLAGS = os.outputof ("llvm-config --cflags ")
LLVM_LFLAGS = os.outputof ("llvm-config --ldflags " .. LLVM_OPTIONS .. "all")
-- sanitize inputs
-- LLVM_CFLAGS = string.gsub (LLVM_CFLAGS, "\n", " ")
-- LLVM_LFLAGS = string.gsub (LLVM_LFLAGS, "\n", " ")
-- common settings
defines { "_GNU_SOURCE", "__STDC_LIMIT_MACROS", "__STDC_CONSTANT_MACROS" }
buildoptions { LLVM_CFLAGS, "-pthread", "-xc", "-O0" }
includedirs { "includes" }
links { "dl" }
linkoptions { LLVM_LFLAGS, "-pthread" }
if os.is ("linux") then
linkoptions { "-Wl,--as-needed -ltinfo" }
end
configuration "Debug"
flags { "Symbols", "ExtraWarnings" }
configuration "Release"
buildoptions { "-march=native", "-O2" }
-- compiler
project "alloyc"
kind "ConsoleApp"
language "C++" -- because LLVM is a bitchling
files { "src/*.c", "src/*.h" }
|
fix various premake/makefile/LLVM errors
|
fix various premake/makefile/LLVM errors
|
Lua
|
mit
|
ark-lang/ark,kiljacken/ark
|
74adb3e7271fd388705285cc7b51c4197d5ef4b2
|
premake5.lua
|
premake5.lua
|
---
-- Premake 5.x build configuration script
-- Use this script to configure the project with Premake5.
---
--
-- Remember my location; I will need it to locate sub-scripts later.
--
local corePath = _SCRIPT_DIR
--
-- Disable deprecation warnings for myself, so that older development
-- versions of Premake can be used to bootstrap new builds.
--
premake.api.deprecations "off"
--
-- Register supporting actions and options.
--
newaction {
trigger = "embed",
description = "Embed scripts in scripts.c; required before release builds",
execute = function ()
include (path.join(corePath, "scripts/embed.lua"))
end
}
newaction {
trigger = "package",
description = "Creates source and binary packages",
execute = function ()
include (path.join(corePath, "scripts/package.lua"))
end
}
newaction {
trigger = "test",
description = "Run the automated test suite",
execute = function ()
include (path.join(corePath, "scripts/test.lua"))
end
}
newoption {
trigger = "test",
description = "When testing, run only the specified suite or test"
}
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
newoption {
trigger = "no-curl",
description = "Disable Curl 3rd party lib"
}
newoption {
trigger = "no-zlib",
description = "Disable Zlib/Zip 3rd party lib"
}
newoption {
trigger = "bytecode",
description = "Embed scripts as bytecode instead of stripped souce code"
}
--
-- Define the project. Put the release configuration first so it will be the
-- default when folks build using the makefile. That way they don't have to
-- worry about the /scripts argument and all that.
--
-- TODO: defaultConfiguration "Release"
--
solution "Premake5"
configurations { "Release", "Debug" }
location ( _OPTIONS["to"] )
flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime", "MultiProcessorCompile" }
if not _OPTIONS["no-zlib"] then
defines { "PREMAKE_COMPRESSION" }
end
if not _OPTIONS["no-curl"] then
defines { "CURL_STATICLIB", "PREMAKE_CURL"}
end
configuration "Debug"
defines "_DEBUG"
flags { "Symbols" }
configuration "Release"
defines "NDEBUG"
optimize "Full"
flags { "NoBufferSecurityCheck", "NoRuntimeChecks" }
configuration "vs*"
defines { "_CRT_SECURE_NO_DEPRECATE", "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" }
configuration { "windows", "Release" }
flags { "NoIncrementalLink", "LinkTimeOptimization" }
configuration { "macosx", "gmake" }
buildoptions { "-mmacosx-version-min=10.4" }
linkoptions { "-mmacosx-version-min=10.4" }
project "Premake5"
targetname "premake5"
language "C"
kind "ConsoleApp"
includedirs { "src/host/lua/src" }
-- optional 3rd party libraries
if not _OPTIONS["no-zlib"] then
includedirs { "contrib/zlib", "contrib/libzip" }
links { "zip-lib", "zlib-lib" }
end
if not _OPTIONS["no-curl"] then
includedirs { "contrib/curl/include" }
links { "curl-lib" }
end
files
{
"*.txt", "**.lua",
"src/**.h", "src/**.c",
}
excludes
{
"src/host/lua/src/lauxlib.c",
"src/host/lua/src/lua.c",
"src/host/lua/src/luac.c",
"src/host/lua/src/print.c",
"src/host/lua/**.lua",
"src/host/lua/etc/*.c"
}
configuration "Debug"
targetdir "bin/debug"
debugargs { "--scripts=%{prj.location} test"}
debugdir "%{prj.location}"
configuration "Release"
targetdir "bin/release"
configuration "windows"
links { "ole32", "ws2_32" }
configuration "linux or bsd or hurd"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
linkoptions { "-rdynamic" }
configuration "linux or hurd"
links { "dl", "rt" }
configuration "linux"
if not _OPTIONS["no-curl"] and os.findlib("ssl") then
links { "ssl", "crypto" }
end
configuration "macosx"
defines { "LUA_USE_MACOSX" }
links { "CoreServices.framework" }
if not _OPTIONS["no-curl"] then
links { "Security.framework" }
end
configuration { "macosx", "gmake" }
toolset "clang"
configuration { "solaris" }
linkoptions { "-Wl,--export-dynamic" }
configuration "aix"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
-- optional 3rd party libraries
group "contrib"
if not _OPTIONS["no-zlib"] then
include "contrib/zlib"
include "contrib/libzip"
end
if not _OPTIONS["no-curl"] then
include "contrib/curl"
end
--
-- A more thorough cleanup.
--
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
|
---
-- Premake 5.x build configuration script
-- Use this script to configure the project with Premake5.
---
--
-- Remember my location; I will need it to locate sub-scripts later.
--
local corePath = _SCRIPT_DIR
--
-- Disable deprecation warnings for myself, so that older development
-- versions of Premake can be used to bootstrap new builds.
--
premake.api.deprecations "off"
--
-- Register supporting actions and options.
--
newaction {
trigger = "embed",
description = "Embed scripts in scripts.c; required before release builds",
execute = function ()
include (path.join(corePath, "scripts/embed.lua"))
end
}
newaction {
trigger = "package",
description = "Creates source and binary packages",
execute = function ()
include (path.join(corePath, "scripts/package.lua"))
end
}
newaction {
trigger = "test",
description = "Run the automated test suite",
execute = function ()
include (path.join(corePath, "scripts/test.lua"))
end
}
newoption {
trigger = "test",
description = "When testing, run only the specified suite or test"
}
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
newoption {
trigger = "no-curl",
description = "Disable Curl 3rd party lib"
}
newoption {
trigger = "no-zlib",
description = "Disable Zlib/Zip 3rd party lib"
}
newoption {
trigger = "bytecode",
description = "Embed scripts as bytecode instead of stripped souce code"
}
--
-- Define the project. Put the release configuration first so it will be the
-- default when folks build using the makefile. That way they don't have to
-- worry about the /scripts argument and all that.
--
-- TODO: defaultConfiguration "Release"
--
solution "Premake5"
configurations { "Release", "Debug" }
location ( _OPTIONS["to"] )
flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime", "MultiProcessorCompile" }
if not _OPTIONS["no-zlib"] then
defines { "PREMAKE_COMPRESSION" }
end
if not _OPTIONS["no-curl"] then
defines { "CURL_STATICLIB", "PREMAKE_CURL"}
end
configuration "Debug"
defines "_DEBUG"
flags { "Symbols" }
configuration "Release"
defines "NDEBUG"
optimize "Full"
flags { "NoBufferSecurityCheck", "NoRuntimeChecks" }
configuration "vs*"
defines { "_CRT_SECURE_NO_DEPRECATE", "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" }
configuration { "windows", "Release" }
flags { "NoIncrementalLink", "LinkTimeOptimization" }
configuration { "macosx", "gmake" }
buildoptions { "-mmacosx-version-min=10.4" }
linkoptions { "-mmacosx-version-min=10.4" }
project "Premake5"
targetname "premake5"
language "C"
kind "ConsoleApp"
includedirs { "src/host/lua/src" }
-- optional 3rd party libraries
if not _OPTIONS["no-zlib"] then
includedirs { "contrib/zlib", "contrib/libzip" }
links { "zip-lib", "zlib-lib" }
end
if not _OPTIONS["no-curl"] then
includedirs { "contrib/curl/include" }
links { "curl-lib" }
end
files
{
"*.txt", "**.lua",
"src/**.h", "src/**.c",
}
excludes
{
"src/host/lua/src/lauxlib.c",
"src/host/lua/src/lua.c",
"src/host/lua/src/luac.c",
"src/host/lua/src/print.c",
"src/host/lua/**.lua",
"src/host/lua/etc/*.c"
}
configuration "Debug"
targetdir "bin/debug"
debugargs { "--scripts=%{prj.location}/%{path.getrelative(prj.location, prj.basedir)} test"}
debugdir "%{path.getrelative(prj.location, prj.basedir)}"
configuration "Release"
targetdir "bin/release"
configuration "windows"
links { "ole32", "ws2_32" }
configuration "linux or bsd or hurd"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
linkoptions { "-rdynamic" }
configuration "linux or hurd"
links { "dl", "rt" }
configuration "linux"
if not _OPTIONS["no-curl"] and os.findlib("ssl") then
links { "ssl", "crypto" }
end
configuration "macosx"
defines { "LUA_USE_MACOSX" }
links { "CoreServices.framework" }
if not _OPTIONS["no-curl"] then
links { "Security.framework" }
end
configuration { "macosx", "gmake" }
toolset "clang"
configuration { "solaris" }
linkoptions { "-Wl,--export-dynamic" }
configuration "aix"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
-- optional 3rd party libraries
group "contrib"
if not _OPTIONS["no-zlib"] then
include "contrib/zlib"
include "contrib/libzip"
end
if not _OPTIONS["no-curl"] then
include "contrib/curl"
end
--
-- A more thorough cleanup.
--
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
|
Final debugargs/debugdir fix.
|
Final debugargs/debugdir fix.
|
Lua
|
bsd-3-clause
|
CodeAnxiety/premake-core,mendsley/premake-core,starkos/premake-core,dcourtois/premake-core,LORgames/premake-core,bravnsgaard/premake-core,lizh06/premake-core,premake/premake-core,lizh06/premake-core,aleksijuvani/premake-core,premake/premake-core,TurkeyMan/premake-core,tvandijck/premake-core,CodeAnxiety/premake-core,aleksijuvani/premake-core,jstewart-amd/premake-core,TurkeyMan/premake-core,xriss/premake-core,LORgames/premake-core,starkos/premake-core,dcourtois/premake-core,soundsrc/premake-core,premake/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,jstewart-amd/premake-core,Blizzard/premake-core,starkos/premake-core,lizh06/premake-core,mandersan/premake-core,resetnow/premake-core,dcourtois/premake-core,jstewart-amd/premake-core,martin-traverse/premake-core,mendsley/premake-core,CodeAnxiety/premake-core,bravnsgaard/premake-core,tvandijck/premake-core,starkos/premake-core,noresources/premake-core,noresources/premake-core,tvandijck/premake-core,xriss/premake-core,soundsrc/premake-core,xriss/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,soundsrc/premake-core,mandersan/premake-core,Blizzard/premake-core,resetnow/premake-core,premake/premake-core,dcourtois/premake-core,dcourtois/premake-core,premake/premake-core,mandersan/premake-core,resetnow/premake-core,LORgames/premake-core,resetnow/premake-core,aleksijuvani/premake-core,tvandijck/premake-core,martin-traverse/premake-core,noresources/premake-core,sleepingwit/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,noresources/premake-core,soundsrc/premake-core,lizh06/premake-core,sleepingwit/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,martin-traverse/premake-core,Blizzard/premake-core,starkos/premake-core,noresources/premake-core,sleepingwit/premake-core,mandersan/premake-core,Zefiros-Software/premake-core,premake/premake-core,tvandijck/premake-core,Blizzard/premake-core,resetnow/premake-core,mendsley/premake-core,xriss/premake-core,TurkeyMan/premake-core,sleepingwit/premake-core,jstewart-amd/premake-core,aleksijuvani/premake-core,premake/premake-core,starkos/premake-core,jstewart-amd/premake-core,CodeAnxiety/premake-core,dcourtois/premake-core,noresources/premake-core,Blizzard/premake-core,dcourtois/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,CodeAnxiety/premake-core,mendsley/premake-core,martin-traverse/premake-core,LORgames/premake-core,noresources/premake-core,LORgames/premake-core,bravnsgaard/premake-core,bravnsgaard/premake-core,xriss/premake-core,starkos/premake-core,TurkeyMan/premake-core,mandersan/premake-core,TurkeyMan/premake-core
|
9b0eb118b3a9c7f682176bbc033fbc0a515636f4
|
Server/Plugins/InfoReg.lua
|
Server/Plugins/InfoReg.lua
|
-- InfoReg.lua
-- Implements registration functions that process g_PluginInfo
--- Lists all the subcommands that the player has permissions for
local function ListSubcommands(a_Player, a_Subcommands, a_CmdString)
if (a_Player == nil) then
LOGINFO("The " .. a_CmdString .. " command requires another verb:")
else
a_Player:SendMessage("The " .. a_CmdString .. " command requires another verb:")
end
-- Enum all the subcommands:
local Verbs = {}
for cmd, info in pairs(a_Subcommands) do
if ((a_Player == nil) or (a_Player:HasPermission(info.Permission or ""))) then
table.insert(Verbs, a_CmdString .. " " .. cmd)
end
end
table.sort(Verbs)
-- Send the list:
if (a_Player == nil) then
for idx, verb in ipairs(Verbs) do
LOGINFO(" " .. verb)
end
else
for idx, verb in ipairs(Verbs) do
a_Player:SendMessage(cCompositeChat(" ", mtInfo):AddSuggestCommandPart(verb, verb))
end
end
end
--- This is a generic command callback used for handling multicommands' parent commands
-- For example, if there are "/gal save" and "/gal load" commands, this callback handles the "/gal" command
-- It is used for both console and in-game commands; the console version has a_Player set to nil
local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_Level, a_EntireCommand)
local Verb = a_Split[a_Level + 1]
if (Verb == nil) then
-- No verb was specified. If there is a handler for the upper level command, call it:
if (a_CmdInfo.Handler ~= nil) then
return a_CmdInfo.Handler(a_Split, a_Player, a_EntireCommand)
end
-- Let the player know they need to give a subcommand:
assert(type(a_CmdInfo.Subcommands) == "table", "Info.lua error: There is no handler for command \"" .. a_CmdString .. "\" and there are no subcommands defined at level " .. a_Level)
ListSubcommands(a_Player, a_CmdInfo.Subcommands, a_CmdString)
return true
end
-- A verb was specified, look it up in the subcommands table:
local Subcommand = a_CmdInfo.Subcommands[Verb]
if (Subcommand == nil) then
if (a_Level > 1) then
-- This is a true subcommand, display the message and make MCS think the command was handled
-- Otherwise we get weird behavior: for "/cmd verb" we get "unknown command /cmd" although "/cmd" is valid
if (a_Player == nil) then
LOGWARNING("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
else
a_Player:SendMessage("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
end
return true
end
-- This is a top-level command, let MCS handle the unknown message
return false;
end
-- Check the permission:
if (a_Player ~= nil) then
if not(a_Player:HasPermission(Subcommand.Permission or "")) then
a_Player:SendMessage("You don't have permission to execute this command")
return true
end
end
-- If the handler is not valid, check the next sublevel:
if (Subcommand.Handler == nil) then
if (Subcommand.Subcommands == nil) then
LOG("Cannot find handler for command " .. a_CmdString .. " " .. Verb)
return false
end
return MultiCommandHandler(a_Split, a_Player, a_CmdString .. " " .. Verb, Subcommand, a_Level + 1, a_EntireCommand)
end
-- Execute:
return Subcommand.Handler(a_Split, a_Player, a_EntireCommand)
end
--- Registers all commands specified in the g_PluginInfo.Commands
function RegisterPluginInfoCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
-- a_Level is the depth of the subcommands being registered, with 1 being the top level command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil)
-- A table that will hold aliases to subcommands temporarily, during subcommand iteration
local AliasTable = {}
-- Iterate through the subcommands, register them, and accumulate aliases:
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd
local Handler = info.Handler
-- Provide a special handler for multicommands:
if (info.Subcommands ~= nil) then
Handler = function(a_Split, a_Player, a_EntireCommand)
return MultiCommandHandler(a_Split, a_Player, CmdName, info, a_Level, a_EntireCommand)
end
end
if (Handler == nil) then
LOGWARNING(g_PluginInfo.Name .. ": Invalid handler for command " .. CmdName .. ", command will not be registered.")
else
local HelpString
if (info.HelpString ~= nil) then
HelpString = " - " .. info.HelpString
else
HelpString = ""
end
cPluginManager:BindCommand(CmdName, info.Permission or "", Handler, HelpString)
-- Register all aliases for the command:
if (info.Alias ~= nil) then
if (type(info.Alias) == "string") then
info.Alias = {info.Alias}
end
for idx, alias in ipairs(info.Alias) do
cPluginManager:BindCommand(a_Prefix .. alias, info.Permission or "", Handler, HelpString)
-- Also copy the alias's info table as a separate subcommand,
-- so that MultiCommandHandler() handles it properly. Need to off-load into a separate table
-- than the one we're currently iterating and join after the iterating.
AliasTable[alias] = info
end
end
end -- else (if Handler == nil)
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1)
end
end -- for cmd, info - a_Subcommands[]
-- Add the subcommand aliases that were off-loaded during registration:
for alias, info in pairs(AliasTable) do
a_Subcommands[alias] = info
end
AliasTable = {}
end
-- Loop through all commands in the plugin info, register each:
if (g_PluginInfo.Commands) then
RegisterSubcommands("", g_PluginInfo.Commands, 1)
end
end
--- Registers all console commands specified in the g_PluginInfo.ConsoleCommands
function RegisterPluginInfoConsoleCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil)
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd
local Handler = info.Handler
if (Handler == nil) then
Handler = function(a_Split, a_EntireCommand)
return MultiCommandHandler(a_Split, nil, CmdName, info, a_Level, a_EntireCommand)
end
end
cPluginManager:BindConsoleCommand(CmdName, Handler, info.HelpString or "")
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1)
end
end
end
-- Loop through all commands in the plugin info, register each:
if (g_PluginInfo.ConsoleCommands) then
RegisterSubcommands("", g_PluginInfo.ConsoleCommands, 1)
end
end
|
-- InfoReg.lua
-- Implements registration functions that process g_PluginInfo
--- Lists all the subcommands that the player has permissions for
local function ListSubcommands(a_Player, a_Subcommands, a_CmdString)
if (a_Player == nil) then
LOGINFO("The " .. a_CmdString .. " command requires another verb:")
else
a_Player:SendMessage("The " .. a_CmdString .. " command requires another verb:")
end
-- Enum all the subcommands:
local Verbs = {}
for cmd, info in pairs(a_Subcommands) do
if ((a_Player == nil) or (a_Player:HasPermission(info.Permission or ""))) then
table.insert(Verbs, a_CmdString .. " " .. cmd)
end
end
table.sort(Verbs)
-- Send the list:
if (a_Player == nil) then
for idx, verb in ipairs(Verbs) do
LOGINFO(" " .. verb)
end
else
for idx, verb in ipairs(Verbs) do
a_Player:SendMessage(cCompositeChat(" ", mtInfo):AddSuggestCommandPart(verb, verb))
end
end
end
--- This is a generic command callback used for handling multicommands' parent commands
-- For example, if there are "/gal save" and "/gal load" commands, this callback handles the "/gal" command
-- It is used for both console and in-game commands; the console version has a_Player set to nil
local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_Level, a_EntireCommand)
local Verb = a_Split[a_Level + 1]
if (Verb == nil) then
-- No verb was specified. If there is a handler for the upper level command, call it:
if (a_CmdInfo.Handler ~= nil) then
return a_CmdInfo.Handler(a_Split, a_Player, a_EntireCommand)
end
-- Let the player know they need to give a subcommand:
assert(type(a_CmdInfo.Subcommands) == "table", "Info.lua error: There is no handler for command \"" .. a_CmdString .. "\" and there are no subcommands defined at level " .. a_Level)
ListSubcommands(a_Player, a_CmdInfo.Subcommands, a_CmdString)
return true
end
-- A verb was specified, look it up in the subcommands table:
local Subcommand = a_CmdInfo.Subcommands[Verb]
if (Subcommand == nil) then
if (a_Level + 1 > 1) then
-- This is a true subcommand, display the message and make MCS think the command was handled
-- Otherwise we get weird behavior: for "/cmd verb" we get "unknown command /cmd" although "/cmd" is valid
if (a_Player == nil) then
LOGWARNING("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
else
a_Player:SendMessage("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
end
return true
end
-- This is a top-level command, let MCS handle the unknown message
return false;
end
-- Check the permission:
if (a_Player ~= nil) then
if not(a_Player:HasPermission(Subcommand.Permission or "")) then
a_Player:SendMessage("You don't have permission to execute this command")
return true
end
end
-- First check if the subcommand has subcommands
if (Subcommand.Subcommands ~= nil) then
-- Next sublevel
return MultiCommandHandler(a_Split, a_Player, a_CmdString .. " " .. Verb, Subcommand, a_Level + 1, a_EntireCommand)
elseif (Subcommand.Handler == nil) then
-- Subcommand has no subcommands and the handler is not found, report error
LOGWARNING("Cannot find handler for command " .. a_CmdString .. " " .. Verb)
return false
end
-- Execute:
return Subcommand.Handler(a_Split, a_Player, a_EntireCommand)
end
--- Registers all commands specified in the g_PluginInfo.Commands
function RegisterPluginInfoCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
-- a_Level is the depth of the subcommands being registered, with 1 being the top level command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil)
-- A table that will hold aliases to subcommands temporarily, during subcommand iteration
local AliasTable = {}
-- Iterate through the subcommands, register them, and accumulate aliases:
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd
local Handler = info.Handler
-- Provide a special handler for multicommands:
if (info.Subcommands ~= nil) then
Handler = function(a_Split, a_Player, a_EntireCommand)
return MultiCommandHandler(a_Split, a_Player, CmdName, info, a_Level, a_EntireCommand)
end
end
if (Handler == nil) then
LOGWARNING(g_PluginInfo.Name .. ": Invalid handler for command " .. CmdName .. ", command will not be registered.")
else
local HelpString
if (info.HelpString ~= nil) then
HelpString = " - " .. info.HelpString
else
HelpString = ""
end
cPluginManager:BindCommand(CmdName, info.Permission or "", Handler, HelpString)
-- Register all aliases for the command:
if (info.Alias ~= nil) then
if (type(info.Alias) == "string") then
info.Alias = {info.Alias}
end
for idx, alias in ipairs(info.Alias) do
cPluginManager:BindCommand(a_Prefix .. alias, info.Permission or "", Handler, HelpString)
-- Also copy the alias's info table as a separate subcommand,
-- so that MultiCommandHandler() handles it properly. Need to off-load into a separate table
-- than the one we're currently iterating and join after the iterating.
AliasTable[alias] = info
end
end
end -- else (if Handler == nil)
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1)
end
end -- for cmd, info - a_Subcommands[]
-- Add the subcommand aliases that were off-loaded during registration:
for alias, info in pairs(AliasTable) do
a_Subcommands[alias] = info
end
AliasTable = {}
end
-- Loop through all commands in the plugin info, register each:
if (g_PluginInfo.Commands) then
RegisterSubcommands("", g_PluginInfo.Commands, 1)
end
end
--- Registers all console commands specified in the g_PluginInfo.ConsoleCommands
function RegisterPluginInfoConsoleCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil)
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd
local Handler = info.Handler
if (Handler == nil) then
Handler = function(a_Split, a_EntireCommand)
return MultiCommandHandler(a_Split, nil, CmdName, info, a_Level, a_EntireCommand)
end
end
cPluginManager:BindConsoleCommand(CmdName, Handler, info.HelpString or "")
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1)
end
end
end
-- Loop through all commands in the plugin info, register each:
if (g_PluginInfo.ConsoleCommands) then
RegisterSubcommands("", g_PluginInfo.ConsoleCommands, 1)
end
end
|
Corrected check for level of subcommand and fixed multiple levels not working (#3758)
|
Corrected check for level of subcommand and fixed multiple levels not working (#3758)
* Corrected check for level of subcommand
A message instead of an error is printed, if the sub command is unknown
* Multiple levels of sub commands now works, too
|
Lua
|
apache-2.0
|
nounoursheureux/MCServer,mc-server/MCServer,mc-server/MCServer,nounoursheureux/MCServer,nounoursheureux/MCServer,nounoursheureux/MCServer,nounoursheureux/MCServer,mc-server/MCServer,mc-server/MCServer,mc-server/MCServer,mc-server/MCServer,nounoursheureux/MCServer
|
7f271688298006d04927fa63cc638a6cbc2bf015
|
mod_adhoc_cmd_modules/mod_adhoc_cmd_modules.lua
|
mod_adhoc_cmd_modules/mod_adhoc_cmd_modules.lua
|
-- Copyright (C) 2009-2010 Florian Zeitz
--
-- This file is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local _G = _G;
local prosody = _G.prosody;
local hosts = prosody.hosts;
require "util.iterators";
local dataforms_new = require "util.dataforms".new;
local array = require "util.array";
local modulemanager = require "modulemanager";
local adhoc_new = module:require "adhoc".new;
function list_modules_handler(self, data, state)
local result = dataforms_new {
title = "List of loaded modules";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#list" };
{ name = "modules", type = "text-multi", label = "The following modules are loaded:" };
};
local modules = array.collect(keys(hosts[data.to].modules)):sort():concat("\n");
return { status = "completed", result = { layout = result; data = { modules = modules } } };
end
function load_module_handler(self, data, state)
local layout = dataforms_new {
title = "Load module";
instructions = "Specify the module to be loaded";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#load" };
{ name = "module", type = "text-single", required = true, label = "Module to be loaded:"};
};
if state then
if data.action == "cancel" then
return { status = "canceled" };
end
local fields = layout:data(data.form);
if (not fields.module) or (fields.module == "") then
return { status = "completed", error = {
message = "Please specify a module. (This means your client misbehaved, as this field is required)"
} };
end
if modulemanager.is_loaded(data.to, fields.module) then
return { status = "completed", info = "Module already loaded" };
end
local ok, err = modulemanager.load(data.to, fields.module);
if ok then
return { status = "completed", info = 'Module "'..fields.module..'" successfully loaded on host "'..data.to..'".' };
else
return { status = "completed", error = { message = 'Failed to load module "'..fields.module..'" on host "'..data.to..
'". Error was: "'..tostring(err or "<unspecified>")..'"' } };
end
else
local modules = array.collect(keys(hosts[data.to].modules)):sort();
return { status = "executing", form = layout }, "executing";
end
end
-- TODO: Allow reloading multiple modules (depends on list-multi)
function reload_modules_handler(self, data, state)
local layout = dataforms_new {
title = "Reload module";
instructions = "Select the module to be reloaded";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#reload" };
{ name = "module", type = "list-single", required = true, label = "Module to be reloaded:"};
};
if state then
if data.action == "cancel" then
return { status = "canceled" };
end
local fields = layout:data(data.form);
if (not fields.module) or (fields.module == "") then
return { status = "completed", error = {
message = "Please specify a module. (This means your client misbehaved, as this field is required)"
} };
end
local ok, err = modulemanager.reload(data.to, fields.module);
if ok then
return { status = "completed", info = 'Module "'..fields.module..'" successfully reloaded on host "'..data.to..'".' };
else
return { status = "completed", error = { message = 'Failed to reload module "'..fields.module..'" on host "'..data.to..
'". Error was: "'..tostring(err)..'"' } };
end
else
local modules = array.collect(keys(hosts[data.to].modules)):sort();
return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing";
end
end
-- TODO: Allow unloading multiple modules (depends on list-multi)
function unload_modules_handler(self, data, state)
local layout = dataforms_new {
title = "Unload module";
instructions = "Select the module to be unloaded";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#unload" };
{ name = "module", type = "list-single", required = true, label = "Module to be unloaded:"};
};
if state then
if data.action == "cancel" then
return { status = "canceled" };
end
local fields = layout:data(data.form);
if (not fields.module) or (fields.module == "") then
return { status = "completed", error = {
message = "Please specify a module. (This means your client misbehaved, as this field is required)"
} };
end
local ok, err = modulemanager.unload(data.to, fields.module);
if ok then
return { status = "completed", info = 'Module "'..fields.module..'" successfully unloaded on host "'..data.to..'".' };
else
return { status = "completed", error = { message = 'Failed to unload module "'..fields.module..'" on host "'..data.to..
'". Error was: "'..tostring(err)..'"' } };
end
else
local modules = array.collect(keys(hosts[data.to].modules)):sort();
return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing";
end
end
local list_modules_desc = adhoc_new("List loaded modules", "http://prosody.im/protocol/modules#list", list_modules_handler, "admin");
local load_module_desc = adhoc_new("Load module", "http://prosody.im/protocol/modules#load", load_module_handler, "admin");
local reload_modules_desc = adhoc_new("Reload module", "http://prosody.im/protocol/modules#reload", reload_modules_handler, "admin");
local unload_modules_desc = adhoc_new("Unload module", "http://prosody.im/protocol/modules#unload", unload_modules_handler, "admin");
module:add_item("adhoc", list_modules_desc);
module:add_item("adhoc", load_module_desc);
module:add_item("adhoc", reload_modules_desc);
module:add_item("adhoc", unload_modules_desc);
|
-- Copyright (C) 2009-2010 Florian Zeitz
--
-- This file is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local _G = _G;
local prosody = _G.prosody;
local hosts = prosody.hosts;
require "util.iterators";
local dataforms_new = require "util.dataforms".new;
local array = require "util.array";
local modulemanager = require "modulemanager";
local adhoc_new = module:require "adhoc".new;
function list_modules_handler(self, data, state)
local result = dataforms_new {
title = "List of loaded modules";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#list" };
{ name = "modules", type = "text-multi", label = "The following modules are loaded:" };
};
local modules = array.collect(keys(hosts[data.to].modules)):sort():concat("\n");
return { status = "completed", result = { layout = result; data = { modules = modules } } };
end
function load_module_handler(self, data, state)
local layout = dataforms_new {
title = "Load module";
instructions = "Specify the module to be loaded";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#load" };
{ name = "module", type = "text-single", required = true, label = "Module to be loaded:"};
};
if state then
if data.action == "cancel" then
return { status = "canceled" };
end
local fields = layout:data(data.form);
if (not fields.module) or (fields.module == "") then
return { status = "completed", error = {
message = "Please specify a module."
} };
end
if modulemanager.is_loaded(data.to, fields.module) then
return { status = "completed", info = "Module already loaded" };
end
local ok, err = modulemanager.load(data.to, fields.module);
if ok then
return { status = "completed", info = 'Module "'..fields.module..'" successfully loaded on host "'..data.to..'".' };
else
return { status = "completed", error = { message = 'Failed to load module "'..fields.module..'" on host "'..data.to..
'". Error was: "'..tostring(err or "<unspecified>")..'"' } };
end
else
local modules = array.collect(keys(hosts[data.to].modules)):sort();
return { status = "executing", form = layout }, "executing";
end
end
-- TODO: Allow reloading multiple modules (depends on list-multi)
function reload_modules_handler(self, data, state)
local layout = dataforms_new {
title = "Reload module";
instructions = "Select the module to be reloaded";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#reload" };
{ name = "module", type = "list-single", required = true, label = "Module to be reloaded:"};
};
if state then
if data.action == "cancel" then
return { status = "canceled" };
end
local fields = layout:data(data.form);
if (not fields.module) or (fields.module == "") then
return { status = "completed", error = {
message = "Please specify a module. (This means your client misbehaved, as this field is required)"
} };
end
local ok, err = modulemanager.reload(data.to, fields.module);
if ok then
return { status = "completed", info = 'Module "'..fields.module..'" successfully reloaded on host "'..data.to..'".' };
else
return { status = "completed", error = { message = 'Failed to reload module "'..fields.module..'" on host "'..data.to..
'". Error was: "'..tostring(err)..'"' } };
end
else
local modules = array.collect(keys(hosts[data.to].modules)):sort();
return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing";
end
end
-- TODO: Allow unloading multiple modules (depends on list-multi)
function unload_modules_handler(self, data, state)
local layout = dataforms_new {
title = "Unload module";
instructions = "Select the module to be unloaded";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#unload" };
{ name = "module", type = "list-single", required = true, label = "Module to be unloaded:"};
};
if state then
if data.action == "cancel" then
return { status = "canceled" };
end
local fields = layout:data(data.form);
if (not fields.module) or (fields.module == "") then
return { status = "completed", error = {
message = "Please specify a module. (This means your client misbehaved, as this field is required)"
} };
end
local ok, err = modulemanager.unload(data.to, fields.module);
if ok then
return { status = "completed", info = 'Module "'..fields.module..'" successfully unloaded on host "'..data.to..'".' };
else
return { status = "completed", error = { message = 'Failed to unload module "'..fields.module..'" on host "'..data.to..
'". Error was: "'..tostring(err)..'"' } };
end
else
local modules = array.collect(keys(hosts[data.to].modules)):sort();
return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing";
end
end
local list_modules_desc = adhoc_new("List loaded modules", "http://prosody.im/protocol/modules#list", list_modules_handler, "admin");
local load_module_desc = adhoc_new("Load module", "http://prosody.im/protocol/modules#load", load_module_handler, "admin");
local reload_modules_desc = adhoc_new("Reload module", "http://prosody.im/protocol/modules#reload", reload_modules_handler, "admin");
local unload_modules_desc = adhoc_new("Unload module", "http://prosody.im/protocol/modules#unload", unload_modules_handler, "admin");
module:add_item("adhoc", list_modules_desc);
module:add_item("adhoc", load_module_desc);
module:add_item("adhoc", reload_modules_desc);
module:add_item("adhoc", unload_modules_desc);
|
mod_adhoc_cmd_modules: Fix error message
|
mod_adhoc_cmd_modules: Fix error message
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
d1f7aecd2a9f1f77daf4d697cf3651def580d87d
|
source/game/versusGame.lua
|
source/game/versusGame.lua
|
--------------------------------------------------------------------------------
-- game.lua - Defines a game which(for now) manages the game logic for a single player game
--------------------------------------------------------------------------------
-- TODO: clean this up!
require "source/utilities/vector"
require "source/utilities/extensions/math"
require "source/game/enemy"
require "source/game/tower"
require "source/pathfinder"
require "source/game/map"
require "source/networking/networkFrameworkEntity"
require "assets/enemies/enemyTypes"
local Towers = require "assets/towers/towers"
-- import
local flower = flower
local math = math
local vector = vector
local MOAIGridSpace = MOAIGridSpace
local ipairs = ipairs
VersusGame = flower.class()
function VersusGame:init(t)
-- TODO: pass is variables instead of hardcoding them
self.texture = "hex-tiles.png"
self.width = 50
self.height = 100
self.tileWidth = 128
self.tileHeight = 111
self.radius = 24
self.default_tile = 0
self.direction = 1
self.messageBoxText = ""
self.chatLog = "hello"
self.currentWave = 1
self.view = t.view
self.nfe = NetworkFrameworkEntity{}
local connected, networkError = self.nfe:isConnected()
if not connected then
self:showEndGameMessage("Cannot connect to server: " .. networkError)
end
end
-- This function is used by the guiUtilities file to generate
-- the status field in the UI
function VersusGame:generateItemInfo()
return self.chatLog
end
function VersusGame:generateStatus()
return "Welcome to Multiplayer:\n " .. self.nfe.theirIP .. ""
end
-- TODO: this could be cleaned up, I don't really like using the bool `recieve` here
function VersusGame:submitText(text, recieve)
if not recieve then
self.nfe:talker(text)
text = "You: " .. text
else
text = "Them: " .. text
end
--self.messageBoxText = text
self.chatLog = self.chatLog .. "\n" .. text..""--self.messageBoxText .. ""
--self.generateItemInfo()
self:updateGUI()
end
function VersusGame:getPopupPos()
return {flower.viewWidth / 5, flower.viewHeight / 2}
end
function VersusGame:getPopupSize()
return {flower.viewWidth / 2, 100}
end
-- Initializes the game to run by turning on the spawning of enemies
function VersusGame:run()
self.enemies = {}
self.enemiesKilled = 0
self.spawnedEnemies = 0
self:paused(false)
flower.Executors.callLoop(self.loop, self)
end
-- Updates to the next wave while taking account the win condition
-- TODO: clean up win condition
function VersusGame:updateWave()
self:paused(true)
self.enemiesKilled = 0
self.spawnedEnemies = 0
self.currentWave = (self.currentWave + 1)
if self.currentWave > #self.map:getWaves() then
self:showEndGameMessage("You Win!")
self.gameOver = true -- todo: this is really messed up as of right now. Change it!
else
self.timers.spawnTimer:setSpan(self.map:getWaves()[self.currentWave].spawnRate)
self:updateGUI()
local msgBox = generateMsgBox(self:getPopupPos(), self:getPopupSize(), "Wave: " .. self.currentWave, self.view)
msgBox:showPopup()
flower.Executors.callLaterTime(3, function()
msgBox:hidePopup()
self:paused(false)
end)
end
end
-- Main game loop which updates all of the entities in the game
function VersusGame:loop()
self:updateGUI()
local data = self.nfe:listener()
if data then
self:submitText(data, true)
elseif not self.nfe:isConnected() then
self:showEndGameMessage("Disconnected from server")
end
while self:paused() do
coroutine.yield()
end
return self:stopped()
end
-- Looses a life and ends the game if the lives count reaches 0
function VersusGame:loseLife()
self.currentLives = self.currentLives - 1
if self.currentLives <= 0 then
self:showEndGameMessage("Game Over!")
end
end
-- Pauses the game if p is true, unpauses the game if p is false
-- If p is nil, paused() return true if the game is paused
function VersusGame:paused(p)
if p ~= nil then
if self.timers then
for k, timer in pairs(self.timers) do
if p then
timer:pause()
else
timer:start()
end
end
end
self.isPaused = p
updatePauseButton(not p)
else
return self.isPaused
end
end
-- Stops the game if s is true
-- Returns true if the game if s is nil
function VersusGame:stopped(s)
if s ~= nil then
if s == true then
self.nfe:stop()
if self.soundManager then
self.soundManager:stop()
end
if self.timers then
for k, timer in pairs(self.timers) do
flower.Executors.cancel(timer)
end
end
end
self.isStopped = s
else
return self.isStopped
end
end
function VersusGame:updateGUI()
updateStatusText(self:generateStatus())
updateChatText(self:generateItemInfo())
end
-- Shows a message box with a message just before ending the VersusGame
function VersusGame:showEndGameMessage(msg)
local msgBox = generateMsgBox(self:getPopupPos(), self:getPopupSize(), msg, self.view)
msgBox:showPopup()
self:stopped(true)
end
-- Updates the current tower selected
function VersusGame:selectTower(tower)
self.towerSelected = tower
self:updateGUI()
end
-- Returns the selected tower
function VersusGame:getSelectedTower()
return self.towerSelected
end
-- Event callback for mouse touch input
--TODO: clean this up
function VersusGame:onTouchDown(pos)
if self:stopped() then
flower.closeScene({animation = "fade"})
end
local tile = self.map:getGrid():getTile(pos[1], pos[2])
if tile == TOWER_TYPES.EMPTY and self.towerSelected ~= nil then
-- Try to place new tower down
if self.currentCash >= self.towerSelected.type.cost then
-- Decrease cash amount
self.currentCash = self.currentCash - self.towerSelected.type.cost
-- Place tower on map
self.map:getGrid():setTile(pos[1], pos[2], self.towerSelected.type.id)
self.towers[Tower.serialize_pos(pos)] = Tower(self.towerSelected.type, pos)
self:updateGUI()
else
-- TODO: alert for insufficient funds
end
elseif tile ~= TOWER_TYPES.EMPTY and tile ~= TOWER_TYPES.ENEMY then
-- Select already placed tower
-- TODO: upgrade and sell options appear
self:selectTower(self.towers[Tower.serialize_pos(pos)])
self.map:selectTile(pos)
end
end
|
--------------------------------------------------------------------------------
-- game.lua - Defines a game which(for now) manages the game logic for a single player game
--------------------------------------------------------------------------------
-- TODO: clean this up!
require "source/utilities/vector"
require "source/utilities/extensions/math"
require "source/game/enemy"
require "source/game/tower"
require "source/pathfinder"
require "source/game/map"
require "source/networking/networkFrameworkEntity"
require "source/utilities/limitedQueue"
require "assets/enemies/enemyTypes"
local Towers = require "assets/towers/towers"
-- import
local flower = flower
local math = math
local vector = vector
local MOAIGridSpace = MOAIGridSpace
local ipairs = ipairs
VersusGame = flower.class()
function VersusGame:init(t)
-- TODO: pass is variables instead of hardcoding them
self.texture = "hex-tiles.png"
self.width = 50
self.height = 100
self.tileWidth = 128
self.tileHeight = 111
self.radius = 24
self.default_tile = 0
self.direction = 1
self.messageBoxText = ""
self.chatQueue = LimitedQueue(12)
self.chatQueue:push("Hello")
self.currentWave = 1
self.view = t.view
self.nfe = NetworkFrameworkEntity{}
local connected, networkError = self.nfe:isConnected()
if not connected then
self:showEndGameMessage("Cannot connect to server: " .. networkError)
end
end
-- This function is used by the guiUtilities file to generate
-- the status field in the UI
function VersusGame:generateItemInfo()
return self.chatQueue:toString()
end
function VersusGame:generateStatus()
return "Welcome to Multiplayer:\n " .. self.nfe.theirIP .. ""
end
-- TODO: this could be cleaned up, I don't really like using the bool `recieve` here
function VersusGame:submitText(text, recieve)
if not recieve then
self.nfe:talker(text)
text = "You: " .. text
else
text = "Them: " .. text
end
self.chatQueue:push(text)
self:updateGUI()
end
function VersusGame:getPopupPos()
return {flower.viewWidth / 5, flower.viewHeight / 2}
end
function VersusGame:getPopupSize()
return {flower.viewWidth / 2, 100}
end
-- Initializes the game to run by turning on the spawning of enemies
function VersusGame:run()
self.enemies = {}
self.enemiesKilled = 0
self.spawnedEnemies = 0
self:paused(false)
flower.Executors.callLoop(self.loop, self)
end
-- Updates to the next wave while taking account the win condition
-- TODO: clean up win condition
function VersusGame:updateWave()
self:paused(true)
self.enemiesKilled = 0
self.spawnedEnemies = 0
self.currentWave = (self.currentWave + 1)
if self.currentWave > #self.map:getWaves() then
self:showEndGameMessage("You Win!")
else
self.timers.spawnTimer:setSpan(self.map:getWaves()[self.currentWave].spawnRate)
self:updateGUI()
local msgBox = generateMsgBox(self:getPopupPos(), self:getPopupSize(), "Wave: " .. self.currentWave, self.view)
msgBox:showPopup()
flower.Executors.callLaterTime(3, function()
msgBox:hidePopup()
self:paused(false)
end)
end
end
-- Main game loop which updates all of the entities in the game
function VersusGame:loop()
self:updateGUI()
local data = self.nfe:listener()
if data then
self:submitText(data, true)
elseif not self.nfe:isConnected() then
self:showEndGameMessage("Disconnected from server")
end
while self:paused() do
coroutine.yield()
end
return self:stopped()
end
-- Looses a life and ends the game if the lives count reaches 0
function VersusGame:loseLife()
self.currentLives = self.currentLives - 1
if self.currentLives <= 0 then
self:showEndGameMessage("Game Over!")
end
end
-- Pauses the game if p is true, unpauses the game if p is false
-- If p is nil, paused() return true if the game is paused
function VersusGame:paused(p)
if p ~= nil then
if self.timers then
for k, timer in pairs(self.timers) do
if p then
timer:pause()
else
timer:start()
end
end
end
self.isPaused = p
updatePauseButton(not p)
else
return self.isPaused
end
end
-- Stops the game if s is true
-- Returns true if the game if s is nil
function VersusGame:stopped(s)
if s ~= nil then
if s == true then
self.nfe:stop()
if self.soundManager then
self.soundManager:stop()
end
if self.timers then
for k, timer in pairs(self.timers) do
flower.Executors.cancel(timer)
end
end
end
self.isStopped = s
else
return self.isStopped
end
end
function VersusGame:updateGUI()
updateStatusText(self:generateStatus())
updateChatText(self:generateItemInfo())
end
-- Shows a message box with a message just before ending the VersusGame
function VersusGame:showEndGameMessage(msg)
local msgBox = generateMsgBox(self:getPopupPos(), self:getPopupSize(), msg, self.view)
msgBox:showPopup()
self:stopped(true)
end
-- Updates the current tower selected
function VersusGame:selectTower(tower)
self.towerSelected = tower
self:updateGUI()
end
-- Returns the selected tower
function VersusGame:getSelectedTower()
return self.towerSelected
end
-- Event callback for mouse touch input
--TODO: clean this up
function VersusGame:onTouchDown(pos)
if self:stopped() then
flower.closeScene({animation = "fade"})
end
local tile = self.map:getGrid():getTile(pos[1], pos[2])
if tile == TOWER_TYPES.EMPTY and self.towerSelected ~= nil then
-- Try to place new tower down
if self.currentCash >= self.towerSelected.type.cost then
-- Decrease cash amount
self.currentCash = self.currentCash - self.towerSelected.type.cost
-- Place tower on map
self.map:getGrid():setTile(pos[1], pos[2], self.towerSelected.type.id)
self.towers[Tower.serialize_pos(pos)] = Tower(self.towerSelected.type, pos)
self:updateGUI()
else
-- TODO: alert for insufficient funds
end
elseif tile ~= TOWER_TYPES.EMPTY and tile ~= TOWER_TYPES.ENEMY then
-- Select already placed tower
-- TODO: upgrade and sell options appear
self:selectTower(self.towers[Tower.serialize_pos(pos)])
self.map:selectTile(pos)
end
end
|
Fixed clipped text in chat box. Fixes #46.
|
Fixed clipped text in chat box. Fixes #46.
|
Lua
|
mit
|
BryceMehring/Hexel
|
c10cf880a89825d117270275c3f84434ba26708c
|
src/copy.lua
|
src/copy.lua
|
#!/usr/bin/lua
-- WANT_JSON
local Ansible = require("ansible")
local File = require("fileutils")
local os = require("os")
function adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, index, module, directory_args, changed)
-- Walk the new directories list and make sure that permissions are as we would expect
local changed = false
if index <= #new_directory_list then
local working_dir = File.join(pre_existing_dir, new_directory_list[i])
directory_args['path'] = working_dir
changed = File.set_fs_attributes_if_different(module, directory_args, changed, nil)
changed = adjust_recursive_directory_permissions(working_dir, new_directory_list, index+1, module, directory_args, changed)
end
return changed
end
function main(arg)
local module = Ansible.new(
{ src = { required=true }
, original_basename = { required=false }
, content = { required=false }
, path = { aliases={'dest'}, required=true }
, backup = { default=false, type='bool' }
, force = { default=true, aliases={'thirsty'}, type='bool' }
, validate = { required=false, type='str' }
, directory_mode = { required=false }
, remote_src = { required=false, type='bool' }
-- file common args
-- , src = {}
, mode = { type='raw' }
, owner = {}
, group = {}
-- Selinux to ignore
, seuser = {}
, serole = {}
, selevel = {}
, setype = {}
, follow = {type='bool', default=false}
-- not taken by the file module, but other modules call file so it must ignore them
, content = {}
, backup = {}
-- , force = {}
, remote_src = {}
, regexp = {}
, delimiter = {}
-- , directory_mode = {}
}
)
module:parse(arg[1])
local p = module:get_params()
local src = File.expanduser(p['src'])
local dest = File.expanduser(p['path'])
local backup = p['backup']
local force = p['force']
local original_basename = p['original_basename']
local validate = p['validate']
local follow = p['follow']
local mode = p['mode']
local remote_src = p['remote_src']
if not File.exists(src) then
module:fail_json({msg="Source " .. src .. " not found"})
end
if not File.readable(src) then
module:fail_json({msg="Source " .. src .. " not readable"})
end
if File.isdir(src) then
module:fail_json({msg="Remote copy does not support recursive copy of directory: " .. src})
end
local checksum_src = File.sha1(module, src)
local checksum_dest = nil
local md5sum_src = File.md5(module, src)
local changed = false
-- Special handling for recursive copy - create intermediate dirs
if original_basename and string.match(dest, "/$") then
dest = File.join(dest, orignal_basename)
local dirname = File.dirname(dest)
if not File.exists(dirname) and File.isabs(dirname) then
local pre_existing_dir, new_directory_list = File.split_pre_existing_dir(dirname)
File.mkdirs(dirname)
local directory_args = p
local direcotry_mode = p['directory_mode']
adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, 1, module, directory_args, changed)
end
end
if File.exists(dest) then
if File.islnk(dest) and follow then
dest = File.realpath(dest)
end
if not force then
module:exit_json({msg="file already exists", src=src, dest=dest, changed=false})
end
if File.isdir(dest) then
local basename = File.basename(src)
if original_basename then
basename = original_basename
end
dest = File.join(dest, basename)
end
if File.readable(dest) then
checksum_dest = File.sha1(module, dest)
end
else
if not File.exists(File.dirname(dest)) then
if nil == File.stat(File.dirname(dest)) then
module:fail_json({msg="Destination directory " .. File.dirname(dest) .. " is not accessible"})
end
module:fail_json({msg="Destination directory " .. File.dirname(dest) .. " does not exist"})
end
end
if not File.writeable(File.dirname(dest)) then
module:fail_json({msg="Destination " .. File.dirname(dest) .. " not writeable"})
end
local backup_file = nil
if checksum_src ~= checksum_dest or File.islnk(dest) then
if not module:check_mode() then
if backup and File.exists(dest) then
backup_file = module:backup_local(dest)
end
local function err(res, msg)
if not res then
module:fail_json({msg="failed to copy: " .. src .. " to " .. dest .. ": " .. msg})
end
end
local res, msg
-- allow for conversion from symlink
if File.islnk(dest) then
res, msg = File.unlink(dest)
err(res, msg)
res, msg = File.touch(dest)
err(res, msg)
end
if validate then
-- FIXME: Validate is currently unsupported
end
if remote_src then
local tmpname, msg = File.mkstemp(File.dirname(dest) .. "/ansibltmp_XXXXXX")
err(tmpname, msg)
res, msg = module:copy(src, tmpdest)
err(res, msg)
res, msg = module:move(tmpdest, dest)
err(res, msg)
else
res, msg = module:move(src, dest)
err(res, msg)
end
end
changed = true
else
changed = false
end
res_args = { dest=dest, src=src, md5sum=md5sum_src, checksum=checksum_src, changed=changed }
if backup_file then
res_args['backup_file'] = backup_file
end
p['dest'] = dest
if not module:check_mode() then
local file_args = p
res_args['changed'] = File.set_fs_attributes_if_different(module, file_args, res_args['changed'], nil)
end
res_args['msg'] = "Dummy"
module:exit_json(res_args)
end
main(arg)
|
#!/usr/bin/lua
-- WANT_JSON
local Ansible = require("ansible")
local File = require("fileutils")
local os = require("os")
function adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, index, module, directory_args, changed)
-- Walk the new directories list and make sure that permissions are as we would expect
local changed = false
if index <= #new_directory_list then
local working_dir = File.join(pre_existing_dir, new_directory_list[i])
directory_args['path'] = working_dir
changed = File.set_fs_attributes_if_different(module, directory_args, changed, nil)
changed = adjust_recursive_directory_permissions(working_dir, new_directory_list, index+1, module, directory_args, changed)
end
return changed
end
function main(arg)
local module = Ansible.new(
{ src = { required=true }
, original_basename = { required=false }
, content = { required=false }
, path = { aliases={'dest'}, required=true }
, backup = { default=false, type='bool' }
, force = { default=true, aliases={'thirsty'}, type='bool' }
, validate = { required=false, type='str' }
, directory_mode = { required=false }
, remote_src = { required=false, type='bool' }
-- sha256sum, to check if the copy was successful - currently ignored
, checksum = {}
-- file common args
-- , src = {}
, mode = { type='raw' }
, owner = {}
, group = {}
-- Selinux to ignore
, seuser = {}
, serole = {}
, selevel = {}
, setype = {}
, follow = {type='bool', default=false}
-- not taken by the file module, but other modules call file so it must ignore them
, content = {}
, backup = {}
-- , force = {}
, remote_src = {}
, regexp = {}
, delimiter = {}
-- , directory_mode = {}
}
)
module:parse(arg[1])
local p = module:get_params()
local src = File.expanduser(p['src'])
local dest = File.expanduser(p['path'])
local backup = p['backup']
local force = p['force']
local original_basename = p['original_basename']
local validate = p['validate']
local follow = p['follow']
local mode = p['mode']
local remote_src = p['remote_src']
if not File.exists(src) then
module:fail_json({msg="Source " .. src .. " not found"})
end
if not File.readable(src) then
module:fail_json({msg="Source " .. src .. " not readable"})
end
if File.isdir(src) then
module:fail_json({msg="Remote copy does not support recursive copy of directory: " .. src})
end
local checksum_src = File.sha1(module, src)
local checksum_dest = nil
local md5sum_src = File.md5(module, src)
local changed = false
-- Special handling for recursive copy - create intermediate dirs
if original_basename and string.match(dest, "/$") then
dest = File.join(dest, orignal_basename)
local dirname = File.dirname(dest)
if not File.exists(dirname) and File.isabs(dirname) then
local pre_existing_dir, new_directory_list = File.split_pre_existing_dir(dirname)
File.mkdirs(dirname)
local directory_args = p
local direcotry_mode = p['directory_mode']
adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, 1, module, directory_args, changed)
end
end
if File.exists(dest) then
if File.islnk(dest) and follow then
dest = File.realpath(dest)
end
if not force then
module:exit_json({msg="file already exists", src=src, dest=dest, changed=false})
end
if File.isdir(dest) then
local basename = File.basename(src)
if original_basename then
basename = original_basename
end
dest = File.join(dest, basename)
end
if File.readable(dest) then
checksum_dest = File.sha1(module, dest)
end
else
if not File.exists(File.dirname(dest)) then
if nil == File.stat(File.dirname(dest)) then
module:fail_json({msg="Destination directory " .. File.dirname(dest) .. " is not accessible"})
end
module:fail_json({msg="Destination directory " .. File.dirname(dest) .. " does not exist"})
end
end
if not File.writeable(File.dirname(dest)) then
module:fail_json({msg="Destination " .. File.dirname(dest) .. " not writeable"})
end
local backup_file = nil
if checksum_src ~= checksum_dest or File.islnk(dest) then
if not module:check_mode() then
if backup and File.exists(dest) then
backup_file = module:backup_local(dest)
end
local function err(res, msg)
if not res then
module:fail_json({msg="failed to copy: " .. src .. " to " .. dest .. ": " .. msg})
end
end
local res, msg
-- allow for conversion from symlink
if File.islnk(dest) then
res, msg = File.unlink(dest)
err(res, msg)
res, msg = File.touch(dest)
err(res, msg)
end
if validate then
-- FIXME: Validate is currently unsupported
end
if remote_src then
local tmpname, msg = File.mkstemp(File.dirname(dest) .. "/ansibltmp_XXXXXX")
err(tmpname, msg)
res, msg = module:copy(src, tmpdest)
err(res, msg)
res, msg = module:move(tmpdest, dest)
err(res, msg)
else
res, msg = module:move(src, dest)
err(res, msg)
end
end
changed = true
else
changed = false
end
res_args = { dest=dest, src=src, md5sum=md5sum_src, checksum=checksum_src, changed=changed }
if backup_file then
res_args['backup_file'] = backup_file
end
p['dest'] = dest
if not module:check_mode() then
local file_args = p
res_args['changed'] = File.set_fs_attributes_if_different(module, file_args, res_args['changed'], nil)
end
res_args['msg'] = "Dummy"
module:exit_json(res_args)
end
main(arg)
|
Bugfix: Ignore "checksum" parameter in copy module
|
Bugfix: Ignore "checksum" parameter in copy module
When copying, recent versions of ansible set the "checksum" field of the
json-payload for validation of the file after copy. As of now, we simply
ignore the parameter.
|
Lua
|
agpl-3.0
|
noctux/philote,noctux/philote
|
5d9186ddbfa0ad2e2757307305d4acb7502dc6e3
|
agents/monitoring/default/client/upgrade.lua
|
agents/monitoring/default/client/upgrade.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Emitter = require('core').Emitter
local timer = require('timer')
local consts = require('../util/constants')
local misc = require('../util/misc')
local logging = require('logging')
local UpgradePollEmitter = Emitter:extend()
function UpgradePollEmitter:initialize()
self.timeout = nil
self.stopped = nil
end
function UpgradePollEmitter:calcTimeout()
return misc.calcJitter(consts.UPGRADE_INTERVAL, consts.UPGRADE_INTERVAL_JITTER)
end
function UpgradePollEmitter:_emit()
process.nextTick(function()
self:emit('upgrade')
end)
end
function UpgradePollEmitter:forceUpgradeCheck()
self:_emit()
end
function UpgradePollEmitter:_registerTimeout(callback)
if self.stopped then
return
end
-- Check for upgrade
function timeout()
self:_registerTimeout(function()
if self.stopped then
return
end
self:_emit()
timeout()
end)
end
self.timeout = self:calcTimeout()
logging.debugf('Using Upgrade Timeout %ums', self.timeout)
self._timer = timer.setTimeout(self.timeout, timeout)
end
function UpgradePollEmitter:start()
self.stopped = nil
if self._timer then
return
end
-- On Startup check for upgrade
self:_emit()
self:_registerTimeout()
end
function UpgradePollEmitter:stop()
if self._timer then
timer.clearTimer(self._timer)
end
self.stopped = true
end
local exports = {}
exports.UpgradePollEmitter = UpgradePollEmitter
return exports
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Emitter = require('core').Emitter
local timer = require('timer')
local consts = require('../util/constants')
local misc = require('../util/misc')
local logging = require('logging')
local UpgradePollEmitter = Emitter:extend()
function UpgradePollEmitter:initialize()
self.timeout = nil
self.stopped = nil
end
function UpgradePollEmitter:calcTimeout()
return misc.calcJitter(consts.UPGRADE_INTERVAL, consts.UPGRADE_INTERVAL_JITTER)
end
function UpgradePollEmitter:_emit()
process.nextTick(function()
self:emit('upgrade')
end)
end
function UpgradePollEmitter:forceUpgradeCheck()
self:_emit()
end
function UpgradePollEmitter:_registerTimeout(callback)
if self.stopped then
return
end
-- Check for upgrade
local timeoutCallback
timeoutCallback = function()
self:_emit()
self:_registerTimeout(timeoutCallback)
end
self.timeout = self:calcTimeout()
logging.debugf('Using Upgrade Timeout %ums', self.timeout)
self._timer = timer.setTimeout(self.timeout, timeoutCallback)
end
function UpgradePollEmitter:start()
self.stopped = nil
if self._timer then
return
end
-- On Startup check for upgrade
self:_emit()
self:_registerTimeout()
end
function UpgradePollEmitter:stop()
if self._timer then
timer.clearTimer(self._timer)
end
self.stopped = true
end
local exports = {}
exports.UpgradePollEmitter = UpgradePollEmitter
return exports
|
fix(upgrades): callback is not triggering correctly
|
fix(upgrades): callback is not triggering correctly
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
fe80e3586a3aa6e71b97ab6fc7f9c0f8adbe8e26
|
src/init.lua
|
src/init.lua
|
local ceil = math.ceil
local floor = math.floor
local pow = math.pow
local substr = string.sub
local upcase = string.upper
local format = string.format
local strcat = table.concat
local push = table.insert
local str_switch_pos
local ok, lib = pcall(require, "hashids.clib");
if ok then
str_switch_pos = lib.str_switch_pos;
else
str_switch_pos = function(str, pos1, pos2)
pos1 = pos1 + 1; pos2 = pos2 + 1;
local a,b = str:sub(pos1,pos1), str:sub(pos2, pos2);
if pos1 > pos2 then return str:gsub(a, b, 1):gsub(b, a, 1); end
return str:gsub(b, a, 1):gsub(a, b, 1);
end
end
hash_mt = {};
hash_mt.__index = hash_mt;
local function gcap(str, pos)
pos = pos + 1;
return str:sub(pos, pos);
end
-- TODO using string concatenation with .. might not be the fastest in a loop
local function hash(number, alphabet)
local hash, alen = "", alphabet:len();
repeat
hash = gcap(alphabet, (number % alen)) .. hash;
number = floor(number / alen);
until number == 0
return hash;
end
local function unhash(input, alphabet)
local number, ilen, alen = 0, input:len(), alphabet:len();
for i=0, ilen do
local cpos = (alphabet:find(gcap(input, i), 1, true) - 1);
number = number + cpos * pow(alen, (ilen - i - 1))
end
return number;
end
local function consistent_shuffle(alphabet, salt)
local slen = salt:len();
if slen == 0 then return alphabet end
local v, p = 0, 0;
for i = (alphabet:len() - 1), 1, -1 do
v = (v % slen);
local ord = gcap(salt, v):byte();
p = p + ord;
local j = (ord + v + p) % i;
alphabet = str_switch_pos(alphabet, j, i);
v = v + 1;
end
return alphabet;
end
function hash_mt:encode(...)
local numbers = {select(1,...)};
local numbers_size, hash_int = #numbers, 0;
for i, number in ipairs(numbers) do
assert(type(number) == 'number', "all paramters must be numbers");
hash_int = hash_int + (number % ((i - 1) + 100));
end
local alpha = self.alphabet;
local alpha_len = alpha:len();
local lottery = gcap(alpha, hash_int % alpha_len);
local ret = lottery;
local last = nil;
for i, number in ipairs(numbers) do
-- for i=1, #numbers do
-- local number = numbers[i];
alpha = consistent_shuffle(alpha, substr(strcat({lottery, self.salt, alpha}), 1, alpha_len));
last = hash(number, alpha);
ret = ret .. last;
if i < numbers_size then
number = number % (last:byte() + (i - 1));
ret = ret .. gcap(self.seps, (number % self.seps:len()));
end
end
local guards_len = self.guards:len();
if ret:len() < self.min_hash_length then
local guard_index = (hash_int + gcap(ret, 0):byte()) % guards_len;
ret = gcap(self.guards, guard_index) .. ret;
if ret:len() < self.min_hash_length then
guard_index = (hash_int + gcap(ret, 2):byte()) % guards_len;
ret = ret .. gcap(self.guards, guard_index);
end
end
local half_len, excess = floor(alpha_len * 0.5), 0; -- alpha_len / 2
while ret:len() < self.min_hash_length do
alpha = consistent_shuffle(alpha, alpha);
ret = alpha:sub(half_len + 1) .. ret .. alpha:sub(1, half_len);
excess = (ret:len() - self.min_hash_length);
if excess > 0 then
excess = (excess * 0.5);
ret = ret:sub(excess + 1, (excess + self.min_hash_length));
end
end
return ret;
end
function hash_mt:encode_hex(str)
local pos, max, numbers = 0, #str, {}
while true do
local part = substr(str, pos + 1, pos + 12)
if part == "" then break end
pos = pos + #part
push(numbers, tonumber("1" .. part, 16))
end
return self:encode(unpack(numbers))
end
function hash_mt:decode(hash)
-- TODO validate input
local parts, index = {}, 1;
for part in hash:gmatch("[^".. self.guards .."]+") do
parts[index] = part;
index = index + 1;
end
local num_parts, t, lottery = #parts;
if num_parts == 3 or num_parts == 2 then
t = parts[2];
else
t = parts[1];
end
lottery = gcap(t, 0); -- put the first char in lottery
t = t:sub(2); -- then put the rest in t
parts, index = {}, 1;
for part in t:gmatch("[^".. self.seps .."]+") do
parts[index] = part;
index = index + 1;
end
local ret, alpha = {}, self.alphabet;
for i=1, #parts do
alpha = consistent_shuffle(alpha, substr(strcat({lottery, self.salt, alpha}), 1, self.alphabet_length));
ret[i] = unhash(parts[i], alpha);
end
return ret;
end
function hash_mt:decode_hex(hash)
local result, numbers = {}, self:decode(hash)
for _, number in ipairs(numbers) do
push(result, substr(format("%x", number), 2))
end
return upcase(strcat(result))
end
return {
VERSION = "1.0.0",
new = function(salt, min_hash_length, alphabet)
salt = salt or "";
min_hash_length = min_hash_length or 0;
alphabet = alphabet or "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
-- TODO make sure alphabet doesn't contain duplicates.
local tmp_seps, tmp_alpha, c = "", "";
local seps = "cfhistuCFHISTU";
for i = 1, alphabet:len() do
c = alphabet:sub(i,i);
if seps:find(c, 1, true) then
tmp_seps = tmp_seps .. c;
else
tmp_alpha = tmp_alpha .. c;
end
end
seps = consistent_shuffle(tmp_seps, salt);
alphabet = tmp_alpha;
-- constants
local SEPS_DIV = 3.5;
local GUARD_DIV = 12;
if seps:len() == 0 or (alphabet:len() / seps:len()) > SEPS_DIV then
local seps_len = floor(ceil(alphabet:len() / SEPS_DIV));
if seps_len == 1 then seps_len = 2 end
if seps_len > seps:len() then
local diff = seps_len - seps:len();
seps = seps .. alphabet:sub(1, diff);
alphabet = alphabet:sub(diff + 1);
else
seps = seps:sub(1, seps_len);
end
end
alphabet = consistent_shuffle(alphabet, salt);
local guards = "";
local guard_count = ceil(alphabet:len() / GUARD_DIV);
if alphabet:len() < 3 then
guards = seps:sub(1, guard_count);
seps = seps:sub(guard_count + 1);
else
guards = alphabet:sub(1, guard_count);
alphabet = alphabet:sub(guard_count + 1);
end
local obj = { salt = salt, alphabet = alphabet, seps = seps, guards = guards, min_hash_length = min_hash_length };
return setmetatable(obj, hash_mt);
end
}
|
local ceil = math.ceil
local floor = math.floor
local pow = math.pow
local substr = string.sub
local upcase = string.upper
local format = string.format
local strcat = table.concat
local push = table.insert
local unpack = table.unpack or unpack
local str_switch_pos
local ok, lib = pcall(require, "hashids.clib");
if ok then
str_switch_pos = lib.str_switch_pos;
else
str_switch_pos = function(str, pos1, pos2)
pos1 = pos1 + 1; pos2 = pos2 + 1;
local a,b = str:sub(pos1,pos1), str:sub(pos2, pos2);
if pos1 > pos2 then return str:gsub(a, b, 1):gsub(b, a, 1); end
return str:gsub(b, a, 1):gsub(a, b, 1);
end
end
hash_mt = {};
hash_mt.__index = hash_mt;
local function gcap(str, pos)
pos = pos + 1;
return str:sub(pos, pos);
end
-- TODO using string concatenation with .. might not be the fastest in a loop
local function hash(number, alphabet)
local hash, alen = "", alphabet:len();
repeat
hash = gcap(alphabet, (number % alen)) .. hash;
number = floor(number / alen);
until number == 0
return hash;
end
local function unhash(input, alphabet)
local number, ilen, alen = 0, input:len(), alphabet:len();
for i=0, ilen do
local cpos = (alphabet:find(gcap(input, i), 1, true) - 1);
number = number + cpos * pow(alen, (ilen - i - 1))
end
return number;
end
local function consistent_shuffle(alphabet, salt)
local slen = salt:len();
if slen == 0 then return alphabet end
local v, p = 0, 0;
for i = (alphabet:len() - 1), 1, -1 do
v = (v % slen);
local ord = gcap(salt, v):byte();
p = p + ord;
local j = (ord + v + p) % i;
alphabet = str_switch_pos(alphabet, j, i);
v = v + 1;
end
return alphabet;
end
function hash_mt:encode(...)
local numbers = {select(1,...)};
if #numbers == 0 then return "" end
local numbers_size, hash_int = #numbers, 0;
for i, number in ipairs(numbers) do
assert(type(number) == 'number', "all paramters must be numbers");
hash_int = hash_int + (number % ((i - 1) + 100));
end
local alpha = self.alphabet;
local alpha_len = alpha:len();
local lottery = gcap(alpha, hash_int % alpha_len);
local ret = lottery;
local last = nil;
for i, number in ipairs(numbers) do
-- for i=1, #numbers do
-- local number = numbers[i];
alpha = consistent_shuffle(alpha, substr(strcat({lottery, self.salt, alpha}), 1, alpha_len));
last = hash(number, alpha);
ret = ret .. last;
if i < numbers_size then
number = number % (last:byte() + (i - 1));
ret = ret .. gcap(self.seps, (number % self.seps:len()));
end
end
local guards_len = self.guards:len();
if ret:len() < self.min_hash_length then
local guard_index = (hash_int + gcap(ret, 0):byte()) % guards_len;
ret = gcap(self.guards, guard_index) .. ret;
if ret:len() < self.min_hash_length then
guard_index = (hash_int + gcap(ret, 2):byte()) % guards_len;
ret = ret .. gcap(self.guards, guard_index);
end
end
local half_len, excess = floor(alpha_len * 0.5), 0; -- alpha_len / 2
while ret:len() < self.min_hash_length do
alpha = consistent_shuffle(alpha, alpha);
ret = alpha:sub(half_len + 1) .. ret .. alpha:sub(1, half_len);
excess = (ret:len() - self.min_hash_length);
if excess > 0 then
excess = (excess * 0.5);
ret = ret:sub(excess + 1, (excess + self.min_hash_length));
end
end
return ret;
end
function hash_mt:encode_hex(str)
if str:match("%X") then return "" end
local pos, max, numbers = 0, #str, {}
while true do
local part = substr(str, pos + 1, pos + 12)
if part == "" then break end
pos = pos + #part
push(numbers, tonumber("1" .. part, 16))
end
return self:encode(unpack(numbers))
end
function hash_mt:decode(hash)
-- TODO validate input
local parts, index = {}, 1;
for part in hash:gmatch("[^".. self.guards .."]+") do
parts[index] = part;
index = index + 1;
end
local num_parts, t, lottery = #parts;
if num_parts == 3 or num_parts == 2 then
t = parts[2];
else
t = parts[1];
end
lottery = gcap(t, 0); -- put the first char in lottery
t = t:sub(2); -- then put the rest in t
parts, index = {}, 1;
for part in t:gmatch("[^".. self.seps .."]+") do
parts[index] = part;
index = index + 1;
end
local ret, alpha = {}, self.alphabet;
for i=1, #parts do
alpha = consistent_shuffle(alpha, substr(strcat({lottery, self.salt, alpha}), 1, self.alphabet_length));
ret[i] = unhash(parts[i], alpha);
end
return ret;
end
function hash_mt:decode_hex(hash)
local result, numbers = {}, self:decode(hash)
for _, number in ipairs(numbers) do
push(result, substr(format("%x", number), 2))
end
return upcase(strcat(result))
end
return {
VERSION = "1.0.0",
new = function(salt, min_hash_length, alphabet)
salt = salt or "";
min_hash_length = min_hash_length or 0;
alphabet = alphabet or "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
-- TODO make sure alphabet doesn't contain duplicates.
local tmp_seps, tmp_alpha, c = "", "";
local seps = "cfhistuCFHISTU";
for i = 1, alphabet:len() do
c = alphabet:sub(i,i);
if seps:find(c, 1, true) then
tmp_seps = tmp_seps .. c;
else
tmp_alpha = tmp_alpha .. c;
end
end
seps = consistent_shuffle(tmp_seps, salt);
alphabet = tmp_alpha;
-- constants
local SEPS_DIV = 3.5;
local GUARD_DIV = 12;
if seps:len() == 0 or (alphabet:len() / seps:len()) > SEPS_DIV then
local seps_len = floor(ceil(alphabet:len() / SEPS_DIV));
if seps_len == 1 then seps_len = 2 end
if seps_len > seps:len() then
local diff = seps_len - seps:len();
seps = seps .. alphabet:sub(1, diff);
alphabet = alphabet:sub(diff + 1);
else
seps = seps:sub(1, seps_len);
end
end
alphabet = consistent_shuffle(alphabet, salt);
local guards = "";
local guard_count = ceil(alphabet:len() / GUARD_DIV);
if alphabet:len() < 3 then
guards = seps:sub(1, guard_count);
seps = seps:sub(guard_count + 1);
else
guards = alphabet:sub(1, guard_count);
alphabet = alphabet:sub(guard_count + 1);
end
local obj = { salt = salt, alphabet = alphabet, seps = seps, guards = guards, min_hash_length = min_hash_length };
return setmetatable(obj, hash_mt);
end
}
|
fix encode() without value; check encode_hex() value; fix unpack() (Lua 5.3)
|
fix encode() without value; check encode_hex() value; fix unpack() (Lua 5.3)
|
Lua
|
mit
|
leihog/hashids.lua
|
714933786e905bcecc381dd6aee2309d99c85afa
|
modules/hearthstone.lua
|
modules/hearthstone.lua
|
local simplehttp = require'simplehttp'
local cache = {}
local trim = function(s)
return s:match('^%s*(.-)%s*$')
end
local pattern = ('<td[^>]*>([^\n]+)\n[^<]+'):rep(10)
local parseData = function(data)
local tmp = {}
local tbody = data:match('<tbody>(.*)</tbody>')
for row in tbody:gmatch('<tr[^>]+>.-</tr>') do
for _, name, class, rarity, kind, race, mana, attack, life, desc in row:gmatch(pattern) do
-- Strip HTML:
name = name:gsub('<%/?[%w:]+.-%/?>', '')
class = class:match('(%w)%.png"') or class
tmp[name:lower()] = {
name = name,
class = class:sub(1, -6),
rarity = rarity:sub(1, -6),
type = kind:sub(1, -6),
race = race ~= "" and race:sub(1, -6) or nil,
mana = mana ~= "" and mana:sub(1, -6) or nil,
attack = attack ~= "" and attack:sub(1, -6) or nil,
life = life ~= "" and attack:sub(1, -6) or nil,
desc = desc ~= "" and desc:sub(1, -6) or nil,
}
end
end
if(next(tmp)) then
cache = tmp
end
end
local formatOutput = function(card)
local out = {}
card = cache[card]
table.insert(out, card.name)
table.insert(out, card.class)
table.insert(out, card.rarity)
table.insert(out, card.type)
if(card.mana) then
table.insert(out, string.format('Cost: %s', card.mana))
end
if(card.attack) then
table.insert(out, string.format('Attack: %s', card.mana))
end
if(card.life) then
table.insert(out, string.format('HP: %s', card.mana))
end
if(card.desc) then
table.insert(out, card.desc)
end
return table.concat(out, ' / ')
end
local checkCache = function(card)
local out
if(cache[card]) then
out = formatOutput(card)
end
if(not out) then
local matches = {}
for name, data in next, cache do
if(name:find(card, 1, true)) then
table.insert(matches, data.name)
end
end
if(#matches == 1) then
out = formatOutput(matches[1]:lower())
elseif(#matches > 1) then
local n = 7
out = {}
local msgLimit = (512 - 16 - 65 - 10) - #ivar2.config.nick - 30
for i=1, #matches do
local name = matches[i]
n = n + #name + 2
if(n < msgLimit) then
table.insert(out, string.format('%s', name))
end
end
out = 'Found: ' .. table.concat(out, ', ')
end
end
return out
end
return {
PRIVMSG = {
['^!hs (.+)$'] = function(self, source, destination, card)
card = trim(card:lower())
local out = checkCache(card)
if(not out) then
simplehttp('http://hearthstonecardlist.com/', function(data)
-- Update cache.
parseData(data)
local out = checkCache(card)
if(out) then
self:Msg('privmsg', destination, source, 'Hearthstone: %s', out)
else
self:Msg('privmsg', destination, source, 'Hearthstone: No matching card found.')
end
end)
end
end,
},
}
|
local simplehttp = require'simplehttp'
local cache = {}
local trim = function(s)
return s:match('^%s*(.-)%s*$')
end
local pattern = ('<td[^>]*>([^\n]+)\n[^<]+'):rep(10)
local parseData = function(data)
local tmp = {}
local tbody = data:match('<tbody>(.*)</tbody>')
for row in tbody:gmatch('<tr[^>]+>.-</tr>') do
for _, name, class, rarity, kind, race, mana, attack, life, desc in row:gmatch(pattern) do
-- Strip HTML:
name = name:gsub('<%/?[%w:]+.-%/?>', '')
class = class:match('alt="([^"]+)"') or class
tmp[name:lower()] = {
name = name,
class = class,
rarity = rarity:sub(1, -6),
type = kind:sub(1, -6),
race = race ~= "" and race:sub(1, -6) or nil,
mana = mana ~= "" and mana:sub(1, -6) or nil,
attack = attack ~= "" and attack:sub(1, -6) or nil,
life = life ~= "" and attack:sub(1, -6) or nil,
desc = desc ~= "" and desc:sub(1, -6) or nil,
}
end
end
if(next(tmp)) then
cache = tmp
end
end
local formatOutput = function(card)
local out = {}
card = cache[card]
table.insert(out, card.name)
table.insert(out, card.class)
table.insert(out, card.rarity)
table.insert(out, card.type)
if(card.mana) then
table.insert(out, string.format('Cost: %s', card.mana))
end
if(card.attack) then
table.insert(out, string.format('Attack: %s', card.mana))
end
if(card.life) then
table.insert(out, string.format('HP: %s', card.mana))
end
if(card.desc) then
table.insert(out, card.desc)
end
return table.concat(out, ' / ')
end
local checkCache = function(card)
local out
if(cache[card]) then
out = formatOutput(card)
end
if(not out) then
local matches = {}
for name, data in next, cache do
if(name:find(card, 1, true)) then
table.insert(matches, data.name)
end
end
if(#matches == 1) then
out = formatOutput(matches[1]:lower())
elseif(#matches > 1) then
local n = 13 + 7
out = {}
local msgLimit = (512 - 16 - 65 - 10) - #ivar2.config.nick - 30
for i=1, #matches do
local name = matches[i]
n = n + #name + 2
if(n < msgLimit) then
table.insert(out, string.format('%s', name))
end
end
out = 'Found: ' .. table.concat(out, ', ')
end
end
return out
end
return {
PRIVMSG = {
['^!hs (.+)$'] = function(self, source, destination, card)
card = trim(card:lower())
local out = checkCache(card)
if(out) then
self:Msg('privmsg', destination, source, 'Hearthstone: %s', out)
return
end
simplehttp('http://hearthstonecardlist.com/', function(data)
-- Update cache.
parseData(data)
local out = checkCache(card)
if(out) then
self:Msg('privmsg', destination, source, 'Hearthstone: %s', out)
else
self:Msg('privmsg', destination, source, 'Hearthstone: No matching card found.')
end
end)
end,
},
}
|
hearthstone: Fix class and output logic.
|
hearthstone: Fix class and output logic.
Former-commit-id: 0ad585908ef65d6ba18dfdef257326d4dc179171 [formerly f2c1ab4a2b0f3c0575e3bd3a494fe2b6ac9b4efc]
Former-commit-id: 7c3e853285c9a94b4c814eb80b812dddc23bc5ec
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
|
173d9600f0724b82f53cc46ef14b7f3fb9fff25d
|
frontend/apps/reader/modules/readerdogear.lua
|
frontend/apps/reader/modules/readerdogear.lua
|
local BD = require("ui/bidi")
local Device = require("device")
local Geom = require("ui/geometry")
local IconWidget = require("ui/widget/iconwidget")
local InputContainer = require("ui/widget/container/inputcontainer")
local RightContainer = require("ui/widget/container/rightcontainer")
local Screen = Device.screen
local ReaderDogear = InputContainer:new{}
function ReaderDogear:init()
-- This image could be scaled for DPI (with scale_for_dpi=true, scale_factor=0.7),
-- but it's as good to scale it to a fraction (1/32) of the screen size.
-- For CreDocument, we should additionally take care of not exceeding margins
-- to not overwrite the book text.
-- For other documents, there is no easy way to know if valuable content
-- may be hidden by the icon (kopt's page_margin is quite obscure).
self.dogear_max_size = math.ceil( math.min(Screen:getWidth(), Screen:getHeight()) / 32)
self.dogear_size = nil
self:setupDogear()
self:resetLayout()
end
function ReaderDogear:setupDogear(new_dogear_size)
if not new_dogear_size then
new_dogear_size = self.dogear_max_size
end
if new_dogear_size ~= self.dogear_size then
self.dogear_size = new_dogear_size
if self[1] then
self[1]:free()
end
self[1] = RightContainer:new{
dimen = Geom:new{w = Screen:getWidth(), h = self.dogear_size},
IconWidget:new{
icon = "dogear.opaque",
rotation_angle = BD.mirroredUILayout() and 90 or 0,
width = self.dogear_size,
height = self.dogear_size,
}
}
end
end
function ReaderDogear:onReadSettings(config)
if not self.ui.document.info.has_pages then
-- Adjust to CreDocument margins (as done in ReaderTypeset)
local h_margins = config:readSetting("copt_h_page_margins") or
G_reader_settings:readSetting("copt_h_page_margins") or
DCREREADER_CONFIG_H_MARGIN_SIZES_MEDIUM
local t_margin = config:readSetting("copt_t_page_margin") or
G_reader_settings:readSetting("copt_t_page_margin") or
DCREREADER_CONFIG_T_MARGIN_SIZES_LARGE
local b_margin = config:readSetting("copt_b_page_margin") or
G_reader_settings:readSetting("copt_b_page_margin") or
DCREREADER_CONFIG_B_MARGIN_SIZES_LARGE
local margins = { h_margins[1], t_margin, h_margins[2], b_margin }
self:onSetPageMargins(margins)
end
end
function ReaderDogear:onSetPageMargins(margins)
if self.ui.document.info.has_pages then
-- we may get called by readerfooter (when hiding the footer)
-- on pdf documents and get margins=nil
return
end
local margin_top, margin_right = margins[2], margins[3]
-- As the icon is squared, we can take the max() instead of the min() of
-- top & right margins and be sure no text is hidden by the icon
-- (the provided margins are not scaled, so do as ReaderTypeset)
local margin = Screen:scaleBySize(math.max(margin_top, margin_right))
local new_dogear_size = math.min(self.dogear_max_size, margin)
self:setupDogear(new_dogear_size)
end
function ReaderDogear:resetLayout()
local new_screen_width = Screen:getWidth()
if new_screen_width == self._last_screen_width then return end
self._last_screen_width = new_screen_width
self[1].dimen.w = new_screen_width
end
function ReaderDogear:onSetDogearVisibility(visible)
self.view.dogear_visible = visible
return true
end
return ReaderDogear
|
local BD = require("ui/bidi")
local Device = require("device")
local Geom = require("ui/geometry")
local IconWidget = require("ui/widget/iconwidget")
local InputContainer = require("ui/widget/container/inputcontainer")
local RightContainer = require("ui/widget/container/rightcontainer")
local VerticalGroup = require("ui/widget/verticalgroup")
local VerticalSpan = require("ui/widget/verticalspan")
local Screen = Device.screen
local ReaderDogear = InputContainer:new{}
function ReaderDogear:init()
-- This image could be scaled for DPI (with scale_for_dpi=true, scale_factor=0.7),
-- but it's as good to scale it to a fraction (1/32) of the screen size.
-- For CreDocument, we should additionally take care of not exceeding margins
-- to not overwrite the book text.
-- For other documents, there is no easy way to know if valuable content
-- may be hidden by the icon (kopt's page_margin is quite obscure).
self.dogear_max_size = math.ceil( math.min(Screen:getWidth(), Screen:getHeight()) / 32)
self.dogear_size = nil
self.dogear_y_offset = 0
self.top_pad = nil
self:setupDogear()
self:resetLayout()
end
function ReaderDogear:setupDogear(new_dogear_size)
if not new_dogear_size then
new_dogear_size = self.dogear_max_size
end
if new_dogear_size ~= self.dogear_size then
self.dogear_size = new_dogear_size
if self[1] then
self[1]:free()
end
self.top_pad = VerticalSpan:new{width = self.dogear_y_offset}
self.vgroup = VerticalGroup:new{
self.top_pad,
IconWidget:new{
icon = "dogear.opaque",
rotation_angle = BD.mirroredUILayout() and 90 or 0,
width = self.dogear_size,
height = self.dogear_size,
}
}
self[1] = RightContainer:new{
dimen = Geom:new{w = Screen:getWidth(), h = self.dogear_y_offset + self.dogear_size},
self.vgroup
}
end
end
function ReaderDogear:onReadSettings(config)
if not self.ui.document.info.has_pages then
-- Adjust to CreDocument margins (as done in ReaderTypeset)
local h_margins = config:readSetting("copt_h_page_margins") or
G_reader_settings:readSetting("copt_h_page_margins") or
DCREREADER_CONFIG_H_MARGIN_SIZES_MEDIUM
local t_margin = config:readSetting("copt_t_page_margin") or
G_reader_settings:readSetting("copt_t_page_margin") or
DCREREADER_CONFIG_T_MARGIN_SIZES_LARGE
local b_margin = config:readSetting("copt_b_page_margin") or
G_reader_settings:readSetting("copt_b_page_margin") or
DCREREADER_CONFIG_B_MARGIN_SIZES_LARGE
local margins = { h_margins[1], t_margin, h_margins[2], b_margin }
self:onSetPageMargins(margins)
end
end
function ReaderDogear:onSetPageMargins(margins)
if self.ui.document.info.has_pages then
-- we may get called by readerfooter (when hiding the footer)
-- on pdf documents and get margins=nil
return
end
local margin_top, margin_right = margins[2], margins[3]
-- As the icon is squared, we can take the max() instead of the min() of
-- top & right margins and be sure no text is hidden by the icon
-- (the provided margins are not scaled, so do as ReaderTypeset)
local margin = Screen:scaleBySize(math.max(margin_top, margin_right))
local new_dogear_size = math.min(self.dogear_max_size, margin)
self:setupDogear(new_dogear_size)
end
function ReaderDogear:updateDogearOffset()
if self.ui.document.info.has_pages then
return
end
self.dogear_y_offset = 0
if self.view.view_mode == "page" then
self.dogear_y_offset = self.ui.document:getHeaderHeight()
end
-- Update components heights and positionnings
if self[1] then
self[1].dimen.h = self.dogear_y_offset + self.dogear_size
self.top_pad.width = self.dogear_y_offset
self.vgroup:resetLayout()
end
end
function ReaderDogear:onUpdatePos()
-- Catching the top status bar toggling with :onSetStatusLine()
-- would be too early. But "UpdatePos" is sent after it has
-- been applied
self:updateDogearOffset()
end
function ReaderDogear:onChangeViewMode()
-- No top status bar when switching between page and scroll mode
self:updateDogearOffset()
end
function ReaderDogear:resetLayout()
local new_screen_width = Screen:getWidth()
if new_screen_width == self._last_screen_width then return end
self._last_screen_width = new_screen_width
self[1].dimen.w = new_screen_width
end
function ReaderDogear:onSetDogearVisibility(visible)
self.view.dogear_visible = visible
return true
end
return ReaderDogear
|
Bookmarks dogear: fix position with CRe top status bar (#7312)
|
Bookmarks dogear: fix position with CRe top status bar (#7312)
Draw it below the CRe top status bar rather than over it.
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader,koreader/koreader,mwoz123/koreader,Frenzie/koreader,Frenzie/koreader,koreader/koreader,NiLuJe/koreader,poire-z/koreader,poire-z/koreader,NiLuJe/koreader
|
b657cde5b59b02b1838b940007f0115b223bdf02
|
xmake-repo/packages/n/nodeeditor/xmake.lua
|
xmake-repo/packages/n/nodeeditor/xmake.lua
|
package("nodeeditor")
set_homepage("https://github.com/paceholder/nodeeditor")
set_description("Qt Node Editor. Dataflow programming framework")
set_license("BSD-3")
set_urls("https://github.com/paceholder/nodeeditor/archive/refs/tags/$(version).tar.gz",
"https://github.com/paceholder/nodeeditor.git")
add_versions("2.1.3", "4e3194a04ac4a2a2bf4bc8eb6cc27d5cc154923143c1ecf579ce7f0115a90585")
add_patches("2.1.3", path.join(os.scriptdir(), "patches", "2.1.3", "fix_qt.patch"), "804ee98d47b675c578981414ed25a745f1b12d0cd8b03ea7d7b079c7e1ce1ea9")
add_deps("cmake")
on_load(function (package)
if package:config("shared") then
package:add("defines", "NODE_EDITOR_SHARED")
else
package:add("defines", "NODE_EDITOR_STATIC")
end
end)
on_install("windows", "linux", "mingw", "macosx", function (package)
import("detect.sdks.find_qt")
local qt = find_qt()
local configs = {"-DBUILD_EXAMPLES=OFF", "-DBUILD_TESTING=OFF"}
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF"))
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
if qt then
table.insert(configs, "-DQt5_DIR=" .. path.join(qt.libdir, "cmake", "Qt5"))
end
import("package.tools.cmake").install(package, configs)
end)
on_test(function (package)
do
-- Disable test until I can test with Qt
return
end
assert(package:check_cxxsnippets({test = [[
void test() {
QtNodes::FlowScene scene(std::make_shared<QtNodes::DataModelRegistry>());
QtNodes::FlowView view(&scene);
}
]]}, {configs = {languages = "c++11"}, includes = {"nodes/FlowScene", "nodes/FlowView"}}))
end)
|
package("nodeeditor")
set_homepage("https://github.com/paceholder/nodeeditor")
set_description("Qt Node Editor. Dataflow programming framework")
set_license("BSD-3")
set_urls("https://github.com/paceholder/nodeeditor/archive/refs/tags/$(version).tar.gz",
"https://github.com/paceholder/nodeeditor.git")
add_versions("2.1.3", "4e3194a04ac4a2a2bf4bc8eb6cc27d5cc154923143c1ecf579ce7f0115a90585")
add_patches("2.1.3", path.join(os.scriptdir(), "patches", "2.1.3", "fix_qt.patch"), "17cdcb44a4e1d7b7a959d3717e71b068c356f2a09d910ae5a7b33e5c65c25139")
add_deps("cmake")
on_load(function (package)
if package:config("shared") then
package:add("defines", "NODE_EDITOR_SHARED")
else
package:add("defines", "NODE_EDITOR_STATIC")
end
end)
on_install("windows", "linux", "mingw", "macosx", function (package)
import("detect.sdks.find_qt")
local qt = find_qt()
local configs = {"-DBUILD_EXAMPLES=OFF", "-DBUILD_TESTING=OFF"}
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF"))
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
if qt then
table.insert(configs, "-DQt5_DIR=" .. path.join(qt.libdir, "cmake", "Qt5"))
end
import("package.tools.cmake").install(package, configs)
end)
on_test(function (package)
do
-- Disable test until I can test with Qt
return
end
assert(package:check_cxxsnippets({test = [[
void test() {
QtNodes::FlowScene scene(std::make_shared<QtNodes::DataModelRegistry>());
QtNodes::FlowView view(&scene);
}
]]}, {configs = {languages = "c++11"}, includes = {"nodes/FlowScene", "nodes/FlowView"}}))
end)
|
Build: fix nodeeditor package
|
Build: fix nodeeditor package
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
fcad680b2021aa9bddb364943d3c0c563850e9b2
|
xmake/platforms/macosx/load.lua
|
xmake/platforms/macosx/load.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- imports
import("core.project.config")
-- load it
function main(platform)
-- init flags for architecture
local arch = config.get("arch") or os.arch()
local target_minver = config.get("target_minver")
-- init flags for the xcode sdk directory
local xcode_dir = config.get("xcode")
local xcode_sdkver = config.get("xcode_sdkver")
local xcode_sdkdir = nil
if xcode_dir and xcode_sdkver then
xcode_sdkdir = xcode_dir .. "/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX" .. xcode_sdkver .. ".sdk"
end
-- init flags for c/c++
platform:add("cxflags", "-arch " .. arch, "-fpascal-strings", "-fmessage-length=0")
platform:add("ldflags", "-arch " .. arch)
if target_minver then
platform:add("ldflags", "-mmacosx-version-min=" .. target_minver)
end
if xcode_sdkdir then
platform:add("cxflags", "-isysroot " .. xcode_sdkdir)
platform:add("ldflags", "-isysroot " .. xcode_sdkdir)
else
platform:add("cxflags", "-I/usr/local/include")
platform:add("cxflags", "-I/usr/include")
platform:add("ldflags", "-L/usr/local/lib")
platform:add("ldflags", "-L/usr/lib")
end
platform:add("ldflags", "-stdlib=libc++")
platform:add("ldflags", "-lz")
platform:add("shflags", platform:get("ldflags"))
-- init flags for objc/c++ (with ldflags and shflags)
platform:add("mxflags", "-arch " .. arch, "-fpascal-strings", "-fmessage-length=0")
if xcode_sdkdir then
platform:add("mxflags", "-isysroot " .. xcode_sdkdir)
end
-- init flags for asm
platform:add("yasm.asflags", arch == "x86_64" and "macho64" or "macho32")
platform:set("fasm.asflags", "")
platform:add("asflags", "-arch " .. arch)
if xcode_sdkdir then
platform:add("asflags", "-isysroot " .. xcode_sdkdir)
end
-- init flags for swift
if target_minver and xcode_sdkdir then
platform:add("scflags", format("-target %s-apple-macosx%s", arch, target_minver) , "-sdk " .. xcode_sdkdir)
platform:add("sc-shflags", format("-target %s-apple-macosx%s", arch, target_minver) , "-sdk " .. xcode_sdkdir)
platform:add("sc-ldflags", format("-target %s-apple-macosx%s", arch, target_minver) , "-sdk " .. xcode_sdkdir)
end
-- init flags for golang
platform:set("gc-ldflags", "")
-- init flags for dlang
local dc_archs = { i386 = "-m32", x86_64 = "-m64" }
platform:add("dcflags", dc_archs[arch] or "")
platform:add("dc-shflags", dc_archs[arch] or "")
platform:add("dc-ldflags", dc_archs[arch] or "" )
-- init flags for rust
platform:set("rc-shflags", "")
platform:set("rc-ldflags", "")
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- imports
import("core.project.config")
-- load it
function main(platform)
-- init flags for architecture
local arch = config.get("arch") or os.arch()
local target_minver = config.get("target_minver")
-- init flags for the xcode sdk directory
local xcode_dir = config.get("xcode")
local xcode_sdkver = config.get("xcode_sdkver")
local xcode_sdkdir = nil
if xcode_dir and xcode_sdkver then
xcode_sdkdir = xcode_dir .. "/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX" .. xcode_sdkver .. ".sdk"
end
-- init flags for c/c++
platform:add("cxflags", "-arch " .. arch, "-fpascal-strings", "-fmessage-length=0")
platform:add("ldflags", "-arch " .. arch)
if target_minver then
platform:add("cxflags", "-mmacosx-version-min=" .. target_minver)
platform:add("mxflags", "-mmacosx-version-min=" .. target_minver)
platform:add("ldflags", "-mmacosx-version-min=" .. target_minver)
end
if xcode_sdkdir then
platform:add("cxflags", "-isysroot " .. xcode_sdkdir)
platform:add("ldflags", "-isysroot " .. xcode_sdkdir)
else
platform:add("cxflags", "-I/usr/local/include")
platform:add("cxflags", "-I/usr/include")
platform:add("ldflags", "-L/usr/local/lib")
platform:add("ldflags", "-L/usr/lib")
end
platform:add("ldflags", "-stdlib=libc++")
platform:add("ldflags", "-lz")
platform:add("shflags", platform:get("ldflags"))
-- init flags for objc/c++ (with ldflags and shflags)
platform:add("mxflags", "-arch " .. arch, "-fpascal-strings", "-fmessage-length=0")
if xcode_sdkdir then
platform:add("mxflags", "-isysroot " .. xcode_sdkdir)
end
-- init flags for asm
platform:add("yasm.asflags", arch == "x86_64" and "macho64" or "macho32")
platform:set("fasm.asflags", "")
platform:add("asflags", "-arch " .. arch)
if xcode_sdkdir then
platform:add("asflags", "-isysroot " .. xcode_sdkdir)
end
-- init flags for swift
if target_minver and xcode_sdkdir then
platform:add("scflags", format("-target %s-apple-macosx%s", arch, target_minver) , "-sdk " .. xcode_sdkdir)
platform:add("sc-shflags", format("-target %s-apple-macosx%s", arch, target_minver) , "-sdk " .. xcode_sdkdir)
platform:add("sc-ldflags", format("-target %s-apple-macosx%s", arch, target_minver) , "-sdk " .. xcode_sdkdir)
end
-- init flags for golang
platform:set("gc-ldflags", "")
-- init flags for dlang
local dc_archs = { i386 = "-m32", x86_64 = "-m64" }
platform:add("dcflags", dc_archs[arch] or "")
platform:add("dc-shflags", dc_archs[arch] or "")
platform:add("dc-ldflags", dc_archs[arch] or "" )
-- init flags for rust
platform:set("rc-shflags", "")
platform:set("rc-ldflags", "")
end
|
fix target_minver for macosx
|
fix target_minver for macosx
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
7843015a0966fc899db343f9d71d4372af47606c
|
tools/structmsgTest/Lua/writeMsgHeaders.lua
|
tools/structmsgTest/Lua/writeMsgHeaders.lua
|
function checkOK(result, fieldName)
if (result ~= "OK") then
print(tostring(result).." for field: "..fieldName)
end
end
McuPartProv=tonumber("4D01",16);
AppPartProv=tonumber("4101",16);
McuPart=tonumber("4D00",16);
AppPart=tonumber("4100",16);
WifiPart=tonumber("5700",16)
CloudPart=tonumber("4300",16)
function writeMsgHeads()
local handleBA=structmsg2.createDispatcher();
result=structmsg2.openFile(handleBA,"MsgHeads.txt","w")
checkOK(result,"open")
result=structmsg2.writeLine(handleBA, "#,39\n")
checkOK(result,"write")
-- description of the first header bytes
-- either "@targetCmd,@totalLgth\n"
-- or "@dst,@src,@totalLgth\n"
-- or similar
-- the following has that format:
-- extraBytes, encrypted, type of cmdKey, cmdKey, type of cmdLgth, cmdLgth
-- example: 0/16, E/N, uint16_t/uint8_t, PP/B, uint0_t/uint8_t/uint16_t, /12/345
result=structmsg2.writeLine(handleBA, "@dst,@src,@totalLgth\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPartProv..","..AppPartProv..",37,0,E,uint16_t,PP,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPartProv..","..McuPartProv..",21,0,E,uint16_t,PA,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..AppPart..",21,0,E,uint16_t,PM,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",37,0,E,uint16_t,PA,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,uint16_t,PN,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,uint16_t,AD,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,uint16_t,AA,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,uint16_t,AN,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,uint16_t,SP,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,uint16_t,SA,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,uint16_t,SN,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,uint16_t,AI,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,uint16_t,AA,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,uint16_t,AN,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..AppPart..",37,0,E,uint16_t,PD,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,uint16_t,PA,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,uint16_t,PN,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..AppPart..",37,0,E,uint16_t,PE,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,uint16_t,PA,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,uint16_t,PN,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..CloudPart..",0,16,E,uint16_t,CD,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,16,E,uint16_t,CA,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,16,E,uint16_t,CN,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",8,0,N,uint8_t,I,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",42,0,N,uint8_t,I,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,uint8_t,I,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",8,0,N,uint8_t,M,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",44,0,N,uint8_t,M,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,uint8_t,M,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",10,0,N,uint8_t,B,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,uint8_t,B,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,uint8_t,B,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",10,0,N,uint8_t,W,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,uint8_t,W,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,uint8_t,W,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",64,0,N,uint8_t,T,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,uint8_t,T,uint0_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,uint8_t,T,uint0_t\n")
checkOK(result,"write")
result=structmsg2.closeFile(handleBA)
checkOK(result,"close")
end
writeMsgHeads()
print("done")
|
function checkOK(result, fieldName)
if (result ~= "OK") then
print(tostring(result).." for field: "..fieldName)
end
end
McuPartProv=tonumber("4D01",16);
AppPartProv=tonumber("4101",16);
McuPart=tonumber("4D00",16);
AppPart=tonumber("4100",16);
WifiPart=tonumber("5700",16)
CloudPart=tonumber("4300",16)
function writeMsgHeads()
local handleBA=structmsg2.createDispatcher();
result=structmsg2.openFile(handleBA,"MsgHeads.txt","w")
checkOK(result,"open")
result=structmsg2.writeLine(handleBA, "#,39\n")
checkOK(result,"write")
-- description of the first header bytes
-- either "@targetCmd,@totalLgth\n"
-- or "@dst,@src,@totalLgth\n"
-- or similar
-- the following has that format:
-- extraBytes, encrypted or not, transfer type, type of cmdKey, cmdKey, type of cmdLgth, cmdLgth
-- E/N encrypted/not encrypted,
-- A/G/S/R/U/W/N send to app/receive from app/send Uart/receive Uart/transfer Uart/transfer Wifi/not relevant
-- example: 0/16, E/N, A/G/S/R/U/W/N, uint16_t/uint8_t, PP/B, uint0_t/uint8_t/uint16_t, /12/345
result=structmsg2.writeLine(handleBA, "@dst,@src,@totalLgth\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPartProv..","..AppPartProv..",37,0,E,W,uint16_t,PP,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPartProv..","..McuPartProv..",21,0,E,U,uint16_t,PA,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPartProv..","..McuPartProv..",21,0,E,U,uint16_t,PN,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..AppPart..",21,0,E,W,uint16_t,PM,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",37,0,E,U,uint16_t,PA,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,U,uint16_t,PN,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,G,uint16_t,AD,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,A,uint16_t,AA,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,A,uint16_t,AN,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,G,uint16_t,SP,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,A,uint16_t,SA,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,A,uint16_t,SN,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..WifiPart..",0,0,E,A,uint16_t,AI,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,G,uint16_t,AA,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..AppPart..",0,0,E,G,uint16_t,AN,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..AppPart..",37,0,E,U,uint16_t,PD,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,W,uint16_t,PA,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,W,uint16_t,PN,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..AppPart..",37,0,E,U,uint16_t,PE,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,W,uint16_t,PA,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, AppPart..","..McuPart..",21,0,E,W,uint16_t,PN,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..CloudPart..",0,16,E,U,uint16_t,CD,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, CloudPart..","..McuPart..",21,16,E,W,uint16_t,CA,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, CloudPart..","..McuPart..",21,16,E,W,uint16_t,CN,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",8,0,N,R,uint8_t,I,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",42,0,N,S,uint8_t,I,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,S,uint8_t,I,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",8,0,N,R,uint8_t,M,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",44,0,N,S,uint8_t,M,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,S,uint8_t,M,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",10,0,N,R,uint8_t,B,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,S,uint8_t,B,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,S,uint8_t,B,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",10,0,N,R,uint8_t,W,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,S,uint8_t,W,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,S,uint8_t,W,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, WifiPart..","..McuPart..",64,0,N,R,uint8_t,T,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,S,uint8_t,T,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.writeLine(handleBA, McuPart..","..WifiPart..",9,0,N,S,uint8_t,T,uint0_t,uint8_t\n")
checkOK(result,"write")
result=structmsg2.closeFile(handleBA)
checkOK(result,"close")
end
writeMsgHeads()
print("done")
|
some fixes/typo fixes added type of crc field.
|
some fixes/typo fixes added type of crc field.
|
Lua
|
mit
|
apwiede/nodemcu-firmware,apwiede/nodemcu-firmware,apwiede/nodemcu-firmware,apwiede/nodemcu-firmware
|
a18fba463793740c69e63b860f75df1a87ae1176
|
engine/Game.lua
|
engine/Game.lua
|
--------------------------------------------------------------------------------
local Background = require 'cherry.components.background'
local Screen = require 'cherry.components.screen'
local Effects = require 'cherry.engine.effects'
--------------------------------------------------------------------------------
local physics = require( 'physics' )
--------------------------------------------------------------------------------
local Game = {
RUNNING = 1,
STOPPED = 2
}
--------------------------------------------------------------------------------
function Game:new(extension)
local game = _.extend({
state = Game.STOPPED
}, extension)
setmetatable(game, { __index = Game })
return game
end
--------------------------------------------------------------------------------
function Game:start()
self:reset()
if (self.load) then
print('loading...')
local success = self:load()
if(success) then
print('loaded successfully')
self:run()
else
print('could not load properly')
self:onLoadFailed()
end
else
self:run()
end
end
function Game:run()
self.state = Game.RUNNING
physics.start()
physics.setGravity( App.xGravity, App.yGravity )
Camera:resetZoom()
Camera:center()
Camera:start()
App.score:createBar()
Background:darken()
self.onRun() -- from extension
Effects:restart()
print('Game runs!')
end
function Game:reset()
Camera:empty()
App.score:reset()
self.onReset() -- from extension
end
------------------------------------------
function Game:stop(userExit)
if(self.state == Game.STOPPED) then return end
self.state = Game.STOPPED
------------------------------------------
Screen:showBands()
Background:lighten()
App.score:display()
------------------------------------------
Effects:stop(true)
Camera:stop()
------------------------------------------
self.onStop(userExit) -- from extension
end
--------------------------------------------------------------------------------
return Game
|
--------------------------------------------------------------------------------
local Background = require 'cherry.components.background'
local Screen = require 'cherry.components.screen'
local Effects = require 'cherry.engine.effects'
--------------------------------------------------------------------------------
local physics = require( 'physics' )
--------------------------------------------------------------------------------
local Game = {
RUNNING = 1,
STOPPED = 2
}
--------------------------------------------------------------------------------
function Game:new(extension)
local game = _.extend({
state = Game.STOPPED
}, extension)
setmetatable(game, { __index = Game })
return game
end
--------------------------------------------------------------------------------
function Game:start()
self:reset()
if (self.load) then
print('loading...')
local success = self:load()
if(success) then
print('loaded successfully')
self:run()
else
print('could not load properly')
self:onLoadFailed()
end
else
self:run()
end
end
function Game:run()
self.state = Game.RUNNING
physics.start()
physics.setGravity( App.xGravity, App.yGravity )
Camera:resetZoom()
Camera:center()
Camera:start()
App.score:createBar()
Background:darken()
self.onRun() -- from extension
Effects:restart()
print('Game runs!')
end
function Game:reset()
Camera:empty()
App.score:reset()
self.onReset() -- from extension
end
------------------------------------------
function Game:stop(userExit)
if(self.state == Game.STOPPED) then return end
self.state = Game.STOPPED
------------------------------------------
if(not userExit) then
Screen:showBands()
App.score:display()
end
------------------------------------------
Background:lighten()
Effects:stop(true)
Camera:stop()
------------------------------------------
self.onStop(userExit) -- from extension
end
--------------------------------------------------------------------------------
return Game
|
fixed game.stop
|
fixed game.stop
|
Lua
|
bsd-3-clause
|
chrisdugne/cherry
|
809c814cb7114bd9b71396d3710097345eed6b82
|
extension/script/backend/worker/stdout.lua
|
extension/script/backend/worker/stdout.lua
|
local ev = require 'common.event'
local foreground
local background
local bright
local underline
local negative
local function split(str)
local r = {}
str:gsub('[^;]+', function (w) r[#r+1] = tonumber(w) end)
return r
end
local function vtmode(text)
local vt = {}
if foreground then
vt[#vt+1] = foreground
end
if background then
vt[#vt+1] = background
end
if bright then
vt[#vt+1] = "1"
end
if underline then
vt[#vt+1] = "4"
end
if negative then
vt[#vt+1] = "7"
end
for vtstr in text:gmatch "\x1b%[([0-9;]+)m" do
local codes = split(vtstr)
for n = 1, #codes do
local code = codes[n]
if code == 0 then
--reset
foreground = nil
background = nil
bright = nil
underline = nil
negative = nil
elseif code == 1 then
-- bright
bright = true
elseif code == 4 then
-- underline
underline = true
elseif code == 24 then
-- no underline
underline = false
elseif code == 7 then
-- negative
negative = true
elseif code == 27 then
-- no negative
negative = false
elseif (code >= 30 and code <= 37) or (code >= 90 and code <= 97) then
-- foreground
foreground = tostring(code)
elseif (code >= 40 and code <= 47) or (code >= 100 and code <= 107) then
-- background
background = tostring(code)
elseif code == 39 then
-- reset foreground
foreground = nil
elseif code == 40 then
-- reset background
background = nil
elseif code == 38 then
-- foreground
if n + 2 <= #codes then
foreground = codes[n] .. ";" .. codes[n + 1] .. ";" .. codes[n + 2]
n = n + 2
end
elseif code == 48 then
-- background
if n + 2 <= #codes then
background = codes[n] .. ";" .. codes[n + 1] .. ";" .. codes[n + 2]
n = n + 2
end
end
end
end
if #vt > 0 then
return "\x1b[" .. table.concat(vt, ";") .."m" .. text
end
return text
end
local curmsg = ''
local cursrc
local curline
local ignore
return function (msg, src, line)
curmsg = curmsg .. msg
cursrc = src and src or cursrc
curline = line and line or curline
if ignore then
if curmsg:sub(1,1) == ignore then
curmsg = curmsg:sub(2) or ''
end
ignore = nil
end
while true do
local pos = curmsg:find('[\r\n]')
if not pos then
cursrc = src
curline = line
return
end
if pos == #curmsg then
ignore = curmsg:sub(pos) == '\n' and '\r' or '\n'
else
local ln1 = curmsg:sub(pos,pos) or ''
local ln2 = curmsg:sub(pos+1,pos+1) or ''
if ln1 == '\n' and ln2 == '\r' then
pos = pos + 1
elseif ln1 == '\r' and ln2 == '\n' then
pos = pos + 1
end
end
local result = curmsg:sub(1,pos) or ''
curmsg = curmsg:sub(pos+1) or ''
ev.emit('output', 'stdout', vtmode(result), cursrc, curline)
cursrc = src
curline = line
end
end
|
local ev = require 'common.event'
local foreground
local background
local bright
local underline
local negative
local function split(str)
local r = {}
str:gsub('[^;]+', function (w) r[#r+1] = tonumber(w) end)
return r
end
local function vtmode(text)
local vt = {}
if foreground then
vt[#vt+1] = foreground
end
if background then
vt[#vt+1] = background
end
if bright then
vt[#vt+1] = "1"
end
if underline then
vt[#vt+1] = "4"
end
if negative then
vt[#vt+1] = "7"
end
for vtstr in text:gmatch "\x1b%[([0-9;]+)m" do
local codes = split(vtstr)
for n = 1, #codes do
local code = codes[n]
if code == 0 then
--reset
foreground = nil
background = nil
bright = nil
underline = nil
negative = nil
elseif code == 1 then
-- bright
bright = true
elseif code == 4 then
-- underline
underline = true
elseif code == 24 then
-- no underline
underline = false
elseif code == 7 then
-- negative
negative = true
elseif code == 27 then
-- no negative
negative = false
elseif (code >= 30 and code <= 37) or (code >= 90 and code <= 97) then
-- foreground
foreground = tostring(code)
elseif (code >= 40 and code <= 47) or (code >= 100 and code <= 107) then
-- background
background = tostring(code)
elseif code == 39 then
-- reset foreground
foreground = nil
elseif code == 40 then
-- reset background
background = nil
elseif code == 38 then
-- foreground
if n + 2 <= #codes then
foreground = codes[n] .. ";" .. codes[n + 1] .. ";" .. codes[n + 2]
n = n + 2
end
elseif code == 48 then
-- background
if n + 2 <= #codes then
background = codes[n] .. ";" .. codes[n + 1] .. ";" .. codes[n + 2]
n = n + 2
end
end
end
end
if #vt > 0 then
return "\x1b[" .. table.concat(vt, ";") .."m" .. text
end
return text
end
return function (msg, src, line)
ev.emit('output', 'stdout', vtmode(msg), src, line)
end
|
VSCode的bug已经修复,不再需要特殊处理了
|
VSCode的bug已经修复,不再需要特殊处理了
|
Lua
|
mit
|
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
|
77b50a21e64652369b9ce414b2a13e2c51d3d576
|
weather-widget/weather.lua
|
weather-widget/weather.lua
|
-------------------------------------------------
-- Weather Widget based on the OpenWeatherMap
-- https://openweathermap.org/
--
-- @author Pavel Makhov
-- @copyright 2018 Pavel Makhov
-------------------------------------------------
local http = require("socket.http")
local json = require("json")
local naughty = require("naughty")
local wibox = require("wibox")
local city = os.getenv("AWW_WEATHER_CITY") or "Montreal,ca"
local open_map_key = os.getenv("AWW_WEATHER_API_KEY") or 'c3d7320b359da4e48c2d682a04076576'
local path_to_icons = "/usr/share/icons/Arc/status/symbolic/"
local icon_widget = wibox.widget {
{
id = "icon",
resize = false,
widget = wibox.widget.imagebox,
},
layout = wibox.container.margin(brightness_icon, 0, 0, 3),
set_image = function(self, path)
self.icon.image = path
end,
}
local temp_widget = wibox.widget{
font = "Play 9",
widget = wibox.widget.textbox,
}
local weather_widget = wibox.widget {
icon_widget,
temp_widget,
layout = wibox.layout.fixed.horizontal,
}
-- helps to map openWeatherMap icons to Arc icons
local icon_map = {
["01d"] = "weather-clear-symbolic.svg",
["02d"] = "weather-few-clouds-symbolic.svg",
["03d"] = "weather-clouds-symbolic.svg",
["04d"] = "weather-overcast-symbolic.svg",
["09d"] = "weather-showers-scattered-symbolic.svg",
["10d"] = "weather-showers-symbolic.svg",
["11d"] = "weather-storm-symbolic.svg",
["13d"] = "weather-snow-symbolic.svg",
["50d"] = "weather-fog-symbolic.svg",
["01n"] = "weather-clear-night-symbolic.svg",
["02n"] = "weather-few-clouds-night-symbolic.svg",
["03n"] = "weather-clouds-night-symbolic.svg",
["04n"] = "weather-overcast-symbolic.svg",
["09n"] = "weather-showers-scattered-symbolic.svg",
["10n"] = "weather-showers-symbolic.svg",
["11n"] = "weather-storm-symbolic.svg",
["13n"] = "weather-snow-symbolic.svg",
["50n"] = "weather-fog-symbolic.svg"
}
-- handy function to convert temperature from Kelvin to Celcius
function to_celcius(kelvin)
return math.floor(tonumber(kelvin) - 273.15)
end
-- Return wind direction as a string.
function to_direction(degrees)
local directions = {
{ "N", 348.75, 360 },
{ "N", 0, 11.25 },
{ "NNE", 11.25, 33.75 },
{ "NE", 33.75, 56.25 },
{ "ENE", 56.25, 78.75 },
{ "E", 78.75, 101.25 },
{ "ESE", 101.25, 123.75 },
{ "SE", 123.75, 146.25 },
{ "SSE", 146.25, 168.75 },
{ "S", 168.75, 191.25 },
{ "SSW", 191.25, 213.75 },
{ "SW", 213.75, 236.25 },
{ "WSW", 236.25, 258.75 },
{ "W", 258.75, 281.25 },
{ "WNW", 281.25, 303.75 },
{ "NW", 303.75, 326.25 },
{ "NNW", 326.25, 348.75 },
}
for i, dir in ipairs(directions) do
if degrees > dir[2] and degrees < dir[3] then
return dir[1]
end
end
end
local weather_timer = timer({ timeout = 60 })
local resp
weather_timer:connect_signal("timeout", function ()
local resp_json = http.request("https://api.openweathermap.org/data/2.5/weather?q=" .. city .."&appid=" .. open_map_key)
if (resp_json ~= nil) then
resp = json.decode(resp_json)
icon_widget.image = path_to_icons .. icon_map[resp.weather[1].icon]
temp_widget:set_text(to_celcius(resp.main.temp) .. "°C")
end
end)
weather_timer:start()
weather_timer:emit_signal("timeout")
-- Notification with weather information. Popups when mouse hovers over the icon
local notification
weather_widget:connect_signal("mouse::enter", function()
notification = naughty.notify{
icon = path_to_icons .. icon_map[resp.weather[1].icon],
icon_size=20,
text =
'<big>' .. resp.weather[1].main .. ' (' .. resp.weather[1].description .. ')</big><br>' ..
'<b>Humidity:</b> ' .. resp.main.humidity .. '%<br>' ..
'<b>Temperature: </b>' .. to_celcius(resp.main.temp) .. '<br>' ..
'<b>Pressure: </b>' .. resp.main.pressure .. 'hPa<br>' ..
'<b>Clouds: </b>' .. resp.clouds.all .. '%<br>' ..
'<b>Wind: </b>' .. resp.wind.speed .. 'm/s (' .. to_direction(resp.wind.deg) .. ')',
timeout = 5, hover_timeout = 10,
width = 200
}
end)
weather_widget:connect_signal("mouse::leave", function()
naughty.destroy(notification)
end)
return weather_widget
|
-------------------------------------------------
-- Weather Widget based on the OpenWeatherMap
-- https://openweathermap.org/
--
-- @author Pavel Makhov
-- @copyright 2018 Pavel Makhov
-------------------------------------------------
local http = require("socket.http")
local json = require("json")
local naughty = require("naughty")
local wibox = require("wibox")
local city = os.getenv("AWW_WEATHER_CITY") or "Montreal,ca"
local open_map_key = os.getenv("AWW_WEATHER_API_KEY") or 'c3d7320b359da4e48c2d682a04076576'
local path_to_icons = "/usr/share/icons/Arc/status/symbolic/"
local icon_widget = wibox.widget {
{
id = "icon",
resize = false,
widget = wibox.widget.imagebox,
},
layout = wibox.container.margin(brightness_icon, 0, 0, 3),
set_image = function(self, path)
self.icon.image = path
end,
}
local temp_widget = wibox.widget{
font = "Play 9",
widget = wibox.widget.textbox,
}
local weather_widget = wibox.widget {
icon_widget,
temp_widget,
layout = wibox.layout.fixed.horizontal,
}
-- helps to map openWeatherMap icons to Arc icons
local icon_map = {
["01d"] = "weather-clear-symbolic.svg",
["02d"] = "weather-few-clouds-symbolic.svg",
["03d"] = "weather-clouds-symbolic.svg",
["04d"] = "weather-overcast-symbolic.svg",
["09d"] = "weather-showers-scattered-symbolic.svg",
["10d"] = "weather-showers-symbolic.svg",
["11d"] = "weather-storm-symbolic.svg",
["13d"] = "weather-snow-symbolic.svg",
["50d"] = "weather-fog-symbolic.svg",
["01n"] = "weather-clear-night-symbolic.svg",
["02n"] = "weather-few-clouds-night-symbolic.svg",
["03n"] = "weather-clouds-night-symbolic.svg",
["04n"] = "weather-overcast-symbolic.svg",
["09n"] = "weather-showers-scattered-symbolic.svg",
["10n"] = "weather-showers-symbolic.svg",
["11n"] = "weather-storm-symbolic.svg",
["13n"] = "weather-snow-symbolic.svg",
["50n"] = "weather-fog-symbolic.svg"
}
-- handy function to convert temperature from Kelvin to Celcius
function to_celcius(kelvin)
return math.floor(tonumber(kelvin) - 273.15)
end
-- Return wind direction as a string.
function to_direction(degrees)
local directions = {
{ "N", 348.75, 360 },
{ "N", 0, 11.25 },
{ "NNE", 11.25, 33.75 },
{ "NE", 33.75, 56.25 },
{ "ENE", 56.25, 78.75 },
{ "E", 78.75, 101.25 },
{ "ESE", 101.25, 123.75 },
{ "SE", 123.75, 146.25 },
{ "SSE", 146.25, 168.75 },
{ "S", 168.75, 191.25 },
{ "SSW", 191.25, 213.75 },
{ "SW", 213.75, 236.25 },
{ "WSW", 236.25, 258.75 },
{ "W", 258.75, 281.25 },
{ "WNW", 281.25, 303.75 },
{ "NW", 303.75, 326.25 },
{ "NNW", 326.25, 348.75 },
}
if degrees == nil then
return "Unknown dir"
end
for i, dir in ipairs(directions) do
if degrees > dir[2] and degrees < dir[3] then
return dir[1]
end
end
end
local weather_timer = timer({ timeout = 60 })
local resp
weather_timer:connect_signal("timeout", function ()
local resp_json = http.request("https://api.openweathermap.org/data/2.5/weather?q=" .. city .."&appid=" .. open_map_key)
if (resp_json ~= nil) then
resp = json.decode(resp_json)
icon_widget.image = path_to_icons .. icon_map[resp.weather[1].icon]
temp_widget:set_text(to_celcius(resp.main.temp) .. "°C")
end
end)
weather_timer:start()
weather_timer:emit_signal("timeout")
-- Notification with weather information. Popups when mouse hovers over the icon
local notification
weather_widget:connect_signal("mouse::enter", function()
notification = naughty.notify{
icon = path_to_icons .. icon_map[resp.weather[1].icon],
icon_size=20,
text =
'<big>' .. resp.weather[1].main .. ' (' .. resp.weather[1].description .. ')</big><br>' ..
'<b>Humidity:</b> ' .. resp.main.humidity .. '%<br>' ..
'<b>Temperature: </b>' .. to_celcius(resp.main.temp) .. '<br>' ..
'<b>Pressure: </b>' .. resp.main.pressure .. 'hPa<br>' ..
'<b>Clouds: </b>' .. resp.clouds.all .. '%<br>' ..
'<b>Wind: </b>' .. resp.wind.speed .. 'm/s (' .. to_direction(resp.wind.deg) .. ')',
timeout = 5, hover_timeout = 10,
width = 200
}
end)
weather_widget:connect_signal("mouse::leave", function()
naughty.destroy(notification)
end)
return weather_widget
|
Take into account case with an unset wind degrees
|
Take into account case with an unset wind degrees
Fixes exception, which happens when comparing nil to a number
|
Lua
|
mit
|
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets,streetturtle/AwesomeWM
|
8d78a889fbfcc2b21ff7427f77432ebe2486dea1
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
local routes6 = luci.sys.net.routes6()
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
if routes6 then
v = m:section(Table, routes6, translate("a_n_routes_kernel6"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return string.format( "%08X", routes6[section].metric )
end
end
end
s = m:section(TypedSection, "route", translate("a_n_routes_static4"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
if routes6 then
s = m:section(TypedSection, "route6", translate("a_n_routes_static6"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target6"))
s:option(Value, "gateway", translate("gateway6")).rmempty = true
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
local routes6 = luci.sys.net.routes6()
local bit = require "bit"
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
if routes6 then
v = m:section(Table, routes6, translate("a_n_routes_kernel6"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
end
s = m:section(TypedSection, "route", translate("a_n_routes_static4"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
if routes6 then
s = m:section(TypedSection, "route6", translate("a_n_routes_static6"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target6"))
s:option(Value, "gateway", translate("gateway6")).rmempty = true
end
return m
|
Fixed an overflow error with IPv6 route metric
|
Fixed an overflow error with IPv6 route metric
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci
|
e4b87cbcabe8ae27ac10ee22d95e9dcbaf2b61ce
|
util/sasl.lua
|
util/sasl.lua
|
-- sasl.lua v0.4
-- Copyright (C) 2008-2009 Tobias Markmann
--
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-- * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
local md5 = require "util.hashes".md5;
local log = require "util.logger".init("sasl");
local st = require "util.stanza";
local set = require "util.set";
local array = require "util.array";
local to_unicode = require "util.encodings".idna.to_unicode;
local tostring = tostring;
local pairs, ipairs = pairs, ipairs;
local t_insert, t_concat = table.insert, table.concat;
local s_match = string.match;
local type = type
local error = error
local setmetatable = setmetatable;
local assert = assert;
local require = require;
require "util.iterators"
local keys = keys
local array = require "util.array"
module "sasl"
--[[
Authentication Backend Prototypes:
state = false : disabled
state = true : enabled
state = nil : non-existant
plain:
function(username, realm)
return password, state;
end
plain-test:
function(username, realm, password)
return true or false, state;
end
digest-md5:
function(username, domain, realm, encoding) -- domain and realm are usually the same; for some broken
-- implementations it's not
return digesthash, state;
end
digest-md5-test:
function(username, domain, realm, encoding, digesthash)
return true or false, state;
end
]]
local method = {};
method.__index = method;
local mechanisms = {};
local backend_mechanism = {};
-- register a new SASL mechanims
local function registerMechanism(name, backends, f)
assert(type(name) == "string", "Parameter name MUST be a string.");
assert(type(backends) == "string" or type(backends) == "table", "Parameter backends MUST be either a string or a table.");
assert(type(f) == "function", "Parameter f MUST be a function.");
mechanisms[name] = f
for _, backend_name in ipairs(backends) do
if backend_mechanism[backend_name] == nil then backend_mechanism[backend_name] = {}; end
t_insert(backend_mechanism[backend_name], name);
end
end
-- create a new SASL object which can be used to authenticate clients
function new(realm, profile, forbidden)
sasl_i = {profile = profile};
sasl_i.realm = realm;
s = setmetatable(sasl_i, method);
s:forbidden(sasl_i, forbidden)
return s;
end
-- get a fresh clone with the same realm, profiles and forbidden mechanisms
function method:clean_clone()
return new(self.realm, self.profile, self:forbidden())
end
-- set the forbidden mechanisms
function method:forbidden( restrict )
if restrict then
-- set forbidden
self.restrict = set.new(restrict);
else
-- get forbidden
return array.collect(self.restrict:items());
end
end
-- get a list of possible SASL mechanims to use
function method:mechanisms()
local mechanisms = {}
for backend, f in pairs(self.profile) do
if backend_mechanism[backend] then
for _, mechanism in ipairs(backend_mechanism[backend]) do
if not sasl_i.restrict:contains(mechanism) then
mechanisms[mechanism] = true;
end
end
end
end
self["possible_mechanisms"] = mechanisms;
return array.collect(keys(mechanisms));
end
-- select a mechanism to use
function method:select(mechanism)
if self.mech_i then
return false;
end
self.mech_i = mechanisms[mechanism]
if self.mech_i == nil then
return false;
end
return true;
end
-- feed new messages to process into the library
function method:process(message)
--if message == "" or message == nil then return "failure", "malformed-request" end
return self.mech_i(self, message);
end
-- load the mechanisms
load_mechs = {"plain", "digest-md5", "anonymous", "scram"}
for _, mech in ipairs(load_mechs) do
local name = "util.sasl."..mech;
local m = require(name);
m.init(registerMechanism)
end
return _M;
|
-- sasl.lua v0.4
-- Copyright (C) 2008-2009 Tobias Markmann
--
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-- * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
local md5 = require "util.hashes".md5;
local log = require "util.logger".init("sasl");
local st = require "util.stanza";
local set = require "util.set";
local array = require "util.array";
local to_unicode = require "util.encodings".idna.to_unicode;
local tostring = tostring;
local pairs, ipairs = pairs, ipairs;
local t_insert, t_concat = table.insert, table.concat;
local s_match = string.match;
local type = type
local error = error
local setmetatable = setmetatable;
local assert = assert;
local require = require;
require "util.iterators"
local keys = keys
local array = require "util.array"
module "sasl"
--[[
Authentication Backend Prototypes:
state = false : disabled
state = true : enabled
state = nil : non-existant
plain:
function(username, realm)
return password, state;
end
plain-test:
function(username, realm, password)
return true or false, state;
end
digest-md5:
function(username, domain, realm, encoding) -- domain and realm are usually the same; for some broken
-- implementations it's not
return digesthash, state;
end
digest-md5-test:
function(username, domain, realm, encoding, digesthash)
return true or false, state;
end
]]
local method = {};
method.__index = method;
local mechanisms = {};
local backend_mechanism = {};
-- register a new SASL mechanims
local function registerMechanism(name, backends, f)
assert(type(name) == "string", "Parameter name MUST be a string.");
assert(type(backends) == "string" or type(backends) == "table", "Parameter backends MUST be either a string or a table.");
assert(type(f) == "function", "Parameter f MUST be a function.");
mechanisms[name] = f
for _, backend_name in ipairs(backends) do
if backend_mechanism[backend_name] == nil then backend_mechanism[backend_name] = {}; end
t_insert(backend_mechanism[backend_name], name);
end
end
-- create a new SASL object which can be used to authenticate clients
function new(realm, profile, forbidden)
local sasl_i = {profile = profile};
sasl_i.realm = realm;
local s = setmetatable(sasl_i, method);
if forbidden == nil then forbidden = {} end
s:forbidden(forbidden)
return s;
end
-- get a fresh clone with the same realm, profiles and forbidden mechanisms
function method:clean_clone()
return new(self.realm, self.profile, self:forbidden())
end
-- set the forbidden mechanisms
function method:forbidden( restrict )
if restrict then
-- set forbidden
self.restrict = set.new(restrict);
else
-- get forbidden
return array.collect(self.restrict:items());
end
end
-- get a list of possible SASL mechanims to use
function method:mechanisms()
local mechanisms = {}
for backend, f in pairs(self.profile) do
if backend_mechanism[backend] then
for _, mechanism in ipairs(backend_mechanism[backend]) do
if not self.restrict:contains(mechanism) then
mechanisms[mechanism] = true;
end
end
end
end
self["possible_mechanisms"] = mechanisms;
return array.collect(keys(mechanisms));
end
-- select a mechanism to use
function method:select(mechanism)
if self.mech_i then
return false;
end
self.mech_i = mechanisms[mechanism]
if self.mech_i == nil then
return false;
end
return true;
end
-- feed new messages to process into the library
function method:process(message)
--if message == "" or message == nil then return "failure", "malformed-request" end
return self.mech_i(self, message);
end
-- load the mechanisms
load_mechs = {"plain", "digest-md5", "anonymous", "scram"}
for _, mech in ipairs(load_mechs) do
local name = "util.sasl."..mech;
local m = require(name);
m.init(registerMechanism)
end
return _M;
|
util.sasl: Move some variables to local space. Fix a bug.
|
util.sasl: Move some variables to local space. Fix a bug.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
4222cc66e9c5fbaa0335bd4180cd03bbd66695db
|
lua_scripts/init.lua
|
lua_scripts/init.lua
|
-- Copyright (c) 2011 Nokia Corporation.
-- Author: Lauri T. Aarnio
--
-- Licensed under LGPL version 2.1, see top level LICENSE file for details.
-- This script is executed by sb2d at startup, this
-- initializes the rule tree database (which is empty
-- but attached when this script is started)
session_dir = os.getenv("SBOX_SESSION_DIR")
debug_messages_enabled = sblib.debug_messages_enabled()
-- This version string is used to check that the lua scripts offer
-- what sb2d expects, and v.v.
-- Increment the number whenever the interface beween Lua and C is changed.
--
-- NOTE: the corresponding identifier for C is in include/sb2.h,
-- see that file for description about differences
sb2d_lua_c_interface_version = "301"
-- Create the "vperm" catalog
-- vperm::inodestats is the binary tree, initially empty,
-- but the entry must be present.
-- all counters must be present and zero in the beginning.
ruletree.catalog_set("vperm", "inodestats", 0)
ruletree.catalog_set("vperm", "num_active_inodestats",
ruletree.new_uint32(0))
function do_file(filename)
if (debug_messages_enabled) then
sblib.log("debug", string.format("Loading '%s'", filename))
end
local f, err = loadfile(filename)
if (f == nil) then
error("\nError while loading " .. filename .. ": \n"
.. err .. "\n")
-- "error()" never returns
else
f() -- execute the loaded chunk
end
end
-- Load session-specific settings
do_file(session_dir .. "/sb2-session.conf")
target_root = sbox_target_root
if (not target_root or target_root == "") then
target_root = "/"
end
tools_root = sbox_tools_root
if (tools_root == "") then
tools_root = nil
end
tools = tools_root
if (not tools) then
tools = "/"
end
if (tools == "/") then
tools_prefix = ""
else
tools_prefix = tools
end
-- Load session configuration, and add variables to ruletree.
do_file(session_dir .. "/sb2-session.conf")
ruletree.catalog_set("config", "sbox_cpu",
ruletree.new_string(sbox_cpu))
ruletree.catalog_set("config", "sbox_uname_machine",
ruletree.new_string(sbox_uname_machine))
ruletree.catalog_set("config", "sbox_emulate_sb1_bugs",
ruletree.new_string(sbox_emulate_sb1_bugs))
-- Load exec config.
-- NOTE: At this point all conf_cputransparency_* variables
-- are still missing from exec_config.lua. Other variables
-- (conf_tools_*, conf_target_*, host_*) are there.
do_file(session_dir .. "/exec_config.lua")
-- Add exec config parameters to ruletree:
ruletree.catalog_set("config", "host_ld_preload", ruletree.new_string(host_ld_preload))
ruletree.catalog_set("config", "host_ld_library_path", ruletree.new_string(host_ld_library_path))
-- Build "all_modes" table. all_modes[1] will be name of default mode.
all_modes_str = os.getenv("SB2_ALL_MODES")
all_modes = {}
if (all_modes_str) then
for m in string.gmatch(all_modes_str, "[^ ]*") do
if m ~= "" then
table.insert(all_modes, m)
ruletree.catalog_set("MODES", m, 0)
end
end
end
ruletree.catalog_set("MODES", "#default", ruletree.new_string(all_modes[1]))
-- Exec preprocessing rules to ruletree:
do_file(session_dir .. "/lua_scripts/init_argvmods_rules.lua")
-- mode-spefic config to ruletree:
do_file(session_dir .. "/lua_scripts/init_modeconfig.lua")
-- Create rules based on "argvmods", e.g. rules for toolchain components etc.
do_file(session_dir .. "/lua_scripts/init_autogen_usr_bin_rules.lua")
-- Create reverse mapping rules.
do_file(session_dir .. "/lua_scripts/create_reverse_rules.lua")
-- Now add all mapping rules to ruletree:
do_file(session_dir .. "/lua_scripts/add_rules_to_rule_tree.lua")
-- and networking rules:
do_file(session_dir .. "/lua_scripts/init_net_modes.lua")
-- Done. conf_cputransparency_* are still missing from the rule tree,
-- but those can't be added yet (see the "sb2" script - it finds
-- values for those variables only after sb2d has executed this
-- script)
io.stdout:flush()
io.stderr:flush()
|
-- Copyright (c) 2011 Nokia Corporation.
-- Author: Lauri T. Aarnio
--
-- Licensed under LGPL version 2.1, see top level LICENSE file for details.
-- This script is executed by sb2d at startup, this
-- initializes the rule tree database (which is empty
-- but attached when this script is started)
session_dir = os.getenv("SBOX_SESSION_DIR")
debug_messages_enabled = sblib.debug_messages_enabled()
-- This version string is used to check that the lua scripts offer
-- what sb2d expects, and v.v.
-- Increment the number whenever the interface beween Lua and C is changed.
--
-- NOTE: the corresponding identifier for C is in include/sb2.h,
-- see that file for description about differences
sb2d_lua_c_interface_version = "301"
-- Create the "vperm" catalog
-- vperm::inodestats is the binary tree, initially empty,
-- but the entry must be present.
-- all counters must be present and zero in the beginning.
ruletree.catalog_set("vperm", "inodestats", 0)
ruletree.catalog_set("vperm", "num_active_inodestats",
ruletree.new_uint32(0))
function do_file(filename)
if (debug_messages_enabled) then
sblib.log("debug", string.format("Loading '%s'", filename))
end
local f, err = loadfile(filename)
if (f == nil) then
error("\nError while loading " .. filename .. ": \n"
.. err .. "\n")
-- "error()" never returns
else
f() -- execute the loaded chunk
end
end
-- A dummy sb2_procfs_mapper function is needed for the rules,
-- now when the real function is gone
function sb2_procfs_mapper()
return true
end
-- Load session-specific settings
do_file(session_dir .. "/sb2-session.conf")
target_root = sbox_target_root
if (not target_root or target_root == "") then
target_root = "/"
end
tools_root = sbox_tools_root
if (tools_root == "") then
tools_root = nil
end
tools = tools_root
if (not tools) then
tools = "/"
end
if (tools == "/") then
tools_prefix = ""
else
tools_prefix = tools
end
-- Load session configuration, and add variables to ruletree.
do_file(session_dir .. "/sb2-session.conf")
ruletree.catalog_set("config", "sbox_cpu",
ruletree.new_string(sbox_cpu))
ruletree.catalog_set("config", "sbox_uname_machine",
ruletree.new_string(sbox_uname_machine))
ruletree.catalog_set("config", "sbox_emulate_sb1_bugs",
ruletree.new_string(sbox_emulate_sb1_bugs))
-- Load exec config.
-- NOTE: At this point all conf_cputransparency_* variables
-- are still missing from exec_config.lua. Other variables
-- (conf_tools_*, conf_target_*, host_*) are there.
do_file(session_dir .. "/exec_config.lua")
-- Add exec config parameters to ruletree:
ruletree.catalog_set("config", "host_ld_preload", ruletree.new_string(host_ld_preload))
ruletree.catalog_set("config", "host_ld_library_path", ruletree.new_string(host_ld_library_path))
-- Build "all_modes" table. all_modes[1] will be name of default mode.
all_modes_str = os.getenv("SB2_ALL_MODES")
all_modes = {}
if (all_modes_str) then
for m in string.gmatch(all_modes_str, "[^ ]*") do
if m ~= "" then
table.insert(all_modes, m)
ruletree.catalog_set("MODES", m, 0)
end
end
end
ruletree.catalog_set("MODES", "#default", ruletree.new_string(all_modes[1]))
-- Exec preprocessing rules to ruletree:
do_file(session_dir .. "/lua_scripts/init_argvmods_rules.lua")
-- mode-spefic config to ruletree:
do_file(session_dir .. "/lua_scripts/init_modeconfig.lua")
-- Create rules based on "argvmods", e.g. rules for toolchain components etc.
do_file(session_dir .. "/lua_scripts/init_autogen_usr_bin_rules.lua")
-- Create reverse mapping rules.
do_file(session_dir .. "/lua_scripts/create_reverse_rules.lua")
-- Now add all mapping rules to ruletree:
do_file(session_dir .. "/lua_scripts/add_rules_to_rule_tree.lua")
-- and networking rules:
do_file(session_dir .. "/lua_scripts/init_net_modes.lua")
-- Done. conf_cputransparency_* are still missing from the rule tree,
-- but those can't be added yet (see the "sb2" script - it finds
-- values for those variables only after sb2d has executed this
-- script)
io.stdout:flush()
io.stderr:flush()
|
Bugfix: /proc mapping rules work again
|
Bugfix: /proc mapping rules work again
- A dummy sb2_procfs_mapper() function is needed; otherwise
/proc rules won't go correctly to the rule tree (the real
sb2_procfs_mapper function was removed when the Lua mapping
logic was removed. Now the function is not called anymore,
but must exist for identifying /proc rules)
|
Lua
|
lgpl-2.1
|
h113331pp/scratchbox2,ldbox/ldbox,ldbox/ldbox,ldbox/ldbox,OlegGirko/ldbox,ldbox/ldbox,OlegGirko/ldbox,OlegGirko/ldbox,ldbox/ldbox,h113331pp/scratchbox2,h113331pp/scratchbox2,OlegGirko/ldbox,h113331pp/scratchbox2,OlegGirko/ldbox,h113331pp/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2
|
e2830e6506fd8f09da122622d4512b663f791200
|
bench/client.lua
|
bench/client.lua
|
local Loader = require "cosy.loader"
local Configuration = require "cosy.configuration"
local I18n = require "cosy.i18n"
local Library = require "cosy.library"
local Value = require "cosy.value"
do
os.execute "redis-cli flushall"
end
local token = arg [1]
local ok, err = pcall (function ()
local function show (name, x)
print (name, Value.expression (x))
end
local lib = Library.connect "http://127.0.0.1:8080/"
-- local lib = Library.connect "http://cosy.linard.fr/"
local info = lib.information ()
-- show ("information", info)
-- print (lib.statistics ())
local tos = lib.tos ()
show ("terms of service", tos)
local token = lib.create_user {
username = "alinard",
password = "password",
email = "[email protected]",
tos_digest = tos.tos_digest:upper (),
locale = "en",
}
show ("create user", token)
local token = lib.authenticate {
username = "alinard",
password = "password",
}
show ("authenticate", token)
-- local result = lib.suspend_user {
-- token = token,
-- username = "alinard",
-- }
-- show ("suspend user", result)
-- local result = lib.delete_user {
-- token = token,
-- }
-- show ("delete user", result)
-- local token = lib.authenticate {
-- username = "alinard",
-- password = "password",
-- }
-- show ("authenticate", token)
--[==[
lib.suspend_user {
token = token,
username = "alinard",
}
lib.reset_user {
email = "[email protected]",
}
--]==]
--[==[
local start = require "socket".gettime ()
local n = 1000
for _ = 1, n do
assert (lib.information ().name)
end
local finish = require "socket".gettime ()
print (math.floor (n / (finish - start)), "requests/second")
--]==]
lib.stop {
token = token,
}
end)
if not ok then
if type (err) == "table" then
local message = I18n (err)
print ("error:", message, Value.expression (err))
else
print (err)
end
end
|
local Loader = require "cosy.loader"
local Configuration = require "cosy.configuration"
local I18n = require "cosy.i18n"
local Library = require "cosy.library"
local Value = require "cosy.value"
local ok, err = pcall (function ()
local function show (name, x)
print (name, Value.expression (x))
end
local lib = Library.connect "http://127.0.0.1:8080/"
-- local lib = Library.connect "http://cosy.linard.fr/"
local info = lib.information ()
show ("information", info)
-- print (lib.statistics ())
local tos = lib.tos ()
show ("terms of service", tos)
--[[
local token = lib.create_user {
username = "alinard",
password = "password",
email = "[email protected]",
tos_digest = tos.tos_digest:upper (),
locale = "en",
}
show ("create user", token)
local token = lib.authenticate {
username = "alinard",
password = "password",
}
show ("authenticate", token)
--]]
-- local result = lib.suspend_user {
-- token = token,
-- username = "alinard",
-- }
-- show ("suspend user", result)
-- local result = lib.delete_user {
-- token = token,
-- }
-- show ("delete user", result)
-- local token = lib.authenticate {
-- username = "alinard",
-- password = "password",
-- }
-- show ("authenticate", token)
--[==[
lib.suspend_user {
token = token,
username = "alinard",
}
lib.reset_user {
email = "[email protected]",
}
--]==]
--[==[
local start = require "socket".gettime ()
local n = 1000
for _ = 1, n do
assert (lib.information ().name)
end
local finish = require "socket".gettime ()
print (math.floor (n / (finish - start)), "requests/second")
--]==]
end)
if not ok then
if type (err) == "table" then
local message = I18n (err)
print ("error:", message, Value.expression (err))
else
print (err)
end
end
|
Small fix of client.
|
Small fix of client.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
83307551d14dff831118fe7549f40fbd7d0c2936
|
scen_edit/view/alliance/diplomacy_window.lua
|
scen_edit/view/alliance/diplomacy_window.lua
|
DiplomacyWindow = LCS.class{}
function DiplomacyWindow:init(trigger)
self.teamsPanel = StackPanel:New {
itemMargin = {0, 0, 0, 0},
x = 1,
y = 1,
right = 1,
autosize = true,
resizeItems = false,
}
--titles
local titlesPanel = MakeComponentPanel(self.teamsPanel)
local lblTeams = Label:New {
caption = "Teams",
x = 1,
width = 150,
parent = titlesPanel,
}
local i = 1
for id, team in pairs(SCEN_EDIT.model.teamManager:getAllTeams()) do
local fontColor = SCEN_EDIT.glToFontColor(team.color)
local lblTeam = Label:New {
caption = fontColor .. id .. "\b",
x = 160 + i * 40,
width = 30,
parent = titlesPanel,
}
i = i + 1
end
--teams
for _, team in pairs(SCEN_EDIT.model.teamManager:getAllTeams()) do
local stackTeamPanel = MakeComponentPanel(self.teamsPanel)
local fontColor = SCEN_EDIT.glToFontColor(team.color)
local lblTeam = Label:New {
caption = fontColor .. "Team: " .. team.name .. "\b",
x = 1,
width = 150,
parent = stackTeamPanel,
}
for _, team2 in pairs(SCEN_EDIT.model.teamManager:getAllTeams()) do
if team1.id ~= team2.id then
self.cbSpecialUnit = Checkbox:New {
caption = '',
x = 160 + j * 40,
width = 30,
checked = Spring.AreTeamsAllied(team.id, team2.id),
boxalign = 'left',
parent = stackTeamPanel,
OnChange = {
function(cbToggled, checked)
local cmd = SetAllyCommand(team.allyTeam, team2.allyTeam, checked)
SCEN_EDIT.commandManager:execute(cmd)
end
}
}
end
end
--[[
local cmbAlliance = ComboBox:New {
x = 160,
width = 110,
height = SCEN_EDIT.conf.B_HEIGHT,
parent = stackTeamPanel,
items = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
}
cmbAlliance:Select(team.allyTeam + 1)
cmbAlliance.OnSelect = {
function(obj, itemIdx, selected)
if selected and itemIdx > 0 then
local newAllyTeamId = cmbAlliance.items[itemIdx]
if newAllyTeamId ~= team.allyTeam then
local cmd = ChangeAllyTeamCommand(team.id, newAllyTeamId)
SCEN_EDIT.commandManager:execute(cmd)
-- TODO: should be updated in a listener instead
team.allyTeam = newAllyTeamId
end
end
end
}
--]]
end
self.btnClose = Button:New {
caption='Close',
width = 100,
right = 1,
bottom = 1,
height = SCEN_EDIT.conf.B_HEIGHT,
OnClick = { function() self.window:Dispose() end }
}
self.window = Window:New {
width = math.min(800, math.max(400, 250 + #SCEN_EDIT.model.teamManager:getAllTeams() * 30)),
height = math.min(800, math.max(400, 250 + #SCEN_EDIT.model.teamManager:getAllTeams() * 30)),
minimumSize = {300,300},
parent = screen0,
caption = "Alliances",
x = 500,
y = 200,
children = {
ScrollPanel:New {
x = 1,
y = 15,
right = 5,
bottom = SCEN_EDIT.conf.C_HEIGHT * 2,
children = {
self.teamsPanel
},
},
self.btnClose,
}
}
end
|
DiplomacyWindow = LCS.class{}
function DiplomacyWindow:init(trigger)
self.teamsPanel = StackPanel:New {
itemMargin = {0, 0, 0, 0},
x = 1,
y = 1,
right = 1,
autosize = true,
resizeItems = false,
}
--titles
local titlesPanel = MakeComponentPanel(self.teamsPanel)
local lblTeams = Label:New {
caption = "Teams",
x = 1,
width = 150,
parent = titlesPanel,
}
local i = 1
for id, team in pairs(SCEN_EDIT.model.teamManager:getAllTeams()) do
local fontColor = SCEN_EDIT.glToFontColor(team.color)
local lblTeam = Label:New {
caption = fontColor .. id .. "\b",
x = 160 + i * 40,
width = 30,
parent = titlesPanel,
}
i = i + 1
end
--teams
for _, team in pairs(SCEN_EDIT.model.teamManager:getAllTeams()) do
local stackTeamPanel = MakeComponentPanel(self.teamsPanel)
local fontColor = SCEN_EDIT.glToFontColor(team.color)
local lblTeam = Label:New {
caption = fontColor .. "Team: " .. team.name .. "\b",
x = 1,
width = 150,
parent = stackTeamPanel,
}
local j = 1
for _, team2 in pairs(SCEN_EDIT.model.teamManager:getAllTeams()) do
if team.id ~= team2.id then
self.cbSpecialUnit = Checkbox:New {
caption = '',
x = 160 + j * 40,
width = 30,
checked = Spring.AreTeamsAllied(team.id, team2.id),
boxalign = 'left',
parent = stackTeamPanel,
OnChange = {
function(cbToggled, checked)
local cmd = SetAllyCommand(team.allyTeam, team2.allyTeam, checked)
SCEN_EDIT.commandManager:execute(cmd)
end
}
}
end
j = j + 1
end
--[[
local cmbAlliance = ComboBox:New {
x = 160,
width = 110,
height = SCEN_EDIT.conf.B_HEIGHT,
parent = stackTeamPanel,
items = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
}
cmbAlliance:Select(team.allyTeam + 1)
cmbAlliance.OnSelect = {
function(obj, itemIdx, selected)
if selected and itemIdx > 0 then
local newAllyTeamId = cmbAlliance.items[itemIdx]
if newAllyTeamId ~= team.allyTeam then
local cmd = ChangeAllyTeamCommand(team.id, newAllyTeamId)
SCEN_EDIT.commandManager:execute(cmd)
-- TODO: should be updated in a listener instead
team.allyTeam = newAllyTeamId
end
end
end
}
--]]
end
self.btnClose = Button:New {
caption='Close',
width = 100,
right = 1,
bottom = 1,
height = SCEN_EDIT.conf.B_HEIGHT,
OnClick = { function() self.window:Dispose() end }
}
self.window = Window:New {
width = math.min(800, math.max(400, 250 + #SCEN_EDIT.model.teamManager:getAllTeams() * 30)),
height = math.min(800, math.max(400, 250 + #SCEN_EDIT.model.teamManager:getAllTeams() * 30)),
minimumSize = {300,300},
parent = screen0,
caption = "Alliances",
x = 500,
y = 200,
children = {
ScrollPanel:New {
x = 1,
y = 15,
right = 5,
bottom = SCEN_EDIT.conf.C_HEIGHT * 2,
children = {
self.teamsPanel
},
},
self.btnClose,
}
}
end
|
fix weird bugs with diplomacy window (probably some old changes went uncommitted..
|
fix weird bugs with diplomacy window (probably some old changes went uncommitted..
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
6fbba696c2e95d7917815b84aa015cdf1b0ee0da
|
AceGUI-3.0/widgets/AceGUIWidget-Keybinding.lua
|
AceGUI-3.0/widgets/AceGUIWidget-Keybinding.lua
|
local AceGUI = LibStub("AceGUI-3.0")
--------------------------
-- Keybinding --
--------------------------
local WotLK = select(4, GetBuildInfo()) >= 30000
do
local Type = "Keybinding"
local Version = 9
local ControlBackdrop = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 3, bottom = 3 }
}
local function Control_OnEnter(this)
this.obj:Fire("OnEnter")
end
local function Control_OnLeave(this)
this.obj:Fire("OnLeave")
end
local function keybindingMsgFixWidth(this)
this:SetWidth(this.msg:GetWidth()+10)
this:SetScript("OnUpdate",nil)
end
local function Keybinding_OnClick(this, button)
if button == "LeftButton" or button == "RightButton" then
local self = this.obj
if self.waitingForKey then
this:EnableKeyboard(false)
self.msgframe:Hide()
this:UnlockHighlight()
self.waitingForKey = nil
else
this:EnableKeyboard(true)
self.msgframe:Show()
this:LockHighlight()
self.waitingForKey = true
end
end
AceGUI:ClearFocus()
end
local ignoreKeys = nil
local function Keybinding_OnKeyDown(this, key)
local self = this.obj
if self.waitingForKey then
local keyPressed = key
if keyPressed == "ESCAPE" then
keyPressed = ""
else
if not ignoreKeys then
ignoreKeys = {
["BUTTON1"] = true, ["BUTTON2"] = true,
["UNKNOWN"] = true,
["LSHIFT"] = true, ["LCTRL"] = true, ["LALT"] = true,
["RSHIFT"] = true, ["RCTRL"] = true, ["RALT"] = true,
}
end
if ignoreKeys[keyPressed] then return end
if IsShiftKeyDown() then
keyPressed = "SHIFT-"..keyPressed
end
if IsControlKeyDown() then
keyPressed = "CTRL-"..keyPressed
end
if IsAltKeyDown() then
keyPressed = "ALT-"..keyPressed
end
end
if not self.disabled then
self:Fire("OnKeyChanged",keyPressed)
self:SetKey(keyPressed)
end
this:EnableKeyboard(false)
self.msgframe:Hide()
this:UnlockHighlight()
self.waitingForKey = nil
end
end
local function Keybinding_OnMouseDown(this, button)
if button == "LeftButton" or button == "RightButton" then
return
elseif button == "MiddleButton" then
button = "BUTTON3"
elseif button == "Button4" then
button = "BUTTON4"
elseif button == "Button5" then
button = "BUTTON5"
end
Keybinding_OnKeyDown(this, button)
end
local function OnAcquire(self)
end
local function OnRelease(self)
self.frame:ClearAllPoints()
self.frame:Hide()
self.waitingForKey = nil
self.msgframe:Hide()
end
local function SetDisabled(self, disabled)
self.disabled = disabled
if disabled then
self.button:Disable()
self.label:SetTextColor(0.5,0.5,0.5)
else
self.button:Enable()
self.label:SetTextColor(1,1,1)
end
end
local function SetKey(self, key)
if (key or "") == "" then
self.button:SetText(NOT_BOUND)
if WotLK then
self.button:SetNormalFontObject("GameFontNormal")
else
self.button:SetTextFontObject("GameFontNormal")
end
else
self.button:SetText(key)
if WotLK then
self.button:SetNormalFontObject("GameFontHighlight")
else
self.button:SetTextFontObject("GameFontHighlight")
end
end
end
local function SetLabel(self, label)
self.label:SetText(label or "")
if (label or "") == "" then
self.alignoffset = nil
self:SetHeight(24)
else
self.alignoffset = 30
self:SetHeight(44)
end
end
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame",nil,UIParent)
local button = CreateFrame("Button","AceGUI-3.0 KeybindingButton"..num,frame,"UIPanelButtonTemplate2")
local self = {}
self.type = Type
self.num = num
local text = button:GetFontString()
text:SetPoint("LEFT",button,"LEFT",7,0)
text:SetPoint("RIGHT",button,"RIGHT",-7,0)
button:SetScript("OnClick",Keybinding_OnClick)
button:SetScript("OnKeyDown",Keybinding_OnKeyDown)
button:SetScript("OnEnter",Control_OnEnter)
button:SetScript("OnLeave",Control_OnLeave)
button:SetScript("OnMouseDown",Keybinding_OnMouseDown)
button:RegisterForClicks("AnyDown")
button:EnableMouse()
button:SetHeight(24)
button:SetWidth(200)
button:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT",0,0)
button:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0)
frame:SetWidth(200)
frame:SetHeight(44)
self.alignoffset = 30
self.button = button
local label = frame:CreateFontString(nil,"OVERLAY","GameFontHighlight")
label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0)
label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
label:SetJustifyH("CENTER")
label:SetHeight(18)
self.label = label
local msgframe = CreateFrame("Frame",nil,UIParent)
msgframe:SetHeight(30)
msgframe:SetBackdrop(ControlBackdrop)
msgframe:SetBackdropColor(0,0,0)
msgframe:SetFrameStrata("FULLSCREEN_DIALOG")
msgframe:SetFrameLevel(1000)
self.msgframe = msgframe
local msg = msgframe:CreateFontString(nil,"OVERLAY","GameFontNormal")
msg:SetText("Press a key to bind, ESC to clear the binding or click the button again to cancel")
msgframe.msg = msg
msg:SetPoint("TOPLEFT",msgframe,"TOPLEFT",5,-5)
msgframe:SetScript("OnUpdate", keybindingMsgFixWidth)
msgframe:SetPoint("BOTTOM",button,"TOP",0,0)
msgframe:Hide()
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.SetLabel = SetLabel
self.SetDisabled = SetDisabled
self.SetKey = SetKey
self.frame = frame
frame.obj = self
button.obj = self
AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
|
local AceGUI = LibStub("AceGUI-3.0")
--------------------------
-- Keybinding --
--------------------------
local WotLK = select(4, GetBuildInfo()) >= 30000
do
local Type = "Keybinding"
local Version = 10
local ControlBackdrop = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 3, bottom = 3 }
}
local function Control_OnEnter(this)
this.obj:Fire("OnEnter")
end
local function Control_OnLeave(this)
this.obj:Fire("OnLeave")
end
local function keybindingMsgFixWidth(this)
this:SetWidth(this.msg:GetWidth()+10)
this:SetScript("OnUpdate",nil)
end
local function Keybinding_OnClick(this, button)
if button == "LeftButton" or button == "RightButton" then
local self = this.obj
if self.waitingForKey then
this:EnableKeyboard(false)
self.msgframe:Hide()
this:UnlockHighlight()
self.waitingForKey = nil
else
this:EnableKeyboard(true)
self.msgframe:Show()
this:LockHighlight()
self.waitingForKey = true
end
end
AceGUI:ClearFocus()
end
local ignoreKeys = nil
local function Keybinding_OnKeyDown(this, key)
local self = this.obj
if self.waitingForKey then
local keyPressed = key
if keyPressed == "ESCAPE" then
keyPressed = ""
else
if not ignoreKeys then
ignoreKeys = {
["BUTTON1"] = true, ["BUTTON2"] = true,
["UNKNOWN"] = true,
["LSHIFT"] = true, ["LCTRL"] = true, ["LALT"] = true,
["RSHIFT"] = true, ["RCTRL"] = true, ["RALT"] = true,
}
end
if ignoreKeys[keyPressed] then return end
if IsShiftKeyDown() then
keyPressed = "SHIFT-"..keyPressed
end
if IsControlKeyDown() then
keyPressed = "CTRL-"..keyPressed
end
if IsAltKeyDown() then
keyPressed = "ALT-"..keyPressed
end
end
this:EnableKeyboard(false)
self.msgframe:Hide()
this:UnlockHighlight()
self.waitingForKey = nil
if not self.disabled then
self:SetKey(keyPressed)
self:Fire("OnKeyChanged",keyPressed)
end
end
end
local function Keybinding_OnMouseDown(this, button)
if button == "LeftButton" or button == "RightButton" then
return
elseif button == "MiddleButton" then
button = "BUTTON3"
elseif button == "Button4" then
button = "BUTTON4"
elseif button == "Button5" then
button = "BUTTON5"
end
Keybinding_OnKeyDown(this, button)
end
local function OnAcquire(self)
self:SetLabel("")
self:SetKey("")
end
local function OnRelease(self)
self.frame:ClearAllPoints()
self.frame:Hide()
self.waitingForKey = nil
self.msgframe:Hide()
end
local function SetDisabled(self, disabled)
self.disabled = disabled
if disabled then
self.button:Disable()
self.label:SetTextColor(0.5,0.5,0.5)
else
self.button:Enable()
self.label:SetTextColor(1,1,1)
end
end
local function SetKey(self, key)
if (key or "") == "" then
self.button:SetText(NOT_BOUND)
if WotLK then
self.button:SetNormalFontObject("GameFontNormal")
else
self.button:SetTextFontObject("GameFontNormal")
end
else
self.button:SetText(key)
if WotLK then
self.button:SetNormalFontObject("GameFontHighlight")
else
self.button:SetTextFontObject("GameFontHighlight")
end
end
end
local function SetLabel(self, label)
self.label:SetText(label or "")
if (label or "") == "" then
self.alignoffset = nil
self:SetHeight(24)
else
self.alignoffset = 30
self:SetHeight(44)
end
end
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame",nil,UIParent)
local button = CreateFrame("Button","AceGUI-3.0 KeybindingButton"..num,frame,"UIPanelButtonTemplate2")
local self = {}
self.type = Type
self.num = num
local text = button:GetFontString()
text:SetPoint("LEFT",button,"LEFT",7,0)
text:SetPoint("RIGHT",button,"RIGHT",-7,0)
button:SetScript("OnClick",Keybinding_OnClick)
button:SetScript("OnKeyDown",Keybinding_OnKeyDown)
button:SetScript("OnEnter",Control_OnEnter)
button:SetScript("OnLeave",Control_OnLeave)
button:SetScript("OnMouseDown",Keybinding_OnMouseDown)
button:RegisterForClicks("AnyDown")
button:EnableMouse()
button:SetHeight(24)
button:SetWidth(200)
button:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT",0,0)
button:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0)
frame:SetWidth(200)
frame:SetHeight(44)
self.alignoffset = 30
self.button = button
local label = frame:CreateFontString(nil,"OVERLAY","GameFontHighlight")
label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0)
label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
label:SetJustifyH("CENTER")
label:SetHeight(18)
self.label = label
local msgframe = CreateFrame("Frame",nil,UIParent)
msgframe:SetHeight(30)
msgframe:SetBackdrop(ControlBackdrop)
msgframe:SetBackdropColor(0,0,0)
msgframe:SetFrameStrata("FULLSCREEN_DIALOG")
msgframe:SetFrameLevel(1000)
self.msgframe = msgframe
local msg = msgframe:CreateFontString(nil,"OVERLAY","GameFontNormal")
msg:SetText("Press a key to bind, ESC to clear the binding or click the button again to cancel")
msgframe.msg = msg
msg:SetPoint("TOPLEFT",msgframe,"TOPLEFT",5,-5)
msgframe:SetScript("OnUpdate", keybindingMsgFixWidth)
msgframe:SetPoint("BOTTOM",button,"TOP",0,0)
msgframe:Hide()
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.SetLabel = SetLabel
self.SetDisabled = SetDisabled
self.SetKey = SetKey
self.frame = frame
frame.obj = self
button.obj = self
AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
|
AceGUI: Fix Keybinding widget text sometimes carrying over through a recycle.
|
AceGUI: Fix Keybinding widget text sometimes carrying over through a recycle.
git-svn-id: 925b317e615c7fb120546cae7ddec4d0d0259f64@696 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
d9e75bd46c40f81ce91c516adf5ccc59361122a6
|
skins.lua
|
skins.lua
|
--[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2013 Kenny Shields --
--]]------------------------------------------------
-- skins library
loveframes.skins = {}
-- available skins
loveframes.skins.available = {}
--[[---------------------------------------------------------
- func: Register(skin)
- desc: registers a skin
--]]---------------------------------------------------------
function loveframes.skins.Register(skin)
local name = skin.name
local author = skin.author
local version = skin.version
local base = skin.base
local newskin = false
if name == "" or not name then
loveframes.util.Error("Skin registration error: Invalid or missing name data.")
end
if author == "" or not author then
loveframes.util.Error("Skin registration error: Invalid or missing author data.")
end
if version == "" or not version then
loveframes.util.Error("Skin registration error: Invalid or missing version data.")
end
local namecheck = loveframes.skins.available[name]
if namecheck then
loveframes.util.Error("Skin registration error: A skin with the name '" ..name.. "' already exists.")
end
local dir = loveframes.config["DIRECTORY"] .. "/skins/" ..name
local dircheck = love.filesystem.isDirectory(dir)
if not dircheck then
loveframes.util.Error("Skin registration error: Could not find a directory for skin '" ..name.. "'.")
end
local imagedir = skin.imagedir or dir .. "/images"
local imagedircheck = love.filesystem.isDirectory(imagedir)
if not imagedircheck then
loveframes.util.Error("Skin registration error: Could not find an image directory for skin '" ..name.. "'.")
end
if base then
local basename = base
base = loveframes.skins.Get(base)
if not base then
loveframes.util.Error("Could not find base skin '" ..basename.. "' for skin '" ..name.. "'.")
end
newskin = loveframes.util.DeepCopy(base)
newskin.name = name
newskin.author = author
newskin.version = version
newskin.imagedir = imagedir
local skincontrols = skin.controls
local basecontrols = base.controls
if skincontrols and basecontrols then
for k, v in pairs(skincontrols) do
newskin.controls[k] = v
end
for k, v in pairs(skin) do
if type(v) == "function" then
newskin[k] = v
end
end
end
end
if newskin then
loveframes.skins.available[name] = newskin
else
loveframes.skins.available[name] = skin
end
loveframes.skins.available[name].dir = dir
loveframes.skins.available[name].images = {}
local indeximages = loveframes.config["INDEXSKINIMAGES"]
if indeximages then
local images = loveframes.util.GetDirectoryContents(imagedir)
for k, v in ipairs(images) do
local filename = v.name
local extension = v.extension
local fullpath = v.fullpath
local key = filename .. "." .. extension
loveframes.skins.available[name].images[key] = love.graphics.newImage(fullpath)
end
end
end
--[[---------------------------------------------------------
- func: GetAvailable()
- desc: gets all available skins
--]]---------------------------------------------------------
function loveframes.skins.GetAvailable()
local available = loveframes.skins.available
return available
end
--[[---------------------------------------------------------
- func: Get(name)
- desc: gets a skin by its name
--]]---------------------------------------------------------
function loveframes.skins.Get(name)
local available = loveframes.skins.available
local skin = available[name] or false
return skin
end
--[[---------------------------------------------------------
- func: SetControl(name, control, value)
- desc: changes the value of a control in the
specified skin
--]]---------------------------------------------------------
function loveframes.skins.SetControl(name, control, value)
local skin = loveframes.skins.Get(name)
if skin then
if skin.controls and skin.controls[control] then
skin.controls[control] = value
end
end
end
--[[---------------------------------------------------------
- func: SetImage(name, image, value)
- desc: changes the value of an image index in
the images table of the specified skin
--]]---------------------------------------------------------
function loveframes.skins.SetImage(name, image, value)
local skin = loveframes.skins.Get(name)
if skin then
if skin.images and skin.images[image] then
skin.images[image] = value
end
end
end
--[[---------------------------------------------------------
- func: SetImageDirectory(name, dir)
- desc: sets the image directory of a skin
--]]---------------------------------------------------------
function loveframes.skins.SetImageDirectory(name, dir)
local skin = loveframes.skins.Get(name)
if skin then
skin.imagedir = dir
end
end
--[[---------------------------------------------------------
- func: ReloadImages(name)
- desc: reloads a skin's images
--]]---------------------------------------------------------
function loveframes.skins.ReloadImages(name)
local skin = loveframes.skins.Get(name)
local indeximages = loveframes.config["INDEXSKINIMAGES"]
if skin and indeximages then
local basedir = loveframes.config["DIRECTORY"]
local imagedir = skin.imagedir or basedir .. "/skins/" ..name.. "/images"
local dircheck = love.filesystem.isDirectory(imagedir)
if dircheck then
local images = loveframes.util.GetDirectoryContents(imagedir)
for k, v in ipairs(images) do
local filename = v.name
local extension = v.extension
local fullpath = v.fullpath
loveframes.skins.available[name].images[filename .. "." .. extension] = love.graphics.newImage(fullpath)
end
end
end
end
|
--[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2013 Kenny Shields --
--]]------------------------------------------------
-- skins library
loveframes.skins = {}
-- available skins
loveframes.skins.available = {}
--[[---------------------------------------------------------
- func: Register(skin)
- desc: registers a skin
--]]---------------------------------------------------------
function loveframes.skins.Register(skin)
local name = skin.name
local author = skin.author
local version = skin.version
local base = skin.base
local newskin = false
if name == "" or not name then
loveframes.util.Error("Skin registration error: Invalid or missing name data.")
end
if author == "" or not author then
loveframes.util.Error("Skin registration error: Invalid or missing author data.")
end
if version == "" or not version then
loveframes.util.Error("Skin registration error: Invalid or missing version data.")
end
local namecheck = loveframes.skins.available[name]
if namecheck then
loveframes.util.Error("Skin registration error: A skin with the name '" ..name.. "' already exists.")
end
local dir = loveframes.config["DIRECTORY"] .. "/skins/" ..name
local dircheck = love.filesystem.isDirectory(dir)
if not dircheck then
loveframes.util.Error("Skin registration error: Could not find a directory for skin '" ..name.. "'.")
end
local imagedir = skin.imagedir or dir .. "/images"
local imagedircheck = love.filesystem.isDirectory(imagedir)
if not imagedircheck then
loveframes.util.Error("Skin registration error: Could not find an image directory for skin '" ..name.. "'.")
end
if base then
local basename = base
base = loveframes.skins.Get(base)
if not base then
loveframes.util.Error("Could not find base skin '" ..basename.. "' for skin '" ..name.. "'.")
end
newskin = loveframes.util.DeepCopy(base)
newskin.name = name
newskin.author = author
newskin.version = version
newskin.imagedir = imagedir
local skincontrols = skin.controls
local basecontrols = base.controls
if skincontrols and basecontrols then
for k, v in pairs(skincontrols) do
newskin.controls[k] = v
end
for k, v in pairs(skin) do
if type(v) == "function" then
newskin[k] = v
end
end
end
end
if newskin then
loveframes.skins.available[name] = newskin
else
loveframes.skins.available[name] = skin
end
loveframes.skins.available[name].dir = dir
loveframes.skins.available[name].images = {}
local indeximages = loveframes.config["INDEXSKINIMAGES"]
if indeximages then
local images = loveframes.util.GetDirectoryContents(imagedir)
for k, v in ipairs(images) do
local filename = v.name
local extension = v.extension
local fullpath = v.fullpath
local key = filename .. "." .. extension
if extension ~= "db" then
loveframes.skins.available[name].images[key] = love.graphics.newImage(fullpath)
end
end
end
end
--[[---------------------------------------------------------
- func: GetAvailable()
- desc: gets all available skins
--]]---------------------------------------------------------
function loveframes.skins.GetAvailable()
local available = loveframes.skins.available
return available
end
--[[---------------------------------------------------------
- func: Get(name)
- desc: gets a skin by its name
--]]---------------------------------------------------------
function loveframes.skins.Get(name)
local available = loveframes.skins.available
local skin = available[name] or false
return skin
end
--[[---------------------------------------------------------
- func: SetControl(name, control, value)
- desc: changes the value of a control in the
specified skin
--]]---------------------------------------------------------
function loveframes.skins.SetControl(name, control, value)
local skin = loveframes.skins.Get(name)
if skin then
if skin.controls and skin.controls[control] then
skin.controls[control] = value
end
end
end
--[[---------------------------------------------------------
- func: SetImage(name, image, value)
- desc: changes the value of an image index in
the images table of the specified skin
--]]---------------------------------------------------------
function loveframes.skins.SetImage(name, image, value)
local skin = loveframes.skins.Get(name)
if skin then
if skin.images and skin.images[image] then
skin.images[image] = value
end
end
end
--[[---------------------------------------------------------
- func: SetImageDirectory(name, dir)
- desc: sets the image directory of a skin
--]]---------------------------------------------------------
function loveframes.skins.SetImageDirectory(name, dir)
local skin = loveframes.skins.Get(name)
if skin then
skin.imagedir = dir
end
end
--[[---------------------------------------------------------
- func: ReloadImages(name)
- desc: reloads a skin's images
--]]---------------------------------------------------------
function loveframes.skins.ReloadImages(name)
local skin = loveframes.skins.Get(name)
local indeximages = loveframes.config["INDEXSKINIMAGES"]
if skin and indeximages then
local basedir = loveframes.config["DIRECTORY"]
local imagedir = skin.imagedir or basedir .. "/skins/" ..name.. "/images"
local dircheck = love.filesystem.isDirectory(imagedir)
if dircheck then
local images = loveframes.util.GetDirectoryContents(imagedir)
for k, v in ipairs(images) do
local filename = v.name
local extension = v.extension
local fullpath = v.fullpath
loveframes.skins.available[name].images[filename .. "." .. extension] = love.graphics.newImage(fullpath)
end
end
end
end
|
Fixed #94
|
Fixed #94
|
Lua
|
mit
|
SimLeek/the-Open-Source-Pony-Game
|
d7dd1d46de46f78648c676ccbfcea1986d33abd9
|
kong/plugins/azure-functions/handler.lua
|
kong/plugins/azure-functions/handler.lua
|
local BasePlugin = require "kong.plugins.base_plugin"
local constants = require "kong.constants"
local meta = require "kong.meta"
local http = require "resty.http"
local pairs = pairs
local server_header = meta._SERVER_TOKENS
local conf_cache = setmetatable({}, { __mode = "k" })
local function send(status, content, headers)
if kong.configuration.enabled_headers[constants.HEADERS.VIA] then
headers = kong.table.merge(headers) -- create a copy of headers
headers[constants.HEADERS.VIA] = server_header
end
return kong.response.exit(status, content, headers)
end
local azure = BasePlugin:extend()
azure.PRIORITY = 749
azure.VERSION = "0.1.1"
function azure:new()
azure.super.new(self, "azure-functions")
end
function azure:access(config)
azure.super.access(self)
-- prepare and store updated config in cache
local conf = conf_cache[config]
if not conf then
conf = {}
for k,v in pairs(config) do
conf[k] = v
end
conf.host = config.appname .. "." .. config.hostdomain
conf.port = config.https and 443 or 80
local f = (config.functionname or ""):match("^/*(.-)/*$") -- drop pre/postfix slashes
local p = (config.routeprefix or ""):match("^/*(.-)/*$") -- drop pre/postfix slashes
if p ~= "" then
p = "/" .. p
end
conf.path = p .. "/" .. f
conf_cache[config] = conf
end
config = conf
local client = http.new()
local request_method = kong.request.get_method()
local request_body = kong.request.get_raw_body()
local request_headers = kong.request.get_headers()
local request_args = kong.request.get_query()
client:set_timeout(config.timeout)
local ok, err = client:connect(config.host, config.port)
if not ok then
kong.log.err("could not connect to Azure service: ", err)
return kong.response.exit(500, { message = "An unexpected error ocurred" })
end
if config.https then
local ok2, err2 = client:ssl_handshake(false, config.host, config.https_verify)
if not ok2 then
kong.log.err("could not perform SSL handshake : ", err2)
return kong.response.exit(500, { message = "An unexpected error ocurred" })
end
end
local upstream_uri = ngx.var.upstream_uri
local path = conf.path
local end1 = path:sub(-1, -1)
local start2 = upstream_uri:sub(1, 1)
if end1 == "/" then
if start2 == "/" then
path = path .. upstream_uri:sub(2,-1)
else
path = path .. upstream_uri
end
else
if start2 == "/" then
path = path .. upstream_uri
else
if upstream_uri ~= "" then
path = path .. "/" .. upstream_uri
end
end
end
local res
res, err = client:request {
method = request_method,
path = path,
body = request_body,
query = request_args,
headers = {
["Content-Length"] = #(request_body or ""),
["Content-Type"] = request_headers["Content-Type"],
["x-functions-key"] = config.apikey,
["x-functions-clientid"] = config.clientid,
}
}
if not res then
kong.log.err(err)
return kong.response.exit(500, { message = "An unexpected error occurred" })
end
local response_headers = res.headers
local response_status = res.status
local response_content = res:read_body()
ok, err = client:set_keepalive(config.keepalive)
if not ok then
kong.log.err("could not keepalive connection: ", err)
end
return send(response_status, response_content, response_headers)
end
return azure
|
local BasePlugin = require "kong.plugins.base_plugin"
local constants = require "kong.constants"
local meta = require "kong.meta"
local http = require "resty.http"
local pairs = pairs
local server_header = meta._SERVER_TOKENS
local conf_cache = setmetatable({}, { __mode = "k" })
local function send(status, content, headers)
if kong.configuration.enabled_headers[constants.HEADERS.VIA] then
headers = kong.table.merge(headers) -- create a copy of headers
headers[constants.HEADERS.VIA] = server_header
end
return kong.response.exit(status, content, headers)
end
local azure = BasePlugin:extend()
azure.PRIORITY = 749
azure.VERSION = "0.1.1"
function azure:new()
azure.super.new(self, "azure-functions")
end
function azure:access(config)
azure.super.access(self)
local var = ngx.var
-- prepare and store updated config in cache
local conf = conf_cache[config]
if not conf then
conf = {}
for k,v in pairs(config) do
conf[k] = v
end
conf.host = config.appname .. "." .. config.hostdomain
conf.port = config.https and 443 or 80
local f = (config.functionname or ""):match("^/*(.-)/*$") -- drop pre/postfix slashes
local p = (config.routeprefix or ""):match("^/*(.-)/*$") -- drop pre/postfix slashes
if p ~= "" then
p = "/" .. p
end
conf.path = p .. "/" .. f
conf_cache[config] = conf
end
config = conf
local client = http.new()
local request_method = kong.request.get_method()
local request_body = kong.request.get_raw_body()
local request_headers = kong.request.get_headers()
local request_args = kong.request.get_query()
client:set_timeout(config.timeout)
local ok, err = client:connect(config.host, config.port)
if not ok then
kong.log.err("could not connect to Azure service: ", err)
return kong.response.exit(500, { message = "An unexpected error ocurred" })
end
if config.https then
local ok2, err2 = client:ssl_handshake(false, config.host, config.https_verify)
if not ok2 then
kong.log.err("could not perform SSL handshake : ", err2)
return kong.response.exit(500, { message = "An unexpected error ocurred" })
end
end
local upstream_uri = var.upstream_uri
local path = conf.path
local end1 = path:sub(-1, -1)
local start2 = upstream_uri:sub(1, 1)
if end1 == "/" then
if start2 == "/" then
path = path .. upstream_uri:sub(2,-1)
else
path = path .. upstream_uri
end
else
if start2 == "/" then
path = path .. upstream_uri
else
if upstream_uri ~= "" then
path = path .. "/" .. upstream_uri
end
end
end
local res
res, err = client:request {
method = request_method,
path = path,
body = request_body,
query = request_args,
headers = {
["Content-Length"] = #(request_body or ""),
["Content-Type"] = request_headers["Content-Type"],
["x-functions-key"] = config.apikey,
["x-functions-clientid"] = config.clientid,
}
}
if not res then
kong.log.err(err)
return kong.response.exit(500, { message = "An unexpected error occurred" })
end
local response_headers = res.headers
local response_status = res.status
local response_content = res:read_body()
if var.http2 then
response_headers["Connection"] = nil
response_headers["Keep-Alive"] = nil
response_headers["Proxy-Connection"] = nil
response_headers["Upgrade"] = nil
response_headers["Transfer-Encoding"] = nil
end
ok, err = client:set_keepalive(config.keepalive)
if not ok then
kong.log.err("could not keepalive connection: ", err)
end
return send(response_status, response_content, response_headers)
end
return azure
|
fix(azure-functions) strip headers that are disallowed by HTTP/2
|
fix(azure-functions) strip headers that are disallowed by HTTP/2
Per https://tools.ietf.org/html/rfc7540#section-8.1.2.2 intermediaries
that proxy HTTP/1.1 responses to HTTP/2 clients should strip certain
headers that do not serve any purpose in HTTP/2. Not stripping these
headers results in a protocol violation for RFC-compliant clients.
See a similar fix for the aws-lambda plugin here:
https://github.com/Kong/kong/commit/f2ee98e2d50d0c70caed4cf19a7a5d48057b9c4f
From #5
Signed-off-by: Thibault Charbonnier <[email protected]>
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
aeea00bd4da718681aa7c3af1f8989d6065dbfff
|
Examples/firefox-debian-sandbox.cfg.lua
|
Examples/firefox-debian-sandbox.cfg.lua
|
-- example config for firefox sandbox, which is created on top of external debian chroot, prepared by debian-setup.cfg.lua
-- xpra x11-forwarding software (must be installed on host, v2.0 and up) may be used to isolate sanbox from host x11 service.
-- opengl acceleration untested and may not work (especially with xpra mode or when using proprietary video drivers that install it's own libgl).
-- this config is based on example.cfg.lua, most comments removed.
tunables.chrootdir=loader.path.combine(loader.workdir,"debian_chroot")
dofile(loader.path.combine(loader.workdir,"debian-version-probe.lua.in"))
tunables.datadir=loader.path.combine(loader.workdir,"userdata-firefox")
tunables.etchost_path=loader.path.combine(tunables.chrootdir,"etc")
tunables.features.dbus_search_prefix=tunables.chrootdir
tunables.features.xpra_search_prefix=tunables.chrootdir
tunables.features.gvfs_fix_search_prefix=tunables.chrootdir
tunables.features.pulse_env_alsa_config="auto"
tunables.features.x11util_build=os_id.."-"..os_version.."-"..os_arch
defaults.recalculate()
sandbox={
features={
"dbus",
"gvfs_fix",
"pulse",
"x11host", -- less secure, try this if you do not have xpra software
--"xpra", -- more secure, you must install xpra software suite with server and client functionality.
"envfix",
},
setup={
executor_build=os_id.."-"..os_version.."-"..os_arch,
commands={
defaults.commands.resolvconf,
defaults.commands.machineid_static,
defaults.commands.passwd,
defaults.commands.home,
defaults.commands.home_gui_config,
defaults.commands.var_cache,
defaults.commands.var_tmp,
},
env_whitelist={
"LANG",
"LC_ALL",
},
env_set={
{"PATH","/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"},
defaults.env.set_xdg_runtime,
defaults.env.set_home,
},
mounts={
defaults.mounts.system_group, -- includes: proc, dev, empty /run dir, empty /var dir, empty /tmp
defaults.mounts.xdg_runtime_dir,
defaults.mounts.home_mount,
defaults.mounts.var_cache_mount,
defaults.mounts.var_tmp_mount,
defaults.mounts.var_lib_mount,
defaults.mounts.usr_ro_mount,
defaults.mounts.host_etc_mount,
defaults.mounts.passwd_mount,
defaults.mounts.machineid_mount,
defaults.mounts.resolvconf_mount,
--defaults.mounts.devsnd_mount, -- for direct alsa support (alsa-pulse may work without it).
--defaults.mounts.devdri_mount, -- may be needed when using x11host for opengl acceleration
--defaults.mounts.sys_mount, -- may be needed when using x11host for opengl acceleration
--defaults.mounts.devinput_mount, -- joystics
--defaults.mounts.devshm_mount,
},
},
bwrap={
defaults.bwrap.unshare_user,
-- defaults.bwrap.unshare_ipc,
defaults.bwrap.unshare_pid,
-- defaults.bwrap.unshare_net,
defaults.bwrap.unshare_uts,
-- defaults.bwrap.unshare_cgroup,
defaults.bwrap.uid,
defaults.bwrap.gid,
}
}
-- add remaining mounts, depending on detected debian version
add_debian_mounts()
shell={
exec="/bin/bash",
args={"-l"},
path="/",
env_set={
{"TERM",os.getenv("TERM")},
},
term_signal=defaults.signals.SIGHUP,
attach=true,
pty=true,
desktop={
name = "Shell for debian-firefox sandbox",
comment = "shell for sandbox uid "..config.sandbox_uid,
icon = "terminal",
terminal = true,
startupnotify = false,
},
}
firefox_log={
exec="/usr/bin/firefox",
path="/home/sandboxer",
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true, -- for now it is needed for logging to work
log_stderr=loader.path.combine(loader.workdir,"firefox_dbg.err.log"),
log_stdout=loader.path.combine(loader.workdir,"firefox_dbg.out.log"),
}
firefox={
exec="/usr/bin/firefox",
path="/home/sandboxer",
args=loader.args,
term_signal=defaults.signals.SIGTERM,
attach=false,
pty=false,
desktop={
name = "Firefox (in sandbox)",
comment = "Firefox browser, sandbox uid "..config.sandbox_uid,
icon = "firefox",
mimetype = "x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ftp;",
field_code="%u",
terminal = false,
startupnotify = false,
categories="Network;WebBrowser;GTK;"
},
}
firefox_home_log={
exec="/home/sandboxer/firefox/firefox",
path="/home/sandboxer",
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true, -- for now it is needed for logging to work
log_stderr=loader.path.combine(loader.workdir,"firefox_dbg.err.log"),
log_stdout=loader.path.combine(loader.workdir,"firefox_dbg.out.log"),
}
firefox_home={
exec="/home/sandboxer/firefox/firefox",
path="/home/sandboxer",
args=loader.args,
term_signal=defaults.signals.SIGTERM,
attach=false,
pty=false,
desktop={
name = "Firefox (in sandbox)",
comment = "Firefox browser, sandbox uid "..config.sandbox_uid,
icon = loader.path.combine(tunables.datadir,"home","sandboxer","firefox","browser","icons","mozicon128.png"),
mimetype = "x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ftp;",
field_code="%u",
terminal = false,
startupnotify = false,
categories="Network;WebBrowser;GTK;"
},
}
|
-- example config for firefox sandbox, which is created on top of external debian chroot, prepared by debian-setup.cfg.lua
-- using debian-sandbox.cfg.lua config file as base
-- xpra x11-forwarding software (must be installed on host, v2.0 and up) may be used to isolate sanbox from host x11 service.
-- opengl acceleration untested and may not work (especially with xpra mode or when using proprietary video drivers that install it's own libgl).
-- redefine defaults.recalculate function, that will be called by base config
defaults.recalculate_orig=defaults.recalculate
function defaults.recalculate()
-- redefine some parameters
tunables.datadir=loader.path.combine(loader.workdir,"userdata-firefox")
tunables.features.pulse_env_alsa_config="auto"
defaults.recalculate_orig()
defaults.mounts.resolvconf_mount=defaults.mounts.direct_resolvconf_mount
end
defaults.recalculate()
-- load base config
dofile(loader.path.combine(loader.workdir,"debian-sandbox.cfg.lua"))
-- remove some mounts
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devsnd_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devdri_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devinput_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sys_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devshm_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sbin_ro_mount)
-- modify PATH env
table.insert(sandbox.setup.env_set,{"PATH","/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"})
firefox_log={
exec="/usr/bin/firefox",
path="/home/sandboxer",
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true, -- for now it is needed for logging to work
log_stderr=loader.path.combine(loader.workdir,"firefox_dbg.err.log"),
log_stdout=loader.path.combine(loader.workdir,"firefox_dbg.out.log"),
}
firefox={
exec="/usr/bin/firefox",
path="/home/sandboxer",
args=loader.args,
term_signal=defaults.signals.SIGTERM,
attach=false,
pty=false,
desktop={
name = "Firefox (in sandbox)",
comment = "Firefox browser, sandbox uid "..config.sandbox_uid,
icon = "firefox",
mimetype = "x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ftp;",
field_code="%u",
terminal = false,
startupnotify = false,
categories="Network;WebBrowser;GTK;"
},
}
firefox_home_log={
exec="/home/sandboxer/firefox/firefox",
path="/home/sandboxer",
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true, -- for now it is needed for logging to work
log_stderr=loader.path.combine(loader.workdir,"firefox_dbg.err.log"),
log_stdout=loader.path.combine(loader.workdir,"firefox_dbg.out.log"),
}
firefox_home={
exec="/home/sandboxer/firefox/firefox",
path="/home/sandboxer",
args=loader.args,
term_signal=defaults.signals.SIGTERM,
attach=false,
pty=false,
desktop={
name = "Firefox (in sandbox)",
comment = "Firefox browser, sandbox uid "..config.sandbox_uid,
icon = loader.path.combine(tunables.datadir,"home","sandboxer","firefox","browser","icons","mozicon128.png"),
mimetype = "x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ftp;",
field_code="%u",
terminal = false,
startupnotify = false,
categories="Network;WebBrowser;GTK;"
},
}
|
fixup! Examples: rework and simplify firefox-debian-sandbox.cfg.lua
|
fixup! Examples: rework and simplify firefox-debian-sandbox.cfg.lua
|
Lua
|
mit
|
DarkCaster/Sandboxer,DarkCaster/Sandboxer
|
15d012b84b6de4d43796d9a45da54a133dab3ca2
|
xmake.lua
|
xmake.lua
|
set_xmakever("2.5.4")
-- project
set_project("hikyuu")
add_rules("mode.debug", "mode.release")
if not is_plat("windows") then
add_rules("mode.coverage", "mode.asan", "mode.msan", "mode.tsan", "mode.lsan")
end
-- version
set_version("1.2.4", {build="%Y%m%d%H%M"})
set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--if is_mode("debug") then
-- set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--else
-- set_configvar("LOG_ACTIVE_LEVEL", 2) -- 激活的日志级别
--end
set_configvar("USE_SPDLOG_LOGGER", 1) -- 是否使用spdlog作为日志输出
set_configvar("USE_SPDLOG_ASYNC_LOGGER", 0) -- 使用异步的spdlog
set_configvar("CHECK_ACCESS_BOUND", 1)
if is_plat("macosx") then
set_configvar("SUPPORT_SERIALIZATION", 0)
else
set_configvar("SUPPORT_SERIALIZATION", is_mode("release") and 1 or 0)
end
set_configvar("SUPPORT_TEXT_ARCHIVE", 0)
set_configvar("SUPPORT_XML_ARCHIVE", 1)
set_configvar("SUPPORT_BINARY_ARCHIVE", 1)
set_configvar("HKU_DISABLE_ASSERT", 0)
-- set warning all as error
if is_plat("windows") then
set_warnings("all", "error")
else
set_warnings("all")
end
-- set language: C99, c++ standard
set_languages("cxx17", "C99")
add_plugindirs("./xmake_plugins")
local hdf5_version = "1.10.4"
local mysql_version = "8.0.21"
if is_plat("windows") then
add_repositories("project-repo hikyuu_extern_libs")
if is_mode("release") then
add_requires("hdf5 " .. hdf5_version)
else
add_requires("hdf5_D " .. hdf5_version)
end
add_requires("mysql " .. mysql_version)
end
add_requires("fmt 8.1.1", {system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("spdlog", {system=false, configs = {header_only = true, fmt_external=true, vs_runtime = "MD"}})
add_requireconfs("spdlog.fmt", {override = true, version = "8.1.1", system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("flatbuffers", {system=false, configs = {vs_runtime="MD"}})
add_requires("nng", {system=false, configs = {vs_runtime="MD", cxflags="-fPIC"}})
add_requires("nlohmann_json", {system=false})
add_requires("cpp-httplib", {system=false})
add_requires("zlib", {system=false})
if is_plat("linux") and linuxos.name() == "ubuntu" then
add_requires("apt::libhdf5-dev", "apt::libmysqlclient-dev", "apt::libsqlite3-dev")
elseif is_plat("macosx") then
add_requires("brew::hdf5")
else
add_requires("sqlite3", {configs = {shared=true, vs_runtime="MD", cxflags="-fPIC"}})
end
add_defines("SPDLOG_DISABLE_DEFAULT_LOGGER") -- 禁用 spdlog 默认 logger
set_objectdir("$(buildir)/$(mode)/$(plat)/$(arch)/.objs")
set_targetdir("$(buildir)/$(mode)/$(plat)/$(arch)/lib")
add_includedirs("$(env BOOST_ROOT)")
add_linkdirs("$(env BOOST_LIB)")
-- modifed to use boost static library, except boost.python, serialization
--add_defines("BOOST_ALL_DYN_LINK")
add_defines("BOOST_SERIALIZATION_DYN_LINK")
if is_host("linux") then
if is_arch("x86_64") then
add_linkdirs("/usr/lib64")
if os.exists("/usr/lib/x86_64-linux-gnu") then
add_linkdirs("/usr/lib/x86_64-linux-gnu")
end
end
end
-- is release now
if is_mode("release") then
if is_plat("windows") then
--Unix-like systems hidden symbols will cause the link dynamic libraries to failed!
set_symbols("hidden")
end
end
-- for the windows platform (msvc)
if is_plat("windows") then
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
add_cxflags("-EHsc", "/Zc:__cplusplus", "/utf-8")
add_cxflags("-wd4819") --template dll export warning
add_defines("WIN32_LEAN_AND_MEAN")
if is_mode("release") then
add_cxflags("-MD")
elseif is_mode("debug") then
add_cxflags("-Gs", "-RTC1", "/bigobj")
add_cxflags("-MDd")
end
end
if not is_plat("windows") then
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_cxflags("-ftemplate-depth=1023", "-pthread")
add_shflags("-pthread")
add_ldflags("-pthread")
end
--add_vectorexts("sse", "sse2", "sse3", "ssse3", "mmx", "avx")
add_subdirs("./hikyuu_cpp/hikyuu")
add_subdirs("./hikyuu_pywrap")
add_subdirs("./hikyuu_cpp/unit_test")
add_subdirs("./hikyuu_cpp/demo")
add_subdirs("./hikyuu_cpp/hikyuu_server")
before_install("scripts.before_install")
on_install("scripts.on_install")
before_run("scripts.before_run")
|
set_xmakever("2.5.4")
-- project
set_project("hikyuu")
add_rules("mode.debug", "mode.release")
if not is_plat("windows") then
add_rules("mode.coverage", "mode.asan", "mode.msan", "mode.tsan", "mode.lsan")
end
-- version
set_version("1.2.4", {build="%Y%m%d%H%M"})
set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--if is_mode("debug") then
-- set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--else
-- set_configvar("LOG_ACTIVE_LEVEL", 2) -- 激活的日志级别
--end
set_configvar("USE_SPDLOG_LOGGER", 1) -- 是否使用spdlog作为日志输出
set_configvar("USE_SPDLOG_ASYNC_LOGGER", 0) -- 使用异步的spdlog
set_configvar("CHECK_ACCESS_BOUND", 1)
if is_plat("macosx") then
set_configvar("SUPPORT_SERIALIZATION", 0)
else
set_configvar("SUPPORT_SERIALIZATION", is_mode("release") and 1 or 0)
end
set_configvar("SUPPORT_TEXT_ARCHIVE", 0)
set_configvar("SUPPORT_XML_ARCHIVE", 1)
set_configvar("SUPPORT_BINARY_ARCHIVE", 1)
set_configvar("HKU_DISABLE_ASSERT", 0)
-- set warning all as error
if is_plat("windows") then
set_warnings("all", "error")
else
set_warnings("all")
end
-- set language: C99, c++ standard
set_languages("cxx17", "C99")
add_plugindirs("./xmake_plugins")
local hdf5_version = "1.10.4"
local mysql_version = "8.0.21"
if is_plat("windows") then
add_repositories("project-repo hikyuu_extern_libs")
if is_mode("release") then
add_requires("hdf5 " .. hdf5_version)
else
add_requires("hdf5_D " .. hdf5_version)
end
add_requires("mysql " .. mysql_version)
end
add_requires("fmt 8.1.1", {system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("spdlog", {system=false, configs = {header_only = true, fmt_external=true, vs_runtime = "MD"}})
add_requires("flatbuffers", {system=false, configs = {vs_runtime="MD"}})
add_requires("nng", {system=false, configs = {vs_runtime="MD", cxflags="-fPIC"}})
add_requires("nlohmann_json", {system=false})
add_requires("cpp-httplib", {system=false})
add_requires("zlib", {system=false})
if is_plat("linux") and linuxos.name() == "ubuntu" then
add_requires("apt::libhdf5-dev", "apt::libmysqlclient-dev", "apt::libsqlite3-dev")
elseif is_plat("macosx") then
add_requires("brew::hdf5")
else
add_requires("sqlite3", {configs = {shared=true, vs_runtime="MD", cxflags="-fPIC"}})
end
add_defines("SPDLOG_DISABLE_DEFAULT_LOGGER") -- 禁用 spdlog 默认 logger
set_objectdir("$(buildir)/$(mode)/$(plat)/$(arch)/.objs")
set_targetdir("$(buildir)/$(mode)/$(plat)/$(arch)/lib")
add_includedirs("$(env BOOST_ROOT)")
add_linkdirs("$(env BOOST_LIB)")
-- modifed to use boost static library, except boost.python, serialization
--add_defines("BOOST_ALL_DYN_LINK")
add_defines("BOOST_SERIALIZATION_DYN_LINK")
if is_host("linux") then
if is_arch("x86_64") then
add_linkdirs("/usr/lib64")
if os.exists("/usr/lib/x86_64-linux-gnu") then
add_linkdirs("/usr/lib/x86_64-linux-gnu")
end
end
end
-- is release now
if is_mode("release") then
if is_plat("windows") then
--Unix-like systems hidden symbols will cause the link dynamic libraries to failed!
set_symbols("hidden")
end
end
-- for the windows platform (msvc)
if is_plat("windows") then
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
add_cxflags("-EHsc", "/Zc:__cplusplus", "/utf-8")
add_cxflags("-wd4819") --template dll export warning
add_defines("WIN32_LEAN_AND_MEAN")
if is_mode("release") then
add_cxflags("-MD")
elseif is_mode("debug") then
add_cxflags("-Gs", "-RTC1", "/bigobj")
add_cxflags("-MDd")
end
end
if not is_plat("windows") then
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_cxflags("-ftemplate-depth=1023", "-pthread")
add_shflags("-pthread")
add_ldflags("-pthread")
end
--add_vectorexts("sse", "sse2", "sse3", "ssse3", "mmx", "avx")
add_subdirs("./hikyuu_cpp/hikyuu")
add_subdirs("./hikyuu_pywrap")
add_subdirs("./hikyuu_cpp/unit_test")
add_subdirs("./hikyuu_cpp/demo")
add_subdirs("./hikyuu_cpp/hikyuu_server")
before_install("scripts.before_install")
on_install("scripts.on_install")
before_run("scripts.before_run")
|
fixed fmt
|
fixed fmt
|
Lua
|
mit
|
fasiondog/hikyuu
|
cd6961779781525f58f9797b19db2df796031ec2
|
item/traps.lua
|
item/traps.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
--Function: Generic trap script
--Last Update: 01/04/2006
--Update by: Nitram
-- UPDATE common SET com_script='item.traps' WHERE com_itemid IN (377,378,379,380,381);
require("base.common")
module("item.traps", package.seeall)
function UseItem(User, SourceItem)
if ((User:increaseAttrib("dexterity",0) + 0.5*User:increaseAttrib("perception",0) + math.random(1,30)) >= 30) then
base.common.InformNLS( User,"Du entschrfst die Falle.","You disarm the trap." );
world:swap(SourceItem,375,333);
else
base.common.InformNLS( User,"Du lst die Falle aus!","You set off the trap!" );
world:gfx(14,SourceItem.pos);
User:increaseAttrib("hitpoints", -5000);
world:swap(SourceItem,376,333);
end
User.movepoints=User.movepoints-10;
end
function CharacterOnField( User )
local SetOff=false;
if (User:increaseAttrib("hitpoints",0)>0) then --ghosts do not set off traps
repeat
local SourceItem = world:getItemOnField( User.pos );
if (User:increaseAttrib("hitpoints",0)>0) then
if( SourceItem.id >= 377 ) and (SourceItem.id <= 381) then
base.common.InformNLS( User,"Du lst eine Falle aus!","You set off a trap!" );
world:gfx(14,User.pos);
User:increaseAttrib("hitpoints", -4999);
world:swap(SourceItem,376,333);
SetOff=true;
else
world:erase(SourceItem,1);
end
end
until ( SetOff == true )
User.movepoints=User.movepoints-10;
end
end
function LookAtItem(User,Item)
if (User:distanceMetricToPosition(Item.pos)<2 and User:increaseAttrib("perception",0)>15) then
if (User:getPlayerLanguage()==0) then
world:itemInform(User,Item,"Falle")
else
world:itemInform(User,Item,"trap")
end
end
end
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
--Function: Generic trap script
--Last Update: 01/04/2006
--Update by: Nitram
-- UPDATE common SET com_script='item.traps' WHERE com_itemid IN (377,378,379,380,381);
require("base.common")
module("item.traps", package.seeall)
function UseItem(User, SourceItem)
if ((User:increaseAttrib("dexterity",0) + 0.5*User:increaseAttrib("perception",0) + math.random(1,30)) >= 30) then
base.common.InformNLS( User,"Du entschrfst die Falle.","You disarm the trap." );
world:swap(SourceItem,375,333);
else
base.common.InformNLS( User,"Du lst die Falle aus!","You set off the trap!" );
world:gfx(14,SourceItem.pos);
User:increaseAttrib("hitpoints", -5000);
world:swap(SourceItem,376,333);
end
User.movepoints=User.movepoints-10;
end
function CharacterOnField( User )
local SetOff=false;
if (User:increaseAttrib("hitpoints",0)>0) then --ghosts do not set off traps
repeat
local SourceItem = world:getItemOnField( User.pos );
if (User:increaseAttrib("hitpoints",0)>0) then
if( SourceItem.id >= 377 ) and (SourceItem.id <= 381) then
base.common.InformNLS( User,"Du lst eine Falle aus!","You set off a trap!" );
world:gfx(14,User.pos);
User:increaseAttrib("hitpoints", -4999);
world:swap(SourceItem,376,333);
SetOff=true;
else
world:erase(SourceItem,1);
end
end
until ( SetOff == true )
User.movepoints=User.movepoints-10;
end
end
function LookAtItem(User,Item)
base.lookat.SetSpecialName(Item, "Falle", "trap");
if (User:distanceMetricToPosition(Item.pos)<2 and User:increaseAttrib("perception",0)>15) then
world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE));
end
end
|
fix an old style lookat() to work as intended
|
fix an old style lookat() to work as intended
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content
|
c2bbdfa778a2c8cc3a8fed69028b6cd66149cf0b
|
lua/include/namespaces.lua
|
lua/include/namespaces.lua
|
local mod = {}
local ffi = require "ffi"
local serpent = require "Serpent"
local stp = require "StackTracePlus"
local lock = require "lock"
ffi.cdef [[
struct namespace { };
struct namespace* create_or_get_namespace(const char* name);
void namespace_store(struct namespace* ns, const char* key, const char* value);
void namespace_delete(struct namespace* ns, const char* key);
const char* namespace_retrieve(struct namespace* ns, const char* key);
void namespace_iterate(struct namespace* ns, void (*func)(const char* key, const char* val));
struct lock* namespace_get_lock(struct namespace* ns);
]]
local C = ffi.C
local namespace = {}
namespace.__index = namespace
local function getNameFromTrace()
return debug.traceback():match("\n.-\n.-\n(.-)\n")
end
--- Get a namespace by its name creating it if necessary.
-- @param name the name, defaults to an auto-generated string consisting of the caller's filename and line number
function mod:get(name)
name = name or getNameFromTrace()
return C.create_or_get_namespace(name)
end
--- Retrieve a *copy* of a value in the namespace.
-- @param key the key, must be a string
function namespace:__index(key)
if type(key) ~= "string" then
error("table index must be a string")
end
if key == "forEach" then
return namespace.forEach
elseif key == "lock" then
return C.namespace_get_lock(self)
end
local val = C.namespace_retrieve(self, key)
return val ~= nil and loadstring(ffi.string(val))() or nil
end
--- Store a value in the namespace.
-- @param key the key, must be a string
-- @param val the value to store, will be serialized
function namespace:__newindex(key, val)
if type(key) ~= "string" then
error("table index must be a string")
end
if key == "forEach" or key == "lock" then
error(key .. " is reserved", 2)
end
if val == nil then
C.namespace_delete(self, key)
else
C.namespace_store(self, key, serpent.dump(val))
end
end
--- Iterate over all keys/values in a namespace
-- Note: namespaces do not offer a 'normal' iterator (e.g. through a __pair metamethod) due to locking.
-- Iterating over a table requires a lock on the whole table; ensuring that the lock is released is
-- easier with a forEach method than with a regular iterator.
-- @param func function to call, receives (key, value) as arguments
function namespace:forEach(func)
local caughtError
local cb = ffi.cast("void (*)(const char* key, const char* val)", function(key, val)
if caughtError then
return
end
-- avoid throwing an error across the C++ frame unnecessarily
-- not sure if this would work properly when compiled with clang instead of gcc
local ok, err = xpcall(func, function(err)
return stp.stacktrace(err)
end, ffi.string(key), loadstring(ffi.string(val))())
if not ok then
caughtError = err
end
end)
C.namespace_iterate(self, cb)
cb:free()
if caughtError then
-- this is gonna be an ugly error message, but at least we get the full call stack
error("error while calling callback, inner error: " .. caughtError)
end
end
ffi.metatype("struct namespace", namespace)
return mod
|
local mod = {}
local ffi = require "ffi"
local serpent = require "Serpent"
local stp = require "StackTracePlus"
local lock = require "lock"
ffi.cdef [[
struct namespace { };
struct namespace* create_or_get_namespace(const char* name);
void namespace_store(struct namespace* ns, const char* key, const char* value);
void namespace_delete(struct namespace* ns, const char* key);
const char* namespace_retrieve(struct namespace* ns, const char* key);
void namespace_iterate(struct namespace* ns, void (*func)(const char* key, const char* val));
struct lock* namespace_get_lock(struct namespace* ns);
]]
local cbType = ffi.typeof("void (*)(const char* key, const char* val)")
local C = ffi.C
local namespace = {}
namespace.__index = namespace
local function getNameFromTrace()
return debug.traceback():match("\n.-\n.-\n(.-)\n")
end
--- Get a namespace by its name creating it if necessary.
-- @param name the name, defaults to an auto-generated string consisting of the caller's filename and line number
function mod:get(name)
name = name or getNameFromTrace()
return C.create_or_get_namespace(name)
end
--- Retrieve a *copy* of a value in the namespace.
-- @param key the key, must be a string
function namespace:__index(key)
if type(key) ~= "string" then
error("table index must be a string")
end
if key == "forEach" then
return namespace.forEach
elseif key == "lock" then
return C.namespace_get_lock(self)
end
local val = C.namespace_retrieve(self, key)
return val ~= nil and loadstring(ffi.string(val))() or nil
end
--- Store a value in the namespace.
-- @param key the key, must be a string
-- @param val the value to store, will be serialized
function namespace:__newindex(key, val)
if type(key) ~= "string" then
error("table index must be a string")
end
if key == "forEach" or key == "lock" then
error(key .. " is reserved", 2)
end
if val == nil then
C.namespace_delete(self, key)
else
C.namespace_store(self, key, serpent.dump(val))
end
end
--- Iterate over all keys/values in a namespace
-- Note: namespaces do not offer a 'normal' iterator (e.g. through a __pair metamethod) due to locking.
-- Iterating over a table requires a lock on the whole table; ensuring that the lock is released is
-- easier with a forEach method than with a regular iterator.
-- @param func function to call, receives (key, value) as arguments
function namespace:forEach(func)
local caughtError
local cb = ffi.cast(cbType, function(key, val)
if caughtError then
return
end
-- avoid throwing an error across the C++ frame unnecessarily
-- not sure if this would work properly when compiled with clang instead of gcc
local ok, err = xpcall(func, function(err)
return stp.stacktrace(err)
end, ffi.string(key), loadstring(ffi.string(val))())
if not ok then
caughtError = err
end
end)
C.namespace_iterate(self, cb)
cb:free()
if caughtError then
-- this is gonna be an ugly error message, but at least we get the full call stack
error("error while calling callback, inner error: " .. caughtError)
end
end
ffi.metatype("struct namespace", namespace)
return mod
|
namespaces: fix yet another memory leak
|
namespaces: fix yet another memory leak
note: cb:set() is not appropiate here (needs to be reentrant)
|
Lua
|
mit
|
scholzd/MoonGen,bmichalo/MoonGen,scholzd/MoonGen,schoenb/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,schoenb/MoonGen,emmericp/MoonGen,atheurer/MoonGen,duk3luk3/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,atheurer/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,slyon/MoonGen,kidaa/MoonGen,werpat/MoonGen,NetronomeMoongen/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,slyon/MoonGen,slyon/MoonGen,bmichalo/MoonGen,werpat/MoonGen,NetronomeMoongen/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,duk3luk3/MoonGen,slyon/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,kidaa/MoonGen,werpat/MoonGen,bmichalo/MoonGen,bmichalo/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,wenhuizhang/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen
|
2754f0e04afc5de4c31ddf15b5d616a480ca9fcb
|
xmake/modules/private/action/build/object.lua
|
xmake/modules/private/action/build/object.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file object.lua
--
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.tool.compiler")
import("core.project.depend")
import("private.tools.ccache")
import("private.async.runjobs")
-- do build file
function _do_build_file(target, sourcefile, opt)
-- get build info
local objectfile = opt.objectfile
local dependfile = opt.dependfile
local sourcekind = opt.sourcekind
local progress = opt.progress
-- load compiler
local compinst = compiler.load(sourcekind, {target = target})
-- get compile flags
local compflags = compinst:compflags({target = target, sourcefile = sourcefile, configs = opt.configs})
-- load dependent info
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
local depvalues = {compinst:program(), compflags}
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectfile), values = depvalues}) then
return
end
-- is verbose?
local verbose = option.get("verbose")
-- exists ccache?
local exists_ccache = ccache.exists()
-- trace progress info
if not opt.quiet then
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
if verbose then
cprint(progress_prefix .. "${dim color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile)
else
cprint(progress_prefix .. "${color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile)
end
end
-- trace verbose info
if verbose then
print(compinst:compcmd(sourcefile, objectfile, {compflags = compflags}))
end
-- compile it
dependinfo.files = {}
if not option.get("dry-run") then
assert(compinst:compile(sourcefile, objectfile, {dependinfo = dependinfo, compflags = compflags}))
end
-- update files and values to the dependent file
dependinfo.values = depvalues
table.join2(dependinfo.files, sourcefile, target:pcoutputfile("cxx") or {}, target:pcoutputfile("c"))
depend.save(dependinfo, dependfile)
end
-- build object
function _build_object(target, sourcefile, opt)
local script = target:script("build_file", _do_build_file)
if script then
script(target, sourcefile, opt)
end
end
-- build the source files
function build(target, sourcebatch, opt)
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
opt.objectfile = sourcebatch.objectfiles[i]
opt.dependfile = sourcebatch.dependfiles[i]
opt.sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
_build_object(target, sourcefile, opt)
end
end
-- add batch jobs to build the source files
function main(target, batchjobs, sourcebatch, opt)
local rootjob = opt.rootjob
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
opt.objectfile = sourcebatch.objectfiles[i]
opt.dependfile = sourcebatch.dependfiles[i]
opt.sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
batchjobs:addjob(sourcefile, function (index, total)
opt.progress = (index * 100) / total
_build_object(target, sourcefile, opt)
end, rootjob)
end
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file object.lua
--
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.tool.compiler")
import("core.project.depend")
import("private.tools.ccache")
import("private.async.runjobs")
-- do build file
function _do_build_file(target, sourcefile, opt)
-- get build info
local objectfile = opt.objectfile
local dependfile = opt.dependfile
local sourcekind = opt.sourcekind
local progress = opt.progress
-- load compiler
local compinst = compiler.load(sourcekind, {target = target})
-- get compile flags
local compflags = compinst:compflags({target = target, sourcefile = sourcefile, configs = opt.configs})
-- load dependent info
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
local depvalues = {compinst:program(), compflags}
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectfile), values = depvalues}) then
return
end
-- is verbose?
local verbose = option.get("verbose")
-- exists ccache?
local exists_ccache = ccache.exists()
-- trace progress info
if not opt.quiet then
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
if verbose then
cprint(progress_prefix .. "${dim color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile)
else
cprint(progress_prefix .. "${color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile)
end
end
-- trace verbose info
if verbose then
print(compinst:compcmd(sourcefile, objectfile, {compflags = compflags}))
end
-- compile it
dependinfo.files = {}
if not option.get("dry-run") then
assert(compinst:compile(sourcefile, objectfile, {dependinfo = dependinfo, compflags = compflags}))
end
-- update files and values to the dependent file
dependinfo.values = depvalues
table.join2(dependinfo.files, sourcefile, target:pcoutputfile("cxx") or {}, target:pcoutputfile("c"))
depend.save(dependinfo, dependfile)
end
-- build object
function _build_object(target, sourcefile, opt)
local script = target:script("build_file", _do_build_file)
if script then
script(target, sourcefile, opt)
end
end
-- build the source files
function build(target, sourcebatch, opt)
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
opt.objectfile = sourcebatch.objectfiles[i]
opt.dependfile = sourcebatch.dependfiles[i]
opt.sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
_build_object(target, sourcefile, opt)
end
end
-- add batch jobs to build the source files
function main(target, batchjobs, sourcebatch, opt)
local rootjob = opt.rootjob
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
local objectfile = sourcebatch.objectfiles[i]
local dependfile = sourcebatch.dependfiles[i]
local sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
batchjobs:addjob(sourcefile, function (index, total)
local build_opt = table.join({objectfile = objectfile, dependfile = dependfile, sourcekind = sourcekind, progress = (index * 100) / total}, opt)
_build_object(target, sourcefile, build_opt)
end, rootjob)
end
end
|
fix build object for batch
|
fix build object for batch
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
f85075a09f03155be17ac0a8e4eebb85aec0df1b
|
onmt/modules/Generator.lua
|
onmt/modules/Generator.lua
|
--[[ Default decoder generator.
Given RNN state, produce categorical distribution for tokens and features
Simply implements $$softmax(W h b)$$.
version 2: merge FeaturesGenerator and Generator - the generator nn is a table
--]]
local Generator, parent = torch.class('onmt.Generator', 'onmt.Network')
-- for back compatibility - still declare FeaturesGenerator - but no need to define it
torch.class('onmt.FeaturesGenerator', 'onmt.Generator')
function Generator:__init(opt, sizes)
parent.__init(self)
self:_buildGenerator(opt, sizes)
-- for backward compatibility with previous model
self.version = 2
end
function Generator:_buildGenerator(opt, sizes)
local generator = nn.ConcatTable()
local rnn_size = opt.rnn_size
for i = 1, #sizes do
local linear = nn.Linear(rnn_size, sizes[i])
if i == 1 then
self.rindexLinear = linear
end
generator:add(nn.Sequential()
:add(linear)
:add(nn.LogSoftMax()))
end
self:set(generator)
end
--[[ If the target vocabulary for the batch is not full vocabulary ]]
function Generator:setTargetVoc(t)
self.rindexLinear:RIndex_setOutputIndices(t)
end
--[[ Release Generator for inference only ]]
function Generator:release()
self.rindexLinear:RIndex_clean()
end
function Generator.load(generator)
if not generator.version then
if torch.type(generator)=='onmt.Generator' then
-- convert previous generator
generator:set(nn.ConcatTable():add(generator.net))
end
generator.version = 2
end
if not generator.rindexLinear then
local firstOutput = generator.net.modules[1]
assert(torch.type(firstOutput.modules[1])=='nn.Linear')
generator.rindexLinear = firstOutput.modules[1]
end
return generator
end
function Generator:updateOutput(input)
input = type(input) == 'table' and input[1] or input
self.output = self.net:updateOutput(input)
return self.output
end
function Generator:updateGradInput(input, gradOutput)
input = type(input) == 'table' and input[1] or input
self.gradInput = self.net:updateGradInput(input, gradOutput)
return self.gradInput
end
function Generator:accGradParameters(input, gradOutput, scale)
input = type(input) == 'table' and input[1] or input
self.net:accGradParameters(input, gradOutput, scale)
end
|
--[[ Default decoder generator.
Given RNN state, produce categorical distribution for tokens and features
Simply implements $$softmax(W h b)$$.
version 2: merge FeaturesGenerator and Generator - the generator nn is a table
--]]
local Generator, parent = torch.class('onmt.Generator', 'onmt.Network')
-- for back compatibility - still declare FeaturesGenerator - but no need to define it
torch.class('onmt.FeaturesGenerator', 'onmt.Generator')
function Generator:__init(opt, sizes)
parent.__init(self)
self:_buildGenerator(opt, sizes)
-- for backward compatibility with previous model
self.version = 2
end
function Generator:_buildGenerator(opt, sizes)
local generator = nn.ConcatTable()
local rnn_size = opt.rnn_size
for i = 1, #sizes do
local linear = nn.Linear(rnn_size, sizes[i])
if i == 1 then
self.rindexLinear = linear
end
generator:add(nn.Sequential()
:add(linear)
:add(nn.LogSoftMax()))
end
self:set(generator)
end
--[[ If the target vocabulary for the batch is not full vocabulary ]]
function Generator:setTargetVoc(t)
self.rindexLinear:RIndex_setOutputIndices(t)
end
--[[ Release Generator for inference only ]]
function Generator:release()
if self.rindexLinear then
self.rindexLinear:RIndex_clean()
end
end
function Generator.load(generator)
if not generator.version then
if torch.type(generator)=='onmt.Generator' then
-- convert previous generator
generator:set(nn.ConcatTable():add(generator.net))
end
generator.version = 2
end
if not generator.rindexLinear then
local firstOutput = generator.net.modules[1]
assert(torch.type(firstOutput.modules[1])=='nn.Linear')
generator.rindexLinear = firstOutput.modules[1]
end
return generator
end
function Generator:updateOutput(input)
input = type(input) == 'table' and input[1] or input
self.output = self.net:updateOutput(input)
return self.output
end
function Generator:updateGradInput(input, gradOutput)
input = type(input) == 'table' and input[1] or input
self.gradInput = self.net:updateGradInput(input, gradOutput)
return self.gradInput
end
function Generator:accGradParameters(input, gradOutput, scale)
input = type(input) == 'table' and input[1] or input
self.net:accGradParameters(input, gradOutput, scale)
end
|
Clean RIndexLinear only when defined
|
Clean RIndexLinear only when defined
Fixes #275.
|
Lua
|
mit
|
monsieurzhang/OpenNMT,da03/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT
|
15ad4c2b47c68d0e58c790804a0f7f43f12039ca
|
kong/plugins/zipkin/reporter.lua
|
kong/plugins/zipkin/reporter.lua
|
local resty_http = require "resty.http"
local to_hex = require "resty.string".to_hex
local cjson = require "cjson".new()
cjson.encode_number_precision(16)
local zipkin_reporter_methods = {}
local zipkin_reporter_mt = {
__name = "kong.plugins.zipkin.reporter";
__index = zipkin_reporter_methods;
}
local function new_zipkin_reporter(conf)
local http_endpoint = conf.http_endpoint
assert(type(http_endpoint) == "string", "invalid http endpoint")
return setmetatable({
http_endpoint = http_endpoint;
pending_spans = {};
pending_spans_n = 0;
}, zipkin_reporter_mt)
end
local span_kind_map = {
client = "CLIENT";
server = "SERVER";
producer = "PRODUCER";
consumer = "CONSUMER";
}
function zipkin_reporter_methods:report(span)
local span_context = span.context
local span_kind = span:get_tag "span.kind"
local port = span:get_tag "peer.port"
local zipkin_tags = {}
for k, v in span:each_tag() do
-- Zipkin tag values should be strings
-- see https://zipkin.io/zipkin-api/#/default/post_spans
-- and https://github.com/Kong/kong-plugin-zipkin/pull/13#issuecomment-402389342
zipkin_tags[k] = tostring(v)
end
local zipkin_span = {
traceId = to_hex(span_context.trace_id);
name = span.name;
parentId = span_context.parent_id and to_hex(span_context.parent_id) or nil;
id = to_hex(span_context.span_id);
kind = span_kind_map[span_kind];
timestamp = span.timestamp * 1000000;
duration = math.floor(span.duration * 1000000); -- zipkin wants integer
-- TODO: shared?
-- TODO: debug?
localEndpoint = cjson.null, -- needs to be null; not the empty object
-- TODO: localEndpoint from ngx.var.server_name/ngx.var.server_port?
remoteEndpoint = port and {
ipv4 = span:get_tag "peer.ipv4";
ipv6 = span:get_tag "peer.ipv6";
port = port; -- port is *not* optional
} or cjson.null;
tags = zipkin_tags;
annotations = span.logs -- XXX: not guaranteed by documented opentracing-lua API to be in correct format
}
local i = self.pending_spans_n + 1
self.pending_spans[i] = zipkin_span
self.pending_spans_n = i
end
function zipkin_reporter_methods:flush()
if self.pending_spans_n == 0 then
return true
end
local pending_spans = cjson.encode(self.pending_spans)
self.pending_spans = {}
self.pending_spans_n = 0
local httpc = resty_http.new()
local res, err = httpc:request_uri(self.http_endpoint, {
method = "POST";
headers = {
["content-type"] = "application/json";
};
body = pending_spans;
})
-- TODO: on failure, retry?
if not res then
return nil, "failed to request: " .. err
elseif res.status < 200 or res.status >= 300 then
return nil, "failed: " .. res.status .. " " .. res.reason
end
return true
end
return {
new = new_zipkin_reporter;
}
|
local resty_http = require "resty.http"
local to_hex = require "resty.string".to_hex
local cjson = require "cjson".new()
cjson.encode_number_precision(16)
local zipkin_reporter_methods = {}
local zipkin_reporter_mt = {
__name = "kong.plugins.zipkin.reporter";
__index = zipkin_reporter_methods;
}
local function new_zipkin_reporter(conf)
local http_endpoint = conf.http_endpoint
assert(type(http_endpoint) == "string", "invalid http endpoint")
return setmetatable({
http_endpoint = http_endpoint;
pending_spans = {};
pending_spans_n = 0;
}, zipkin_reporter_mt)
end
local span_kind_map = {
client = "CLIENT";
server = "SERVER";
producer = "PRODUCER";
consumer = "CONSUMER";
}
function zipkin_reporter_methods:report(span)
local span_context = span.context
local span_kind = span:get_tag "span.kind"
local port = span:get_tag "peer.port"
local zipkin_tags = {}
for k, v in span:each_tag() do
-- Zipkin tag values should be strings
-- see https://zipkin.io/zipkin-api/#/default/post_spans
-- and https://github.com/Kong/kong-plugin-zipkin/pull/13#issuecomment-402389342
zipkin_tags[k] = tostring(v)
end
local localEndpoint do
local service = ngx.ctx.service
if service and service.name ~= ngx.null then
localEndpoint = {
serviceName = service.name;
-- TODO: ip/port from ngx.var.server_name/ngx.var.server_port?
}
else
-- needs to be null; not the empty object
localEndpoint = cjson.null
end
end
local zipkin_span = {
traceId = to_hex(span_context.trace_id);
name = span.name;
parentId = span_context.parent_id and to_hex(span_context.parent_id) or nil;
id = to_hex(span_context.span_id);
kind = span_kind_map[span_kind];
timestamp = span.timestamp * 1000000;
duration = math.floor(span.duration * 1000000); -- zipkin wants integer
-- TODO: shared?
-- TODO: debug?
localEndpoint = localEndpoint;
remoteEndpoint = port and {
ipv4 = span:get_tag "peer.ipv4";
ipv6 = span:get_tag "peer.ipv6";
port = port; -- port is *not* optional
} or cjson.null;
tags = zipkin_tags;
annotations = span.logs -- XXX: not guaranteed by documented opentracing-lua API to be in correct format
}
local i = self.pending_spans_n + 1
self.pending_spans[i] = zipkin_span
self.pending_spans_n = i
end
function zipkin_reporter_methods:flush()
if self.pending_spans_n == 0 then
return true
end
local pending_spans = cjson.encode(self.pending_spans)
self.pending_spans = {}
self.pending_spans_n = 0
local httpc = resty_http.new()
local res, err = httpc:request_uri(self.http_endpoint, {
method = "POST";
headers = {
["content-type"] = "application/json";
};
body = pending_spans;
})
-- TODO: on failure, retry?
if not res then
return nil, "failed to request: " .. err
elseif res.status < 200 or res.status >= 300 then
return nil, "failed: " .. res.status .. " " .. res.reason
end
return true
end
return {
new = new_zipkin_reporter;
}
|
kong/plugins/zipkin/reporter.lua: Use current kong service name as localEndpoint
|
kong/plugins/zipkin/reporter.lua: Use current kong service name as localEndpoint
Fixes #12
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
6fdfa4d65e6899c80009dbdfc6940cf4f3210102
|
src/kong/plugins/authentication/schema.lua
|
src/kong/plugins/authentication/schema.lua
|
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC and names then
return false, "This field is not available for \""..constants.AUTHENTICATION.BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= constants.AUTHENTICATION.BASIC then
if names then
if type(names) == "table" and utils.table_size(names) > 0 then
return true
else
return false, "You need to specify an array"
end
else
return false, "This field is required for query and header authentication"
end
end
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC and names then
return false, "This field is not available for \""..constants.AUTHENTICATION.BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= constants.AUTHENTICATION.BASIC then
if not names or type(names) ~= "table" or utils.table_size(names) == 0 then
return false, "You need to specify an array with at least one value"
end
end
return true
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
fixing logic in authentication schema
|
fixing logic in authentication schema
|
Lua
|
apache-2.0
|
shiprabehera/kong,kyroskoh/kong,jebenexer/kong,li-wl/kong,ind9/kong,ajayk/kong,vzaramel/kong,ind9/kong,jerizm/kong,xvaara/kong,salazar/kong,rafael/kong,vzaramel/kong,isdom/kong,ejoncas/kong,kyroskoh/kong,smanolache/kong,streamdataio/kong,Vermeille/kong,isdom/kong,streamdataio/kong,Kong/kong,beauli/kong,akh00/kong,ccyphers/kong,rafael/kong,Kong/kong,Kong/kong,ejoncas/kong,icyxp/kong,Mashape/kong
|
8b1e662dee1fc1c8b94ff6a09ee9f57fc418dc40
|
support/mod_websocket.lua
|
support/mod_websocket.lua
|
module.host = "*" -- Global module
local logger = require "util.logger";
local log = logger.init("mod_websocket");
local httpserver = require "net.httpserver";
local lxp = require "lxp";
local init_xmlhandlers = require "core.xmlhandlers";
local st = require "util.stanza";
local sm = require "core.sessionmanager";
local sessions = {};
local default_headers = { };
local stream_callbacks = { default_ns = "jabber:client",
streamopened = sm.streamopened,
streamclosed = sm.streamclosed,
handlestanza = core_process_stanza };
function stream_callbacks.error(session, error, data)
if error == "no-stream" then
session.log("debug", "Invalid opening stream header");
session:close("invalid-namespace");
elseif session.close then
(session.log or log)("debug", "Client XML parse error: %s", tostring(error));
session:close("xml-not-well-formed");
end
end
local function session_reset_stream(session)
local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "\1");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
data, _ = data:gsub("[%z\255]", "")
log("debug", "Parsing: %s", data)
local ok, err = parser:parse(data)
if not ok then
log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data,
data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
session:close("xml-not-well-formed");
end
end
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
local log = session.log or log;
if session.conn then
if session.notopen then
session.send("<?xml version='1.0'?>");
session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
log("info", "Disconnecting client, <stream:error> is: %s", reason);
session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
log("info", "Disconnecting client, <stream:error> is: %s", tostring(stanza));
session.send(stanza);
elseif reason.name then -- a stanza
log("info", "Disconnecting client, <stream:error> is: %s", tostring(reason));
session.send(reason);
end
end
end
session.send("</stream:stream>");
session.conn:close();
websocket_listener.ondisconnect(session.conn, (reason and (reason.text or reason.condition)) or reason or "session closed");
end
end
local websocket_listener = { default_mode = "*a" };
function websocket_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { type = "c2s_unauthed",
conn = conn,
reset_stream = session_reset_stream,
close = session_close,
dispatch_stanza = stream_callbacks.handlestanza,
log = logger.init("websocket"),
secure = conn.ssl };
function session.send(s)
conn:write("\00" .. tostring(s) .. "\255");
end
sessions[conn] = session;
end
session_reset_stream(session);
if data then
session.data(conn, data);
end
end
function websocket_listener.ondisconnect(conn, err)
local session = sessions[conn];
if session then
(session.log or log)("info", "Client disconnected: %s", err);
sm.destroy_session(session, err);
sessions[conn] = nil;
session = nil;
end
end
function handle_request(method, body, request)
if request.method ~= "GET" or request.headers["upgrade"] ~= "WebSocket" or request.headers["connection"] ~= "Upgrade" then
if request.method == "OPTIONS" then
return { headers = default_headers, body = "" };
else
return "<html><body>You really don't look like a Websocket client to me... what do you want?</body></html>";
end
end
local subprotocol = request.headers["Websocket-Protocol"];
if subprotocol ~= nil and subprotocol ~= "XMPP" then
return "<html><body>You really don't look like an XMPP Websocket client to me... what do you want?</body></html>";
end
if not method then
log("debug", "Request %s suffered error %s", tostring(request.id), body);
return;
end
request.conn:setlistener(websocket_listener);
request.write("HTTP/1.1 101 Web Socket Protocol Handshake\r\n");
request.write("Upgrade: WebSocket\r\n");
request.write("Connection: Upgrade\r\n");
request.write("WebSocket-Origin: file://\r\n"); -- FIXME
request.write("WebSocket-Location: ws://localhost:5281/xmpp-websocket\r\n"); -- FIXME
request.write("WebSocket-Protocol: XMPP\r\n");
request.write("\r\n");
return true;
end
local function setup()
local ports = module:get_option("websocket_ports") or { 5281 };
httpserver.new_from_config(ports, handle_request, { base = "xmpp-websocket" });
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
--Obtained from http://code.google.com/p/prosody-modules/source/browse/mod_websocket/mod_websocket.lua
--Author appears to be Ali Sabil <[email protected]>
--Code had no license in attribution in header, emailed Ali 4-17-12 to see if he wanted any since we will have to modify this heavily and probably re-release
--Changes to support latest WebSocket RFC by Fred Kilbourn <[email protected]>
module.host = "*" -- Global module
local logger = require "util.logger";
local log = logger.init("mod_websocket");
local httpserver = require "net.httpserver";
local lxp = require "lxp";
local new_xmpp_stream = require "util.xmppstream".new;
local st = require "util.stanza";
local sm = require "core.sessionmanager";
local sessions = {};
local default_headers = { };
local stream_callbacks = { default_ns = "jabber:client",
streamopened = sm.streamopened,
streamclosed = sm.streamclosed,
handlestanza = core_process_stanza };
function stream_callbacks.error(session, error, data)
if error == "no-stream" then
session.log("debug", "Invalid opening stream header");
session:close("invalid-namespace");
elseif session.close then
(session.log or log)("debug", "Client XML parse error: %s", tostring(error));
session:close("xml-not-well-formed");
end
end
local function session_reset_stream(session)
local stream = new_xmpp_stream(session, stream_callbacks);
session.stream = stream;
session.notopen = true;
--TODO: might not be necessary, don't understand yet
-- (added based on http://hg.prosody.im/0.8/rev/ccf417c7b5d4)
function session.reset_stream()
session.notopen = true;
session.stream:reset()
end
function session.data(conn, data)
data, _ = data:gsub("[%z\255]", "")
log("debug", "Parsing: %s", data)
local ok, err = stream:feed(data);
if not ok then
log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data,
data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
session:close("xml-not-well-formed");
end
end
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
local log = session.log or log;
if session.conn then
if session.notopen then
session.send("<?xml version='1.0'?>");
session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
log("info", "Disconnecting client, <stream:error> is: %s", reason);
session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
log("info", "Disconnecting client, <stream:error> is: %s", tostring(stanza));
session.send(stanza);
elseif reason.name then -- a stanza
log("info", "Disconnecting client, <stream:error> is: %s", tostring(reason));
session.send(reason);
end
end
end
session.send("</stream:stream>");
session.conn:close();
websocket_listener.ondisconnect(session.conn, (reason and (reason.text or reason.condition)) or reason or "session closed");
end
end
local websocket_listener = { default_mode = "*a" };
function websocket_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { type = "c2s_unauthed",
conn = conn,
reset_stream = session_reset_stream,
close = session_close,
dispatch_stanza = stream_callbacks.handlestanza,
log = logger.init("websocket"),
secure = conn.ssl };
function session.send(s)
conn:write("\00" .. tostring(s) .. "\255");
end
sessions[conn] = session;
end
session_reset_stream(session);
if data then
session.data(conn, data);
end
end
function websocket_listener.ondisconnect(conn, err)
local session = sessions[conn];
if session then
(session.log or log)("info", "Client disconnected: %s", err);
sm.destroy_session(session, err);
sessions[conn] = nil;
session = nil;
end
end
function handle_request(method, body, request)
if request.method ~= "GET" or request.headers["upgrade"] ~= "websocket" or request.headers["connection"] ~= "Upgrade" then
if request.method == "OPTIONS" then
return { headers = default_headers, body = "" };
else
return "<html><body>You really don't look like a Websocket client to me... what do you want?</body></html>";
end
end
--implement subprotocol support
--Optionally, a |Sec-WebSocket-Protocol| header field, with a list
-- of values indicating which protocols the client would like to
-- speak, ordered by preference.
-- local subprotocol = request.headers["Websocket-Protocol"];
-- if subprotocol ~= nil and subprotocol ~= "XMPP" then
-- return "<html><body>You really don't look like an XMPP Websocket client to me... what do you want?</body></html>";
-- end
if not method then
log("debug", "Request %s suffered error %s", tostring(request.id), body);
return;
end
request.conn:setlistener(websocket_listener);
request.write("HTTP/1.1 101 Web Socket Protocol Handshake\r\n");
request.write("Upgrade: WebSocket\r\n");
request.write("Connection: Upgrade\r\n");
-- request.write("WebSocket-Origin: file://\r\n"); -- FIXME
-- request.write("WebSocket-Location: ws://localhost:5281/xmpp-websocket\r\n"); -- FIXME
-- request.write("WebSocket-Protocol: XMPP\r\n");
request.write("\r\n");
return true;
end
local function setup()
local ports = module:get_option("websocket_ports") or { 5281 };
httpserver.new_from_config(ports, handle_request, { base = "xmpp-websocket" });
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
Convert to use util.xmppstream, started updating to latest WebSocket RFC xmppstream fixes based on: http://hg.prosody.im/0.8/rev/93ea0f9622a1 rfc: http://tools.ietf.org/html/rfc6455
|
Convert to use util.xmppstream, started updating to latest WebSocket RFC
xmppstream fixes based on: http://hg.prosody.im/0.8/rev/93ea0f9622a1
rfc: http://tools.ietf.org/html/rfc6455
|
Lua
|
mit
|
ltg-uic/phenomena-website,ltg-uic/phenomena-website,ltg-uic/phenomena-website
|
b509bceb1bce79c9e5b0ddf51fa88957f8e3df9c
|
packages/torch/torch.lua
|
packages/torch/torch.lua
|
local function sizestr(x)
local strt = {}
table.insert(strt, _G.torch.typename(x):match('torch%.(.+)') .. ' - size: ')
for i=1,x:nDimension() do
table.insert(strt, x:size(i))
if i ~= x:nDimension() then
table.insert(strt, 'x')
end
end
return table.concat(strt)
end
-- k : name of variable
-- m : max length
local function printvar(key,val,m)
local name = '[' .. tostring(key) .. ']'
--io.write(name)
name = name .. string.rep(' ',m-name:len()+2)
local tp = type(val)
if tp == 'userdata' then
tp = torch.typename(val)
if tp:find('torch.*Tensor') then
tp = sizestr(val)
end
if tp:find('torch.*Storage') then
tp = sizestr(val)
end
elseif tp == 'table' then
tp = tp .. ' - size: ' .. #val
elseif tp == 'string' then
local tostr = val:gsub('\n','\\n')
if #tostr>40 then
tostr = tostr:sub(1,40)
end
tp = tp .. ' = "' .. tostr .. '"'
else
tp = tostring(val)
end
return name .. ' = ' .. tp
end
local function getmaxlen(vars)
local m = 0
if type(vars) ~= 'table' then return tostring(vars):len() end
for k,v in pairs(vars) do
local s = tostring(k)
if s:len() > m then
m = s:len()
end
end
return m
end
-- who:
-- a simple function that prints all the symbols defined by the user
-- very much like Matlab's who function
function who()
local m = getmaxlen(_G)
local p = _G._preloaded_
local function printsymb(sys)
for k,v in pairs(_G) do
if (sys and p[k]) or (not sys and not p[k]) then
print(printvar(k,_G[k],m))
end
end
end
print('== System Variables ==')
printsymb(true)
print('== User Variables ==')
printsymb(false)
print('==')
end
print_old=print
_G._preloaded_ = {}
for k,v in pairs(_G) do
_G._preloaded_[k] = true
end
-- print:
-- a smarter print for Lua, the default Lua print is quite terse
-- this new print is much more verbose, automatically recursing through
-- lua tables, and objects.
function print(obj,...)
local m = getmaxlen(obj)
if _G.type(obj) == 'table' then
local mt = _G.getmetatable(obj)
if mt and mt.__tostring__ then
_G.io.write(mt.__tostring__(obj))
else
local tos = _G.tostring(obj)
local obj_w_usage = false
if tos and not _G.string.find(tos,'table: ') then
if obj.usage and _G.type(obj.usage) == 'string' then
_G.io.write(obj.usage)
_G.io.write('\n\nFIELDS:\n')
obj_w_usage = true
else
_G.io.write(tos .. ':\n')
end
end
_G.io.write('{')
local idx = 1
local tab = ''
local newline = ''
for k,v in pairs(obj) do
local line = printvar(k,v,m)
_G.io.write(newline .. tab .. line)
if idx == 1 then
tab = ' '
newline = '\n'
end
idx = idx + 1
end
_G.io.write('}')
if obj_w_usage then
_G.io.write('')
end
end
else
_G.io.write(_G.tostring(obj))
end
if _G.select('#',...) > 0 then
_G.io.write(' ')
print(...)
else
_G.io.write('\n')
end
end
|
local function sizestr(x)
local strt = {}
table.insert(strt, _G.torch.typename(x):match('torch%.(.+)') .. ' - size: ')
for i=1,x:nDimension() do
table.insert(strt, x:size(i))
if i ~= x:nDimension() then
table.insert(strt, 'x')
end
end
if x:nDimension() == 0 then
table.insert(strt, '-')
end
return table.concat(strt)
end
-- k : name of variable
-- m : max length
local function printvar(key,val,m)
local name = '[' .. tostring(key) .. ']'
--io.write(name)
name = name .. string.rep(' ',m-name:len()+2)
local tp = type(val)
if tp == 'userdata' then
tp = torch.typename(val)
if tp:find('torch.*Tensor') then
tp = sizestr(val)
end
if tp:find('torch.*Storage') then
tp = sizestr(val)
end
elseif tp == 'table' then
tp = tp .. ' - size: ' .. #val
elseif tp == 'string' then
local tostr = val:gsub('\n','\\n')
if #tostr>40 then
tostr = tostr:sub(1,40)
end
tp = tp .. ' = "' .. tostr .. '"'
else
tp = tostring(val)
end
return name .. ' = ' .. tp
end
local function getmaxlen(vars)
local m = 0
if type(vars) ~= 'table' then return tostring(vars):len() end
for k,v in pairs(vars) do
local s = tostring(k)
if s:len() > m then
m = s:len()
end
end
return m
end
-- who:
-- a simple function that prints all the symbols defined by the user
-- very much like Matlab's who function
function who()
local m = getmaxlen(_G)
local p = _G._preloaded_
local function printsymb(sys)
for k,v in pairs(_G) do
if (sys and p[k]) or (not sys and not p[k]) then
print(printvar(k,_G[k],m))
end
end
end
print('== System Variables ==')
printsymb(true)
print('== User Variables ==')
printsymb(false)
print('==')
end
print_old=print
_G._preloaded_ = {}
for k,v in pairs(_G) do
_G._preloaded_[k] = true
end
-- print:
-- a smarter print for Lua, the default Lua print is quite terse
-- this new print is much more verbose, automatically recursing through
-- lua tables, and objects.
function print(obj,...)
local m = getmaxlen(obj)
if _G.type(obj) == 'table' then
local mt = _G.getmetatable(obj)
if mt and mt.__tostring__ then
_G.io.write(mt.__tostring__(obj))
else
local tos = _G.tostring(obj)
local obj_w_usage = false
if tos and not _G.string.find(tos,'table: ') then
if obj.usage and _G.type(obj.usage) == 'string' then
_G.io.write(obj.usage)
_G.io.write('\n\nFIELDS:\n')
obj_w_usage = true
else
_G.io.write(tos .. ':\n')
end
end
_G.io.write('{')
local idx = 1
local tab = ''
local newline = ''
for k,v in pairs(obj) do
local line = printvar(k,v,m)
_G.io.write(newline .. tab .. line)
if idx == 1 then
tab = ' '
newline = '\n'
end
idx = idx + 1
end
_G.io.write('}')
if obj_w_usage then
_G.io.write('')
end
end
else
_G.io.write(_G.tostring(obj))
end
if _G.select('#',...) > 0 then
_G.io.write(' ')
print(...)
else
_G.io.write('\n')
end
end
|
Fixed some details
|
Fixed some details
|
Lua
|
bsd-3-clause
|
soumith/TH,soumith/TH,soumith/TH,soumith/TH
|
c8a8c2a6a11dd781f3634ce6ef64ba4b57268ced
|
lib/utils.lua
|
lib/utils.lua
|
#!/usr/bin/env lua
-- utils.lua
-- Useful methods for process.lua script
-- Olivier DOSSMANN
--[[ Methods ]]--
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function deleteBeginSpace(string)
local res = string.gsub(string, "^ *", '')
return res
end
function deleteEndSpace(string)
local res = string.gsub(string, " *$", '')
return res
end
function listing (path, extension)
local files = {}
if lfs.attributes(path) then
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..'/'..file
local attr = lfs.attributes (f)
local filext = (string.match(file, "[^\\/]-%.?([^%.\\/]*)$"))
if attr.mode == 'file' and filext == extension then
table.insert(files, f)
end
end
end
else
files = nil
end
return files
end
function getConfig(file)
local result = {}
local f = assert(io.open(file, 'r'))
while true do
local line = f.read(f)
if not line then break end
local key = line:match('(.-)[ ]+=')
local val = line:match('=[ ]+(.*)')
local comment = string.find(line, '^#+.*')
if comment then
-- do nothing with commented lines
elseif key then
result[key] = val
end
end
assert(f:close())
return result
end
function replace(string, table)
return string:gsub("$(%b{})", function(string)
return table[string:sub(2,-2)]
end)
end
function checkDirectory(path)
if lfs.attributes(path) == nil then
assert(lfs.mkdir(path))
-- Display created directory
print (string.format("-- [%s] New folder: %s", display_success, path))
end
end
function readFile(path, mode)
local result = ''
if mode == nil then
local mode = 'r'
end
if mode ~= 'r' and mode ~= 'rb' then
print(string.format("-- [%s] Unknown read mode while reading this path: %s.", display_error, path))
os.exit(1)
end
local attr = lfs.attributes(path)
if attr and attr.mode == 'file' then
local f = assert(io.open(path, mode))
result = assert(f:read('*a'))
assert(f:close())
end
return result
end
function headFile(path, number)
local result = ''
if not number then
return readFile(path, 'r')
else
local attr = lfs.attributes(path)
if attr and attr.mode == 'file' then
local f = assert(io.open(path, mode))
i = 0
for line in f:lines() do
result = result .. line .. '\n'
i = i + 1
if i == number then break end
end
end
end
return result
end
function copyFile(origin, destination, freplace)
local content = ''
if lfs.attributes(origin) and lfs.attributes(origin).mode == 'file' then
-- open the file
content = readFile(origin, 'r')
end
-- write in destination
local result = assert(io.open(destination, 'wb'))
if content == nil then
result:close()
else
if freplace then
result:write(replace(content, freplace))
else
result:write(content)
end
end
result:close()
end
function copy(origin, destination)
local attr = lfs.attributes(origin)
if attr and attr.mode == 'directory' then
-- create destination if no one exists
if lfs.attributes(destination) == nil then
lfs.mkdir(destination)
end
-- browse origin directory
for element in lfs.dir(origin) do
if element ~= '.' and element ~= '..' then
local path = origin .. '/' .. element
-- launch copy directory if element is a directory, otherwise copy file
if lfs.attributes(path) and lfs.attributes(path).mode == 'directory' then
copy(path, destination .. '/' .. element)
else
copyFile(path, destination .. '/' .. element)
end
end
end
-- if origin is a file, just launch copyFile function
elseif attr and attr.mode == 'file' then
copyFile(origin, destination)
else
print (string.format("-- [%s] %s not found in copy method!", display_error, origin))
os.exit(1)
end
end
function getSubstitutions(replaces, local_replaces)
-- create substitutions list
local result = {}
for k, v in pairs(replaces) do
result[k] = v
end
for k, v in pairs(local_replaces) do
result[k] = v
end
return result
end
function dispatcher ()
while true do
local n = table.getn(threads)
if n == 0 then break end -- no more threads to run
for i=1,n do
local status, res = coroutine.resume(threads[i])
if not res then -- thread finished its task?
table.remove(threads, i)
break
end
end
end
end
function compare_post(a, b, order)
local r = a['file'] > b['file']
if order == nil then
r = a['file'] > b['file']
elseif order == 'asc' then
r = a['file'] < b['file']
elseif order == 'desc' then
r = a['file'] > b['file']
else
r = a['file'] > b['file']
end
return r
end
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
|
#!/usr/bin/env lua
-- utils.lua
-- Useful methods for process.lua script
-- Olivier DOSSMANN
--[[ Methods ]]--
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function deleteBeginSpace(string)
local res = string.gsub(string, "^ *", '')
return res
end
function deleteEndSpace(string)
local res = string.gsub(string, " *$", '')
return res
end
function listing (path, extension)
local files = {}
if lfs.attributes(path) then
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..'/'..file
local attr = lfs.attributes (f)
local filext = (string.match(file, "[^\\/]-%.?([^%.\\/]*)$"))
if attr.mode == 'file' and filext == extension then
table.insert(files, f)
end
end
end
else
files = nil
end
return files
end
function getConfig(file)
local result = {}
local f = assert(io.open(file, 'r'))
while true do
local line = f.read(f)
if not line then break end
local key = line:match('(.-)[ ]+=')
local val = line:match('=[ ]+(.*)')
local comment = string.find(line, '^#+.*')
if comment then
-- do nothing with commented lines
elseif key then
result[key] = val
end
end
assert(f:close())
return result
end
function replace(string, table)
return string:gsub("$(%b{})", function(string)
return table[string:sub(2,-2)]
end)
end
function checkDirectory(path)
if lfs.attributes(path) == nil then
assert(lfs.mkdir(path))
-- Display created directory
print (string.format("-- [%s] New folder: %s", display_success, path))
end
end
function readFile(path, mode)
local result = ''
if mode == nil then
local mode = 'r'
end
if mode ~= 'r' and mode ~= 'rb' then
print(string.format("-- [%s] Unknown read mode while reading this path: %s.", display_error, path))
os.exit(1)
end
local attr = lfs.attributes(path)
if attr and attr.mode == 'file' then
local f = assert(io.open(path, mode))
result = assert(f:read('*a'))
assert(f:close())
end
return result
end
function headFile(path, number)
local result = ''
if not number then
return readFile(path, 'r')
else
local attr = lfs.attributes(path)
if attr and attr.mode == 'file' then
local f = assert(io.open(path, mode))
i = 0
for line in f:lines() do
result = result .. line .. '\n'
i = i + 1
if i == number then break end
end
end
end
return result
end
function copyFile(origin, destination, freplace)
local content = ''
if lfs.attributes(origin) and lfs.attributes(origin).mode == 'file' then
-- open the file
content = readFile(origin, 'r')
end
-- write in destination
local result = assert(io.open(destination, 'wb'))
if content == nil then
result:close()
else
if freplace then
result:write(replace(content, freplace))
else
result:write(content)
end
end
result:close()
end
function copy(origin, destination)
local attr = lfs.attributes(origin)
if attr and attr.mode == 'directory' then
-- create destination if no one exists
if lfs.attributes(destination) == nil then
lfs.mkdir(destination)
end
-- browse origin directory
for element in lfs.dir(origin) do
if element ~= '.' and element ~= '..' then
local path = origin .. '/' .. element
-- launch copy directory if element is a directory, otherwise copy file
if lfs.attributes(path) and lfs.attributes(path).mode == 'directory' then
copy(path, destination .. '/' .. element)
else
copyFile(path, destination .. '/' .. element)
end
end
end
-- if origin is a file, just launch copyFile function
elseif attr and attr.mode == 'file' then
copyFile(origin, destination)
else
print (string.format("-- [%s] %s not found in copy method!", display_error, origin))
os.exit(1)
end
end
function getSubstitutions(replaces, local_replaces)
-- create substitutions list
local result = {}
for k, v in pairs(replaces) do
result[k] = v
end
for k, v in pairs(local_replaces) do
result[k] = v
end
return result
end
function dispatcher ()
while true do
local n = table.getn(threads)
if n == 0 then break end -- no more threads to run
for i=1,n do
if coroutine.status(threads[i]) == 'dead' then
table.remove(threads, i)
break
end
local status, res = coroutine.resume(threads[i])
if not res then -- thread finished its task?
table.remove(threads, i)
break
end
end
end
end
function compare_post(a, b, order)
local r = a['file'] > b['file']
if order == nil then
r = a['file'] > b['file']
elseif order == 'asc' then
r = a['file'] < b['file']
elseif order == 'desc' then
r = a['file'] > b['file']
else
r = a['file'] > b['file']
end
return r
end
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
|
[FIX] refs #244 Kill dead coroutines
|
[FIX] refs #244 Kill dead coroutines
|
Lua
|
agpl-3.0
|
blankoworld/makefly,blankoworld/makefly,blankoworld/makefly
|
53920b58a3ca2e5f136c63115a28e708f56a2285
|
src/lua/example.capdiss.lua
|
src/lua/example.capdiss.lua
|
--
-- Capdiss script counting frames.
--
capdiss = {}
local i
function capdiss.begin (filename, link_type)
-- Not much to do here, just initialize the counter variable
i = 0
io.write (string.format ("Begin parsing '%s'...\n", filename))
end
function capdiss.each (ts, frame)
i = i + 1
io.write (string.format ("%s :: pkt no. %d\n", os.date ("%Y-%m-%d %H:%M:%S", ts), i))
end
function capdiss.finish ()
io.write (string.format ("Done parsing ... %d\n", i))
end
|
--
-- Capdiss script counting frames.
--
capdiss = {}
local i
function capdiss.begin (filename, link_type)
-- Not much to do here, just initialize the counter variable
io.write (string.format ("Begin parsing '%s' (linktype: %s)...\n", filename, link_type))
end
function capdiss.each (frame, ts, num)
i = num
io.write (string.format ("%s :: pkt no. %d\n", os.date ("%Y-%m-%d %H:%M:%S", ts), i))
end
function capdiss.finish ()
io.write (string.format ("Done parsing ... %d\n", i))
end
|
New example script. Fix param order.
|
New example script. Fix param order.
|
Lua
|
mit
|
antagon/capdiss
|
53c0a44d35182cf5b44145ab681cbf063174a2a2
|
share/media/funnyordie.lua
|
share/media/funnyordie.lua
|
-- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2010 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local FunnyOrDie = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = FunnyOrDie.can_parse_url(qargs),
domains = table.concat({'funnyordie.com'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
qargs.thumb_url = p:match('"og:image" content="(.-)"') or ''
qargs.title = p:match('"og:title" content="(.-)">') or ''
qargs.id = p:match('key:%s+"(.-)"') or ''
qargs.streams = FunnyOrDie.iter_streams(p)
return qargs
end
--
-- Utility functions
--
function FunnyOrDie.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('funnyordie%.com$')
and t.path and t.path:lower():match('^/videos/%w+')
then
return true
else
return false
end
end
function FunnyOrDie.iter_streams(p)
local t = {}
-- 41a7516647: added the pattern in the next line, and removed...
for u in p:gmatch('type: "video/mp4", src: "(.-)"') do table.insert(t,u) end
for u in p:gmatch('source src="(.-)"') do table.insert(t,u) end -- ... This.
-- Keep both of them.
if #t ==0 then
error('no match: media stream URL')
end
local S = require 'quvi/stream'
local r = {}
-- nostd is a dictionary used by this script only. libquvi ignores it.
for _,u in pairs(t) do
local q,c = u:match('/(%w+)%.(%w+)$')
if q and c then
local s = S.stream_new(u)
s.nostd = {quality=q}
s.container = c
s.id = FunnyOrDie.to_id(s)
table.insert(r,s)
end
end
if #r >1 then
FunnyOrDie.ch_best(r)
end
return r
end
function FunnyOrDie.ch_best(t)
t[1].flags.best = true
end
function FunnyOrDie.to_id(t)
return string.format("%s_%s", t.nostd.quality, t.container)
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2010 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local FunnyOrDie = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = FunnyOrDie.can_parse_url(qargs),
domains = table.concat({'funnyordie.com'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
quvi.http.header('Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0')
local p = quvi.http.fetch(qargs.input_url).data
qargs.thumb_url = p:match('"og:image" content="(.-)"') or ''
qargs.title = p:match('"og:title" content="(.-)">') or ''
qargs.id = p:match('key:%s+"(.-)"') or ''
qargs.streams = FunnyOrDie.iter_streams(p)
return qargs
end
--
-- Utility functions
--
function FunnyOrDie.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('funnyordie%.com$')
and t.path and t.path:lower():match('^/videos/%w+')
then
return true
else
return false
end
end
function FunnyOrDie.iter_streams(p)
local t = {}
-- 41a7516647: added the pattern in the next line, and removed...
for u in p:gmatch('type: "video/mp4", src: "(.-)"') do table.insert(t,u) end
for u in p:gmatch('source src="(.-)"') do table.insert(t,u) end -- ... This.
-- Keep both of them.
if #t ==0 then
error('no match: media stream URL')
end
local S = require 'quvi/stream'
local r = {}
-- nostd is a dictionary used by this script only. libquvi ignores it.
for _,u in pairs(t) do
local q,c = u:match('/(%w+)%.(%w+)$')
if q and c then
local s = S.stream_new(u)
s.nostd = {quality=q}
s.container = c
s.id = FunnyOrDie.to_id(s)
table.insert(r,s)
end
end
if #r >1 then
FunnyOrDie.ch_best(r)
end
return r
end
function FunnyOrDie.ch_best(t)
t[1].flags.best = true
end
function FunnyOrDie.to_id(t)
return string.format("%s_%s", t.nostd.quality, t.container)
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/funnyordie.lua: Set "Accept-Encoding" HTTP header
|
FIX: media/funnyordie.lua: Set "Accept-Encoding" HTTP header
For an unknown reason when:
1) libcurl sends "Accept-Encoding: deflate, gzip" by default
2) server returns gzipped data without "Encoding: gzip" within the reply
Causing the following:
1) libcurl skips decompression and passes the compressed data to libquvi
2) libquvi passes the compressed data to the media/funnyordie.lua
3) script fails to match any of the patterns due to the compressed data
This commit makes the script override the default "Accept-Encoding"
value with one that seems to work with the servers and libcurl.
Package: libcurl4-gnutls-dev
Version: 7.26.0-1+wheezy3
Versions of packages libcurl4-gnutls-dev depends on:
ii libc6-dev [libc-dev] 2.13-38
ii libcurl3-gnutls 7.26.0-1+wheezy3
ii libgnutls-dev 2.12.20-7
ii libidn11-dev 1.25-2
ii libkrb5-dev 1.10.1+dfsg-5+deb7u1
ii libldap2-dev 2.4.31-1+nmu2
ii librtmp-dev 2.4+20111222.git4e06e21-1
ii libssh2-1-dev 1.4.2-1.1
ii zlib1g-dev 1:1.2.7.dfsg-1
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts
|
1d61bfded6f6d0a72cd71a177cd4b5b9fada69bb
|
vinyl/theme.lua
|
vinyl/theme.lua
|
-- bamboo, awesome3 theme, by zhuravlik, based on Zenburn
--{{{ Main
local awful = require("awful")
awful.util = require("awful.util")
theme = {}
home = os.getenv("HOME")
config = awful.util.getdir("config")
shared = "/usr/share/awesome"
if not awful.util.file_readable(shared .. "/icons/awesome16.png") then
shared = "/usr/share/local/awesome"
end
sharedicons = shared .. "/icons"
sharedthemes = shared .. "/themes"
themes = config .. "/themes"
themename = "/vinyl"
if not awful.util.file_readable(themes .. themename .. "/theme.lua") then
themes = sharedthemes
end
themedir = themes .. themename
wallpaper1 = themedir .. "/background.jpg"
wallpaper2 = themedir .. "/background.png"
wallpaper3 = sharedthemes .. "/zenburn/zenburn-background.png"
wallpaper4 = sharedthemes .. "/default/background.png"
wpscript = home .. "/.wallpaper"
if awful.util.file_readable(wallpaper1) then
theme.wallpaper = wallpaper1
elseif awful.util.file_readable(wallpaper2) then
theme.wallpaper = wallpaper2
elseif awful.util.file_readable(wpscript) then
theme.wallpaper_cmd = { "sh " .. wpscript }
elseif awful.util.file_readable(wallpaper3) then
theme.wallpaper = wallpaper3
else
theme.wallpaper = wallpaper4
end
if awful.util.file_readable(config .. "/vain/init.lua") then
theme.useless_gap_width = "3"
end
--}}}
theme.font = "anorexia 9"
theme.bg_normal = "#000001"
theme.bg_focus = "#000001"
theme.bg_urgent = "#000000"
theme.bg_minimize = "#000000"
theme.fg_normal = "#575757"
theme.fg_focus = "#D2D46B"
theme.fg_urgent = "#000000"
theme.fg_minimize = "#000000"
theme.border_width = "0"
theme.border_normal = "#000000"
theme.border_focus = "#000000"
theme.border_marked = "#000000"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- [taglist|tasklist]_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- Example:
--theme.taglist_bg_focus = "#ff0000"
-- Display the taglist squares
theme.taglist_squares_sel = sharedthemes .. "/default/taglist/squarefw.png"
theme.taglist_squares_unsel = sharedthemes .. "/default/taglist/squarew.png"
theme.tasklist_floating_icon = sharedthemes .. "/default/tasklist/floatingw.png"
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_submenu_icon = sharedthemes .. "/default/submenu.png"
theme.menu_height = "15"
theme.menu_width = "100"
-- You can add as many variables as
-- you wish and access them by using
-- beautiful.variable in your rc.lua
--theme.bg_widget = "#cc0000"
-- Define the image to load
theme.titlebar_close_button_normal = sharedthemes .. "/default/titlebar/close_normal.png"
theme.titlebar_close_button_focus = sharedthemes .. "/default/titlebar/close_focus.png"
theme.titlebar_ontop_button_normal_inactive = sharedthemes .. "/default/titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = sharedthemes .. "/default/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = sharedthemes .. "/default/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = sharedthemes .. "/default/titlebar/ontop_focus_active.png"
theme.titlebar_sticky_button_normal_inactive = sharedthemes .. "/default/titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = sharedthemes .. "/default/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = sharedthemes .. "/default/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = sharedthemes .. "/default/titlebar/sticky_focus_active.png"
theme.titlebar_floating_button_normal_inactive = sharedthemes .. "/default/titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = sharedthemes .. "/default/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = sharedthemes .. "/default/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = sharedthemes .. "/default/titlebar/floating_focus_active.png"
theme.titlebar_maximized_button_normal_inactive = sharedthemes .. "/default/titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = sharedthemes .. "/default/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = sharedthemes .. "/default/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = sharedthemes .. "/default/titlebar/maximized_focus_active.png"
-- You can use your own layout icons like this:
theme.layout_fairh = sharedthemes .. "/default/layouts/fairhw.png"
theme.layout_fairv = sharedthemes .. "/default/layouts/fairvw.png"
theme.layout_floating = sharedthemes .. "/default/layouts/floatingw.png"
theme.layout_magnifier = sharedthemes .. "/default/layouts/magnifierw.png"
theme.layout_max = sharedthemes .. "/default/layouts/maxw.png"
theme.layout_fullscreen = sharedthemes .. "/default/layouts/fullscreenw.png"
theme.layout_tilebottom = sharedthemes .. "/default/layouts/tilebottomw.png"
theme.layout_tileleft = sharedthemes .. "/default/layouts/tileleftw.png"
theme.layout_tile = sharedthemes .. "/default/layouts/tilew.png"
theme.layout_tiletop = sharedthemes .. "/default/layouts/tiletopw.png"
theme.layout_spiral = sharedthemes .. "/default/layouts/spiralw.png"
theme.layout_dwindle = sharedthemes .. "/default/layouts/dwindlew.png"
theme.awesome_icon = sharedicons .. "/awesome16.png"
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=80
|
-- bamboo, awesome3 theme, by zhuravlik, based on Zenburn
--{{{ Main
local awful = require("awful")
awful.util = require("awful.util")
theme = {}
home = os.getenv("HOME")
config = awful.util.getdir("config")
shared = "/usr/share/awesome"
if not awful.util.file_readable(shared .. "/icons/awesome16.png") then
shared = "/usr/share/local/awesome"
end
sharedicons = shared .. "/icons"
sharedthemes = shared .. "/themes"
themes = config .. "/themes"
themename = "/vinyl"
if not awful.util.file_readable(themes .. themename .. "/theme.lua") then
themes = sharedthemes
end
themedir = themes .. themename
wallpaper1 = themedir .. "/background.jpg"
wallpaper2 = themedir .. "/background.png"
wallpaper3 = sharedthemes .. "/zenburn/zenburn-background.png"
wallpaper4 = sharedthemes .. "/default/background.png"
wpscript = home .. "/.wallpaper"
if awful.util.file_readable(wallpaper1) then
theme.wallpaper = wallpaper1
elseif awful.util.file_readable(wallpaper2) then
theme.wallpaper = wallpaper2
elseif awful.util.file_readable(wpscript) then
theme.wallpaper_cmd = { "sh " .. wpscript }
elseif awful.util.file_readable(wallpaper3) then
theme.wallpaper = wallpaper3
else
theme.wallpaper = wallpaper4
end
if awful.util.file_readable(wallpaper1) then
theme.wallpaper_cmd = { "awsetbg " .. wallpaper1 }
elseif awful.util.file_readable(wallpaper2) then
theme.wallpaper_cmd = { "awsetbg " .. wallpaper2 }
elseif awful.util.file_readable(wpscript) then
theme.wallpaper_cmd = { "sh " .. wpscript }
elseif awful.util.file_readable(wallpaper3) then
theme.wallpaper_cmd = { "awsetbg " .. wallpaper3 }
else
theme.wallpaper_cmd = { "awsetbg " .. wallpaper4 }
end
if awful.util.file_readable(config .. "/vain/init.lua") then
theme.useless_gap_width = "3"
end
--}}}
theme.font = "anorexia 9"
theme.bg_normal = "#000001"
theme.bg_focus = "#000001"
theme.bg_urgent = "#000000"
theme.bg_minimize = "#000000"
theme.fg_normal = "#575757"
theme.fg_focus = "#D2D46B"
theme.fg_urgent = "#000000"
theme.fg_minimize = "#000000"
theme.border_width = "0"
theme.border_normal = "#000000"
theme.border_focus = "#000000"
theme.border_marked = "#000000"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- [taglist|tasklist]_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- Example:
--theme.taglist_bg_focus = "#ff0000"
-- Display the taglist squares
theme.taglist_squares_sel = sharedthemes .. "/default/taglist/squarefw.png"
theme.taglist_squares_unsel = sharedthemes .. "/default/taglist/squarew.png"
theme.tasklist_floating_icon = sharedthemes .. "/default/tasklist/floatingw.png"
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_submenu_icon = sharedthemes .. "/default/submenu.png"
theme.menu_height = "15"
theme.menu_width = "100"
-- You can add as many variables as
-- you wish and access them by using
-- beautiful.variable in your rc.lua
--theme.bg_widget = "#cc0000"
-- Define the image to load
theme.titlebar_close_button_normal = sharedthemes .. "/default/titlebar/close_normal.png"
theme.titlebar_close_button_focus = sharedthemes .. "/default/titlebar/close_focus.png"
theme.titlebar_ontop_button_normal_inactive = sharedthemes .. "/default/titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = sharedthemes .. "/default/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = sharedthemes .. "/default/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = sharedthemes .. "/default/titlebar/ontop_focus_active.png"
theme.titlebar_sticky_button_normal_inactive = sharedthemes .. "/default/titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = sharedthemes .. "/default/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = sharedthemes .. "/default/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = sharedthemes .. "/default/titlebar/sticky_focus_active.png"
theme.titlebar_floating_button_normal_inactive = sharedthemes .. "/default/titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = sharedthemes .. "/default/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = sharedthemes .. "/default/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = sharedthemes .. "/default/titlebar/floating_focus_active.png"
theme.titlebar_maximized_button_normal_inactive = sharedthemes .. "/default/titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = sharedthemes .. "/default/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = sharedthemes .. "/default/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = sharedthemes .. "/default/titlebar/maximized_focus_active.png"
-- You can use your own layout icons like this:
theme.layout_fairh = sharedthemes .. "/default/layouts/fairhw.png"
theme.layout_fairv = sharedthemes .. "/default/layouts/fairvw.png"
theme.layout_floating = sharedthemes .. "/default/layouts/floatingw.png"
theme.layout_magnifier = sharedthemes .. "/default/layouts/magnifierw.png"
theme.layout_max = sharedthemes .. "/default/layouts/maxw.png"
theme.layout_fullscreen = sharedthemes .. "/default/layouts/fullscreenw.png"
theme.layout_tilebottom = sharedthemes .. "/default/layouts/tilebottomw.png"
theme.layout_tileleft = sharedthemes .. "/default/layouts/tileleftw.png"
theme.layout_tile = sharedthemes .. "/default/layouts/tilew.png"
theme.layout_tiletop = sharedthemes .. "/default/layouts/tiletopw.png"
theme.layout_spiral = sharedthemes .. "/default/layouts/spiralw.png"
theme.layout_dwindle = sharedthemes .. "/default/layouts/dwindlew.png"
theme.awesome_icon = sharedicons .. "/awesome16.png"
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=80
|
fixed vinyl
|
fixed vinyl
|
Lua
|
mit
|
mikar/awesome34-themes
|
3aa2d29b34a79c75b8ce5680851410f2f6ac331c
|
kong_api_authz/src/kong/plugins/opa/access.lua
|
kong_api_authz/src/kong/plugins/opa/access.lua
|
local cjson_safe = require "cjson.safe"
local http = require "resty.http"
local jwt = require "resty.jwt"
-- string interpolation with named parameters in table
local function interp(s, tab)
return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end))
end
-- query "Get a Document (with Input)" endpoint from the OPA Data API
local function getDocument(input, conf)
-- serialize the input into a string containing the JSON representation
local json_body = assert(cjson_safe.encode({ input = input }))
local opa_uri = interp("${protocol}://${host}:${port}/${base_path}/${decision}", {
protocol = conf.server.protocol,
host = conf.server.host,
port = conf.server.port,
base_path = conf.policy.base_path,
decision = conf.policy.decision
})
local res, err = http.new():request_uri(opa_uri, {
method = "POST",
body = json_body,
headers = {
["Content-Type"] = "application/json",
},
keepalive_timeout = conf.server.connection.timeout,
keepalive_pool = conf.server.connection.pool
})
if err then
error(err) -- failed to request the endpoint
end
-- deserialise the response into a Lua table
return assert(cjson_safe.decode(res.body))
end
-- module
local _M = {}
function _M.execute(conf)
local authorization = ngx.var.http_authorization
-- decode JWT token
local token = {}
if authorization and string.find(authorization, "Bearer") then
local encoded_token = authorization:gsub("Bearer ", "")
token = jwt:load_jwt(encoded_token)
end
-- input document that will be send to opa
local input = {
token = token,
method = ngx.var.request_method,
path = ngx.var.upstream_uri,
}
local status, res = pcall(getDocument, input, conf)
if not status then
kong.log.err("Failed to get document: ", res)
return kong.response.exit(500, [[{"message":"Oops, something went wrong"}]])
end
-- when the policy fail, 'result' is omitted
if not res.result then
kong.log.info("Access forbidden")
return kong.response.exit(403, [[{"message":"Access Forbidden"}]])
end
-- access allowed
kong.log.debug(interp("Access allowed to ${method} ${path} for user ${subject}", {
method = input.method,
path = input.path,
subject = token.payload.sub
}))
end
return _M
|
local cjson_safe = require "cjson.safe"
local http = require "resty.http"
local jwt = require "resty.jwt"
-- string interpolation with named parameters in table
local function interp(s, tab)
return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end))
end
-- query "Get a Document (with Input)" endpoint from the OPA Data API
local function getDocument(input, conf)
-- serialize the input into a string containing the JSON representation
local json_body = assert(cjson_safe.encode({ input = input }))
local opa_uri = interp("${protocol}://${host}:${port}/${base_path}/${decision}", {
protocol = conf.server.protocol,
host = conf.server.host,
port = conf.server.port,
base_path = conf.policy.base_path,
decision = conf.policy.decision
})
local res, err = http.new():request_uri(opa_uri, {
method = "POST",
body = json_body,
headers = {
["Content-Type"] = "application/json",
},
keepalive_timeout = conf.server.connection.timeout,
keepalive_pool = conf.server.connection.pool
})
if err then
error(err) -- failed to request the endpoint
end
-- deserialise the response into a Lua table
return assert(cjson_safe.decode(res.body))
end
-- module
local _M = {}
function _M.execute(conf)
local authorization = ngx.var.http_authorization
-- decode JWT token
local token = {}
if authorization and string.find(authorization, "Bearer") then
local encoded_token = authorization:gsub("Bearer ", "")
token = jwt:load_jwt(encoded_token)
end
-- input document that will be send to opa
local input = {
token = token,
method = ngx.var.request_method,
path = ngx.var.upstream_uri,
}
local status, res = pcall(getDocument, input, conf)
if not status then
kong.log.err("Failed to get document: ", res)
return kong.response.exit(500, [[{"message":"Oops, something went wrong"}]])
end
-- when the policy fail, 'result' is omitted
if not res.result then
kong.log.info("Access forbidden")
return kong.response.exit(403, [[{"message":"Access Forbidden"}]])
end
-- access allowed
kong.log.debug(interp("Access allowed to ${method} ${path} for user ${subject}", {
method = input.method,
path = input.path,
subject = (token.payload and token.payload.sub or 'anonymous')
}))
end
return _M
|
kong_api_authz: Fix error when no JWT token is provided
|
kong_api_authz: Fix error when no JWT token is provided
When no token is provided with the request, the execution fail the attempt to index the field 'payload' (a nil value).
In case the subject from the JWT token is not be defined or there's no token, 'anonymous' will be used instead.
Fixes open-policy-agent/contrib#146
Signed-off-by: Younes Zahidi <72eed1b76a71c19c7380804f92c254bd3e36c5b0@users.noreply.github.com>
|
Lua
|
apache-2.0
|
open-policy-agent/contrib,open-policy-agent/contrib,open-policy-agent/contrib,open-policy-agent/contrib,open-policy-agent/contrib,open-policy-agent/contrib,open-policy-agent/contrib,open-policy-agent/contrib
|
51a30013f3a118daa4fdc35f982c1bfad99c9324
|
mimetypes.lua
|
mimetypes.lua
|
local mimetypes = {}
function mimetypes.getMime(ext)
if ext == ""
then
return mimetypes['mconf']['.html']['mime']
else
return mimetypes['mconf'][ext]['mime']
end
end
function mimetypes.isBinary(ext)
if ext == ""
then
return mimetypes['mconf']['.html']['bin']
else
return mimetypes['mconf'][ext]['bin']
end
end
mimetypes["mconf"] = {
[".html"] = {
["mime"] = "text/html",
["bin"] = false,
},
[".xml"] = {
["mime"] = "application/xml",
["bin"] = false,
},
[".txt"] = {
["mime"] = "text/plain",
["bin"] = false,
},
[".css"] = {
["mime"] = "text/css",
["bin"] = false,
},
[".js"] = {
["mime"] = "application/x-javascript",
["bin"] = false,
},
[".jpg"] = {
["mime"] = "image/jpeg",
["bin"] = true,
},
[".jpeg"] = {
["mime"] = "image/jpeg",
["bin"] = true,
},
[".png"] = {
["mime"] = "image/png",
["bin"] = true,
},
[".gif"] = {
["mime"] = "image/gif",
["bin"] = true,
},
[".ico"] = {
["mime"] = "image/x-icon",
["bin"] = true,
},
}
return mimetypes
|
local mimetypes = {}
function mimetypes.getMime(ext)
--print("mimetypes: ext=" .. ext)
if ext == "" or mimetypes['mconf'][ext] == nil
then
return "application/octet-stream"
else
return mimetypes['mconf'][ext]['mime']
end
end
function mimetypes.isBinary(ext)
if ext == "" or mimetypes['mconf'][ext] == nil
then
return false
else
return mimetypes['mconf'][ext]['bin']
end
end
mimetypes["mconf"] = {
[".html"] = {
["mime"] = "text/html",
["bin"] = false,
},
[".xml"] = {
["mime"] = "application/xml",
["bin"] = false,
},
[".txt"] = {
["mime"] = "text/plain",
["bin"] = false,
},
[".css"] = {
["mime"] = "text/css",
["bin"] = false,
},
[".js"] = {
["mime"] = "application/x-javascript",
["bin"] = false,
},
[".jpg"] = {
["mime"] = "image/jpeg",
["bin"] = true,
},
[".jpeg"] = {
["mime"] = "image/jpeg",
["bin"] = true,
},
[".png"] = {
["mime"] = "image/png",
["bin"] = true,
},
[".gif"] = {
["mime"] = "image/gif",
["bin"] = true,
},
[".ico"] = {
["mime"] = "image/x-icon",
["bin"] = true,
},
}
return mimetypes
|
fixes and improvoments in mimetypes.lua
|
fixes and improvoments in mimetypes.lua
|
Lua
|
mit
|
danielrempel/ladle
|
d8f2f5d50ec47abb3277c4d518de8febe54c459d
|
tacky/analysis/optimise.lua
|
tacky/analysis/optimise.lua
|
local builtins = require "tacky.analysis.resolve".builtins
local visitor = require "tacky.analysis.visitor"
--- Checks if a node has side effects
local function hasSideEffects(node)
local kind = node.tag
if kind == "number" or kind == "boolean" or kind == "string" or node.tag == "key" or kind == "symbol" then
-- Do nothing: this is a constant term after all
return false
elseif kind == "list" then
local first = node[1]
if first and first.tag == "symbol" then
local func = first.var
return func ~= builtins["lambda"] and func ~= builtins["quote"]
else
return true
end
else
error("Unknown type " .. tostring(kind))
end
end
--- Checks if a node is a constant
local function isConstant(node)
local kind = node.tag
return kind == "number" or kind == "boolean" or kind == "string" or node.tag == "key"
end
local function getVarEntry(varLookup, var)
local varEntry = varLookup[var]
if not varEntry then
varEntry = {
var = var,
usages = {},
defs = {},
active = false,
}
varLookup[var] = varEntry
end
return varEntry
end
--- Gather all definitions into the variable lookup
local function gatherDefinitions(nodes, varLookup)
varLookup = varLookup or {}
local function addDefinition(var, def)
local defs = getVarEntry(varLookup, var).defs
defs[#defs + 1] = def
end
visitor.visitBlock(nodes, 1, function(node)
if node.tag ~= "list" then return end
local first = node[1]
if not first or first.tag ~= "symbol" then return end
local func = first.var
if func == builtins["lambda"] then
for i = 1, node[2].n do
addDefinition(node[2][i].var, {
tag = "arg",
value = node[2][i],
node = node,
})
end
elseif func == builtins["set!"] then
addDefinition(node[2].var, {
tag = "set",
value = node[3],
node = node,
})
elseif func == builtins["define"] or func == builtins["define-macro"] then
addDefinition(node.defVar, {
tag = "define",
value = node[3],
node = node,
})
elseif func == builtins["define-native"] then
addDefinition(node.defVar, {
tag = "native",
node = node,
})
end
end)
return varLookup
end
--- Build a lookup of usages. Note, this will only visit "active" nodes: those
-- which have a side effect or are used somewhere else.
local function gatherUsages(nodes, varLookup)
local queue = {}
local function addUsage(var, user)
local varEntry = varLookup[var]
if varEntry == nil then return end
-- If never seen before then enqueue all definitions
if not varEntry.active then
varEntry.active = true
for i = 1, #varEntry.defs do
local defVal = varEntry.defs[i].value
if defVal then
queue[#queue + 1] = defVal
end
end
end
local usages = varEntry.usages
usages[#usages + 1] = usages
end
local function visit(node)
if node.tag == "symbol" then
addUsage(node.var, node)
return
elseif node.tag == "list" then
local first = node[1]
if not first or first.tag ~= "symbol" then return end
local func = first.var
if func == builtins["set!"] or func == builtins["define"] or func == builtins["define-macro"] then
if not hasSideEffects(node[3]) then
-- Skip the definition if it has no side effects
return false
else
local varEntry = varLookup[node.var]
-- varEntry may be nil for builtins
if varEntry and varEntry.active then
-- We've already visited this node so skip it
return false
end
end
end
end
end
for i = 1, #nodes do
local node = nodes[i]
if hasSideEffects(node) then
queue[#queue + 1] = node
end
end
while #queue > 0 do
local node = table.remove(queue, 1)
visitor.visitNode(node, visit)
end
end
return function(nodes)
-- Strip all import expressions
for i = #nodes, 1, -1 do
local node = nodes[i]
if node.tag == "list" then
local first = node[1]
if first and first.tag == "symbol" and first.var == builtins["import"] then
nodes.n = nodes.n - 1
table.remove(nodes, i)
end
end
end
local varLookup = {}
gatherDefinitions(nodes, varLookup)
gatherUsages(nodes, varLookup)
for i = #nodes, 1, -1 do
local node = nodes[i]
if not hasSideEffects(node) or (node.defVar and not varLookup[node.defVar].active) then
nodes.n = nodes.n - 1
table.remove(nodes, i)
end
end
return nodes
end
|
local builtins = require "tacky.analysis.resolve".builtins
local visitor = require "tacky.analysis.visitor"
--- Checks if a node has side effects
local function hasSideEffects(node)
local kind = node.tag
if kind == "number" or kind == "boolean" or kind == "string" or node.tag == "key" or kind == "symbol" then
-- Do nothing: this is a constant term after all
return false
elseif kind == "list" then
local first = node[1]
if first and first.tag == "symbol" then
local func = first.var
return func ~= builtins["lambda"] and func ~= builtins["quote"]
else
return true
end
else
error("Unknown type " .. tostring(kind))
end
end
--- Checks if a node is a constant
local function isConstant(node)
local kind = node.tag
return kind == "number" or kind == "boolean" or kind == "string" or node.tag == "key"
end
local function getVarEntry(varLookup, var)
local varEntry = varLookup[var]
if not varEntry then
varEntry = {
var = var,
usages = {},
defs = {},
active = false,
}
varLookup[var] = varEntry
end
return varEntry
end
--- Gather all definitions into the variable lookup
local function gatherDefinitions(nodes, varLookup)
varLookup = varLookup or {}
local function addDefinition(var, def)
local defs = getVarEntry(varLookup, var).defs
defs[#defs + 1] = def
end
visitor.visitBlock(nodes, 1, function(node)
if node.tag ~= "list" then return end
local first = node[1]
if not first or first.tag ~= "symbol" then return end
local func = first.var
if func == builtins["lambda"] then
for i = 1, node[2].n do
addDefinition(node[2][i].var, {
tag = "arg",
value = node[2][i],
node = node,
})
end
elseif func == builtins["set!"] then
addDefinition(node[2].var, {
tag = "set",
value = node[3],
node = node,
})
elseif func == builtins["define"] or func == builtins["define-macro"] then
addDefinition(node.defVar, {
tag = "define",
value = node[3],
node = node,
})
elseif func == builtins["define-native"] then
addDefinition(node.defVar, {
tag = "native",
node = node,
})
end
end)
return varLookup
end
--- Build a lookup of usages. Note, this will only visit "active" nodes: those
-- which have a side effect or are used somewhere else.
local function gatherUsages(nodes, varLookup)
local queue = {}
local function addUsage(var, user)
local varEntry = varLookup[var]
if varEntry == nil then return end
-- If never seen before then enqueue all definitions
if not varEntry.active then
varEntry.active = true
for i = 1, #varEntry.defs do
local defVal = varEntry.defs[i].value
if defVal then
queue[#queue + 1] = defVal
end
end
end
local usages = varEntry.usages
usages[#usages + 1] = usages
end
local function visit(node)
if node.tag == "symbol" then
addUsage(node.var, node)
return
elseif node.tag == "list" then
local first = node[1]
if not first or first.tag ~= "symbol" then return end
local func = first.var
if func == builtins["set!"] or func == builtins["define"] or func == builtins["define-macro"] then
if not hasSideEffects(node[3]) then
-- Skip the definition if it has no side effects
return false
else
local varEntry = varLookup[node.var]
-- varEntry may be nil for builtins
if varEntry and varEntry.active then
-- We've already visited this node so skip it
return false
end
end
end
end
end
for i = 1, #nodes do
queue[#queue + 1] = nodes[i]
end
while #queue > 0 do
local node = table.remove(queue, 1)
visitor.visitNode(node, visit)
end
end
return function(nodes)
-- Strip all import expressions
for i = #nodes, 1, -1 do
local node = nodes[i]
if node.tag == "list" then
local first = node[1]
if first and first.tag == "symbol" and first.var == builtins["import"] then
nodes.n = nodes.n - 1
table.remove(nodes, i)
end
end
end
for i = #nodes - 1, 1, -1 do
if not hasSideEffects(nodes[i]) then
nodes.n = nodes.n - 1
table.remove(nodes, i)
end
end
local varLookup = {}
gatherDefinitions(nodes, varLookup)
gatherUsages(nodes, varLookup)
for i = #nodes, 1, -1 do
local node = nodes[i]
if (node.defVar and not varLookup[node.defVar].active) then
if i == #nodes then
nodes[i] = { tag = "symbol", contents = "nil" }
else
nodes.n = nodes.n - 1
table.remove(nodes, i)
end
end
end
return nodes
end
|
Minor fixes to the optimiser
|
Minor fixes to the optimiser
|
Lua
|
bsd-3-clause
|
SquidDev/urn,SquidDev/urn
|
2ea61fcd5a59d688f37acaa87ebb04ca6873e818
|
share/lua/meta/art/03_lastfm.lua
|
share/lua/meta/art/03_lastfm.lua
|
--[[
Gets an artwork from last.fm
$Id$
Copyright © 2010 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Return the artwork
function fetch_art()
if vlc.item == nil then return nil end
local meta = vlc.item:metas()
if meta["Listing Type"] == "radio"
or meta["Listing Type"] == "tv"
then return nil end
if meta["artist"] and meta["album"] then
title = meta["artist"].."/"..meta["album"]
else
return nil
end
-- remove -.* from string
title = string.gsub( title, " ?%-.*", "" )
-- remove (info..) from string
title = string.gsub( title, "%(.*%)", "" )
-- remove CD2 etc from string
title = string.gsub( title, "CD%d+", "" )
-- remove Disc \w+ from string
title = string.gsub( title, "Disc %w+", "" )
fd = vlc.stream( "http://www.last.fm/music/" .. title )
if not fd then return nil end
page = fd:read( 65653 )
fd = nil
_, _, arturl = string.find( page, "<img width=\"174\" src=\"([^\"]+)\" class=\"art\" />\n" )
-- Don't use default album-art (not found one)
if not arturl or string.find( arturl, "default_album_mega.png") then
return nil
end
return arturl
end
|
--[[
Gets an artwork from last.fm
$Id$
Copyright © 2010 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Return the artwork
function fetch_art()
if vlc.item == nil then return nil end
local meta = vlc.item:metas()
if meta["Listing Type"] == "radio"
or meta["Listing Type"] == "tv"
then return nil end
if meta["artist"] and meta["album"] then
title = meta["artist"].."/"..meta["album"]
else
return nil
end
-- remove -.* from string
title = string.gsub( title, " ?%-.*", "" )
-- remove (info..) from string
title = string.gsub( title, "%(.*%)", "" )
-- remove CD2 etc from string
title = string.gsub( title, "CD%d+", "" )
-- remove Disc \w+ from string
title = string.gsub( title, "Disc %w+", "" )
fd = vlc.stream( "http://www.last.fm/music/" .. title )
if not fd then return nil end
page = fd:read( 65653 )
fd = nil
_, _, arturl = string.find( page, "<meta property=\"og:image\" content=\"([^\"]+)\" />" )
-- Don't use default album-art (not found one)
if not arturl or string.find( arturl, "default_album_mega.png") then
return nil
end
return arturl
end
|
lua: lastfm: fix matching
|
lua: lastfm: fix matching
(cherry picked from commit 4553ce6dac0b1aa9a46d6b033eb866581900f722)
Signed-off-by: Jean-Baptiste Kempf <[email protected]>
|
Lua
|
lgpl-2.1
|
jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1
|
d5008bf3d0cbdd812d5b34aaf73d15c9f0c4cbf7
|
packages/nn/LookupTable.lua
|
packages/nn/LookupTable.lua
|
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 2
function LookupTable:__init(nIndex, ...)
parent.__init(self)
if select('#', ...) == 1 and type(select(1, ...)) ~= "number" then
local size = select(1, ...)
self.size = torch.LongStorage(#size + 1)
for i=1,#size do
self.size[i+1] = size[i]
end
else
self.size = torch.LongStorage(select('#', ...)+1)
for i=1,select('#',...) do
self.size[i+1] = select(i, ...)
end
end
self.size[1] = nIndex
self.weight = torch.Tensor(self.size)
self.gradWeight = torch.Tensor(self.size)
self.currentInputs = {}
self:reset()
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:apply(function()
return random.normal(0, stdv)
end)
end
function LookupTable:forward(input)
local nIndex = input:size(1)
self.size[1] = nIndex
self.output:resize(self.size)
for i=1,nIndex do
self.output:select(1, i):copy(self.weight:select(1, input[i]))
end
return self.output
end
function LookupTable:zeroGradParameters()
for i=1,#self.currentInputs do
self.gradWeight:select(1, currentInput[i]):zero()
self.currentInputs[i] = nil
end
end
function LookupTable:accGradParameters(input, gradOutput, scale)
table.insert(self.currentInputs, input.new(input:size()):copy(input))
for i=1,input:size(1) do
self.gradWeight:select(1, input[i]):add(scale, gradOutput:select(1, i))
end
end
function LookupTable:accUpdateGradParameters(input, gradOutput, lr)
for i=1,input:size(1) do
self.weight:select(1, input[i]):add(-lr, gradOutput:select(1, i))
end
end
function LookupTable:updateParameters(learningRate)
for i=1,#self.currentInputs do
local currentInput = self.currentInputs[i]
local currentGradWeight = self.currentGradWeights[i]
for i=1,currentInput:size(1) do
self.weight:select(1, currentInput[i]):add(-learningRate, self.gradWeight:select(1, currentInput[i]))
end
end
end
|
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 2
function LookupTable:__init(nIndex, ...)
parent.__init(self)
if select('#', ...) == 1 and type(select(1, ...)) ~= "number" then
local size = select(1, ...)
self.size = torch.LongStorage(#size + 1)
for i=1,#size do
self.size[i+1] = size[i]
end
else
self.size = torch.LongStorage(select('#', ...)+1)
for i=1,select('#',...) do
self.size[i+1] = select(i, ...)
end
end
self.size[1] = nIndex
self.weight = torch.Tensor(self.size)
self.gradWeight = torch.Tensor(self.size)
self.currentInputs = {}
self:reset()
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:apply(function()
return random.normal(0, stdv)
end)
end
function LookupTable:forward(input)
local nIndex = input:size(1)
self.size[1] = nIndex
self.output:resize(self.size)
for i=1,nIndex do
self.output:select(1, i):copy(self.weight:select(1, input[i]))
end
return self.output
end
function LookupTable:zeroGradParameters()
for i=1,#self.currentInputs do
local currentInput = self.currentInputs[i]
for i=1,currentInput:size(1) do
self.gradWeight:select(1, currentInput[i]):zero()
end
self.currentInputs[i] = nil
end
end
function LookupTable:accGradParameters(input, gradOutput, scale)
table.insert(self.currentInputs, input.new(input:size()):copy(input))
for i=1,input:size(1) do
self.gradWeight:select(1, input[i]):add(scale, gradOutput:select(1, i))
end
end
function LookupTable:accUpdateGradParameters(input, gradOutput, lr)
for i=1,input:size(1) do
self.weight:select(1, input[i]):add(-lr, gradOutput:select(1, i))
end
end
function LookupTable:updateParameters(learningRate)
for i=1,#self.currentInputs do
local currentInput = self.currentInputs[i]
for i=1,currentInput:size(1) do
self.weight:select(1, currentInput[i]):add(-learningRate, self.gradWeight:select(1, currentInput[i]))
end
end
end
|
bug corrections in LookupTable @#$%^&*()
|
bug corrections in LookupTable @#$%^&*()
|
Lua
|
bsd-3-clause
|
soumith/TH,soumith/TH,soumith/TH,soumith/TH
|
8b470280735545982a32ead11c6d9f9245a65dea
|
xmake/scripts/base/rule.lua
|
xmake/scripts/base/rule.lua
|
--!The Automatic Cross-platform Build Tool
--
-- XMake is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
--
-- XMake is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2009 - 2015, ruki All rights reserved.
--
-- @author ruki
-- @file rule.lua
--
-- define module: rule
local rule = rule or {}
-- load modules
local os = require("base/os")
local path = require("base/path")
local table = require("base/table")
local utils = require("base/utils")
local config = require("base/config")
local platform = require("platform/platform")
-- get the building log file path
function rule.logfile()
-- the logdir
local logdir = config.get("buildir") or os.tmpdir()
assert(logdir)
-- get it
return path.translate(logdir .. "/.build.log")
end
-- get the filename from the given name and kind
function rule.filename(name, kind)
-- check
assert(name and kind)
-- get format
local format = platform.format(kind) or {"", ""}
-- make it
return format[1] .. name .. format[2]
end
-- get configure file for the given target
function rule.config_h(target)
-- get the target configure file
local config_h = target.config_h
if config_h then
-- translate file path
if not path.is_absolute(config_h) then
config_h = path.absolute(config_h, xmake._PROJECT_DIR)
else
config_h = path.translate(config_h)
end
end
-- ok?
return config_h
end
-- get the temporary backup directory for package
function rule.backupdir(target_name, arch)
-- the temporary directory
local tmpdir = os.tmpdir()
assert(tmpdir)
-- the project name
local project_name = path.basename(xmake._PROJECT_DIR)
assert(project_name)
-- make it
return string.format("%s/.xmake/%s/pkgfiles/%s/%s", tmpdir, project_name, target_name, arch)
end
-- get target file for the given target
function rule.targetfile(target_name, target, buildir)
-- check
assert(target_name and target and target.kind)
-- the target directory
local targetdir = target.targetdir or buildir or config.get("buildir")
assert(targetdir and type(targetdir) == "string")
-- the target file name
local filename = rule.filename(target_name, target.kind)
assert(filename)
-- make the target file path
return targetdir .. "/" .. filename
end
-- get object files for the given source files
function rule.objectdir(target_name, target, buildir)
-- check
assert(target_name and target)
-- the object directory
local objectdir = target.objectdir
if not objectdir then
-- the build directory
if not buildir then
buildir = config.get("buildir")
end
assert(buildir)
-- make the default object directory
objectdir = buildir .. "/.objs"
end
-- ok?
return objectdir
end
-- get object files for the given source files
function rule.objectfiles(target_name, target, sourcefiles, buildir)
-- check
assert(target_name and target and sourcefiles)
-- the object directory
local objectdir = rule.objectdir(target_name, target, buildir)
assert(objectdir and type(objectdir) == "string")
-- make object files
local i = 1
local objectfiles = {}
for _, sourcefile in ipairs(sourcefiles) do
-- make object file
local objectfile = string.format("%s/%s/%s/%s", objectdir, target_name, path.directory(sourcefile), rule.filename(path.basename(sourcefile), "object"))
-- save it
objectfiles[i] = path.translate(objectfile)
i = i + 1
end
-- ok?
return objectfiles
end
-- get the source files from the given target
function rule.sourcefiles(target)
-- check
assert(target)
-- no files?
if not target.files then
return {}
end
-- wrap files first
local targetfiles = utils.wrap(target.files)
-- match files
local i = 1
local sourcefiles = {}
for _, targetfile in ipairs(targetfiles) do
-- match source files
local files = os.match(targetfile)
-- process source files
for _, file in ipairs(files) do
-- convert to the relative path
if path.is_absolute(file) then
file = path.relative(file, xmake._PROJECT_DIR)
end
-- save it
sourcefiles[i] = file
i = i + 1
end
end
-- remove repeat files
sourcefiles = utils.unique(sourcefiles)
-- ok?
return sourcefiles
end
-- get the header files from the given target
function rule.headerfiles(target, headerdir)
-- check
assert(target)
-- no headers?
local headers = target.headers
if not headers then return end
-- get the headerdir
if not headerdir then headerdir = target.headerdir or config.get("buildir") end
assert(headerdir)
-- get the source pathes and destinate pathes
local srcheaders = {}
local dstheaders = {}
for _, header in ipairs(utils.wrap(headers)) do
-- get the root directory
local rootdir = header:gsub("%(.*%)", ""):gsub("|.*$", "")
-- remove '(' and ')'
local srcpathes = header:gsub("[%(%)]", "")
if srcpathes then
-- get the source pathes
srcpathes = os.match(srcpathes)
if srcpathes then
-- add the source headers
table.join2(srcheaders, srcpathes)
-- add the destinate headers
for _, srcpath in ipairs(srcpathes) do
-- the header
local dstheader = path.absolute(path.relative(srcpath, rootdir), headerdir)
assert(dstheader)
-- add it
table.insert(dstheaders, dstheader)
end
end
end
end
-- ok?
return srcheaders, dstheaders
end
-- return module: rule
return rule
|
--!The Automatic Cross-platform Build Tool
--
-- XMake is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
--
-- XMake is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2009 - 2015, ruki All rights reserved.
--
-- @author ruki
-- @file rule.lua
--
-- define module: rule
local rule = rule or {}
-- load modules
local os = require("base/os")
local path = require("base/path")
local table = require("base/table")
local utils = require("base/utils")
local config = require("base/config")
local platform = require("platform/platform")
-- get the building log file path
function rule.logfile()
-- the logdir
local logdir = config.get("buildir") or os.tmpdir()
assert(logdir)
-- get it
return path.translate(logdir .. "/.build.log")
end
-- get the filename from the given name and kind
function rule.filename(name, kind)
-- check
assert(name and kind)
-- get format
local format = platform.format(kind) or {"", ""}
-- make it
return format[1] .. name .. format[2]
end
-- get configure file for the given target
function rule.config_h(target)
-- get the target configure file
local config_h = target.config_h
if config_h then
-- translate file path
if not path.is_absolute(config_h) then
config_h = path.absolute(config_h, xmake._PROJECT_DIR)
else
config_h = path.translate(config_h)
end
end
-- ok?
return config_h
end
-- get the temporary backup directory for package
function rule.backupdir(target_name, arch)
-- the temporary directory
local tmpdir = os.tmpdir()
assert(tmpdir)
-- the project name
local project_name = path.basename(xmake._PROJECT_DIR)
assert(project_name)
-- make it
return string.format("%s/.xmake/%s/pkgfiles/%s/%s", tmpdir, project_name, target_name, arch)
end
-- get target file for the given target
function rule.targetfile(target_name, target, buildir)
-- check
assert(target_name and target and target.kind)
-- the target directory
local targetdir = target.targetdir or buildir or config.get("buildir")
assert(targetdir and type(targetdir) == "string")
-- the target file name
local filename = rule.filename(target_name, target.kind)
assert(filename)
-- make the target file path
return targetdir .. "/" .. filename
end
-- get object files for the given source files
function rule.objectdir(target_name, target, buildir)
-- check
assert(target_name and target)
-- the object directory
local objectdir = target.objectdir
if not objectdir then
-- the build directory
if not buildir then
buildir = config.get("buildir")
end
assert(buildir)
-- make the default object directory
objectdir = buildir .. "/.objs"
end
-- ok?
return objectdir
end
-- get object files for the given source files
function rule.objectfiles(target_name, target, sourcefiles, buildir)
-- check
assert(target_name and target and sourcefiles)
-- the object directory
local objectdir = rule.objectdir(target_name, target, buildir)
assert(objectdir and type(objectdir) == "string")
-- make object files
local i = 1
local objectfiles = {}
for _, sourcefile in ipairs(sourcefiles) do
-- make object file
local objectfile = string.format("%s/%s/%s/%s", objectdir, target_name, path.directory(sourcefile), rule.filename(path.basename(sourcefile), "object"))
-- translate path
--
-- .e.g
--
-- src/xxx.c
-- project/xmake.lua
-- build/.objs
--
-- objectfile: project/build/.objs/xxxx/../../xxx.c will be out of range for objectdir
--
-- we need replace '..' to '__' in this case
--
objectfile = (path.translate(objectfile):gsub("%.%.", "__"))
-- save it
objectfiles[i] = objectfile
i = i + 1
end
-- ok?
return objectfiles
end
-- get the source files from the given target
function rule.sourcefiles(target)
-- check
assert(target)
-- no files?
if not target.files then
return {}
end
-- wrap files first
local targetfiles = utils.wrap(target.files)
-- match files
local i = 1
local sourcefiles = {}
for _, targetfile in ipairs(targetfiles) do
-- match source files
local files = os.match(targetfile)
-- process source files
for _, file in ipairs(files) do
-- convert to the relative path
if path.is_absolute(file) then
file = path.relative(file, xmake._PROJECT_DIR)
end
-- save it
sourcefiles[i] = file
i = i + 1
end
end
-- remove repeat files
sourcefiles = utils.unique(sourcefiles)
-- ok?
return sourcefiles
end
-- get the header files from the given target
function rule.headerfiles(target, headerdir)
-- check
assert(target)
-- no headers?
local headers = target.headers
if not headers then return end
-- get the headerdir
if not headerdir then headerdir = target.headerdir or config.get("buildir") end
assert(headerdir)
-- get the source pathes and destinate pathes
local srcheaders = {}
local dstheaders = {}
for _, header in ipairs(utils.wrap(headers)) do
-- get the root directory
local rootdir = header:gsub("%(.*%)", ""):gsub("|.*$", "")
-- remove '(' and ')'
local srcpathes = header:gsub("[%(%)]", "")
if srcpathes then
-- get the source pathes
srcpathes = os.match(srcpathes)
if srcpathes then
-- add the source headers
table.join2(srcheaders, srcpathes)
-- add the destinate headers
for _, srcpath in ipairs(srcpathes) do
-- the header
local dstheader = path.absolute(path.relative(srcpath, rootdir), headerdir)
assert(dstheader)
-- add it
table.insert(dstheaders, dstheader)
end
end
end
end
-- ok?
return srcheaders, dstheaders
end
-- return module: rule
return rule
|
fix object file path bug
|
fix object file path bug
|
Lua
|
apache-2.0
|
tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake
|
0e5de8a6148b12508e3dbcc1a68f39475a33721c
|
ffi/framebuffer_android.lua
|
ffi/framebuffer_android.lua
|
local ffi = require("ffi")
local android = require("android")
local BB = require("ffi/blitbuffer")
local C = ffi.C
--[[ configuration for devices with an electric paper display controller ]]--
-- does the device has an e-ink screen?
local has_eink_screen, eink_platform = android.isEink()
-- does the device needs to handle all screen refreshes
local has_eink_full_support = android.isEinkFull()
local full, partial, full_ui, partial_ui, fast, delay_page, delay_ui, delay_fast = android.getEinkConstants()
local framebuffer = {}
-- update a region of the screen
function framebuffer:_updatePartial(mode, delay, x, y, w, h)
local bb = self.full_bb or self.bb
w, x = BB.checkBounds(w or bb:getWidth(), x or 0, 0, bb:getWidth(), 0xFFFF)
h, y = BB.checkBounds(h or bb:getHeight(), y or 0, 0, bb:getHeight(), 0xFFFF)
x, y, w, h = bb:getPhysicalRect(x, y, w, h)
android.einkUpdate(mode, delay, x, y, (x + w), (y + h))
end
-- update the entire screen
function framebuffer:_updateFull()
-- freescale ntx platform
if has_eink_screen and (eink_platform == "freescale" or eink_platform == "qualcomm") then
if has_eink_full_support then
-- we handle the screen entirely
self:_updatePartial(full, delay_page)
else
-- we're racing against system driver. Let the system win and apply
-- a full update after it.
self:_updatePartial(full, 500)
end
-- rockchip rk3x platform
elseif has_eink_screen and (eink_platform == "rockchip") then
android.einkUpdate(full)
end
end
function framebuffer:init()
-- we present this buffer to the outside
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
self.bb:fill(BB.COLOR_WHITE)
self:_updateWindow()
framebuffer.parent.init(self)
end
-- resize on rotation or split view.
function framebuffer:resize()
android.screen.width = android.getScreenWidth()
android.screen.height = android.getScreenHeight()
local rotation
local inverse
if self.bb then
rotation = self.bb:getRotation()
inverse = self.bb:getInverse() == 1
self.bb:free()
end
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
-- Rotation and inverse must be inherited
if rotation then
self.bb:setRotation(rotation)
end
if inverse then
self.bb:invert()
end
self.bb:fill(inverse and BB.COLOR_BLACK or BB.COLOR_WHITE)
self:_updateWindow()
end
function framebuffer:getRotationMode()
if android.hasNativeRotation() then
return android.orientation.get()
else
return self.cur_rotation_mode
end
end
function framebuffer:setRotationMode(mode)
if android.hasNativeRotation() then
local key
if mode == 0 then key = "PORTRAIT"
elseif mode == 1 then key = "LANDSCAPE"
elseif mode == 2 then key = "REVERSE_PORTRAIT"
elseif mode == 3 then key = "REVERSE_LANDSCAPE" end
if key then
android.orientation.set(C["ASCREEN_ORIENTATION_" .. key])
end
else
framebuffer.parent.setRotationMode(self, mode)
end
end
function framebuffer:_updateWindow()
if android.app.window == nil then
android.LOGW("cannot blit: no window")
return
end
local buffer = ffi.new("ANativeWindow_Buffer[1]")
if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then
android.LOGW("Unable to lock window buffer")
return
end
local bb = nil
if buffer[0].format == C.WINDOW_FORMAT_RGBA_8888
or buffer[0].format == C.WINDOW_FORMAT_RGBX_8888
then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4, buffer[0].stride)
elseif buffer[0].format == C.WINDOW_FORMAT_RGB_565 then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2, buffer[0].stride)
else
android.LOGE("unsupported window format!")
end
if bb then
local ext_bb = self.full_bb or self.bb
-- Rotations and inverse are applied in the base ffi/framebuffer class, so our shadow buffer is already inverted and rotated.
-- All we need is to do is simply clone the invert and rotation settings, so that the blit below becomes 1:1 copy.
bb:setInverse(ext_bb:getInverse())
bb:setRotation(ext_bb:getRotation())
-- getUseCBB should *always* be true on Android, but let's be thorough...
if bb:getInverse() == 1 and BB:getUseCBB() then
-- If we're using the CBB (which we should), the invert flag has been thoroughly ignored up until now,
-- so, simply invert everything *now* ;).
-- The idea is that we absolutely want to avoid the Lua BB on Android, because it is *extremely* erratic,
-- because of the mcode alloc issues...
bb:invertblitFrom(ext_bb)
else
bb:blitFrom(ext_bb)
end
end
android.lib.ANativeWindow_unlockAndPost(android.app.window);
end
function framebuffer:refreshFullImp(x, y, w, h) -- luacheck: ignore
self:_updateWindow()
self:_updateFull()
end
function framebuffer:refreshPartialImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(partial, delay_page, x, y, w, h)
end
end
function framebuffer:refreshFlashPartialImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(full, delay_page, x, y, w, h)
end
end
function framebuffer:refreshUIImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(partial_ui, delay_ui, x, y, w, h)
end
end
function framebuffer:refreshFlashUIImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(full_ui, delay_ui, x, y, w, h)
end
end
function framebuffer:refreshFastImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(fast, delay_fast, x, y, w, h)
end
end
return require("ffi/framebuffer"):extend(framebuffer)
|
local ffi = require("ffi")
local android = require("android")
local BB = require("ffi/blitbuffer")
local C = ffi.C
--[[ configuration for devices with an electric paper display controller ]]--
-- does the device has an e-ink screen?
local has_eink_screen, eink_platform = android.isEink()
-- does the device needs to handle all screen refreshes
local has_eink_full_support = android.isEinkFull()
local full, partial, full_ui, partial_ui, fast, delay_page, delay_ui, delay_fast = android.getEinkConstants()
local framebuffer = {}
-- update a region of the screen
function framebuffer:_updatePartial(mode, delay, x, y, w, h)
local bb = self.full_bb or self.bb
w, x = BB.checkBounds(w or bb:getWidth(), x or 0, 0, bb:getWidth(), 0xFFFF)
h, y = BB.checkBounds(h or bb:getHeight(), y or 0, 0, bb:getHeight(), 0xFFFF)
x, y, w, h = bb:getPhysicalRect(x, y, w, h)
android.einkUpdate(mode, delay, x, y, (x + w), (y + h))
end
-- update the entire screen
function framebuffer:_updateFull()
-- freescale ntx platform
if has_eink_screen and (eink_platform == "freescale" or eink_platform == "qualcomm") then
if has_eink_full_support then
-- we handle the screen entirely
self:_updatePartial(full, delay_page)
else
-- we're racing against system driver. Let the system win and apply
-- a full update after it.
self:_updatePartial(full, 500)
end
-- rockchip rk3x platform
elseif has_eink_screen and (eink_platform == "rockchip") then
android.einkUpdate(full)
end
end
function framebuffer:init()
-- we present this buffer to the outside
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
self.bb:fill(BB.COLOR_WHITE)
self:_updateWindow()
framebuffer.parent.init(self)
end
-- resize on rotation or split view.
function framebuffer:resize()
android.screen.width = android.getScreenWidth()
android.screen.height = android.getScreenHeight()
local rotation
local inverse
if self.bb then
rotation = self.bb:getRotation()
inverse = self.bb:getInverse() == 1
self.bb:free()
end
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
-- Rotation and inverse must be inherited
if rotation then
self.bb:setRotation(rotation)
end
if inverse then
self.bb:invert()
end
self.bb:fill(inverse and BB.COLOR_BLACK or BB.COLOR_WHITE)
self:_updateWindow()
end
function framebuffer:getRotationMode()
if android.hasNativeRotation() then
return android.orientation.get()
else
return self.cur_rotation_mode
end
end
function framebuffer:setRotationMode(mode)
if android.hasNativeRotation() then
local key
if mode == 0 then key = "PORTRAIT"
elseif mode == 1 then key = "LANDSCAPE"
elseif mode == 2 then key = "REVERSE_PORTRAIT"
elseif mode == 3 then key = "REVERSE_LANDSCAPE" end
if key then
android.orientation.set(C["ASCREEN_ORIENTATION_" .. key])
end
else
framebuffer.parent.setRotationMode(self, mode)
end
end
function framebuffer:_updateWindow()
if android.app.window == nil then
android.LOGW("cannot blit: no window")
return
end
local buffer = ffi.new("ANativeWindow_Buffer[1]")
if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then
android.LOGW("Unable to lock window buffer")
return
end
local bb = nil
if buffer[0].format == C.WINDOW_FORMAT_RGBA_8888
or buffer[0].format == C.WINDOW_FORMAT_RGBX_8888
then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4, buffer[0].stride)
elseif buffer[0].format == C.WINDOW_FORMAT_RGB_565 then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2, buffer[0].stride)
else
android.LOGE("unsupported window format!")
end
if bb then
local ext_bb = self.full_bb or self.bb
-- Rotations and inverse are applied in the base ffi/framebuffer class, so our shadow buffer is already inverted and rotated.
-- All we need is to do is simply clone the invert and rotation settings, so that the blit below becomes 1:1 copy.
bb:setInverse(ext_bb:getInverse())
bb:setRotation(ext_bb:getRotation())
-- getUseCBB should *always* be true on Android, but let's be thorough...
if bb:getInverse() == 1 and BB:getUseCBB() then
-- If we're using the CBB (which we should), the invert flag has been thoroughly ignored up until now,
-- so, simply invert everything *now* ;).
-- The idea is that we absolutely want to avoid the Lua BB on Android, because it is *extremely* erratic,
-- because of the mcode alloc issues...
-- NOTE: CBB's invertblitFrom requires source & dest bb to be of the same type!
if bb:getType() == ext_bb:getType() then
-- In practice, this means RGB32, because our self.bb is always RGB32 (c.f., init above)
bb:invertblitFrom(ext_bb)
else
-- On ther other hand, if the window buffer is RGB565, things become uglier...
bb:blitFrom(ext_bb)
-- Fair warning, this is inaccurate for anything that isn't pure black or white on RGB565 ;).
bb:invertRect(0, 0, bb:getWidth(), bb:getHeight())
end
else
bb:blitFrom(ext_bb)
end
end
android.lib.ANativeWindow_unlockAndPost(android.app.window);
end
function framebuffer:refreshFullImp(x, y, w, h) -- luacheck: ignore
self:_updateWindow()
self:_updateFull()
end
function framebuffer:refreshPartialImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(partial, delay_page, x, y, w, h)
end
end
function framebuffer:refreshFlashPartialImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(full, delay_page, x, y, w, h)
end
end
function framebuffer:refreshUIImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(partial_ui, delay_ui, x, y, w, h)
end
end
function framebuffer:refreshFlashUIImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(full_ui, delay_ui, x, y, w, h)
end
end
function framebuffer:refreshFastImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(fast, delay_fast, x, y, w, h)
end
end
return require("ffi/framebuffer"):extend(framebuffer)
|
Android: Fix nighmode on devices w/ RGB565 windows w/ the C blitter (#1293)
|
Android: Fix nighmode on devices w/ RGB565 windows w/ the C blitter (#1293)
The CBB can't do an invertBlitFrom if source & dest type don't match, so, do it another way in these instances ;).
|
Lua
|
agpl-3.0
|
Frenzie/koreader-base,Frenzie/koreader-base,koreader/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base
|
26eba4bcfdb3de662c16f359f66e4240fc9283d4
|
src/luarocks/core/vers.lua
|
src/luarocks/core/vers.lua
|
local vers = {}
local util = require("luarocks.core.util")
local require = nil
--------------------------------------------------------------------------------
local deltas = {
scm = 1100,
cvs = 1000,
rc = -1000,
pre = -10000,
beta = -100000,
alpha = -1000000
}
local version_mt = {
--- Equality comparison for versions.
-- All version numbers must be equal.
-- If both versions have revision numbers, they must be equal;
-- otherwise the revision number is ignored.
-- @param v1 table: version table to compare.
-- @param v2 table: version table to compare.
-- @return boolean: true if they are considered equivalent.
__eq = function(v1, v2)
if #v1 ~= #v2 then
return false
end
for i = 1, #v1 do
if v1[i] ~= v2[i] then
return false
end
end
if v1.revision and v2.revision then
return (v1.revision == v2.revision)
end
return true
end,
--- Size comparison for versions.
-- All version numbers are compared.
-- If both versions have revision numbers, they are compared;
-- otherwise the revision number is ignored.
-- @param v1 table: version table to compare.
-- @param v2 table: version table to compare.
-- @return boolean: true if v1 is considered lower than v2.
__lt = function(v1, v2)
for i = 1, math.max(#v1, #v2) do
local v1i, v2i = v1[i] or 0, v2[i] or 0
if v1i ~= v2i then
return (v1i < v2i)
end
end
if v1.revision and v2.revision then
return (v1.revision < v2.revision)
end
return false
end
}
local version_cache = {}
setmetatable(version_cache, {
__mode = "kv"
})
--- Parse a version string, converting to table format.
-- A version table contains all components of the version string
-- converted to numeric format, stored in the array part of the table.
-- If the version contains a revision, it is stored numerically
-- in the 'revision' field. The original string representation of
-- the string is preserved in the 'string' field.
-- Returned version tables use a metatable
-- allowing later comparison through relational operators.
-- @param vstring string: A version number in string format.
-- @return table or nil: A version table or nil
-- if the input string contains invalid characters.
function vers.parse_version(vstring)
if not vstring then return nil end
assert(type(vstring) == "string")
local cached = version_cache[vstring]
if cached then
return cached
end
local version = {}
local i = 1
local function add_token(number)
version[i] = version[i] and version[i] + number/100000 or number
i = i + 1
end
-- trim leading and trailing spaces
vstring = vstring:match("^%s*(.*)%s*$")
version.string = vstring
-- store revision separately if any
local main, revision = vstring:match("(.*)%-(%d+)$")
if revision then
vstring = main
version.revision = tonumber(revision)
end
while #vstring > 0 do
-- extract a number
local token, rest = vstring:match("^(%d+)[%.%-%_]*(.*)")
if token then
add_token(tonumber(token))
else
-- extract a word
token, rest = vstring:match("^(%a+)[%.%-%_]*(.*)")
if not token then
util.printerr("Warning: version number '"..vstring.."' could not be parsed.")
version[i] = 0
break
end
version[i] = deltas[token] or (token:byte() / 1000)
end
vstring = rest
end
setmetatable(version, version_mt)
version_cache[vstring] = version
return version
end
--- Utility function to compare version numbers given as strings.
-- @param a string: one version.
-- @param b string: another version.
-- @return boolean: True if a > b.
function vers.compare_versions(a, b)
return vers.parse_version(a) > vers.parse_version(b)
end
--- A more lenient check for equivalence between versions.
-- This returns true if the requested components of a version
-- match and ignore the ones that were not given. For example,
-- when requesting "2", then "2", "2.1", "2.3.5-9"... all match.
-- When requesting "2.1", then "2.1", "2.1.3" match, but "2.2"
-- doesn't.
-- @param version string or table: Version to be tested; may be
-- in string format or already parsed into a table.
-- @param requested string or table: Version requested; may be
-- in string format or already parsed into a table.
-- @return boolean: True if the tested version matches the requested
-- version, false otherwise.
local function partial_match(version, requested)
assert(type(version) == "string" or type(version) == "table")
assert(type(requested) == "string" or type(version) == "table")
if type(version) ~= "table" then version = vers.parse_version(version) end
if type(requested) ~= "table" then requested = vers.parse_version(requested) end
if not version or not requested then return false end
for i, ri in ipairs(requested) do
local vi = version[i] or 0
if ri ~= vi then return false end
end
if requested.revision then
return requested.revision == version.revision
end
return true
end
--- Check if a version satisfies a set of constraints.
-- @param version table: A version in table format
-- @param constraints table: An array of constraints in table format.
-- @return boolean: True if version satisfies all constraints,
-- false otherwise.
function vers.match_constraints(version, constraints)
assert(type(version) == "table")
assert(type(constraints) == "table")
local ok = true
setmetatable(version, version_mt)
for _, constr in pairs(constraints) do
if type(constr.version) == "string" then
constr.version = vers.parse_version(constr.version)
end
local constr_version, constr_op = constr.version, constr.op
setmetatable(constr_version, version_mt)
if constr_op == "==" then ok = version == constr_version
elseif constr_op == "~=" then ok = version ~= constr_version
elseif constr_op == ">" then ok = version > constr_version
elseif constr_op == "<" then ok = version < constr_version
elseif constr_op == ">=" then ok = version >= constr_version
elseif constr_op == "<=" then ok = version <= constr_version
elseif constr_op == "~>" then ok = partial_match(version, constr_version)
end
if not ok then break end
end
return ok
end
return vers
|
local vers = {}
local util = require("luarocks.core.util")
local require = nil
--------------------------------------------------------------------------------
local deltas = {
scm = 1100,
cvs = 1000,
rc = -1000,
pre = -10000,
beta = -100000,
alpha = -1000000
}
local version_mt = {
--- Equality comparison for versions.
-- All version numbers must be equal.
-- If both versions have revision numbers, they must be equal;
-- otherwise the revision number is ignored.
-- @param v1 table: version table to compare.
-- @param v2 table: version table to compare.
-- @return boolean: true if they are considered equivalent.
__eq = function(v1, v2)
if #v1 ~= #v2 then
return false
end
for i = 1, #v1 do
if v1[i] ~= v2[i] then
return false
end
end
if v1.revision and v2.revision then
return (v1.revision == v2.revision)
end
return true
end,
--- Size comparison for versions.
-- All version numbers are compared.
-- If both versions have revision numbers, they are compared;
-- otherwise the revision number is ignored.
-- @param v1 table: version table to compare.
-- @param v2 table: version table to compare.
-- @return boolean: true if v1 is considered lower than v2.
__lt = function(v1, v2)
for i = 1, math.max(#v1, #v2) do
local v1i, v2i = v1[i] or 0, v2[i] or 0
if v1i ~= v2i then
return (v1i < v2i)
end
end
if v1.revision and v2.revision then
return (v1.revision < v2.revision)
end
return false
end
}
local version_cache = {}
setmetatable(version_cache, {
__mode = "kv"
})
--- Parse a version string, converting to table format.
-- A version table contains all components of the version string
-- converted to numeric format, stored in the array part of the table.
-- If the version contains a revision, it is stored numerically
-- in the 'revision' field. The original string representation of
-- the string is preserved in the 'string' field.
-- Returned version tables use a metatable
-- allowing later comparison through relational operators.
-- @param vstring string: A version number in string format.
-- @return table or nil: A version table or nil
-- if the input string contains invalid characters.
function vers.parse_version(vstring)
if not vstring then return nil end
assert(type(vstring) == "string")
local cached = version_cache[vstring]
if cached then
return cached
end
local version = {}
local i = 1
local function add_token(number)
version[i] = version[i] and version[i] + number/100000 or number
i = i + 1
end
-- trim leading and trailing spaces
local v = vstring:match("^%s*(.*)%s*$")
version.string = v
-- store revision separately if any
local main, revision = v:match("(.*)%-(%d+)$")
if revision then
v = main
version.revision = tonumber(revision)
end
while #v > 0 do
-- extract a number
local token, rest = v:match("^(%d+)[%.%-%_]*(.*)")
if token then
add_token(tonumber(token))
else
-- extract a word
token, rest = v:match("^(%a+)[%.%-%_]*(.*)")
if not token then
util.printerr("Warning: version number '"..v.."' could not be parsed.")
version[i] = 0
break
end
version[i] = deltas[token] or (token:byte() / 1000)
end
v = rest
end
setmetatable(version, version_mt)
version_cache[vstring] = version
return version
end
--- Utility function to compare version numbers given as strings.
-- @param a string: one version.
-- @param b string: another version.
-- @return boolean: True if a > b.
function vers.compare_versions(a, b)
return vers.parse_version(a) > vers.parse_version(b)
end
--- A more lenient check for equivalence between versions.
-- This returns true if the requested components of a version
-- match and ignore the ones that were not given. For example,
-- when requesting "2", then "2", "2.1", "2.3.5-9"... all match.
-- When requesting "2.1", then "2.1", "2.1.3" match, but "2.2"
-- doesn't.
-- @param version string or table: Version to be tested; may be
-- in string format or already parsed into a table.
-- @param requested string or table: Version requested; may be
-- in string format or already parsed into a table.
-- @return boolean: True if the tested version matches the requested
-- version, false otherwise.
local function partial_match(version, requested)
assert(type(version) == "string" or type(version) == "table")
assert(type(requested) == "string" or type(version) == "table")
if type(version) ~= "table" then version = vers.parse_version(version) end
if type(requested) ~= "table" then requested = vers.parse_version(requested) end
if not version or not requested then return false end
for i, ri in ipairs(requested) do
local vi = version[i] or 0
if ri ~= vi then return false end
end
if requested.revision then
return requested.revision == version.revision
end
return true
end
--- Check if a version satisfies a set of constraints.
-- @param version table: A version in table format
-- @param constraints table: An array of constraints in table format.
-- @return boolean: True if version satisfies all constraints,
-- false otherwise.
function vers.match_constraints(version, constraints)
assert(type(version) == "table")
assert(type(constraints) == "table")
local ok = true
setmetatable(version, version_mt)
for _, constr in pairs(constraints) do
if type(constr.version) == "string" then
constr.version = vers.parse_version(constr.version)
end
local constr_version, constr_op = constr.version, constr.op
setmetatable(constr_version, version_mt)
if constr_op == "==" then ok = version == constr_version
elseif constr_op == "~=" then ok = version ~= constr_version
elseif constr_op == ">" then ok = version > constr_version
elseif constr_op == "<" then ok = version < constr_version
elseif constr_op == ">=" then ok = version >= constr_version
elseif constr_op == "<=" then ok = version <= constr_version
elseif constr_op == "~>" then ok = partial_match(version, constr_version)
end
if not ok then break end
end
return ok
end
return vers
|
Fix version cache
|
Fix version cache
|
Lua
|
mit
|
keplerproject/luarocks,keplerproject/luarocks,luarocks/luarocks,keplerproject/luarocks,luarocks/luarocks,tarantool/luarocks,luarocks/luarocks,tarantool/luarocks,tarantool/luarocks,keplerproject/luarocks
|
4604c2e80440fd42840a23c530586edafdd5bf5c
|
gui-stobo.lua
|
gui-stobo.lua
|
#!./bin/lua
require 'stobo'
local lgi = require 'lgi'
local Gtk = lgi.Gtk
local builder = Gtk.Builder()
builder:add_from_file('app/screen.glade')
local window = builder:get_object('main')
local statusbar = builder:get_object('statusbar')
local listYears = builder:get_object('listYears')
local listStocks = builder:get_object('listStocks')
local stocksCombo = builder:get_object('stocks')
local yearsCombo = builder:get_object('years')
local startDateEntry = builder:get_object('startDate')
local endDateEntry = builder:get_object('endDate')
local textview = builder:get_object('textview')
local textbuffer = builder:get_object('textbuffer')
local byVolumeCheck = builder:get_object('byVolume')
local stockList = {}
local filtredStockList = {}
local symbols = {}
-- Fill years combo
local years = { '2015', '2014', '2013', '2012', '2011' }
for i,year in pairs(years) do
listYears:append({ year })
end
function status(text)
print(text)
statusbar:push(0, text)
while Gtk.events_pending() do
Gtk.main_iteration()
end
end
function fillStocksCombo()
local listByVolume = byVolumeCheck:get_active()
symbols = filtredStockList:symbols(listByVolume)
listStocks:clear()
status('Montando exibição de ações...')
for i,symbol in ipairs(symbols) do
listStocks:append({ symbol })
end
end
function displayOutput()
local selecterYear = years[yearsCombo:get_active() + 1]
local startDateValue = startDateEntry:get_text()
local endDateValue = endDateEntry:get_text()
local selectedStockValue = symbols[stocksCombo:get_active() + 1]
local startDateWithYear = #startDateValue == 4 and selecterYear..startDateValue or ''
local endDateWithYear = #endDateValue == 4 and selecterYear..endDateValue or ''
filtredStockList = stockList:bySymbol(selectedStockValue)
:byStartDate(startDateWithYear)
:byEndDate(endDateWithYear)
local outputText = ''
for i,quote in ipairs(filtredStockList.quotes) do
outputText = outputText..quote.symbol..
' ('..quote.date..') -'..
' O:'..quote.open..
' H:'..quote.high..
' L:'..quote.low..
' C:'..quote.close..
' V:'..quote.volume..
'\n'
end
textbuffer:set_text(outputText, #outputText)
end
print 'Bidding screen signals'
builder:connect_signals {
on_year_changed = function()
startDateEntry:set_text('')
endDateEntry:set_text('')
local selecterYear = years[yearsCombo:get_active() + 1]
status('Obtendo dados...')
local dataText = Database.get('05'..selecterYear)
status('Processando banco de dados...')
stockList = Stocks.new(dataText)
filtredStockList = stockList -- TODO: Identificar bug de selecionar ano novamente
status('Exibindo stocks no combo...')
fillStocksCombo()
status('Pronto')
end,
on_startDate_changed = function(widget)
local textValue = widget:get_text()
if #textValue == 4 then displayOutput() end
end,
on_endDate_changed = function(widget)
local textValue = widget:get_text()
if #textValue == 4 then displayOutput() end
end,
on_stocks_changed = function()
displayOutput()
end,
on_byVolume_toggled = function()
fillStocksCombo()
end
}
window.on_destroy = Gtk.main_quit
window:show_all()
Gtk.main()
|
#!./bin/lua
require 'stobo'
local lgi = require 'lgi'
local Gtk = lgi.Gtk
local builder = Gtk.Builder()
builder:add_from_file('app/screen.glade')
local window = builder:get_object('main')
local statusbar = builder:get_object('statusbar')
local listYears = builder:get_object('listYears')
local listStocks = builder:get_object('listStocks')
local stocksCombo = builder:get_object('stocks')
local yearsCombo = builder:get_object('years')
local startDateEntry = builder:get_object('startDate')
local endDateEntry = builder:get_object('endDate')
local textview = builder:get_object('textview')
local textbuffer = builder:get_object('textbuffer')
local byVolumeCheck = builder:get_object('byVolume')
local stockList = {}
local filtredStockList = {}
local symbols = {}
-- Fill years combo
local years = { '2015', '2014', '2013', '2012', '2011' }
for i,year in pairs(years) do
listYears:append({ year })
end
function waitEventsPending()
while Gtk.events_pending() do
Gtk.main_iteration()
end
end
function status(text)
print(text)
statusbar:push(0, text)
waitEventsPending()
end
function fillStocksCombo()
local listByVolume = byVolumeCheck:get_active()
symbols = filtredStockList:symbols(listByVolume)
listStocks:clear()
status('Montando exibição de ações...')
for i,symbol in ipairs(symbols) do
listStocks:append({ symbol })
end
status('Pronto')
end
function displayOutput()
local selecterYear = years[yearsCombo:get_active() + 1]
local startDateValue = startDateEntry:get_text()
local endDateValue = endDateEntry:get_text()
local selectedStockValue = symbols[stocksCombo:get_active() + 1]
local startDateWithYear = #startDateValue == 4 and selecterYear..startDateValue or ''
local endDateWithYear = #endDateValue == 4 and selecterYear..endDateValue or ''
filtredStockList = stockList:bySymbol(selectedStockValue)
:byStartDate(startDateWithYear)
:byEndDate(endDateWithYear)
print 'Preparing output format...'
local outputText = ''
if selectedStockValue then
for i,quote in ipairs(filtredStockList.quotes) do
outputText = outputText..quote.symbol..
' ('..quote.date..') -'..
' O:'..quote.open..
' H:'..quote.high..
' L:'..quote.low..
' C:'..quote.close..
' V:'..quote.volume..
'\n'
end
end
print 'Displaying output...'
textbuffer:set_text(outputText, #outputText)
end
print 'Bidding screen signals'
builder:connect_signals {
on_year_changed = function()
startDateEntry:set_text('')
endDateEntry:set_text('')
local selecterYear = years[yearsCombo:get_active() + 1]
status('Obtendo dados...')
local dataText = Database.get('05'..selecterYear)
status('Processando banco de dados...')
stockList = Stocks.new(dataText)
filtredStockList = stockList
status('Exibindo stocks no combo...')
fillStocksCombo()
end,
on_startDate_changed = function(widget)
local textValue = widget:get_text()
if #textValue == 4 then displayOutput() end
end,
on_endDate_changed = function(widget)
local textValue = widget:get_text()
if #textValue == 4 then displayOutput() end
end,
on_stocks_changed = function()
displayOutput()
end,
on_byVolume_toggled = function()
fillStocksCombo()
end
}
window.on_destroy = Gtk.main_quit
window:show_all()
Gtk.main()
|
Fixing stocks freeze
|
Fixing stocks freeze
|
Lua
|
mit
|
henriquegogo/stobo,henriquegogo/stobo,henriquegogo/stobo,henriquegogo/stobo
|
2d1dad1615f028e646f3294fa909f7d3020a3121
|
lvim/.config/lvim/lua/uelei/neotest.lua
|
lvim/.config/lvim/lua/uelei/neotest.lua
|
-- local function setup_vim_test()
-- vim.api.nvim_exec(
-- [[
-- " Test config
-- let test#strategy = "neovim"
-- let test#neovim#term_position = "belowright"
-- let g:test#preserve_screen = 1
-- let g:test#echo_command = 1
-- " javascript
-- " let g:test#javascript#runner = 'karma'
-- ]],
-- false
-- )
-- end
local test = require("neotest")
test.setup({
adapters = {
pcall(function()
require("neotest-python")({
-- Extra arguments for nvim-dap configuration
dap = { justMyCode = false },
-- Command line arguments for runner
-- Can also be a function to return dynamic values
args = {"--log-level", "DEBUG"},
-- Runner to use. Will use pytest if available by default.
-- Can be a function to return dynamic value.
runner = "pytest",
-- Returns if a given file path is a test file.
-- NB: This function is called a lot so don't perform any heavy tasks within it.
-- is_test_file = function(file_path)
-- end,
})
end),
pcall(function()
require("neotest-jest")({
jestCommand = "npm test --",
})
end),
pcall(function()
require("neotest-vim-test")({
-- It is recommended to add any filetypes that are covered by another adapter to the ignore list
ignore_file_types = { "python", "vim", "lua" },
})
end),
-- Or to only allow specified file types
-- require("neotest-vim-test")({ allow_file_types = { "haskell", "elixir" } }),
pcall(function()
require("neotest-go")
end),
},
-- setup_vim_test()
})
lvim.builtin.which_key.mappings["t"] = {
name = "Test",
a = { "<cmd>lua require('neotest').run.attach()<cr>", "Attach" },
f = { "<cmd>lua require('neotest').run.run(vim.fn.expand('%'))<cr>", "Run File" },
F = { "<cmd>lua require('neotest').run.run({vim.fn.expand('%'), strategy = 'dap'})<cr>", "Debug File" },
l = { "<cmd>lua require('neotest').run.run_last()<cr>", "Run Last" },
L = { "<cmd>lua require('neotest').run.run_last({ strategy = 'dap' })<cr>", "Debug Last" },
n = { "<cmd>lua require('neotest').run.run()<cr>", "Run Nearest" },
N = { "<cmd>lua require('neotest').run.run({strategy = 'dap'})<cr>", "Debug Nearest" },
o = { "<cmd>lua require('neotest').output.open({ enter = true })<cr>", "Output" },
S = { "<cmd>lua require('neotest').run.stop()<cr>", "Stop" },
s = { "<cmd>lua require('neotest').summary.toggle()<cr>", "Summary" },
}
|
local status_ok, test = pcall(require, "neotest")
if not status_ok then
return
end
-- local function setup_vim_test()
-- vim.api.nvim_exec(
-- [[
-- " Test config
-- let test#strategy = "neovim"
-- let test#neovim#term_position = "belowright"
-- let g:test#preserve_screen = 1
-- let g:test#echo_command = 1
-- " javascript
-- " let g:test#javascript#runner = 'karma'
-- ]],
-- false
-- )
-- end
test.setup({
adapters = {
pcall(function()
require("neotest-python")({
-- Extra arguments for nvim-dap configuration
dap = { justMyCode = false },
-- Command line arguments for runner
-- Can also be a function to return dynamic values
args = {"--log-level", "DEBUG"},
-- Runner to use. Will use pytest if available by default.
-- Can be a function to return dynamic value.
runner = "pytest",
-- Returns if a given file path is a test file.
-- NB: This function is called a lot so don't perform any heavy tasks within it.
-- is_test_file = function(file_path)
-- end,
})
end),
pcall(function()
require("neotest-jest")({
jestCommand = "npm test --",
})
end),
pcall(function()
require("neotest-vim-test")({
-- It is recommended to add any filetypes that are covered by another adapter to the ignore list
ignore_file_types = { "python", "vim", "lua" },
})
end),
-- Or to only allow specified file types
-- require("neotest-vim-test")({ allow_file_types = { "haskell", "elixir" } }),
pcall(function()
require("neotest-go")
end),
},
-- setup_vim_test()
})
lvim.builtin.which_key.mappings["t"] = {
name = "Test",
a = { "<cmd>lua require('neotest').run.attach()<cr>", "Attach" },
f = { "<cmd>lua require('neotest').run.run(vim.fn.expand('%'))<cr>", "Run File" },
F = { "<cmd>lua require('neotest').run.run({vim.fn.expand('%'), strategy = 'dap'})<cr>", "Debug File" },
l = { "<cmd>lua require('neotest').run.run_last()<cr>", "Run Last" },
L = { "<cmd>lua require('neotest').run.run_last({ strategy = 'dap' })<cr>", "Debug Last" },
n = { "<cmd>lua require('neotest').run.run()<cr>", "Run Nearest" },
N = { "<cmd>lua require('neotest').run.run({strategy = 'dap'})<cr>", "Debug Nearest" },
o = { "<cmd>lua require('neotest').output.open({ enter = true })<cr>", "Output" },
S = { "<cmd>lua require('neotest').run.stop()<cr>", "Stop" },
s = { "<cmd>lua require('neotest').summary.toggle()<cr>", "Summary" },
}
|
🐛 fix(neotest): add protect call to neotest
|
🐛 fix(neotest): add protect call to neotest
|
Lua
|
mit
|
uelei/dotfiles
|
dd97e32469caf3ab583ed8e0e2c652419fbd0d61
|
kong/plugins/acl/migrations/001_14_to_15.lua
|
kong/plugins/acl/migrations/001_14_to_15.lua
|
return {
postgres = {
up = [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "acls" ADD "cache_key" TEXT UNIQUE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "acls"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "acls_consumer_id" RENAME TO "acls_consumer_id_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "acls_group" RENAME TO "acls_group_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
]],
teardown = function(connector, helpers)
assert(connector:connect_migrations())
for rows, err in connector:iterate('SELECT * FROM "acls" ORDER BY "created_at";') do
if err then
return nil, err
end
for i = 1, #rows do
local row = rows[i]
local cache_key = string.format("%s:%s:%s:::", "acls",
row.consumer_id or "",
row.group or "")
local sql = string.format([[
UPDATE "acls" SET "cache_key" = '%s' WHERE "id" = '%s';
]], cache_key, row.id)
assert(connector:query(sql))
end
end
end,
},
cassandra = {
up = [[
ALTER TABLE acls ADD cache_key text;
CREATE INDEX IF NOT EXISTS acls_cache_key_idx ON acls(cache_key);
]],
teardown = function(connector, helpers)
local cassandra = require "cassandra"
local coordinator = assert(connector:connect_migrations())
for rows, err in coordinator:iterate("SELECT * FROM acls") do
if err then
return nil, err
end
for i = 1, #rows do
local row = rows[i]
local cache_key = string.format("%s:%s:%s:::", "acls",
row.consumer_id or "",
row.group or "")
assert(connector:query("UPDATE acls SET cache_key = ? WHERE id = ?", {
cache_key,
cassandra.uuid(row.id),
}))
end
end
end,
},
}
|
return {
postgres = {
up = [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "acls" ADD "cache_key" TEXT UNIQUE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "acls"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "acls_consumer_id" RENAME TO "acls_consumer_id_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "acls_group" RENAME TO "acls_group_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
]],
teardown = function(connector, helpers)
assert(connector:connect_migrations())
for row, err in connector:iterate('SELECT * FROM "acls" ORDER BY "created_at";') do
if err then
return nil, err
end
local cache_key = string.format("%s:%s:%s:::", "acls",
row.consumer_id or "",
row.group or "")
local sql = string.format([[
UPDATE "acls" SET "cache_key" = '%s' WHERE "id" = '%s';
]], cache_key, row.id)
assert(connector:query(sql))
end
end,
},
cassandra = {
up = [[
ALTER TABLE acls ADD cache_key text;
CREATE INDEX IF NOT EXISTS acls_cache_key_idx ON acls(cache_key);
]],
teardown = function(connector, helpers)
local cassandra = require "cassandra"
local coordinator = assert(connector:connect_migrations())
for rows, err in coordinator:iterate("SELECT * FROM acls") do
if err then
return nil, err
end
for i = 1, #rows do
local row = rows[i]
local cache_key = string.format("%s:%s:%s:::", "acls",
row.consumer_id or "",
row.group or "")
assert(connector:query("UPDATE acls SET cache_key = ? WHERE id = ?", {
cache_key,
cassandra.uuid(row.id),
}))
end
end
end,
},
}
|
fix(acl) fix migration of acls on postgres
|
fix(acl) fix migration of acls on postgres
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
cdf7907b22941072bbfe5ad5bb25a1ea9b754d40
|
extensions/application/test_application.lua
|
extensions/application/test_application.lua
|
hs.application = require("hs.application")
hs.dockicon = require("hs.dockicon")
menuTestValue = nil
function testInitWithPidFailures()
assertIsNil(hs.application.applicationForPID(1))
return success()
end
function testInitWithPid()
local apps = hs.application.runningApplications()
for _,app in pairs(apps) do
local pidApp = hs.application.applicationForPID(app:pid())
if pidApp == nil then
assertIsEqual(app:name(), nil)
end
assertIsEqual(app:name(), pidApp:name())
end
return success()
end
function testAttributesFromBundleID()
local appName = "Safari"
local appPath = "/Applications/Safari.app"
local bundleID = "com.apple.Safari"
assertTrue(hs.application.launchOrFocusByBundleID(bundleID))
local app = hs.application.applicationsForBundleID(bundleID)[1]
assertIsEqual(appName, app:name())
assertIsEqual(appPath, app:path())
assertIsString(tostring(app))
assertIsEqual(appName, hs.application.nameForBundleID(bundleID))
assertIsEqual(appPath, hs.application.pathForBundleID(bundleID))
assertIsEqual("Safari", hs.application.infoForBundleID("com.apple.Safari")["CFBundleExecutable"])
assertIsNil(hs.application.infoForBundleID("some.nonsense"))
assertIsEqual("Safari", hs.application.infoForBundlePath("/Applications/Safari.app")["CFBundleExecutable"])
assertIsNil(hs.application.infoForBundlePath("/C/Windows/System32/lol.exe"))
app:kill()
return success()
end
function testBasicAttributes()
local appName = "Hammerspoon"
local bundleID = "org.hammerspoon.Hammerspoon"
local currentPID = hs.processInfo.processID
assertIsNil(hs.application.applicationForPID(1))
local app = hs.application.applicationForPID(currentPID)
assertIsEqual(bundleID, app:bundleID())
assertIsEqual(appName, app:name())
assertIsEqual(appName, app:title())
assertIsEqual(currentPID, app:pid())
assertFalse(app:isUnresponsive())
-- This is disabled for now, not sure why it's failing
-- hs.dockicon.show()
-- hs.timer.usleep(200000)
-- assertIsEqual(1, app:kind())
-- hs.dockicon.hide()
-- hs.timer.usleep(200000)
-- assertIsEqual(0, app:kind())
return success()
end
function testActiveAttributes()
-- need to use application.watcher for testing these async events
local appName = "Stickies"
local app = hs.application.open(appName, 0, true)
assertTrue(app:isRunning())
assertTrue(app:activate())
assertTrue(app:hide())
assertTrue(app:isHidden())
assertTrue(app:unhide())
assertFalse(app:isHidden())
assertTrue(app:activate())
local menuPathBlue = {"Color", "Blue"}
local menuPathGreen = {"Color", "Green"}
assertTrue(app:selectMenuItem(menuPathBlue))
app:selectMenuItem({"Color"})
assertTrue(app:findMenuItem(menuPathBlue).ticked)
assertTrue(app:selectMenuItem(menuPathGreen))
app:selectMenuItem({"Color"})
assertFalse(app:findMenuItem(menuPathBlue).ticked)
assertIsEqual(appName, app:getMenuItems()[1].AXTitle)
return success()
end
function testMetaTable()
-- hs.application's userdata is not aligned with other HS types (via LuaSkin) because it is old and special
-- the `__type` field is not currently on hs.application object metatables like everything else
-- this test should pass but can wait for rewrite
local app = launchAndReturnAppFromBundleID("com.apple.Safari")
assertIsUserdataOfType("hs.application", app)
return success()
end
function testFrontmostApplication()
hs.openConsole()
local app = hs.application.frontmostApplication()
app:activate()
assertIsNotNil(app)
assertTrue(app:isFrontmost())
assertTrue(app:setFrontmost())
return success()
end
function testRunningApplications()
local apps = hs.application.runningApplications()
assertIsEqual("table", type(apps))
assertGreaterThan(1, #apps)
return success()
end
function testHiding()
hs.application.open("Stickies", 5, true)
return success()
end
function testHidingValues()
local app = hs.application.get("Stickies")
assertIsNotNil(app)
assertTrue(app:isRunning())
assertFalse(app:isHidden())
app:hide()
hs.timer.usleep(500000)
assertTrue(app:isHidden())
app:unhide()
hs.timer.usleep(500000)
assertFalse(app:isHidden())
app:kill9()
return success()
end
function testKilling()
local app = hs.application.open("Audio MIDI Setup", 5, true)
return success()
end
function testKillingValues()
local app = hs.application.get("Audio MIDI Setup")
assertIsNotNil(app)
assertTrue(app:isRunning())
app:kill()
hs.timer.usleep(500000)
assertFalse(app:isRunning())
return success()
end
function testForceKilling()
hs.application.open("Calculator", 5, true)
return success()
end
function testForceKillingValues()
local app = hs.application.get("Calculator")
assertIsNotNil(app)
assertTrue(app:isRunning())
app:kill9()
hs.timer.usleep(500000)
assertFalse(app:isRunning())
return success()
end
function testWindows()
local dock = hs.application.get("Dock")
assertIsNil(dock:mainWindow())
hs.application.open("Grapher", 5, true)
return success()
end
function testWindowsValues()
local app = hs.application.get("Grapher")
assertIsNotNil(app)
local wins = app:allWindows()
assertIsEqual("table", type(wins))
assertIsEqual(1, #wins)
local win = app:focusedWindow()
assertIsEqual("Grapher", win:application():name())
app:kill()
return success()
end
function testMenus()
local app = hs.application.get("Hammerspoon")
local menus = app:getMenuItems()
assertIsTable(menus)
assertIsEqual("Hammerspoon", menus[1]["AXTitle"])
local item = app:findMenuItem({"Edit", "Cut"})
assertIsTable(item)
assertIsBoolean(item["enabled"])
assertIsNil(app:findMenuItem({"Foo", "Bar"}))
item = app:findMenuItem("Cut")
assertIsTable(item)
assertIsBoolean(item["enabled"])
assertIsNil(app:findMenuItem("Foo"))
assertTrue(app:selectMenuItem({"Edit", "Select All"}))
assertIsNil(app:selectMenuItem({"Edit", "No Such Menu Item"}))
assertTrue(app:selectMenuItem("Select All"))
assertIsNil(app:selectMenuItem("Some Nonsense"))
app = hs.application.get("Dock")
app:activate(true)
menus = app:getMenuItems()
assertIsNil(menus)
return success()
end
function testMenusAsync()
local app = hs.application.get("Hammerspoon")
local value = app:getMenuItems(function(menutable) menuTestValue = menutable end)
assertIsUserdataOfType("hs.application", value)
return success()
end
function testMenusAsyncValues()
assertIsTable(menuTestValue)
assertIsEqual("Hammerspoon", menuTestValue[1]["AXTitle"])
return success()
end
function testUTI()
local bundle = hs.application.defaultAppForUTI('public.jpeg')
assertIsEqual("com.apple.Preview", bundle)
return success()
end
|
hs.application = require("hs.application")
hs.dockicon = require("hs.dockicon")
menuTestValue = nil
function testInitWithPidFailures()
assertIsNil(hs.application.applicationForPID(1))
return success()
end
function testInitWithPid()
local apps = hs.application.runningApplications()
for _,app in pairs(apps) do
local pidApp = hs.application.applicationForPID(app:pid())
if pidApp == nil then
assertIsEqual(app:name(), nil) -- works in XCode now, but still not in GithubActions
end
assertIsEqual(app:name(), pidApp:name())
end
return success()
end
function testAttributesFromBundleID()
local appName = "Safari"
local appPath = "/Applications/Safari.app"
local bundleID = "com.apple.Safari"
assertTrue(hs.application.launchOrFocusByBundleID(bundleID))
local app = hs.application.applicationsForBundleID(bundleID)[1]
assertIsEqual(appName, app:name())
assertIsEqual(appPath, app:path())
assertIsString(tostring(app))
assertIsEqual(appName, hs.application.nameForBundleID(bundleID))
assertIsEqual(appPath, hs.application.pathForBundleID(bundleID))
assertIsEqual("Safari", hs.application.infoForBundleID("com.apple.Safari")["CFBundleExecutable"])
assertIsNil(hs.application.infoForBundleID("some.nonsense"))
assertIsEqual("Safari", hs.application.infoForBundlePath("/Applications/Safari.app")["CFBundleExecutable"])
assertIsNil(hs.application.infoForBundlePath("/C/Windows/System32/lol.exe"))
app:kill()
return success()
end
function testBasicAttributes()
local appName = "Hammerspoon"
local bundleID = "org.hammerspoon.Hammerspoon"
local currentPID = hs.processInfo.processID
assertIsNil(hs.application.applicationForPID(1))
local app = hs.application.applicationForPID(currentPID)
assertIsEqual(bundleID, app:bundleID())
assertIsEqual(appName, app:name())
assertIsEqual(appName, app:title())
assertIsEqual(currentPID, app:pid())
assertFalse(app:isUnresponsive())
-- This is disabled for now, not sure why it's failing
-- hs.dockicon.show()
-- hs.timer.usleep(200000)
-- assertIsEqual(1, app:kind())
-- hs.dockicon.hide()
-- hs.timer.usleep(200000)
-- assertIsEqual(0, app:kind())
return success()
end
function testActiveAttributes()
-- need to use application.watcher for testing these async events
local appName = "Stickies"
local app = hs.application.open(appName, 0, true)
assertTrue(app:isRunning())
assertTrue(app:activate())
assertTrue(app:hide())
assertTrue(app:isHidden())
assertTrue(app:unhide())
assertFalse(app:isHidden())
assertTrue(app:activate())
local menuPathBlue = {"Color", "Blue"}
local menuPathGreen = {"Color", "Green"}
assertTrue(app:selectMenuItem(menuPathBlue))
app:selectMenuItem({"Color"})
assertTrue(app:findMenuItem(menuPathBlue).ticked)
assertTrue(app:selectMenuItem(menuPathGreen))
app:selectMenuItem({"Color"})
assertFalse(app:findMenuItem(menuPathBlue).ticked)
assertIsEqual(appName, app:getMenuItems()[1].AXTitle)
return success()
end
function testMetaTable()
-- hs.application's userdata is not aligned with other HS types (via LuaSkin) because it is old and special
-- the `__type` field is not currently on hs.application object metatables like everything else
-- this test should pass but can wait for rewrite
local app = launchAndReturnAppFromBundleID("com.apple.Safari")
assertIsUserdataOfType("hs.application", app)
return success()
end
function testFrontmostApplication()
hs.openConsole()
local app = hs.application.frontmostApplication()
app:activate()
assertIsNotNil(app)
assertTrue(app:isFrontmost())
assertTrue(app:setFrontmost())
return success()
end
function testRunningApplications()
local apps = hs.application.runningApplications()
assertIsEqual("table", type(apps))
assertGreaterThan(1, #apps)
return success()
end
function testHiding()
hs.application.open("Stickies", 5, true)
return success()
end
function testHidingValues()
local app = hs.application.get("Stickies")
assertIsNotNil(app)
assertTrue(app:isRunning())
assertFalse(app:isHidden())
app:hide()
hs.timer.usleep(500000)
assertTrue(app:isHidden())
app:unhide()
hs.timer.usleep(500000)
assertFalse(app:isHidden())
app:kill9()
return success()
end
function testKilling()
local app = hs.application.open("Audio MIDI Setup", 5, true)
return success()
end
function testKillingValues()
local app = hs.application.get("Audio MIDI Setup")
assertIsNotNil(app)
assertTrue(app:isRunning())
app:kill()
hs.timer.usleep(500000)
assertFalse(app:isRunning())
return success()
end
function testForceKilling()
hs.application.open("Calculator", 5, true)
return success()
end
function testForceKillingValues()
local app = hs.application.get("Calculator")
assertIsNotNil(app)
assertTrue(app:isRunning())
app:kill9()
hs.timer.usleep(500000)
assertFalse(app:isRunning())
return success()
end
function testWindows()
local dock = hs.application.get("Dock")
assertIsNil(dock:mainWindow())
hs.application.open("Grapher", 5, true)
return success()
end
function testWindowsValues()
local app = hs.application.get("Grapher")
assertIsNotNil(app)
local wins = app:allWindows()
assertIsEqual("table", type(wins))
assertIsEqual(1, #wins)
local win = app:focusedWindow()
assertIsEqual("Grapher", win:application():name())
app:kill()
return success()
end
function testMenus()
local app = hs.application.get("Hammerspoon")
local menus = app:getMenuItems()
assertIsTable(menus)
assertIsEqual("Hammerspoon", menus[1]["AXTitle"])
local item = app:findMenuItem({"Edit", "Cut"})
assertIsTable(item)
assertIsBoolean(item["enabled"])
assertIsNil(app:findMenuItem({"Foo", "Bar"}))
item = app:findMenuItem("Cut")
assertIsTable(item)
assertIsBoolean(item["enabled"])
assertIsNil(app:findMenuItem("Foo"))
assertTrue(app:selectMenuItem({"Edit", "Select All"}))
assertIsNil(app:selectMenuItem({"Edit", "No Such Menu Item"}))
assertTrue(app:selectMenuItem("Select All"))
assertIsNil(app:selectMenuItem("Some Nonsense"))
app = hs.application.get("Dock")
app:activate(true)
menus = app:getMenuItems()
assertIsNil(menus)
return success()
end
function testMenusAsync()
local app = hs.application.get("Hammerspoon")
local value = app:getMenuItems(function(menutable) menuTestValue = menutable end)
assertIsUserdataOfType("hs.application", value)
return success()
end
function testMenusAsyncValues()
assertIsTable(menuTestValue)
assertIsEqual("Hammerspoon", menuTestValue[1]["AXTitle"])
return success()
end
function testUTI()
local bundle = hs.application.defaultAppForUTI('public.jpeg')
assertIsEqual("com.apple.Preview", bundle)
return success()
end
|
make note of who to blame; fix helps in Xcode, not in GithubActions
|
make note of who to blame; fix helps in Xcode, not in GithubActions
|
Lua
|
mit
|
latenitefilms/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon
|
e2a5b6bd7586dc641bb5076d4e1a7cdef3491852
|
api/server.lua
|
api/server.lua
|
local htmlparser = require("htmlparser")
local http = require('socket.http')
local json = require('json')
local app = require('waffle').CmdLine()
local search = function(req, res)
local query = req.url.args.zoektermen
local queryType = tonumber(req.url.args.opZoeken)
local queryPage = tonumber(req.url.args.page) or 0
local queryEan = ""
if query == nil then
res.send("Error")
end
-- Ean query
if queryType == 1 then
queryEan = query
query = ""
end
local url = {'http://livaad.nl/app/loaddata.php', '?artq=', query, '&eanq=', queryEan, '&producentq=&p=', queryPage}
if queryPage < 1 then
url[1] = 'http://livaad.nl/database/'
end
local body, c, l, h = http.request(table.concat(url, ""))
local root = htmlparser.parse(body)
if queryPage < 1 then
local dataContainer = root:select("#data-container")
if #dataContainer>=1 then
root = htmlparser.parse(dataContainer[1]:getcontent())
else
res.send("Error")
end
end
local products = root:select(".panel")
local results = {}
-- Get all products
for i=1,#products do
local header = products[i](".panel-heading")
if #header >= 1 then
local brand, name = unpack(header[1]:select('div'))
brand = brand:getcontent()
name, c = string.gsub(name:getcontent(), '<(.*)>', "")
local rows = products[i]('.row')
local attributes = {}
for i=1,#rows do
local k, v = unpack(rows[i]('div'))
attributes[k:getcontent():gsub("[( |:)]", "")] = v:getcontent()
end
local bsm = "" -- By default TODO
local source = "" -- By default TODO
-- 1 is free, 2 is contains
local _, starch = attributes["Tarwezetmeel"]:gsub("vrij", "vrij")
starch = starch > 0 and 1 or 2
local _, lactose = attributes["Lactose"]:gsub("vrij", "vrij")
lactose = lactose > 0 and 1 or 2
local datum = string.gsub(attributes["Checkdatum"], '<(.*)>(.*)</(.*)>', ""):gsub(" ", ""):gsub("-201", "") -- TODO: Fix in app
results[#results+1] = {name, attributes["EAN"], brand, attributes["Soort"], starch, lactose, bsm, datum, source}
end
end
res.header('Content-Type', 'application/x-json')
res.send(json.encode{api_version=0.2, results=results})
end
app.get('/search.php', search)
app.get('/glutenvrij/search.php', search)
-- 127.0.0.1
app.listen()
|
local htmlparser = require("htmlparser")
local http = require('socket.http')
local json = require('json')
local app = require('waffle').CmdLine()
local search = function(req, res)
local query = req.url.args.zoektermen
local queryType = tonumber(req.url.args.opZoeken)
local queryPage = tonumber(req.url.args.page) or 0
local queryEan = ""
if query == nil then
res.send("Error")
end
-- Ean query
if queryType == 1 then
queryEan = query
query = ""
end
local url = {'http://livaad.nl/app/loaddata.php', '?artq=', query, '&eanq=', queryEan, '&producentq=&p=', queryPage}
if queryPage < 1 then
url[1] = 'http://livaad.nl/database/'
end
local body, c, l, h = http.request(table.concat(url, ""))
local root = htmlparser.parse(body)
if queryPage < 1 then
local dataContainer = root:select("#data-container")
if #dataContainer>=1 then
root = htmlparser.parse(dataContainer[1]:getcontent())
else
res.send("Error")
end
end
local products = root:select(".panel")
local results = {}
-- Get all products
for i=1,#products do
local header = products[i](".panel-heading")
if #header >= 1 then
local brand, name = unpack(header[1]:select('div'))
brand = brand:getcontent()
name, c = string.gsub(name:getcontent(), '<(.*)>', "")
local rows = products[i]('.row')
local attributes = {}
for i=1,#rows do
local k, v = unpack(rows[i]('div'))
attributes[k:getcontent():gsub("[( |:)]", "")] = v:getcontent()
end
local bsm = "" -- By default TODO
local source = "" -- By default TODO
-- 1 is free, 2 is contains
local _, starch = attributes["Tarwezetmeel"]:gsub("vrij", "vrij")
starch = starch > 0 and 1 or 2
local _, lactose = attributes["Lactose"]:gsub("vrij", "vrij")
lactose = lactose > 0 and 1 or 2
local datum = string.gsub(attributes["Checkdatum"], '<(.*)>(.*)</(.*)>', ""):gsub(" ", ""):gsub("-201", "") -- TODO: Fix in app
datum = datum:sub(3,3) .. datum:sub(1,2) -- Last number year, month
results[#results+1] = {name, attributes["EAN"], brand, attributes["Soort"], starch, lactose, bsm, datum, source}
end
end
res.header('Content-Type', 'application/x-json')
res.send(json.encode{api_version=0.2, results=results})
end
app.get('/search.php', search)
app.get('/glutenvrij/search.php', search)
-- 127.0.0.1
app.listen()
|
Fix date format
|
Fix date format
|
Lua
|
mit
|
JoostvDoorn/GlutenVrijApp
|
0fe7bd3216177265038ff7d3f83d1d47e748141c
|
src/humanoidspeed/src/Server/HumanoidSpeed.lua
|
src/humanoidspeed/src/Server/HumanoidSpeed.lua
|
--[=[
Manages speed of a humanoid
@server
@class HumanoidSpeed
]=]
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local RogueHumanoidProperties = require("RogueHumanoidProperties")
local HumanoidSpeed = setmetatable({}, BaseObject)
HumanoidSpeed.ClassName = "HumanoidSpeed"
HumanoidSpeed.__index = HumanoidSpeed
--[=[
Constructs a new HumanoidSpeed
@param humanoid Humanoid
@return HumanoidSpeed
]=]
function HumanoidSpeed.new(humanoid, serviceBag)
local self = setmetatable(BaseObject.new(humanoid), HumanoidSpeed)
self._serviceBag = assert(serviceBag, "No serviceBag")
self._properties = RogueHumanoidProperties:GetPropertyTable(self._serviceBag, self._obj)
return self
end
--[=[
Sets the default speed for the humanoid
@param defaultSpeed number
]=]
function HumanoidSpeed:SetDefaultSpeed(defaultSpeed)
self._properties.WalkSpeed:SetBaseValue(defaultSpeed)
end
--[=[
Applies a speed multipler to the player's speed
@param multiplier number
@return function -- Cleanup function
]=]
function HumanoidSpeed:ApplySpeedMultiplier(multiplier)
assert(type(multiplier) == "number", "Bad multiplier")
assert(multiplier >= 0, "Bad multiplier")
return self._properties.WalkSpeed:CreateMultiplier(multiplier)
end
--[=[
Applies a speed additive to the player's speed
@param amount number
@return function -- Cleanup function
]=]
function HumanoidSpeed:ApplySpeedAdditive(amount)
assert(type(amount) == "number", "Bad amount")
return self._properties.WalkSpeed:CreateAdditive(amount)
end
return HumanoidSpeed
|
--[=[
Manages speed of a humanoid
@server
@class HumanoidSpeed
]=]
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local RogueHumanoidProperties = require("RogueHumanoidProperties")
local HumanoidSpeed = setmetatable({}, BaseObject)
HumanoidSpeed.ClassName = "HumanoidSpeed"
HumanoidSpeed.__index = HumanoidSpeed
--[=[
Constructs a new HumanoidSpeed
@param humanoid Humanoid
@param serviceBag ServiceBag
@return HumanoidSpeed
]=]
function HumanoidSpeed.new(humanoid, serviceBag)
local self = setmetatable(BaseObject.new(humanoid), HumanoidSpeed)
self._serviceBag = assert(serviceBag, "No serviceBag")
self._properties = RogueHumanoidProperties:GetPropertyTable(self._serviceBag, self._obj)
return self
end
--[=[
Sets the default speed for the humanoid
@param defaultSpeed number
]=]
function HumanoidSpeed:SetDefaultSpeed(defaultSpeed)
self._properties.WalkSpeed:SetBaseValue(defaultSpeed)
end
--[=[
Applies a speed multipler to the player's speed
@param multiplier number
@return function -- Cleanup function
]=]
function HumanoidSpeed:ApplySpeedMultiplier(multiplier)
assert(type(multiplier) == "number", "Bad multiplier")
assert(multiplier >= 0, "Bad multiplier")
return self._properties.WalkSpeed:CreateMultiplier(multiplier)
end
--[=[
Applies a speed additive to the player's speed
@param amount number
@return function -- Cleanup function
]=]
function HumanoidSpeed:ApplySpeedAdditive(amount)
assert(type(amount) == "number", "Bad amount")
return self._properties.WalkSpeed:CreateAdditive(amount)
end
return HumanoidSpeed
|
docs: Fix HumanoidSpeed docs
|
docs: Fix HumanoidSpeed docs
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
cc0dec2faa68b6b1ac802b71e49a8a386f1b8a28
|
dev/coverage.lua
|
dev/coverage.lua
|
local string = require"luv.string"
local table, require = table, require
local io, ipairs, type, error, debug = io, ipairs, type, error, debug
local unpack, pairs, math = unpack, pairs, math
local Object = require"luv.oop".Object
local html = require"luv.utils.html"
local Exception = require"luv.exceptions".Exception
module(...)
local property = Object.property
local Coverage = Object:extend{
__tag = .....".Coverage";
oldHook = property"table";
counter = property"number";
sourceFileName = property"string";
init = function (self)
self._info = {}
self:oldHook{debug.gethook()}
self:counter(0)
self:sourceFileName(debug.getinfo(1).short_src)
debug.sethook(function (type, lineNumber)
local counter = self:counter()
if counter > 10000000 then
debug.sethook()
Exception"recursion"
end
self:counter(counter+1)
if type ~= "line" then
return
end
local hook = {debug.gethook()}
debug.sethook()
local info = debug.getinfo(2)
local fileName = info.short_src
self._info[fileName] = self._info[fileName] or {}
local activelines = debug.getinfo(2, "L").activelines
for _, line in ipairs(activelines) do
self._info[fileName][line] = self._info[fileName][line] or false
end
if "Lua" == info.what and self:sourceFileName() ~= info.short_src then
self._info[fileName][lineNumber] = true
end
debug.sethook(unpack(hook))
end, "l")
end;
_end = function (self)
debug.sethook(unpack(self:oldHook() or {}))
self:oldHook{}
end;
info = function (self, only, exclude)
if self._coveredInfo then
return self._coveredInfo
end
self:_end()
self._parsedInfo = {}
self._coverInfo = {}
for source, info in pairs(self._info) do
local skipFlag = false
if only then
for i, v in ipairs(only) do
if not string.find(source, v) then
skipFlag = true
end
end
end
if exclude then
for i, v in ipairs(exclude) do
if string.find(source, v) then
skipFlag = true
end
end
end
if not skipFlag then
self._parsedInfo[source] = self:_parseScript(source)
local covered, notCovered, coveredEmpty = {}, {}, {}
for line, parsedInfo in pairs(self._parsedInfo[source]) do
if not info[line] then
notCovered[line] = parsedInfo
else
covered[line] = parsedInfo
end
end
for line, coverInfo in pairs(info) do
if not self._parsedInfo[source][line] then
coveredEmpty[line] = coverInfo
end
end
self._coverInfo[source] = {covered=covered;notCovered=notCovered;coveredEmpty=coveredEmpty;coverPercentage=math.floor(table.size(info)/table.size(self._parsedInfo[source])*100)}
end
end
return self._coverInfo
end;
asHtmlTable = function (self, ...)
self:_end()
local coverInfo = self._info
require"luv.dev".dprint(coverInfo, 2)
--[[local res = '<table class="coverage"><thead><tr><td>Source</td><td>Coverage (±10%)</td></tr></thead><tbody>'
for source, info in pairs(coverInfo) do
--local min, max = math.max(info.coverPercentage-5, 0), math.min(info.coverPercentage+5, 100)
res = res.."<tr><td>"..html.escape(source).."</td><td>"..(info.coverPercentage or "-").."%</td></tr>"
end
return res.."</tbody></table>"]]
end;
sourceAsHtml = function (self, source)
local lineNumber = 1
local info = self:info()[source]
local res = '<pre class="coverage">'
for line in io.lines(source) do
if info.covered and info.covered[lineNumber] then
res = res..'<span class="covered">'..html.escape(line).."</span><br />"
elseif info.notCovered and info.notCovered[lineNumber] then
res = res..'<span class="notCovered">'..html.escape(line).."</span><br />"
elseif info.coveredEmpty and info.coveredEmpty[lineNumber] then
res = res..'<span class="coveredEmpty">'..html.escape(line).."</span><br />"
else
res = res..'<span class="empty">'..html.escape(line).."</span><br />"
end
lineNumber = lineNumber + 1
end
return res.."</pre>"
end;
}
return {Coverage=Coverage}
|
local string = require"luv.string"
local table, require, tostring = table, require, tostring
local io, ipairs, type, error, debug = io, ipairs, type, error, debug
local unpack, pairs, math = unpack, pairs, math
local Object = require"luv.oop".Object
local html = require"luv.utils.html"
local Exception = require"luv.exceptions".Exception
local crypt = require"luv.crypt"
module(...)
local property = Object.property
local Coverage = Object:extend{
__tag = .....".Coverage";
oldHook = property"table";
sourceFileName = property"string";
info = property"table";
init = function (self)
self:info{}
self:oldHook{debug.gethook()}
self:sourceFileName(debug.getinfo(1).short_src)
debug.sethook(function (type, lineNumber)
local hook = {debug.gethook()}
debug.sethook()
local funcInfo = debug.getinfo(2)
local fileName = funcInfo.short_src
local info = self:info()
if not fileName:beginsWith"[" then
info[fileName] = info[fileName] or {}
local activelines = debug.getinfo(2, "L").activelines
for line in pairs(activelines) do
info[fileName][line] = info[fileName][line] or false
end
if "Lua" == funcInfo.what and self:sourceFileName() ~= fileName then
info[fileName][lineNumber] = true
end
end
debug.sethook(unpack(hook))
end, "l")
end;
_end = function (self)
debug.sethook(unpack(self:oldHook() or {}))
self:oldHook{}
end;
asHtmlTable = function (self, ...)
self:_end()
local info = self._info
local res = '<table class="coverage"><thead><tr><td>Source</td><td>Coverage</td></tr></thead><tbody>'
for fileName, info in pairs(info) do
local totalLines, coveredLines = 0, 0
for line, value in pairs(info) do
totalLines = totalLines + 1
if value then coveredLines = coveredLines + 1 end
end
res = res.."<tr><td>"..html.escape(fileName).."</td><td>"..(math.ceil(coveredLines/totalLines*100)).."%</td></tr>"
end
return res.."</tbody></table>"
end;
sourceAsHtml = function (self, source)
self:_end()
local lineNumber = 1
local info = self._info[source]
local res = '<pre class="coverage">'
for line in io.lines(source) do
local covered = info[lineNumber]
if covered then
res = res..'<span class="covered">'..html.escape(line).."</span><br />"
elseif false == covered then
res = res..'<span class="notCovered">'..html.escape(line).."</span><br />"
else
res = res..'<span class="empty">'..html.escape(line).."</span><br />"
end
lineNumber = lineNumber + 1
end
return res.."</pre>"
end;
fullInfoAsHtml = function (self)
self:_end()
local info = self._info
local res = '<table class="coverage"><thead><tr><td>Source</td><td>Coverage</td></tr></thead><tbody>'
for fileName, info in pairs(info) do
local totalLines, coveredLines = 0, 0
for line, value in pairs(info) do
totalLines = totalLines + 1
if value then coveredLines = coveredLines + 1 end
end
res = res..'<tr><td><a href="#'..tostring(crypt.Md5(fileName))..'">'..html.escape(fileName).."</a></td><td>"..(math.ceil(coveredLines/totalLines*100)).."%</td></tr>"
end
res = res.."</tbody></table>"
for fileName, info in pairs(info) do
res = res..'<a name="'..tostring(crypt.Md5(fileName))..'" /><h2>'..fileName.."</h2>"..self:sourceAsHtml(fileName)
end
return res
end;
}
return {Coverage=Coverage}
|
Improved & fixed dev.coverage.
|
Improved & fixed dev.coverage.
|
Lua
|
bsd-3-clause
|
metadeus/luv
|
3bba9bf233d58591b2867175042646c3e2aafddf
|
examples/libcpp/premake5.lua
|
examples/libcpp/premake5.lua
|
-- Copyright © 2017 Embedded Artistry LLC.
-- License: MIT. See LICENSE file for details.
-- For reference, please refer to the premake wiki:
-- https://github.com/premake/premake-core/wiki
local ROOT = "./"
local RESULTSROOT = ROOT .. "buildresults/%{cfg.platform}_%{cfg.buildcfg}/"
---------------------------------
-- [ WORKSPACE CONFIGURATION --
---------------------------------
workspace "embedded-resources libcpp"
configurations { "debug", "release" }
platforms { "x86_64", "x86" }
-- _ACTION is the argument you passed into premake5 when you ran it.
local project_action = "UNDEFINED"
if _ACTION ~= nill then project_action = _ACTION end
-- Where the project/make files are output
location(ROOT .. "buildresults/build")
-----------------------------------
-- Global Compiler/Linker Config --
-----------------------------------
filter "configurations:Debug" defines { "DEBUG" } symbols "On"
filter "configurations:Release" defines { "NDEBUG" } optimize "On"
filter { "platforms:x86" } architecture "x86"
filter { "platforms:x86_64" } architecture "x86_64"
-- Global settings for building makefiles
filter { "action:gmake" }
flags { "C++11" }
-- Global settings for building make files on mac specifically
filter { "system:macosx", "action:gmake"}
toolset "clang"
filter {} -- clear filter when you know you no longer need it!
-------------------------------
-- [ PROJECT CONFIGURATION ] --
-------------------------------
project "libcpp_threadx"
kind "StaticLib"
language "C++"
targetdir (RESULTSROOT)
targetname "cpp_threadx"
local SourceDir = ROOT;
files
{
SourceDir .. "mutex.cpp",
SourceDir .. "mutex",
SourceDir .. "__mutex_base"
}
defines { "THREADX=1", "_LIBCPP_NO_EXCEPTIONS", "THREADING=1" }
-- fPIC -ffreestanding?
buildoptions {"-fno-builtin", "-static", "-nodefaultlibs"}
linkoptions {"-static", "-nodefaultlibs", "-nostartfiles",
"-Wl,-preload -Wl,-all_load", "-Wl,-dead_strip", "-Wl,-prebind"}
filter {} -- clear filter!
includedirs
{
SourceDir,
SourceDir .. "../rtos",
"/usr/local/opt/llvm/include/c++/v1/",
"/usr/local/opt/llvm/include"
}
-- Library Dependencies
libdirs
{
}
links
{
}
project "libcpp_freertos"
kind "StaticLib"
language "C++"
targetdir (RESULTSROOT)
targetname "cpp_freertos"
local SourceDir = ROOT;
files
{
SourceDir .. "mutex.cpp",
SourceDir .. "mutex",
SourceDir .. "__mutex_base"
}
defines { "FREERTOS=1", "_LIBCPP_NO_EXCEPTIONS", "THREADING=1" }
-- fPIC -ffreestanding?
buildoptions {"-fno-builtin", "-static", "-nodefaultlibs"}
linkoptions {"-static", "-nodefaultlibs", "-nostartfiles",
"-Wl,-preload -Wl,-all_load", "-Wl,-dead_strip", "-Wl,-prebind"}
filter {} -- clear filter!
includedirs
{
SourceDir,
SourceDir .. "../rtos",
"/usr/local/opt/llvm/include/c++/v1/",
"/usr/local/opt/llvm/include"
}
-- Library Dependencies
libdirs
{
}
links
{
}
|
-- Copyright © 2017 Embedded Artistry LLC.
-- License: MIT. See LICENSE file for details.
-- For reference, please refer to the premake wiki:
-- https://github.com/premake/premake-core/wiki
local ROOT = "./"
local RESULTSROOT = ROOT .. "buildresults/%{cfg.platform}_%{cfg.buildcfg}/"
---------------------------------
-- [ WORKSPACE CONFIGURATION --
---------------------------------
workspace "embedded-resources libcpp"
configurations { "debug", "release" }
platforms { "x86_64", "x86" }
-- _ACTION is the argument you passed into premake5 when you ran it.
local project_action = "UNDEFINED"
if _ACTION ~= nill then project_action = _ACTION end
-- Where the project/make files are output
location(ROOT .. "buildresults/build")
-----------------------------------
-- Global Compiler/Linker Config --
-----------------------------------
filter "configurations:Debug" defines { "DEBUG" } symbols "On"
filter "configurations:Release" defines { "NDEBUG" } optimize "On"
filter { "platforms:x86" } architecture "x86"
filter { "platforms:x86_64" } architecture "x86_64"
-- Global settings for building makefiles
filter { "action:gmake" }
flags { "C++11" }
-- Global settings for building make files on mac specifically
filter { "system:macosx", "action:gmake"}
toolset "clang"
filter {} -- clear filter when you know you no longer need it!
-------------------------------
-- [ PROJECT CONFIGURATION ] --
-------------------------------
project "libcpp_threadx"
kind "StaticLib"
language "C++"
targetdir (RESULTSROOT)
targetname "cpp_threadx"
defines { "THREADX=1", "_LIBCPP_NO_EXCEPTIONS", "THREADING=1" }
local SourceDir = ROOT;
files
{
SourceDir .. "mutex.cpp",
SourceDir .. "mutex",
SourceDir .. "__mutex_base"
}
-- fPIC -ffreestanding?
buildoptions {"-fno-builtin", "-static", "-nodefaultlibs"}
linkoptions {"-static", "-nodefaultlibs", "-nostartfiles",
"-Wl,-preload -Wl,-all_load", "-Wl,-dead_strip", "-Wl,-prebind"}
filter {} -- clear filter!
includedirs
{
SourceDir,
SourceDir .. "../rtos",
"/usr/local/opt/llvm/include/c++/v1/",
"/usr/local/opt/llvm/include"
}
-- Library Dependencies
libdirs
{
}
links
{
}
project "libcpp_freertos"
kind "StaticLib"
language "C++"
targetdir (RESULTSROOT)
targetname "cpp_freertos"
local SourceDir = ROOT;
files
{
SourceDir .. "mutex.cpp",
SourceDir .. "mutex",
SourceDir .. "__mutex_base"
}
defines { "FREERTOS=1", "_LIBCPP_NO_EXCEPTIONS", "THREADING=1" }
-- fPIC -ffreestanding?
buildoptions {"-fno-builtin", "-static", "-nodefaultlibs"}
linkoptions {"-static", "-nodefaultlibs", "-nostartfiles",
"-Wl,-preload -Wl,-all_load", "-Wl,-dead_strip", "-Wl,-prebind"}
filter {} -- clear filter!
includedirs
{
SourceDir,
SourceDir .. "../rtos",
"/usr/local/opt/llvm/include/c++/v1/",
"/usr/local/opt/llvm/include"
}
-- Library Dependencies
libdirs
{
}
links
{
}
|
Reorder to fix sequential build problem in mutex example
|
Reorder to fix sequential build problem in mutex example
|
Lua
|
cc0-1.0
|
embeddedartistry/embedded-resources,phillipjohnston/embedded-resources
|
072a5a60fd9195bce26fc902d552df655659f847
|
extension/script/backend/worker/filesystem.lua
|
extension/script/backend/worker/filesystem.lua
|
local utility = require 'remotedebug.utility'
local ev = require 'common.event'
local rdebug = require 'remotedebug.visitor'
local OS = utility.platform_os()
local absolute = utility.fs_absolute
local u2a = utility.u2a or function (...) return ... end
local a2u = utility.a2u or function (...) return ... end
local sourceFormat = "path"
local pathFormat = "path"
local useWSL = false
local useUtf8 = false
local function towsl(s)
if not useWSL or not s:match "^%a:" then
return s
end
return s:gsub("\\", "/"):gsub("^(%a):", function(c)
return "/mnt/"..c:lower()
end)
end
local function nativepath(s)
if not useWSL and not useUtf8 then
return u2a(s)
end
return towsl(s)
end
local function init_searchpath(config, name)
if not config[name] then
return
end
local value = config[name]
if type(value) == 'table' then
local path = {}
for _, v in ipairs(value) do
if type(v) == "string" then
path[#path+1] = nativepath(v)
end
end
value = table.concat(path, ";")
else
value = nativepath(value)
end
local visitor = rdebug.index(rdebug.index(rdebug._G, "package"), name)
if not rdebug.assign(visitor, value) then
return
end
end
ev.on('initializing', function(config)
sourceFormat = config.sourceFormat or "path"
pathFormat = config.pathFormat or "path"
useWSL = config.useWSL
useUtf8 = config.sourceCoding == "utf8"
init_searchpath(config, 'path')
init_searchpath(config, 'cpath')
end)
local function normalize_posix(p)
local stack = {}
p:gsub('[^/]*', function (w)
if #w == 0 and #stack ~= 0 then
elseif w == '..' and #stack ~= 0 and stack[#stack] ~= '..' then
stack[#stack] = nil
elseif w ~= '.' then
stack[#stack + 1] = w
end
end)
return stack
end
local function normalize_win32(p)
local stack = {}
p:gsub('[^/\\]*', function (w)
if #w == 0 and #stack ~= 0 then
elseif w == '..' and #stack ~= 0 and stack[#stack] ~= '..' then
stack[#stack] = nil
elseif w ~= '.' then
stack[#stack + 1] = w
end
end)
return stack
end
local m = {}
function m.fromwsl(s)
if sourceFormat == "string" then
return s
end
if not useWSL or not s:match "^/mnt/%a" then
return s
end
return s:gsub("^/mnt/(%a)", "%1:")
end
function m.source_native(s)
return sourceFormat == "path" and s:lower() or s
end
function m.path_native(s)
return pathFormat == "path" and s:lower() or s
end
function m.source_normalize(path)
if sourceFormat == "string" then
return path
end
if sourceFormat == "path" then
local absolute_path = OS == 'Windows' and absolute(path) or path
return table.concat(normalize_win32(absolute_path), '/')
end
local absolute_path = OS ~= 'Windows' and absolute(path) or path
return table.concat(normalize_posix(absolute_path), '/')
end
function m.path_normalize(path)
local normalize = pathFormat == "path" and normalize_win32 or normalize_posix
return table.concat(normalize(path), '/')
end
function m.path_relative(path, base)
local normalize = pathFormat == "path" and normalize_win32 or normalize_posix
local rpath = normalize(path)
local rbase = normalize(base)
while #rpath > 0 and #rbase > 0 and rpath[1] == rbase[1] do
table.remove(rpath, 1)
table.remove(rbase, 1)
end
if #rpath == 0 and #rbase== 0 then
return "./"
end
local s = {}
for _ in ipairs(rbase) do
s[#s+1] = '..'
end
for _, e in ipairs(rpath) do
s[#s+1] = e
end
return table.concat(s, '/')
end
function m.path_filename(path)
local normalize = pathFormat == "path" and normalize_win32 or normalize_posix
local paths = normalize(path)
return paths[#paths]
end
m.a2u = a2u
return m
|
local utility = require 'remotedebug.utility'
local ev = require 'common.event'
local rdebug = require 'remotedebug.visitor'
local OS = utility.platform_os()
local absolute = utility.fs_absolute
local u2a = utility.u2a or function (...) return ... end
local a2u = utility.a2u or function (...) return ... end
local sourceFormat = OS == "Windows" and "path" or "linuxpath"
local pathFormat = "path"
local useWSL = false
local useUtf8 = false
local function towsl(s)
if not useWSL or not s:match "^%a:" then
return s
end
return s:gsub("\\", "/"):gsub("^(%a):", function(c)
return "/mnt/"..c:lower()
end)
end
local function nativepath(s)
if not useWSL and not useUtf8 then
return u2a(s)
end
return towsl(s)
end
local function init_searchpath(config, name)
if not config[name] then
return
end
local value = config[name]
if type(value) == 'table' then
local path = {}
for _, v in ipairs(value) do
if type(v) == "string" then
path[#path+1] = nativepath(v)
end
end
value = table.concat(path, ";")
else
value = nativepath(value)
end
local visitor = rdebug.index(rdebug.index(rdebug._G, "package"), name)
if not rdebug.assign(visitor, value) then
return
end
end
ev.on('initializing', function(config)
sourceFormat = config.sourceFormat or (OS == "Windows" and "path" or "linuxpath")
pathFormat = config.pathFormat or "path"
useWSL = config.useWSL
useUtf8 = config.sourceCoding == "utf8"
init_searchpath(config, 'path')
init_searchpath(config, 'cpath')
end)
local function normalize_posix(p)
local stack = {}
p:gsub('[^/]*', function (w)
if #w == 0 and #stack ~= 0 then
elseif w == '..' and #stack ~= 0 and stack[#stack] ~= '..' then
stack[#stack] = nil
elseif w ~= '.' then
stack[#stack + 1] = w
end
end)
return stack
end
local function normalize_win32(p)
local stack = {}
p:gsub('[^/\\]*', function (w)
if #w == 0 and #stack ~= 0 then
elseif w == '..' and #stack ~= 0 and stack[#stack] ~= '..' then
stack[#stack] = nil
elseif w ~= '.' then
stack[#stack + 1] = w
end
end)
return stack
end
local m = {}
function m.fromwsl(s)
if sourceFormat == "string" then
return s
end
if not useWSL or not s:match "^/mnt/%a" then
return s
end
return s:gsub("^/mnt/(%a)", "%1:")
end
function m.source_native(s)
return sourceFormat == "path" and s:lower() or s
end
function m.path_native(s)
return pathFormat == "path" and s:lower() or s
end
function m.source_normalize(path)
if sourceFormat == "string" then
return path
end
if sourceFormat == "path" then
local absolute_path = OS == 'Windows' and absolute(path) or path
return table.concat(normalize_win32(absolute_path), '/')
end
local absolute_path = OS ~= 'Windows' and absolute(path) or path
return table.concat(normalize_posix(absolute_path), '/')
end
function m.path_normalize(path)
local normalize = pathFormat == "path" and normalize_win32 or normalize_posix
return table.concat(normalize(path), '/')
end
function m.path_relative(path, base)
local normalize = pathFormat == "path" and normalize_win32 or normalize_posix
local rpath = normalize(path)
local rbase = normalize(base)
while #rpath > 0 and #rbase > 0 and rpath[1] == rbase[1] do
table.remove(rpath, 1)
table.remove(rbase, 1)
end
if #rpath == 0 and #rbase== 0 then
return "./"
end
local s = {}
for _ in ipairs(rbase) do
s[#s+1] = '..'
end
for _, e in ipairs(rpath) do
s[#s+1] = e
end
return table.concat(s, '/')
end
function m.path_filename(path)
local normalize = pathFormat == "path" and normalize_win32 or normalize_posix
local paths = normalize(path)
return paths[#paths]
end
m.a2u = a2u
return m
|
修复一个bug
|
修复一个bug
|
Lua
|
mit
|
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
|
81a55a0e7a8b6c2c8f996d9a3c0b81d336e18a86
|
src/cosy/server/header/transfer_encoding.lua
|
src/cosy/server/header/transfer_encoding.lua
|
local Transfer_Encoding = {
depends = {
"Connection",
"Content-Length",
"TE",
},
}
function Transfer_Encoding.request (context)
local request = context.request
local headers = request.headers
local tokens = {}
for word in headers.transfer_encoding:gmatch "([^,%s]+)" do
tokens [word:lower ():gsub ("-", "_")] = true
end
headers.transfer_encoding = tokens
--
local skt = context.skt
if tokens.chunked then
local body = ""
repeat
local line
while not line or line == "" do
line = skt:receive "*l"
end
body = body .. skt:receive (tonumber (line))
until size == 0 or not size
request.body = body
end
if headers.connection and headers.connection.te then
repeat
local line = skt:receive "*l"
if line ~= "" then
local name, value = line:match "([^:]+):%s*(.*)"
name = name:trim ():lower ():gsub ("-", "_")
value = value:trim ()
headers [name] = value
end
until line == ""
end
end
function Transfer_Encoding.response (context)
context.response.headers.transfer_encoding = nil
end
return Transfer_Encoding
|
local Transfer_Encoding = {
depends = {
"Connection",
"Content-Length",
"TE",
},
}
function Transfer_Encoding.request (context)
local request = context.request
local headers = request.headers
local tokens = {}
for word in headers.transfer_encoding:gmatch "([^,%s]+)" do
tokens [word:lower ():gsub ("-", "_")] = true
end
headers.transfer_encoding = tokens
--
local skt = context.skt
if tokens.chunked then
local body = ""
repeat
local line
while not line or line == "" do
line = skt:receive "*l"
end
local size = tonumber (line)
body = body .. skt:receive (size)
until size == 0 or not size
request.body = body
end
if headers.connection and headers.connection.te then
repeat
local line = skt:receive "*l"
if line ~= "" then
local name, value = line:match "([^:]+):%s*(.*)"
name = name:trim ():lower ():gsub ("-", "_")
value = value:trim ()
headers [name] = value
end
until line == ""
end
end
function Transfer_Encoding.response (context)
context.response.headers.transfer_encoding = nil
end
return Transfer_Encoding
|
Fix missing variable.
|
Fix missing variable.
|
Lua
|
mit
|
CosyVerif/data-server,CosyVerif/data-server
|
d66eab4b15a74808a297e61254c81484f139683c
|
telnet.lua
|
telnet.lua
|
--
-- setup a telnet server that hooks the sockets input
--
local client
local server
local function sendout(str)
if client then
client:send(str)
end
end
local function onReceive(sock, input)
node.input(input)
end
local function onDisconnect(sock)
node.output(nil)
client = nil
end
local function listen(sock)
if client then
sock:send("Already in use.\n")
sock:close()
return
end
client = sock
node.output(sendout, 0)
sock:on("receive", onReceive)
sock:on("disconnection", onDisconnect)
sock:send("NodeMCU\n")
end
local function open()
server = net.createServer(net.TCP, 180)
server:listen(23, listen)
end
local function close()
if client then
client:close()
client = nil
end
if server then
server:close()
server = nil
end
end
return { open = open, close = close }
|
--
-- setup a telnet server that hooks the sockets input
--
local client
local server
local fifo
local drained
local function sendnext(sock)
local s = table.remove(fifo, 1)
if s then
sock:send(s)
else
drained = true
end
end
local function output(s)
if client then
table.insert(fifo, s)
if drained then
drained = false
sendnext(client)
end
end
end
local function onReceive(sock, input)
node.input(input)
end
local function onDisconnect(sock)
node.output(nil)
client = nil
fifo = nil
drained = nil
end
local function listen(sock)
if client then
sock:send("Already in use.\n")
sock:close()
return
end
client = sock
fifo = {}
drained = true
node.output(output, 0)
sock:on("receive", onReceive)
sock:on("disconnection", onDisconnect)
sock:on("sent", sendnext)
sock:send("NodeMCU\n")
end
local function open(port)
server = net.createServer(net.TCP, 180)
server:listen(port or 23, listen)
end
local function close()
if client then
client:close()
client = nil
end
if server then
server:close()
server = nil
end
end
return { open = open, close = close }
|
use fifo to send output to telnet client
|
use fifo to send output to telnet client
Should fix issues with only the first line of multiline output being displayed
|
Lua
|
mit
|
realraum/r3LoTHRPipeLEDs,realraum/r3LoTHRPipeLEDs
|
7fd896e7dfc30be91c3b1ac41aa7248720671a94
|
libs/web/luasrc/template.lua
|
libs/web/luasrc/template.lua
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.template", package.seeall)
require("luci.config")
require("luci.util")
require("luci.fs")
require("luci.http")
luci.config.template = luci.config.template or {}
viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
-- Enforce cache security
compiledir = compiledir .. "/" .. luci.sys.process.info("uid")
-- Compile modes:
-- none: Never compile, only use precompiled data from files
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = luci.config.template.compiler_mode or "memory"
-- Define the namespace for template modules
viewns = {
write = io.write,
include = function(name) Template(name):render(getfenv(2)) end,
}
-- Compiles a given template into an executable Lua module
function compile(template)
-- Search all <% %> expressions (remember: Lua table indexes begin with #1)
local function expr_add(command)
table.insert(expr, command)
return "<%" .. tostring(#expr) .. "%>"
end
-- As "expr" should be local, we have to assign it to the "expr_add" scope
local expr = {}
luci.util.extfenv(expr_add, "expr", expr)
-- Save all expressiosn to table "expr"
template = template:gsub("<%%(.-)%%>", expr_add)
local function sanitize(s)
s = luci.util.escape(s)
s = luci.util.escape(s, "'")
s = luci.util.escape(s, "\n")
return s
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = "write('"
local footer = "')"
template = header .. template .. footer
-- Replacements
local r_include = "')\ninclude('%s')\nwrite('"
local r_i18n = "'..translate('%1','%2')..'"
local r_pexec = "'..(%s or '')..'"
local r_exec = "')\n%s\nwrite('"
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
elseif p == "=" then
re = r_pexec:format(v:sub(2))
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
-- Oldstyle render shortcut
function render(name, scope, ...)
scope = scope or getfenv(2)
local s, t = pcall(Template, name)
if not s then
error(t)
else
t:render(scope, ...)
end
end
-- Template class
Template = luci.util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = {}
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
if self.cache[name] then
self.template = self.cache[name]
else
self.template = nil
end
-- Create a new namespace for this template
self.viewns = {}
-- Copy over from general namespace
for k, v in pairs(viewns) do
self.viewns[k] = v
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Compile and build
local sourcefile = viewdir .. "/" .. name .. ".htm"
local compiledfile = compiledir .. "/" .. luci.http.urlencode(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = luci.fs.mtime(sourcefile)
local commt = luci.fs.mtime(compiledfile)
if not luci.fs.mtime(compiledir) then
luci.fs.mkdir(compiledir, true)
luci.fs.chmod(luci.fs.dirname(compiledir), "a+rxw")
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
luci.fs.writefile(compiledfile, luci.util.dump(compiled))
self.template = compiled
end
else
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "none" then
self.template, err = loadfile(self.compiledfile)
elseif compiler_mode == "memory" then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
luci.util.resfenv(self.template)
luci.util.updfenv(self.template, scope)
luci.util.updfenv(self.template, self.viewns)
-- Now finally render the thing
self.template()
-- Reset environment
setfenv(self.template, oldfenv)
end
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.template", package.seeall)
require("luci.config")
require("luci.util")
require("luci.fs")
require("luci.http")
luci.config.template = luci.config.template or {}
viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
-- Compile modes:
-- none: Never compile, only use precompiled data from files
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = luci.config.template.compiler_mode or "memory"
-- Define the namespace for template modules
viewns = {
write = io.write,
include = function(name) Template(name):render(getfenv(2)) end,
}
-- Compiles a given template into an executable Lua module
function compile(template)
-- Search all <% %> expressions (remember: Lua table indexes begin with #1)
local function expr_add(command)
table.insert(expr, command)
return "<%" .. tostring(#expr) .. "%>"
end
-- As "expr" should be local, we have to assign it to the "expr_add" scope
local expr = {}
luci.util.extfenv(expr_add, "expr", expr)
-- Save all expressiosn to table "expr"
template = template:gsub("<%%(.-)%%>", expr_add)
local function sanitize(s)
s = luci.util.escape(s)
s = luci.util.escape(s, "'")
s = luci.util.escape(s, "\n")
return s
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = "write('"
local footer = "')"
template = header .. template .. footer
-- Replacements
local r_include = "')\ninclude('%s')\nwrite('"
local r_i18n = "'..translate('%1','%2')..'"
local r_pexec = "'..(%s or '')..'"
local r_exec = "')\n%s\nwrite('"
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
elseif p == "=" then
re = r_pexec:format(v:sub(2))
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
-- Oldstyle render shortcut
function render(name, scope, ...)
scope = scope or getfenv(2)
local s, t = pcall(Template, name)
if not s then
error(t)
else
t:render(scope, ...)
end
end
-- Template class
Template = luci.util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = {}
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
if self.cache[name] then
self.template = self.cache[name]
else
self.template = nil
end
-- Create a new namespace for this template
self.viewns = {}
-- Copy over from general namespace
for k, v in pairs(viewns) do
self.viewns[k] = v
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Enforce cache security
local cdir = compiledir .. "/" .. luci.sys.process.info("uid")
-- Compile and build
local sourcefile = viewdir .. "/" .. name .. ".htm"
local compiledfile = cdir .. "/" .. luci.http.urlencode(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = luci.fs.mtime(sourcefile)
local commt = luci.fs.mtime(compiledfile)
if not luci.fs.mtime(cdir) then
luci.fs.mkdir(cdir, true)
luci.fs.chmod(luci.fs.dirname(cdir), "a+rxw")
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
luci.fs.writefile(compiledfile, luci.util.dump(compiled))
self.template = compiled
end
else
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "none" then
self.template, err = loadfile(self.compiledfile)
elseif compiler_mode == "memory" then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
luci.util.resfenv(self.template)
luci.util.updfenv(self.template, scope)
luci.util.updfenv(self.template, self.viewns)
-- Now finally render the thing
self.template()
-- Reset environment
setfenv(self.template, oldfenv)
end
|
* libs/web: Fixed secure caching with setuid/setgid handling
|
* libs/web: Fixed secure caching with setuid/setgid handling
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2309 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,Flexibity/luci,saraedum/luci-packages-old,vhpham80/luci,Flexibity/luci,ch3n2k/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,8devices/carambola2-luci,gwlim/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,jschmidlapp/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,saraedum/luci-packages-old,alxhh/piratenluci,ch3n2k/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,Canaan-Creative/luci,vhpham80/luci,phi-psi/luci,alxhh/piratenluci,stephank/luci,ch3n2k/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,stephank/luci,projectbismark/luci-bismark,gwlim/luci,Flexibity/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,8devices/carambola2-luci,freifunk-gluon/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,ThingMesh/openwrt-luci,gwlim/luci,8devices/carambola2-luci,projectbismark/luci-bismark,ch3n2k/luci,freifunk-gluon/luci,phi-psi/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,gwlim/luci,phi-psi/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,eugenesan/openwrt-luci,ch3n2k/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,jschmidlapp/luci,8devices/carambola2-luci,jschmidlapp/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,alxhh/piratenluci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,8devices/carambola2-luci,alxhh/piratenluci,dtaht/cerowrt-luci-3.3,stephank/luci,vhpham80/luci,alxhh/piratenluci,yeewang/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,Flexibity/luci,gwlim/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,vhpham80/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,stephank/luci,freifunk-gluon/luci,projectbismark/luci-bismark,phi-psi/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,saraedum/luci-packages-old,freifunk-gluon/luci,8devices/carambola2-luci,ch3n2k/luci,phi-psi/luci,phi-psi/luci,alxhh/piratenluci,jschmidlapp/luci,Flexibity/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,stephank/luci,alxhh/piratenluci
|
04585beaafe473757b93f3f84319e687aca73e34
|
hammerspoon/hammerspoon.symlink/modules/audio-device.lua
|
hammerspoon/hammerspoon.symlink/modules/audio-device.lua
|
-- Define audio device names for headphone/speaker switching
local usbAudioSearch = "VIA Technologies" -- USB sound card
-- Toggle between speaker and headphone sound devices (useful if you have multiple USB soundcards that are always connected)
function setDefaultAudio()
local current = hs.audiodevice.defaultOutputDevice()
local usbAudio = findOutputByPartialUID(usbAudioSearch)
if usbAudio and current:name() ~= usbAudio:name() then
usbAudio:setDefaultOutputDevice()
end
hs.notify.new({
title='Hammerspoon',
informativeText='Default output device:' .. hs.audiodevice.defaultOutputDevice():name()
}):send()
end
function findOutputByPartialUID(uid)
for _, device in pairs(hs.audiodevice.allOutputDevices()) do
if device:uid():match(uid) then
return device
end
end
end
hs.usb.watcher.new(setDefaultAudio):start()
setDefaultAudio()
|
-- -- Define audio device names for headphone/speaker switching
-- local usbAudioSearch = "VIA Technologies" -- USB sound card
--
-- -- Toggle between speaker and headphone sound devices (useful if you have multiple USB soundcards that are always connected)
-- function setDefaultAudio()
-- local current = hs.audiodevice.defaultOutputDevice()
-- local usbAudio = findOutputByPartialUID(usbAudioSearch)
--
-- if usbAudio and current:name() ~= usbAudio:name() then
-- usbAudio:setDefaultOutputDevice()
-- end
--
-- hs.notify.new({
-- title='Hammerspoon',
-- informativeText='Default output device:' .. hs.audiodevice.defaultOutputDevice():name()
-- }):send()
-- end
--
-- function findOutputByPartialUID(uid)
-- for _, device in pairs(hs.audiodevice.allOutputDevices()) do
-- if device:uid():match(uid) then
-- return device
-- end
-- end
-- end
--
-- hs.usb.watcher.new(setDefaultAudio):start()
-- setDefaultAudio()
|
fix(Hammerspoon): Disable audio switcher, it causes unexpected audio splitting
|
fix(Hammerspoon): Disable audio switcher, it causes unexpected audio splitting
|
Lua
|
mit
|
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
|
64dd93128926f2bf1941fc459a271bd2043c0bc3
|
MMOCoreORB/bin/scripts/screenplays/caves/tatooine_hutt_hideout.lua
|
MMOCoreORB/bin/scripts/screenplays/caves/tatooine_hutt_hideout.lua
|
HuttHideoutScreenPlay = ScreenPlay:new {
numberOfActs = 1,
lootContainers = {
134411,
8496263,
8496262,
8496260
},
lootLevel = 32,
lootGroups = "armor_attachments",
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("HuttHideoutScreenPlay", true)
function HuttHideoutScreenPlay:start()
self:spawnMobiles()
self:initializeLootContainers()
end
function HuttHideoutScreenPlay:spawnMobiles()
spawnMobile("tatooine", "jabba_enforcer", 200, -3.5, -12.7, -6.7, 24, 4235585)
spawnMobile("tatooine", "jabba_henchman", 200, 1.1, -14.4, -9.3, 15, 4235585)
spawnMobile("tatooine", "jabba_compound_guard", 200, -12.1, -32.2, -34, 19, 4235586)
spawnMobile("tatooine", "jabba_enforcer", 200, -10.5, -40.4, -81.3, -178, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 5.8, -40.9, -79.6, -37, 4235587)
spawnMobile("tatooine", "jabba_enforcer", 200, 14.5, -40.5, -74.2, -131, 4235587)
spawnMobile("tatooine", "jabba_enforcer", 200, 20, -39.6, -77.9, -50, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 10.7, -41.1, -60.3, -124, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 47, -46.7, -50.8, -163, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 50.4, -46.8, -58.6, -19, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 51.6, -46, -91.6, -126, 4235588)
spawnMobile("tatooine", "jabba_enforcer", 200, 47.1, -46.2, -96.3, 46, 4235588)
spawnMobile("tatooine", "jabba_compound_guard", 200, 44.9, -46.2, -102.8, -41, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 13.9, -45, -121.1, 30, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 1.5, -45, -141.6, 117, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, -10, -45.6, -148, 26, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, -12.4, -45, -130.8, 125, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 58.8, -47.1, -124.6, -21, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 73.5, -52.9, -144.7, -178, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 72.5, -54.4, -151.6, -20, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 38.2, -55.7, -155.4, -78, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 36.9, -56.1, -157.2, -53, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 67.5, -57.3, -176.7, 62, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 58.6, -57.7, -185.3, -70, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 53, -57, -185.3, 59, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 58.8, -56.4, -159.5, -60, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 53.3, -56.6, -160.2, 45, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 6, -63.9, -181.8, 90, 4235590)
spawnMobile("tatooine", "jabba_compound_guard", 200, -8.1, -65.1, -201.3, -10, 4235590)
spawnMobile("tatooine", "jabba_compound_guard", 200, -37.5, -67, -182.8, 91, 4235590)
spawnMobile("tatooine", "jabba_henchman", 200, -18.7, -65.5, -210.3, -152, 4235591)
spawnMobile("tatooine", "jabba_compound_guard", 200, -22.5, -64.6, -220.2, -131, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -17.6, -65.4, -216.8, -7, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -4.8, -64.2, -231.5, 178, 4235591)
spawnMobile("tatooine", "jabba_assassin", 200, -1.3, -64.2, -238.5, 88, 4235591)
spawnMobile("tatooine", "jabba_compound_guard", 200, -224, -65, -249.8, -174, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -19.3, -62.6, -261.6, 43, 4235591)
spawnMobile("tatooine", "jabba_assassin", 200, -10.6, -63.3, -261.2, -77, 4235591)
end
function HuttHideoutScreenPlay:initializeLootContainers()
for k,v in pairs(self.lootContainers) do
local pContainer = getSceneObject(v)
createObserver(OPENCONTAINER, "HuttHideoutScreenPlay", "spawnContainerLoot", pContainer)
end
end
function HuttHideoutScreenPlay:spawnContainerLoot(pContainer)
if (pContainer == nil) then
return
end
local container = LuaSceneObject(pContainer)
local time = getTimestamp()
print(time)
print(readData(container:getObjectID()))
if (readData(container:getObjectID()) > time) then
return
end
--If it has loot already, then exit.
if (container:getContainerObjectsSize() > 0) then
return
end
local lootGroup = self:selectLootGroup()
createLoot(pContainer, lootGroup, self.lootLevel)
print(time + self.lootContainerRespawn)
writeData(container:getObjectID(), time + self.lootContainerRespawn)
end
function HuttHideoutScreenPlay:selectLootGroup()
--TODO: Expand this to allow for multiple loot groups.
return self.lootGroups
end
|
HuttHideoutScreenPlay = ScreenPlay:new {
numberOfActs = 1,
lootContainers = {
134411,
8496263,
8496262,
8496260
},
lootLevel = 32,
lootGroups = "armor_attachments",
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("HuttHideoutScreenPlay", true)
function HuttHideoutScreenPlay:start()
self:spawnMobiles()
self:initializeLootContainers()
end
function HuttHideoutScreenPlay:spawnMobiles()
spawnMobile("tatooine", "jabba_enforcer", 200, -3.5, -12.7, -6.7, 24, 4235585)
spawnMobile("tatooine", "jabba_henchman", 200, 1.1, -14.4, -9.3, 15, 4235585)
spawnMobile("tatooine", "jabba_compound_guard", 200, -12.1, -32.2, -34, 19, 4235586)
spawnMobile("tatooine", "jabba_enforcer", 200, -10.5, -40.4, -81.3, -178, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 5.8, -40.9, -79.6, -37, 4235587)
spawnMobile("tatooine", "jabba_enforcer", 200, 14.5, -40.5, -74.2, -131, 4235587)
spawnMobile("tatooine", "jabba_enforcer", 200, 20, -39.6, -77.9, -50, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 10.7, -41.1, -60.3, -124, 4235587)
spawnMobile("tatooine", "jabba_henchman", 200, 47, -46.7, -50.8, -163, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 50.4, -46.8, -58.6, -19, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 51.6, -46, -91.6, -126, 4235588)
spawnMobile("tatooine", "jabba_enforcer", 200, 47.1, -46.2, -96.3, 46, 4235588)
spawnMobile("tatooine", "jabba_compound_guard", 200, 44.9, -46.2, -102.8, -41, 4235588)
spawnMobile("tatooine", "jabba_henchman", 200, 13.9, -45, -121.1, 30, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 1.5, -45, -141.6, 117, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, -10, -45.6, -148, 26, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, -12.4, -45, -130.8, 125, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 58.8, -47.1, -124.6, -21, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 73.5, -52.9, -144.7, -178, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 72.5, -54.4, -151.6, -20, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 38.2, -55.7, -155.4, -78, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 36.9, -56.1, -157.2, -53, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 67.5, -57.3, -176.7, 62, 4235589)
spawnMobile("tatooine", "jabba_enforcer", 200, 58.6, -57.7, -185.3, -70, 4235589)
spawnMobile("tatooine", "jabba_henchman", 200, 53, -57, -185.3, 59, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 58.8, -56.4, -159.5, -60, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 53.3, -56.6, -160.2, 45, 4235589)
spawnMobile("tatooine", "jabba_compound_guard", 200, 6, -63.9, -181.8, 90, 4235590)
spawnMobile("tatooine", "jabba_compound_guard", 200, -8.1, -65.1, -201.3, -10, 4235590)
spawnMobile("tatooine", "jabba_compound_guard", 200, -37.5, -67, -182.8, 91, 4235590)
spawnMobile("tatooine", "jabba_henchman", 200, -18.7, -65.5, -210.3, -152, 4235591)
spawnMobile("tatooine", "jabba_compound_guard", 200, -22.5, -64.6, -220.2, -131, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -17.6, -65.4, -216.8, -7, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -4.8, -64.2, -231.5, 178, 4235591)
spawnMobile("tatooine", "jabba_assassin", 200, -1.3, -64.2, -238.5, 88, 4235591)
spawnMobile("tatooine", "jabba_compound_guard", 200, -224, -65, -249.8, -174, 4235591)
spawnMobile("tatooine", "jabba_henchman", 200, -19.3, -62.6, -261.6, 43, 4235591)
spawnMobile("tatooine", "jabba_assassin", 200, -10.6, -63.3, -261.2, -77, 4235591)
end
function HuttHideoutScreenPlay:initializeLootContainers()
for k,v in pairs(self.lootContainers) do
local pContainer = getSceneObject(v)
createObserver(OPENCONTAINER, "HuttHideoutScreenPlay", "spawnContainerLoot", pContainer)
end
end
function HuttHideoutScreenPlay:spawnContainerLoot(pContainer)
if (pContainer == nil) then
return
end
local container = LuaSceneObject(pContainer)
local time = getTimestamp()
if (readData(container:getObjectID()) > time) then
return
end
--If it has loot already, then exit.
if (container:getContainerObjectsSize() > 0) then
return
end
local lootGroup = self:selectLootGroup()
createLoot(pContainer, lootGroup, self.lootLevel)
writeData(container:getObjectID(), time + self.lootContainerRespawn)
end
function HuttHideoutScreenPlay:selectLootGroup()
--TODO: Expand this to allow for multiple loot groups.
return self.lootGroups
end
|
(unstable) [fixed] Removed debug statements.
|
(unstable) [fixed] Removed debug statements.
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5488 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
|
ffbd7cc79eea7a0a4fd5d74f7609836bedfcb366
|
Disks/Config/Configuring.lua
|
Disks/Config/Configuring.lua
|
------- Metadata --------------------------------------------------------------
-- Configuring
-- Author: Lucky Penny
-- Description: Generates the meters necessary for disks configuration.
-- License: Creative Commons BY-NC-SA 3.0
-- Version: 0.0.1
--
-- Initialize(): As described.
-------------------------------------------------------------------------------
function Initialize()
dofile(SKIN:ReplaceVariables("#@#").."FileHelper.lua")
local disks = ReadIni(SKIN:ReplaceVariables("#@#").."disks.var")
local refreshDisks = false
if next(disks)==nil then refreshDisks = true end
local generated = ReadIni(SKIN:ReplaceVariables("#CurrentPath#").."generated.inc")
local refreshGenerated = false
if next(generated)==nil then refreshGenerated = true end
local templateDiskMeters = ReadFile(SKIN:ReplaceVariables("#CurrentPath#").."TemplateDiskMeters.inc")
local templateDiskVars = ReadFile(SKIN:ReplaceVariables("#@#").."Templates\\TemplateDisksDefault.inc")
-- loop through the data for each disk
local variables = {}
GenerateMetadata(variables,"DisksSettings","Lucky Penny","Variables for the disks","0.0.1")
table.insert(variables,"[Variables]")
table.insert(variables,"DisksTotal="..disks.Variables.DisksTotal)
local content = {}
for loop=1,disks.Variables.DisksTotal,1 do
local currentDisk = ("Disk%s"):format(loop)
if not disks.Variables[currentDisk.."Letter"] then refreshDisks = true end
if not generated[currentDisk.."Title"] then refreshGenerated = true end
for _,value in ipairs(templateDiskMeters) do
local str = ""
if value:find("|") then
str = value:gsub("|",currentDisk)
else
str = value
end
table.insert(content,str)
end
for _,value in ipairs(templateDiskVars) do
local str = ""
if value:find("|") then
str = value:gsub("|",currentDisk)
else
str = value
end
table.insert(variables,str)
end
end
if generated["Disk"..(tonumber(disks.Variables.DisksTotal)+1).."Title"] then
refreshGenerated = true
end
-- Writes the values to files
if refreshDisks or refreshGenerated then
WriteFile(table.concat(variables,"\n"),SKIN:ReplaceVariables("#@#").."disks.var")
WriteFile(table.concat(content,"\n"),SKIN:ReplaceVariables("#CurrentPath#").."generated.inc")
SKIN:Bang('!RefreshGroup Disks')
end
SKIN:Bang("!UpdateMeter SkinSizing")
end
|
------- Metadata --------------------------------------------------------------
-- Configuring
-- Author: Lucky Penny
-- Description: Generates the meters necessary for disks configuration.
-- License: Creative Commons BY-NC-SA 3.0
-- Version: 0.0.1
--
-- Initialize(): As described.
-------------------------------------------------------------------------------
function Initialize()
dofile(SKIN:ReplaceVariables("#@#").."FileHelper.lua")
local disks = ReadIni(SKIN:ReplaceVariables("#@#").."disks.var")
local refreshDisks = false
if next(disks)==nil then refreshDisks = true end
local generated = ReadIni(SKIN:ReplaceVariables("#CurrentPath#").."generated.inc")
local refreshGenerated = false
if next(generated)==nil then refreshGenerated = true end
local templateDiskMeters = ReadFile(SKIN:ReplaceVariables("#CurrentPath#").."TemplateDiskMeters.inc")
local templateDiskVars = ReadFile(SKIN:ReplaceVariables("#@#").."Templates\\TemplateDisksDefault.inc")
-- loop through the data for each disk
local variables = {}
GenerateMetadata(variables,"DisksSettings","Lucky Penny","Variables for the disks","0.0.1")
table.insert(variables,"[Variables]")
table.insert(variables,"DisksTotal="..disks.Variables.DisksTotal)
local content = {}
for loop=1,disks.Variables.DisksTotal,1 do
local currentDisk = ("Disk%s"):format(loop)
if not disks.Variables[currentDisk.."Letter"] then refreshDisks = true end
if not generated[currentDisk.."Title"] then refreshGenerated = true end
for _,value in ipairs(templateDiskMeters) do
local str = ""
if value:find("|") then
str = value:gsub("|",currentDisk)
else
str = value
end
table.insert(content,str)
end
for _,value in ipairs(templateDiskVars) do
local str = ""
if value:find("|") then
str = value:gsub("|",currentDisk)
else
str = value
end
if str:find("DisksTotal")==nil then table.insert(variables,str) end
end
end
if generated["Disk"..(tonumber(disks.Variables.DisksTotal)+1).."Title"] then
refreshGenerated = true
end
-- Writes the values to files
if refreshDisks or refreshGenerated then
WriteFile(table.concat(variables,"\n"),SKIN:ReplaceVariables("#@#").."disks.var")
WriteFile(table.concat(content,"\n"),SKIN:ReplaceVariables("#CurrentPath#").."generated.inc")
SKIN:Bang('!RefreshGroup Disks')
end
SKIN:Bang("!UpdateMeter SkinSizing")
end
|
DisksConfig: Bug corrected Since the Var file template mentions the DiskTotal, care had to be taken to not have it repeat. Otherwise the config window and the meter itself wouldn't be able to generate properly
|
DisksConfig: Bug corrected
Since the Var file template mentions the DiskTotal, care had to be taken to not have it repeat. Otherwise the config window and the meter itself wouldn't be able to generate properly
|
Lua
|
unlicense
|
Spesiel/LuckysDashboard,Spesiel/LuckysDashboard
|
9b329f3e5246477f039a1fb2b129706370237c89
|
src/lua-factory/sources/grl-spotify-cover.lua
|
src/lua-factory/sources/grl-spotify-cover.lua
|
--[[
* Copyright (C) 2015 Bastien Nocera.
*
* Contact: Bastien Nocera <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-spotify-cover",
name = "Spotify Cover",
description = "a source for music covers",
supported_keys = { 'thumbnail' },
supported_media = { 'audio' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "album" },
},
tags = { 'music', 'net:internet' },
}
------------------
-- Source utils --
------------------
SPOTIFY_SEARCH_ALBUM = 'https://api.spotify.com/v1/search?q=album:%s+artist:%s&type=album&limit=1'
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.album
or #req.artist == 0 or #req.album == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = grl.encode(req.artist)
album = grl.encode(req.album)
url = string.format(SPOTIFY_SEARCH_ALBUM, album, artist)
grl.fetch(url, "fetch_page_cb")
end
---------------
-- Utilities --
---------------
function fetch_page_cb(result)
local json = {}
if not result then
grl.callback()
return
end
json = grl.lua.json.string_to_table(result)
if not json or
not json.albums or
json.albums.total == 0 or
not json.albums.items or
not #json.albums.items or
not json.albums.items[1].images then
grl.callback()
return
end
local media = {}
media.thumbnail = {}
for i, item in ipairs(json.albums.items[1].images) do
table.insert(media.thumbnail, item.url)
end
grl.callback(media, 0)
end
|
--[[
* Copyright (C) 2015 Bastien Nocera.
*
* Contact: Bastien Nocera <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-spotify-cover",
name = "Spotify Cover",
description = "a source for music covers",
supported_keys = { 'thumbnail' },
supported_media = { 'audio' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "album" },
},
tags = { 'music', 'net:internet' },
}
------------------
-- Source utils --
------------------
SPOTIFY_SEARCH_ALBUM = 'https://api.spotify.com/v1/search?q=album:%s+artist:%s&type=album&limit=1'
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve(media, options, callback)
local url
local artist, title
if not media or not media.artist or not media.album
or #media.artist == 0 or #media.album == 0 then
callback()
return
end
-- Prepare artist and title strings to the url
artist = grl.encode(media.artist)
album = grl.encode(media.album)
url = string.format(SPOTIFY_SEARCH_ALBUM, album, artist)
local userdata = {callback = callback, media = media}
grl.fetch(url, fetch_page_cb, userdata)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(result, userdata)
local json = {}
if not result then
userdata.callback()
return
end
json = grl.lua.json.string_to_table(result)
if not json or
not json.albums or
json.albums.total == 0 or
not json.albums.items or
not #json.albums.items or
not json.albums.items[1].images then
userdata.callback()
return
end
userdata.media.thumbnail = {}
for i, item in ipairs(json.albums.items[1].images) do
table.insert(userdata.media.thumbnail, item.url)
end
userdata.callback(userdata.media, 0)
end
|
lua-factory: port grl-spotify-cover.lua to the new lua system
|
lua-factory: port grl-spotify-cover.lua to the new lua system
https://bugzilla.gnome.org/show_bug.cgi?id=753141
Acked-by: Victor Toso <[email protected]>
|
Lua
|
lgpl-2.1
|
jasuarez/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins
|
83288c969ee29a62f3babcb00cfa5fa5394d7c67
|
worldedit_commands/mark.lua
|
worldedit_commands/mark.lua
|
worldedit.marker1 = {}
worldedit.marker2 = {}
worldedit.marker_region = {}
--marks worldedit region position 1
worldedit.mark_pos1 = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if pos1 ~= nil then
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos1)
end
if worldedit.marker1[name] ~= nil then --marker already exists
worldedit.marker1[name]:remove() --remove marker
worldedit.marker1[name] = nil
end
if pos1 ~= nil then
--add marker
worldedit.marker1[name] = minetest.add_entity(pos1, "worldedit:pos1")
if worldedit.marker1[name] ~= nil then
worldedit.marker1[name]:get_luaentity().player_name = name
end
end
worldedit.mark_region(name)
end
--marks worldedit region position 2
worldedit.mark_pos2 = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if pos2 ~= nil then
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos2, pos2)
end
if worldedit.marker2[name] ~= nil then --marker already exists
worldedit.marker2[name]:remove() --remove marker
worldedit.marker2[name] = nil
end
if pos2 ~= nil then
--add marker
worldedit.marker2[name] = minetest.add_entity(pos2, "worldedit:pos2")
if worldedit.marker2[name] ~= nil then
worldedit.marker2[name]:get_luaentity().player_name = name
end
end
worldedit.mark_region(name)
end
worldedit.mark_region = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if worldedit.marker_region[name] ~= nil then --marker already exists
--wip: make the area stay loaded somehow
for _, entity in ipairs(worldedit.marker_region[name]) do
entity:remove()
end
worldedit.marker_region[name] = nil
end
if pos1 ~= nil and pos2 ~= nil then
local pos1, pos2 = worldedit.sort_pos(pos1, pos2)
local thickness = 0.2
local sizex, sizey, sizez = (1 + pos2.x - pos1.x) / 2, (1 + pos2.y - pos1.y) / 2, (1 + pos2.z - pos1.z) / 2
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos2)
local markers = {}
--XY plane markers
for _, z in ipairs({pos1.z - 0.5, pos2.z + 0.5}) do
local marker = minetest.add_entity({x=pos1.x + sizex - 0.5, y=pos1.y + sizey - 0.5, z=z}, "worldedit:region_cube")
marker:set_properties({
visual_size={x=sizex * 2, y=sizey * 2},
collisionbox = {-sizex, -sizey, -thickness, sizex, sizey, thickness},
})
marker:get_luaentity().player_name = name
table.insert(markers, marker)
end
--YZ plane markers
for _, x in ipairs({pos1.x - 0.5, pos2.x + 0.5}) do
local marker = minetest.add_entity({x=x, y=pos1.y + sizey - 0.5, z=pos1.z + sizez - 0.5}, "worldedit:region_cube")
marker:set_properties({
visual_size={x=sizez * 2, y=sizey * 2},
collisionbox = {-thickness, -sizey, -sizez, thickness, sizey, sizez},
})
marker:setyaw(math.pi / 2)
marker:get_luaentity().player_name = name
table.insert(markers, marker)
end
worldedit.marker_region[name] = markers
end
end
minetest.register_entity(":worldedit:pos1", {
initial_properties = {
visual = "cube",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_pos1.png", "worldedit_pos1.png",
"worldedit_pos1.png", "worldedit_pos1.png",
"worldedit_pos1.png", "worldedit_pos1.png"},
collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker1[self.player_name] == nil then
self.object:remove()
end
end,
on_punch = function(self, hitter)
self.object:remove()
worldedit.marker1[self.player_name] = nil
end,
})
minetest.register_entity(":worldedit:pos2", {
initial_properties = {
visual = "cube",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_pos2.png", "worldedit_pos2.png",
"worldedit_pos2.png", "worldedit_pos2.png",
"worldedit_pos2.png", "worldedit_pos2.png"},
collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker2[self.player_name] == nil then
self.object:remove()
end
end,
on_punch = function(self, hitter)
self.object:remove()
worldedit.marker2[self.player_name] = nil
end,
})
minetest.register_entity(":worldedit:region_cube", {
initial_properties = {
visual = "upright_sprite",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_cube.png"},
visual_size = {x=10, y=10},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker_region[self.player_name] == nil then
self.object:remove()
return
end
end,
on_punch = function(self, hitter)
local markers = worldedit.marker_region[self.player_name]
if not markers then
return
end
for _, entity in ipairs(markers) do
entity:remove()
end
worldedit.marker_region[self.player_name] = nil
end,
})
|
worldedit.marker1 = {}
worldedit.marker2 = {}
worldedit.marker_region = {}
--marks worldedit region position 1
worldedit.mark_pos1 = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if pos1 ~= nil then
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos1)
end
if worldedit.marker1[name] ~= nil then --marker already exists
worldedit.marker1[name]:remove() --remove marker
worldedit.marker1[name] = nil
end
if pos1 ~= nil then
--add marker
worldedit.marker1[name] = minetest.add_entity(pos1, "worldedit:pos1")
if worldedit.marker1[name] ~= nil then
worldedit.marker1[name]:get_luaentity().player_name = name
end
end
worldedit.mark_region(name)
end
--marks worldedit region position 2
worldedit.mark_pos2 = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if pos2 ~= nil then
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos2, pos2)
end
if worldedit.marker2[name] ~= nil then --marker already exists
worldedit.marker2[name]:remove() --remove marker
worldedit.marker2[name] = nil
end
if pos2 ~= nil then
--add marker
worldedit.marker2[name] = minetest.add_entity(pos2, "worldedit:pos2")
if worldedit.marker2[name] ~= nil then
worldedit.marker2[name]:get_luaentity().player_name = name
end
end
worldedit.mark_region(name)
end
worldedit.mark_region = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if worldedit.marker_region[name] ~= nil then --marker already exists
--wip: make the area stay loaded somehow
for _, entity in ipairs(worldedit.marker_region[name]) do
entity:remove()
end
worldedit.marker_region[name] = nil
end
if pos1 ~= nil and pos2 ~= nil then
local pos1, pos2 = worldedit.sort_pos(pos1, pos2)
local vec = vector.subtract(pos2, pos1)
local maxside = math.max(vec.x, math.max(vec.y, vec.z))
local limit = tonumber(minetest.setting_get("active_object_send_range_blocks")) * 16
if maxside > limit * 1.5 then
-- The client likely won't be able to see the plane markers as intended anyway,
-- thus don't place them and also don't load the area into memory
return
end
local thickness = 0.2
local sizex, sizey, sizez = (1 + pos2.x - pos1.x) / 2, (1 + pos2.y - pos1.y) / 2, (1 + pos2.z - pos1.z) / 2
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos2)
local markers = {}
--XY plane markers
for _, z in ipairs({pos1.z - 0.5, pos2.z + 0.5}) do
local marker = minetest.add_entity({x=pos1.x + sizex - 0.5, y=pos1.y + sizey - 0.5, z=z}, "worldedit:region_cube")
marker:set_properties({
visual_size={x=sizex * 2, y=sizey * 2},
collisionbox = {-sizex, -sizey, -thickness, sizex, sizey, thickness},
})
marker:get_luaentity().player_name = name
table.insert(markers, marker)
end
--YZ plane markers
for _, x in ipairs({pos1.x - 0.5, pos2.x + 0.5}) do
local marker = minetest.add_entity({x=x, y=pos1.y + sizey - 0.5, z=pos1.z + sizez - 0.5}, "worldedit:region_cube")
marker:set_properties({
visual_size={x=sizez * 2, y=sizey * 2},
collisionbox = {-thickness, -sizey, -sizez, thickness, sizey, sizez},
})
marker:setyaw(math.pi / 2)
marker:get_luaentity().player_name = name
table.insert(markers, marker)
end
worldedit.marker_region[name] = markers
end
end
minetest.register_entity(":worldedit:pos1", {
initial_properties = {
visual = "cube",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_pos1.png", "worldedit_pos1.png",
"worldedit_pos1.png", "worldedit_pos1.png",
"worldedit_pos1.png", "worldedit_pos1.png"},
collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker1[self.player_name] == nil then
self.object:remove()
end
end,
on_punch = function(self, hitter)
self.object:remove()
worldedit.marker1[self.player_name] = nil
end,
})
minetest.register_entity(":worldedit:pos2", {
initial_properties = {
visual = "cube",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_pos2.png", "worldedit_pos2.png",
"worldedit_pos2.png", "worldedit_pos2.png",
"worldedit_pos2.png", "worldedit_pos2.png"},
collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker2[self.player_name] == nil then
self.object:remove()
end
end,
on_punch = function(self, hitter)
self.object:remove()
worldedit.marker2[self.player_name] = nil
end,
})
minetest.register_entity(":worldedit:region_cube", {
initial_properties = {
visual = "upright_sprite",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_cube.png"},
visual_size = {x=10, y=10},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker_region[self.player_name] == nil then
self.object:remove()
return
end
end,
on_punch = function(self, hitter)
local markers = worldedit.marker_region[self.player_name]
if not markers then
return
end
for _, entity in ipairs(markers) do
entity:remove()
end
worldedit.marker_region[self.player_name] = nil
end,
})
|
Don't mark or load areas into memory when they are over a certain size, fixes #97
|
Don't mark or load areas into memory when they are over a certain size, fixes #97
|
Lua
|
agpl-3.0
|
Uberi/Minetest-WorldEdit
|
bf9881ca31671c591f449aaa51d68c21f1995dc5
|
lua/entities/gmod_wire_starfall_screen/init.lua
|
lua/entities/gmod_wire_starfall_screen/init.lua
|
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
include("starfall/SFLib.lua")
include("libtransfer/libtransfer.lua")
assert(SF, "Starfall didn't load correctly!")
local context = SF.CreateContext()
local screens = {}
hook.Add("PlayerInitialSpawn","sf_screen_download",function(ply)
local tbl = {}
for _,s in pairs(screens) do
tbl[#tbl+1] = {
ent = s,
owner = s.owner,
files = s.task.files,
main = s.task.mainfile,
}
end
if #tbl > 0 then
datastream.StreamToClients(ply,"sf_screen_download",tbl)
end
end)
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType( 3 )
self.Inputs = WireLib.CreateInputs(self, {})
self.Outputs = WireLib.CreateOutputs(self, {})
local r,g,b,a = self:GetColor()
end
function ENT:OnRestore()
end
function ENT:UpdateName(state)
if state ~= "" then state = "\n"..state end
if self.instance and self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then
self:SetOverlayText("Starfall Processor\n"..tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])..state)
else
self:SetOverlayText("Starfall Processor"..state)
end
end
function ENT:Compile(codetbl, mainfile)
if self.instance then self.instance:deinitialize() end
local ok, instance = SF.Compiler.Compile(codetbl,context,mainfile,self.owner)
if not ok then self:Error(instance) return end
self.instance = instance
instance.data.entity = self
local ok, msg = instance:initialize()
if not ok then
self:Error(msg)
return
end
self:UpdateName("")
local r,g,b,a = self:GetColor()
self:SetColor(255, 255, 255, a)
end
function ENT:Error(msg, override)
ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n")
WireLib.ClientError(msg, self.owner)
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self:UpdateName("Inactive (Error)")
local r,g,b,a = self:GetColor()
self:SetColor(255, 0, 0, a)
end
function ENT:CodeSent(ply, task)
if ply ~= self.owner then return end
self.task = task
datastream.StreamToClients(player.GetHumans(), "sf_screen_download",
{{
ent = self,
owner = ply,
files = task.files,
main = task.mainfile,
}})
screens[self] = self
local ppdata = {}
SF.Preprocessor.ParseDirectives(task.mainfile, task.files[task.mainfile], {}, ppdata)
if ppdata.sharedscreen then
self:Compile(task.files, task.mainfile)
self.sharedscreen = true
end
end
function ENT:Think()
self.BaseClass.Think(self)
self:NextThink(CurTime())
if self.instance and not self.instance.error then
self.instance:resetOps()
self:RunScriptHook("think")
end
return true
end
-- Sends a umsg to all clients about the use.
function ENT:Use( activator )
if activator:IsPlayer() then
umsg.Start( "starfall_screen_used" )
umsg.Short( self:EntIndex() )
umsg.Short( activator:EntIndex() )
umsg.End( )
end
if self.sharedscreen then
self:RunScriptHook( "starfall_used", SF.Entities.Wrap( activator ) )
end
end
function ENT:OnRemove()
if not self.instance then return end
screens[self] = nil
self.instance:deinitialize()
self.instance = nil
end
function ENT:RunScriptHook(hook, ...)
if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then
local ok, rt = self.instance:runScriptHook(hook, ...)
if not ok then self:Error(rt) end
end
end
function ENT:TriggerInput(key, value)
if self.instance and not self.instance.error then
self.instance:RunScriptHook("input",key,value)
end
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.starfall = SF.SerializeCode(self.task.files, self.task.mainfile)
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.owner = ply
local code, main = SF.DeserializeCode(info.starfall)
local task = {files = code, mainfile = main}
self:CodeSent(ply, task)
end
|
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
include("starfall/SFLib.lua")
include("libtransfer/libtransfer.lua")
assert(SF, "Starfall didn't load correctly!")
local context = SF.CreateContext()
local screens = {}
hook.Add("PlayerInitialSpawn","sf_screen_download",function(ply)
local tbl = {}
for _,s in pairs(screens) do
tbl[#tbl+1] = {
ent = s,
owner = s.owner,
files = s.task.files,
main = s.task.mainfile,
}
end
if #tbl > 0 then
datastream.StreamToClients(ply,"sf_screen_download",tbl)
end
end)
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType( 3 )
self.Inputs = WireLib.CreateInputs(self, {})
self.Outputs = WireLib.CreateOutputs(self, {})
local r,g,b,a = self:GetColor()
end
function ENT:OnRestore()
end
function ENT:UpdateName(state)
if state ~= "" then state = "\n"..state end
if self.instance and self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then
self:SetOverlayText("Starfall Processor\n"..tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])..state)
else
self:SetOverlayText("Starfall Processor"..state)
end
end
function ENT:Compile(codetbl, mainfile)
if self.instance then self.instance:deinitialize() end
local ok, instance = SF.Compiler.Compile(codetbl,context,mainfile,self.owner)
if not ok then self:Error(instance) return end
self.instance = instance
instance.data.entity = self
local ok, msg = instance:initialize()
if not ok then
self:Error(msg)
return
end
self:UpdateName("")
local r,g,b,a = self:GetColor()
self:SetColor(255, 255, 255, a)
end
function ENT:Error(msg, override)
ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n")
WireLib.ClientError(msg, self.owner)
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self:UpdateName("Inactive (Error)")
local r,g,b,a = self:GetColor()
self:SetColor(255, 0, 0, a)
end
function ENT:CodeSent(ply, task)
if ply ~= self.owner then return end
self.task = task
datastream.StreamToClients(player.GetHumans(), "sf_screen_download",
{{
ent = self,
owner = ply,
files = task.files,
main = task.mainfile,
}})
screens[self] = self
local ppdata = {}
SF.Preprocessor.ParseDirectives(task.mainfile, task.files[task.mainfile], {}, ppdata)
if ppdata.sharedscreen then
self:Compile(task.files, task.mainfile)
self.sharedscreen = true
end
end
function ENT:Think()
self.BaseClass.Think(self)
self:NextThink(CurTime())
if self.instance and not self.instance.error then
self.instance:resetOps()
self:RunScriptHook("think")
end
return true
end
-- Sends a umsg to all clients about the use.
function ENT:Use( activator )
if activator:IsPlayer() then
umsg.Start( "starfall_screen_used" )
umsg.Short( self:EntIndex() )
umsg.Short( activator:EntIndex() )
umsg.End( )
end
if self.sharedscreen then
self:RunScriptHook( "starfall_used", SF.Entities.Wrap( activator ) )
end
end
function ENT:OnRemove()
if not self.instance then return end
screens[self] = nil
self.instance:deinitialize()
self.instance = nil
end
function ENT:RunScriptHook(hook, ...)
if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then
local ok, rt = self.instance:runScriptHook(hook, ...)
if not ok then self:Error(rt) end
end
end
function ENT:TriggerInput(key, value)
self:RunScriptHook("input",key,value)
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.starfall = SF.SerializeCode(self.task.files, self.task.mainfile)
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.owner = ply
local code, main = SF.DeserializeCode(info.starfall)
local task = {files = code, mainfile = main}
self:CodeSent(ply, task)
end
|
Fixed input hook on SF screens. Fixes #87
|
Fixed input hook on SF screens. Fixes #87
|
Lua
|
bsd-3-clause
|
Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Xandaros/Starfall,INPStarfall/Starfall,INPStarfall/Starfall
|
74f1c41df6fa42f4428db56ffdcc17a6ed036254
|
pages/library/houses/bid/post.lua
|
pages/library/houses/bid/post.lua
|
function post()
if not session:isLogged() then
http:redirect("/")
return
end
local account = session:loggedAccount()
local house = db:singleQuery([[
SELECT c.name AS bidname, b.bid, b.bid_end, b.last_bid, a.name AS ownername, b.name, b.rent, b.size, b.beds, b.town_id, b.id FROM houses b
LEFT JOIN players a ON a.id = b.owner
LEFT JOIN players c ON c.id = b.highest_bidder
WHERE b.id = ?
]], http.postValues.id)
if house == nil then
http:redirect("/")
return
end
if house.ownername ~= nil then
http:redirect("/")
return
end
local character = db:singleQuery("SELECT id, balance FROM players WHERE name = ? AND account_id = ?", url:decode(http.postValues.character), account.ID)
if character == nil then
http:redirect("/")
return
end
if character.balance < tonumber(http.postValues.bid) then
session:setFlash("error", "You need more gold coins to place that bid")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
if db:singleQuery("SELECT id FROM houses WHERE highest_bidder = ?", character.id) ~= nil then
session:setFlash("error", "You already have a bid in place")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
-- There is no bid for the house
if house.bidname == nil then
db:execute(
"UPDATE houses SET bid = ?, bid_end = ?, last_bid = ?, highest_bidder = ? WHERE id = ?",
http.postValues.bid,
os.time() + app.Custom.HouseBidOpenTime,
http.postValues.bid,
character.id,
house.id
)
session:setFlash("success", "Bid placed")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
if house.highest_bidder == character.id then
session:setFlash("error", "You cannot outbid your own bid")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
if tonumber(http.postValues.bid) < house.last_bid then
session:setFlash("error", "Your bid needs to be higher than the last bid. The last bid is currently " .. house.last_bid)
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
db:execute(
"UPDATE houses SET bid = bid + ?, last_bid = ?, highest_bidder = ? WHERE id = ?",
http.postValues.bid,
http.postValues.bid,
character.id,
house.id
)
end
|
function post()
if not session:isLogged() then
http:redirect("/")
return
end
local account = session:loggedAccount()
local house = db:singleQuery([[
SELECT c.name AS bidname, b.bid, b.bid_end, b.last_bid, a.name AS ownername, b.name, b.rent, b.size, b.beds, b.town_id, b.id FROM houses b
LEFT JOIN players a ON a.id = b.owner
LEFT JOIN players c ON c.id = b.highest_bidder
WHERE b.id = ?
]], http.postValues.id)
if house == nil then
http:redirect("/")
return
end
if house.ownername ~= nil then
http:redirect("/")
return
end
local character = db:singleQuery("SELECT id, balance FROM players WHERE name = ? AND account_id = ?", url:decode(http.postValues.character), account.ID)
if character == nil then
http:redirect("/")
return
end
if http.postValues.bid == "" then
session:setFlash("error", "Invalid bid amount")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
if character.balance < tonumber(http.postValues.bid) then
session:setFlash("error", "You need more gold coins to place that bid")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
if db:singleQuery("SELECT id FROM houses WHERE highest_bidder = ?", character.id) ~= nil then
session:setFlash("error", "You already have a bid in place")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
-- There is no bid for the house
if house.bidname == nil then
db:execute(
"UPDATE houses SET bid = ?, bid_end = ?, last_bid = ?, highest_bidder = ? WHERE id = ?",
http.postValues.bid,
os.time() + app.Custom.HouseBidOpenTime,
http.postValues.bid,
character.id,
house.id
)
session:setFlash("success", "Bid placed")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
if house.highest_bidder == character.id then
session:setFlash("error", "You cannot outbid your own bid")
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
if tonumber(http.postValues.bid) < house.last_bid then
session:setFlash("error", "Your bid needs to be higher than the last bid. The last bid is currently " .. house.last_bid)
http:redirect("/subtopic/library/houses/view?id=" .. house.id)
return
end
db:execute(
"UPDATE houses SET bid = bid + ?, last_bid = ?, highest_bidder = ? WHERE id = ?",
http.postValues.bid,
http.postValues.bid,
character.id,
house.id
)
end
|
Fix house bidding error
|
Fix house bidding error
|
Lua
|
mit
|
Raggaer/castro,Raggaer/castro,Raggaer/castro
|
80430c3b967d7428a8e66dcc9e59c7a5df235b2d
|
nvim/.config/nvim/after/plugin/lspconfig.rc.lua
|
nvim/.config/nvim/after/plugin/lspconfig.rc.lua
|
local nvim_lsp_installed, nvim_lsp = pcall(require, "lspconfig")
if not nvim_lsp_installed then
print("nvim-lsp is not installed! Aborting")
return
end
local mason_installed, mason_lspconfig = pcall(require, "mason-lspconfig")
if not mason_installed then
print("Unable to install LSP servers because mason-lspconfig is not installed")
return
end
-- Automatically install these LSP servers and set them up with proper 'on_attach' functions
local lsp_servers = {
'bashls',
'dockerls',
'gopls',
'jsonnet_ls',
'pyright',
'solargraph',
'sumneko_lua',
'terraformls',
'vimls',
'yamlls',
}
mason_lspconfig.setup({
automatic_installation = true,
ensure_installed = lsp_servers,
})
-- Specify any custom settings for an LSP server here
local server_specific_opts = {
['solargraph'] = function(opts)
opts.settings = {
filetypes = { 'ruby', 'rake' }
}
end,
['gopls'] = function(opts)
opts.cmd = { 'gopls', '-remote=auto' }
end,
['sumneko_lua'] = function(opts)
opts.settings = {
Lua = {
diagnostics = {
globals = {
'vim',
},
},
workspace = {
library = vim.api.nvim_get_runtime_file("", true),
},
},
}
end,
}
local lsp_handlers = require("lsp/handlers")
for _, server_name in pairs(lsp_servers) do
local opts = {
on_attach = lsp_handlers.on_attach,
capabilities = lsp_handlers.capabilities,
}
if server_specific_opts[server_name] then
server_specific_opts[server_name](opts)
end
nvim_lsp[server_name].setup(opts)
end
|
local nvim_lsp_installed, nvim_lsp = pcall(require, "lspconfig")
if not nvim_lsp_installed then
print("nvim-lsp is not installed! Aborting")
return
end
local mason_installed, mason_config = pcall(require, "mason")
if not mason_installed then
print("Unable to install LSP servers because mason is not installed")
return
end
local mason_lspconfig_installed, mason_lspconfig = pcall(require, "mason-lspconfig")
if not mason_lspconfig_installed then
print("Unable to install LSP servers because mason-lspconfig is not installed")
return
end
-- Automatically install these LSP servers and set them up with proper 'on_attach' functions
local lsp_servers = {
'bashls',
'dockerls',
'gopls',
'jsonnet_ls',
'pyright',
'solargraph',
'sumneko_lua',
'terraformls',
'vimls',
'yamlls',
}
mason_lspconfig.setup({
automatic_installation = true,
ensure_installed = lsp_servers,
})
-- Specify any custom settings for an LSP server here
local server_specific_opts = {
['solargraph'] = function(opts)
opts.settings = {
filetypes = { 'ruby', 'rake' }
}
end,
['gopls'] = function(opts)
opts.cmd = { 'gopls', '-remote=auto' }
end,
['sumneko_lua'] = function(opts)
opts.settings = {
Lua = {
diagnostics = {
globals = {
'vim',
},
},
workspace = {
library = vim.api.nvim_get_runtime_file("", true),
},
},
}
end,
}
local lsp_handlers = require("lsp/handlers")
for _, server_name in pairs(lsp_servers) do
local opts = {
on_attach = lsp_handlers.on_attach,
capabilities = lsp_handlers.capabilities,
}
if server_specific_opts[server_name] then
server_specific_opts[server_name](opts)
end
nvim_lsp[server_name].setup(opts)
end
|
fix: Fix mason install
|
fix: Fix mason install
|
Lua
|
mit
|
hectron/dotfiles,hectron/dotfiles
|
ab8aafbcfeff8a77050f3763a4a2b909c2eaa267
|
evaluation.lua
|
evaluation.lua
|
--
-- Created by IntelliJ IDEA.
-- User: bking
-- Date: 1/30/17
-- Time: 2:25 AM
-- To change this template use File | Settings | File Templates.
--
package.path = ';/homes/iws/kingb12/LanguageModelRNN/?.lua;'..package.path
require 'torch'
require 'nn'
require 'nnx'
require 'util'
require 'torch-rnn'
require 'DynamicView'
require 'Sampler'
cjson = require 'cjson'
torch.setheaptracking(true)
-- =========================================== COMMAND LINE OPTIONS ====================================================
local cmd = torch.CmdLine()
-- Options
cmd:option('-gpu', false)
-- Dataset options
cmd:option('-train_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_set.th7')
cmd:option('-valid_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_valid_set.th7')
cmd:option('-test_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_test_set.th7')
cmd:option('-wmap_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_map.th7")
cmd:option('-wfreq_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_freq.th7")
-- Model options
cmd:option('-model', 'newcudamodel.th7')
--Output Options
cmd:option('-batch_loss_file', '')
cmd:option('-num_samples', 10)
cmd:option('-max_sample_length', 10)
cmd:option('-run', false)
local opt = cmd:parse(arg)
-- ================================================ EVALUATION =========================================================
train_set = torch.load(opt.train_set)
valid_set = torch.load(opt.valid_set)
test_set = torch.load(opt.test_set)
model = torch.load(opt.model)
criterion = nn.ClassNLLCriterion()
-- CUDA everything if GPU
if opt.gpu then
train_set = train_set:cuda()
valid_set = valid_set:cuda()
test_set = test_set:cuda()
model = model:cuda()
criterion = criterion:cuda()
end
function loss_on_dataset(data_set, criterion)
local loss = 0.0
local batch_losses = {}
for i=1, data_set:size() do
local l, n = criterion:forward(model:forward(data_set[i][1]), data_set[i][2])
batch_losses[i] = l
loss = loss + (l / n)
end
return loss, batch_losses
end
-- We will build a report as a table which will be converted to json.
output = {}
-- calculate losses
local tr_set_loss, tr_batch_loss = loss_on_dataset(train_set, criterion)
output['train_loss'] = tr_set_loss
output['train_batch_loss'] = tr_batch_loss
local vd_set_loss, vd_batch_loss = loss_on_dataset(valid_set, criterion)
output['valid_loss'] = vd_set_loss
output['valid_batch_loss'] = vd_batch_loss
local ts_set_loss, ts_batch_loss = loss_on_dataset(test_set, criterion)
output['test_loss'] = ts_set_loss
output['test_batch_loss'] = ts_batch_loss
sampler = nn.Sampler()
function sample(output, max_samples)
if max_samples == nil then
max_samples = 1
end
local output = torch.cat(output, torch.zeros(output:size(1)))
local sampled = sampler:forward(output)
for i=1, output:size(1) do output[i][output:size(2) + 1] = sampled[i] end
if max_samples == 1 then
return output
else
return sample(output, max_samples - 1)
end
end
-- generate some samples
for i=1, opt.num_samples do
end
|
--
-- Created by IntelliJ IDEA.
-- User: bking
-- Date: 1/30/17
-- Time: 2:25 AM
-- To change this template use File | Settings | File Templates.
--
package.path = ';/homes/iws/kingb12/LanguageModelRNN/?.lua;'..package.path
require 'torch'
require 'nn'
require 'nnx'
require 'util'
require 'torch-rnn'
require 'DynamicView'
require 'Sampler'
cjson = require 'cjson'
torch.setheaptracking(true)
-- =========================================== COMMAND LINE OPTIONS ====================================================
local cmd = torch.CmdLine()
-- Options
cmd:option('-gpu', false)
-- Dataset options
cmd:option('-train_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_set.th7')
cmd:option('-valid_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_valid_set.th7')
cmd:option('-test_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_test_set.th7')
cmd:option('-wmap_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_map.th7")
cmd:option('-wfreq_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_freq.th7")
-- Model options
cmd:option('-model', 'newcudamodel.th7')
--Output Options
cmd:option('-batch_loss_file', '')
cmd:option('-num_samples', 10)
cmd:option('-max_sample_length', 10)
cmd:option('-run', false)
local opt = cmd:parse(arg)
-- ================================================ EVALUATION =========================================================
train_set = torch.load(opt.train_set)
valid_set = torch.load(opt.valid_set)
test_set = torch.load(opt.test_set)
model = torch.load(opt.model)
criterion = nn.ClassNLLCriterion()
-- CUDA everything if GPU
if opt.gpu then
require 'cutorch'
require 'cunn'
train_set = train_set:cuda()
valid_set = valid_set:cuda()
test_set = test_set:cuda()
model = model:cuda()
criterion = criterion:cuda()
end
function loss_on_dataset(data_set, criterion)
local loss = 0.0
local batch_losses = {}
for i=1, data_set:size() do
local l, n = criterion:forward(model:forward(data_set[i][1]), data_set[i][2])
batch_losses[i] = l
loss = loss + (l / n)
end
return loss, batch_losses
end
-- We will build a report as a table which will be converted to json.
output = {}
-- calculate losses
local tr_set_loss, tr_batch_loss = loss_on_dataset(train_set, criterion)
output['train_loss'] = tr_set_loss
output['train_batch_loss'] = tr_batch_loss
local vd_set_loss, vd_batch_loss = loss_on_dataset(valid_set, criterion)
output['valid_loss'] = vd_set_loss
output['valid_batch_loss'] = vd_batch_loss
local ts_set_loss, ts_batch_loss = loss_on_dataset(test_set, criterion)
output['test_loss'] = ts_set_loss
output['test_batch_loss'] = ts_batch_loss
sampler = nn.Sampler()
function sample(output, max_samples)
if max_samples == nil then
max_samples = 1
end
local output = torch.cat(output, torch.zeros(output:size(1)))
local sampled = sampler:forward(output)
for i=1, output:size(1) do output[i][output:size(2) + 1] = sampled[i] end
if max_samples == 1 then
return output
else
return sample(output, max_samples - 1)
end
end
-- generate some samples
for i=1, opt.num_samples do
end
|
cuun fix eval"
|
cuun fix eval"
|
Lua
|
mit
|
kingb12/languagemodelRNN,kingb12/languagemodelRNN,kingb12/languagemodelRNN
|
dfe3d4996f0c279fa5454a6639694aeaaa1b1173
|
tests/sample.lua
|
tests/sample.lua
|
local cutil = require "cutil"
function filter_spec_chars(s)
local ss = {}
for k = 1, #s do
local c = string.byte(s,k)
if not c then break end
if (c>=48 and c<=57) or (c>= 65 and c<=90) or (c>=97 and c<=122) then
table.insert(ss, string.char(c))
elseif c>=228 and c<=233 then
local c1 = string.byte(s,k+1)
local c2 = string.byte(s,k+2)
if not c1 or not c2 then break end
local a1,a2,a3,a4 = 128,191,128,191
if c == 228 then a1 = 184 end
if c == 233 then a2, a4 = 190, 165 end
if c1>=a1 and c1<=a2 and c2>=a3 and c2<=a4 then
k = k + 2
table.insert(ss, string.char(c,c1,c2))
end
end
end
return table.concat(ss)
end
ss = '$s%sfoo"明天"a"你好、,。~!@#¥%……&×(){}|:“《》?"foo%%23333|'
print("lua version: ", filter_spec_chars(ss))
print("cutil version: ", cutil.filter_spec_chars(ss))
print("efficiency comparison: ")
t = os.clock()
for k = 1,100000 do
filter_spec_chars(ss)
end
t1 = os.clock()
print("test lua version: ", t1-t) -- 5.78
t = os.clock()
for k = 1,100000 do
cutil.filter_spec_chars(ss)
end
t1 = os.clock()
print("test cutil version: ", t1-t) -- 0.06
|
local cutil = require "cutil"
function filter_spec_chars(s)
local ss = {}
for k = 1, #s do
local c = string.byte(s,k)
if not c then break end
if (c>=48 and c<=57) or (c>= 65 and c<=90) or (c>=97 and c<=122) then
table.insert(ss, string.char(c))
elseif c>=228 and c<=233 then
local c1 = string.byte(s,k+1)
local c2 = string.byte(s,k+2)
if c1 and c2 then
local a1,a2,a3,a4 = 128,191,128,191
if c == 228 then a1 = 184
elseif c == 233 then a2,a4 = 190,165
end
if c1>=a1 and c1<=a2 and c2>=a3 and c2<=a4 then
k = k + 2
table.insert(ss, string.char(c,c1,c2))
end
end
end
end
return table.concat(ss)
end
ss = '$s%sfoo"明天"a"你好、,。~!@#¥%……&×(){}|:“《》?"foo%%23333|'
print("lua version: ", filter_spec_chars(ss))
print("cutil version: ", cutil.filter_spec_chars(ss))
print("efficiency comparison: ")
t = os.clock()
for k = 1,100000 do
filter_spec_chars(ss)
end
t1 = os.clock()
print("test lua version: ", t1-t) -- 5.61
t = os.clock()
for k = 1,100000 do
cutil.filter_spec_chars(ss)
end
t1 = os.clock()
print("test cutil version: ", t1-t) -- 0.06
|
bugfix: last second char may be ingored
|
bugfix: last second char may be ingored
|
Lua
|
mit
|
chenweiqi/lua-cutil
|
1f41ddd22833ed01bb49d30b3d4eca107077de42
|
resources/prosody-plugins/mod_muc_allowners.lua
|
resources/prosody-plugins/mod_muc_allowners.lua
|
local filters = require 'util.filters';
local jid = require "util.jid";
local jid_bare = require "util.jid".bare;
local jid_host = require "util.jid".host;
local um_is_admin = require "core.usermanager".is_admin;
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local extract_subdomain = util.extract_subdomain;
local presence_check_status = util.presence_check_status;
local MUC_NS = 'http://jabber.org/protocol/muc';
local moderated_subdomains;
local moderated_rooms;
local function load_config()
moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {})
moderated_rooms = module:get_option_set("allowners_moderated_rooms", {})
end
load_config();
local function is_admin(jid)
return um_is_admin(jid, module.host);
end
-- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted
-- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should
-- have length of 1
local joining_moderator_participants = {};
-- Checks whether the jid is moderated, the room name is in moderated_rooms
-- or if the subdomain is in the moderated_subdomains
-- @return returns on of the:
-- -> false
-- -> true, room_name, subdomain
-- -> true, room_name, nil (if no subdomain is used for the room)
local function is_moderated(room_jid)
if moderated_subdomains:empty() and moderated_rooms:empty() then
return false;
end
local room_node = jid.node(room_jid);
-- parses bare room address, for multidomain expected format is:
-- [subdomain][email protected]
local target_subdomain, target_room_name = extract_subdomain(room_node);
if target_subdomain then
if moderated_subdomains:contains(target_subdomain) then
return true, target_room_name, target_subdomain;
end
elseif moderated_rooms:contains(room_node) then
return true, room_node, nil;
end
return false;
end
module:hook("muc-occupant-pre-join", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
return;
end
local moderated, room_name, subdomain = is_moderated(room.jid);
if moderated then
local session = event.origin;
local token = session.auth_token;
if not token then
module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name);
return;
end
if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then
module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s', room_name, session.jitsi_meet_room);
return;
end
if not (subdomain == session.jitsi_meet_context_group) then
module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s', subdomain, session.jitsi_meet_context_group);
return;
end
end
-- mark this participant that it will be promoted and is currently joining
joining_moderator_participants[occupant.bare_jid] = true;
end, 2);
module:hook("muc-occupant-joined", function (event)
local room, occupant = event.room, event.occupant;
local promote_to_moderator = joining_moderator_participants[occupant.bare_jid];
-- clear it
joining_moderator_participants[occupant.bare_jid] = nil;
if promote_to_moderator ~= nil then
room:set_affiliation(true, occupant.bare_jid, "owner");
end
end, 2);
module:hook("muc-occupant-left", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) then
return;
end
room:set_affiliation(true, occupant.bare_jid, nil);
end, 2);
module:hook_global('config-reloaded', load_config);
-- Filters self-presences to a jid that exist in joining_participants array
-- We want to filter those presences where we send first `participant` and just after it `moderator`
function filter_stanza(stanza)
-- when joining_moderator_participants is empty there is nothing to filter
if next(joining_moderator_participants) == nil or not stanza.attr or not stanza.attr.to or stanza.name ~= "presence" then
return stanza;
end
-- we want to filter presences only on this host for allowners and skip anything like lobby etc.
local host_from = jid_host(stanza.attr.from);
if host_from ~= module.host then
return stanza;
end
local bare_to = jid_bare(stanza.attr.to);
if stanza:get_error() and joining_moderator_participants[bare_to] then
-- pre-join succeeded but joined did not so we need to clear cache
joining_moderator_participants[bare_to] = nil;
return stanza;
end
local muc_x = stanza:get_child('x', MUC_NS..'#user');
if not muc_x then
return stanza;
end
if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then
-- skip the local presence for participant
return nil;
end
-- skip sending the 'participant' presences to all other people in the room
for item in muc_x:childtags('item') do
if joining_moderator_participants[jid_bare(item.attr.jid)] then
return nil;
end
end
return stanza;
end
function filter_session(session)
-- domain mapper is filtering on default priority 0, and we need it after that
filters.add_filter(session, 'stanzas/out', filter_stanza, -1);
end
-- enable filtering presences
filters.add_filter_hook(filter_session);
|
local filters = require 'util.filters';
local jid = require "util.jid";
local jid_bare = require "util.jid".bare;
local jid_host = require "util.jid".host;
local um_is_admin = require "core.usermanager".is_admin;
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local extract_subdomain = util.extract_subdomain;
local presence_check_status = util.presence_check_status;
local MUC_NS = 'http://jabber.org/protocol/muc';
local moderated_subdomains;
local moderated_rooms;
local function load_config()
moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {})
moderated_rooms = module:get_option_set("allowners_moderated_rooms", {})
end
load_config();
local function is_admin(jid)
return um_is_admin(jid, module.host);
end
-- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted
-- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should
-- have length of 1
local joining_moderator_participants = {};
-- Checks whether the jid is moderated, the room name is in moderated_rooms
-- or if the subdomain is in the moderated_subdomains
-- @return returns on of the:
-- -> false
-- -> true, room_name, subdomain
-- -> true, room_name, nil (if no subdomain is used for the room)
local function is_moderated(room_jid)
if moderated_subdomains:empty() and moderated_rooms:empty() then
return false;
end
local room_node = jid.node(room_jid);
-- parses bare room address, for multidomain expected format is:
-- [subdomain][email protected]
local target_subdomain, target_room_name = extract_subdomain(room_node);
if target_subdomain then
if moderated_subdomains:contains(target_subdomain) then
return true, target_room_name, target_subdomain;
end
elseif moderated_rooms:contains(room_node) then
return true, room_node, nil;
end
return false;
end
module:hook("muc-occupant-pre-join", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
return;
end
local moderated, room_name, subdomain = is_moderated(room.jid);
if moderated then
local session = event.origin;
local token = session.auth_token;
if not token then
module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name);
return;
end
if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then
module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s', room_name, session.jitsi_meet_room);
return;
end
if not (subdomain == session.jitsi_meet_context_group) then
module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s', subdomain, session.jitsi_meet_context_group);
return;
end
end
-- mark this participant that it will be promoted and is currently joining
joining_moderator_participants[occupant.bare_jid] = true;
end, 2);
module:hook("muc-occupant-joined", function (event)
local room, occupant = event.room, event.occupant;
local promote_to_moderator = joining_moderator_participants[occupant.bare_jid];
-- clear it
joining_moderator_participants[occupant.bare_jid] = nil;
if promote_to_moderator ~= nil then
room:set_affiliation(true, occupant.bare_jid, "owner");
end
end, 2);
module:hook_global('config-reloaded', load_config);
-- Filters self-presences to a jid that exist in joining_participants array
-- We want to filter those presences where we send first `participant` and just after it `moderator`
function filter_stanza(stanza)
-- when joining_moderator_participants is empty there is nothing to filter
if next(joining_moderator_participants) == nil or not stanza.attr or not stanza.attr.to or stanza.name ~= "presence" then
return stanza;
end
-- we want to filter presences only on this host for allowners and skip anything like lobby etc.
local host_from = jid_host(stanza.attr.from);
if host_from ~= module.host then
return stanza;
end
local bare_to = jid_bare(stanza.attr.to);
if stanza:get_error() and joining_moderator_participants[bare_to] then
-- pre-join succeeded but joined did not so we need to clear cache
joining_moderator_participants[bare_to] = nil;
return stanza;
end
local muc_x = stanza:get_child('x', MUC_NS..'#user');
if not muc_x then
return stanza;
end
if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then
-- skip the local presence for participant
return nil;
end
-- skip sending the 'participant' presences to all other people in the room
for item in muc_x:childtags('item') do
if joining_moderator_participants[jid_bare(item.attr.jid)] then
return nil;
end
end
return stanza;
end
function filter_session(session)
-- domain mapper is filtering on default priority 0, and we need it after that
filters.add_filter(session, 'stanzas/out', filter_stanza, -1);
end
-- enable filtering presences
filters.add_filter_hook(filter_session);
|
fix: Drops extra message sent on leave.
|
fix: Drops extra message sent on leave.
|
Lua
|
apache-2.0
|
jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet
|
b6f62fd983e470ee5983540721b6470276490b38
|
layout-app.lua
|
layout-app.lua
|
SILE.scratch.layout = "app"
local class = SILE.documentState.documentClass
SILE.documentState.paperSize = SILE.paperSizeParser("80mm x 128mm")
SILE.documentState.orgPaperSize = SILE.documentState.paperSize
class:defineMaster({
id = "right",
firstContentFrame = "content",
frames = {
content = {
left = "2mm",
right = "100%pw-2mm",
top = "bottom(runningHead)+2mm",
bottom = "top(footnotes)"
},
runningHead = {
left = "left(content)",
right = "right(content)",
top = "2mm",
bottom = "14mm"
},
footnotes = {
left = "left(content)",
right = "right(content)",
height = "0",
bottom = "100%ph-2mm"
}
}
})
class:mirrorMaster("right", "left")
SILE.call("switch-master-one-page", { id = "right" })
SILE.registerCommand("output-right-running-head", function (options, content)
if not SILE.scratch.headers.right then return end
SILE.typesetNaturally(SILE.getFrame("runningHead"), function ()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue)
SILE.call("book:right-running-head-font", {}, function ()
SILE.call("center", {}, function()
SILE.call("meta:title")
end)
end)
SILE.call("skip", { height = "2pt" })
SILE.call("book:right-running-head-font", {}, SILE.scratch.headers.right)
SILE.call("hfill")
SILE.call("book:page-number-font", {}, { SILE.formatCounter(SILE.scratch.counters.folio) })
SILE.call("skip", { height = "-8pt" })
SILE.call("fullrule", { raise = 0 })
end)
end)
SILE.registerCommand("output-left-running-head", function (options, content)
SILE.call("output-right-running-head")
end)
local oldImprintFont = SILE.Commands["imprint:font"]
SILE.registerCommand("imprint:font", function (options, content)
options.size = options.size or "6.5pt"
oldImprintFont(options, content)
end)
SILE.registerCommand("meta:distribution", function (options, content)
SILE.call("font", { weight = 600, style = "Bold" }, { "Yayın: " })
SILE.typesetter:typeset("Bu PDF biçimi, akıl telefon cihazlar için uygun biçimlemiştir ve Fetiye Halk Kilise’nin hazırladığı Kilise Uygulaması içinde ve Via Christus’un internet sitesinde izinle üçretsiz yayılmaktadır.")
end)
-- Mobile device PDF readers don't need blank even numbered pages ;)
SILE.registerCommand("open-double-page", function ()
SILE.typesetter:leaveHmode();
SILE.Commands["supereject"]();
SILE.typesetter:leaveHmode();
end)
-- Forgo bottom of page layouts for mobile devices
SILE.registerCommand("topfill", function (options, content)
SILE.typesetter:leaveHmode();
end)
if SILE.documentState.documentClass.options.background() == "true" then
SILE.require("packages/background")
SILE.call("background", { color = "#e1e2e6" })
local inkColor = SILE.colorparser("#19191A")
SILE.outputter:pushColor(inkColor)
end
SILE.settings.set("linebreak.emergencyStretch", SILE.length.parse("3em"))
|
SILE.scratch.layout = "app"
local class = SILE.documentState.documentClass
SILE.documentState.paperSize = SILE.paperSizeParser("80mm x 128mm")
SILE.documentState.orgPaperSize = SILE.documentState.paperSize
class:defineMaster({
id = "right",
firstContentFrame = "content",
frames = {
content = {
left = "2mm",
right = "100%pw-2mm",
top = "bottom(runningHead)+2mm",
bottom = "top(footnotes)"
},
runningHead = {
left = "left(content)",
right = "right(content)",
top = "2mm",
bottom = "14mm"
},
footnotes = {
left = "left(content)",
right = "right(content)",
height = "0",
bottom = "100%ph-2mm"
}
}
})
class:mirrorMaster("right", "left")
SILE.call("switch-master-one-page", { id = "right" })
SILE.registerCommand("output-right-running-head", function (options, content)
SILE.typesetNaturally(SILE.getFrame("runningHead"), function ()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue)
SILE.call("book:right-running-head-font", {}, function ()
SILE.call("center", {}, function()
SILE.call("meta:title")
end)
end)
SILE.call("skip", { height = "2pt" })
SILE.call("book:right-running-head-font", {}, SILE.scratch.headers.right)
SILE.call("hfill")
SILE.call("book:page-number-font", {}, { SILE.formatCounter(SILE.scratch.counters.folio) })
SILE.call("skip", { height = "-8pt" })
SILE.call("fullrule", { raise = 0 })
end)
end)
SILE.registerCommand("output-left-running-head", function (options, content)
SILE.call("output-right-running-head")
end)
local oldImprintFont = SILE.Commands["imprint:font"]
SILE.registerCommand("imprint:font", function (options, content)
options.size = options.size or "6.5pt"
oldImprintFont(options, content)
end)
SILE.registerCommand("meta:distribution", function (options, content)
SILE.call("font", { weight = 600, style = "Bold" }, { "Yayın: " })
SILE.typesetter:typeset("Bu PDF biçimi, akıl telefon cihazlar için uygun biçimlemiştir ve Fetiye Halk Kilise’nin hazırladığı Kilise Uygulaması içinde ve Via Christus’un internet sitesinde izinle üçretsiz yayılmaktadır.")
end)
-- Mobile device PDF readers don't need blank even numbered pages ;)
SILE.registerCommand("open-double-page", function ()
SILE.typesetter:leaveHmode();
SILE.Commands["supereject"]();
SILE.typesetter:leaveHmode();
end)
-- Forgo bottom of page layouts for mobile devices
SILE.registerCommand("topfill", function (options, content)
SILE.typesetter:leaveHmode();
end)
if SILE.documentState.documentClass.options.background() == "true" then
SILE.require("packages/background")
SILE.call("background", { color = "#e1e2e6" })
local inkColor = SILE.colorparser("#19191A")
SILE.outputter:pushColor(inkColor)
end
SILE.settings.set("linebreak.emergencyStretch", SILE.length.parse("3em"))
|
Always include headers in app layout, fixes #49
|
Always include headers in app layout, fixes #49
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
05c87568b77df00b484d9cad0b2d212052be485b
|
ios-icons/fn.lua
|
ios-icons/fn.lua
|
local insert = table.insert
local fn = {}
local append = function(a, b)
for _, v in ipairs(b) do
insert(a, v)
end
end
fn.select = function(tab, cond)
assert(type(cond) == 'function', 'cond must be a predicate')
local result = {}
for _,v in pairs(tab) do
if type(v) == 'folder' then
local fresult = fn.select(v.icons, cond)
append(result, fresult)
elseif type(v) == 'page' then
local fresult = fn.select(v, cond)
append(result, fresult)
elseif type(v) == 'icon' then
if cond(v) then
insert(result, v)
end
end
end
return result
end
return fn
|
local insert = table.insert
local fn = {}
local append = function(a, b)
for _, v in ipairs(b) do
insert(a, v)
end
end
fn.select = function(tab, cond)
assert(type(cond) == 'function', 'cond must be a predicate')
local t = tab
local result = {}
if type(t) == 'folder' then
t = t.icons
end
for _,v in pairs(t) do
if type(v) == 'folder' then
local fresult = fn.select(v.icons, cond)
append(result, fresult)
elseif type(v) == 'page' then
local fresult = fn.select(v, cond)
append(result, fresult)
elseif type(v) == 'icon' then
if cond(v) then
insert(result, v)
end
end
end
return result
end
return fn
|
fixed fn.select so it works properly if given a folder as first argument
|
fixed fn.select so it works properly if given a folder as first argument
|
Lua
|
mit
|
profburke/ios-icons,profburke/ios-icons,profburke/ios-icons
|
9a031b53a2f7322f5bc6e0e9e694367d2a20ba0d
|
particles.lua
|
particles.lua
|
Particle = {}
function Particle.ballImpactWithWall(nx, ny, x, y)
local tex = love.graphics.newImage("assets/textures/particle.png")
local emitter = love.graphics.newParticleSystem(tex,25)
emitter:setDirection(vector.angleTo(nx, ny))
emitter:setAreaSpread("none",0,0)
emitter:setEmissionRate(300)
emitter:setEmitterLifetime(1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(1,1)
emitter:setRadialAcceleration(200,250)
emitter:setRotation(0,0)
emitter:setTangentialAcceleration(12,27)
emitter:setSpeed(100,250)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(2.7999999523163)
emitter:setRelativeRotation(false)
emitter:setOffset(0, 0)
emitter:setSizes(1,0)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255)
emitter:setPosition(x, y)
return emitter;
end
function Particle.ballImpactWithPlayer(nx, ny, x, y)
local tex = love.graphics.newImage("assets/textures/spark.png")
local emitter = love.graphics.newParticleSystem(tex,50)
emitter:setDirection(vector.angleTo(nx, ny))
emitter:setAreaSpread("none",0,0)
emitter:setEmissionRate(300)
emitter:setEmitterLifetime(1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(1,1)
emitter:setRadialAcceleration(200,250)
emitter:setRotation(0,0)
emitter:setTangentialAcceleration(12,27)
emitter:setSpeed(100,250)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(5.5999999046326)
emitter:setRelativeRotation(false)
emitter:setOffset(0, 0)
emitter:setSizes(1,0)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255)
emitter:setPosition(x, y)
return emitter;
end
function Particle.ballMovement()
local tex = love.graphics.newImage("assets/textures/particle.png")
local emitter = love.graphics.newParticleSystem(tex,100)
emitter:setDirection(0)
emitter:setAreaSpread("uniform",8,8)
emitter:setEmissionRate(100)
emitter:setEmitterLifetime(-1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(0.5,0.2)
emitter:setRadialAcceleration(0,0)
emitter:setRotation(0,0)
emitter:setTangentialAcceleration(0,0)
emitter:setSpeed(0,0)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(2)
emitter:setRelativeRotation(false)
emitter:setOffset(25,25)
emitter:setSizes(1.5, 0)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255,255,255,255,0)
return emitter;
end
function Particle.sunMenu()
local tex = love.graphics.newImage("assets/textures/startscreen_particle.png")
emitter = love.graphics.newParticleSystem(tex,200)
emitter:setDirection(1.6000000238419)
emitter:setAreaSpread("normal",200,80)
emitter:setEmissionRate(36)
emitter:setEmitterLifetime(-1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(5,5)
emitter:setRadialAcceleration(0,0)
emitter:setRotation(0,0)
emitter:setTangentialAcceleration(0,0)
emitter:setSpeed(3,73)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(6.1999998092651)
emitter:setRelativeRotation(false)
emitter:setOffset(88,95)
emitter:setSizes(0,1,0)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,100 )
return emitter;
end
function Particle.playerPushReady()
local tex = love.graphics.newImage("assets/textures/miniParticle.png")
local emitter = love.graphics.newParticleSystem(tex,50)
emitter:setDirection(0)
emitter:setAreaSpread("normal",8,32)
emitter:setEmissionRate(35)
emitter:setEmitterLifetime(-1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(0.5,0.7)
emitter:setRadialAcceleration(50,100)
emitter:setRotation(0,360)
emitter:setTangentialAcceleration(12,24)
emitter:setSpeed(50,75)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(6.1999998092651)
emitter:setRelativeRotation(false)
emitter:setOffset(0,0)
emitter:setSizes(1,0.5)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255)
return emitter;
end
function Particle.boxExplosion()
local tex = love.graphics.newImage("assets/textures/woodParticle.png")
local emitter = love.graphics.newParticleSystem(tex,4)
emitter:setDirection(0)
emitter:setAreaSpread("none",0,0)
emitter:setEmissionRate(150)
emitter:setEmitterLifetime(0.2)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(0.5,0.5)
emitter:setRadialAcceleration(50,100)
emitter:setRotation(0,360)
emitter:setTangentialAcceleration(12,24)
emitter:setSpeed(100,250)
emitter:setSpin(1,10)
emitter:setSpinVariation(0.5)
emitter:setLinearDamping(0,0)
emitter:setSpread(6.1999998092651)
emitter:setRelativeRotation(false)
emitter:setOffset(tex:getWidth()/2, tex:getHeight()/2)
emitter:setSizes(1)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255 )
return emitter;
end
|
Particle = {}
function Particle.ballImpactWithWall(nx, ny, x, y)
local tex = love.graphics.newImage("assets/textures/particle.png")
local emitter = love.graphics.newParticleSystem(tex,25)
emitter:setDirection(vector.angleTo(nx, ny))
emitter:setAreaSpread("none",0,0)
emitter:setEmissionRate(300)
emitter:setEmitterLifetime(0.8)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(1,1)
emitter:setRadialAcceleration(200,250)
emitter:setRotation(0,0)
emitter:setTangentialAcceleration(12,27)
emitter:setSpeed(100,250)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(2.7999999523163)
emitter:setRelativeRotation(false)
emitter:setOffset(tex:getHeight()/2, tex:getWidth()/2)
emitter:setSizes(1,0)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255)
emitter:setPosition(x, y)
return emitter;
end
function Particle.ballImpactWithPlayer(nx, ny, x, y)
local tex = love.graphics.newImage("assets/textures/spark.png")
local emitter = love.graphics.newParticleSystem(tex,50)
emitter:setDirection(vector.angleTo(nx, ny))
emitter:setAreaSpread("none",0,0)
emitter:setEmissionRate(300)
emitter:setEmitterLifetime(1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(1,1)
emitter:setRadialAcceleration(200,250)
emitter:setRotation(0,0)
emitter:setTangentialAcceleration(12,27)
emitter:setSpeed(100,250)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(5.5999999046326)
emitter:setRelativeRotation(false)
emitter:setOffset(tex:getHeight()/2, tex:getWidth()/2)
emitter:setSizes(1,0)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255)
emitter:setPosition(x, y)
return emitter;
end
function Particle.ballMovement()
local tex = love.graphics.newImage("assets/textures/particle.png")
local emitter = love.graphics.newParticleSystem(tex,100)
emitter:setDirection(0)
emitter:setAreaSpread("uniform",8,8)
emitter:setEmissionRate(100)
emitter:setEmitterLifetime(-1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(0.5,0.2)
emitter:setRadialAcceleration(0,0)
emitter:setRotation(0,0)
emitter:setTangentialAcceleration(0,0)
emitter:setSpeed(0,0)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(2)
emitter:setRelativeRotation(false)
emitter:setOffset(tex:getHeight()/2, tex:getWidth()/2)
emitter:setSizes(1.5, 0)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255,255,255,255,0)
return emitter;
end
function Particle.sunMenu()
local tex = love.graphics.newImage("assets/textures/startscreen_particle.png")
emitter = love.graphics.newParticleSystem(tex,200)
emitter:setDirection(1.6000000238419)
emitter:setAreaSpread("normal",200,80)
emitter:setEmissionRate(36)
emitter:setEmitterLifetime(-1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(5,5)
emitter:setRadialAcceleration(0,0)
emitter:setRotation(0,0)
emitter:setTangentialAcceleration(0,0)
emitter:setSpeed(3,73)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(6.1999998092651)
emitter:setRelativeRotation(false)
emitter:setOffset(tex:getHeight()/2, tex:getWidth()/2)
emitter:setSizes(0,1,0)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,100 )
return emitter;
end
function Particle.playerPushReady()
local tex = love.graphics.newImage("assets/textures/miniParticle.png")
local emitter = love.graphics.newParticleSystem(tex,50)
emitter:setDirection(0)
emitter:setAreaSpread("normal",8,32)
emitter:setEmissionRate(35)
emitter:setEmitterLifetime(-1)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(0.5,0.7)
emitter:setRadialAcceleration(50,100)
emitter:setRotation(0,360)
emitter:setTangentialAcceleration(12,24)
emitter:setSpeed(50,75)
emitter:setSpin(0,0)
emitter:setSpinVariation(0)
emitter:setLinearDamping(0,0)
emitter:setSpread(6.1999998092651)
emitter:setRelativeRotation(false)
emitter:setOffset(0,0)
emitter:setSizes(1,0.5)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255)
emitter:setOffset(tex:getHeight()/2, tex:getWidth()/2)
return emitter;
end
function Particle.boxExplosion()
local tex = love.graphics.newImage("assets/textures/woodParticle.png")
local emitter = love.graphics.newParticleSystem(tex,4)
emitter:setDirection(0)
emitter:setAreaSpread("none",0,0)
emitter:setEmissionRate(150)
emitter:setEmitterLifetime(0.2)
emitter:setLinearAcceleration(0,0,0,0)
emitter:setParticleLifetime(0.5,0.5)
emitter:setRadialAcceleration(50,100)
emitter:setRotation(0,360)
emitter:setTangentialAcceleration(12,24)
emitter:setSpeed(100,250)
emitter:setSpin(1,10)
emitter:setSpinVariation(0.5)
emitter:setLinearDamping(0,0)
emitter:setSpread(6.1999998092651)
emitter:setRelativeRotation(false)
emitter:setOffset(tex:getWidth()/2, tex:getHeight()/2)
emitter:setSizes(1)
emitter:setSizeVariation(0)
emitter:setColors(255,255,255,255 )
return emitter;
end
|
Fixed particle offset for ball+wall collisions
|
Fixed particle offset for ball+wall collisions
|
Lua
|
mit
|
GuiSim/pixel
|
72838e1936041a2ca4e15a271ff6f4399a5767c2
|
source/lt/display_data.lua
|
source/lt/display_data.lua
|
-- a package of classes for describing display data
-- these classes are used by the display list objects and the resource loaded
-- copyright 2016 Samuel Baird MIT Licence
local class = require('core.class')
local array = require('core.array')
local math = require('core.math')
local cache = require('core.cache')
-- color
local color = class(function (color)
function color:init(r, g, b, alpha)
self.r = r or 0
self.g = g or 0
self.b = b or 0
self.alpha = alpha or 1
end
function color:unpack_with_alpha(alpha)
return self.r, self.g, self.b, self.alpha * alpha * 255
end
color.white = color(255, 255, 255)
color.black = color(0, 0, 0)
color.clear = color(0, 0, 0, 0)
color.grey = function (grey_level)
return color(grey_level, grey_level, grey_level)
end
end)
-- font
local font = class(function (font)
font.default_font_name = nil
font.default_asset_scale = 1
function font:init(font_size, font_name, font_color, font_asset_scale)
self.size = font_size or 12
self.name = font_name or font.default_font_name
self.color = font_color or color.black
self.asset_scale = font_asset_scale or font.default_asset_scale
end
local font_cache = cache(8)
function font:cached_font_object()
local key = (self.name or '') .. ':' .. self.size
local obj = font_cache:get(key)
if not obj then
if self.name then
obj = love.graphics.newFont(self.name, self.size * self.asset_scale)
else
obj = love.graphics.newFont(self.size * self.asset_scale)
end
font_cache:set(key, obj)
end
return obj
end
font.default = font()
end)
-- single image within a texture
local image_data = class(function(image_data)
function image_data:init(name, texture, quad, xy)
self.name = name
self.texture = texture
self.quad = quad
self.xy = xy
self.ox = -xy[1]
self.oy = -xy[2]
end
function image_data:bounds()
local xy = self.xy
return xy[1], xy[2], xy[3] - xy[1], xy[4] - xy[2]
end
end)
-- clip data, a sequence of frames, each with arbitrary sub-content
local clip_data = class(function (clip_data)
function clip_data:init(name)
self.name = name
self.frames = array()
self.labels = {}
end
local clip_frame = class(function (clip_frame)
function clip_frame:init(label)
self.label = label
self.content = array()
end
function clip_frame:generate_instance(name)
local count = 1
for _, c in ipairs(self.content) do
if c.image_data == image_data then
count = count + 1
end
end
return '_' .. name .. '_' .. count
end
function clip_frame:add_image_content(instance, image_data, x, y, scale_x, scale_y, rotation, alpha)
-- generate an instance name automatically if not supplied
if not instance then
instance = self:generate_instance('img_' .. image_data.name)
end
local entry = {
instance = instance,
image_data = image_data,
x = x or 0,
y = y or 0,
scale_x = scale_x or 1,
scale_y = scale_y or 1,
rotation = rotation or 0,
alpha = alpha or 1,
}
self.content:push(entry)
return self
end
function clip_data:add_clip_content(instance, clip_data, x, y, scale_x, scale_y, rotation, alpha, frame_no)
-- generate an instance name automatically if not supplied
if not instance then
instance = self:generate_instance('clip_' .. clip_data.name)
end
local entry = {
instance = instance,
clip_data = clip_data,
x = x or 0,
y = y or 0,
scale_x = scale_x or 1,
scale_y = scale_y or 1,
rotation = rotation or 0,
alpha = alpha or 1,
frame_no = frame_no,
}
self.content:push(entry)
return self
end
end)
function clip_data:add_frame(label)
local frame = clip_frame(label)
self.frames:push(frame)
return frame
end
function clip_data:link_resources(resources)
-- generate start and end points for all frame labels as go through
self.labels['all'] = { 1, #self.frames }
local tracking_label = nil
for frame_no, frame in ipairs(self.frames) do
if frame.label then
tracking_label = { frame_no, frame_no }
self.labels[frame.label] = tracking_label
elseif tracking_label then
-- make sure end frame is stored for last tracked label
tracking_label[2] = frame_no
end
-- link image_data and clip_data objects directly
for _, c in ipairs(frame.content) do
if c.image_data and type(c.image_data) == 'string' then
c.image_data = resources.get_image_data(c.image_data)
end
if c.clip_data and type(c.clip_data) == 'string' then
c.clip_data = resources.get_clip_data(c.clip_data)
end
end
end
end
end)
return class.package({
color = color,
font = font,
image_data = image_data,
clip_data = clip_data,
})
|
-- a package of classes for describing display data
-- these classes are used by the display list objects and the resource loaded
-- copyright 2016 Samuel Baird MIT Licence
local class = require('core.class')
local array = require('core.array')
local math = require('core.math')
local cache = require('core.cache')
-- color
local color = class(function (color)
function color:init(r, g, b, alpha)
self.r = r or 0
self.g = g or 0
self.b = b or 0
self.alpha = alpha or 1
end
function color:unpack_with_alpha(alpha)
return self.r, self.g, self.b, self.alpha * alpha * 255
end
color.white = color(255, 255, 255)
color.black = color(0, 0, 0)
color.clear = color(0, 0, 0, 0)
color.grey = function (grey_level)
return color(grey_level, grey_level, grey_level)
end
end)
-- font
local font = class(function (font)
font.default_font_name = nil
font.default_asset_scale = 1
function font:init(font_size, font_name, font_color, font_asset_scale)
self.size = font_size or 12
self.name = font_name or font.default_font_name
self.color = font_color or color.black
self.asset_scale = font_asset_scale or font.default_asset_scale
end
local font_cache = cache(8)
function font:cached_font_object()
local key = (self.name or '') .. ':' .. self.size
local obj = font_cache:get(key)
if not obj then
if self.name then
obj = love.graphics.newFont(self.name, self.size * self.asset_scale)
else
obj = love.graphics.newFont(self.size * self.asset_scale)
end
font_cache:set(key, obj)
end
return obj
end
font.default = font()
end)
-- single image within a texture
local image_data = class(function(image_data)
function image_data:init(name, texture, quad, xy)
self.name = name
self.texture = texture
self.quad = quad
self.xy = xy
self.ox = -xy[1]
self.oy = -xy[2]
end
function image_data:bounds()
local xy = self.xy
return xy[1], xy[2], xy[3] - xy[1], xy[4] - xy[2]
end
end)
-- clip data, a sequence of frames, each with arbitrary sub-content
local clip_data = class(function (clip_data)
function clip_data:init(name)
self.name = name
self.frames = array()
self.labels = {}
end
local clip_frame = class(function (clip_frame)
function clip_frame:init(label)
self.label = label
self.content = array()
end
function clip_frame:generate_instance(name, data)
local count = 1
for _, c in ipairs(self.content) do
if c.image_data == data or c.clip_data == data then
count = count + 1
end
end
return '_' .. name .. '_' .. count
end
function clip_frame:add_image_content(instance, image_data, x, y, scale_x, scale_y, rotation, alpha)
-- generate an instance name automatically if not supplied
if not instance then
instance = self:generate_instance('img_' .. image_data.name, image_data)
end
local entry = {
instance = instance,
image_data = image_data,
x = x or 0,
y = y or 0,
scale_x = scale_x or 1,
scale_y = scale_y or 1,
rotation = rotation or 0,
alpha = alpha or 1,
}
self.content:push(entry)
return self
end
function clip_data:add_clip_content(instance, clip_data, x, y, scale_x, scale_y, rotation, alpha, frame_no)
-- generate an instance name automatically if not supplied
if not instance then
instance = self:generate_instance('clip_' .. clip_data.name, clip_data)
end
local entry = {
instance = instance,
clip_data = clip_data,
x = x or 0,
y = y or 0,
scale_x = scale_x or 1,
scale_y = scale_y or 1,
rotation = rotation or 0,
alpha = alpha or 1,
frame_no = frame_no,
}
self.content:push(entry)
return self
end
end)
function clip_data:add_frame(label)
local frame = clip_frame(label)
self.frames:push(frame)
return frame
end
function clip_data:link_resources(resources)
-- generate start and end points for all frame labels as go through
self.labels['all'] = { 1, #self.frames }
local tracking_label = nil
for frame_no, frame in ipairs(self.frames) do
if frame.label then
tracking_label = { frame_no, frame_no }
self.labels[frame.label] = tracking_label
elseif tracking_label then
-- make sure end frame is stored for last tracked label
tracking_label[2] = frame_no
end
-- link image_data and clip_data objects directly
for _, c in ipairs(frame.content) do
if c.image_data and type(c.image_data) == 'string' then
c.image_data = resources.get_image_data(c.image_data)
end
if c.clip_data and type(c.clip_data) == 'string' then
c.clip_data = resources.get_clip_data(c.clip_data)
end
end
end
end
end)
return class.package({
color = color,
font = font,
image_data = image_data,
clip_data = clip_data,
})
|
bug fix in clip data instance name assignment
|
bug fix in clip data instance name assignment
|
Lua
|
mit
|
samuelwbaird/letter
|
d8b50be25c2650663bdf7bc7afaa4bd8c4242af4
|
NaoTHSoccer/Make/projectconfig.lua
|
NaoTHSoccer/Make/projectconfig.lua
|
----------------------------------------
function printPath(prefix, path)
local msg = tostring(prefix) .. tostring(path)
if path == nil then
print ( "WARNING: path not set:", msg )
elseif os.isdir(path) then
print ( msg )
else
print ( "ERROR: path doesn't exist:", msg )
end
end
function table.append(t,s)
if s ~= nil then for _,v in pairs(s) do if v ~= nil then
table.insert(t, 1, v)
end end end
end
--------------------------------------------------------------
PATH = {}
PATH.libs = {}
PATH.includes = {}
function PATH:includedirs(s)
table.append(self.includes,s)
end
function PATH:libdirs(s)
table.append(self.libs,s)
end
-- for debug
function PATH:print()
print("INFO: list includedirs")
for _,v in pairs(self.includes) do
printPath("> ",v)
end
print("INFO: list libdirs")
for _,v in pairs(self.libs) do
printPath("> ",v)
end
end
--------------------------------------------------------------
-- load local user settings if available
if os.isfile("projectconfig.user.lua") then
print("INFO: loading local user path settings")
dofile "projectconfig.user.lua"
end
-------------- Set default paths if not set by the user ------------
-- path to the framework
if FRAMEWORK_PATH == nil then
FRAMEWORK_PATH = path.getabsolute("../../Framework")
end
-- external directory for the local system
if EXTERN_PATH_NATIVE == nil then
EXTERN_PATH_NATIVE = os.getenv("EXTERN_PATH_NATIVE")
end
-- path to the directory containing the nao cross compile tool chain
-- in a default configuration the directory NAO_CTC has the following layout
-- NAO_CTC
-- |-- compiler
-- `-- extern
-- needed to cross compile for the Nao
if NAO_CTC == nil then
NAO_CTC = os.getenv("NAO_CTC")
end
-- external libraries for the Nao robot
if EXTERN_PATH_NAO == nil and NAO_CTC ~= nil then
EXTERN_PATH_NAO = NAO_CTC .. "/extern"
end
if COMPILER_PATH_NAO == nil and NAO_CTC ~= nil then
COMPILER_PATH_NAO = NAO_CTC .. "/compiler"
end
-- (optional) path to the aldebarans naoqi directory for Nao
-- used to compile the NaoSMAL
if AL_DIR == nil then
AL_DIR = os.getenv("AL_DIR")
end
-- (optional) path to the installation of webots, e.g., C:\Program files\Webots
-- needed by webots platform
if WEBOTS_HOME == nil then
WEBOTS_HOME = os.getenv("WEBOTS_HOME")
end
--------------------------------------------------------------
assert(FRAMEWORK_PATH ~= nil and os.isdir(FRAMEWORK_PATH),
"a valid FRAMEWORK_PATH is needed for compilation.")
dofile (FRAMEWORK_PATH .. "/BuildTools/ansicolors.lua")
print("INFO: list raw path configuration")
printPath(" FRAMEWORK_PATH = ", tostring(FRAMEWORK_PATH))
printPath(" EXTERN_PATH_NATIVE = ", tostring(EXTERN_PATH_NATIVE))
printPath(" NAO_CTC = ", tostring(NAO_CTC))
printPath(" EXTERN_PATH_NAO = ", tostring(EXTERN_PATH_NAO))
printPath(" COMPILER_PATH_NAO = ", tostring(COMPILER_PATH_NAO))
printPath(" AL_DIR = ", tostring(AL_DIR))
printPath(" WEBOTS_HOME = ", tostring(WEBOTS_HOME))
--------------------------------------------------------------
-- define pathes depending on the platform
if PLATFORM == "Nao" then
assert(EXTERN_PATH_NAO ~= nil, "EXTERN_PATH_NAO is needed to be able to compile for nao.")
EXTERN_PATH = path.getabsolute(EXTERN_PATH_NAO)
if AL_DIR ~= nil then
PATH:includedirs {AL_DIR .. "/include"}
PATH:libdirs {AL_DIR .. "/lib"}
end
else
assert(EXTERN_PATH_NATIVE ~= nil, "EXTERN_PATH_NATIVE is need to be able to compile.")
EXTERN_PATH = path.getabsolute(EXTERN_PATH_NATIVE)
if WEBOTS_HOME ~= nil then
PATH:includedirs {WEBOTS_HOME .. "/include/controller/c"}
PATH:libdirs {WEBOTS_HOME .. "/lib"}
end
end
-- add general pathes
-- this mainly reflects the internal structure of the extern directory
PATH:includedirs {
FRAMEWORK_PATH .. "/Commons/Source",
FRAMEWORK_PATH .. "/Commons/Source/Messages",
EXTERN_PATH .. "/include",
EXTERN_PATH .. "/include/glib-2.0",
EXTERN_PATH .. "/include/gio-unix-2.0",
EXTERN_PATH .. "/lib/glib-2.0/include"
}
PATH:libdirs { EXTERN_PATH .. "/lib"}
--------------------------------------------------------------
PATH:print()
print()
|
--------------------------------------------------------------
function printPath(prefix, path)
local msg = tostring(prefix) .. tostring(path)
if path == nil then
print ( "WARNING: path not set:", msg )
elseif os.isdir(path) then
print ( msg )
else
print ( "ERROR: path doesn't exist:", msg )
end
end
function table.append(t,s)
if s ~= nil then for _,v in pairs(s) do if v ~= nil then
table.insert(t, 1, v)
end end end
end
--------------------------------------------------------------
PATH = {}
PATH.libs = {}
PATH.includes = {}
function PATH:includedirs(s)
table.append(self.includes,s)
end
function PATH:libdirs(s)
table.append(self.libs,s)
end
-- for debug
function PATH:print()
print("INFO: list includedirs")
for _,v in pairs(self.includes) do
printPath("> ",v)
end
print("INFO: list libdirs")
for _,v in pairs(self.libs) do
printPath("> ",v)
end
end
--------------------------------------------------------------
-- load local user settings if available
if os.isfile("projectconfig.user.lua") then
print("INFO: loading local user path settings")
dofile "projectconfig.user.lua"
end
-------------- Set default paths if not set by the user ------------
-- path to the framework
if FRAMEWORK_PATH == nil then
FRAMEWORK_PATH = path.getabsolute("../../Framework")
end
-- external directory for the local system
if EXTERN_PATH_NATIVE == nil then
EXTERN_PATH_NATIVE = os.getenv("EXTERN_PATH_NATIVE")
end
-- path to the directory containing the nao cross compile tool chain
-- in a default configuration the directory NAO_CTC has the following layout
-- NAO_CTC
-- |-- compiler
-- `-- extern
-- needed to cross compile for the Nao
if NAO_CTC == nil then
NAO_CTC = os.getenv("NAO_CTC")
end
-- external libraries for the Nao robot
if EXTERN_PATH_NAO == nil and NAO_CTC ~= nil then
EXTERN_PATH_NAO = NAO_CTC .. "/extern"
end
if COMPILER_PATH_NAO == nil and NAO_CTC ~= nil then
COMPILER_PATH_NAO = NAO_CTC .. "/compiler"
end
-- (optional) path to the aldebarans naoqi directory for Nao
-- used to compile the NaoSMAL and the WhistleDetector
if AL_DIR == nil then
AL_DIR = os.getenv("AL_DIR")
end
--------------------------------------------------------------
assert(FRAMEWORK_PATH ~= nil and os.isdir(FRAMEWORK_PATH),
"a valid FRAMEWORK_PATH is needed for compilation.")
dofile (FRAMEWORK_PATH .. "/BuildTools/ansicolors.lua")
print("INFO: list raw path configuration")
printPath(" FRAMEWORK_PATH = ", tostring(FRAMEWORK_PATH))
printPath(" EXTERN_PATH_NATIVE = ", tostring(EXTERN_PATH_NATIVE))
printPath(" NAO_CTC = ", tostring(NAO_CTC))
printPath(" EXTERN_PATH_NAO = ", tostring(EXTERN_PATH_NAO))
printPath(" COMPILER_PATH_NAO = ", tostring(COMPILER_PATH_NAO))
printPath(" AL_DIR = ", tostring(AL_DIR))
--------------------------------------------------------------
-- define pathes depending on the platform
if PLATFORM == "Nao" then
assert(EXTERN_PATH_NAO ~= nil, "EXTERN_PATH_NAO is needed to be able to compile for nao.")
EXTERN_PATH = path.getabsolute(EXTERN_PATH_NAO)
if AL_DIR ~= nil then
PATH:includedirs {AL_DIR .. "/include"}
PATH:libdirs {AL_DIR .. "/lib"}
end
else
assert(EXTERN_PATH_NATIVE ~= nil, "EXTERN_PATH_NATIVE is need to be able to compile.")
EXTERN_PATH = path.getabsolute(EXTERN_PATH_NATIVE)
end
-- add general pathes
-- this mainly reflects the internal structure of the extern directory
PATH:includedirs {
FRAMEWORK_PATH .. "/Commons/Source",
FRAMEWORK_PATH .. "/Commons/Source/Messages",
EXTERN_PATH .. "/include",
EXTERN_PATH .. "/include/glib-2.0",
-- EXTERN_PATH .. "/include/gio-unix-2.0", -- does not exists anymore
EXTERN_PATH .. "/lib/glib-2.0/include"
}
PATH:libdirs { EXTERN_PATH .. "/lib"}
--------------------------------------------------------------
PATH:print()
print()
|
fixed warning in projectconfig.lua
|
fixed warning in projectconfig.lua
|
Lua
|
apache-2.0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
2c166275815aa0030503c180ffdf203607dc3f30
|
lua/starfall/libs_sh/net.lua
|
lua/starfall/libs_sh/net.lua
|
-------------------------------------------------------------------------------
-- Networking library.
-------------------------------------------------------------------------------
local net = net
--- Net message library. Used for sending data from the server to the client and back
local net_library, _ = SF.Libraries.Register("net")
local function can_send( instance, noupdate )
if instance.data.net.lasttime < CurTime() - 1 then
if not noupdate then
instance.data.net.lasttime = CurTime()
end
return true
else
return false
end
end
local function write( instance, type, value, setting )
instance.data.net.data[#instance.data.net.data+1] = { "Write" .. type, value, setting }
end
SF.Libraries.AddHook( "initialize", function( instance )
instance.data.net = {
started = false,
lasttime = 0,
data = {},
}
end)
SF.Libraries.AddHook( "deinitialize", function( instance )
if instance.data.net.started then
instance.data.net.started = false
end
end)
if SERVER then
util.AddNetworkString( "SF_netmessage" )
local function checktargets( target )
if target then
if SF.GetType(target) == "table" then
local newtarget = {}
for i=1,#target do
SF.CheckType( SF.Entities.Unwrap(target[i]), "Player", 1 )
newtarget[i] = SF.Entities.Unwrap(target[i])
end
return net.Send, newtarget
else
SF.CheckType( SF.Entities.Unwrap(target), "Player", 1 ) -- TODO: unhacky this
return net.Send, SF.Entities.Unwrap(target)
end
else
return net.Broadcast
end
end
function net_library.send( target )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local sendfunc, newtarget = checktargets( target )
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
sendfunc( newtarget )
end
else
function net_library.send()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
net.SendToServer()
end
end
function net_library.start( name )
SF.CheckType( name, "string" )
local instance = SF.instance
if not can_send( instance ) then return error("can't send net messages that often",2) end
instance.data.net.started = true
instance.data.net.data = {}
write( instance, "String", name )
end
function net_library.writeTable( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "table" )
write( instance, "Table", SF.Unsanitize(t) )
return true
end
function net_library.readTable()
return SF.Sanitize(net.ReadTable())
end
function net_library.writeString( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "string" )
write( instance, "String", t )
return true
end
function net_library.readString()
return net.ReadString()
end
function net_library.writeInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Int", t, n )
return true
end
function net_library.readInt(n)
return net.ReadInt(n)
end
function net_library.writeUInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "UInt", t, n )
return true
end
function net_library.readUInt(n)
return net.ReadUInt(n)
end
function net_library.writeBit( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "boolean" )
write( instance, "Bit", t )
return true
end
function net_library.readBit()
return net.ReadBit()
end
function net_library.writeDouble( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Double", t )
return true
end
function net_library.readDouble()
return net.ReadDouble()
end
function net_library.writeFloat( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Float", t )
return true
end
function net_library.readFloat()
return net.ReadFloat()
end
function net_library.bytesWritten()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
return net.BytesWritten()
end
function net_library.canSend()
return can_send(SF.instance, true)
end
net.Receive( "SF_netmessage", function( len )
SF.RunScriptHook( "net", net.ReadString(), len )
end)
|
-------------------------------------------------------------------------------
-- Networking library.
-------------------------------------------------------------------------------
local net = net
--- Net message library. Used for sending data from the server to the client and back
local net_library, _ = SF.Libraries.Register("net")
local function can_send( instance, noupdate )
if instance.data.net.lasttime < CurTime() - 1 then
if not noupdate then
instance.data.net.lasttime = CurTime()
end
return true
else
return false
end
end
local function write( instance, type, value, setting )
instance.data.net.data[#instance.data.net.data+1] = { "Write" .. type, value, setting }
end
SF.Libraries.AddHook( "initialize", function( instance )
instance.data.net = {
started = false,
lasttime = 0,
data = {},
}
end)
SF.Libraries.AddHook( "deinitialize", function( instance )
if instance.data.net.started then
instance.data.net.started = false
end
end)
if SERVER then
util.AddNetworkString( "SF_netmessage" )
local function checktargets( target )
if target then
if SF.GetType(target) == "table" then
local newtarget = {}
for i=1,#target do
SF.CheckType( SF.Entities.Unwrap(target[i]), "Player", 1 )
newtarget[i] = SF.Entities.Unwrap(target[i])
end
return net.Send, newtarget
else
SF.CheckType( SF.Entities.Unwrap(target), "Player", 1 ) -- TODO: unhacky this
return net.Send, SF.Entities.Unwrap(target)
end
else
return net.Broadcast
end
end
function net_library.send( target )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local sendfunc, newtarget = checktargets( target )
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
sendfunc( newtarget )
end
else
function net_library.send()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
net.SendToServer()
end
end
function net_library.start( name )
SF.CheckType( name, "string" )
local instance = SF.instance
if not can_send( instance ) then return error("can't send net messages that often",2) end
instance.data.net.started = true
instance.data.net.data = {}
write( instance, "String", name )
end
function net_library.writeTable( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "table" )
write( instance, "Table", SF.Unsanitize(t) )
return true
end
function net_library.readTable()
return SF.Sanitize(net.ReadTable())
end
function net_library.writeString( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "string" )
write( instance, "String", t )
return true
end
function net_library.readString()
return net.ReadString()
end
function net_library.writeInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "Int", t, n )
return true
end
function net_library.readInt(n)
SF.CheckType( n, "number" )
return net.ReadInt(n)
end
function net_library.writeUInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "UInt", t, n )
return true
end
function net_library.readUInt(n)
SF.CheckType( n, "number" )
return net.ReadUInt(n)
end
function net_library.writeBit( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "boolean" )
write( instance, "Bit", t )
return true
end
function net_library.readBit()
return net.ReadBit()
end
function net_library.writeDouble( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Double", t )
return true
end
function net_library.readDouble()
return net.ReadDouble()
end
function net_library.writeFloat( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Float", t )
return true
end
function net_library.readFloat()
return net.ReadFloat()
end
function net_library.bytesWritten()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
return net.BytesWritten()
end
function net_library.canSend()
return can_send(SF.instance, true)
end
net.Receive( "SF_netmessage", function( len )
SF.RunScriptHook( "net", net.ReadString(), len )
end)
|
[Fix] some netlibs not doing typechecks
|
[Fix] some netlibs not doing typechecks
|
Lua
|
bsd-3-clause
|
Jazzelhawk/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall
|
a32832a1d32c7fce4d698f1b185b584466af0d10
|
game/scripts/vscripts/modules/SimpleAI/SimpleAI.lua
|
game/scripts/vscripts/modules/SimpleAI/SimpleAI.lua
|
AI_THINK_INTERVAL = 0.3
AI_STATE_IDLE = 0
AI_STATE_AGGRESSIVE = 1
AI_STATE_RETURNING = 2
AI_STATE_CASTING = 3
AI_STATE_ORDER = 4
ModuleLinkLuaModifier(..., "modifier_simple_ai")
SimpleAI = {}
SimpleAI.__index = SimpleAI
function SimpleAI:new( unit, profile, params )
local ai = {}
setmetatable( ai, SimpleAI )
ai.unit = unit
ai.ThinkEnabled = true
ai.Thinkers = {}
ai.state = AI_STATE_IDLE
ai.profile = profile
if profile == "boss" then
ai.stateThinks = {
[AI_STATE_IDLE] = 'IdleThink',
[AI_STATE_AGGRESSIVE] = 'AggressiveThink',
[AI_STATE_RETURNING] = 'ReturningThink',
[AI_STATE_CASTING] = 'CastingThink',
[AI_STATE_ORDER] = 'OrderThink',
}
ai.spawnPos = params.spawnPos or unit:GetAbsOrigin()
ai.aggroRange = params.aggroRange or unit:GetAcquisitionRange()
ai.leashRange = params.leashRange or 1000
ai.abilityCastCallback = params.abilityCastCallback
end
if profile == "tower" then
ai.stateThinks = {
[AI_STATE_IDLE] = 'IdleThink',
[AI_STATE_AGGRESSIVE] = 'AggressiveThink',
[AI_STATE_CASTING] = 'CastingThink',
[AI_STATE_ORDER] = 'OrderThink',
}
ai.spawnPos = params.spawnPos or unit:GetAbsOrigin()
ai.aggroRange = unit:GetAttackRange()
ai.leashRange = ai.aggroRange
ai.abilityCastCallback = params.abilityCastCallback
end
unit:AddNewModifier(unit, nil, "modifier_simple_ai", {})
Timers:CreateTimer( ai.GlobalThink, ai )
if unit.ai then
unit.ai:Destroy()
end
unit.ai = ai
return ai
end
function SimpleAI:SwitchState(newState)
if self.stateThinks[newState] then
self.state = newState
if newState == AI_STATE_RETURNING then
self.unit:MoveToPosition(self.spawnPos)
end
else
self:SwitchState(AI_STATE_IDLE)
end
end
function SimpleAI:GlobalThink()
if self.MarkedForDestroy or not self.unit:IsAlive() then
return
end
if self.ThinkEnabled then
Dynamic_Wrap(SimpleAI, self.stateThinks[ self.state ])(self)
if self.abilityCastCallback and self.state ~= AI_STATE_CASTING then
self.abilityCastCallback(self)
end
end
for k,_ in pairs(self.Thinkers) do
if not k() then
self.Thinkers[k] = nil
end
end
return AI_THINK_INTERVAL
end
--Boss Thinkers
function SimpleAI:IdleThink()
--local units = Dynamic_Wrap(SimpleAI, "FindUnitsNearby")(self, self.aggroRange, false, true)
local units = self:FindUnitsNearby(self.aggroRange, false, true, nil, DOTA_UNIT_TARGET_FLAG_NO_INVIS)
if #units > 0 then
self.unit:MoveToTargetToAttack( units[1] )
self.aggroTarget = units[1]
self:SwitchState(AI_STATE_AGGRESSIVE)
return
end
end
function SimpleAI:AggressiveThink()
local aggroTarget = self.aggroTarget
if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() > self.leashRange
or not IsValidEntity(aggroTarget)
or not aggroTarget:IsAlive()
or (aggroTarget.IsInvisible and aggroTarget:IsInvisible())
or (aggroTarget.IsInvulnerable and aggroTarget:IsInvulnerable())
or (aggroTarget.IsAttackImmune and aggroTarget:IsAttackImmune())
or (self.profile == "tower" and (self.spawnPos - aggroTarget:GetAbsOrigin()):Length2D() > self.leashRange) then
self:SwitchState(AI_STATE_RETURNING)
return
else
self.unit:MoveToTargetToAttack(self.aggroTarget)
end
end
function SimpleAI:ReturningThink()
self.unit:MoveToPosition(self.spawnPos) -- If movement order was interrupted for some reason (Force Staff)
if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() < 10 then
self:SwitchState(AI_STATE_IDLE)
return
end
end
function SimpleAI:CastingThink()
end
function SimpleAI:OrderThink()
local orderEnd = false
if self.ExecutingOrder.OrderType == DOTA_UNIT_ORDER_MOVE_TO_POSITION then
if (self.ExecutingOrder.Position - self.unit:GetAbsOrigin()):Length2D() < 10 then
orderEnd = true
end
end
if orderEnd then
self.ExecutingOrder = nil
self:SwitchState(AI_STATE_RETURNING)
end
end
--Utils
function SimpleAI:OnTakeDamage(attacker)
if (self.state == AI_STATE_IDLE or self.state == AI_STATE_RETURNING) and (self.spawnPos - attacker:GetAbsOrigin()):Length2D() < self.leashRange then
self.unit:MoveToTargetToAttack( attacker )
self.aggroTarget = attacker
self:SwitchState(AI_STATE_AGGRESSIVE)
end
end
function SimpleAI:AddThink(func)
self.Thinkers[func] = true
end
--Legacy
function SimpleAI:FindUnitsNearby(radius, bAllies, bEnemies, targettype, flags)
local teamfilter = DOTA_UNIT_TARGET_TEAM_NONE
if bAllies then
teamfilter = teamfilter + DOTA_UNIT_TARGET_TEAM_FRIENDLY
end
if bEnemies then
teamfilter = teamfilter + DOTA_UNIT_TARGET_TEAM_ENEMY
end
local units = FindUnitsInRadius(self.unit:GetTeam(), self.unit:GetAbsOrigin(), nil, radius, teamfilter or DOTA_UNIT_TARGET_TEAM_ENEMY, targettype or DOTA_UNIT_TARGET_ALL, flags or DOTA_UNIT_TARGET_FLAG_NONE, FIND_CLOSEST, false)
return units
end
function SimpleAI:FindUnitsNearbyForAbility(ability)
local selfAbs = self.unit:GetAbsOrigin()
return FindUnitsInRadius(self.unit:GetTeam(), selfAbs, nil, ability:GetCastRange(selfAbs, nil), ability:GetAbilityTargetTeam(), ability:GetAbilityTargetType(), ability:GetAbilityTargetFlags(), FIND_CLOSEST, false)
end
function SimpleAI:UseAbility(ability, target)
if self.state ~= AI_STATE_CASTING and ability:IsFullyCastable() then
self:SwitchState(AI_STATE_CASTING)
if ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_NO_TARGET) then
self.unit:CastAbilityNoTarget(ability, -1)
elseif ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_UNIT_TARGET) then
self.unit:CastAbilityOnTarget(target, ability, -1)
elseif ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_POINT) then
self.unit:CastAbilityOnPosition(target, ability, -1)
end
local endtime = GameRules:GetGameTime() + ability:GetCastPoint() + 0.1
self:AddThink(function()
if GameRules:GetGameTime() >= endtime and not self.unit:IsChanneling() then
self:SwitchState(AI_STATE_RETURNING)
return false
end
return true
end)
end
end
function SimpleAI:ExecuteOrder(order)
self.ExecutingOrder = order
ExecuteOrderFromTable(order)
self:SwitchState(AI_STATE_ORDER)
end
function SimpleAI:SetThinkEnabled(state)
self.ThinkEnabled = state
end
function SimpleAI:AreUnitsInLineAround(width, length, teamFilter, typeFilter, flagFilter, min_unit_count)
local line_count = 360/width
for i = 1, line_count do
local newLoc = self.unit:GetAbsOrigin() + (RotatePosition(Vector(0,0,0),QAngle(0,i*line_count,0),Vector(1,1,0))):Normalized() * speed
local units = FindUnitsInLine(self.unit:GetTeam(), self.unit:GetAbsOrigin(), newLoc, nil, width, teamFilter or DOTA_UNIT_TARGET_TEAM_ENEMY, typeFilter or DOTA_UNIT_TARGET_ALL, flagFilter or DOTA_UNIT_TARGET_FLAG_NONE)
if not min_unit_count or #units > min_unit_count then
return units
end
end
end
function SimpleAI:Destroy()
self.MarkedForDestroy = true
end
|
AI_THINK_INTERVAL = 0.3
AI_STATE_IDLE = 0
AI_STATE_AGGRESSIVE = 1
AI_STATE_RETURNING = 2
AI_STATE_CASTING = 3
AI_STATE_ORDER = 4
ModuleLinkLuaModifier(..., "modifier_simple_ai")
SimpleAI = {}
SimpleAI.__index = SimpleAI
function SimpleAI:new( unit, profile, params )
local ai = {}
setmetatable( ai, SimpleAI )
ai.unit = unit
ai.ThinkEnabled = true
ai.Thinkers = {}
ai.state = AI_STATE_IDLE
ai.profile = profile
if profile == "boss" then
ai.stateThinks = {
[AI_STATE_IDLE] = 'IdleThink',
[AI_STATE_AGGRESSIVE] = 'AggressiveThink',
[AI_STATE_RETURNING] = 'ReturningThink',
[AI_STATE_CASTING] = 'CastingThink',
[AI_STATE_ORDER] = 'OrderThink',
}
ai.spawnPos = params.spawnPos or unit:GetAbsOrigin()
ai.aggroRange = params.aggroRange or unit:GetAcquisitionRange()
ai.leashRange = params.leashRange or 1000
ai.abilityCastCallback = params.abilityCastCallback
end
if profile == "tower" then
ai.stateThinks = {
[AI_STATE_IDLE] = 'IdleThink',
[AI_STATE_AGGRESSIVE] = 'AggressiveThink',
[AI_STATE_CASTING] = 'CastingThink',
[AI_STATE_ORDER] = 'OrderThink',
}
ai.spawnPos = params.spawnPos or unit:GetAbsOrigin()
ai.aggroRange = unit:GetAttackRange()
ai.leashRange = ai.aggroRange
ai.abilityCastCallback = params.abilityCastCallback
end
unit:AddNewModifier(unit, nil, "modifier_simple_ai", {})
Timers:CreateTimer( ai.GlobalThink, ai )
if unit.ai then
unit.ai:Destroy()
end
unit.ai = ai
return ai
end
function SimpleAI:SwitchState(newState)
if self.stateThinks[newState] then
self.state = newState
if newState == AI_STATE_RETURNING then
self.unit:MoveToPosition(self.spawnPos)
end
else
self:SwitchState(AI_STATE_IDLE)
end
end
function SimpleAI:GlobalThink()
if self.MarkedForDestroy or not self.unit:IsAlive() then
return
end
if self.ThinkEnabled then
Dynamic_Wrap(SimpleAI, self.stateThinks[ self.state ])(self)
if self.abilityCastCallback and self.state ~= AI_STATE_CASTING then
self.abilityCastCallback(self)
end
end
for k,_ in pairs(self.Thinkers) do
if not k() then
self.Thinkers[k] = nil
end
end
return AI_THINK_INTERVAL
end
--Boss Thinkers
function SimpleAI:IdleThink()
--local units = Dynamic_Wrap(SimpleAI, "FindUnitsNearby")(self, self.aggroRange, false, true)
local units = self:FindUnitsNearby(self.aggroRange, false, true, nil, DOTA_UNIT_TARGET_FLAG_NO_INVIS)
if #units > 0 then
self.unit:MoveToTargetToAttack( units[1] )
self.aggroTarget = units[1]
self:SwitchState(AI_STATE_AGGRESSIVE)
return
end
end
function SimpleAI:AggressiveThink()
local aggroTarget = self.aggroTarget
if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() > self.leashRange
or not IsValidEntity(aggroTarget)
or not aggroTarget:IsAlive()
or (aggroTarget.IsInvisible and aggroTarget:IsInvisible())
or (aggroTarget.IsInvulnerable and aggroTarget:IsInvulnerable())
or (aggroTarget.IsAttackImmune and aggroTarget:IsAttackImmune())
or (self.profile == "tower" and (self.spawnPos - aggroTarget:GetAbsOrigin()):Length2D() > self.leashRange) then
self:SwitchState(AI_STATE_RETURNING)
return
else
-- Pretty dirty hack to forecefully update target
self.unit:MoveToTargetToAttack(self.unit)
self.unit:MoveToTargetToAttack(self.aggroTarget)
end
end
function SimpleAI:ReturningThink()
self.unit:MoveToPosition(self.spawnPos) -- If movement order was interrupted for some reason (Force Staff)
if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() < 10 then
self:SwitchState(AI_STATE_IDLE)
return
end
end
function SimpleAI:CastingThink()
end
function SimpleAI:OrderThink()
local orderEnd = false
if self.ExecutingOrder.OrderType == DOTA_UNIT_ORDER_MOVE_TO_POSITION then
if (self.ExecutingOrder.Position - self.unit:GetAbsOrigin()):Length2D() < 10 then
orderEnd = true
end
end
if orderEnd then
self.ExecutingOrder = nil
self:SwitchState(AI_STATE_RETURNING)
end
end
--Utils
function SimpleAI:OnTakeDamage(attacker)
if (self.state == AI_STATE_IDLE or self.state == AI_STATE_RETURNING) and (self.spawnPos - attacker:GetAbsOrigin()):Length2D() < self.leashRange then
self.unit:MoveToTargetToAttack( attacker )
self.aggroTarget = attacker
self:SwitchState(AI_STATE_AGGRESSIVE)
end
end
function SimpleAI:AddThink(func)
self.Thinkers[func] = true
end
--Legacy
function SimpleAI:FindUnitsNearby(radius, bAllies, bEnemies, targettype, flags)
local teamfilter = DOTA_UNIT_TARGET_TEAM_NONE
if bAllies then
teamfilter = teamfilter + DOTA_UNIT_TARGET_TEAM_FRIENDLY
end
if bEnemies then
teamfilter = teamfilter + DOTA_UNIT_TARGET_TEAM_ENEMY
end
local units = FindUnitsInRadius(self.unit:GetTeam(), self.unit:GetAbsOrigin(), nil, radius, teamfilter or DOTA_UNIT_TARGET_TEAM_ENEMY, targettype or DOTA_UNIT_TARGET_ALL, flags or DOTA_UNIT_TARGET_FLAG_NONE, FIND_CLOSEST, false)
return units
end
function SimpleAI:FindUnitsNearbyForAbility(ability)
local selfAbs = self.unit:GetAbsOrigin()
return FindUnitsInRadius(self.unit:GetTeam(), selfAbs, nil, ability:GetCastRange(selfAbs, nil), ability:GetAbilityTargetTeam(), ability:GetAbilityTargetType(), ability:GetAbilityTargetFlags(), FIND_CLOSEST, false)
end
function SimpleAI:UseAbility(ability, target)
if self.state ~= AI_STATE_CASTING and ability:IsFullyCastable() then
self:SwitchState(AI_STATE_CASTING)
if ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_NO_TARGET) then
self.unit:CastAbilityNoTarget(ability, -1)
elseif ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_UNIT_TARGET) then
self.unit:CastAbilityOnTarget(target, ability, -1)
elseif ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_POINT) then
self.unit:CastAbilityOnPosition(target, ability, -1)
end
local endtime = GameRules:GetGameTime() + ability:GetCastPoint() + 0.1
self:AddThink(function()
if GameRules:GetGameTime() >= endtime and not self.unit:IsChanneling() then
self:SwitchState(AI_STATE_RETURNING)
return false
end
return true
end)
end
end
function SimpleAI:ExecuteOrder(order)
self.ExecutingOrder = order
ExecuteOrderFromTable(order)
self:SwitchState(AI_STATE_ORDER)
end
function SimpleAI:SetThinkEnabled(state)
self.ThinkEnabled = state
end
function SimpleAI:AreUnitsInLineAround(width, length, teamFilter, typeFilter, flagFilter, min_unit_count)
local line_count = 360/width
for i = 1, line_count do
local newLoc = self.unit:GetAbsOrigin() + (RotatePosition(Vector(0,0,0),QAngle(0,i*line_count,0),Vector(1,1,0))):Normalized() * speed
local units = FindUnitsInLine(self.unit:GetTeam(), self.unit:GetAbsOrigin(), newLoc, nil, width, teamFilter or DOTA_UNIT_TARGET_TEAM_ENEMY, typeFilter or DOTA_UNIT_TARGET_ALL, flagFilter or DOTA_UNIT_TARGET_FLAG_NONE)
if not min_unit_count or #units > min_unit_count then
return units
end
end
end
function SimpleAI:Destroy()
self.MarkedForDestroy = true
end
|
fix(SimpleAI): bosses AI aggro target won't be reattacked after invulnerability
|
fix(SimpleAI): bosses AI aggro target won't be reattacked after invulnerability
This is caused by wired MoveToTargetToAttack behaviour.
It stops attacking if target get's invulnerable.
Under normal conditions, it should be handled by IsInvulnerable() check above,
but since think interval is much larger than invulnerability duration, it won't lose target.
It's rather dirty solution, so we should find something better later.
Fixes #14
|
Lua
|
mit
|
ark120202/aabs
|
b5b652042b739acb2a899d18f0dad3b5bafc01da
|
test_scripts/Polices/build_options/ATF_Start_PTU_retry_sequence.lua
|
test_scripts/Polices/build_options/ATF_Start_PTU_retry_sequence.lua
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] Local Policy Table retry sequence start
--
-- Description:
-- In case PoliciesManager does not receive the Updated PT during time defined in
-- "timeout_after_x_seconds" section of Local PT, it must start the retry sequence.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag
-- Application not in PT is registered -> PTU is triggered
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[])
-- HMI -> SDL: SDL.GetURLs (<service>)
-- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType: PROPRIETARY)
-- 2. Performed steps
-- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON")
-- Expected result:
-- Timeout expires and retry sequence started
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Sending_PTS_to_mobile_application()
local time_update_needed = {}
local time_system_request = {}
local endpoints = {}
local is_test_fail = false
local SystemFilesPath = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
local PathToSnapshot = commonFunctions:read_parameter_from_smart_device_link_ini("PathToSnapshot")
local file_pts = SystemFilesPath.."/"..PathToSnapshot
local seconds_between_retries = {}
local timeout_pts = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds")
for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do
seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value
end
local time_wait = (timeout_pts*seconds_between_retries[1]*1000 + 2000)
commonTestCases:DelayedExp(time_wait) -- tolerance 10 sec
for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do
if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then
endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = nil}
end
end
local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } )
:Do(function(_,_)
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" })
--first retry sequence
local function verify_retry_sequence(occurences)
--time_update_needed[#time_update_needed + 1] = testCasesForPolicyTable.time_trigger
time_update_needed[#time_update_needed + 1] = timestamp()
local time_1 = time_update_needed[#time_update_needed]
local time_2 = time_system_request[#time_system_request]
local timeout = (time_1 - time_2)
if( ( timeout > (timeout_pts*1000 + 2000) ) or ( timeout < (timeout_pts*1000 - 2000) )) then
is_test_fail = true
commonFunctions:printError("ERROR: timeout for retry sequence "..occurences.." is not as expected: "..timeout_pts.."msec(5sec tolerance). real: "..timeout.."ms")
else
print("timeout is as expected for retry sequence "..occurences..": "..timeout_pts.."ms. real: "..timeout)
end
return true
end
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"})
:Do(function(_,_) time_system_request[#time_system_request + 1] = timestamp() end)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}, {status = "UPDATE_NEEDED"}):Times(2):Timeout(64000)
:Do(function(exp_pu, data)
print(exp_pu.occurences..":"..data.params.status)
if(data.params.status == "UPDATE_NEEDED") then
verify_retry_sequence(exp_pu.occurences - 1)
end
end)
--TODO(istoimenova): Remove when "[GENIVI] PTU is restarted each 10 sec." is fixed.
EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0)
:Do(function(_,data)
is_test_fail = true
commonFunctions:printError("ERROR: PTU sequence is restarted again!")
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
end)
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] Local Policy Table retry sequence start
--
-- Description:
-- In case PoliciesManager does not receive the Updated PT during time defined in
-- "timeout_after_x_seconds" section of Local PT, it must start the retry sequence.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag
-- Application not in PT is registered -> PTU is triggered
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[])
--
-- 2. Performed steps
-- HMI -> SDL: SDL.GetURLs (<service>)
-- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType: PROPRIETARY)
--
-- Expected result:
-- Timeout expires and retry sequence started
-- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON")
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
config.application1.registerAppInterfaceParams.appHMIType = { "MEDIA" }
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
local mobile_session = require('mobile_session')
local atf_logger = require('atf_logger')
--[[ Local variables ]]
local time_prev = 0
local time_curr = 0
local exp_timeout = 30000
local tolerance = 500 -- ms
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/build_options/retry_seq.json")
--[[ General Settings for configuration ]]
Test = require('user_modules/connecttest_resumption')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Connect_device()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_OnStatusUpdate_UPDATE_NEEDED_new_PTU_request()
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", {application = {appName = config.application1.registerAppInterfaceParams.appName}})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}, {status = "UPDATING"})
:Do(function(exp, data)
print("[" .. atf_logger.formated_time(true) .. "] " .. "SDL->HMI: SDL.OnStatusUpdate()" .. ": " .. exp.occurences .. ": " .. data.params.status)
if (exp.occurences == 2) and (data.params.status == "UPDATING") then
time_prev = timestamp()
end
end)
:Times(2)
self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" })
self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"})
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
:Do(function()
print("[" .. atf_logger.formated_time(true) .. "] " .. "SDL->HMI: BC.PolicyUpdate")
local requestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(requestId)
:Do(function()
local policy_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
local pts_file_name = commonFunctions:read_parameter_from_smart_device_link_ini("PathToSnapshot")
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = policy_file_path .. pts_file_name })
self.mobileSession:ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" })
end)
end)
end
function Test:TestStep_RetrySequenceStart()
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}, {status = "UPDATING"})
:Do(function(exp, data)
print("[" .. atf_logger.formated_time(true) .. "] " .. "SDL->HMI: SDL.OnStatusUpdate()" .. ": " .. exp.occurences .. ": " .. data.params.status)
if (exp.occurences == 1) and (data.params.status == "UPDATE_NEEDED") then
time_curr = timestamp()
local act_timeout = time_curr - time_prev
print("Timeout between retries: " .. act_timeout .. "ms")
if (act_timeout > exp_timeout + tolerance) or (act_timeout < exp_timeout - tolerance) then
self:FailTestCase("Timeout for retry sequence is not as expected: " .. exp_timeout .. "ms (" .. tolerance .. "ms tolerance)")
end
end
end)
:Times(2)
:Timeout(40000)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0)
self.mobileSession:ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }):Times(1)
commonTestCases:DelayedExp(40000)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Restore_files()
commonPreconditions:RestoreFile("sdl_preloaded_pt.json")
end
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
Fix retry sequence
|
Fix retry sequence
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
06e63ed65e70d382981abada5aba73e65c6ccd14
|
applications/luci-wol/luasrc/model/cbi/wol.lua
|
applications/luci-wol/luasrc/model/cbi/wol.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local uci = require "luci.model.uci".cursor()
local utl = require "luci.util"
local sys = require "luci.sys"
local fs = require "nixio.fs"
m = SimpleForm("wol", translate("Wake on LAN"),
translate("Wake on LAN is a mechanism to remotely boot computers in the local network."))
m.submit = translate("Wake up host")
m.reset = false
local has_ewk = fs.access("/usr/bin/etherwake")
local has_wol = fs.access("/usr/bin/wol")
s = m:section(SimpleSection)
local arp = { }
local e, ip, mac, name
if has_ewk and has_wol then
bin = s:option(ListValue, "binary", translate("WoL program"),
translate("Sometimes only one of both tools work. If one of fails, try the other one"))
bin:value("/usr/bin/etherwake", "Etherwake")
bin:value("/usr/bin/wol", "WoL")
end
if has_ewk then
iface = s:option(ListValue, "iface", translate("Network interface to use"),
translate("Specifies the interface the WoL packet is sent on"))
if has_wol then
iface:depends("binary", "/usr/bin/etherwake")
end
iface:value("", translate("Broadcast on all interfaces"))
for _, e in ipairs(sys.net.devices()) do
if e ~= "lo" then iface:value(e) end
end
end
for _, e in ipairs(sys.net.arptable()) do
arp[e["HW address"]:upper()] = { e["IP address"] }
end
for e in io.lines("/etc/ethers") do
mac, ip = e:match("^([a-f0-9]%S+) (%S+)")
if mac and ip then arp[mac:upper()] = { ip } end
end
for e in io.lines("/var/dhcp.leases") do
mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
if mac and ip then arp[mac:upper()] = { ip, name ~= "*" and name } end
end
uci:foreach("dhcp", "host",
function(s)
if s.mac and s.ip then
arp[s.mac:upper()] = { s.ip, s.name }
end
end)
host = s:option(Value, "mac", translate("Host to wake up"),
translate("Choose the host to wake up or enter a custom MAC address to use"))
for mac, ip in utl.kspairs(arp) do
host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] })
end
function host.write(self, s, val)
local host = luci.http.formvalue("cbid.wol.1.mac")
if host and #host > 0 then
local cmd
local util = luci.http.formvalue("cbid.wol.1.binary") or (
has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol"
)
if util == "/usr/bin/etherwake" then
local iface = luci.http.formvalue("cbid.wol.1.iface")
cmd = "%s -D%s %q" %{
util, (iface ~= "" and " -i %q" % iface or ""), host
}
else
cmd = "%s -v %q" %{ util, host }
end
local msg = "<p><strong>%s</strong><br /><br /><code>%s<br /><br />" %{
translate("Starting WoL utility:"), cmd
}
local p = io.popen(cmd .. " 2>&1")
if p then
while true do
local l = p:read("*l")
if l then
if #l > 100 then l = l:sub(1, 100) .. "..." end
msg = msg .. l .. "<br />"
else
break
end
end
p:close()
end
msg = msg .. "</code></p>"
m.message = msg
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local uci = require "luci.model.uci".cursor()
local utl = require "luci.util"
local sys = require "luci.sys"
local fs = require "nixio.fs"
m = SimpleForm("wol", translate("Wake on LAN"),
translate("Wake on LAN is a mechanism to remotely boot computers in the local network."))
m.submit = translate("Wake up host")
m.reset = false
local has_ewk = fs.access("/usr/bin/etherwake")
local has_wol = fs.access("/usr/bin/wol")
s = m:section(SimpleSection)
local arp = { }
local e, ip, mac, name
if has_ewk and has_wol then
bin = s:option(ListValue, "binary", translate("WoL program"),
translate("Sometimes only one of both tools work. If one of fails, try the other one"))
bin:value("/usr/bin/etherwake", "Etherwake")
bin:value("/usr/bin/wol", "WoL")
end
if has_ewk then
iface = s:option(ListValue, "iface", translate("Network interface to use"),
translate("Specifies the interface the WoL packet is sent on"))
if has_wol then
iface:depends("binary", "/usr/bin/etherwake")
end
iface:value("", translate("Broadcast on all interfaces"))
for _, e in ipairs(sys.net.devices()) do
if e ~= "lo" then iface:value(e) end
end
end
for _, e in ipairs(sys.net.arptable()) do
arp[e["HW address"]:upper()] = { e["IP address"] }
end
for e in io.lines("/etc/ethers") do
mac, ip = e:match("^([a-f0-9]%S+) (%S+)")
if mac and ip then arp[mac:upper()] = { ip } end
end
for e in io.lines("/var/dhcp.leases") do
mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
if mac and ip then arp[mac:upper()] = { ip, name ~= "*" and name } end
end
uci:foreach("dhcp", "host",
function(s)
if s.mac and s.ip then
arp[s.mac:upper()] = { s.ip, s.name }
end
end)
host = s:option(Value, "mac", translate("Host to wake up"),
translate("Choose the host to wake up or enter a custom MAC address to use"))
for mac, ip in utl.kspairs(arp) do
host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] })
end
function host.write(self, s, val)
local host = luci.http.formvalue("cbid.wol.1.mac")
if host and #host > 0 and host:match("^[a-fA-F0-9:]+$") then
local cmd
local util = luci.http.formvalue("cbid.wol.1.binary") or (
has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol"
)
if util == "/usr/bin/etherwake" then
local iface = luci.http.formvalue("cbid.wol.1.iface")
cmd = "%s -D%s %q" %{
util, (iface ~= "" and " -i %q" % iface or ""), host
}
else
cmd = "%s -v %q" %{ util, host }
end
local msg = "<p><strong>%s</strong><br /><br /><code>%s<br /><br />" %{
translate("Starting WoL utility:"), cmd
}
local p = io.popen(cmd .. " 2>&1")
if p then
while true do
local l = p:read("*l")
if l then
if #l > 100 then l = l:sub(1, 100) .. "..." end
msg = msg .. l .. "<br />"
else
break
end
end
p:close()
end
msg = msg .. "</code></p>"
m.message = msg
end
end
return m
|
applications/luci-wol: fix XSS
|
applications/luci-wol: fix XSS
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6545 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI
|
876d3b6debff62c479ccb0f8e59e3d7bfe28cfa7
|
RobotModel.lua
|
RobotModel.lua
|
local ffi = require 'ffi'
local torch = require 'torch'
local moveit = require 'moveit.env'
local utils = require 'moveit.utils'
local ros = require 'ros'
local std = ros.std
local RobotModel = torch.class('moveit.RobotModel', moveit)
local f
function init()
local RobotModel_method_names = {
"new",
"delete",
"release",
"getName",
"getModelFrame",
"isEmpty",
"printModelInfo",
"getRootJointName",
"getEndEffectorNames",
"getJointModelGroupNames"
}
f = utils.create_method_table("moveit_RobotModel_", RobotModel_method_names)
end
init()
function RobotModel:__init()
self.o = f.new()
end
function RobotModel:cdata()
return self.o
end
function RobotModel:release()
f.release(self.o)
end
function RobotModel:getName()
return ffi.string(f.getName(self.o))
end
function RobotModel:getModelFrame()
return ffi.string(f.getModelFrame(self.o))
end
function RobotModel:isEmpty()
return f.isEmpty(self.o)
end
function RobotModel:printModelInfo()
local s = std.String()
f.printModelInfo(self.o, s:cdata())
return s
end
function RobotModel:getRootJointName()
return ffi.string(f.getRootJointName(self.o))
end
function RobotModel:getEndEffectorNames(strings)
strings = strings or std.StringVector()
return f.getEndEffectorNames(self.o, strings:cdata())
end
function RobotModel:getJointModelGroupNames(strings)
strings = strings or std.StringVector()
return f.getJointModelGroupNames(self.o, strings:cdata())
end
|
local ffi = require 'ffi'
local torch = require 'torch'
local moveit = require 'moveit.env'
local utils = require 'moveit.utils'
local ros = require 'ros'
local std = ros.std
local RobotModel = torch.class('moveit.RobotModel', moveit)
local f
function init()
local RobotModel_method_names = {
"new",
"delete",
"release",
"getName",
"getModelFrame",
"isEmpty",
"printModelInfo",
"getRootJointName",
"getEndEffectorNames",
"getJointModelGroupNames"
}
f = utils.create_method_table("moveit_RobotModel_", RobotModel_method_names)
end
init()
function RobotModel:__init()
self.o = f.new()
end
function RobotModel:cdata()
return self.o
end
function RobotModel:release()
f.release(self.o)
end
function RobotModel:getName()
return ffi.string(f.getName(self.o))
end
function RobotModel:getModelFrame()
return ffi.string(f.getModelFrame(self.o))
end
function RobotModel:isEmpty()
return f.isEmpty(self.o)
end
function RobotModel:printModelInfo()
local s = std.String()
f.printModelInfo(self.o, s:cdata())
return s
end
function RobotModel:getRootJointName()
return ffi.string(f.getRootJointName(self.o))
end
function RobotModel:getEndEffectorNames(strings)
strings = strings or std.StringVector()
f.getEndEffectorNames(self.o, strings:cdata())
return strings
end
function RobotModel:getJointModelGroupNames(strings)
strings = strings or std.StringVector()
f.getJointModelGroupNames(self.o, strings:cdata())
return strings
end
|
bugfix
|
bugfix
|
Lua
|
bsd-3-clause
|
Xamla/torch-moveit
|
18173f070458106fe3c98a0e5f03f3b1a66ed754
|
modules/admin-full/luasrc/model/cbi/admin_system/ipkg.lua
|
modules/admin-full/luasrc/model/cbi/admin_system/ipkg.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local ipkgfile = "/etc/opkg.conf"
f = SimpleForm("ipkgconf", translate("a_s_p_ipkg"))
t = f:field(TextValue, "lines")
t.rows = 10
function t.cfgvalue()
return luci.fs.readfile(ipkgfile) or ""
end
f:append(Template("admin_system/ipkg"))
function f.handle(self, state, data)
if state == FORM_VALID then
if (luci.fs.readfile(ipkgfile) or "") ~= data.lines then
luci.fs.writefile(ipkgfile, data.lines)
end
end
return true
end
return f
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local ipkgfile = "/etc/opkg.conf"
f = SimpleForm("ipkgconf", translate("a_s_p_ipkg"))
t = f:field(TextValue, "lines")
t.rows = 10
function t.cfgvalue()
return luci.fs.readfile(ipkgfile) or ""
end
function t.write(self, section, data)
return luci.fs.writefile(ipkgfile, data)
end
f:append(Template("admin_system/ipkg"))
function f.handle(self, state, data)
return true
end
return f
|
Fix saving of ipkg configuration file
|
Fix saving of ipkg configuration file
|
Lua
|
apache-2.0
|
8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci
|
729519e7e948fc1f1daa914faebfa66bf3c3f19d
|
rootfs/usr/local/etc/haproxy/lua/auth-request.lua
|
rootfs/usr/local/etc/haproxy/lua/auth-request.lua
|
-- The MIT License (MIT)
--
-- Copyright (c) 2018 Tim Düsterhus
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
local http = require("socket.http")
--- Monkey Patches around bugs in haproxy's Socket class
-- This function calls core.tcp(), fixes a few methods and
-- returns the resulting socket.
-- @return Socket
function create_sock()
local sock = core.tcp()
-- https://www.mail-archive.com/[email protected]/msg28574.html
sock.old_receive = sock.receive
sock.receive = function(socket, pattern, prefix)
local a, b
if pattern == nil then pattern = "*l" end
if prefix == nil then
a, b = sock:old_receive(pattern)
else
a, b = sock:old_receive(pattern, prefix)
end
return a, b
end
-- https://www.mail-archive.com/[email protected]/msg28604.html
sock.old_settimeout = sock.settimeout
sock.settimeout = function(socket, timeout)
socket:old_settimeout(timeout)
return 1
end
return sock
end
core.register_action("auth-request", { "http-req" }, function(txn, be, path)
txn:set_var("txn.auth_response_successful", false)
-- Check whether the given backend exists.
if core.backends[be] == nil then
txn:Alert("Unknown auth-request backend '" .. be .. "'")
txn:set_var("txn.auth_response_code", 500)
return
end
-- Check whether the given backend has servers that
-- are not `DOWN`.
local addr = nil
for name, server in pairs(core.backends[be].servers) do
if server:get_stats()['status'] == "UP" then
addr = server:get_addr()
break
end
end
if addr == nil then
txn:Warning("No servers available for auth-request backend: '" .. be .. "'")
txn:set_var("txn.auth_response_code", 500)
return
end
-- Transform table of request headers from haproxy's to
-- socket.http's format.
local headers = {}
for header, values in pairs(txn.http:req_get_headers()) do
for i, v in pairs(values) do
if headers[header] == nil then
headers[header] = v
else
headers[header] = headers[header] .. ", " .. v
end
end
end
-- Make request to backend.
local b, c, h = http.request {
url = "http://" .. addr .. path,
headers = headers,
create = create_sock,
-- Disable redirects, because DNS does not work here.
redirect = false
}
-- Check whether we received a valid HTTP response.
if b == nil then
txn:Warning("Failure in auth-request backend '" .. be .. "': " .. c)
txn:set_var("txn.auth_response_code", 500)
return
end
-- 2xx: Allow request.
if 200 <= c and c < 300 then
txn:set_var("txn.auth_response_successful", true)
txn:set_var("txn.auth_response_code", c)
txn:set_var("txn.auth_response_email", h["x-auth-request-email"])
-- 401 / 403: Do not allow request.
elseif c == 401 or c == 403 then
txn:set_var("txn.auth_response_code", c)
-- Everything else: Do not allow request and log.
else
txn:Warning("Invalid status code in auth-request backend '" .. be .. "': " .. c)
txn:set_var("txn.auth_response_code", c)
end
end, 2)
|
-- The MIT License (MIT)
--
-- Copyright (c) 2018 Tim Düsterhus
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
local http = require("socket.http")
--- Monkey Patches around bugs in haproxy's Socket class
-- This function calls core.tcp(), fixes a few methods and
-- returns the resulting socket.
-- @return Socket
function create_sock()
local sock = core.tcp()
-- https://www.mail-archive.com/[email protected]/msg28574.html
sock.old_receive = sock.receive
sock.receive = function(socket, pattern, prefix)
local a, b
if pattern == nil then pattern = "*l" end
if prefix == nil then
a, b = sock:old_receive(pattern)
else
a, b = sock:old_receive(pattern, prefix)
end
return a, b
end
-- https://www.mail-archive.com/[email protected]/msg28604.html
sock.old_settimeout = sock.settimeout
sock.settimeout = function(socket, timeout)
socket:old_settimeout(timeout)
return 1
end
return sock
end
core.register_action("auth-request", { "http-req" }, function(txn, be, path)
txn:set_var("txn.auth_response_successful", false)
-- Check whether the given backend exists.
if core.backends[be] == nil then
txn:Alert("Unknown auth-request backend '" .. be .. "'")
txn:set_var("txn.auth_response_code", 500)
return
end
-- Check whether the given backend has servers that
-- are not `DOWN`.
local addr = nil
for name, server in pairs(core.backends[be].servers) do
local status = server:get_stats()['status']
if status == "no check" or status:find("UP") == 1 then
addr = server:get_addr()
break
end
end
if addr == nil then
txn:Warning("No servers available for auth-request backend: '" .. be .. "'")
txn:set_var("txn.auth_response_code", 500)
return
end
-- Transform table of request headers from haproxy's to
-- socket.http's format.
local headers = {}
for header, values in pairs(txn.http:req_get_headers()) do
for i, v in pairs(values) do
if headers[header] == nil then
headers[header] = v
else
headers[header] = headers[header] .. ", " .. v
end
end
end
-- Make request to backend.
local b, c, h = http.request {
url = "http://" .. addr .. path,
headers = headers,
create = create_sock,
-- Disable redirects, because DNS does not work here.
redirect = false
}
-- Check whether we received a valid HTTP response.
if b == nil then
txn:Warning("Failure in auth-request backend '" .. be .. "': " .. c)
txn:set_var("txn.auth_response_code", 500)
return
end
-- 2xx: Allow request.
if 200 <= c and c < 300 then
txn:set_var("txn.auth_response_successful", true)
txn:set_var("txn.auth_response_code", c)
txn:set_var("txn.auth_response_email", h["x-auth-request-email"])
-- 401 / 403: Do not allow request.
elseif c == 401 or c == 403 then
txn:set_var("txn.auth_response_code", c)
-- Everything else: Do not allow request and log.
else
txn:Warning("Invalid status code in auth-request backend '" .. be .. "': " .. c)
txn:set_var("txn.auth_response_code", c)
end
end, 2)
|
Fix status check of auth-request.lua
|
Fix status check of auth-request.lua
|
Lua
|
apache-2.0
|
jcmoraisjr/haproxy-ingress,jcmoraisjr/haproxy-ingress
|
8fd802a0117c43e949416df7abe429bfa196c5b6
|
src/server/base/Factory.lua
|
src/server/base/Factory.lua
|
--[[
Copyright (c) 2015 gameboxcloud.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
local Factory = class("Factory")
function Factory.create(config, classNamePrefix, ...)
local path = config.appRootPath .. "/?.lua;"
if not string.find(package.path, path, 1, true) then
package.path = path .. package.path
end
local ok, appConfig = pcall(require, "app_config")
if ok and type(appConfig) == "table" then
table.merge(config, appConfig)
end
local tagretClass
local ok, _tagretClass = pcall(require, classNamePrefix)
if ok then
tagretClass = _tagretClass
end
if not tagretClass then
tagretClass = require("server.base." .. classNamePrefix .. "Base")
end
return tagretClass:create(config, ...)
end
return Factory
|
--[[
Copyright (c) 2015 gameboxcloud.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
local Factory = class("Factory")
function Factory.create(config, classNamePrefix, ...)
local path = config.appRootPath .. "/?.lua;"
if not string.find(package.path, path, 1, true) then
package.path = path .. package.path
end
local ok, appConfig = pcall(require, "app_config")
if ok and type(appConfig) == "table" then
config = clone(config)
table.merge(config, appConfig)
end
local tagretClass
local ok, _tagretClass = pcall(require, classNamePrefix)
if ok then
tagretClass = _tagretClass
end
if not tagretClass then
tagretClass = require("server.base." .. classNamePrefix .. "Base")
end
return tagretClass:create(config, ...)
end
return Factory
|
fix app config
|
fix app config
|
Lua
|
mit
|
dualface/gbc-core,dualface/gbc-core,dualface/gbc-core,dualface/gbc-core
|
792b9fc52f872c668754ef0b0a7022b95fc4870f
|
gumbo/dom/Element.lua
|
gumbo/dom/Element.lua
|
local util = require "gumbo.dom.util"
local Buffer = require "gumbo.util".Buffer
local getters, setters = {}, {}
local Element = util.merge("Node", "ChildNode", {
type = "element",
nodeType = 1,
namespaceURI = "http://www.w3.org/1999/xhtml",
attributes = {}
})
function Element:__index(k)
if type(k) == "number" then
return self.childNodes[k]
end
local field = Element[k]
if field then
return field
else
local getter = getters[k]
if getter then
return getter(self)
end
end
end
function Element:__newindex(k, v)
local setter = setters[k]
if setter then
setter(self, v)
else
rawset(self, k, v)
end
end
function Element:getElementsByTagName(localName)
local collection = {} -- TODO: = setmetatable({}, HTMLCollection)
local length = 0
for node in self:walk() do
if node.type == "element" and node.localName == localName then
length = length + 1
collection[length] = node
end
end
collection.length = length
return collection
end
function Element:getAttribute(name)
if type(name) == "string" then
-- If the context object is in the HTML namespace and its node document
-- is an HTML document, let name be converted to ASCII lowercase.
if self.namespaceURI == "http://www.w3.org/1999/xhtml" then
name = name:lower()
end
-- Return the value of the first attribute in the context object's
-- attribute list whose name is name, and null otherwise.
local attr = self.attributes[name]
if attr then
return attr.value
end
end
end
function Element:hasAttribute(name)
return self:getAttribute(name) and true or false
end
function Element:hasAttributes()
return self.attributes[1] and true or false
end
function Element:cloneNode(deep)
if deep then error "NYI" end -- << TODO
local clone = {
localName = self.localName,
namespaceURI = self.namespaceURI,
prefix = self.prefix
}
if self:hasAttributes() then
local attrs = {}
for i, attr in ipairs(self.attributes) do
attrs[i] = {
name = attr.name,
value = attr.value,
prefix = attr.prefix
}
attrs[attr.name] = attrs[i]
end
clone.attributes = attrs
end
return setmetatable(clone, Element)
end
function getters:firstChild()
return self.childNodes[1]
end
function getters:lastChild()
local cnodes = self.childNodes
return cnodes[#cnodes]
end
-- TODO: implement all cases from http://www.w3.org/TR/dom/#dom-element-tagname
function getters:tagName()
if self.namespaceURI == "http://www.w3.org/1999/xhtml" then
return self.localName:upper()
else
return self.localName
end
end
function getters:classList()
local class = self.attributes.class
if class then
local list = {}
local length = 0
for s in class.value:gmatch "%S+" do
length = length + 1
list[length] = s
end
list.length = length
return list
end
end
-- TODO: Move to separate ParentNode module when inheritance system is fixed
function getters:children()
if self:hasChildNodes() then
local collection = {}
local length = 0
for i, node in ipairs(self.childNodes) do
if node.type == "element" then
length = length + 1
collection[length] = node
end
end
collection.length = length
return collection
end
end
local function Set(t)
local set = {}
for i = 1, #t do set[t[i]] = true end
return set
end
local void = Set {
"area", "base", "basefont", "bgsound", "br", "col", "embed",
"frame", "hr", "img", "input", "keygen", "link", "menuitem", "meta",
"param", "source", "track", "wbr"
}
local raw = Set {
"style", "script", "xmp", "iframe", "noembed", "noframes",
"plaintext"
}
local boolattr = Set {
"allowfullscreen", "async", "autofocus", "autoplay", "checked",
"compact", "controls", "declare", "default", "defer", "disabled",
"formnovalidate", "hidden", "inert", "ismap", "itemscope", "loop",
"multiple", "multiple", "muted", "nohref", "noresize", "noshade",
"novalidate", "nowrap", "open", "readonly", "required", "reversed",
"scoped", "seamless", "selected", "sortable", "truespeed",
"typemustmatch"
}
local escmap = {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """
}
local function escape_text(text)
return (text:gsub("[&<>]", escmap):gsub("\xC2\xA0", " "))
end
local function escape_attr(text)
return (text:gsub('[&"]', escmap):gsub("\xC2\xA0", " "))
end
function getters:innerHTML()
local buf = Buffer()
for node, level, index, length in self:walk() do
if node.type == "element" then
local tag = node.localName
buf:write("<", tag)
for i, attr in ipairs(node.attributes) do
local ns, name, val = attr.prefix, attr.name, attr.value
if ns and not (ns == "xmlns" and name == "xmlns") then
buf:write(" ", ns, ":", name)
else
buf:write(" ", name)
end
if not boolattr[name] or not (val == "" or val == name) then
buf:write('="', escape_attr(val), '"')
end
end
buf:write(">")
if node.childNodes.length == 0 and not void[tag] then
buf:write("</", tag, ">")
end
elseif node.type == "text" then
if raw[node.parentNode.localName] then
buf:write(node.data)
else
buf:write(escape_text(node.data))
end
elseif node.type == "whitespace" then
buf:write(node.data)
elseif node.type == "comment" then
buf:write("<!--", node.data, "-->")
end
if index == length and level > 1 then
buf:write("</", node.parentNode.localName, ">")
end
end
return tostring(buf)
end
local function attr_getter(name)
return function(self)
local attr = self.attributes[name]
if attr then return attr.value end
end
end
local function attr_setter(name)
return function(self, value)
local attributes = self.attributes
local attr = attributes[name]
if attr then
attr.value = value
else
attr = {name = name, value = value}
attributes[#attributes + 1] = attr
attributes[name] = attr
end
end
end
getters.nodeName = getters.tagName
getters.id = attr_getter("id")
setters.id = attr_setter("id")
getters.className = attr_getter("class")
setters.className = attr_setter("class")
return Element
|
local util = require "gumbo.dom.util"
local Buffer = require "gumbo.util".Buffer
local getters, setters = {}, {}
local Element = util.merge("Node", "ChildNode", {
type = "element",
nodeType = 1,
namespaceURI = "http://www.w3.org/1999/xhtml",
attributes = {}
})
function Element:__index(k)
if type(k) == "number" then
return self.childNodes[k]
end
local field = Element[k]
if field then
return field
else
local getter = getters[k]
if getter then
return getter(self)
end
end
end
function Element:__newindex(k, v)
local setter = setters[k]
if setter then
setter(self, v)
else
rawset(self, k, v)
end
end
function Element:getElementsByTagName(localName)
local collection = {} -- TODO: = setmetatable({}, HTMLCollection)
local length = 0
for node in self:walk() do
if node.type == "element" and node.localName == localName then
length = length + 1
collection[length] = node
end
end
collection.length = length
return collection
end
function Element:getAttribute(name)
if type(name) == "string" then
-- If the context object is in the HTML namespace and its node document
-- is an HTML document, let name be converted to ASCII lowercase.
if self.namespaceURI == "http://www.w3.org/1999/xhtml" then
name = name:lower()
end
-- Return the value of the first attribute in the context object's
-- attribute list whose name is name, and null otherwise.
local attr = self.attributes[name]
if attr then
return attr.value
end
end
end
function Element:hasAttribute(name)
return self:getAttribute(name) and true or false
end
function Element:hasAttributes()
return self.attributes[1] and true or false
end
function Element:cloneNode(deep)
if deep then error "NYI" end -- << TODO
local clone = {
localName = self.localName,
namespaceURI = self.namespaceURI,
prefix = self.prefix
}
if self:hasAttributes() then
local attrs = {}
for i, attr in ipairs(self.attributes) do
attrs[i] = {
name = attr.name,
value = attr.value,
prefix = attr.prefix
}
attrs[attr.name] = attrs[i]
end
clone.attributes = attrs
end
return setmetatable(clone, Element)
end
function getters:firstChild()
return self.childNodes[1]
end
function getters:lastChild()
local cnodes = self.childNodes
return cnodes[#cnodes]
end
-- TODO: implement all cases from http://www.w3.org/TR/dom/#dom-element-tagname
function getters:tagName()
if self.namespaceURI == "http://www.w3.org/1999/xhtml" then
return self.localName:upper()
else
return self.localName
end
end
function getters:classList()
local class = self.attributes.class
if class then
local list = {}
local length = 0
for s in class.value:gmatch "%S+" do
length = length + 1
list[length] = s
end
list.length = length
return list
end
end
-- TODO: Move to separate ParentNode module when inheritance system is fixed
function getters:children()
if self:hasChildNodes() then
local collection = {}
local length = 0
for i, node in ipairs(self.childNodes) do
if node.type == "element" then
length = length + 1
collection[length] = node
end
end
collection.length = length
return collection
end
end
local function Set(t)
local set = {}
for i = 1, #t do set[t[i]] = true end
return set
end
local void = Set {
"area", "base", "basefont", "bgsound", "br", "col", "embed",
"frame", "hr", "img", "input", "keygen", "link", "menuitem", "meta",
"param", "source", "track", "wbr"
}
local raw = Set {
"style", "script", "xmp", "iframe", "noembed", "noframes",
"plaintext"
}
local boolattr = Set {
"allowfullscreen", "async", "autofocus", "autoplay", "checked",
"compact", "controls", "declare", "default", "defer", "disabled",
"formnovalidate", "hidden", "inert", "ismap", "itemscope", "loop",
"multiple", "multiple", "muted", "nohref", "noresize", "noshade",
"novalidate", "nowrap", "open", "readonly", "required", "reversed",
"scoped", "seamless", "selected", "sortable", "truespeed",
"typemustmatch"
}
local escmap = {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """
}
local function escape_text(text)
return (text:gsub("[&<>]", escmap):gsub("\xC2\xA0", " "))
end
local function escape_attr(text)
return (text:gsub('[&"]', escmap):gsub("\xC2\xA0", " "))
end
-- FIXME: Logic for serializing closing tags is broken.
function getters:innerHTML()
local buf = Buffer()
for node, level, index, length in self:walk() do
if node.type == "element" then
local tag = node.localName
buf:write("<", tag)
for i, attr in ipairs(node.attributes) do
local ns, name, val = attr.prefix, attr.name, attr.value
if ns and not (ns == "xmlns" and name == "xmlns") then
buf:write(" ", ns, ":", name)
else
buf:write(" ", name)
end
if not boolattr[name] or not (val == "" or val == name) then
buf:write('="', escape_attr(val), '"')
end
end
buf:write(">")
if node.childNodes.length == 0 and not void[tag] then
buf:write("</", tag, ">")
end
elseif node.type == "text" then
if raw[node.parentNode.localName] then
buf:write(node.data)
else
buf:write(escape_text(node.data))
end
elseif node.type == "whitespace" then
buf:write(node.data)
elseif node.type == "comment" then
buf:write("<!--", node.data, "-->")
end
if index == length and level > 1 then
buf:write("</", node.parentNode.localName, ">")
end
end
return tostring(buf)
end
local function attr_getter(name)
return function(self)
local attr = self.attributes[name]
if attr then return attr.value end
end
end
local function attr_setter(name)
return function(self, value)
local attributes = self.attributes
local attr = attributes[name]
if attr then
attr.value = value
else
attr = {name = name, value = value}
attributes[#attributes + 1] = attr
attributes[name] = attr
end
end
end
getters.nodeName = getters.tagName
getters.id = attr_getter("id")
setters.id = attr_setter("id")
getters.className = attr_getter("class")
setters.className = attr_setter("class")
return Element
|
Add FIXME note for Element.innerHTML
|
Add FIXME note for Element.innerHTML
|
Lua
|
apache-2.0
|
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
|
bd8be73109f3835fb5248e540cc6ca8d34b644ac
|
himan-scripts/LVP.lua
|
himan-scripts/LVP.lua
|
logger:Info("Calculating LVP (Low Visibility Procedures) probability")
local Missing = missingf
local probLVP = {}
local producer = configuration:GetSourceProducer(0)
local ensSize = tonumber(radon:GetProducerMetaData(producer, "ensemble size"))
if not ensSize then
logger.Error("Ensemble size not found from database for producer " .. producer:GetId())
return
end
local ens1 = lagged_ensemble(param("VV2-M"), ensSize, time_duration(HPTimeResolution.kHourResolution, -6), 2)
local ens2 = lagged_ensemble(param("CL-2-FT"), ensSize, time_duration(HPTimeResolution.kHourResolution, -6), 2)
ens1:Fetch(configuration, current_time, current_level)
ens2:Fetch(configuration, current_time, current_level)
local lagEnsSize = ens1:Size()
ens1:ResetLocation()
ens2:ResetLocation()
local i = 0
while ens1:NextLocation() and ens2:NextLocation() do
i = i+1
local vals1 = ens1:Values()
local vals2 = ens2:Values()
local numLVP = 0
probLVP[i] = Missing
for j = 1, #vals1 do
local val1 = vals1[j]
local val2 = vals2[j]
if val1 < 600 or val2 <= 200 then
numLVP = numLVP + 1
end
end
probLVP[i] = numLVP / lagEnsSize
end
local probParam = param("PROB-LVP-1")
result:SetForecastType(forecast_type(HPForecastType.kStatisticalProcessing))
result:SetParam(probParam)
result:SetValues(probLVP)
luatool:WriteToFile(result)
|
logger:Info("Calculating LVP (Low Visibility Procedures) probability")
local Missing = missingf
local probLVP = {}
local producer = configuration:GetSourceProducer(0)
local ensSize = tonumber(radon:GetProducerMetaData(producer, "ensemble size"))
if not ensSize then
logger.Error("Ensemble size not found from database for producer " .. producer:GetId())
return
end
local ens1 = lagged_ensemble(param("VV2-M"), ensSize, time_duration(HPTimeResolution.kHourResolution, -1), 6)
local ens2 = lagged_ensemble(param("CL-2-FT"), ensSize, time_duration(HPTimeResolution.kHourResolution, -1), 6)
ens1:SetMaximumMissingForecasts(2500)
ens2:SetMaximumMissingForecasts(2500)
ens1:Fetch(configuration, current_time, current_level)
ens2:Fetch(configuration, current_time, current_level)
local lagEnsSize = ens1:Size()
ens1:ResetLocation()
ens2:ResetLocation()
local i = 0
while ens1:NextLocation() and ens2:NextLocation() do
i = i+1
local vals1 = ens1:Values()
local vals2 = ens2:Values()
local numLVP = 0
probLVP[i] = Missing
for j = 1, #vals1 do
local val1 = vals1[j]
local val2 = vals2[j]
if val1 < 600 or val2 <= 200 then
numLVP = numLVP + 1
end
end
probLVP[i] = numLVP / lagEnsSize
end
local probParam = param("PROB-LVP-1")
result:SetForecastType(forecast_type(HPForecastType.kStatisticalProcessing))
result:SetParam(probParam)
result:SetValues(probLVP)
luatool:WriteToFile(result)
|
Fix LVP to read MEPS-lagged forecasts
|
Fix LVP to read MEPS-lagged forecasts
|
Lua
|
mit
|
fmidev/himan,fmidev/himan,fmidev/himan
|
c1b4210ac294c3bb26840358980f66ad86bd8b3b
|
libs/web/luasrc/template.lua
|
libs/web/luasrc/template.lua
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.template", package.seeall)
require("luci.config")
require("luci.util")
require("luci.fs")
require("luci.http")
luci.config.template = luci.config.template or {}
viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
-- Enforce cache security
compiledir = compiledir .. "/" .. luci.sys.process.info("uid")
-- Compile modes:
-- none: Never compile, only use precompiled data from files
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = luci.config.template.compiler_mode or "memory"
-- Define the namespace for template modules
viewns = {
write = io.write,
include = function(name) Template(name):render(getfenv(2)) end,
}
-- Compiles a given template into an executable Lua module
function compile(template)
-- Search all <% %> expressions (remember: Lua table indexes begin with #1)
local function expr_add(command)
table.insert(expr, command)
return "<%" .. tostring(#expr) .. "%>"
end
-- As "expr" should be local, we have to assign it to the "expr_add" scope
local expr = {}
luci.util.extfenv(expr_add, "expr", expr)
-- Save all expressiosn to table "expr"
template = template:gsub("<%%(.-)%%>", expr_add)
local function sanitize(s)
s = luci.util.escape(s)
s = luci.util.escape(s, "'")
s = luci.util.escape(s, "\n")
return s
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = "write('"
local footer = "')"
template = header .. template .. footer
-- Replacements
local r_include = "')\ninclude('%s')\nwrite('"
local r_i18n = "'..translate('%1','%2')..'"
local r_pexec = "'..(%s or '')..'"
local r_exec = "')\n%s\nwrite('"
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
elseif p == "=" then
re = r_pexec:format(v:sub(2))
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
-- Oldstyle render shortcut
function render(name, scope, ...)
scope = scope or getfenv(2)
local s, t = pcall(Template, name)
if not s then
error(t)
else
t:render(scope, ...)
end
end
-- Template class
Template = luci.util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = {}
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
if self.cache[name] then
self.template = self.cache[name]
else
self.template = nil
end
-- Create a new namespace for this template
self.viewns = {}
-- Copy over from general namespace
for k, v in pairs(viewns) do
self.viewns[k] = v
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Compile and build
local sourcefile = viewdir .. "/" .. name .. ".htm"
local compiledfile = compiledir .. "/" .. luci.http.urlencode(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = luci.fs.mtime(sourcefile)
local commt = luci.fs.mtime(compiledfile)
if not luci.fs.mtime(compiledir) then
luci.fs.mkdir(compiledir, true)
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
luci.fs.writefile(compiledfile, luci.util.dump(compiled))
self.template = compiled
end
else
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "none" then
self.template, err = loadfile(self.compiledfile)
elseif compiler_mode == "memory" then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
luci.util.resfenv(self.template)
luci.util.updfenv(self.template, scope)
luci.util.updfenv(self.template, self.viewns)
-- Now finally render the thing
self.template()
-- Reset environment
setfenv(self.template, oldfenv)
end
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.template", package.seeall)
require("luci.config")
require("luci.util")
require("luci.fs")
require("luci.http")
luci.config.template = luci.config.template or {}
viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
-- Enforce cache security
compiledir = compiledir .. "/" .. luci.sys.process.info("uid")
-- Compile modes:
-- none: Never compile, only use precompiled data from files
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = luci.config.template.compiler_mode or "memory"
-- Define the namespace for template modules
viewns = {
write = io.write,
include = function(name) Template(name):render(getfenv(2)) end,
}
-- Compiles a given template into an executable Lua module
function compile(template)
-- Search all <% %> expressions (remember: Lua table indexes begin with #1)
local function expr_add(command)
table.insert(expr, command)
return "<%" .. tostring(#expr) .. "%>"
end
-- As "expr" should be local, we have to assign it to the "expr_add" scope
local expr = {}
luci.util.extfenv(expr_add, "expr", expr)
-- Save all expressiosn to table "expr"
template = template:gsub("<%%(.-)%%>", expr_add)
local function sanitize(s)
s = luci.util.escape(s)
s = luci.util.escape(s, "'")
s = luci.util.escape(s, "\n")
return s
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = "write('"
local footer = "')"
template = header .. template .. footer
-- Replacements
local r_include = "')\ninclude('%s')\nwrite('"
local r_i18n = "'..translate('%1','%2')..'"
local r_pexec = "'..(%s or '')..'"
local r_exec = "')\n%s\nwrite('"
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
elseif p == "=" then
re = r_pexec:format(v:sub(2))
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
-- Oldstyle render shortcut
function render(name, scope, ...)
scope = scope or getfenv(2)
local s, t = pcall(Template, name)
if not s then
error(t)
else
t:render(scope, ...)
end
end
-- Template class
Template = luci.util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = {}
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
if self.cache[name] then
self.template = self.cache[name]
else
self.template = nil
end
-- Create a new namespace for this template
self.viewns = {}
-- Copy over from general namespace
for k, v in pairs(viewns) do
self.viewns[k] = v
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Compile and build
local sourcefile = viewdir .. "/" .. name .. ".htm"
local compiledfile = compiledir .. "/" .. luci.http.urlencode(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = luci.fs.mtime(sourcefile)
local commt = luci.fs.mtime(compiledfile)
if not luci.fs.mtime(compiledir) then
luci.fs.mkdir(compiledir, true)
luci.fs.chmod(luci.fs.dirname(compiledir), "a+rxw")
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
luci.fs.writefile(compiledfile, luci.util.dump(compiled))
self.template = compiled
end
else
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "none" then
self.template, err = loadfile(self.compiledfile)
elseif compiler_mode == "memory" then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
luci.util.resfenv(self.template)
luci.util.updfenv(self.template, scope)
luci.util.updfenv(self.template, self.viewns)
-- Now finally render the thing
self.template()
-- Reset environment
setfenv(self.template, oldfenv)
end
|
* Fixed last commit
|
* Fixed last commit
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2308 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ThingMesh/openwrt-luci,saraedum/luci-packages-old,8devices/carambola2-luci,zwhfly/openwrt-luci,ch3n2k/luci,gwlim/luci,jschmidlapp/luci,phi-psi/luci,alxhh/piratenluci,ThingMesh/openwrt-luci,vhpham80/luci,jschmidlapp/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,jschmidlapp/luci,eugenesan/openwrt-luci,gwlim/luci,Flexibity/luci,phi-psi/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,ch3n2k/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,alxhh/piratenluci,jschmidlapp/luci,alxhh/piratenluci,eugenesan/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,stephank/luci,jschmidlapp/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,gwlim/luci,phi-psi/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,zwhfly/openwrt-luci,vhpham80/luci,jschmidlapp/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,freifunk-gluon/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,Flexibity/luci,vhpham80/luci,freifunk-gluon/luci,yeewang/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,saraedum/luci-packages-old,alxhh/piratenluci,Flexibity/luci,projectbismark/luci-bismark,freifunk-gluon/luci,Flexibity/luci,freifunk-gluon/luci,gwlim/luci,Flexibity/luci,saraedum/luci-packages-old,gwlim/luci,stephank/luci,alxhh/piratenluci,vhpham80/luci,yeewang/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,Canaan-Creative/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,ThingMesh/openwrt-luci,ch3n2k/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,stephank/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,vhpham80/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,alxhh/piratenluci,Canaan-Creative/luci,saraedum/luci-packages-old,ch3n2k/luci,8devices/carambola2-luci,freifunk-gluon/luci,8devices/carambola2-luci,Canaan-Creative/luci,phi-psi/luci,phi-psi/luci,ch3n2k/luci,stephank/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,gwlim/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,ch3n2k/luci,yeewang/openwrt-luci,stephank/luci
|
72f7f08c12462d59b94f36e01a5db5e51b1a04c9
|
lib/acid/unittest.lua
|
lib/acid/unittest.lua
|
local _M = { _VERSION='0.1' }
local function tostr(x)
return '[' .. tostring( x ) .. ']'
end
local function dd(...)
local args = {...}
local s = ''
for _, mes in ipairs(args) do
s = s .. tostring(mes)
end
_M.output( s )
end
function _M.output(s)
print( s )
end
local function is_test_file( fn )
return fn:sub( 1, 5 ) == 'test_' and fn:sub( -4, -1 ) == '.lua'
end
local function scandir(directory)
local t = {}
for filename in io.popen('ls "'..directory..'"'):lines() do
table.insert( t, filename )
end
return t
end
local function keys(tbl)
local n = 0
local ks = {}
for k, v in pairs( tbl ) do
table.insert( ks, k )
n = n + 1
end
table.sort( ks, function(a, b) return tostring(a)<tostring(b) end )
return ks, n
end
local testfuncs = {
ass= function (self, expr, expection, mes)
mes = mes or ''
local thisfile = debug.getinfo(1).short_src
local info
for i = 2, 10 do
info = debug.getinfo(i)
if info.short_src ~= thisfile then
break
end
end
local pos = 'Failure: \n'
pos = pos .. ' in ' .. info.short_src .. '\n'
pos = pos .. ' ' .. self._name .. '():' .. info.currentline .. '\n'
assert( expr, pos .. ' expect ' .. expection .. ' (' .. mes .. ')' )
self._suite.n_assert = self._suite.n_assert + 1
end,
eq= function( self, a, b, mes )
self:ass( a==b, 'to be ' .. tostr(a) .. ' but is ' .. tostr(b), mes )
end,
neq= function( self, a, b, mes )
self:ass( a~=b, 'not to be' .. tostr(a) .. ' but the same: ' .. tostr(b), mes )
end,
err= function ( self, func, mes )
local ok, rst = pcall( func )
self:eq( false, ok, mes )
end,
eqlist= function( self, a, b, mes )
self:neq( nil, a, "left list is not nil " .. (mes or '') )
self:neq( nil, b, "right list is not nil " .. (mes or '') )
for i, e in ipairs(a) do
self:ass( e==b[i], i .. 'th elt to be ' .. tostr(e) .. ' but is ' .. tostr(b[i]), mes )
end
-- check if b has more elements
for i, e in ipairs(b) do
self:ass( nil~=a[i], i .. 'th elt to be nil but is ' .. tostr(e), mes )
end
end,
eqdict= function( self, a, b, mes )
mes = mes or ''
if a == b then
return
end
self:neq( nil, a, "left table is not nil" .. mes )
self:neq( nil, b, "right table is not nil" .. mes )
local akeys, an = keys( a )
local bkeys, bn = keys( b )
for _, k in ipairs( akeys ) do
self:ass( b[k] ~= nil, '["' .. k .. '"] in right but not. '.. mes )
end
for _, k in ipairs( bkeys ) do
self:ass( a[k] ~= nil, '["' .. k .. '"] in left but not. '.. mes )
end
for _, k in ipairs( akeys ) do
local av, bv = a[k], b[k]
if type( av ) == 'table' and type( bv ) == 'table' then
self:eqdict( av, bv, k .. '<' .. mes )
else
self:ass( a[k] == b[k],
'["' .. k .. '"] to be ' .. tostr(a[k]) .. ' but is ' .. tostr(b[k]), mes )
end
end
end,
contain= function( self, a, b, mes )
self:neq( nil, a, "left table is not nil" )
self:neq( nil, b, "right table is not nil" )
for k, e in pairs(a) do
self:ass( e==b[k], '["' .. k .. '"] to be ' .. tostr(e) .. ' but is ' .. tostr(b[k]), mes )
end
end,
}
local _mt = { __index= testfuncs }
local function find_tests(tbl)
local tests = {}
for k, v in pairs(tbl) do
if k:sub( 1, 5 ) == 'test_' and type( v ) == 'function' then
tests[ k ] = v
end
end
return tests
end
function _M.test_one( suite, name, func )
dd( "* testing ", name, ' ...' )
local tfuncs = {}
setmetatable( tfuncs, _mt )
tfuncs._name = name
tfuncs._suite = suite
local co = coroutine.create( func )
local ok, rst = coroutine.resume( co, tfuncs )
if not ok then
dd( rst )
dd( debug.traceback(co) )
os.exit(1)
end
suite.n = suite.n + 1
end
function _M.testall( suite )
local names = {}
local tests = find_tests( _G )
for k, v in pairs(tests) do
table.insert( names, { k, v } )
end
table.sort( names, function(x, y) return x[ 1 ]<y[ 1 ] end )
for _, t in ipairs( names ) do
local funcname, func = t[ 1 ], t[ 2 ]
_M.test_one( suite, funcname, func )
end
end
function _M.testdir( dir )
package.path = package.path .. ';'..dir..'/?.lua'
local suite = { n=0, n_assert=0 }
local fns = scandir( dir )
for _, fn in ipairs(fns) do
if is_test_file( fn ) then
dd( "---- ", fn, ' ----' )
local tests0 = find_tests( _G )
require( fn:sub( 1, -5 ) )
local tests1 = find_tests( _G )
_M.testall( suite )
for k, v in pairs(tests1) do
if tests0[ k ] == nil then
_G[ k ] = nil
end
end
end
end
dd( suite.n, ' tests all passed. nr of assert: ', suite.n_assert )
return true
end
function _M.t()
if arg == nil then
-- lua -l unittest
_M.testdir( '.' )
os.exit()
else
-- require( "unittest" )
end
end
_M.t()
return _M
|
local _M = { _VERSION='0.1' }
local function tostr(x)
return '[' .. tostring( x ) .. ']'
end
local function dd(...)
local args = {...}
local s = ''
for _, mes in ipairs(args) do
s = s .. tostring(mes)
end
_M.output( s )
end
function _M.output(s)
print( s )
end
local function is_test_file( fn )
return fn:sub( 1, 5 ) == 'test_' and fn:sub( -4, -1 ) == '.lua'
end
local function scandir(directory)
local t = {}
for filename in io.popen('ls "'..directory..'"'):lines() do
table.insert( t, filename )
end
return t
end
local function keys(tbl)
local n = 0
local ks = {}
for k, v in pairs( tbl ) do
table.insert( ks, k )
n = n + 1
end
table.sort( ks, function(a, b) return tostring(a)<tostring(b) end )
return ks, n
end
local testfuncs = {
ass= function (self, expr, expection, mes)
mes = mes or ''
local thisfile = debug.getinfo(1).short_src
local info
for i = 2, 10 do
info = debug.getinfo(i)
if info.short_src ~= thisfile then
break
end
end
local pos = 'Failure: \n'
pos = pos .. ' in ' .. info.short_src .. '\n'
pos = pos .. ' ' .. self._name .. '():' .. info.currentline .. '\n'
assert( expr, pos .. ' expect ' .. expection .. ' (' .. mes .. ')' )
self._suite.n_assert = self._suite.n_assert + 1
end,
eq= function( self, a, b, mes )
self:ass( a==b, 'to be ' .. tostr(a) .. ' but is ' .. tostr(b), mes )
end,
neq= function( self, a, b, mes )
self:ass( a~=b, 'not to be' .. tostr(a) .. ' but the same: ' .. tostr(b), mes )
end,
err= function ( self, func, mes )
local ok, rst = pcall( func )
self:eq( false, ok, mes )
end,
eqlist= function( self, a, b, mes )
if a == b then
return
end
self:neq( nil, a, "left list is not nil " .. (mes or '') )
self:neq( nil, b, "right list is not nil " .. (mes or '') )
for i, e in ipairs(a) do
self:ass( e==b[i], i .. 'th elt to be ' .. tostr(e) .. ' but is ' .. tostr(b[i]), mes )
end
-- check if b has more elements
for i, e in ipairs(b) do
self:ass( nil~=a[i], i .. 'th elt to be nil but is ' .. tostr(e), mes )
end
end,
eqdict= function( self, a, b, mes )
mes = mes or ''
if a == b then
return
end
self:neq( nil, a, "left table is not nil " .. mes )
self:neq( nil, b, "right table is not nil " .. mes )
local akeys, an = keys( a )
local bkeys, bn = keys( b )
for _, k in ipairs( akeys ) do
self:ass( b[k] ~= nil, '["' .. k .. '"] in right but not. '.. mes )
end
for _, k in ipairs( bkeys ) do
self:ass( a[k] ~= nil, '["' .. k .. '"] in left but not. '.. mes )
end
for _, k in ipairs( akeys ) do
local av, bv = a[k], b[k]
if type( av ) == 'table' and type( bv ) == 'table' then
self:eqdict( av, bv, k .. '<' .. mes )
else
self:ass( a[k] == b[k],
'["' .. k .. '"] to be ' .. tostr(a[k]) .. ' but is ' .. tostr(b[k]), mes )
end
end
end,
contain= function( self, a, b, mes )
self:neq( nil, a, "left table is not nil" )
self:neq( nil, b, "right table is not nil" )
for k, e in pairs(a) do
self:ass( e==b[k], '["' .. k .. '"] to be ' .. tostr(e) .. ' but is ' .. tostr(b[k]), mes )
end
end,
}
local _mt = { __index= testfuncs }
local function find_tests(tbl)
local tests = {}
for k, v in pairs(tbl) do
if k:sub( 1, 5 ) == 'test_' and type( v ) == 'function' then
tests[ k ] = v
end
end
return tests
end
function _M.test_one( suite, name, func )
dd( "* testing ", name, ' ...' )
local tfuncs = {}
setmetatable( tfuncs, _mt )
tfuncs._name = name
tfuncs._suite = suite
local co = coroutine.create( func )
local ok, rst = coroutine.resume( co, tfuncs )
if not ok then
dd( rst )
dd( debug.traceback(co) )
os.exit(1)
end
suite.n = suite.n + 1
end
function _M.testall( suite )
local names = {}
local tests = find_tests( _G )
for k, v in pairs(tests) do
table.insert( names, { k, v } )
end
table.sort( names, function(x, y) return x[ 1 ]<y[ 1 ] end )
for _, t in ipairs( names ) do
local funcname, func = t[ 1 ], t[ 2 ]
_M.test_one( suite, funcname, func )
end
end
function _M.testdir( dir )
package.path = package.path .. ';'..dir..'/?.lua'
local suite = { n=0, n_assert=0 }
local fns = scandir( dir )
for _, fn in ipairs(fns) do
if is_test_file( fn ) then
dd( "---- ", fn, ' ----' )
local tests0 = find_tests( _G )
require( fn:sub( 1, -5 ) )
local tests1 = find_tests( _G )
_M.testall( suite )
for k, v in pairs(tests1) do
if tests0[ k ] == nil then
_G[ k ] = nil
end
end
end
end
dd( suite.n, ' tests all passed. nr of assert: ', suite.n_assert )
return true
end
function _M.t()
if arg == nil then
-- lua -l unittest
_M.testdir( '.' )
os.exit()
else
-- require( "unittest" )
end
end
_M.t()
return _M
|
fix unittest: eqdict add space between expectation and mes
|
fix unittest: eqdict add space between expectation and mes
|
Lua
|
mit
|
baishancloud/lua-acid,baishancloud/lua-acid,baishancloud/lua-acid
|
7d029bc05976bd2fff513b160e2c6e4fc8ce3b42
|
modules/goodreads.lua
|
modules/goodreads.lua
|
local simplehttp = require'simplehttp'
local urlEncode = function(str)
return str:gsub(
'([^%w ])',
function (c)
return string.format ("%%%02X", string.byte(c))
end
):gsub(' ', '+')
end
local blacklistedShelves = {
['series'] = true,
['to-read'] = true,
['favourites'] = true,
['favorites'] = true,
}
local lookup = function(self, source, destination, id)
simplehttp(
string.format(
"https://www.goodreads.com/book/show/%s?format=xml&key=%s",
id,
self.config.goodreadsAPIKey
),
function(data)
if(data:find("Could not find this book.", 1, true)) then
return self:Msg('privmsg', destination, source, "Found no book with that id.")
end
local id = data:match("<id>([^>]+)</id>")
local avgRating = data:match("<average_rating>([^>]+)</average_rating>")
local work = data:match("<work>(.*)</work>")
local day = work:match("<original_publication_day[^>]+>([^<]+)</original_publication_day>")
local month = work:match("<original_publication_month[^>]+>([^<]+)</original_publication_month>")
local year = work:match("<original_publication_year[^>]+>([^<]+)</original_publication_year>")
local title = work:match("original_title>([^<]+)</original_title>")
local date = string.format("%02d/%02d/%d", day, month, year)
local authors = {}
for author in data:match("<authors>(.-)</authors>"):gmatch("<author>(.-)</author>") do
local name = author:match("<name>([^<]+)</name>")
table.insert(authors, name)
end
local genres = {}
for shelf in data:match("<popular_shelves>(.-)</popular_shelves>"):gmatch('<shelf name="([^"]+)"') do
if(not blacklistedShelves[shelf]) then
table.insert(genres, shelf)
end
end
local out = {}
if(title) then
table.insert(out, string.format("\002%s\002", title))
end
if(#authors > 0) then
table.insert(out, string.format("by %s", table.concat(authors, ", ")))
end
if(date) then
table.insert(out, string.format("(%s)", date))
end
if(avgRating) then
table.insert(out, string.format("\002Rating:\002 %s", avgRating))
end
if(#genres > 0) then
table.insert(out, string.format("// %s", table.concat(genres, ", ")))
end
if(id) then
table.insert(out, string.format("| https://www.goodreads.com/book/show/%s", id))
end
self:Msg('privmsg', destination, source, table.concat(out, " "))
end,
true,
2^16
)
end
local search = function(self, source, destination, title)
simplehttp(
string.format(
"https://www.goodreads.com/search.xml?key=%s&q=%s",
self.config.goodreadsAPIKey,
urlEncode(title)
),
function(data)
local books = {}
for work in data:gmatch("<work>(.-)</work>") do
local book = work:match("<best_book[^>]+>(.*)</best_book>")
local id = book:match("<id[^>]+>([^<]+)</id>")
local title = book:match("<title>([^<]+)</title>"):gsub(" %(.*, #%d+%)$", "")
local author = book:match("<name>([^<]+)</name>"):gsub('(%u)%S* %l*%s*', '%1. ')
table.insert(books, {
id = id,
title = title,
author = author,
})
end
local out = {}
for i=1, #books do
local book = books[i]
table.insert(out, string.format("\002[%s]\002 %s by %s", book.id, book.title, book.author))
end
self:Msg(
'privmsg', destination, source,
table.concat(self:LimitOutput(destination, out, 1), ' ')
)
return books
end,
true,
2^16
)
end
return {
PRIVMSG = {
['!gr (.*)$'] = function(self, source, destination, input)
if(tonumber(input)) then
lookup(self, source, destination, input)
else
search(self, source, destination,input)
end
end,
},
}
|
local simplehttp = require'simplehttp'
local urlEncode = function(str)
return str:gsub(
'([^%w ])',
function (c)
return string.format ("%%%02X", string.byte(c))
end
):gsub(' ', '+')
end
local blacklistedShelves = {
['series'] = true,
['to-read'] = true,
['favourites'] = true,
['favorites'] = true,
}
local lookup = function(self, source, destination, id)
simplehttp(
string.format(
"https://www.goodreads.com/book/show/%s?format=xml&key=%s",
id,
self.config.goodreadsAPIKey
),
function(data)
if(data:find("Could not find this book.", 1, true)) then
return self:Msg('privmsg', destination, source, "Found no book with that id.")
end
local id = data:match("<id>([^>]+)</id>")
local avgRating = data:match("<average_rating>([^>]+)</average_rating>")
local work = data:match("<work>(.*)</work>")
local day = work:match("<original_publication_day[^>]+>([^<]+)</original_publication_day>")
local month = work:match("<original_publication_month[^>]+>([^<]+)</original_publication_month>")
local year = work:match("<original_publication_year[^>]+>([^<]+)</original_publication_year>")
local title = work:match("original_title>([^<]+)</original_title>")
local date = {}
if(day) then
table.insert(date, string.format("%02d", day))
end
if(month) then
table.insert(date, string.format("%02d", month))
end
if(year) then
table.insert(date, year)
end
date = table.concat(date, "/")
local authors = {}
for author in data:match("<authors>(.-)</authors>"):gmatch("<author>(.-)</author>") do
local name = author:match("<name>([^<]+)</name>")
table.insert(authors, name)
end
local genres = {}
for shelf in data:match("<popular_shelves>(.-)</popular_shelves>"):gmatch('<shelf name="([^"]+)"') do
if(not blacklistedShelves[shelf]) then
table.insert(genres, shelf)
end
end
local out = {}
if(title) then
table.insert(out, string.format("\002%s\002", title))
end
if(#authors > 0) then
table.insert(out, string.format("by %s", table.concat(authors, ", ")))
end
if(date) then
table.insert(out, string.format("(%s)", date))
end
if(avgRating) then
table.insert(out, string.format("\002Rating:\002 %s", avgRating))
end
if(#genres > 0) then
table.insert(out, string.format("// %s", table.concat(genres, ", ")))
end
if(id) then
table.insert(out, string.format("| https://www.goodreads.com/book/show/%s", id))
end
self:Msg('privmsg', destination, source, table.concat(out, " "))
end,
true,
2^16
)
end
local search = function(self, source, destination, title)
simplehttp(
string.format(
"https://www.goodreads.com/search.xml?key=%s&q=%s",
self.config.goodreadsAPIKey,
urlEncode(title)
),
function(data)
local books = {}
for work in data:gmatch("<work>(.-)</work>") do
local book = work:match("<best_book[^>]+>(.*)</best_book>")
local id = book:match("<id[^>]+>([^<]+)</id>")
local title = book:match("<title>([^<]+)</title>"):gsub(" %(.*, #%d+%)$", "")
local author = book:match("<name>([^<]+)</name>"):gsub('(%u)%S* %l*%s*', '%1. ')
table.insert(books, {
id = id,
title = title,
author = author,
})
end
local out = {}
for i=1, #books do
local book = books[i]
table.insert(out, string.format("\002[%s]\002 %s by %s", book.id, book.title, book.author))
end
self:Msg(
'privmsg', destination, source,
table.concat(self:LimitOutput(destination, out, 1), ' ')
)
return books
end,
true,
2^16
)
end
return {
PRIVMSG = {
['!gr (.*)$'] = function(self, source, destination, input)
if(tonumber(input)) then
lookup(self, source, destination, input)
else
search(self, source, destination,input)
end
end,
},
}
|
goodreads: Fix date output.
|
goodreads: Fix date output.
Former-commit-id: 2dfb51d4db3b9f99d20f5a20977c7056517caf29 [formerly 02e9f45536ec151ba477bc335387828643709b8e]
Former-commit-id: b4724a96028b6ca167be9ceb343190e52c4f0884
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
|
d4aa44310c52465dace1fc2c9e39676525141ab2
|
SpatialBatchNormalization.lua
|
SpatialBatchNormalization.lua
|
--[[
This file implements Batch Normalization as described in the paper:
"Batch Normalization: Accelerating Deep Network Training
by Reducing Internal Covariate Shift"
by Sergey Ioffe, Christian Szegedy
This implementation is useful for inputs coming from convolution layers.
For Non-convolutional layers, see BatchNormalization.lua
The operation implemented is:
y = ( x - mean(x) )
-------------------- * gamma + beta
standard-deviation(x)
where gamma and beta are learnable parameters.
The learning of gamma and beta is optional.
Usage:
with learnable parameters: nn.BatchNormalization(N [,eps] [,momentum])
where N = dimensionality of input
without learnable parameters: nn.BatchNormalization(N [,eps] [,momentum], false)
eps is a small value added to the variance to avoid divide-by-zero.
Defaults to 1e-5
In training time, this layer keeps a running estimate of it's computed mean and std.
The running sum is kept with a default momentup of 0.1 (unless over-ridden)
In test time, this running mean/std is used to normalize.
]]--
local BN,parent = torch.class('nn.SpatialBatchNormalization', 'nn.Module')
BN.__version = 2
function BN:__init(nFeature, eps, momentum, affine)
parent.__init(self)
assert(nFeature and type(nFeature) == 'number',
'Missing argument #1: Number of feature planes. ')
assert(nFeature ~= 0, 'To set affine=false call SpatialBatchNormalization'
.. '(nFeature, eps, momentum, false) ')
if affine ~= nil then
assert(type(affine) == 'boolean', 'affine has to be true/false')
self.affine = affine
else
self.affine = true
end
self.eps = eps or 1e-5
self.train = true
self.momentum = momentum or 0.1
self.running_mean = torch.zeros(nFeature)
self.running_var = torch.ones(nFeature)
if self.affine then
self.weight = torch.Tensor(nFeature)
self.bias = torch.Tensor(nFeature)
self.gradWeight = torch.Tensor(nFeature)
self.gradBias = torch.Tensor(nFeature)
self:reset()
end
end
function BN:reset()
if self.weight then
self.weight:uniform()
end
if self.bias then
self.bias:zero()
end
end
function BN:updateOutput(input)
assert(input:dim() == 4, 'only mini-batch supported (4D tensor), got '
.. input:dim() .. 'D tensor instead')
self.output:resizeAs(input)
self.save_mean = self.save_mean or input.new():resizeAs(self.running_mean)
self.save_std = self.save_std or input.new():resizeAs(self.running_var)
input.nn.SpatialBatchNormalization_updateOutput(
input,
self.output,
self.weight,
self.bias,
self.train,
self.eps,
self.momentum,
self.running_mean,
self.running_var,
self.save_mean,
self.save_std)
return self.output
end
local function backward(self, input, gradOutput, scale, gradInput, gradWeight, gradBias)
assert(input:dim() == 4, 'only mini-batch supported')
assert(gradOutput:dim() == 4, 'only mini-batch supported')
assert(self.train == true, 'should be in training mode when self.train is true')
assert(self.save_mean and self.save_std, 'must call :updateOutput() first')
scale = scale or 1
if gradInput then
gradInput:resizeAs(gradOutput)
end
input.nn.SpatialBatchNormalization_backward(
input,
gradOutput,
gradInput,
gradWeight,
gradBias,
self.weight,
self.save_mean,
self.save_std,
scale)
return self.gradInput
end
function BN:backward(input, gradOutput, scale)
return backward(self, input, gradOutput, scale, self.gradInput, self.gradWeight, self.gradBias)
end
function BN:updateGradInput(input, gradOutput)
return backward(self, input, gradOutput, 1, self.gradInput)
end
function BN:accGradParameters(input, gradOutput, scale)
return backward(self, input, gradOutput, scale, nil, self.gradWeight, self.gradBias)
end
function BN:read(file, version)
local var = file:readObject()
for k,v in pairs(var) do
if version < 2 and k == 'running_std' then
k = 'running_var'
v = v:cmul(v):pow(-1)
end
self[k] = v
end
end
|
--[[
This file implements Batch Normalization as described in the paper:
"Batch Normalization: Accelerating Deep Network Training
by Reducing Internal Covariate Shift"
by Sergey Ioffe, Christian Szegedy
This implementation is useful for inputs coming from convolution layers.
For Non-convolutional layers, see BatchNormalization.lua
The operation implemented is:
y = ( x - mean(x) )
-------------------- * gamma + beta
standard-deviation(x)
where gamma and beta are learnable parameters.
The learning of gamma and beta is optional.
Usage:
with learnable parameters: nn.BatchNormalization(N [,eps] [,momentum])
where N = dimensionality of input
without learnable parameters: nn.BatchNormalization(N [,eps] [,momentum], false)
eps is a small value added to the variance to avoid divide-by-zero.
Defaults to 1e-5
In training time, this layer keeps a running estimate of it's computed mean and std.
The running sum is kept with a default momentup of 0.1 (unless over-ridden)
In test time, this running mean/std is used to normalize.
]]--
local BN,parent = torch.class('nn.SpatialBatchNormalization', 'nn.Module')
BN.__version = 2
function BN:__init(nFeature, eps, momentum, affine)
parent.__init(self)
assert(nFeature and type(nFeature) == 'number',
'Missing argument #1: Number of feature planes. ')
assert(nFeature ~= 0, 'To set affine=false call SpatialBatchNormalization'
.. '(nFeature, eps, momentum, false) ')
if affine ~= nil then
assert(type(affine) == 'boolean', 'affine has to be true/false')
self.affine = affine
else
self.affine = true
end
self.eps = eps or 1e-5
self.train = true
self.momentum = momentum or 0.1
self.running_mean = torch.zeros(nFeature)
self.running_var = torch.ones(nFeature)
if self.affine then
self.weight = torch.Tensor(nFeature)
self.bias = torch.Tensor(nFeature)
self.gradWeight = torch.Tensor(nFeature)
self.gradBias = torch.Tensor(nFeature)
self:reset()
end
end
function BN:reset()
if self.weight then
self.weight:uniform()
end
if self.bias then
self.bias:zero()
end
self.running_mean:zero()
self.running_var:fill(1)
end
function BN:updateOutput(input)
assert(input:dim() == 4, 'only mini-batch supported (4D tensor), got '
.. input:dim() .. 'D tensor instead')
self.output:resizeAs(input)
self.save_mean = self.save_mean or input.new():resizeAs(self.running_mean)
self.save_std = self.save_std or input.new():resizeAs(self.running_var)
input.nn.SpatialBatchNormalization_updateOutput(
input,
self.output,
self.weight,
self.bias,
self.train,
self.eps,
self.momentum,
self.running_mean,
self.running_var,
self.save_mean,
self.save_std)
return self.output
end
local function backward(self, input, gradOutput, scale, gradInput, gradWeight, gradBias)
assert(input:dim() == 4, 'only mini-batch supported')
assert(gradOutput:dim() == 4, 'only mini-batch supported')
assert(self.train == true, 'should be in training mode when self.train is true')
assert(self.save_mean and self.save_std, 'must call :updateOutput() first')
scale = scale or 1
if gradInput then
gradInput:resizeAs(gradOutput)
end
input.nn.SpatialBatchNormalization_backward(
input,
gradOutput,
gradInput,
gradWeight,
gradBias,
self.weight,
self.save_mean,
self.save_std,
scale)
return self.gradInput
end
function BN:backward(input, gradOutput, scale)
return backward(self, input, gradOutput, scale, self.gradInput, self.gradWeight, self.gradBias)
end
function BN:updateGradInput(input, gradOutput)
return backward(self, input, gradOutput, 1, self.gradInput)
end
function BN:accGradParameters(input, gradOutput, scale)
return backward(self, input, gradOutput, scale, nil, self.gradWeight, self.gradBias)
end
function BN:read(file, version)
local var = file:readObject()
for k,v in pairs(var) do
if version < 2 and k == 'running_std' then
k = 'running_var'
v = v:cmul(v):pow(-1)
end
self[k] = v
end
end
|
fix batchnorm reset
|
fix batchnorm reset
|
Lua
|
bsd-3-clause
|
nicholas-leonard/nn,sagarwaghmare69/nn,jonathantompson/nn,kmul00/nn,diz-vara/nn,PraveerSINGH/nn,apaszke/nn,elbamos/nn,eriche2016/nn,joeyhng/nn,andreaskoepf/nn,colesbury/nn,caldweln/nn,jhjin/nn,xianjiec/nn
|
1e2d9409a5d6799a8a60929e2ee6a2906cb7705c
|
modules/admin-full/luasrc/controller/admin/uci.lua
|
modules/admin-full/luasrc/controller/admin/uci.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.admin.uci", package.seeall)
function index()
local i18n = luci.i18n.translate
entry({"admin", "uci"}, nil, i18n("config"))
entry({"admin", "uci", "changes"}, call("action_changes"), i18n("changes"), 40)
entry({"admin", "uci", "revert"}, call("action_revert"), i18n("revert"), 30)
entry({"admin", "uci", "apply"}, call("action_apply"), i18n("apply"), 20)
entry({"admin", "uci", "saveapply"}, call("action_apply"), i18n("saveapply"), 10)
end
function convert_changes(changes)
local ret = {}
for r, tbl in pairs(changes) do
for s, os in pairs(tbl) do
for o, v in pairs(os) do
local val, str
if (v == "") then
str = "-"
val = ""
else
str = ""
val = "="..luci.util.pcdata(v)
end
str = r.."."..s
if o ~= ".type" then
str = str.."."..o
end
table.insert(ret, str..val)
end
end
end
return table.concat(ret, "\n")
end
function action_changes()
local changes = convert_changes(luci.model.uci.cursor():changes())
luci.template.render("admin_uci/changes", {changes=changes})
end
function action_apply()
local path = luci.dispatcher.context.path
local changes = luci.model.uci.changes()
local output = ""
local uci = luci.model.uci.cursor()
if changes then
local com = {}
local run = {}
-- Collect files to be applied and commit changes
for r, tbl in pairs(changes) do
if r then
if path[#path] ~= "apply" then
uci:load(r)
uci:commit(r)
uci:unload(r)
end
if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then
run[luci.config.uci_oncommit[r]] = true
end
end
end
-- Search for post-commit commands
for cmd, i in pairs(run) do
output = output .. cmd .. ":" .. luci.util.exec(cmd) .. "\n"
end
end
luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output})
end
function action_revert()
local uci = luci.model.uci.cursor()
local changes = uci:changes()
if changes then
local revert = {}
-- Collect files to be reverted
for r, tbl in pairs(changes) do
uci:load(r)
uci:revert(r)
uci:unload(r)
end
end
luci.template.render("admin_uci/revert", {changes=convert_changes(changes)})
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.admin.uci", package.seeall)
function index()
local i18n = luci.i18n.translate
entry({"admin", "uci"}, nil, i18n("config"))
entry({"admin", "uci", "changes"}, call("action_changes"), i18n("changes"), 40)
entry({"admin", "uci", "revert"}, call("action_revert"), i18n("revert"), 30)
entry({"admin", "uci", "apply"}, call("action_apply"), i18n("apply"), 20)
entry({"admin", "uci", "saveapply"}, call("action_apply"), i18n("saveapply"), 10)
end
function convert_changes(changes)
local ret = {}
for r, tbl in pairs(changes) do
for s, os in pairs(tbl) do
for o, v in pairs(os) do
local val, str
if (v == "") then
str = "-"
val = ""
else
str = ""
val = "="..luci.util.pcdata(v)
end
str = r.."."..s
if o ~= ".type" then
str = str.."."..o
end
table.insert(ret, str..val)
end
end
end
return table.concat(ret, "\n")
end
function action_changes()
local changes = convert_changes(luci.model.uci.cursor():changes())
luci.template.render("admin_uci/changes", {changes=changes})
end
function action_apply()
local path = luci.dispatcher.context.path
local output = ""
local uci = luci.model.uci.cursor()
local changes = uci:changes()
if changes then
local com = {}
local run = {}
-- Collect files to be applied and commit changes
for r, tbl in pairs(changes) do
if r then
if path[#path] ~= "apply" then
uci:load(r)
uci:commit(r)
uci:unload(r)
end
if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then
run[luci.config.uci_oncommit[r]] = true
end
end
end
-- Search for post-commit commands
for cmd, i in pairs(run) do
output = output .. cmd .. ":" .. luci.util.exec(cmd) .. "\n"
end
end
luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output})
end
function action_revert()
local uci = luci.model.uci.cursor()
local changes = uci:changes()
if changes then
local revert = {}
-- Collect files to be reverted
for r, tbl in pairs(changes) do
uci:load(r)
uci:revert(r)
uci:unload(r)
end
end
luci.template.render("admin_uci/revert", {changes=convert_changes(changes)})
end
|
Fix missing UCI transition
|
Fix missing UCI transition
|
Lua
|
apache-2.0
|
aircross/OpenWrt-Firefly-LuCI,bittorf/luci,tcatm/luci,ollie27/openwrt_luci,jorgifumi/luci,fkooman/luci,opentechinstitute/luci,shangjiyu/luci-with-extra,maxrio/luci981213,thesabbir/luci,MinFu/luci,Hostle/openwrt-luci-multi-user,wongsyrone/luci-1,RuiChen1113/luci,artynet/luci,981213/luci-1,palmettos/cnLuCI,shangjiyu/luci-with-extra,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,ollie27/openwrt_luci,kuoruan/lede-luci,chris5560/openwrt-luci,LuttyYang/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,david-xiao/luci,remakeelectric/luci,mumuqz/luci,taiha/luci,lbthomsen/openwrt-luci,openwrt/luci,palmettos/cnLuCI,openwrt/luci,forward619/luci,RuiChen1113/luci,LuttyYang/luci,harveyhu2012/luci,palmettos/test,ReclaimYourPrivacy/cloak-luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,fkooman/luci,ff94315/luci-1,tobiaswaldvogel/luci,artynet/luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,nwf/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,teslamint/luci,ff94315/luci-1,sujeet14108/luci,maxrio/luci981213,marcel-sch/luci,fkooman/luci,remakeelectric/luci,aa65535/luci,urueedi/luci,bright-things/ionic-luci,wongsyrone/luci-1,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,chris5560/openwrt-luci,RuiChen1113/luci,urueedi/luci,sujeet14108/luci,marcel-sch/luci,taiha/luci,kuoruan/lede-luci,daofeng2015/luci,artynet/luci,palmettos/test,ollie27/openwrt_luci,cappiewu/luci,Wedmer/luci,cshore/luci,daofeng2015/luci,sujeet14108/luci,ff94315/luci-1,wongsyrone/luci-1,palmettos/test,david-xiao/luci,rogerpueyo/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,palmettos/test,daofeng2015/luci,chris5560/openwrt-luci,forward619/luci,bright-things/ionic-luci,bright-things/ionic-luci,Wedmer/luci,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,981213/luci-1,joaofvieira/luci,LuttyYang/luci,Kyklas/luci-proto-hso,joaofvieira/luci,harveyhu2012/luci,jchuang1977/luci-1,kuoruan/lede-luci,daofeng2015/luci,daofeng2015/luci,remakeelectric/luci,marcel-sch/luci,kuoruan/lede-luci,NeoRaider/luci,oyido/luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,fkooman/luci,openwrt/luci,RuiChen1113/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,chris5560/openwrt-luci,slayerrensky/luci,daofeng2015/luci,zhaoxx063/luci,male-puppies/luci,david-xiao/luci,RuiChen1113/luci,Kyklas/luci-proto-hso,bittorf/luci,thess/OpenWrt-luci,ff94315/luci-1,thess/OpenWrt-luci,florian-shellfire/luci,taiha/luci,joaofvieira/luci,Noltari/luci,ff94315/luci-1,sujeet14108/luci,ollie27/openwrt_luci,mumuqz/luci,db260179/openwrt-bpi-r1-luci,marcel-sch/luci,aa65535/luci,schidler/ionic-luci,obsy/luci,florian-shellfire/luci,openwrt-es/openwrt-luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,daofeng2015/luci,mumuqz/luci,palmettos/test,nwf/openwrt-luci,obsy/luci,joaofvieira/luci,cshore-firmware/openwrt-luci,cshore/luci,kuoruan/luci,florian-shellfire/luci,thesabbir/luci,mumuqz/luci,tcatm/luci,jlopenwrtluci/luci,hnyman/luci,nwf/openwrt-luci,urueedi/luci,ff94315/luci-1,chris5560/openwrt-luci,981213/luci-1,oyido/luci,aa65535/luci,NeoRaider/luci,shangjiyu/luci-with-extra,tcatm/luci,nwf/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,forward619/luci,thesabbir/luci,urueedi/luci,zhaoxx063/luci,artynet/luci,NeoRaider/luci,bright-things/ionic-luci,remakeelectric/luci,thess/OpenWrt-luci,oyido/luci,opentechinstitute/luci,ff94315/luci-1,zhaoxx063/luci,Noltari/luci,thesabbir/luci,cappiewu/luci,jorgifumi/luci,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,fkooman/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,keyidadi/luci,nmav/luci,hnyman/luci,RedSnake64/openwrt-luci-packages,schidler/ionic-luci,tobiaswaldvogel/luci,cappiewu/luci,oneru/luci,forward619/luci,obsy/luci,aircross/OpenWrt-Firefly-LuCI,david-xiao/luci,nmav/luci,keyidadi/luci,tcatm/luci,tcatm/luci,male-puppies/luci,deepak78/new-luci,Noltari/luci,artynet/luci,nmav/luci,hnyman/luci,dismantl/luci-0.12,jlopenwrtluci/luci,shangjiyu/luci-with-extra,deepak78/new-luci,Hostle/luci,dwmw2/luci,LuttyYang/luci,openwrt/luci,nmav/luci,zhaoxx063/luci,tobiaswaldvogel/luci,NeoRaider/luci,schidler/ionic-luci,kuoruan/lede-luci,slayerrensky/luci,db260179/openwrt-bpi-r1-luci,artynet/luci,dismantl/luci-0.12,cshore/luci,jorgifumi/luci,cappiewu/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,schidler/ionic-luci,male-puppies/luci,dwmw2/luci,bittorf/luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,hnyman/luci,teslamint/luci,nwf/openwrt-luci,slayerrensky/luci,daofeng2015/luci,Noltari/luci,maxrio/luci981213,oneru/luci,MinFu/luci,florian-shellfire/luci,joaofvieira/luci,wongsyrone/luci-1,lcf258/openwrtcn,maxrio/luci981213,teslamint/luci,Wedmer/luci,artynet/luci,kuoruan/lede-luci,nwf/openwrt-luci,jorgifumi/luci,jorgifumi/luci,oyido/luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,deepak78/new-luci,lcf258/openwrtcn,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,dwmw2/luci,981213/luci-1,chris5560/openwrt-luci,tobiaswaldvogel/luci,dwmw2/luci,palmettos/cnLuCI,chris5560/openwrt-luci,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,981213/luci-1,Wedmer/luci,deepak78/new-luci,tobiaswaldvogel/luci,dwmw2/luci,remakeelectric/luci,mumuqz/luci,obsy/luci,forward619/luci,zhaoxx063/luci,hnyman/luci,florian-shellfire/luci,aa65535/luci,taiha/luci,oneru/luci,rogerpueyo/luci,zhaoxx063/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,lcf258/openwrtcn,cappiewu/luci,palmettos/cnLuCI,harveyhu2012/luci,nmav/luci,db260179/openwrt-bpi-r1-luci,harveyhu2012/luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,Wedmer/luci,teslamint/luci,teslamint/luci,hnyman/luci,oyido/luci,david-xiao/luci,lcf258/openwrtcn,Wedmer/luci,keyidadi/luci,hnyman/luci,kuoruan/luci,mumuqz/luci,keyidadi/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,obsy/luci,male-puppies/luci,urueedi/luci,opentechinstitute/luci,cappiewu/luci,taiha/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,MinFu/luci,marcel-sch/luci,obsy/luci,db260179/openwrt-bpi-r1-luci,cshore/luci,NeoRaider/luci,maxrio/luci981213,bittorf/luci,tcatm/luci,RedSnake64/openwrt-luci-packages,MinFu/luci,palmettos/test,fkooman/luci,RuiChen1113/luci,MinFu/luci,aa65535/luci,Wedmer/luci,palmettos/cnLuCI,jlopenwrtluci/luci,cshore/luci,kuoruan/lede-luci,dismantl/luci-0.12,opentechinstitute/luci,bright-things/ionic-luci,oneru/luci,981213/luci-1,Noltari/luci,obsy/luci,981213/luci-1,jchuang1977/luci-1,cappiewu/luci,tcatm/luci,dwmw2/luci,openwrt-es/openwrt-luci,male-puppies/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,jlopenwrtluci/luci,Noltari/luci,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,forward619/luci,oneru/luci,slayerrensky/luci,dismantl/luci-0.12,oneru/luci,florian-shellfire/luci,palmettos/cnLuCI,cshore-firmware/openwrt-luci,obsy/luci,sujeet14108/luci,openwrt-es/openwrt-luci,slayerrensky/luci,urueedi/luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,bittorf/luci,rogerpueyo/luci,slayerrensky/luci,nmav/luci,kuoruan/luci,teslamint/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,openwrt/luci,kuoruan/lede-luci,oyido/luci,palmettos/cnLuCI,wongsyrone/luci-1,wongsyrone/luci-1,shangjiyu/luci-with-extra,Hostle/luci,nmav/luci,lcf258/openwrtcn,thess/OpenWrt-luci,maxrio/luci981213,thesabbir/luci,jchuang1977/luci-1,artynet/luci,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,jorgifumi/luci,LuttyYang/luci,male-puppies/luci,MinFu/luci,Wedmer/luci,fkooman/luci,sujeet14108/luci,taiha/luci,schidler/ionic-luci,teslamint/luci,ReclaimYourPrivacy/cloak-luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,rogerpueyo/luci,keyidadi/luci,remakeelectric/luci,ollie27/openwrt_luci,remakeelectric/luci,joaofvieira/luci,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,tcatm/luci,artynet/luci,florian-shellfire/luci,MinFu/luci,openwrt-es/openwrt-luci,mumuqz/luci,LuttyYang/luci,bittorf/luci,LuttyYang/luci,lbthomsen/openwrt-luci,nmav/luci,fkooman/luci,wongsyrone/luci-1,lcf258/openwrtcn,Noltari/luci,kuoruan/luci,david-xiao/luci,harveyhu2012/luci,dwmw2/luci,male-puppies/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,rogerpueyo/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,Kyklas/luci-proto-hso,forward619/luci,jchuang1977/luci-1,deepak78/new-luci,kuoruan/luci,thess/OpenWrt-luci,lcf258/openwrtcn,jlopenwrtluci/luci,openwrt-es/openwrt-luci,aa65535/luci,keyidadi/luci,kuoruan/luci,Noltari/luci,nwf/openwrt-luci,Hostle/luci,nmav/luci,MinFu/luci,bittorf/luci,aa65535/luci,keyidadi/luci,teslamint/luci,kuoruan/luci,wongsyrone/luci-1,LuttyYang/luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,male-puppies/luci,oyido/luci,bittorf/luci,thess/OpenWrt-luci,Kyklas/luci-proto-hso,jorgifumi/luci,schidler/ionic-luci,opentechinstitute/luci,dismantl/luci-0.12,hnyman/luci,harveyhu2012/luci,Hostle/luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,shangjiyu/luci-with-extra,cappiewu/luci,forward619/luci,marcel-sch/luci,Sakura-Winkey/LuCI,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,cshore/luci,lbthomsen/openwrt-luci,mumuqz/luci,aa65535/luci,marcel-sch/luci,urueedi/luci,taiha/luci,openwrt/luci,oyido/luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,jorgifumi/luci,david-xiao/luci,kuoruan/luci,marcel-sch/luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,openwrt/luci,slayerrensky/luci,dismantl/luci-0.12,NeoRaider/luci,dwmw2/luci,Sakura-Winkey/LuCI,RedSnake64/openwrt-luci-packages,bright-things/ionic-luci,thesabbir/luci,schidler/ionic-luci,oneru/luci,taiha/luci,tobiaswaldvogel/luci,remakeelectric/luci,RuiChen1113/luci,thesabbir/luci,openwrt/luci,urueedi/luci,slayerrensky/luci,Hostle/luci,cshore-firmware/openwrt-luci,deepak78/new-luci,keyidadi/luci,ff94315/luci-1,NeoRaider/luci,sujeet14108/luci,jchuang1977/luci-1,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,lcf258/openwrtcn,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,Kyklas/luci-proto-hso,cshore/luci,lbthomsen/openwrt-luci,david-xiao/luci,Noltari/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci
|
ada2d5696c68719e7702f6e0f63aeb70d5a94dde
|
protocols/ppp/luasrc/model/network/proto_ppp.lua
|
protocols/ppp/luasrc/model/network/proto_ppp.lua
|
--[[
LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "ppp" then
return luci.i18n.translate("PPP")
elseif p == "pptp" then
return luci.i18n.translate("PPtP")
elseif p == "3g" then
return luci.i18n.translate("UMTS/GPRS/EV-DO")
elseif p == "pppoe" then
return luci.i18n.translate("PPPoE")
elseif p == "pppoa" then
return luci.i18n.translate("PPPoATM")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
if p == "ppp" or p == "pptp" then
return p
elseif p == "3g" then
return "comgt"
elseif p == "pppoe" then
return "ppp-mod-pppoe"
elseif p == "pppoa" then
return "ppp-mod-pppoa"
end
end
function proto.is_installed(self)
return nixio.fs.access("/lib/network/" .. p .. ".sh")
end
function proto.is_floating(self)
return (p ~= "pppoe")
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
if self:is_floating() then
return nil
else
return netmod.protocol.get_interfaces(self)
end
end
function proto.contains_interface(self, ifc)
if self:is_floating() then
return (netmod:ifnameof(ifc) == self:ifname())
else
return netmod.protocol.contains_interface(self, ifc)
end
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
--[[
LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "ppp" then
return luci.i18n.translate("PPP")
elseif p == "pptp" then
return luci.i18n.translate("PPtP")
elseif p == "3g" then
return luci.i18n.translate("UMTS/GPRS/EV-DO")
elseif p == "pppoe" then
return luci.i18n.translate("PPPoE")
elseif p == "pppoa" then
return luci.i18n.translate("PPPoATM")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
if p == "ppp" or p == "pptp" then
return p
elseif p == "3g" then
return "comgt"
elseif p == "pppoe" then
return "ppp-mod-pppoe"
elseif p == "pppoa" then
return "ppp-mod-pppoa"
end
end
function proto.is_installed(self)
if nixio.fs.access("/lib/network/" .. p .. ".sh") then
return true
elseif p == "pppoa" then
return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil)
elseif p == "pppoe" then
return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil)
elseif p == "3g" then
return nixio.fs.access("/lib/netifd/proto/3g.sh")
else
return nixio.fs.access("/lib/netifd/proto/ppp.sh")
end
end
function proto.is_floating(self)
return (p ~= "pppoe")
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
if self:is_floating() then
return nil
else
return netmod.protocol.get_interfaces(self)
end
end
function proto.contains_interface(self, ifc)
if self:is_floating() then
return (netmod:ifnameof(ifc) == self:ifname())
else
return netmod.protocol.contains_interface(self, ifc)
end
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
protocols/ppp: fix install state detection with netifd
|
protocols/ppp: fix install state detection with netifd
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8657 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
a2d608756ff0dc359dce3b3ae0c4e320fdfaff4b
|
libs/http/luasrc/http/protocol/conditionals.lua
|
libs/http/luasrc/http/protocol/conditionals.lua
|
--[[
HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
--- LuCI http protocol implementation - HTTP/1.1 bits.
-- This class provides basic ETag handling and implements most of the
-- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 .
module("luci.http.protocol.conditionals", package.seeall)
local date = require("luci.http.protocol.date")
--- Implement 14.19 / ETag.
-- @param stat A file.stat structure
-- @return String containing the generated tag suitable for ETag headers
function mk_etag( stat )
if stat ~= nil then
return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime )
end
end
--- 14.24 / If-Match
-- Test whether the given message object contains an "If-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
-- Check for matching resource
if type(h['If-Match']) == "string" then
for ent in h['If-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
return true
end
end
return false, 412
end
return true
end
--- 14.25 / If-Modified-Since
-- Test whether the given message object contains an "If-Modified-Since" header
-- and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_modified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Modified-Since']) == "string" then
local since = date.to_unix( h['If-Modified-Since'] )
if stat == nil or since < stat.mtime then
return true
end
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
end
return true
end
--- 14.26 / If-None-Match
-- Test whether the given message object contains an "If-None-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_none_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
-- Check for matching resource
if type(h['If-None-Match']) == "string" then
for ent in h['If-None-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
if req.request_method == "get" or
req.request_method == "head"
then
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
else
return false, 412
end
end
end
end
return true
end
--- 14.27 / If-Range
-- The If-Range header is currently not implemented due to the lack of general
-- byte range stuff in luci.http.protocol . This function will always return
-- false, 412 to indicate a failed precondition.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_range( req, stat )
-- Sorry, no subranges (yet)
return false, 412
end
--- 14.28 / If-Unmodified-Since
-- Test whether the given message object contains an "If-Unmodified-Since"
-- header and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_unmodified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Unmodified-Since']) == "string" then
local since = date.to_unix( h['If-Unmodified-Since'] )
if stat ~= nil and since <= stat.mtime then
return false, 412
end
end
return true
end
|
--[[
HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
--- LuCI http protocol implementation - HTTP/1.1 bits.
-- This class provides basic ETag handling and implements most of the
-- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 .
module("luci.http.protocol.conditionals", package.seeall)
local date = require("luci.http.protocol.date")
--- Implement 14.19 / ETag.
-- @param stat A file.stat structure
-- @return String containing the generated tag suitable for ETag headers
function mk_etag( stat )
if stat ~= nil then
return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime )
end
end
--- 14.24 / If-Match
-- Test whether the given message object contains an "If-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
-- Check for matching resource
if type(h['If-Match']) == "string" then
for ent in h['If-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
return true
end
end
return false, 412
end
return true
end
--- 14.25 / If-Modified-Since
-- Test whether the given message object contains an "If-Modified-Since" header
-- and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_modified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Modified-Since']) == "string" then
local since = date.to_unix( h['If-Modified-Since'] )
if stat == nil or since < stat.mtime then
return true
end
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
end
return true
end
--- 14.26 / If-None-Match
-- Test whether the given message object contains an "If-None-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_none_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
local method = req.env and req.env.REQUEST_METHOD or "GET"
-- Check for matching resource
if type(h['If-None-Match']) == "string" then
for ent in h['If-None-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
if method == "GET" or method == "HEAD" then
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
else
return false, 412
end
end
end
end
return true
end
--- 14.27 / If-Range
-- The If-Range header is currently not implemented due to the lack of general
-- byte range stuff in luci.http.protocol . This function will always return
-- false, 412 to indicate a failed precondition.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_range( req, stat )
-- Sorry, no subranges (yet)
return false, 412
end
--- 14.28 / If-Unmodified-Since
-- Test whether the given message object contains an "If-Unmodified-Since"
-- header and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_unmodified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Unmodified-Since']) == "string" then
local since = date.to_unix( h['If-Unmodified-Since'] )
if stat ~= nil and since <= stat.mtime then
return false, 412
end
end
return true
end
|
libs/http: fix incorrent treatment of If-None-Match (#100)
|
libs/http: fix incorrent treatment of If-None-Match (#100)
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5635 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.