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
|
---|---|---|---|---|---|---|---|---|---|
7ad676e5bf506c900564ff28080d5114f3c222a3
|
wow/30-FontString-Text.lua
|
wow/30-FontString-Text.lua
|
require "wow/Frame";
require "rainback/AnchoredBound";
require "rainback/Graphics";
local Delegate = OOP.Class();
function Delegate:Constructor(frame)
self.frame = frame;
self.text = "";
self.font = Rainback.Font();
self.color = {0, 0, 0, 1};
frame:OnDelegateSet(function(category, delegate)
if category ~= "layout" then
return;
end;
self:AttachLayout(delegate);
end);
if frame:GetDelegate("layout") then
self:AttachLayout(delegate);
end;
end;
function Delegate:AttachLayout(delegate)
if not delegate.GetBounds then
return;
end;
local bounds = delegate:GetBounds();
if type(bounds) ~= "table" then
return;
end;
if not bounds.GetNaturalHeight or not bounds.GetNaturalWidth then
return;
end;
bounds.GetNaturalHeight = Override(self, "GetNaturalHeight");
bounds.GetNaturalWidth = Override(self, "GetNaturalWidth");
end;
function Delegate:GetText()
return self.text;
end;
function Delegate:SetText(text)
self.text = tostring(text);
Rainback.Update();
end;
function Delegate:GetNaturalWidth(height)
return self.font:width(self.text);
end;
function Delegate:GetNaturalHeight(width)
return self.font:height(self.text, width);
end;
function Delegate:GetWrappedWidth()
return self:GetNaturalWidth();
end;
function Delegate:GetStringWidth()
return self:GetNaturalWidth();
end;
function Delegate:GetStringHeight()
return self:GetNaturalHeight();
end;
function Delegate:SetFont(family, size)
self.font.family = family;
self.font.pointSize = size;
Rainback.Update();
end;
function Delegate:GetFont()
return self.font.family, self.folnt.pointSize;
end;
function Delegate:SetTextColor(r, g, b, a)
self.color = {r, g, b, a};
Rainback.Update();
end;
function Delegate:GetTextColor()
return unpack(self.color);
end;
function Delegate:GetInternalFont()
return self.font;
end;
function Delegate:ToString()
return "[Rainback Text Delegate]";
end;
WoW.SetFrameDelegate("FontString", "text", Delegate, "New");
|
require "wow/Frame";
require "rainback/AnchoredBound";
require "rainback/Graphics";
local Delegate = OOP.Class();
function Delegate:Constructor(frame)
self.frame = frame;
self.text = "";
self.font = Rainback.Font();
self.color = {0, 0, 0, 1};
frame:OnDelegateSet(function(category, delegate)
if category ~= "layout" then
return;
end;
self:AttachLayout(delegate);
end);
local delegate = frame:GetDelegate("layout");
if delegate then
frame:AttachLayout(delegate);
end;
end;
function Delegate:AttachLayout(delegate)
if not delegate.GetBounds then
return;
end;
local bounds = delegate:GetBounds();
if type(bounds) ~= "table" then
return;
end;
if not bounds.GetNaturalHeight or not bounds.GetNaturalWidth then
return;
end;
bounds.GetNaturalHeight = Override(self, "GetNaturalHeight");
bounds.GetNaturalWidth = Override(self, "GetNaturalWidth");
end;
function Delegate:GetText()
return self.text;
end;
function Delegate:SetText(text)
self.text = tostring(text);
Rainback.Update();
end;
function Delegate:GetNaturalWidth(height)
return self.font:width(self.text);
end;
function Delegate:GetNaturalHeight(width)
return self.font:height(self.text, width);
end;
function Delegate:GetWrappedWidth()
return self:GetNaturalWidth();
end;
function Delegate:GetStringWidth()
return self:GetNaturalWidth();
end;
function Delegate:GetStringHeight()
return self:GetNaturalHeight();
end;
function Delegate:SetFont(family, size)
self.font.family = family;
self.font.pointSize = size;
Rainback.Update();
end;
function Delegate:GetFont()
return self.font.family, self.folnt.pointSize;
end;
function Delegate:SetTextColor(r, g, b, a)
self.color = {r, g, b, a};
Rainback.Update();
end;
function Delegate:GetTextColor()
return unpack(self.color);
end;
function Delegate:GetInternalFont()
return self.font;
end;
function Delegate:ToString()
return "[Rainback Text Delegate]";
end;
WoW.SetFrameDelegate("FontString", "text", Delegate, "New");
|
Fix a lingering bug in FontString
|
Fix a lingering bug in FontString
|
Lua
|
mit
|
Thonik/rainback
|
32d54ef9a3e786b6dfb11994e53db5448e32f078
|
tests/lua/scope.lua
|
tests/lua/scope.lua
|
local env = environment()
local l = param_univ("l")
local nat = Const("nat")
local real = Const("real")
local one = Const("one")
local Ul = mk_sort(l)
local lst_l = Const("lst", {l})
local vec_l = Const("vec", {l})
local mat_l = Const("mat", {l})
local A = Local("A", Ul)
local n = Local("n", nat)
local ll = Local("ll", lst_l(A))
local len_l = Const("len", {l})
local lst_1 = Const("lst", {1})
local l1 = param_univ("l1")
local l2 = param_univ("l2")
local m = Local("m", nat)
env = add_decl(env, mk_var_decl("nat", Type))
env = add_decl(env, mk_var_decl("real", Type))
env = add_decl(env, mk_var_decl("one", nat))
env = add_decl(env, mk_var_decl("lst", {l}, mk_arrow(Ul, Ul)))
env = add_decl(env, mk_var_decl("len", {l}, Pi(A, mk_arrow(lst_l(A), nat))))
env = add_decl(env, mk_var_decl("vec", {l}, mk_arrow(Ul, nat, Ul)))
env = add_decl(env, mk_var_decl("mat", {l}, mk_arrow(Ul, nat, nat, Ul)))
env = add_decl(env, mk_var_decl("dlst", {l1, l2}, mk_arrow(mk_sort(l1), mk_sort(l2), mk_sort(max_univ(l1, l2)))))
env = add_decl(env, mk_var_decl("vec2lst", {l}, Pi({A, n}, mk_arrow(vec_l(A, n), lst_l(A)))))
env = add_decl(env, mk_var_decl("lst2vec", {l}, Pi({A, ll}, vec_l(A, len_l(A, ll)))))
env = add_decl(env, mk_var_decl("vec2mat", {l}, Pi({A, n}, mk_arrow(vec_l(A, n), mat_l(A, n, one)))))
env = add_decl(env, mk_var_decl("mat2dlst", {l}, Pi({A, n, m}, mk_arrow(mat_l(A, n, m), Const("dlst", {l, 1})(A, nat)))))
env = add_decl(env, mk_var_decl("nat2lst", mk_arrow(nat, lst_1(nat))))
env = add_coercion(env, "lst2vec")
env = push_scope(env, "tst")
local lst_nat = lst_1(nat)
print(get_coercion(env, lst_nat, "vec"))
env = add_coercion(env, "vec2mat")
print(get_coercion(env, lst_nat, "mat"))
assert(env:type_check(get_coercion(env, lst_nat, "mat")))
function get_num_coercions(env)
local r = 0
for_each_coercion_user(env, function(C, D, f) r = r + 1 end)
return r
end
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 3)
env = pop_scope(env)
print("---------")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 1)
print("---------")
env = push_scope(env)
env = using_namespace_objects(env, "tst")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 3)
env = pop_scope(env)
print("---------")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 1)
print("---------")
env = push_scope(env, "tst")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 3)
print("---------")
env = push_scope(env)
env = add_coercion(env, "nat2lst")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 6)
print("---------")
env = pop_scope(env)
assert(get_num_coercions(env) == 3)
env = pop_scope(env)
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 1)
env = push_scope(env, "tst")
assert(get_num_coercions(env) == 3)
os.exit(0)
print(get_coercion(env, nat, "mat"))
assert(env:type_check(get_coercion(env, nat, "mat")))
env = add_coercion(env, "mat2dlst")
print("---------")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
print(get_coercion(env, lst_nat, "dlst"))
assert(env:type_check(get_coercion(env, lst_nat, "dlst")))
env:export("coe1_mod.olean")
local env2 = import_modules("coe1_mod")
print(get_coercion(env2, lst_nat, "dlst"))
assert(env2:type_check(get_coercion(env2, lst_nat, "dlst")))
assert(is_coercion(env2, "vec2mat"))
assert(is_coercion(env2, "lst2vec"))
env2 = add_decl(env2, mk_var_decl("lst2vec2", {l}, Pi({A, ll}, vec_l(A, len_l(A, ll)))))
print("======")
env2 = add_coercion(env2, "lst2vec2")
print("======")
print(get_coercion(env2, lst_nat, "dlst"))
print("---------")
for_each_coercion_user(env2, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
env2 = add_coercion(env2, "vec2lst")
env2 = add_decl(env2, mk_var_decl("lst2nat", {l}, Pi({A}, mk_arrow(lst_l(A), nat))))
env2 = add_coercion(env2, "lst2nat")
print("---------")
for_each_coercion_user(env2, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D)) end)
for_each_coercion_user(env2, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(has_coercions_from(env2, lst_nat))
assert(not has_coercions_from(env2, Const("foo")))
assert(not has_coercions_from(env2, Const("lst", {1})))
assert(has_coercions_from(env2, Const("vec", {1})(nat, one)))
assert(not has_coercions_from(env2, Const("vec", {1})(nat)))
assert(not has_coercions_from(env2, Const("vec")(nat, one)))
print("Coercions (vec nat one): ")
cs = get_user_coercions(env2, Const("vec", {1})(nat, one))
for i = 1, #cs do
print(tostring(cs[i][1]) .. " : " .. tostring(cs[i][3]) .. " : " .. tostring(cs[i][2]))
end
|
local env = environment()
local l = param_univ("l")
local nat = Const("nat")
local real = Const("real")
local one = Const("one")
local Ul = mk_sort(l)
local lst_l = Const("lst", {l})
local vec_l = Const("vec", {l})
local mat_l = Const("mat", {l})
local A = Local("A", Ul)
local n = Local("n", nat)
local ll = Local("ll", lst_l(A))
local len_l = Const("len", {l})
local lst_1 = Const("lst", {1})
local l1 = param_univ("l1")
local l2 = param_univ("l2")
local m = Local("m", nat)
env = add_decl(env, mk_var_decl("nat", Type))
env = add_decl(env, mk_var_decl("real", Type))
env = add_decl(env, mk_var_decl("one", nat))
env = add_decl(env, mk_var_decl("lst", {l}, mk_arrow(Ul, Ul)))
env = add_decl(env, mk_var_decl("len", {l}, Pi(A, mk_arrow(lst_l(A), nat))))
env = add_decl(env, mk_var_decl("vec", {l}, mk_arrow(Ul, nat, Ul)))
env = add_decl(env, mk_var_decl("mat", {l}, mk_arrow(Ul, nat, nat, Ul)))
env = add_decl(env, mk_var_decl("dlst", {l1, l2}, mk_arrow(mk_sort(l1), mk_sort(l2), mk_sort(max_univ(l1, l2)))))
env = add_decl(env, mk_var_decl("vec2lst", {l}, Pi({A, n}, mk_arrow(vec_l(A, n), lst_l(A)))))
env = add_decl(env, mk_var_decl("lst2vec", {l}, Pi({A, ll}, vec_l(A, len_l(A, ll)))))
env = add_decl(env, mk_var_decl("vec2mat", {l}, Pi({A, n}, mk_arrow(vec_l(A, n), mat_l(A, n, one)))))
env = add_decl(env, mk_var_decl("mat2dlst", {l}, Pi({A, n, m}, mk_arrow(mat_l(A, n, m), Const("dlst", {l, 1})(A, nat)))))
env = add_decl(env, mk_var_decl("nat2lst", mk_arrow(nat, lst_1(nat))))
env = add_coercion(env, "lst2vec")
env = push_scope(env, "tst")
local lst_nat = lst_1(nat)
print(get_coercion(env, lst_nat, "vec"))
env = add_coercion(env, "vec2mat")
print(get_coercion(env, lst_nat, "mat"))
assert(env:type_check(get_coercion(env, lst_nat, "mat")))
function get_num_coercions(env)
local r = 0
for_each_coercion_user(env, function(C, D, f) r = r + 1 end)
return r
end
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 3)
env = pop_scope(env)
print("---------")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 1)
print("---------")
env = push_scope(env)
env = using_namespace_objects(env, "tst")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 3)
env = pop_scope(env)
print("---------")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 1)
print("---------")
env = push_scope(env, "tst")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 3)
print("---------")
env = push_scope(env)
env = add_coercion(env, "nat2lst")
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 6)
print("---------")
env = pop_scope(env)
assert(get_num_coercions(env) == 3)
env = pop_scope(env)
for_each_coercion_user(env, function(C, D, f) print(tostring(C) .. " >-> " .. tostring(D) .. " : " .. tostring(f)) end)
assert(get_num_coercions(env) == 1)
env = push_scope(env, "tst")
assert(get_num_coercions(env) == 3)
|
fix(tests/lua): remove os.exit(0), it does not work if it is executed in the scope of a lock
|
fix(tests/lua): remove os.exit(0), it does not work if it is executed in the scope of a lock
Signed-off-by: Leonardo de Moura <[email protected]>
|
Lua
|
apache-2.0
|
rlewis1988/lean,fgdorais/lean,fpvandoorn/lean2,avigad/lean,rlewis1988/lean,leanprover-community/lean,fpvandoorn/lean,javra/lean,htzh/lean,johoelzl/lean,fgdorais/lean,avigad/lean,soonhokong/lean-osx,htzh/lean,Kha/lean,soonhokong/lean,fpvandoorn/lean,avigad/lean,soonhokong/lean-windows,dselsam/lean,eigengrau/lean,javra/lean,levnach/lean,leanprover-community/lean,dselsam/lean,UlrikBuchholtz/lean,sp3ctum/lean,Kha/lean,soonhokong/lean-windows,soonhokong/lean-osx,sp3ctum/lean,leanprover-community/lean,soonhokong/lean-osx,digama0/lean,c-cube/lean,sp3ctum/lean,fpvandoorn/lean2,leodemoura/lean,rlewis1988/lean,fgdorais/lean,leanprover/lean,c-cube/lean,dselsam/lean,soonhokong/lean-windows,johoelzl/lean,soonhokong/lean,soonhokong/lean,fgdorais/lean,soonhokong/lean,c-cube/lean,htzh/lean,eigengrau/lean,UlrikBuchholtz/lean,leanprover/lean,levnach/lean,fpvandoorn/lean2,digama0/lean,avigad/lean,soonhokong/lean-osx,rlewis1988/lean,levnach/lean,javra/lean,javra/lean,digama0/lean,fpvandoorn/lean,leodemoura/lean,fgdorais/lean,leanprover-community/lean,eigengrau/lean,fpvandoorn/lean2,avigad/lean,leodemoura/lean,Kha/lean,rlewis1988/lean,leanprover-community/lean,sp3ctum/lean,htzh/lean,fpvandoorn/lean,soonhokong/lean,leanprover-community/lean,fpvandoorn/lean,sp3ctum/lean,leanprover/lean,c-cube/lean,digama0/lean,javra/lean,johoelzl/lean,Kha/lean,fgdorais/lean,levnach/lean,UlrikBuchholtz/lean,leodemoura/lean,soonhokong/lean-windows,c-cube/lean,htzh/lean,fpvandoorn/lean,leodemoura/lean,rlewis1988/lean,Kha/lean,eigengrau/lean,dselsam/lean,leanprover/lean,avigad/lean,johoelzl/lean,soonhokong/lean-osx,leodemoura/lean,Kha/lean,UlrikBuchholtz/lean,digama0/lean,johoelzl/lean,levnach/lean,eigengrau/lean,fpvandoorn/lean2,leanprover/lean,dselsam/lean,dselsam/lean,digama0/lean,soonhokong/lean-windows,UlrikBuchholtz/lean,johoelzl/lean,leanprover/lean
|
5203c1f0cd453082add7d251d1a732033564a62d
|
premake4.lua
|
premake4.lua
|
function copy(src, dst, always)
local action = "python"
local script = "\"" .. path.join(os.getcwd(), "copy-data.py") .. "\""
src = "\"" .. src .. "\""
dst = "\"" .. dst .. "\""
cwd = "\"" .. os.getcwd() .. "\""
postbuildcommands { action .. " " .. script .. " " .. cwd .. " " .. src .. " " .. dst .. " " .. tostring(always) }
end
function resource(src, dst, always)
if always == nil then
always = false
else
always = true
end
copy(src, path.join("build", dst), always)
copy(src, path.join("bin", dst), always)
end
saved_config = {}
function save_config()
saved_config = configuration().terms
end
function restore_config()
configuration(saved_config)
end
function windows_libdir(basePath)
save_config()
--XXX: merge configurations?
for _,arch in pairs({"x32", "x64"}) do
for _,conf in pairs({"debug", "release"}) do
for _, plat in pairs({"vs2008"}) do
local confpath = plat .. "/" .. arch .. "/" .. conf
configuration { "windows", arch, conf, plat }
libdirs { path.join(basePath, confpath) }
end
end
end
restore_config()
end
function windows_binary(basePath, debugDllName, releaseDllName)
if releaseDllName == nil then
releaseDllName = debugDllName
end
save_config()
for _,arch in pairs({"x32", "x64"}) do
for _, plat in pairs({"vs2008"}) do
local confpath = plat .. "/" .. arch .. "/" .. "debug"
configuration { "windows", arch, "debug", plat }
resource(path.join(path.join(basePath, confpath), debugDllName), debugDllName, true)
local confpath = plat .. "/" .. arch .. "/" .. "release"
configuration { "windows", arch, "release", plat }
resource(path.join(path.join(basePath, confpath), releaseDllName), releaseDllName, true)
end
end
restore_config()
end
newaction {
trigger = 'clean',
description = 'Cleans up the project.',
shortname = "clean",
execute = function()
os.rmdir("bin")
os.rmdir("build")
end
}
solution "blowmorph"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location "build"
targetdir "bin"
flags { "FatalWarnings", "NoRTTI" }
configuration { "linux" }
flags { "NoExceptions" }
-- TODO: use "-stdlib=libc++" for clang.
linkoptions { "-std=c++11" }
buildoptions { "-std=c++11" }
configuration { "windows" }
-- TODO: C++11
includedirs { "src/windows" }
defines { "WIN32", "_WIN32" }
defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE", "_SCL_SECURE_NO_WARNINGS" }
configuration { "debug" }
defines { "DEBUG" }
flags { "Symbols" }
configuration { "release" }
defines { "NDEBUG" }
flags { "Optimize" }
project "client"
kind "ConsoleApp"
language "C++"
targetname "client"
includedirs { "src" }
files { "src/client/**.cpp",
"src/client/**.h" }
links { "base", "engine" }
configuration "windows"
resource("data", "data")
-- SFML
configuration "windows"
includedirs { "third-party/SFML/include" }
windows_libdir("third-party/SFML/bin")
windows_binary("third-party/SFML/bin", "sfml-system-d-2.dll", "sfml-system-2.dll")
windows_binary("third-party/SFML/bin", "sfml-window-d-2.dll", "sfml-window-2.dll")
windows_binary("third-party/SFML/bin", "sfml-graphics-d-2.dll", "sfml-graphics-2.dll")
windows_binary("third-party/SFML/bin", "sfml-audio-d-2.dll", "sfml-audio-2.dll")
configuration { "windows", "debug" }
links { "sfml-system-d" }
links { "sfml-window-d" }
links { "sfml-graphics-d" }
links { "sfml-audio-d" }
configuration { "windows", "release" }
links { "sfml-system" }
links { "sfml-window" }
links { "sfml-graphics" }
links { "sfml-audio" }
configuration "linux"
links { "sfml-system" }
links { "sfml-window" }
links { "sfml-graphics" }
links { "sfml-audio" }
-- PugiXML
configuration "windows"
includedirs { "third-party/pugixml/include" }
windows_libdir("third-party/pugixml/bin")
links { "pugixml" }
configuration "linux"
links { "pugixml" }
-- ENetPlus
configuration "windows"
includedirs { "third-party/enet-plus/include" }
windows_libdir("third-party/enet-plus/bin")
windows_binary("third-party/enet-plus/bin", "enet-plus.dll")
links { "enet-plus" }
configuration "linux"
links { "enet-plus" }
-- Box2D
configuration "windows"
-- TODO
configuration "linux"
links { "Box2D" }
project "server"
kind "ConsoleApp"
language "C++"
targetname "server"
includedirs { "src" }
files { "src/server/**.cpp",
"src/server/**.h" }
links { "base", "engine" }
configuration "windows"
resource("data", "data")
-- JsonCpp
configuration "windows"
-- TODO
configuration "linux"
links { "jsoncpp" }
-- ENetPlus
configuration "windows"
includedirs { "third-party/enet-plus/include" }
windows_libdir("third-party/enet-plus/bin")
windows_binary("third-party/enet-plus/bin", "enet-plus.dll")
links { "enet-plus" }
configuration "linux"
links { "enet-plus" }
-- Box2D
configuration "windows"
-- TODO
configuration "linux"
links { "Box2D" }
project "base"
kind "SharedLib"
language "C++"
defines { "BM_BASE_DLL" }
includedirs { "src" }
files { "src/base/**.cpp",
"src/base/**.h" }
-- JsonCpp
configuration "windows"
-- TODO
configuration "linux"
links { "jsoncpp" }
-- libconfig
configuration "windows"
includedirs { "third-party/libconfig/include" }
windows_libdir("third-party/libconfig/bin")
windows_binary("third-party/libconfig/bin", "libconfig_d.dll", "libconfig.dll")
configuration { "windows", "debug" }
links { "libconfig_d" }
configuration { "windows", "release" }
links { "libconfig" }
configuration "linux"
links { "config" }
-- ENetPlus
configuration "windows"
includedirs { "third-party/enet-plus/include" }
windows_libdir("third-party/enet-plus/bin")
windows_binary("third-party/enet-plus/bin", "enet-plus.dll")
links { "enet-plus" }
configuration "linux"
links { "enet-plus" }
project "engine"
kind "SharedLib"
language "C++"
defines { "BM_ENGINE_DLL" }
includedirs { "src" }
files { "src/engine/**.cpp",
"src/engine/**.h" }
links { "base" }
-- Box2D
configuration "windows"
-- TODO
configuration "linux"
links { "Box2D" }
project "interpolator"
kind "StaticLib"
language "C++"
includedirs { "src" }
files { "src/interpolator/**.cpp",
"src/interpolator/**.h" }
|
function copy(src, dst, always)
local action = "python"
local script = "\"" .. path.join(os.getcwd(), "copy-data.py") .. "\""
src = "\"" .. src .. "\""
dst = "\"" .. dst .. "\""
cwd = "\"" .. os.getcwd() .. "\""
postbuildcommands { action .. " " .. script .. " " .. cwd .. " " .. src .. " " .. dst .. " " .. tostring(always) }
end
function resource(src, dst, always)
if always == nil then
always = false
else
always = true
end
copy(src, path.join("build", dst), always)
copy(src, path.join("bin", dst), always)
end
saved_config = {}
function save_config()
saved_config = configuration().terms
end
function restore_config()
configuration(saved_config)
end
function windows_libdir(basePath)
save_config()
--XXX: merge configurations?
for _,arch in pairs({"x32", "x64"}) do
for _,conf in pairs({"debug", "release"}) do
for _, plat in pairs({"vs2008"}) do
local confpath = plat .. "/" .. arch .. "/" .. conf
configuration { "windows", arch, conf, plat }
libdirs { path.join(basePath, confpath) }
end
end
end
restore_config()
end
function windows_binary(basePath, debugDllName, releaseDllName)
if releaseDllName == nil then
releaseDllName = debugDllName
end
save_config()
for _,arch in pairs({"x32", "x64"}) do
for _, plat in pairs({"vs2008"}) do
local confpath = plat .. "/" .. arch .. "/" .. "debug"
configuration { "windows", arch, "debug", plat }
resource(path.join(path.join(basePath, confpath), debugDllName), debugDllName, true)
local confpath = plat .. "/" .. arch .. "/" .. "release"
configuration { "windows", arch, "release", plat }
resource(path.join(path.join(basePath, confpath), releaseDllName), releaseDllName, true)
end
end
restore_config()
end
newaction {
trigger = 'clean',
description = 'Cleans up the project.',
shortname = "clean",
execute = function()
os.rmdir("bin")
os.rmdir("build")
end
}
solution "blowmorph"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location "build"
targetdir "bin"
flags { "FatalWarnings", "NoRTTI" }
configuration { "linux" }
flags { "NoExceptions" }
-- TODO: use "-stdlib=libc++" for clang.
linkoptions { "-std=c++11" }
buildoptions { "-std=c++11" }
configuration { "windows" }
-- TODO: C++11
includedirs { "src/windows" }
defines { "WIN32", "_WIN32" }
defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE", "_SCL_SECURE_NO_WARNINGS" }
configuration { "debug" }
defines { "DEBUG" }
flags { "Symbols" }
configuration { "release" }
defines { "NDEBUG" }
flags { "Optimize" }
project "client"
kind "ConsoleApp"
language "C++"
targetname "client"
includedirs { "src" }
files { "src/client/**.cpp",
"src/client/**.h" }
links { "base", "engine" }
configuration "windows"
resource("data", "data")
-- SFML
configuration "windows"
includedirs { "third-party/SFML/include" }
windows_libdir("third-party/SFML/bin")
windows_binary("third-party/SFML/bin", "sfml-system-d-2.dll", "sfml-system-2.dll")
windows_binary("third-party/SFML/bin", "sfml-window-d-2.dll", "sfml-window-2.dll")
windows_binary("third-party/SFML/bin", "sfml-graphics-d-2.dll", "sfml-graphics-2.dll")
windows_binary("third-party/SFML/bin", "sfml-audio-d-2.dll", "sfml-audio-2.dll")
configuration { "windows", "debug" }
links { "sfml-system-d" }
links { "sfml-window-d" }
links { "sfml-graphics-d" }
links { "sfml-audio-d" }
configuration { "windows", "release" }
links { "sfml-system" }
links { "sfml-window" }
links { "sfml-graphics" }
links { "sfml-audio" }
configuration "linux"
links { "sfml-system" }
links { "sfml-window" }
links { "sfml-graphics" }
links { "sfml-audio" }
-- ENetPlus
configuration "windows"
includedirs { "third-party/enet-plus/include" }
windows_libdir("third-party/enet-plus/bin")
windows_binary("third-party/enet-plus/bin", "enet-plus.dll")
links { "enet-plus" }
configuration "linux"
links { "enet-plus" }
-- Box2D
configuration "windows"
-- TODO
configuration "linux"
links { "Box2D" }
project "server"
kind "ConsoleApp"
language "C++"
targetname "server"
includedirs { "src" }
files { "src/server/**.cpp",
"src/server/**.h" }
links { "base", "engine" }
configuration "windows"
resource("data", "data")
-- JsonCpp
configuration "windows"
-- TODO
configuration "linux"
links { "jsoncpp" }
-- ENetPlus
configuration "windows"
includedirs { "third-party/enet-plus/include" }
windows_libdir("third-party/enet-plus/bin")
windows_binary("third-party/enet-plus/bin", "enet-plus.dll")
links { "enet-plus" }
configuration "linux"
links { "enet-plus" }
-- Box2D
configuration "windows"
-- TODO
configuration "linux"
links { "Box2D" }
project "base"
kind "SharedLib"
language "C++"
defines { "BM_BASE_DLL" }
includedirs { "src" }
files { "src/base/**.cpp",
"src/base/**.h" }
-- JsonCpp
configuration "windows"
-- TODO
configuration "linux"
links { "jsoncpp" }
-- libconfig
configuration "windows"
includedirs { "third-party/libconfig/include" }
windows_libdir("third-party/libconfig/bin")
windows_binary("third-party/libconfig/bin", "libconfig_d.dll", "libconfig.dll")
configuration { "windows", "debug" }
links { "libconfig_d" }
configuration { "windows", "release" }
links { "libconfig" }
configuration "linux"
links { "config" }
-- ENetPlus
configuration "windows"
includedirs { "third-party/enet-plus/include" }
windows_libdir("third-party/enet-plus/bin")
windows_binary("third-party/enet-plus/bin", "enet-plus.dll")
links { "enet-plus" }
configuration "linux"
links { "enet-plus" }
project "engine"
kind "SharedLib"
language "C++"
defines { "BM_ENGINE_DLL" }
includedirs { "src" }
files { "src/engine/**.cpp",
"src/engine/**.h" }
links { "base" }
-- Box2D
configuration "windows"
-- TODO
configuration "linux"
links { "Box2D" }
project "interpolator"
kind "StaticLib"
language "C++"
includedirs { "src" }
files { "src/interpolator/**.cpp",
"src/interpolator/**.h" }
|
Fix premake.lua
|
Fix premake.lua
|
Lua
|
bsd-3-clause
|
bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph,bmteam/blowmorph
|
72035316c7141c4147f2b67508b4817e9d045c40
|
premake4.lua
|
premake4.lua
|
--
-- Premake4 build script (http://industriousone.com/premake/download)
--
solution 'WinsockExamples'
configurations {'Debug', 'Release'}
language 'C++'
flags {'ExtraWarnings'}
targetdir 'bin'
configuration 'Debug'
defines { 'DEBUG' }
flags { 'Symbols' }
configuration 'Release'
defines { 'NDEBUG' }
flags { 'Symbols', 'Optimize' }
project 'Socket'
location 'build'
kind 'ConsoleApp'
uuid "AB7D1C15-7A44-41a7-8864-230D8E345608"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/winsock/common/utility.h',
'src/winsock/common/utility.c',
'src/winsock/socket/*.h',
'src/winsock/socket/*.c',
}
includedirs
{
'src/winsock',
}
project 'Select'
location 'build'
kind 'ConsoleApp'
uuid "8701594A-72B8-4a6a-AEF3-6B41BBC33E65"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/winsock/common/*.h',
'src/winsock/common/*.c',
'src/winsock/select/*.h',
'src/winsock/select/*.c',
}
includedirs
{
'src/winsock',
}
project 'AsyncSelect'
location 'build'
kind 'ConsoleApp'
uuid "83CA7514-377C-4957-8399-9E407CFDD8DF"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/winsock/common/*.h',
'src/winsock/common/*.c',
'src/winsock/async_select/*.h',
'src/winsock/async_select/*.c',
}
includedirs
{
'src/winsock',
}
project 'AsyncEvent'
location 'build'
kind 'ConsoleApp'
uuid "DB1835D4-DA1F-4499-8F21-6E1913C2122E"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/winsock/common/*.h',
'src/winsock/common/*.c',
'src/winsock/async_event/*.h',
'src/winsock/async_event/*.c',
}
includedirs
{
'src/winsock',
}
project 'CompleteRoutine'
location 'build'
kind 'ConsoleApp'
uuid "729FA509-952E-41f2-A33C-1E061FADE78A"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/winsock/common/*.h',
'src/winsock/common/*.c',
'src/winsock/complete_routine/*.h',
'src/winsock/complete_routine/*.c',
}
includedirs
{
'src/winsock',
}
project 'Overlapped'
location 'build'
kind 'ConsoleApp'
uuid "18A51657-E2D5-49a0-B3C7-FE2BE55AD98A"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/winsock/common/*.h',
'src/winsock/common/*.c',
'src/winsock/overlapped/*.h',
'src/winsock/overlapped/*.c',
}
includedirs
{
'src/winsock',
}
project 'IOCP'
location 'build'
kind 'ConsoleApp'
uuid "588E072A-B1B8-4b36-B9BC-0E82547C7344"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/winsock/common/*.h',
'src/winsock/common/*.c',
'src/winsock/iocp/*.h',
'src/winsock/iocp/*.c',
}
includedirs
{
'src/winsock',
}
solution 'TestClient'
configurations {'Debug', 'Release'}
language 'C++'
flags {'ExtraWarnings'}
targetdir 'bin'
configuration 'Debug'
defines { 'DEBUG' }
flags { 'Symbols' }
configuration 'Release'
defines { 'NDEBUG' }
flags { 'Symbols', 'Optimize' }
project 'TestClient'
location 'build'
kind 'ConsoleApp'
uuid "FC0C8C22-35CF-4ce4-9A90-F99AD63A7BEA"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/winsock/common/*.h',
'src/winsock/common/*.c',
'tests/test_client/*.h',
'tests/test_client/*.c',
}
includedirs
{
'src/winsock',
}
|
--
-- Premake4 build script (http://industriousone.com/premake/download)
--
solution 'WinsockExamples'
configurations {'Debug', 'Release'}
language 'C++'
flags {'ExtraWarnings'}
targetdir 'bin'
configuration 'Debug'
defines { 'DEBUG' }
flags { 'Symbols' }
configuration 'Release'
defines { 'NDEBUG' }
flags { 'Symbols', 'Optimize' }
project 'Socket'
location 'build'
kind 'ConsoleApp'
uuid "AB7D1C15-7A44-41a7-8864-230D8E345608"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/common/utility.h',
'src/common/utility.c',
'src/socket/*.h',
'src/socket/*.c',
}
includedirs
{
'src',
}
project 'Select'
location 'build'
kind 'ConsoleApp'
uuid "8701594A-72B8-4a6a-AEF3-6B41BBC33E65"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/common/*.h',
'src/common/*.c',
'src/select/*.h',
'src/select/*.c',
}
includedirs
{
'src',
}
project 'AsyncSelect'
location 'build'
kind 'ConsoleApp'
uuid "83CA7514-377C-4957-8399-9E407CFDD8DF"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/common/*.h',
'src/common/*.c',
'src/async_select/*.h',
'src/async_select/*.c',
}
includedirs
{
'src',
}
project 'AsyncEvent'
location 'build'
kind 'ConsoleApp'
uuid "DB1835D4-DA1F-4499-8F21-6E1913C2122E"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/common/*.h',
'src/common/*.c',
'src/async_event/*.h',
'src/async_event/*.c',
}
includedirs
{
'src',
}
project 'CompleteRoutine'
location 'build'
kind 'ConsoleApp'
uuid "729FA509-952E-41f2-A33C-1E061FADE78A"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/common/*.h',
'src/common/*.c',
'src/complete_routine/*.h',
'src/complete_routine/*.c',
}
includedirs
{
'src',
}
project 'Overlapped'
location 'build'
kind 'ConsoleApp'
uuid "18A51657-E2D5-49a0-B3C7-FE2BE55AD98A"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/common/*.h',
'src/common/*.c',
'src/overlapped/*.h',
'src/overlapped/*.c',
}
includedirs
{
'src',
}
project 'IOCPServer'
location 'build'
kind 'ConsoleApp'
uuid "588E072A-B1B8-4b36-B9BC-0E82547C7344"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/common/*.h',
'src/common/*.c',
'src/iocp_server/*.h',
'src/iocp_server/*.c',
}
includedirs
{
'src',
}
project 'IOCPClient'
location 'build'
kind 'ConsoleApp'
uuid "FC0C8C22-35CF-4ce4-9A90-F99AD63A7BEA"
defines
{
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0501',
'NOMINMAX',
}
files
{
'src/common/*.h',
'src/common/*.c',
'src/iocp_client/*.h',
'src/iocp_client/*.c',
}
includedirs
{
'src',
}
|
fix building script
|
fix building script
|
Lua
|
apache-2.0
|
ichenq/WinsockTut,ichenq/WinsockTut,ichenq/WinsockTut
|
b166041f15531079c6dd6a0ecd6b14c788a80a8e
|
contrib/scripts/autoprop.lua
|
contrib/scripts/autoprop.lua
|
-- Automatically create a winprop for the WClientWin given.
-- Basic functionality by pinko
-- Extended by Etan Reisner <[email protected]>
-- kpress(META.."W", "autoprop(_sub, _, false)", "_sub:WClientWin")
-- kpress(MOD4.."W", "autoprop(_sub, _, true)", "_sub:WClientWin")
-- Use autoprop(_sub, nil, X) to remove a winprop
local savefile="autoprops"
local autoprops={}
function autoprop(cwin, dest, save)
local p={}
if type(dest)=="nil" then
name=nil
else
name=dest:name()
end
p.class="*"
p.role="*"
p.instance="*"
p.target=name
p=table.join(cwin:get_ident(), p)
defwinprop{
class=p.class,
instance=p.instance,
role=p.role,
target=name
}
if save and p.target then
autoprops[p.class..p.role..p.instance]=p
end
if p.target==nil then
autoprops[p.class..p.role..p.instance]=nil
end
end
local function save_autoprops()
ioncore.write_savefile(savefile, autoprops)
end
local function load_autoprops()
local d=ioncore.read_savefile(savefile)
if not d then
return
end
table.foreach(d, function(k, tab)
defwinprop{
class=tab.class,
instance=tab.instance,
role=tab.role,
target=tab.target
}
autoprops[tab.class..tab.role..tab.instance]=tab
end)
end
local function init()
load_autoprops()
ioncore.get_hook("ioncore_snapshot_hook"):add(save_autoprops)
end
init()
|
-- Automatically create a winprop for the WClientWin given.
-- Basic functionality by pinko
-- Extended by Etan Reisner <[email protected]>
--defbindings("WFrame", {
---- add winprop permanentlu
-- kpress(META.."W", "autoprop(_sub, _, true)", "_sub:WGroupCW"),
---- add winprop for this session only
-- kpress(META.."E", "autoprop(_sub, _, false)", "_sub:WGroupCW"),
---- remove winprop (permanently)
-- kpress(META.."Q", "autoprop(_sub, nil, X)"),
--})
-- Use autoprop(_sub, nil, X) to remove a winprop
local savefile="autoprops"
local autoprops={}
function autoprop(cwin_group, dest, save)
-- if cwin_group.__typename ~= "WGroupCW" then
-- return
-- end
local p={}
local cwin = cwin_group:bottom()
if type(dest)=="nil" then
name=nil
else
name=dest:name()
end
p.class="*"
p.role="*"
p.instance="*"
p.target=name
p=table.join(cwin:get_ident(), p)
defwinprop{
class=p.class,
instance=p.instance,
role=p.role,
target=name
}
if save and p.target then
autoprops[p.class..p.role..p.instance]=p
end
if p.target==nil then
autoprops[p.class..p.role..p.instance]=nil
end
end
local function save_autoprops()
ioncore.write_savefile(savefile, autoprops)
end
local function load_autoprops()
local d=ioncore.read_savefile(savefile)
if not d then
return
end
table.foreach(d, function(k, tab)
defwinprop{
class=tab.class,
instance=tab.instance,
role=tab.role,
target=tab.target
}
autoprops[tab.class..tab.role..tab.instance]=tab
end)
end
local function init()
load_autoprops()
ioncore.get_hook("ioncore_snapshot_hook"):add(save_autoprops)
end
init()
|
improve/bugfix autoprop.lua
|
improve/bugfix autoprop.lua
|
Lua
|
lgpl-2.1
|
raboof/notion,knixeur/notion,neg-serg/notion,dkogan/notion.xfttest,p5n/notion,anoduck/notion,anoduck/notion,p5n/notion,dkogan/notion.xfttest,p5n/notion,dkogan/notion.xfttest,anoduck/notion,neg-serg/notion,knixeur/notion,raboof/notion,neg-serg/notion,dkogan/notion,anoduck/notion,dkogan/notion,knixeur/notion,dkogan/notion,dkogan/notion,knixeur/notion,anoduck/notion,raboof/notion,p5n/notion,raboof/notion,dkogan/notion,dkogan/notion.xfttest,neg-serg/notion,knixeur/notion,p5n/notion
|
e8c4ec22bfc233a9bf756ed30042b76e42197431
|
premake4.lua
|
premake4.lua
|
local action = _ACTION or ""
solution "nanovg"
location ( "build" )
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
project "nanovg"
language "C"
kind "StaticLib"
includedirs { "src" }
files { "src/*.c" }
targetdir("build")
project "example_gl2"
kind "ConsoleApp"
language "C"
files { "example/example_gl2.c", "example/demo.c" }
includedirs { "src", "example" }
targetdir("build")
links { "nanovg" }
configuration { "linux" }
links { "X11","Xrandr", "rt", "GL", "GLU", "pthread", "m", "glfw3", "GLEW" }
defines { "NANOVG_GLEW" }
configuration { "windows" }
links { "glu32","opengl32", "gdi32", "winmm", "user32" }
configuration { "macosx" }
links { "glfw3" }
linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols", "ExtraWarnings"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "ExtraWarnings"}
project "example_gl3"
kind "ConsoleApp"
language "C"
files { "example/example_gl3.c", "example/demo.c" }
includedirs { "src", "example" }
targetdir("build")
links { "nanovg" }
configuration { "linux" }
links { "X11","Xrandr", "rt", "GL", "GLU", "pthread", "m", "glfw3", "GLEW" }
defines { "NANOVG_GLEW" }
configuration { "windows" }
links { "glu32","opengl32", "gdi32", "winmm", "user32" }
configuration { "macosx" }
links { "glfw3" }
linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols", "ExtraWarnings"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "ExtraWarnings"}
|
local action = _ACTION or ""
solution "nanovg"
location ( "build" )
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
project "nanovg"
language "C"
kind "StaticLib"
includedirs { "src" }
files { "src/*.c" }
targetdir("build")
project "example_gl2"
kind "ConsoleApp"
language "C"
files { "example/example_gl2.c", "example/demo.c" }
includedirs { "src", "example" }
targetdir("build")
links { "nanovg" }
configuration { "linux" }
links { "X11","Xrandr", "rt", "GL", "GLU", "pthread", "m", "glfw3", "GLEW" }
defines { "NANOVG_GLEW" }
configuration { "windows" }
links { "glu32","opengl32", "gdi32", "winmm", "user32" }
configuration { "macosx" }
links { "glfw3" }
linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols", "ExtraWarnings"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "ExtraWarnings"}
project "example_gl3"
kind "ConsoleApp"
language "C"
files { "example/example_gl3.c", "example/demo.c" }
includedirs { "src", "example" }
targetdir("build")
links { "nanovg" }
configuration { "linux" }
links { "X11","Xrandr", "rt", "GL", "GLU", "pthread", "m", "glfw3", "GLEW" }
defines { "NANOVG_GLEW" }
configuration { "windows" }
links { "glu32","opengl32", "gdi32", "winmm", "user32" }
configuration { "macosx" }
links { "glfw3" }
linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols", "ExtraWarnings"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "ExtraWarnings"}
|
Fix issue #10
|
Fix issue #10
- link to framework CoreVideo on OSX, fixes compiling on OSX 10.9
|
Lua
|
bsd-3-clause
|
dleslie/nanovg-egg
|
814e8cc95ef89e04d79eb07e667334fb0e4552bc
|
mods/00_bt_messages/00_bt_important_messages/init.lua
|
mods/00_bt_messages/00_bt_important_messages/init.lua
|
local MESSAGE_INTERVAL = 300
local mod_storage = minetest.get_mod_storage()
important_message = {}
important_message.message = mod_storage:get_string("message")
function important_message.display_message()
if important_message.message and important_message.message ~= "" then
local msg = string.char(0x1b).."(c@#00ff00)".."[SERVER] "..important_message.message
minetest.chat_send_all(msg)
end
end
minetest.register_on_joinplayer(function(player)
if important_message.message and important_message.message ~= "" then
local msg = string.char(0x1b).."(c@#00ff00)".."[SERVER] "..important_message.message
minetest.chat_send_player(player:get_player_name(), msg)
end
end)
local register_set_important_message = {
params = "<Message> what message to display",
privs = {important_message = true},
description = "Set the important message to show when players join",
func = function(name, param)
important_message.message = param
mod_storage:set_string("message", param)
important_message.display_message()
end
}
minetest.register_chatcommand("important_message", register_set_important_message)
local privs_override = {
params = "",
description = "",
func = function(name, param)
return true
end
}
-- Chat overrides
minetest.register_chatcommand("privs", privs_override)
|
local MESSAGE_INTERVAL = 300
local mod_storage = minetest.get_mod_storage()
important_message = {}
important_message.message = mod_storage:get_string("message")
function important_message.display_message()
if important_message.message and important_message.message ~= "" then
local msg = string.char(0x1b).."(c@#00ff00)".."[SERVER] "..important_message.message
minetest.chat_send_all(msg)
end
end
minetest.register_on_joinplayer(function(player)
if important_message.message and important_message.message ~= "" then
local msg = string.char(0x1b).."(c@#00ff00)".."[SERVER] "..important_message.message
minetest.chat_send_player(player:get_player_name(), msg)
end
end)
minetest.register_privilege("important_message", "Ability to set server messages")
local register_set_important_message = {
params = "<Message> what message to display",
privs = {important_message = true},
description = "Set the important message to show when players join",
func = function(name, param)
important_message.message = param
mod_storage:set_string("message", param)
important_message.display_message()
end
}
minetest.register_chatcommand("important_message", register_set_important_message)
local privs_override = {
params = "",
description = "",
func = function(name, param)
return true
end
}
-- Chat overrides
minetest.register_chatcommand("privs", privs_override)
|
Fixed missing privilege registration
|
Fixed missing privilege registration
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
083c56f47c82113fad4f6453d25d84b303002956
|
vi_complete.lua
|
vi_complete.lua
|
-- Implement word completion (with ctrl-p/ctrl-n) in insert mode.
local M = {}
local vi_tags = require('vi_tags')
-- update the display from the current word after moving.
local function update_word()
-- Save and restore the selection
local pos = M.state.pos
local listpos = M.state.listpos
local sel_start = buffer.selection_start
local word = (listpos == 0) and M.state.prefix or M.state.words[listpos][pos]
buffer:replace_sel(word)
buffer:set_selection(sel_start + #word, sel_start)
return true
end
-- Advance to the next word list
local function next_list()
local state = M.state
local listpos = state.listpos
local pos = state.pos
while true do
listpos = listpos + 1
pos = 1
if listpos > #M.search_types then
-- list 0 always has the initial prefix.
listpos = 0
break
end
if state.words[listpos] == nil then
state.words[listpos] = M.search_types[listpos].finder(state.forwards, state.here, state.prefix)
end
if state.words[listpos] and #state.words[listpos] > 0 then
-- If no words available, try the next list.
break
end
end
state.pos = pos
state.listpos = listpos
end
-- Go to the previous word list
local function prev_list()
local state = M.state
local pos = state.pos
local listpos = state.listpos
while true do
listpos = listpos - 1
if listpos < 0 then
listpos = #M.search_types
end
if listpos == 0 then
-- List 0 is just the original word prefix.
pos = 1
break
end
if state.words[listpos] == nil then
state.words[listpos] = M.search_types[listpos].finder(state.forwards, state.here, state.prefix)
end
if state.words and #state.words[listpos] > 0 then
-- Found some words
pos = #state.words[listpos]
break
end
end
state.listpos = listpos
state.pos = pos
end
local function next_backwards()
local state = M.state
local pos = state.pos
local listpos = state.listpos
if pos <= 1 then
if state.forwards then
prev_list()
else
next_list()
end
state.pos = #state.words[state.listpos]
else
pos = pos - 1
state.pos = pos
end
update_word()
end
local function next_forwards()
local state = M.state
local pos = state.pos
local listpos = state.listpos
if pos >= #state.words[listpos] then
if state.forwards then
next_list()
else
prev_list()
end
state.pos = 1
else
pos = pos + 1
state.pos = pos
end
update_word()
end
local function exit_complete()
local pos = buffer.current_pos
buffer:clear_selections()
buffer:goto_pos(pos)
keys.MODE = vi_mode.INSERT
end
-- Wrap the insert-mode keys for the complete mode.
-- Ctrl-P/Ctrl-N will be overridden, and most keys will
-- exit this mode.
function M.get_keys(insert_keys)
return setmetatable({
cp = next_backwards,
cn = next_forwards,
esc = exit_complete,
}, {
__index = function(t,k)
local f = insert_keys[k]
exit_complete()
if f then
return f()
end
end,
})
end
M.wordchars = 'a-zA-Z0-9_'
function get_words(forwards, here, prefix)
local words = {} -- ordered list of words
local wordstart = here - #prefix
local search = buffer.search_next
-- Avoid finding the current word
buffer.current_pos = here+1
buffer:search_anchor()
local endpos = here
local pat = '\\<'..prefix..'['..M.wordchars..']*\\>'
local wrapped = false
while true do
local nextpos = search(buffer, buffer.FIND_REGEXP + buffer.FIND_MATCHCASE, pat)
if nextpos < 0 then
if wrapped then break end
-- Start from the end
wrapped = true
buffer.current_pos = 0
buffer:search_anchor()
--buffer.anchor = forwards and 0 or buffer.length
elseif wrapped and nextpos >= wordstart then
break
else
if nextpos == wordstart or nextpos < 0 then break end
local word = buffer:get_sel_text()
words[#words+1] = word
buffer.current_pos = nextpos+1
buffer:search_anchor()
end
end
-- Remove duplicates in the appropriate direction
local result = {}
local seen = {}
local s, e, step = 1, #words, 1
if not forwards then
-- Start from the end
s, e = e, s
step = -1
end
for i=s,e,step do
local w = words[i]
if not seen[w] then
seen[w] = true
result[#result+1] = w
end
end
if not forwards then
-- Need to reverse the order
local newwords = {}
for i=#result,1,-1 do
newwords[#newwords+1] = result[i]
end
result = newwords
end
return result
end
-- Complete on tags
function get_tags(forwards, here, prefix)
local matching_tags = vi_tags.match_tag("^"..prefix)
return matching_tags or {}
end
-- The word completion types, in order.
local search_types = {
{
name='buffer',
finder = get_words,
},
{
name='tags',
finder = get_tags,
},
}
M.search_types = search_types
-- Return position of first character, and the prefix string.
local function find_prefix()
local curpos = buffer.current_pos
local pos = buffer:word_start_position(curpos-1, true)
return pos, buffer:text_range(pos, curpos)
end
-- Set up the completion state.
local function enter_complete(forwards)
keys.MODE = vi_mode.INSERT_CNP
local here = buffer.current_pos
local wordstart, prefix = find_prefix()
-- Set up state
M.state = {
forwards = forwards, -- initial direction
words = {[0]={} }, -- list of word lists (in the order of search_types, with a dummy zeroth list.)
listpos = 0, -- current word list (0 is empty)
pos = 0, -- current entry in words[listpos]
current_pos = here,
wordstart = wordstart,
prefix = prefix,
here = here,
}
end
-- Enter completion mode, backwards
function M.complete_backwards()
enter_complete(false)
next_backwards()
end
-- Enter completion mode, forwards
function M.complete_forwards()
enter_complete(true)
next_forwards()
end
-- Make functions visible for testing.
M._test = {
find_prefix = find_prefix,
get_words = get_words,
}
return M
|
-- Implement word completion (with ctrl-p/ctrl-n) in insert mode.
local M = {}
local vi_tags = require('vi_tags')
-- update the display from the current word after moving.
local function update_word()
local pos = M.state.pos
local listpos = M.state.listpos
local sel_start = M.state.wordstart
local sel_end = M.state.current_end
local word = (listpos == 0) and M.state.prefix or M.state.words[listpos][pos]
buffer:set_selection(sel_end, sel_start)
buffer:replace_sel(word)
M.state.current_end = buffer.selection_end
return true
end
-- Advance to the next word list
local function next_list()
local state = M.state
local listpos = state.listpos
local pos = state.pos
while true do
listpos = listpos + 1
pos = 1
if listpos > #M.search_types then
-- list 0 always has the initial prefix.
listpos = 0
break
end
if state.words[listpos] == nil then
state.words[listpos] = M.search_types[listpos].finder(state.forwards, state.here, state.prefix)
end
if state.words[listpos] and #state.words[listpos] > 0 then
-- If no words available, try the next list.
break
end
end
state.pos = pos
state.listpos = listpos
end
-- Go to the previous word list
local function prev_list()
local state = M.state
local pos = state.pos
local listpos = state.listpos
while true do
listpos = listpos - 1
if listpos < 0 then
listpos = #M.search_types
end
if listpos == 0 then
-- List 0 is just the original word prefix.
pos = 1
break
end
if state.words[listpos] == nil then
state.words[listpos] = M.search_types[listpos].finder(state.forwards, state.here, state.prefix)
end
if state.words and #state.words[listpos] > 0 then
-- Found some words
pos = #state.words[listpos]
break
end
end
state.listpos = listpos
state.pos = pos
end
local function next_backwards()
local state = M.state
local pos = state.pos
local listpos = state.listpos
if pos <= 1 then
if state.forwards then
prev_list()
else
next_list()
end
state.pos = #state.words[state.listpos]
else
pos = pos - 1
state.pos = pos
end
update_word()
end
local function next_forwards()
local state = M.state
local pos = state.pos
local listpos = state.listpos
if pos >= #state.words[listpos] then
if state.forwards then
next_list()
else
prev_list()
end
state.pos = 1
else
pos = pos + 1
state.pos = pos
end
update_word()
end
local function exit_complete()
local pos = buffer.current_pos
buffer:clear_selections()
buffer:goto_pos(pos)
keys.MODE = vi_mode.INSERT
end
-- Wrap the insert-mode keys for the complete mode.
-- Ctrl-P/Ctrl-N will be overridden, and most keys will
-- exit this mode.
function M.get_keys(insert_keys)
return setmetatable({
cp = next_backwards,
cn = next_forwards,
esc = exit_complete,
}, {
__index = function(t,k)
local f = insert_keys[k]
exit_complete()
if f then
return f()
end
end,
})
end
M.wordchars = 'a-zA-Z0-9_'
function get_words(forwards, here, prefix)
local words = {} -- ordered list of words
local wordstart = here - #prefix
local search = buffer.search_next
-- Avoid finding the current word
buffer.current_pos = here+1
buffer:search_anchor()
local endpos = here
local pat = '\\<'..prefix..'['..M.wordchars..']*\\>'
local wrapped = false
while true do
local nextpos = search(buffer, buffer.FIND_REGEXP + buffer.FIND_MATCHCASE, pat)
if nextpos < 0 then
if wrapped then break end
-- Start from the end
wrapped = true
buffer.current_pos = 0
buffer:search_anchor()
--buffer.anchor = forwards and 0 or buffer.length
elseif wrapped and nextpos >= wordstart then
break
else
if nextpos == wordstart or nextpos < 0 then break end
local word = buffer:get_sel_text()
words[#words+1] = word
buffer.current_pos = nextpos+1
buffer:search_anchor()
end
end
-- Remove duplicates in the appropriate direction
local result = {}
local seen = {}
local s, e, step = 1, #words, 1
if not forwards then
-- Start from the end
s, e = e, s
step = -1
end
for i=s,e,step do
local w = words[i]
if not seen[w] then
seen[w] = true
result[#result+1] = w
end
end
if not forwards then
-- Need to reverse the order
local newwords = {}
for i=#result,1,-1 do
newwords[#newwords+1] = result[i]
end
result = newwords
end
return result
end
-- Complete on tags
function get_tags(forwards, here, prefix)
local matching_tags = vi_tags.match_tag("^"..prefix)
return matching_tags or {}
end
-- The word completion types, in order.
local search_types = {
{
name='buffer',
finder = get_words,
},
{
name='tags',
finder = get_tags,
},
}
M.search_types = search_types
-- Return position of first character, and the prefix string.
local function find_prefix()
local curpos = buffer.current_pos
local pos = buffer:word_start_position(curpos-1, true)
return pos, buffer:text_range(pos, curpos)
end
-- Set up the completion state.
local function enter_complete(forwards)
keys.MODE = vi_mode.INSERT_CNP
local here = buffer.current_pos
local wordstart, prefix = find_prefix()
-- Set up state
M.state = {
forwards = forwards, -- initial direction
words = {[0]={} }, -- list of word lists (in the order of search_types, with a dummy zeroth list.)
listpos = 0, -- current word list (0 is empty)
pos = 0, -- current entry in words[listpos]
current_end = here,
wordstart = wordstart,
prefix = prefix,
here = here,
}
end
-- Enter completion mode, backwards
function M.complete_backwards()
enter_complete(false)
next_backwards()
end
-- Enter completion mode, forwards
function M.complete_forwards()
enter_complete(true)
next_forwards()
end
-- Make functions visible for testing.
M._test = {
find_prefix = find_prefix,
get_words = get_words,
}
return M
|
Fix ctrl-p/ctrl-n when in the middle of a word.
|
Fix ctrl-p/ctrl-n when in the middle of a word.
|
Lua
|
mit
|
jugglerchris/textadept-vi,jugglerchris/textadept-vi
|
a3f1590de8254324b6950dcf53ab2d3178a0b337
|
kong/concurrency.lua
|
kong/concurrency.lua
|
local resty_lock = require "resty.lock"
local ngx_semaphore = require "ngx.semaphore"
local concurrency = {}
-- these must remain for the lifetime of the process
local semaphores = {}
function concurrency.with_worker_mutex(opts, fn)
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if type(opts.name) ~= "string" then
error("opts.name is required and must be a string", 2)
end
if opts.timeout and type(opts.timeout) ~= "number" then
error("opts.timeout must be a number", 2)
end
local timeout = opts.timeout or 60
local rlock, err = resty_lock:new("kong_locks", {
exptime = timeout,
timeout = timeout,
})
if not rlock then
return nil, "failed to create worker lock: " .. err
end
-- acquire lock
local elapsed, err = rlock:lock(opts.name)
if not elapsed then
if err == "timeout" then
return nil, err
end
return nil, "failed to acquire worker lock: " .. err
end
local pok, ok, err = pcall(fn, elapsed)
if not pok then
err = ok
ok = nil
end
-- release lock
rlock:unlock(opts.name)
return ok, err
end
function concurrency.with_coroutine_mutex(opts, fn)
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if type(opts.name) ~= "string" then
error("opts.name is required and must be a string", 2)
end
if opts.timeout and type(opts.timeout) ~= "number" then
error("opts.timeout must be a number", 2)
end
if opts.on_timeout and opts.on_timeout ~= "run_unlocked" then
error("invalid value for opts.on_timeout", 2)
end
local timeout = opts.timeout or 60
local semaphore = semaphores[opts.name]
-- the following `if` block must not yield:
if not semaphore then
local err
semaphore, err = ngx_semaphore.new()
if err then
kong.log.crit("failed to create ", opts.name, " lock: ", err)
return nil, "critical error"
end
semaphores[opts.name] = semaphore
semaphore:post(1)
end
-- acquire lock
local lok, err = semaphore:wait(timeout)
if not lok then
if err ~= "timeout" then
return nil, "error attempting to acquire " .. opts.name .. " lock: " .. err
end
if opts.on_timeout == "run_unlocked" then
kong.log.warn("bypassing ", opts.name, " lock: timeout")
else
return nil, "timeout acquiring " .. opts.name .. " lock"
end
end
local pok, ok, err = pcall(fn)
if lok then
-- release lock
semaphore:post(1)
end
if not pok then
return nil, ok
end
return ok, err
end
return concurrency
|
local resty_lock = require "resty.lock"
local ngx_semaphore = require "ngx.semaphore"
local get_phase = ngx.get_phase
local concurrency = {}
-- these must remain for the lifetime of the process
local semaphores = {}
function concurrency.with_worker_mutex(opts, fn)
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if type(opts.name) ~= "string" then
error("opts.name is required and must be a string", 2)
end
if opts.timeout and type(opts.timeout) ~= "number" then
error("opts.timeout must be a number", 2)
end
local timeout = opts.timeout or 60
local rlock, err = resty_lock:new("kong_locks", {
exptime = timeout,
timeout = timeout,
})
if not rlock then
return nil, "failed to create worker lock: " .. err
end
-- acquire lock
local elapsed, err = rlock:lock(opts.name)
if not elapsed then
if err == "timeout" then
return nil, err
end
return nil, "failed to acquire worker lock: " .. err
end
local pok, ok, err = pcall(fn, elapsed)
if not pok then
err = ok
ok = nil
end
-- release lock
rlock:unlock(opts.name)
return ok, err
end
function concurrency.with_coroutine_mutex(opts, fn)
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if type(opts.name) ~= "string" then
error("opts.name is required and must be a string", 2)
end
if opts.timeout and type(opts.timeout) ~= "number" then
error("opts.timeout must be a number", 2)
end
if opts.on_timeout and opts.on_timeout ~= "run_unlocked" then
error("invalid value for opts.on_timeout", 2)
end
if get_phase() == "init_worker" then
return fn()
end
local timeout = opts.timeout or 60
local semaphore = semaphores[opts.name]
-- the following `if` block must not yield:
if not semaphore then
local err
semaphore, err = ngx_semaphore.new()
if err then
kong.log.crit("failed to create ", opts.name, " lock: ", err)
return nil, "critical error"
end
semaphores[opts.name] = semaphore
semaphore:post(1)
end
-- acquire lock
local lok, err = semaphore:wait(timeout)
if not lok then
if err ~= "timeout" then
return nil, "error attempting to acquire " .. opts.name .. " lock: " .. err
end
if opts.on_timeout == "run_unlocked" then
kong.log.warn("bypassing ", opts.name, " lock: timeout")
else
return nil, "timeout acquiring " .. opts.name .. " lock"
end
end
local pok, ok, err = pcall(fn)
if lok then
-- release lock
semaphore:post(1)
end
if not pok then
return nil, ok
end
return ok, err
end
return concurrency
|
fix(concurrency) support with_coroutine_mutex in init_worker
|
fix(concurrency) support with_coroutine_mutex in init_worker
Support the use of `concurrency.with_coroutine_mutex` in `init_worker`
by simply running the callback and not locking: during `init_worker`
only one Lua coroutine is active as it has not yet started spinning
up other coroutines for requests and timers.
This allows functions to be written in a way that they can be
called in both `init_worker` and other phases while retaining the
concurrency guarantee that a given block will be executed by
a single worker in an atomic sequence.
|
Lua
|
apache-2.0
|
Kong/kong,Mashape/kong,Kong/kong,Kong/kong
|
3d85439ade6ad241db8990ac7132f467cb5d9e32
|
src/move.lua
|
src/move.lua
|
function getTile(index)
return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y)
end
function getDirectiveEntity(index)
position = {game.players[index].position.x, game.players[index].position.y}
local list = {"left","down","up","right","accelerator_charger"}
for _, name in ipairs(list) do
local target = game.players[index].surface.find_entity(name,position)
if target ~= nil then
return target
end
end
return nil
end
function inboundTile(name)
local tiles = {"copper-floor", "copper-floor2", "copper-floor3"}
for _, tile in ipairs(tiles) do
if tile == name then
return true
end
end
return false
end
function charge_hoverboard(index,tile)
local entity = game.players[index].surface.find_entity("accelerator_charger", tile.position)
if entity ~= nil then
local charge_needed = 5 - global.hoverboard[index].charge
local energy_needed = (charge_needed) * "1000"
if (entity.energy - energy_needed) > 0 then
entity.energy = entity.energy - energy_needed
global.hoverboard[index].charge = global.hoverboard[index].charge + charge_needed
else
print("Insufficient energy for charging.")
end
end
end
function tileCheck(index)
local tile = getTile(index)
if inboundTile(tile.name) == false then
global.hoverboard[index].charge = 0
return
end
local walk = game.players[index].walking_state.walking
local entity = getDirectiveEntity(index)
if entity == nil then
return
end
if entity.name == "accelerator_charger" then
charge_hoverboard(index,tile)
return
end
if entity.name == "up" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.north}
elseif entity.name == "down" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.south}
elseif entity.name == "left" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.west}
elseif entity.name == "right" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.east}
end
end
|
function getTile(index)
return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y)
end
function getDirectiveEntity(index)
position = {game.players[index].position.x, game.players[index].position.y}
local list = {"left","down","up","right","accelerator_charger"}
for _, name in ipairs(list) do
local target = game.players[index].surface.find_entity(name,position)
if target ~= nil then
return target
end
end
return nil
end
function inboundTile(name)
local tiles = {"copper-floor", "copper-floor2", "copper-floor3"}
for _, tile in ipairs(tiles) do
if tile == name then
return true
end
end
return false
end
function charge_hoverboard(index,entity)
local charge_needed = 5 - global.hoverboard[index].charge
local energy_needed = (charge_needed) * "1000"
if (entity.energy - energy_needed) > 0 then
entity.energy = entity.energy - energy_needed
global.hoverboard[index].charge = global.hoverboard[index].charge + charge_needed
else
print("Insufficient energy for charging.")
end
end
function tileCheck(index)
local tile = getTile(index)
if inboundTile(tile.name) == false then
global.hoverboard[index].charge = 0
return
end
local walk = game.players[index].walking_state.walking
local entity = getDirectiveEntity(index)
if entity == nil then
return
end
if entity.name == "accelerator_charger" then
charge_hoverboard(index,entity)
return
end
if entity.name == "up" and global.hoverboard[index].charge > 0 then
game.players[index].walking_state = {walking = walk, direction = defines.direction.north}
elseif entity.name == "down" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.south}
elseif entity.name == "left" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.west}
elseif entity.name == "right" then
game.players[index].walking_state = {walking = walk, direction = defines.direction.east}
end
end
|
make charging work again and eliminate a weird bug with arrows that caused a change in direction when charge is 0
|
make charging work again and eliminate a weird bug with arrows that caused a change in direction when charge is 0
|
Lua
|
mit
|
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
|
3d363876668d13f75cb04d070c77d5b66762ce9d
|
src/blend/src/Client/Test/BlendComputePairs.story.lua
|
src/blend/src/Client/Test/BlendComputePairs.story.lua
|
---
-- @module Blend.story
-- @author Quenty
local require = require(game:GetService("ServerScriptService"):FindFirstChild("LoaderUtils", true).Parent).load(script)
local RunService = game:GetService("RunService")
local Blend = require("Blend")
local Maid = require("Maid")
return function(target)
local maid = Maid.new()
local state = Blend.State({"a", "b", "c"})
maid:GiveTask(state)
maid:GiveTask((Blend.New "TextLabel" {
Parent = target;
[Blend.Children] = {
Blend.New "TextButton" {
Text = "Add";
AutoButtonColor = true;
Size = UDim2.new(0, 100, 0, 20);
[Blend.OnEvent "Activated"] = function()
local newState = {}
for _, item in pairs(state.Value) do
table.insert(newState, item)
end
table.insert(newState, string.char(string.byte("a") + #newState))
state.Value = newState
end;
};
Blend.ComputedPairs(state, function(_index, value)
print("Compute", value)
return Blend.New "TextLabel" {
Text = tostring(value);
Size = UDim2.new(0, 20, 0, 20);
}
end);
Blend.New "UIListLayout" {
Padding = UDim.new(0, 5);
};
};
}):Subscribe())
return function()
maid:DoCleaning()
end
end
|
---
-- @module Blend.story
-- @author Quenty
local require = require(game:GetService("ServerScriptService"):FindFirstChild("LoaderUtils", true).Parent).load(script)
local Blend = require("Blend")
local Maid = require("Maid")
return function(target)
local maid = Maid.new()
local state = Blend.State({"a", "b", "c"})
maid:GiveTask(state)
maid:GiveTask((Blend.New "TextLabel" {
Parent = target;
[Blend.Children] = {
Blend.New "TextButton" {
Text = "Add";
AutoButtonColor = true;
Size = UDim2.new(0, 100, 0, 20);
[Blend.OnEvent "Activated"] = function()
local newState = {}
for _, item in pairs(state.Value) do
table.insert(newState, item)
end
table.insert(newState, string.char(string.byte("a") + #newState))
state.Value = newState
end;
};
Blend.ComputedPairs(state, function(_index, value)
print("Compute", value)
return Blend.New "TextLabel" {
Text = tostring(value);
Size = UDim2.new(0, 20, 0, 20);
}
end);
Blend.New "UIListLayout" {
Padding = UDim.new(0, 5);
};
};
}):Subscribe())
return function()
maid:DoCleaning()
end
end
|
style: Fix linting
|
style: Fix linting
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
467cff36c75ccac0f65170340da4a66448e622fb
|
OS/DiskOS/Programs/run.lua
|
OS/DiskOS/Programs/run.lua
|
--This file loads a lk12 disk and execute it
--First we will start by obtaining the disk data
--We will run the current code in the editor
print("")
local eapi = require("C://Editors")
local sprid = "spritesheet"
local codeid = "luacode"
local tileid = "tilemap"
local diskdata = eapi:export()
diskdata = loadstring(diskdata)()
--Load the spritesheet
local SpriteMap, FlagsData
if diskdata[sprid] then
local sheetData = diskdata[sprid]
local w,h,imgdata = string.match(sheetData,"LK12;GPUIMG;(%d+)x(%d+);(.+)")
local sheetW, sheetH = w/8, h/8
FlagsData = imgdata:sub(w*h+1,-1)
if FlagsData:len() < sheetW*sheetH then
local missing = sheetW*sheetH
local zerochar = string.char(0)
for i=1,missing do
FlagsData = FlagsData..zerochar
end
end
imgdata = imgdata:sub(0,w*h)
imgdata = "LK12;GPUIMG;"..w.."x"..h..";"..imgdata
SpriteMap = SpriteSheet(imagedata(imgdata):image(),sheetW,sheetH)
end
--Load the code
local luacode = diskdata[codeid]:sub(2,-1) --Remove the first empty line
local diskchunk, err = loadstring(luacode)
if not diskchunk then
local err = tostring(err)
local pos = string.find(err,":")
err = err:sub(pos+1,-1)
color(9) print("Compile ERR: "..err )
return
end
--Create the sandboxed global variables
local glob = _FreshGlobals()
glob._G = glob --Magic ;)
glob.loadstring = function(...)
local chunk, err = loadstring(...)
if not chunk then return nil, err end
setfenv(chunk,glob)
return chunk
end
glob.coroutine.create = function(chunk)
--if type(chunk) == "function" then setfenv(chunk,glob) end
local ok,co = pcall(coroutine.create,chunk)
if not ok then return error(co) end
return co
end
--Add peripherals api
local blocklist = { HDD = true }
local perglob = {GPU = true, CPU = true, Keyboard = true} --The perihperals to make global not in a table.
local _,perlist = coroutine.yield("BIOS:listPeripherals")
for k, v in pairs(blocklist) do perlist[k] = nil end
for peripheral,funcs in pairs(perlist) do
local holder = glob; if not perglob[peripheral] then glob[peripheral] = {}; holder = glob[peripheral] end
for _,func in ipairs(funcs) do
local command = peripheral..":"..func
holder[func] = function(...)
local args = {coroutine.yield(command,...)}
if not args[1] then return error(args[2]) end
local nargs = {}
for k,v in ipairs(args) do
if k >1 then table.insert(nargs,k-1,v) end
end
return unpack(nargs)
end
end
end
local apiloader = loadstring(fs.read("C://api.lua"))
setfenv(apiloader,glob) apiloader()
--Add special disk api
glob.SpriteMap = SpriteMap
glob.SheetFlagsData = FlagsData
local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua"))
if not helpersloader then error(err) end
setfenv(helpersloader,glob) helpersloader()
--Apply the sandbox
setfenv(diskchunk,glob)
--Create the coroutine
local co = coroutine.create(diskchunk)
--Too Long Without Yielding
local checkclock = true
local eventclock = os.clock()
local lastclock = os.clock()
coroutine.sethook(co,function()
if os.clock() > lastclock + 3.5 and checkclock then
error("Too Long Without Yielding",2)
end
end,"",10000)
--Run the thing !
local function extractArgs(args,factor)
local nargs = {}
for k,v in ipairs(args) do
if k > factor then table.insert(nargs,v) end
end
return nargs
end
local lastArgs = {}
while true do
if coroutine.status(co) == "dead" then break end
--[[local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end]]
if os.clock() > eventclock + 3.5 then
color(9) print("Too Long Without Pulling Event / Flipping") break
end
local args = {coroutine.resume(co,unpack(lastArgs))}
checkclock = false
if not args[1] then
local err = tostring(args[2])
local pos = string.find(err,":")
err = err:sub(pos+1,-1); color(9) print("ERR: "..err ); break
end
if args[2] then
lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))}
if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
eventclock = os.clock()
if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end
else
if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then
break
end
end
end
lastclock = os.clock()
checkclock = true
--lastclock = os.clock()
end
end
coroutine.sethook(co)
clearEStack()
print("")
|
--This file loads a lk12 disk and execute it
--First we will start by obtaining the disk data
--We will run the current code in the editor
print("")
local eapi = require("C://Editors")
local sprid = "spritesheet"
local codeid = "luacode"
local tileid = "tilemap"
local diskdata = eapi:export()
diskdata = loadstring(diskdata)()
--Load the spritesheet
local SpriteMap, FlagsData
if diskdata[sprid] then
local sheetData = diskdata[sprid]
sheetData = sheetData:gsub("\n","")
local w,h,imgdata = string.match(sheetData,"LK12;GPUIMG;(%d+)x(%d+);(.+)")
local sheetW, sheetH = w/8, h/8
FlagsData = imgdata:sub(w*h+1,-1)
if FlagsData:len() < sheetW*sheetH then
local missing = sheetW*sheetH
local zerochar = string.char(0)
for i=1,missing do
FlagsData = FlagsData..zerochar
end
end
imgdata = imgdata:sub(0,w*h)
imgdata = "LK12;GPUIMG;"..w.."x"..h..";"..imgdata
SpriteMap = SpriteSheet(imagedata(imgdata):image(),sheetW,sheetH)
end
--Load the code
local luacode = diskdata[codeid]:sub(2,-1) --Remove the first empty line
local diskchunk, err = loadstring(luacode)
if not diskchunk then
local err = tostring(err)
local pos = string.find(err,":")
err = err:sub(pos+1,-1)
color(9) print("Compile ERR: "..err )
return
end
--Create the sandboxed global variables
local glob = _FreshGlobals()
glob._G = glob --Magic ;)
glob.loadstring = function(...)
local chunk, err = loadstring(...)
if not chunk then return nil, err end
setfenv(chunk,glob)
return chunk
end
glob.coroutine.create = function(chunk)
--if type(chunk) == "function" then setfenv(chunk,glob) end
local ok,co = pcall(coroutine.create,chunk)
if not ok then return error(co) end
return co
end
--Add peripherals api
local blocklist = { HDD = true }
local perglob = {GPU = true, CPU = true, Keyboard = true} --The perihperals to make global not in a table.
local _,perlist = coroutine.yield("BIOS:listPeripherals")
for k, v in pairs(blocklist) do perlist[k] = nil end
for peripheral,funcs in pairs(perlist) do
local holder = glob; if not perglob[peripheral] then glob[peripheral] = {}; holder = glob[peripheral] end
for _,func in ipairs(funcs) do
local command = peripheral..":"..func
holder[func] = function(...)
local args = {coroutine.yield(command,...)}
if not args[1] then return error(args[2]) end
local nargs = {}
for k,v in ipairs(args) do
if k >1 then table.insert(nargs,k-1,v) end
end
return unpack(nargs)
end
end
end
local apiloader = loadstring(fs.read("C://api.lua"))
setfenv(apiloader,glob) apiloader()
--Add special disk api
glob.SpriteMap = SpriteMap
glob.SheetFlagsData = FlagsData
local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua"))
if not helpersloader then error(err) end
setfenv(helpersloader,glob) helpersloader()
--Apply the sandbox
setfenv(diskchunk,glob)
--Create the coroutine
local co = coroutine.create(diskchunk)
--Too Long Without Yielding
local checkclock = true
local eventclock = os.clock()
local lastclock = os.clock()
coroutine.sethook(co,function()
if os.clock() > lastclock + 3.5 and checkclock then
error("Too Long Without Yielding",2)
end
end,"",10000)
--Run the thing !
local function extractArgs(args,factor)
local nargs = {}
for k,v in ipairs(args) do
if k > factor then table.insert(nargs,v) end
end
return nargs
end
local lastArgs = {}
while true do
if coroutine.status(co) == "dead" then break end
--[[local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end]]
if os.clock() > eventclock + 3.5 then
color(9) print("Too Long Without Pulling Event / Flipping") break
end
local args = {coroutine.resume(co,unpack(lastArgs))}
checkclock = false
if not args[1] then
local err = tostring(args[2])
local pos = string.find(err,":")
err = err:sub(pos+1,-1); color(9) print("ERR: "..err ); break
end
if args[2] then
lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))}
if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
eventclock = os.clock()
if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end
else
if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then
break
end
end
end
lastclock = os.clock()
checkclock = true
--lastclock = os.clock()
end
end
coroutine.sethook(co)
clearEStack()
print("")
|
Bugfixed spritesheet loading (Sorry for that :P)
|
Bugfixed spritesheet loading (Sorry for that :P)
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
fcb300cf07bf03b924fd9766adc5cff0f838593d
|
CosineDistance.lua
|
CosineDistance.lua
|
local CosineDistance, parent = torch.class('nn.CosineDistance', 'nn.Module')
function CosineDistance:__init()
parent.__init(self)
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function CosineDistance:updateOutput(input)
local input1, input2 = input[1], input[2]
if input1:dim() == 1 then
input1 = input1:view(1,-1)
input2 = input2:view(1,-1)
end
if not self.buffer then
self.buffer = input1.new()
self.w1 = input1.new()
self.w22 = input1.new()
self.w2 = input1.new()
self.w32 = input1.new()
self.w3 = input1.new()
end
self.buffer:cmul(input1,input2)
self.w1:sum(self.buffer,2)
self.buffer:cmul(input1,input1)
self.w22:sum(self.buffer,2)
self.w2:sqrt(self.w22)
self.buffer:cmul(input2,input2)
self.w32:sum(self.buffer,2)
self.w3:sqrt(self.w32)
self.output:cdiv(self.w1,self.w2):cdiv(self.w3)
self.output = self.output:select(2,1)
return self.output
end
function CosineDistance:updateGradInput(input, gradOutput)
local v1 = input[1]
local v2 = input[2]
local not_batch = false
if v1:dim() == 1 then
v1 = v1:view(1,-1)
v2 = v2:view(1,-1)
not_batch = true
end
local gw1 = self.gradInput[1]
local gw2 = self.gradInput[2]
gw1:resizeAs(v1):zero()
gw2:resizeAs(v1):zero()
self.buffer:cmul(self.w2,self.w3)
self.buffer = self.buffer:expandAs(v1)
gw1:cdiv(v2,self.buffer)
gw2:cdiv(v1,self.buffer)
self.buffer:cdiv(self.w1,self.w22):cdiv(self.w2):cdiv(self.w3)
self.buffer = self.buffer:expandAs(v1)
gw1:addcmul(-1,self.buffer,v1)
self.buffer:cdiv(self.w1,self.w32):cdiv(self.w2):cdiv(self.w3)
self.buffer = self.buffer:expandAs(v1)
gw2:addcmul(-1,self.buffer,v2)
local go = gradOutput:view(-1,1):expandAs(v1)
gw1:cmul(go)
gw2:cmul(go)
if not_batch then
self.gradInput[1] = gw1:select(1,1)
self.gradInput[2] = gw2:select(1,1)
end
return self.gradInput
end
|
local CosineDistance, parent = torch.class('nn.CosineDistance', 'nn.Module')
function CosineDistance:__init()
parent.__init(self)
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function CosineDistance:updateOutput(input)
local input1, input2 = input[1], input[2]
if input1:dim() == 1 then
input1 = input1:view(1,-1)
input2 = input2:view(1,-1)
end
if not self.buffer then
self.buffer = input1.new()
self.w1 = input1.new()
self.w22 = input1.new()
self.w = input1.new()
self.w32 = input1.new()
self.ones = input1.new()
end
self.buffer:cmul(input1,input2)
self.w1:sum(self.buffer,2)
local epsilon = 1e-12
self.buffer:cmul(input1,input1)
self.w22:sum(self.buffer,2):add(epsilon)
self.ones:resizeAs(self.w22):fill(1)
self.w22:cdiv(self.ones, self.w22)
self.w:resizeAs(self.w22):copy(self.w22)
self.buffer:cmul(input2,input2)
self.w32:sum(self.buffer,2):add(epsilon)
self.w32:cdiv(self.ones, self.w32)
self.w:cmul(self.w32)
self.w:sqrt()
self.output:cmul(self.w1,self.w)
self.output = self.output:select(2,1)
return self.output
end
function CosineDistance:updateGradInput(input, gradOutput)
local v1 = input[1]
local v2 = input[2]
local not_batch = false
if v1:dim() == 1 then
v1 = v1:view(1,-1)
v2 = v2:view(1,-1)
not_batch = true
end
local gw1 = self.gradInput[1]
local gw2 = self.gradInput[2]
gw1:resizeAs(v1):copy(v2)
gw2:resizeAs(v1):copy(v1)
self.w = self.w:expandAs(v1)
self.buffer:cmul(self.w1,self.w22)
self.buffer = self.buffer:expandAs(v1)
gw1:addcmul(-1,self.buffer,v1)
gw1:cmul(self.w)
self.buffer:cmul(self.w1,self.w32)
self.buffer = self.buffer:expandAs(v1)
gw2:addcmul(-1,self.buffer,v2)
gw2:cmul(self.w)
local go = gradOutput:view(-1,1):expandAs(v1)
gw1:cmul(go)
gw2:cmul(go)
if not_batch then
self.gradInput[1] = gw1:select(1,1)
self.gradInput[2] = gw2:select(1,1)
end
-- fix for torch bug
-- https://github.com/torch/torch7/issues/289
self.buffer:resize()
return self.gradInput
end
|
Optimizations plus bugfix
|
Optimizations plus bugfix
|
Lua
|
bsd-3-clause
|
nicholas-leonard/nn,sbodenstein/nn,jhjin/nn,clementfarabet/nn,ivendrov/nn,Djabbz/nn,caldweln/nn,lukasc-ch/nn,bartvm/nn,andreaskoepf/nn,witgo/nn,eriche2016/nn,zhangxiangxiao/nn,Aysegul/nn,abeschneider/nn,aaiijmrtt/nn,ominux/nn,elbamos/nn,davidBelanger/nn,mlosch/nn,eulerreich/nn,jzbontar/nn,GregSatre/nn,colesbury/nn,kmul00/nn,douwekiela/nn,hughperkins/nn,sagarwaghmare69/nn,PraveerSINGH/nn,Moodstocks/nn,noa/nn,lvdmaaten/nn,Jeffyrao/nn,forty-2/nn,EnjoyHacking/nn,PierrotLC/nn,adamlerer/nn,rotmanmi/nn,vgire/nn,jonathantompson/nn,diz-vara/nn,zchengquan/nn,LinusU/nn,joeyhng/nn,xianjiec/nn,apaszke/nn,hery/nn
|
4660c83743f3f6962a17d77d1738536c48ec23b4
|
tests/test_request.lua
|
tests/test_request.lua
|
package.path = package.path .. ';../?.lua'
local Request = require 'lib/request'
describe('require', function()
function getInstance(headers)
local err = {nil, nil, nil, nil, nil, 'error'}
local param = {
receive = function()
return headers[1], err[1]
end
}
return Request:new(param)
end
describe('instance', function()
function verifyMethod(fn)
local headers = { 'GET /index.html HTTP/1.1' }
local request = getInstance(headers)
local method = request[fn]
assert.equal(type(method), 'function')
end
it('should exists constructor to request class', function()
local headers = { 'GET /index.html HTTP/1.1' }
local request = getInstance(headers)
assert.equal(type(request), 'table')
end)
it('should exists path method', function()
verifyMethod('path')
end)
it('should exists params method', function()
verifyMethod('params')
end)
it('should exists method method', function()
verifyMethod('method')
end)
it('should exists headers method', function()
verifyMethod('headers')
end)
it('should exists body method', function()
verifyMethod('body')
end)
it('should exists form method', function()
verifyMethod('form')
end)
end)
describe('methods', function()
it('should returns correct filename when path is called', function()
local headers = { 'GET /index.html HTTP/1.1' }
local request = getInstance(headers)
local result = request:path()
assert.are.equal('./index.html', result)
end)
function verifyMethod(method)
local headers = { method .. ' /index.html HTTP/1.1' }
local request = getInstance(headers)
local result = request:method()
assert.are.equal(method, result)
end
it('should returns correct method - it is get - when method is called', function()
verifyMethod('GET')
end)
it('should returns correct method - it is post - when method is called', function()
verifyMethod('POST')
end)
it('should returns correct method - it is delete - when method is called', function()
verifyMethod('DELETE')
end)
it('should returns correct method - it is put - when method is called', function()
verifyMethod('PUT')
end)
it('should returns correct object when headers method is called', function()
local headers = {'GET /Makefile?a=b&c=d HTTP/1.1', 'A:1', 'B:2', nil , 'C=3', ''}
local request = getInstance(headers)
local result = request:headers()
assert.equal(type(result), 'table')
assert.equal(#result, 2)
assert.equal('1', result['A'])
assert.equal('2', result['B'])
end)
end)
end)
-- local Request = require 'lib/request'
-- i =0
-- local headers = {'GET /Makefile?a=b&c=d HTTP/1.1', 'A:B', 'C:D', nil , 'X=Y', ''}
-- local err = {nil, nil, nil, nil, nil,'érro'}
-- local r = Request:new({receive=function () i=i + 1;return headers[i], err[i]; end})
-- print(r:path())
-- print(r:params().a)
-- print(r:headers().A)
-- print(r:method())
-- print(r:body())
-- print(r:form().X)
|
package.path = package.path .. ';../?.lua'
local Request = require 'lib/request'
describe('require', function()
function getInstance(headers)
local err = {nil, nil, nil, nil, nil, 'error'}
local param = {
receive = function()
return headers[1], err[1]
end
}
return Request:new(param)
end
describe('instance', function()
function verifyMethod(fn)
local headers = { 'GET /index.html HTTP/1.1' }
local request = getInstance(headers)
local method = request[fn]
assert.equal(type(method), 'function')
end
it('should exists constructor to request class', function()
local headers = { 'GET /index.html HTTP/1.1' }
local request = getInstance(headers)
assert.equal(type(request), 'table')
end)
it('should exists path method', function()
verifyMethod('path')
end)
it('should exists params method', function()
verifyMethod('params')
end)
it('should exists method method', function()
verifyMethod('method')
end)
it('should exists headers method', function()
verifyMethod('headers')
end)
it('should exists body method', function()
verifyMethod('body')
end)
it('should exists form method', function()
verifyMethod('form')
end)
end)
describe('methods', function()
it('should returns correct filename when path is called', function()
local headers = { 'GET /index.html HTTP/1.1' }
local request = getInstance(headers)
local result = request:path()
assert.are.equal('./index.html', result)
end)
function verifyMethod(method)
local headers = { method .. ' /index.html HTTP/1.1' }
local request = getInstance(headers)
local result = request:method()
assert.are.equal(method, result)
end
it('should returns correct method - it is get - when method is called', function()
verifyMethod('GET')
end)
it('should returns correct method - it is post - when method is called', function()
verifyMethod('POST')
end)
it('should returns correct method - it is delete - when method is called', function()
verifyMethod('DELETE')
end)
it('should returns correct method - it is put - when method is called', function()
verifyMethod('PUT')
end)
it('should returns correct object when headers method is called', function()
local headers = {'GET /Makefile?a=b&c=d HTTP/1.1', 'A:1', 'B:2', nil , 'C=3', ''}
local request = getInstance(headers)
local result = request:headers()
assert.equal(type(result), 'table')
assert.equal(#result, 2)
assert.equal('1', result['A'])
assert.equal('2', result['B'])
end)
end)
end)
-- local Request = require 'lib/request'
-- i =0
-- local headers = {'GET /Makefile?a=b&c=d HTTP/1.1', 'A:B', 'C:D', nil , 'X=Y', ''}
-- local err = {nil, nil, nil, nil, nil,'érro'}
-- local r = Request:new({receive=function () i=i + 1;return headers[i], err[i]; end})
-- print(r:path())
-- print(r:params().a)
-- print(r:headers().A)
-- print(r:method())
-- print(r:body())
-- print(r:form().X)
|
fixed problem with tab
|
fixed problem with tab
|
Lua
|
mit
|
EvandroLG/pegasus.lua,dieseltravis/pegasus.lua
|
0d0154f66bdda50b40846491cfc9c63a8c0f9311
|
prosody-modules/mod_auth_external.lua
|
prosody-modules/mod_auth_external.lua
|
--
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://modules.prosody.im/mod_auth_external.html#installation");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local server = require "net.server";
local have_async, async = pcall(require, "util.async");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
local blocking = module:get_option_boolean("external_auth_blocking", not(have_async and server.event and lpty.getfd));
local auth_processes = module:get_option_number("external_auth_processes", 1);
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
assert(not host:find(":"), "Invalid hostname");
if not blocking then
log("debug", "External auth in non-blocking mode, yay!")
waiter, guard = async.waiter, async.guarder();
elseif auth_processes > 1 then
log("warn", "external_auth_processes is greater than 1, but we are in blocking mode - reducing to 1");
auth_processes = 1;
end
local ptys = {};
local pty_options = { throw_errors = false, no_local_echo = true, use_path = false };
for i = 1, auth_processes do
ptys[i] = lpty.new(pty_options);
end
local curr_process = 0;
function send_query(text)
curr_process = (curr_process%auth_processes)+1;
local pty = ptys[curr_process];
local finished_with_pty
if not blocking then
finished_with_pty = guard(pty); -- Prevent others from crossing this line while we're busy
end
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:send(text);
if blocking then
return pty:read(read_timeout);
else
local response;
local wait, done = waiter();
server.addevent(pty:getfd(), server.event.EV_READ, function ()
response = pty:read();
done();
return -1;
end);
wait();
finished_with_pty();
return response;
end
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
elseif script_type == "generic" then
query = query..'\n';
end
local response, err = send_query(query);
if not response then
log("warn", "Error while waiting for result from auth process: %s", err or "unknown error");
elseif (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
|
--
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://modules.prosody.im/mod_auth_external.html#installation");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local server = require "net.server";
local have_async, async = pcall(require, "util.async");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
local blocking = module:get_option_boolean("external_auth_blocking", not(have_async and server.event and lpty.getfd));
local auth_processes = module:get_option_number("external_auth_processes", 1);
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
assert(not host:find(":"), "Invalid hostname");
if not blocking then
log("debug", "External auth in non-blocking mode, yay!")
waiter, guard = async.waiter, async.guarder();
elseif auth_processes > 1 then
log("warn", "external_auth_processes is greater than 1, but we are in blocking mode - reducing to 1");
auth_processes = 1;
end
local ptys = {};
local pty_options = { throw_errors = false, no_local_echo = true, use_path = false };
for i = 1, auth_processes do
ptys[i] = lpty.new(pty_options);
end
local curr_process = 0;
function send_query(text)
curr_process = (curr_process%auth_processes)+1;
local pty = ptys[curr_process];
local finished_with_pty
if not blocking then
finished_with_pty = guard(pty); -- Prevent others from crossing this line while we're busy
end
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:flush("i");
pty:send(text);
if blocking then
local response;
response = pty:read(read_timeout);
if response == text then
response = pty:read(read_timeout);
end
return response;
else
local response;
local wait, done = waiter();
server.addevent(pty:getfd(), server.event.EV_READ, function ()
response = pty:read();
if not response == text then
done();
end
return -1;
end);
wait();
finished_with_pty();
return response;
end
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
elseif script_type == "generic" then
query = query..'\n';
end
local response, err = send_query(query);
if response then log("debug", "Reponse %s", response ); end
if not response then
log("warn", "Error while waiting for result from auth process: %s", err or "unknown error");
elseif (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
|
Work around the `mod_auth_external.lua` echo bug
|
Work around the `mod_auth_external.lua` echo bug
Thanks to Damien Fetis and his patch in https://prosody.im/issues/issue/855
Does not currently work with non-blocking I/O, so do **not** enable
`use_libevent = true;` in your `/etc/prosody/prosody.cfg.lua` when
running prosody-trunk. I hope Damien will be able to find a fix,
otherwise we will have to modify this module to disable
non-blocking mode internally.
Please follow the
[installation instructions](https://github.com/jsxc/xmpp-cloud-auth/wiki)
to make sure everything works smoothly.
Fixes #21
|
Lua
|
mit
|
jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth
|
fae5cdbcacba7a0ed3683867e2b8c0c2ea76e8e9
|
fusion/core/lexer.lua
|
fusion/core/lexer.lua
|
local re = require("re");
local defs = {}
local current_file;
defs['true'] = function() return true end
defs['false'] = function() return false end
defs['bool'] = function(...) return defs[(...)]() end
defs['numberify'] = tonumber
defs.print = print
defs.incomplete_statement = function(pos, char)
local line = 1
local start = 1
local line_start = 0
while start < pos do
if current_file:find("^\n", start) then
line_start = start + 1
line = line + 1
end
start = start + 1
end
local line_end = current_file:find("\n", pos)
if not line_end then
line_end = #current_file
else
line_end = line_end - 1
end
local msg_start = math.max(pos - 5, line_start)
local msg_end = math.min(pos + 5, line_end)
local input = ""
local tab_len = 8
if msg_start == pos - 5 and msg_start ~= line_start then
tab_len = 11
input = "..."
end
input = input .. current_file:sub(msg_start, msg_end)
if msg_end ~= line_end and msg_end == pos + 5 then
input = input .. "..."
end
errormsg_table = {
"SyntaxError";
("Unfinished statement on line %d"):format(line);
("Input: %q"):format(input);
(" "):rep(tab_len + math.max(pos - msg_start, 0)) .. "^";
}
errormsg = {
pos = {
y = line;
x = pos - line_start;
};
context = current_file:match("[A-Za-z_][A-Za-z0-9_]*", pos);
quick = "syntax"
}
setmetatable(errormsg, {
__tostring = function()
return table.concat(errormsg_table, "\n")
end
})
error(errormsg,0)
end
local pattern = re.compile([[
statement_list <- ws {| ((! '}') rstatement ws)* |}
statement_block <- {| {:block: '' -> 'block' :} '{' ws statement_list ws '}' |}
statement <- (
function_call /
assignment /
return /
{| {:type: 'break' :} |} /
'--' {| {:type: '' -> 'comment' :} ws {[^;]*} |}
) ws ';' ws / (
statement_block /
while_loop /
numeric_for_loop /
iterative_for_loop /
function_definition /
if /
class
)
rstatement <- statement / required
required <- ({} {.}) -> incomplete_statement
class <- {| {:type: 'new' -> 'class' :} space {:name: name :}
(ws 'extends' ws {:extends: variable :})? ws
'{' ws {| ((! '}') (class_field / required) ws)* |} ws '}'
|}
class_field <-
function_definition /
{| {:type: '' -> 'class_field' :}
(
'[' ws {:name: variable :} ws ']' ws '=' ws expression ws ';' /
{:name: name :} ws '=' ws expression ws ';'
)
|}
return <- {| {:type: {'return' / 'yield'} :} ws expression_list? |}
lambda <- {| {:type: '' -> 'lambda' :}
function_body
|}
function_definition <- {| {:type: '' -> 'function_definition' :}
{:is_async: 'async' -> true space :}? ws
variable ({:is_self: ws ':' -> true :} ws name)? ws function_body
|}
function_body <-
'(' ws function_defined_arguments? ws ')' ws
({:is_self: '=' -> true :} / '-') '>' ws
(statement / expression_list / required)
function_defined_arguments <- {|
function_argument (ws ',' ws function_argument)*
|}
function_argument <- {|
{:name: name :} (ws '=' ws {:default: expression :})?
|}
while_loop <- {| {:type: '' -> 'while_loop' :}
'while' ws {:condition: expression :} ws rstatement
|}
iterative_for_loop <- {| {:type: '' -> 'iterative_for_loop' :}
'for' ws '(' ws name_list ws 'in' ws expression ws ')' ws rstatement
|}
numeric_for_loop <- {| {:type: '' -> 'numeric_for_loop' :}
'for' ws numeric_for_assignment ws rstatement
|}
numeric_for_assignment <- '('
{:incremented_variable: name :} ws '=' ws
{:start: expression :} ws
',' ws {:stop: expression :} ws
(',' ws {:step: expression :})?
')'
if <- {|
{:type: 'if' :} ws {:condition: expression :} ws rstatement
(ws 'else' ws {:else: rstatement :})?
|}
function_call <- {| {:type: '' -> 'function_call' :} (
(variable / '(' expression ')') ({:has_self: ':' -> true :} variable ws
{:index_class: ws '<' ws {expression} ws '>' :}? )?
) ws '(' ws function_call_body? ws ')' |}
function_call_body <- {:generator: {|
expression (ws 'for' ws variable_list)? ws 'in' ws expression
|} :} / function_args
function_args <- expression_list?
assignment <- {| {:type: '' -> 'assignment' :}
(variable_list ws '=' ws expression_list /
{:is_local: 'local' -> true :} space name_list ws '=' ws
expression_list)
|}
name_list <- {:variable_list: {|
local_name (ws ',' ws local_name)*
|} :} / {:variable_list: {|
{:is_destructuring: '{' -> true :} ws local_name
(ws ',' ws local_name)* ws '}'
|} :}
local_name <- {| {:type: '' -> 'variable' :} name |}
expression_list <- {:expression_list: {|
expression (ws ',' ws expression)*
|} :}
expression <- value / {| {:type: '' -> 'expression' :}
'(' ws operator (ws expression)+ ws ')'
|}
operator <- {:operator:
'//' /
'>>' /
'<<' /
[=!<>] '=' /
'&&' /
'||' /
'..' /
[-!#~+*/%^&|<>]
:}
value <-
lambda /
function_call /
literal /
variable /
'(' expression ')'
variable_list <- {:variable_list: {|
variable (ws ',' ws variable)*
|} :}
variable <- {| {:type: '' -> 'variable' :}
((name ws ('.' ws name / ws '[' ws expression ws ']')*) /
('@' -> 'self' name? ws ('.' ws name / ws '[' ws expression ws ']')*))
|}
name <- {[A-Za-z_][A-Za-z0-9_]*}
literal <-
table /
{| {:type: '' -> 'vararg' :} { '...' } |} /
number /
string /
{| {:type: '' -> 'boolean' :}
('true' / 'false') -> bool
|} /
{| {'nil' -> 'nil'} |}
number <- {| {:type: '' -> 'number' :} {:is_negative: '-' -> true :}? (
base16num /
base10num
) |}
base10num <- {:base: '' -> '10' :} {
((integer '.' integer) /
(integer '.') /
('.' integer) /
integer) int_exponent?
} -> numberify
integer <- [0-9]+
int_exponent <- [eE] [+-]? integer
base16num <- {:base: '' -> '16' :} {
'0' [Xx] [0-9A-Fa-f]+ hex_exponent?
} -> numberify
hex_exponent <- [pP] [+-]? integer
string <- {| dqstring / sqstring / blstring |}
dqstring <- {:type: '' -> 'dqstring' :} '"' { (('\' .) /
([^]] .. '\r\n' .. [["]))* } '"' -- no escape codes in block quotes
sqstring <- {:type: '' -> 'sqstring' :} "'" { [^]] .. '\r\n' .. [[']* } "'"
blstring <- {:type: '' -> 'blstring' :} '[' {:eq: '='* :} '[' blclose
blclose <- ']' =eq ']' / . blclose
table <- {| {:type: '' -> 'table' :} '{' ws -- TODO `for` constructor
(
table_generator /
table_field (ws ',' ws table_field)*
)?
ws '}' |}
table_generator <- {| {:type: '' -> 'generator' :}
table_field (ws 'for' ws variable_list)? ws 'in' ws expression
|}
table_field <-
{| '[' ws {:index: variable :} ws ']' ws '=' ws expression |} /
{| {:name: name :} ws '=' ws expression |} /
expression
ws <- %s*
space <- %s+
]], defs);
return {
match = function(self, input)
current_file = input
return pattern:match(input)
end
}
|
local re = require("re");
local defs = {}
local current_file;
defs['true'] = function() return true end
defs['false'] = function() return false end
defs['bool'] = function(...) return defs[(...)]() end
defs['numberify'] = tonumber
defs.print = print
defs.incomplete_statement = function(pos, char)
local line = 1
local start = 1
local line_start = 0
while start < pos do
if current_file:find("^\n", start) then
line_start = start + 1
line = line + 1
end
start = start + 1
end
local line_end = current_file:find("\n", pos)
if not line_end then
line_end = #current_file
else
line_end = line_end - 1
end
local msg_start = math.max(pos - 5, line_start)
local msg_end = math.min(pos + 5, line_end)
local input = ""
local tab_len = 8
if msg_start == pos - 5 and msg_start ~= line_start then
tab_len = 11
input = "..."
end
input = input .. current_file:sub(msg_start, msg_end)
if msg_end ~= line_end and msg_end == pos + 5 then
input = input .. "..."
end
errormsg_table = {
"SyntaxError";
("Unfinished statement on line %d"):format(line);
("Input: %q"):format(input);
(" "):rep(tab_len + math.max(pos - msg_start, 0)) .. "^";
}
errormsg = {
pos = {
y = line;
x = pos - line_start;
};
context = current_file:match("[A-Za-z_][A-Za-z0-9_]*", pos);
quick = "syntax"
}
setmetatable(errormsg, {
__tostring = function()
return table.concat(errormsg_table, "\n")
end
})
error(errormsg,0)
end
local pattern = re.compile([[
statement_list <- ws {| ((! '}') rstatement ws)* |}
statement_block <- {| {:type: '' -> 'block' :} '{' ws statement_list ws '}' |}
statement <- (
function_call /
assignment /
return /
{| {:type: 'break' :} |} /
'--' {| {:type: '' -> 'comment' :} ws {[^;]*} |}
) ws ';' ws / (
statement_block /
while_loop /
numeric_for_loop /
iterative_for_loop /
function_definition /
if /
class
)
rstatement <- statement / required
required <- ({} {.}) -> incomplete_statement
class <- {| {:type: 'new' -> 'class' :} space {:name: name :}
(ws 'extends' ws {:extends: variable :})? ws
'{' ws {| ((! '}') (class_field / required) ws)* |} ws '}'
|}
class_field <-
function_definition /
{| {:type: '' -> 'class_field' :}
(
'[' ws {:name: variable :} ws ']' ws '=' ws expression ws ';' /
{:name: name :} ws '=' ws expression ws ';'
)
|}
return <- {| {:type: {'return' / 'yield'} :} ws expression_list? |}
lambda <- {| {:type: '' -> 'lambda' :}
function_body
|}
function_definition <- {| {:type: '' -> 'function_definition' :}
{:is_async: 'async' -> true space :}? ws
variable ws function_body -- Do NOT write functions with :
|}
function_body <-
'(' ws function_defined_arguments? ws ')' ws
({:is_self: '=' -> true :} / '-') '>' ws
(statement / expression_list / required)
function_defined_arguments <- {|
function_argument (ws ',' ws function_argument)*
|}
function_argument <- {|
{:name: name :} (ws '=' ws {:default: expression :})?
|}
while_loop <- {| {:type: '' -> 'while_loop' :}
'while' ws {:condition: expression :} ws rstatement
|}
iterative_for_loop <- {| {:type: '' -> 'iterative_for_loop' :}
'for' ws '(' ws name_list ws 'in' ws expression ws ')' ws rstatement
|}
numeric_for_loop <- {| {:type: '' -> 'numeric_for_loop' :}
'for' ws numeric_for_assignment ws rstatement
|}
numeric_for_assignment <- '('
{:incremented_variable: name :} ws '=' ws
{:start: expression :} ws
',' ws {:stop: expression :} ws
(',' ws {:step: expression :})?
')'
if <- {|
{:type: 'if' :} ws {:condition: expression :} ws rstatement
(ws 'else' ws {:else: rstatement :})?
|}
function_call <- {| {:type: '' -> 'function_call' :} (
(variable / '(' expression ')') ({:has_self: ':' -> true :} variable ws
{:index_class: ws '<' ws {expression} ws '>' :}? )?
) ws '(' ws function_call_body? ws ')' |}
function_call_body <- {:generator: {|
expression (ws 'for' ws variable_list)? ws 'in' ws expression
|} :} / function_args
function_args <- expression_list?
assignment <- {| {:type: '' -> 'assignment' :}
(variable_list ws '=' ws expression_list /
{:is_local: 'local' -> true :} space name_list ws '=' ws
expression_list)
|}
name_list <- {:variable_list: {|
local_name (ws ',' ws local_name)*
|} :} / {:variable_list: {|
{:is_destructuring: '{' -> true :} ws local_name
(ws ',' ws local_name)* ws '}'
|} :}
local_name <- {| {:type: '' -> 'variable' :} name |}
expression_list <- {:expression_list: {|
expression (ws ',' ws expression)*
|} :}
expression <- value / {| {:type: '' -> 'expression' :}
'(' ws operator (ws expression)+ ws ')'
|}
operator <- {:operator:
'//' /
'>>' /
'<<' /
[=!<>] '=' /
'&&' /
'||' /
'..' /
[-!#~+*/%^&|<>]
:}
value <-
lambda /
function_call /
literal /
variable /
'(' expression ')'
variable_list <- {:variable_list: {|
variable (ws ',' ws variable)*
|} :}
variable <- {| {:type: '' -> 'variable' :}
((name ws ('.' ws name / ws '[' ws expression ws ']')*) /
('@' -> 'self' name? ws ('.' ws name / ws '[' ws expression ws ']')*))
|}
name <- {[A-Za-z_][A-Za-z0-9_]*}
literal <-
table /
{| {:type: '' -> 'vararg' :} { '...' } |} /
number /
string /
{| {:type: '' -> 'boolean' :}
('true' / 'false') -> bool
|} /
{| {'nil' -> 'nil'} |}
number <- {| {:type: '' -> 'number' :} {:is_negative: '-' -> true :}? (
base16num /
base10num
) |}
base10num <- {:base: '' -> '10' :} {
((integer '.' integer) /
(integer '.') /
('.' integer) /
integer) int_exponent?
} -> numberify
integer <- [0-9]+
int_exponent <- [eE] [+-]? integer
base16num <- {:base: '' -> '16' :} {
'0' [Xx] [0-9A-Fa-f]+ hex_exponent?
} -> numberify
hex_exponent <- [pP] [+-]? integer
string <- {| dqstring / sqstring / blstring |}
dqstring <- {:type: '' -> 'dqstring' :} '"' { (('\' .) /
([^]] .. '\r\n' .. [["]))* } '"' -- no escape codes in block quotes
sqstring <- {:type: '' -> 'sqstring' :} "'" { [^]] .. '\r\n' .. [[']* } "'"
blstring <- {:type: '' -> 'blstring' :} '[' {:eq: '='* :} '[' blclose
blclose <- ']' =eq ']' / . blclose
table <- {| {:type: '' -> 'table' :} '{' ws -- TODO `for` constructor
(
table_generator /
table_field (ws ',' ws table_field)*
)?
ws '}' |}
table_generator <- {| {:type: '' -> 'generator' :}
table_field (ws 'for' ws variable_list)? ws 'in' ws expression
|}
table_field <-
{| '[' ws {:index: variable :} ws ']' ws '=' ws expression |} /
{| {:name: name :} ws '=' ws expression |} /
expression
ws <- %s*
space <- %s+
]], defs);
return {
match = function(self, input)
current_file = input
return pattern:match(input)
end
}
|
lexer: fix blcok type and remove `:` token in method definition
|
lexer: fix blcok type and remove `:` token in method definition
|
Lua
|
mit
|
RyanSquared/FusionScript
|
9b0a839130b657963cfc72d68f7d051fbceb9a2f
|
modules/tollpost.lua
|
modules/tollpost.lua
|
local ev = require'ev'
local util = require'util'
local simplehttp = util.simplehttp
local json = util.json
local apiurl = 'http://www.tollpost.no/XMLServer/rest/trackandtrace/%s'
local duration = 60
if(not ivar2.timers) then ivar2.timers = {} end
-- Abuse the ivar2 global to store out ephemeral event data until we can get some persistant storage
if(not ivar2.shipmentEvents) then ivar2.shipmentEvents = {} end
local split = function(str, pattern)
local out = {}
str:gsub(pattern, function(match)
table.insert(out, match)
end)
return out
end
local function titlecase(str)
local buf = {}
for word in string.gfind(str, "%S+") do
local first, rest = string.sub(word, 1, 1), string.sub(word, 2)
table.insert(buf, string.upper(first) .. string.lower(rest))
end
return table.concat(buf, " ")
end
local eventHandler = function(event)
if not event then return nil end
local out = {}
local date = event.eventTime:sub(1,10)
local time = event.eventTime:sub(12)
table.insert(out, date)
table.insert(out, time)
table.insert(out, event.eventDescription)
local location = event.location
if location then
local city = location['displayName']
if city and city ~= '' then city = '('..titlecase(city)..')' end
table.insert(out, city)
end
return table.concat(out, ' ')
end
local shipmentTrack = function(self, source, destination, pid, alias)
local nick = source.nick
local id = pid .. nick
local runningTimer = self.timers[id]
if(runningTimer) then
-- cancel existing timer
self:Notice(nick, "Canceling existing tracking for alias %s.", alias)
self.shipmentEvents[id] = -1
runningTimer:stop(ivar2.Loop)
end
-- Store the eventcount in the ivar2 global
-- if the eventcount increases it means new events on the shipment happened.
local eventCount = self.shipmentEvents[id]
if not eventCount then
self.shipmentEvents[id] = -1
end
local timer = ev.Timer.new(
function(loop, timer, revents)
simplehttp(string.format(apiurl, pid), function(data)
local info = json.decode(data)
local root = info['TrackingInformationResponse']
local cs = root['shipments']
if not cs[1] then
if self.shipmentEvents[id] == -1 then
say('%s: Found nothing for shipment %s', nick, pid)
end
self.shipmentEvents[id] = 0
return
else
cs = cs[1]
end
local out = {}
local items = cs['items'][1]
local status = string.format('\002%s\002', titlecase(items['status']))
local events = items['events']
local newEventCount = #events
print('id:',id,'new:',newEventCount,'old:',self.shipmentEvents[id])
if newEventCount < self.shipmentEvents[id] then
-- We can never go backwards
return
end
if newEventCount > self.shipmentEvents[id] then
table.insert(out, string.format('Status: %s', status))
end
for i=self.shipmentEvents[id]+1,newEventCount do
print('loop:',i)
local event = events[i]
table.insert(out, eventHandler(event))
-- Cancel event here somehow?
end
if #out > 0 then
say('%s: \002%s\002 %s', nick, alias, table.concat(out, ', '))
end
self.shipmentEvents[id] = newEventCount
end)
end,
1,
duration
)
self.timers[id] = timer
timer:start(ivar2.Loop)
end
local shipmentLocate = function(self, source, destination, pid)
local nick = source.nick
simplehttp(string.format(apiurl, pid), function(data)
local info = json.decode(data)
local root = info['TrackingInformationResponse']
local cs = root['shipments']
if not cs[1] then
say('%s: Found nothing for shipment %s', nick, pid)
return
else
cs = cs[1]
end
local out = {}
local items = cs['items'][1]
local status = string.format('\002%s\002', titlecase(items['status']))
table.insert(out, string.format('Status: %s', status))
for i, event in pairs(items['events']) do
table.insert(out, eventHandler(event))
end
say('%s: %s', nick, table.concat(out, ', '))
end)
end
local shipmentHelp = function(self, source, destination)
return say('For lookup: !mypack pakkeid. For tracking: !mypack pakkeid alias')
end
return {
PRIVMSG = {
['^%pmypack (%d+) (.*)$'] = shipmentTrack,
['^%pmypack (%d+)$'] = shipmentLocate,
['^%pmypack$'] = shipmentHelp,
},
}
|
local ev = require'ev'
local util = require'util'
local simplehttp = util.simplehttp
local json = util.json
local apiurl = 'http://www.tollpost.no/XMLServer/rest/trackandtrace/%s'
local duration = 60
if(not ivar2.timers) then ivar2.timers = {} end
-- Abuse the ivar2 global to store out ephemeral event data until we can get some persistant storage
if(not ivar2.shipmentEvents) then ivar2.shipmentEvents = {} end
local split = function(str, pattern)
local out = {}
str:gsub(pattern, function(match)
table.insert(out, match)
end)
return out
end
local function titlecase(str)
local buf = {}
for word in string.gfind(str, "%S+") do
local first, rest = string.sub(word, 1, 1), string.sub(word, 2)
table.insert(buf, string.upper(first) .. string.lower(rest))
end
return table.concat(buf, " ")
end
local eventHandler = function(event)
if not event then return nil end
local out = {}
local date = event.eventTime:sub(1,10)
local time = event.eventTime:sub(12)
table.insert(out, date)
table.insert(out, time)
table.insert(out, event.eventDescription)
local location = event.location
if location then
local city = location['displayName']
if city and city ~= '' then city = '('..titlecase(city)..')' end
table.insert(out, city)
end
return table.concat(out, ' ')
end
local shipmentTrack = function(self, source, destination, pid, alias)
local nick = source.nick
local id = pid .. nick
local runningTimer = self.timers[id]
if(runningTimer) then
-- cancel existing timer
self:Notice(nick, "Canceling existing tracking for alias %s.", alias)
self.shipmentEvents[id] = -1
runningTimer:stop(ivar2.Loop)
end
-- Store the eventcount in the ivar2 global
-- if the eventcount increases it means new events on the shipment happened.
local eventCount = self.shipmentEvents[id]
if not eventCount then
self.shipmentEvents[id] = -1
end
local timer = ev.Timer.new(
function(loop, timer, revents)
simplehttp(string.format(apiurl, pid), function(data)
local info = json.decode(data)
local root = info['TrackingInformationResponse']
local cs = root['shipments']
if not cs[1] then
if self.shipmentEvents[id] == -1 then
say('%s: Found nothing for shipment %s', nick, pid)
end
self.shipmentEvents[id] = 0
return
else
cs = cs[1]
end
local out = {}
local items = cs['items'][1]
local status = string.format('\002%s\002', titlecase(items['status']))
local events = items['events']
local newEventCount = #events
print('id:',id,'new:',newEventCount,'old:',self.shipmentEvents[id])
if newEventCount < self.shipmentEvents[id] then
-- We can never go backwards
return
end
if newEventCount > self.shipmentEvents[id] then
table.insert(out, string.format('Status: %s', status))
end
for i=self.shipmentEvents[id]+1,newEventCount do
print('loop:',i)
local event = events[i]
table.insert(out, eventHandler(event))
-- Cancel event here somehow?
end
if #out > 0 then
say('%s: \002%s\002 %s', nick, alias, table.concat(out, ', '))
end
self.shipmentEvents[id] = newEventCount
end)
end,
1,
duration
)
self.timers[id] = timer
timer:start(ivar2.Loop)
end
local shipmentLocate = function(self, source, destination, pid)
local nick = source.nick
simplehttp(string.format(apiurl, pid), function(data)
local info = json.decode(data)
local root = info['TrackingInformationResponse']
local cs = root['shipments']
if not cs[1] then
say('%s: Found nothing for shipment %s', nick, pid)
return
else
cs = cs[1]
end
local out = {}
local items = cs['items'][1]
local status = string.format('\002%s\002', titlecase(items['status']))
table.insert(out, string.format('Status: %s', status))
for i, event in pairs(items['events']) do
table.insert(out, eventHandler(event))
end
say('%s: %s', nick, table.concat(out, ', '))
end)
end
local shipmentHelp = function(self, source, destination)
return say('For lookup: !mypack pakkeid. For tracking: !mypack pakkeid alias')
end
return {
PRIVMSG = {
['^%pmypack (%d+) (.*)$'] = shipmentTrack,
['^%pmypack (%d+)$'] = shipmentLocate,
['^%pmypack$'] = shipmentHelp,
},
}
|
tollpost: Remove trailing whitespaces and fix mixed indent.
|
tollpost: Remove trailing whitespaces and fix mixed indent.
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
|
b7f5185b40f10c87d978db378ee2782a414c8d70
|
Normalize.lua
|
Normalize.lua
|
local Normalize, parent = torch.class('nn.Normalize', 'nn.Module')
function Normalize:__init(p,eps)
parent.__init(self)
assert(p,'p-norm not provided')
assert(p > 0, p..'-norm not supported')
self.p = p
self.eps = eps or 1e-10
end
function Normalize:updateOutput(input)
assert(input:dim() <= 2, 'only 1d layer supported')
local input_size = input:size()
if input:dim() == 1 then
input = input:view(1,-1)
end
self._output = self._output or input.new()
self.norm = self.norm or input.new()
self.buffer = self.buffer or input.new()
self._output:resizeAs(input)
if self.p == math.huge then
-- specialization for the infinity norm
self._indices = self._indices or
(torch.type(self.output) == 'torch.CudaTensor' and
torch.CudaTensor() or torch.LongTensor())
self.buffer:abs(input)
torch.max(self.norm, self._indices, self.buffer, 2)
self.norm:add(self.eps)
else
self.normp = self.normp or input.new()
if self.p % 2 ~= 0 then
self.buffer:abs(input):pow(self.p)
else
self.buffer:pow(input,self.p)
end
self.normp:sum(self.buffer,2):add(self.eps)
self.norm:pow(self.normp,1/self.p)
end
self._output:cdiv(input, self.norm:view(-1,1):expandAs(input))
self.output:view(self._output, input_size)
return self.output
end
function Normalize:updateGradInput(input, gradOutput)
assert(input:dim() <= 2, 'only 1d layer supported')
assert(gradOutput:dim() <= 2, 'only 1d layer supported')
local input_size = input:size()
if input:dim() == 1 then
input = input:view(1,-1)
end
local n = input:size(1) -- batch size
local d = input:size(2) -- dimensionality of vectors
self._gradInput = self._gradInput or input.new()
self.cross = self.cross or input.new()
-- compute diagonal term with gradOutput
self._gradInput:resize(n,d)
if self.p == math.huge then
-- specialization for the inf case
self._gradInput:cmul(self.norm:view(n,1,1):expand(n,d,1),gradOutput)
self.buffer:resizeAs(input):zero()
self.cross:resize(n,1)
self.cross:gather(input,2,self._indices)
self.cross:cdiv(self.norm)
self.buffer:scatter(2,self._indices,self.cross)
else
self._gradInput:cmul(self.normp:view(n,1):expand(n,d), gradOutput)
-- small optimizations for different p
-- buffer = input*|input|^(p-2)
if self.p % 2 ~= 0 then
-- for non-even p, need to add absolute value
if self.p < 2 then
-- add eps to avoid possible division by 0
self.buffer:abs(input):add(self.eps):pow(self.p-2):cmul(input)
else
self.buffer:abs(input):pow(self.p-2):cmul(input)
end
elseif self.p == 2 then
-- special case for p == 2, pow(x,0) = 1
self.buffer:copy(input)
else
-- p is even and > 2, pow(x,p) is always positive
self.buffer:pow(input,self.p-2):cmul(input)
end
end
-- compute cross term in two steps
self.cross:resize(n,1)
-- instead of having a huge temporary matrix (b1*b2),
-- do the computations as b1*(b2*gradOutput). This avoids redundant
-- computation and also a huge buffer of size n*d^2
self.buffer2 = self.buffer2 or input.new() -- nxd
self.buffer2:cmul(input, gradOutput)
self.cross:sum(self.buffer2, 2)
self.buffer:cmul(self.cross:expandAs(self.buffer))
self._gradInput:add(-1, self.buffer)
-- reuse cross buffer for normalization
if self.p == math.huge then
self.cross:cmul(self.norm,self.norm)
else
self.cross:cmul(self.normp,self.norm)
end
self._gradInput:cdiv(self.cross:expand(n,d))
self.gradInput:view(self._gradInput, input_size)
return self.gradInput
end
function Normalize:__tostring__()
local s
-- different prints if the norm is integer
if self.p % 1 == 0 then
s = '%s(%d)'
else
s = '%s(%f)'
end
return string.format(s,torch.type(self),self.p)
end
function Normalize:type(type, tensorCache)
-- torch.max expects a LongTensor as indices, whereas cutorch.max expects a CudaTensor.
if type == 'torch.CudaTensor' then
parent.type(self, type, tensorCache)
else
-- self._indices must be a LongTensor. Setting it to nil temporarily avoids
-- unnecessary memory allocations.
local indices
indices, self._indices = self._indices, nil
parent.type(self, type, tensorCache)
self._indices = indices and indices:long() or nil
end
return self
end
function Normalize:clearState()
nn.utils.clear(self, {
'_output',
'_indices',
'_gradInput',
'buffer',
'norm',
'normp',
'cross',
})
return parent.clearState(self)
end
|
local Normalize, parent = torch.class('nn.Normalize', 'nn.Module')
function Normalize:__init(p,eps)
parent.__init(self)
assert(p,'p-norm not provided')
assert(p > 0, p..'-norm not supported')
self.p = p
self.eps = eps or 1e-10
end
function Normalize:updateOutput(input)
assert(input:dim() <= 2, 'only 1d layer supported')
local input_size = input:size()
if input:dim() == 1 then
input = input:view(1,-1)
end
self._output = self._output or input.new()
self.norm = self.norm or input.new()
self.buffer = self.buffer or input.new()
self._output:resizeAs(input)
if self.p == math.huge then
-- specialization for the infinity norm
self._indices = self._indices or
(torch.type(self.output) == 'torch.CudaTensor' and
torch.CudaLongTensor() or torch.LongTensor())
self.buffer:abs(input)
torch.max(self.norm, self._indices, self.buffer, 2)
self.norm:add(self.eps)
else
self.normp = self.normp or input.new()
if self.p % 2 ~= 0 then
self.buffer:abs(input):pow(self.p)
else
self.buffer:pow(input,self.p)
end
self.normp:sum(self.buffer,2):add(self.eps)
self.norm:pow(self.normp,1/self.p)
end
self._output:cdiv(input, self.norm:view(-1,1):expandAs(input))
self.output:view(self._output, input_size)
return self.output
end
function Normalize:updateGradInput(input, gradOutput)
assert(input:dim() <= 2, 'only 1d layer supported')
assert(gradOutput:dim() <= 2, 'only 1d layer supported')
local input_size = input:size()
if input:dim() == 1 then
input = input:view(1,-1)
end
local n = input:size(1) -- batch size
local d = input:size(2) -- dimensionality of vectors
self._gradInput = self._gradInput or input.new()
self.cross = self.cross or input.new()
-- compute diagonal term with gradOutput
self._gradInput:resize(n,d)
if self.p == math.huge then
-- specialization for the inf case
self._gradInput:cmul(self.norm:view(n,1,1):expand(n,d,1),gradOutput)
self.buffer:resizeAs(input):zero()
self.cross:resize(n,1)
self.cross:gather(input,2,self._indices)
self.cross:cdiv(self.norm)
self.buffer:scatter(2,self._indices,self.cross)
else
self._gradInput:cmul(self.normp:view(n,1):expand(n,d), gradOutput)
-- small optimizations for different p
-- buffer = input*|input|^(p-2)
if self.p % 2 ~= 0 then
-- for non-even p, need to add absolute value
if self.p < 2 then
-- add eps to avoid possible division by 0
self.buffer:abs(input):add(self.eps):pow(self.p-2):cmul(input)
else
self.buffer:abs(input):pow(self.p-2):cmul(input)
end
elseif self.p == 2 then
-- special case for p == 2, pow(x,0) = 1
self.buffer:copy(input)
else
-- p is even and > 2, pow(x,p) is always positive
self.buffer:pow(input,self.p-2):cmul(input)
end
end
-- compute cross term in two steps
self.cross:resize(n,1)
-- instead of having a huge temporary matrix (b1*b2),
-- do the computations as b1*(b2*gradOutput). This avoids redundant
-- computation and also a huge buffer of size n*d^2
self.buffer2 = self.buffer2 or input.new() -- nxd
self.buffer2:cmul(input, gradOutput)
self.cross:sum(self.buffer2, 2)
self.buffer:cmul(self.cross:expandAs(self.buffer))
self._gradInput:add(-1, self.buffer)
-- reuse cross buffer for normalization
if self.p == math.huge then
self.cross:cmul(self.norm,self.norm)
else
self.cross:cmul(self.normp,self.norm)
end
self._gradInput:cdiv(self.cross:expand(n,d))
self.gradInput:view(self._gradInput, input_size)
return self.gradInput
end
function Normalize:__tostring__()
local s
-- different prints if the norm is integer
if self.p % 1 == 0 then
s = '%s(%d)'
else
s = '%s(%f)'
end
return string.format(s,torch.type(self),self.p)
end
function Normalize:type(type, tensorCache)
self._indices = nil
parent.type(self, type, tensorCache)
return self
end
function Normalize:clearState()
nn.utils.clear(self, {
'_output',
'_indices',
'_gradInput',
'buffer',
'norm',
'normp',
'cross',
})
return parent.clearState(self)
end
|
fixing nn.Normalize for new cutorch types
|
fixing nn.Normalize for new cutorch types
|
Lua
|
bsd-3-clause
|
colesbury/nn,nicholas-leonard/nn,apaszke/nn,eriche2016/nn,joeyhng/nn,sagarwaghmare69/nn,kmul00/nn
|
58fc97025dfe874d9daaeed0267cfbb35f535603
|
parts/main.lua
|
parts/main.lua
|
local lua = require "lapis.lua"
local lapis = require "lapis.init"
local lapis_application = require "lapis.application"
local respond_to = lapis_application.respond_to
local yield_error = lapis_application.yield_error
local capture_errors = lapis_application.capture_errors
local lapis_validate = require "lapis.validate"
local assert_valid = lapis_validate.assert_valid
local fmt = string.format
local cfg = require("lapis.config").get()
local model = require "model"
local User = model.User
local Module = model.Module
local Label = model.Label
local app = {
path = "",
name = "main.",
}
app[{home = "/"}] = respond_to {
GET = function(self)
self.modules = Module:all()
self.labels = Label:all()
return {render = true}
end,
}
app[{["module"] = "/module/:id"}] = respond_to {
GET = function(self)
self.module = Module:new(self.params.id)
return {render = true}
end,
POST = capture_errors(function(self)
local u = assert(self.current_user)
local m = Module:new(self.params.id)
local action = self.params.action
assert(type(action) == "string")
self.module = m
if action == "endorse" then
assert(not u:endorses(m))
u:endorse(m)
elseif action == "deendorse" then
assert(u:endorses(m))
u:deendorse(m)
elseif action == "label" then
assert_valid(self.params, {
{"label", min_length = 3, max_length = 128},
})
l = Label:get_by_name(self.params.label)
if not l then
l = Label:create{name = self.params.label}
end
m:label(l)
else
error(fmt("invalid action %s", action))
end
return {render = true}
end),
}
app[{["label"] = "/label/:id"}] = respond_to {
GET = function(self)
self.label = Label:new(self.params.id)
return {render = true}
end,
}
app[{user = "/user/:id"}] = respond_to {
GET = function(self)
self.user = User:new(self.params.id)
return {render = true}
end,
}
return lua.class(app, lapis.Application)
|
local lua = require "lapis.lua"
local lapis = require "lapis.init"
local lapis_application = require "lapis.application"
local respond_to = lapis_application.respond_to
local yield_error = lapis_application.yield_error
local capture_errors = lapis_application.capture_errors
local lapis_validate = require "lapis.validate"
local assert_valid = lapis_validate.assert_valid
local fmt = string.format
local cfg = require("lapis.config").get()
local model = require "model"
local User = model.User
local Module = model.Module
local Label = model.Label
local app = {
path = "",
name = "main.",
}
app[{home = "/"}] = respond_to {
GET = function(self)
self.modules = Module:all()
self.labels = Label:all()
self.title = "Lua Toolbox"
return {render = true}
end,
}
app[{["module"] = "/module/:id"}] = respond_to {
GET = function(self)
self.module = Module:new(self.params.id)
self.title = fmt("Lua Toolbox - %s", self.module:get_name())
return {render = true}
end,
POST = capture_errors(function(self)
local u = assert(self.current_user)
local m = Module:new(self.params.id)
local action = self.params.action
assert(type(action) == "string")
self.module = m
if action == "endorse" then
assert(not u:endorses(m))
u:endorse(m)
elseif action == "deendorse" then
assert(u:endorses(m))
u:deendorse(m)
elseif action == "label" then
assert_valid(self.params, {
{"label", min_length = 3, max_length = 128},
})
l = Label:get_by_name(self.params.label)
if not l then
l = Label:create{name = self.params.label}
end
m:label(l)
else
error(fmt("invalid action %s", action))
end
return {render = true}
end),
}
app[{["label"] = "/label/:id"}] = respond_to {
GET = function(self)
self.label = Label:new(self.params.id)
self.title = fmt(
"Lua Toolbox - modules labelled %s",
self.label:get_name()
)
return {render = true}
end,
}
app[{user = "/user/:id"}] = respond_to {
GET = function(self)
self.user = User:new(self.params.id)
self.title = fmt("Lua Toolbox - %s", self.user:get_fullname())
return {render = true}
end,
}
return lua.class(app, lapis.Application)
|
page titles - fix #6
|
page titles - fix #6
|
Lua
|
mit
|
catwell/lua-toolbox
|
90876a80700d2282fa1b9a062bd76e55772c004e
|
lua-ubjson/ubjson.lua
|
lua-ubjson/ubjson.lua
|
--local _ENV = nil -- blocking globals in Lua 5.2
local math = require 'math'
local ubjson = { version = 'lua-ubjson 0.1' }
local pow2 = function(v)
local out = 1
for i = 0, v do
-- Use floats, since this may end up very large.
out = out * 2.0
end
return out
end
-- Mapping from maximum value -> ubjson tag
local int_maxes = {
pow2( 7),
pow2(15),
pow2(31),
pow2(63),
}
local int_tags = {
'i',
'I',
'l',
'L',
}
local int_tag_size = {
U = 1,
i = 1,
I = 2,
l = 4,
L = 8,
}
local use_double = false
local function int_data(val)
if val >= 0 and val < 256 then
return 'U', 1
end
local last_key = 'i'
local size = 1
-- Calculate the absolute value.
if val < 0 then
val = -val
-- Because twos-complement can hold slightly larger negatives than
-- positives.
if val ~= 0 then
val = val - 1
end
end
for idx, max in ipairs(int_maxes) do
if val > max then
return last_key, size
else
last_key = int_tags[idx]
size = size * 2
end
end
return last_key, size / 2
end
local function val_tag(val)
local t = type(val)
if t == 'number' then
t = int_data(val)
elseif t == 'boolean' then
if t then
return 'T'
else
return 'F'
end
elseif t == 'nil' then
return 'Z'
end
return t
end
local encode = nil
local function array_helper(val)
local t = nil
local length = 0
local non_int = false
local max = 0
for k, v in pairs(val) do
if type(k) ~= 'number' or k <= 0 then
non_int = true
elseif k > max then
max = k
end
if t == nil then
t = val_tag(v)
end
if t ~= val_tag(v) then
t = 'mixed'
end
length = length + 1
end
local function write_val(val, buffer, memo)
encode(val, buffer, memo)
end
if #t == 1 then
local size = int_tag_size[t]
if size then
write_val = function(val, buffer, memo)
table.insert(buffer, string.dumpint(val, size, 'b'))
end
elseif t == 'f' then
write_val = function(val, buffer, memo)
table.insert(buffer, string.dumpfloat(val, 'f', 'b'))
end
elseif t == 'd' then
write_val = function(val, buffer, memo)
table.insert(buffer, string.dumpfloat(val, 'd', 'b'))
end
else
-- Tag should be 'T', 'F', 'Z'
write_val = function(val, buffer, memo)
end
end
end
if max > 2 * length then
-- This table is a sparse array, so don't create a ubjson array.
return true, length, max, t, encode
end
return non_int, length, max, t, write_val
end
local function encode_int(val, buffer)
local tag, size = int_data(val)
table.insert(buffer, tag)
table.insert(buffer, string.dumpint(val, size, 'b'))
-- TODO(kzentner): Huge int support?
end
encode = function(val, buffer, memo)
if memo[val] then
error("Cannot serialize circular data structure.")
end
local t = type(val)
if t == 'number' then
if math.floor(val) == val then
encode_int(val, buffer)
else
if use_double then
table.insert(buffer, 'D')
table.insert(buffer, string.dumpfloat(val, 'd', 'b'))
else
table.insert(buffer, 'd')
table.insert(buffer, string.dumpfloat(val, 'f', 'b'))
end
end
elseif t == 'nil' then
table.insert(buffer, 'Z')
elseif t == 'boolean' then
if t then
table.insert(buffer, 'T')
else
table.insert(buffer, 'F')
end
elseif t == 'string' then
table.insert(buffer, 'S')
encode_int(#val, buffer)
table.insert(buffer, val)
elseif t == 'table' then
memo[val] = true
local use_obj, length, max, tag, write_val = array_helper(val)
if use_obj then
table.insert(buffer, '{')
else
table.insert(buffer, '[')
end
if #tag == 1 then
table.insert(buffer, '$')
table.insert(buffer, tag)
end
table.insert(buffer, '#')
encode_int(length, buffer)
if use_obj then
for k, v in pairs(val) do
local str = k .. ''
encode_int(#str, buffer)
table.insert(buffer, str)
write_val(v, buffer, memo)
end
else
for k = 1, max do
write_val(val[k], buffer, memo)
end
end
memo[val] = nil
end
end
function ubjson.encode(value, state)
local buffer = {}
local memo = {}
encode(value, buffer, memo)
out = ''
for k, v in pairs(buffer) do
out = out .. v
end
return out
end
function hex(str)
local out = ''
for i = 1, #str do
out = out .. string.format('%02x', str:byte(i))
end
return out
end
function ascii(str)
local out = ''
for i = 1, #str do
local c = str:sub(i, i)
if c:match('%g') then
out = out .. c .. ' '
else
out = (out .. ' ')
end
end
return out
end
local function test(val)
local enc = ubjson.encode(val)
print('length:', #enc)
print(hex(enc))
print(ascii(enc))
end
test({1, 2, 3, 4})
test({1, 2, 3, 4, 5, -1})
test({0, 1, 2, 3, 4, 5})
test({PiELESDigitalVals = {true, true, true, true, true, true, true, true},
PiELESAnalogVals = {127, 127, 127, 127, 127, 127, 127}})
test{[1] = 1, [3] = 4, [14] = 5}
|
--local _ENV = nil -- blocking globals in Lua 5.2
local math = require 'math'
local ubjson = { version = 'lua-ubjson 0.1' }
local pow2 = function(v)
local out = 1
for i = 0, v do
-- Use floats, since this may end up very large.
out = out * 2.0
end
return out
end
-- Mapping from maximum value -> ubjson tag
local int_maxes = {
pow2( 7),
pow2(15),
pow2(31),
pow2(63),
}
local int_tags = {
'i',
'I',
'l',
'L',
}
local int_tag_size = {
U = 1,
i = 1,
I = 2,
l = 4,
L = 8,
}
local use_double = false
local function int_data(val)
if val >= 0 and val < 256 then
return 'U', 1
end
local last_key = 'i'
local size = 1
-- Calculate the absolute value.
if val < 0 then
val = -val
-- Because twos-complement can hold slightly larger negatives than
-- positives.
if val ~= 0 then
val = val - 1
end
end
for idx, max in ipairs(int_maxes) do
if val > max then
return last_key, size
else
last_key = int_tags[idx]
size = size * 2
end
end
return last_key, size / 2
end
local function val_tag(val)
local t = type(val)
if t == 'number' then
t = int_data(val)
elseif t == 'boolean' then
if t then
return 'T'
else
return 'F'
end
elseif t == 'nil' then
return 'Z'
end
return t
end
local encode = nil
local function array_helper(val)
local t = nil
local length = 0
local non_int = false
local max = 0
for k, v in pairs(val) do
if type(k) ~= 'number' or k <= 0 then
non_int = true
elseif k > max then
max = k
end
if t == nil then
t = val_tag(v)
end
if t ~= val_tag(v) then
t = 'mixed'
end
length = length + 1
end
local write_val = encode
if #t == 1 then
local size = int_tag_size[t]
if size then
write_val = function(val, buffer, memo)
table.insert(buffer, string.dumpint(val, size, 'b'))
end
elseif t == 'f' then
write_val = function(val, buffer, memo)
table.insert(buffer, string.dumpfloat(val, 'f', 'b'))
end
elseif t == 'd' then
write_val = function(val, buffer, memo)
table.insert(buffer, string.dumpfloat(val, 'd', 'b'))
end
else
-- Tag should be 'T', 'F', 'Z'
write_val = function(val, buffer, memo)
end
end
end
if max > 2 * length then
-- This table is a sparse array, so don't create a ubjson array.
return true, length, max, t, encode
end
return non_int, length, max, t, write_val
end
local function encode_int(val, buffer)
local tag, size = int_data(val)
table.insert(buffer, tag)
table.insert(buffer, string.dumpint(val, size, 'b'))
-- TODO(kzentner): Huge int support?
end
encode = function(val, buffer, memo, depth)
if memo[val] then
error("Cannot serialize circular data structure.", depth)
end
local t = type(val)
if t == 'number' then
if math.floor(val) == val then
encode_int(val, buffer)
else
if use_double then
table.insert(buffer, 'D')
table.insert(buffer, string.dumpfloat(val, 'd', 'b'))
else
table.insert(buffer, 'd')
table.insert(buffer, string.dumpfloat(val, 'f', 'b'))
end
end
elseif t == 'nil' then
table.insert(buffer, 'Z')
elseif t == 'boolean' then
if t then
table.insert(buffer, 'T')
else
table.insert(buffer, 'F')
end
elseif t == 'string' then
table.insert(buffer, 'S')
encode_int(#val, buffer)
table.insert(buffer, val)
elseif t == 'table' then
memo[val] = true
local use_obj, length, max, tag, write_val = array_helper(val)
if use_obj then
table.insert(buffer, '{')
else
table.insert(buffer, '[')
end
if #tag == 1 then
table.insert(buffer, '$')
table.insert(buffer, tag)
end
table.insert(buffer, '#')
encode_int(length, buffer)
if use_obj then
for k, v in pairs(val) do
local str = k .. ''
encode_int(#str, buffer)
table.insert(buffer, str)
write_val(v, buffer, memo, depth + 1)
end
else
for k = 1, max do
write_val(val[k], buffer, memo, depth + 1)
end
end
memo[val] = nil
end
end
function ubjson.encode(value, state)
local buffer = {}
local memo = {}
encode(value, buffer, memo, 3)
out = ''
for k, v in pairs(buffer) do
out = out .. v
end
return out
end
function hex(str)
local out = ''
for i = 1, #str do
out = out .. string.format('%02x', str:byte(i))
end
return out
end
function ascii(str)
local out = ''
for i = 1, #str do
local c = str:sub(i, i)
if c:match('%g') then
out = out .. c .. ' '
else
out = (out .. ' ')
end
end
return out
end
local function test(val)
local enc = ubjson.encode(val)
print('length:', #enc)
print(hex(enc))
print(ascii(enc))
end
test({1, 2, 3, 4})
test({1, 2, 3, 4, 5, -1})
test({0, 1, 2, 3, 4, 5})
test({PiELESDigitalVals = {true, true, true, true, true, true, true, true},
PiELESAnalogVals = {127, 127, 127, 127, 127, 127, 127}})
test{[1] = 1, [3] = 4, [14] = 5}
t = {}
t[1] = t
xpcall(test, print, t)
|
Fix depth of error message.
|
Fix depth of error message.
|
Lua
|
apache-2.0
|
tobinsarah/tenshi,jessicakam/tenshi,tobinsarah/tenshi,cduck/tenshi,jarzofjam/tenshi,tobinsarah/tenshi,chuen0630/tenshi,JaronArmiger/tenshi,JaronArmiger/tenshi,jarzofjam/tenshi,SamboyKirk/tenshi,pioneers/tenshi,hozhu123/tenshi,tobinsarah/tenshi,abhishyantkhare/tenshi,SamboyKirk/tenshi,cduck/tenshi,tobinsarah/tenshi,zentner-kyle/tenshi-old,abhishyantkhare/tenshi,tobinsarah/tenshi,hozhu123/tenshi,JaronArmiger/tenshi,zentner-kyle/tenshi-old,jarzofjam/tenshi,zentner-kyle/tenshi-old,chuen0630/tenshi,pioneers/tenshi,SamboyKirk/tenshi,SamboyKirk/tenshi,JaronArmiger/tenshi,jessicakam/tenshi,jessicakam/tenshi,chuen0630/tenshi,jarzofjam/tenshi,jessicakam/tenshi,abhishyantkhare/tenshi,hozhu123/tenshi,chuen0630/tenshi,jarzofjam/tenshi,pioneers/tenshi,jessicakam/tenshi,pioneers/tenshi,zentner-kyle/tenshi-old,hozhu123/tenshi,cduck/tenshi,zentner-kyle/tenshi-old,SamboyKirk/tenshi,chuen0630/tenshi,cduck/tenshi,JaronArmiger/tenshi,JaronArmiger/tenshi,jessicakam/tenshi,pioneers/tenshi,abhishyantkhare/tenshi,cduck/tenshi,hozhu123/tenshi,pioneers/tenshi,tobinsarah/tenshi,cduck/tenshi,hozhu123/tenshi,zentner-kyle/tenshi-old,pioneers/tenshi,jarzofjam/tenshi,cduck/tenshi,hozhu123/tenshi,abhishyantkhare/tenshi,chuen0630/tenshi,jessicakam/tenshi,jarzofjam/tenshi,SamboyKirk/tenshi,abhishyantkhare/tenshi,JaronArmiger/tenshi,abhishyantkhare/tenshi,SamboyKirk/tenshi,chuen0630/tenshi
|
e07bd8b2c7e95cb3fd4632c693b2915f64f53e0d
|
ssbase/gamemode/storeitems/accessories/tails_feline.lua
|
ssbase/gamemode/storeitems/accessories/tails_feline.lua
|
ITEM.ID = "tails_feline" -- Should be a unique string that identifies the item
ITEM.Name = "Tail (Cat)" -- The name the item should display
ITEM.Price = 2000
ITEM.Model = "models/mrgiggles/skeyler/accessories/tails_feline.mdl" -- Model used by the item
ITEM.Type = "tail" -- Also works for stuff like "mask" and such. Used for item compatibility
ITEM.Colorable = false -- Used if the model is colorable via setcolor (or in a models case, setplayercolor)
ITEM.Tintable = false -- Used if the model is colorable, but a translation is needed to $selfillumtint
ITEM.Rotate = 45
ITEM.CamPos = Vector(30, 22, -3) -- Used the modify the position of the camera on DModelPanels
ITEM.LookAt = Vector(-20, 0, -3) -- Used to change the angle at which the camera views the model
ITEM.Fov = 20
ITEM.Functions = {} -- Anything that can be called but not a gmod hook but more of a "store hook" goes here
ITEM.Functions["Equip"] = function () -- e.g miku hair attach with the models Equip
end
ITEM.Functions["Unequip"] = function () -- e.g miku hair attach with the models Equip
end
ITEM.Hooks = {} -- Could run some shit in think hook maybe clientside only (e.g. repositioning or HEALTH CALCULATIONS OR SOMETHING LIKE THAT)
ITEM.Hooks["UpdateAnimation"] = function (item,ply)
if CLIENT then
if(SS.STORE.CSModels[ply] && SS.STORE.CSModels[ply][item.ID]) then
local i = SS.STORE.CSModels[ply][item.ID]
if(ply:GetWalkSpeed() == ply:GetRunSpeed()) then
ply.running = false
if(ply:GetVelocity():Length() == 0) then
ply.idle = true
else
ply.idle = false
end
elseif(ply:GetVelocity():Length() > ply:GetWalkSpeed()+25) then
ply.running = true
ply.idle = false
elseif(ply:Speed() == 0) then
ply.idle = true
else
ply.idle = false
ply.running = false
end
local tidle = i:LookupSequence("ACT_IDLE") -- This should eliminate the need to figure out which enumerations are what
--local twalk = i:LookupSequence("ACT_WALK")
--local trun = i:LookupSequence("ACT_RUN")
if ply.idle then
i:SetSequence(tidle)
elseif(!ply.running && i:GetSequence() != 5) then
i:SetSequence(5)
elseif(ply.running && i:GetSequence() != 4) then
i:SetSequence(4)
end
if(i.lastthink) then
i:FrameAdvance(RealTime()-i.lastthink) --this function better fucking work I HAD TO FIND THIS IN DMODELPANEL ITS NOT EVEN DOCUMENTED!
end
i.lastthink = CurTime()
end
end
end
/* ACCESSORY VARIABLES */
ITEM.Bone = "ValveBiped.Bip01_Spine" -- Bone the item is attached to. ONLY NEED TO DEFINE FOR HATS/ACCESSORIES.
ITEM.BoneMerge = false -- May be used for certain accessories to bonemerge the item instead. ONLY NEED TO DEFINE FOR HATS/ACCESSORIES.
ITEM.Models = {}
ITEM.Models["elin"] = { ["0_0_0_0"]= {pos=Vector(0, -2.6, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["miku"] = { ["0_0_0_0"]= {pos=Vector(0, -3.4, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["tron"] = { ["0_0_0_0"]= {pos=Vector(0.2, -3.5, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["usif"] = { ["0_0_0_0"]= {pos=Vector(1.5, -0.75, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["zer0"] = { ["0_0_0_0"]= {pos=Vector(0.35, -5.25, 0), ang=Angle(0, 180, -90), scale=2.0774}}
/* ************* */
|
ITEM.ID = "tails_feline" -- Should be a unique string that identifies the item
ITEM.Name = "Tail (Cat)" -- The name the item should display
ITEM.Price = 2000
ITEM.Model = "models/mrgiggles/skeyler/accessories/tails_feline.mdl" -- Model used by the item
ITEM.Type = "tail" -- Also works for stuff like "mask" and such. Used for item compatibility
ITEM.Colorable = false -- Used if the model is colorable via setcolor (or in a models case, setplayercolor)
ITEM.Tintable = false -- Used if the model is colorable, but a translation is needed to $selfillumtint
ITEM.Rotate = 45
ITEM.CamPos = Vector(30, 22, -3) -- Used the modify the position of the camera on DModelPanels
ITEM.LookAt = Vector(-20, 0, -3) -- Used to change the angle at which the camera views the model
ITEM.Fov = 20
ITEM.Functions = {} -- Anything that can be called but not a gmod hook but more of a "store hook" goes here
ITEM.Functions["Equip"] = function () -- e.g miku hair attach with the models Equip
end
ITEM.Functions["Unequip"] = function () -- e.g miku hair attach with the models Equip
end
ITEM.Hooks = {} -- Could run some shit in think hook maybe clientside only (e.g. repositioning or HEALTH CALCULATIONS OR SOMETHING LIKE THAT)
ITEM.Hooks["UpdateAnimation"] = function (item,ply)
if CLIENT then
if(SS.STORE.CSModels[ply] && SS.STORE.CSModels[ply][item.ID]) then
local i = SS.STORE.CSModels[ply][item.ID]
if(ply:GetWalkSpeed() == ply:GetRunSpeed()) then
ply.running = false
if(ply:GetVelocity():Length() == 0) then
ply.idle = true
else
ply.idle = false
end
elseif(ply:GetVelocity():Length() > ply:GetWalkSpeed()+25) then
ply.running = true
ply.idle = false
elseif(ply:Speed() == 0) then
ply.idle = true
else
ply.idle = false
ply.running = false
end
local tidle = i:LookupSequence("idle01") -- Tables also wrong names, I checked the sequence names in my modelviewer
local twalk = i:LookupSequence("walk_unarmed")
local trun = i:LookupSequence("run_unarmed")
if (ply.idle) then
i:SetSequence(tidle)
elseif(!ply.running) then
i:SetSequence(twalk)
elseif(ply.running) then
i:SetSequence(trun)
end
if(i.lastthink) then
i:FrameAdvance(CurTime()-i.lastthink) --this function better fucking work I HAD TO FIND THIS IN DMODELPANEL ITS NOT EVEN DOCUMENTED!
end
i.lastthink = CurTime()
end
end
end
/* ACCESSORY VARIABLES */
ITEM.Bone = "ValveBiped.Bip01_Spine" -- Bone the item is attached to. ONLY NEED TO DEFINE FOR HATS/ACCESSORIES.
ITEM.BoneMerge = false -- May be used for certain accessories to bonemerge the item instead. ONLY NEED TO DEFINE FOR HATS/ACCESSORIES.
ITEM.Models = {}
ITEM.Models["elin"] = { ["0_0_0_0"]= {pos=Vector(0, -2.6, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["miku"] = { ["0_0_0_0"]= {pos=Vector(0, -3.4, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["tron"] = { ["0_0_0_0"]= {pos=Vector(0.2, -3.5, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["usif"] = { ["0_0_0_0"]= {pos=Vector(1.5, -0.75, 0), ang=Angle(0, 180, -90), scale=2.0774}}
ITEM.Models["zer0"] = { ["0_0_0_0"]= {pos=Vector(0.35, -5.25, 0), ang=Angle(0, 180, -90), scale=2.0774}}
/* ************* */
|
Possible fix for spazzy tail
|
Possible fix for spazzy tail
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
a70686aa48edfba30b238fe996e3bd6632ae1d91
|
scripts/texturec.lua
|
scripts/texturec.lua
|
--
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
project "texturec"
uuid "838801ee-7bc3-11e1-9f19-eae7d36e7d26"
kind "ConsoleApp"
defines {
"ENTRY_CONFIG_PROFILER=0",
}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "src"),
}
files {
path.join(BGFX_DIR, "src/image.*"),
path.join(BGFX_DIR, "tools/texturec/**.cpp"),
path.join(BGFX_DIR, "tools/texturec/**.h"),
}
links {
-- "bgfx",
}
configuration { "osx" }
links {
"Cocoa.framework",
}
|
--
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
project "texturec"
uuid "838801ee-7bc3-11e1-9f19-eae7d36e7d26"
kind "ConsoleApp"
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "src"),
path.join(BGFX_DIR, "3rdparty"),
}
files {
path.join(BGFX_DIR, "src/image.*"),
path.join(BGFX_DIR, "tools/texturec/**.cpp"),
path.join(BGFX_DIR, "tools/texturec/**.h"),
}
links {
-- "bgfx",
}
configuration { "osx" }
links {
"Cocoa.framework",
}
|
Fixed "fix"
|
Fixed "fix"
|
Lua
|
bsd-2-clause
|
Synxis/bgfx,bkaradzic/bgfx,0-wiz-0/bgfx,MikePopoloski/bgfx,jdryg/bgfx,Synxis/bgfx,aonorin/bgfx,MikePopoloski/bgfx,bkaradzic/bgfx,septag/bgfx,jpcy/bgfx,marco-we/bgfx,LWJGL-CI/bgfx,emoon/bgfx,0-wiz-0/bgfx,v3n/bgfx,mendsley/bgfx,jdryg/bgfx,fluffyfreak/bgfx,v3n/bgfx,fluffyfreak/bgfx,emoon/bgfx,bkaradzic/bgfx,mmicko/bgfx,bkaradzic/bgfx,attilaz/bgfx,jpcy/bgfx,attilaz/bgfx,jdryg/bgfx,fluffyfreak/bgfx,LWJGL-CI/bgfx,kondrak/bgfx,aonorin/bgfx,andr3wmac/bgfx,marco-we/bgfx,septag/bgfx,kondrak/bgfx,attilaz/bgfx,fluffyfreak/bgfx,mendsley/bgfx,LWJGL-CI/bgfx,aonorin/bgfx,v3n/bgfx,mmicko/bgfx,septag/bgfx,LWJGL-CI/bgfx,jdryg/bgfx,marco-we/bgfx,andr3wmac/bgfx,elmindreda/bgfx,0-wiz-0/bgfx,Synxis/bgfx,jpcy/bgfx,mendsley/bgfx,mmicko/bgfx,elmindreda/bgfx,elmindreda/bgfx,emoon/bgfx,kondrak/bgfx,andr3wmac/bgfx,MikePopoloski/bgfx,jpcy/bgfx
|
f70ccfc0d207aaa504e44adc557c93c7a6aadc82
|
tests/proxymenu/proxymenu.lua
|
tests/proxymenu/proxymenu.lua
|
require "fmt"
stead.proxy_prefix = ' '
local function proxy_wrap(nam, fwd)
if not fwd then fwd = nam end
return function(s, ...)
local t
local o = _(s.ref)
local act = s.acts or { }
act = act[nam] or nam
local r, v = std.call(std.game, 'before_'..act, o, ...)
t = std.par(std.scene_delim, t or false, r)
if v == false then
return t or r, true
end
if nam == 'use' then
local oo = {...}
oo = oo[1]
if oo:type 'proxy' then
oo = _(oo.ref)
end
r, v = std.call(oo, s.acts.used or 'used', o)
t = std.par(std.scene_delim, t or false, r)
if v == true then
oo['__nr_used'] = (oo['__nr_used'] or 0) + 1
return t or r, true
end
r, v = std.call(o, act, oo)
else
r, v = std.call(o, act, ...)
end
t = std.par(std.scene_delim, t or false, r)
if type(v) == 'boolean' then
o['__nr_'..act] = (o['__nr_'..act] or 0) + 1
end
if r ~= nil and v == false then -- deny
return t or r, true
end
if v then
r, v = std.call(std.game, 'after_'..act, o, ...)
t = std.par(std.scene_delim, t or false, r)
end
if not t then -- game action
r, v = std.call(game, act, o, ...)
t = std.par(std.scene_delim, t or false, r)
end
return t or r, true
end
end
std.proxy_obj = std.class ({
__proxy_type = true;
new = function(s, v)
if type(v) ~= 'table' then
std.err ("Wrong argument to std.proxy_obj: "..std.tostr(v), 2)
end
if not v.ref then
std.err ("Wrong argument to std.proxy_obj (no ref attr): "..std.tostr(v), 2)
end
if v.use_mode then
v.__menu_type = false
end
v = std.obj (v)
return v
end;
disp = function(s)
local o = _(s.ref)
if have(o) then
return stead.proxy_prefix..fmt.em(std.dispof(o))
end
return stead.proxy_prefix..std.dispof(o)
end;
act = proxy_wrap ('act');
inv = proxy_wrap ('inv');
use = proxy_wrap ('use');
menu = proxy_wrap ('menu');
tak = proxy_wrap ('tak');
}, std.menu)
local function fill_obj(v, s)
if not v:visible() then
return nil, false -- do not do it recurse
end
if not v:type 'menu' and not std.is_system(v) then -- usual objects
-- add to proxy
local o = {
ref = std.nameof(v),
use_mode = s.use_mode,
sources = s.sources,
acts = s.acts,
}
s.obj:add(new(proxy_obj, o))
end
if v:closed() then
return nil, false -- do not do it recurse
end
end
std.proxy_menu = std.class ({
__proxy_menu_type = true;
new = function(s, v)
if type(v) ~= 'table' then
std.err ("Wrong argument to std.proxy_obj: "..std.tostr(v), 2)
end
if v.disp then
v.title = v.disp
v.disp = nil
end
return std.menu(v)
end;
disp = function(s)
local d
if s.title then
d = std.call(s, 'title')
else
d = std.dispof(s)
end
-- s:fill()
if not s:closed() then
return fmt.u(fmt.b(fmt.nb(d)))
else
return fmt.b(fmt.nb(d))
end
end;
menu = function(s) -- open/close
if not s:closed() then
s:close()
else
std.me().obj:for_each(function (v)
if v:type 'proxy_menu' and v ~= s then
v:close()
end
end)
s:open()
end
return false
end;
fill = function(s) -- fill prox
s:for_each(function(v)
delete(v) -- delete obj
end)
s.obj:zap()
-- by default -- all obj
local src = s.sources or { scene = true }
if src.inv then
me():inventory():for_each(function(v)
fill_obj(v, s)
end)
end
if src.scene then
std.here():for_each(function(v)
return fill_obj(v, s)
end)
end
if src.ways then
std.here().way:for_each(function(v)
fill_obj(v, s)
end)
end
end;
}, std.menu)
std.menu_player = std.class ({
__menu_player_type = true;
new = function(self, v)
if type(v) ~= 'table' then
std.err ("Wrong argument to std.menu_player: "..std.tostr(v), 2)
end
if not v.nam then
v.nam = 'menu_player'
end
if not v.room then
v.room = 'main'
end
v.invent = std.list {}
return std.player(v)
end;
inventory = function(s)
return s.invent
end;
}, std.player)
function proxy_obj(v)
local vv = {
ref = v.ref;
use_mode = v.use_mode;
sources = v.sources;
acts = v.acts;
}
return std.proxy_obj(vv)
end
function proxy_menu(v)
local vv = {
nam = v.nam;
disp = v.disp;
use_mode = v.use_mode;
sources = v.sources;
acts = v.acts;
}
return std.proxy_menu(vv):close()
end
std.mod_init(function() -- declarations
declare 'proxy_obj' (proxy_obj)
declare 'proxy_menu' (proxy_menu)
end)
std.mod_step(function()
me().obj:for_each(function(v)
if v:type 'proxy_menu' then
v:fill()
end
end)
end)
|
require "fmt"
stead.proxy_prefix = ' '
local function proxy_wrap(nam, fwd)
if not fwd then fwd = nam end
return function(s, ...)
local t
local o = _(s.ref)
local act = s.acts or { }
act = act[nam] or nam
local r, v = std.call(std.game, 'before_'..act, o, ...)
t = std.par(std.scene_delim, t or false, r)
if v == false then
return t or r, true
end
if nam == 'use' then
local oo = {...}
oo = oo[1]
if oo:type 'proxy' then
oo = _(oo.ref)
end
r, v = std.call(oo, s.acts.used or 'used', o)
t = std.par(std.scene_delim, t or false, r)
if v == true then
oo['__nr_used'] = (oo['__nr_used'] or 0) + 1
return t or r, true
end
r, v = std.call(o, act, oo)
else
r, v = std.call(o, act, ...)
end
t = std.par(std.scene_delim, t or false, r)
if type(v) == 'boolean' then
o['__nr_'..act] = (o['__nr_'..act] or 0) + 1
end
if r ~= nil and v == false then -- deny
return t or r, true
end
if v then
r, v = std.call(std.game, 'after_'..act, o, ...)
t = std.par(std.scene_delim, t or false, r)
end
if not t then -- game action
r, v = std.call(game, act, o, ...)
t = std.par(std.scene_delim, t or false, r)
end
return t or r, true
end
end
std.proxy_obj = std.class ({
__proxy_type = true;
new = function(s, v)
if type(v) ~= 'table' then
std.err ("Wrong argument to std.proxy_obj: "..std.tostr(v), 2)
end
if not v.ref then
std.err ("Wrong argument to std.proxy_obj (no ref attr): "..std.tostr(v), 2)
end
if v.use_mode then
v.__menu_type = false
end
v = std.obj (v)
return v
end;
disp = function(s)
local o = _(s.ref)
local d = std.dispof(o)
if type(d) ~= 'string' then
return d
end
if have(o) then
return stead.proxy_prefix..fmt.em(d)
end
return stead.proxy_prefix..d
end;
act = proxy_wrap ('act');
inv = proxy_wrap ('inv');
use = proxy_wrap ('use');
menu = proxy_wrap ('menu');
tak = proxy_wrap ('tak');
}, std.menu)
local function fill_obj(v, s)
if not v:visible() then
return nil, false -- do not do it recurse
end
if not v:type 'menu' and not std.is_system(v) then -- usual objects
-- add to proxy
local o = {
ref = std.nameof(v),
use_mode = s.use_mode,
sources = s.sources,
acts = s.acts,
}
s.obj:add(new(proxy_obj, o))
end
if v:closed() then
return nil, false -- do not do it recurse
end
end
std.proxy_menu = std.class ({
__proxy_menu_type = true;
new = function(s, v)
if type(v) ~= 'table' then
std.err ("Wrong argument to std.proxy_obj: "..std.tostr(v), 2)
end
if v.disp then
v.title = v.disp
v.disp = nil
end
return std.menu(v)
end;
disp = function(s)
local d
if s.title then
d = std.call(s, 'title')
else
d = std.dispof(s)
end
-- s:fill()
if not s:closed() then
return fmt.u(fmt.b(fmt.nb(d)))
else
return fmt.b(fmt.nb(d))
end
end;
menu = function(s) -- open/close
if not s:closed() then
s:close()
else
std.me().obj:for_each(function (v)
if v:type 'proxy_menu' and v ~= s then
v:close()
end
end)
s:open()
end
return false
end;
fill = function(s) -- fill prox
s:for_each(function(v)
delete(v) -- delete obj
end)
s.obj:zap()
-- by default -- all obj
local src = s.sources or { scene = true }
if src.inv then
me():inventory():for_each(function(v)
fill_obj(v, s)
end)
end
if src.scene then
std.here():for_each(function(v)
return fill_obj(v, s)
end)
end
if src.ways then
std.here().way:for_each(function(v)
fill_obj(v, s)
end)
end
end;
}, std.menu)
std.menu_player = std.class ({
__menu_player_type = true;
new = function(self, v)
if type(v) ~= 'table' then
std.err ("Wrong argument to std.menu_player: "..std.tostr(v), 2)
end
if not v.nam then
v.nam = 'menu_player'
end
if not v.room then
v.room = 'main'
end
v.invent = std.list {}
return std.player(v)
end;
inventory = function(s)
return s.invent
end;
}, std.player)
function proxy_obj(v)
local vv = {
ref = v.ref;
use_mode = v.use_mode;
sources = v.sources;
acts = v.acts;
}
return std.proxy_obj(vv)
end
function proxy_menu(v)
local vv = {
nam = v.nam;
disp = v.disp;
use_mode = v.use_mode;
sources = v.sources;
acts = v.acts;
}
return std.proxy_menu(vv):close()
end
std.mod_init(function() -- declarations
declare 'proxy_obj' (proxy_obj)
declare 'proxy_menu' (proxy_menu)
end)
std.mod_step(function()
me().obj:for_each(function(v)
if v:type 'proxy_menu' then
v:fill()
end
end)
end)
|
proxymenu disp fix
|
proxymenu disp fix
|
Lua
|
mit
|
gl00my/stead3
|
bdc57888fbd2c68f536fbc3336a1ac49c0c6693a
|
lua/plugins/init.lua
|
lua/plugins/init.lua
|
local nvim = require'nvim'
local echoerr = require'tools'.messages.echoerr
-- local load_module = require'tools'.helpers.load_module
-- TODO: Add dynamic plugin load
if nvim.has('nvim-0.5') then
local plugins = {
iron = { ok = false, status = false},
lsp = { ok = false, status = false},
telescope = { ok = false, status = false},
neorocks = { ok = false, status = false},
treesitter = { ok = false, status = false},
-- snippets = { ok = false, status = false},
colors = { ok = false, status = false},
statusline = { ok = false, status = false},
completion = { ok = false, status = false},
}
for plugin, _ in pairs(plugins) do
local ok, status = pcall(require, 'plugins/'..plugin)
plugins[plugin].ok = ok
plugins[plugin].status = status
if not ok then
echoerr(string.format('Failed to load %s, Error: %s', plugin, status))
plugins[plugin].status = false
end
end
if plugins.telescope.ok and not plugins.telescope.status then
pcall(require, 'grep')
end
pcall(require, 'host')
pcall(require, 'work')
end
local function get_plugins()
return nvim.g.plugs
end
local plugins = get_plugins()
if plugins == nil then
return nil
end
local function convert2settings(name)
name = name:gsub('+', '')
name = name:gsub('[-/%.]', '_')
return name:lower()
end
-- TODO: Add glob function to call just the available configs
for plugin, _ in pairs(plugins) do
-- _ = nvim.plugins[plugin] -- Cache plugins for future use
local func_name = convert2settings(plugin)
local ok, error_code = pcall(nvim.command, 'runtime! autoload/plugins/'..func_name..'.vim')
if not ok and not error_code:match('Vim:E117') then
echoerr("Something failed '"..error_code.."' Happened trying to source "..func_name..".vim")
end
end
|
local nvim = require'nvim'
local echoerr = require'tools'.messages.echoerr
-- local load_module = require'tools'.helpers.load_module
-- TODO: Add dynamic plugin load
if nvim.has('nvim-0.5') then
local plugins = {
iron = { ok = false, status = false},
lsp = { ok = false, status = false},
telescope = { ok = false, status = false},
neorocks = { ok = false, status = false},
treesitter = { ok = false, status = false},
-- snippets = { ok = false, status = false},
colors = { ok = false, status = false},
statusline = { ok = false, status = false},
completion = { ok = false, status = false},
}
for plugin, _ in pairs(plugins) do
local ok, status = pcall(require, 'plugins/'..plugin)
plugins[plugin].ok = ok
plugins[plugin].status = status
if not ok then
echoerr(string.format('Failed to load %s, Error: %s', plugin, status))
plugins[plugin].status = false
end
end
pcall(require, 'host')
pcall(require, 'work')
end
local function get_plugins()
return nvim.g.plugs
end
local plugins = get_plugins()
if plugins == nil then
return nil
end
local function convert2settings(name)
name = name:gsub('+', '')
name = name:gsub('[-/%.]', '_')
return name:lower()
end
-- TODO: Add glob function to call just the available configs
for plugin, _ in pairs(plugins) do
-- _ = nvim.plugins[plugin] -- Cache plugins for future use
local func_name = convert2settings(plugin)
local ok, error_code = pcall(nvim.command, 'runtime! autoload/plugins/'..func_name..'.vim')
if not ok and not error_code:match('Vim:E117') then
echoerr("Something failed '"..error_code.."' Happened trying to source "..func_name..".vim")
end
end
|
fix: remove dead code
|
fix: remove dead code
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
5fcce8db2aeee016ab927c8ca36a715c02f982f9
|
example/custom.lua
|
example/custom.lua
|
function mean(vals)
local sum=0
for i=1,#vals do
sum = sum + vals[i]
end
return sum / #vals
end
function loc(chrom, start, stop)
return chrom .. ":" .. start .. "-" .. stop
end
CLINVAR_LOOKUP = {}
CLINVAR_LOOKUP['0'] = 'unknown'
CLINVAR_LOOKUP['1'] = 'germline'
CLINVAR_LOOKUP['2'] = 'somatic'
CLINVAR_LOOKUP['4'] = 'inherited'
CLINVAR_LOOKUP['8'] = 'paternal'
CLINVAR_LOOKUP['16'] = 'maternal'
CLINVAR_LOOKUP['32'] = 'de-novo'
CLINVAR_LOOKUP['64'] = 'biparental'
CLINVAR_LOOKUP['128'] = 'uniparental'
CLINVAR_LOOKUP['256'] = 'not-tested'
CLINVAR_LOOKUP['512'] = 'tested-inconclusive'
CLINVAR_LOOKUP['1073741824'] = 'other'
CLINVAR_SIG = {}
CLINVAR_SIG['0'] = 'uncertain'
CLINVAR_SIG['1'] = 'not-provided'
CLINVAR_SIG['2'] = 'benign'
CLINVAR_SIG['3'] = 'likely-benign'
CLINVAR_SIG['4'] = 'likely-pathogenic'
CLINVAR_SIG['5'] = 'pathogenic'
CLINVAR_SIG['6'] = 'drug-response'
CLINVAR_SIG['7'] = 'histocompatibility'
CLINVAR_SIG['255'] = 'other'
CLINVAR_SIG['.'] = '.'
function intotbl(ud)
local tbl = {}
for i=1,#ud do
tbl[i] = ud[i]
end
return tbl
end
-- from lua-users wiki
function split(str, sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
str:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function contains(str, tok)
return string.find(str, tok) ~= nil
end
function div2(a, b)
if(a == 0) then return "0.0" end
return string.format("%.9f", (a + 0) / b)
end
function ratio(vals)
vals = vals[1] -- get 2 values per element. ref and alt counts.
if vals[2] == 0 then return "0.0" end
return string.format("%.9f", vals[2] / (vals[1] + vals[2]))
end
function clinvar_sig(vals)
local t = type(vals)
-- just a single-value
if(t == "string" or t == "number") and not contains(vals, "|") then
return CLINVAR_SIG[vals]
elseif t ~= "table" then
if not contains(t, "userdata") then
if t == "string" then
vals = split(vals, ",")
else
vals = {vals}
end
else
vals = intotbl(vals)
end
end
local ret = {}
for i=1,#vals do
if not contains(vals[i], "|") then
ret[#ret+1] = CLINVAR_SIG[vals[i]]
else
local invals = split(vals[i], "|")
local inret = {}
for j=1,#invals do
inret[#inret+1] = CLINVAR_SIG[invals[j]]
end
ret[#ret+1] = join(inret, "|")
end
end
return join(ret, ",")
end
join = table.concat
function check_clinvar_aaf(clinvar_sig, max_aaf_all, aaf_cutoff)
-- didn't find an aaf for this so can't be common
if max_aaf_all == nil or clinvar_sig == nil then
return false
end
if type(clinvar_sig) ~= "string" then
clinvar_sig = join(clinvar_sig, ",")
end
return contains(clinvar_sig, "pathogenic") and max_aaf_all > aaf_cutoff
end
function setid(...)
local t = {...}
local res = {}
local seen = {}
for i, v in pairs(t) do
if v ~= "." and v ~= nil and v ~= "" then
if seen[v] == nil then
res[#res+1] = string.gsub(v, ",", ";")
seen[v] = true
end
end
end
return table.concat(res, ";")
end
|
function mean(vals)
local sum=0
for i=1,#vals do
sum = sum + vals[i]
end
return sum / #vals
end
function loc(chrom, start, stop)
return chrom .. ":" .. start .. "-" .. stop
end
CLINVAR_LOOKUP = {}
CLINVAR_LOOKUP['0'] = 'unknown'
CLINVAR_LOOKUP['1'] = 'germline'
CLINVAR_LOOKUP['2'] = 'somatic'
CLINVAR_LOOKUP['4'] = 'inherited'
CLINVAR_LOOKUP['8'] = 'paternal'
CLINVAR_LOOKUP['16'] = 'maternal'
CLINVAR_LOOKUP['32'] = 'de-novo'
CLINVAR_LOOKUP['64'] = 'biparental'
CLINVAR_LOOKUP['128'] = 'uniparental'
CLINVAR_LOOKUP['256'] = 'not-tested'
CLINVAR_LOOKUP['512'] = 'tested-inconclusive'
CLINVAR_LOOKUP['1073741824'] = 'other'
CLINVAR_SIG = {}
CLINVAR_SIG['0'] = 'uncertain'
CLINVAR_SIG['1'] = 'not-provided'
CLINVAR_SIG['2'] = 'benign'
CLINVAR_SIG['3'] = 'likely-benign'
CLINVAR_SIG['4'] = 'likely-pathogenic'
CLINVAR_SIG['5'] = 'pathogenic'
CLINVAR_SIG['6'] = 'drug-response'
CLINVAR_SIG['7'] = 'histocompatibility'
CLINVAR_SIG['255'] = 'other'
CLINVAR_SIG['.'] = '.'
function intotbl(ud)
local tbl = {}
for i=1,#ud do
tbl[i] = ud[i]
end
return tbl
end
-- from lua-users wiki
function split(str, sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
str:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function contains(str, tok)
return string.find(str, tok) ~= nil
end
function div2(a, b)
if(a == 0) then return "0.0" end
return string.format("%.9f", (a + 0) / b)
end
function ratio(vals)
vals = vals[1] -- get 2 values per element. ref and alt counts.
if vals[2] == 0 then return "0.0" end
return string.format("%.9f", vals[2] / (vals[1] + vals[2]))
end
function clinvar_sig(vals)
local t = type(vals)
-- just a single-value
if(t == "string" or t == "number") and not contains(vals, "|") then
return CLINVAR_SIG[vals]
elseif t ~= "table" then
if not contains(t, "userdata") then
if t == "string" then
vals = split(vals, ",")
else
vals = {vals}
end
else
vals = intotbl(vals)
end
end
local ret = {}
for i=1,#vals do
if not contains(vals[i], "|") then
ret[#ret+1] = CLINVAR_SIG[vals[i]]
else
local invals = split(vals[i], "|")
local inret = {}
for j=1,#invals do
inret[#inret+1] = CLINVAR_SIG[invals[j]]
end
ret[#ret+1] = join(inret, "|")
end
end
return join(ret, ",")
end
join = table.concat
function check_clinvar_aaf(clinvar_sig, max_aaf_all, aaf_cutoff)
-- didn't find an aaf for this so can't be common
if max_aaf_all == nil or clinvar_sig == nil then
return false
end
if type(clinvar_sig) ~= "string" then
clinvar_sig = join(clinvar_sig, ",")
end
if false == contains(clinvar_sig, "pathogenic") then
return false
end
if type(max_aaf_all) ~= "table" then
return max_aaf_all > aaf_cutoff
end
for i, aaf in pairs(max_aaf_all) do
if aaf > aaf_cutoff then
return true
end
end
return false
end
function setid(...)
local t = {...}
local res = {}
local seen = {}
for i, v in pairs(t) do
if v ~= "." and v ~= nil and v ~= "" then
if seen[v] == nil then
res[#res+1] = string.gsub(v, ",", ";")
seen[v] = true
end
end
end
return table.concat(res, ";")
end
|
fix clinvar code
|
fix clinvar code
|
Lua
|
mit
|
brentp/vcfanno,brentp/vcfanno,brentp/vcfanno
|
a169bcf354f3ac67aa5320c4fbf190859f408ded
|
kong/pdk/private/phases.lua
|
kong/pdk/private/phases.lua
|
local bit = require "bit"
local band = bit.band
local fmt = string.format
local PHASES = {
--init = 0x00000001,
init_worker = 0x00000001,
certificate = 0x00000002,
--set = 0x00000004,
rewrite = 0x00000010,
access = 0x00000020,
balancer = 0x00000040,
--content = 0x00000100,
header_filter = 0x00000200,
body_filter = 0x00000400,
--timer = 0x00001000,
log = 0x00002000,
preread = 0x00004000,
admin_api = 0x10000000,
}
do
local n = 0
for k, v in pairs(PHASES) do
n = n + 1
PHASES[v] = k
end
PHASES.n = n
end
local function new_phase(...)
return bit.bor(...)
end
local function get_phases_names(phases)
local names = {}
local n = 1
for _ = 1, PHASES.n do
if band(phases, n) ~= 0 and PHASES[n] then
table.insert(names, PHASES[n])
end
n = bit.lshift(n, 1)
end
return names
end
local function check_phase(accepted_phases)
if not kong then
-- no _G.kong, we are likely in tests
return
end
local current_phase = kong.ctx.core.phase
if not current_phase then
error("no phase in kong.ctx.core.phase")
end
if band(current_phase, accepted_phases) ~= 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local accepted_phases_names = get_phases_names(accepted_phases)
error(fmt("function cannot be called in %s phase (only in: %s)",
current_phase_name,
table.concat(accepted_phases_names, ", ")))
end
local function check_not_phase(rejected_phases)
if not kong then
-- no _G.kong, we are likely in tests
return
end
local current_phase = kong.ctx.core.phase
if not current_phase then
error("no phase in kong.ctx.core.phase")
end
if band(current_phase, rejected_phases) == 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local rejected_phases_names = get_phases_names(rejected_phases)
error(fmt("function cannot be called in %s phase (can be called in any " ..
"phases except: %s)",
current_phase_name,
table.concat(rejected_phases_names, ", ")))
end
-- Exact phases + convenience aliases
local public_phases = setmetatable({
request = new_phase(PHASES.rewrite,
PHASES.access,
PHASES.header_filter,
PHASES.body_filter,
PHASES.log,
PHASES.admin_api),
}, {
__index = function(t, k)
error("unknown phase or phase alias: " .. k)
end
})
for k, v in pairs(PHASES) do
public_phases[k] = v
end
return {
new = new_phase,
check = check_phase,
check_not = check_not_phase,
phases = public_phases,
}
|
local bit = require "bit"
local band = bit.band
local fmt = string.format
local ngx_get_phase = ngx.get_phase
local PHASES = {
--init = 0x00000001,
init_worker = 0x00000001,
certificate = 0x00000002,
--set = 0x00000004,
rewrite = 0x00000010,
access = 0x00000020,
balancer = 0x00000040,
--content = 0x00000100,
header_filter = 0x00000200,
body_filter = 0x00000400,
--timer = 0x00001000,
log = 0x00002000,
preread = 0x00004000,
admin_api = 0x10000000,
}
do
local n = 0
for k, v in pairs(PHASES) do
n = n + 1
PHASES[v] = k
end
PHASES.n = n
end
local function new_phase(...)
return bit.bor(...)
end
local function get_phases_names(phases)
local names = {}
local n = 1
for _ = 1, PHASES.n do
if band(phases, n) ~= 0 and PHASES[n] then
table.insert(names, PHASES[n])
end
n = bit.lshift(n, 1)
end
return names
end
local function check_phase(accepted_phases)
if not kong then
-- no _G.kong, we are likely in tests
return
end
local current_phase = kong.ctx.core.phase
if not current_phase then
if ngx_get_phase() == "content" then
-- treat custom content blocks as the Admin API
current_phase = PHASES.admin_api
else
error("no phase in kong.ctx.core.phase")
end
end
if band(current_phase, accepted_phases) ~= 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local accepted_phases_names = get_phases_names(accepted_phases)
error(fmt("function cannot be called in %s phase (only in: %s)",
current_phase_name,
table.concat(accepted_phases_names, ", ")))
end
local function check_not_phase(rejected_phases)
if not kong then
-- no _G.kong, we are likely in tests
return
end
local current_phase = kong.ctx.core.phase
if not current_phase then
error("no phase in kong.ctx.core.phase")
end
if band(current_phase, rejected_phases) == 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local rejected_phases_names = get_phases_names(rejected_phases)
error(fmt("function cannot be called in %s phase (can be called in any " ..
"phases except: %s)",
current_phase_name,
table.concat(rejected_phases_names, ", ")))
end
-- Exact phases + convenience aliases
local public_phases = setmetatable({
request = new_phase(PHASES.rewrite,
PHASES.access,
PHASES.header_filter,
PHASES.body_filter,
PHASES.log,
PHASES.admin_api),
}, {
__index = function(t, k)
error("unknown phase or phase alias: " .. k)
end
})
for k, v in pairs(PHASES) do
public_phases[k] = v
end
return {
new = new_phase,
check = check_phase,
check_not = check_not_phase,
phases = public_phases,
}
|
fix(pdk) treat custom content blocks as the Admin API
|
fix(pdk) treat custom content blocks as the Admin API
This is a small workaround to a problem that happens when any custom
content_by_lua block attempts to use the PDK. For example, this happens when
trying to hit the `/` endpoint of the metrics server of the Prometheus plugin:
https://github.com/Kong/kong-plugin-prometheus/blob/0.4.1/kong/plugins/prometheus/serve.lua#L32
In normal operation of Kong, `kong.ctx.core.phase` is always set,
so the code path added should never be hit.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
|
e6fd69d402142bb2e2513ff48b9dce421f624f11
|
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
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
744d292b8ecbc3bea733f91f3350a9d4c2437f38
|
.config/nvim/lua/config/tabline.lua
|
.config/nvim/lua/config/tabline.lua
|
local status_ok, p = pcall(require, "tabline")
if not status_ok then
return
end
p.setup({
enable = true,
options = {
show_filename_only = true,
},
})
local lualine_status_ok, lualine = pcall(require, "lualine")
if not lualine_status_ok then
return
end
lualine.setup({
tabline = {
lualine_a = {},
lualine_b = {},
lualine_c = { require("tabline").tabline_buffers },
lualine_x = { require("tabline").tabline_tabs },
lualine_y = {},
lualine_z = {},
},
})
-- store tabpages and globals in session
vim.opt.sessionoptions:append("tabpages,globals")
|
local status_ok, p = pcall(require, "tabline")
if not status_ok then
return
end
p.setup({
enable = true,
options = {
show_filename_only = true,
},
})
-- NOTE: tabline読み込み後に発火させる
vim.api.nvim_create_autocmd({ "ModeChanged" }, {
group = "_",
once = true,
callback = function()
p.toggle_show_all_buffers()
end,
})
local lualine_status_ok, lualine = pcall(require, "lualine")
if not lualine_status_ok then
return
end
lualine.setup({
tabline = {
lualine_a = {},
lualine_b = {},
lualine_c = { require("tabline").tabline_buffers },
lualine_x = { require("tabline").tabline_tabs },
lualine_y = {},
lualine_z = {},
},
})
-- store tabpages and globals in session
vim.opt.sessionoptions:append("tabpages,globals")
|
[nvim] Fix tabline config
|
[nvim] Fix tabline config
|
Lua
|
mit
|
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
|
f0a0e503783d6571c1a0a90bf14e7531b2f2a176
|
libs/httpd/luasrc/httpd.lua
|
libs/httpd/luasrc/httpd.lua
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]>
(c) 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.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
local _meta = {__mode = "k"}
setmetatable(threads, _meta)
setmetatable(threadm, _meta)
setmetatable(threadi, _meta)
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threadc = threadc - 1
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]>
(c) 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.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
local _meta = {__mode = "k"}
setmetatable(threadm, _meta)
setmetatable(threadi, _meta)
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threadc = threadc - 1
threads[client] = nil
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
collectgarbage()
socket.sleep(THREAD_IDLEWAIT)
end
end
|
* libs/httpd: Fixed garbage collection
|
* libs/httpd: Fixed garbage collection
|
Lua
|
apache-2.0
|
Wedmer/luci,dismantl/luci-0.12,zhaoxx063/luci,fkooman/luci,florian-shellfire/luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,chris5560/openwrt-luci,oneru/luci,joaofvieira/luci,NeoRaider/luci,shangjiyu/luci-with-extra,male-puppies/luci,marcel-sch/luci,rogerpueyo/luci,Noltari/luci,male-puppies/luci,sujeet14108/luci,florian-shellfire/luci,Wedmer/luci,dwmw2/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,MinFu/luci,LuttyYang/luci,jorgifumi/luci,keyidadi/luci,deepak78/new-luci,teslamint/luci,kuoruan/lede-luci,RuiChen1113/luci,jchuang1977/luci-1,cappiewu/luci,opentechinstitute/luci,slayerrensky/luci,nwf/openwrt-luci,chris5560/openwrt-luci,jorgifumi/luci,kuoruan/luci,cshore-firmware/openwrt-luci,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,deepak78/new-luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/luci,981213/luci-1,joaofvieira/luci,shangjiyu/luci-with-extra,Hostle/luci,bright-things/ionic-luci,palmettos/test,Kyklas/luci-proto-hso,jlopenwrtluci/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,nmav/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,palmettos/cnLuCI,chris5560/openwrt-luci,artynet/luci,artynet/luci,thess/OpenWrt-luci,rogerpueyo/luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,wongsyrone/luci-1,bright-things/ionic-luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,tcatm/luci,oneru/luci,sujeet14108/luci,remakeelectric/luci,david-xiao/luci,dismantl/luci-0.12,Sakura-Winkey/LuCI,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,Wedmer/luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,lbthomsen/openwrt-luci,Hostle/luci,slayerrensky/luci,nmav/luci,obsy/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,artynet/luci,LuttyYang/luci,joaofvieira/luci,cappiewu/luci,mumuqz/luci,wongsyrone/luci-1,zhaoxx063/luci,maxrio/luci981213,ollie27/openwrt_luci,wongsyrone/luci-1,keyidadi/luci,Kyklas/luci-proto-hso,aircross/OpenWrt-Firefly-LuCI,jorgifumi/luci,Wedmer/luci,urueedi/luci,hnyman/luci,wongsyrone/luci-1,maxrio/luci981213,bittorf/luci,RuiChen1113/luci,taiha/luci,981213/luci-1,openwrt/luci,ff94315/luci-1,harveyhu2012/luci,schidler/ionic-luci,joaofvieira/luci,thesabbir/luci,palmettos/test,RedSnake64/openwrt-luci-packages,thess/OpenWrt-luci,oneru/luci,taiha/luci,taiha/luci,deepak78/new-luci,teslamint/luci,taiha/luci,artynet/luci,slayerrensky/luci,dwmw2/luci,RedSnake64/openwrt-luci-packages,bittorf/luci,cshore-firmware/openwrt-luci,joaofvieira/luci,lbthomsen/openwrt-luci,harveyhu2012/luci,dwmw2/luci,tobiaswaldvogel/luci,urueedi/luci,oyido/luci,nmav/luci,kuoruan/luci,keyidadi/luci,opentechinstitute/luci,jlopenwrtluci/luci,lcf258/openwrtcn,obsy/luci,david-xiao/luci,chris5560/openwrt-luci,palmettos/cnLuCI,nwf/openwrt-luci,dismantl/luci-0.12,jorgifumi/luci,jlopenwrtluci/luci,cshore/luci,openwrt/luci,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,male-puppies/luci,fkooman/luci,oyido/luci,bright-things/ionic-luci,kuoruan/luci,obsy/luci,harveyhu2012/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,thesabbir/luci,Noltari/luci,Hostle/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,slayerrensky/luci,tcatm/luci,bittorf/luci,Hostle/luci,lbthomsen/openwrt-luci,david-xiao/luci,joaofvieira/luci,cappiewu/luci,kuoruan/luci,hnyman/luci,dismantl/luci-0.12,marcel-sch/luci,cshore/luci,deepak78/new-luci,aa65535/luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,david-xiao/luci,openwrt/luci,mumuqz/luci,aircross/OpenWrt-Firefly-LuCI,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,oneru/luci,aa65535/luci,palmettos/test,thesabbir/luci,openwrt/luci,lcf258/openwrtcn,slayerrensky/luci,cappiewu/luci,thess/OpenWrt-luci,dismantl/luci-0.12,oyido/luci,Noltari/luci,mumuqz/luci,LuttyYang/luci,ff94315/luci-1,forward619/luci,cshore-firmware/openwrt-luci,NeoRaider/luci,MinFu/luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,zhaoxx063/luci,sujeet14108/luci,jorgifumi/luci,remakeelectric/luci,Hostle/luci,cappiewu/luci,Kyklas/luci-proto-hso,tobiaswaldvogel/luci,hnyman/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,cshore/luci,hnyman/luci,harveyhu2012/luci,daofeng2015/luci,openwrt/luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,forward619/luci,openwrt/luci,david-xiao/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,oyido/luci,nmav/luci,dwmw2/luci,thesabbir/luci,lbthomsen/openwrt-luci,opentechinstitute/luci,sujeet14108/luci,marcel-sch/luci,bright-things/ionic-luci,Sakura-Winkey/LuCI,981213/luci-1,dwmw2/luci,palmettos/cnLuCI,jchuang1977/luci-1,forward619/luci,RedSnake64/openwrt-luci-packages,forward619/luci,daofeng2015/luci,harveyhu2012/luci,florian-shellfire/luci,maxrio/luci981213,jlopenwrtluci/luci,daofeng2015/luci,Wedmer/luci,chris5560/openwrt-luci,fkooman/luci,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,oneru/luci,NeoRaider/luci,forward619/luci,palmettos/test,bittorf/luci,urueedi/luci,kuoruan/lede-luci,RuiChen1113/luci,aa65535/luci,jlopenwrtluci/luci,sujeet14108/luci,tcatm/luci,forward619/luci,cshore-firmware/openwrt-luci,palmettos/test,taiha/luci,ff94315/luci-1,Kyklas/luci-proto-hso,lbthomsen/openwrt-luci,harveyhu2012/luci,NeoRaider/luci,sujeet14108/luci,remakeelectric/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,fkooman/luci,ff94315/luci-1,remakeelectric/luci,shangjiyu/luci-with-extra,male-puppies/luci,zhaoxx063/luci,florian-shellfire/luci,chris5560/openwrt-luci,opentechinstitute/luci,kuoruan/lede-luci,LuttyYang/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,deepak78/new-luci,kuoruan/luci,urueedi/luci,david-xiao/luci,remakeelectric/luci,bittorf/luci,rogerpueyo/luci,male-puppies/luci,teslamint/luci,NeoRaider/luci,oyido/luci,maxrio/luci981213,teslamint/luci,MinFu/luci,nmav/luci,mumuqz/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,bright-things/ionic-luci,MinFu/luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,taiha/luci,lcf258/openwrtcn,oneru/luci,dwmw2/luci,palmettos/cnLuCI,zhaoxx063/luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,bittorf/luci,lcf258/openwrtcn,david-xiao/luci,zhaoxx063/luci,sujeet14108/luci,ollie27/openwrt_luci,Noltari/luci,mumuqz/luci,teslamint/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,981213/luci-1,Hostle/luci,ff94315/luci-1,bright-things/ionic-luci,deepak78/new-luci,openwrt/luci,Noltari/luci,florian-shellfire/luci,schidler/ionic-luci,bittorf/luci,tobiaswaldvogel/luci,forward619/luci,cshore-firmware/openwrt-luci,NeoRaider/luci,nwf/openwrt-luci,artynet/luci,schidler/ionic-luci,openwrt-es/openwrt-luci,Sakura-Winkey/LuCI,nwf/openwrt-luci,jchuang1977/luci-1,florian-shellfire/luci,Sakura-Winkey/LuCI,schidler/ionic-luci,palmettos/test,shangjiyu/luci-with-extra,daofeng2015/luci,schidler/ionic-luci,mumuqz/luci,teslamint/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,jorgifumi/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,palmettos/test,RedSnake64/openwrt-luci-packages,aa65535/luci,male-puppies/luci,male-puppies/luci,bright-things/ionic-luci,aa65535/luci,florian-shellfire/luci,ollie27/openwrt_luci,fkooman/luci,bright-things/ionic-luci,daofeng2015/luci,jorgifumi/luci,deepak78/new-luci,NeoRaider/luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,oneru/luci,aa65535/luci,deepak78/new-luci,opentechinstitute/luci,remakeelectric/luci,ff94315/luci-1,Kyklas/luci-proto-hso,lcf258/openwrtcn,shangjiyu/luci-with-extra,thess/OpenWrt-luci,thess/OpenWrt-luci,keyidadi/luci,RuiChen1113/luci,harveyhu2012/luci,daofeng2015/luci,NeoRaider/luci,slayerrensky/luci,MinFu/luci,thesabbir/luci,kuoruan/lede-luci,teslamint/luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,thess/OpenWrt-luci,marcel-sch/luci,981213/luci-1,nmav/luci,slayerrensky/luci,tcatm/luci,LuttyYang/luci,oyido/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,Hostle/luci,jchuang1977/luci-1,opentechinstitute/luci,sujeet14108/luci,slayerrensky/luci,bittorf/luci,dwmw2/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,thesabbir/luci,tcatm/luci,jlopenwrtluci/luci,obsy/luci,cshore/luci,MinFu/luci,urueedi/luci,cshore/luci,opentechinstitute/luci,nmav/luci,hnyman/luci,remakeelectric/luci,oyido/luci,obsy/luci,nwf/openwrt-luci,981213/luci-1,maxrio/luci981213,cshore/luci,RedSnake64/openwrt-luci-packages,Noltari/luci,cshore/luci,marcel-sch/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,keyidadi/luci,kuoruan/luci,daofeng2015/luci,mumuqz/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,Sakura-Winkey/LuCI,ollie27/openwrt_luci,thess/OpenWrt-luci,taiha/luci,marcel-sch/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,981213/luci-1,kuoruan/luci,forward619/luci,palmettos/cnLuCI,artynet/luci,artynet/luci,lcf258/openwrtcn,taiha/luci,dismantl/luci-0.12,MinFu/luci,Hostle/luci,fkooman/luci,shangjiyu/luci-with-extra,aa65535/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,cshore/luci,nwf/openwrt-luci,cappiewu/luci,thesabbir/luci,tcatm/luci,daofeng2015/luci,kuoruan/lede-luci,male-puppies/luci,ReclaimYourPrivacy/cloak-luci,LuttyYang/luci,RuiChen1113/luci,Noltari/luci,keyidadi/luci,cappiewu/luci,palmettos/cnLuCI,zhaoxx063/luci,Noltari/luci,kuoruan/lede-luci,Wedmer/luci,jchuang1977/luci-1,maxrio/luci981213,david-xiao/luci,joaofvieira/luci,jchuang1977/luci-1,rogerpueyo/luci,urueedi/luci,teslamint/luci,marcel-sch/luci,Noltari/luci,artynet/luci,cappiewu/luci,MinFu/luci,RuiChen1113/luci,nmav/luci,wongsyrone/luci-1,Kyklas/luci-proto-hso,artynet/luci,chris5560/openwrt-luci,lcf258/openwrtcn,joaofvieira/luci,nwf/openwrt-luci,LuttyYang/luci,jchuang1977/luci-1,kuoruan/lede-luci,urueedi/luci,keyidadi/luci,openwrt/luci,aa65535/luci,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,nmav/luci,rogerpueyo/luci,obsy/luci,jlopenwrtluci/luci,Kyklas/luci-proto-hso,jorgifumi/luci,rogerpueyo/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,urueedi/luci,palmettos/cnLuCI,marcel-sch/luci,openwrt-es/openwrt-luci,obsy/luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,oyido/luci
|
a6d0d430a3ab5a188dcefa48923e8318c6cbc4f2
|
map/text.lua
|
map/text.lua
|
text = {}
local text = text
text.skills = {} --技能表,以技能ID为索引
--以1秒为周期进行循环检查
timer.loop(1,
function()
local hero = game.self()
local flag = jass.IsPlayerObserver(jass.GetLocalPlayer())
if hero then
for i = 0, 99 do
local ab = japi.EXGetUnitAbilityByIndex(hero, i)
if not ab then break end --如果技能不存在就结束
text.setAbText(ab)
end
end
for i = 1, #game.heroes do
local hero = game.heroes[i]
if flag then
for i = 0, 99 do
local ab = japi.EXGetUnitAbilityByIndex(hero, i)
if not ab then break end --如果技能不存在就结束
text.setAbText(ab)
end
end
jass.UnitAddAbility(hero, |Amgl|)
jass.UnitRemoveAbility(hero, |Amgl|)
end
end
)
--设置技能文本
text.setAbText = function(ab)
local id = japi.EXGetAbilityId(ab) --获取该技能的ID
local texts = text.skills[id]
local selfhero = game.self()
if texts == nil then
--如果该技能不在技能表中,则进行判定
if text.newAbText(ab, id) then
texts = text.skills[id]
else
return
end
elseif texts == false then
--该技能无需动态文本,直接跳过
return
end
--对文本进行动态修改
local lv = jass.GetUnitAbilityLevel(selfhero, id)
local nums = {}
local t = texts[lv] --该等级的数据
for i = 1 , 10 do
local func = t[i * 2 - 1]
if not func then
break
end
local num = t[i * 2]
table.insert(nums, func(selfhero, true) * num)
end
local te = string.format(t.text, unpack(nums))
japi.EXSetAbilityDataString(ab, lv, 218, te)
japi.EXSetAbilityDataString(ab, 1, 217, texts.research)
end
--判定技能文本
text.newAbText = function(ab, id)
--获取该技能文本
local texts = {}
local flag = false
for i = 1, 10 do
local te = japi.EXGetAbilityDataString(ab, i, 218) --技能说明文本
if te ~= nil and te ~= "" then
local t = text.newText(te)
if t then
texts[i] = t
flag = true
end
texts.maxlv = i
else
break
end
end
if not flag then
--该技能无需动态文本,进行标记
text.skills[id] = false
return false
end
texts.research = japi.EXGetAbilityDataString(ab, 1, 217) --技能学习文本
text.skills[id] = texts
return true --该技能需要动态文本
end
--判定文本
text.newText = function(te)
local start = 1
local t = {}
local flag
te = string.gsub(te, "%%", "%%%%") --以免文本中本来包含的%符号被当做匹配符
while start do
start = string.find(te, "×", start)
if start then
local word = string.sub(te, start - 6, start - 1)
local func
if word == "力量" then
func = jass.GetHeroStr
elseif word == "敏捷" then
func = jass.GetHeroAgi
elseif word == "智力" then
func = jass.GetHeroInt
end
if func then
local s, e = string.find(te, "[%d.]+", start + 2)
if s then
local num = string.sub(te, s, e)
if te:sub(s - 9, s - 9) == '+' then
te = string.sub(te, 1, s - 10) .. "(+%d)" .. string.sub(te, e + 1, -1)
else
te = string.sub(te, 1, s - 9) .. "%d" .. string.sub(te, e + 1, -1)
end
table.insert(t, func)
table.insert(t, num)
flag = true
end
end
start = start + 1
end
end
if flag then
t.text = te
return t
end
end
|
text = {}
local text = text
text.skills = {} --技能表,以技能ID为索引
--以1秒为周期进行循环检查
timer.loop(1,
function()
local hero = game.self()
if hero then
for i = 0, 99 do
local ab = japi.EXGetUnitAbilityByIndex(hero, i)
if not ab then break end --如果技能不存在就结束
text.setAbText(ab)
end
end
for i = 1, #game.heroes do
local hero = game.heroes[i]
jass.UnitAddAbility(hero, |Amgl|)
jass.UnitRemoveAbility(hero, |Amgl|)
end
end
)
--设置技能文本
text.setAbText = function(ab)
local id = japi.EXGetAbilityId(ab) --获取该技能的ID
local texts = text.skills[id]
local selfhero = game.self()
if texts == nil then
--如果该技能不在技能表中,则进行判定
if text.newAbText(ab, id) then
texts = text.skills[id]
else
return
end
elseif texts == false then
--该技能无需动态文本,直接跳过
return
end
--对文本进行动态修改
local lv = jass.GetUnitAbilityLevel(selfhero, id)
local nums = {}
local t = texts[lv] --该等级的数据
for i = 1 , 10 do
local func = t[i * 2 - 1]
if not func then
break
end
local num = t[i * 2]
table.insert(nums, func(selfhero, true) * num)
end
local te = string.format(t.text, unpack(nums))
japi.EXSetAbilityDataString(ab, lv, 218, te)
japi.EXSetAbilityDataString(ab, 1, 217, texts.research)
end
--判定技能文本
text.newAbText = function(ab, id)
--获取该技能文本
local texts = {}
local flag = false
for i = 1, 10 do
local te = japi.EXGetAbilityDataString(ab, i, 218) --技能说明文本
if te ~= nil and te ~= "" then
local t = text.newText(te)
if t then
texts[i] = t
flag = true
end
texts.maxlv = i
else
break
end
end
if not flag then
--该技能无需动态文本,进行标记
text.skills[id] = false
return false
end
texts.research = japi.EXGetAbilityDataString(ab, 1, 217) --技能学习文本
text.skills[id] = texts
return true --该技能需要动态文本
end
--判定文本
text.newText = function(te)
local start = 1
local t = {}
local flag
te = string.gsub(te, "%%", "%%%%") --以免文本中本来包含的%符号被当做匹配符
while start do
start = string.find(te, "×", start)
if start then
local word = string.sub(te, start - 6, start - 1)
local func
if word == "力量" then
func = jass.GetHeroStr
elseif word == "敏捷" then
func = jass.GetHeroAgi
elseif word == "智力" then
func = jass.GetHeroInt
end
if func then
local s, e = string.find(te, "[%d.]+", start + 2)
if s then
local num = string.sub(te, s, e)
if te:sub(s - 9, s - 9) == '+' then
te = string.sub(te, 1, s - 10) .. "(+%d)" .. string.sub(te, e + 1, -1)
else
te = string.sub(te, 1, s - 9) .. "%d" .. string.sub(te, e + 1, -1)
end
table.insert(t, func)
table.insert(t, num)
flag = true
end
end
start = start + 1
end
end
if flag then
t.text = te
return t
end
end
|
修正裁判会掉线的BUG
|
修正裁判会掉线的BUG
|
Lua
|
apache-2.0
|
syj2010syj/All-star-Battle
|
1b6246a3c1eb8a838d7656df996b5e89c1c3d99c
|
nvim/lua/user/ui.lua
|
nvim/lua/user/ui.lua
|
local filereadable_key = 'filereadable'
local current_normal_winnr_key = 'current_normal_winnr'
local function file_exists(name)
local f = io.open(name, 'r')
return f ~= nil and io.close(f)
end
local function update_filereadable()
local path = vim.api.nvim_buf_get_name(0)
if path ~= '' then
vim.api.nvim_buf_set_var(0, filereadable_key, file_exists(path))
end
end
local function safe_buf_get_var(bufnr, name, default)
local ok, value = pcall(vim.api.nvim_buf_get_var, bufnr, name)
if ok then return value end
return default
end
local function safe_tabpage_get_var(tabnr, name, default)
local ok, value = pcall(vim.api.nvim_tabpage_get_var, tabnr, name)
if ok then return value end
return default
end
local function tabpage_get_win(tabnr)
local winnr = vim.api.nvim_tabpage_get_win(tabnr)
local config = vim.api.nvim_win_get_config(winnr)
local is_normal = config.relative == ''
if is_normal then
vim.api.nvim_tabpage_set_var(tabnr, current_normal_winnr_key, winnr)
return winnr
end
return safe_tabpage_get_var(tabnr, current_normal_winnr_key, winnr)
end
local function tabline()
local line = {}
local tab_list = vim.api.nvim_list_tabpages()
local current = vim.api.nvim_get_current_tabpage()
for _, tabnr in ipairs(tab_list) do
local winnr = tabpage_get_win(tabnr)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local path = vim.api.nvim_buf_get_name(bufnr)
local name = vim.fn.fnamemodify(path, ':t')
name = name ~= '' and name or '[No Name]'
local flags = {}
if vim.bo[bufnr].mod then
table.insert(flags, '+')
end
if not safe_buf_get_var(bufnr, filereadable_key, true) then
table.insert(flags, '?')
end
local tab = {
'%', tabnr, 'T',
(tabnr == current and '%#TabLineSel#' or '%#TabLine#'),
' ', name,
(#flags > 0 and ' ' .. table.concat(flags, '') or ''),
' ',
}
table.insert(line, table.concat(tab, ''))
end
table.insert(line, '%#TabLineFill#')
return table.concat(line, '')
end
local function render_statusline(winnr, active)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local path = vim.api.nvim_buf_get_name(bufnr)
local buftype = vim.bo[bufnr].buftype
local is_file = (buftype == '')
local l0 = {}
local l1 = {}
local r1 = {}
local r0 = {}
if active then
table.insert(l0, '%#StatusLineMode#▌%#StatusLineL0#')
else
table.insert(l0, '%#StatusLine#')
end
if active then
local filetype = vim.bo[bufnr].filetype
table.insert(l0, filetype == '' and 'plain' or filetype)
else
if is_file and path ~= '' then
local rel_path = vim.fn.fnamemodify(path, ':p:~:.')
table.insert(l0, rel_path)
elseif is_file then
table.insert(l0, '[No Name]')
else
table.insert(l0, buftype)
end
end
local flags = {}
if vim.bo[bufnr].readonly then
table.insert(flags, '!')
end
if vim.bo[bufnr].modified then
table.insert(flags, '+')
end
if not safe_buf_get_var(bufnr, filereadable_key, true) then
table.insert(flags, '?')
end
if #flags > 0 then
table.insert(l0, table.concat(flags, ''))
end
if active and is_file then
local last_saved_time = safe_buf_get_var(bufnr, 'auto_save_last_saved_time', 0)
if 0 < last_saved_time and last_saved_time >= os.time() - 60 then
table.insert(l1, os.date('✓ %X', last_saved_time))
end
end
if active then
local diagnostics = { E = 0, W = 0, I = 0, H = 0 }
local status = safe_buf_get_var(bufnr, 'coc_diagnostic_info', nil)
if status then
diagnostics.E = diagnostics.E + (status.error or 0)
diagnostics.W = diagnostics.W + (status.warning or 0)
diagnostics.I = diagnostics.I + (status.information or 0)
diagnostics.H = diagnostics.H + (status.hint or 0)
end
if diagnostics.E > 0 then
local text = string.format('%%#StatusLineDiagnosticsError#%s %d%%*', '✗', diagnostics.E)
table.insert(l1, text)
end
if diagnostics.W > 0 then
local text = string.format('%%#StatusLineDiagnosticsWarning#%s %d%%*', '∆', diagnostics.W)
table.insert(l1, text)
end
if diagnostics.I > 0 then
local text = string.format('%%#StatusLineDiagnosticsInfo#%s %d%%*', '▸', diagnostics.I)
table.insert(l1, text)
end
if diagnostics.H > 0 then
local text = string.format('%%#StatusLineDiagnosticsHint#%s %d%%*', '▪︎', diagnostics.H)
table.insert(l1, text)
end
end
local coc_status = vim.g.coc_status or ''
if active and coc_status ~= '' then
table.insert(r1, string.sub(coc_status, 0, 60))
end
if active then
local encoding = vim.bo[bufnr].fileencoding
local format = vim.bo[bufnr].fileformat
table.insert(r0, encoding ~= '' and encoding or vim.o.encoding)
table.insert(r0, format)
table.insert(r0, '∙')
table.insert(r0, '%l:%c')
table.insert(r0, '∙')
table.insert(r0, '%p%%')
end
return table.concat({
table.concat(l0, ' '),
'%*',
table.concat(l1, ' '),
'%=',
table.concat(r1, ' '),
'%*',
table.concat(r0, ' '),
'%*',
}, ' ')
end
local function statusline()
local winnr = vim.g.statusline_winid
local active = winnr == vim.fn.win_getid()
if active then
require('candle').update_mode_highlight()
end
return render_statusline(winnr, active)
end
local function setup()
vim.o.tabline = [[%!v:lua.require'user.ui'.tabline()]]
vim.o.statusline = [[%!v:lua.require'user.ui'.statusline()]]
vim.api.nvim_exec([[
augroup user_ui_statusline
autocmd!
autocmd FocusGained,BufEnter,BufReadPost,BufWritePost * lua require'user.ui'.update_filereadable()
autocmd WinLeave,BufLeave * lua vim.wo.statusline=require'user.ui'.statusline()
autocmd BufWinEnter,WinEnter,BufEnter * set statusline<
autocmd VimResized * redrawstatus
augroup END
]], false)
end
return {
setup = setup,
statusline = statusline,
tabline = tabline,
update_filereadable = update_filereadable,
}
|
local filereadable_key = 'filereadable'
local current_normal_winnr_key = 'current_normal_winnr'
local function file_exists(name)
local f = io.open(name, 'r')
return f ~= nil and io.close(f)
end
local function update_filereadable()
local path = vim.api.nvim_buf_get_name(0)
if path ~= '' then
vim.api.nvim_buf_set_var(0, filereadable_key, file_exists(path))
end
end
local function safe_buf_get_var(bufnr, name, default)
local ok, value = pcall(vim.api.nvim_buf_get_var, bufnr, name)
if ok then return value end
return default
end
local function safe_tabpage_get_var(tabnr, name, default)
local ok, value = pcall(vim.api.nvim_tabpage_get_var, tabnr, name)
if ok then return value end
return default
end
local function tabpage_get_win(tabnr)
local winnr = vim.api.nvim_tabpage_get_win(tabnr)
local config = vim.api.nvim_win_get_config(winnr)
local is_normal = config.relative == ''
if is_normal then
vim.api.nvim_tabpage_set_var(tabnr, current_normal_winnr_key, winnr)
return winnr
end
return safe_tabpage_get_var(tabnr, current_normal_winnr_key, winnr)
end
local function tabline()
local line = {}
local tab_list = vim.api.nvim_list_tabpages()
local current = vim.api.nvim_get_current_tabpage()
for _, tabnr in ipairs(tab_list) do
local winnr = tabpage_get_win(tabnr)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local path = vim.api.nvim_buf_get_name(bufnr)
local name = vim.fn.fnamemodify(path, ':t')
name = name ~= '' and name or '[No Name]'
local flags = {}
if vim.bo[bufnr].mod then
table.insert(flags, '+')
end
if not safe_buf_get_var(bufnr, filereadable_key, true) then
table.insert(flags, '?')
end
local tab = {
'%', tabnr, 'T',
(tabnr == current and '%#TabLineSel#' or '%#TabLine#'),
' ', name,
(#flags > 0 and ' ' .. table.concat(flags, '') or ''),
' ',
}
table.insert(line, table.concat(tab, ''))
end
table.insert(line, '%#TabLineFill#')
return table.concat(line, '')
end
local function render_statusline(winnr, active)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local path = vim.api.nvim_buf_get_name(bufnr)
local buftype = vim.bo[bufnr].buftype
local is_file = (buftype == '')
local l0 = {}
local l1 = {}
local r1 = {}
local r0 = {}
if active then
table.insert(l0, '%#StatusLineMode#▌%#StatusLineL0#')
else
table.insert(l0, '%#StatusLine#')
end
if active then
local filetype = vim.bo[bufnr].filetype
table.insert(l0, filetype == '' and 'plain' or filetype)
else
if is_file and path ~= '' then
local rel_path = vim.fn.fnamemodify(path, ':p:~:.')
table.insert(l0, rel_path)
elseif is_file then
table.insert(l0, '[No Name]')
else
table.insert(l0, buftype)
end
end
local flags = {}
if vim.bo[bufnr].readonly then
table.insert(flags, '!')
end
if vim.bo[bufnr].modified then
table.insert(flags, '+')
end
if not safe_buf_get_var(bufnr, filereadable_key, true) then
table.insert(flags, '?')
end
if #flags > 0 then
table.insert(l0, table.concat(flags, ''))
end
if active and is_file then
local last_saved_time = safe_buf_get_var(bufnr, 'auto_save_last_saved_time', 0)
if 0 < last_saved_time and last_saved_time >= os.time() - 60 then
table.insert(l1, os.date('✓ %X', last_saved_time))
end
end
if active then
local diagnostics = { E = 0, W = 0, I = 0, H = 0 }
local status = safe_buf_get_var(bufnr, 'coc_diagnostic_info', nil)
if status then
diagnostics.E = diagnostics.E + (status.error or 0)
diagnostics.W = diagnostics.W + (status.warning or 0)
diagnostics.I = diagnostics.I + (status.information or 0)
diagnostics.H = diagnostics.H + (status.hint or 0)
end
if diagnostics.E > 0 then
local text = string.format('%%#StatusLineDiagnosticsError#%s %d%%*', '✗', diagnostics.E)
table.insert(l1, text)
end
if diagnostics.W > 0 then
local text = string.format('%%#StatusLineDiagnosticsWarning#%s %d%%*', '∆', diagnostics.W)
table.insert(l1, text)
end
if diagnostics.I > 0 then
local text = string.format('%%#StatusLineDiagnosticsInfo#%s %d%%*', '▸', diagnostics.I)
table.insert(l1, text)
end
if diagnostics.H > 0 then
local text = string.format('%%#StatusLineDiagnosticsHint#%s %d%%*', '▪︎', diagnostics.H)
table.insert(l1, text)
end
end
local coc_status = vim.g.coc_status or ''
if active and coc_status ~= '' then
table.insert(r1, string.sub(coc_status, 0, 60))
end
if active then
local encoding = vim.bo[bufnr].fileencoding
local format = vim.bo[bufnr].fileformat
table.insert(r0, encoding ~= '' and encoding or vim.o.encoding)
table.insert(r0, format)
table.insert(r0, '∙')
table.insert(r0, '%l:%c')
table.insert(r0, '∙')
table.insert(r0, '%p%%')
end
return table.concat({
table.concat(l0, ' '),
'%*',
table.concat(l1, ' '),
'%=',
table.concat(r1, ' '),
'%*',
table.concat(r0, ' '),
'%*',
}, ' ')
end
local function statusline()
local winnr = vim.g.statusline_winid
local active = winnr == vim.fn.win_getid()
if active then
require('candle').update_mode_highlight()
end
if not winnr then
return
end
return render_statusline(winnr, active)
end
local function setup()
vim.o.tabline = [[%!v:lua.require'user.ui'.tabline()]]
vim.o.statusline = [[%!v:lua.require'user.ui'.statusline()]]
vim.api.nvim_exec([[
augroup user_ui_statusline
autocmd!
autocmd FocusGained,BufEnter,BufReadPost,BufWritePost * lua require'user.ui'.update_filereadable()
autocmd WinLeave,BufLeave * lua vim.wo.statusline=require'user.ui'.statusline()
autocmd BufWinEnter,WinEnter,BufEnter * set statusline<
autocmd VimResized * redrawstatus
augroup END
]], false)
end
return {
setup = setup,
statusline = statusline,
tabline = tabline,
update_filereadable = update_filereadable,
}
|
Fix for neovim 0.7.0
|
Fix for neovim 0.7.0
|
Lua
|
mit
|
creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles
|
bae3044fc23fa5716810c4ce4b7e91bbabb3a467
|
src_trunk/resources/killmessages/vgkillmessages_server.lua
|
src_trunk/resources/killmessages/vgkillmessages_server.lua
|
local config = {
["lines"] = 5,
["startY"] = 0.35,
["textHeight"] = 16,
["iconHeight"] = 20,
["iconSpacing"] = 4,
["defaultWeapon"] = 255,
["fadeTime"] = 5000,
["startFade"] = 15000,
["align"] = "right",
["startX"] = -10
}
local default = {
["lines"] = 5,
["startY"] = 0.25,
["textHeight"] = 16,
["iconHeight"] = 20,
["iconSpacing"] = 4,
["defaultWeapon"] = 255,
["fadeTime"] = 5000,
["startFade"] = 15000,
["align"] = "right",
["startX"] = -10
}
local vehicleIDs = { [50]=true,[49]=true,[31]=true,[38]=true,[52]=true }
function KillMessages_onPlayerWasted ( totalammo, killer, killerweapon, bodypart )
---These are special checks for certain kill types
local usedVehicle
if killerweapon == 19 then --rockets
killerweapon = getPlayerWeapon(killer)
if not killerweapon then
killerweapon = 51
end
elseif vehicleIDs[killerweapon] then --heliblades/rammed
if ( getElementType ( killer ) == "vehicle" ) then
usedVehicle = getElementModel ( killer )
killer = getVehicleOccupant ( killer, 0 )
end
elseif ( killerweapon == 59 ) then
if ( getElementType ( killer ) == "player" ) then
local vehicle = getPedOccupiedVehicle(killer)
if ( vehicle ) then
usedVehicle = getElementModel ( vehicle )
end
end
end
--finish this
-- Got a killer? Print the normal "* X died" if not
if ( killer ) then
local kr,kg,kb = getPlayerNametagColor ( killer )
if getPlayerTeam ( source ) then
kr,kg,kb = getTeamColor ( getPlayerTeam ( killer ) )
end
-- Suicide?
if (source == killer) then
if not killerweapon then killerweapon = 255 end
local triggered = triggerEvent ( "onPlayerKillMessage", source,false,killerweapon,bodypart )
--outputDebugString ( "Cancelled: "..tostring(triggered) )
if ( triggered ) then
eventTriggered ( source,false,killerweapon,bodypart,true,usedVehicle)
return
end
end
local triggered = triggerEvent ( "onPlayerKillMessage", source,killer,killerweapon,bodypart )
--outputDebugString ( "Cancelled: "..tostring(triggered) )
if ( triggered ) then
eventTriggered ( source,killer,killerweapon,bodypart,false,usedVehicle)
end
else
local triggered = triggerEvent ( "onPlayerKillMessage", getRandomPlayer(),false,killerweapon,bodypart )
--outputDebugString ( "Cancelled: "..tostring(triggered) )
if ( triggered ) then
eventTriggered ( source,false,killerweapon,bodypart,false,usedVehicle)
end
end
end
addEventHandler ( "onPlayerWasted", getRootElement(), KillMessages_onPlayerWasted )
addEvent ( "onPlayerKillMessage", "wasted,killer,weapon" )
function eventTriggered ( source,killer,weapon,bodypart,suicide,usedVehicle )
local wr,wg,wb = getPlayerNametagColor ( source )
if getPlayerTeam ( source ) then
wr,wg,wb = getTeamColor ( getPlayerTeam ( source ) )
end
local kr,kg,kb = false,false,false
if ( killer ) then
kr,kg,kb = getPlayerNametagColor ( killer )
if getPlayerTeam ( source ) then
kr,kg,kb = getTeamColor ( getPlayerTeam ( killer ) )
end
end
if ( usedVehicle ) then
weapon = usedVehicle
end
outputKillMessage ( source, wr,wg,wb,killer,kr,kg,kb,weapon )
--
local extra = ""
if ( usedVehicle ) then
extra = " (Vehicle)"
end
if ( killer ) then
if suicide then
local weaponName = getWeaponNameFromID ( weapon )
if weaponName then
outputConsoleKillMessage ( "* "..getPlayerName(source).." killed himself. ("..weaponName..")" )
else
outputConsoleKillMessage ( "* "..getPlayerName(source).." killed himself."..extra )
end
else
local weaponName = getWeaponNameFromID ( weapon )
if weaponName then
outputConsoleKillMessage ( "* "..getPlayerName(killer).." killed "..getPlayerName(source)..". ("..weaponName..")" )
else
outputConsoleKillMessage ( "* "..getPlayerName(killer).." killed "..getPlayerName(source).."."..extra )
end
end
else
outputConsoleKillMessage ( "* "..getPlayerName(source).." died."..extra )
end
--
end
function outputConsoleKillMessage ( text )
local time = getRealTime()
text = ("[%02d:%02d] %s"):format(time.hour, time.minute, text)
for k, v in pairs(exports.pool:getPoolElementsByType("player")) do
if exports.global:isPlayerAdmin(v) then
return triggerClientEvent(v,"onClientPlayerKillMessageConsole",v,text)
end
end
end
function outputKillMessage ( killed, wr,wg,wb,killer,kr,kg,kb,weapon,width,resource )
if ( resource ) then resource = getResourceName(resource) end
if not isElement(killed) then
outputDebugString ( "outputKillMessage - Invalid 'wasted' player specified",0,0,0,100)
return false
end
if not getElementType(killed) == "player" then
outputDebugString ( "outputKillMessage - Invalid 'wasted' player specified",0,0,0,100)
return false
end
for k, v in pairs(exports.pool:getPoolElementsByType("player")) do
if tonumber(getElementData(v, "adminduty")) == 1 then
return triggerClientEvent(v,"onClientPlayerKillMessage",killed,killer,weapon,wr,wg,wb,kr,kg,kb,width,resource )
end
end
end
function outputMessage ( message, visibleTo, r, g, b, font )
if type(message) ~= "string" and type(message) ~= "table" then
outputDebugString ( "outputMessage - Bad 'message' argument", 0, 112, 112, 112 )
return false
end
if not isElement(visibleTo) then
outputDebugString ( "outputMessage - Bad argument", 0, 112, 112, 112 )
return false
end
--Turn any resources into resource names
if type(message) == "table" then
for i,part in ipairs(message) do
if type(part) == "table" and part[1] == "image" then
if part.resource then
message[i].resourceName = getResourceName(part.resource)
else
part.resourceName = getResourceName(sourceResource)
end
end
end
end
return triggerClientEvent ( visibleTo, "doOutputMessage", visibleTo, message, r, g, b, font )
end
function setKillMessageStyle ( startX,startY,align,lines,fadeStart,fadeAnimTime )
if ( not startX ) then startX = default.startX end
if ( not startY ) then startY = default.startY end
if ( not align ) then startY = align.startY end
if ( not lines ) then lines = default.lines end
if ( not fadeStart ) then fadeStart = default.startFade end
if ( not fadeAnimTime ) then fadeAnimTime = default.fadeTime end
config.startX = startX
config.startY = startY
config.align = align
config.lines = lines
config.startFade = fadeStart
config.fadeTime = fadeAnimTime
for k,v in ipairs(getElementsByType"player") do
triggerClientEvent(v,"doSetKillMessageStyle",v,config.startX,config.startY,config.alignX,config.lines,config.startFade,config.fadeTime)
end
return true
end
addEvent ("onClientKillmessagesLoaded",true)
addEventHandler ( "onClientKillmessagesLoaded", getRootElement(),
function()
triggerClientEvent(source,"doSetKillMessageStyle",source,config.startX,config.startY,config.alignX,config.lines,config.startFade,config.fadeTime)
end )
|
local config = {
["lines"] = 5,
["startY"] = 0.35,
["textHeight"] = 16,
["iconHeight"] = 20,
["iconSpacing"] = 4,
["defaultWeapon"] = 255,
["fadeTime"] = 5000,
["startFade"] = 15000,
["align"] = "right",
["startX"] = -10
}
local default = {
["lines"] = 5,
["startY"] = 0.25,
["textHeight"] = 16,
["iconHeight"] = 20,
["iconSpacing"] = 4,
["defaultWeapon"] = 255,
["fadeTime"] = 5000,
["startFade"] = 15000,
["align"] = "right",
["startX"] = -10
}
local vehicleIDs = { [50]=true,[49]=true,[31]=true,[38]=true,[52]=true }
function KillMessages_onPlayerWasted ( totalammo, killer, killerweapon, bodypart )
---These are special checks for certain kill types
local usedVehicle
if killerweapon == 19 then --rockets
killerweapon = getPlayerWeapon(killer)
if not killerweapon then
killerweapon = 51
end
elseif vehicleIDs[killerweapon] then --heliblades/rammed
if ( getElementType ( killer ) == "vehicle" ) then
usedVehicle = getElementModel ( killer )
killer = getVehicleOccupant ( killer, 0 )
end
elseif ( killerweapon == 59 ) then
if ( getElementType ( killer ) == "player" ) then
local vehicle = getPedOccupiedVehicle(killer)
if ( vehicle ) then
usedVehicle = getElementModel ( vehicle )
end
end
end
--finish this
-- Got a killer? Print the normal "* X died" if not
if ( killer ) then
local kr,kg,kb = getPlayerNametagColor ( killer )
if getPlayerTeam ( source ) then
kr,kg,kb = getTeamColor ( getPlayerTeam ( killer ) )
end
-- Suicide?
if (source == killer) then
if not killerweapon then killerweapon = 255 end
local triggered = triggerEvent ( "onPlayerKillMessage", source,false,killerweapon,bodypart )
--outputDebugString ( "Cancelled: "..tostring(triggered) )
if ( triggered ) then
eventTriggered ( source,false,killerweapon,bodypart,true,usedVehicle)
return
end
end
local triggered = triggerEvent ( "onPlayerKillMessage", source,killer,killerweapon,bodypart )
--outputDebugString ( "Cancelled: "..tostring(triggered) )
if ( triggered ) then
eventTriggered ( source,killer,killerweapon,bodypart,false,usedVehicle)
end
else
local triggered = triggerEvent ( "onPlayerKillMessage", getRandomPlayer(),false,killerweapon,bodypart )
--outputDebugString ( "Cancelled: "..tostring(triggered) )
if ( triggered ) then
eventTriggered ( source,false,killerweapon,bodypart,false,usedVehicle)
end
end
end
addEventHandler ( "onPlayerWasted", getRootElement(), KillMessages_onPlayerWasted )
addEvent ( "onPlayerKillMessage", "wasted,killer,weapon" )
function eventTriggered ( source,killer,weapon,bodypart,suicide,usedVehicle )
local wr,wg,wb = getPlayerNametagColor ( source )
if getPlayerTeam ( source ) then
wr,wg,wb = getTeamColor ( getPlayerTeam ( source ) )
end
local kr,kg,kb = false,false,false
if ( killer ) then
kr,kg,kb = getPlayerNametagColor ( killer )
if getPlayerTeam ( source ) then
kr,kg,kb = getTeamColor ( getPlayerTeam ( killer ) )
end
end
if ( usedVehicle ) then
weapon = usedVehicle
end
outputKillMessage ( source, wr,wg,wb,killer,kr,kg,kb,weapon )
--
local extra = ""
if ( usedVehicle ) then
extra = " (Vehicle)"
end
if ( killer ) then
if suicide then
local weaponName = getWeaponNameFromID ( weapon )
if weaponName then
outputConsoleKillMessage ( "* "..getPlayerName(source).." killed himself. ("..weaponName..")" )
else
outputConsoleKillMessage ( "* "..getPlayerName(source).." killed himself."..extra )
end
else
local weaponName = getWeaponNameFromID ( weapon )
if weaponName then
outputConsoleKillMessage ( "* "..getPlayerName(killer).." killed "..getPlayerName(source)..". ("..weaponName..")" )
else
outputConsoleKillMessage ( "* "..getPlayerName(killer).." killed "..getPlayerName(source).."."..extra )
end
end
else
outputConsoleKillMessage ( "* "..getPlayerName(source).." died."..extra )
end
--
end
function outputConsoleKillMessage ( text )
local time = getRealTime()
text = ("[%02d:%02d] %s"):format(time.hour, time.minute, text)
for k, v in pairs(exports.pool:getPoolElementsByType("player")) do
if exports.global:isPlayerAdmin(v) then
triggerClientEvent(v,"onClientPlayerKillMessageConsole",v,text)
end
end
return true
end
function outputKillMessage ( killed, wr,wg,wb,killer,kr,kg,kb,weapon,width,resource )
if ( resource ) then resource = getResourceName(resource) end
if not isElement(killed) then
outputDebugString ( "outputKillMessage - Invalid 'wasted' player specified",0,0,0,100)
return false
end
if not getElementType(killed) == "player" then
outputDebugString ( "outputKillMessage - Invalid 'wasted' player specified",0,0,0,100)
return false
end
for k, v in pairs(exports.pool:getPoolElementsByType("player")) do
if tonumber(getElementData(v, "adminduty")) == 1 then
triggerClientEvent(v,"onClientPlayerKillMessage",killed,killer,weapon,wr,wg,wb,kr,kg,kb,width,resource )
end
end
return true
end
function outputMessage ( message, visibleTo, r, g, b, font )
if type(message) ~= "string" and type(message) ~= "table" then
outputDebugString ( "outputMessage - Bad 'message' argument", 0, 112, 112, 112 )
return false
end
if not isElement(visibleTo) then
outputDebugString ( "outputMessage - Bad argument", 0, 112, 112, 112 )
return false
end
--Turn any resources into resource names
if type(message) == "table" then
for i,part in ipairs(message) do
if type(part) == "table" and part[1] == "image" then
if part.resource then
message[i].resourceName = getResourceName(part.resource)
else
part.resourceName = getResourceName(sourceResource)
end
end
end
end
return triggerClientEvent ( visibleTo, "doOutputMessage", visibleTo, message, r, g, b, font )
end
function setKillMessageStyle ( startX,startY,align,lines,fadeStart,fadeAnimTime )
if ( not startX ) then startX = default.startX end
if ( not startY ) then startY = default.startY end
if ( not align ) then startY = align.startY end
if ( not lines ) then lines = default.lines end
if ( not fadeStart ) then fadeStart = default.startFade end
if ( not fadeAnimTime ) then fadeAnimTime = default.fadeTime end
config.startX = startX
config.startY = startY
config.align = align
config.lines = lines
config.startFade = fadeStart
config.fadeTime = fadeAnimTime
for k,v in ipairs(getElementsByType"player") do
triggerClientEvent(v,"doSetKillMessageStyle",v,config.startX,config.startY,config.alignX,config.lines,config.startFade,config.fadeTime)
end
return true
end
addEvent ("onClientKillmessagesLoaded",true)
addEventHandler ( "onClientKillmessagesLoaded", getRootElement(),
function()
triggerClientEvent(source,"doSetKillMessageStyle",source,config.startX,config.startY,config.alignX,config.lines,config.startFade,config.fadeTime)
end )
|
fix for killmessages
|
fix for killmessages
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1075 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
5e2040b2c5bd17d19de10de90fbda55afc52a8d9
|
Interface/AddOns/RayUI/mini/TooltipItemID/TooltipItemID.lua
|
Interface/AddOns/RayUI/mini/TooltipItemID/TooltipItemID.lua
|
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local
local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", function(_, _, name)
f:UnregisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", nil)
end)
local function addLine(self,id,isItem)
for i = 1, self:NumLines() do
local line = _G["GameTooltipTextLeft"..i]
if not line then break end
local text = line:GetText()
if text and (text:match("FFCA3C3C技能ID") or text:match("FFCA3C3C堆疊數") or text:match("FFCA3C3C已擁有") or text:match("FFCA3C3C物品ID")) then
return
end
end
self:AddLine(" ")
if isItem then
if select(8, GetItemInfo(id)) and select(8, GetItemInfo(id)) >1 then
self:AddDoubleLine("|cFFCA3C3C堆疊數:|r","|cffffffff"..select(8, GetItemInfo(id)))
end
if GetItemCount(id, true) and GetItemCount(id, true) - GetItemCount(id) > 0 then
self:AddDoubleLine("|cFFCA3C3C已擁有(|r"..R:RGBToHex(50/255, 217/255, 1).."銀行|r".."|cFFCA3C3C):|r","|cffffffff"..GetItemCount(id, true).."(|r"..R:RGBToHex(50/255, 217/255, 1)..GetItemCount(id, true) - GetItemCount(id).."|r|cffffffff)|r")
elseif GetItemCount(id) > 0 then
self:AddDoubleLine("|cFFCA3C3C已擁有:|r","|cffffffff"..GetItemCount(id))
end
self:AddDoubleLine("|cFFCA3C3C物品ID:|r","|cffffffff"..id)
else
self:AddDoubleLine("|cFFCA3C3C技能ID:|r","|cffffffff"..id)
end
self:Show()
end
hooksecurefunc(GameTooltip, "SetUnitConsolidatedBuff", function(self, unit, index)
local name = GetRaidBuffTrayAuraInfo(index)
local _, _, _, _, _, _, _, caster, _, _, id = UnitAura(unit, name)
if id then
self:AddLine(" ")
if caster then
self:AddLine(UnitName(caster))
end
self:AddDoubleLine("|cFFCA3C3C技能ID:|r","|cffffffff"..id)
self:Show()
end
end)
hooksecurefunc(GameTooltip, "SetUnitAura", function(self,...)
local id = select(11, UnitAura(...))
local caster = select (8, UnitAura(...))
if id then
self:AddLine(" ")
if caster ~= nil then
self:AddLine(UnitName(caster))
end
self:AddDoubleLine("|cFFCA3C3C技能ID:|r","|cffffffff"..id)
self:Show()
end
end)
GameTooltip:HookScript("OnTooltipSetSpell", function(self)
local id = select(3,self:GetSpell())
if id then addLine(self,id) end
end)
-- Item Hooks -----------------------------------------------------------------
hooksecurefunc("SetItemRef", function(link, ...)
local id = tonumber(link:match("spell:(%d+)"))
if id then addLine(ItemRefTooltip,id) end
end)
local function attachItemTooltip(self)
local link = select(2,self:GetItem())
if not link then return end
local id = select(3,strfind(link, "^|%x+|Hitem:(%-?%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%-?%d+):(%-?%d+)"))
if id then addLine(self,id,true) end
end
GameTooltip:HookScript("OnTooltipSetItem", attachItemTooltip)
ItemRefTooltip:HookScript("OnTooltipSetItem", attachItemTooltip)
ItemRefShoppingTooltip1:HookScript("OnTooltipSetItem", attachItemTooltip)
ItemRefShoppingTooltip2:HookScript("OnTooltipSetItem", attachItemTooltip)
ShoppingTooltip1:HookScript("OnTooltipSetItem", attachItemTooltip)
ShoppingTooltip2:HookScript("OnTooltipSetItem", attachItemTooltip)
|
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local
local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", function(_, _, name)
f:UnregisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", nil)
end)
local function addLine(self,id,isItem)
for i = 1, self:NumLines() do
local line = _G["GameTooltipTextLeft"..i]
if not line then break end
local text = line:GetText()
if text and (text:match("FFCA3C3C技能ID") or text:match("FFCA3C3C堆疊數") or text:match("FFCA3C3C已擁有") or text:match("FFCA3C3C物品ID")) then
return
end
end
self:AddLine(" ")
if isItem then
if select(8, GetItemInfo(id)) and select(8, GetItemInfo(id)) >1 then
self:AddDoubleLine("|cFFCA3C3C堆疊數:|r","|cffffffff"..select(8, GetItemInfo(id)))
end
if GetItemCount(id, true) and GetItemCount(id, true) - GetItemCount(id) > 0 then
self:AddDoubleLine("|cFFCA3C3C已擁有(|r"..R:RGBToHex(50/255, 217/255, 1).."銀行|r".."|cFFCA3C3C):|r","|cffffffff"..GetItemCount(id, true).."(|r"..R:RGBToHex(50/255, 217/255, 1)..GetItemCount(id, true) - GetItemCount(id).."|r|cffffffff)|r")
elseif GetItemCount(id) > 0 then
self:AddDoubleLine("|cFFCA3C3C已擁有:|r","|cffffffff"..GetItemCount(id))
end
self:AddDoubleLine("|cFFCA3C3C物品ID:|r","|cffffffff"..id)
else
self:AddDoubleLine("|cFFCA3C3C技能ID:|r","|cffffffff"..id)
end
self:Show()
end
hooksecurefunc(GameTooltip, "SetUnitConsolidatedBuff", function(self, unit, index)
local name = GetRaidBuffTrayAuraInfo(index)
local _, _, _, _, _, _, _, caster, _, _, id = UnitAura(unit, name)
if id then
self:AddLine(" ")
if caster then
self:AddLine(UnitName(caster))
end
self:AddDoubleLine("|cFFCA3C3C技能ID:|r","|cffffffff"..id)
self:Show()
end
end)
hooksecurefunc(GameTooltip, "SetUnitAura", function(self,...)
local id = select(11, UnitAura(...))
local caster = select (8, UnitAura(...))
if id then
self:AddLine(" ")
if caster ~= nil then
self:AddLine(UnitName(caster))
end
self:AddDoubleLine("|cFFCA3C3C技能ID:|r","|cffffffff"..id)
self:Show()
end
end)
GameTooltip:HookScript("OnTooltipSetSpell", function(self)
local id = select(3,self:GetSpell())
if id then addLine(self,id) end
end)
-- Item Hooks -----------------------------------------------------------------
hooksecurefunc("SetItemRef", function(link, ...)
local id = tonumber(link:match("spell:(%d+)"))
if id then addLine(ItemRefTooltip,id) end
end)
local function attachItemTooltip(self)
local link = select(2,self:GetItem())
if not link then return end
local itemId = tonumber(string.match(link, "item:(%d+):"))
if (itemId == 0 and TradeSkillFrame ~= nil and TradeSkillFrame:IsVisible()) then
local newItemId
if ((GetMouseFocus():GetName()) == "TradeSkillSkillIcon") then
newItemId = tonumber(GetTradeSkillItemLink(TradeSkillFrame.selectedSkill):match("item:(%d+):"))
else
for i = 1, 12 do
if ((GetMouseFocus():GetName()) == "TradeSkillReagent"..i) then
newItemId = tonumber(GetTradeSkillReagentItemLink(TradeSkillFrame.selectedSkill, i):match("item:(%d+):"))
break
end
end
end
_, link = GetItemInfo(newItemId)
end
local id = select(3,strfind(link, "^|%x+|Hitem:(%-?%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%-?%d+):(%-?%d+)"))
if id then addLine(self,id,true) end
end
GameTooltip:HookScript("OnTooltipSetItem", attachItemTooltip)
ItemRefTooltip:HookScript("OnTooltipSetItem", attachItemTooltip)
ItemRefShoppingTooltip1:HookScript("OnTooltipSetItem", attachItemTooltip)
ItemRefShoppingTooltip2:HookScript("OnTooltipSetItem", attachItemTooltip)
ShoppingTooltip1:HookScript("OnTooltipSetItem", attachItemTooltip)
ShoppingTooltip2:HookScript("OnTooltipSetItem", attachItemTooltip)
|
fix
|
fix
fix TradeSkillFrame Tooltip ItemID.Reference from BagSync
|
Lua
|
mit
|
fgprodigal/RayUI
|
363a8d84d6a979c91b0e1354735b6c4d5b73602a
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
local window,screen=require'hs.window',require'hs.screen'
local application,spaces=require'hs.application',require'hs.spaces'
local drawing,canvas=require'hs.drawing',require'hs.canvas'
local uielement=require'hs.uielement'
local fnutils=require'hs.fnutils'
-- local serial = require("hs._asm.serial")
local lastScreenId = -1
-- local usePhysicalIndicator = false
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorTopHeight = 23
local indicatorBottomHeight = 1
local indicatorTopColor = drawing.color.asRGB({
red = 0.99,
green = 0.76,
blue = 0.25,
alpha = 0.2
})
local indicatorBottomColor = drawing.color.asRGB({
red = 0.99,
green = 0.76,
blue = 0.25,
alpha = 0.4
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
-- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == application.watcher.launched then
watchApp(app)
elseif event == application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == uielement.watcher.windowCreated then
watchWindow(element)
elseif event == uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
else
handleMonitorMonitorChange()
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
frame = window:frame()
left = frame.x
width = frame.w
indicator = canvas.new{
x = left,
y = screeng.y,
w = width,
h = indicatorTopHeight + indicatorBottomHeight
}:appendElements(
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = 0,
w = width,
h = indicatorTopHeight
},
fillColor = indicatorTopColor
},
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = indicatorTopHeight,
w = width,
h = indicatorBottomHeight
},
fillColor = indicatorBottomColor
}
)
indicator
:level(canvas.windowLevels.cursor)
:behavior(canvas.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
-- function updatePhysicalScreenIndicator(screenId)
-- local devicePath = getSerialOutputDevice()
-- if devicePath == "" then return end
-- port = serial.port(devicePath):baud(115200):open()
-- if port:isOpen() then
-- port:write("set " .. screenId .. "\n")
-- port:flushBuffer()
-- port:close()
-- end
-- end
-- function getSerialOutputDevice()
-- local command = "ioreg -c IOSerialBSDClient -r -t " ..
-- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
-- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
-- local handle = io.popen(command)
-- local result = handle:read("*a")
-- handle:close()
-- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
-- return result:match("^%s*(.-)%s*$")
-- end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = application.runningApplications()
apps = fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
-- kind() returns -1 if the app is prohibited from GUI components
if app:kind() == -1 then return end
watcher:start({ uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
uielement.watcher.elementDestroyed,
uielement.watcher.windowResized,
uielement.watcher.windowMoved,
uielement.watcher.windowMinimized,
uielement.watcher.windowUnminimized
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = screen.primaryScreen():id()
for _, screen in pairs(screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
local window,screen=require'hs.window',require'hs.screen'
local application,spaces=require'hs.application',require'hs.spaces'
local drawing,canvas=require'hs.drawing',require'hs.canvas'
local uielement=require'hs.uielement'
local fnutils=require'hs.fnutils'
-- local serial = require("hs._asm.serial")
local lastScreenId = -1
-- local usePhysicalIndicator = false
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorBottomHeight = 1
local indicatorTopColor = drawing.color.asRGB({
red = 0.99,
green = 0.76,
blue = 0.25,
alpha = 0.2
})
local indicatorBottomColor = drawing.color.asRGB({
red = 0.99,
green = 0.76,
blue = 0.25,
alpha = 0.4
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
-- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == application.watcher.launched then
watchApp(app)
elseif event == application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == uielement.watcher.windowCreated then
watchWindow(element)
elseif event == uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
else
handleMonitorMonitorChange()
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
local frame = window:frame()
local left = frame.x
local width = frame.w
local menubarHeight = screen:frame().y - screeng.y
local indicatorTopHeight = menubarHeight - indicatorBottomHeight
if menubarHeight > 30 then
-- Notched Menubar
indicatorTopHeight = indicatorTopHeight - 1
end
indicator = canvas.new{
x = left,
y = screeng.y,
w = width,
h = menubarHeight
}:appendElements(
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = 0,
w = width,
h = indicatorTopHeight
},
fillColor = indicatorTopColor
},
{
action = "fill",
type = "rectangle",
frame = {
x = 0,
y = indicatorTopHeight,
w = width,
h = indicatorBottomHeight
},
fillColor = indicatorBottomColor
}
)
indicator
:level(canvas.windowLevels.cursor)
:behavior(canvas.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
-- function updatePhysicalScreenIndicator(screenId)
-- local devicePath = getSerialOutputDevice()
-- if devicePath == "" then return end
-- port = serial.port(devicePath):baud(115200):open()
-- if port:isOpen() then
-- port:write("set " .. screenId .. "\n")
-- port:flushBuffer()
-- port:close()
-- end
-- end
-- function getSerialOutputDevice()
-- local command = "ioreg -c IOSerialBSDClient -r -t " ..
-- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
-- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
-- local handle = io.popen(command)
-- local result = handle:read("*a")
-- handle:close()
-- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
-- return result:match("^%s*(.-)%s*$")
-- end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = application.runningApplications()
apps = fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
-- kind() returns -1 if the app is prohibited from GUI components
if app:kind() == -1 then return end
watcher:start({ uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
uielement.watcher.elementDestroyed,
uielement.watcher.windowResized,
uielement.watcher.windowMoved,
uielement.watcher.windowMinimized,
uielement.watcher.windowUnminimized
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = screen.primaryScreen():id()
for _, screen in pairs(screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
fix(hammerspoon): calculate actual menubar height
|
fix(hammerspoon): calculate actual menubar height
|
Lua
|
mit
|
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
|
228f92472717fe0208f32b6f851bf33c5af1446e
|
premake4.lua
|
premake4.lua
|
if not _ACTION then _ACTION="vs2010" end
solution "TaskScheduler"
language "C++"
location ( "Build/" .. _ACTION )
flags {"NoManifest", "ExtraWarnings", "StaticRuntime", "NoMinimalRebuild", "FloatFast", "EnableSSE2" }
optimization_flags = { "OptimizeSpeed" }
targetdir("Bin")
local config_list = {
"Release",
"Debug",
}
local platform_list = {
"x32",
"x64"
}
configurations(config_list)
platforms(platform_list)
-- CONFIGURATIONS
configuration "Release"
defines { "NDEBUG" }
flags { "Symbols", optimization_flags }
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
configuration "x32"
libdirs { "$(DXSDK_DIR)/Lib/x86" }
buildoptions { "/wd4127" }
configuration "x64"
libdirs { "$(DXSDK_DIR)/Lib/x64" }
buildoptions { "/wd4127" }
-- give each configuration/platform a unique output directory
for _, config in ipairs(config_list) do
for _, plat in ipairs(platform_list) do
configuration { config, plat }
objdir ( "build/" .. _ACTION .. "/tmp/" .. config .. "-" .. plat )
end
end
-- SUBPROJECTS
project "TaskScheduler"
flags {"NoPCH"}
kind "ConsoleApp"
files {
"Src/**.*",
}
includedirs
{
"Squish"
}
links {
"UnitTest++", "Squish"
}
project "UnitTest++"
kind "StaticLib"
defines { "_CRT_SECURE_NO_WARNINGS" }
files {
"TestFramework/UnitTest++/**.*",
}
excludes {
"TestFramework/UnitTest++/Posix/**.*"
}
project "Squish"
kind "StaticLib"
defines { "_CRT_SECURE_NO_WARNINGS" }
files {
"Squish/**.*",
}
includedirs
{
"Squish"
}
|
if not _ACTION then
_ACTION="vs2010"
end
isVisualStudio = false
if _ACTION == "vs2002" or _ACTION == "vs2003" or _ACTION == "vs2005" or _ACTION == "vs2008" or _ACTION == "vs2010" then
isVisualStudio = true
end
solution "TaskScheduler"
language "C++"
location ( "Build/" .. _ACTION )
flags {"NoManifest", "ExtraWarnings", "StaticRuntime", "NoMinimalRebuild", "FloatFast", "EnableSSE2" }
optimization_flags = { "OptimizeSpeed" }
targetdir("Bin")
local config_list = {
"Release",
"Debug",
}
local platform_list = {
"x32",
"x64"
}
configurations(config_list)
platforms(platform_list)
-- CONFIGURATIONS
configuration "Release"
defines { "NDEBUG" }
flags { "Symbols", optimization_flags }
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
configuration "x32"
libdirs { "$(DXSDK_DIR)/Lib/x86" }
if isVisualStudio then
buildoptions { "/wd4127" }
else
buildoptions { "-std=c++11 }
end
configuration "x64"
libdirs { "$(DXSDK_DIR)/Lib/x64" }
if isVisualStudio then
buildoptions { "/wd4127" }
else
buildoptions { "-std=c++11 }
end
-- give each configuration/platform a unique output directory
for _, config in ipairs(config_list) do
for _, plat in ipairs(platform_list) do
configuration { config, plat }
objdir ( "build/" .. _ACTION .. "/tmp/" .. config .. "-" .. plat )
end
end
-- SUBPROJECTS
project "TaskScheduler"
flags {"NoPCH"}
kind "ConsoleApp"
files {
"Src/**.*",
}
includedirs
{
"Squish"
}
links {
"UnitTest++", "Squish"
}
project "UnitTest++"
kind "StaticLib"
defines { "_CRT_SECURE_NO_WARNINGS" }
files {
"TestFramework/UnitTest++/**.*",
}
excludes {
"TestFramework/UnitTest++/Posix/**.*"
}
project "Squish"
kind "StaticLib"
defines { "_CRT_SECURE_NO_WARNINGS" }
files {
"Squish/**.*",
}
includedirs
{
"Squish"
}
|
fixed premake4.lua for correct codeblocks support
|
fixed premake4.lua for correct codeblocks support
|
Lua
|
mit
|
galek/TaskScheduler,SergeyMakeev/TaskScheduler,vr3d/TaskScheduler,galek/TaskScheduler,SergeyMakeev/TaskScheduler,vr3d/TaskScheduler,galek/TaskScheduler,vr3d/TaskScheduler
|
a0b7176ef321b2b2b315c1bd9251a89ab359a8d1
|
lua/mp_menu/volume_control.lua
|
lua/mp_menu/volume_control.lua
|
local math = math
local ceil = math.ceil
local clamp = math.Clamp
local surface = surface
local color_white = color_white
local PANEL = {}
PANEL.Margin = 16
PANEL.ButtonWidth = 18
PANEL.ButtonSpacing = 8
PANEL.BackgroundColor = Color( 28, 100, 157 )
function PANEL:Init()
self.BaseClass.Init( self )
self.VolumeButton = vgui.Create( "MP.VolumeButton", self )
self.VolumeSlider = vgui.Create( "MP.VolumeSlider", self )
self.BtnList = vgui.Create( "DHorizontalList", self )
self.BtnList:SetSpacing( self.ButtonSpacing )
if hook.Run( MP.EVENTS.UI.PRIVILEGED_PLAYER ) then
self.RepeatBtn = vgui.Create( "MP.RepeatButton" )
self:AddButton( self.RepeatBtn )
self.ShuffleBtn = vgui.Create( "MP.ShuffleButton" )
self:AddButton( self.ShuffleBtn )
end
self:OnVolumeChanged( MediaPlayer.Volume() )
hook.Add( MP.EVENTS.VOLUME_CHANGED, self, self.OnVolumeChanged )
hook.Add( MP.EVENTS.UI.MEDIA_PLAYER_CHANGED, self, self.OnMediaPlayerChanged )
end
function PANEL:AddButton( panel )
self.BtnList:AddItem( panel )
end
function PANEL:OnVolumeChanged( volume )
self.VolumeSlider:SetSlideX( volume )
self:InvalidateChildren()
end
function PANEL:OnMediaPlayerChanged( mp )
self.RepeatBtn:SetEnabled( mp:GetQueueRepeat() )
self.ShuffleBtn:SetEnabled( mp:GetQueueShuffle() )
end
function PANEL:Paint( w, h )
surface.SetDrawColor( self.BackgroundColor )
surface.DrawRect( 0, 0, w, h )
end
function PANEL:PerformLayout( w, h )
self.BtnList:InvalidateLayout( true )
self.BtnList:CenterVertical()
self.BtnList:AlignRight( self.Margin )
self.VolumeButton:CenterVertical()
self.VolumeButton:AlignLeft( self.Margin )
local sliderWidth = ( self.BtnList:GetPos() - 15 ) -
( self.VolumeButton:GetPos() + self.VolumeButton:GetWide() + 15 )
self.VolumeSlider:SetWide( sliderWidth )
self.VolumeSlider:CenterVertical()
self.VolumeSlider:MoveRightOf( self.VolumeButton, 15 )
end
function PANEL:OnRemove()
hook.Remove( MP.EVENTS.VOLUME_CHANGED, self )
end
derma.DefineControl( "MP.VolumeControl", "", PANEL, "DPanel" )
local VOLUME_BUTTON = {}
function VOLUME_BUTTON:Init()
self.BaseClass.Init( self )
self:SetIcon( 'mp-volume' )
self:SetSize( 18, 17 )
end
function VOLUME_BUTTON:DoClick()
MediaPlayer.ToggleMute()
end
derma.DefineControl( "MP.VolumeButton", "", VOLUME_BUTTON, "MP.SidebarButton" )
local VOLUME_SLIDER = {}
VOLUME_SLIDER.BarHeight = 3
VOLUME_SLIDER.KnobSize = 12
VOLUME_SLIDER.BarBgColor = Color( 13, 41, 62 )
VOLUME_SLIDER.ScrollIncrement = 0.1 -- out of 1
function VOLUME_SLIDER:Init()
self.BaseClass.Init( self )
self.Knob:SetSize( self.KnobSize, self.KnobSize )
self.Knob.Paint = self.PaintKnob
-- Remove some hidden panel child from the inherited DSlider control; I have
-- no idea where it's being created...
for _, child in pairs( self:GetChildren() ) do
if child ~= self.Knob then
child:Remove()
end
end
end
function VOLUME_SLIDER:Paint( w, h )
local progress = self.m_fSlideX
local vmid = ceil((h / 2) - (self.BarHeight / 2))
surface.SetDrawColor( self.BarBgColor )
surface.DrawRect( 0, vmid, w, self.BarHeight )
surface.SetDrawColor( color_white )
surface.DrawRect( 0, vmid, ceil(w * progress), self.BarHeight )
end
function VOLUME_SLIDER:PaintKnob( w, h )
draw.RoundedBoxEx( ceil(w/2), 0, 0, w, h, color_white, true, true, true, true )
end
function VOLUME_SLIDER:SetSlideX( value )
if self._lockVolume then return end
value = clamp(value, 0, 1)
self.m_fSlideX = value
self:InvalidateLayout()
self._lockVolume = true
MediaPlayer.Volume( value )
self._lockVolume = nil
end
function VOLUME_SLIDER:OnMouseWheeled( delta )
local change = self.ScrollIncrement * delta
local value = clamp(self.m_fSlideX + change, 0, 1)
self:SetSlideX( value )
end
derma.DefineControl( "MP.VolumeSlider", "", VOLUME_SLIDER, "DSlider" )
local REPEAT_BTN = {}
function REPEAT_BTN:Init()
self.BaseClass.Init( self )
self:SetIcon( "mp-repeat" )
self:SetTooltip( "Repeat" )
end
function REPEAT_BTN:DoClick()
self.BaseClass.DoClick( self )
hook.Run( MP.EVENTS.UI.TOGGLE_REPEAT )
end
derma.DefineControl( "MP.RepeatButton", "", REPEAT_BTN, "MP.SidebarToggleButton" )
local SHUFFLE_BTN = {}
function SHUFFLE_BTN:Init()
self.BaseClass.Init( self )
self:SetIcon( "mp-shuffle" )
self:SetTooltip( "Shuffle" )
end
function SHUFFLE_BTN:DoClick()
self.BaseClass.DoClick( self )
hook.Run( MP.EVENTS.UI.TOGGLE_SHUFFLE )
end
derma.DefineControl( "MP.ShuffleButton", "", SHUFFLE_BTN, "MP.SidebarToggleButton" )
|
local math = math
local ceil = math.ceil
local clamp = math.Clamp
local surface = surface
local color_white = color_white
local PANEL = {}
PANEL.Margin = 16
PANEL.ButtonWidth = 18
PANEL.ButtonSpacing = 8
PANEL.BackgroundColor = Color( 28, 100, 157 )
function PANEL:Init()
self.BaseClass.Init( self )
self.VolumeButton = vgui.Create( "MP.VolumeButton", self )
self.VolumeSlider = vgui.Create( "MP.VolumeSlider", self )
self.BtnList = vgui.Create( "DHorizontalList", self )
self.BtnList:SetSpacing( self.ButtonSpacing )
if hook.Run( MP.EVENTS.UI.PRIVILEGED_PLAYER ) then
self.RepeatBtn = vgui.Create( "MP.RepeatButton" )
self:AddButton( self.RepeatBtn )
self.ShuffleBtn = vgui.Create( "MP.ShuffleButton" )
self:AddButton( self.ShuffleBtn )
end
self:OnVolumeChanged( MediaPlayer.Volume() )
hook.Add( MP.EVENTS.VOLUME_CHANGED, self, self.OnVolumeChanged )
hook.Add( MP.EVENTS.UI.MEDIA_PLAYER_CHANGED, self, self.OnMediaPlayerChanged )
end
function PANEL:AddButton( panel )
self.BtnList:AddItem( panel )
end
function PANEL:OnVolumeChanged( volume )
self.VolumeSlider:SetSlideX( volume )
self:InvalidateChildren()
end
function PANEL:OnMediaPlayerChanged( mp )
if hook.Run( MP.EVENTS.UI.PRIVILEGED_PLAYER ) then
self.RepeatBtn:SetEnabled( mp:GetQueueRepeat() )
self.ShuffleBtn:SetEnabled( mp:GetQueueShuffle() )
end
end
function PANEL:Paint( w, h )
surface.SetDrawColor( self.BackgroundColor )
surface.DrawRect( 0, 0, w, h )
end
function PANEL:PerformLayout( w, h )
self.BtnList:InvalidateLayout( true )
self.BtnList:CenterVertical()
self.BtnList:AlignRight( self.Margin )
self.VolumeButton:CenterVertical()
self.VolumeButton:AlignLeft( self.Margin )
local sliderWidth = ( self.BtnList:GetPos() - 15 ) -
( self.VolumeButton:GetPos() + self.VolumeButton:GetWide() + 15 )
self.VolumeSlider:SetWide( sliderWidth )
self.VolumeSlider:CenterVertical()
self.VolumeSlider:MoveRightOf( self.VolumeButton, 15 )
end
function PANEL:OnRemove()
hook.Remove( MP.EVENTS.VOLUME_CHANGED, self )
end
derma.DefineControl( "MP.VolumeControl", "", PANEL, "DPanel" )
local VOLUME_BUTTON = {}
function VOLUME_BUTTON:Init()
self.BaseClass.Init( self )
self:SetIcon( 'mp-volume' )
self:SetSize( 18, 17 )
end
function VOLUME_BUTTON:DoClick()
MediaPlayer.ToggleMute()
end
derma.DefineControl( "MP.VolumeButton", "", VOLUME_BUTTON, "MP.SidebarButton" )
local VOLUME_SLIDER = {}
VOLUME_SLIDER.BarHeight = 3
VOLUME_SLIDER.KnobSize = 12
VOLUME_SLIDER.BarBgColor = Color( 13, 41, 62 )
VOLUME_SLIDER.ScrollIncrement = 0.1 -- out of 1
function VOLUME_SLIDER:Init()
self.BaseClass.Init( self )
self.Knob:SetSize( self.KnobSize, self.KnobSize )
self.Knob.Paint = self.PaintKnob
-- Remove some hidden panel child from the inherited DSlider control; I have
-- no idea where it's being created...
for _, child in pairs( self:GetChildren() ) do
if child ~= self.Knob then
child:Remove()
end
end
end
function VOLUME_SLIDER:Paint( w, h )
local progress = self.m_fSlideX
local vmid = ceil((h / 2) - (self.BarHeight / 2))
surface.SetDrawColor( self.BarBgColor )
surface.DrawRect( 0, vmid, w, self.BarHeight )
surface.SetDrawColor( color_white )
surface.DrawRect( 0, vmid, ceil(w * progress), self.BarHeight )
end
function VOLUME_SLIDER:PaintKnob( w, h )
draw.RoundedBoxEx( ceil(w/2), 0, 0, w, h, color_white, true, true, true, true )
end
function VOLUME_SLIDER:SetSlideX( value )
if self._lockVolume then return end
value = clamp(value, 0, 1)
self.m_fSlideX = value
self:InvalidateLayout()
self._lockVolume = true
MediaPlayer.Volume( value )
self._lockVolume = nil
end
function VOLUME_SLIDER:OnMouseWheeled( delta )
local change = self.ScrollIncrement * delta
local value = clamp(self.m_fSlideX + change, 0, 1)
self:SetSlideX( value )
end
derma.DefineControl( "MP.VolumeSlider", "", VOLUME_SLIDER, "DSlider" )
local REPEAT_BTN = {}
function REPEAT_BTN:Init()
self.BaseClass.Init( self )
self:SetIcon( "mp-repeat" )
self:SetTooltip( "Repeat" )
end
function REPEAT_BTN:DoClick()
self.BaseClass.DoClick( self )
hook.Run( MP.EVENTS.UI.TOGGLE_REPEAT )
end
derma.DefineControl( "MP.RepeatButton", "", REPEAT_BTN, "MP.SidebarToggleButton" )
local SHUFFLE_BTN = {}
function SHUFFLE_BTN:Init()
self.BaseClass.Init( self )
self:SetIcon( "mp-shuffle" )
self:SetTooltip( "Shuffle" )
end
function SHUFFLE_BTN:DoClick()
self.BaseClass.DoClick( self )
hook.Run( MP.EVENTS.UI.TOGGLE_SHUFFLE )
end
derma.DefineControl( "MP.ShuffleButton", "", SHUFFLE_BTN, "MP.SidebarToggleButton" )
|
Fixed lua error for queue management buttons.
|
Fixed lua error for queue management buttons.
|
Lua
|
mit
|
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
|
5b55d75d8ddfae8bd3303297e67047217d5b844b
|
readline.lua
|
readline.lua
|
-- Very basic FFI interface to readline,
-- with history saving/restoring
--
local ffi = require 'ffi'
local assert = assert
local cocreate, coresume, costatus = coroutine.create, coroutine.resume, coroutine.status
local readline = {}
ffi.cdef[[
/* libc definitions */
void* malloc(size_t bytes);
void free(void *);
/* basic history handling */
char *readline (const char *prompt);
void add_history(const char *line);
int read_history(const char *filename);
int write_history(const char *filename);
void rl_set_signals(void);
/* completion */
typedef char **rl_completion_func_t (const char *, int, int);
typedef char *rl_compentry_func_t (const char *, int);
char **rl_completion_matches (const char *, rl_compentry_func_t *);
const char *rl_basic_word_break_characters;
const char *rl_completer_quote_characters;
rl_completion_func_t *rl_attempted_completion_function;
char *rl_line_buffer;
int rl_completion_append_character;
int rl_attempted_completion_over;
const char *rl_readline_name;
int rl_initialize();
]]
local libreadline = ffi.load("readline")
-- enable application specific parsing with inputrc
libreadline.rl_readline_name = 'lua'
function readline.completion_append_character(char)
libreadline.rl_completion_append_character = #char > 0 and char:byte(1,1) or 0
end
if jit.os ~= 'OSX' then
--libreadline.rl_set_signals()
end
function readline.shell(config)
-- restore history
libreadline.read_history(config.history)
-- configure completion, if any
if config.complete then
if config.word_break_characters then
libreadline.rl_basic_word_break_characters = config.word_break_characters
end
libreadline.rl_completer_quote_characters = '\'"'
function libreadline.rl_attempted_completion_function(word, startpos, endpos)
local strword = ffi.string(word)
local buffer = ffi.string(libreadline.rl_line_buffer)
local matches = config.complete(strword, buffer, startpos, endpos)
if not matches then return nil end
-- if matches is an empty array, tell readline to not call default completion (file)
libreadline.rl_attempted_completion_over = 1
-- translate matches table to C strings
-- (there is probably more efficient ways to do it)
return libreadline.rl_completion_matches(word, function(text, i)
local match = matches[i+1]
if match then
-- readline will free the C string by itself, so create copies of them
local buf = ffi.C.malloc(#match + 1)
ffi.copy(buf, match, #match+1)
return buf
else
return ffi.new("void*", nil)
end
end)
end
end
-- re-initialize in case
libreadline.rl_initialize()
-- main loop
local running = true
while running do
local userfunc = cocreate(config.getcommand)
local _, prompt = assert(coresume(userfunc))
while costatus(userfunc) ~= "dead" do
-- get next line
local s = libreadline.readline(prompt)
if s == nil then -- end of file
running = false
break
end
local line = ffi.string(s)
ffi.C.free(s)
_, prompt = assert(coresume(userfunc, line))
end
if not running then
io.stdout:write('\nDo you really want to exit ([y]/n)? ') io.flush()
local line = io.read('*l')
if line == '' or line:lower() == 'y' then
os.exit()
else
readline.shell(config)
end
elseif prompt then -- final return value is the value to add to history
libreadline.add_history(prompt)
libreadline.write_history(config.history)
end
end
end
return readline
|
-- Very basic FFI interface to readline,
-- with history saving/restoring
--
local ffi = require 'ffi'
local assert = assert
local cocreate, coresume, costatus = coroutine.create, coroutine.resume, coroutine.status
local readline = {}
ffi.cdef[[
/* libc definitions */
void* malloc(size_t bytes);
void free(void *);
/* basic history handling */
char *readline (const char *prompt);
void add_history(const char *line);
int read_history(const char *filename);
int write_history(const char *filename);
void rl_set_signals(void);
/* completion */
typedef char **rl_completion_func_t (const char *, int, int);
typedef char *rl_compentry_func_t (const char *, int);
char **rl_completion_matches (const char *, rl_compentry_func_t *);
const char *rl_basic_word_break_characters;
const char *rl_completer_quote_characters;
rl_completion_func_t *rl_attempted_completion_function;
rl_completion_func_t *rl_completion_entry_function;
char *rl_line_buffer;
int rl_completion_append_character;
int rl_completion_suppress_append;
int rl_attempted_completion_over;
const char *rl_readline_name;
int rl_initialize();
]]
local libreadline = ffi.load("readline")
-- enable application specific parsing with inputrc
libreadline.rl_readline_name = 'lua'
function readline.completion_append_character(char)
libreadline.rl_completion_append_character = #char > 0 and char:byte(1,1) or 0
end
if jit.os ~= 'OSX' then
--libreadline.rl_set_signals()
end
function readline.shell(config)
-- restore history
libreadline.read_history(config.history)
-- configure completion, if any
if config.complete then
if config.word_break_characters then
libreadline.rl_basic_word_break_characters = config.word_break_characters
end
libreadline.rl_completer_quote_characters = '\'"'
local matches
libreadline.rl_completion_entry_function = function(word, i)
libreadline.rl_attempted_completion_over = 1
local strword = ffi.string(word)
local buffer = ffi.string(libreadline.rl_line_buffer)
if i == 0 then
matches = config.complete(strword, buffer, startpos, endpos)
end
local match = matches[i+1]
if match then
-- readline will free the C string by itself, so create copies of them
local buf = ffi.C.malloc(#match + 1)
ffi.copy(buf, match, #match+1)
return buf
end
end
end
-- main loop
local running = true
while running do
local userfunc = cocreate(config.getcommand)
local _, prompt = assert(coresume(userfunc))
while costatus(userfunc) ~= "dead" do
-- get next line
local s = libreadline.readline(prompt)
if s == nil then -- end of file
running = false
break
end
local line = ffi.string(s)
ffi.C.free(s)
_, prompt = assert(coresume(userfunc, line))
end
if not running then
io.stdout:write('\nDo you really want to exit ([y]/n)? ') io.flush()
local line = io.read('*l')
if line == '' or line:lower() == 'y' then
os.exit()
else
readline.shell(config)
end
elseif prompt then -- final return value is the value to add to history
libreadline.add_history(prompt)
libreadline.write_history(config.history)
end
end
end
return readline
|
fixed READLINE on Linux.
|
fixed READLINE on Linux.
|
Lua
|
bsd-3-clause
|
hughperkins/trepl,colesbury/trepl,torch/trepl,ninjin/trepl,zhengwy888/trepl
|
782a734e924d2173862a5b335fa755b4b73c27b0
|
WzComparerR2.LuaConsole/Examples/DumpImages.lua
|
WzComparerR2.LuaConsole/Examples/DumpImages.lua
|
import 'WzComparerR2.PluginBase'
import 'WzComparerR2.WzLib'
import 'System.IO'
import 'System.Xml'
------------------------------------------------------------
local function enumAllWzNodes(node)
return coroutine.wrap(function()
coroutine.yield(node)
for _,v in each(node.Nodes) do
for child in enumAllWzNodes(v) do
coroutine.yield(child)
end
end
end)
end
local function isPng(value)
if value and type(value) == "userdata" and value:GetType().Name == 'Wz_Png' then
return true
else
return false
end
end
------------------------------------------------------------
-- all variables
local topWzPath = 'Character'
local topNode = PluginManager.FindWz(topWzPath)
local outputDir = "D:\\wzDump"
------------------------------------------------------------
-- main function
if not topNode then
env:WriteLine('"{0}" not loaded.', topWzPath)
return
end
-- enum all wz_images
for n in enumAllWzNodes(topNode) do
local value = n.Value
if value and type(value) == "userdata" and value:GetType().Name == 'Wz_Image' then
local img = value
--extract wz image
env:WriteLine('(extract)'..(img.Name))
if img:TryExtract() then
local dir = outputDir.."\\"..(n.FullPathToFile)
local dirCreated = false
--find all png
for n2 in enumAllWzNodes(img.Node) do
local png = n2.Value
if isPng(png) and (png.Width>1 or png.Height>1) then
local fn = n2.FullPath:sub(img.Name:len()+2):gsub("\\", ".")
fn = Path.Combine(dir, fn .. ".png")
--ensure dir exists
if not dirCreated then
if not Directory.Exists(dir) then
Directory.CreateDirectory(dir)
end
dirCreated = true
end
--save as png
local bmp = png:ExtractPng()
bmp:Save(fn)
bmp:Dispose()
end
end
img:Unextract()
else --error
env:WriteLine((img.Name)..' extract failed.')
end --end extract
end -- end type validate
end -- end foreach
env:WriteLine('--------Done.---------')
|
import 'WzComparerR2.PluginBase'
import 'WzComparerR2.WzLib'
import 'System.IO'
import 'System.Xml'
------------------------------------------------------------
local function enumAllWzNodes(node)
return coroutine.wrap(function()
coroutine.yield(node)
for _,v in each(node.Nodes) do
for child in enumAllWzNodes(v) do
coroutine.yield(child)
end
end
end)
end
local function isPng(value)
if value and type(value) == "userdata" and value:GetType().Name == 'Wz_Png' then
return true
else
return false
end
end
local p = Path.GetInvalidFileNameChars()
local ivStr = ""
for i, v in each(p) do
if v >= 32 then
ivStr = ivStr .. string.char(v)
end
end
local ivPattern = "["..ivStr.."]"
------------------------------------------------------------
-- all variables
local topWzPath = 'Character'
local topNode = PluginManager.FindWz(topWzPath)
local outputDir = "D:\\wzDump"
------------------------------------------------------------
-- main function
if not topNode then
env:WriteLine('"{0}" not loaded.', topWzPath)
return
end
-- enum all wz_images
for n in enumAllWzNodes(topNode) do
local value = n.Value
if value and type(value) == "userdata" and value:GetType().Name == 'Wz_Image' then
local img = value
--extract wz image
env:WriteLine('(extract)'..(img.Name))
if img:TryExtract() then
local dir = outputDir.."\\"..(n.FullPathToFile)
local dirCreated = false
--find all png
for n2 in enumAllWzNodes(img.Node) do
local png = n2.Value
if isPng(png) and (png.Width>1 or png.Height>1) then
local fn = n2.FullPath:sub(img.Name:len()+2):gsub("\\", "."):gsub(ivPattern, "")
fn = Path.Combine(dir, fn .. ".png")
--ensure dir exists
if not dirCreated then
if not Directory.Exists(dir) then
Directory.CreateDirectory(dir)
end
dirCreated = true
end
--save as png
local bmp = png:ExtractPng()
bmp:Save(fn)
bmp:Dispose()
end
end
img:Unextract()
else --error
env:WriteLine((img.Name)..' extract failed.')
end --end extract
end -- end type validate
end -- end foreach
env:WriteLine('--------Done.---------')
|
LuaConsole: fix filename bug in example script.
|
LuaConsole: fix filename bug in example script.
|
Lua
|
mit
|
Kagamia/WzComparerR2,KENNYSOFT/WzComparerR2
|
9e43697a4a69aa3b70c9f7db59f2e3eed6735a5c
|
App/NevermoreEngineLoader.lua
|
App/NevermoreEngineLoader.lua
|
--- This scripts loads Nevermore from the server.
-- It also replicates the into ReplicatedStorage for internal usage.
-----------------------
-- UTILITY FUNCTIONS --
-----------------------
local TestService = game:GetService('TestService')
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local function Warn(WarningText)
--- Used to yell at the player
-- @param WarningText The text to warn with.
spawn(function()
TestService:Warn(false, WarningText)
end)
end
local function WaitForChild(Parent, Name)
--- Yields until a child is added. Warns after 5 seconds of yield.
-- @param Parent The parent to wait for the child of
-- @param Name The name of the child
-- @return The child found
local Child = Parent:FindFirstChild(Name)
local StartTime = tick()
local Warned = false;
while not Child do
wait(0)
Child = Parent:FindFirstChild(Name)
if not Warned and StartTime + 5 <= tick() then
Warned = true;
Warn("[NevermoreEngineLoader] -" .. " " .. Name .. " has not replicated after 5 seconds, may not be able to execute Nevermore.")
end
end
return Child
end
-------------
-- LOADING --
-------------
-- Wait for parent to resolve
while not script.Parent do
wait(0)
end
-- Identify the modular script
-- local NevermoreModularScript = WaitForChild(script.Parent, "NevermoreEngine")
local NevermoreModularScript = ReplicatedStorage:FindFirstChild("NevermoreEngine")
if not NevermoreModularScript then
local NevermoreModularScriptSource = WaitForChild(script.Parent, "NevermoreEngine")
NevermoreModularScript = NevermoreModularScriptSource:Clone()
NevermoreModularScript.Archivable = false
end
local Nevermore = require(NevermoreModularScript)
-- Set identifier, and initiate.
Nevermore.Initiate()
NevermoreModularScript.Parent = ReplicatedStorage
|
--- This scripts loads Nevermore from the server.
-- It also replicates the into ReplicatedStorage for internal usage.
-----------------------
-- UTILITY FUNCTIONS --
-----------------------
local TestService = game:GetService('TestService')
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local function WaitForChild(Parent, Name, TimeLimit)
-- Waits for a child to appear. Not efficient, but it shoudln't have to be. It helps with debugging.
-- Useful when ROBLOX lags out, and doesn't replicate quickly.
-- @param TimeLimit If TimeLimit is given, then it will return after the timelimit, even if it hasn't found the child.
assert(Parent ~= nil, "Parent is nil")
assert(type(Name) == "string", "Name is not a string.")
local Child = Parent:FindFirstChild(Name)
local StartTime = tick()
local Warned = false
while not Child and Parent do
wait(0)
Child = Parent:FindFirstChild(Name)
if not Warned and StartTime + (TimeLimit or 5) <= tick() then
Warned = true
warn("Infinite yield possible for WaitForChild(" .. Parent:GetFullName() .. ", " .. Name .. ")")
if TimeLimit then
return Parent:FindFirstChild(Name)
end
end
end
if not Parent then
warn("Parent became nil.")
end
return Child
end
-------------
-- LOADING --
-------------
-- Wait for parent to resolve
while not script.Parent do
wait(0)
end
-- Identify the modular script
local NevermoreModularScript = ReplicatedStorage:FindFirstChild("NevermoreEngine")
if not NevermoreModularScript then
local NevermoreModularScriptSource = WaitForChild(script.Parent, "NevermoreEngine")
NevermoreModularScript = NevermoreModularScriptSource:Clone()
NevermoreModularScript.Archivable = false
end
local Nevermore = require(NevermoreModularScript)
-- Set identifier, and initiate.
Nevermore.Initiate()
NevermoreModularScript.Parent = ReplicatedStorage
|
Fixed loader. Thanks user Looah!
|
Fixed loader. Thanks user Looah!
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
a9c048c9109efaa12ae0e84ffe1f97126faeaf45
|
src/extensions/cp/apple/finalcutpro/export/destinations.lua
|
src/extensions/cp/apple/finalcutpro/export/destinations.lua
|
--- === cp.apple.finalcutpro.export.destinations ===
---
--- Provides access to the list of Share Destinations configured for the user.
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
local log = require("hs.logger").new("destinations")
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local fs = require("hs.fs")
local pathwatcher = require("hs.pathwatcher")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local plist = require("cp.plist")
local archiver = require("cp.plist.archiver")
--------------------------------------------------------------------------------
-- 3rd Party Extensions:
--------------------------------------------------------------------------------
local _ = require("moses")
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- cp.apple.finalcutpro.export.destinations.PREFERENCES_PATH -> string
--- Constant
--- The Preferences Path
mod.PREFERENCES_PATH = "~/Library/Preferences"
--- cp.apple.finalcutpro.export.destinations.DESTINATIONS_FILE -> string
--- Constant
--- The Destinations File.
mod.DESTINATIONS_FILE = "com.apple.FinalCut.UserDestinations"
mod.DESTINATIONS_PATTERN = ".*" .. mod.DESTINATIONS_FILE .. "[1-9]%.plist"
--- cp.apple.finalcutpro.export.destinations.DESTINATIONS_PATH -> string
--- Constant
--- The Destinations Path.
mod.DESTINATIONS_PATH = mod.PREFERENCES_PATH .. "/" .. mod.DESTINATIONS_FILE .. ".plist"
local function findDestinationsPath()
-- in some situations, you can end up with "com.apple.FinalCut.UserDestinations2.plist", and, one assumes 3, 4, etc.
local path = fs.pathToAbsolute(mod.DESTINATIONS_PATH)
if not path then -- try with numbers 1-9
for i=1,9 do
path = fs.pathToAbsolute(mod.PREFERENCES_PATH .. "/" .. mod.DESTINATIONS_FILE .. tostring(i) .. ".plist")
if path then
return path
end
end
end
return path
end
-- load() -> table | nil, string
-- Function
-- Loads the Destinations Property List.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function load()
local destinationsPlist, err = plist.fileToTable(findDestinationsPath())
if destinationsPlist then
return archiver.unarchiveBase64(destinationsPlist.FFShareDestinationsKey).root
else
return nil, err
end
end
-- watch() -> none
-- Function
-- Sets up a new Path Watcher.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function watch()
if not mod._watcher then
mod._watcher = pathwatcher.new(mod.PREFERENCES_PATH, function(files)
for _,file in pairs(files) do
if file:match(mod.DESTINATIONS_PATTERN) ~= nil then
local err
mod._details, err = load()
if err then
log.wf("Unable to load FCPX User Destinations")
end
return
end
end
end):start()
end
end
--- cp.apple.finalcutpro.export.destinations.details() -> table
--- Function
--- Returns the full details of the current Share Destinations as a table.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The table of Share Destinations.
function mod.details()
if not mod._details then
local list, err = load()
if list then
mod._details = list
watch()
else
return list, err
end
end
return mod._details
end
--- cp.apple.finalcutpro.export.destinations.names() -> table
--- Function
--- Returns an array of the names of destinations, in their current order.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The table of Share Destination names.
function mod.names()
local list, err = mod.details()
if list then
return _.map(list, function(_, e) return e.name end)
else
return nil, err
end
end
--- cp.apple.finalcutpro.export.destinations.indexOf(name) -> number
--- Function
--- Returns the index of the Destination with the specified name, or `nil` if not found.
---
--- Parameters:
--- * `name` - The name of the Destination
---
--- Returns:
--- * The index of the named Destination, or `nil`.
function mod.indexOf(name)
local list = mod.details()
if list then
return _.detect(list, function(e) return e.name == name end)
else
return nil
end
end
return mod
|
--- === cp.apple.finalcutpro.export.destinations ===
---
--- Provides access to the list of Share Destinations configured for the user.
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
local log = require("hs.logger").new("destinations")
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local fs = require("hs.fs")
local pathwatcher = require("hs.pathwatcher")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local plist = require("cp.plist")
local archiver = require("cp.plist.archiver")
--------------------------------------------------------------------------------
-- 3rd Party Extensions:
--------------------------------------------------------------------------------
local _ = require("moses")
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- cp.apple.finalcutpro.export.destinations.PREFERENCES_PATH -> string
--- Constant
--- The Preferences Path
mod.PREFERENCES_PATH = "~/Library/Preferences"
--- cp.apple.finalcutpro.export.destinations.DESTINATIONS_FILE -> string
--- Constant
--- The Destinations File.
mod.DESTINATIONS_FILE = "com.apple.FinalCut.UserDestinations"
--- cp.apple.finalcutpro.export.destinations.DESTINATIONS_PATTERN -> string
--- Constant
--- Destinations File Pattern.
mod.DESTINATIONS_PATTERN = ".*" .. mod.DESTINATIONS_FILE .. "[1-9]%.plist"
--- cp.apple.finalcutpro.export.destinations.DESTINATIONS_PATH -> string
--- Constant
--- The Destinations Path.
mod.DESTINATIONS_PATH = mod.PREFERENCES_PATH .. "/" .. mod.DESTINATIONS_FILE .. ".plist"
-- findDestinationsPath() -> string | nil
-- Function
-- Gets the Final Cut Pro Destination Property List Path.
--
-- Parameters:
-- * None
--
-- Returns:
-- * The Final Cut Pro Destination Property List Path as a string or `nil` if the file cannot be found.
local function findDestinationsPath()
--------------------------------------------------------------------------------
-- For some strange reason Final Cut Pro creates a file called
-- `com.apple.FinalCut.UserDestinations2.plist` on most/all machines which is
-- where the actual User Destinations are stored.
--------------------------------------------------------------------------------
local path = fs.pathToAbsolute(mod.PREFERENCES_PATH .. "/" .. mod.DESTINATIONS_FILE .. "2.plist")
if not path then
path = fs.pathToAbsolute(mod.DESTINATIONS_PATH)
end
return path
end
-- load() -> table | nil, string
-- Function
-- Loads the Destinations Property List.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function load()
local destinationsPlist, err = plist.fileToTable(findDestinationsPath())
if destinationsPlist then
return archiver.unarchiveBase64(destinationsPlist.FFShareDestinationsKey).root
else
return nil, err
end
end
-- watch() -> none
-- Function
-- Sets up a new Path Watcher.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function watch()
if not mod._watcher then
mod._watcher = pathwatcher.new(mod.PREFERENCES_PATH, function(files)
for _,file in pairs(files) do
if file:match(mod.DESTINATIONS_PATTERN) ~= nil then
local err
mod._details, err = load()
if err then
log.wf("Unable to load FCPX User Destinations")
end
return
end
end
end):start()
end
end
--- cp.apple.finalcutpro.export.destinations.details() -> table
--- Function
--- Returns the full details of the current Share Destinations as a table.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The table of Share Destinations.
function mod.details()
if not mod._details then
local list, err = load()
if list then
mod._details = list
watch()
else
return list, err
end
end
return mod._details
end
--- cp.apple.finalcutpro.export.destinations.names() -> table
--- Function
--- Returns an array of the names of destinations, in their current order.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The table of Share Destination names.
function mod.names()
local list, err = mod.details()
if list then
local result = {}
for i, v in pairs(list) do
if v.name and v.name ~= "" then
table.insert(result, v.name)
end
end
return result
else
return nil, err
end
end
--- cp.apple.finalcutpro.export.destinations.indexOf(name) -> number
--- Function
--- Returns the index of the Destination with the specified name, or `nil` if not found.
---
--- Parameters:
--- * `name` - The name of the Destination
---
--- Returns:
--- * The index of the named Destination, or `nil`.
function mod.indexOf(name)
local list = mod.details()
if list then
return _.detect(list, function(e) return e.name == name end)
else
return nil
end
end
return mod
|
#1349
|
#1349
- Fixed bug in `findDestinationsPath()` where it was reading the wrong
plist file.
- Fixed bug in `cp.apple.finalcutpro.export.destinations.names()` where
it could return a blank value
- Closes #1349
|
Lua
|
mit
|
CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks
|
539113c77802c35ecf937c280639a964aa5d633b
|
minetestforfun_game/mods/default/commands.lua
|
minetestforfun_game/mods/default/commands.lua
|
minetest.register_privilege("physics", {
description = "Allows player to set their gravity, jump height and movement speed"})
-- Infotool code by PilzAdam:
minetest.register_craftitem("default:infotool", {
description = "Infotool",
inventory_image = "default_infotool.png",
wield_image = "default_infotool.png^[transformR90",
groups = {not_in_creative_inventory = 1},
on_use = function(_, user, pt)
if pt.type ~= "node" then return end
local nn = minetest.get_node(pt.under).name
if type(minetest.registered_items[nn].tiles[1]) ~= "string" then return end
local def = minetest.registered_nodes[nn]
if not def then return end
local textures = def.tiles
local description = def.description
if not textures then
textures = {"(no texture)"}
end
if not description then
description = {"(no description)"}
end
for i = 1,6 do
if not textures[i] then
textures[i] = textures[i-1]
end
end
local dir = vector.subtract(pt.above, pt.under)
local index
-- This doesn't work for facedir or other drawtypes yet.
if dir.y == 1 then
index = 1
elseif dir.y == -1 then
index = 2
else
if dir.x == 1 then
index = 3
elseif dir.x == -1 then
index = 4
else
if dir.z == 1 then
index = 5
else
index = 6
end
end
end
minetest.chat_send_player(user:get_player_name(), description .. ": " .. nn .. " (" .. textures[index] .. ")")
end,
})
minetest.register_chatcommand("info", {
description = "Gives an Infotool, click to receive information on the pointed node",
func = function(name)
local receiverref = minetest.get_player_by_name(name)
receiverref:get_inventory():add_item("main", "default:infotool")
minetest.chat_send_player(name, "\"default:infotool\" added to inventory.")
end,
})
minetest.register_chatcommand("clearinventory", {
params = "<inventory>",
description = "Clears an entire inventory, \"main\" if unspecified, \"craft\" is another possible choice",
func = function(name, param)
local player = minetest.get_player_by_name(name)
local player_inv = player:get_inventory()
if not player then
minetest.log("error", "Unable to clear inventory, no player.")
return false, "Unable to clear inventory, no player."
end
if param == "" then
player_inv:set_list("main", {})
return true, "Inventory \"main\" cleared."
else
player_inv:set_list(param, {})
return true, "Inventory \"" .. param .. "\" cleared."
end
end,
})
-- The following commands /whoami, /suicide, /speed, /gravity and /jump by Wuzzy:
minetest.register_chatcommand("whoami", {
params = "",
description = "Tells your name",
privs = {},
func = function(name)
minetest.chat_send_player(name, "Your name is: " .. name)
end,
})
minetest.register_chatcommand("ip", {
params = "",
description = "Shows your IP address",
privs = {},
func = function(name)
minetest.chat_send_player(name, "Your IP address is: "..minetest.get_player_ip(name))
end
})
minetest.register_chatcommand("suicide", {
params = "",
description = "Kills yourself",
func = function(name, param)
local player = minetest.get_player_by_name(name)
if not player then return end
player:set_hp(0)
if minetest.setting_getbool("enable_damage") == false then
minetest.chat_send_player(name, "[X] Damage is disabled on this server.")
else
minetest.chat_send_player(name, "[X] You suicided.")
end
end,
})
minetest.register_chatcommand("speed", {
params = "[speed]",
description = "Sets your movement speed (defaults to 1).",
privs = {physics = true},
func = function(name, speed)
local player = minetest.get_player_by_name(name)
if not player then return end
if speed == "" then speed = 1 end
if type(tonumber(speed)) ~= "number"
or tonumber(speed) < 0
or tonumber(speed) > 10 then
minetest.chat_send_player(name, "[~] Speed must be between 0.0 and 10.0.")
return
end
player:set_physics_override(tonumber(speed), nil, nil)
minetest.chat_send_player(name, "[~] Speed set to " .. tonumber(speed) * 100 .. " %.")
end,
})
minetest.register_chatcommand("gravity", {
params = "[gravity]",
description = "Sets your gravity (defaults to 1).",
privs = {physics = true},
func = function(name, gravity)
local player = minetest.get_player_by_name(name)
if not player then return end
if gravity == "" then gravity = 1 end
if type(tonumber(gravity)) ~= "number"
or tonumber(gravity) < -10
or tonumber(gravity) > 10 then
minetest.chat_send_player(name, "[~] Gravity must be between -10.0 and 10.0.")
return
end
player:set_physics_override(nil, nil, tonumber(gravity))
minetest.chat_send_player(name, "[~] Gravity set to " .. tonumber(gravity) * 100 .. " %.")
end,
})
minetest.register_chatcommand("jump", {
params = "[height]",
description = "Sets your jump height (defaults to 1)",
privs = {physics = true},
func = function(name, jump)
local player = minetest.get_player_by_name(name)
if not player then return end
if jump == "" then jump = 1 end
if type(tonumber(jump)) ~= "number"
or tonumber(jump) < 0
or tonumber(jump) > 10 then
minetest.chat_send_player(name, "[~] Jump height must be between 0.0 and 10.0.")
return
end
player:set_physics_override(nil, tonumber(jump), nil)
minetest.chat_send_player(name, "[~] Jump height set to " .. tonumber(jump) * 100 .. " %.")
end,
})
minetest.register_chatcommand("hotbar", {
params = "[size]",
description = "Sets the size of your hotbar",
func = function(name, slots)
if slots == "" then slots = 16 end
if type(tonumber(slots)) ~= "number" or tonumber(slots) < 1 or tonumber(slots) > 23 then
minetest.chat_send_player(name, "[_] Hotbar size must be between 1 and 23.")
return
end
local player = minetest.get_player_by_name(name)
player:hud_set_hotbar_itemcount(tonumber(slots))
minetest.chat_send_player(name, "[_] Hotbar size set to " .. tonumber(slots) .. ".")
end,
})
|
minetest.register_privilege("physics", {
description = "Allows player to set their gravity, jump height and movement speed"})
-- Infotool code by PilzAdam:
minetest.register_craftitem("default:infotool", {
description = "Infotool",
inventory_image = "default_infotool.png",
wield_image = "default_infotool.png^[transformR90",
groups = {not_in_creative_inventory = 1},
on_use = function(_, user, pt)
if pt.type ~= "node" then return end
local nn = minetest.get_node(pt.under).name
if minetest.registered_items[nn] == nil or type(minetest.registered_items[nn].tiles[1]) ~= "string" then return end
local def = minetest.registered_nodes[nn]
if not def then return end
local textures = def.tiles
local description = def.description
if not textures then
textures = {"(no texture)"}
end
if not description then
description = {"(no description)"}
end
for i = 1,6 do
if not textures[i] then
textures[i] = textures[i-1]
end
end
local dir = vector.subtract(pt.above, pt.under)
local index
-- This doesn't work for facedir or other drawtypes yet.
if dir.y == 1 then
index = 1
elseif dir.y == -1 then
index = 2
else
if dir.x == 1 then
index = 3
elseif dir.x == -1 then
index = 4
else
if dir.z == 1 then
index = 5
else
index = 6
end
end
end
minetest.chat_send_player(user:get_player_name(), description .. ": " .. nn .. " (" .. textures[index] .. ")")
end,
})
minetest.register_chatcommand("info", {
description = "Gives an Infotool, click to receive information on the pointed node",
func = function(name)
local receiverref = minetest.get_player_by_name(name)
receiverref:get_inventory():add_item("main", "default:infotool")
minetest.chat_send_player(name, "\"default:infotool\" added to inventory.")
end,
})
minetest.register_chatcommand("clearinventory", {
params = "<inventory>",
description = "Clears an entire inventory, \"main\" if unspecified, \"craft\" is another possible choice",
func = function(name, param)
local player = minetest.get_player_by_name(name)
local player_inv = player:get_inventory()
if not player then
minetest.log("error", "Unable to clear inventory, no player.")
return false, "Unable to clear inventory, no player."
end
if param == "" then
player_inv:set_list("main", {})
return true, "Inventory \"main\" cleared."
else
player_inv:set_list(param, {})
return true, "Inventory \"" .. param .. "\" cleared."
end
end,
})
-- The following commands /whoami, /suicide, /speed, /gravity and /jump by Wuzzy:
minetest.register_chatcommand("whoami", {
params = "",
description = "Tells your name",
privs = {},
func = function(name)
minetest.chat_send_player(name, "Your name is: " .. name)
end,
})
minetest.register_chatcommand("ip", {
params = "",
description = "Shows your IP address",
privs = {},
func = function(name)
minetest.chat_send_player(name, "Your IP address is: "..minetest.get_player_ip(name))
end
})
minetest.register_chatcommand("suicide", {
params = "",
description = "Kills yourself",
func = function(name, param)
local player = minetest.get_player_by_name(name)
if not player then return end
player:set_hp(0)
if minetest.setting_getbool("enable_damage") == false then
minetest.chat_send_player(name, "[X] Damage is disabled on this server.")
else
minetest.chat_send_player(name, "[X] You suicided.")
end
end,
})
minetest.register_chatcommand("speed", {
params = "[speed]",
description = "Sets your movement speed (defaults to 1).",
privs = {physics = true},
func = function(name, speed)
local player = minetest.get_player_by_name(name)
if not player then return end
if speed == "" then speed = 1 end
if type(tonumber(speed)) ~= "number"
or tonumber(speed) < 0
or tonumber(speed) > 10 then
minetest.chat_send_player(name, "[~] Speed must be between 0.0 and 10.0.")
return
end
player:set_physics_override(tonumber(speed), nil, nil)
minetest.chat_send_player(name, "[~] Speed set to " .. tonumber(speed) * 100 .. " %.")
end,
})
minetest.register_chatcommand("gravity", {
params = "[gravity]",
description = "Sets your gravity (defaults to 1).",
privs = {physics = true},
func = function(name, gravity)
local player = minetest.get_player_by_name(name)
if not player then return end
if gravity == "" then gravity = 1 end
if type(tonumber(gravity)) ~= "number"
or tonumber(gravity) < -10
or tonumber(gravity) > 10 then
minetest.chat_send_player(name, "[~] Gravity must be between -10.0 and 10.0.")
return
end
player:set_physics_override(nil, nil, tonumber(gravity))
minetest.chat_send_player(name, "[~] Gravity set to " .. tonumber(gravity) * 100 .. " %.")
end,
})
minetest.register_chatcommand("jump", {
params = "[height]",
description = "Sets your jump height (defaults to 1)",
privs = {physics = true},
func = function(name, jump)
local player = minetest.get_player_by_name(name)
if not player then return end
if jump == "" then jump = 1 end
if type(tonumber(jump)) ~= "number"
or tonumber(jump) < 0
or tonumber(jump) > 10 then
minetest.chat_send_player(name, "[~] Jump height must be between 0.0 and 10.0.")
return
end
player:set_physics_override(nil, tonumber(jump), nil)
minetest.chat_send_player(name, "[~] Jump height set to " .. tonumber(jump) * 100 .. " %.")
end,
})
minetest.register_chatcommand("hotbar", {
params = "[size]",
description = "Sets the size of your hotbar",
func = function(name, slots)
if slots == "" then slots = 16 end
if type(tonumber(slots)) ~= "number" or tonumber(slots) < 1 or tonumber(slots) > 23 then
minetest.chat_send_player(name, "[_] Hotbar size must be between 1 and 23.")
return
end
local player = minetest.get_player_by_name(name)
player:hud_set_hotbar_itemcount(tonumber(slots))
minetest.chat_send_player(name, "[_] Hotbar size set to " .. tonumber(slots) .. ".")
end,
})
|
fix infotool crash when unknow node
|
fix infotool crash when unknow node
|
Lua
|
unlicense
|
Coethium/server-minetestforfun,paly2/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,paly2/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
|
55220babe8db8923d99c2223f73798c6e68e22d1
|
stdlib/surface.lua
|
stdlib/surface.lua
|
--- Surface module
-- @module Surface
require 'stdlib/core'
Surface = {}
--- Flexible, safe lookup function for surfaces. <p>
-- May be given a string, the name of a surface, or may be given a table with surface names,
-- may be given the a surface object, or may be given a table of surface objects, or
-- may be given nil. <p>
-- Returns an array of surface objects of all valid, existing surfaces
-- If a surface does not exist for the surface, it is ignored, if no surfaces
-- are given, an empty array is returned.
-- @param surface to lookup
-- @return the list of surfaces looked up
function Surface.lookup(surface)
if not surface then
return {}
end
if type(surface) == 'string' then
if game.surfaces[surface] then
return {game.surfaces[surface]}
end
return {}
end
local result = {}
for _, surface_item in pairs(surface) do
if type(surface_item) == 'string' then
if game.surfaces[surface_item] then
table.insert(result, game.surfaces[surface_item])
end
elseif type(surface_item) == 'table' and surface_item['__self'] then
table.insert(result, surface_item)
end
end
return result
end
--- Given search criteria, a table that contains a name or type of entity to search for,
-- and optionally surface or force, searches all loaded chunks for the entities that
-- match the critera.
-- @usage
----Surface.final_all_entities({ type = 'unit', surface = 'nauvis' }) --returns a list containing all unit entities on the nauvis surface
-- @param search_criteria a table of criteria. Must contain either the name or type or force of an entity. May contain surface or force.
-- @return an array of all entities that matched the criteria
function Surface.find_all_entities(search_criteria)
fail_if_missing(search_criteria, "missing search_criteria argument")
if search_criteria.name == nil and search_criteria.type == nil and search_criteria.force == nil then
error("Missing search criteria field: name or type or force of entity", 2)
end
local surface_list = Surface.lookup(search_criteria.surface)
if search_criteria.surface == nil then
surface_list = game.surfaces
end
local result = {}
for _, surface in pairs(surface_list) do
-- TODO: this chunk iteration is no longer nessecary in Factorio 13.10+
-- see https://forums.factorio.com/viewtopic.php?f=3&t=29612 for details
for chunk in surface.get_chunks() do
local entities = surface.find_entities_filtered(
{
area = { left_top = { x = chunk.x * 32, y = chunk.y * 32 }, right_bottom = {x = (chunk.x + 1) * 32, y = (chunk.y + 1) * 32}},
name = search_criteria.name,
type = search_criteria.type,
force = search_criteria.force
})
for _, entity in pairs(entities) do
table.insert(result, entity)
end
end
end
return result
end
return Surface
|
--- Surface module
-- @module Surface
require 'stdlib/core'
require 'stdlib/area/area'
Surface = {}
--- Flexible, safe lookup function for surfaces. <p>
-- May be given a string, the name of a surface, or may be given a table with surface names,
-- may be given the a surface object, or may be given a table of surface objects, or
-- may be given nil. <p>
-- Returns an array of surface objects of all valid, existing surfaces
-- If a surface does not exist for the surface, it is ignored, if no surfaces
-- are given, an empty array is returned.
-- @param surface to lookup
-- @return the list of surfaces looked up
function Surface.lookup(surface)
if not surface then
return {}
end
if type(surface) == 'string' then
if game.surfaces[surface] then
return {game.surfaces[surface]}
end
return {}
end
local result = {}
for _, surface_item in pairs(surface) do
if type(surface_item) == 'string' then
if game.surfaces[surface_item] then
table.insert(result, game.surfaces[surface_item])
end
elseif type(surface_item) == 'table' and surface_item['__self'] then
table.insert(result, surface_item)
end
end
return result
end
--- Given search criteria, a table that contains a name or type of entity to search for,
-- and optionally surface or force, searches all loaded chunks for the entities that
-- match the critera.
-- @usage
----Surface.final_all_entities({ type = 'unit', surface = 'nauvis', area = {{-1000,20},{-153,2214}}) --returns a list containing all unit entities on the nauvis surface in the given area
-- @param search_criteria a table of criteria. Must contain either the *name* or *type* or *force* of an entity. May contain *surface* or *force* or *area*.
-- @return an array of all entities that matched the criteria
function Surface.find_all_entities(search_criteria)
fail_if_missing(search_criteria, "missing search_criteria argument")
if search_criteria.name == nil and search_criteria.type == nil and search_criteria.force == nil and search_criteria.area == nil then
error("Missing search criteria field: name or type or force or area of entity", 2)
end
local surface_list = Surface.lookup(search_criteria.surface)
if search_criteria.surface == nil then
surface_list = game.surfaces
end
local result = {}
for _, surface in pairs(surface_list) do
local entities = surface.find_entities_filtered(
{
area = search_criteria.area,
name = search_criteria.name,
type = search_criteria.type,
force = search_criteria.force
})
for _, entity in pairs(entities) do
table.insert(result, entity)
end
end
return result
end
--- determine surface extension
-- returns Area covering entire extension of this surface
-- useful, if you compare total number of chunks with number of chunks of this area
-- @param surface A surface table, see lookup() to get one.
-- @return Area
function Surface.get_surface_bounds(surface)
fail_if_missing(surface, "missing surface value")
local x1, y1, x2, y2 = 0, 0, 0, 0
for chunk in surface.get_chunks() do
if chunk.x < x1 then
x1 = chunk.x
elseif chunk.x > x2 then
x2 = chunk.x
end
if chunk.y < y1 then
y1 = chunk.y
elseif chunk.y > y2 then
y2 = chunk.y
end
end
return Area.construct(x1*32, y1*32, x2*32, y2*32)
end
return Surface
|
Fixed Surface.find_all_entities() for Factorio 0.13.10 (incompatible with previous versions!), but increased search speed a lot.
|
Fixed Surface.find_all_entities() for Factorio 0.13.10 (incompatible with previous versions!), but increased search speed a lot.
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
8b9d91913e6bc302922d08ad302cc088bb40bcbc
|
init.lua
|
init.lua
|
-- Alias various helper variables.
local opt = vim.opt -- Options.
local cmd = vim.cmd -- Vim commands.
-- Enable relative line numbers.
opt.number = true
opt.relativenumber = true
opt.scrolloff = 3
-- Highlight current line.
opt.cursorline = true
-- Ignore case in searches.
opt.ignorecase = true
-- Show the filename in the window titlebar.
opt.title = true
-- Tabs configuration.
opt.tabstop = 2
opt.shiftwidth = 2
opt.expandtab = true
-- Use smart indentation.
opt.smartindent = true
-- Load packages.
require('packer').startup(function()
use 'wbthomason/packer.nvim' -- package manager
use 'connorholyday/vim-snazzy' -- theme
use 'lukas-reineke/indent-blankline.nvim' -- indentation guides
use 'tpope/vim-fugitive' -- git
use 'airblade/vim-gitgutter' -- git gutter
use 'bling/vim-airline' -- status line
use 'vim-airline/vim-airline-themes' -- status line themes
end)
-- Configure theme.
cmd 'colorscheme snazzy'
-- Configure indentation guides.
vim.g.indent_blankline_char = '│'
-- Configure status line.
opt.laststatus = 2
cmd([[
let g:airline_theme='base16_snazzy'
let g:airline_left_sep = ''
let g:airline_right_sep = ''
let g:airline_section_z = airline#section#create(['%3p%%', 'linenr', 'maxlinenr'])
if !exists('g:airline_symbols')
let g:airline_symbols = {}
endif
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = ' Ξ '
let g:airline_symbols.notexists = '!'
let g:airline_symbols.maxlinenr = ' ¶'
]])
|
-- Alias various helper variables.
local opt = vim.opt -- Options.
local cmd = vim.cmd -- Vim commands.
-- Enable relative line numbers.
opt.number = true
opt.relativenumber = true
opt.scrolloff = 3
-- Highlight current line.
opt.cursorline = true
-- Ignore case in searches.
opt.ignorecase = true
-- Show the filename in the window titlebar.
opt.title = true
-- Tabs configuration.
opt.tabstop = 2
opt.shiftwidth = 2
opt.expandtab = true
-- Use smart indentation.
opt.smartindent = true
-- Load packages.
require('packer').startup(function()
use 'wbthomason/packer.nvim' -- package manager
use 'connorholyday/vim-snazzy' -- theme
use 'lukas-reineke/indent-blankline.nvim' -- indentation guides
use 'tpope/vim-fugitive' -- git
use 'airblade/vim-gitgutter' -- git gutter
use 'bling/vim-airline' -- status line
use 'vim-airline/vim-airline-themes' -- status line themes
end)
-- Configure theme.
cmd 'colorscheme snazzy'
-- Fix color scheme search highlight colors
cmd 'autocmd ColorScheme * highlight Search guibg=#ff6ac1'
cmd 'autocmd ColorScheme * highlight IncSearch guibg=#ff6ac1'
-- Configure indentation guides.
vim.g.indent_blankline_char = '│'
-- Configure status line.
opt.laststatus = 2
cmd([[
let g:airline_theme='base16_snazzy'
let g:airline_left_sep = ''
let g:airline_right_sep = ''
let g:airline_section_z = airline#section#create(['%3p%%', 'linenr', 'maxlinenr'])
if !exists('g:airline_symbols')
let g:airline_symbols = {}
endif
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = ' Ξ '
let g:airline_symbols.notexists = '!'
let g:airline_symbols.maxlinenr = ' ¶'
]])
|
Fix nvim color scheme search highlight colors
|
Fix nvim color scheme search highlight colors
|
Lua
|
mit
|
HiDeoo/dotfiles
|
7d4c4bf72a84d1a69c439bf3cfbc293c5cef95ec
|
init.lua
|
init.lua
|
local textadept = require("textadept")
local events = require("events")
local constants = require("textadept-nim.constants")
local icons = require("textadept-nim.icons")
local nimsuggest = require("textadept-nim.nimsuggest")
local check_executable = require("textadept-nim.utils").check_executable
local sessions = require("textadept-nim.sessions")
local nim_shutdown_all_sessions = function() sessions:stop_all() end
local renamer = require("textadept-nim.rename")
-- Keybinds:
-- API Helper key
local api_helper_key = "ch"
-- GoTo Definition key
local goto_definition_key = "cG"
-- Smart replacer key
local smart_replace_key = "cg"
local on_buffer_delete = function()
-- Checks if any nimsuggest session left without
-- binding to buffer.
-- All unbound sessions will be closed
local to_remove = {}
for k, v in pairs(sessions.session_of) do
local keep = false
for i, b in ipairs(_BUFFERS) do
if b.filename ~= nil then
if b.filename == k then keep = true end
end
end
if not keep then table.insert(to_remove, k) end
end
for i, v in pairs(to_remove) do
sessions:detach(v)
end
end
local on_file_load = function()
-- Called when editor loads file.
-- Trying to get information about project and starts nimsuggest
if buffer ~= nil and buffer:get_lexer(true) == "nim" then
buffer.use_tabs = false
buffer.tab_width = 2
nimsuggest.check()
end
end
local function gotoDeclaration(position)
-- Puts cursor to declaration
local answer = nimsuggest.definition(position)
if #answer > 0 then
local path = answer[1].file
local line = tonumber(answer[1].line) - 1
local col = tonumber(answer[1].column)
if path ~= buffer.filename then
ui.goto_file(path, false, view)
end
local pos = buffer:find_column(line, col)
buffer:goto_pos(pos)
buffer:vertical_centre_caret()
buffer:word_right_end_extend()
end
end
-- list of additional actions on symbol encountering
-- for further use
local actions_on_symbol = {
[40] = function(pos)
local suggestions = nimsuggest.context(pos)
for i, v in pairs(suggestions) do
local brackets = v.type:match("%((.*)%)")
buffer:call_tip_show(pos, brackets)
end
end,
[46] = function(pos)
textadept.editing.autocomplete("nim")
end,
}
local function remove_type_info(text, position)
if buffer == nil or buffer:get_lexer(true) ~= "nim" then
return
end
local name = text:match("^([^:]+):.*")
if name ~= nil
then
local pos = buffer.current_pos
local to_paste = name:sub(pos-position+1)
buffer:insert_text(pos, to_paste)
buffer:word_right_end()
buffer:auto_c_cancel()
end
end
local function nim_complete(name)
-- Returns a list of suggestions for autocompletion
buffer.auto_c_separator = 35
icons:register()
local shift = 0
local curline = buffer:get_cur_line()
local cur_col = buffer.column[buffer.current_pos] + 1
local startprefix = cur_col
for i = 1, cur_col do
local shifted_col = cur_col - i
local c = curline:sub(shifted_col, shifted_col)
if c == c:match("([^%w_-])")
then
shift = i - 1
break
end
startprefix = shifted_col
end
local suggestions = {}
local prefix = curline:sub(startprefix, cur_col-1)
local token_list = nimsuggest.suggest(buffer.current_pos-shift)
for i, v in pairs(token_list) do
local start, _ = v.name:find(prefix, 0, 1)
if start == 1 then
table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind])
end
end
if #suggestions == 0 then
return textadept.editing.autocompleters.word(name)
end
if #suggestions == 1 then
remove_type_info(suggestions[1], buffer.current_pos - shift)
return
end
return shift, suggestions
end
if check_executable(constants.nimsuggest_exe) then
events.connect(events.FILE_AFTER_SAVE, on_file_load)
events.connect(events.QUIT, nim_shutdown_all_sessions)
events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions)
events.connect(events.FILE_OPENED, on_file_load)
events.connect(events.BUFFER_DELETED, on_buffer_delete)
events.connect(events.AUTO_C_SELECTION, remove_type_info)
events.connect(events.CHAR_ADDED, function(ch)
if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil
then return end
actions_on_symbol[ch](buffer.current_pos)
end)
keys.nim = {
-- Documentation loader on Ctrl-H
[api_helper_key] = function()
if buffer:get_lexer() == "nim" then
if textadept.editing.api_files.nim == nil then
textadept.editing.api_files.nim = {}
end
local answer = nimsuggest.definition(buffer.current_pos)
if #answer > 0 then
buffer:call_tip_show(buffer.current_pos,
answer[1].skind:match("sk(.*)").." "..answer[1].name..": "..
answer[1].type.."\n"..answer[1].comment)
end
end
end,
-- Goto definition on Ctrl-Shift-G
[goto_definition_key] = function()
gotoDeclaration(buffer.current_pos)
end,
-- Smart replace
[smart_replace_key] = renamer.spawn_dialog,
}
textadept.editing.autocompleters.nim = nim_complete
end
if check_executable(constants.nim_compiler_exe) then
textadept.run.compile_commands.nim = function ()
return constants.nim_compiler_exe.." "..
sessions.active[sessions.session_of[buffer.filename]].project.backend..
" %p"
end
textadept.run.run_commands.nim = function ()
return constants.nim_compiler_exe.." "..
sessions.active[sessions.session_of[buffer.filename]].project.backend..
" --run %p"
end
end
|
local textadept = require("textadept")
local events = require("events")
local constants = require("textadept-nim.constants")
local icons = require("textadept-nim.icons")
local nimsuggest = require("textadept-nim.nimsuggest")
local check_executable = require("textadept-nim.utils").check_executable
local sessions = require("textadept-nim.sessions")
local nim_shutdown_all_sessions = function() sessions:stop_all() end
local renamer = require("textadept-nim.rename")
-- Keybinds:
-- API Helper key
local api_helper_key = "ch"
-- GoTo Definition key
local goto_definition_key = "cG"
-- Smart replacer key
local smart_replace_key = "cg"
local on_buffer_delete = function()
-- Checks if any nimsuggest session left without
-- binding to buffer.
-- All unbound sessions will be closed
local to_remove = {}
for k, v in pairs(sessions.session_of) do
local keep = false
for i, b in ipairs(_BUFFERS) do
if b.filename ~= nil then
if b.filename == k then keep = true end
end
end
if not keep then table.insert(to_remove, k) end
end
for i, v in pairs(to_remove) do
sessions:detach(v)
end
end
local on_file_load = function()
-- Called when editor loads file.
-- Trying to get information about project and starts nimsuggest
if buffer ~= nil and buffer:get_lexer(true) == "nim" then
buffer.use_tabs = false
buffer.tab_width = 2
nimsuggest.check()
end
end
local function gotoDeclaration(position)
-- Puts cursor to declaration
local answer = nimsuggest.definition(position)
if #answer > 0 then
local path = answer[1].file
local line = tonumber(answer[1].line) - 1
local col = tonumber(answer[1].column)
if path ~= buffer.filename then
ui.goto_file(path, false, view)
end
local pos = buffer:find_column(line, col)
buffer:goto_pos(pos)
buffer:vertical_centre_caret()
buffer:word_right_end_extend()
end
end
-- list of additional actions on symbol encountering
-- for further use
local actions_on_symbol = {
[40] = function(pos)
local suggestions = nimsuggest.context(pos)
for i, v in pairs(suggestions) do
local brackets = v.type:match("%((.*)%)")
buffer:call_tip_show(pos, brackets)
end
end,
[46] = function(pos)
textadept.editing.autocomplete("nim")
end,
}
local function remove_type_info(text, position)
if buffer == nil or buffer:get_lexer(true) ~= "nim" then
return
end
local name = text:match("^([^:]+):.*")
if name ~= nil
then
local pos = buffer.current_pos
local to_paste = name:sub(pos-position+1)
buffer:insert_text(pos, to_paste)
buffer:word_right_end()
buffer:auto_c_cancel()
end
end
local function nim_complete(name)
-- Returns a list of suggestions for autocompletion
buffer.auto_c_separator = 35
icons:register()
local shift = 0
local curline = buffer:get_cur_line()
local cur_col = buffer.column[buffer.current_pos] + 1
local startprefix = cur_col
for i = 1, cur_col do
local shifted_col = cur_col - i
local c = curline:sub(shifted_col, shifted_col)
shift = i - 1
if c:match("[^%w_]")
then
break
end
startprefix = shifted_col
end
local suggestions = {}
local token_list = nimsuggest.suggest(buffer.current_pos-shift)
for i, v in pairs(token_list) do
table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind])
end
if #suggestions == 0 then
return textadept.editing.autocompleters.word(name)
end
if #suggestions == 1 then
remove_type_info(suggestions[1], buffer.current_pos - shift)
return
end
return shift, suggestions
end
if check_executable(constants.nimsuggest_exe) then
events.connect(events.FILE_AFTER_SAVE, on_file_load)
events.connect(events.QUIT, nim_shutdown_all_sessions)
events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions)
events.connect(events.FILE_OPENED, on_file_load)
events.connect(events.BUFFER_DELETED, on_buffer_delete)
events.connect(events.AUTO_C_SELECTION, remove_type_info)
events.connect(events.CHAR_ADDED, function(ch)
if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil
then return end
actions_on_symbol[ch](buffer.current_pos)
end)
keys.nim = {
-- Documentation loader on Ctrl-H
[api_helper_key] = function()
if buffer:get_lexer() == "nim" then
if textadept.editing.api_files.nim == nil then
textadept.editing.api_files.nim = {}
end
local answer = nimsuggest.definition(buffer.current_pos)
if #answer > 0 then
buffer:call_tip_show(buffer.current_pos,
answer[1].skind:match("sk(.*)").." "..answer[1].name..": "..
answer[1].type.."\n"..answer[1].comment)
end
end
end,
-- Goto definition on Ctrl-Shift-G
[goto_definition_key] = function()
gotoDeclaration(buffer.current_pos)
end,
-- Smart replace
[smart_replace_key] = renamer.spawn_dialog,
}
textadept.editing.autocompleters.nim = nim_complete
end
if check_executable(constants.nim_compiler_exe) then
textadept.run.compile_commands.nim = function ()
return constants.nim_compiler_exe.." "..
sessions.active[sessions.session_of[buffer.filename]].project.backend..
" %p"
end
textadept.run.run_commands.nim = function ()
return constants.nim_compiler_exe.." "..
sessions.active[sessions.session_of[buffer.filename]].project.backend..
" --run %p"
end
end
|
Fixes original filtering of suggestion
|
Fixes original filtering of suggestion
|
Lua
|
mit
|
xomachine/textadept-nim
|
72728ed45da04c3e59a53ae14f0e3ae52af4fa29
|
scripts/shaderc.lua
|
scripts/shaderc.lua
|
--
-- Copyright 2010-2016 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
project "glslang"
kind "StaticLib"
configuration { "vs*" }
buildoptions {
"/wd4005", -- warning C4005: '_CRT_SECURE_NO_WARNINGS': macro redefinition
}
configuration { "not vs*" }
buildoptions {
"-Wno-ignored-qualifiers",
"-Wno-inconsistent-missing-override",
"-Wno-missing-field-initializers",
"-Wno-reorder",
"-Wno-shadow",
"-Wno-sign-compare",
"-Wno-undef",
"-Wno-unknown-pragmas",
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration { "osx" }
buildoptions {
"-Wno-c++11-extensions",
"-Wno-unused-const-variable",
}
configuration { "linux-*" }
buildoptions {
"-Wno-unused-but-set-variable",
}
configuration {}
includedirs {
"../3rdparty/glslang",
}
files {
"../3rdparty/glslang/glslang/**.cpp",
"../3rdparty/glslang/glslang/**.h",
"../3rdparty/glslang/hlsl/**.cpp",
"../3rdparty/glslang/hlsl/**.h",
"../3rdparty/glslang/SPIRV/**.cpp",
"../3rdparty/glslang/SPIRV/**.h",
"../3rdparty/glslang/OGLCompilersDLL/**.cpp",
"../3rdparty/glslang/OGLCompilersDLL/**.h",
"../3rdparty/glsl-parser/**.cpp",
"../3rdparty/glsl-parser/**.h",
}
removefiles {
"../3rdparty/glsl-parser/main.cpp",
"../3rdparty/glslang/glslang/OSDependent/Unix/main.cpp",
"../3rdparty/glslang/glslang/OSDependent/Windows/main.cpp",
}
configuration { "windows" }
removefiles {
"../3rdparty/glslang/glslang/OSDependent/Unix/**.cpp",
"../3rdparty/glslang/glslang/OSDependent/Unix/**.h",
}
configuration { "not windows" }
removefiles {
"../3rdparty/glslang/glslang/OSDependent/Windows/**.cpp",
"../3rdparty/glslang/glslang/OSDependent/Windows/**.h",
}
configuration {}
project "shaderc"
kind "ConsoleApp"
local GLSL_OPTIMIZER = path.join(BGFX_DIR, "3rdparty/glsl-optimizer")
local FCPP_DIR = path.join(BGFX_DIR, "3rdparty/fcpp")
includedirs {
path.join(GLSL_OPTIMIZER, "src"),
}
removeflags {
-- GCC 4.9 -O2 + -fno-strict-aliasing don't work together...
"OptimizeSpeed",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "src/glsl/msvc"),
}
defines { -- glsl-optimizer
"__STDC__",
"__STDC_VERSION__=199901L",
"strdup=_strdup",
"alloca=_alloca",
"isascii=__isascii",
}
buildoptions {
"/wd4996" -- warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup.
}
configuration { "mingw-*" }
targetextension ".exe"
configuration { "mingw* or linux or osx" }
buildoptions {
"-fno-strict-aliasing", -- glsl-optimizer has bugs if strict aliasing is used.
"-Wno-unused-parameter",
}
removebuildoptions {
"-Wshadow", -- glsl-optimizer is full of -Wshadow warnings ignore it.
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "include/c99"),
}
configuration {}
defines { -- fcpp
"NINCLUDE=64",
"NWORK=65536",
"NBUFF=65536",
"OLD_PREPROCESSOR=0",
}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
FCPP_DIR,
path.join(BGFX_DIR, "3rdparty/glslang/glslang/Public"),
path.join(BGFX_DIR, "3rdparty/glslang/glslang/Include"),
path.join(BGFX_DIR, "3rdparty/glslang"),
-- path.join(BGFX_DIR, "3rdparty/spirv-tools/include"),
path.join(GLSL_OPTIMIZER, "include"),
path.join(GLSL_OPTIMIZER, "src/mesa"),
path.join(GLSL_OPTIMIZER, "src/mapi"),
path.join(GLSL_OPTIMIZER, "src/glsl"),
}
files {
path.join(BGFX_DIR, "tools/shaderc/**.cpp"),
path.join(BGFX_DIR, "tools/shaderc/**.h"),
path.join(BGFX_DIR, "src/vertexdecl.**"),
path.join(BGFX_DIR, "src/shader_spirv.**"),
path.join(FCPP_DIR, "**.h"),
path.join(FCPP_DIR, "cpp1.c"),
path.join(FCPP_DIR, "cpp2.c"),
path.join(FCPP_DIR, "cpp3.c"),
path.join(FCPP_DIR, "cpp4.c"),
path.join(FCPP_DIR, "cpp5.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.h"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.h"),
path.join(GLSL_OPTIMIZER, "src/util/**.c"),
path.join(GLSL_OPTIMIZER, "src/util/**.h"),
}
removefiles {
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/glcpp.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/tests/**"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.l"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.y"),
path.join(GLSL_OPTIMIZER, "src/glsl/ir_set_program_inouts.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/main.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/builtin_stubs.cpp"),
}
links {
"glslang",
}
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), {
path.join(BGFX_DIR, "scripts/shaderc.lua"), }) then
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), {
path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"), }) then
removefiles {
path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"),
}
end
dofile(path.join(BGFX_DIR, "../bgfx-ext/scripts/shaderc.lua") )
end
configuration { "osx or linux-*" }
links {
"pthread",
}
configuration {}
strip()
|
--
-- Copyright 2010-2016 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
project "glslang"
kind "StaticLib"
configuration { "vs2012" }
defines {
"strtoll=_strtoi64",
"strtoull=_strtoui64",
}
configuration { "vs*" }
buildoptions {
"/wd4005", -- warning C4005: '_CRT_SECURE_NO_WARNINGS': macro redefinition
}
configuration { "not vs*" }
buildoptions {
"-Wno-ignored-qualifiers",
"-Wno-inconsistent-missing-override",
"-Wno-missing-field-initializers",
"-Wno-reorder",
"-Wno-shadow",
"-Wno-sign-compare",
"-Wno-undef",
"-Wno-unknown-pragmas",
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration { "osx" }
buildoptions {
"-Wno-c++11-extensions",
"-Wno-unused-const-variable",
}
configuration { "linux-*" }
buildoptions {
"-Wno-unused-but-set-variable",
}
configuration {}
includedirs {
"../3rdparty/glslang",
}
files {
"../3rdparty/glslang/glslang/**.cpp",
"../3rdparty/glslang/glslang/**.h",
"../3rdparty/glslang/hlsl/**.cpp",
"../3rdparty/glslang/hlsl/**.h",
"../3rdparty/glslang/SPIRV/**.cpp",
"../3rdparty/glslang/SPIRV/**.h",
"../3rdparty/glslang/OGLCompilersDLL/**.cpp",
"../3rdparty/glslang/OGLCompilersDLL/**.h",
"../3rdparty/glsl-parser/**.cpp",
"../3rdparty/glsl-parser/**.h",
}
removefiles {
"../3rdparty/glsl-parser/main.cpp",
"../3rdparty/glslang/glslang/OSDependent/Unix/main.cpp",
"../3rdparty/glslang/glslang/OSDependent/Windows/main.cpp",
}
configuration { "windows" }
removefiles {
"../3rdparty/glslang/glslang/OSDependent/Unix/**.cpp",
"../3rdparty/glslang/glslang/OSDependent/Unix/**.h",
}
configuration { "not windows" }
removefiles {
"../3rdparty/glslang/glslang/OSDependent/Windows/**.cpp",
"../3rdparty/glslang/glslang/OSDependent/Windows/**.h",
}
configuration {}
project "shaderc"
kind "ConsoleApp"
local GLSL_OPTIMIZER = path.join(BGFX_DIR, "3rdparty/glsl-optimizer")
local FCPP_DIR = path.join(BGFX_DIR, "3rdparty/fcpp")
includedirs {
path.join(GLSL_OPTIMIZER, "src"),
}
removeflags {
-- GCC 4.9 -O2 + -fno-strict-aliasing don't work together...
"OptimizeSpeed",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "src/glsl/msvc"),
}
defines { -- glsl-optimizer
"__STDC__",
"__STDC_VERSION__=199901L",
"strdup=_strdup",
"alloca=_alloca",
"isascii=__isascii",
}
buildoptions {
"/wd4996" -- warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup.
}
configuration { "mingw-*" }
targetextension ".exe"
configuration { "mingw* or linux or osx" }
buildoptions {
"-fno-strict-aliasing", -- glsl-optimizer has bugs if strict aliasing is used.
"-Wno-unused-parameter",
}
removebuildoptions {
"-Wshadow", -- glsl-optimizer is full of -Wshadow warnings ignore it.
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "include/c99"),
}
configuration {}
defines { -- fcpp
"NINCLUDE=64",
"NWORK=65536",
"NBUFF=65536",
"OLD_PREPROCESSOR=0",
}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
FCPP_DIR,
path.join(BGFX_DIR, "3rdparty/glslang/glslang/Public"),
path.join(BGFX_DIR, "3rdparty/glslang/glslang/Include"),
path.join(BGFX_DIR, "3rdparty/glslang"),
-- path.join(BGFX_DIR, "3rdparty/spirv-tools/include"),
path.join(GLSL_OPTIMIZER, "include"),
path.join(GLSL_OPTIMIZER, "src/mesa"),
path.join(GLSL_OPTIMIZER, "src/mapi"),
path.join(GLSL_OPTIMIZER, "src/glsl"),
}
files {
path.join(BGFX_DIR, "tools/shaderc/**.cpp"),
path.join(BGFX_DIR, "tools/shaderc/**.h"),
path.join(BGFX_DIR, "src/vertexdecl.**"),
path.join(BGFX_DIR, "src/shader_spirv.**"),
path.join(FCPP_DIR, "**.h"),
path.join(FCPP_DIR, "cpp1.c"),
path.join(FCPP_DIR, "cpp2.c"),
path.join(FCPP_DIR, "cpp3.c"),
path.join(FCPP_DIR, "cpp4.c"),
path.join(FCPP_DIR, "cpp5.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.h"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.h"),
path.join(GLSL_OPTIMIZER, "src/util/**.c"),
path.join(GLSL_OPTIMIZER, "src/util/**.h"),
}
removefiles {
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/glcpp.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/tests/**"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.l"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.y"),
path.join(GLSL_OPTIMIZER, "src/glsl/ir_set_program_inouts.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/main.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/builtin_stubs.cpp"),
}
links {
"glslang",
}
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), {
path.join(BGFX_DIR, "scripts/shaderc.lua"), }) then
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), {
path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"), }) then
removefiles {
path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"),
}
end
dofile(path.join(BGFX_DIR, "../bgfx-ext/scripts/shaderc.lua") )
end
configuration { "osx or linux-*" }
links {
"pthread",
}
configuration {}
strip()
|
Fixed VS2012 build.
|
Fixed VS2012 build.
|
Lua
|
bsd-2-clause
|
bkaradzic/bgfx,jdryg/bgfx,emoon/bgfx,mmicko/bgfx,fluffyfreak/bgfx,attilaz/bgfx,bkaradzic/bgfx,jdryg/bgfx,bkaradzic/bgfx,emoon/bgfx,fluffyfreak/bgfx,jpcy/bgfx,MikePopoloski/bgfx,attilaz/bgfx,septag/bgfx,mmicko/bgfx,Synxis/bgfx,jpcy/bgfx,jpcy/bgfx,LWJGL-CI/bgfx,emoon/bgfx,bkaradzic/bgfx,mendsley/bgfx,septag/bgfx,LWJGL-CI/bgfx,jpcy/bgfx,mendsley/bgfx,fluffyfreak/bgfx,Synxis/bgfx,jdryg/bgfx,mendsley/bgfx,fluffyfreak/bgfx,jdryg/bgfx,MikePopoloski/bgfx,Synxis/bgfx,attilaz/bgfx,LWJGL-CI/bgfx,MikePopoloski/bgfx,LWJGL-CI/bgfx,septag/bgfx,mmicko/bgfx
|
802c71b0e9b076d01646c4839791681eeeee323f
|
data/templates/metronome/metronome.cfg.lua
|
data/templates/metronome/metronome.cfg.lua
|
-- ** Metronome's config file example **
--
-- The format is exactly equal to Prosody's:
--
-- Lists are written { "like", "this", "one" }
-- Lists can also be of { 1, 2, 3 } numbers, etc.
-- Either commas, or semi-colons; may be used as seperators.
--
-- A table is a list of values, except each value has a name. An
-- example would be:
--
-- ssl = { key = "keyfile.key", certificate = "certificate.cert" }
--
-- Tip: You can check that the syntax of this file is correct when you have finished
-- by running: luac -p metronome.cfg.lua
-- If there are any errors, it will let you know what and where they are, otherwise it
-- will keep quiet.
-- Global settings go in this section
-- This is the list of modules Metronome will load on startup.
-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
modules_enabled = {
-- Generally required
"roster"; -- Allow users to have a roster. Recommended.
"saslauth"; -- Authentication for clients. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"disco"; -- Service discovery
-- Not essential, but recommended
"private"; -- Private XML storage (for room bookmarks, etc.)
"vcard"; -- Allow users to set vCards
"pep"; -- Allows setting of mood, tune, etc.
"posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
"bidi"; -- Enables Bidirectional Server-to-Server Streams.
-- Nice to have
"version"; -- Replies to server version requests
"uptime"; -- Report how long server has been running
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"register"; -- Allow users to register on this server using a client and change passwords
"stream_management"; -- Allows clients and servers to use Stream Management
"stanza_optimizations"; -- Allows clients to use Client State Indication and SIFT
"message_carbons"; -- Allows clients to enable carbon copies of messages
"mam"; -- Enable server-side message archives using Message Archive Management
"push"; -- Enable Push Notifications via PubSub using XEP-0357
"lastactivity"; -- Enables clients to know the last presence status of an user
"adhoc_cm"; -- Allow to set client certificates to login through SASL External via adhoc
"admin_adhoc"; -- administration adhoc commands
"bookmarks"; -- XEP-0048 Bookmarks synchronization between PEP and Private Storage
"sec_labels"; -- Allows to use a simplified version XEP-0258 Security Labels and related ACDFs.
-- Other specific functionality
--"admin_telnet"; -- administration console, telnet to port 5582
--"admin_web"; -- administration web interface
"bosh"; -- Enable support for BOSH clients, aka "XMPP over Bidirectional Streams over Synchronous HTTP"
--"compression"; -- Allow clients to enable Stream Compression
--"spim_block"; -- Require authorization via OOB form for messages from non-contacts and block unsollicited messages
--"gate_guard"; -- Enable config-based blacklisting and hit-based auto-banning features
--"incidents_handling"; -- Enable Incidents Handling support (can be administered via adhoc commands)
--"server_presence"; -- Enables Server Buddies extension support
--"service_directory"; -- Enables Service Directories extension support
--"public_service"; -- Enables Server vCard support for public services in directories and advertises in features
--"register_api"; -- Provides secure API for both Out-Of-Band and In-Band registration for E-Mail verification
"websocket"; -- Enable support for WebSocket clients, aka "XMPP over WebSockets"
};
-- Server PID
pidfile = "/var/run/metronome/metronome.pid"
-- HTTP server
http_ports = { 5290 }
http_interfaces = { "127.0.0.1", "::1" }
--https_ports = { 5291 }
--https_interfaces = { "127.0.0.1", "::1" }
-- Enable IPv6
use_ipv6 = true
-- Discovery items
disco_items = {
{ "muc.{{ main_domain }}" },
{ "pubsub.{{ main_domain }}" },
{ "vjud.{{ main_domain }}" }
};
-- BOSH configuration (mod_bosh)
consider_bosh_secure = true
cross_domain_bosh = true
-- WebSocket configuration (mod_websocket)
consider_websocket_secure = true
cross_domain_websocket = true
-- Disable account creation by default, for security
allow_registration = false
-- Use LDAP storage backend for all stores
storage = "ldap"
-- Logging configuration
log = {
info = "/var/log/metronome/metronome.log"; -- Change 'info' to 'debug' for verbose logging
error = "/var/log/metronome/metronome.err";
-- "*syslog"; -- Uncomment this for logging to syslog
-- "*console"; -- Log to the console, useful for debugging with daemonize=false
}
------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
---Set up a local BOSH service
Component "localhost" "http"
modules_enabled = { "bosh" }
---Set up a MUC (multi-user chat) room server
Component "muc.{{ main_domain }}" "muc"
name = "{{ main_domain }} Chatrooms"
modules_enabled = {
"muc_limits";
"muc_log";
"muc_log_mam";
"muc_log_http";
"muc_vcard";
}
muc_event_rate = 0.5
muc_burst_factor = 10
---Set up a PubSub server
Component "pubsub.{{ main_domain }}" "pubsub"
name = "{{ main_domain }} Publish/Subscribe"
unrestricted_node_creation = true -- Anyone can create a PubSub node (from any server)
---Set up a VJUD service
Component "vjud.{{ main_domain }}" "vjud"
ud_disco_name = "{{ main_domain }} User Directory"
----------- Virtual hosts -----------
-- You need to add a VirtualHost entry for each domain you wish Metronome to serve.
-- Settings under each VirtualHost entry apply *only* to that host.
Include "conf.d/*.cfg.lua"
|
-- ** Metronome's config file example **
--
-- The format is exactly equal to Prosody's:
--
-- Lists are written { "like", "this", "one" }
-- Lists can also be of { 1, 2, 3 } numbers, etc.
-- Either commas, or semi-colons; may be used as seperators.
--
-- A table is a list of values, except each value has a name. An
-- example would be:
--
-- ssl = { key = "keyfile.key", certificate = "certificate.cert" }
--
-- Tip: You can check that the syntax of this file is correct when you have finished
-- by running: luac -p metronome.cfg.lua
-- If there are any errors, it will let you know what and where they are, otherwise it
-- will keep quiet.
-- Global settings go in this section
-- This is the list of modules Metronome will load on startup.
-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
modules_enabled = {
-- Generally required
"roster"; -- Allow users to have a roster. Recommended.
"saslauth"; -- Authentication for clients. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"disco"; -- Service discovery
-- Not essential, but recommended
"private"; -- Private XML storage (for room bookmarks, etc.)
"vcard"; -- Allow users to set vCards
"pep"; -- Allows setting of mood, tune, etc.
"posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
"bidi"; -- Enables Bidirectional Server-to-Server Streams.
-- Nice to have
"version"; -- Replies to server version requests
"uptime"; -- Report how long server has been running
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"register"; -- Allow users to register on this server using a client and change passwords
"stream_management"; -- Allows clients and servers to use Stream Management
"stanza_optimizations"; -- Allows clients to use Client State Indication and SIFT
"message_carbons"; -- Allows clients to enable carbon copies of messages
"mam"; -- Enable server-side message archives using Message Archive Management
"push"; -- Enable Push Notifications via PubSub using XEP-0357
"lastactivity"; -- Enables clients to know the last presence status of an user
"adhoc_cm"; -- Allow to set client certificates to login through SASL External via adhoc
"admin_adhoc"; -- administration adhoc commands
"bookmarks"; -- XEP-0048 Bookmarks synchronization between PEP and Private Storage
"sec_labels"; -- Allows to use a simplified version XEP-0258 Security Labels and related ACDFs.
-- Other specific functionality
--"admin_telnet"; -- administration console, telnet to port 5582
--"admin_web"; -- administration web interface
"bosh"; -- Enable support for BOSH clients, aka "XMPP over Bidirectional Streams over Synchronous HTTP"
--"compression"; -- Allow clients to enable Stream Compression
--"spim_block"; -- Require authorization via OOB form for messages from non-contacts and block unsollicited messages
--"gate_guard"; -- Enable config-based blacklisting and hit-based auto-banning features
--"incidents_handling"; -- Enable Incidents Handling support (can be administered via adhoc commands)
--"server_presence"; -- Enables Server Buddies extension support
--"service_directory"; -- Enables Service Directories extension support
--"public_service"; -- Enables Server vCard support for public services in directories and advertises in features
--"register_api"; -- Provides secure API for both Out-Of-Band and In-Band registration for E-Mail verification
"websocket"; -- Enable support for WebSocket clients, aka "XMPP over WebSockets"
};
-- Server PID
pidfile = "/var/run/metronome/metronome.pid"
-- HTTP server
http_ports = { 5290 }
http_interfaces = { "127.0.0.1", "::1" }
--https_ports = { 5291 }
--https_interfaces = { "127.0.0.1", "::1" }
-- Enable IPv6
use_ipv6 = true
-- Discovery items
disco_items = {
{ "muc.{{ main_domain }}" },
{ "pubsub.{{ main_domain }}" },
{ "upload.{{ main_domain }}" },
{ "vjud.{{ main_domain }}" }
};
-- BOSH configuration (mod_bosh)
consider_bosh_secure = true
cross_domain_bosh = true
-- WebSocket configuration (mod_websocket)
consider_websocket_secure = true
cross_domain_websocket = true
-- Disable account creation by default, for security
allow_registration = false
-- Use LDAP storage backend for all stores
storage = "ldap"
-- Logging configuration
log = {
info = "/var/log/metronome/metronome.log"; -- Change 'info' to 'debug' for verbose logging
error = "/var/log/metronome/metronome.err";
-- "*syslog"; -- Uncomment this for logging to syslog
-- "*console"; -- Log to the console, useful for debugging with daemonize=false
}
------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
---Set up a local BOSH service
Component "localhost" "http"
modules_enabled = { "bosh" }
---Set up a MUC (multi-user chat) room server
Component "muc.{{ main_domain }}" "muc"
name = "{{ main_domain }} Chatrooms"
modules_enabled = {
"muc_limits";
"muc_log";
"muc_log_mam";
"muc_log_http";
"muc_vcard";
}
muc_event_rate = 0.5
muc_burst_factor = 10
---Set up a PubSub server
Component "pubsub.{{ main_domain }}" "pubsub"
name = "{{ main_domain }} Publish/Subscribe"
unrestricted_node_creation = true -- Anyone can create a PubSub node (from any server)
---Set up a HTTP Upload service
Component "upload.{{ main_domain }}" "http_upload"
name = "{{ main_domain }} Sharing Service"
http_file_size_limit = 6*1024*1024
http_file_quota = 60*1024*1024
---Set up a VJUD service
Component "vjud.{{ main_domain }}" "vjud"
ud_disco_name = "{{ main_domain }} User Directory"
----------- Virtual hosts -----------
-- You need to add a VirtualHost entry for each domain you wish Metronome to serve.
-- Settings under each VirtualHost entry apply *only* to that host.
Include "conf.d/*.cfg.lua"
|
Update data/templates/metronome/metronome.cfg.lua
|
Update data/templates/metronome/metronome.cfg.lua
Add HTTP Upload service (moul's request), and fix indenting
|
Lua
|
agpl-3.0
|
YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost
|
18bca68cfe9d5d061d5a86e485a28fbb712f8e28
|
packages/rules.lua
|
packages/rules.lua
|
SILE.baseClass:loadPackage("raiselower")
SILE.baseClass:loadPackage("rebox")
SILE.registerCommand("hrule", function (options, _)
local width = SU.cast("length", options.width)
local height = SU.cast("length", options.height)
local depth = SU.cast("length", options.depth)
SILE.typesetter:pushHbox({
width = width:absolute(),
height = height:absolute(),
depth = depth:absolute(),
value = options.src,
outputYourself= function (self, typesetter, line)
local outputWidth = SU.rationWidth(self.width, self.width, line.ratio)
SILE.outputter.rule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY - self.height, outputWidth, self.height + self.depth)
typesetter.frame:advanceWritingDirection(outputWidth)
end
})
end, "Creates a line of width <width> and height <height>")
SILE.registerCommand("fullrule", function (options, _)
SILE.call("raise", { height = options.raise or "0.5em" }, function ()
SILE.call("hrule", {
height = options.height or "0.2pt",
width = options.width or "100%lw"
})
end)
end, "Draw a full width hrule centered on the current line")
SILE.registerCommand("underline", function (_, content)
local hbox = SILE.call("hbox", {}, content)
local gl = SILE.length() - hbox.width
SILE.call("lower", {height = "0.5pt"}, function()
SILE.call("hrule", {width = gl.length, height = "0.5pt"})
end)
SILE.typesetter:pushGlue({width = hbox.width})
end, "Underlines some content (badly)")
SILE.registerCommand("boxaround", function (_, content)
local hbox = SILE.call("hbox", {}, content)
local gl = SILE.length() - hbox.width
SILE.call("rebox", {width = 0}, function()
SILE.call("hrule", {width = gl.length-1, height = "0.5pt"})
end)
SILE.call("raise", {height = hbox.height}, function ()
SILE.call("hrule", {width = gl.length-1, height = "0.5pt"})
end)
SILE.call("hrule", { height = hbox.height, width = "0.5pt"})
SILE.typesetter:pushGlue({width = hbox.width})
SILE.call("hrule", { height = hbox.height, width = "0.5pt"})
end, "Draws a box around some content")
return { documentation = [[\begin{document}
The \code{rules} package draws lines. It provides three commands.
The first command is \code{\\hrule},
which draws a line of a given length and thickness, although it calls these
\code{width} and \code{height}. (A box is just a square line.)
Lines are treated just like other text to be output, and so can appear in the
middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one
was generated with \code{\\hrule[width=20pt, height=0.5pt]}.)
Like images, rules are placed along the baseline of a line of text.
The second command provided by \code{rules} is \code{\\underline}, which
underlines its contents.
\note{
Underlining is horrible typographic practice, and
you should \underline{never} do it.}
(That was produced with \code{\\underline\{never\}}.)
Finally, \code{fullrule} draws a thin line across the width of the current frame.
\end{document}]] }
|
SILE.baseClass:loadPackage("raiselower")
SILE.baseClass:loadPackage("rebox")
SILE.registerCommand("hrule", function (options, _)
local width = SU.cast("length", options.width)
local height = SU.cast("length", options.height)
local depth = SU.cast("length", options.depth)
SILE.typesetter:pushHbox({
width = width:absolute(),
height = height:absolute(),
depth = depth:absolute(),
value = options.src,
outputYourself= function (self, typesetter, line)
local outputWidth = SU.rationWidth(self.width, self.width, line.ratio)
local advance = typesetter.frame:writingDirection() == "RTL" and -outputWidth or outputWidth
SILE.outputter.rule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY - self.height, advance, self.height + self.depth)
typesetter.frame:advanceWritingDirection(outputWidth)
end
})
end, "Creates a line of width <width> and height <height>")
SILE.registerCommand("fullrule", function (options, _)
SILE.call("raise", { height = options.raise or "0.5em" }, function ()
SILE.call("hrule", {
height = options.height or "0.2pt",
width = options.width or "100%lw"
})
end)
end, "Draw a full width hrule centered on the current line")
SILE.registerCommand("underline", function (_, content)
local hbox = SILE.call("hbox", {}, content)
local gl = SILE.length() - hbox.width
SILE.call("lower", {height = "0.5pt"}, function()
SILE.call("hrule", {width = gl.length, height = "0.5pt"})
end)
SILE.typesetter:pushGlue({width = hbox.width})
end, "Underlines some content (badly)")
SILE.registerCommand("boxaround", function (_, content)
local hbox = SILE.call("hbox", {}, content)
local gl = SILE.length() - hbox.width
SILE.call("rebox", {width = 0}, function()
SILE.call("hrule", {width = gl.length-1, height = "0.5pt"})
end)
SILE.call("raise", {height = hbox.height}, function ()
SILE.call("hrule", {width = gl.length-1, height = "0.5pt"})
end)
SILE.call("hrule", { height = hbox.height, width = "0.5pt"})
SILE.typesetter:pushGlue({width = hbox.width})
SILE.call("hrule", { height = hbox.height, width = "0.5pt"})
end, "Draws a box around some content")
return { documentation = [[\begin{document}
The \code{rules} package draws lines. It provides three commands.
The first command is \code{\\hrule},
which draws a line of a given length and thickness, although it calls these
\code{width} and \code{height}. (A box is just a square line.)
Lines are treated just like other text to be output, and so can appear in the
middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one
was generated with \code{\\hrule[width=20pt, height=0.5pt]}.)
Like images, rules are placed along the baseline of a line of text.
The second command provided by \code{rules} is \code{\\underline}, which
underlines its contents.
\note{
Underlining is horrible typographic practice, and
you should \underline{never} do it.}
(That was produced with \code{\\underline\{never\}}.)
Finally, \code{fullrule} draws a thin line across the width of the current frame.
\end{document}]] }
|
fix(packages): Draw rules in the writing direction
|
fix(packages): Draw rules in the writing direction
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
979b883d36301307cb3eecef7fedea5858be7192
|
kong/pdk/table.lua
|
kong/pdk/table.lua
|
--- Utilities for Lua tables
--
-- @module kong.table
local new_tab
local clear_tab
do
---
-- Returns a table with pre-allocated number of slots in its array and hash
-- parts.
--
-- @function kong.table.new
-- @tparam[opt] number narr specifies the number of slots to pre-allocate
-- in the array part.
-- @tparam[opt] number nrec specifies the number of slots to pre-allocate in
-- the hash part.
-- @treturn table the newly created table
-- @usage
-- local tab = kong.table.new(4, 4)
local ok
ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function (narr, nrec) return {} end
end
---
-- Clears a table from all of its array and hash parts entries.
--
-- @function kong.table.clear
-- @tparam table tab the table which will be cleared
-- @return Nothing
-- @usage
-- local tab = {
-- "hello",
-- foo = "bar"
-- }
--
-- kong.table.clear(tab)
--
-- kong.log(tab[1]) -- nil
-- kong.log(tab.foo) -- nil
ok, clear_tab = pcall(require, "table.clear")
if not ok then
clear_tab = function (tab)
for k, _ in pairs(tab) do
tab[k] = nil
end
end
end
end
--- Merges the contents of two tables together, producing a new one.
-- The entries of both tables are copied non-recursively to the new one.
-- If both tables have the same key, the second one takes precedence.
-- @tparam table t1 The first table
-- @tparam table t2 The second table
-- @treturn table The (new) merged table
-- @usage
-- local t1 = {1, 2, 3, foo = "f"}
-- local t2 = {4, 5, bar = "b"}
-- local t3 = kong.table.merge(t1, t2) -- {4, 5, 3, foo = "f", bar = "b"}
local function merge_tab(t1, t2)
local res = {}
if t1 then
for k,v in pairs(t1) do
res[k] = v
end
end
if t2 then
for k,v in pairs(t2) do
res[k] = v
end
end
return res
end
local function new(self)
return {
new = new_tab,
clear = clear_tab,
merge = merge_tab,
}
end
return {
new = new,
}
|
--- Utilities for Lua tables
--
-- @module kong.table
local new_tab
local clear_tab
do
---
-- Returns a table with pre-allocated number of slots in its array and hash
-- parts.
--
-- @function kong.table.new
-- @tparam[opt] number narr specifies the number of slots to pre-allocate
-- in the array part.
-- @tparam[opt] number nrec specifies the number of slots to pre-allocate in
-- the hash part.
-- @treturn table the newly created table
-- @usage
-- local tab = kong.table.new(4, 4)
local ok
ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function (narr, nrec) return {} end
end
---
-- Clears a table from all of its array and hash parts entries.
--
-- @function kong.table.clear
-- @tparam table tab the table which will be cleared
-- @return Nothing
-- @usage
-- local tab = {
-- "hello",
-- foo = "bar"
-- }
--
-- kong.table.clear(tab)
--
-- kong.log(tab[1]) -- nil
-- kong.log(tab.foo) -- nil
ok, clear_tab = pcall(require, "table.clear")
if not ok then
clear_tab = function (tab)
for k, _ in pairs(tab) do
tab[k] = nil
end
end
end
end
--- Merges the contents of two tables together, producing a new one.
-- The entries of both tables are copied non-recursively to the new one.
-- If both tables have the same key, the second one takes precedence.
-- If only one table is given, it returns a copy.
-- @function kong.table.merge
-- @tparam[opt] table t1 The first table
-- @tparam[opt] table t2 The second table
-- @treturn table The (new) merged table
-- @usage
-- local t1 = {1, 2, 3, foo = "f"}
-- local t2 = {4, 5, bar = "b"}
-- local t3 = kong.table.merge(t1, t2) -- {4, 5, 3, foo = "f", bar = "b"}
local function merge_tab(t1, t2)
local res = {}
if t1 then
for k,v in pairs(t1) do
res[k] = v
end
end
if t2 then
for k,v in pairs(t2) do
res[k] = v
end
end
return res
end
local function new(self)
return {
new = new_tab,
clear = clear_tab,
merge = merge_tab,
}
end
return {
new = new,
}
|
docs(pdk) fix kong.table.merge ldoc comment (#6961)
|
docs(pdk) fix kong.table.merge ldoc comment (#6961)
Most likely the culprit is the missing `@function` tag
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
2ce7efd31062d91e4823010331cb820f97d3af96
|
src/lounge/lua/show.lua
|
src/lounge/lua/show.lua
|
#!/lounge/bin/janosh -f
local util = require("util")
local VIDEO_HOSTS={
["grooveshark.com/"]='youtube',
["youtube.com/"]='youtube',
["youtu.be/"]='youtube',
["vine.com/"]='youtube',
["tvthek.orf.at/"]='orf',
["videos.arte.tv/"]='arte7',
["vimeo.com/"]='vimeo',
["soundcloud.com/"]='soundcloud',
["ted.com/"]='ted',
["jamendo.com/"]='jamendo',
["bandcamp.com/"]='bandcamp',
["tindeck.com/"]='tindeck',
["put.io/"]='putio'
}
local CATEGORY_MAP={
["video"]='player',
["multipart"]='browser',
["audio"]='player',
["image"]='browser',
["animation"]='browser',
["radio"]='player',
["text"]='browser',
["pdf"]='pdf',
["youtube"]='player',
["orf"]='player',
["arte7"]='player',
["vimeo"]='player',
["soundcloud"]='player',
["ted"]='player',
["jamendo"]='player',
["bandcamp"]='player',
["tindeck"]='player',
["joker"]='player',
["putio"]='player',
["magnet"]='player'
}
local CATEGORY_FIX={
["application/octet-stream"]='video',
["application/x-matroska"]='video',
["audio/x-mpegurl"]='radio',
["application/pls"]='radio',
["application/pdf"]='pdf',
["audio/x-scpls"]='radio',
["image/gif"]='animation',
["application/ogg"]='video',
["application/x-bittorrent"]='joker'
}
function open(key, op, value)
util:notify("Resolving url: " .. value)
print("open:",value)
function ends(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
function getCategory(url)
print("getCategory:", url)
if string.match(url, "magnet:?") then
return "magnet"
end
hUrl=string.match(url, "http[s]*://([0-9a-zA-z.-_]*/)")
if hUrl ~= nil then
for host,category in pairs(VIDEO_HOSTS) do
print(hUrl,host);
if ends(hUrl,host) then
return category
end
end
end
mimeType="unknown/"
if string.match(url, "http[s]*://") then
head=""
location=url
lastloc=url
while location ~= nil do
lastloc=location
p, i, o, e = Janosh:popen("curl", "--head", location)
line=""
head=""
while true do
line=Janosh:preadLine(o)
if line == nil then break end
head= head .. string.gsub(line, "\r", "\n")
end
Janosh:pclose(i)
Janosh:pclose(e)
Janosh:pclose(o)
Janosh:pwait(p)
p, i, o, e = Janosh:popen("grep", "-iPo", "Location: \\K(.*)?(?=)")
Janosh:pwrite(i, head)
Janosh:pclose(i)
location=Janosh:preadLine(o)
Janosh:pclose(i)
Janosh:pclose(e)
Janosh:pclose(o)
Janosh:pwait(p)
end
line=util:split(head,"\n")[1]
token=util:split(line," ")[2]
code=tonumber(token)
print("code:", code)
if code ~= 200 then
mimeType="video/fixed"
else
mimeType=Janosh:capture("curl --head \"" .. lastloc .. "\" | grep -iPo 'Content-Type: \\K(.*)?(?=)'")
end
elseif string.match(url, "[a-zA-Z]+://") then
mimeType = "video/fixed"
else
file=url
mimeType=Janosh:capture("file -i \"" .. file .. "\" | sed 's/.*: \\([a-zA-Z]*\\/[a-zA-Z]*\\).*/\\1/p' | sed '1d'")
end
mimeType=util:trim(mimeType)
if mimeType == nil or mimeType == "" then
return nil
end
category=CATEGORY_FIX[mimeType]
if category == nil then
category=Janosh:capture("echo \"" .. mimeType .. "\" | cut -d'/' -f1")
end
return util:trim(category);
end
url=value
cat=getCategory(url)
handler=CATEGORY_MAP[cat]
print("triggering:", handler, "/", cat)
if handler ~= nil then
Janosh:set_all_t({"/" .. handler .. "/category",cat, "/" .. handler .. "/url", url})
else
util:exception("Unable to handle url: " .. url)
end
end
Janosh:subscribe("showUrl", open)
while true do
Janosh:sleep(100000)
end
|
#!/lounge/bin/janosh -f
local util = require("util")
local VIDEO_HOSTS={
["grooveshark.com/"]='youtube',
["youtube.com/"]='youtube',
["youtu.be/"]='youtube',
["vine.com/"]='youtube',
["dailymotion.com/"]='youtube',
["tvthek.orf.at/"]='orf',
["videos.arte.tv/"]='arte7',
["vimeo.com/"]='vimeo',
["soundcloud.com/"]='soundcloud',
["ted.com/"]='ted',
["jamendo.com/"]='jamendo',
["bandcamp.com/"]='bandcamp',
["tindeck.com/"]='tindeck',
["put.io/"]='putio'
}
local CATEGORY_MAP={
["video"]='player',
["multipart"]='browser',
["audio"]='player',
["image"]='browser',
["animation"]='browser',
["radio"]='player',
["text"]='browser',
["pdf"]='pdf',
["youtube"]='player',
["orf"]='player',
["arte7"]='player',
["vimeo"]='player',
["soundcloud"]='player',
["ted"]='player',
["jamendo"]='player',
["bandcamp"]='player',
["tindeck"]='player',
["joker"]='player',
["putio"]='player',
["magnet"]='player'
}
local CATEGORY_FIX={
["application/octet-stream"]='video',
["application/x-matroska"]='video',
["audio/x-mpegurl"]='radio',
["application/pls"]='radio',
["application/pdf"]='pdf',
["audio/x-scpls"]='radio',
["image/gif"]='animation',
["application/ogg"]='video',
["application/x-bittorrent"]='joker'
}
function open(key, op, value)
util:notify("Resolving url: " .. value)
print("open:",value)
function ends(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
function getCategory(url)
print("getCategory:", url)
if string.match(url, "magnet:?") then
return "magnet"
end
hUrl=string.match(url, "http[s]*://[w.]*([0-9a-zA-z._-]*/)")
if hUrl ~= nil then
for host,category in pairs(VIDEO_HOSTS) do
print(hUrl,host);
if ends(hUrl,host) then
return category
end
end
end
mimeType="unknown/"
if string.match(url, "http[s]*://") then
head=""
location=url
lastloc=url
while location ~= nil do
lastloc=location
p, i, o, e = Janosh:popen("curl", "--head", location)
line=""
head=""
while true do
line=Janosh:preadLine(o)
if line == nil then break end
head= head .. string.gsub(line, "\r", "\n")
end
Janosh:pclose(i)
Janosh:pclose(e)
Janosh:pclose(o)
Janosh:pwait(p)
p, i, o, e = Janosh:popen("grep", "-iPo", "Location: \\K(.*)?(?=)")
Janosh:pwrite(i, head)
Janosh:pclose(i)
location=Janosh:preadLine(o)
Janosh:pclose(i)
Janosh:pclose(e)
Janosh:pclose(o)
Janosh:pwait(p)
end
line=util:split(head,"\n")[1]
token=util:split(line," ")[2]
code=tonumber(token)
print("code:", code)
if code ~= 200 then
mimeType="video/fixed"
else
mimeType=Janosh:capture("curl --head \"" .. lastloc .. "\" | grep -iPo 'Content-Type: \\K(.*)?(?=)'")
end
elseif string.match(url, "[a-zA-Z]+://") then
mimeType = "video/fixed"
else
file=url
mimeType=Janosh:capture("file -i \"" .. file .. "\" | sed 's/.*: \\([a-zA-Z]*\\/[a-zA-Z]*\\).*/\\1/p' | sed '1d'")
end
mimeType=util:trim(mimeType)
if mimeType == nil or mimeType == "" then
return nil
end
category=CATEGORY_FIX[mimeType]
if category == nil then
category=Janosh:capture("echo \"" .. mimeType .. "\" | cut -d'/' -f1")
end
return util:trim(category);
end
url=value
cat=getCategory(url)
handler=CATEGORY_MAP[cat]
print("triggering:", handler, "/", cat)
if handler ~= nil then
Janosh:set_all_t({"/" .. handler .. "/category",cat, "/" .. handler .. "/url", url})
else
util:exception("Unable to handle url: " .. url)
end
end
Janosh:subscribe("showUrl", open)
while true do
Janosh:sleep(100000)
end
|
fix video host matching regex and add dailymotion support
|
fix video host matching regex and add dailymotion support
|
Lua
|
agpl-3.0
|
screeninvader/ScreenInvader,screeninvader/ScreenInvader
|
c34b494190e2c5cd537fddb05800248c6b9da02e
|
conf/rewrite_request.lua
|
conf/rewrite_request.lua
|
local inspect = require "inspect"
local plutils = require "pl.utils"
local stringx = require "pl.stringx"
local types = require "pl.types"
local utils = require "utils"
local deep_merge_overwrite_arrays = utils.deep_merge_overwrite_arrays
local is_empty = types.is_empty
local split = plutils.split
local strip = stringx.strip
local function pass_api_key(user, settings)
ngx.req.set_header("X-Api-Umbrella-Backend-Id", ngx.var.api_umbrella_backend_id)
-- DEPRECATED: We don't want to pass api keys to backends for security
-- reasons. Instead, we want to only pass the X-Api-User-Id for identifying
-- the user. But for legacy purposes, we still support passing api keys to
-- specific backends.
local pass_api_key_header = settings["pass_api_key_header"]
if pass_api_key_header and user then
-- Standardize how the api key is passed to backends, so backends only have
-- to check one place (the HTTP header).
ngx.req.set_header("X-Api-Key", user["api_key"])
else
ngx.req.clear_header("X-Api-Key")
end
-- DEPRECATED: We don't want to pass api keys to backends (see above).
-- Passing it via the query string is even worse, since it prevents
-- caching, but again, for legacy purposes, we support passing it this way
-- for specific backends.
local pass_api_key_query_param = settings["pass_api_key_query_param"]
local arg_api_key = ngx.ctx.arg_api_key
if pass_api_key_query_param and arg_api_key and user then
if arg_api_key ~= user["api_key"] then
local args = ngx.req.get_uri_args() or {}
args["api_key"] = user["api_key"]
ngx.req.set_uri_args(args)
end
elseif arg_api_key then
-- Strip the api key from the query string, so better HTTP caching can be
-- performed (so the URL won't vary for each user).
local args = ngx.req.get_uri_args() or {}
args["api_key"] = nil
ngx.req.set_uri_args(args)
end
-- Never pass along basic auth if it's how the api key was passed in
-- (otherwise, we don't want to touch the basic auth and pass along
-- whatever it contains)..
if user and ngx.ctx.remote_user == user["api_key"] then
ngx.req.clear_header("Authorization")
end
end
local function set_user_id_header(user)
if user then
ngx.req.set_header("X-Api-User-Id", user["id"])
else
ngx.req.clear_header("X-Api-User-Id")
end
end
local function set_roles_header(user)
if user and user["roles"] then
ngx.req.set_header("X-Api-Roles", table.concat(user["roles"], ","))
else
ngx.req.clear_header("X-Api-Roles")
end
end
local function append_query_string(settings)
if settings["_append_query_args"] then
local args = ngx.req.get_uri_args() or {}
deep_merge_overwrite_arrays(args, settings["_append_query_args"])
ngx.req.set_uri_args(args)
end
end
local function set_headers(settings)
if settings["headers"] then
for _, header in ipairs(settings["headers"]) do
ngx.req.set_header(header["key"], header["value"])
end
end
end
local function set_http_basic_auth(settings)
if settings["_http_basic_auth_header"] then
ngx.req.set_header("Authorization", settings["_http_basic_auth_header"])
end
end
local function strip_cookies(settings)
local cookie_header = ngx.var.http_cookie
if not cookie_header then return end
local strips = config["strip_cookies"]
if not strips then return end
local cookies = split(cookie_header, "; *")
local kept_cookies = {}
for _, cookie in ipairs(cookies) do
local cookie_name = string.match(cookie, "(.-)=")
local remove_cookie = false
if cookie_name then
cookie_name = strip(cookie_name)
for _, strip_regex in ipairs(strips) do
local matches, err = ngx.re.match(cookie_name, strip_regex, "io")
if matches then
remove_cookie = true
break
end
end
end
if not remove_cookie then
table.insert(kept_cookies, cookie)
end
end
if is_empty(kept_cookies) then
ngx.req.clear_header("Cookie")
else
ngx.req.set_header("Cookie", table.concat(kept_cookies, "; "))
end
end
return function(user, api, settings)
pass_api_key(user, settings)
set_user_id_header(user)
set_roles_header(user)
append_query_string(settings)
set_headers(settings)
set_http_basic_auth(settings)
strip_cookies(settings)
end
|
local inspect = require "inspect"
local plutils = require "pl.utils"
local stringx = require "pl.stringx"
local tablex = require "pl.tablex"
local types = require "pl.types"
local utils = require "utils"
local deep_merge_overwrite_arrays = utils.deep_merge_overwrite_arrays
local is_empty = types.is_empty
local keys = tablex.keys
local split = plutils.split
local strip = stringx.strip
local function pass_api_key(user, settings)
ngx.req.set_header("X-Api-Umbrella-Backend-Id", ngx.var.api_umbrella_backend_id)
-- DEPRECATED: We don't want to pass api keys to backends for security
-- reasons. Instead, we want to only pass the X-Api-User-Id for identifying
-- the user. But for legacy purposes, we still support passing api keys to
-- specific backends.
local pass_api_key_header = settings["pass_api_key_header"]
if pass_api_key_header and user then
-- Standardize how the api key is passed to backends, so backends only have
-- to check one place (the HTTP header).
ngx.req.set_header("X-Api-Key", user["api_key"])
else
ngx.req.clear_header("X-Api-Key")
end
-- DEPRECATED: We don't want to pass api keys to backends (see above).
-- Passing it via the query string is even worse, since it prevents
-- caching, but again, for legacy purposes, we support passing it this way
-- for specific backends.
local pass_api_key_query_param = settings["pass_api_key_query_param"]
local arg_api_key = ngx.ctx.arg_api_key
if pass_api_key_query_param and arg_api_key and user then
if arg_api_key ~= user["api_key"] then
local args = ngx.req.get_uri_args() or {}
args["api_key"] = user["api_key"]
ngx.req.set_uri_args(args)
end
elseif arg_api_key then
-- Strip the api key from the query string, so better HTTP caching can be
-- performed (so the URL won't vary for each user).
local args = ngx.req.get_uri_args() or {}
args["api_key"] = nil
ngx.req.set_uri_args(args)
end
-- Never pass along basic auth if it's how the api key was passed in
-- (otherwise, we don't want to touch the basic auth and pass along
-- whatever it contains)..
if user and ngx.ctx.remote_user == user["api_key"] then
ngx.req.clear_header("Authorization")
end
end
local function set_user_id_header(user)
if user then
ngx.req.set_header("X-Api-User-Id", user["id"])
else
ngx.req.clear_header("X-Api-User-Id")
end
end
local function set_roles_header(user)
if user and user["roles"] then
ngx.req.set_header("X-Api-Roles", table.concat(keys(user["roles"]), ","))
else
ngx.req.clear_header("X-Api-Roles")
end
end
local function append_query_string(settings)
if settings["_append_query_args"] then
local args = ngx.req.get_uri_args() or {}
deep_merge_overwrite_arrays(args, settings["_append_query_args"])
ngx.req.set_uri_args(args)
end
end
local function set_headers(settings)
if settings["headers"] then
for _, header in ipairs(settings["headers"]) do
ngx.req.set_header(header["key"], header["value"])
end
end
end
local function set_http_basic_auth(settings)
if settings["_http_basic_auth_header"] then
ngx.req.set_header("Authorization", settings["_http_basic_auth_header"])
end
end
local function strip_cookies(settings)
local cookie_header = ngx.var.http_cookie
if not cookie_header then return end
local strips = config["strip_cookies"]
if not strips then return end
local cookies = split(cookie_header, "; *")
local kept_cookies = {}
for _, cookie in ipairs(cookies) do
local cookie_name = string.match(cookie, "(.-)=")
local remove_cookie = false
if cookie_name then
cookie_name = strip(cookie_name)
for _, strip_regex in ipairs(strips) do
local matches, err = ngx.re.match(cookie_name, strip_regex, "io")
if matches then
remove_cookie = true
break
end
end
end
if not remove_cookie then
table.insert(kept_cookies, cookie)
end
end
if is_empty(kept_cookies) then
ngx.req.clear_header("Cookie")
else
ngx.req.set_header("Cookie", table.concat(kept_cookies, "; "))
end
end
return function(user, api, settings)
pass_api_key(user, settings)
set_user_id_header(user)
set_roles_header(user)
append_query_string(settings)
set_headers(settings)
set_http_basic_auth(settings)
strip_cookies(settings)
end
|
Fix setting the X-Api-Roles header.
|
Fix setting the X-Api-Roles header.
|
Lua
|
mit
|
apinf/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,NREL/api-umbrella
|
c58ab340e18f683e372d11af5db483a3d5826716
|
turbo/log.lua
|
turbo/log.lua
|
--[[ Turbo Log module
Copyright John Abrahamsen 2011, 2012, 2013 < [email protected] >
"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 util = require "turbo.util"
local ffi = require "ffi"
local log = {} -- log namespace.
log.stringify = function (t, name, indent)
local cart -- a container
local autoref -- for self references
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "__unnamed__"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
local buf = ffi.new("char[4096]") -- Buffer for log lines.
local time_t = ffi.new("time_t[1]")
--[[ Usefull table printer for debug. ]]
log.dump = function(stuff, description)
io.stdout:write(log.stringify(stuff, description) .. "\n")
end
log.success = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "\x1b[32m[S %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() > 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\x1b[37m\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stdout)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\x1b[37m\n")
end
end
--[[ Prints a notice to stdout. ]]
log.notice = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "[I %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stdout)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\n")
end
end
--[[ Prints a notice to stdout. ]]
log.debug = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "[D %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stderr)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\n")
end
end
--[[ Prints a error to stdout. ]]
log.error = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "\x1b[31m[E %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\x1b[37m\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stderr)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\x1b[37m\n")
end
end
--[[ Prints a warning to stdout. ]]
log.warning = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "\x1b[33m[W %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\x1b[37m\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stderr)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\x1b[37m\n")
end
end
--[[ Prints a error to stdout. ]]
log.stacktrace = function(str) io.stderr:write(str .. "\n") end
log.devel = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "\x1b[36m[d %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\x1b[37m\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stdout)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\x1b[37m\n")
end
end
return log
|
--[[ Turbo Log module
Copyright John Abrahamsen 2011, 2012, 2013 < [email protected] >
"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 util = require "turbo.util"
local ffi = require "ffi"
local log = {} -- log namespace.
log.stringify = function (t, name, indent)
local cart -- a container
local autoref -- for self references
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "__unnamed__"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
local buf = ffi.new("char[4096]") -- Buffer for log lines.
local time_t = ffi.new("time_t[1]")
--[[ Usefull table printer for debug. ]]
log.dump = function(stuff, description)
io.stdout:write(log.stringify(stuff, description) .. "\n")
end
log.success = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "\x1b[32m[S %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() > 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\x1b[37m\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stdout)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\x1b[37m\n")
end
end
--[[ Prints a notice to stdout. ]]
log.notice = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "[I %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stdout)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\n")
end
end
--[[ Prints a notice to stdout. ]]
log.debug = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "[D %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stderr)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\n")
end
end
--[[ Prints a error to stdout. ]]
log.error = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "\x1b[31m[E %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\x1b[37m\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stderr)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\x1b[37m\n")
end
end
--[[ Prints a warning to stdout. ]]
log.warning = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "\x1b[33m[W %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\x1b[37m\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stderr)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\x1b[37m\n")
end
end
--[[ Prints a error to stdout. ]]
log.stacktrace = function(str) io.stderr:write(str .. "\n") end
log.devel = function(str)
ffi.C.time(time_t)
local tm = ffi.C.localtime(time_t)
local sz = ffi.C.strftime(buf, 4096, "\x1b[36m[d %Y/%m/%d %H:%M:%S] ", tm)
local offset
if sz + str:len() < 4094 then
-- Use static buffer.
ffi.C.sprintf(buf + sz, "%s\x1b[37m\n", ffi.cast("const char*", str))
ffi.C.fputs(buf, io.stdout)
else
-- Use Lua string.
io.stdout:write(ffi.string(buf, sz) .. str .. "\x1b[37m\n")
end
end
return log
|
Fixed broken dump func.
|
Fixed broken dump func.
|
Lua
|
apache-2.0
|
ddysher/turbo,mniestroj/turbo,zcsteele/turbo,kernelsauce/turbo,zcsteele/turbo,YuanPeir-Chen/turbo-support-mipsel,luastoned/turbo,luastoned/turbo,YuanPeir-Chen/turbo-support-mipsel,ddysher/turbo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.