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
92949416a45e4d784e0df9723ec6b7cc7da9f7bc
mod_auth_dovecot/mod_auth_dovecot.lua
mod_auth_dovecot/mod_auth_dovecot.lua
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010 Javier Torres -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- local socket_unix = require "socket.unix"; local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_dovecot"); local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local base64 = require "util.encodings".base64; local pposix = require "util.pposix"; local prosody = _G.prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_default_provider(host) local provider = { name = "dovecot", c = nil }; log("debug", "initializing dovecot authentication provider for host '%s'", host); -- Closes the socket function provider.close(self) if (provider.c ~= nil) then provider.c:close(); end provider.c = nil; end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); provider.c = socket.unix(); -- Create a connection to dovecot socket local r, e = provider.c:connect(socket_path); if (not r) then log("warn", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, e); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); if not provider:send("VERSION\t1\t1\n") then return false end if (not provider:send("CPID\t" .. pid .. "\n")) then return false end -- Parse Dovecot's handshake local done = false; while (not done) do local l = provider:receive(); if (not l) then return false; end parts = string.gmatch(l, "[^\t]+"); first = parts(); if (first == "VERSION") then -- Version should be 1.1 local v1 = parts(); local v2 = parts(); if (not (v1 == "1" and v2 == "1")) then log("warn", "server version is not 1.1. it is %s.%s", v1, v2); provider:close(); return false; end elseif (first == "MECH") then -- Mechanisms should include PLAIN local ok = false; for p in parts do if p == "PLAIN" then ok = true; end end if (not ok) then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", l); provider:close(); return false; end elseif (first == "DONE") then done = true; end end return true; end -- Wrapper for send(). Handles errors function provider.send(self, data) local r, e = provider.c:send(data); if (not r) then log("warn", "error sending '%s' to dovecot. error was '%s'", data, e); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local r, e = provider.c:receive(); if (not r) then log("warn", "error receiving data from dovecot. error was '%s'", socket, e); provider:close(); return false; end return r; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local tries = 0; if (provider.c == nil or tries > 0) then if (not provider:connect()) then return nil, "Auth failed. Dovecot communications error"; end end -- Send auth data username = username .. "@" .. module.host; -- FIXME: this is actually a hack for my server local b64 = base64.encode(username .. "\0" .. username .. "\0" .. password); local id = "54321"; -- FIXME: probably can just be a fixed value if making one request per connection if (not provider:send("AUTH\t" .. id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64 .. "\n")) then return nil, "Auth failed. Dovecot communications error"; end -- Get response local l = provider:receive(); if (not l) then return nil, "Auth failed. Dovecot communications error"; end local parts = string.gmatch(l, "[^\t]+"); -- Check response if (parts() == "OK") then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Cannot get_password in dovecot backend."; end function provider.set_password(username, password) return nil, "Cannot set_password in dovecot backend."; end function provider.user_exists(username) --TODO: Send an auth request. If it returns FAIL <id> user=<user> then user exists. return nil, "user_exists not yet implemented in dovecot backend."; end function provider.create_user(username, password) return nil, "Cannot create_user in dovecot backend."; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local getpass_authentication_profile = { plain_test = function(username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, realm, password), true; end }; return new_sasl(realm, getpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_default_provider(module.host));
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010 Javier Torres -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- local socket_unix = require "socket.unix"; local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_dovecot"); local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local base64 = require "util.encodings".base64; local pposix = require "util.pposix"; local prosody = _G.prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_default_provider(host) local provider = { name = "dovecot", c = nil, request_id = 0 }; log("debug", "initializing dovecot authentication provider for host '%s'", host); -- Closes the socket function provider.close(self) if (provider.c ~= nil) then provider.c:close(); end provider.c = nil; end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); provider.c = socket.unix(); -- Create a connection to dovecot socket local r, e = provider.c:connect(socket_path); if (not r) then log("warn", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, e); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); if not provider:send("VERSION\t1\t1\n") then return false end if (not provider:send("CPID\t" .. pid .. "\n")) then return false end -- Parse Dovecot's handshake local done = false; while (not done) do local l = provider:receive(); if (not l) then return false; end parts = string.gmatch(l, "[^\t]+"); first = parts(); if (first == "VERSION") then -- Version should be 1.1 local v1 = parts(); local v2 = parts(); if (not (v1 == "1" and v2 == "1")) then log("warn", "server version is not 1.1. it is %s.%s", v1, v2); provider:close(); return false; end elseif (first == "MECH") then -- Mechanisms should include PLAIN local ok = false; for p in parts do if p == "PLAIN" then ok = true; end end if (not ok) then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", l); provider:close(); return false; end elseif (first == "DONE") then done = true; end end return true; end -- Wrapper for send(). Handles errors function provider.send(self, data) local r, e = provider.c:send(data); if (not r) then log("warn", "error sending '%s' to dovecot. error was '%s'", data, e); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local r, e = provider.c:receive(); if (not r) then log("warn", "error receiving data from dovecot. error was '%s'", socket, e); provider:close(); return false; end return r; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local tries = 0; if (provider.c == nil or tries > 0) then if (not provider:connect()) then return nil, "Auth failed. Dovecot communications error"; end end -- Send auth data username = username .. "@" .. module.host; -- FIXME: this is actually a hack for my server local b64 = base64.encode(username .. "\0" .. username .. "\0" .. password); provider.request_id = provider.request_id + 1 if (not provider:send("AUTH\t" .. provider.request_id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64 .. "\n")) then return nil, "Auth failed. Dovecot communications error"; end -- Get response local l = provider:receive(); if (not l) then return nil, "Auth failed. Dovecot communications error"; end local parts = string.gmatch(l, "[^\t]+"); -- Check response if (parts() == "OK") then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Cannot get_password in dovecot backend."; end function provider.set_password(username, password) return nil, "Cannot set_password in dovecot backend."; end function provider.user_exists(username) --TODO: Send an auth request. If it returns FAIL <id> user=<user> then user exists. return nil, "user_exists not yet implemented in dovecot backend."; end function provider.create_user(username, password) return nil, "Cannot create_user in dovecot backend."; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local getpass_authentication_profile = { plain_test = function(username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, realm, password), true; end }; return new_sasl(realm, getpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_default_provider(module.host));
mod_auth_dovecot: Use sequential (instead of fixed) id for messages
mod_auth_dovecot: Use sequential (instead of fixed) id for messages
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
718861d80c197980fc600502e371b7e025c1362a
mods/builtin_item/init.lua
mods/builtin_item/init.lua
minetest.register_entity(":__builtin:item", { initial_properties = { hp_max = 1, physical = true, collisionbox = {-0.175, -0.175, -0.175, 0.175, 0.175, 0.175}, collide_with_objects = false, visual = "sprite", visual_size = {x=0.5, y=0.5}, textures = {""}, spritediv = {x=1, y=1}, initial_sprite_basepos = {x=0, y=0}, is_visible = false, timer = 0, }, itemstring = "", physical_state = true, set_item = function(self, itemstring) self.itemstring = itemstring local stack = ItemStack(itemstring) local itemtable = stack:to_table() local itemname = nil if itemtable then itemname = stack:to_table().name end local item_texture = nil local item_type = "" if minetest.registered_items[itemname] then item_texture = minetest.registered_items[itemname].inventory_image item_type = minetest.registered_items[itemname].type end local prop = { is_visible = true, visual = "sprite", textures = {"unknown_item.png"} } if item_texture and item_texture ~= "" then prop.visual = "wielditem" prop.textures = {itemname} prop.visual_size = {x=0.25, y=0.25} else prop.visual = "wielditem" prop.textures = {itemname} prop.visual_size = {x=0.25, y=0.25} prop.automatic_rotate = math.pi * 0.5 end self.object:set_properties(prop) end, get_staticdata = function(self) --return self.itemstring return minetest.serialize({ itemstring = self.itemstring, always_collect = self.always_collect, timer = self.timer, }) end, on_activate = function(self, staticdata, dtime_s) if string.sub(staticdata, 1, string.len("return")) == "return" then local data = minetest.deserialize(staticdata) if data and type(data) == "table" then self.itemstring = data.itemstring self.always_collect = data.always_collect self.timer = data.timer if not self.timer then self.timer = 0 end self.timer = self.timer+dtime_s end else self.itemstring = staticdata end self.object:set_armor_groups({immortal=1}) self.object:setvelocity({x=0, y=2, z=0}) self.object:setacceleration({x=0, y=-10, z=0}) self:set_item(self.itemstring) end, on_step = function(self, dtime) local time = tonumber(minetest.setting_get("remove_items")) if not time then time = 600 end if not self.timer then self.timer = 0 end self.timer = self.timer + dtime if time ~= 0 and (self.timer > time) then self.object:remove() end local p = self.object:getpos() local name = minetest.get_node(p).name if (minetest.registered_nodes[name] and minetest.registered_nodes[name].damage_per_second > 0) or name == "maptools:igniter" then minetest.sound_play("builtin_item_lava", {pos = self.object:getpos(), gain = 0.5}) self.object:remove() return end --[[ if name == "default:water_source" then self.object:setacceleration({x = 0, y = 4, z = 0}) else self.object:setacceleration({x = 0, y = -10, z = 0}) end --]] if minetest.registered_nodes[name].liquidtype == "flowing" then local get_flowing_dir = function(self) local pos = self.object:getpos() local param2 = minetest.get_node(pos).param2 for i,d in ipairs({-1, 1, -1, 1}) do if i<3 then pos.x = pos.x+d else pos.z = pos.z+d end local name = minetest.get_node(pos).name local par2 = minetest.get_node(pos).param2 if name == "default:water_flowing" and par2 < param2 then return pos end if i<3 then pos.x = pos.x-d else pos.z = pos.z-d end end end local vec = get_flowing_dir(self) if vec then local v = self.object:getvelocity() if vec and vec.x-p.x > 0 then self.object:setacceleration({x = 0, y = 0, z = 0}) self.object:setvelocity({x = 1, y = -0.22, z = 0}) elseif vec and vec.x-p.x < 0 then self.object:setacceleration({x = 0, y = 0, z = 0}) self.object:setvelocity({x = -1, y = -0.22, z = 0}) elseif vec and vec.z-p.z > 0 then self.object:setacceleration({x = 0, y = 0, z = 0}) self.object:setvelocity({x = 0, y = -0.22, z = 1}) elseif vec and vec.z-p.z < 0 then self.object:setacceleration({x = 0, y = 0, z = 0}) self.object:setvelocity({x = 0, y = -0.22, z = -1}) end self.object:setacceleration({x = 0, y = -10, z = 0}) self.physical_state = true self.object:set_properties({ physical = true }) return end end p.y = p.y - 0.3 local nn = minetest.get_node(p).name -- If node is not registered or node is walkably solid. if not minetest.registered_nodes[nn] or minetest.registered_nodes[nn].walkable then if self.physical_state then self.object:setvelocity({x=0,y=0,z=0}) self.object:setacceleration({x=0, y=0, z=0}) self.physical_state = false self.object:set_properties({ physical = false }) end else if not self.physical_state then self.object:setvelocity({x=0,y=0,z=0}) self.object:setacceleration({x=0, y=-10, z=0}) self.physical_state = true self.object:set_properties({ physical = true }) end end end, --[[ This causes a duplication glitch if a player walks upon an item and clicks on it at the same time. on_punch = function(self, hitter) if self.itemstring ~= "" then local left = hitter:get_inventory():add_item("main", self.itemstring) if not left:is_empty() then self.itemstring = left:to_string() return end end self.object:remove() end, --]] }) if minetest.setting_get("log_mods") then minetest.log("action", "[builtin_item] loaded.") end
minetest.register_entity(":__builtin:item", { initial_properties = { hp_max = 1, physical = true, collisionbox = {-0.175, -0.175, -0.175, 0.175, 0.175, 0.175}, collide_with_objects = false, visual = "sprite", visual_size = {x=0.5, y=0.5}, textures = {""}, spritediv = {x=1, y=1}, initial_sprite_basepos = {x=0, y=0}, is_visible = false, timer = 0, }, itemstring = "", physical_state = true, set_item = function(self, itemstring) self.itemstring = itemstring local stack = ItemStack(itemstring) local itemtable = stack:to_table() local itemname = nil if itemtable then itemname = stack:to_table().name end local item_texture = nil local item_type = "" if minetest.registered_items[itemname] then item_texture = minetest.registered_items[itemname].inventory_image item_type = minetest.registered_items[itemname].type end local prop = { is_visible = true, visual = "sprite", textures = {"unknown_item.png"} } if item_texture and item_texture ~= "" then prop.visual = "wielditem" prop.textures = {itemname} prop.visual_size = {x=0.25, y=0.25} else prop.visual = "wielditem" prop.textures = {itemname} prop.visual_size = {x=0.25, y=0.25} prop.automatic_rotate = math.pi * 0.5 end self.object:set_properties(prop) end, get_staticdata = function(self) --return self.itemstring return minetest.serialize({ itemstring = self.itemstring, always_collect = self.always_collect, timer = self.timer, }) end, on_activate = function(self, staticdata, dtime_s) if string.sub(staticdata, 1, string.len("return")) == "return" then local data = minetest.deserialize(staticdata) if data and type(data) == "table" then self.itemstring = data.itemstring self.always_collect = data.always_collect self.timer = data.timer if not self.timer then self.timer = 0 end self.timer = self.timer+dtime_s end else self.itemstring = staticdata end self.object:set_armor_groups({immortal=1}) self.object:setvelocity({x=0, y=2, z=0}) self.object:setacceleration({x=0, y=-10, z=0}) self:set_item(self.itemstring) end, on_step = function(self, dtime) local time = tonumber(minetest.setting_get("remove_items")) if not time then time = 600 end if not self.timer then self.timer = 0 end self.timer = self.timer + dtime if time ~= 0 and (self.timer > time) then self.object:remove() end local p = self.object:getpos() local name = minetest.get_node(p).name if (minetest.registered_nodes[name] and minetest.registered_nodes[name].damage_per_second > 0) or name == "maptools:igniter" then minetest.sound_play("builtin_item_lava", {pos = self.object:getpos(), gain = 0.5}) self.object:remove() return end --[[ if name == "default:water_source" then self.object:setacceleration({x = 0, y = 4, z = 0}) else self.object:setacceleration({x = 0, y = -10, z = 0}) end --]] if not minetest.registered_nodes[name] then return end if minetest.registered_nodes[name].liquidtype == "flowing" then local get_flowing_dir = function(self) local pos = self.object:getpos() local param2 = minetest.get_node(pos).param2 for i,d in ipairs({-1, 1, -1, 1}) do if i<3 then pos.x = pos.x+d else pos.z = pos.z+d end local name = minetest.get_node(pos).name local par2 = minetest.get_node(pos).param2 if name == "default:water_flowing" and par2 < param2 then return pos end if i<3 then pos.x = pos.x-d else pos.z = pos.z-d end end end local vec = get_flowing_dir(self) if vec then local v = self.object:getvelocity() if vec and vec.x-p.x > 0 then self.object:setacceleration({x = 0, y = 0, z = 0}) self.object:setvelocity({x = 1, y = -0.22, z = 0}) elseif vec and vec.x-p.x < 0 then self.object:setacceleration({x = 0, y = 0, z = 0}) self.object:setvelocity({x = -1, y = -0.22, z = 0}) elseif vec and vec.z-p.z > 0 then self.object:setacceleration({x = 0, y = 0, z = 0}) self.object:setvelocity({x = 0, y = -0.22, z = 1}) elseif vec and vec.z-p.z < 0 then self.object:setacceleration({x = 0, y = 0, z = 0}) self.object:setvelocity({x = 0, y = -0.22, z = -1}) end self.object:setacceleration({x = 0, y = -10, z = 0}) self.physical_state = true self.object:set_properties({ physical = true }) return end end p.y = p.y - 0.3 local nn = minetest.get_node(p).name -- If node is not registered or node is walkably solid. if not minetest.registered_nodes[nn] or minetest.registered_nodes[nn].walkable then if self.physical_state then self.object:setvelocity({x=0,y=0,z=0}) self.object:setacceleration({x=0, y=0, z=0}) self.physical_state = false self.object:set_properties({ physical = false }) end else if not self.physical_state then self.object:setvelocity({x=0,y=0,z=0}) self.object:setacceleration({x=0, y=-10, z=0}) self.physical_state = true self.object:set_properties({ physical = true }) end end end, --[[ This causes a duplication glitch if a player walks upon an item and clicks on it at the same time. on_punch = function(self, hitter) if self.itemstring ~= "" then local left = hitter:get_inventory():add_item("main", self.itemstring) if not left:is_empty() then self.itemstring = left:to_string() return end end self.object:remove() end, --]] }) if minetest.setting_get("log_mods") then minetest.log("action", "[builtin_item] loaded.") end
Fixed all unknown's use in builtin with a check then return
Fixed all unknown's use in builtin with a check then return
Lua
unlicense
Coethium/server-minetestforfun,paly2/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
89ba9a8391c429a3891003265f0e55de1db08358
Modules/Localization/ClientTranslator.lua
Modules/Localization/ClientTranslator.lua
--- Gets local translator for player -- @module ClientTranslator local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local LocalizationService = game:GetService("LocalizationService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Players = game:GetService("Players") local RunService = game:GetService("RunService") local JsonToLocalizationTable = require("JsonToLocalizationTable") local PseudoLocalize = require("PseudoLocalize") local Promise = require("Promise") assert(RunService:IsClient(), "ClientTranslator can only be required on client") local ClientTranslatorFacade = {} --- Initializes a new instance of the ClientTranslatorFacade -- Must be called before usage function ClientTranslatorFacade:Init() local localizationTable = JsonToLocalizationTable.loadFolder(ReplicatedStorage:WaitForChild("i18n")) localizationTable.Name = "JSONTranslationTable" localizationTable.Parent = LocalizationService if RunService:IsStudio() then PseudoLocalize.addToLocalizationTable(localizationTable, "qlp-pls", "en") end self._englishTranslator = localizationTable:GetTranslator("en") local asyncTranslatorPromise = Promise.new(function(resolve, reject) local translator = nil local ok, err = pcall(function() translator = LocalizationService:GetTranslatorForPlayerAsync(Players.LocalPlayer) end) if not ok then reject(err or "Failed to GetTranslatorForPlayerAsync") return end if translator then resolve(translator) return end reject("Translator was not returned") return end) -- Give longer in non-studio mode local timeout = 20 if RunService:IsStudio() then timeout = 0.5 end delay(timeout, function() if not asyncTranslatorPromise:IsPending() then return end warn(("[ERR][ClientTranslatorFacade] - GetTranslatorForPlayerAsync is still pending after %f, using local table") :format(timeout)) local translator = LocalizationService:GetTranslatorForPlayer(Players.LocalPlayer) asyncTranslatorPromise:Fulfill(translator) end) self._clientTranslator = asyncTranslatorPromise:Wait() assert(self._clientTranslator) print("Done loading") return self end --- @{inheritDoc} function ClientTranslatorFacade:FormatByKey(key, ...) assert(self._clientTranslator) assert(type(key) == "string", "Key must be a string") local data = {...} local result local ok, err = pcall(function() result = self._clientTranslator:FormatByKey(key, unpack(data)) end) if ok and not err then return result end if err then warn(err) else warn("Failed to localize '" .. key .. "'") end -- Fallback to English if self._clientTranslator.LocaleId ~= self._englishTranslator.LocaleId then -- Ignore results as we know this may error ok, err = pcall(function() result = self._englishTranslator:FormatByKey(key, unpack(data)) end) if ok and not err then return result end end return key end return ClientTranslatorFacade
--- Gets local translator for player -- @module ClientTranslator local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local LocalizationService = game:GetService("LocalizationService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Players = game:GetService("Players") local RunService = game:GetService("RunService") local JsonToLocalizationTable = require("JsonToLocalizationTable") local PseudoLocalize = require("PseudoLocalize") local Promise = require("Promise") assert(RunService:IsClient(), "ClientTranslator can only be required on client") local ClientTranslatorFacade = {} --- Initializes a new instance of the ClientTranslatorFacade -- Must be called before usage function ClientTranslatorFacade:Init() local localizationTable = JsonToLocalizationTable.loadFolder(ReplicatedStorage:WaitForChild("i18n")) localizationTable.Name = "JSONTranslationTable" localizationTable.Parent = LocalizationService if RunService:IsStudio() then PseudoLocalize.addToLocalizationTable(localizationTable, "qlp-pls", "en") end self._englishTranslator = localizationTable:GetTranslator("en") local asyncTranslatorPromise = Promise.new(function(resolve, reject) local translator = nil local ok, err = pcall(function() translator = LocalizationService:GetTranslatorForPlayerAsync(Players.LocalPlayer) end) if not ok then reject(err or "Failed to GetTranslatorForPlayerAsync") return end if translator then assert(typeof(translator) == "Instance") resolve(translator) return end reject("Translator was not returned") return end) -- Give longer in non-studio mode local timeout = 20 if RunService:IsStudio() then timeout = 0.5 end delay(timeout, function() if not asyncTranslatorPromise:IsPending() then return end asyncTranslatorPromise:Reject( ("GetTranslatorForPlayerAsync is still pending after %f, using local table") :format(timeout)) end) local finalPromise = asyncTranslatorPromise:Catch(function(err) warn(("[ERR][ClientTranslatorFacade] - %s"):format(tostring(err))) local translator = LocalizationService:GetTranslatorForPlayer(Players.LocalPlayer) return translator end) self._clientTranslator = finalPromise:Wait() assert(typeof(self._clientTranslator) == "Instance") return self end --- @{inheritDoc} function ClientTranslatorFacade:FormatByKey(key, ...) assert(self._clientTranslator, "ClientTranslator is not initialized") assert(type(key) == "string", "Key must be a string") local data = {...} local result local ok, err = pcall(function() result = self._clientTranslator:FormatByKey(key, unpack(data)) end) if ok and not err then return result end if err then warn(err) else warn("Failed to localize '" .. key .. "'") end -- Fallback to English if self._clientTranslator.LocaleId ~= self._englishTranslator.LocaleId then -- Ignore results as we know this may error ok, err = pcall(function() result = self._englishTranslator:FormatByKey(key, unpack(data)) end) if ok and not err then return result end end return key end return ClientTranslatorFacade
Fix translator not loading on instant return
Fix translator not loading on instant return
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
a63d7633d12cd65e0947774c02cf81ecf9d2b8e1
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ipaddr, adv_interface, adv_subnet local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network")) adv_interface.widget = "checkbox" adv_interface.exclude = arg[1] adv_interface.default = "lan" adv_interface.template = "cbi/network_netlist" adv_interface.nocreate = true adv_interface.nobridges = true adv_interface.novirtual = true adv_subnet = section:taboption("general", Value, "adv_subnet", translate("Advertised network ID"), translate("Allowed range is 1 to 65535")) adv_subnet.placeholder = "1" adv_subnet.datatype = "range(1,65535)" function adv_subnet.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v and tonumber(v, 16) end function adv_subnet .write(self, section, value) value = tonumber(value) or 1 if value > 65535 then value = 65535 elseif value < 1 then value = 1 end Value.write(self, section, "%X" % value) end adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime", translate("Use valid lifetime"), translate("Specifies the advertised valid prefix lifetime in seconds")) adv_valid_lifetime.placeholder = "300" adv_valid_lifetime.datatype = "uinteger" adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime", translate("Use preferred lifetime"), translate("Specifies the advertised preferred prefix lifetime in seconds")) adv_preferred_lifetime.placeholder = "120" adv_preferred_lifetime.datatype = "uinteger" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(1500)"
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ipaddr, adv_interface, adv_subnet local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network")) adv_interface.widget = "checkbox" adv_interface.exclude = arg[1] adv_interface.default = "lan" adv_interface.template = "cbi/network_netlist" adv_interface.nocreate = true adv_interface.nobridges = true adv_interface.novirtual = true function adv_interface.remove(self, section) self:write(section, " ") end adv_subnet = section:taboption("general", Value, "adv_subnet", translate("Advertised network ID"), translate("Allowed range is 1 to 65535")) adv_subnet.placeholder = "1" adv_subnet.datatype = "range(1,65535)" function adv_subnet.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v and tonumber(v, 16) end function adv_subnet .write(self, section, value) value = tonumber(value) or 1 if value > 65535 then value = 65535 elseif value < 1 then value = 1 end Value.write(self, section, "%X" % value) end adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime", translate("Use valid lifetime"), translate("Specifies the advertised valid prefix lifetime in seconds")) adv_valid_lifetime.placeholder = "300" adv_valid_lifetime.datatype = "uinteger" adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime", translate("Use preferred lifetime"), translate("Specifies the advertised preferred prefix lifetime in seconds")) adv_preferred_lifetime.placeholder = "120" adv_preferred_lifetime.datatype = "uinteger" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(1500)"
protocols/6x4: fix turning off 6ro4 advertising on all interfaces
protocols/6x4: fix turning off 6ro4 advertising on all interfaces git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8135 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
Flexibity/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,stephank/luci,8devices/carambola2-luci,vhpham80/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,Flexibity/luci,vhpham80/luci,Canaan-Creative/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,Flexibity/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,8devices/carambola2-luci,Flexibity/luci,jschmidlapp/luci,ch3n2k/luci,8devices/carambola2-luci,ch3n2k/luci,8devices/carambola2-luci,gwlim/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,ch3n2k/luci,gwlim/luci,freifunk-gluon/luci,ch3n2k/luci,Canaan-Creative/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,phi-psi/luci,saraedum/luci-packages-old,vhpham80/luci,gwlim/luci,phi-psi/luci,freifunk-gluon/luci,freifunk-gluon/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,Flexibity/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,vhpham80/luci,ch3n2k/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,saraedum/luci-packages-old,gwlim/luci,Flexibity/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,phi-psi/luci,freifunk-gluon/luci,phi-psi/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,jschmidlapp/luci,jschmidlapp/luci,phi-psi/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,stephank/luci,Canaan-Creative/luci,phi-psi/luci,Canaan-Creative/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,stephank/luci,ch3n2k/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,8devices/carambola2-luci,stephank/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,Flexibity/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci
76129e47ff9acc33888cfe1a2999cd45db6ba26a
nyagos.d/catalog/git.lua
nyagos.d/catalog/git.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share.git = {} -- setup local branch listup local branchlist = function() local gitbranches = {} local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul') for line in gitbranch_tmp:gmatch('[^\n]+') do table.insert(gitbranches,line) end return gitbranches end --setup current branch string local currentbranch = function() return nyagos.eval('git rev-parse --abbrev-ref HEAD 2> nul') end -- subcommands local gitsubcommands={} -- keyword gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"} gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"} gitsubcommands["reflog"]={"show", "delete", "expire"} gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"} gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"} gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"} gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"} gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"} -- branch gitsubcommands["checkout"]=branchlist gitsubcommands["reset"]=branchlist gitsubcommands["merge"]=branchlist gitsubcommands["rebase"]=branchlist local gitvar=share.git gitvar.subcommand=gitsubcommands gitvar.branch=branchlist gitvar.currentbranch=currentbranch share.git=gitvar if share.maincmds then if share.maincmds["git"] then -- git command complementation exists. local maincmds = share.maincmds -- build for key, cmds in pairs(gitsubcommands) do local gitcommand="git "..key maincmds[gitcommand]=cmds end -- replace share.maincmds = maincmds end end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share.git = {} -- setup local branch listup local branchlist = function() local gitbranches = {} local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul') for line in gitbranch_tmp:gmatch('[^\n]+') do table.insert(gitbranches,line) end return gitbranches end --setup current branch string local currentbranch = function() return nyagos.eval('git rev-parse --abbrev-ref HEAD 2> nul') end -- subcommands local gitsubcommands={} -- keyword gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"} gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"} gitsubcommands["reflog"]={"show", "delete", "expire"} gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"} gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"} gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"} gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"} gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"} -- branch gitsubcommands["checkout"]=branchlist gitsubcommands["reset"]=branchlist gitsubcommands["merge"]=branchlist gitsubcommands["rebase"]=branchlist local gitvar=share.git gitvar.subcommand=gitsubcommands gitvar.branch=branchlist gitvar.currentbranch=currentbranch share.git=gitvar if share.maincmds then if share.maincmds["git"] then -- git command complementation exists. local maincmds = share.maincmds -- build for key, cmds in pairs(gitsubcommands) do local gitcommand="git "..key maincmds[gitcommand]=cmds end -- replace share.maincmds = maincmds end end -- EOF
Fix git.lua lf to crlf and small style treat
Fix git.lua lf to crlf and small style treat
Lua
bsd-3-clause
zetamatta/nyagos,nocd5/nyagos,tsuyoshicho/nyagos
fb4ffa06d9c6ff2f26383e23fb03c50e9a18d163
agents/monitoring/tests/net/init.lua
agents/monitoring/tests/net/init.lua
local table = require('table') local async = require('async') local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream local misc = require('monitoring/default/util/misc') local helper = require('../helper') local timer = require('timer') local fixtures = require('../fixtures') local constants = require('constants') local consts = require('../../default/util/constants') local Endpoint = require('../../default/endpoint').Endpoint local path = require('path') local exports = {} local child function counterTrigger(trigger, callback) local counter = 0 return function() counter = counter + 1 if counter == trigger then callback() end end end exports['test_reconnects'] = function(test, asserts) local options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } local client = ConnectionStream:new('id', 'token', 'guid', options) local clientEnd = 0 local reconnect = 0 client:on('client_end', function(err) clientEnd = clientEnd + 1 end) client:on('reconnect', function(err) reconnect = reconnect + 1 end) async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', counterTrigger(3, callback)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', counterTrigger(3, callback)) end) end, }, function() helper.stop_server(child) asserts.ok(clientEnd > 0) asserts.ok(reconnect > 0) test.done() end) end exports['test_upgrades'] = function(test, asserts) local options, client, endpoints -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } endpoints = get_endpoints() async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client = ConnectionStream:new('id', 'token', 'guid', options) client:on('handshake_success', misc.nCallbacks(callback, 3)) client:createConnections(endpoints, function() end) end, function(callback) callback = misc.nCallbacks(callback, 4) client:on('binary_upgrade.found', callback) client:on('bundle_upgrade.found', callback) client:on('bundle_upgrade.error', callback) client:on('binary_upgrade.error', callback) client:getUpgrade():forceUpgradeCheck() end }, function() helper.stop_server(child) client:done() test.done() end) end return exports
local table = require('table') local async = require('async') local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream local misc = require('monitoring/default/util/misc') local helper = require('../helper') local timer = require('timer') local fixtures = require('../fixtures') local constants = require('constants') local consts = require('../../default/util/constants') local Endpoint = require('../../default/endpoint').Endpoint local path = require('path') local exports = {} local child exports['test_reconnects'] = function(test, asserts) local options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } local client = ConnectionStream:new('id', 'token', 'guid', options) local clientEnd = 0 local reconnect = 0 client:on('client_end', function(err) clientEnd = clientEnd + 1 end) client:on('reconnect', function(err) reconnect = reconnect + 1 end) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', misc.nCallbacks(callback, 3)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', misc.nCallbacks(callback, 3)) end) end, }, function() helper.stop_server(child) asserts.ok(clientEnd > 0) asserts.ok(reconnect > 0) test.done() end) end exports['test_upgrades'] = function(test, asserts) local options, client, endpoints -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client = ConnectionStream:new('id', 'token', 'guid', options) client:on('handshake_success', misc.nCallbacks(callback, 3)) client:createConnections(endpoints, function() end) end, function(callback) callback = misc.nCallbacks(callback, 4) client:on('binary_upgrade.found', callback) client:on('bundle_upgrade.found', callback) client:on('bundle_upgrade.error', callback) client:on('binary_upgrade.error', callback) client:getUpgrade():forceUpgradeCheck() end }, function() helper.stop_server(child) client:done() test.done() end) end return exports
fixes
fixes
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
3010a2deadb740c3e4990aa9f2d9e13a709a1c99
core/componentmanager.lua
core/componentmanager.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local prosody = prosody; local log = require "util.logger".init("componentmanager"); local configmanager = require "core.configmanager"; local modulemanager = require "core.modulemanager"; local jid_split = require "util.jid".split; local fire_event = require "core.eventmanager".fire_event; local events_new = require "util.events".new; local st = require "util.stanza"; local hosts = hosts; local pairs, type, tostring = pairs, type, tostring; local components = {}; local disco_items = require "util.multitable".new(); local NULL = {}; module "componentmanager" local function default_component_handler(origin, stanza) log("warn", "Stanza being handled by default component, bouncing error"); if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then origin.send(st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable")); end end function load_enabled_components(config) local defined_hosts = config or configmanager.getconfig(); for host, host_config in pairs(defined_hosts) do if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then hosts[host] = create_component(host); hosts[host].connected = false; components[host] = default_component_handler; local ok, err = modulemanager.load(host, host_config.core.component_module); if not ok then log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err)); else fire_event("component-activated", host, host_config); log("debug", "Activated %s component: %s", host_config.core.component_module, host); end end end end prosody.events.add_handler("server-starting", load_enabled_components); function handle_stanza(origin, stanza) local node, host = jid_split(stanza.attr.to); local component = nil; if host then if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server if not component then component = components[host]; end end if component then log("debug", "%s stanza being handled by component: %s", stanza.name, host); component(origin, stanza, hosts[host]); else log("error", "Component manager recieved a stanza for a non-existing component: "..tostring(stanza)); end end function create_component(host, component, events) -- TODO check for host well-formedness local ssl_ctx; if host then -- We need to find SSL context to use... -- Discussion in prosody@ concluded that -- 1 level back is usually enough by default local base_host = host:gsub("^[^%.]+%.", ""); if hosts[base_host] then ssl_ctx = hosts[base_host].ssl_ctx; end end return { type = "component", host = host, connected = true, s2sout = {}, ssl_ctx = ssl_ctx, events = events or events_new() }; end function register_component(host, component, session) if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then local old_events = hosts[host] and hosts[host].events; components[host] = component; hosts[host] = session or create_component(host, component, old_events); -- Add events object if not already one if not hosts[host].events then hosts[host].events = old_events or events_new(); end -- add to disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:set(host:sub(host:find(".", 1, true)+1), host, true); end -- FIXME only load for a.b.c if b.c has dialback, and/or check in config modulemanager.load(host, "dialback"); log("debug", "component added: "..host); return session or hosts[host]; else log("error", "Attempt to set component for existing host: "..host); end end function deregister_component(host) if components[host] then modulemanager.unload(host, "dialback"); hosts[host].connected = nil; local host_config = configmanager.getconfig()[host]; if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then -- Set default handler components[host] = default_component_handler; else -- Component not in config, or disabled, remove hosts[host] = nil; components[host] = nil; end -- remove from disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:remove(host:sub(host:find(".", 1, true)+1), host); end log("debug", "component removed: "..host); return true; else log("error", "Attempt to remove component for non-existing host: "..host); end end function set_component_handler(host, handler) components[host] = handler; end function get_children(host) return disco_items:get(host) or NULL; end return _M;
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local prosody = prosody; local log = require "util.logger".init("componentmanager"); local configmanager = require "core.configmanager"; local modulemanager = require "core.modulemanager"; local jid_split = require "util.jid".split; local fire_event = require "core.eventmanager".fire_event; local events_new = require "util.events".new; local st = require "util.stanza"; local hosts = hosts; local pairs, type, tostring = pairs, type, tostring; local components = {}; local disco_items = require "util.multitable".new(); local NULL = {}; module "componentmanager" local function default_component_handler(origin, stanza) log("warn", "Stanza being handled by default component, bouncing error"); if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then origin.send(st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable")); end end function load_enabled_components(config) local defined_hosts = config or configmanager.getconfig(); for host, host_config in pairs(defined_hosts) do if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then hosts[host] = create_component(host); hosts[host].connected = false; components[host] = default_component_handler; local ok, err = modulemanager.load(host, host_config.core.component_module); if not ok then log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err)); else fire_event("component-activated", host, host_config); log("debug", "Activated %s component: %s", host_config.core.component_module, host); end end end end prosody.events.add_handler("server-starting", load_enabled_components); function handle_stanza(origin, stanza) local node, host = jid_split(stanza.attr.to); local component = nil; if host then if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server if not component then component = components[host]; end end if component then log("debug", "%s stanza being handled by component: %s", stanza.name, host); component(origin, stanza, hosts[host]); else log("error", "Component manager recieved a stanza for a non-existing component: "..tostring(stanza)); end end function create_component(host, component, events) -- TODO check for host well-formedness local ssl_ctx; if host then -- We need to find SSL context to use... -- Discussion in prosody@ concluded that -- 1 level back is usually enough by default local base_host = host:gsub("^[^%.]+%.", ""); if hosts[base_host] then ssl_ctx = hosts[base_host].ssl_ctx; end end return { type = "component", host = host, connected = true, s2sout = {}, ssl_ctx = ssl_ctx, events = events or events_new() }; end function register_component(host, component, session) if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then local old_events = hosts[host] and hosts[host].events; components[host] = component; hosts[host] = session or create_component(host, component, old_events); -- Add events object if not already one if not hosts[host].events then hosts[host].events = old_events or events_new(); end -- add to disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:set(host:sub(host:find(".", 1, true)+1), host, true); end modulemanager.load(host, "dialback"); log("debug", "component added: "..host); return session or hosts[host]; else log("error", "Attempt to set component for existing host: "..host); end end function deregister_component(host) if components[host] then modulemanager.unload(host, "dialback"); hosts[host].connected = nil; local host_config = configmanager.getconfig()[host]; if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then -- Set default handler components[host] = default_component_handler; else -- Component not in config, or disabled, remove hosts[host] = nil; components[host] = nil; end -- remove from disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:remove(host:sub(host:find(".", 1, true)+1), host); end log("debug", "component removed: "..host); return true; else log("error", "Attempt to remove component for non-existing host: "..host); end end function set_component_handler(host, handler) components[host] = handler; end function get_children(host) return disco_items:get(host) or NULL; end return _M;
componentmanager: Remove FIXME
componentmanager: Remove FIXME
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
c28d97394101a193cbed7c0b01378831b60194e6
frontend/device/pocketbook/device.lua
frontend/device/pocketbook/device.lua
local Generic = require("device/generic/device") -- <= look at this file! local DEBUG = require("dbg") local function yes() return true end local PocketBook = Generic:new{ -- both the following are just for testing similar behaviour -- see ffi/framebuffer_mxcfb.lua model = "KindlePaperWhite", isKindle = yes, isTouchDevice = yes, display_dpi = 212, touch_dev = "/dev/input/event0", } function PocketBook:init() -- this example uses the mxcfb framebuffer driver: self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = DEBUG} -- we inject an input hook for debugging purposes. You probably don't want -- it after everything is implemented. self.input:registerEventAdjustHook(function(event) DEBUG("got event:", event) end) -- no backlight management yet self.input.open("/dev/input/event0") self.input.open("/dev/input/event1") self.input.open("/dev/input/event2") self.input.open("/dev/input/event3") Generic.init(self) end -- maybe additional implementations are needed for other models, -- testing on PocketBook Lux 2 for now. return PocketBook
local Generic = require("device/generic/device") -- <= look at this file! local DEBUG = require("dbg") local function yes() return true end local PocketBook = Generic:new{ -- both the following are just for testing similar behaviour -- see ffi/framebuffer_mxcfb.lua model = "KindlePaperWhite", isKindle = yes, isTouchDevice = yes, display_dpi = 212, touch_dev = "/dev/input/event0", } function PocketBook:init() -- this example uses the mxcfb framebuffer driver: self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = DEBUG} self.input = require("device/input"):new{device = self} -- we inject an input hook for debugging purposes. You probably don't want -- it after everything is implemented. self.input:registerEventAdjustHook(function(event) DEBUG("got event:", event) end) -- no backlight management yet self.input.open("/dev/input/event0") self.input.open("/dev/input/event1") self.input.open("/dev/input/event2") self.input.open("/dev/input/event3") Generic.init(self) end -- maybe additional implementations are needed for other models, -- testing on PocketBook Lux 2 for now. return PocketBook
fix: load input driver before configuring it
fix: load input driver before configuring it
Lua
agpl-3.0
Hzj-jie/koreader,koreader/koreader,chihyang/koreader,NiLuJe/koreader,poire-z/koreader,noname007/koreader,poire-z/koreader,ashang/koreader,frankyifei/koreader,apletnev/koreader,lgeek/koreader,mwoz123/koreader,Frenzie/koreader,houqp/koreader,chrox/koreader,NickSavage/koreader,robert00s/koreader,pazos/koreader,Markismus/koreader,ashhher3/koreader,NiLuJe/koreader,Frenzie/koreader,koreader/koreader,mihailim/koreader
a66cc99708aabdaa0e3c963e36dc7af850e40832
dmc_lua/lua_states_mix.lua
dmc_lua/lua_states_mix.lua
--====================================================================-- -- dmc_lua/lua_states_mix.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2013-2015 David McCuskey. All Rights Reserved. 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. --]] --====================================================================-- --== DMC Lua Library : Lua States Mixin --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "1.3.1" --====================================================================-- --== Setup, Constants local States --====================================================================-- --== Support Functions -- create general output string function outStr( msg ) return "Lua States (debug) :: " .. tostring( msg ) end -- create general error string function errStr( msg ) return "\n\nERROR: Lua States :: " .. tostring( msg ) .. "\n\n" end function _patch( obj ) obj = obj or {} -- add properties States.__init__( obj ) -- add methods obj.resetStates = States.resetStates obj.getState = States.getState obj.setState = States.setState obj.gotoState = States.gotoState obj.getPreviousState = States.getPreviousState obj.gotoPreviousState = States.gotoPreviousState obj.pushStateStack = States.pushStateStack obj.popStateStack = States.popStateStack obj.setDebug = States.setDebug -- private method, for testing obj._stateStackSize = States._stateStackSize return obj end --====================================================================-- --== States Mixin --====================================================================-- States = {} States.NAME = "States Mixin" --======================================================-- -- Start: Mixin Setup for Lua Objects function States.__init__( self, params ) -- print( "States.__init__" ) params = params or {} --==-- States.resetStates( self, params ) end function States.__undoInit__( self ) -- print( "States.__undoInit__" ) States.resetStates( self ) end -- END: Mixin Setup for Lua Objects --======================================================-- --====================================================================-- --== Public Methods function States.resetStates( self, params ) if self.__debug_on then print( outStr( "resetStates: resetting object states" ) ) end self.__state_stack = {} self.__curr_state_func = nil self.__curr_state_name = "" self.__debug_on = params.debug_on == nil and false or params.debug_on end function States.getState( self ) return self.__curr_state_name end function States.setState( self, state_name ) assert( state_name, errStr("missing state name") ) assert( type(state_name)=='string', errStr("state name must be string'" .. tostring( state_name ) ) ) --==-- if self.__debug_on then print( outStr("setState: is now '" .. tostring( state_name ) .. "'" ) ) end local f = self[ state_name ] assert( type(f)=='function', errStr("missing method for state name: '" .. tostring( state_name ) ) ) self.__curr_state_func = f self.__curr_state_name = state_name end function States.gotoState( self, state_name, ... ) assert( state_name, errStr("no state name given") ) assert( self.__curr_state_func, errStr("no initial state method") ) --==-- if self.__debug_on then print( outStr("gotoState: '" .. self.__curr_state_name .. "' >> '".. tostring( state_name ) .. "'" ) ) end self:pushStateStack( self.__curr_state_name ) self.__curr_state_func( self, state_name, ... ) end function States.getPreviousState( self ) assert( #self.__state_stack > 0, errStr("state stack is empty") ) return self.__state_stack[1] end function States.gotoPreviousState( self, ... ) local state_name = self:popStateStack() assert( state_name, errStr("no state name given") ) assert( self.__curr_state_func, errStr("no initial state method") ) if self.__debug_on then print( outStr("gotoPreviousState: going to >> " .. tostring( state_name ) ) ) end self.__curr_state_func( self, state_name, ... ) end function States.pushStateStack( self, state_name ) assert( state_name, errStr("no state name given") ) table.insert( self.__state_stack, 1, state_name ) end function States.popStateStack( self ) assert( #self.__state_stack > 0, errStr("state stack is empty") ) return table.remove( self.__state_stack, 1 ) end function States.setDebug( self, value ) self.__debug_on = value end -- private method, for testing function States._stateStackSize( self ) return #self.__state_stack end --====================================================================-- --== States Facade --====================================================================-- return { StatesMix=States, patch=_patch, }
--====================================================================-- -- dmc_lua/lua_states_mix.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2013-2015 David McCuskey. All Rights Reserved. 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. --]] --====================================================================-- --== DMC Lua Library : Lua States Mixin --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "1.3.1" --====================================================================-- --== Setup, Constants local tinsert = table.insert local tremove = table.remove local States --====================================================================-- --== Support Functions -- create general output string function outStr( msg ) return "Lua States (debug) :: " .. tostring( msg ) end -- create general error string function errStr( msg ) return "\n\nERROR: Lua States :: " .. tostring( msg ) .. "\n\n" end function _patch( obj ) obj = obj or {} -- add properties States.__init__( obj ) -- add methods obj.resetStates = States.resetStates obj.getState = States.getState obj.setState = States.setState obj.gotoState = States.gotoState obj.getPreviousState = States.getPreviousState obj.gotoPreviousState = States.gotoPreviousState obj.pushStateStack = States.pushStateStack obj.popStateStack = States.popStateStack obj.setDebug = States.setDebug -- private method, for testing obj._stateStackSize = States._stateStackSize return obj end --====================================================================-- --== States Mixin --====================================================================-- States = {} States.NAME = "States Mixin" --======================================================-- -- Start: Mixin Setup for Lua Objects function States.__init__( self, params ) -- print( "States.__init__" ) params = params or {} --==-- States.resetStates( self, params ) end function States.__undoInit__( self ) -- print( "States.__undoInit__" ) States.resetStates( self ) end -- END: Mixin Setup for Lua Objects --======================================================-- --====================================================================-- --== Public Methods function States.resetStates( self, params ) params = params or {} --==-- if self.__debug_on then print( outStr( "resetStates: resetting object states" ) ) end self.__state_stack = {} self.__curr_state_func = nil self.__curr_state_name = "" self.__debug_on = params.debug_on == nil and false or params.debug_on end function States.getState( self ) return self.__curr_state_name end function States.setState( self, state_name ) assert( state_name, errStr("missing state name") ) assert( type(state_name)=='string', errStr("state name must be string'" .. tostring( state_name ) ) ) --==-- if self.__debug_on then print( outStr("setState: is now '" .. tostring( state_name ) .. "'" ) ) end local f = self[ state_name ] assert( type(f)=='function', errStr("missing method for state name: '" .. tostring( state_name ) ) ) self.__curr_state_func = f self.__curr_state_name = state_name end function States.gotoState( self, state_name, ... ) assert( state_name, errStr("no state name given") ) assert( self.__curr_state_func, errStr("no initial state method") ) --==-- if self.__debug_on then print( outStr("gotoState: '" .. self.__curr_state_name .. "' >> '".. tostring( state_name ) .. "'" ) ) end self:pushStateStack( self.__curr_state_name ) self.__curr_state_func( self, state_name, ... ) end function States.getPreviousState( self ) assert( #self.__state_stack > 0, errStr("state stack is empty") ) return self.__state_stack[1] end function States.gotoPreviousState( self, ... ) local state_name = self:popStateStack() assert( state_name, errStr("no state name given") ) assert( self.__curr_state_func, errStr("no initial state method") ) if self.__debug_on then print( outStr("gotoPreviousState: going to >> " .. tostring( state_name ) ) ) end self.__curr_state_func( self, state_name, ... ) end function States.pushStateStack( self, state_name ) assert( state_name, errStr("no state name given") ) tinsert( self.__state_stack, 1, state_name ) end function States.popStateStack( self ) assert( #self.__state_stack > 0, errStr("state stack is empty") ) return tremove( self.__state_stack, 1 ) end function States.setDebug( self, value ) self.__debug_on = value end -- private method, for testing function States._stateStackSize( self ) return #self.__state_stack end --====================================================================-- --== States Facade --====================================================================-- return { StatesMix=States, patch=_patch, }
minor fixes
minor fixes
Lua
mit
dmccuskey/lua-states-mixin
a91c5c365b94f1b2392089d1360e742e9afa392d
lib/http.lua
lib/http.lua
local TCP = require('tcp') local Request = require('request') local Response = require('response') local HTTP_Parser = require('http_parser') local HTTP = {} function HTTP.create_server(host, port, on_connection) local server = TCP.new() server:bind(host, port) server:listen(function (err) if err then return server:emit("error", err) end -- Accept the client and build request and response objects local client = TCP.new() server:accept(client) client:read_start() local request = Request.new(client) local response = Response.new(client) -- Convert TCP stream to HTTP stream local current_field local parser local headers parser = HTTP_Parser.new("request", { on_message_begin = function () headers = {} request.headers = headers end, on_url = function (url) request.url = url end, on_header_field = function (field) current_field = field end, on_header_value = function (value) headers[current_field:lower()] = value end, on_headers_complete = function (info) request.method = info.method if info.upgrade then server:emit("upgrade", request, client) else on_connection(request, response) end end, on_body = function (chunk) request:emit('data', chunk) end, on_message_complete = function () parser:finish() request:emit('end') end }) client:on("data", function (chunk, len) if len == 0 then return end local nparsed = parser:execute(chunk, 0, len) if nparsed < len then request:emit("error", "parse error") end end) client:on("end", function () parser:finish() end) end) return server end return HTTP
local TCP = require('tcp') local Request = require('request') local Response = require('response') local HTTP_Parser = require('http_parser') local HTTP = {} function HTTP.create_server(host, port, on_connection) local server = TCP.new() server:bind(host, port) server:listen(function (err) if err then return server:emit("error", err) end -- Accept the client and build request and response objects local client = TCP.new() server:accept(client) client:read_start() local request = Request.new(client) local response = Response.new(client) -- Convert TCP stream to HTTP stream local current_field local parser local headers parser = HTTP_Parser.new("request", { on_message_begin = function () headers = {} request.headers = headers end, on_url = function (url) request.url = url end, on_header_field = function (field) current_field = field end, on_header_value = function (value) headers[current_field:lower()] = value end, on_headers_complete = function (info) request.method = info.method request.version_major = info.version_major request.version_minor = info.version_minor request.upgrade = info.upgrade request.should_keep_alive = info.should_keep_alive if not request.upgrade then on_connection(request, response) end end, on_body = function (chunk) request:emit('data', chunk) end, on_message_complete = function () parser:finish() request:emit('end') end }) client:on("data", function (chunk, len) if len == 0 then return end local nparsed = parser:execute(chunk, 0, len) if nparsed < len then if request.upgrade then request:emit("upgrade", request, client, chunk:sub(nparsed + 1)) else request:emit("error", "parse error") end end end) client:on("end", function () parser:finish() end) end) return server end return HTTP
Possible fix for upgrade events
Possible fix for upgrade events Change-Id: Iab1f16737880d781204918b6e431cb3045a656cd
Lua
apache-2.0
AndrewTsao/luvit,rjeli/luvit,rjeli/luvit,kaustavha/luvit,bsn069/luvit,sousoux/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,boundary/luvit,boundary/luvit,sousoux/luvit,DBarney/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,bsn069/luvit,zhaozg/luvit,AndrewTsao/luvit,rjeli/luvit,boundary/luvit,DBarney/luvit,sousoux/luvit,connectFree/lev,sousoux/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,connectFree/lev,rjeli/luvit,DBarney/luvit,kaustavha/luvit,luvit/luvit,boundary/luvit,bsn069/luvit,DBarney/luvit,AndrewTsao/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,brimworks/luvit
0f949350e08df282bc2c9d2f22f56d960de65009
scheduled/mapitemreset.lua
scheduled/mapitemreset.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") -- INSERT INTO scheduledscripts VALUES('scheduled.mapitemreset', 30, 30, 'resetMapitem') local M = {} function M.resetMapitem() -- close rockwall entrance again (item 623) local pos = position(894, 627, 0); -- move character who blocks the entrance if (world:isCharacterOnField(pos)) then local blocker = world:getCharacterOnField(pos); world:gfx(7, pos); world:makeSound(4, pos); local targetPos = position(892, 627, 0); blocker:warp(targetPos); world:gfx(7, targetPos); common.HighInformNLS(blocker, "Ein Windstoss wirft dich zurck bevor die Felswand dich trifft!", "A wind gust throws you back before the rock hits you!"); end -- close rockwall if (world:getItemOnField(pos).id ~= 623) then world:createItemFromId(623, 1, pos, true, 333, nil); --rock local Characters = world:getPlayersInRangeOf(pos, 5); for i, Char in pairs(Characters) do common.InformNLS(Char, "Eine Steinwand erscheint wie aus dem nichts.", "A rock wall appears out of nowhere."); end end -- reset the fires at Ronagan Dungeon if (world:getItemOnField(position(898, 600, -9)).id ~= 298) then wworld:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(898, 600, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 597, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(898, 597, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 600. -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(894, 600. -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 597, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(894, 597, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 594, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(898, 594, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 594, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(894, 594, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 591, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(894, 591, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 588, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(898, 588, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField( position(894, 588, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(894, 588, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 585, -9)).id ~= 298) then world:erase(12, 1, position(898, 585, -9), true, 333, nil); --lit fire world:createItemFromId(298, 1, position(898, 585, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 585, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(894, 585, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 591, -9)).id ~= 298) then world:erase(deleteItem,1); --lit fire world:createItemFromId(298, 1, position(898, 591, -9), true, 333, nil); --unlit fire end -- reset akultut burning room if (world:getItemOnField(position(480, 834, -9)).id ~= 2039) then for xx = 474, 482 do for yy = 834, 844 do local pos = position(xx, yy, -9) local flame = world:getItemOnField(pos) if flame.id == 359 then world:erase(flame, flame.number) end end end local skull = world:createItemFromId(2039, 1, position(480, 834, -9), true, 333, nil) skull.wear = 255 world:changeItem(skull) end -- reset akultut exploded skull if (world:getItemOnField(position(482, 838, -9)).id ~= 2038) then local skull = world:createItemFromId(2038, 1, position(482, 838, -9), true, 333, nil) skull.wear = 255 world:changeItem(skull) end -- reset lake of life bridge local lever1 = world:getItemOnField(position(720, 258, -9)) local lever2 = world:getItemOnField(position(781, 188, -9)) if (lever1.id == 436 or lever2.id == 436) then local trippingTime1 = tonumber(lever1:getData("LastUseTime")) or 0 local trippingTime2 = tonumber(lever2:getData("LastUseTime")) or 0 local serverTime = world:getTime("unix") --check if 10min are over if math.max(trippingTime1, trippingTime2) + 600 > serverTime then return end -- switch back levers lever1.id = 434 world:changeItem(lever1) local plyList = world:getPlayersInRangeOf(lever1.pos, 10) for _, char in pairs(plyList) do common.InformNLS(char, "Du hrst ein klicken von dem Hebel.", "You hear a click from the lever.") end lever2.id = 434 world:changeItem(lever2) local plyList = world:getPlayersInRangeOf(lever2.pos, 10) for _, char in pairs(plyList) do common.InformNLS(char, "Du hrst ein klicken von dem Hebel.", "You hear a click from the lever.") end -- delete bridge for xx = 722, 723 do for yy = 240, 258 do local pos = position(xx, yy, -9) local bridge = world:getItemOnField(pos) if bridge.id == 614 or bridge.id == 615 or bridge.id == 617 then -- port out characters on the bridge if world:isCharacterOnField(pos) then local char = world:getCharacterOnField(pos) char:warp(position(721, 260, -9)) common.InformNLS(char, "Du wirst ans Ufer gesplt als die Brcke verschwindet.", "You are flushed to the shore as the bridge disappears.") end world:erase(bridge, bridge.number) end end end end end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") -- INSERT INTO scheduledscripts VALUES('scheduled.mapitemreset', 30, 30, 'resetMapitem') local M = {} function M.resetMapitem() -- close rockwall entrance again (item 623) local pos = position(894, 627, 0); -- move character who blocks the entrance if (world:isCharacterOnField(pos)) then local blocker = world:getCharacterOnField(pos); world:gfx(7, pos); world:makeSound(4, pos); local targetPos = position(892, 627, 0); blocker:warp(targetPos); world:gfx(7, targetPos); common.HighInformNLS(blocker, "Ein Windstoss wirft dich zurck bevor die Felswand dich trifft!", "A wind gust throws you back before the rock hits you!"); end -- close rockwall if (world:getItemOnField(pos).id ~= 623) then world:createItemFromId(623, 1, pos, true, 333, nil); --rock local Characters = world:getPlayersInRangeOf(pos, 5); for i, Char in pairs(Characters) do common.InformNLS(Char, "Eine Steinwand erscheint wie aus dem nichts.", "A rock wall appears out of nowhere."); end end -- reset the fires at Ronagan Dungeon if (world:getItemOnField(position(898, 600, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(898, 600, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 597, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(898, 597, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 600. -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(894, 600. -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 597, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(894, 597, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 594, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(898, 594, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 594, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(894, 594, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 591, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(894, 591, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 588, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(898, 588, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField( position(894, 588, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(894, 588, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 585, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(898, 585, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(894, 585, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(894, 585, -9), true, 333, nil); --unlit fire elseif (world:getItemOnField(position(898, 591, -9)).id ~= 298) then world:erase(deleteItem,12); --lit fire world:createItemFromId(298, 1, position(898, 591, -9), true, 333, nil); --unlit fire end -- reset akultut burning room if (world:getItemOnField(position(480, 834, -9)).id ~= 2039) then for xx = 474, 482 do for yy = 834, 844 do local pos = position(xx, yy, -9) local flame = world:getItemOnField(pos) if flame.id == 359 then world:erase(flame, flame.number) end end end local skull = world:createItemFromId(2039, 1, position(480, 834, -9), true, 333, nil) skull.wear = 255 world:changeItem(skull) end -- reset akultut exploded skull if (world:getItemOnField(position(482, 838, -9)).id ~= 2038) then local skull = world:createItemFromId(2038, 1, position(482, 838, -9), true, 333, nil) skull.wear = 255 world:changeItem(skull) end -- reset lake of life bridge local lever1 = world:getItemOnField(position(720, 258, -9)) local lever2 = world:getItemOnField(position(781, 188, -9)) if (lever1.id == 436 or lever2.id == 436) then local trippingTime1 = tonumber(lever1:getData("LastUseTime")) or 0 local trippingTime2 = tonumber(lever2:getData("LastUseTime")) or 0 local serverTime = world:getTime("unix") --check if 10min are over if math.max(trippingTime1, trippingTime2) + 600 > serverTime then return end -- switch back levers lever1.id = 434 world:changeItem(lever1) local plyList = world:getPlayersInRangeOf(lever1.pos, 10) for _, char in pairs(plyList) do common.InformNLS(char, "Du hrst ein klicken von dem Hebel.", "You hear a click from the lever.") end lever2.id = 434 world:changeItem(lever2) local plyList = world:getPlayersInRangeOf(lever2.pos, 10) for _, char in pairs(plyList) do common.InformNLS(char, "Du hrst ein klicken von dem Hebel.", "You hear a click from the lever.") end -- delete bridge for xx = 722, 723 do for yy = 240, 258 do local pos = position(xx, yy, -9) local bridge = world:getItemOnField(pos) if bridge.id == 614 or bridge.id == 615 or bridge.id == 617 then -- port out characters on the bridge if world:isCharacterOnField(pos) then local char = world:getCharacterOnField(pos) char:warp(position(721, 260, -9)) common.InformNLS(char, "Du wirst ans Ufer gesplt als die Brcke verschwindet.", "You are flushed to the shore as the bridge disappears.") end world:erase(bridge, bridge.number) end end end end end return M
fix typo
fix typo
Lua
agpl-3.0
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content
40ec582c601a735c614bbf175be27192833941a3
configs/neovim/lua/packer-config.lua
configs/neovim/lua/packer-config.lua
local fn = vim.fn local install_path = fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim" if fn.empty(fn.glob(install_path)) > 0 then packer_bootstrap = fn.system({ "git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path }) end return require("packer").startup(function() use {"wbthomason/packer.nvim"} use { "nvim-lualine/lualine.nvim", config = function() require("lualine").setup() end } -- Status Line use {"editorconfig/editorconfig-vim"} use {"junegunn/fzf.vim"} use { "kyazdani42/nvim-tree.lua", config = function() require("nvim-tree").setup() end } use { "lewis6991/spellsitter.nvim", config = function() require("spellsitter").setup() end } use {"romgrk/barbar.nvim", requires = {"kyazdani42/nvim-web-devicons"}} -- Tabs use {"airblade/vim-gitgutter"} -- Git diff in sign column -- Rust use { "saecki/crates.nvim", requires = { "nvim-lua/plenary.nvim" }, config = function() require("crates").setup() end, } use {"simrat39/rust-tools.nvim", config = function() require("rust-tools").setup({}) end} -- treesitter use {"nvim-treesitter/nvim-treesitter", run = ":TSUpdate"} use { "nvim-treesitter/nvim-treesitter-context", config = function() require("treesitter-context").setup() end } use {"nvim-treesitter/nvim-treesitter-refactor"} -- lsp use {"neovim/nvim-lspconfig"} use {"onsails/lspkind-nvim"} -- vscode-like pictograms for neovim lsp completion items use {"hrsh7th/nvim-cmp"} -- Autocompletion plugin use {"hrsh7th/cmp-nvim-lsp"} -- LSP source for nvim-cmp use {"saadparwaiz1/cmp_luasnip"} -- Snippets source for nvim-cmp use {"L3MON4D3/LuaSnip"} -- Snippets plugin -- Automatically set up your configuration after cloning packer.nvim -- Put this at the end after all plugins if packer_bootstrap then require("packer").sync() end end)
-- clean install with -- rm -rf ~/.cache/nvim ~/.local/share/nvim ~/.local/state/nvim ~/.config/nvim/plugin local ensure_packer = function() local fn = vim.fn local install_path = fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim" if fn.empty(fn.glob(install_path)) > 0 then fn.system({ "git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path }) vim.cmd [[packadd packer.nvim]] return true end return false end local packer_bootstrap = ensure_packer() return require("packer").startup(function(use) use {"wbthomason/packer.nvim"} use { "nvim-lualine/lualine.nvim", config = function() require("lualine").setup() end } -- Status Line use { "kyazdani42/nvim-tree.lua", config = function() require("nvim-tree").setup() end } use {"airblade/vim-gitgutter"} -- Git diff in sign column use {"editorconfig/editorconfig-vim"} use {"junegunn/fzf.vim"} use {"romgrk/barbar.nvim", requires = {"kyazdani42/nvim-web-devicons"}} -- Tabs -- Rust use { "saecki/crates.nvim", requires = { "nvim-lua/plenary.nvim" }, config = function() require("crates").setup() end, } use {"simrat39/rust-tools.nvim", config = function() require("rust-tools").setup({}) end} -- treesitter use {"nvim-treesitter/nvim-treesitter", run = ":TSUpdate"} use { "nvim-treesitter/nvim-treesitter-context", config = function() require("treesitter-context").setup() end } use {"nvim-treesitter/nvim-treesitter-refactor"} -- lsp use {"neovim/nvim-lspconfig"} use {"onsails/lspkind-nvim"} -- vscode-like pictograms for neovim lsp completion items use {"hrsh7th/nvim-cmp"} -- Autocompletion plugin use {"hrsh7th/cmp-nvim-lsp"} -- LSP source for nvim-cmp use {"saadparwaiz1/cmp_luasnip"} -- Snippets source for nvim-cmp use {"L3MON4D3/LuaSnip"} -- Snippets plugin -- Automatically set up your configuration after cloning packer.nvim -- Put this at the end after all plugins if packer_bootstrap then require("packer").sync() end end)
fix(neovim): fix ensure_packer script
fix(neovim): fix ensure_packer script also sort/update use thingies for neovim v0.8
Lua
mit
EdJoPaTo/LinuxScripts
a5940ecf4ae76c1e0ae947fb85ae97f796e3f34d
agents/monitoring/tests/fixtures/protocol/server.lua
agents/monitoring/tests/fixtures/protocol/server.lua
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local table = require('table') local http = require("http") local url = require('url') local lineEmitter = LineEmitter:new() local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') set_option(opts, "perform_client_disconnect", 'true') set_option(opts, "rate_limit", 3000) set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) local destroy = false -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil -- Handle rate limit logic client.rate_limit = client.rate_limit - 1 if client.rate_limit <= 0 then response = JSON.parse(fixtures['rate-limiting']['rate-limit-error']) destroy = true end response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') if destroy == true then client:destroy() end end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end local server = tls.createServer(options, function (client) client.rate_limit = opts.rate_limit client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) respond(log, client, payload) end) -- Reset rate limit counter timer.setTimeout(opts.rate_limit_reset, function() client.rate_limit = opts.rate_limit end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic if opts.perform_client_disconnect == 'true' then local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end end):listen(port, opts.listen_ip) return server end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local table = require('table') local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local table = require('table') local http = require("http") local url = require('url') local lineEmitter = LineEmitter:new() local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') set_option(opts, "perform_client_disconnect", 'true') set_option(opts, "rate_limit", 3000) set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) local destroy = false -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil -- Handle rate limit logic client.rate_limit = client.rate_limit - 1 if client.rate_limit <= 0 then response = JSON.parse(fixtures['rate-limiting']['rate-limit-error']) destroy = true end response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') if destroy == true then client:destroy() end return destroy end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function clear_timers(timer_ids) for k, v in pairs(timer_ids) do if v._closed ~= true then timer.clearTimer(v) end end end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end local server = tls.createServer(options, function (client) local destroyed = false local timers = {} client.rate_limit = opts.rate_limit client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) destroyed = respond(log, client, payload) if destroyed == true then clear_timers(timers) end end) -- Reset rate limit counter timer.setTimeout(opts.rate_limit_reset, function() client.rate_limit = opts.rate_limit end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) table.insert(timers, timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) ) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic if opts.perform_client_disconnect == 'true' then local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end end):listen(port, opts.listen_ip) return server end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
monitoring: fixtures: server: clear interval timers
monitoring: fixtures: server: clear interval timers setup infrastructure to clear interval timers if a connection is destroyed.
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base
fc4ae61aaaa1899445c9c69d77e1be3fe4d4a9f8
Main/Libraries/Macaroni/Lua/5.1.4/Source/PrepareBoostBuild.lua
Main/Libraries/Macaroni/Lua/5.1.4/Source/PrepareBoostBuild.lua
require "Macaroni.IO.GeneratedFileWriter"; require "Macaroni.Model.Library"; require "Macaroni.IO.Path"; function getIncludePath() local success, path = pcall(function() return properties.lua["5.1.4"].include; end); if (not success) then error([[Could not find variable properties.lua["5.1.4"].include.]]); end return path; end function Prepare(library, sources, outputPath, installPath, extraArgs) local includePath = getIncludePath(); local buildjam = outputPath:NewPath("/jamroot.jam"); print("Creating Boost.Build file at " .. buildjam.AbsolutePath .. "."); local writer = buildjam:CreateFile(); writer:Write([[ # Generated by Macaroni. import boost ; import path ; project : usage-requirements <include>]] .. includePath .. [[ ; alias libSources : ; ]]); writer:Close(); end
require "Macaroni.IO.GeneratedFileWriter"; require "Macaroni.Model.Library"; require "Macaroni.IO.Path"; function getIncludePath() local success, path = pcall(function() return properties.lua["5.1.4"].include; end); if (not success) then error([[Could not find variable properties.lua["5.1.4"].include.]]); end return path; end function Prepare(library, sources, outputPath, installPath, extraArgs) local includePath = getIncludePath(); local buildjam = outputPath:NewPath("/jamroot.jam"); print("Creating Boost.Build file at " .. buildjam.AbsolutePath .. "."); local writer = buildjam:CreateFile(); writer:Write([[ # Generated by Macaroni. import boost ; import path ; project : usage-requirements <include>]] .. includePath .. [[ ; alias library : [ path.glob-tree ]] .. includePath .. [[ : *.c : luac.c lua.c ] ; ]]); writer:Close(); end
Fixed a *very* annoying issue in the Macaroni Library for Lua.
Fixed a *very* annoying issue in the Macaroni Library for Lua.
Lua
apache-2.0
TimSimpson/Macaroni,bowlofstew/Macaroni,TimSimpson/Macaroni,TimSimpson/Macaroni,bowlofstew/Macaroni,bowlofstew/Macaroni,bowlofstew/Macaroni,bowlofstew/Macaroni,TimSimpson/Macaroni,TimSimpson/Macaroni
8fbf3c0fc4b973ff6a1f3a13113e90a4491b8717
examples/languagemodel.lua
examples/languagemodel.lua
require 'dp' --error"Work in progress: not ready for use" --[[command line arguments]]-- cmd = torch.CmdLine() cmd:text() cmd:text('Train a Language Model on BillionWords dataset using SoftmaxTree') cmd:text('Example:') cmd:text('$> th languagemodel.lua --small --batchSize 512 --momentum 0.5') cmd:text('Options:') cmd:option('--learningRate', 0.1, 'learning rate at t=0') cmd:option('--maxOutNorm', 1, 'max norm each layers output neuron weights') cmd:option('--momentum', 0, 'momentum') cmd:option('--batchSize', 512, 'number of examples per batch') cmd:option('--type', 'double', 'type: double | float | cuda') cmd:option('--maxEpoch', 100, 'maximum number of epochs to run') cmd:option('--maxTries', 30, 'maximum number of epochs to try to find a better local minima for early-stopping') cmd:option('--dropout', false, 'apply dropout on hidden neurons, requires "nnx" luarock') cmd:option('--contextSize', 5, 'number of words preceding the target word used to predict the target work') cmd:option('--inputEmbeddingSize', 100, 'number of neurons per word embedding') cmd:option('--neuralSize', 200, 'number of hidden units used for first hidden layer (used when --convolution is not used)') --or cmd:option('--convolution', false, 'use a Convolution1D instead of Neural for the first hidden layer') cmd:option('--convOutputSize', 200, 'number of output neurons of the convolutional kernel (outputFrameSize)') cmd:option('--convKernelSize', 2, 'number of words considered by convolution') cmd:option('--convKernelStride', 1, 'stride (step size) of the convolution') cmd:option('--convPoolSize', 2, 'number of words max pooled after convolution') cmd:option('--convPoolStride', 2, 'stride of the max pooling after the convolution') cmd:option('--outputEmbeddingSize', 100, 'number of hidden units at softmaxtree') cmd:option('--small', false, 'use a small (1/30th) subset of the training set') cmd:option('--tiny', false, 'use a tiny (1/100th) subset of the training set') cmd:text() opt = cmd:parse(arg or {}) print(opt) --[[data]]-- local train_file = 'train_data.th7' if opt.small then train_file = 'train_small.th7' elseif opt.tiny then train_file = 'train_tiny.th7' end local datasource = dp.BillionWords{ context_size = opt.contextSize, train_file = train_file } --[[Model]]-- local dropout if opt.dropout then require 'nnx' end print("Input to first hidden layer has ".. opt.contextSize*opt.inputEmbeddingSize.." neurons.") local hiddenModel, inputSize if opt.convolution then print"Using convolution for first hidden layer" hiddenModel = dp.Convolution1D{ input_size = opt.inputEmbeddingSize, output_size = opt.convOutputSize, kernel_size = opt.convKernelSize, kernel_stride = opt.convKernelStride, pool_size = opt.convPoolSize, pool_stride = opt.convPoolStride, transfer = nn.Tanh(), dropout = opt.dropout and nn.Dropout() or nil } local nOutputFrame = hiddenModel:nOutputFrame(opt.contextSize) print("Convolution has "..nOutputFrame.." output Frames") inputSize = nOutputFrame*opt.convOutputSize else hiddenModel = dp.Neural{ input_size = opt.contextSize*opt.inputEmbeddingSize, output_size = opt.neuralSize, transfer = nn.Tanh(), dropout = opt.dropout and nn.Dropout() or nil } inputSize = opt.neuralSize end print("input to second hidden layer has size "..inputSize) mlp = dp.Sequential{ models = { dp.Dictionary{ dict_size = datasource:vocabularySize(), output_size = opt.inputEmbeddingSize }, hiddenModel, dp.Neural{ input_size = inputSize, output_size = opt.outputEmbeddingSize, transfer = nn.Tanh(), dropout = opt.dropout and nn.Dropout() or nil }, dp.SoftmaxTree{ input_size = opt.outputEmbeddingSize, hierarchy = datasource:hierarchy(), dropout = opt.dropout and nn.Dropout() or nil } } } --[[GPU or CPU]]-- if opt.type == 'cuda' then print"Using CUDA" require 'cutorch' require 'cunn' mlp:cuda() end --[[Propagators]]-- train = dp.Optimizer{ loss = dp.TreeNLL(), visitor = { -- the ordering here is important: dp.Momentum{momentum_factor = opt.momentum}, dp.Learn{ learning_rate = opt.learningRate, observer = dp.LearningRateSchedule{ schedule = {[200]=0.01, [400]=0.001} } }, dp.MaxNorm{max_out_norm = opt.maxOutNorm} }, feedback = dp.Perplexity(), sampler = dp.ShuffleSampler{batch_size = opt.batchSize}, progress = true } valid = dp.Evaluator{ loss = dp.TreeNLL(), feedback = dp.Perplexity(), sampler = dp.Sampler() } test = dp.Evaluator{ loss = dp.TreeNLL(), feedback = dp.Perplexity(), sampler = dp.Sampler() } --[[Experiment]]-- xp = dp.Experiment{ model = mlp, optimizer = train, validator = valid, tester = test, observer = { dp.FileLogger(), --[[dp.EarlyStopper{ maximize = true, max_epochs = opt.maxTries }--]] }, random_seed = os.time(), max_epoch = opt.maxEpoch } xp:run(datasource)
require 'dp' --error"Work in progress: not ready for use" --[[command line arguments]]-- cmd = torch.CmdLine() cmd:text() cmd:text('Train a Language Model on BillionWords dataset using SoftmaxTree') cmd:text('Example:') cmd:text('$> th languagemodel.lua --small --batchSize 512 --momentum 0.5') cmd:text('Options:') cmd:option('--learningRate', 0.1, 'learning rate at t=0') cmd:option('--maxOutNorm', 1, 'max norm each layers output neuron weights') cmd:option('--momentum', 0, 'momentum') cmd:option('--batchSize', 512, 'number of examples per batch') cmd:option('--type', 'double', 'type: double | float | cuda') cmd:option('--maxEpoch', 100, 'maximum number of epochs to run') cmd:option('--maxTries', 30, 'maximum number of epochs to try to find a better local minima for early-stopping') cmd:option('--dropout', false, 'apply dropout on hidden neurons, requires "nnx" luarock') cmd:option('--contextSize', 5, 'number of words preceding the target word used to predict the target work') cmd:option('--inputEmbeddingSize', 100, 'number of neurons per word embedding') cmd:option('--neuralSize', 200, 'number of hidden units used for first hidden layer (used when --convolution is not used)') --or cmd:option('--convolution', false, 'use a Convolution1D instead of Neural for the first hidden layer') cmd:option('--convOutputSize', 200, 'number of output neurons of the convolutional kernel (outputFrameSize)') cmd:option('--convKernelSize', 2, 'number of words considered by convolution') cmd:option('--convKernelStride', 1, 'stride (step size) of the convolution') cmd:option('--convPoolSize', 2, 'number of words max pooled after convolution') cmd:option('--convPoolStride', 2, 'stride of the max pooling after the convolution') cmd:option('--outputEmbeddingSize', 100, 'number of hidden units at softmaxtree') cmd:option('--small', false, 'use a small (1/30th) subset of the training set') cmd:option('--tiny', false, 'use a tiny (1/100th) subset of the training set') cmd:text() opt = cmd:parse(arg or {}) print(opt) --[[data]]-- local train_file = 'train_data.th7' local valid_tile = 'valid_data.th7' if opt.small then train_file = 'train_small.th7' elseif opt.tiny then valid_file = 'test_data.th7' train_file = 'train_tiny.th7' end local datasource = dp.BillionWords{ context_size = opt.contextSize, train_file = train_file, valid_file = valid_file } --[[Model]]-- local dropout if opt.dropout then require 'nnx' end print("Input to first hidden layer has ".. opt.contextSize*opt.inputEmbeddingSize.." neurons.") local hiddenModel, inputSize if opt.convolution then print"Using convolution for first hidden layer" hiddenModel = dp.Convolution1D{ input_size = opt.inputEmbeddingSize, output_size = opt.convOutputSize, kernel_size = opt.convKernelSize, kernel_stride = opt.convKernelStride, pool_size = opt.convPoolSize, pool_stride = opt.convPoolStride, transfer = nn.Tanh(), dropout = opt.dropout and nn.Dropout() or nil } local nOutputFrame = hiddenModel:nOutputFrame(opt.contextSize) print("Convolution has "..nOutputFrame.." output Frames") inputSize = nOutputFrame*opt.convOutputSize else hiddenModel = dp.Neural{ input_size = opt.contextSize*opt.inputEmbeddingSize, output_size = opt.neuralSize, transfer = nn.Tanh(), dropout = opt.dropout and nn.Dropout() or nil } inputSize = opt.neuralSize end print("input to second hidden layer has size "..inputSize) mlp = dp.Sequential{ models = { dp.Dictionary{ dict_size = datasource:vocabularySize(), output_size = opt.inputEmbeddingSize }, hiddenModel, dp.Neural{ input_size = inputSize, output_size = opt.outputEmbeddingSize, transfer = nn.Tanh(), dropout = opt.dropout and nn.Dropout() or nil }, dp.SoftmaxTree{ input_size = opt.outputEmbeddingSize, hierarchy = datasource:hierarchy(), dropout = opt.dropout and nn.Dropout() or nil } } } --[[GPU or CPU]]-- if opt.type == 'cuda' then print"Using CUDA" require 'cutorch' require 'cunn' mlp:cuda() end --[[Propagators]]-- train = dp.Optimizer{ loss = dp.TreeNLL(), visitor = { -- the ordering here is important: dp.Momentum{momentum_factor = opt.momentum}, dp.Learn{ learning_rate = opt.learningRate, observer = dp.LearningRateSchedule{ schedule = {[200]=0.01, [400]=0.001} } }, dp.MaxNorm{max_out_norm = opt.maxOutNorm} }, feedback = dp.Perplexity(), sampler = dp.ShuffleSampler{batch_size = opt.batchSize}, progress = true } valid = dp.Evaluator{ loss = dp.TreeNLL(), feedback = dp.Perplexity(), sampler = dp.Sampler() } test = dp.Evaluator{ loss = dp.TreeNLL(), feedback = dp.Perplexity(), sampler = dp.Sampler() } --[[Experiment]]-- xp = dp.Experiment{ model = mlp, optimizer = train, validator = valid, tester = test, observer = { dp.FileLogger(), --[[dp.EarlyStopper{ maximize = true, max_epochs = opt.maxTries }--]] }, random_seed = os.time(), max_epoch = opt.maxEpoch } xp:run(datasource)
Tiny dataset temp fix
Tiny dataset temp fix
Lua
bsd-3-clause
fiskio/dp,kracwarlock/dp,sagarwaghmare69/dp,eulerreich/dp,rickyHong/dptorchLib,nicholas-leonard/dp,jnhwkim/dp
ec1bca238e2ea6bca3fd641a36d2bc821e0bda95
lualib/http/httpc.lua
lualib/http/httpc.lua
local socket = require "http.sockethelper" local url = require "http.url" local internal = require "http.internal" local string = string local table = table local httpc = {} local function request(fd, method, host, url, recvheader, header, content) local read = socket.readfunc(fd) local write = socket.writefunc(fd) local header_content = "" if header then for k,v in pairs(header) do header_content = string.format("%s%s:%s\r\n", header_content, k, v) end if header.host then host = "" end else host = string.format("host:%s\r\n",host) end if content then local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n%s\r\n%s", method, url, host, #content, header_content, content) write(data) else local request_header = string.format("%s %s HTTP/1.1\r\nhost:%s\r\ncontent-length:0\r\n%s\r\n", method, url, host, header_content) write(request_header) end local tmpline = {} local body = internal.recvheader(read, tmpline, "") if not body then error(socket.socket_error) end local statusline = tmpline[1] local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$" code = assert(tonumber(code)) local header = internal.parseheader(tmpline,2,recvheader or {}) if not header then error("Invalid HTTP response header") end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then error ("Unsupport transfer-encoding") end end if mode == "chunked" then body, header = internal.recvchunkedbody(read, nil, header, body) if not body then error("Invalid response body") end else -- identity mode if length then if #body >= length then body = body:sub(1,length) else local padding = read(length - #body) body = body .. padding end else body = nil end end return code, body end function httpc.request(method, host, url, recvheader, header, content) local hostname, port = host:match"([^:]+):?(%d*)$" if port == "" then port = 80 else port = tonumber(port) end local fd = socket.connect(hostname, port) local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content) socket.close(fd) if ok then return statuscode, body else error(statuscode) end end function httpc.get(...) return httpc.request("GET", ...) end local function escape(s) return (string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02X", string.byte(c)) end)) end function httpc.post(host, url, form, recvheader) local header = { ["content-type"] = "application/x-www-form-urlencoded" } local body = {} for k,v in pairs(form) do table.insert(body, string.format("%s=%s",escape(k),escape(v))) end return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&")) end return httpc
local socket = require "http.sockethelper" local url = require "http.url" local internal = require "http.internal" local string = string local table = table local httpc = {} local function request(fd, method, host, url, recvheader, header, content) local read = socket.readfunc(fd) local write = socket.writefunc(fd) local header_content = "" if header then for k,v in pairs(header) do header_content = string.format("%s%s:%s\r\n", header_content, k, v) end if header.host then host = "" else host = string.format("host:%s\r\n", host) end else host = string.format("host:%s\r\n",host) end if content then local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n%s\r\n%s", method, url, host, #content, header_content, content) write(data) else local request_header = string.format("%s %s HTTP/1.1\r\nhost:%s\r\ncontent-length:0\r\n%s\r\n", method, url, host, header_content) write(request_header) end local tmpline = {} local body = internal.recvheader(read, tmpline, "") if not body then error(socket.socket_error) end local statusline = tmpline[1] local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$" code = assert(tonumber(code)) local header = internal.parseheader(tmpline,2,recvheader or {}) if not header then error("Invalid HTTP response header") end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then error ("Unsupport transfer-encoding") end end if mode == "chunked" then body, header = internal.recvchunkedbody(read, nil, header, body) if not body then error("Invalid response body") end else -- identity mode if length then if #body >= length then body = body:sub(1,length) else local padding = read(length - #body) body = body .. padding end else body = nil end end return code, body end function httpc.request(method, host, url, recvheader, header, content) local hostname, port = host:match"([^:]+):?(%d*)$" if port == "" then port = 80 else port = tonumber(port) end local fd = socket.connect(hostname, port) local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content) socket.close(fd) if ok then return statuscode, body else error(statuscode) end end function httpc.get(...) return httpc.request("GET", ...) end local function escape(s) return (string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02X", string.byte(c)) end)) end function httpc.post(host, url, form, recvheader) local header = { ["content-type"] = "application/x-www-form-urlencoded" } local body = {} for k,v in pairs(form) do table.insert(body, string.format("%s=%s",escape(k),escape(v))) end return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&")) end return httpc
fix: httpc.post
fix: httpc.post 调用httpc.post时,如果没有在header里面设置host时有问题
Lua
mit
sundream/skynet,firedtoad/skynet,cpascal/skynet,helling34/skynet,ag6ag/skynet,yinjun322/skynet,ludi1991/skynet,lc412/skynet,letmefly/skynet,cdd990/skynet,xjdrew/skynet,ypengju/skynet_comment,samael65535/skynet,sundream/skynet,microcai/skynet,puXiaoyi/skynet,fztcjjl/skynet,great90/skynet,icetoggle/skynet,xjdrew/skynet,zhangshiqian1214/skynet,fhaoquan/skynet,pichina/skynet,dymx101/skynet,chuenlungwang/skynet,ag6ag/skynet,zhangshiqian1214/skynet,kebo/skynet,lawnight/skynet,chuenlungwang/skynet,gitfancode/skynet,zzh442856860/skynet-Note,iskygame/skynet,u20024804/skynet,nightcj/mmo,ruleless/skynet,zhoukk/skynet,asanosoyokaze/skynet,cmingjian/skynet,zhoukk/skynet,catinred2/skynet,leezhongshan/skynet,Zirpon/skynet,wangjunwei01/skynet,bingo235/skynet,yunGit/skynet,korialuo/skynet,u20024804/skynet,zhangshiqian1214/skynet,JiessieDawn/skynet,letmefly/skynet,winglsh/skynet,MoZhonghua/skynet,harryzeng/skynet,zhouxiaoxiaoxujian/skynet,vizewang/skynet,nightcj/mmo,helling34/skynet,zzh442856860/skynet-Note,LiangMa/skynet,JiessieDawn/skynet,samael65535/skynet,MetSystem/skynet,sdgdsffdsfff/skynet,wangyi0226/skynet,liuxuezhan/skynet,KAndQ/skynet,pigparadise/skynet,samael65535/skynet,asanosoyokaze/skynet,cloudwu/skynet,javachengwc/skynet,sanikoyes/skynet,pigparadise/skynet,boyuegame/skynet,yinjun322/skynet,microcai/skynet,cloudwu/skynet,great90/skynet,wangyi0226/skynet,icetoggle/skynet,winglsh/skynet,hongling0/skynet,letmefly/skynet,longmian/skynet,zhaijialong/skynet,lawnight/skynet,bigrpg/skynet,javachengwc/skynet,KAndQ/skynet,Markal128/skynet,MRunFoss/skynet,wangjunwei01/skynet,MoZhonghua/skynet,nightcj/mmo,pichina/skynet,great90/skynet,ilylia/skynet,sundream/skynet,iskygame/skynet,jxlczjp77/skynet,plsytj/skynet,zhaijialong/skynet,chenjiansnail/skynet,Ding8222/skynet,cmingjian/skynet,bigrpg/skynet,xcjmine/skynet,korialuo/skynet,enulex/skynet,jiuaiwo1314/skynet,ludi1991/skynet,chfg007/skynet,lynx-seu/skynet,KAndQ/skynet,rainfiel/skynet,matinJ/skynet,sanikoyes/skynet,zhoukk/skynet,cuit-zhaxin/skynet,lynx-seu/skynet,ludi1991/skynet,cuit-zhaxin/skynet,zhaijialong/skynet,firedtoad/skynet,Markal128/skynet,plsytj/skynet,ypengju/skynet_comment,chenjiansnail/skynet,KittyCookie/skynet,wangyi0226/skynet,matinJ/skynet,xjdrew/skynet,u20024804/skynet,sanikoyes/skynet,jxlczjp77/skynet,hongling0/skynet,lawnight/skynet,liuxuezhan/skynet,fhaoquan/skynet,ilylia/skynet,firedtoad/skynet,Zirpon/skynet,boyuegame/skynet,lc412/skynet,ruleless/skynet,plsytj/skynet,felixdae/skynet,xcjmine/skynet,zzh442856860/skynet,pigparadise/skynet,your-gatsby/skynet,winglsh/skynet,QuiQiJingFeng/skynet,zhouxiaoxiaoxujian/skynet,jxlczjp77/skynet,puXiaoyi/skynet,jiuaiwo1314/skynet,boyuegame/skynet,xcjmine/skynet,cpascal/skynet,dymx101/skynet,catinred2/skynet,enulex/skynet,rainfiel/skynet,JiessieDawn/skynet,pichina/skynet,gitfancode/skynet,chenjiansnail/skynet,liuxuezhan/skynet,kyle-wang/skynet,catinred2/skynet,LiangMa/skynet,iskygame/skynet,longmian/skynet,QuiQiJingFeng/skynet,togolwb/skynet,matinJ/skynet,bttscut/skynet,MRunFoss/skynet,puXiaoyi/skynet,harryzeng/skynet,fztcjjl/skynet,hongling0/skynet,codingabc/skynet,bingo235/skynet,cdd990/skynet,harryzeng/skynet,kebo/skynet,microcai/skynet,fztcjjl/skynet,zzh442856860/skynet,felixdae/skynet,cdd990/skynet,togolwb/skynet,KittyCookie/skynet,felixdae/skynet,zhangshiqian1214/skynet,sdgdsffdsfff/skynet,zhouxiaoxiaoxujian/skynet,enulex/skynet,codingabc/skynet,LiangMa/skynet,zzh442856860/skynet-Note,Zirpon/skynet,sdgdsffdsfff/skynet,your-gatsby/skynet,fhaoquan/skynet,cpascal/skynet,KittyCookie/skynet,lawnight/skynet,xinjuncoding/skynet,icetoggle/skynet,ludi1991/skynet,letmefly/skynet,helling34/skynet,yinjun322/skynet,yunGit/skynet,MoZhonghua/skynet,zzh442856860/skynet,korialuo/skynet,QuiQiJingFeng/skynet,vizewang/skynet,longmian/skynet,czlc/skynet,cmingjian/skynet,lc412/skynet,codingabc/skynet,liuxuezhan/skynet,asanosoyokaze/skynet,MetSystem/skynet,yunGit/skynet,Markal128/skynet,ruleless/skynet,bttscut/skynet,bigrpg/skynet,MRunFoss/skynet,xinjuncoding/skynet,Ding8222/skynet,chfg007/skynet,gitfancode/skynet,zhangshiqian1214/skynet,bttscut/skynet,xinjuncoding/skynet,zhangshiqian1214/skynet,javachengwc/skynet,Ding8222/skynet,czlc/skynet,togolwb/skynet,chfg007/skynet,czlc/skynet,lynx-seu/skynet,vizewang/skynet,bingo235/skynet,dymx101/skynet,kebo/skynet,cuit-zhaxin/skynet,kyle-wang/skynet,MetSystem/skynet,jiuaiwo1314/skynet,ilylia/skynet,zzh442856860/skynet-Note,wangjunwei01/skynet,ag6ag/skynet,leezhongshan/skynet,cloudwu/skynet,your-gatsby/skynet,leezhongshan/skynet,chuenlungwang/skynet,ypengju/skynet_comment,rainfiel/skynet,kyle-wang/skynet
acf9a1a7df758a24c728625143e53ab130b2076f
src/lgi.lua
src/lgi.lua
--[[-- Base lgi bootstrapper. Author: Pavel Holejsovsky Licence: MIT --]]-- local pairs, table = pairs, table local core = require 'lgi._core' module 'lgi' -- Helper for loading gi methods used only during bootstrapping. local function getface(namespace, interface, prefix, functions) local t = {} for _, func in pairs(functions) do local fname = prefix .. func t[func] = interface and core.get_by_name(namespace, interface, fname) or core.get_by_name(namespace, fname) end return t end -- Contains gi utilities. local gi = { IRepository = getface( 'GIRepository', 'IRepository', '', { 'require', 'find_by_name', 'get_n_infos', 'get_info' }), IBaseInfo = getface( 'GIRepository', nil, 'base_info_', { 'unref', 'get_type', 'get_name', 'is_deprecated', 'get_container', }), INFO_TYPE_FUNCTION = 1, INFO_TYPE_STRUCT = 3, INFO_TYPE_ENUM = 5, INFO_TYPE_OBJECT = 7, INFO_TYPE_INTERFACE = 8, INFO_TYPE_CONSTANT = 9, } local function load_baseinfo(target, info) -- Decide according to type. local type = gi.IBaseInfo.get_type(info) local name = gi.IBaseInfo.get_name(info) if type == gi.INFO_TYPE_CONSTANT or type == gi.INFO_TYPE_FUNCTION then target[name] = core.get_by_info(info) end end local ns_mt = { -- Tries to lookup symbol in all _enums in the namespace table. __index = function(ns, symbol) for _, enum in ns._enums do local value = enum[symbol] if value then return value end end end, } -- Creates namespace table bound to specified glib namespace. function core.new_namespace(name) local ns = { _enums = {}, _name = name } -- Recursively populate namespace using GI. gi.IRepository.require(nil, name); for i = 0, gi.IRepository.get_n_infos(nil, name) do local info = gi.IRepository.get_info(nil, name, i) load_baseinfo(ns, info) gi.IBaseInfo.unref(info) end -- Make sure that namespace table properly resolves unions. return setmetatable(ns, ns_mt) end
--[[-- Base lgi bootstrapper. Author: Pavel Holejsovsky Licence: MIT --]]-- local setmetatable, pairs, table = setmetatable, pairs, table local core = require 'lgi._core' module 'lgi' -- Helper for loading gi methods used only during bootstrapping. local function getface(namespace, interface, prefix, functions) local t = {} for _, func in pairs(functions) do local fname = prefix .. func t[func] = interface and core.get_by_name(namespace, interface, fname) or core.get_by_name(namespace, fname) end return t end -- Contains gi utilities. local gi = { IRepository = getface( 'GIRepository', 'IRepository', '', { 'require', 'find_by_name', 'get_n_infos', 'get_info' }), IBaseInfo = getface( 'GIRepository', nil, 'base_info_', { 'unref', 'get_type', 'get_name', 'is_deprecated', 'get_container', }), INFO_TYPE_FUNCTION = 1, INFO_TYPE_STRUCT = 3, INFO_TYPE_ENUM = 5, INFO_TYPE_OBJECT = 7, INFO_TYPE_INTERFACE = 8, INFO_TYPE_CONSTANT = 9, } local function load_baseinfo(target, info) -- Decide according to type. local type = gi.IBaseInfo.get_type(info) local name = gi.IBaseInfo.get_name(info) if type == gi.INFO_TYPE_CONSTANT or type == gi.INFO_TYPE_FUNCTION then target[name] = core.get_by_info(info) end end local ns_mt = { -- Tries to lookup symbol in all _enums in the namespace table. __index = function(ns, symbol) for _, enum in ns._enums do local value = enum[symbol] if value then return value end end end, } -- Creates namespace table bound to specified glib namespace. function core.new_namespace(name) local ns = { _enums = {}, _name = name } -- Recursively populate namespace using GI. gi.IRepository.require(nil, name); for i = 0, gi.IRepository.get_n_infos(nil, name) - 1 do local info = gi.IRepository.get_info(nil, name, i) load_baseinfo(ns, info) gi.IBaseInfo.unref(info) end -- Make sure that namespace table properly resolves unions. return setmetatable(ns, ns_mt) end
More loader fixes.
More loader fixes.
Lua
mit
zevv/lgi,psychon/lgi,pavouk/lgi
e5d5e2a7a2bc0ba957f3bd280ccee97de66744ce
tools/premake/android_studio/android_studio.lua
tools/premake/android_studio/android_studio.lua
-- Android Studio Premake Module -- Module interface local m = {} newaction { trigger = "android-studio", shortname = "Android Studio", description = "Generate Android Studio Gradle Files", toolset = "clang", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "SharedLib", "StaticLib", "Makefile", "Utility", "None" }, valid_languages = { "C", "C++" }, valid_tools = { cc = { "clang" }, }, } function workspace(wks) print("oh hai workspace") end function project(base, prj) print(base) print("oh hai project") end print("The android studio module has loaded!") -- Return module interface return m
-- Android Studio Premake Module -- Module interface local m = {} newaction { trigger = "android-studio", shortname = "Android Studio", description = "Generate Android Studio Gradle Files", toolset = "clang", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "SharedLib", "StaticLib", "Makefile", "Utility", "None" }, valid_languages = { "C", "C++" }, valid_tools = { cc = { "clang" }, }, onStart = function() print("Starting android studio generation") end, onWorkspace = function(wks) printf("Generating android studio workspace '%s'", wks.name) end, onProject = function(prj) printf("Generating android studio project '%s'", prj.name) end, execute = function() print("Executing android studio action") end, onEnd = function() print("Android studio generation complete") end } function m.workspace(wks) print("oh hai workspace") end function m.project(base, prj) print(base) print("oh hai project") end print("Premake: loaded module android-studio") -- Return module interface return m
fix premake generation always taking the android path, after adding module
fix premake generation always taking the android path, after adding module
Lua
mit
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
913fa262741d84deda352930448cfbee4f8434a8
config/nvim/lua/plugins/init.lua
config/nvim/lua/plugins/init.lua
local cmd = vim.cmd local g = vim.g local fn = vim.fn local utils = require("utils") local nmap = utils.nmap local plugLoad = fn["functions#PlugLoad"] local plugBegin = fn["plug#begin"] local plugEnd = fn["plug#end"] plugLoad() -- cmd('call functions#PlugLoad()') plugBegin("~/.config/nvim/plugged") -- NOTE: the argument passed to Plug has to be wrapped with single-quotes -- easy commenting cmd [[Plug 'tpope/vim-commentary']] -- bracket mappings for moving between buffers, quickfix items, etc. cmd [[Plug 'tpope/vim-unimpaired']] -- mappings to easily delete, change and add such surroundings in pairs, such as quotes, parens, etc. cmd [[Plug 'tpope/vim-surround']] -- endings for html, xml, etc. - ehances surround cmd [[Plug 'tpope/vim-ragtag']] -- enables repeating other supported plugins with the . command cmd [[Plug 'tpope/vim-repeat']] -- single/multi line code handler: gS - split one line into multiple, gJ - combine multiple lines into one cmd [[Plug 'AndrewRadev/splitjoin.vim']] -- detect indent style (tabs vs. spaces) cmd [[Plug 'tpope/vim-sleuth']] -- Startify: Fancy startup screen for vim {{{ cmd "Plug 'mhinz/vim-startify'" -- fugitive cmd [[Plug 'tpope/vim-fugitive']] cmd [[Plug 'tpope/vim-rhubarb']] nmap("<leader>gr", ":Gread<cr>") nmap("<leader>gb", ":G blame<cr>") -- general plugins -- emmet support for vim - easily create markdup wth CSS-like syntax cmd [[Plug 'mattn/emmet-vim']] -- match tags in html, similar to paren support cmd [[Plug 'gregsexton/MatchTag', { 'for': 'html' }]] -- html5 support cmd [[Plug 'othree/html5.vim', { 'for': 'html' }]] -- mustache support cmd [[Plug 'mustache/vim-mustache-handlebars']] -- pug / jade support cmd [[Plug 'digitaltoad/vim-pug', { 'for': ['jade', 'pug'] }]] -- nunjucks support cmd [[Plug 'niftylettuce/vim-jinja']] -- liquid support cmd [[Plug 'tpope/vim-liquid']] cmd [[Plug 'othree/yajs.vim', { 'for': [ 'javascript', 'javascript.jsx', 'html' ] }]] -- Plug 'pangloss/vim-javascript', { 'for': ['javascript', 'javascript.jsx', 'html'] } cmd [[Plug 'moll/vim-node', { 'for': 'javascript' }]] cmd [[Plug 'MaxMEllon/vim-jsx-pretty']] g.vim_jsx_pretty_highlight_close_tag = 1 cmd [[Plug 'leafgarland/typescript-vim', { 'for': ['typescript', 'typescript.tsx'] }]] cmd [[Plug 'wavded/vim-stylus', { 'for': ['stylus', 'markdown'] }]] cmd [[Plug 'groenewege/vim-less', { 'for': 'less' }]] cmd [[Plug 'hail2u/vim-css3-syntax', { 'for': 'css' }]] cmd [[Plug 'cakebaker/scss-syntax.vim', { 'for': 'scss' }]] cmd [[Plug 'stephenway/postcss.vim', { 'for': 'css' }]] cmd [[Plug 'udalov/kotlin-vim']] cmd("Plug 'tpope/vim-markdown', { 'for': 'markdown' }") g.markdown_fenced_languages = {tsx = "typescript.tsx"} -- Open markdown files in Marked.app - mapped to <leader>m cmd [[Plug 'itspriddle/vim-marked', { 'for': 'markdown', 'on': 'MarkedOpen' }]] nmap("<leader>m", ":MarkedOpen!<cr>") nmap("<leader>mq", ":MarkedQuit<cr>") nmap("<leader>*", "*<c-o>:%s///gn<cr>") cmd [[Plug 'elzr/vim-json', { 'for': 'json' }]] g.vim_json_syntax_conceal = 0 cmd [[Plug 'ekalinin/Dockerfile.vim']] cmd [[Plug 'jparise/vim-graphql']] cmd [[Plug 'hrsh7th/vim-vsnip']] -- TODO: set this plugin up cmd [[Plug 'sirVer/ultisnips']] g.UltiSnipsExpandTrigger = "<tab>" g.UltiSnipsJumpForwardTrigger = "<C-j>" g.UltiSnipsJumpBackwardTrigger = "<C-k>" -- Lua plugins cmd [[Plug 'norcalli/nvim-colorizer.lua']] cmd [[Plug 'kyazdani42/nvim-web-devicons']] cmd [[Plug 'nvim-lua/plenary.nvim']] cmd [[Plug 'kyazdani42/nvim-tree.lua']] cmd [[Plug 'lewis6991/gitsigns.nvim']] cmd [[Plug 'neovim/nvim-lspconfig']] cmd [[Plug 'kabouzeid/nvim-lspinstall']] cmd [[Plug 'hrsh7th/nvim-compe']] cmd [[Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}]] cmd [[Plug 'nvim-treesitter/playground']] cmd [[Plug 'nvim-treesitter/nvim-treesitter-textobjects']] cmd [[Plug 'p00f/nvim-ts-rainbow']] cmd [[Plug 'onsails/lspkind-nvim']] cmd [[Plug 'RRethy/nvim-base16']] cmd [[Plug 'glepnir/galaxyline.nvim' , {'branch': 'main'}]] cmd [[Plug 'windwp/nvim-autopairs']] cmd [[Plug 'mhartington/formatter.nvim']] cmd [[Plug 'alvarosevilla95/luatab.nvim']] cmd [[Plug 'SmiteshP/nvim-gps']] -- fzf cmd [[Plug $HOMEBREW_PREFIX . '/opt/fzf']] cmd [[Plug 'junegunn/fzf.vim']] cmd [[Plug 'folke/trouble.nvim']] plugEnd() require("nvim-autopairs").setup() require("colorizer").setup() require("plugins.gitsigns") require("plugins.trouble") require("plugins.fzf") require("plugins.lspconfig") require("plugins.completion") require("plugins.treesitter") require("plugins.nvimtree") require("plugins.galaxyline") require("plugins.formatter") require("plugins.tabline") require("plugins.startify")
local cmd = vim.cmd local g = vim.g local fn = vim.fn local utils = require("utils") local nmap = utils.nmap local plugLoad = fn["functions#PlugLoad"] local plugBegin = fn["plug#begin"] local plugEnd = fn["plug#end"] plugLoad() -- cmd('call functions#PlugLoad()') plugBegin("~/.config/nvim/plugged") -- NOTE: the argument passed to Plug has to be wrapped with single-quotes -- easy commenting cmd [[Plug 'tpope/vim-commentary']] -- bracket mappings for moving between buffers, quickfix items, etc. cmd [[Plug 'tpope/vim-unimpaired']] -- mappings to easily delete, change and add such surroundings in pairs, such as quotes, parens, etc. cmd [[Plug 'tpope/vim-surround']] -- endings for html, xml, etc. - ehances surround cmd [[Plug 'tpope/vim-ragtag']] -- enables repeating other supported plugins with the . command cmd [[Plug 'tpope/vim-repeat']] -- single/multi line code handler: gS - split one line into multiple, gJ - combine multiple lines into one cmd [[Plug 'AndrewRadev/splitjoin.vim']] -- detect indent style (tabs vs. spaces) cmd [[Plug 'tpope/vim-sleuth']] -- Startify: Fancy startup screen for vim {{{ cmd "Plug 'mhinz/vim-startify'" -- fugitive cmd [[Plug 'tpope/vim-fugitive']] cmd [[Plug 'tpope/vim-rhubarb']] nmap("<leader>gr", ":Gread<cr>") nmap("<leader>gb", ":G blame<cr>") -- general plugins -- emmet support for vim - easily create markdup wth CSS-like syntax cmd [[Plug 'mattn/emmet-vim']] -- match tags in html, similar to paren support cmd [[Plug 'gregsexton/MatchTag', { 'for': 'html' }]] -- html5 support cmd [[Plug 'othree/html5.vim', { 'for': 'html' }]] -- mustache support cmd [[Plug 'mustache/vim-mustache-handlebars']] -- pug / jade support cmd [[Plug 'digitaltoad/vim-pug', { 'for': ['jade', 'pug'] }]] -- nunjucks support cmd [[Plug 'niftylettuce/vim-jinja']] -- edit quickfix list cmd [[Plug 'itchyny/vim-qfedit']] -- liquid support cmd [[Plug 'tpope/vim-liquid']] cmd [[Plug 'othree/yajs.vim', { 'for': [ 'javascript', 'javascript.jsx', 'html' ] }]] -- Plug 'pangloss/vim-javascript', { 'for': ['javascript', 'javascript.jsx', 'html'] } cmd [[Plug 'moll/vim-node', { 'for': 'javascript' }]] cmd [[Plug 'MaxMEllon/vim-jsx-pretty']] g.vim_jsx_pretty_highlight_close_tag = 1 cmd [[Plug 'leafgarland/typescript-vim', { 'for': ['typescript', 'typescript.tsx'] }]] cmd [[Plug 'wavded/vim-stylus', { 'for': ['stylus', 'markdown'] }]] cmd [[Plug 'groenewege/vim-less', { 'for': 'less' }]] cmd [[Plug 'hail2u/vim-css3-syntax', { 'for': 'css' }]] cmd [[Plug 'cakebaker/scss-syntax.vim', { 'for': 'scss' }]] cmd [[Plug 'stephenway/postcss.vim', { 'for': 'css' }]] cmd [[Plug 'udalov/kotlin-vim']] cmd("Plug 'tpope/vim-markdown', { 'for': 'markdown' }") g.markdown_fenced_languages = {tsx = "typescript.tsx"} -- Open markdown files in Marked.app - mapped to <leader>m cmd [[Plug 'itspriddle/vim-marked', { 'for': 'markdown', 'on': 'MarkedOpen' }]] nmap("<leader>m", ":MarkedOpen!<cr>") nmap("<leader>mq", ":MarkedQuit<cr>") nmap("<leader>*", "*<c-o>:%s///gn<cr>") cmd [[Plug 'elzr/vim-json', { 'for': 'json' }]] g.vim_json_syntax_conceal = 0 cmd [[Plug 'ekalinin/Dockerfile.vim']] cmd [[Plug 'jparise/vim-graphql']] cmd [[Plug 'hrsh7th/vim-vsnip']] -- TODO: set this plugin up cmd [[Plug 'sirVer/ultisnips']] g.UltiSnipsExpandTrigger = "<tab>" g.UltiSnipsJumpForwardTrigger = "<C-j>" g.UltiSnipsJumpBackwardTrigger = "<C-k>" -- Lua plugins cmd [[Plug 'norcalli/nvim-colorizer.lua']] cmd [[Plug 'kyazdani42/nvim-web-devicons']] cmd [[Plug 'nvim-lua/plenary.nvim']] cmd [[Plug 'kyazdani42/nvim-tree.lua']] cmd [[Plug 'lewis6991/gitsigns.nvim']] cmd [[Plug 'neovim/nvim-lspconfig']] cmd [[Plug 'kabouzeid/nvim-lspinstall']] cmd [[Plug 'hrsh7th/nvim-compe']] cmd [[Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}]] cmd [[Plug 'nvim-treesitter/playground']] cmd [[Plug 'nvim-treesitter/nvim-treesitter-textobjects']] cmd [[Plug 'p00f/nvim-ts-rainbow']] cmd [[Plug 'onsails/lspkind-nvim']] cmd [[Plug 'RRethy/nvim-base16']] cmd [[Plug 'glepnir/galaxyline.nvim' , {'branch': 'main'}]] cmd [[Plug 'windwp/nvim-autopairs']] cmd [[Plug 'mhartington/formatter.nvim']] cmd [[Plug 'alvarosevilla95/luatab.nvim']] cmd [[Plug 'SmiteshP/nvim-gps']] -- fzf cmd [[Plug $HOMEBREW_PREFIX . '/opt/fzf']] cmd [[Plug 'junegunn/fzf.vim']] cmd [[Plug 'folke/trouble.nvim']] plugEnd() require("nvim-autopairs").setup() require("colorizer").setup() require("plugins.gitsigns") require("plugins.trouble") require("plugins.fzf") require("plugins.lspconfig") require("plugins.completion") require("plugins.treesitter") require("plugins.nvimtree") require("plugins.galaxyline") require("plugins.formatter") require("plugins.tabline") require("plugins.startify")
feat(vim): add qfedit plugin to edit quickfix lists
feat(vim): add qfedit plugin to edit quickfix lists
Lua
mit
nicknisi/dotfiles,nicknisi/dotfiles,nicknisi/dotfiles
85d5fd38ed34a506f26bca5b0f13c65c81cd9894
includes/server/nginx.lua
includes/server/nginx.lua
local time, ngx_print, ngx_var, ngx_req = os.time, ngx.print, ngx.var, ngx.req local explode, unescape = seawolf.text.explode, socket.url.unescape local trim = seawolf.text.trim env._SERVER = function (v) if v == 'QUERY_STRING' then return ngx_var.args elseif v == 'SCRIPT_NAME' then return ngx_var.uri elseif v == 'HTTP_HOST' then return ngx_req.get_headers()["Host"] elseif v == 'SERVER_NAME' then return ngx_var[v:lower()] else return ngx_var[v] end end local cookies, parsed, tmp, key, value = ngx_req.get_headers()['Cookie'] or '', {} cookies = explode(';', cookies) for _, v in pairs(cookies) do v = trim(v) if #v > 0 then tmp = explode('=', v) key = unescape((tmp[1] or ''):gsub('+', ' ')) value = unescape((tmp[2] or ''):gsub('+', ' ')) parsed[key] = value end end ophal.cookies = parsed function write(s) ngx.print(s) end io.write = write function headerCookieSetString(name, value, expires, path, domain) return ('%s=%s; domain=%s; expires=%s; path=%s'):format(name, value, domain, ngx.cookie_time(expires+time()), path) end function header(n, v) if type(v) == 'function' then v = v() end ngx.header[n] = v end --[[ Redirect to raw destination URL. ]] function redirect(dest_url, http_response_code) ngx.redirect(dest_url, http_response_code or 302) end do local body function request_get_body() local file = {} if body == nil then ngx.req.read_body() -- try from memory body = ngx.req.get_body_data() if body == nil then file.name = ngx.req.get_body_file() if file.name then file.handle = io.open(file.name) body = file.handle:read '*a' else body = '' end end end return body end end
local time, ngx_print, ngx_var, ngx_req = os.time, ngx.print, ngx.var, ngx.req local explode, unescape = seawolf.text.explode, socket.url.unescape local trim = seawolf.text.trim env._SERVER = function (v) if v == 'QUERY_STRING' then return ngx_var.args elseif v == 'SCRIPT_NAME' then return ngx_var.uri elseif v == 'HTTP_HOST' then return ngx_req.get_headers()["Host"] elseif v == 'SERVER_NAME' then return ngx_var[v:lower()] else return ngx_var[v] end end local cookies, parsed, tmp, key, value = ngx_req.get_headers()['Cookie'] or '', {} cookies = explode(';', cookies) for _, v in pairs(cookies) do v = trim(v) if #v > 0 then tmp = explode('=', v) key = unescape((tmp[1] or ''):gsub('+', ' ')) value = unescape((tmp[2] or ''):gsub('+', ' ')) parsed[key] = value end end ophal.cookies = parsed function write(s) ngx.print(s) end io.write = write function headerCookieSetString(name, value, expires, path, domain) return ('%s=%s; domain=%s; expires=%s; path=%s'):format(name, value, domain, ngx.cookie_time(expires+time()), path) end function header(n, v) if n == 'status' then ngx.status = v else if type(v) == 'function' then v = v() end ngx.header[n] = v end end --[[ Redirect to raw destination URL. ]] function redirect(dest_url, http_response_code) ngx.redirect(dest_url, http_response_code or 302) end do local body function request_get_body() local file = {} if body == nil then ngx.req.read_body() -- try from memory body = ngx.req.get_body_data() if body == nil then file.name = ngx.req.get_body_file() if file.name then file.handle = io.open(file.name) body = file.handle:read '*a' else body = '' end end end return body end end
Bug fix: HTTP header 'status' not being assigned on nginx.
Bug fix: HTTP header 'status' not being assigned on nginx.
Lua
agpl-3.0
ophal/core,ophal/core,coinzen/coinage,coinzen/coinage,coinzen/coinage,ophal/core
75141123f4caf0c9d187b4e2b4ba327ecde12b6c
build/LLVM.lua
build/LLVM.lua
-- Setup the LLVM dependency directories LLVMRootDir = "../../deps/llvm/" LLVMBuildDir = "../../deps/llvm/build/" -- TODO: Search for available system dependencies function SetupLLVMIncludes() local c = configuration() includedirs { path.join(LLVMRootDir, "include"), path.join(LLVMRootDir, "tools/clang/include"), path.join(LLVMRootDir, "tools/clang/lib"), path.join(LLVMBuildDir, "include"), path.join(LLVMBuildDir, "tools/clang/include"), } configuration(c) end function SetupLLVMLibs() local c = configuration() libdirs { path.join(LLVMBuildDir, "lib") } configuration { "Debug", "vs*" } libdirs { path.join(LLVMBuildDir, "Debug/lib") } configuration { "Release", "vs*" } libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") } configuration "not vs*" defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" } configuration "macosx" links { "c++", "curses", "pthread", "z" } configuration "*" links { "LLVMAnalysis", "LLVMAsmParser", "LLVMBitReader", "LLVMBitWriter", "LLVMCodeGen", "LLVMCore", "LLVMipa", "LLVMipo", "LLVMInstCombine", "LLVMInstrumentation", "LLVMIRReader", "LLVMLinker", "LLVMMC", "LLVMMCParser", "LLVMObjCARCOpts", "LLVMObject", "LLVMOption", "LLVMProfileData", "LLVMScalarOpts", "LLVMSupport", "LLVMTarget", "LLVMTransformUtils", "LLVMVectorize", "LLVMX86AsmParser", "LLVMX86AsmPrinter", "LLVMX86Desc", "LLVMX86Info", "LLVMX86Utils", "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic", "clangIndex", } configuration(c) end
-- Setup the LLVM dependency directories LLVMRootDir = "../../deps/llvm/" LLVMBuildDir = "../../deps/llvm/build/" -- TODO: Search for available system dependencies function SetupLLVMIncludes() local c = configuration() includedirs { path.join(LLVMRootDir, "include"), path.join(LLVMRootDir, "tools/clang/include"), path.join(LLVMRootDir, "tools/clang/lib"), path.join(LLVMBuildDir, "include"), path.join(LLVMBuildDir, "tools/clang/include"), } configuration(c) end function SetupLLVMLibs() local c = configuration() libdirs { path.join(LLVMBuildDir, "lib") } configuration { "Debug", "vs*" } libdirs { path.join(LLVMBuildDir, "Debug/lib") } configuration { "Release", "vs*" } libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") } configuration "not vs*" defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" } configuration "macosx" links { "c++", "curses", "pthread", "z" } configuration "*" links { "LLVMObjCARCOpts", "LLVMLinker", "LLVMipo", "LLVMVectorize", "LLVMBitWriter", "LLVMIRReader", "LLVMAsmParser", "LLVMOption", "LLVMInstrumentation", "LLVMProfileData", "LLVMX86AsmParser", "LLVMX86Desc", "LLVMObject", "LLVMMCParser", "LLVMBitReader", "LLVMX86Info", "LLVMX86AsmPrinter", "LLVMX86Utils", "LLVMCodeGen", "LLVMScalarOpts", "LLVMInstCombine", "LLVMTransformUtils", "LLVMipa", "LLVMAnalysis", "LLVMTarget", "LLVMMC", "LLVMCore", "LLVMSupport", "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic", "clangIndex", } configuration(c) end
build: fix llvm linking
build: fix llvm linking At least on linux with gcc the linking order of the libraries is important. Fix linking llvm libraries by changing the link order. Signed-off-by: Tomi Valkeinen <[email protected]>
Lua
mit
mydogisbox/CppSharp,mono/CppSharp,u255436/CppSharp,Samana/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,mono/CppSharp,SonyaSa/CppSharp,txdv/CppSharp,KonajuGames/CppSharp,SonyaSa/CppSharp,zillemarco/CppSharp,mydogisbox/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,zillemarco/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,inordertotest/CppSharp,Samana/CppSharp,genuinelucifer/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,genuinelucifer/CppSharp,mydogisbox/CppSharp,txdv/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,imazen/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,Samana/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,xistoso/CppSharp,KonajuGames/CppSharp,genuinelucifer/CppSharp,nalkaro/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,mono/CppSharp,mono/CppSharp,Samana/CppSharp,txdv/CppSharp,KonajuGames/CppSharp,imazen/CppSharp,inordertotest/CppSharp,KonajuGames/CppSharp,inordertotest/CppSharp,xistoso/CppSharp,nalkaro/CppSharp,imazen/CppSharp,mono/CppSharp,xistoso/CppSharp,KonajuGames/CppSharp,u255436/CppSharp,mydogisbox/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,mono/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,txdv/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,genuinelucifer/CppSharp,Samana/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,xistoso/CppSharp
524d1ed86cefa774f40e5fb4fa82e44b08706834
src_trunk/resources/realism-system/s_weapons_back.lua
src_trunk/resources/realism-system/s_weapons_back.lua
function createWeaponModelOnBack(x, y, z, weapon) local objectID = 355 if (weapon==31) then objectID = 356 elseif (weapon==30) then objectID = 355 end local currobject = getElementData(source, "weaponback.object") if (isElement(currobject)) then destroyElement(currobject) end local object = createObject(objectID, x, y, z) exports.pool:allocateElement(object) setElementData(source, "weaponback.object", object, false) attachElements(object, source, x, y, z, 0, 60, 0) end addEvent("createWeaponBackModel", true) addEventHandler("createWeaponBackModel", getRootElement(), createWeaponModelOnBack) function destroyWeaponModelOnBack() local currobject = getElementData(source, "weaponback.object") if (isElement(currobject)) then destroyElement(currobject) end end addEvent("destroyWeaponBackModel", true) addEventHandler("destroyWeaponBackModel", getRootElement(), destroyWeaponModelOnBack) addEventHandler("onPlayerQuit", getRootElement(), destroyWeaponModelOnBack) function interiorChange (pickup) local currobject = getElementData(source, "weaponback.object") local dimension = getElementData(pickup, "dbid") local interior = getElementData(pickup, "interior") local inttype = getElementData(pickup, "type") if (inttype=="interiorexit") then dimension = getElementData(pickup, "dimension") end if (currobject) then setElementInterior(currobject, interior) setElementDimension(currobject, dimension) end end addEventHandler("onPlayerInteriorEnter", getRootElement(), interiorChange) addEventHandler("onPlayerInteriorExit", getRootElement(), interiorChange)
function createWeaponModelOnBack(x, y, z, weapon) local objectID = 355 if (weapon==31) then objectID = 356 elseif (weapon==30) then objectID = 355 end local currobject = getElementData(source, "weaponback.object") if (isElement(currobject)) then destroyElement(currobject) end local object = createObject(objectID, x, y, z) exports.pool:allocateElement(object) setElementData(source, "weaponback.object", object, false) attachElements(object, source, x, y, z, 0, 60, 0) end addEvent("createWeaponBackModel", true) addEventHandler("createWeaponBackModel", getRootElement(), createWeaponModelOnBack) function destroyWeaponModelOnBack() local currobject = getElementData(source, "weaponback.object") if (isElement(currobject)) then destroyElement(currobject) end removeElementData(source, "weaponback.object") end addEvent("destroyWeaponBackModel", true) addEventHandler("destroyWeaponBackModel", getRootElement(), destroyWeaponModelOnBack) addEventHandler("onPlayerQuit", getRootElement(), destroyWeaponModelOnBack) function interiorChange (pickup) local currobject = getElementData(source, "weaponback.object") if (currobject) then local dimension = getElementData(pickup, "dbid") local interior = getElementData(pickup, "interior") local inttype = getElementData(pickup, "type") if (inttype=="interiorexit") then dimension = getElementData(pickup, "dimension") end setElementInterior(currobject, interior) setElementDimension(currobject, dimension) end end addEventHandler("onPlayerInteriorEnter", getRootElement(), interiorChange) addEventHandler("onPlayerInteriorExit", getRootElement(), interiorChange)
small fix
small fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1117 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
d7644d92a99a64d02f4c9b430411ed3076ab6179
transportation.lua
transportation.lua
--[[ This file is part of ClearTables @author Paul Norman <[email protected]> @copyright 2015-2016 Paul Norman, MIT license ]]-- --[[ Code for the transportation layers. These are some of the most complex. There's a few principles - Separate tables are needed for roads and rail - A way might appear in both if it's both a road and rail - z_order is consistent across highways and rail, allowing a UNION ALL to be done - Non-moterized lines are processed to avoid highway=path insanity ]]-- require "common" local highway = { motorway = {z=36, class="motorway", oneway="yes", motor_access="yes", bicycle="no", ramp="false"}, trunk = {z=35, class="trunk", motor_access="yes", ramp="false"}, primary = {z=34, class="primary", motor_access="yes", bicycle="yes", ramp="false"}, secondary = {z=33, class="secondary", motor_access="yes", bicycle="yes", ramp="false"}, tertiary = {z=32, class="tertiary", motor_access="yes", bicycle="yes", ramp="false"}, unclassified = {z=31, class="minor", motor_access="yes", bicycle="yes", ramp="false"}, residential = {z=31, class="minor", motor_access="yes", bicycle="yes", ramp="false"}, road = {z=31, class="unknown", motor_access="yes"}, living_street = {z=30, class="minor", motor_access="yes"}, motorway_link = {z=26, class="motorway", oneway="yes", motor_access="yes", ramp="true"}, trunk_link = {z=25, class="trunk", oneway="yes", motor_access="yes", ramp="true"}, primary_link = {z=24, class="primary", oneway="yes", motor_access="yes", ramp="true"}, secondary_link = {z=23, class="secondary", oneway="yes", motor_access="yes", ramp="true"}, tertiary_link = {z=22, class="tertiary", oneway="yes", motor_access="yes", ramp="true"}, service = {z=15, class="service", motor_access="yes", bicycle="yes"}, track = {z=12, class="track"}, pedestrian = {z=11, class="path", motor_access="no"}, path = {z=10, class="path", motor_access="no"}, footway = {z=10, class="path", motor_access="no"}, cycleway = {z=10, class="path", motor_access="no", bicycle="yes"}, steps = {z=10, class="path", motor_access="no"}, proposed = {z=1} } local railway = { rail = {z=44, class="rail"}, subway = {z=42, class="subway"}, narrow_gauge = {z=42, class="narrow_gauge"}, light_rail = {z=42, class="light_rail"}, preserved = {z=42, class="preserved"}, funicular = {z=42, class="funicular"}, monorail = {z=42, class="monorail"}, miniature = {z=42, class="miniature"}, turntable = {z=42, class="turntable"}, tram = {z=41, class="tram"}, disused = {z=40, class="disused"}, construction = {z=40, class="construction"} } --- Normalizes lane tags -- @param v The lane tag value -- @return An integer > 0 or nil for the lane tag function lanes (v) return v and string.find(v, "^%d+$") and tonumber(v) < 100 and tonumber(v) > 0 and v or nil end function brunnel (tags) return isset(tags["bridge"]) and "bridge" or isset(tags["tunnel"]) and "tunnel" or nil end function accept_road (tags) return highway[tags["highway"]] end function accept_rail (tags) return railway[tags["railway"]] end function accept_road_point (tags) return tags["highway"] and ( tags["highway"]== "crossing" or tags["highway"]== "traffic_signals" or tags["highway"]== "motorway_junction") end function transform_road_point (tags) local cols = {} cols.type = tags["highway"] cols.name = tags["name"] cols.names = names(tags) cols.ref = tags["ref"] return cols end function transform_road (tags) local cols = {} cols.name = tags["name"] cols.names = names(tags) cols.refs = split_list(tags["ref"]) if highway[tags["highway"]] then cols.class = highway[tags["highway"]]["class"] cols.ramp = highway[tags["highway"]]["ramp"] cols.oneway = oneway(tags["oneway"] or highway[tags["highway"]]["oneway"] or (tags["junction"] == "roundabout" and "yes") or nil) -- Build access tags, taking the first non-nil value from the access hiarchy, or if that fails, taking a sane default cols.motor_access = access(tags["motor_vehicle"] or tags["vehicle"] or tags["access"] or highway[tags["highway"]]["motor_access"]) cols.bicycle_access = access(tags["bicycle"] or tags["vehicle"] or tags["access"] or highway[tags["highway"]]["bicycle_access"]) cols.maxspeed = speed(tags["maxspeed"]) cols.brunnel = brunnel(tags) cols.layer = layer(tags["layer"]) cols.z_order = highway[tags["highway"]]["z"] or 0 end return cols end function transform_rail (tags) local cols = {} cols.name = tags["name"] cols.names = names(tags) if railway[tags["railway"]] then cols.class = railway[tags["railway"]]["class"] cols.brunnel = brunnel(tags) cols.layer = layer(tags["layer"]) cols.z_order = railway[tags["railway"]]["z"] or 0 end return cols end function road_ways (tags, num_keys) return generic_line_way(tags, accept_road, transform_road) end function road_area_ways (tags, num_keys) return generic_polygon_way(tags, accept_road, transform_road) -- uses the same accept/transform functions as lines end function road_area_rels (tags, num_keys) if (tags["type"] == "multipolygon" and accept_road(tags)) then return 0, tags end return 1, {} end function road_area_rel_members (tags, member_tags, member_roles, membercount) return generic_multipolygon_members(tags, member_tags, membercount, accept_road, transform_road) end function road_points (tags, num_keys) return generic_node(tags, accept_road_point, transform_road_point) end function rail_ways (tags, num_keys) return generic_line_way(tags, accept_rail, transform_rail) end
--[[ This file is part of ClearTables @author Paul Norman <[email protected]> @copyright 2015-2016 Paul Norman, MIT license ]]-- --[[ Code for the transportation layers. These are some of the most complex. There's a few principles - Separate tables are needed for roads and rail - A way might appear in both if it's both a road and rail - z_order is consistent across highways and rail, allowing a UNION ALL to be done - Non-moterized lines are processed to avoid highway=path insanity ]]-- require "common" local highway = { motorway = {z=36, class="motorway", oneway="yes", motor_access="yes", bicycle="no", ramp="false"}, trunk = {z=35, class="trunk", motor_access="yes", ramp="false"}, primary = {z=34, class="primary", motor_access="yes", bicycle="yes", ramp="false"}, secondary = {z=33, class="secondary", motor_access="yes", bicycle="yes", ramp="false"}, tertiary = {z=32, class="tertiary", motor_access="yes", bicycle="yes", ramp="false"}, unclassified = {z=31, class="minor", motor_access="yes", bicycle="yes", ramp="false"}, residential = {z=31, class="minor", motor_access="yes", bicycle="yes", ramp="false"}, road = {z=31, class="unknown", motor_access="yes"}, living_street = {z=30, class="minor", motor_access="yes"}, motorway_link = {z=26, class="motorway", oneway="yes", motor_access="yes", ramp="true"}, trunk_link = {z=25, class="trunk", oneway="yes", motor_access="yes", ramp="true"}, primary_link = {z=24, class="primary", oneway="yes", motor_access="yes", ramp="true"}, secondary_link = {z=23, class="secondary", oneway="yes", motor_access="yes", ramp="true"}, tertiary_link = {z=22, class="tertiary", oneway="yes", motor_access="yes", ramp="true"}, service = {z=15, class="service", motor_access="yes", bicycle="yes"}, track = {z=12, class="track"}, pedestrian = {z=11, class="path", motor_access="no"}, path = {z=10, class="path", motor_access="no"}, footway = {z=10, class="path", motor_access="no"}, cycleway = {z=10, class="path", motor_access="no", bicycle="yes"}, steps = {z=10, class="path", motor_access="no"}, proposed = {z=1} } local railway = { rail = {z=44, class="rail"}, subway = {z=42, class="subway"}, narrow_gauge = {z=42, class="narrow_gauge"}, light_rail = {z=42, class="light_rail"}, preserved = {z=42, class="preserved"}, funicular = {z=42, class="funicular"}, monorail = {z=42, class="monorail"}, miniature = {z=42, class="miniature"}, turntable = {z=42, class="turntable"}, tram = {z=41, class="tram"} } --- Normalizes lane tags -- @param v The lane tag value -- @return An integer > 0 or nil for the lane tag function lanes (v) return v and string.find(v, "^%d+$") and tonumber(v) < 100 and tonumber(v) > 0 and v or nil end function brunnel (tags) return isset(tags["bridge"]) and "bridge" or isset(tags["tunnel"]) and "tunnel" or nil end function accept_road (tags) return highway[tags["highway"]] end function accept_rail (tags) return railway[tags["railway"]] end function accept_road_point (tags) return tags["highway"] and ( tags["highway"]== "crossing" or tags["highway"]== "traffic_signals" or tags["highway"]== "motorway_junction") end function transform_road_point (tags) local cols = {} cols.type = tags["highway"] cols.name = tags["name"] cols.names = names(tags) cols.ref = tags["ref"] return cols end function transform_road (tags) local cols = {} cols.name = tags["name"] cols.names = names(tags) cols.refs = split_list(tags["ref"]) if highway[tags["highway"]] then cols.class = highway[tags["highway"]]["class"] cols.ramp = highway[tags["highway"]]["ramp"] cols.oneway = oneway(tags["oneway"] or highway[tags["highway"]]["oneway"] or (tags["junction"] == "roundabout" and "yes") or nil) -- Build access tags, taking the first non-nil value from the access hiarchy, or if that fails, taking a sane default cols.motor_access = access(tags["motor_vehicle"] or tags["vehicle"] or tags["access"] or highway[tags["highway"]]["motor_access"]) cols.bicycle_access = access(tags["bicycle"] or tags["vehicle"] or tags["access"] or highway[tags["highway"]]["bicycle_access"]) cols.maxspeed = speed(tags["maxspeed"]) cols.brunnel = brunnel(tags) cols.layer = layer(tags["layer"]) cols.z_order = highway[tags["highway"]]["z"] or 0 end return cols end function transform_rail (tags) local cols = {} cols.name = tags["name"] cols.names = names(tags) if railway[tags["railway"]] then cols.class = railway[tags["railway"]]["class"] cols.brunnel = brunnel(tags) cols.layer = layer(tags["layer"]) cols.z_order = railway[tags["railway"]]["z"] or 0 end return cols end function road_ways (tags, num_keys) return generic_line_way(tags, accept_road, transform_road) end function road_area_ways (tags, num_keys) return generic_polygon_way(tags, accept_road, transform_road) -- uses the same accept/transform functions as lines end function road_area_rels (tags, num_keys) if (tags["type"] == "multipolygon" and accept_road(tags)) then return 0, tags end return 1, {} end function road_area_rel_members (tags, member_tags, member_roles, membercount) return generic_multipolygon_members(tags, member_tags, membercount, accept_road, transform_road) end function road_points (tags, num_keys) return generic_node(tags, accept_road_point, transform_road_point) end function rail_ways (tags, num_keys) return generic_line_way(tags, accept_rail, transform_rail) end
Remove disused rail from rail table
Remove disused rail from rail table Fixes #31
Lua
mit
ClearTables/ClearTables,pnorman/ClearTables
674c0915d81526edbf8565428331816835594a1d
plugins/mod_auth_internal_hashed.lua
plugins/mod_auth_internal_hashed.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_internal_hashed"); local type = type; local error = error; local ipairs = ipairs; local hashes = require "util.hashes"; local jid_bare = require "util.jid".bare; local getAuthenticationDatabaseSHA1 = require "util.sasl.scram".getAuthenticationDatabaseSHA1; local config = require "core.configmanager"; local usermanager = require "core.usermanager"; local generate_uuid = require "util.uuid".generate; local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local hosts = hosts; -- COMPAT w/old trunk: remove these two lines before 0.8 release local hmac_sha1 = require "util.hmac".sha1; local sha1 = require "util.hashes".sha1; local to_hex; do local function replace_byte_with_hex(byte) return ("%02x"):format(byte:byte()); end function to_hex(binary_string) return binary_string:gsub(".", replace_byte_with_hex); end end local from_hex; do local function replace_hex_with_byte(hex) return string.char(tonumber(hex, 16)); end function from_hex(hex_string) return hex_string:gsub("..", replace_hex_with_byte); end end local prosody = _G.prosody; -- Default; can be set per-user local iteration_count = 4096; function new_hashpass_provider(host) local provider = { name = "internal_hashed" }; log("debug", "initializing hashpass authentication provider for host '%s'", host); function provider.test_password(username, password) local credentials = datamanager.load(username, host, "accounts") or {}; if credentials.password ~= nil and string.len(credentials.password) ~= 0 then if credentials.password ~= password then return nil, "Auth failed. Provided password is incorrect."; end if provider.set_password(username, credentials.password) == nil then return nil, "Auth failed. Could not set hashed password from plaintext."; else return true; end end if credentials.iteration_count == nil or credentials.salt == nil or string.len(credentials.salt) == 0 then return nil, "Auth failed. Stored salt and iteration count information is not complete."; end -- convert hexpass to stored_key and server_key -- COMPAT w/old trunk: remove before 0.8 release if credentials.hashpass then local salted_password = from_hex(credentials.hashpass); credentials.stored_key = sha1(hmac_sha1(salted_password, "Client Key"), true); credentials.server_key = to_hex(hmac_sha1(salted_password, "Server Key")); credentials.hashpass = nil datamanager.store(username, host, "accounts", credentials); end local valid, stored_key, server_key = getAuthenticationDatabaseSHA1(password, credentials.salt, credentials.iteration_count); local stored_key_hex = to_hex(stored_key); local server_key_hex = to_hex(server_key); if valid and stored_key_hex == credentials.stored_key and server_key_hex == credentials.server_key then return true; else return nil, "Auth failed. Invalid username, password, or password hash information."; end end function provider.set_password(username, password) local account = datamanager.load(username, host, "accounts"); if account then account.salt = account.salt or generate_uuid(); account.iteration_count = account.iteration_count or iteration_count; local valid, stored_key, server_key = getAuthenticationDatabaseSHA1(password, account.salt, account.iteration_count); local stored_key_hex = to_hex(stored_key); local server_key_hex = to_hex(server_key); account.stored_key = stored_key_hex account.server_key = server_key_hex account.password = nil; return datamanager.store(username, host, "accounts", account); end return nil, "Account not available."; end function provider.user_exists(username) local account = datamanager.load(username, host, "accounts"); if not account then log("debug", "account not found for username '%s' at host '%s'", username, module.host); return nil, "Auth failed. Invalid username"; end return true; end function provider.create_user(username, password) local salt = generate_uuid(); local valid, stored_key, server_key = getAuthenticationDatabaseSHA1(password, salt, iteration_count); local stored_key_hex = to_hex(stored_key); local server_key_hex = to_hex(server_key); return datamanager.store(username, host, "accounts", {stored_key = stored_key_hex, server_key = server_key_hex, salt = salt, iteration_count = iteration_count}); end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local testpass_authentication_profile = { plain_test = function(username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, password, realm), true; end, scram_sha_1 = function(username, realm) local credentials = datamanager.load(username, host, "accounts") or {}; if credentials.password then usermanager.set_password(username, credentials.password, host); credentials = datamanager.load(username, host, "accounts") or {}; end -- convert hexpass to stored_key and server_key -- COMPAT w/old trunk: remove before 0.8 release if credentials.hashpass then local salted_password = from_hex(credentials.hashpass); credentials.stored_key = sha1(hmac_sha1(salted_password, "Client Key"), true); credentials.server_key = to_hex(hmac_sha1(salted_password, "Server Key")); credentials.hashpass = nil datamanager.store(username, host, "accounts", credentials); end local stored_key, server_key, iteration_count, salt = credentials.stored_key, credentials.server_key, credentials.iteration_count, credentials.salt; stored_key = stored_key and from_hex(stored_key); server_key = server_key and from_hex(server_key); return stored_key, server_key, iteration_count, salt, true; end }; return new_sasl(realm, testpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_hashpass_provider(module.host));
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_internal_hashed"); local type = type; local error = error; local ipairs = ipairs; local hashes = require "util.hashes"; local jid_bare = require "util.jid".bare; local getAuthenticationDatabaseSHA1 = require "util.sasl.scram".getAuthenticationDatabaseSHA1; local config = require "core.configmanager"; local usermanager = require "core.usermanager"; local generate_uuid = require "util.uuid".generate; local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local hosts = hosts; -- COMPAT w/old trunk: remove these two lines before 0.8 release local hmac_sha1 = require "util.hmac".sha1; local sha1 = require "util.hashes".sha1; local to_hex; do local function replace_byte_with_hex(byte) return ("%02x"):format(byte:byte()); end function to_hex(binary_string) return binary_string:gsub(".", replace_byte_with_hex); end end local from_hex; do local function replace_hex_with_byte(hex) return string.char(tonumber(hex, 16)); end function from_hex(hex_string) return hex_string:gsub("..", replace_hex_with_byte); end end local prosody = _G.prosody; -- Default; can be set per-user local iteration_count = 4096; function new_hashpass_provider(host) local provider = { name = "internal_hashed" }; log("debug", "initializing hashpass authentication provider for host '%s'", host); function provider.test_password(username, password) local credentials = datamanager.load(username, host, "accounts") or {}; if credentials.password ~= nil and string.len(credentials.password) ~= 0 then if credentials.password ~= password then return nil, "Auth failed. Provided password is incorrect."; end if provider.set_password(username, credentials.password) == nil then return nil, "Auth failed. Could not set hashed password from plaintext."; else return true; end end if credentials.iteration_count == nil or credentials.salt == nil or string.len(credentials.salt) == 0 then return nil, "Auth failed. Stored salt and iteration count information is not complete."; end -- convert hexpass to stored_key and server_key -- COMPAT w/old trunk: remove before 0.8 release if credentials.hashpass then local salted_password = from_hex(credentials.hashpass); credentials.stored_key = sha1(hmac_sha1(salted_password, "Client Key"), true); credentials.server_key = to_hex(hmac_sha1(salted_password, "Server Key")); credentials.hashpass = nil datamanager.store(username, host, "accounts", credentials); end local valid, stored_key, server_key = getAuthenticationDatabaseSHA1(password, credentials.salt, credentials.iteration_count); local stored_key_hex = to_hex(stored_key); local server_key_hex = to_hex(server_key); if valid and stored_key_hex == credentials.stored_key and server_key_hex == credentials.server_key then return true; else return nil, "Auth failed. Invalid username, password, or password hash information."; end end function provider.set_password(username, password) local account = datamanager.load(username, host, "accounts"); if account then account.salt = account.salt or generate_uuid(); account.iteration_count = account.iteration_count or iteration_count; local valid, stored_key, server_key = getAuthenticationDatabaseSHA1(password, account.salt, account.iteration_count); local stored_key_hex = to_hex(stored_key); local server_key_hex = to_hex(server_key); account.stored_key = stored_key_hex account.server_key = server_key_hex account.password = nil; return datamanager.store(username, host, "accounts", account); end return nil, "Account not available."; end function provider.user_exists(username) local account = datamanager.load(username, host, "accounts"); if not account then log("debug", "account not found for username '%s' at host '%s'", username, module.host); return nil, "Auth failed. Invalid username"; end return true; end function provider.create_user(username, password) local salt = generate_uuid(); local valid, stored_key, server_key = getAuthenticationDatabaseSHA1(password, salt, iteration_count); local stored_key_hex = to_hex(stored_key); local server_key_hex = to_hex(server_key); return datamanager.store(username, host, "accounts", {stored_key = stored_key_hex, server_key = server_key_hex, salt = salt, iteration_count = iteration_count}); end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local testpass_authentication_profile = { plain_test = function(username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, password, realm), true; end, scram_sha_1 = function(username, realm) local credentials = datamanager.load(username, host, "accounts"); if not credentials then return; end if credentials.password then usermanager.set_password(username, credentials.password, host); credentials = datamanager.load(username, host, "accounts"); if not credentials then return; end end -- convert hexpass to stored_key and server_key -- COMPAT w/old trunk: remove before 0.8 release if credentials.hashpass then local salted_password = from_hex(credentials.hashpass); credentials.stored_key = sha1(hmac_sha1(salted_password, "Client Key"), true); credentials.server_key = to_hex(hmac_sha1(salted_password, "Server Key")); credentials.hashpass = nil datamanager.store(username, host, "accounts", credentials); end local stored_key, server_key, iteration_count, salt = credentials.stored_key, credentials.server_key, credentials.iteration_count, credentials.salt; stored_key = stored_key and from_hex(stored_key); server_key = server_key and from_hex(server_key); return stored_key, server_key, iteration_count, salt, true; end }; return new_sasl(realm, testpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_hashpass_provider(module.host));
mod_auth_internal_hashed: Fixed SCRAM-SHA-1 mechanism to not traceback on non-existent users.
mod_auth_internal_hashed: Fixed SCRAM-SHA-1 mechanism to not traceback on non-existent users.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
e8f8e6e7b206162c6358a8242518ce18eee82903
triangle/triangle_test.lua
triangle/triangle_test.lua
local Triangle = require('triangle') describe("Triangle", function() it("equilateral triangles have equal sides", function() assert.are.equals(Triangle.kind(2, 2, 2), "equilateral") end) it("larger equilateral triangles also have equal sides", function() assert.are.equals(Triangle.kind(10, 10, 10), "equilateral") end) it("isosceles triangles have last two sides equal", function() assert.are.equals(Triangle.kind(3, 4, 4), "isosceles") end) it("isosceles trianges have first and last sides equal", function() assert.are.equals(Triangle.kind(4, 3, 4), "isosceles") end) it("isosceles triangles have two first sides equal", function() assert.are.equals(Triangle.kind(4, 4, 3), "isosceles") end) it("isosceles triangles have in fact exactly two sides equal", function() assert.are.equals(Triangle.kind(10, 10, 2), "isosceles") end) it("scalene triangles have no equal sides", function() assert.are.equals(Triangle.kind(3, 4, 5), "scalene") end) it("scalene triangles have no equal sides at a larger scale too", function() assert.are.equals(Triangle.kind(10, 11, 12), "scalene") end) it("scalene triangles have no equal sides in descending order either", function() assert.are.equals(Triangle.kind(5, 4, 2), "scalene") end) it("very small triangles are legal", function() assert.are.equals(Triangle.kind(0.4, 0.6, 0.3), "scalene") end) it("test triangles with no size are illegal", function() assert.has_error(function() Triangle.kind(0, 0, 0) end, "Input Error") end) it("triangles with negative sides are illegal", function() assert.has_error(function() Triangle.kind(3, 4, -5) end, "Input Error") end) it("triangles violating triangle inequality are illegal", function() assert.has_error(function() Triangle.kind(1, 1, 3) end, "Input Error") end) it("triangles violating triangle inequality are illegal 2", function() assert.has_error(function() Triangle.kind(2, 4, 2) end, "Input Error") end) it("triangles violating triangle inequality are illegal 3", function() assert.has_error(function() Triangle.kind(7, 3, 2) end, "Input Error") end) end)
local Triangle = require('triangle') describe("Triangle", function() it("equilateral triangles have equal sides", function() assert.are.equals("equilateral", Triangle.kind(2, 2, 2)) end) it("larger equilateral triangles also have equal sides", function() assert.are.equals("equilateral", Triangle.kind(10, 10, 10)) end) it("isosceles triangles have last two sides equal", function() assert.are.equals("isosceles", Triangle.kind(3, 4, 4)) end) it("isosceles trianges have first and last sides equal", function() assert.are.equals("isosceles", Triangle.kind(4, 3, 4)) end) it("isosceles triangles have two first sides equal", function() assert.are.equals("isosceles", Triangle.kind(4, 4, 3)) end) it("isosceles triangles have in fact exactly two sides equal", function() assert.are.equals("isosceles", Triangle.kind(10, 10, 2)) end) it("scalene triangles have no equal sides", function() assert.are.equals("scalene", Triangle.kind(3, 4, 5)) end) it("scalene triangles have no equal sides at a larger scale too", function() assert.are.equals("scalene", Triangle.kind(10, 11, 12)) end) it("scalene triangles have no equal sides in descending order either", function() assert.are.equals("scalene", Triangle.kind(5, 4, 2)) end) it("very small triangles are legal", function() assert.are.equals("scalene", Triangle.kind(0.4, 0.6, 0.3)) end) it("test triangles with no size are illegal", function() assert.has_error(function() Triangle.kind(0, 0, 0) end, "Input Error") end) it("triangles with negative sides are illegal", function() assert.has_error(function() Triangle.kind(3, 4, -5) end, "Input Error") end) it("triangles violating triangle inequality are illegal", function() assert.has_error(function() Triangle.kind(1, 1, 3) end, "Input Error") end) it("triangles violating triangle inequality are illegal 2", function() assert.has_error(function() Triangle.kind(2, 4, 2) end, "Input Error") end) it("triangles violating triangle inequality are illegal 3", function() assert.has_error(function() Triangle.kind(7, 3, 2) end, "Input Error") end) end)
Fixed assertion order
Fixed assertion order
Lua
mit
ryanplusplus/xlua,exercism/xlua,fyrchik/xlua
20daf19a6a28c49fc1507a99353a082238662f30
src/cosy/tool/cli.lua
src/cosy/tool/cli.lua
package.path = package.path .. ";./?.lua" local Loader = require "cosy.loader.lua" {} local I18n = Loader.load "cosy.i18n" local Scheduler = Loader.load "cosy.scheduler" local Layer = Loader.require "layeredata" local Arguments = Loader.require "argparse" local Colors = Loader.require "ansicolors" local i18n = I18n.load { "cosy.tool", } local parser = Arguments () { name = "cosy-tool", description = i18n ["tool:description"] % {}, add_help = { action = function () end }, } parser:argument "tool" { description = i18n ["tool:tool:description"] % {}, } parser:argument "parameters" { args = "*", description = i18n ["tool:parameters:description"] % {}, } parser:require_command (false) local toolname do local arguments = { table.unpack (_G.arg)} local _exit = _G.os.exit _G.os.exit = function () end repeat local ok, args = parser:pparse (arguments) if ok then toolname = args.tool elseif args:match "^unknown option" then local option = args:match "^unknown option '(.*)'$" for i = 1, # arguments do if arguments [i]:find (option) == 1 then table.remove (arguments, i) break end end else break end until ok -- End of UGLY hack. _G.os.exit = _exit end do Layer.require = function (name) local package = name:gsub ("/", ".") if Layer.loaded [package] then return Layer.loaded [package] else local layer = Layer.new { name = name, data = { [Layer.key.labels] = { [name] = true, } } } local reference = Layer.reference (name) layer = require (package) (Layer, layer, reference) or layer return layer, reference end end end local mytool = toolname and Layer.require (toolname) or nil local parameters = {} if mytool then local parameter_type = mytool [Layer.key.meta].parameter_type local seen = {} local function find_parameters (x) if getmetatable (x) == Layer.Proxy then if parameter_type <= x then parameters [x] = true end seen [x] = true for _, v in pairs (x) do if not seen [v] then find_parameters (v) end end end end find_parameters (mytool) end local help = parser if mytool then parser = Arguments () { name = "cosy-tool", description = i18n ["tool:description"] % {}, add_help = { action = function () print "here" end }, } local command = parser:command (toolname) { description = mytool.description, } for key in pairs (parameters) do command:option ("--" .. key.name) { description = key.description .. (key.type and " (" .. tostring (key.type) .. ")" or ""), default = key.default, required = key.default and false or true, } end parser:require_command (true) help = command end local ok, arguments = parser:pparse () if not ok then print (arguments) print (help:get_help ()) os.exit (1) end local all_found = true for key in pairs (parameters) do if not arguments [key.name] then print ("Argument " .. key.name .. " is mandatory.") all_found = false else local value = arguments [key.name] if key.type == "string" then value = value elseif key.type == "number" then value = tonumber (value) elseif key.type == "boolean" and key.type:lower () == "true" then value = true elseif key.type == "boolean" and key.type:lower () == "false" then value = false elseif key.type == "function" then value = loadstring (value) () elseif getmetatable (key.type) == Layer.Proxy then if key.update then value = Layer.require (value) else value = { [Layer.key.refines] = { Layer.require (value) } } end else assert (false) end Layer.Proxy.replacewith (key, value) end end if not all_found then print (help:get_help ()) os.exit (1) end Scheduler.addthread (function () mytool.run { model = mytool, scheduler = Scheduler, } end) Scheduler.loop () do local filename = os.tmpname () local file = io.open (filename, "w") file:write (Layer.encode (mytool)) file:close () print (Colors ("%{green blackbg}" .. i18n ["tool:model-output"] % { filename = filename, })) end
package.path = package.path .. ";./?.lua" local Loader = require "cosy.loader.lua" {} local I18n = Loader.load "cosy.i18n" local Scheduler = Loader.load "cosy.scheduler" local Layer = Loader.require "layeredata" local Arguments = Loader.require "argparse" local Colors = Loader.require "ansicolors" local i18n = I18n.load { "cosy.tool", } local parser = Arguments () { name = "cosy-tool", description = i18n ["tool:description"] % {}, add_help = { action = function () end }, } parser:argument "tool" { description = i18n ["tool:tool:description"] % {}, } parser:argument "parameters" { args = "*", description = i18n ["tool:parameters:description"] % {}, } parser:require_command (false) local toolname do local arguments = { table.unpack (_G.arg)} local _exit = _G.os.exit _G.os.exit = function () end repeat local ok, args = parser:pparse (arguments) if ok then toolname = args.tool elseif args:match "^unknown option" then local option = args:match "^unknown option '(.*)'$" for i = 1, # arguments do if arguments [i]:find (option) == 1 then table.remove (arguments, i) break end end else break end until ok -- End of UGLY hack. _G.os.exit = _exit end do Layer.require = function (name) local package = name:gsub ("/", ".") if Layer.loaded [package] then return Layer.loaded [package] else local layer = Layer.new { name = name, data = { [Layer.key.labels] = { [name] = true, } } } local reference = Layer.reference (name) layer = require (package) (Layer, layer, reference) or layer return layer, reference end end end local loaded = {} for k in pairs (Layer.loaded) do loaded [k] = true end local mytool = toolname and Layer.require (toolname) or nil local parameters = {} if mytool then local parameter_type = mytool [Layer.key.meta].parameter_type local seen = {} local function find_parameters (x) if getmetatable (x) == Layer.Proxy then if parameter_type <= x then parameters [x] = true end seen [x] = true for _, v in pairs (x) do if not seen [v] then find_parameters (v) end end end end find_parameters (mytool) end local help = parser if mytool then parser = Arguments () { name = "cosy-tool", description = i18n ["tool:description"] % {}, add_help = { action = function () print "here" end }, } local command = parser:command (toolname) { description = mytool.description, } for key in pairs (parameters) do command:option ("--" .. key.name) { description = key.description .. (key.type and " (" .. tostring (key.type) .. ")" or ""), default = key.default, required = key.default and false or true, } end parser:require_command (true) help = command end local ok, arguments = parser:pparse () if not ok then print (arguments) print (help:get_help ()) os.exit (1) end local all_found = true for key in pairs (parameters) do if not arguments [key.name] then print ("Argument " .. key.name .. " is mandatory.") all_found = false else local value = arguments [key.name] if key.type == "string" then value = value elseif key.type == "number" then value = tonumber (value) elseif key.type == "boolean" and key.type:lower () == "true" then value = true elseif key.type == "boolean" and key.type:lower () == "false" then value = false elseif key.type == "function" then value = loadstring (value) () elseif getmetatable (key.type) == Layer.Proxy then if key.update then value = Layer.require (value) else value = { [Layer.key.refines] = { Layer.require (value) } } end else assert (false) end Layer.Proxy.replacewith (key, value) end end if not all_found then print (help:get_help ()) os.exit (1) end Scheduler.addthread (function () mytool.run { model = mytool, scheduler = Scheduler, } end) Scheduler.loop () do local directory = os.tmpname () os.execute ([[ rm -rf {{{directory}}} mkdir -p {{{directory}}} ]] % { directory = directory }) for name, model in pairs (Layer.loaded) do if not loaded [name] then local package = name:gsub ("/", ".") local file = assert (io.open (directory .. "/" .. package, "w")) file:write (Layer.encode (model)) file:close () end end print (Colors ("%{green blackbg}" .. i18n ["tool:model-output"] % { directory = directory, })) end
Dump all formalisms and models at the end of tool executions. Fix #191
Dump all formalisms and models at the end of tool executions. Fix #191
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
70bb5200cdbfdf9ab4a20e415cedf683cc67ccb4
test/runtest.lua
test/runtest.lua
-- See Copyright Notice in the file LICENSE do local path = "./?.lua;" if package.path:sub(1, #path) ~= path then package.path = path .. package.path end end local luatest = require "luatest" -- returns: number of failures local function test_library (libname, setfile, verbose) if verbose then print (("[lib: %s; file: %s]"):format (libname, setfile)) end local lib = require (libname) local f = require (setfile) local sets = f (libname) local n = 0 -- number of failures for _, set in ipairs (sets) do if verbose then print (set.Name or "Unnamed set") end local err = luatest.test_set (set, lib) if verbose then for _,v in ipairs (err) do print (" Test " .. v.i) luatest.print_results (v, " ") end end n = n + #err end if verbose then print "" end return n end local avail_tests = { posix = { lib = "rex_posix", "common_sets", "posix_sets", }, spencer = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" }, posix1 = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" }, tre = { lib = "rex_tre", "common_sets", "posix_sets", "spencer_sets" }, lord = { lib = "rex_lord", "common_sets", "posix_sets" }, maddock = { lib = "rex_maddock", "common_sets", "posix_sets", }, pcreposix = { lib = "rex_pcreposix","common_sets", "posix_sets", }, pcre = { lib = "rex_pcre", "common_sets", "pcre_sets", "pcre_sets2", }, pcre_nr = { lib = "rex_pcre_nr", "common_sets", "pcre_sets", "pcre_sets2", }, pcre45 = { lib = "rex_pcre45", "common_sets", "pcre_sets", "pcre_sets2", }, } do local verbose, tests, nerr = false, {}, 0 local dir -- check arguments for i = 1, select ("#", ...) do local arg = select (i, ...) if arg:sub(1,1) == "-" then if arg == "-v" then verbose = true else dir = arg:match("^%-d(.+)") end else if avail_tests[arg] then tests[#tests+1] = avail_tests[arg] else error ("invalid argument: [" .. arg .. "]") end end end assert (#tests > 0, "no library specified") -- give priority to libraries located in the specified directory if dir then dir = dir:gsub("[/\\]+$", "") for _, ext in ipairs {"dll", "so", "dylib"} do if package.cpath:match ("%?%." .. ext) then local cpath = dir .. "/?." .. ext .. ";" if package.cpath:sub(1, #cpath) ~= cpath then package.cpath = cpath .. package.cpath end break end end end -- do tests for _, test in ipairs (tests) do for _, setfile in ipairs (test) do nerr = nerr + test_library (test.lib, setfile, verbose) end end print ("Total number of failures: " .. nerr) end
-- See Copyright Notice in the file LICENSE do local path = "./?.lua;" if package.path:sub(1, #path) ~= path then package.path = path .. package.path end end local luatest = require "luatest" -- returns: number of failures local function test_library (libname, setfile, verbose) if verbose then print (("[lib: %s; file: %s]"):format (libname, setfile)) end local lib = require (libname) local f = require (setfile) local sets = f (libname) local n = 0 -- number of failures for _, set in ipairs (sets) do if verbose then print (set.Name or "Unnamed set") end local err = luatest.test_set (set, lib) if verbose then for _,v in ipairs (err) do print (" Test " .. v.i) luatest.print_results (v, " ") end end n = n + #err end if verbose then print "" end return n end local avail_tests = { posix = { lib = "rex_posix", "common_sets", "posix_sets", }, spencer = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" }, posix1 = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" }, tre = { lib = "rex_tre", "common_sets", "posix_sets", "spencer_sets" }, lord = { lib = "rex_lord", "common_sets", "posix_sets" }, maddock = { lib = "rex_maddock", "common_sets", "posix_sets", }, pcreposix = { lib = "rex_pcreposix","common_sets", "posix_sets", }, pcre = { lib = "rex_pcre", "common_sets", "pcre_sets", "pcre_sets2", }, pcre_nr = { lib = "rex_pcre_nr", "common_sets", "pcre_sets", "pcre_sets2", }, pcre45 = { lib = "rex_pcre45", "common_sets", "pcre_sets", "pcre_sets2", }, } do local verbose, tests, nerr = false, {}, 0 local dir -- check arguments for i = 1, select ("#", ...) do local arg = select (i, ...) if arg:sub(1,1) == "-" then if arg == "-v" then verbose = true elseif arg:sub(1,2) == "-d" then dir = arg:sub(3) end else if avail_tests[arg] then tests[#tests+1] = avail_tests[arg] else error ("invalid argument: [" .. arg .. "]") end end end assert (#tests > 0, "no library specified") -- give priority to libraries located in the specified directory if dir then dir = dir:gsub("[/\\]+$", "") for _, ext in ipairs {"dll", "so", "dylib"} do if package.cpath:match ("%?%." .. ext) then local cpath = dir .. "/?." .. ext .. ";" if package.cpath:sub(1, #cpath) ~= cpath then package.cpath = cpath .. package.cpath end break end end end -- do tests for _, test in ipairs (tests) do for _, setfile in ipairs (test) do nerr = nerr + test_library (test.lib, setfile, verbose) end end print ("Total number of failures: " .. nerr) end
small fix
small fix
Lua
mit
LuaDist/lrexlib-pcre,LuaDist/lrexlib-pcre,LuaDist/lrexlib-oniguruma,LuaDist/lrexlib-gnu,LuaDist/lrexlib-tre,LuaDist/lrexlib-oniguruma,LuaDist/lrexlib-gnu,LuaDist/lrexlib-posix,LuaDist/lrexlib-posix,StoneDot/lrexlib,StoneDot/lrexlib,LuaDist/lrexlib-tre
df6b54d2f57d1b50fee2f2b69f2118b266f65f37
worldedit_commands/mark.lua
worldedit_commands/mark.lua
worldedit.marker1 = {} worldedit.marker2 = {} worldedit.marker_region = {} --marks worldedit region position 1 worldedit.mark_pos1 = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos1 ~= nil then --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos1, pos1) end if worldedit.marker1[name] ~= nil then --marker already exists worldedit.marker1[name]:remove() --remove marker worldedit.marker1[name] = nil end if pos1 ~= nil then --add marker worldedit.marker1[name] = minetest.add_entity(pos1, "worldedit:pos1") if worldedit.marker1[name] ~= nil then worldedit.marker1[name]:get_luaentity().player_name = name end end worldedit.mark_region(name) end --marks worldedit region position 2 worldedit.mark_pos2 = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos2 ~= nil then --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos2, pos2) end if worldedit.marker2[name] ~= nil then --marker already exists worldedit.marker2[name]:remove() --remove marker worldedit.marker2[name] = nil end if pos2 ~= nil then --add marker worldedit.marker2[name] = minetest.add_entity(pos2, "worldedit:pos2") if worldedit.marker2[name] ~= nil then worldedit.marker2[name]:get_luaentity().player_name = name end end worldedit.mark_region(name) end worldedit.mark_region = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if worldedit.marker_region[name] ~= nil then --marker already exists --wip: make the area stay loaded somehow for _, entity in ipairs(worldedit.marker_region[name]) do entity:remove() end worldedit.marker_region[name] = nil end if pos1 ~= nil and pos2 ~= nil then local pos1, pos2 = worldedit.sort_pos(pos1, pos2) local thickness = 0.2 local sizex, sizey, sizez = (1 + pos2.x - pos1.x) / 2, (1 + pos2.y - pos1.y) / 2, (1 + pos2.z - pos1.z) / 2 --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos1, pos2) local markers = {} --XY plane markers for _, z in ipairs({pos1.z - 0.5, pos2.z + 0.5}) do local marker = minetest.add_entity({x=pos1.x + sizex - 0.5, y=pos1.y + sizey - 0.5, z=z}, "worldedit:region_cube") marker:set_properties({ visual_size={x=sizex * 2, y=sizey * 2}, collisionbox = {-sizex, -sizey, -thickness, sizex, sizey, thickness}, }) marker:get_luaentity().player_name = name table.insert(markers, marker) end --YZ plane markers for _, x in ipairs({pos1.x - 0.5, pos2.x + 0.5}) do local marker = minetest.add_entity({x=x, y=pos1.y + sizey - 0.5, z=pos1.z + sizez - 0.5}, "worldedit:region_cube") marker:set_properties({ visual_size={x=sizez * 2, y=sizey * 2}, collisionbox = {-thickness, -sizey, -sizez, thickness, sizey, sizez}, }) marker:setyaw(math.pi / 2) marker:get_luaentity().player_name = name table.insert(markers, marker) end worldedit.marker_region[name] = markers end end minetest.register_entity(":worldedit:pos1", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, physical = false, }, on_step = function(self, dtime) if worldedit.marker1[self.player_name] == nil then self.object:remove() end end, on_punch = function(self, hitter) self.object:remove() worldedit.marker1[self.player_name] = nil end, }) minetest.register_entity(":worldedit:pos2", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, physical = false, }, on_step = function(self, dtime) if worldedit.marker2[self.player_name] == nil then self.object:remove() end end, on_punch = function(self, hitter) self.object:remove() worldedit.marker2[self.player_name] = nil end, }) minetest.register_entity(":worldedit:region_cube", { initial_properties = { visual = "upright_sprite", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_cube.png"}, visual_size = {x=10, y=10}, physical = false, }, on_step = function(self, dtime) if worldedit.marker_region[self.player_name] == nil then self.object:remove() return end end, on_punch = function(self, hitter) for _, entity in ipairs(worldedit.marker_region[self.player_name]) do entity:remove() end worldedit.marker_region[self.player_name] = nil end, })
worldedit.marker1 = {} worldedit.marker2 = {} worldedit.marker_region = {} --marks worldedit region position 1 worldedit.mark_pos1 = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos1 ~= nil then --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos1, pos1) end if worldedit.marker1[name] ~= nil then --marker already exists worldedit.marker1[name]:remove() --remove marker worldedit.marker1[name] = nil end if pos1 ~= nil then --add marker worldedit.marker1[name] = minetest.add_entity(pos1, "worldedit:pos1") if worldedit.marker1[name] ~= nil then worldedit.marker1[name]:get_luaentity().player_name = name end end worldedit.mark_region(name) end --marks worldedit region position 2 worldedit.mark_pos2 = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos2 ~= nil then --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos2, pos2) end if worldedit.marker2[name] ~= nil then --marker already exists worldedit.marker2[name]:remove() --remove marker worldedit.marker2[name] = nil end if pos2 ~= nil then --add marker worldedit.marker2[name] = minetest.add_entity(pos2, "worldedit:pos2") if worldedit.marker2[name] ~= nil then worldedit.marker2[name]:get_luaentity().player_name = name end end worldedit.mark_region(name) end worldedit.mark_region = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if worldedit.marker_region[name] ~= nil then --marker already exists --wip: make the area stay loaded somehow for _, entity in ipairs(worldedit.marker_region[name]) do entity:remove() end worldedit.marker_region[name] = nil end if pos1 ~= nil and pos2 ~= nil then local pos1, pos2 = worldedit.sort_pos(pos1, pos2) local thickness = 0.2 local sizex, sizey, sizez = (1 + pos2.x - pos1.x) / 2, (1 + pos2.y - pos1.y) / 2, (1 + pos2.z - pos1.z) / 2 --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos1, pos2) local markers = {} --XY plane markers for _, z in ipairs({pos1.z - 0.5, pos2.z + 0.5}) do local marker = minetest.add_entity({x=pos1.x + sizex - 0.5, y=pos1.y + sizey - 0.5, z=z}, "worldedit:region_cube") marker:set_properties({ visual_size={x=sizex * 2, y=sizey * 2}, collisionbox = {-sizex, -sizey, -thickness, sizex, sizey, thickness}, }) marker:get_luaentity().player_name = name table.insert(markers, marker) end --YZ plane markers for _, x in ipairs({pos1.x - 0.5, pos2.x + 0.5}) do local marker = minetest.add_entity({x=x, y=pos1.y + sizey - 0.5, z=pos1.z + sizez - 0.5}, "worldedit:region_cube") marker:set_properties({ visual_size={x=sizez * 2, y=sizey * 2}, collisionbox = {-thickness, -sizey, -sizez, thickness, sizey, sizez}, }) marker:setyaw(math.pi / 2) marker:get_luaentity().player_name = name table.insert(markers, marker) end worldedit.marker_region[name] = markers end end minetest.register_entity(":worldedit:pos1", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, physical = false, }, on_step = function(self, dtime) if worldedit.marker1[self.player_name] == nil then self.object:remove() end end, on_punch = function(self, hitter) self.object:remove() worldedit.marker1[self.player_name] = nil end, }) minetest.register_entity(":worldedit:pos2", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, physical = false, }, on_step = function(self, dtime) if worldedit.marker2[self.player_name] == nil then self.object:remove() end end, on_punch = function(self, hitter) self.object:remove() worldedit.marker2[self.player_name] = nil end, }) minetest.register_entity(":worldedit:region_cube", { initial_properties = { visual = "upright_sprite", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_cube.png"}, visual_size = {x=10, y=10}, physical = false, }, on_step = function(self, dtime) if worldedit.marker_region[self.player_name] == nil then self.object:remove() return end end, on_punch = function(self, hitter) local markers = worldedit.marker_region[self.player_name] if not markers then return end for _, entity in ipairs(markers) do entity:remove() end worldedit.marker_region[self.player_name] = nil end, })
Fix blowing up TNT near worldedit markers
Fix blowing up TNT near worldedit markers
Lua
agpl-3.0
Uberi/Minetest-WorldEdit
51411a6e53703877fa0b9835e2c6846a0c9e37cc
applications/luci-samba/luasrc/model/cbi/samba.lua
applications/luci-samba/luasrc/model/cbi/samba.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("samba") s = m:section(TypedSection, "samba", "Samba") s.anonymous = true s:option(Value, "name") s:option(Value, "description") s:option(Value, "workgroup") s:option(Flag, "homes") s = m:section(TypedSection, "sambashare") s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s:option(Value, "name", translate("name")) s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab") s:option(Value, "users").rmempty = true ro = s:option(Flag, "read_only") ro.enabled = "yes" ro.disabled = "no" go = s:option(Flag, "guest_ok") go.enabled = "yes" go.disabled = "no" cm = s:option(Value, "create_mask") cm.rmempty = true cm.size = 4 dm = s:option(Value, "dir_mask") dm.rmempty = true dm.size = 4 return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("samba") s = m:section(TypedSection, "samba", "Samba") s.anonymous = true s:option(Value, "name") s:option(Value, "description") s:option(Value, "workgroup") s:option(Flag, "homes") s = m:section(TypedSection, "sambashare") s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s:option(Value, "name", translate("name")) s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab") s:option(Value, "users").rmempty = true ro = s:option(Flag, "read_only") ro.rmempty = false ro.enabled = "yes" ro.disabled = "no" go = s:option(Flag, "guest_ok") go.rmempty = false go.enabled = "yes" go.disabled = "no" cm = s:option(Value, "create_mask") cm.rmempty = true cm.size = 4 dm = s:option(Value, "dir_mask") dm.rmempty = true dm.size = 4 return m
Fix samba "read only" and "guest ok" settings not applied correctly.
Fix samba "read only" and "guest ok" settings not applied correctly.
Lua
apache-2.0
8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
b40cd8ee3ba056d10d00aed50ff8a5e8466f1aff
constants.lua
constants.lua
<<<<<<< HEAD PULL_LENGTH = 300; -- How far player can pull PULL_LENGTH2 = PULL_LENGTH * PULL_LENGTH; -- Square of how far player can pull PULL_FORCE = 400; -- Force at which the player pulls the ball PUSH_COST = 100; PUSH_COOLDOWN = 5; PUSH_LENGTH = 100; -- How far player can push PUSH_LENGTH2 = PUSH_LENGTH * PUSH_LENGTH; -- Square of how far player can push PUSH_FORCE = -800; -- Force at which the player pulls the ball PLAYER_FORCE = 5000; -- Force put on the player to move the joystick ======= PULL_LENGTH2 = 325 * 325; -- Square of how far player can pull PULL_FORCE = 500; -- Force at which the player pulls the ball PLAYER_FORCE = 6000; -- Force put on the player to move the joystick >>>>>>> bd6f266525af0ddd8a79843dc2e57216b037bbce PLAYER_DAMPENING = 5; -- Dampening on player movement PLAYER_DENSITY = 10; -- Player density (higher means more mass) PLAYER_HITPOINTS = 100; BALL_DAMAGE = 8; BALL_RADIUS = 8; BALL_DAMAGE_SPEED_SCALING = 450; -- Higher leads to less damage based on speed BALL_MAX_DAMAGE = 25; PLAYER_RADIUS = 16; -- Size of the player's circle <<<<<<< HEAD PLAYER_ENERGIE_GIVEN = 10; -- pull give energie to other PLAYER_ENERGIE_MAX = 10; -- pull give energie to other ======= PLAYER_INVULNERABILITY_DURATION = 1; -- Duration of invulnerability following a player's hit (s) >>>>>>> bd6f266525af0ddd8a79843dc2e57216b037bbce
PULL_LENGTH = 325; -- How far player can pull PULL_LENGTH2 = PULL_LENGTH * PULL_LENGTH; -- Square of how far player can pull PULL_FORCE = 500; -- Force at which the player pulls the ball PUSH_COST = 100; PUSH_COOLDOWN = 5; PUSH_LENGTH = 100; -- How far player can push PUSH_LENGTH2 = PUSH_LENGTH * PUSH_LENGTH; -- Square of how far player can push PUSH_FORCE = -800; -- Force at which the player pulls the ball PLAYER_FORCE = 6000; -- Force put on the player to move the joystick PLAYER_DAMPENING = 5; -- Dampening on player movement PLAYER_DENSITY = 10; -- Player density (higher means more mass) PLAYER_HITPOINTS = 100; BALL_DAMAGE = 8; BALL_RADIUS = 8; BALL_DAMAGE_SPEED_SCALING = 450; -- Higher leads to less damage based on speed BALL_MAX_DAMAGE = 25; PLAYER_RADIUS = 16; -- Size of the player's circle PLAYER_ENERGIE_GIVEN = 10; -- pull give energie to other PLAYER_ENERGIE_MAX = 10; -- pull give energie to other PLAYER_INVULNERABILITY_DURATION = 1; -- Duration of invulnerability following a player's hit (s)
fix my stuff
fix my stuff
Lua
mit
GuiSim/pixel
f5e7956e69ac581d2ed5bf5aa5e00ae7f3a28f4e
src/cosy/methods/i18n.lua
src/cosy/methods/i18n.lua
local Configuration = require "cosy.configuration" local Layer = require "layeredata" Configuration.load "cosy.methods" local result = { ["translation:failure"] = { "translation failed: {{{reason}}}", }, ["captcha:failure"] = { "captcha verification failed", }, ["method:administration-only"] = { "method is reserved to server administrator", }, ["server:information"] = { en = "show information about the server", }, ["server:list-methods"] = { en = "list all methods available on the server", }, ["server:tos"] = { en = "show the terms of service of the server", }, ["server:stop"] = { en = "stop the server", }, ["server:filter"] = { en = "run an iterator on the server", }, ["server:filter:not-enough"] = { en = "filtering requires {{{required}}} reputation, but only {{{owned}}} is owned", }, ["server:filter:error"] = { en = "filtering has failed, because {{{reason}}}", }, ["user:create"] = { en = "create a user account on the server", }, ["user:authenticate"] = { en = "authenticate a user", }, ["user:delete"] = { en = "delete your account", }, ["user:information"] = { en = "show user information", }, ["user:authentified-as"] = { en = "shows identified user", }, ["user:list"] = { en = "list all users", }, ["user:recover"] = { en = "recover your account", }, ["user:reset"] = { en = "reset your account", }, ["user:release"] = { en = "release a suspended user account", }, ["user:suspend"] = { en = "suspend a user account", }, ["user:send-validation"] = { en = "send (again) email validation", }, ["user:update"] = { en = "update user information", }, ["user:validate"] = { en = "validate email address", }, ["project:list"] = { en = "list projects", }, ["project:create"] = { en = "create a project", }, ["project:delete"] = { en = "delete a project", }, ["project:update"] = { en = "update project information", }, ["terms-of-service"] = { en = [[I agree to give my soul to CosyVerif.]], }, ["identifier:miss"] = { en = "identifier {{{identifier}}} does not exist", }, ["identifier:exist"] = { en = "identifier {{{identifier}}} exists already", }, ["email:exist"] = { en = "email {{{email}}} is already bound to an account", }, ["user:authenticate:failure"] = { en = "authentication failed", }, ["user:create:from"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:create:to"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:create:subject"] = { en = [=[[{{{servername}}}] Welcome, {{{identifier}}}!]=], }, ["user:create:body"] = { en = "{{{identifier}}}, we are happy to see you! Please click here to validate your email address <a href='http://{{{host}}}/?token={{{token}}}.", }, ["user:update:from"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:update:to"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:update:subject"] = { en = [=[[{{{servername}}}] Update, {{{identifier}}}!]=], }, ["user:update:body"] = { en = "{{{identifier}}}, please validate your email address using token {{{token}}}.", }, ["user:reset:from"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:reset:to"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:reset:subject"] = { en = [=[[{{{servername}}}] Welcome back, {{{identifier}}}!]=], }, ["user:reset:body"] = { en = "{{{identifier}}}, your validation token is <{{{validation}}}>.", }, ["user:reset:retry"] = { en = "reset failed, please try again later", }, ["user:suspend:not-user"] = { en = "account {{{identifier}}} is not a user", }, ["user:suspend:self"] = { en = "are you mad?", }, ["user:release:not-user"] = { en = "account {{{identifier}}} is not a user", }, ["user:suspend:not-suspended"] = { en = "account {{{identifier}}} is not suspended", }, ["user:release:self"] = { en = "nice try ;-)" }, ["user:suspend:not-enough"] = { en = "suspending a user requires {{{required}}} reputation, but only {{{owned}}} is owned", }, ["resource:exist"] = { en = "resource {{{name}}} exists already", }, ["resource:miss"] = { en = "resource {{{name}}} does not exist", }, ["resource:forbidden"] = { en = "restricted to resource owner", }, } for id, data in Layer.pairs (Configuration.resource.project ["/"]) do result [id .. ":create"] = { en = "create a " .. id, } result [id .. ":copy"] = { en = "copy a " .. id, } result [id .. ":delete"] = { en = "delete a " .. id, } end return result
local Configuration = require "cosy.configuration" local Layer = require "layeredata" Configuration.load "cosy.methods" local result = { ["translation:failure"] = { "translation failed: {{{reason}}}", }, ["captcha:failure"] = { "captcha verification failed", }, ["method:administration-only"] = { "method is reserved to server administrator", }, ["server:information"] = { en = "show information about the server", }, ["server:list-methods"] = { en = "list all methods available on the server", }, ["server:tos"] = { en = "show the terms of service of the server", }, ["server:stop"] = { en = "stop the server", }, ["server:filter"] = { en = "run an iterator on the server", }, ["server:filter:not-enough"] = { en = "filtering requires {{{required}}} reputation, but only {{{owned}}} is owned", }, ["server:filter:error"] = { en = "filtering has failed, because {{{reason}}}", }, ["user:create"] = { en = "create a user account on the server", }, ["user:authenticate"] = { en = "authenticate a user", }, ["user:delete"] = { en = "delete your account", }, ["user:information"] = { en = "show user information", }, ["user:authentified-as"] = { en = "shows identified user", }, ["user:list"] = { en = "list all users", }, ["user:recover"] = { en = "recover your account", }, ["user:reset"] = { en = "reset your account", }, ["user:release"] = { en = "release a suspended user account", }, ["user:suspend"] = { en = "suspend a user account", }, ["user:send-validation"] = { en = "send (again) email validation", }, ["user:update"] = { en = "update user information", }, ["user:validate"] = { en = "validate email address", }, ["project:list"] = { en = "list projects", }, ["project:create"] = { en = "create a project", }, ["project:delete"] = { en = "delete a project", }, ["project:update"] = { en = "update project information", }, ["terms-of-service"] = { en = [[I agree to give my soul to CosyVerif.]], }, ["identifier:miss"] = { en = "identifier {{{identifier}}} does not exist", }, ["identifier:exist"] = { en = "identifier {{{identifier}}} exists already", }, ["email:exist"] = { en = "email {{{email}}} is already bound to an account", }, ["user:authenticate:failure"] = { en = "authentication failed", }, ["user:create:from"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:create:to"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:create:subject"] = { en = [=[[{{{servername}}}] Welcome, {{{identifier}}}!]=], }, ["user:create:body"] = { en = "{{{identifier}}}, we are happy to see you! Please click here to validate your email address <a href='http://{{{host}}}/?token={{{token}}}.", }, ["user:update:from"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:update:to"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:update:subject"] = { en = [=[[{{{servername}}}] Update, {{{identifier}}}!]=], }, ["user:update:body"] = { en = "{{{identifier}}}, please validate your email address using token {{{token}}}.", }, ["user:reset:from"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:reset:to"] = { en = [["{{{name}}}" <{{{email}}}>]], }, ["user:reset:subject"] = { en = [=[[{{{servername}}}] Welcome back, {{{identifier}}}!]=], }, ["user:reset:body"] = { en = "{{{identifier}}}, your validation token is <{{{validation}}}>.", }, ["user:reset:retry"] = { en = "reset failed, please try again later", }, ["user:suspend:not-user"] = { en = "account {{{identifier}}} is not a user", }, ["user:suspend:self"] = { en = "are you mad?", }, ["user:release:not-user"] = { en = "account {{{identifier}}} is not a user", }, ["user:suspend:not-suspended"] = { en = "account {{{identifier}}} is not suspended", }, ["user:release:self"] = { en = "nice try ;-)" }, ["user:suspend:not-enough"] = { en = "suspending a user requires {{{required}}} reputation, but only {{{owned}}} is owned", }, ["resource:exist"] = { en = "resource {{{name}}} exists already", }, ["resource:miss"] = { en = "resource {{{name}}} does not exist", }, ["resource:forbidden"] = { en = "restricted to resource owner", }, } for id, data in Layer.pairs (Configuration.resource.project ["/"]) do local a = "a" if id:match "^[aeiou]" then a = "an" end a = a .. " " result [id .. ":create"] = { en = "create " .. a .. id, } result [id .. ":copy"] = { en = "copy " .. a .. id, } result [id .. ":delete"] = { en = "delete " .. a .. id, } end return result
Fix english messages for resource methods.
Fix english messages for resource methods.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
fab54e9f44459d535ca036748b21018e007c8e3a
.config/nvim/lua/config/nvim-tree.lua
.config/nvim/lua/config/nvim-tree.lua
local status_ok, nvim_tree = pcall(require, "nvim-tree") if not status_ok then return end vim.g.nvim_tree_icons = { default = "", symlink = "", git = { unstaged = "", staged = "", unmerged = "", renamed = "➜", untracked = "", deleted = "", ignored = "◌", }, folder = { arrow_open = "", arrow_closed = "", default = "", open = "", empty = "", empty_open = "", symlink = "", symlink_open = "", }, } nvim_tree.setup({ -- BEGIN_DEFAULT_OPTS auto_reload_on_write = true, disable_netrw = true, hijack_cursor = true, hijack_netrw = true, open_on_setup = true, view = { width = 30, mappings = { custom_only = true, list = { -- Default Mappings -- { key = { "<CR>", "o", "<2-LeftMouse>" }, action = "edit" }, -- { key = "<C-e>", action = "edit_in_place" }, -- { key = { "O" }, action = "edit_no_picker" }, { key = { "<2-RightMouse>", "<C-]>" }, action = "cd" }, { key = "<C-v>", action = "vsplit" }, { key = "<C-x>", action = "split" }, { key = "<C-t>", action = "tabnew" }, { key = "<", action = "prev_sibling" }, { key = ">", action = "next_sibling" }, { key = "P", action = "parent_node" }, -- { key = "<BS>", action = "close_node" }, { key = "<Tab>", action = "preview" }, { key = "K", action = "first_sibling" }, { key = "J", action = "last_sibling" }, { key = "I", action = "toggle_git_ignored" }, { key = "H", action = "toggle_dotfiles" }, { key = "R", action = "refresh" }, -- { key = "a", action = "create" }, { key = "d", action = "remove" }, { key = "D", action = "trash" }, { key = "r", action = "rename" }, { key = "<C-r>", action = "full_rename" }, { key = "x", action = "cut" }, { key = "c", action = "copy" }, { key = "p", action = "paste" }, { key = "y", action = "copy_name" }, { key = "Y", action = "copy_path" }, { key = "gy", action = "copy_absolute_path" }, -- { key = "[c", action = "prev_git_item" }, -- { key = "]c", action = "next_git_item" }, { key = "-", action = "dir_up" }, { key = "s", action = "system_open" }, -- { key = "f", action = "live_filter" }, -- { key = "F", action = "clear_live_filter" }, { key = "q", action = "close" }, -- { key = "g?", action = "toggle_help" }, -- { key = "W", action = "collapse_all" }, -- { key = "S", action = "search_node" }, { key = "<C-k>", action = "toggle_file_info" }, { key = ".", action = "run_file_command" }, -- Custom Mappings { key = { "O" }, action = "edit" }, { key = { "<CR>", "o", "l" }, action = "edit_no_picker" }, { key = { "<BS>", "h" }, action = "close_node" }, { key = "i", action = "create" }, { key = "[g", action = "prev_git_item" }, { key = "]g", action = "next_git_item" }, { key = "z", action = "collapse_all" }, { key = "?", action = "toggle_help" }, { key = "/", action = "live_filter" }, { key = "<C-x>", action = "clear_live_filter" }, }, }, }, renderer = { indent_markers = { enable = false, icons = { corner = "└ ", edge = "│ ", none = " ", }, }, icons = { webdev_colors = true, git_placement = "before", }, }, hijack_directories = { enable = true, auto_open = true, }, filters = { dotfiles = false, }, git = { enable = true, ignore = true, timeout = 400, }, actions = { use_system_clipboard = true, change_dir = { enable = false, global = false, restrict_above_cwd = false, }, }, trash = { cmd = "rm -rf", require_confirm = true, }, }) local opts = { noremap = true, silent = true } local keymap = vim.api.nvim_set_keymap keymap("n", "<Leader>e", "<Cmd>NvimTreeFindFileToggle<CR>", opts)
local status_ok, nvim_tree = pcall(require, "nvim-tree") if not status_ok then return end nvim_tree.setup({ -- BEGIN_DEFAULT_OPTS auto_reload_on_write = true, disable_netrw = true, hijack_cursor = true, hijack_netrw = true, open_on_setup = false, view = { width = 30, mappings = { custom_only = true, list = { -- Default Mappings -- { key = { "<CR>", "o", "<2-LeftMouse>" }, action = "edit" }, -- { key = "<C-e>", action = "edit_in_place" }, -- { key = { "O" }, action = "edit_no_picker" }, { key = { "<2-RightMouse>", "<C-]>" }, action = "cd" }, { key = "<C-v>", action = "vsplit" }, { key = "<C-x>", action = "split" }, { key = "<C-t>", action = "tabnew" }, { key = "<", action = "prev_sibling" }, { key = ">", action = "next_sibling" }, { key = "P", action = "parent_node" }, -- { key = "<BS>", action = "close_node" }, { key = "<Tab>", action = "preview" }, { key = "K", action = "first_sibling" }, { key = "J", action = "last_sibling" }, { key = "I", action = "toggle_git_ignored" }, { key = "H", action = "toggle_dotfiles" }, { key = "R", action = "refresh" }, -- { key = "a", action = "create" }, { key = "d", action = "remove" }, { key = "D", action = "trash" }, { key = "r", action = "rename" }, { key = "<C-r>", action = "full_rename" }, { key = "x", action = "cut" }, { key = "c", action = "copy" }, { key = "p", action = "paste" }, { key = "y", action = "copy_name" }, { key = "Y", action = "copy_path" }, { key = "gy", action = "copy_absolute_path" }, -- { key = "[c", action = "prev_git_item" }, -- { key = "]c", action = "next_git_item" }, { key = "-", action = "dir_up" }, { key = "s", action = "system_open" }, -- { key = "f", action = "live_filter" }, -- { key = "F", action = "clear_live_filter" }, { key = "q", action = "close" }, -- { key = "g?", action = "toggle_help" }, -- { key = "W", action = "collapse_all" }, -- { key = "S", action = "search_node" }, { key = "<C-k>", action = "toggle_file_info" }, { key = ".", action = "run_file_command" }, -- Custom Mappings { key = { "O" }, action = "edit" }, { key = { "<CR>", "o", "l" }, action = "edit_no_picker" }, { key = { "<BS>", "h" }, action = "close_node" }, { key = "i", action = "create" }, { key = "[g", action = "prev_git_item" }, { key = "]g", action = "next_git_item" }, { key = "z", action = "collapse_all" }, { key = "?", action = "toggle_help" }, { key = "/", action = "live_filter" }, { key = "<C-x>", action = "clear_live_filter" }, }, }, }, renderer = { indent_markers = { enable = false, icons = { corner = "└ ", edge = "│ ", none = " ", }, }, icons = { webdev_colors = true, git_placement = "before", glyphs = { default = "", symlink = "", git = { unstaged = "", staged = "", unmerged = "", renamed = "➜", untracked = "", deleted = "", ignored = "◌", }, folder = { arrow_open = "", arrow_closed = "", default = "", open = "", empty = "", empty_open = "", symlink = "", symlink_open = "", }, }, }, }, hijack_directories = { enable = true, auto_open = true, }, filters = { dotfiles = false, }, git = { enable = true, ignore = true, timeout = 400, }, actions = { use_system_clipboard = true, change_dir = { enable = false, global = false, restrict_above_cwd = false, }, }, trash = { cmd = "rm -rf", require_confirm = true, }, }) local opts = { noremap = true, silent = true } local keymap = vim.api.nvim_set_keymap keymap("n", "<Leader>e", "<Cmd>NvimTreeFindFileToggle<CR>", opts)
[nvim] Fix nvim-tree config
[nvim] Fix nvim-tree config
Lua
mit
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
af2c63c7c4d9c0a41af8a22b9a1c3838159e0962
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,Mashape/kong,Kong/kong,Kong/kong
2990fbc7cfa07522757a289f45fff3e1d63d670b
lualib/skynet/multicast.lua
lualib/skynet/multicast.lua
local skynet = require "skynet" local mc = require "skynet.multicast.core" local multicastd local multicast = {} local dispatch = setmetatable({} , {__mode = "kv" }) local chan = {} local chan_meta = { __index = chan, __gc = function(self) self:unsubscribe() end, __tostring = function (self) return string.format("[Multicast:%x]",self.channel) end, } local function default_conf(conf) conf = conf or {} conf.pack = conf.pack or skynet.pack conf.unpack = conf.unpack or skynet.unpack return conf end function multicast.new(conf) assert(multicastd, "Init first") local self = {} conf = conf or self self.channel = conf.channel if self.channel == nil then self.channel = skynet.call(multicastd, "lua", "NEW") end self.__pack = conf.pack or skynet.pack self.__unpack = conf.unpack or skynet.unpack self.__dispatch = conf.dispatch return setmetatable(self, chan_meta) end function chan:delete() local c = assert(self.channel) skynet.send(multicastd, "lua", "DEL", c) self.channel = nil self.__subscribe = nil end function chan:publish(...) local c = assert(self.channel) skynet.call(multicastd, "lua", "PUB", c, mc.pack(self.__pack(...))) end function chan:subscribe() local c = assert(self.channel) if self.__subscribe then -- already subscribe return end skynet.call(multicastd, "lua", "SUB", c) self.__subscribe = true dispatch[c] = self end function chan:unsubscribe() if not self.__subscribe then -- already unsubscribe return end local c = assert(self.channel) skynet.send(multicastd, "lua", "USUB", c) self.__subscribe = nil end local function dispatch_subscribe(channel, source, pack, msg, sz) local self = dispatch[channel] if not self then mc.close(pack) error ("Unknown channel " .. channel) end if self.__subscribe then local ok, err = pcall(self.__dispatch, self, source, self.__unpack(msg, sz)) mc.close(pack) assert(ok, err) else -- maybe unsubscribe first, but the message is send out. drop the message unneed mc.close(pack) end end local function init() multicastd = skynet.uniqueservice "multicastd" skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = mc.unpack, dispatch = dispatch_subscribe, } end skynet.init(init, "multicast") return multicast
local skynet = require "skynet" local mc = require "skynet.multicast.core" local multicastd local multicast = {} local dispatch = setmetatable({} , {__mode = "kv" }) local chan = {} local chan_meta = { __index = chan, __gc = function(self) self:unsubscribe() end, __tostring = function (self) return string.format("[Multicast:%x]",self.channel) end, } local function default_conf(conf) conf = conf or {} conf.pack = conf.pack or skynet.pack conf.unpack = conf.unpack or skynet.unpack return conf end function multicast.new(conf) assert(multicastd, "Init first") local self = {} conf = conf or self self.channel = conf.channel if self.channel == nil then self.channel = skynet.call(multicastd, "lua", "NEW") end self.__pack = conf.pack or skynet.pack self.__unpack = conf.unpack or skynet.unpack self.__dispatch = conf.dispatch return setmetatable(self, chan_meta) end function chan:delete() local c = assert(self.channel) skynet.send(multicastd, "lua", "DEL", c) self.channel = nil self.__subscribe = nil end function chan:publish(...) local c = assert(self.channel) skynet.call(multicastd, "lua", "PUB", c, mc.pack(self.__pack(...))) end function chan:subscribe() local c = assert(self.channel) if self.__subscribe then -- already subscribe return end skynet.call(multicastd, "lua", "SUB", c) self.__subscribe = true dispatch[c] = self end function chan:unsubscribe() if not self.__subscribe then -- already unsubscribe return end local c = assert(self.channel) skynet.send(multicastd, "lua", "USUB", c) self.__subscribe = nil end local function dispatch_subscribe(channel, source, pack, msg, sz) -- channel as session, do need response skynet.ignoreret() local self = dispatch[channel] if not self then mc.close(pack) error ("Unknown channel " .. channel) end if self.__subscribe then local ok, err = pcall(self.__dispatch, self, source, self.__unpack(msg, sz)) mc.close(pack) assert(ok, err) else -- maybe unsubscribe first, but the message is send out. drop the message unneed mc.close(pack) end end local function init() multicastd = skynet.uniqueservice "multicastd" skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = mc.unpack, dispatch = dispatch_subscribe, } end skynet.init(init, "multicast") return multicast
ignore response, fix #841
ignore response, fix #841
Lua
mit
cloudwu/skynet,firedtoad/skynet,bigrpg/skynet,sundream/skynet,icetoggle/skynet,ag6ag/skynet,wangyi0226/skynet,korialuo/skynet,jxlczjp77/skynet,JiessieDawn/skynet,zhouxiaoxiaoxujian/skynet,bigrpg/skynet,korialuo/skynet,pigparadise/skynet,great90/skynet,zhangshiqian1214/skynet,bttscut/skynet,sundream/skynet,great90/skynet,bigrpg/skynet,sanikoyes/skynet,hongling0/skynet,zhouxiaoxiaoxujian/skynet,bttscut/skynet,codingabc/skynet,firedtoad/skynet,zhangshiqian1214/skynet,JiessieDawn/skynet,xjdrew/skynet,xjdrew/skynet,xjdrew/skynet,firedtoad/skynet,Ding8222/skynet,xcjmine/skynet,codingabc/skynet,Ding8222/skynet,xcjmine/skynet,sundream/skynet,hongling0/skynet,JiessieDawn/skynet,Ding8222/skynet,hongling0/skynet,sanikoyes/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,cloudwu/skynet,cloudwu/skynet,wangyi0226/skynet,sanikoyes/skynet,great90/skynet,korialuo/skynet,ag6ag/skynet,icetoggle/skynet,wangyi0226/skynet,ag6ag/skynet,zhouxiaoxiaoxujian/skynet,zhangshiqian1214/skynet,xcjmine/skynet,codingabc/skynet,pigparadise/skynet,jxlczjp77/skynet,icetoggle/skynet,pigparadise/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,bttscut/skynet
1db4dab0c9b341f360fb2d5efb9a9df1a4294d28
Modules/qGUI/3DRender/GUIRender3D.lua
Modules/qGUI/3DRender/GUIRender3D.lua
local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local ScreenSpace = LoadCustomLibrary("ScreenSpace") local GUIRender3D = {} GUIRender3D.__index = GUIRender3D GUIRender3D.ClassName = "GUIRender3D" -- Renders a frame and its descendants in 3D space. -- @author Quenty function GUIRender3D.new(Frame) local self = setmetatable({}, GUIRender3D) self.Depth = -10 -- studs return self end function GUIRender3D:SetDepth(Depth) if Depth > 0 then warn("Depth > 0, will not render on screen @ " .. debug.traceback()) end self.Depth = Depth end function GUIRender3D:GetFrame() return self.Frame end function GUIRender3D:SetFrame(Frame) self.Frame = Frame or error() local Part = Instance.new("Part", workspace.CurrentCamera) Part.Archivable = false Part.FormFactor = "Custom" Part.CanCollide = false Part.Anchored = true Part.Name = Frame.Name .. "_3DRender" Part.Transparency = 1 self.Part = Part local SurfaceGui = Instance.new("SurfaceGui", Part) SurfaceGui.Adornee = Part SurfaceGui.Face = "Back" self.SurfaceGui = SurfaceGui local FakeFrame = Instance.new("Frame") FakeFrame.Parent = Frame.Parent FakeFrame.Name = "FakeFrame_" .. Frame.Name FakeFrame.BackgroundTransparency = 1; FakeFrame.Size = Frame.Size FakeFrame.Position = Frame.Position FakeFrame.SizeConstraint = Frame.SizeConstraint FakeFrame.Visible = true self.FakeFrame = FakeFrame Frame.Parent = self.SurfaceGui; Frame.Position = UDim2.new(0, 0, 0, 0) Frame.Size = UDim2.new(1, 0, 1, 0) Frame.SizeConstraint = "RelativeXY" self:UpdatePartSize() end function GUIRender3D:UpdatePartSize() local Size = self.FakeFrame.AbsoluteSize local WorldWidth = ScreenSpace.ScreenWidthToWorldWidth(Size.X, self.Depth) local WorldHeight = ScreenSpace.ScreenHeightToWorldHeight(Size.Y, self.Depth) self.Part.Size = Vector3.new(WorldWidth, WorldHeight, 0.2) self.SurfaceGui.CanvasSize = Size end function GUIRender3D:Hide() self.Part.Parent = nil end function GUIRender3D:Show() self.Part.Parent = workspace.CurrentCamera end function GUIRender3D:GetPrimaryCFrame() local Size = self.FakeFrame.AbsoluteSize local FrameCenter = self.FakeFrame.AbsolutePosition + Size/2 local Position = ScreenSpace.ScreenToWorldByWidthDepth(FrameCenter.X, FrameCenter.Y, Size.Y, self.Depth) return workspace.CurrentCamera.CoordinateFrame * CFrame.new(Position) * -- Transform by camera coordinates CFrame.new(0, 0, -self.Part.Size.Z/2) -- And take out the part size factor. end function GUIRender3D:Update() self:UpdatePartSize() self.Part.CFrame = self:GetPrimaryCFrame() end function GUIRender3D:Destroy() self.Part:Destroy() self.FakeFrame:Destroy() self.Frame:Destroy() self.Part, self.FakeFrame = nil, nil self.Frame = nil setmetatable(self, nil) end return GUIRender3D
local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local ScreenSpace = LoadCustomLibrary("ScreenSpace") local GUIRender3D = {} GUIRender3D.__index = GUIRender3D GUIRender3D.ClassName = "GUIRender3D" -- Renders a frame and its descendants in 3D space. -- @author Quenty function GUIRender3D.new(Frame) local self = setmetatable({}, GUIRender3D) self.Depth = -10 -- studs return self end function GUIRender3D:SetDepth(Depth) if Depth > 0 then warn("Depth > 0, will not render on screen @ " .. debug.traceback()) end self.Depth = Depth end function GUIRender3D:GetFrame() return self.Frame end function GUIRender3D:SetFrame(Frame) self.Frame = Frame or error() local Part = Instance.new("Part", workspace.CurrentCamera) Part.Archivable = false Part.FormFactor = "Custom" Part.CanCollide = false Part.Anchored = true Part.Name = Frame.Name .. "_3DRender" Part.Transparency = 1 self.Part = Part local SurfaceGui = Instance.new("SurfaceGui", Part) SurfaceGui.Adornee = Part SurfaceGui.Face = "Back" self.SurfaceGui = SurfaceGui local FakeFrame = Instance.new("Frame") FakeFrame.Parent = Frame.Parent FakeFrame.Name = "FakeFrame_" .. Frame.Name FakeFrame.BackgroundTransparency = 1; FakeFrame.Size = Frame.Size FakeFrame.Position = Frame.Position FakeFrame.SizeConstraint = Frame.SizeConstraint FakeFrame.Visible = true FakeFrame.Active = Frame.Active self.FakeFrame = FakeFrame Frame.Parent = self.SurfaceGui; Frame.Position = UDim2.new(0, 0, 0, 0) Frame.Size = UDim2.new(1, 0, 1, 0) Frame.SizeConstraint = "RelativeXY" self:UpdatePartSize() end function GUIRender3D:GetFakeFrame() return self.FakeFrame end function GUIRender3D:UpdatePartSize() local Size = self.FakeFrame.AbsoluteSize local WorldWidth = ScreenSpace.ScreenWidthToWorldWidth(Size.X, self.Depth) local WorldHeight = ScreenSpace.ScreenHeightToWorldHeight(Size.Y, self.Depth) self.Part.Size = Vector3.new(WorldWidth, WorldHeight, 0.2) self.SurfaceGui.CanvasSize = Size end function GUIRender3D:Hide() self.Part.Parent = nil end function GUIRender3D:Show() self.Part.Parent = workspace.CurrentCamera end function GUIRender3D:GetPrimaryCFrame() local Size = self.FakeFrame.AbsoluteSize local FrameCenter = self.FakeFrame.AbsolutePosition + Size/2 local Position = ScreenSpace.ScreenToWorldByWidthDepth(FrameCenter.X, FrameCenter.Y, Size.X, self.Depth) return workspace.CurrentCamera.CoordinateFrame * CFrame.new(Position) * -- Transform by camera coordinates CFrame.new(0, 0, -self.Part.Size.Z/2) -- And take out the part size factor. end function GUIRender3D:Update() self:UpdatePartSize() self.Part.CFrame = self:GetPrimaryCFrame() end function GUIRender3D:Destroy() self.Part:Destroy() self.FakeFrame:Destroy() self.Frame:Destroy() self.Part, self.FakeFrame = nil, nil self.Frame = nil setmetatable(self, nil) end return GUIRender3D
Fix ScreenWidth usage, add a way to retrieve the fake frame.
Fix ScreenWidth usage, add a way to retrieve the fake frame.
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
c5dedd5eb888d5b8fab596c880898022c4ca104e
src_trunk/resources/realism-system/c_nametags.lua
src_trunk/resources/realism-system/c_nametags.lua
local localPlayer = getLocalPlayer() local show = true function startRes(res) if (res==getThisResource()) then for key, value in ipairs(getElementsByType("player")) do setPlayerNametagShowing(value, false) end end end addEventHandler("onClientResourceStart", getRootElement(), startRes) function setNametagOnJoin() setPlayerNametagShowing(source, false) end addEventHandler("onClientPlayerJoin", getRootElement(), setNametagOnJoin) function renderNametags() if (show) then for key, player in ipairs(getElementsByType("player")) do if (isElement(player)) then local lx, ly, lz = getElementPosition(localPlayer) local rx, ry, rz = getElementPosition(player) local distance = getDistanceBetweenPoints3D(lx, ly, lz, rx, ry, rz) local limitdistance = 20 local reconx = getElementData(localPlayer, "reconx") if (player~=localPlayer) and (isElementOnScreen(player)) and ((distance<limitdistance) or reconx) then if not getElementData(player, "reconx") and not getElementData(player, "freecam:state") then local lx, ly, lz = getPedBonePosition(localPlayer, 7) local vehicle = getPedOccupiedVehicle(player) local collision = processLineOfSight(lx, ly, lz+1, rx, ry, rz, true, true, false, true, false, false, true, false, vehicle) if not (collision) or (reconx) then local x, y, z = getPedBonePosition(player, 7) local sx, sy = getScreenFromWorldPosition(x, y, z+0.45, 100, false) -- HP if (sx) and (sy) then local health = getElementHealth(player) if (health>0) then distance = distance / 5 if (distance<1) then distance = 1 end if (distance>2) then distance = 2 end if (reconx) then distance = 1 end local offset = 45 / distance -- DRAW BG dxDrawRectangle(sx-offset-5, sy, 95 / distance, 20 / distance, tocolor(0, 0, 0, 100), false) -- DRAW HEALTH local width = 85 local hpsize = (width / 100) * health local barsize = (width / 100) * (100-health) local color if (health>70) then color = tocolor(0, 255, 0, 130) elseif (health>35 and health<=70) then color = tocolor(255, 255, 0, 130) else color = tocolor(255, 0, 0, 130) end if (distance<1.2) then dxDrawRectangle(sx-offset, sy+5, hpsize/distance, 10 / distance, color, false) dxDrawRectangle((sx-offset)+(hpsize/distance), sy+5, barsize/distance, 10 / distance, tocolor(162, 162, 162, 100), false) else dxDrawRectangle(sx-offset, sy+5, hpsize/distance-5, 10 / distance-3, color, false) dxDrawRectangle((sx-offset)+(hpsize/distance-5), sy+5, barsize/distance-2, 10 / distance-3, tocolor(162, 162, 162, 100), false) end end end -- ARMOR --sx, sy2 = getScreenFromWorldPosition(x, y, z+0.25, 100, false) if (distance==1) then sy = sy + 30 elseif (distance<=1.5) then sy = sy + 20 else sy = sy + 10 end if (sx) and (sy) then local armor = getPedArmor(player) if (armor>0) then local offset = 45 / distance -- DRAW BG dxDrawRectangle(sx-offset-5, sy, 95 / distance, 20 / distance, tocolor(0, 0, 0, 100), false) -- DRAW HEALTH local width = 85 local armorsize = (width / 100) * armor local barsize = (width / 100) * (100-armor) if (distance<1.2) then dxDrawRectangle(sx-offset, sy+5, armorsize/distance, 10 / distance, tocolor(197, 197, 197, 130), false) dxDrawRectangle((sx-offset)+(armorsize/distance), sy+5, barsize/distance, 10 / distance, tocolor(162, 162, 162, 100), false) else dxDrawRectangle(sx-offset, sy+5, armorsize/distance-5, 10 / distance-3, tocolor(197, 197, 197, 130), false) dxDrawRectangle((sx-offset)+(armorsize/distance-5), sy+5, barsize/distance-2, 10 / distance-3, tocolor(162, 162, 162, 100), false) end end end -- NAME --sx, sy = getScreenFromWorldPosition(x, y, z+0.6, 100, false) --sy = sy - (60 - distance*10) if (distance==1) then sy = sy - 60 elseif (distance<=1.25) then sy = sy - 50 elseif (distance<=1.5) then sy = sy - 40 elseif (distance<=1.75) then sy = sy - 30 else sy = sy - 20 end if (sx) and (sy) then if (distance < 1) then distance = 1 end if (distance > 2) then distance = 2 end local offset = 65 / distance local scale = 0.6 / distance local font = "bankgothic" local r, g, b = getPlayerNametagColor(player) dxDrawText(getPlayerNametagText(player), sx-offset+2, sy+2, (sx-offset)+130 / distance, sy+20 / distance, tocolor(0, 0, 0, 220), scale, font, "center", "middle", false, false, false) dxDrawText(getPlayerNametagText(player), sx-offset, sy, (sx-offset)+130 / distance, sy+20 / distance, tocolor(r, g, b, 220), scale, font, "center", "middle", false, false, false) end end end end end end end end addEventHandler("onClientRender", getRootElement(), renderNametags) function hideNametags() show = false end addEvent("hidenametags", true) addEventHandler("hidenametags", getRootElement(), hideNametags) function showNametags() show = true end addEvent("shownametags", true) addEventHandler("shownametags", getRootElement(), showNametags)
local localPlayer = getLocalPlayer() local show = true function startRes(res) if (res==getThisResource()) then for key, value in ipairs(getElementsByType("player")) do setPlayerNametagShowing(value, false) end end end addEventHandler("onClientResourceStart", getRootElement(), startRes) function setNametagOnJoin() setPlayerNametagShowing(source, false) end addEventHandler("onClientPlayerJoin", getRootElement(), setNametagOnJoin) function renderNametags() if (show) then local players = { } local distances = { } local lx, ly, lz = getElementPosition(localPlayer) for key, player in ipairs(getElementsByType("player")) do if (isElement(player)) then local lx, ly, lz = getElementPosition(localPlayer) local rx, ry, rz = getElementPosition(player) local distance = getDistanceBetweenPoints3D(lx, ly, lz, rx, ry, rz) local limitdistance = 20 local reconx = getElementData(localPlayer, "reconx") if (player~=localPlayera) and (isElementOnScreen(player)) and ((distance<limitdistance) or reconx) then if not getElementData(player, "reconx") and not getElementData(player, "freecam:state") then local lx, ly, lz = getPedBonePosition(localPlayer, 7) local vehicle = getPedOccupiedVehicle(player) local collision = processLineOfSight(lx, ly, lz+1, rx, ry, rz, true, true, false, true, false, false, true, false, vehicle) if not (collision) or (reconx) then local x, y, z = getPedBonePosition(player, 7) local sx, sy = getScreenFromWorldPosition(x, y, z+0.45, 100, false) -- HP if (sx) and (sy) then --if (isPedInVehicle(player)) then sy = sy - 50 end local health = getElementHealth(player) if (health>0) then distance = distance / 5 if (distance<1) then distance = 1 end if (distance>2) then distance = 2 end if (reconx) then distance = 1 end local offset = 45 / distance -- DRAW BG dxDrawRectangle(sx-offset-5, sy, 95 / distance, 20 / distance, tocolor(0, 0, 0, 100), false) -- DRAW HEALTH local width = 85 local hpsize = (width / 100) * health local barsize = (width / 100) * (100-health) local color if (health>70) then color = tocolor(0, 255, 0, 130) elseif (health>35 and health<=70) then color = tocolor(255, 255, 0, 130) else color = tocolor(255, 0, 0, 130) end if (distance<1.2) then dxDrawRectangle(sx-offset, sy+5, hpsize/distance, 10 / distance, color, false) dxDrawRectangle((sx-offset)+(hpsize/distance), sy+5, barsize/distance, 10 / distance, tocolor(162, 162, 162, 100), false) else dxDrawRectangle(sx-offset, sy+5, hpsize/distance-5, 10 / distance-3, color, false) dxDrawRectangle((sx-offset)+(hpsize/distance-5), sy+5, barsize/distance-2, 10 / distance-3, tocolor(162, 162, 162, 100), false) end end end -- ARMOR --sx, sy2 = getScreenFromWorldPosition(x, y, z+0.25, 100, false) if (sx) and (sy) then if (distance==1) then sy = sy + 30 elseif (distance<=1.5) then sy = sy + 20 else sy = sy + 10 end if (sx) and (sy) then local armor = getPedArmor(player) if (armor>0) then local offset = 45 / distance -- DRAW BG dxDrawRectangle(sx-offset-5, sy, 95 / distance, 20 / distance, tocolor(0, 0, 0, 100), false) -- DRAW HEALTH local width = 85 local armorsize = (width / 100) * armor local barsize = (width / 100) * (100-armor) if (distance<1.2) then dxDrawRectangle(sx-offset, sy+5, armorsize/distance, 10 / distance, tocolor(197, 197, 197, 130), false) dxDrawRectangle((sx-offset)+(armorsize/distance), sy+5, barsize/distance, 10 / distance, tocolor(162, 162, 162, 100), false) else dxDrawRectangle(sx-offset, sy+5, armorsize/distance-5, 10 / distance-3, tocolor(197, 197, 197, 130), false) dxDrawRectangle((sx-offset)+(armorsize/distance-5), sy+5, barsize/distance-2, 10 / distance-3, tocolor(162, 162, 162, 100), false) end end end -- NAME --sx, sy = getScreenFromWorldPosition(x, y, z+0.6, 100, false) --sy = sy - (60 - distance*10) if (distance==1) then sy = sy - 60 elseif (distance<=1.25) then sy = sy - 50 elseif (distance<=1.5) then sy = sy - 40 elseif (distance<=1.75) then sy = sy - 30 else sy = sy - 20 end if (sx) and (sy) then if (distance < 1) then distance = 1 end if (distance > 2) then distance = 2 end local offset = 65 / distance local scale = 0.6 / distance local font = "bankgothic" local r, g, b = getPlayerNametagColor(player) dxDrawText(getPlayerNametagText(player), sx-offset+2, sy+2, (sx-offset)+130 / distance, sy+20 / distance, tocolor(0, 0, 0, 220), scale, font, "center", "middle", false, false, false) dxDrawText(getPlayerNametagText(player), sx-offset, sy, (sx-offset)+130 / distance, sy+20 / distance, tocolor(r, g, b, 220), scale, font, "center", "middle", false, false, false) end end end end end end end end end addEventHandler("onClientRender", getRootElement(), renderNametags) function hideNametags() show = false end addEvent("hidenametags", true) addEventHandler("hidenametags", getRootElement(), hideNametags) function showNametags() show = true end addEvent("shownametags", true) addEventHandler("shownametags", getRootElement(), showNametags)
More nametags fixes
More nametags fixes git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1173 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
07ab038935a500f450ec41a7055013df21e77c1b
OS/DiskOS/Libraries/map.lua
OS/DiskOS/Libraries/map.lua
local path = select(1,...) local strformat = string.format local function newMap(w,h,sheet) local Map = {} Map.w, Map.h = w or 24, h or 9 --Initialize the map table Map.m = {} for x=0, Map.w-1 do Map.m[x] = {} for y=0, Map.h-1 do Map.m[x][y] = 0 end end Map.sheet = sheet --If called with a function, it will be called on everycell with x,y,sprid args --The function can return an new sprid to set --If called with no args, it will return the map table. function Map:map(func,x,y,w,h) x,y,w,h = x or 0, y or 0, w or self.w, h or self.h assert(x >= 0, "Attempted to map out of bounds: x less than 0 ("..x..")") assert(y >= 0, "Attempted to map out of bounds: y less than 0 ("..y..")") assert(x+w <= self.w, "Attempted to map out of bounds: right side greater than map width (Width is "..self.w..", right side is "..x+w..")") assert(y+h <= self.h, "Attempted to map out of bounds: lower side greater than map height (Height is "..self.h..", lower side is "..y+h..")") if func then for iy=y, y+h-1 do for ix=x, x+w-1 do self.m[ix][iy] = func(ix,iy,self.m[ix][iy]) or self.m[ix][iy] end end end return self.m end function Map:cell(x,y,newID) if x >= self.w or y >= self.h or x < 0 or y < 0 then return false, "out of range" end if newID then self.m[x][y] = newID or 0 return self else return self.m[x][y] end end function Map:cut(x,y,w,h) local x,y,w,h = math.floor(x or 0), math.floor(y or 0), math.floor(w or self.w), math.floor(h or self.h) local nMap = newMap(w,h,self.sheet) local m = nMap:map() for my=y, y+h-1 do for mx=x, x+w-1 do if self.m[mx] and self.m[mx][my] then m[mx-x][my-y] = self.m[mx][my] end end end return nMap end function Map:size() return self.w, self.h end function Map:width() return self.w end function Map:height() return self.h end function Map:draw(dx,dy,x,y,w,h,sx,sy,sheet) local dx,dy,x,y,w,h,sx,sy = dx or 0, dy or 0, x or 0, y or 0, w or self.w, h or self.h, sx or 1, sy or 1 self:map(function(spx,spy,sprid) if sprid < 1 then return end spx, spy = spx-x, spy-y; (self.sheet or sheet):draw(sprid,dx + spx*8*sx, dy + spy*8*sy, 0, sx, sy) end,x,y,w,h) return self end function Map:export() local data = {strformat("LK12;TILEMAP;%dx%d;",self.w,self.h)} local datalen = 2 self:map(function(x,y,sprid) if x == 0 then data[datalen] = "\n" datalen = datalen + 1 end data[datalen] = sprid data[datalen+1] = ";" datalen = datalen+2 end) return table.concat(data) end function Map:import(data) if not data:sub(1,13) == "LK12;TILEMAP;" then error("Wrong header") end data = data:gsub("\n","") local w,h,mdata = string.match(data,"LK12;TILEMAP;(%d+)x(%d+);(.+)") local nextid = mdata:gmatch("(.-);") self:map(function(x,y,sprid) return 0 end) for y=0,h-1 do for x=0,w-1 do self:cell(x,y,tonumber(nextid() or "0")) end end return self end return Map end return newMap
local path = select(1,...) local strformat = string.format local function newMap(w,h,sheet) local Map = {} Map.w, Map.h = w or 24, h or 9 --Initialize the map table Map.m = {} for x=0, Map.w-1 do Map.m[x] = {} for y=0, Map.h-1 do Map.m[x][y] = 0 end end Map.sheet = sheet --If called with a function, it will be called on everycell with x,y,sprid args --The function can return an new sprid to set --If called with no args, it will return the map table. function Map:map(func,x,y,w,h) x,y,w,h = x or 0, y or 0, w or self.w, h or self.h assert(x >= 0, "Attempted to map out of bounds: x less than 0 ("..x..")") assert(y >= 0, "Attempted to map out of bounds: y less than 0 ("..y..")") assert(x+w <= self.w, "Attempted to map out of bounds: right side greater than map width (Width is "..self.w..", right side is "..x+w..")") assert(y+h <= self.h, "Attempted to map out of bounds: lower side greater than map height (Height is "..self.h..", lower side is "..y+h..")") if func then for iy=y, y+h-1 do for ix=x, x+w-1 do self.m[ix][iy] = func(ix,iy,self.m[ix][iy]) or self.m[ix][iy] end end end return self.m end function Map:cell(x,y,newID) if x >= self.w or y >= self.h or x < 0 or y < 0 then return false, "out of range" end if newID then self.m[x][y] = newID or 0 return self else return self.m[x][y] end end function Map:cut(x,y,w,h) local x,y,w,h = math.floor(x or 0), math.floor(y or 0), math.floor(w or self.w), math.floor(h or self.h) local nMap = newMap(w,h,self.sheet) local m = nMap:map() for my=y, y+h-1 do for mx=x, x+w-1 do if self.m[mx] and self.m[mx][my] then m[mx-x][my-y] = self.m[mx][my] end end end return nMap end function Map:size() return self.w, self.h end function Map:width() return self.w end function Map:height() return self.h end function Map:draw(dx,dy,x,y,w,h,sx,sy,sheet) local dx,dy,x,y,w,h,sx,sy = dx or 0, dy or 0, x or 0, y or 0, w or self.w, h or self.h, sx or 1, sy or 1 --mapX and mapY are different from x and y so that if x or y are less --than 0, the clamping doesn't affect the relative position of --the tiles on the screen. mapX = math.max(x,0) mapY = math.max(y,0) w = math.min(w+x,self.w)-x h = math.min(h+y,self.h)-y self:map(function(spx,spy,sprid) if sprid < 1 then return end spx, spy = spx-x, spy-y; (self.sheet or sheet):draw(sprid,dx + spx*8*sx, dy + spy*8*sy, 0, sx, sy) end,mapX,mapY,w,h) return self end function Map:export() local data = {strformat("LK12;TILEMAP;%dx%d;",self.w,self.h)} local datalen = 2 self:map(function(x,y,sprid) if x == 0 then data[datalen] = "\n" datalen = datalen + 1 end data[datalen] = sprid data[datalen+1] = ";" datalen = datalen+2 end) return table.concat(data) end function Map:import(data) if not data:sub(1,13) == "LK12;TILEMAP;" then error("Wrong header") end data = data:gsub("\n","") local w,h,mdata = string.match(data,"LK12;TILEMAP;(%d+)x(%d+);(.+)") local nextid = mdata:gmatch("(.-);") self:map(function(x,y,sprid) return 0 end) for y=0,h-1 do for x=0,w-1 do self:cell(x,y,tonumber(nextid() or "0")) end end return self end return Map end return newMap
Fixed bug with Map:draw function
Fixed bug with Map:draw function Map:draw now has automatic clamping. Former-commit-id: ad066c447683f700c105c8f68906077f5a223b8c
Lua
mit
RamiLego4Game/LIKO-12
f7f25c26ae1db48c918a71e7cbca870778ac857a
spec/resty/concurrent/timer_pool_executor_spec.lua
spec/resty/concurrent/timer_pool_executor_spec.lua
local TimerPoolExecutor = require('resty.concurrent.timer_pool_executor') local function yield() ngx.sleep(0) end local noop = function() end describe('TimerPoolExecutor', function() describe('worker garbage collection', function() it('automatically checks in back old workers', function() local pool = TimerPoolExecutor.new({ max_timers = 1 }) assert(pool:post(noop):wait(1)) yield() assert.equal(0, #pool) assert(pool:post(noop):wait(1)) end) it('puts back worker even when task crashes', function () local pool = TimerPoolExecutor.new({ max_timers = 1 }) assert(pool:post(error, 'message'):wait(1)) yield() assert.equal(0, #pool) assert(pool:post(error, 'message'):wait(1)) end) end) describe('fallback policies', function() it('can discard tasks', function() local pool = TimerPoolExecutor.new({ max_timers = 0, fallback_policy = 'discard' }) assert.returns_error('rejected execution', pool:post(noop)) end) it('can throw error', function() local pool = TimerPoolExecutor.new({ max_timers = 0, fallback_policy = 'abort' }) assert.has_error(function() pool:post(noop) end, 'rejected execution') end) it('can run within the caller', function() local pool = TimerPoolExecutor.new({ max_timers = 0, fallback_policy = 'caller_runs' }) local task = spy.new(function () return coroutine.running() end) assert(pool:post(task)) assert.spy(task).was_called(1) assert.spy(task).was_returned_with(coroutine.running()) end) end) end)
local TimerPoolExecutor = require('resty.concurrent.timer_pool_executor') local function yield() ngx.sleep(0) end local timeout = 10 local noop = function() end describe('TimerPoolExecutor', function() describe('worker garbage collection', function() it('automatically checks in back old workers', function() local pool = TimerPoolExecutor.new({ max_timers = 1 }) assert(pool:post(noop):wait(timeout)) yield() assert.equal(0, #pool) assert(pool:post(noop):wait(timeout)) end) it('puts back worker even when task crashes', function () local pool = TimerPoolExecutor.new({ max_timers = 1 }) assert(pool:post(error, 'message'):wait(timeout)) yield() assert.equal(0, #pool) assert(pool:post(error, 'message'):wait(timeout)) end) end) describe('fallback policies', function() it('can discard tasks', function() local pool = TimerPoolExecutor.new({ max_timers = 0, fallback_policy = 'discard' }) assert.returns_error('rejected execution', pool:post(noop)) end) it('can throw error', function() local pool = TimerPoolExecutor.new({ max_timers = 0, fallback_policy = 'abort' }) assert.has_error(function() pool:post(noop) end, 'rejected execution') end) it('can run within the caller', function() local pool = TimerPoolExecutor.new({ max_timers = 0, fallback_policy = 'caller_runs' }) local task = spy.new(function () return coroutine.running() end) assert(pool:post(task)) assert.spy(task).was_called(1) assert.spy(task).was_returned_with(coroutine.running()) end) end) end)
[spec] fix random failure in resty.concurrent spec
[spec] fix random failure in resty.concurrent spec sometimes tests would timeout, increasing the timeout to 10 seconds works
Lua
mit
3scale/docker-gateway,3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/apicast,3scale/apicast
39549bfce231528ec8d07b3546b0a7c1792a7e67
lua/job.lua
lua/job.lua
local _M = { _VERSION = "1.1.0" } local lock = require "resty.lock" local JOBS = ngx.shared.jobs local ipairs = ipairs local update_time = ngx.update_time local ngx_now = ngx.now local worker_exiting = ngx.worker.exiting local timer_at = ngx.timer.at local ngx_log = ngx.log local INFO, ERR, WARN = ngx.INFO, ngx.ERR, ngx.WARN local pcall, setmetatable = pcall, setmetatable local worker_pid = ngx.worker.pid local tinsert = table.insert local function now() update_time() return ngx_now() end local main local function run_job(delay, self, ...) if worker_exiting() then return self:finish() end local ok, err = timer_at(delay, main, self, ...) if not ok then ngx_log(ERR, self.key .. " failed to add timer: ", err) self:stop() self:clean() end end main = function(premature, self, ...) if premature then return self:finish() end if not self:running() then return end for _,other in ipairs(self.wait_others) do if not other:completed() then run_job(0.1, self, ...) return end end local mtx = lock:new("jobs", { timeout = 0.1, exptime = 600 }) local remains = mtx:lock(self.key .. ":mtx") if not remains then if self:running() then run_job(0.1, self, ...) end return end if self:suspended() then run_job(0.1, self, ...) mtx:unlock() return end if now() >= self:get_next_time() then local counter = JOBS:incr(self.key .. ":counter", 1, -1) local ok, err = pcall(self.callback, { counter = counter, hup = self.pid == nil }, ...) if not self.pid then self.pid = worker_pid() end if not ok then ngx_log(WARN, self.key, ": ", err) end self:set_next_time() end mtx:unlock() run_job(self:get_next_time() - now(), self, ...) end local job = {} -- public api function _M.new(name, callback, interval, finish) local j = { callback = callback, finish_fn = finish, interval = interval, key = name, wait_others = {}, pid = nil } return setmetatable(j, { __index = job }) end function job:run(...) if not self:completed() then ngx_log(INFO, "job ", self.key, " start") JOBS:set(self.key .. ":running", 1) self:set_next_time() return run_job(0, self, ...) end ngx_log(INFO, "job ", self.key, " already completed") return nil, "completed" end function job:suspend() if not self:suspended() then ngx_log(INFO, "job ", self.key, " suspended") JOBS:set(self.key .. ":suspended", 1) end end function job:resume() if self:suspended() then ngx_log(INFO, "job ", self.key, " resumed") JOBS:delete(self.key .. ":suspended") end end function job:stop() ngx_log(INFO, "job ", self.key, " stopped") JOBS:delete(self.key .. ":running") JOBS:set(self.key .. ":completed", 1) end function job:completed() return JOBS:get(self.key .. ":completed") == 1 end function job:running() return JOBS:get(self.key .. ":running") == 1 end function job:suspended() return JOBS:get(self.key .. ":suspended") == 1 end function job:finish() if self.finish_fn then self.finish_fn() end JOBS:delete(self.key .. ":running") end function job:wait_for(other) tinsert(self.wait_others, other) end function job:set_next_time() JOBS:set(self.key .. ":next", now() + self.interval) end function job:get_next_time() return JOBS:get(self.key .. ":next") end function job:clean() if not self:running() then JOBS:delete(self.key .. ":running") JOBS:delete(self.key .. ":completed") JOBS:delete(self.key .. ":suspended") return true end return false end return _M
local _M = { _VERSION = "1.1.0" } local lock = require "resty.lock" local JOBS = ngx.shared.jobs local ipairs = ipairs local update_time = ngx.update_time local ngx_now = ngx.now local worker_exiting = ngx.worker.exiting local timer_at = ngx.timer.at local ngx_log = ngx.log local INFO, ERR, WARN = ngx.INFO, ngx.ERR, ngx.WARN local pcall, setmetatable = pcall, setmetatable local worker_pid = ngx.worker.pid local tinsert = table.insert local function now() update_time() return ngx_now() end local main local function run_job(delay, self, ...) if worker_exiting() then return self:finish(...) end local ok, err = timer_at(delay, main, self, ...) if not ok then ngx_log(ERR, self.key .. " failed to add timer: ", err) self:stop() self:clean() end end main = function(premature, self, ...) if premature or not self:running() then return self:finish(...) end for _,other in ipairs(self.wait_others) do if not other:completed() then run_job(0.1, self, ...) return end end local mtx = lock:new("jobs", { timeout = 0.1, exptime = 600 }) local remains = mtx:lock(self.key .. ":mtx") if not remains then if self:running() then run_job(0.1, self, ...) end return end if self:suspended() then run_job(0.1, self, ...) mtx:unlock() return end if now() >= self:get_next_time() then local counter = JOBS:incr(self.key .. ":counter", 1, -1) local ok, err = pcall(self.callback, { counter = counter, hup = self.pid == nil }, ...) if not self.pid then self.pid = worker_pid() end if not ok then ngx_log(WARN, self.key, ": ", err) end self:set_next_time() end mtx:unlock() run_job(self:get_next_time() - now(), self, ...) end local job = {} -- public api function _M.new(name, callback, interval, finish) local j = { callback = callback, finish_fn = finish, interval = interval, key = name, wait_others = {}, pid = nil } return setmetatable(j, { __index = job }) end function job:run(...) if not self:completed() then ngx_log(INFO, "job ", self.key, " start") JOBS:set(self.key .. ":running", 1) self:set_next_time() return run_job(0, self, ...) end ngx_log(INFO, "job ", self.key, " already completed") return nil, "completed" end function job:suspend() if not self:suspended() then ngx_log(INFO, "job ", self.key, " suspended") JOBS:set(self.key .. ":suspended", 1) end end function job:resume() if self:suspended() then ngx_log(INFO, "job ", self.key, " resumed") JOBS:delete(self.key .. ":suspended") end end function job:stop() ngx_log(INFO, "job ", self.key, " stopped") JOBS:delete(self.key .. ":running") JOBS:set(self.key .. ":completed", 1) end function job:completed() return JOBS:get(self.key .. ":completed") == 1 end function job:running() return JOBS:get(self.key .. ":running") == 1 end function job:suspended() return JOBS:get(self.key .. ":suspended") == 1 end function job:finish(...) if self.finish_fn then self.finish_fn(...) end JOBS:delete(self.key .. ":running") end function job:wait_for(other) tinsert(self.wait_others, other) end function job:set_next_time() JOBS:set(self.key .. ":next", now() + self.interval) end function job:get_next_time() return JOBS:get(self.key .. ":next") end function job:clean() if not self:running() then JOBS:delete(self.key .. ":running") JOBS:delete(self.key .. ":completed") JOBS:delete(self.key .. ":suspended") return true end return false end return _M
job:finish fix
job:finish fix
Lua
bsd-2-clause
ZigzagAK/nginx-resty-auto-healthcheck-config,ZigzagAK/nginx-resty-auto-healthcheck-config
0508572f99d0fe5bc56c49e5a10e5f7810ed5421
src/apps/socket/unix.lua
src/apps/socket/unix.lua
--unix socket app: transmit and receive packets through a named socket. --can be used in server (listening) or client (connecting) mode. module(...,package.seeall) local ffi = require("ffi") local link = require("core.link") local packet = require("core.packet") local S = require("syscall") UnixSocket = {} UnixSocket.__index = UnixSocket local modes = {stream = "stream", packet = "dgram"} function UnixSocket:new (arg) -- Process args assert(arg, "filename or options expected") local file, listen, mode if type(arg) == "string" then file = arg else file = arg.filename listen = arg.listen mode = arg.mode end mode = assert(modes[mode or "stream"], "invalid mode") assert(file, "filename expected") -- Open/close socket local open, close if listen then --server mode local sock = assert(S.socket("unix", mode..", nonblock")) S.unlink(file) --unlink to avoid EINVAL on bind() local sa = S.t.sockaddr_un(file) assert(sock:bind(sa)) if mode == "stream" then assert(sock:listen()) end function close() sock:close() S.unlink(file) end function open() if mode == "dgram" then return sock end local sa = S.t.sockaddr_un() local csock, err = sock:accept(sa) if not csock then if err.AGAIN then return end assert(nil, err) end local close0 = close function close() csock:close() close0() end assert(csock:nonblock()) return csock end else --client mode local sock = assert(S.socket("unix", mode..", nonblock")) function open() local sa = S.t.sockaddr_un(file) local ok, err = sock:connect(sa) if not ok then if err.CONNREFUSED or err.AGAIN or err.NOENT then return end assert(nil, err) end return sock end function close() sock:close() end end -- Get connected socket local sock local function connect() sock = sock or open() return sock end -- App object local self = setmetatable({}, self) -- Preallocated buffer for the next packet. local rxp = packet.allocate() -- Try to read payload into rxp. -- Return true on success or false if no data is available. local function try_read () local bytes = S.read(sock, rxp.data, packet.max_payload) if bytes then rxp.length = bytes return true else return false end end function self:pull() connect() local l = self.output.tx local limit = engine.pull_npackets if sock and l ~= nil then while limit > 0 and try_read() do link.transmit(l, rxp) rxp = packet.allocate() limit = limit - 1 end end end function self:push() local l = self.input.rx if l ~= nil then -- Transmit all queued packets. -- Let the kernel drop them if it does not have capacity. while sock and not link.empty(l) do local p = link.receive(l) S.write(connect(), p.data, p.length) packet.free(p) end end end function self:stop() close() end return self end function selftest () print("selftest: socket/unix") local printapp = {} function printapp:new (name) return { push = function(self) local l = self.input.rx if l == nil then return end while not link.empty(l) do local p = link.receive(l) print(name..': ', p.length, ffi.string(p.data, p.length)) packet.free(p) end end } end local echoapp = {} function echoapp:new (text) return { pull = function(self) local l = self.output.tx if l == nil then return end for i=1,engine.pull_npackets do local p = packet.allocate() ffi.copy(p.data, text) p.length = #text link.transmit(l, p) end end } end local file = "/var/tmp/selftest.sock" local c = config.new() config.app(c, "server", UnixSocket, {filename = file, listen = true}) config.app(c, "client", UnixSocket, file) config.app(c, "print_client_tx", printapp, "client tx") config.app(c, "say_hello", echoapp, "hello ") config.link(c, "client.tx -> print_client_tx.rx") config.link(c, "say_hello.tx -> client.rx") config.link(c, "server.tx -> server.rx") engine.configure(c) engine.main({duration=0.1, report = {showlinks=true}}) print("selftest: done") end
--unix socket app: transmit and receive packets through a named socket. --can be used in server (listening) or client (connecting) mode. module(...,package.seeall) local ffi = require("ffi") local link = require("core.link") local packet = require("core.packet") local S = require("syscall") UnixSocket = {} UnixSocket.__index = UnixSocket local modes = {stream = "stream", packet = "dgram"} function UnixSocket:new (arg) -- Process args assert(arg, "filename or options expected") local file, listen, mode if type(arg) == "string" then file = arg else file = arg.filename listen = arg.listen mode = arg.mode end mode = assert(modes[mode or "stream"], "invalid mode") assert(file, "filename expected") -- Open/close socket local open, close if listen then --server mode local sock = assert(S.socket("unix", mode..", nonblock")) S.unlink(file) --unlink to avoid EINVAL on bind() local sa = S.t.sockaddr_un(file) assert(sock:bind(sa)) if mode == "stream" then assert(sock:listen()) end function close() sock:close() S.unlink(file) end function open() if mode == "dgram" then return sock end local sa = S.t.sockaddr_un() local csock, err = sock:accept(sa) if not csock then if err.AGAIN then return end assert(nil, err) end local close0 = close function close() csock:close() close0() end assert(csock:nonblock()) return csock end else --client mode local sock = assert(S.socket("unix", mode..", nonblock")) function open() local sa = S.t.sockaddr_un(file) local ok, err = sock:connect(sa) if not ok then if err.CONNREFUSED or err.AGAIN or err.NOENT then return end assert(nil, err) end return sock end function close() sock:close() end end -- Get connected socket local sock local function connect() sock = sock or open() return sock end -- App object local self = setmetatable({}, self) -- Preallocated buffer for the next packet. local rxp = packet.allocate() -- Try to read payload into rxp. -- Return true on success or false if no data is available. local function try_read () local bytes = S.read(sock, rxp.data, packet.max_payload) -- Error, likely EAGAIN if not bytes then return false end -- EOF, reset sock if bytes == 0 then sock = nil return false end rxp.length = bytes return true end function self:pull() connect() local l = self.output.tx local limit = engine.pull_npackets if sock and l ~= nil then while limit > 0 and try_read() do link.transmit(l, rxp) rxp = packet.allocate() limit = limit - 1 end end end function self:push() local l = self.input.rx if l ~= nil then -- Transmit all queued packets. -- Let the kernel drop them if it does not have capacity. while sock and not link.empty(l) do local p = link.receive(l) S.write(connect(), p.data, p.length) packet.free(p) end end end function self:stop() close() end return self end function selftest () print("selftest: socket/unix") local printapp = {} function printapp:new (name) return { push = function(self) local l = self.input.rx if l == nil then return end while not link.empty(l) do local p = link.receive(l) print(name..': ', p.length, ffi.string(p.data, p.length)) packet.free(p) end end } end local echoapp = {} function echoapp:new (text) return { pull = function(self) local l = self.output.tx if l == nil then return end for i=1,engine.pull_npackets do local p = packet.allocate() ffi.copy(p.data, text) p.length = #text link.transmit(l, p) end end } end local file = "/var/tmp/selftest.sock" local c = config.new() config.app(c, "server", UnixSocket, {filename = file, listen = true}) config.app(c, "client", UnixSocket, file) config.app(c, "print_client_tx", printapp, "client tx") config.app(c, "say_hello", echoapp, "hello ") config.link(c, "client.tx -> print_client_tx.rx") config.link(c, "say_hello.tx -> client.rx") config.link(c, "server.tx -> server.rx") engine.configure(c) engine.main({duration=0.1, report = {showlinks=true}}) print("selftest: done") end
Fix Unix socket EOF handling
Fix Unix socket EOF handling Signed-off-by: Ben Agricola <[email protected]>
Lua
apache-2.0
alexandergall/snabbswitch,eugeneia/snabbswitch,dpino/snabb,snabbco/snabb,Igalia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,dpino/snabb,Igalia/snabb,Igalia/snabb,dpino/snabbswitch,dpino/snabb,Igalia/snabb,dpino/snabb,Igalia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,dpino/snabb,snabbco/snabb,eugeneia/snabbswitch,eugeneia/snabbswitch,Igalia/snabb,eugeneia/snabb,eugeneia/snabb,dpino/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,dpino/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,dpino/snabb,Igalia/snabb,eugeneia/snabb,dpino/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,snabbco/snabb,dpino/snabbswitch,snabbco/snabb,SnabbCo/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,snabbco/snabb
9904ae3bda3bf82d03470ffcfbb495b55af0b7bc
mods/death_messages/init.lua
mods/death_messages/init.lua
----------------------------------------------------------------------------------------------- local title = "Death Messages" local version = "0.1.2" local mname = "death_messages" ----------------------------------------------------------------------------------------------- dofile(minetest.get_modpath("death_messages").."/settings.txt") ----------------------------------------------------------------------------------------------- -- A table of quips for death messages local messages = {} -- Fill this table with sounds local sounds = { [1] = "death_messages_player_1", [2] = "death_messages_player_2", } -- Lava death messages messages.lava = { " pensait que la lave etait cool.", " s'est sentit oblige de toucher la lave.", " est tombe dans la lave.", " est mort(e) dans de la lave.", " ne savait pas que la lave etait vraiment chaude.", " a detruit l'anneau de Sauron." } -- Drowning death messages messages.water = { " a manque d'air.", " a essaye d'usurper l'identite d'une ancre.", " a oublie qu'il n'etait pas un poisson.", " a oublier qu'il lui fallait respirer sous l'eau.", " n'est pas bon en natation.", " a cherche le secret de la licorne.", " a oublie son scaphandre." } -- Burning death messages messages.fire = { " a eut un peu trop chaud.", " a ete trop pres du feu.", " vient de se faire rotir.", " a ete carbonise.", " s'est prit pour la torche.", " a allume le feu." } -- Acid death messages messages.acid = { " a desormais des parties en moins.", " a decouvert que l'acide c'est fun.", " a mis sa tete la ou elle a fondu.", " a decouvert que son corps dans l'acide, c'est comme du sucre dans de l'eau.", " a cru qu'il se baignait dans du jus de pomme.", " a donne son corps pour faire une infusion.", " a bu la mauvaise tasse.", " a voulu tester la solubilite de son corps dans l'acide." } -- Quicksands death messages messages.sand = { " a appris que le sable etait moins fluide que l'eau.", " a rejoint les momies.", " s'est fait(e) ensevelir.", " a choisi la voie de la fossilisation." } -- Other death messages messages.other = { " a fait quelque chose qui lui a ete fatale.", " est mort(e).", " n'est plus de ce monde.", " a rejoint le paradis des mineurs.", " a perdu la vie.", " a vu la lumière." } local function sound_play_all(dead) for _, p in ipairs(minetest.get_connected_players()) do local player_name = p:get_player_name() if player_name and player_name ~= dead then minetest.sound_play("death_messages_people_1",{to_player=player_name, gain=soundset.get_gain(player_name,"other")}) end end end if RANDOM_MESSAGES == true then minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] if minetest.is_singleplayer() then player_name = "You" end local death_message = "" -- Death by lava if node.groups.lava ~= nil then death_message = player_name .. messages.lava[math.random(1,#messages.lava)] -- Death by acid elseif node.groups.acid ~= nil then death_message = player_name .. messages.acid[math.random(1,#messages.acid)] -- Death by drowning elseif player:get_breath() == 0 and node.groups.water then death_message = player_name .. messages.water[math.random(1,#messages.water)] -- Death by fire elseif node.name == "fire:basic_flame" then death_message = player_name .. messages.fire[math.random(1,#messages.fire)] -- Death in quicksand elseif player:get_breath() == 0 and node.name == "default:sand_source" or node.name == "default:sand_flowing" then death_message = player_name .. messages.sand[math.random(1,#messages.sand)] -- Death by something else else death_message = player_name .. messages.other[math.random(1,#messages.other)] end -- Actually tell something minetest.chat_send_all(death_message) irc:say(death_message) minetest.sound_play(sounds[math.random(1,#sounds)],{to_player=player:get_player_name(),gain=soundset.get_gain(player:get_player_name(),"other")}) sound_play_all(player:get_player_name()) end) else minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] if minetest.is_singleplayer() then player_name = "You" end -- Death by lava if node.groups.lava ~= nil then minetest.chat_send_all(player_name .. " melted into a ball of fire") -- Death by drowning elseif player:get_breath() == 0 then minetest.chat_send_all(player_name .. " ran out of air.") -- Death by fire elseif node.name == "fire:basic_flame" then minetest.chat_send_all(player_name .. " burned to a crisp.") -- Death by something else else minetest.chat_send_all(player_name .. " died.") end minetest.sound_play(sounds[math.random(1,#sounds)],{to_player=player:get_player_name(),gain=soundset.get_gain(player:get_player_name(),"other")}) sound_play_all(player:get_player_name()) end) end ----------------------------------------------------------------------------------------------- minetest.log("action", "[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...") -----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------- local title = "Death Messages" local version = "0.1.2" local mname = "death_messages" ----------------------------------------------------------------------------------------------- dofile(minetest.get_modpath("death_messages").."/settings.txt") ----------------------------------------------------------------------------------------------- -- A table of quips for death messages local messages = {} -- Fill this table with sounds local sounds = { [1] = "death_messages_player_1", [2] = "death_messages_player_2", } -- Lava death messages messages.lava = { " pensait que la lave etait cool.", " s'est sentit oblige de toucher la lave.", " est tombe dans la lave.", " est mort(e) dans de la lave.", " ne savait pas que la lave etait vraiment chaude.", " a detruit l'anneau de Sauron." } -- Drowning death messages messages.water = { " a manque d'air.", " a essaye d'usurper l'identite d'une ancre.", " a oublie qu'il n'etait pas un poisson.", " a oublier qu'il lui fallait respirer sous l'eau.", " n'est pas bon en natation.", " a cherche le secret de la licorne.", " a oublie son scaphandre." } -- Burning death messages messages.fire = { " a eut un peu trop chaud.", " a ete trop pres du feu.", " vient de se faire rotir.", " a ete carbonise.", " s'est prit pour la torche.", " a allume le feu." } -- Acid death messages messages.acid = { " a desormais des parties en moins.", " a decouvert que l'acide c'est fun.", " a mis sa tete la ou elle a fondu.", " a decouvert que son corps dans l'acide, c'est comme du sucre dans de l'eau.", " a cru qu'il se baignait dans du jus de pomme.", " a donne son corps pour faire une infusion.", " a bu la mauvaise tasse.", " a voulu tester la solubilite de son corps dans l'acide." } -- Quicksands death messages messages.sand = { " a appris que le sable etait moins fluide que l'eau.", " a rejoint les momies.", " s'est fait(e) ensevelir.", " a choisi la voie de la fossilisation." } -- Other death messages messages.other = { " a fait quelque chose qui lui a ete fatale.", " est mort(e).", " n'est plus de ce monde.", " a rejoint le paradis des mineurs.", " a perdu la vie.", " a vu la lumière." } local function sound_play_all(dead) for _, p in ipairs(minetest.get_connected_players()) do local player_name = p:get_player_name() if player_name and player_name ~= dead then minetest.sound_play("death_messages_people_1",{to_player=player_name, gain=soundset.get_gain(player_name,"other")}) end end end if RANDOM_MESSAGES == true then minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] if minetest.is_singleplayer() then player_name = "You" end local death_message = "" -- Death by lava if node.groups.lava ~= nil then death_message = player_name .. messages.lava[math.random(1,#messages.lava)] -- Death by acid elseif node.groups.acid ~= nil then death_message = player_name .. messages.acid[math.random(1,#messages.acid)] -- Death by drowning elseif player:get_breath() == 0 and node.groups.water then death_message = player_name .. messages.water[math.random(1,#messages.water)] -- Death by fire elseif node.name == "fire:basic_flame" then death_message = player_name .. messages.fire[math.random(1,#messages.fire)] -- Death in quicksand elseif player:get_breath() == 0 and node.name == "default:sand_source" or node.name == "default:sand_flowing" then death_message = player_name .. messages.sand[math.random(1,#messages.sand)] -- Death by something else else death_message = player_name .. messages.other[math.random(1,#messages.other)] end -- Actually tell something minetest.chat_send_all(death_message) if minetest.get_modpath("irc") ~= nil then irc:say(death_message) end minetest.sound_play(sounds[math.random(1,#sounds)],{to_player=player:get_player_name(),gain=soundset.get_gain(player:get_player_name(),"other")}) sound_play_all(player:get_player_name()) end) else minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] if minetest.is_singleplayer() then player_name = "You" end -- Death by lava if node.groups.lava ~= nil then minetest.chat_send_all(player_name .. " melted into a ball of fire") -- Death by drowning elseif player:get_breath() == 0 then minetest.chat_send_all(player_name .. " ran out of air.") -- Death by fire elseif node.name == "fire:basic_flame" then minetest.chat_send_all(player_name .. " burned to a crisp.") -- Death by something else else minetest.chat_send_all(player_name .. " died.") end minetest.sound_play(sounds[math.random(1,#sounds)],{to_player=player:get_player_name(),gain=soundset.get_gain(player:get_player_name(),"other")}) sound_play_all(player:get_player_name()) end) end ----------------------------------------------------------------------------------------------- minetest.log("action", "[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...") -----------------------------------------------------------------------------------------------
fixed crash if irc mod disabled
fixed crash if irc mod disabled
Lua
unlicense
MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,paly2/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,paly2/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun
4db557bedf4839f2c09b5104a834e57b1d369071
xmake/modules/private/tools/vstool.lua
xmake/modules/private/tools/vstool.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file vstool.lua -- -- quietly run command with arguments list function runv(program, argv, opt) -- init options opt = opt or {} -- make temporary output and error file local outpath = os.tmpfile() local errpath = os.tmpfile() local outfile = io.open(outpath, 'w') -- enable unicode output for vs toolchains, e.g. cl.exe, link.exe and etc. -- @see https://github.com/xmake-io/xmake/issues/528 opt.envs = opt.envs or {} opt.envs.VS_UNICODE_OUTPUT = outfile:rawfd() -- execute it local ok, syserrors = os.execv(program, argv, table.join(opt, {try = true, stdout = outfile, stderr = errpath})) -- close outfile first outfile:close() -- failed? if ok ~= 0 then -- read errors local outdata = os.isfile(outpath) and io.readfile(outpath, {encoding = "utf16le"}) or nil local errdata = os.isfile(errpath) and io.readfile(errpath) or nil local errors = errdata or "" if #errors:trim() == 0 then errors = outdata or "" end -- make the default errors if not errors or #errors == 0 then -- get command local cmd = program if argv then cmd = cmd .. " " .. os.args(argv) end -- get errors if ok ~= nil then errors = string.format("vstool.runv(%s) failed(%d)", cmd, ok) else errors = string.format("vstool.runv(%s), %s", cmd, syserrors and syserrors or "unknown reason") end end -- remove the files os.tryrm(outpath) os.tryrm(errpath) -- raise errors os.raise({errors = errors, stderr = errdata, stdout = outdata}) end -- remove the files os.tryrm(outpath) os.tryrm(errpath) end -- run command and return output and error data function iorunv(program, argv, opt) -- init options opt = opt or {} -- make temporary output and error file local outpath = os.tmpfile() local errpath = os.tmpfile() local outfile = io.open(outpath, 'w') -- enable unicode output for vs toolchains, e.g. cl.exe, link.exe and etc. -- @see https://github.com/xmake-io/xmake/issues/528 opt.envs = opt.envs or {} opt.envs.VS_UNICODE_OUTPUT = outfile:rawfd() -- run command local ok, syserrors = os.execv(program, argv, table.join(opt, {try = true, stdout = outfile, stderr = errpath})) -- get output and error data outfile:close() local outdata = os.isfile(outpath) and io.readfile(outpath, {encoding = "utf16le"}) or nil local errdata = os.isfile(errpath) and io.readfile(errpath) or nil -- remove the temporary output and error file os.tryrm(outpath) os.tryrm(errpath) -- failed? if ok ~= 0 then -- get errors local errors = errdata or "" if #errors:trim() == 0 then errors = outdata or "" end -- make the default errors if not errors or #errors == 0 then -- get command local cmd = program if argv then cmd = cmd .. " " .. os.args(argv) end -- get errors if ok ~= nil then errors = string.format("vstool.iorunv(%s) failed(%d)", cmd, ok) else errors = string.format("vstool.iorunv(%s), %s", cmd, syserrors and syserrors or "unknown reason") end end -- raise errors os.raise({errors = errors, stderr = errdata, stdout = outdata}) end -- ok? return outdata, errdata end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file vstool.lua -- -- quietly run command with arguments list function runv(program, argv, opt) -- init options opt = opt or {} -- make temporary output and error file local outpath = os.tmpfile() local errpath = os.tmpfile() local outfile = io.open(outpath, 'w') -- enable unicode output for vs toolchains, e.g. cl.exe, link.exe and etc. -- @see https://github.com/xmake-io/xmake/issues/528 opt.envs = table.join(opt.envs or {}, {VS_UNICODE_OUTPUT = outfile:rawfd()}) -- execute it local ok, syserrors = os.execv(program, argv, table.join(opt, {try = true, stdout = outfile, stderr = errpath})) -- close outfile first outfile:close() -- failed? if ok ~= 0 then -- read errors local outdata = os.isfile(outpath) and io.readfile(outpath, {encoding = "utf16le"}) or nil local errdata = os.isfile(errpath) and io.readfile(errpath) or nil local errors = errdata or "" if #errors:trim() == 0 then errors = outdata or "" end -- make the default errors if not errors or #errors == 0 then -- get command local cmd = program if argv then cmd = cmd .. " " .. os.args(argv) end -- get errors if ok ~= nil then errors = string.format("vstool.runv(%s) failed(%d)", cmd, ok) else errors = string.format("vstool.runv(%s), %s", cmd, syserrors and syserrors or "unknown reason") end end -- remove the files os.tryrm(outpath) os.tryrm(errpath) -- raise errors os.raise({errors = errors, stderr = errdata, stdout = outdata}) end -- remove the files os.tryrm(outpath) os.tryrm(errpath) end -- run command and return output and error data function iorunv(program, argv, opt) -- init options opt = opt or {} -- make temporary output and error file local outpath = os.tmpfile() local errpath = os.tmpfile() local outfile = io.open(outpath, 'w') -- enable unicode output for vs toolchains, e.g. cl.exe, link.exe and etc. -- @see https://github.com/xmake-io/xmake/issues/528 opt.envs = table.join(opt.envs or {}, {VS_UNICODE_OUTPUT = outfile:rawfd()}) -- run command local ok, syserrors = os.execv(program, argv, table.join(opt, {try = true, stdout = outfile, stderr = errpath})) -- get output and error data outfile:close() local outdata = os.isfile(outpath) and io.readfile(outpath, {encoding = "utf16le"}) or nil local errdata = os.isfile(errpath) and io.readfile(errpath) or nil -- remove the temporary output and error file os.tryrm(outpath) os.tryrm(errpath) -- failed? if ok ~= 0 then -- get errors local errors = errdata or "" if #errors:trim() == 0 then errors = outdata or "" end -- make the default errors if not errors or #errors == 0 then -- get command local cmd = program if argv then cmd = cmd .. " " .. os.args(argv) end -- get errors if ok ~= nil then errors = string.format("vstool.iorunv(%s) failed(%d)", cmd, ok) else errors = string.format("vstool.iorunv(%s), %s", cmd, syserrors and syserrors or "unknown reason") end end -- raise errors os.raise({errors = errors, stderr = errdata, stdout = outdata}) end -- ok? return outdata, errdata end
fix vstool
fix vstool
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
119932c9928eb72da71f9ae6d278b574d71a563d
ffi/framebuffer_SDL1_2.lua
ffi/framebuffer_SDL1_2.lua
local ffi = require("ffi") local bit = require("bit") -- load common SDL input/video library local SDL = require("ffi/SDL1_2") local BB = require("ffi/blitbuffer") local fb = {} function fb.open() if not fb.dummy then SDL.open() -- we present this buffer to the outside fb.bb = BB.new(SDL.screen.w, SDL.screen.h) fb.real_bb = BB.new(SDL.screen.w, SDL.screen.h, BB.TYPE_BBRGB32, SDL.screen.pixels, SDL.screen.pitch) else fb.bb = BB.new(600, 800) fb.real_bb = BB.new(600, 800) end fb.real_bb:invert() fb:refresh() return fb end function fb:getSize() return self.bb.w, self.bb.h end function fb:getPitch() return self.bb.pitch end function fb:setOrientation(mode) if mode == 1 or mode == 3 then -- TODO: landscape setting else -- TODO: flip back to portrait end end function fb:getOrientation() if SDL.screen.w > SDL.screen.h then return 1 else return 0 end end function fb:refresh(refreshtype, waveform_mode, x1, y1, w, h) if self.dummy then return end if x1 == nil then x1 = 0 end if y1 == nil then y1 = 0 end -- adapt to possible rotation changes self.real_bb:setRotation(self.bb:getRotation()) if SDL.SDL.SDL_LockSurface(SDL.screen) < 0 then error("Locking screen surface") end self.real_bb:blitFrom(self.bb, x1, y1, x1, y1, w, h) SDL.SDL.SDL_UnlockSurface(SDL.screen) SDL.SDL.SDL_Flip(SDL.screen) end function fb:close() SDL.SDL.SDL_Quit() end return fb
local ffi = require("ffi") local bit = require("bit") -- load common SDL input/video library local SDL = require("ffi/SDL1_2") local BB = require("ffi/blitbuffer") local fb = {} function fb.open() if not fb.dummy then SDL.open() -- we present this buffer to the outside fb.bb = BB.new(SDL.screen.w, SDL.screen.h, BB.TYPE_BBRGB32, SDL.screen.pixels, SDL.screen.pitch) else fb.bb = BB.new(600, 800) end fb.bb:invert() fb:refresh() return fb end function fb:getSize() return self.bb.w, self.bb.h end function fb:getPitch() return self.bb.pitch end function fb:setOrientation(mode) if mode == 1 or mode == 3 then -- TODO: landscape setting else -- TODO: flip back to portrait end end function fb:getOrientation() if SDL.screen.w > SDL.screen.h then return 1 else return 0 end end function fb:refresh(refreshtype, waveform_mode, x1, y1, w, h) if self.dummy then return end -- adapt to possible rotation changes self.bb:setRotation(self.bb:getRotation()) if SDL.SDL.SDL_LockSurface(SDL.screen) < 0 then error("Locking screen surface") end SDL.SDL.SDL_UnlockSurface(SDL.screen) SDL.SDL.SDL_Flip(SDL.screen) end function fb:close() SDL.SDL.SDL_Quit() end return fb
fix SDL1.2 implementation: don't use shadow blitbuffer
fix SDL1.2 implementation: don't use shadow blitbuffer The use of a shadow blitbuffer lead to the issue that the night mode doesn't work. Since the blitbuffer module is fine using any implemented buffer layout, we can get rid of the shadow blitbuffer alltogether.
Lua
agpl-3.0
NiLuJe/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,apletnev/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,houqp/koreader-base,koreader/koreader-base,frankyifei/koreader-base,houqp/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,houqp/koreader-base,koreader/koreader-base,koreader/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base
f594547391dee2f75272ddbb4704afaa33c1b956
Modules/Shared/Utility/QFrame.lua
Modules/Shared/Utility/QFrame.lua
--- CFrame representation as a quaternion -- @module QFrame local QFrame = {} QFrame.__index = QFrame function QFrame.new(x, y, z, W, X, Y, Z) local self = setmetatable({}, QFrame) self.x = x or 0 self.y = y or 0 self.z = z or 0 self.W = W or 1 self.X = X or 0 self.Y = Y or 0 self.Z = Z or 0 return self end function QFrame.fromCFrameClosestTo(cframe, closestTo) local axis, angle = cframe:toAxisAngle() local W = math.cos(angle/2) local X = math.sin(angle/2)*axis.x local Y = math.sin(angle/2)*axis.y local Z = math.sin(angle/2)*axis.z local dot = W*closestTo.W + X*closestTo.X + Y*closestTo.Y + Z*closestTo.Z if dot < 0 then return QFrame.new(cframe.x, cframe.y, cframe.z, -W, -X, -Y, -Z) end return QFrame.new(cframe.x, cframe.y, cframe.z, W, X, Y, Z) end function QFrame.toCFrame(self) local cframe = CFrame.new(self.x, self.y, self.z, self.X, self.Y, self.Z, self.W) if cframe == cframe then return cframe else return nil end end function QFrame.toPosition(self) return Vector3.new(self.x, self.y, self.z) end function QFrame.isNAN(a) return a.x == a.x and a.y == a.y and a.z == a.z and a.W == a.W and a.X == a.X and a.Y == a.Y and a.Z == a.Z end function QFrame.__unm(a) return QFrame.new(-a.x, -a.y, -a.z, -a.W, -a.X, -a.Y, -a.Z) end function QFrame.__add(a, b) assert(getmetatable(a) == QFrame and getmetatable(b) == QFrame, "QFrame + non-QFrame attempted") return QFrame.new(a.x + b.x, a.y + b.y, a.z + b.z, a.W + b.W, a.X + b.X, a.Y + b.Y, a.Z + b.Z) end function QFrame.__sub(a, b) assert(getmetatable(a) == QFrame and getmetatable(b) == QFrame, "QFrame - non-QFrame attempted") return QFrame.new(a.x - b.x, a.y - b.y, a.z - b.z, a.W - b.W, a.X - b.X, a.Y - b.Y, a.Z - b.Z) end function QFrame.__mul(a, b) if type(a) == "number" then return QFrame.new(a*b.x, a*b.y, a*b.z, a*b.W, a*b.X, a*b.Y, a*b.Z) elseif type(b) == "number" then return QFrame.new(a.x*b, a.y*b, a.z*b, a.W*b, a.X*b, a.Y*b, a.Z*b) else error("QFrame * non-QFrame attempted") end end function QFrame.__div(a, b) if type(b) == "number" then return QFrame.new(a.x/b, a.y/b, a.z/b, a.W/b, a.X/b, a.Y/b, a.Z/b) else error("QFrame / non-QFrame attempted") end end function QFrame.__eq(a, b) error("Use isNAN") end return QFrame
--- CFrame representation as a quaternion -- @module QFrame local QFrame = {} QFrame.__index = QFrame function QFrame.new(x, y, z, W, X, Y, Z) local self = setmetatable({}, QFrame) self.x = x or 0 self.y = y or 0 self.z = z or 0 self.W = W or 1 self.X = X or 0 self.Y = Y or 0 self.Z = Z or 0 return self end function QFrame.fromCFrameClosestTo(cframe, closestTo) local axis, angle = cframe:toAxisAngle() local W = math.cos(angle/2) local X = math.sin(angle/2)*axis.x local Y = math.sin(angle/2)*axis.y local Z = math.sin(angle/2)*axis.z local dot = W*closestTo.W + X*closestTo.X + Y*closestTo.Y + Z*closestTo.Z if dot < 0 then return QFrame.new(cframe.x, cframe.y, cframe.z, -W, -X, -Y, -Z) end return QFrame.new(cframe.x, cframe.y, cframe.z, W, X, Y, Z) end function QFrame.toCFrame(self) local cframe = CFrame.new(self.x, self.y, self.z, self.X, self.Y, self.Z, self.W) if cframe == cframe then return cframe else return nil end end function QFrame.toPosition(self) return Vector3.new(self.x, self.y, self.z) end function QFrame.isNAN(a) return a.x == a.x and a.y == a.y and a.z == a.z and a.W == a.W and a.X == a.X and a.Y == a.Y and a.Z == a.Z end function QFrame.__unm(a) return QFrame.new(-a.x, -a.y, -a.z, -a.W, -a.X, -a.Y, -a.Z) end function QFrame.__add(a, b) assert(getmetatable(a) == QFrame and getmetatable(b) == QFrame, "QFrame + non-QFrame attempted") return QFrame.new(a.x + b.x, a.y + b.y, a.z + b.z, a.W + b.W, a.X + b.X, a.Y + b.Y, a.Z + b.Z) end function QFrame.__sub(a, b) assert(getmetatable(a) == QFrame and getmetatable(b) == QFrame, "QFrame - non-QFrame attempted") return QFrame.new(a.x - b.x, a.y - b.y, a.z - b.z, a.W - b.W, a.X - b.X, a.Y - b.Y, a.Z - b.Z) end function QFrame.__mul(a, b) if type(a) == "number" then return QFrame.new(a*b.x, a*b.y, a*b.z, a*b.W, a*b.X, a*b.Y, a*b.Z) elseif type(b) == "number" then return QFrame.new(a.x*b, a.y*b, a.z*b, a.W*b, a.X*b, a.Y*b, a.Z*b) else error("QFrame * non-QFrame attempted") end end function QFrame.__div(a, b) if type(b) == "number" then return QFrame.new(a.x/b, a.y/b, a.z/b, a.W/b, a.X/b, a.Y/b, a.Z/b) else error("QFrame / non-QFrame attempted") end end function QFrame.__eq(a, b) return a.x == b.x and a.y == b.y and a.z == b.z and a.W == b.W and a.X == b.X and a.Y == b.Y and a.Z == b.Z end return QFrame
Fix __eq implementation in qFrame
Fix __eq implementation in qFrame
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
8ed8f49f45db6d64e45b5dfda8bd6a179a8acc1f
Modules/Client/Camera/Effects/FadeBetweenCamera.lua
Modules/Client/Camera/Effects/FadeBetweenCamera.lua
--- Add another layer of effects that can be faded in/out -- @classmod FadeBetweenCamera local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Spring = require("Spring") local SummedCamera = require("SummedCamera") local EPSILON = 1e-4 local FadeBetweenCamera = {} FadeBetweenCamera.ClassName = "FadeBetweenCamera" function FadeBetweenCamera.new(cameraA, cameraB) local self = setmetatable({ _spring = Spring.new(0); CameraA = cameraA or error("No cameraA"); CameraB = cameraB or error("No cameraB"); }, FadeBetweenCamera) self.Damper = 1 self.Speed = 15 return self end function FadeBetweenCamera:__add(other) return SummedCamera.new(self, other) end function FadeBetweenCamera:__newindex(index, value) if index == "Damper" then self._spring.Damper = value elseif index == "Value" then self._spring.Value = value elseif index == "Speed" then self._spring.Speed = value elseif index == "Target" then self._spring.Target = value elseif index == "Velocity" then self._spring.Velocity = value elseif index == "CameraA" or index == "CameraB" then rawset(self, index, value) else error(("%q is not a valid member of FadeBetweenCamera"):format(tostring(index))) end end function FadeBetweenCamera:__index(index) if index == "CameraState" then local value = self._spring.Value if math.abs(value - 1) <= EPSILON then return self.CameraStateB elseif math.abs(value) <= EPSILON then return self.CameraStateA else local stateA = self.CameraStateA local stateB = self.CameraStateB return stateA + (stateB - stateA)*value end elseif index == "CameraStateA" then return self.CameraA.CameraState or self.CameraA elseif index == "CameraStateB" then return self.CameraB.CameraState or self.CameraB elseif index == "Damper" then return self._spring.Damper elseif index == "Value" then return self._spring.Value elseif index == "Speed" then return self._spring.Speed elseif index == "Target" then return self._spring.Target elseif index == "Velocity" then return self._spring.Velocity elseif index == "HasReachedTarget" then return math.abs(self.Value - self.Target) < EPSILON and math.abs(self.Velocity) < EPSILON elseif index == "Spring" then return self._spring else return FadeBetweenCamera[index] end end return FadeBetweenCamera
--- Add another layer of effects that can be faded in/out -- @classmod FadeBetweenCamera local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Spring = require("Spring") local SummedCamera = require("SummedCamera") local EPSILON = 1e-4 local FadeBetweenCamera = {} FadeBetweenCamera.ClassName = "FadeBetweenCamera" function FadeBetweenCamera.new(cameraA, cameraB) local self = setmetatable({ _spring = Spring.new(0); CameraA = cameraA or error("No cameraA"); CameraB = cameraB or error("No cameraB"); }, FadeBetweenCamera) self.Damper = 1 self.Speed = 15 return self end function FadeBetweenCamera:__add(other) return SummedCamera.new(self, other) end function FadeBetweenCamera:__newindex(index, value) if index == "Damper" then self._spring.Damper = value elseif index == "Value" then self._spring.Value = value elseif index == "Speed" then self._spring.Speed = value elseif index == "Target" then self._spring.Target = value elseif index == "Velocity" then self._spring.Velocity = value elseif index == "CameraA" or index == "CameraB" then rawset(self, index, value) else error(("%q is not a valid member of FadeBetweenCamera"):format(tostring(index))) end end function FadeBetweenCamera:__index(index) if index == "CameraState" then local value = self._spring.Value if math.abs(value - 1) <= EPSILON then return self.CameraStateB elseif math.abs(value) <= EPSILON then return self.CameraStateA else local stateA = self.CameraStateA local stateB = self.CameraStateB local delta = stateB - stateA if delta.Quaterion.w < 0 then delta.Quaterion = -delta.Quaterion end return stateA + delta*value end elseif index == "CameraStateA" then return self.CameraA.CameraState or self.CameraA elseif index == "CameraStateB" then return self.CameraB.CameraState or self.CameraB elseif index == "Damper" then return self._spring.Damper elseif index == "Value" then return self._spring.Value elseif index == "Speed" then return self._spring.Speed elseif index == "Target" then return self._spring.Target elseif index == "Velocity" then return self._spring.Velocity elseif index == "HasReachedTarget" then return math.abs(self.Value - self.Target) < EPSILON and math.abs(self.Velocity) < EPSILON elseif index == "Spring" then return self._spring else return FadeBetweenCamera[index] end end return FadeBetweenCamera
Fix long standing quaternion interpolation bug
Fix long standing quaternion interpolation bug
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
af748aa82660e3098da65068dccc6bc998ff5c68
src/plugins/finalcutpro/tangent/overlay.lua
src/plugins/finalcutpro/tangent/overlay.lua
--- === plugins.finalcutpro.tangent.overlay === --- --- Final Cut Pro Tangent Viewer Overlay Group -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- -- local log = require("hs.logger").new("fcptng_timeline") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local fcp = require("cp.apple.finalcutpro") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} --- plugins.finalcutpro.tangent.overlay.group --- Constant --- The `core.tangent.manager.group` that collects Final Cut Pro New actions/parameters/etc. mod.group = nil --- plugins.finalcutpro.tangent.overlay.init() -> none --- Function --- Initialises the module. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.init(fcpGroup, overlays) local baseID = 0x00120000 mod.group = fcpGroup:group(i18n("viewerOverlay")) mod.group:action(baseID+1, i18n("cpViewerBasicGrid_title")) :onPress(function() overlays.basicGridEnabled:toggle() overlays.update() end) mod.group:action(baseID+2, i18n("cpViewerDraggableGuide_title")) :onPress(function() overlays.draggableGuideEnabled:toggle() overlays.update() end) mod.group:action(baseID+3, i18n("cpToggleAllViewerOverlays_title")) :onPress(function() overlays.disabled:toggle() overlays.update() end) local nextID = baseID+4 for i=1, overlays.NUMBER_OF_MEMORIES do mod.group:action(nextID, i18n("viewStillsMemory") .. " " .. i) :onPress(function() overlays.viewMemory(i) end) nextID = nextID + 1 mod.group:action(nextID, i18n("saveCurrentFrameToStillsMemory") .. " " .. i) :onPress(function() overlays.saveMemory(i) end) nextID = nextID + 1 end end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.tangent.new", group = "finalcutpro", dependencies = { ["finalcutpro.tangent.group"] = "fcpGroup", ["finalcutpro.viewer.overlays"] = "overlays", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps) -------------------------------------------------------------------------------- -- Initalise the Module: -------------------------------------------------------------------------------- if deps and deps.fcpGroup and deps.overlays then mod.init(deps.fcpGroup, deps.overlays) end return mod end return plugin
--- === plugins.finalcutpro.tangent.overlay === --- --- Final Cut Pro Tangent Viewer Overlay Group -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- -- local log = require("hs.logger").new("tangentOverlay") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} --- plugins.finalcutpro.tangent.overlay.group --- Constant --- The `core.tangent.manager.group` that collects Final Cut Pro New actions/parameters/etc. mod.group = nil --- plugins.finalcutpro.tangent.overlay.init() -> none --- Function --- Initialises the module. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.init(fcpGroup, overlays) local baseID = 0x00120000 mod.group = fcpGroup:group(i18n("viewerOverlay")) mod.group:action(baseID+1, i18n("cpViewerBasicGrid_title")) :onPress(function() overlays.basicGridEnabled:toggle() overlays.update() end) mod.group:action(baseID+2, i18n("cpViewerDraggableGuide_title")) :onPress(function() overlays.draggableGuideEnabled:toggle() overlays.update() end) mod.group:action(baseID+3, i18n("cpToggleAllViewerOverlays_title")) :onPress(function() overlays.disabled:toggle() overlays.update() end) local nextID = baseID+4 for i=1, overlays.NUMBER_OF_MEMORIES do mod.group:action(nextID, i18n("viewStillsMemory") .. " " .. i) :onPress(function() overlays.viewMemory(i) end) nextID = nextID + 1 mod.group:action(nextID, i18n("saveCurrentFrameToStillsMemory") .. " " .. i) :onPress(function() overlays.saveMemory(i) end) nextID = nextID + 1 end end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.tangent.new", group = "finalcutpro", dependencies = { ["finalcutpro.tangent.group"] = "fcpGroup", ["finalcutpro.viewer.overlays"] = "overlays", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps) -------------------------------------------------------------------------------- -- Initalise the Module: -------------------------------------------------------------------------------- if deps and deps.fcpGroup and deps.overlays then mod.init(deps.fcpGroup, deps.overlays) end return mod end return plugin
#1289
#1289 - Fixed @stickler-ci errors
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
0fd251753f4122b56ab1f382314593ac1058d0cd
MMOCoreORB/bin/scripts/screenplays/caves/tatooine_hutt_hideout.lua
MMOCoreORB/bin/scripts/screenplays/caves/tatooine_hutt_hideout.lua
HuttHideoutScreenPlay = ScreenPlay:new { numberOfActs = 1, lootContainers = { 134411, 8496263, 8496262, 8496261, 8496260 }, lootLevel = 26, lootGroups = { { groups = { {group = "color_crystals", chance = 160000}, {group = "junk", chance = 8600000}, {group = "rifles", chance = 500000}, {group = "pistols", chance = 500000}, {group = "clothing_attachments", chance = 300000}, {group = "armor_attachments", chance = 300000} }, lootChance = 8000000 } }, lootContainerRespawn = 1800 -- 30 minutes } registerScreenPlay("HuttHideoutScreenPlay", true) function HuttHideoutScreenPlay:start() if (isZoneEnabled("tatooine")) then self:spawnMobiles() self:initializeLootContainers() end end function HuttHideoutScreenPlay:spawnMobiles() spawnMobile("tatooine", "jabba_enforcer", 200, -3.5, -12.7, -6.7, 24, 4235585) spawnMobile("tatooine", "jabba_henchman", 200, 1.1, -14.4, -9.3, 15, 4235585) spawnMobile("tatooine", "jabba_compound_guard", 200, -12.1, -32.2, -34, 19, 4235586) spawnMobile("tatooine", "jabba_enforcer", 200, -10.5, -40.4, -81.3, -178, 4235587) spawnMobile("tatooine", "jabba_henchman", 200, 5.8, -40.9, -79.6, -37, 4235587) spawnMobile("tatooine", "jabba_enforcer", 200, 14.5, -40.5, -74.2, -131, 4235587) spawnMobile("tatooine", "jabba_enforcer", 200, 20, -39.6, -77.9, -50, 4235587) spawnMobile("tatooine", "jabba_henchman", 200, 10.7, -41.1, -60.3, -124, 4235587) spawnMobile("tatooine", "jabba_henchman", 200, 47, -46.7, -50.8, -163, 4235588) spawnMobile("tatooine", "jabba_henchman", 200, 50.4, -46.8, -58.6, -19, 4235588) spawnMobile("tatooine", "jabba_henchman", 200, 51.6, -46, -91.6, -126, 4235588) spawnMobile("tatooine", "jabba_enforcer", 200, 47.1, -46.2, -96.3, 46, 4235588) spawnMobile("tatooine", "jabba_compound_guard", 200, 44.9, -46.2, -102.8, -41, 4235588) spawnMobile("tatooine", "jabba_henchman", 200, 13.9, -45, -121.1, 30, 4235589) spawnMobile("tatooine", "jabba_enforcer", 200, 1.5, -45, -141.6, 117, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, -10, -45.6, -148, 26, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, -12.4, -45, -130.8, 125, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 58.8, -47.1, -124.6, -21, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 73.5, -52.9, -144.7, -178, 4235589) spawnMobile("tatooine", "jabba_enforcer", 200, 72.5, -54.4, -151.6, -20, 4235589) spawnMobile("tatooine", "jabba_enforcer", 200, 38.2, -55.7, -155.4, -78, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 36.9, -56.1, -157.2, -53, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 67.5, -57.3, -176.7, 62, 4235589) spawnMobile("tatooine", "jabba_enforcer", 200, 58.6, -57.7, -185.3, -70, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 53, -57, -185.3, 59, 4235589) spawnMobile("tatooine", "jabba_compound_guard", 200, 58.8, -56.4, -159.5, -60, 4235589) spawnMobile("tatooine", "jabba_compound_guard", 200, 53.3, -56.6, -160.2, 45, 4235589) spawnMobile("tatooine", "jabba_compound_guard", 200, 6, -63.9, -181.8, 90, 4235590) spawnMobile("tatooine", "jabba_compound_guard", 200, -8.1, -65.1, -201.3, -10, 4235590) spawnMobile("tatooine", "jabba_compound_guard", 200, -37.5, -67, -182.8, 91, 4235590) spawnMobile("tatooine", "jabba_henchman", 200, -18.7, -65.5, -210.3, -152, 4235591) spawnMobile("tatooine", "jabba_compound_guard", 200, -22.5, -64.6, -220.2, -131, 4235591) spawnMobile("tatooine", "jabba_henchman", 200, -17.6, -65.4, -216.8, -7, 4235591) spawnMobile("tatooine", "jabba_henchman", 200, -4.8, -64.2, -231.5, 178, 4235591) spawnMobile("tatooine", "jabba_assassin", 200, -1.3, -64.2, -238.5, 88, 4235591) spawnMobile("tatooine", "jabba_compound_guard", 200, -224, -65, -249.8, -174, 4235591) spawnMobile("tatooine", "jabba_henchman", 200, -19.3, -62.6, -261.6, 43, 4235591) spawnMobile("tatooine", "jabba_assassin", 200, -10.6, -63.3, -261.2, -77, 4235591) spawnMobile("tatooine", "jabba_henchman", 200, -57.1, -70.2, -193, -70, 4235592) spawnMobile("tatooine", "jabba_compound_guard", 200, -71.8, -68.6, -182.3, 99, 4235592) spawnMobile("tatooine", "jabba_henchman", 200, -59.3, -69.8, -170.9, -53, 4235592) spawnMobile("tatooine", "jabba_enforcer", 200, -71.5, -70, -166.7, 141, 4235592) spawnMobile("tatooine", "jabba_assassin", 200, -98.3, -72.4, -174.9, 72, 4235592) spawnMobile("tatooine", "jabba_henchman", 200, -112.2, -69.1, -119.7, 84, 4235592) spawnMobile("tatooine", "jabba_enforcer", 200, -106.1, -68.6, -112.2, -76, 4235592) spawnMobile("tatooine", "jabba_assassin", 200, -84.2, -70.3, -129.7, 83, 4235592) spawnMobile("tatooine", "jabba_enforcer", 200, -94.9, -102.6, -137.2, 154, 4235592) spawnMobile("tatooine", "jabba_enforcer", 200, -95.6, -102.1, -140.6, 0, 4235592) spawnMobile("tatooine", "jabba_henchman", 200, -51.4, -68.9, -95.4, 135, 4235593) spawnMobile("tatooine", "jabba_enforcer", 200, -47.6, -69.3, -95.4, -133, 4235593) spawnMobile("tatooine", "jabba_enforcer", 200, -46.3, -69.3, -99, -52, 4235593) spawnMobile("tatooine", "jabba_compound_guard", 200, -59.4, -70.1, -88, -179, 4235593) spawnMobile("tatooine", "jabba_henchman", 200, -69.4, -68.5, -101.7, 110, 4235593) spawnMobile("tatooine", "jabba_compound_guard", 200, -65.6, -68.3, -103.1, -74, 4235593) spawnMobile("tatooine", "jabba_assassin", 200, -8.6, -68.6, -97.1, -162, 4235593) spawnMobile("tatooine", "jabba_compound_guard", 200, -32.1, -80.2, -143.5, 80, 4235594) spawnMobile("tatooine", "jabba_henchman", 200, -19.7, -79.8, -146.9, -59, 4235594) spawnMobile("tatooine", "jabba_henchman", 200, -21.2, -79.6, -143.8, 160, 4235594) spawnMobile("tatooine", "jabba_compound_guard", 200, -79, -100.9, -130, -100, 4235595) spawnMobile("tatooine", "jabba_assassin", 200, -83.8, -100.6, -106.6, -1, 4235595) spawnMobile("tatooine", "jabba_enforcer", 200, -86.4, -100.5, -103.6, 123, 4235595) spawnMobile("tatooine", "jabba_assassin", 200, -100.4, -99.9, -114.2, 162, 4235595) spawnMobile("tatooine", "jabba_enforcer", 200, -98.3, -100, -105.2, -43, 4235595) end function HuttHideoutScreenPlay:initializeLootContainers() for k,v in pairs(self.lootContainers) do local pContainer = getSceneObject(v) createObserver(OPENCONTAINER, "HuttHideoutScreenPlay", "spawnContainerLoot", pContainer) self:spawnContainerLoot(pContainer) end end function HuttHideoutScreenPlay:spawnContainerLoot(pContainer) if (pContainer == nil) then return end local container = LuaSceneObject(pContainer) local time = getTimestamp() if (readData(container:getObjectID()) > time) then return end --If it has loot already, then exit. if (container:getContainerObjectsSize() > 0) then return end createLootFromCollection(pContainer, self.lootGroups, self.lootLevel) writeData(container:getObjectID(), time + self.lootContainerRespawn) end
HuttHideoutScreenPlay = ScreenPlay:new { numberOfActs = 1, lootContainers = { 134411, 8496263, 8496262, 8496261, 8496260 }, lootLevel = 26, lootGroups = { { groups = { {group = "color_crystals", chance = 160000}, {group = "junk", chance = 8600000}, {group = "rifles", chance = 500000}, {group = "pistols", chance = 500000}, {group = "clothing_attachments", chance = 300000}, {group = "armor_attachments", chance = 300000} }, lootChance = 8000000 } }, lootContainerRespawn = 1800 -- 30 minutes } registerScreenPlay("HuttHideoutScreenPlay", true) function HuttHideoutScreenPlay:start() if (isZoneEnabled("tatooine")) then self:spawnMobiles() self:initializeLootContainers() end end function HuttHideoutScreenPlay:spawnMobiles() spawnMobile("tatooine", "jabba_enforcer", 200, -3.5, -12.7, -6.7, 24, 4235585) spawnMobile("tatooine", "jabba_henchman", 200, 1.1, -14.4, -9.3, 15, 4235585) spawnMobile("tatooine", "jabba_compound_guard", 200, -12.1, -32.2, -34, 19, 4235586) spawnMobile("tatooine", "jabba_enforcer", 200, -10.5, -40.4, -81.3, -178, 4235587) spawnMobile("tatooine", "jabba_henchman", 200, 5.8, -40.9, -79.6, -37, 4235587) spawnMobile("tatooine", "jabba_enforcer", 200, 14.5, -40.5, -74.2, -131, 4235587) spawnMobile("tatooine", "jabba_enforcer", 200, 20, -39.6, -77.9, -50, 4235587) spawnMobile("tatooine", "jabba_henchman", 200, 10.7, -41.1, -60.3, -124, 4235587) spawnMobile("tatooine", "jabba_henchman", 200, 47, -46.7, -50.8, -163, 4235588) spawnMobile("tatooine", "jabba_henchman", 200, 50.4, -46.8, -58.6, -19, 4235588) spawnMobile("tatooine", "jabba_henchman", 200, 51.6, -46, -91.6, -126, 4235588) spawnMobile("tatooine", "jabba_enforcer", 200, 47.1, -46.2, -96.3, 46, 4235588) spawnMobile("tatooine", "jabba_compound_guard", 200, 44.9, -46.2, -102.8, -41, 4235588) spawnMobile("tatooine", "jabba_henchman", 200, 13.9, -45, -121.1, 30, 4235589) spawnMobile("tatooine", "jabba_enforcer", 200, 1.5, -45, -141.6, 117, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, -10, -45.6, -148, 26, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, -12.4, -45, -130.8, 125, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 58.8, -47.1, -124.6, -21, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 73.5, -52.9, -144.7, -178, 4235589) spawnMobile("tatooine", "jabba_enforcer", 200, 72.5, -54.4, -151.6, -20, 4235589) spawnMobile("tatooine", "jabba_enforcer", 200, 38.2, -55.7, -155.4, -78, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 36.9, -56.1, -157.2, -53, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 67.5, -57.3, -176.7, 62, 4235589) spawnMobile("tatooine", "jabba_enforcer", 200, 58.6, -57.7, -185.3, -70, 4235589) spawnMobile("tatooine", "jabba_henchman", 200, 53, -57, -185.3, 59, 4235589) spawnMobile("tatooine", "jabba_compound_guard", 200, 58.8, -56.4, -159.5, -60, 4235589) spawnMobile("tatooine", "jabba_compound_guard", 200, 53.3, -56.6, -160.2, 45, 4235589) spawnMobile("tatooine", "jabba_compound_guard", 200, 6, -63.9, -181.8, 90, 4235590) spawnMobile("tatooine", "jabba_compound_guard", 200, -8.1, -65.1, -201.3, -10, 4235590) spawnMobile("tatooine", "jabba_compound_guard", 200, -37.5, -67, -182.8, 91, 4235590) spawnMobile("tatooine", "jabba_henchman", 200, -18.7, -65.5, -210.3, -152, 4235591) spawnMobile("tatooine", "jabba_compound_guard", 200, -22.5, -64.6, -220.2, -131, 4235591) spawnMobile("tatooine", "jabba_henchman", 200, -17.6, -65.4, -216.8, -7, 4235591) spawnMobile("tatooine", "jabba_henchman", 200, -4.8, -64.2, -231.5, 178, 4235591) spawnMobile("tatooine", "jabba_assassin", 200, -1.3, -64.2, -238.5, 88, 4235591) spawnMobile("tatooine", "jabba_compound_guard", 200, -224, -65, -249.8, -174, 4235591) spawnMobile("tatooine", "jabba_henchman", 200, -19.3, -62.6, -261.6, 43, 4235591) spawnMobile("tatooine", "jabba_assassin", 200, -10.6, -63.3, -261.2, -77, 4235591) spawnMobile("tatooine", "jabba_henchman", 200, -57.1, -70.2, -193, -70, 4235592) spawnMobile("tatooine", "jabba_compound_guard", 200, -71.8, -68.6, -182.3, 99, 4235592) spawnMobile("tatooine", "jabba_henchman", 200, -59.3, -69.8, -170.9, -53, 4235592) spawnMobile("tatooine", "jabba_enforcer", 200, -71.5, -70, -166.7, 141, 4235592) spawnMobile("tatooine", "jabba_assassin", 200, -98.3, -72.4, -174.9, 72, 4235592) spawnMobile("tatooine", "jabba_henchman", 200, -112.2, -69.1, -119.7, 84, 4235592) spawnMobile("tatooine", "jabba_enforcer", 200, -106.1, -68.6, -112.2, -76, 4235592) spawnMobile("tatooine", "jabba_assassin", 200, -84.2, -70.3, -129.7, 83, 4235592) spawnMobile("tatooine", "jabba_enforcer", 200, -94.9, -102.6, -137.2, 154, 4235592) spawnMobile("tatooine", "jabba_enforcer", 200, -95.6, -102.1, -140.6, 0, 4235592) spawnMobile("tatooine", "jabba_henchman", 200, -51.4, -68.9, -95.4, 135, 4235593) spawnMobile("tatooine", "jabba_enforcer", 200, -47.6, -69.3, -95.4, -133, 4235593) spawnMobile("tatooine", "jabba_enforcer", 200, -46.3, -69.3, -99, -52, 4235593) spawnMobile("tatooine", "jabba_compound_guard", 200, -59.4, -70.1, -88, -179, 4235593) spawnMobile("tatooine", "jabba_henchman", 200, -69.4, -68.5, -101.7, 110, 4235593) spawnMobile("tatooine", "jabba_compound_guard", 200, -65.6, -68.3, -103.1, -74, 4235593) spawnMobile("tatooine", "jabba_assassin", 200, -8.6, -68.6, -97.1, -162, 4235593) spawnMobile("tatooine", "jabba_compound_guard", 200, -32.1, -80.2, -143.5, 80, 4235594) spawnMobile("tatooine", "jabba_henchman", 200, -19.7, -79.8, -146.9, -59, 4235594) spawnMobile("tatooine", "jabba_henchman", 200, -21.2, -79.6, -143.8, 160, 4235594) spawnMobile("tatooine", "jabba_compound_guard", 200, -79, -100.9, -130, -100, 4235595) spawnMobile("tatooine", "jabba_assassin", 200, -83.8, -100.6, -106.6, -1, 4235595) spawnMobile("tatooine", "jabba_enforcer", 200, -86.4, -100.5, -103.6, 123, 4235595) spawnMobile("tatooine", "jabba_assassin", 200, -100.4, -99.9, -114.2, 162, 4235595) spawnMobile("tatooine", "jabba_enforcer", 200, -98.3, -100, -105.2, -43, 4235595) end function HuttHideoutScreenPlay:initializeLootContainers() for k,v in pairs(self.lootContainers) do local pContainer = getSceneObject(v) if (pContainer ~= nil) then createObserver(OPENCONTAINER, "HuttHideoutScreenPlay", "spawnContainerLoot", pContainer) self:spawnContainerLoot(pContainer) local container = LuaSceneObject(pContainer) container:setContainerDefaultAllowPermission(MOVEOUT + OPEN) end end end function HuttHideoutScreenPlay:spawnContainerLoot(pContainer) local container = LuaSceneObject(pContainer) local time = getTimestamp() if (readData(container:getObjectID()) > time) then return end --If it has loot already, then exit. if (container:getContainerObjectsSize() > 0) then return end createLootFromCollection(pContainer, self.lootGroups, self.lootLevel) writeData(container:getObjectID(), time + self.lootContainerRespawn) end
(unstable) [fixed] Unremovable loot in jabba cave.
(unstable) [fixed] Unremovable loot in jabba cave. git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5526 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
cd2fe6e758b86f174e93f3c0f6104841243a1765
applications/luci-radvd/luasrc/model/cbi/radvd.lua
applications/luci-radvd/luasrc/model/cbi/radvd.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 $Id$ ]]-- m = Map("radvd", translate("Radvd"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) local nm = require "luci.model.network".init(m.uci) -- -- Interfaces -- s = m:section(TypedSection, "interface", translate("Interfaces")) s.template = "cbi/tblsection" s.extedit = luci.dispatcher.build_url("admin/network/radvd/interface/%s") s.anonymous = true s.addremove = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s.extedit % id) end function s.remove(self, section) local iface = m.uci:get("radvd", section, "interface") if iface then m.uci:delete_all("radvd", "prefix", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "route", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "rdnss", function(s) return s.interface == iface end) end return TypedSection.remove(self, section) end o = s:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s:option(DummyValue, "UnicastOnly", translate("Multicast")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("no") or translate("yes") end o = s:option(DummyValue, "AdvSendAdvert", translate("Advertising")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "MaxRtrAdvInterval", translate("Max. interval")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "600" return v .. "s" end o = s:option(DummyValue, "AdvHomeAgentFlag", translate("Mobile IPv6")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "AdvDefaultPreference", translate("Preference")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "medium" return translate(v) end -- -- Prefixes -- s2 = m:section(TypedSection, "prefix", translate("Prefixes")) s2.template = "cbi/tblsection" s2.extedit = luci.dispatcher.build_url("admin/network/radvd/prefix/%s") s2.addremove = true s2.anonymous = true function s2.create(...) local id = TypedSection.create(...) luci.http.redirect(s2.extedit % id) end o = s2:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s2:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:string() break end end end end else v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s2:option(DummyValue, "AdvAutonomous", translate("Autonomous")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvOnLink", translate("On-link")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvValidLifetime", translate("Validity time")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "86400" return translate(v) end -- -- Routes -- s3 = m:section(TypedSection, "route", translate("Routes")) s3.template = "cbi/tblsection" s3.extedit = luci.dispatcher.build_url("admin/network/radvd/route/%s") s3.addremove = true s3.anonymous = true function s3.create(...) local id = TypedSection.create(...) luci.http.redirect(s3.extedit % id) end o = s3:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s3:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if v then v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s3:option(DummyValue, "AdvRouteLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1800" return translate(v) end o = s3:option(DummyValue, "AdvRoutePreference", translate("Preference")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "medium" return translate(v) end -- -- RDNSS -- s4 = m:section(TypedSection, "rdnss", translate("RDNSS")) s4.template = "cbi/tblsection" s4.extedit = luci.dispatcher.build_url("admin/network/radvd/rdnss/%s") s4.addremove = true s4.anonymous = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s4.extedit % id) end o = s4:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s4:option(DummyValue, "addr", translate("Address")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:network(128):string() break end end end end else v = luci.ip.IPv6(v) v = v and v:network(128):string() end return v or "?" end o = s4:option(DummyValue, "AdvRDNSSOpen", translate("Open")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v == "1" and translate("yes") or translate("no") end o = s4:option(DummyValue, "AdvRDNSSLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1200" return translate(v) 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 $Id$ ]]-- m = Map("radvd", translate("Radvd"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) local nm = require "luci.model.network".init(m.uci) -- -- Interfaces -- s = m:section(TypedSection, "interface", translate("Interfaces")) s.template = "cbi/tblsection" s.extedit = luci.dispatcher.build_url("admin/network/radvd/interface/%s") s.anonymous = true s.addremove = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s.extedit % id) end function s.remove(self, section) if m.uci:get("radvd", section) == "interface" then local iface = m.uci:get("radvd", section, "interface") if iface then m.uci:delete_all("radvd", "prefix", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "route", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "rdnss", function(s) return s.interface == iface end) end end return TypedSection.remove(self, section) end o = s:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s:option(DummyValue, "UnicastOnly", translate("Multicast")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("no") or translate("yes") end o = s:option(DummyValue, "AdvSendAdvert", translate("Advertising")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "MaxRtrAdvInterval", translate("Max. interval")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "600" return v .. "s" end o = s:option(DummyValue, "AdvHomeAgentFlag", translate("Mobile IPv6")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "AdvDefaultPreference", translate("Preference")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "medium" return translate(v) end -- -- Prefixes -- s2 = m:section(TypedSection, "prefix", translate("Prefixes")) s2.template = "cbi/tblsection" s2.extedit = luci.dispatcher.build_url("admin/network/radvd/prefix/%s") s2.addremove = true s2.anonymous = true function s2.create(...) local id = TypedSection.create(...) luci.http.redirect(s2.extedit % id) end o = s2:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s2:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:string() break end end end end else v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s2:option(DummyValue, "AdvAutonomous", translate("Autonomous")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvOnLink", translate("On-link")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvValidLifetime", translate("Validity time")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "86400" return translate(v) end -- -- Routes -- s3 = m:section(TypedSection, "route", translate("Routes")) s3.template = "cbi/tblsection" s3.extedit = luci.dispatcher.build_url("admin/network/radvd/route/%s") s3.addremove = true s3.anonymous = true function s3.create(...) local id = TypedSection.create(...) luci.http.redirect(s3.extedit % id) end o = s3:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s3:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if v then v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s3:option(DummyValue, "AdvRouteLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1800" return translate(v) end o = s3:option(DummyValue, "AdvRoutePreference", translate("Preference")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "medium" return translate(v) end -- -- RDNSS -- s4 = m:section(TypedSection, "rdnss", translate("RDNSS")) s4.template = "cbi/tblsection" s4.extedit = luci.dispatcher.build_url("admin/network/radvd/rdnss/%s") s4.addremove = true s4.anonymous = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s4.extedit % id) end o = s4:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s4:option(DummyValue, "addr", translate("Address")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:network(128):string() break end end end end else v = luci.ip.IPv6(v) v = v and v:network(128):string() end return v or "?" end o = s4:option(DummyValue, "AdvRDNSSOpen", translate("Open")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v == "1" and translate("yes") or translate("no") end o = s4:option(DummyValue, "AdvRDNSSLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1200" return translate(v) end return m
applications/luci-radvd: fix removal of section in overview page
applications/luci-radvd: fix removal of section in overview page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6530 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI
c0da355bbeb8b9334e4e43fc405fe6abdcdbfb08
modules/admin-mini/luasrc/model/cbi/mini/system.lua
modules/admin-mini/luasrc/model/cbi/mini/system.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") m = Map("system", translate("system"), translate("a_s_desc")) s = m:section(TypedSection, "system", "") s.anonymous = true local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:option(DummyValue, "_system", translate("system")).value = system s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() s:option(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:option(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") s:option(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") m = Map("system", translate("system"), translate("a_s_desc")) s = m:section(TypedSection, "system", "") s.anonymous = true local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:option(DummyValue, "_system", translate("system")).value = system s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() s:option(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:option(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("mem_cached", "")), 100 * membuffers / memtotal, tostring(translate("mem_buffered", "")), 100 * memfree / memtotal, tostring(translate("mem_free", "")) s:option(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end return m
modules/admin-mini: fix the same issue in admin-mini
modules/admin-mini: fix the same issue in admin-mini git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5149 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
ReclaimYourPrivacy/cloak-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,gwlim/luci,Flexibity/luci,ThingMesh/openwrt-luci,phi-psi/luci,saraedum/luci-packages-old,jschmidlapp/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,jschmidlapp/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,jschmidlapp/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,8devices/carambola2-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,jschmidlapp/luci,ThingMesh/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,stephank/luci,zwhfly/openwrt-luci,stephank/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,ch3n2k/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,stephank/luci,ch3n2k/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,vhpham80/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,phi-psi/luci,ch3n2k/luci,eugenesan/openwrt-luci,ch3n2k/luci,phi-psi/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,Canaan-Creative/luci,Flexibity/luci,gwlim/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,Canaan-Creative/luci,8devices/carambola2-luci,gwlim/luci,Flexibity/luci,projectbismark/luci-bismark,freifunk-gluon/luci,vhpham80/luci,saraedum/luci-packages-old,saraedum/luci-packages-old,yeewang/openwrt-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,Canaan-Creative/luci,Flexibity/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,yeewang/openwrt-luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,8devices/carambola2-luci,ch3n2k/luci,Canaan-Creative/luci,stephank/luci,eugenesan/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,phi-psi/luci,stephank/luci,8devices/carambola2-luci,8devices/carambola2-luci,vhpham80/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,phi-psi/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,vhpham80/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,ch3n2k/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci
9a6ac53de7a7becec2598aeedfa3c38ccee3f519
modules/alarm.lua
modules/alarm.lua
local ev = require'ev' if(not ivar2.timers) then ivar2.timers = {} end local dateFormat = '%Y-%m-%d %X %Z' local split = function(str, pattern) local out = {} str:gsub(pattern, function(match) table.insert(out, match) end) return out end local timeMatches = { { '(%d+)[:.](%d%d)[:.]?(%d?%d?)', function(h, m, s) -- Seconds will always return a match. if(s == '') then s = 0 end local duration = 0 local now = os.time() local date = os.date'*t' local ntime = date.hour * 60 * 60 + date.min * 60 + date.sec local atime = h * 60 * 60 + m * 60 + s -- Set the correct time of day. date.hour = h date.min = m date.sec = s -- If the alarm is right now or in the past, bump it to the next day. if(ntime >= atime) then date.day = date.day + 1 end return os.time(date) - now end }, {'^(%d+)w$', function(w) return w * 60 * 60 * 24 * 7 end}, {'^(%d+)d$', function(d) return d * 60 * 60 * 24 end}, {'^(%d+)[ht]$', function(h) return h * 60 * 60 end}, {'^(%d+)m$', function(m) return m * 60 end}, {'^(%d+)[^%p%w]*$', function(m) return m * 60 end}, {'^(%d+)s$', function(s) return s end}, } local parseTime = function(input) local duration = 0 local offset for i=1, #input do local found local str = input[i] for j=1, #timeMatches do local pattern, func = unpack(timeMatches[j]) local a1, a2, a3 = str:match(pattern) if(a1) then found = true duration = duration + func(a1, a2, a3) end end if(not found) then break end offset = i + 1 end if(duration ~= 0) then return duration, table.concat(input, ' ', offset) end end local alarm = function(self, source, destination, message) local duration, message = parseTime(split(message, '%S+')) -- Couldn't figure out what the user wanted. if(not duration) then return end -- 60 days or more? local nick = source.nick if(duration >= (60 * 60 * 24 * 60) or duration == 0) then return self:Msg('privmsg', destination, source, "%s: :'(", nick) end local id = 'Alarm: ' .. nick local runningTimer = self.timers[id] if(runningTimer) then -- Send a notification if we are overriding an old timer. if(runningTimer.utimestamp > os.time()) then if(runningTimer.message) then self:Notice( nick, 'Previously active timer set to trigger at %s with message "%s" has been removed.', os.date(dateFormat, runningTimer.utimestamp), runningTimer.message ) else self:Notice( nick, 'Previously active timer set to trigger at %s has been removed.', os.date(dateFormat, runningTimer.utimestamp) ) end end -- message is probably changed. runningTimer:stop(ivar2.Loop) end local timer = ev.Timer.new( function(loop, timer, revents) if(#message == 0) then message = 'Timer finished.' end self:Msg('privmsg', destination, source, '%s: %s', nick, message or 'Timer finished.') end, duration ) if(#message > 0) then timer.message = message end timer.utimestamp = os.time() + duration self:Notice(nick, "I'll poke you at %s.", os.date(dateFormat, timer.utimestamp)) self.timers[id] = timer timer:start(ivar2.Loop) end return { PRIVMSG = { ['^!alarm (.*)$'] = alarm, ['^!timer (.*)$'] = alarm, }, }
local ev = require'ev' if(not ivar2.timers) then ivar2.timers = {} end local dateFormat = '%Y-%m-%d %X %Z' local split = function(str, pattern) local out = {} str:gsub(pattern, function(match) table.insert(out, match) end) return out end local timeMatches = { { '(%d+)[:.](%d%d)[:.]?(%d?%d?)', function(h, m, s) -- Seconds will always return a match. if(s == '') then s = 0 end local duration = 0 local now = os.time() local date = os.date'*t' local ntime = date.hour * 60 * 60 + date.min * 60 + date.sec local atime = h * 60 * 60 + m * 60 + s -- Set the correct time of day. date.hour = h date.min = m date.sec = s -- If the alarm is right now or in the past, bump it to the next day. if(ntime >= atime) then date.day = date.day + 1 end return os.time(date) - now end }, {'^(%d+)w$', function(w) return w * 60 * 60 * 24 * 7 end}, {'^(%d+)d$', function(d) return d * 60 * 60 * 24 end}, {'^(%d+)[ht]$', function(h) return h * 60 * 60 end}, {'^(%d+)m$', function(m) return m * 60 end}, {'^(%d+)[^%p%w]*$', function(m) return m * 60 end, true}, {'^(%d+)s$', function(s) return s end}, } local parseTime = function(input) local duration = 0 local offset for i=1, #input do local found local str = input[i] for j=1, #timeMatches do local pattern, func, skipIfFound = unpack(timeMatches[j]) local a1, a2, a3 = str:match(pattern) if(a1 and not (skipIfFound and duration > 0)) then found = true duration = duration + func(a1, a2, a3) end end if(not found) then break end offset = i + 1 end if(duration ~= 0) then return duration, table.concat(input, ' ', offset) end end local alarm = function(self, source, destination, message) local duration, message = parseTime(split(message, '%S+')) -- Couldn't figure out what the user wanted. if(not duration) then return end -- 60 days or more? local nick = source.nick if(duration >= (60 * 60 * 24 * 60) or duration == 0) then return self:Msg('privmsg', destination, source, "%s: :'(", nick) end local id = 'Alarm: ' .. nick local runningTimer = self.timers[id] if(runningTimer) then -- Send a notification if we are overriding an old timer. if(runningTimer.utimestamp > os.time()) then if(runningTimer.message) then self:Notice( nick, 'Previously active timer set to trigger at %s with message "%s" has been removed.', os.date(dateFormat, runningTimer.utimestamp), runningTimer.message ) else self:Notice( nick, 'Previously active timer set to trigger at %s has been removed.', os.date(dateFormat, runningTimer.utimestamp) ) end end -- message is probably changed. runningTimer:stop(ivar2.Loop) end local timer = ev.Timer.new( function(loop, timer, revents) if(#message == 0) then message = 'Timer finished.' end self:Msg('privmsg', destination, source, '%s: %s', nick, message or 'Timer finished.') end, duration ) if(#message > 0) then timer.message = message end timer.utimestamp = os.time() + duration self:Notice(nick, "I'll poke you at %s.", os.date(dateFormat, timer.utimestamp)) self.timers[id] = timer timer:start(ivar2.Loop) end return { PRIVMSG = { ['^!alarm (.*)$'] = alarm, ['^!timer (.*)$'] = alarm, }, }
alarm: Only parse times without postfix as minutes, if there hasn't been a duration found earlier.
alarm: Only parse times without postfix as minutes, if there hasn't been a duration found earlier.
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
0210e9796eaae64db1279fb5d0e29d42eee1de5a
server-test-send-webpage.lua
server-test-send-webpage.lua
wifi.sta.disconnect() wifi.setmode(wifi.STATIONAP) local cfg = {} cfg.ssid = "mysticalNetwork" cfg.pwd = "mystical5000" wifi.ap.config(cfg) local srv=net.createServer(net.TCP, 300) srv:listen(80,function(conn) conn:on("receive", function(client, request) print("recieve") print(request) sendWebpage(client, 'mainpage.html') end) end) function sendWebpage(client, pageFile) line = file.readline() while (line~=nul) do file.open(pageFile) client:send(line) print(line) end end
wifi.sta.disconnect() wifi.setmode(wifi.STATIONAP) local cfg = {} cfg.ssid = "mysticalNetwork" cfg.pwd = "mystical5000" wifi.ap.config(cfg) local srv=net.createServer(net.TCP, 300) srv:listen(80,function(conn) conn:on("receive", function(client, request) print("recieve") print(request) sendWebpage(client, 'mainpage.html') end) end) function sendWebpage(client, pageFile) file.open(pageFile) line = file.readline() while (line~=nul) do client:send(line) print(line) line = file.readline() end end
fixed loop
fixed loop
Lua
mit
wordsforthewise/esp8266-server-test
c5bfbbbc2d4a5327a2a49e30e9106d82babb8279
mock/anim/AnimatorState.lua
mock/anim/AnimatorState.lua
module 'mock' local function _onAnimUpdate( anim ) local t = anim:getTime() local state = anim.source return state:onUpdate( t ) end local function _onAnimKeyFrame( timer, keyId, timesExecuted, time, value ) local state = timer.source local keys= state.keyEventMap[ keyId ] local time = timer:getTime() for i, key in ipairs( keys ) do key:executeEvent( state, time ) end end -------------------------------------------------------------------- CLASS: AnimatorState () :MODEL{} function AnimatorState:__init() self.anim = MOAIAnim.new() self.anim.source = self self.anim:setListener( MOAIAnim.EVENT_ACTION_POST_UPDATE, _onAnimUpdate ) self.anim:setListener( MOAIAnim.EVENT_TIMER_KEYFRAME, _onAnimKeyFrame ) self.trackContexts = {} self.updateListenerTracks = {} self.attrLinks = {} self.attrLinkCount = 0 self.throttle = 1 self.trackTargets = {} end function AnimatorState:setThrottle( t ) self.throttle = t self.anim:throttle( t ) end function AnimatorState:start() self.anim:start() end function AnimatorState:stop() self.anim:stop() end function AnimatorState:setMode( mode ) self.anim:setMode( mode ) end function AnimatorState:pause( paused ) self.anim:pause( paused ) end function AnimatorState:resume() self.anim:resume() end function AnimatorState:getTime() return self.anim:getTime() end function AnimatorState:apply( t ) local anim = self.anim local t0 = anim:getTime() anim:setTime( t ) anim:apply( t0, t ) t = anim:getTime() self:onUpdate( t ) end function AnimatorState:onUpdate( t ) for track, target in pairs( self.updateListenerTracks ) do track:apply( self, target, t ) end end function AnimatorState:loadClip( animator, clip ) self.animator = animator self.targetRoot = animator._entity self.targetScene = self.targetRoot.scene self.clip = clip local anim = self.anim local context = clip:getBuiltContext() anim:setSpan( context.length ) for track in pairs( context.playableTracks ) do track:onStateLoad( self ) end anim:reserveLinks( self.attrLinkCount ) for i, linkInfo in ipairs( self.attrLinks ) do local track, curve, target, attrId, asDelta = unpack( linkInfo ) anim:setLink( i, curve, target, attrId, asDelta ) end --event key anim:setCurve( context.eventCurve ) self.keyEventMap = context.keyEventMap end function AnimatorState:addUpdateListenerTrack( track, target ) self.updateListenerTracks[ track ] = target end function AnimatorState:addAttrLink( track, curve, target, id, asDelta ) self.attrLinkCount = self.attrLinkCount + 1 self.attrLinks[ self.attrLinkCount ] = { track, curve, target, id, asDelta or false } end function AnimatorState:findTarget( targetPath ) local obj = targetPath:get( self.targetRoot, self.targetScene ) return obj end function AnimatorState:getTargetRoot() return self.targetRoot, self.targetScene end function AnimatorState:setTrackTarget( track, target ) self.trackTargets[ track ] = target end function AnimatorState:getTrackTarget( track ) return self.trackTargets[ track ] end -- function AnimatorState:addEventKey( track ) -- end
module 'mock' local function _onAnimUpdate( anim ) local t = anim:getTime() local state = anim.source return state:onUpdate( t ) end local function _onAnimKeyFrame( timer, keyId, timesExecuted, time, value ) local state = timer.source local keys= state.keyEventMap[ keyId ] local time = timer:getTime() for i, key in ipairs( keys ) do key:executeEvent( state, time ) end end -------------------------------------------------------------------- CLASS: AnimatorState () :MODEL{} function AnimatorState:__init() self.anim = MOAIAnim.new() self.anim.source = self self.anim:setListener( MOAIAnim.EVENT_ACTION_POST_UPDATE, _onAnimUpdate ) self.anim:setListener( MOAIAnim.EVENT_TIMER_KEYFRAME, _onAnimKeyFrame ) self.trackContexts = {} self.updateListenerTracks = {} self.attrLinks = {} self.attrLinkCount = 0 self.throttle = 1 self.trackTargets = {} self.stopping = false end function AnimatorState:setThrottle( t ) self.throttle = t self.anim:throttle( t ) end function AnimatorState:start() self.anim:start() end function AnimatorState:stop() self.stopping = true self.anim:stop() end function AnimatorState:isActive() return self.anim:isActive() end function AnimatorState:isDone() return self.anim:isDone() end function AnimatorState:isPaused() return self.anim:isPaused() end function AnimatorState:isBusy() return self.anim:isBusy() end function AnimatorState:isDone() return self.anim:isDone() end function AnimatorState:setMode( mode ) self.anim:setMode( mode or MOAITimer.NORMAL ) end function AnimatorState:pause( paused ) self.anim:pause( paused ) end function AnimatorState:resume() self.anim:resume() end function AnimatorState:getTime() return self.anim:getTime() end function AnimatorState:apply( t ) local anim = self.anim local t0 = anim:getTime() anim:setTime( t ) anim:apply( t0, t ) t = anim:getTime() self:onUpdate( t ) end function AnimatorState:onUpdate( t ) for track, target in pairs( self.updateListenerTracks ) do if self.stopping then return end --edge case: new clip started in apply track:apply( self, target, t ) end end function AnimatorState:loadClip( animator, clip ) self.animator = animator self.targetRoot = animator._entity self.targetScene = self.targetRoot.scene self.clip = clip local anim = self.anim local context = clip:getBuiltContext() anim:setSpan( context.length ) for track in pairs( context.playableTracks ) do track:onStateLoad( self ) end anim:reserveLinks( self.attrLinkCount ) for i, linkInfo in ipairs( self.attrLinks ) do local track, curve, target, attrId, asDelta = unpack( linkInfo ) anim:setLink( i, curve, target, attrId, asDelta ) end --event key anim:setCurve( context.eventCurve ) self.keyEventMap = context.keyEventMap end function AnimatorState:addUpdateListenerTrack( track, target ) self.updateListenerTracks[ track ] = target end function AnimatorState:addAttrLink( track, curve, target, id, asDelta ) self.attrLinkCount = self.attrLinkCount + 1 self.attrLinks[ self.attrLinkCount ] = { track, curve, target, id, asDelta or false } end function AnimatorState:findTarget( targetPath ) local obj = targetPath:get( self.targetRoot, self.targetScene ) return obj end function AnimatorState:getTargetRoot() return self.targetRoot, self.targetScene end function AnimatorState:setTrackTarget( track, target ) self.trackTargets[ track ] = target end function AnimatorState:getTrackTarget( track ) return self.trackTargets[ track ] end -- function AnimatorState:addEventKey( track ) -- end
fix minor animator bug
fix minor animator bug
Lua
mit
tommo/mock
acad517e5ce23a82979a87155bb639f91098adaf
xmake/core/base/winos.lua
xmake/core/base/winos.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file winos.lua -- -- define module: winos local winos = winos or {} -- load modules local os = require("base/os") local semver = require("base/semver") -- get windows version from name function winos._version_from_name(name) -- make defined values winos._VERSIONS = winos._VERSIONS or { nt4 = "4.0" , win2k = "5.0" , winxp = "5.1" , ws03 = "5.2" , win6 = "6.0" , vista = "6.0" , ws08 = "6.0" , longhorn = "6.0" , win7 = "6.1" , win8 = "6.2" , winblue = "6.3" , win81 = "6.3" , win10 = "10.0" } return winos._VERSIONS[name] end -- v1 == v2 with name (winxp, win10, ..)? function winos._version_eq(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) == 0 else return semver.compare(self:rawstr(), version) == 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) == 0 end end -- v1 < v2 with name (winxp, win10, ..)? function winos._version_lt(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) < 0 else return semver.compare(self:rawstr(), version) < 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) < 0 end end -- v1 <= v2 with name (winxp, win10, ..)? function winos._version_le(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) <= 0 else return semver.compare(self:rawstr(), version) <= 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) <= 0 end end -- get system version function winos.version() -- get it from cache first if winos._VERSION ~= nil then return winos._VERSION end -- get winver local winver = nil local ok, verstr = os.iorun("cmd /c ver") if ok and verstr then winver = verstr:match("%[.-(%d+%.%d+%.%d+)]") if winver then winver = winver:trim() end winver = semver.new(winver) end -- rewrite comparator if winver then winver.eq = winos._version_eq winver.lt = winos._version_lt winver.le = winos._version_le end -- save to cache winos._VERSION = winver or false -- done return winver end -- return module: winos return winos
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file winos.lua -- -- define module: winos local winos = winos or {} -- load modules local os = require("base/os") local semver = require("base/semver") -- get windows version from name function winos._version_from_name(name) -- make defined values winos._VERSIONS = winos._VERSIONS or { nt4 = "4.0" , win2k = "5.0" , winxp = "5.1" , ws03 = "5.2" , win6 = "6.0" , vista = "6.0" , ws08 = "6.0" , longhorn = "6.0" , win7 = "6.1" , win8 = "6.2" , winblue = "6.3" , win81 = "6.3" , win10 = "10.0" } return winos._VERSIONS[name] end -- v1 == v2 with name (winxp, win10, ..)? function winos._version_eq(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) == 0 else return semver.compare(self:rawstr(), version) == 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) == 0 end end -- v1 < v2 with name (winxp, win10, ..)? function winos._version_lt(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) < 0 else return semver.compare(self:rawstr(), version) < 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) < 0 end end -- v1 <= v2 with name (winxp, win10, ..)? function winos._version_le(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) <= 0 else return semver.compare(self:rawstr(), version) <= 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) <= 0 end end -- get system version function winos.version() -- get it from cache first if winos._VERSION ~= nil then return winos._VERSION end -- get winver local winver = nil local ok, verstr = os.iorun("cmd /c ver") if ok and verstr then winver = verstr:match("%[.-([%d%.]+)]") if winver then winver = winver:trim() end local sem_winver = nil local seg = 0 for num in winver:gmatch("%d+") do if seg == 0 then sem_winver = num elseif seg == 3 then sem_winver = sem_winver .. "+" .. num else sem_winver = sem_winver .. "." .. num end seg = seg + 1 end winver = semver.new(sem_winver) end -- rewrite comparator if winver then winver.eq = winos._version_eq winver.lt = winos._version_lt winver.le = winos._version_le end -- save to cache winos._VERSION = winver or false -- done return winver end -- return module: winos return winos
fix winver
fix winver
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
46de106e8a7aeb3d64453c59cae69de3106e2f33
inputbox.lua
inputbox.lua
require "rendertext" require "keys" require "graphics" InputBox = { -- Class vars: h = 100, input_slot_w = nil, input_start_x = 145, input_start_y = nil, input_cur_x = nil, -- points to the start of next input pos input_bg = 0, input_string = "", shiftmode = false, altmode = false, cursor = nil, -- font for displaying input content -- we have to use mono here for better distance controlling face = freetype.newBuiltinFace("mono", 25), fhash = "m25", fheight = 25, fwidth = 15, } function InputBox:refreshText() -- clear previous painted text fb.bb:paintRect(140, self.input_start_y-19, self.input_slot_w, self.fheight, self.input_bg) -- paint new text renderUtf8Text(fb.bb, self.input_start_x, self.input_start_y, self.face, self.fhash, self.input_string, 0) end function InputBox:addChar(char) self.cursor:clear() -- draw new text local cur_index = (self.cursor.x_pos + 3 - self.input_start_x) / self.fwidth self.input_string = self.input_string:sub(0,cur_index)..char.. self.input_string:sub(cur_index+1) self:refreshText() self.input_cur_x = self.input_cur_x + self.fwidth -- draw new cursor self.cursor:moveHorizontal(self.fwidth) self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:delChar() if self.input_start_x == self.input_cur_x then return end self.cursor:clear() -- draw new text local cur_index = (self.cursor.x_pos + 3 - self.input_start_x) / self.fwidth self.input_string = self.input_string:sub(0,cur_index-1).. self.input_string:sub(cur_index+1, -1) self:refreshText() self.input_cur_x = self.input_cur_x - self.fwidth -- draw new cursor self.cursor:moveHorizontal(-self.fwidth) self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:clearText() self.cursor:clear() self.input_string = "" self:refreshText() self.cursor.x_pos = self.input_start_x - 3 self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:drawBox(ypos, w, h, title) -- draw input border fb.bb:paintRect(20, ypos, w, h, 5) -- draw input slot fb.bb:paintRect(140, ypos + 10, w - 130, h - 20, self.input_bg) -- draw input title renderUtf8Text(fb.bb, 35, self.input_start_y, self.face, self.fhash, title, true) end ---------------------------------------------------------------------- -- InputBox:input() -- -- @title: input prompt for the box -- @d_text: default to nil (used to set default text in input slot) ---------------------------------------------------------------------- function InputBox:input(ypos, height, title, d_text) -- do some initilization self.h = height self.input_start_y = ypos + 35 self.input_cur_x = self.input_start_x self.input_slot_w = fb.bb:getWidth() - 170 self.cursor = Cursor:new { x_pos = self.input_start_x - 3, y_pos = ypos + 13, h = 30, } -- draw box and content w = fb.bb:getWidth() - 40 h = height - 45 self:drawBox(ypos, w, h, title) if d_text then self.input_string = d_text self.input_cur_x = self.input_cur_x + (self.fwidth * d_text:len()) self.cursor.x_pos = self.cursor.x_pos + (self.fwidth * d_text:len()) self:refreshText() end self.cursor:draw() fb:refresh(1, 20, ypos, w, h) while true do local ev = input.waitForEvent() ev.code = adjustKeyEvents(ev) if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then --local secs, usecs = util.gettime() if ev.code == KEY_FW_UP then elseif ev.code == KEY_FW_DOWN then elseif ev.code == KEY_A then self:addChar("a") elseif ev.code == KEY_B then self:addChar("b") elseif ev.code == KEY_C then self:addChar("c") elseif ev.code == KEY_D then self:addChar("d") elseif ev.code == KEY_E then self:addChar("e") elseif ev.code == KEY_F then self:addChar("f") elseif ev.code == KEY_G then self:addChar("g") elseif ev.code == KEY_H then self:addChar("h") elseif ev.code == KEY_I then self:addChar("i") elseif ev.code == KEY_J then self:addChar("j") elseif ev.code == KEY_K then self:addChar("k") elseif ev.code == KEY_L then self:addChar("l") elseif ev.code == KEY_M then self:addChar("m") elseif ev.code == KEY_N then self:addChar("n") elseif ev.code == KEY_O then self:addChar("o") elseif ev.code == KEY_P then self:addChar("p") elseif ev.code == KEY_Q then self:addChar("q") elseif ev.code == KEY_R then self:addChar("r") elseif ev.code == KEY_S then self:addChar("s") elseif ev.code == KEY_T then self:addChar("t") elseif ev.code == KEY_U then self:addChar("u") elseif ev.code == KEY_V then self:addChar("v") elseif ev.code == KEY_W then self:addChar("w") elseif ev.code == KEY_X then self:addChar("x") elseif ev.code == KEY_Y then self:addChar("y") elseif ev.code == KEY_Z then self:addChar("z") elseif ev.code == KEY_1 then self:addChar("1") elseif ev.code == KEY_2 then self:addChar("2") elseif ev.code == KEY_3 then self:addChar("3") elseif ev.code == KEY_4 then self:addChar("4") elseif ev.code == KEY_5 then self:addChar("5") elseif ev.code == KEY_6 then self:addChar("6") elseif ev.code == KEY_7 then self:addChar("7") elseif ev.code == KEY_8 then self:addChar("8") elseif ev.code == KEY_9 then self:addChar("9") elseif ev.code == KEY_0 then self:addChar("0") elseif ev.code == KEY_SPACE then self:addChar(" ") elseif ev.code == KEY_PGFWD then elseif ev.code == KEY_PGBCK then elseif ev.code == KEY_FW_LEFT then if (self.cursor.x_pos + 3) > self.input_start_x then self.cursor:moveHorizontalAndDraw(-self.fwidth) fb:refresh(1, self.input_start_x-5, ypos, self.input_slot_w, h) end elseif ev.code == KEY_FW_RIGHT then if (self.cursor.x_pos + 3) < self.input_cur_x then self.cursor:moveHorizontalAndDraw(self.fwidth) fb:refresh(1,self.input_start_x-5, ypos, self.input_slot_w, h) end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then if self.input_string == "" then self.input_string = nil end break elseif ev.code == KEY_DEL then if Keys.shiftmode then self:clearText() else self:delChar() end elseif ev.code == KEY_BACK or ev.code == KEY_HOME then self.input_string = nil break end --local nsecs, nusecs = util.gettime() --local dur = (nsecs - secs) * 1000000 + nusecs - usecs --print("E: T="..ev.type.." V="..ev.value.." C="..ev.code.." DUR="..dur) end -- if end -- while return self.input_string end
require "rendertext" require "keys" require "graphics" InputBox = { -- Class vars: h = 100, input_slot_w = nil, input_start_x = 145, input_start_y = nil, input_cur_x = nil, -- points to the start of next input pos input_bg = 0, input_string = "", shiftmode = false, altmode = false, cursor = nil, -- font for displaying input content -- we have to use mono here for better distance controlling face = freetype.newBuiltinFace("mono", 25), fhash = "m25", fheight = 25, fwidth = 15, } function InputBox:refreshText() -- clear previous painted text fb.bb:paintRect(140, self.input_start_y-19, self.input_slot_w, self.fheight, self.input_bg) -- paint new text renderUtf8Text(fb.bb, self.input_start_x, self.input_start_y, self.face, self.fhash, self.input_string, 0) end function InputBox:addChar(char) self.cursor:clear() -- draw new text local cur_index = (self.cursor.x_pos + 3 - self.input_start_x) / self.fwidth self.input_string = self.input_string:sub(0,cur_index)..char.. self.input_string:sub(cur_index+1) self:refreshText() self.input_cur_x = self.input_cur_x + self.fwidth -- draw new cursor self.cursor:moveHorizontal(self.fwidth) self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:delChar() if self.input_start_x == self.input_cur_x then return end self.cursor:clear() -- draw new text local cur_index = (self.cursor.x_pos + 3 - self.input_start_x) / self.fwidth self.input_string = self.input_string:sub(0,cur_index-1).. self.input_string:sub(cur_index+1, -1) self:refreshText() self.input_cur_x = self.input_cur_x - self.fwidth -- draw new cursor self.cursor:moveHorizontal(-self.fwidth) self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:clearText() self.cursor:clear() self.input_string = "" self:refreshText() self.cursor.x_pos = self.input_start_x - 3 self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:drawBox(ypos, w, h, title) -- draw input border fb.bb:paintRect(20, ypos, w, h, 5) -- draw input slot fb.bb:paintRect(140, ypos + 10, w - 130, h - 20, self.input_bg) -- draw input title renderUtf8Text(fb.bb, 35, self.input_start_y, self.face, self.fhash, title, true) end ---------------------------------------------------------------------- -- InputBox:input() -- -- @title: input prompt for the box -- @d_text: default to nil (used to set default text in input slot) ---------------------------------------------------------------------- function InputBox:input(ypos, height, title, d_text) -- do some initilization self.h = height self.input_start_y = ypos + 35 self.input_cur_x = self.input_start_x self.input_slot_w = fb.bb:getWidth() - 170 self.cursor = Cursor:new { x_pos = self.input_start_x - 3, y_pos = ypos + 13, h = 30, } -- draw box and content w = fb.bb:getWidth() - 40 h = height - 45 self:drawBox(ypos, w, h, title) if d_text then self.input_string = d_text self.input_cur_x = self.input_cur_x + (self.fwidth * d_text:len()) self.cursor.x_pos = self.cursor.x_pos + (self.fwidth * d_text:len()) self:refreshText() end self.cursor:draw() fb:refresh(1, 20, ypos, w, h) while true do local ev = input.waitForEvent() ev.code = adjustKeyEvents(ev) if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then --local secs, usecs = util.gettime() if ev.code == KEY_FW_UP then elseif ev.code == KEY_FW_DOWN then elseif ev.code == KEY_A then self:addChar("a") elseif ev.code == KEY_B then self:addChar("b") elseif ev.code == KEY_C then self:addChar("c") elseif ev.code == KEY_D then self:addChar("d") elseif ev.code == KEY_E then self:addChar("e") elseif ev.code == KEY_F then self:addChar("f") elseif ev.code == KEY_G then self:addChar("g") elseif ev.code == KEY_H then self:addChar("h") elseif ev.code == KEY_I then self:addChar("i") elseif ev.code == KEY_J then self:addChar("j") elseif ev.code == KEY_K then self:addChar("k") elseif ev.code == KEY_L then self:addChar("l") elseif ev.code == KEY_M then self:addChar("m") elseif ev.code == KEY_N then self:addChar("n") elseif ev.code == KEY_O then self:addChar("o") elseif ev.code == KEY_P then self:addChar("p") elseif ev.code == KEY_Q then self:addChar("q") elseif ev.code == KEY_R then self:addChar("r") elseif ev.code == KEY_S then self:addChar("s") elseif ev.code == KEY_T then self:addChar("t") elseif ev.code == KEY_U then self:addChar("u") elseif ev.code == KEY_V then self:addChar("v") elseif ev.code == KEY_W then self:addChar("w") elseif ev.code == KEY_X then self:addChar("x") elseif ev.code == KEY_Y then self:addChar("y") elseif ev.code == KEY_Z then self:addChar("z") elseif ev.code == KEY_1 then self:addChar("1") elseif ev.code == KEY_2 then self:addChar("2") elseif ev.code == KEY_3 then self:addChar("3") elseif ev.code == KEY_4 then self:addChar("4") elseif ev.code == KEY_5 then self:addChar("5") elseif ev.code == KEY_6 then self:addChar("6") elseif ev.code == KEY_7 then self:addChar("7") elseif ev.code == KEY_8 then self:addChar("8") elseif ev.code == KEY_9 then self:addChar("9") elseif ev.code == KEY_0 then self:addChar("0") elseif ev.code == KEY_SPACE then self:addChar(" ") elseif ev.code == KEY_PGFWD then elseif ev.code == KEY_PGBCK then elseif ev.code == KEY_FW_LEFT then if (self.cursor.x_pos + 3) > self.input_start_x then self.cursor:moveHorizontalAndDraw(-self.fwidth) fb:refresh(1, self.input_start_x-5, ypos, self.input_slot_w, h) end elseif ev.code == KEY_FW_RIGHT then if (self.cursor.x_pos + 3) < self.input_cur_x then self.cursor:moveHorizontalAndDraw(self.fwidth) fb:refresh(1,self.input_start_x-5, ypos, self.input_slot_w, h) end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then if self.input_string == "" then self.input_string = nil end break elseif ev.code == KEY_DEL then if Keys.shiftmode then self:clearText() else self:delChar() end elseif ev.code == KEY_BACK or ev.code == KEY_HOME then self.input_string = nil break end --local nsecs, nusecs = util.gettime() --local dur = (nsecs - secs) * 1000000 + nusecs - usecs --print("E: T="..ev.type.." V="..ev.value.." C="..ev.code.." DUR="..dur) end -- if end -- while local return_str = self.input_string self.input_string = "" return return_str end
fix: clear input_text before input result return
fix: clear input_text before input result return
Lua
agpl-3.0
houqp/koreader,Hzj-jie/koreader-base,mihailim/koreader,Hzj-jie/koreader,Hzj-jie/koreader-base,houqp/koreader-base,NickSavage/koreader,houqp/koreader-base,ashang/koreader,apletnev/koreader,Frenzie/koreader,houqp/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,noname007/koreader,apletnev/koreader-base,chihyang/koreader,frankyifei/koreader-base,NiLuJe/koreader,koreader/koreader-base,NiLuJe/koreader,koreader/koreader-base,apletnev/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,Markismus/koreader,koreader/koreader,apletnev/koreader-base,koreader/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,poire-z/koreader,pazos/koreader,frankyifei/koreader-base,mwoz123/koreader,koreader/koreader-base,poire-z/koreader,Frenzie/koreader,NiLuJe/koreader-base,NiLuJe/koreader-base,robert00s/koreader,koreader/koreader-base,frankyifei/koreader-base,chrox/koreader,frankyifei/koreader,ashhher3/koreader,lgeek/koreader,NiLuJe/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base
f707ad8b74cb1a45dc5bd68612be2f1be109cb5d
spec/02-integration/02-dao/02-migrations_spec.lua
spec/02-integration/02-dao/02-migrations_spec.lua
local helpers = require "spec.02-integration.02-dao.helpers" local utils = require "kong.tools.utils" local Factory = require "kong.dao.factory" helpers.for_each_dao(function(kong_config) describe("Model migrations with DB: #"..kong_config.database, function() local factory setup(function() -- some `setup` functions also use `factory` and they run before the `before_each` chain -- hence we need to set it here, and again in `before_each`. factory = assert(Factory.new(kong_config)) factory:drop_schema() end) before_each(function() factory = assert(Factory.new(kong_config)) end) describe("current_migrations()", function() it("should return an empty table if no migrations have been run", function() local cur_migrations, err = factory:current_migrations() assert.falsy(err) assert.same({}, cur_migrations) end) if kong_config.database == "cassandra" then it("returns empty migrations on non-existing Cassandra keyspace", function() local invalid_conf = utils.shallow_copy(kong_config) invalid_conf.cassandra_keyspace = "_inexistent_" local xfactory = assert(Factory.new(invalid_conf)) local cur_migrations, err = xfactory:current_migrations() assert.is_nil(err) assert.same({}, cur_migrations) end) end end) describe("migrations_modules()", function() it("should return the core migrations", function() local migrations = factory:migrations_modules() assert.is_table(migrations) assert.is_table(migrations.core) assert.True(#migrations.core > 0) end) end) --- -- Integration behavior. -- Must run in order. describe("[INTEGRATION]", function() local n_ids = 0 local flatten_migrations = {} setup(function() factory:drop_schema() for identifier, migs in pairs(factory:migrations_modules()) do n_ids = n_ids + 1 for _, mig in ipairs(migs) do flatten_migrations[#flatten_migrations + 1] = { identifier = identifier, name = mig.name } end end end) it("should run the migrations with callbacks", function() local on_migration = spy.new(function() end) local on_success = spy.new(function() end) local ok, err = factory:run_migrations(on_migration, on_success) assert.falsy(err) assert.True(ok) assert.spy(on_migration).was_called(n_ids) assert.spy(on_success).was_called(#flatten_migrations) for _, mig in ipairs(flatten_migrations) do assert.spy(on_migration).was_called_with(mig.identifier, factory:infos()) assert.spy(on_success).was_called_with(mig.identifier, mig.name, factory:infos()) end end) it("should return the migrations recorded as executed", function() local cur_migrations, err = factory:current_migrations() assert.falsy(err) assert.truthy(next(cur_migrations)) assert.is_table(cur_migrations.core) end) it("should not run any migration on subsequent run", function() local on_migration = spy.new(function() end) local on_success = spy.new(function() end) local ok, err = factory:run_migrations() assert.falsy(err) assert.True(ok) assert.spy(on_migration).was_not_called() assert.spy(on_success).was_not_called() end) end) describe("errors", function() it("returns errors prefixed by the DB type in __tostring()", function() local pg_port = kong_config.pg_port local cassandra_port = kong_config.cassandra_port local cassandra_timeout = kong_config.cassandra_timeout finally(function() kong_config.pg_port = pg_port kong_config.cassandra_port = cassandra_port kong_config.cassandra_timeout = cassandra_timeout end) kong_config.pg_port = 3333 kong_config.cassandra_port = 3333 kong_config.cassandra_timeout = 1000 assert.error_matches(function() local fact = assert(Factory.new(kong_config)) assert(fact:run_migrations()) end, "["..kong_config.database.." error]", nil, true) end) end) end) end)
local helpers = require "spec.02-integration.02-dao.helpers" local utils = require "kong.tools.utils" local Factory = require "kong.dao.factory" helpers.for_each_dao(function(kong_config) describe("Model migrations with DB: #"..kong_config.database, function() local factory setup(function() -- some `setup` functions also use `factory` and they run before the `before_each` chain -- hence we need to set it here, and again in `before_each`. factory = assert(Factory.new(kong_config)) factory:drop_schema() end) before_each(function() factory = assert(Factory.new(kong_config)) end) describe("current_migrations()", function() it("should return an empty table if no migrations have been run", function() local cur_migrations, err = factory:current_migrations() assert.falsy(err) assert.same({}, cur_migrations) end) if kong_config.database == "cassandra" then it("returns empty migrations on non-existing Cassandra keyspace", function() local invalid_conf = utils.shallow_copy(kong_config) invalid_conf.cassandra_keyspace = "_inexistent_" local xfactory = assert(Factory.new(invalid_conf)) local cur_migrations, err = xfactory:current_migrations() assert.is_nil(err) assert.same({}, cur_migrations) end) end end) describe("migrations_modules()", function() it("should return the core migrations", function() local migrations = factory:migrations_modules() assert.is_table(migrations) assert.is_table(migrations.core) assert.True(#migrations.core > 0) end) end) --- -- Integration behavior. -- Must run in order. describe("[INTEGRATION]", function() local n_ids = 0 local flatten_migrations = {} setup(function() factory:drop_schema() for identifier, migs in pairs(factory:migrations_modules()) do n_ids = n_ids + 1 for _, mig in ipairs(migs) do flatten_migrations[#flatten_migrations + 1] = { identifier = identifier, name = mig.name } end end end) it("should run the migrations with callbacks", function() local on_migration = spy.new(function() end) local on_success = spy.new(function() end) local ok, err = factory:run_migrations(on_migration, on_success) assert.falsy(err) assert.True(ok) assert.spy(on_migration).was_called(n_ids) assert.spy(on_success).was_called(#flatten_migrations) for _, mig in ipairs(flatten_migrations) do assert.spy(on_migration).was_called_with(mig.identifier, factory:infos()) assert.spy(on_success).was_called_with(mig.identifier, mig.name, factory:infos()) end end) it("should return the migrations recorded as executed", function() local cur_migrations, err = factory:current_migrations() assert.falsy(err) assert.truthy(next(cur_migrations)) assert.is_table(cur_migrations.core) end) it("should not run any migration on subsequent run", function() local on_migration = spy.new(function() end) local on_success = spy.new(function() end) local ok, err = factory:run_migrations() assert.falsy(err) assert.True(ok) assert.spy(on_migration).was_not_called() assert.spy(on_success).was_not_called() end) end) describe("errors", function() it("returns errors prefixed by the DB type in __tostring()", function() local pg_port = kong_config.pg_port local cassandra_port = kong_config.cassandra_port local cassandra_timeout = kong_config.cassandra_timeout finally(function() kong_config.pg_port = pg_port kong_config.cassandra_port = cassandra_port kong_config.cassandra_timeout = cassandra_timeout ngx.shared.cassandra:flush_all() end) kong_config.pg_port = 3333 kong_config.cassandra_port = 3333 kong_config.cassandra_timeout = 1000 assert.error_matches(function() local fact = assert(Factory.new(kong_config)) assert(fact:run_migrations()) end, "["..kong_config.database.." error]", nil, true) end) end) end) end)
tests(dao) fix failing C* tests due to host being considered down
tests(dao) fix failing C* tests due to host being considered down Clean the shm after the forced failure in this test, so that the next time we spawn a C* DAO, the shm does not contain mislieading informations about the `127.0.0.1` peer.
Lua
apache-2.0
shiprabehera/kong,Kong/kong,akh00/kong,ccyphers/kong,Kong/kong,jebenexer/kong,li-wl/kong,Kong/kong,icyxp/kong,Mashape/kong,salazar/kong
2ff8f11b63a86defc1f941287ca607acb46cece7
src/entity.lua
src/entity.lua
Entity = class("Entity") function Entity:__init(parent) self.components = {} self.eventManager = nil self.alive = true if parent then self:setParent(parent) else parent = nil end self.children = {} end -- Sets the entities component of this type to the given component. -- An entity can only have one Component of each type. function Entity:add(component) if self.components[component.__name] then print("Trying to add " .. component.__name .. ", but it's already existing. Please use Entity:set to overwrite a component in an entity.") else self.components[component.__name] = component if self.eventManager then self.eventManager:fireEvent(ComponentAdded(self, component.__name)) end end end function Entity:set(component) if self.components[component.__name] == nil then self:add(component) else self.components[component.__name] = component end end function Entity:addMultiple(componentList) for _, component in pairs(componentList) do self:add(component) end end -- Removes a component from the entity. function Entity:remove(name) if self.components[name] then self.components[name] = nil else print("Trying to remove unexisting component " .. name .. " from Entity. Please fix this") end if self.eventManager then self.eventManager:fireEvent(ComponentRemoved(self, name)) end end function Entity:setParent(parent) self.parent = parent end function Entity:getParent(parent) return self.parent end function Entity:registerAsChild() self.parent.children[self.id] = self end function Entity:get(name) return self.components[name] end function Entity:has(name) if self.components[name] then return true else return false end end function Entity:getComponents() return self.components end function Entity:has(name) return not (self:get(name) == nil) end
Entity = class("Entity") function Entity:__init(parent) self.components = {} self.eventManager = nil self.alive = true if parent then self:setParent(parent) else parent = nil end self.children = {} end -- Sets the entities component of this type to the given component. -- An entity can only have one Component of each type. function Entity:add(component) if self.components[component.__name] then print("Trying to add " .. component.__name .. ", but it's already existing. Please use Entity:set to overwrite a component in an entity.") else self.components[component.__name] = component if self.eventManager then self.eventManager:fireEvent(ComponentAdded(self, component.__name)) end end end function Entity:set(component) if self.components[component.__name] == nil then self:add(component) else self.components[component.__name] = component end end function Entity:addMultiple(componentList) for _, component in pairs(componentList) do self:add(component) end end -- Removes a component from the entity. function Entity:remove(name) if self.components[name] then self.components[name] = nil else print("Trying to remove unexisting component " .. name .. " from Entity. Please fix this") end if self.eventManager then self.eventManager:fireEvent(ComponentRemoved(self, name)) end end function Entity:setParent(parent) if self.parent then self.parent.children[self.id] = nil end self.parent = parent self:registerAsChild() end function Entity:getParent(parent) return self.parent end function Entity:registerAsChild() if self.id then self.parent.children[self.id] = self end end function Entity:get(name) return self.components[name] end function Entity:has(name) if self.components[name] then return true else return false end end function Entity:getComponents() return self.components end function Entity:has(name) return not (self:get(name) == nil) end
Fixed Entity:setParent not updating the parent's children table
Fixed Entity:setParent not updating the parent's children table
Lua
mit
xpol/lovetoys,takaaptech/lovetoys
1eb9be75e8924379e03234f09d15129bdb670389
lua/hmap.lua
lua/hmap.lua
local ffi = require "ffi" local log = require "log" local flowtrackerlib = ffi.load("../build/flowtracker") local tuple = require "tuple" local C = ffi.C local hmapTemplate = [[ typedef struct hmapk{key_size}v{value_size} hmapk{key_size}v{value_size}; typedef struct hmapk{key_size}v{value_size}_accessor hmapk{key_size}v{value_size}_accessor; hmapk{key_size}v{value_size}* hmapk{key_size}v{value_size}_create(); void hmapk{key_size}v{value_size}_delete(hmapk{key_size}v{value_size}* map); void hmapk{key_size}v{value_size}_clear(hmapk{key_size}v{value_size}* map); hmapk{key_size}v{value_size}_accessor* hmapk{key_size}v{value_size}_new_accessor(); void hmapk{key_size}v{value_size}_accessor_free(hmapk{key_size}v{value_size}_accessor* a); void hmapk{key_size}v{value_size}_accessor_release(hmapk{key_size}v{value_size}_accessor* a); bool hmapk{key_size}v{value_size}_access(hmapk{key_size}v{value_size}* map, hmapk{key_size}v{value_size}_accessor* a, const void* key); bool hmapk{key_size}v{value_size}_erase(hmapk{key_size}v{value_size}* map, hmapk{key_size}v{value_size}_accessor* a); uint8_t* hmapk{key_size}v{value_size}_accessor_get_value(hmapk{key_size}v{value_size}_accessor* a); ]] local module = {} local keySizes = { 8, 16, 32, 64 } local valueSizes = { 8, 16, 32, 64, 128 } -- Get tbb hash map with fitting key and value size function module.createTable(keySize, valueSize) local realKeySize, realKeySize = 0, 0 if keySize <= 8 then realKeySize = 8 elseif keySize <= 16 then realKeySize = 16 elseif keySize <= 32 then realKeySize = 32 elseif keySize <= 64 then realKeySize = 64 else log:error("Keys of size %d are not supported", keySize) return nil end if valueSize <= 8 then realValueSize = 8 elseif valueSize <= 16 then realValueSize = 16 elseif valueSize <= 32 then realValueSize = 32 elseif valueSize <= 64 then realValueSize = 64 elseif valueSize <= 128 then realValueSize = 128 else log:error("Values of size %d are not supported", valueSize) return nil end return flowtrackerlib["hmapk" .. realKeySize .. "v" .. realValueSize .. "_create"]() end function makeHashmapFor(keySize, valueSize) local map = {} function map:clear() flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_clear"](self) end function map:delete() flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_delete"](self) end function map:access(a, tpl) return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_access"](self, a, tpl) end function map.newAccessor() return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_new_accessor"]() end function map:erase(a) return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_erase"](self, a) end function map.keyBufSize() return keySize end local accessor = {} function accessor:get() return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_accessor_get_value"](self) end function accessor:free() return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_accessor_free"](self) end function accessor:release() return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_accessor_release"](self) end map.__index = map accessor.__index = accessor ffi.metatype("hmapk" .. keySize .. "v" .. valueSize, map) ffi.metatype("hmapk" .. keySize .. "v" .. valueSize .. "_accessor", accessor) return map end for _, k in pairs(keySizes) do for _, v in pairs(valueSizes) do local definition, _ = hmapTemplate:gsub("{value_size}", v) definition, _ = definition:gsub("{key_size}", k) ffi.cdef(definition) makeHashmapFor(k, v) end end -- FIXME: Are these really needed? -- local hmap8 = makeHashmapFor(8) -- local hmap16 = makeHashmapFor(16) -- local hmap32 = makeHashmapFor(32) -- local hmap64 = makeHashmapFor(64) -- local hmap128 = makeHashmapFor(128) return module
local ffi = require "ffi" local log = require "log" local flowtrackerlib = ffi.load("../build/flowtracker") local tuple = require "tuple" local C = ffi.C local hmapTemplate = [[ typedef struct hmapk{key_size}v{value_size} hmapk{key_size}v{value_size}; typedef struct hmapk{key_size}v{value_size}_accessor hmapk{key_size}v{value_size}_accessor; hmapk{key_size}v{value_size}* hmapk{key_size}v{value_size}_create(); void hmapk{key_size}v{value_size}_delete(hmapk{key_size}v{value_size}* map); void hmapk{key_size}v{value_size}_clear(hmapk{key_size}v{value_size}* map); hmapk{key_size}v{value_size}_accessor* hmapk{key_size}v{value_size}_new_accessor(); void hmapk{key_size}v{value_size}_accessor_free(hmapk{key_size}v{value_size}_accessor* a); void hmapk{key_size}v{value_size}_accessor_release(hmapk{key_size}v{value_size}_accessor* a); bool hmapk{key_size}v{value_size}_access(hmapk{key_size}v{value_size}* map, hmapk{key_size}v{value_size}_accessor* a, const void* key); bool hmapk{key_size}v{value_size}_erase(hmapk{key_size}v{value_size}* map, hmapk{key_size}v{value_size}_accessor* a); uint8_t* hmapk{key_size}v{value_size}_accessor_get_value(hmapk{key_size}v{value_size}_accessor* a); ]] local module = {} local keySizes = { 8, 16, 32, 64 } local valueSizes = { 8, 16, 32, 64, 128 } -- Get tbb hash map with fitting key and value size function module.createHashmap(keySize, valueSize) local realKeySize, realValueSize = 0, 0 if keySize <= 8 then realKeySize = 8 elseif keySize <= 16 then realKeySize = 16 elseif keySize <= 32 then realKeySize = 32 elseif keySize <= 64 then realKeySize = 64 else log:error("Keys of size %d are not supported", keySize) return nil end if valueSize <= 8 then realValueSize = 8 elseif valueSize <= 16 then realValueSize = 16 elseif valueSize <= 32 then realValueSize = 32 elseif valueSize <= 64 then realValueSize = 64 elseif valueSize <= 128 then realValueSize = 128 else log:error("Values of size %d are not supported", valueSize) return nil end return flowtrackerlib["hmapk" .. realKeySize .. "v" .. realValueSize .. "_create"]() end function makeHashmapFor(keySize, valueSize) local map = {} function map:clear() flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_clear"](self) end function map:delete() flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_delete"](self) end function map:access(a, tpl) return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_access"](self, a, tpl) end function map.newAccessor() return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_new_accessor"]() end function map:erase(a) return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_erase"](self, a) end function map.keyBufSize() return keySize end local accessor = {} function accessor:get() return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_accessor_get_value"](self) end function accessor:free() return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_accessor_free"](self) end function accessor:release() return flowtrackerlib["hmapk" .. keySize .. "v" .. valueSize .. "_accessor_release"](self) end map.__index = map accessor.__index = accessor ffi.metatype("hmapk" .. keySize .. "v" .. valueSize, map) ffi.metatype("hmapk" .. keySize .. "v" .. valueSize .. "_accessor", accessor) end for _, k in pairs(keySizes) do for _, v in pairs(valueSizes) do local definition, _ = hmapTemplate:gsub("{value_size}", v) definition, _ = definition:gsub("{key_size}", k) ffi.cdef(definition) makeHashmapFor(k, v) end end return module
Fix small errors in hash map library
Fix small errors in hash map library
Lua
mit
emmericp/FlowScope
ec0bdb0fd0b07be3baf49fc0225b1439fa9fb0e4
lua/wincent/commandt/private/prompt.lua
lua/wincent/commandt/private/prompt.lua
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors. -- SPDX-License-Identifier: BSD-2-Clause local prompt = {} local input_buffer = nil local input_window = nil local title_buffer = nil local title_window = nil prompt.show = function(options) -- TODO: merge options if input_buffer == nil then input_buffer = vim.api.nvim_create_buf( false, -- listed true -- scratch ) if input_buffer == 0 then error('wincent.commandt.private.prompt.show(): nvim_create_buf() failed') end local ps1 = '> ' vim.api.nvim_buf_set_option(input_buffer, 'buftype', 'prompt') vim.fn.prompt_setprompt(input_buffer, ps1) vim.api.nvim_buf_set_option(input_buffer, 'filetype', 'CommandTPrompt') vim.api.nvim_create_autocmd('TextChanged', { buffer = input_buffer, callback = function() if options and options.onchange then -- Should be able to use `prompt_getprompt()`, but it only returns the -- prompt prefix for some reason... -- local query = vim.fn.prompt_getprompt(input_buffer) local query = vim.api.nvim_get_current_line():sub(#ps1 + 1) options.onchange(query) end end, }) vim.api.nvim_create_autocmd('TextChangedI', { buffer = input_buffer, callback = function() if options and options.onchange then local query = vim.api.nvim_get_current_line():sub(#ps1 + 1) options.onchange(query) end end, }) end if input_window == nil then local width = vim.o.columns input_window = vim.api.nvim_open_win( input_buffer, true, -- enter { border = 'single', col = 0, focusable = false, height = 1, noautocmd = true, relative = 'editor', row = vim.o.lines - 3, style = 'minimal', width = width, } ) if input_window == 0 then error('wincent.commandt.private.prompt.show(): nvim_open_win() failed') end -- TODO: maybe watch for buffer destruction too -- TODO: watch for resize events vim.api.nvim_create_autocmd('WinClosed', { once = true, callback = function() input_window = nil end, }) vim.api.nvim_win_set_option(input_window, 'wrap', false) end vim.api.nvim_buf_set_lines( input_buffer, 0, -- start -1, -- end false, -- strict indexing {} -- replacement lines ) -- This is verbose; make utility methods... if title_buffer == nil then title_buffer = vim.api.nvim_create_buf( false, -- listed true -- scratch ) if title_buffer == 0 then error('wincent.commandt.private.prompt.show(): nvim_create_buf() failed') end vim.api.nvim_buf_set_option(title_buffer, 'buftype', 'nofile') vim.api.nvim_buf_set_option(title_buffer, 'filetype', 'CommandTTitle') end local prompt_title = 'Command-T [type]' if title_window == nil then title_window = vim.api.nvim_open_win( title_buffer, false, -- enter { col = 2, focusable = false, height = 1, noautocmd = true, relative = 'win', row = 0, -- BUG: can't show it above the border, only on top of the contents -- BUG: also a bug, doesn't appear immediately style = 'minimal', width = #prompt_title, win = prompt_window, zindex = 160, -- Default for floats is 50 } ) if title_window == 0 then error('wincent.commandt.private.prompt.show(): nvim_open_win() failed') end end vim.api.nvim_buf_set_lines( title_buffer, 0, -- start -1, -- end false, -- strict indexing { prompt_title } -- TODO: put actual type ) vim.api.nvim_set_current_win(input_window) vim.cmd('startinsert') -- vim.api.nvim_feedkeys( -- 'i', -- keys -- 'n', -- don't remap -- true -- escape K_SPECIAL bytes in keys -- ) end return prompt
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors. -- SPDX-License-Identifier: BSD-2-Clause local prompt = {} local input_buffer = nil local input_window = nil local title_buffer = nil local title_window = nil prompt.show = function(options) -- TODO: merge options if input_buffer == nil then input_buffer = vim.api.nvim_create_buf( false, -- listed true -- scratch ) if input_buffer == 0 then error('wincent.commandt.private.prompt.show(): nvim_create_buf() failed') end local ps1 = '> ' vim.api.nvim_buf_set_option(input_buffer, 'buftype', 'prompt') vim.fn.prompt_setprompt(input_buffer, ps1) vim.api.nvim_buf_set_option(input_buffer, 'filetype', 'CommandTPrompt') vim.api.nvim_create_autocmd('TextChanged', { buffer = input_buffer, callback = function() if options and options.onchange then -- Should be able to use `prompt_getprompt()`, but it only returns the -- prompt prefix for some reason... -- local query = vim.fn.prompt_getprompt(input_buffer) local query = vim.api.nvim_get_current_line():sub(#ps1 + 1) options.onchange(query) end end, }) vim.api.nvim_create_autocmd('TextChangedI', { buffer = input_buffer, callback = function() if options and options.onchange then local query = vim.api.nvim_get_current_line():sub(#ps1 + 1) options.onchange(query) end end, }) end if input_window == nil then local width = vim.o.columns input_window = vim.api.nvim_open_win( input_buffer, true, -- enter { border = 'single', col = 0, focusable = false, height = 1, noautocmd = true, relative = 'editor', row = vim.o.lines - 3, style = 'minimal', width = width, } ) if input_window == 0 then error('wincent.commandt.private.prompt.show(): nvim_open_win() failed') end -- TODO: maybe watch for buffer destruction too -- TODO: watch for resize events vim.api.nvim_create_autocmd('WinClosed', { once = true, callback = function() input_window = nil end, }) vim.api.nvim_win_set_option(input_window, 'wrap', false) end vim.api.nvim_buf_set_lines( input_buffer, 0, -- start -1, -- end false, -- strict indexing {} -- replacement lines ) -- This is verbose; make utility methods... if title_buffer == nil then title_buffer = vim.api.nvim_create_buf( false, -- listed true -- scratch ) if title_buffer == 0 then error('wincent.commandt.private.prompt.show(): nvim_create_buf() failed') end vim.api.nvim_buf_set_option(title_buffer, 'buftype', 'nofile') vim.api.nvim_buf_set_option(title_buffer, 'filetype', 'CommandTTitle') end local prompt_title = ' Command-T [type] ' if title_window == nil then title_window = vim.api.nvim_open_win( title_buffer, false, -- enter { col = 3, focusable = false, height = 1, noautocmd = true, relative = 'editor', row = vim.o.lines - 4, style = 'minimal', width = #prompt_title, win = prompt_window, zindex = 60, -- Default for floats is 50 } ) if title_window == 0 then error('wincent.commandt.private.prompt.show(): nvim_open_win() failed') end end vim.api.nvim_buf_set_lines( title_buffer, 0, -- start -1, -- end false, -- strict indexing { prompt_title } -- TODO: put actual type ) vim.api.nvim_set_current_win(input_window) vim.cmd('startinsert') -- vim.api.nvim_feedkeys( -- 'i', -- keys -- 'n', -- don't remap -- true -- escape K_SPECIAL bytes in keys -- ) end return prompt
fix(lua): make title appear on top of border
fix(lua): make title appear on top of border
Lua
bsd-2-clause
wincent/command-t,wincent/command-t,wincent/command-t
412177e01c94cb92eca322a78128c81810c6bce5
src/application.lua
src/application.lua
if not cfg.data.sta_ssid then print('Wifi: No config') return end if not (cfg.data.mqtt_user and cfg.data.mqtt_password) then print('MQTT: No config') return end local queue_report = nil local send_report = nil local flush_data = nil local mq_prefix = "/nodes/" .. node_id local mq = mqtt.Client(node_id, 120, cfg.data.mqtt_user, cfg.data.mqtt_password) local mq_connected = false mq_data = {} mq_data_ptr = 0 -- Register MQTT event handlers mq:lwt("/lwt", "offline", 0, 0) mq:on("connect", function(conn) print("MQTT: Connected") mq_connected = true -- Subscribe to all command topics for topic, handler in pairs(cmds) do if topic:sub(1, 1) ~= '/' then topic = mq_prefix .. '/commands/' .. topic end print('MQTT: Subscribing, topic:', topic) mq:subscribe(topic, 0, function(conn) end) end send_report() collectgarbage() end) mq:on("offline", function(conn) print("MQTT: Disconnected") mq_connected = false end) mq:on("message", function(conn, topic, data) print("MQTT: Received, topic:", topic) local part = topic:sub(1, #mq_prefix + 1) == mq_prefix .. '/' and topic:sub(#mq_prefix + 1) or topic local cmd = part:match('/commands/(.+)') or part local res = handleCmd(cmd, data) if res ~= nil then mq_data[#mq_data + 1] = { mq_prefix .. '/responses' .. part, res } flush_data() end cmd = nil part = nil res = nil collectgarbage() if data ~= nil then print("MQTT: Data:", data) end end) flush_data = function(callback) mq_data_ptr = mq_data_ptr + 1 if mq_data_ptr > #mq_data then mq_data = {} mq_data_ptr = 0 if callback ~= nil then callback() end else local d = mq_data[mq_data_ptr] mq:publish(d[1], d[2], 0, 0, function(conn) flush_data(callback) end) d = nil end collectgarbage() end queue_report = function() if cfg.data.sleep then if mq_connected then mq:close() end node.dsleep(cfg.data.report_interval * 1000 * 1000, 4) else tmr.stop(0) tmr.alarm(0, cfg.data.report_interval * 1000, 0, function() send_report() collectgarbage() end) end end send_report = function() if not cfg.data.sleep then queue_report() end if not wifi.sta.getip() then print('Report: No Wifi') wifi.sta.connect() elseif not mq_connected then print('Report: No MQTT') mq:connect(cfg.data.mqtt_host, cfg.data.mqtt_port, cfg.data.mqtt_secure) else print('Report: Sending..') mq_data = triggerModules('_report_data') mq_data = tablesMerge(mq_data) for i, v in pairs(mq_data) do mq_data[i] = nil mq_data[mq_prefix .. i] = v end collectgarbage() flush_data(function() print('Report: Finished') if cfg.data.sleep then queue_report() end end) end end wifi.setphymode(wifi.PHYMODE_N) wifi.setmode(wifi.STATION) wifi.sta.eventMonReg(wifi.STA_GOTIP, function() -- wifi.sta.eventMonStop(1) print("WIFI: Connected") send_report() end) wifi.sta.eventMonReg(wifi.STA_CONNECTING, function() print("WIFI: Connecting..") end) if cfg.data.sta_ip and cfg.data.sta_gateway and cfg.data.sta_netmask then wifi.sta.setip({ ip = cfg.data.sta_ip, netmask = cfg.data.sta_netmask, gateway = cfg.data.sta_gateway }) end wifi.sta.eventMonStart(100) wifi.sta.config(cfg.data.sta_ssid, cfg.data.sta_psk) send_report()
if not cfg.data.sta_ssid then print('Wifi: No config') return end if not (cfg.data.mqtt_user and cfg.data.mqtt_password) then print('MQTT: No config') return end local queue_report = nil local send_report = nil local flush_data = nil local mq_prefix = "/nodes/" .. node_id local mq = mqtt.Client(node_id, 120, cfg.data.mqtt_user, cfg.data.mqtt_password) local mq_connected = false mq_data = {} mq_data_ptr = 0 -- Register MQTT event handlers mq:lwt("/lwt", "offline", 0, 0) mq:on("connect", function(conn) print("MQTT: Connected") mq_connected = true -- Subscribe to all command topics for topic, handler in pairs(cmds) do if topic:sub(1, 1) ~= '/' then topic = mq_prefix .. '/commands/' .. topic end print('MQTT: Subscribing, topic:', topic) mq:subscribe(topic, 0, function(conn) end) end send_report() collectgarbage() end) mq:on("offline", function(conn) print("MQTT: Disconnected") mq_connected = false end) mq:on("message", function(conn, topic, data) print("MQTT: Received, topic:", topic) local part = topic:sub(1, #mq_prefix + 1) == mq_prefix .. '/' and topic:sub(#mq_prefix + 1) or topic local cmd = part:match('/commands/(.+)') or part local res = handleCmd(cmd, data) if res ~= nil then mq_data[#mq_data + 1] = { mq_prefix .. '/responses' .. part, res } flush_data() end cmd = nil part = nil res = nil collectgarbage() if data ~= nil then print("MQTT: Data:", data) end end) flush_data = function(callback) mq_data_ptr = mq_data_ptr + 1 if mq_data_ptr > #mq_data then mq_data = {} mq_data_ptr = 0 if callback ~= nil then callback() end else local d = mq_data[mq_data_ptr] mq:publish(d[1], d[2], 0, 0, function(conn) flush_data(callback) end) d = nil end collectgarbage() end queue_report = function() if cfg.data.sleep then if mq_connected then mq:close() end node.dsleep(cfg.data.report_interval * 1000 * 1000, 4) else tmr.stop(0) tmr.alarm(0, cfg.data.report_interval * 1000, 0, function() send_report() collectgarbage() end) end end send_report = function() if not cfg.data.sleep then queue_report() end if not wifi.sta.getip() then print('Report: No Wifi') wifi.sta.connect() elseif not mq_connected then print('Report: No MQTT') mq:connect(cfg.data.mqtt_host, cfg.data.mqtt_port, cfg.data.mqtt_secure) else print('Report: Sending..') local data = triggerModules('_report_data') data = tablesMerge(data) mq_data = {} for i, v in pairs(data) do mq_data[mq_prefix .. i] = v end data = nil collectgarbage() flush_data(function() print('Report: Finished') if cfg.data.sleep then queue_report() end end) end end wifi.setphymode(wifi.PHYMODE_N) wifi.setmode(wifi.STATION) wifi.sta.eventMonReg(wifi.STA_GOTIP, function() -- wifi.sta.eventMonStop(1) print("WIFI: Connected") send_report() end) wifi.sta.eventMonReg(wifi.STA_CONNECTING, function() print("WIFI: Connecting..") end) if cfg.data.sta_ip and cfg.data.sta_gateway and cfg.data.sta_netmask then wifi.sta.setip({ ip = cfg.data.sta_ip, netmask = cfg.data.sta_netmask, gateway = cfg.data.sta_gateway }) end wifi.sta.eventMonStart(100) wifi.sta.config(cfg.data.sta_ssid, cfg.data.sta_psk) send_report()
Bugfix to prefixing of report data
Bugfix to prefixing of report data Signed-off-by: Kalman Olah <[email protected]>
Lua
mit
kalmanolah/kalmon-ESP8266
d75381a28c308bf4ec445dcb711a4c748d43e38d
src/program/lwaftr/generate_binding_table/generate_binding_table.lua
src/program/lwaftr/generate_binding_table/generate_binding_table.lua
module(...,package.seeall) local bit = require("bit") local ipv4 = require("lib.protocol.ipv4") local ipv6 = require("lib.protocol.ipv6") local lib = require("core.lib") local band, rshift = bit.band, bit.rshift local function to_ipv4_string(uint32) return ("%i.%i.%i.%i"):format( rshift(uint32, 24), rshift(band(uint32, 0xff0000), 16), rshift(band(uint32, 0xff00), 8), band(uint32, 0xff)) end local function to_ipv4_u32(ip) assert(type(ip) == "string") ip = ipv4:pton(ip) return ip[0] * 2^24 + ip[1] * 2^16 + ip[2] * 2^8 + ip[3] end local function inc_ipv4(uint32) return uint32 + 1 end local function softwire_entry(v4addr, psid_len, b4, br_address, port_set) if tonumber(v4addr) then v4addr = to_ipv4_string(v4addr) end local softwire = " softwire { ipv4 %s; psid %d; b4-ipv4 %s; br-address %s;" softwire = softwire .. " port-set { psid-length %d; }}" return softwire:format(v4addr, psid_len, b4, br_address, port_set.psid_len) end local function inc_ipv6(ipv6) for i = 15, 0, -1 do if ipv6[i] == 255 then ipv6[i] = 0 else ipv6[i] = ipv6[i] + 1 break end end return ipv6 end local function softwire_entries(from_ipv4, num_ips, psid_len, from_b4, port_set) local entries = {} local v4addr = to_ipv4_u32(params.from_ipv4) local b4 = ipv6:pton(params.from_b4) local n = 2^params.psid_len for _ = 1, params.num_ips do for psid = 1, n-1 do table.insert( entries, softwire_entry(v4addr, psid, ipv6:ntop(b4), port_set) ) b4 = inc_ipv6(b4) end v4addr = inc_ipv4(v4addr) end return entries end local function softwires(w, params) local v4addr = to_ipv4_u32(params.from_ipv4) local b4 = ipv6:pton(params.from_b4) local br_address = ipv6:pton(params.br_address) local n = 2^params.psid_len for _ = 1, params.num_ips do for psid = 1, n-1 do w:ln(softwire_entry(v4addr, psid, ipv6:ntop(b4), ipv6:ntop(br_address), params.port_set)) b4 = inc_ipv6(b4) end v4addr = inc_ipv4(v4addr) end end local w = {} function w:ln(...) io.write(...) io.write("\n") end function w:close() end function show_usage(code) print(require("program.lwaftr.generate_binding_table.README_inc")) main.exit(code) end function parse_args(args) local handlers = {} function handlers.o(arg) local fd = assert(io.open(arg, "w"), ("Couldn't find %s"):format(arg)) function w:ln(...) fd:write(...) fd:write("\n") end function w:close() fd:close() end end function handlers.h() show_usage(0) end args = lib.dogetopt(args, handlers, "ho:", { help="h" , output="o" }) if #args < 1 or #args > 6 then show_usage(1) end return unpack(args) end function run(args) local from_ipv4, num_ips, br_address, from_b4, psid_len, shift = parse_args(args) psid_len = assert(tonumber(psid_len)) if not shift then shift = 16 - psid_len end assert(psid_len + shift == 16) w:ln("binding-table {") softwires(w, { from_ipv4 = from_ipv4, num_ips = num_ips, from_b4 = from_b4, psid_len = psid_len, br_address = br_address, port_set = { psid_len = psid_len, shift = shift } }) w:ln("}") w:close() main.exit(0) end
module(...,package.seeall) local bit = require("bit") local ipv4 = require("lib.protocol.ipv4") local ipv6 = require("lib.protocol.ipv6") local lib = require("core.lib") local band, rshift = bit.band, bit.rshift local function to_ipv4_string(uint32) return ("%i.%i.%i.%i"):format( rshift(uint32, 24), rshift(band(uint32, 0xff0000), 16), rshift(band(uint32, 0xff00), 8), band(uint32, 0xff)) end local function to_ipv4_u32(ip) assert(type(ip) == "string") ip = ipv4:pton(ip) return ip[0] * 2^24 + ip[1] * 2^16 + ip[2] * 2^8 + ip[3] end local function inc_ipv4(uint32) return uint32 + 1 end local function softwire_entry(v4addr, psid_len, b4, br_address, port_set) if tonumber(v4addr) then v4addr = to_ipv4_string(v4addr) end local softwire = " softwire { ipv4 %s; psid %d; b4-ipv6 %s; br-address %s;" softwire = softwire .. " port-set { psid-length %d; }}" return softwire:format(v4addr, psid_len, b4, br_address, port_set.psid_len) end local function inc_ipv6(ipv6) for i = 15, 0, -1 do if ipv6[i] == 255 then ipv6[i] = 0 else ipv6[i] = ipv6[i] + 1 break end end return ipv6 end local function softwire_entries(from_ipv4, num_ips, psid_len, from_b4, port_set) local entries = {} local v4addr = to_ipv4_u32(params.from_ipv4) local b4 = ipv6:pton(params.from_b4) local n = 2^params.psid_len for _ = 1, params.num_ips do for psid = 1, n-1 do table.insert( entries, softwire_entry(v4addr, psid, ipv6:ntop(b4), port_set) ) b4 = inc_ipv6(b4) end v4addr = inc_ipv4(v4addr) end return entries end local function softwires(w, params) local v4addr = to_ipv4_u32(params.from_ipv4) local b4 = ipv6:pton(params.from_b4) local br_address = ipv6:pton(params.br_address) local n = 2^params.psid_len for _ = 1, params.num_ips do for psid = 1, n-1 do w:ln(softwire_entry(v4addr, psid, ipv6:ntop(b4), ipv6:ntop(br_address), params.port_set)) b4 = inc_ipv6(b4) end v4addr = inc_ipv4(v4addr) end end local w = {} function w:ln(...) io.write(...) io.write("\n") end function w:close() end function show_usage(code) print(require("program.lwaftr.generate_binding_table.README_inc")) main.exit(code) end function parse_args(args) local handlers = {} function handlers.o(arg) local fd = assert(io.open(arg, "w"), ("Couldn't find %s"):format(arg)) function w:ln(...) fd:write(...) fd:write("\n") end function w:close() fd:close() end end function handlers.h() show_usage(0) end args = lib.dogetopt(args, handlers, "ho:", { help="h" , output="o" }) if #args < 1 or #args > 6 then show_usage(1) end return unpack(args) end function run(args) local from_ipv4, num_ips, br_address, from_b4, psid_len, shift = parse_args(args) psid_len = assert(tonumber(psid_len)) if not shift then shift = 16 - psid_len else shift = assert(tonumber(shift)) end assert(psid_len + shift <= 16) w:ln("binding-table {") softwires(w, { from_ipv4 = from_ipv4, num_ips = num_ips, from_b4 = from_b4, psid_len = psid_len, br_address = br_address, port_set = { psid_len = psid_len, shift = shift } }) w:ln("}") w:close() main.exit(0) end
Fix bugs in generate-binding-table.
Fix bugs in generate-binding-table. Fixes #889 and #890.
Lua
apache-2.0
eugeneia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,Igalia/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,snabbco/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,Igalia/snabbswitch,Igalia/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,Igalia/snabb,snabbco/snabb,dpino/snabb,snabbco/snabb,dpino/snabb,eugeneia/snabb,dpino/snabb,snabbco/snabb,Igalia/snabb,eugeneia/snabb,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,Igalia/snabb,dpino/snabb,dpino/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,Igalia/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabb,Igalia/snabbswitch,dpino/snabbswitch,Igalia/snabb,eugeneia/snabb
a4e5891423c060ea8e9057cbe64dc058196a7add
Assets/ToLua/Lua/list.lua
Assets/ToLua/Lua/list.lua
-------------------------------------------------------------------------------- -- Copyright (c) 2015 - 2016 , 蒙占志(topameng) [email protected] -- All rights reserved. -- Use, modification and distribution are subject to the "MIT License" -------------------------------------------------------------------------------- local setmetatable = setmetatable local list = {} list.__index = list function list:new() local t = {length = 0, _prev = 0, _next = 0} t._prev = t t._next = t return setmetatable(t, list) end function list:clear() self._next = self self._prev = self self.length = 0 end function list:push(value) --assert(value) local node = {value = value, _prev = 0, _next = 0, removed = false} self._prev._next = node node._next = self node._prev = self._prev self._prev = node self.length = self.length + 1 return node end function list:pushnode(node) if not node.removed then return end self._prev._next = node node._next = self node._prev = self._prev self._prev = node node.removed = false self.length = self.length + 1 end function list:pop() local _prev = self._prev self:remove(_prev) return _prev.value end function list:unshift(v) local node = {value = v, _prev = 0, _next = 0, removed = false} self._next._prev = node node._prev = self node._next = self._next self._next = node self.length = self.length + 1 return node end function list:shift() local _next = self._next self:remove(_next) return _next.value end function list:remove(iter) if iter.removed then return end local _prev = iter._prev local _next = iter._next _next._prev = _prev _prev._next = _next self.length = math.max(0, self.length - 1) iter.removed = true end function list:find(v, iter) iter = iter or self while iter do if v == iter.value then return iter else iter = iter._next end end return nil end function list:findlast(v, iter) iter = iter or self while iter do if v == iter.value then return iter end iter = iter._prev end return nil end function list:next(iter) local _next = iter._next if _next ~= self then return _next, _next.value end return nil end function list:prev(iter) local _prev = iter._prev if _prev ~= self then return _prev, _prev.value end return nil end function list:erase(v) local iter = self:find(v) if iter then self:remove(iter) end end function list:insert(v, iter) if not iter then return self:push(v) end local node = {value = v, _next = 0, _prev = 0, removed = false} if iter._next then iter._next._prev = node node._next = iter._next else self.last = node end node._prev = iter iter._next = node self.length = self.length + 1 return node end function list:head() return self._next.value end function list:tail() return self._prev.value end function list:clone() local t = list:new() for i, v in list.next, self, self do t:push(v) end return t end ilist = function(_list) return list.next, _list, _list end rilist = function(_list) return list.prev, _list, _list end setmetatable(list, {__call = list.new}) return list
-------------------------------------------------------------------------------- -- Copyright (c) 2015 - 2016 , 蒙占志(topameng) [email protected] -- All rights reserved. -- Use, modification and distribution are subject to the "MIT License" -------------------------------------------------------------------------------- local setmetatable = setmetatable local list = {} list.__index = list function list:new() local t = {length = 0, _prev = 0, _next = 0} t._prev = t t._next = t return setmetatable(t, list) end function list:clear() self._next = self self._prev = self self.length = 0 end function list:push(value) --assert(value) local node = {value = value, _prev = 0, _next = 0, removed = false} self._prev._next = node node._next = self node._prev = self._prev self._prev = node self.length = self.length + 1 return node end function list:pushnode(node) if not node.removed then return end self._prev._next = node node._next = self node._prev = self._prev self._prev = node node.removed = false self.length = self.length + 1 end function list:pop() local _prev = self._prev self:remove(_prev) return _prev.value end function list:unshift(v) local node = {value = v, _prev = 0, _next = 0, removed = false} self._next._prev = node node._prev = self node._next = self._next self._next = node self.length = self.length + 1 return node end function list:shift() local _next = self._next self:remove(_next) return _next.value end function list:remove(iter) if iter.removed then return end local _prev = iter._prev local _next = iter._next _next._prev = _prev _prev._next = _next self.length = math.max(0, self.length - 1) iter.removed = true end function list:find(v, iter) iter = iter or self repeat if v == iter.value then return iter else iter = iter._next end until iter == self return nil end function list:findlast(v, iter) iter = iter or self repeat if v == iter.value then return iter end iter = iter._prev until iter == self return nil end function list:next(iter) local _next = iter._next if _next ~= self then return _next, _next.value end return nil end function list:prev(iter) local _prev = iter._prev if _prev ~= self then return _prev, _prev.value end return nil end function list:erase(v) local iter = self:find(v) if iter then self:remove(iter) end end function list:insert(v, iter) if not iter then return self:push(v) end local node = {value = v, _next = 0, _prev = 0, removed = false} if iter._next then iter._next._prev = node node._next = iter._next else self.last = node end node._prev = iter iter._next = node self.length = self.length + 1 return node end function list:head() return self._next.value end function list:tail() return self._prev.value end function list:clone() local t = list:new() for i, v in list.next, self, self do t:push(v) end return t end ilist = function(_list) return list.next, _list, _list end rilist = function(_list) return list.prev, _list, _list end setmetatable(list, {__call = list.new}) return list
1.0.7.367 fixed list.find不到问题
1.0.7.367 fixed list.find不到问题
Lua
mit
topameng/tolua
6dc69d658fe62d3041af7f0edcd454984d0aef4f
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() print(collectgarbage("count")) 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(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
* libs/httpd: Fixed last commit
* libs/httpd: Fixed last commit git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2490 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
freifunk-gluon/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,vhpham80/luci,vhpham80/luci,projectbismark/luci-bismark,jschmidlapp/luci,stephank/luci,yeewang/openwrt-luci,alxhh/piratenluci,eugenesan/openwrt-luci,ch3n2k/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,gwlim/luci,Flexibity/luci,phi-psi/luci,Flexibity/luci,projectbismark/luci-bismark,Canaan-Creative/luci,saraedum/luci-packages-old,ch3n2k/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,stephank/luci,stephank/luci,alxhh/piratenluci,eugenesan/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,vhpham80/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,freifunk-gluon/luci,freifunk-gluon/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,jschmidlapp/luci,alxhh/piratenluci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,stephank/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,Flexibity/luci,vhpham80/luci,8devices/carambola2-luci,Canaan-Creative/luci,freifunk-gluon/luci,phi-psi/luci,phi-psi/luci,freifunk-gluon/luci,Canaan-Creative/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,yeewang/openwrt-luci,zwhfly/openwrt-luci,ch3n2k/luci,phi-psi/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,gwlim/luci,jschmidlapp/luci,ch3n2k/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,gwlim/luci,Flexibity/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,zwhfly/openwrt-luci,ch3n2k/luci,phi-psi/luci,yeewang/openwrt-luci,phi-psi/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,Flexibity/luci,jschmidlapp/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,Flexibity/luci,alxhh/piratenluci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,eugenesan/openwrt-luci,vhpham80/luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,ch3n2k/luci,alxhh/piratenluci,stephank/luci,stephank/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,freifunk-gluon/luci,gwlim/luci,gwlim/luci,phi-psi/luci,8devices/carambola2-luci,gwlim/luci
4af2ca2aaa3a0cfc3f1d0955b32f6968bc6e1801
lua/entities/gmod_wire_egp/lib/egplib/materials.lua
lua/entities/gmod_wire_egp/lib/egplib/materials.lua
-------------------------------------------------------- -- Materials (And fonts) -------------------------------------------------------- local EGP = EGP -- Valid fonts table EGP.ValidFonts_Lookup = {} EGP.ValidFonts = {} EGP.ValidFonts[1] = "WireGPU_ConsoleFont" EGP.ValidFonts[2] = "Coolvetica" EGP.ValidFonts[3] = "Arial" EGP.ValidFonts[4] = "Lucida Console" EGP.ValidFonts[5] = "Trebuchet" EGP.ValidFonts[6] = "Courier New" EGP.ValidFonts[7] = "Times New Roman" EGP.ValidFonts[8] = "ChatFont" EGP.ValidFonts[9] = "Marlett" if (CLIENT) then local new = {} for k,v in ipairs( EGP.ValidFonts ) do local font = "WireEGP_18_"..k local fontTable = { font=v, size = 18, weight = 800, antialias = true, additive = false } surface.CreateFont( font, fontTable ) EGP.ValidFonts_Lookup[font] = true table.insert( new, font ) end for k,v in ipairs( new ) do table.insert( EGP.ValidFonts, v ) end local type = type local SetMaterial = surface.SetMaterial local SetTexture = surface.SetTexture local GetTextureID = surface.GetTextureID local NoTexture = draw.NoTexture function EGP:SetMaterial( Mat ) if type(Mat) == "IMaterial" then SetMaterial( Mat ) elseif isentity(Mat) then if (!Mat:IsValid() or !Mat.GPU or !Mat.GPU.RT) then NoTexture() return end local OldTex = WireGPU_matScreen:GetTexture("$basetexture") WireGPU_matScreen:SetTexture("$basetexture", Mat.GPU.RT) SetTexture(GetTextureID( "GPURT" )) return OldTex else NoTexture() end end function EGP:FixMaterial( OldTex ) if (!OldTex) then return end WireGPU_matScreen:SetTexture("$basetexture", OldTex) end end
-------------------------------------------------------- -- Materials (And fonts) -------------------------------------------------------- local EGP = EGP -- Valid fonts table EGP.ValidFonts_Lookup = {} EGP.ValidFonts = {} EGP.ValidFonts[1] = "WireGPU_ConsoleFont" EGP.ValidFonts[2] = "Coolvetica" EGP.ValidFonts[3] = "Arial" EGP.ValidFonts[4] = "Lucida Console" EGP.ValidFonts[5] = "Trebuchet" EGP.ValidFonts[6] = "Courier New" EGP.ValidFonts[7] = "Times New Roman" EGP.ValidFonts[8] = "ChatFont" EGP.ValidFonts[9] = "Marlett" EGP.ValidFonts[10] = "Roboto" if (CLIENT) then local new = {} for k,v in ipairs( EGP.ValidFonts ) do local font = "WireEGP_18_"..k local fontTable = { font=v, size = 18, weight = 800, antialias = true, additive = false } surface.CreateFont( font, fontTable ) EGP.ValidFonts_Lookup[font] = true table.insert( new, font ) end for k,v in ipairs( new ) do table.insert( EGP.ValidFonts, v ) end local type = type local SetMaterial = surface.SetMaterial local SetTexture = surface.SetTexture local GetTextureID = surface.GetTextureID local NoTexture = draw.NoTexture function EGP:SetMaterial( Mat ) if type(Mat) == "IMaterial" then SetMaterial( Mat ) elseif isentity(Mat) then if (!Mat:IsValid() or !Mat.GPU or !Mat.GPU.RT) then NoTexture() return end local OldTex = WireGPU_matScreen:GetTexture("$basetexture") WireGPU_matScreen:SetTexture("$basetexture", Mat.GPU.RT) SetTexture(GetTextureID( "GPURT" )) return OldTex else NoTexture() end end function EGP:FixMaterial( OldTex ) if (!OldTex) then return end WireGPU_matScreen:SetTexture("$basetexture", OldTex) end end
Add Roboto to the allowed EGP fonts. Fix #813.
Add Roboto to the allowed EGP fonts. Fix #813.
Lua
apache-2.0
sammyt291/wire,wiremod/wire,thegrb93/wire,rafradek/wire,plinkopenguin/wiremod,mitterdoo/wire,bigdogmat/wire,NezzKryptic/Wire,dvdvideo1234/wire,CaptainPRICE/wire,mms92/wire,immibis/wiremod,garrysmodlua/wire,Grocel/wire,Python1320/wire,notcake/wire
a24a65df15b291dfe0796137b44515055322fc17
ffi/framebuffer_android.lua
ffi/framebuffer_android.lua
local ffi = require("ffi") local android = require("android") local BB = require("ffi/blitbuffer") local C = ffi.C --[[ configuration for devices with an electric paper display controller ]]-- -- does the device has an e-ink screen? local has_eink_screen, eink_platform = android.isEink() -- does the device needs to handle all screen refreshes local has_eink_full_support = android.isEinkFull() -- for *some* rockchip devices local rk_full, rk_partial, rk_a2, rk_auto = 1, 2, 3, 4 -- luacheck: ignore -- for *some* freescale devices local ntx_du, ntx_gc16, ntx_auto, ntx_regal, ntx_full = 1, 2, 5, 7, 34 -- luacheck: ignore -- update a region of the screen local function updatePartial(mode, delay, x, y, w, h) if not (x and y and w and h) then x = 0 y = 0 w = android.screen.width h = android.screen.height end if x < 0 then x = 0 end if y < 0 then y = 0 end if (x + w) > android.screen.width then w = android.screen.width - x end if (y + h) > android.screen.height then h = android.screen.height - y end android.einkUpdate(mode, delay, x, y, (x + w), (y + h)) end -- update the entire screen local function updateFull() -- freescale ntx platform if has_eink_screen and (eink_platform == "freescale") then if has_eink_full_support then -- we handle the screen entirely. Add a delay before a full update. updatePartial(ntx_full, 50) else -- we're racing against system driver, update without delay to avoid artifacts updatePartial(ntx_full, 0) end -- rockchip rk3x platform elseif has_eink_screen and (eink_platform == "rockchip") then android.einkUpdate(rk_full) end end local framebuffer = {} function framebuffer:init() -- we present this buffer to the outside self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32) self.invert_bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32) -- TODO: should we better use these? -- android.lib.ANativeWindow_getWidth(window) -- android.lib.ANativeWindow_getHeight(window) self.bb:fill(BB.COLOR_WHITE) self:_updateWindow() framebuffer.parent.init(self) end function framebuffer:_updateWindow() if android.app.window == nil then android.LOGW("cannot blit: no window") return end local buffer = ffi.new("ANativeWindow_Buffer[1]") if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then android.LOGW("Unable to lock window buffer") return end local bb = nil if buffer[0].format == C.WINDOW_FORMAT_RGBA_8888 or buffer[0].format == C.WINDOW_FORMAT_RGBX_8888 then bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4, buffer[0].stride) elseif buffer[0].format == C.WINDOW_FORMAT_RGB_565 then bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2, buffer[0].stride) else android.LOGE("unsupported window format!") end if bb then local ext_bb = self.full_bb or self.bb bb:setInverse(ext_bb:getInverse()) -- adapt to possible rotation changes bb:setRotation(ext_bb:getRotation()) self.invert_bb:setRotation(ext_bb:getRotation()) if ext_bb:getInverse() == 1 then self.invert_bb:invertblitFrom(ext_bb) bb:blitFrom(self.invert_bb) else bb:blitFrom(ext_bb) end end android.lib.ANativeWindow_unlockAndPost(android.app.window); end function framebuffer:refreshFullImp(x, y, w, h) self:_updateWindow() updateFull() end function framebuffer:refreshPartialImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(ntx_auto, 0, x, y, w, h) end end function framebuffer:refreshFlashPartialImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(ntx_gc16, 0, x, y, w, h) end end function framebuffer:refreshUIImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(ntx_auto, 0, x, y, w, h) end end function framebuffer:refreshFlashUIImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(ntx_gc16, 0, x, y, w, h) end end function framebuffer:refreshFastImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(ntx_du, 0, x, y, w, h) end end return require("ffi/framebuffer"):extend(framebuffer)
local ffi = require("ffi") local android = require("android") local BB = require("ffi/blitbuffer") local C = ffi.C --[[ configuration for devices with an electric paper display controller ]]-- -- does the device has an e-ink screen? local has_eink_screen, eink_platform = android.isEink() -- does the device needs to handle all screen refreshes local has_eink_full_support = android.isEinkFull() -- for *some* rockchip devices local rk_full, rk_partial, rk_a2, rk_auto = 1, 2, 3, 4 -- luacheck: ignore -- for *some* freescale devices local update_full, update_partial = 32, 0 -- luacheck: ignore local waveform_du, waveform_gc16, waveform_regal = 1, 2, 7 -- luacheck: ignore local partial_du, partial_gc16, partial_regal = waveform_du, waveform_gc16, waveform_regal -- luacheck: ignore local full_gc16, full_regal = update_full + waveform_gc16, update_full + waveform_regal -- luacheck: ignore -- update a region of the screen local function updatePartial(mode, delay, x, y, w, h) if not (x and y and w and h) then x = 0 y = 0 w = android.screen.width h = android.screen.height end if x < 0 then x = 0 end if y < 0 then y = 0 end if (x + w) > android.screen.width then w = android.screen.width - x end if (y + h) > android.screen.height then h = android.screen.height - y end android.einkUpdate(mode, delay, x, y, (x + w), (y + h)) end -- update the entire screen local function updateFull() -- freescale ntx platform if has_eink_screen and (eink_platform == "freescale") then if has_eink_full_support then -- we handle the screen entirely. No delay is needed updatePartial(full_gc16, 0) else -- we're racing against system driver. Let the system win and apply -- a full update after it. updatePartial(full_gc16, 500) end -- rockchip rk3x platform elseif has_eink_screen and (eink_platform == "rockchip") then android.einkUpdate(rk_full) end end local framebuffer = {} function framebuffer:init() -- we present this buffer to the outside self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32) self.invert_bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32) -- TODO: should we better use these? -- android.lib.ANativeWindow_getWidth(window) -- android.lib.ANativeWindow_getHeight(window) self.bb:fill(BB.COLOR_WHITE) self:_updateWindow() framebuffer.parent.init(self) end function framebuffer:_updateWindow() if android.app.window == nil then android.LOGW("cannot blit: no window") return end local buffer = ffi.new("ANativeWindow_Buffer[1]") if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then android.LOGW("Unable to lock window buffer") return end local bb = nil if buffer[0].format == C.WINDOW_FORMAT_RGBA_8888 or buffer[0].format == C.WINDOW_FORMAT_RGBX_8888 then bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4, buffer[0].stride) elseif buffer[0].format == C.WINDOW_FORMAT_RGB_565 then bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2, buffer[0].stride) else android.LOGE("unsupported window format!") end if bb then local ext_bb = self.full_bb or self.bb bb:setInverse(ext_bb:getInverse()) -- adapt to possible rotation changes bb:setRotation(ext_bb:getRotation()) self.invert_bb:setRotation(ext_bb:getRotation()) if ext_bb:getInverse() == 1 then self.invert_bb:invertblitFrom(ext_bb) bb:blitFrom(self.invert_bb) else bb:blitFrom(ext_bb) end end android.lib.ANativeWindow_unlockAndPost(android.app.window); end function framebuffer:refreshFullImp(x, y, w, h) self:_updateWindow() updateFull() end function framebuffer:refreshPartialImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(partial_regal, 0, x, y, w, h) end end function framebuffer:refreshFlashPartialImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(full_regal, 0, x, y, w, h) end end function framebuffer:refreshUIImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(partial_regal, 0, x, y, w, h) end end function framebuffer:refreshFlashUIImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(full_regal, 0, x, y, w, h) end end function framebuffer:refreshFastImp(x, y, w, h) self:_updateWindow() if has_eink_full_support then updatePartial(partial_du, 0, x, y, w, h) end end return require("ffi/framebuffer"):extend(framebuffer)
[Android] some tolino/nook waveform fixes (#933)
[Android] some tolino/nook waveform fixes (#933)
Lua
agpl-3.0
NiLuJe/koreader-base,koreader/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,koreader/koreader-base
65ebb891b422598feda49ebf6d56bc5fe0bbf5d5
OS/CartOS/Programs/rm.lua
OS/CartOS/Programs/rm.lua
--Remove/delete a specific file local args = {...} --Get the arguments passed to this program if #args < 1 then color(9) print("\nMust provide the path") return end local tar = table.concat(args," ") --The path may include whitespaces local term = require("C://terminal") print("") --A new line local function index(path,notfirst) color(8) if fs.isFile(path) then print("Deleted "..path) fs.remove(path) return end local items = fs.directoryItems(path) for k, item in ipairs(items) do if fs.isDirectory(path..item) then print("Entering directory "..path..item.."/",true) index(path..item.."/") else print("Deleted "..path..item) fs.remove(path..item) end end fs.remove(path) if not notfirst then print("Deleted File/s successfully") end return true end local d, p = tar:match("(.+)://(.+)") if d and p then if fs.exists(tar) then index(tar) end return end local d = tar:match("/(.+)") if d then if fs.exists(term.getdrive().."://"..tar) then index(term.getdrive().."://"..tar) end return end if fs.exists(term.getpath()..tar) then index(term.getpath()..tar) return end color(9) print("Path doesn't exists")
--Remove/delete a specific file local args = {...} --Get the arguments passed to this program if #args < 1 then color(9) print("\nMust provide the path") return end local tar = table.concat(args," ") --The path may include whitespaces local term = require("C://terminal") print("") --A new line local function index(path,notfirst) color(8) if fs.isFile(path) then print("Deleted "..path) fs.remove(path) return end local items = fs.directoryItems(path) for k, item in ipairs(items) do if fs.isDirectory(path..item) then print("Entering directory "..path..item.."/",true) index(path..item.."/") else print("Deleted "..path..item) fs.remove(path..item) end end fs.remove(path) if not notfirst then print("Deleted File/s successfully") end return true end local d, p = tar:match("(.+)://(.+)") if d and p then if fs.exists(tar) then index(tar) end return end local d = tar:match("/(.+)") if d then if fs.exists(term.getdrive().."://"..tar) then index(term.getdrive().."://"..tar) end return end if fs.exists(term.getpath()..tar) then index(term.getpath()..(tar:sub(-2,-1) == "/" and tar or tar.."/")) return end color(9) print("Path doesn't exists")
Bugfix
Bugfix
Lua
mit
RamiLego4Game/LIKO-12
f4f419419e96fb22053f51dd8fbadfc376dffcef
NaoTHSoccer/Make/premake4.lua
NaoTHSoccer/Make/premake4.lua
-- set the default global platform PLATFORM = _OPTIONS["platform"] if PLATFORM == nil then PLATFORM = "Native" end -- load the global default settings dofile "projectconfig.lua" -- load some helpers dofile (FRAMEWORK_PATH .. "/BuildTools/info.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/protoc.lua") --dofile (FRAMEWORK_PATH .. "/BuildTools/ilpath.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator_2.7+.lua") --dofile (FRAMEWORK_PATH .. "/BuildTools/extract_todos.lua") -- include the Nao platform if COMPILER_PATH_NAO ~= nil then include (COMPILER_PATH_NAO) end -- test -- print("INFO:" .. (os.findlib("Controller") or "couldn't fined the lib Controller")) newoption { trigger = "Wno-conversion", description = "Disable te -Wconversion warnin for gCC" } newoption { trigger = "Wno-misleading-indentation", description = "Disable the -Wmisleading-indentation warning/error for gcc (6.0+)" } newoption { trigger = "Wno-ignored-attributes", description = "Disable the -Wignored-attributes warning/error for gcc (6.0+)" } -- definition of the solution solution "NaoTHSoccer" platforms {"Native", "Nao"} configurations {"OptDebug", "Debug", "Release"} location "../build" print("generating solution NaoTHSoccer for platform " .. PLATFORM) -- global lib path for all configurations -- additional includes libdirs (PATH["libs"]) -- global include path for all projects and configurations includedirs (PATH["includes"]) -- global links ( needed by NaoTHSoccer ) links { "opencv_core", "opencv_ml", "opencv_imgproc", "opencv_objdetect" } -- set the repository information defines { "REVISION=\"" .. REVISION .. "\"", "USER_NAME=\"" .. USER_NAME .. "\"", "BRANCH_PATH=\"" .. BRANCH_PATH .. "\"" } -- TODO: howto compile the framework representations properly *inside* the project? local COMMONS_MESSAGES = FRAMEWORK_PATH .. "/Commons/Messages/" invokeprotoc( { COMMONS_MESSAGES .. "CommonTypes.proto", COMMONS_MESSAGES .. "Framework-Representations.proto", COMMONS_MESSAGES .. "Messages.proto" }, FRAMEWORK_PATH .. "/Commons/Source/Messages/", "../../RobotControl/RobotConnector/src/", "../../Utils/pyLogEvaluator", {COMMONS_MESSAGES} ) invokeprotoc( {"../Messages/Representations.proto"}, "../Source/Messages/", "../../RobotControl/RobotConnector/src/", "../../Utils/pyLogEvaluator", {COMMONS_MESSAGES, "../Messages/"} ) print ("operation system: " .. os.get()) configuration { "Debug" } defines { "DEBUG" } flags { "Symbols", "FatalWarnings" } configuration { "OptDebug" } defines { "DEBUG" } flags { "Optimize", "FatalWarnings" } configuration{"Native"} targetdir "../dist/Native" -- special defines for the Nao robot configuration {"Nao"} defines { "NAO" } targetdir "../dist/Nao" flags { "ExtraWarnings" } -- disable warning "comparison always true due to limited range of data type" -- this warning is caused by protobuf 2.4.1 buildoptions {"-Wno-type-limits"} -- some of the protobuf messages are marked as deprecated but are still in use for legacy reasons buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-std=c++11"} if _OPTIONS["Wno-conversion"] == nil then -- enable the conversion warning by default buildoptions {"-Wconversion"} defines { "_NAOTH_CHECK_CONVERSION_" } end -- additional defines for visual studio configuration {"windows", "vs*"} defines {"WIN32", "NOMINMAX", "EIGEN_DONT_ALIGN"} buildoptions {"/wd4351"} -- disable warning: "...new behavior: elements of array..." buildoptions {"/wd4996"} -- disable warning: "...deprecated..." buildoptions {"/wd4290"} -- exception specification ignored (typed stecifications are ignored) links {"ws2_32"} debugdir "$(SolutionDir).." configuration {"linux", "gmake"} -- "position-independent code" needed to compile shared libraries. -- In our case it's only the NaoSMAL. So, we probably don't need this one. -- Premake4 automatically includes -fPIC if a project is declared as a SharedLib. -- http://www.akkadia.org/drepper/dsohowto.pdf buildoptions {"-fPIC"} -- may be needed for newer glib2 versions, remove if not needed buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wno-deprecated"} buildoptions {"-std=c++11"} --flags { "ExtraWarnings" } links {"pthread"} if _OPTIONS["Wno-conversion"] == nil then buildoptions {"-Wconversion"} defines { "_NAOTH_CHECK_CONVERSION_" } end if _OPTIONS["Wno-misleading-indentation"] ~= nil then buildoptions {"-Wno-misleading-indentation"} end if _OPTIONS["Wno-ignored-attributes"] ~= nil then buildoptions {"-Wno-ignored-attributes"} end -- Why? OpenCV is always dynamically linked and we can only garantuee that there is one version in Extern (Thomas) linkoptions {"-Wl,-rpath \"" .. path.getabsolute(EXTERN_PATH .. "/lib/") .. "\""} configuration {"macosx"} defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" } buildoptions {"-std=c++11"} -- disable some warnings buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wno-deprecated-register"} buildoptions {"-Wno-logical-op-parentheses"} -- use clang on macOS premake.gcc.cc = 'clang' premake.gcc.cxx = 'clang++' -- commons dofile (FRAMEWORK_PATH .. "/Commons/Make/Commons.lua") -- core dofile "NaoTHSoccer.lua" -- set up platforms if _OPTIONS["platform"] == "Nao" then dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoSMAL.lua") -- HACK: boost from NaoQI SDK makes problems buildoptions {"-Wno-conversion"} defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" } -- ACHTUNG: NaoSMAL doesn't build with the flag -std=c++11 (because of Boost) buildoptions {"-std=gnu++11"} dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoRobot.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } else dofile (FRAMEWORK_PATH .. "/Platforms/Make/SimSpark.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } debugargs { "--sync" } dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulator.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulatorJNI.lua") kind "SharedLib" links { "NaoTHSoccer", "Commons" } end
-- set the default global platform PLATFORM = _OPTIONS["platform"] if PLATFORM == nil then PLATFORM = "Native" end -- load the global default settings dofile "projectconfig.lua" -- load some helpers dofile (FRAMEWORK_PATH .. "/BuildTools/info.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/protoc.lua") --dofile (FRAMEWORK_PATH .. "/BuildTools/ilpath.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator_2.7+.lua") --dofile (FRAMEWORK_PATH .. "/BuildTools/extract_todos.lua") -- include the Nao platform if COMPILER_PATH_NAO ~= nil then include (COMPILER_PATH_NAO) end -- test -- print("INFO:" .. (os.findlib("Controller") or "couldn't fined the lib Controller")) newoption { trigger = "Wno-conversion", description = "Disable te -Wconversion warnin for gCC" } newoption { trigger = "Wno-misleading-indentation", description = "Disable the -Wmisleading-indentation warning/error for gcc (6.0+)" } newoption { trigger = "Wno-ignored-attributes", description = "Disable the -Wignored-attributes warning/error for gcc (6.0+)" } -- definition of the solution solution "NaoTHSoccer" platforms {"Native", "Nao"} configurations {"OptDebug", "Debug", "Release"} location "../build" print("INFO: generating solution NaoTHSoccer") print(" PLATFORM = " .. PLATFORM) print(" OS = " .. os.get()) print(" ACTION = " .. _ACTION) -- global lib path for all configurations -- additional includes libdirs (PATH["libs"]) -- global include path for all projects and configurations includedirs (PATH["includes"]) -- global links ( needed by NaoTHSoccer ) links { "opencv_core", "opencv_ml", "opencv_imgproc", "opencv_objdetect" } -- set the repository information defines { "REVISION=\"" .. REVISION .. "\"", "USER_NAME=\"" .. USER_NAME .. "\"", "BRANCH_PATH=\"" .. BRANCH_PATH .. "\"" } -- TODO: howto compile the framework representations properly *inside* the project? local COMMONS_MESSAGES = FRAMEWORK_PATH .. "/Commons/Messages/" invokeprotoc( { COMMONS_MESSAGES .. "CommonTypes.proto", COMMONS_MESSAGES .. "Framework-Representations.proto", COMMONS_MESSAGES .. "Messages.proto" }, FRAMEWORK_PATH .. "/Commons/Source/Messages/", "../../RobotControl/RobotConnector/src/", "../../Utils/pyLogEvaluator", {COMMONS_MESSAGES} ) invokeprotoc( {"../Messages/Representations.proto"}, "../Source/Messages/", "../../RobotControl/RobotConnector/src/", "../../Utils/pyLogEvaluator", {COMMONS_MESSAGES, "../Messages/"} ) configuration { "Debug" } defines { "DEBUG" } flags { "Symbols", "FatalWarnings" } configuration { "OptDebug" } defines { "DEBUG" } flags { "Optimize", "FatalWarnings" } configuration{"Native"} targetdir "../dist/Native" -- special defines for the Nao robot configuration {"Nao"} defines { "NAO" } targetdir "../dist/Nao" flags { "ExtraWarnings" } -- disable warning "comparison always true due to limited range of data type" -- this warning is caused by protobuf 2.4.1 buildoptions {"-Wno-type-limits"} -- some of the protobuf messages are marked as deprecated but are still in use for legacy reasons buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-std=c++11"} if _OPTIONS["Wno-conversion"] == nil then -- enable the conversion warning by default buildoptions {"-Wconversion"} defines { "_NAOTH_CHECK_CONVERSION_" } end -- additional defines for visual studio configuration {"windows", "vs*"} defines {"WIN32", "NOMINMAX", "EIGEN_DONT_ALIGN"} buildoptions {"/wd4351"} -- disable warning: "...new behavior: elements of array..." buildoptions {"/wd4996"} -- disable warning: "...deprecated..." buildoptions {"/wd4290"} -- exception specification ignored (typed stecifications are ignored) links {"ws2_32"} debugdir "$(SolutionDir).." configuration {"linux", "gmake"} -- "position-independent code" needed to compile shared libraries. -- In our case it's only the NaoSMAL. So, we probably don't need this one. -- Premake4 automatically includes -fPIC if a project is declared as a SharedLib. -- http://www.akkadia.org/drepper/dsohowto.pdf buildoptions {"-fPIC"} -- may be needed for newer glib2 versions, remove if not needed buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wno-deprecated"} buildoptions {"-std=c++11"} --flags { "ExtraWarnings" } links {"pthread"} if _OPTIONS["Wno-conversion"] == nil then buildoptions {"-Wconversion"} defines { "_NAOTH_CHECK_CONVERSION_" } end if _OPTIONS["Wno-misleading-indentation"] ~= nil then buildoptions {"-Wno-misleading-indentation"} end if _OPTIONS["Wno-ignored-attributes"] ~= nil then buildoptions {"-Wno-ignored-attributes"} end -- Why? OpenCV is always dynamically linked and we can only garantuee that there is one version in Extern (Thomas) linkoptions {"-Wl,-rpath \"" .. path.getabsolute(EXTERN_PATH .. "/lib/") .. "\""} configuration {"macosx"} defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" } buildoptions {"-std=c++11"} -- disable some warnings buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wno-deprecated-register"} buildoptions {"-Wno-logical-op-parentheses"} -- use clang on macOS -- NOTE: configuration doesn't affect these settings, they NEED to be in a if if os.is("macosx") then premake.gcc.cc = 'clang' premake.gcc.cxx = 'clang++' end -- commons dofile (FRAMEWORK_PATH .. "/Commons/Make/Commons.lua") -- core dofile "NaoTHSoccer.lua" -- set up platforms if _OPTIONS["platform"] == "Nao" then dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoSMAL.lua") -- HACK: boost from NaoQI SDK makes problems buildoptions {"-Wno-conversion"} defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" } -- ACHTUNG: NaoSMAL doesn't build with the flag -std=c++11 (because of Boost) buildoptions {"-std=gnu++11"} dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoRobot.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } else dofile (FRAMEWORK_PATH .. "/Platforms/Make/SimSpark.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } debugargs { "--sync" } dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulator.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulatorJNI.lua") kind "SharedLib" links { "NaoTHSoccer", "Commons" } end
fix macos stuff add some system info
fix macos stuff add some system info
Lua
apache-2.0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
b0ce33d759adc66362ca7e34ed18298eb70da6ad
mod_mam/rsm.lib.lua
mod_mam/rsm.lib.lua
local stanza = require"util.stanza".stanza; local tostring, tonumber = tostring, tonumber; local type = type; local pairs = pairs; local xmlns_rsm = 'http://jabber.org/protocol/rsm'; local element_parsers; do local function xs_int(st) return tonumber((st:get_text())); end local function xs_string(st) return st:get_text(); end element_parsers = { after = xs_string; before = function(st) return st:get_text() or true; end; max = xs_int; index = xs_int; first = function(st) return { index = tonumber(st.attr.index); st:get_text() }; end; last = xs_string; count = xs_int; } end local element_generators = setmetatable({ first = function(st, data) if type(data) == "table" then st:tag("first", { index = data.index }):text(data[1]):up(); else st:tag("first"):text(tostring(data)):up(); end end; before = function(st, data) if data == true then st:tag("before"):up(); else st:tag("before"):text(tostring(data)):up(); end end }, { __index = function(_, name) return function(st, data) st:tag(name):text(tostring(data)):up(); end end; }); local function parse(stanza) local rs = {}; for tag in stanza:childtags() do local name = tag.name; local parser = name and element_parsers[name]; if parser then rs[name] = parser(tag); end end return rs; end local function generate(t) local st = stanza("set", { xmlns = xmlns_rsm }); for k,v in pairs(t) do if element_parsers[k] then element_generators[k](st, v); end end return st; end local function get(st) local set = st:get_child("set", xmlns_rsm); if set and #set.tags > 0 then return parse(set); end end return { parse = parse, generate = generate, get = get };
local stanza = require"util.stanza".stanza; local tostring, tonumber = tostring, tonumber; local type = type; local pairs = pairs; local xmlns_rsm = 'http://jabber.org/protocol/rsm'; local element_parsers; do local function xs_int(st) return tonumber((st:get_text())); end local function xs_string(st) return st:get_text(); end element_parsers = { after = xs_string; before = function(st) local text = st:get_text(); return text == "" or text; end; max = xs_int; index = xs_int; first = function(st) return { index = tonumber(st.attr.index); st:get_text() }; end; last = xs_string; count = xs_int; } end local element_generators = setmetatable({ first = function(st, data) if type(data) == "table" then st:tag("first", { index = data.index }):text(data[1]):up(); else st:tag("first"):text(tostring(data)):up(); end end; before = function(st, data) if data == true then st:tag("before"):up(); else st:tag("before"):text(tostring(data)):up(); end end }, { __index = function(_, name) return function(st, data) st:tag(name):text(tostring(data)):up(); end end; }); local function parse(stanza) local rs = {}; for tag in stanza:childtags() do local name = tag.name; local parser = name and element_parsers[name]; if parser then rs[name] = parser(tag); end end return rs; end local function generate(t) local st = stanza("set", { xmlns = xmlns_rsm }); for k,v in pairs(t) do if element_parsers[k] then element_generators[k](st, v); end end return st; end local function get(st) local set = st:get_child("set", xmlns_rsm); if set and #set.tags > 0 then return parse(set); end end return { parse = parse, generate = generate, get = get };
mod_mam/rsm.lib: Fix parsing of empty before tag
mod_mam/rsm.lib: Fix parsing of empty before tag
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
597387c55758c5f2a5686b2b43cdc95f997bca00
src/nodes/floor.lua
src/nodes/floor.lua
local Floor = {} Floor.__index = Floor function Floor.new(node, collider) local floor = {} setmetatable(floor, Floor) --If the node is a polyline, we need to draw a polygon rather than rectangle if node.polyline or node.polygon then local polygon = node.polyline or node.polygon local vertices = {} for k,vertex in ipairs(polygon) do -- Determine whether this is an X or Y coordinate if k % 2 == 0 then table.insert(vertices, vertex + node.y) else table.insert(vertices, vertex + node.x) end end floor.bb = collider:addPolygon( unpack(vertices) ) -- Stash the polyline on the collider object for future reference floor.bb.polyline = polygon else floor.bb = collider:addRectangle(node.x, node.y, node.width, node.height) floor.bb.polyline = nil end floor.bb.node = floor collider:setPassive(floor.bb) floor.isSolid = true return floor end function Floor:collide(player, dt, mtv_x, mtv_y) local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = player.bb:bbox() local distance = math.abs(player.velocity.y * dt) + 0.10 function updatePlayer() player:moveBoundingBox() player.jumping = false player.rebounding = false end if self.bb.polyline and player.velocity.y >= 0 -- Prevent the player from being treadmilled through an object and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then player.velocity.y = 0 -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles player.position.y = (py1 - 1) + mtv_y updatePlayer() player:impactDamage() return end if mtv_y ~= 0 then player.velocity.y = 0 player.position.y = wy1 - player.height updatePlayer() player:impactDamage() end if mtv_x ~= 0 and mtv_y > 5 then player.velocity.x = 0 player.position.x = player.position.x + mtv_x updatePlayer() end end return Floor
local Floor = {} Floor.__index = Floor function Floor.new(node, collider) local floor = {} setmetatable(floor, Floor) --If the node is a polyline, we need to draw a polygon rather than rectangle if node.polyline or node.polygon then local polygon = node.polyline or node.polygon local vertices = {} for k,vertex in ipairs(polygon) do -- Determine whether this is an X or Y coordinate if k % 2 == 0 then table.insert(vertices, vertex + node.y) else table.insert(vertices, vertex + node.x) end end floor.bb = collider:addPolygon( unpack(vertices) ) -- Stash the polyline on the collider object for future reference floor.bb.polyline = polygon else floor.bb = collider:addRectangle(node.x, node.y, node.width, node.height) floor.bb.polyline = nil end floor.bb.node = floor collider:setPassive(floor.bb) floor.isSolid = true return floor end function Floor:collide(player, dt, mtv_x, mtv_y) local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = player.bb:bbox() local distance = math.abs(player.velocity.y * dt) + 0.10 function updatePlayer() player:moveBoundingBox() player.jumping = false player.rebounding = false end if self.bb.polyline and player.velocity.y >= 0 -- Prevent the player from being treadmilled through an object and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then player.velocity.y = 0 -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles player.position.y = (py1 - 1) + mtv_y updatePlayer() player:impactDamage() return end if mtv_x ~= 0 and wy1 + 2 < player.position.y + player.height then --prevent horizontal movement player.velocity.x = 0 player.position.x = player.position.x + mtv_x updatePlayer() end if mtv_y ~= 0 then --push back up player.velocity.y = 0 player.position.y = wy1 - player.height updatePlayer() player:impactDamage() end end return Floor
bugfix... I'm dumb...
bugfix... I'm dumb...
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
049ddd9275eb667a58b9476257736a97380faef0
durden/tools/advfloat/minimize.lua
durden/tools/advfloat/minimize.lua
-- apply the hide- target config (tgt) defined as part of 'advfloat_hide' gconfig_register("advfloat_hide", "statusbar-left"); local function hide_tgt(wnd, tgt) if (tgt == "statusbar-left" or tgt == "statusbar-right") then local old_show = wnd.show; local btn; -- deal with window being destroyed while we're hidden local on_destroy = function() if (btn) then btn:destroy(); end end; local wm = wnd.wm; local pad = gconfig_get("sbar_tpad") * wm.scalef; local str = string.sub(tgt, 11); -- actual button: -- click: migrate+reveal -- rclick: not-yet: select+popup btn = wm.statusbar:add_button(str, "sbar_item_bg", "sbar_item", wnd:get_name(), pad, wm.font_resfn, nil, nil, { click = function() local props = image_surface_resolve(btn.bg); wnd.show = old_show; wnd:drop_handler("destroy", on_destroy); btn:destroy(); wnd.wm:switch_ws(wnd.space); wnd:select(); if (#wm.on_wnd_hide > 0) then for k,v in ipairs(wm.on_wnd_hide) do v(wm, wnd, props.x, props.y, props.width, props.height, false); end else wnd:show(); wnd:select(); end end } ); -- out of VIDs if (not btn) then warning("hide-to-button: creation failed"); return; end -- safeguard against show being called from somewhere else wnd.show = function(wnd) if (btn.bg) then btn:click(); else wnd.show = old_show; old_show(wnd); end end; -- safeguard against window being destroyed while hidden wnd:add_handler("destroy", on_destroy); wnd:deselect(); -- event handler registered? (flair tool) if (#wm.on_wnd_hide > 0) then local props = image_surface_resolve(btn.bg); for k,v in ipairs(wm.on_wnd_hide) do v(wm, wnd, props.x, props.y, props.width, props.height, true); end else wnd:hide(); end else warning("unknown hide target: " .. tgt); end end menus_register("target", "window", { kind = "action", name = "hide", label = "Hide", description = "Hide or Minimize the window to a preset location", kind = "action", eval = function() return gconfig_get("advfloat_hide") ~= "disabled" and active_display().selected.space.mode == "float"; end, handler = function() local wnd = active_display().selected; if (not wnd.hide) then return; end local tgt = gconfig_get("advfloat_hide"); hide_tgt(wnd, tgt); end }); menus_register("global", "settings/wspaces/float", { kind = "value", name = "hide_target", description = "Chose where the window hide option will compress the window", initial = gconfig_get("advfloat_hide"), label = "Hide Target", set = {"disabled", "statusbar-left", "statusbar-right"}, handler = function(ctx, val) gconfig_set("advfloat_hide", val); end });
-- apply the hide- target config (tgt) defined as part of 'advfloat_hide' gconfig_register("advfloat_hide", "statusbar-left"); local function hide_tgt(wnd, tgt) -- prevent dual invocation (from ipc or wherever) if wnd.minimize_btn then return; end if (tgt == "statusbar-left" or tgt == "statusbar-right") then local old_show = wnd.show; local btn; -- deal with window being destroyed while we're hidden local on_destroy = function() if (btn) then wnd.minimize_btn = nil; btn:destroy(); end end; local wm = wnd.wm; local pad = gconfig_get("sbar_tpad") * wm.scalef; local str = string.sub(tgt, 11); -- actual button: -- click: migrate+reveal -- rclick: not-yet: select+popup btn = wm.statusbar:add_button(str, "sbar_item_bg", "sbar_item", wnd:get_name(), pad, wm.font_resfn, nil, nil, { click = function() local props = image_surface_resolve(btn.bg); wnd.minimize_btn = nil; wnd.show = old_show; wnd:drop_handler("destroy", on_destroy); btn:destroy(); wnd.wm:switch_ws(wnd.space); wnd:select(); if (#wm.on_wnd_hide > 0) then for k,v in ipairs(wm.on_wnd_hide) do v(wm, wnd, props.x, props.y, props.width, props.height, false); end else wnd:show(); wnd:select(); end end } ); -- out of VIDs if (not btn) then warning("hide-to-button: creation failed"); return; end -- safeguard against show being called from somewhere else wnd.show = function(wnd) if (btn.bg) then btn:click(); else wnd.show = old_show; old_show(wnd); end end; -- safeguard against window being destroyed while hidden wnd:add_handler("destroy", on_destroy); wnd:deselect(); wnd.minimize_btn = btn; -- event handler registered? (flair tool) if (#wm.on_wnd_hide > 0) then local props = image_surface_resolve(btn.bg); for k,v in ipairs(wm.on_wnd_hide) do v(wm, wnd, props.x, props.y, props.width, props.height, true); end else wnd:hide(); end else warning("unknown hide target: " .. tgt); end end menus_register("target", "window", { kind = "action", name = "hide", label = "Hide", description = "Hide or Minimize the window to a preset location", kind = "action", eval = function() return gconfig_get("advfloat_hide") ~= "disabled" and active_display().selected.space.mode == "float"; end, handler = function() local wnd = active_display().selected; if (not wnd.hide) then return; end local tgt = gconfig_get("advfloat_hide"); hide_tgt(wnd, tgt); end }); menus_register("global", "settings/wspaces/float", { kind = "value", name = "hide_target", description = "Chose where the window hide option will compress the window", initial = gconfig_get("advfloat_hide"), label = "Hide Target", set = {"disabled", "statusbar-left", "statusbar-right"}, handler = function(ctx, val) gconfig_set("advfloat_hide", val); end });
advfloat - safeguard on minimize to statusbar
advfloat - safeguard on minimize to statusbar if the minimize path was called mulitple times (possible through IPC) each new call would create a new button in the statusbar, fixed.
Lua
bsd-3-clause
letoram/durden
fa9b3137898c17a4410136263f2f1b7563598da2
lua/wire/stools/trigger.lua
lua/wire/stools/trigger.lua
-- Wire Trigger created by mitterdoo WireToolSetup.setCategory( "Detection" ) WireToolSetup.open( "trigger", "Trigger", "gmod_wire_trigger", nil, "Triggers" ) WireToolSetup.BaseLang() WireToolSetup.SetupMax( 64 ) TOOL.ClientConVar = { model = "models/jaanus/wiretool/wiretool_siren.mdl", filter = 0, -- 0: all entities, 1: only players, 2: only props (and stuff that isn't a player) owneronly = 0, sizex = 64, sizey = 64, sizez = 64, offsetx = 0, offsety = 0, offsetz = 0, } local DrawOutline if CLIENT then DrawOutline = CreateClientConVar( "wire_trigger_drawalltriggers", "0", true ) language.Add( "Tool.wire_trigger.filter", "Filters" ) language.Add( "Tool.wire_trigger.owneronly", "Owner's Stuff Only" ) language.Add( "Tool.wire_trigger.sizex", "Size X" ) language.Add( "Tool.wire_trigger.sizey", "Size Y" ) language.Add( "Tool.wire_trigger.sizez", "Size Z" ) language.Add( "Tool.wire_trigger.offsetx", "Offset X" ) language.Add( "Tool.wire_trigger.offsety", "Offset Y" ) language.Add( "Tool.wire_trigger.offsetz", "Offset Z" ) language.Add( "tool.wire_trigger.name", "Trigger Tool (Wire)" ) language.Add( "tool.wire_trigger.desc", "Spawns a Trigger" ) language.Add( "Tool.wire_trigger.alltriggers", "All Triggers Visible" ) language.Add( "tool.wire_trigger.resetsize", "Reset Size" ) language.Add( "tool.wire_trigger.resetoffset", "Reset Offset" ) language.Add( "Tool.wire_trigger.filter_all", "All Entities" ) language.Add( "Tool.wire_trigger.filter_players", "Only Players" ) language.Add( "Tool.wire_trigger.filter_props", "Only Props" ) language.Add( "tool."..TOOL.Mode..".0", "Primary: Create "..TOOL.Name.."" ) concommand.Add( "wire_trigger_reset_size", function( ply, cmd, args ) RunConsoleCommand( "wire_trigger_sizex", 64 ) RunConsoleCommand( "wire_trigger_sizey", 64 ) RunConsoleCommand( "wire_trigger_sizez", 64 ) end ) concommand.Add( "wire_trigger_reset_offset", function( ply, cmd, args ) RunConsoleCommand( "wire_trigger_offsetx", 0 ) RunConsoleCommand( "wire_trigger_offsety", 0 ) RunConsoleCommand( "wire_trigger_offsetz", 0 ) end ) end function TOOL:GetConVars() return self:GetClientInfo( "model" ), self:GetClientNumber( "filter" ), self:GetClientNumber( "owneronly" ), self:GetClientNumber( "sizex" ), self:GetClientNumber( "sizey" ), self:GetClientNumber( "sizez" ), self:GetClientNumber( "offsetx" ), self:GetClientNumber( "offsety" ), self:GetClientNumber( "offsetz" ) end local function DrawTriggerOutlines( list ) cam.Start3D( LocalPlayer():EyePos(), LocalPlayer():EyeAngles() ) for k,ent in pairs( list ) do local trig = ent:GetTriggerEntity() render.DrawWireframeBox( trig:GetPos(), Angle(0,0,0), trig:OBBMins(), trig:OBBMaxs(), Color( 255, 255, 0 ), true ) render.DrawLine( trig:GetPos(), ent:GetPos(), Color( 255, 255, 0 ) ) end cam.End3D() end hook.Add( "HUDPaint", "wire_trigger_draw_all_triggers", function() if DrawOutline:GetBool() then DrawTriggerOutlines( ents.FindByClass( "gmod_wire_trigger" ) ) end end ) function TOOL:DrawHUD() local tr = util.TraceLine( util.GetPlayerTrace( LocalPlayer() ) ) local ent = tr.Entity if IsValid( ent ) and ent:GetClass() == "gmod_wire_trigger" and not DrawOutline:GetBool() then DrawTriggerOutlines( {ent} ) end end function TOOL:RightClick( tr ) if IsValid( tr.Entity ) then local ent = tr.Entity if ent:GetClass() == "gmod_wire_trigger" then -- http:--youtu.be/RTR1ny0O_io local size = ent:GetTriggerSize() local offset = ent:GetTriggerOffset() RunConsoleCommand( "wire_trigger_sizex", size.x ) RunConsoleCommand( "wire_trigger_sizey", size.y ) RunConsoleCommand( "wire_trigger_sizez", size.z ) RunConsoleCommand( "wire_trigger_offsetx", offset.x ) RunConsoleCommand( "wire_trigger_offsety", offset.y ) RunConsoleCommand( "wire_trigger_offsetz", offset.z ) RunConsoleCommand( "wire_trigger_filter", ent:GetFilter() ) RunConsoleCommand( "wire_trigger_owneronly", ent:GetOwnerOnly() and 1 or 0 ) RunConsoleCommand( "wire_trigger_model", ent:GetModel() ) return true end end end function TOOL.BuildCPanel( panel ) ModelPlug_AddToCPanel(panel, "Misc_Tools", "wire_trigger") panel:CheckBox( "#Tool.wire_trigger.alltriggers", "wire_trigger_drawalltriggers" ) panel:AddControl( "ComboBox", { Label = "#Tool.wire_trigger.filter", Options = { ["#Tool.wire_trigger.filter_all"] = { wire_trigger_filter = 0 }, ["#Tool.wire_trigger.filter_players"] = { wire_trigger_filter = 1 }, ["#Tool.wire_trigger.filter_props"] = { wire_trigger_filter = 2 }, } }) panel:CheckBox( "#Tool.wire_trigger.owneronly", "wire_trigger_owneronly" ) panel:Button( "#Tool.wire_trigger.resetsize", "wire_trigger_reset_size" ) panel:NumSlider("#Tool.wire_trigger.sizex", "wire_trigger_sizex", -1000, 1000, 64) panel:NumSlider("#Tool.wire_trigger.sizey", "wire_trigger_sizey", -1000, 1000, 64) panel:NumSlider("#Tool.wire_trigger.sizez", "wire_trigger_sizez", -1000, 1000, 64) panel:Button( "#Tool.wire_trigger.resetoffset", "wire_trigger_reset_offset" ) panel:NumSlider("#Tool.wire_trigger.offsetx", "wire_trigger_offsetx", -1000, 1000, 0) panel:NumSlider("#Tool.wire_trigger.offsety", "wire_trigger_offsety", -1000, 1000, 0) panel:NumSlider("#Tool.wire_trigger.offsetz", "wire_trigger_offsetz", -1000, 1000, 0) end
-- Wire Trigger created by mitterdoo WireToolSetup.setCategory( "Detection" ) WireToolSetup.open( "trigger", "Trigger", "gmod_wire_trigger", nil, "Triggers" ) WireToolSetup.BaseLang() WireToolSetup.SetupMax( 64 ) TOOL.ClientConVar = { model = "models/jaanus/wiretool/wiretool_siren.mdl", filter = 0, -- 0: all entities, 1: only players, 2: only props (and stuff that isn't a player) owneronly = 0, sizex = 64, sizey = 64, sizez = 64, offsetx = 0, offsety = 0, offsetz = 0, } local DrawOutline if CLIENT then DrawOutline = CreateClientConVar( "wire_trigger_drawalltriggers", "0", true ) language.Add( "Tool.wire_trigger.filter", "Filters" ) language.Add( "Tool.wire_trigger.owneronly", "Owner's Stuff Only" ) language.Add( "Tool.wire_trigger.sizex", "Size X" ) language.Add( "Tool.wire_trigger.sizey", "Size Y" ) language.Add( "Tool.wire_trigger.sizez", "Size Z" ) language.Add( "Tool.wire_trigger.offsetx", "Offset X" ) language.Add( "Tool.wire_trigger.offsety", "Offset Y" ) language.Add( "Tool.wire_trigger.offsetz", "Offset Z" ) language.Add( "tool.wire_trigger.name", "Trigger Tool (Wire)" ) language.Add( "tool.wire_trigger.desc", "Spawns a Trigger" ) language.Add( "Tool.wire_trigger.alltriggers", "All Triggers Visible" ) language.Add( "tool.wire_trigger.resetsize", "Reset Size" ) language.Add( "tool.wire_trigger.resetoffset", "Reset Offset" ) language.Add( "Tool.wire_trigger.filter_all", "All Entities" ) language.Add( "Tool.wire_trigger.filter_players", "Only Players" ) language.Add( "Tool.wire_trigger.filter_props", "Only Props" ) language.Add( "tool."..TOOL.Mode..".0", "Primary: Create "..TOOL.Name.."" ) concommand.Add( "wire_trigger_reset_size", function( ply, cmd, args ) RunConsoleCommand( "wire_trigger_sizex", 64 ) RunConsoleCommand( "wire_trigger_sizey", 64 ) RunConsoleCommand( "wire_trigger_sizez", 64 ) end ) concommand.Add( "wire_trigger_reset_offset", function( ply, cmd, args ) RunConsoleCommand( "wire_trigger_offsetx", 0 ) RunConsoleCommand( "wire_trigger_offsety", 0 ) RunConsoleCommand( "wire_trigger_offsetz", 0 ) end ) end function TOOL:GetConVars() return self:GetClientInfo( "model" ), self:GetClientNumber( "filter" ), self:GetClientNumber( "owneronly" ), self:GetClientNumber( "sizex" ), self:GetClientNumber( "sizey" ), self:GetClientNumber( "sizez" ), self:GetClientNumber( "offsetx" ), self:GetClientNumber( "offsety" ), self:GetClientNumber( "offsetz" ) end local function DrawTriggerOutlines( list ) cam.Start3D( LocalPlayer():EyePos(), LocalPlayer():EyeAngles() ) for k,ent in pairs( list ) do local trig = ent:GetTriggerEntity() render.DrawWireframeBox( trig:GetPos(), Angle(0,0,0), trig:OBBMins(), trig:OBBMaxs(), Color( 255, 255, 0 ), true ) render.DrawLine( trig:GetPos(), ent:GetPos(), Color( 255, 255, 0 ) ) end cam.End3D() end hook.Add( "HUDPaint", "wire_trigger_draw_all_triggers", function() end ) function TOOL:DrawHUD() local tr = util.TraceLine( util.GetPlayerTrace( LocalPlayer() ) ) local ent = tr.Entity if IsValid( ent ) and ent:GetClass() == "gmod_wire_trigger" and not DrawOutline:GetBool() then DrawTriggerOutlines( {ent} ) elseif DrawOutline:GetBool() then DrawTriggerOutlines( ents.FindByClass( "gmod_wire_trigger" ) ) end end function TOOL:RightClick( tr ) if IsValid( tr.Entity ) then local ent = tr.Entity if ent:GetClass() == "gmod_wire_trigger" then -- http:--youtu.be/RTR1ny0O_io local size = ent:GetTriggerSize() local offset = ent:GetTriggerOffset() RunConsoleCommand( "wire_trigger_sizex", size.x ) RunConsoleCommand( "wire_trigger_sizey", size.y ) RunConsoleCommand( "wire_trigger_sizez", size.z ) RunConsoleCommand( "wire_trigger_offsetx", offset.x ) RunConsoleCommand( "wire_trigger_offsety", offset.y ) RunConsoleCommand( "wire_trigger_offsetz", offset.z ) RunConsoleCommand( "wire_trigger_filter", ent:GetFilter() ) RunConsoleCommand( "wire_trigger_owneronly", ent:GetOwnerOnly() and 1 or 0 ) RunConsoleCommand( "wire_trigger_model", ent:GetModel() ) return true end end end function TOOL.BuildCPanel( panel ) ModelPlug_AddToCPanel(panel, "Misc_Tools", "wire_trigger") panel:CheckBox( "#Tool.wire_trigger.alltriggers", "wire_trigger_drawalltriggers" ) panel:AddControl( "ComboBox", { Label = "#Tool.wire_trigger.filter", Options = { ["#Tool.wire_trigger.filter_all"] = { wire_trigger_filter = 0 }, ["#Tool.wire_trigger.filter_players"] = { wire_trigger_filter = 1 }, ["#Tool.wire_trigger.filter_props"] = { wire_trigger_filter = 2 }, } }) panel:CheckBox( "#Tool.wire_trigger.owneronly", "wire_trigger_owneronly" ) panel:Button( "#Tool.wire_trigger.resetsize", "wire_trigger_reset_size" ) panel:NumSlider("#Tool.wire_trigger.sizex", "wire_trigger_sizex", -1000, 1000, 64) panel:NumSlider("#Tool.wire_trigger.sizey", "wire_trigger_sizey", -1000, 1000, 64) panel:NumSlider("#Tool.wire_trigger.sizez", "wire_trigger_sizez", -1000, 1000, 64) panel:Button( "#Tool.wire_trigger.resetoffset", "wire_trigger_reset_offset" ) panel:NumSlider("#Tool.wire_trigger.offsetx", "wire_trigger_offsetx", -1000, 1000, 0) panel:NumSlider("#Tool.wire_trigger.offsety", "wire_trigger_offsety", -1000, 1000, 0) panel:NumSlider("#Tool.wire_trigger.offsetz", "wire_trigger_offsetz", -1000, 1000, 0) end
Fixed drawing all trigger boxes not working properly
Fixed drawing all trigger boxes not working properly
Lua
apache-2.0
garrysmodlua/wire,rafradek/wire,NezzKryptic/Wire,dvdvideo1234/wire,Grocel/wire,plinkopenguin/wiremod,wiremod/wire,notcake/wire,CaptainPRICE/wire,immibis/wiremod,bigdogmat/wire,thegrb93/wire,mitterdoo/wire,sammyt291/wire,mms92/wire,Python1320/wire
4b2eec4bbd20bcf618b68136f413355dca7c61c1
base/repair.lua
base/repair.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local money = require("base.money") itemPos = {{en="Head", de="Kopf"},{en="Neck", de="Hals"},{en="Breast", de="Brust"},{en="Both Hands", de="Beide Hnde"},{en="Left Hand", de="Linke Hand"}, {en="Right Tool", de="Rechte Hand"}, {en="Left Finger", de="Linker Finger"},{en="Right Finger", de="Rechter Finger"} ,{en="Legs", de="Beine"}, {en="Feet", de="Fe"}, {en="Coat", de="Umhang"},{en="Belt 1", de="Grtel 1"}, {en="Belt 2", de="Grtel 2"},{en="Belt 3", de="Grtel 3"},{en="Belt 4", de="Grtel 4"},{en="Belt 5", de="Grtel 5"},{en="Belt 6", de="Grtel 6"}} itemPos[0] = {en="Backpack", de="Rucksack"} local M = {} --opens a selection dialog for the player to choose an item to repair function M.repairDialog(npcChar, speaker) local dialogTitle, dialogInfoText, repairPriceText; local language = speaker:getPlayerLanguage(); --Set dialogmessages if language == 0 then --german dialogTitle = "Reparieren"; dialogInfoText = "Whle den Gegenstand aus, den du reparieren mchtest:"; repairPriceText = " Kosten: "; else --english dialogTitle = "Repair"; dialogInfoText = "Please choose an item you wish to repair:"; repairPriceText = " Cost: "; end --get all the items the char has on him, without the stuff in the backpack local itemsOnChar = {}; local itemPosOnChar = {}; for i=17,0,-1 do local item = speaker:getItemAt(i); if (item.id > 0) and (item.number == 1) and (getRepairPrice(item,speaker) ~= 0) then --only add items which are single items and repairable table.insert(itemsOnChar, item); table.insert(itemPosOnChar, itemPos[i]) end end local cbChooseItem = function (dialog) if (not dialog:getSuccess()) then return; end local index = dialog:getSelectedIndex()+1; local chosenItem = itemsOnChar[index] if chosenItem ~= nil then repair(npcChar, speaker, chosenItem, language); -- let's repair M.repairDialog(npcChar, speaker); -- call dialog recursively, to allow further repairs else speaker:inform("[ERROR] Something went wrong, please inform a developer."); end end local sdItems = SelectionDialog(dialogTitle, dialogInfoText, cbChooseItem); sdItems:setCloseOnMove(); local itemName, repairPrice, itemPosText; for i,item in ipairs(itemsOnChar) do itemName = world:getItemName(item.id,language) repairPrice = getRepairPrice(item,speaker) itemPosText = common.GetNLS(speaker, itemPosOnChar[i].de, itemPosOnChar[i].en) sdItems:addOption(item.id,itemName .. " (" .. itemPosText .. ")\n"..repairPriceText..repairPrice); end speaker:requestSelectionDialog(sdItems); end --returns the price as string to repair the item according to playerlanguage or 0 if the price is 0 function getRepairPrice(theItem, speaker) local theItemStats=world:getItemStats(theItem); if theItemStats.MaxStack == 1 then local durability=theItem.quality-100*math.floor(theItem.quality/100); --calculate the durability local toRepair=99-durability; --the amount of durability points that has to repaired local price=math.ceil(0.5*theItemStats.Worth*toRepair/1000)*10; --Price rounded up in 10 cp steps local gstring,estring; if price == 0 then return price; else gstring,estring=money.MoneyToString(price) end return common.GetNLS(speaker, gstring, estring) end return 0; end -- Repairs theItem. The NPC speaks if the repair was successful or the char has not enough money function repair(npcChar, speaker, theItem, language) local theItemStats=world:getItemStats(theItem); if theItem then local durability=theItem.quality-100*math.floor(theItem.quality/100); --calculate the durability local toRepair=99-durability; --the amount of durability points that has to repaired local price=math.ceil(0.5*theItemStats.Worth*toRepair/1000)*10; local priceMessage = getRepairPrice(theItem, speaker); if theItemStats.Worth == 0 or theItemStats.isStackable or durability==99 then --Cannot repair perfect, priceless or stackable items local notRepairable={"Entschuldigt, aber das kann ich nicht reparieren.", "I cannot repair this, sorry."}; --Priceless, perfect or stackable item npcChar:talk(Character.say, notRepairable[language+1]); else -- I can repair it! if not money.CharHasMoney(speaker,price) then --player is broke local notEnoughMoney={"Ihr habt anscheinend nicht genug Geld. Die Reparatur wrde"..priceMessage.." kosten.","You don't have enough money I suppose. I demand"..priceMessage.." for repairing this item."}; --Player is broke npcChar:talk(Character.say, notEnoughMoney[language+1]); else --he has the money local successRepair={"Der Gegenstand wird fr"..priceMessage.." in Stand gesetzt.", "The item is repaired at a cost of"..priceMessage.."."}; speaker:inform(successRepair[language+1]); money.TakeMoneyFromChar(speaker,price); --pay! theItem.quality=theItem.quality+toRepair; --repair! world:changeItem(theItem); end --price/repair end --there is an item end --item exists end; return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local money = require("base.money") itemPos = {{en="Head", de="Kopf"},{en="Neck", de="Hals"},{en="Breast", de="Brust"},{en="Both Hands", de="Beide Hnde"},{en="Left Hand", de="Linke Hand"}, {en="Right Tool", de="Rechte Hand"}, {en="Left Finger", de="Linker Finger"},{en="Right Finger", de="Rechter Finger"} ,{en="Legs", de="Beine"}, {en="Feet", de="Fe"}, {en="Coat", de="Umhang"},{en="Belt 1", de="Grtel 1"}, {en="Belt 2", de="Grtel 2"},{en="Belt 3", de="Grtel 3"},{en="Belt 4", de="Grtel 4"},{en="Belt 5", de="Grtel 5"},{en="Belt 6", de="Grtel 6"}} itemPos[0] = {en="Backpack", de="Rucksack"} local M = {} --opens a selection dialog for the player to choose an item to repair function M.repairDialog(npcChar, speaker) local dialogTitle, dialogInfoText, repairPriceText; local language = speaker:getPlayerLanguage(); --Set dialogmessages if language == 0 then --german dialogTitle = "Reparieren"; dialogInfoText = "Whle den Gegenstand aus, den du reparieren mchtest:"; repairPriceText = " Kosten: "; else --english dialogTitle = "Repair"; dialogInfoText = "Please choose an item you wish to repair:"; repairPriceText = " Cost: "; end --get all the items the char has on him, without the stuff in the backpack local itemsOnChar = {}; local itemPosOnChar = {}; for i=17,0,-1 do local item = speaker:getItemAt(i); if (item.id > 0) and (item.number == 1) and (getRepairPrice(item,speaker) ~= 0) then --only add items which are single items and repairable table.insert(itemsOnChar, item); table.insert(itemPosOnChar, itemPos[i]) end end local cbChooseItem = function (dialog) if (not dialog:getSuccess()) then return; end local index = dialog:getSelectedIndex()+1; local chosenItem = itemsOnChar[index] if chosenItem ~= nil then repair(npcChar, speaker, chosenItem, language); -- let's repair M.repairDialog(npcChar, speaker); -- call dialog recursively, to allow further repairs else speaker:inform("[ERROR] Something went wrong, please inform a developer."); end end local sdItems = SelectionDialog(dialogTitle, dialogInfoText, cbChooseItem); sdItems:setCloseOnMove(); local itemName, repairPrice, itemPosText; for i,item in ipairs(itemsOnChar) do itemName = world:getItemName(item.id,language) repairPrice = getRepairPrice(item,speaker) itemPosText = common.GetNLS(speaker, itemPosOnChar[i].de, itemPosOnChar[i].en) sdItems:addOption(item.id,itemName .. " (" .. itemPosText .. ")\n"..repairPriceText..repairPrice); end speaker:requestSelectionDialog(sdItems); end --returns the price as string to repair the item according to playerlanguage or 0 if the price is 0 function getRepairPrice(theItem, speaker) local theItemStats=world:getItemStats(theItem); if theItemStats.MaxStack == 1 then local durability=theItem.quality-100*math.floor(theItem.quality/100); --calculate the durability local toRepair=99-durability; --the amount of durability points that has to repaired local price=math.ceil(0.5*theItemStats.Worth*toRepair/1000)*10; --Price rounded up in 10 cp steps local gstring,estring; if price == 0 then return price; else gstring,estring=money.MoneyToString(price) end return common.GetNLS(speaker, gstring, estring) end return 0; end -- Repairs theItem. The NPC speaks if the repair was successful or the char has not enough money function repair(npcChar, speaker, theItem, language) local theItemStats=world:getItemStats(theItem); --Check all the items the char has on him, without the stuff in the backpack. Is the item still around? local itemsOnChar = {}; local itemPosOnChar = {}; for i=17,0,-1 do local item = speaker:getItemAt(i); if (item==theItem) then --if the item is around... found=true; end end if theItem and found then local durability=theItem.quality-100*math.floor(theItem.quality/100); --calculate the durability local toRepair=99-durability; --the amount of durability points that has to repaired local price=math.ceil(0.5*theItemStats.Worth*toRepair/1000)*10; local priceMessage = getRepairPrice(theItem, speaker); if theItemStats.Worth == 0 or theItemStats.isStackable or durability==99 then --Cannot repair perfect, priceless or stackable items local notRepairable={"Entschuldigt, aber das kann ich nicht reparieren.", "I cannot repair this, sorry."}; --Priceless, perfect or stackable item npcChar:talk(Character.say, notRepairable[language+1]); else -- I can repair it! if not money.CharHasMoney(speaker,price) then --player is broke local notEnoughMoney={"Ihr habt anscheinend nicht genug Geld. Die Reparatur wrde"..priceMessage.." kosten.","You don't have enough money I suppose. I demand"..priceMessage.." for repairing this item."}; --Player is broke npcChar:talk(Character.say, notEnoughMoney[language+1]); else --he has the money local successRepair={"Der Gegenstand wird fr"..priceMessage.." in Stand gesetzt.", "The item is repaired at a cost of"..priceMessage.."."}; speaker:inform(successRepair[language+1]); money.TakeMoneyFromChar(speaker,price); --pay! theItem.quality=theItem.quality+toRepair; --repair! world:changeItem(theItem); end --price/repair end --there is an item else speaker:inform("[ERROR] Item not found.","[FEHLER] Gegenstand nicht gefunden."); end --item exists end; return M
Hotfix for #11095
Hotfix for #11095
Lua
agpl-3.0
Illarion-eV/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
a7dfc8101b979fef009a51c32307fb12c209c35e
agents/monitoring/tests/fixtures/protocol/server.lua
agents/monitoring/tests/fixtures/protocol/server.lua
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local lineEmitter = LineEmitter:new() local port = 50041 local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(client, payload) -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil response.target = payload.source response.source = payload.target response.id = payload.id print("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') end local send_schedule_changed = function(client) local request = fixtures['check_schedule.changed.request'] print("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end tls.createServer(options, function (client) client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) print("Got payload:") p(payload) respond(client, payload) end) local send_schedule_changed_timer = timer.setTimeout(2000, function() send_schedule_changed(client) end) local send_schedule_changed_timer = timer.setInterval(60000, function() send_schedule_changed(client) end) end):listen(port) print("TCP echo server listening on port " .. port)
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local lineEmitter = LineEmitter:new() local port = 50041 local send_schedule_changed_initial = 2000 local send_schedule_changed_interval = 60000 local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(client, payload) -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil response.target = payload.source response.source = payload.target response.id = payload.id print("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') end local send_schedule_changed = function(client) local request = fixtures['check_schedule.changed.request'] print("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end tls.createServer(options, function (client) client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) print("Got payload:") p(payload) respond(client, payload) end) timer.setTimeout(send_schedule_changed_initial, function() send_schedule_changed(client) end) timer.setInterval(send_schedule_changed_interval, function() send_schedule_changed(client) end) end):listen(port) print("TCP echo server listening on port " .. port)
monitoring: fixtures: server: move constants to top
monitoring: fixtures: server: move constants to top move the timer constants to the top of the file.
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base
f5fde2ebbdb1422062449c4a4c9baaafb437e26b
test_scripts/Polices/build_options/004_ATF_P_TC_REQUEST_PTU_Trigger_PTU_failed_previous_IGN_ON_HTTP.lua
test_scripts/Polices/build_options/004_ATF_P_TC_REQUEST_PTU_Trigger_PTU_failed_previous_IGN_ON_HTTP.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Policy Table Update in case of failed retry strategy during previous IGN_ON -- [HMI API] PolicyUpdate request/response -- Description: -- SDL should request in case of failed retry strategy during previour IGN_ON -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- Connect mobile phone over WiFi. -- Register new application. -- Successful PTU. -- Register new application. -- PTU is requested. -- IGN OFF -- 2. Performed steps -- IGN ON. -- Connect device. Application is registered. -- -- Expected result: -- PTU is requested. PTS is created. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local testCasesForPolicyTableSnapshot = require ('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') --[[ Local Variables ]] local hmi_app_id1, hmi_app_id2 --[[ General Precondition before ATF start ]] --TODO: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_HTTP_Successful_Flow () commonFunctions:check_ptu_sequence_partly(self, "files/ptu_general.json", "ptu_general.json") end function Test:Precondition_StartNewSession() self.mobileSession1 = mobile_session.MobileSession( self, self.mobileConnection) self.mobileSession1:StartService(7) end function Test:Precondition_RegisterNewApplication() hmi_app_id1 = self.applications[config.application1.registerAppInterfaceParams.appName] local correlationId = self.mobileSession1:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application2.registerAppInterfaceParams.appName } }) :Do(function(_,_data2) hmi_app_id2 = _data2.params.application.appID EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}) testCasesForPolicyTableSnapshot:verify_PTS(true, {config.application1.registerAppInterfaceParams.appID, config.application2.registerAppInterfaceParams.appID}, {config.deviceMAC}, {hmi_app_id1, hmi_app_id2}) local timeout_after_x_seconds = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds") local seconds_between_retries = {} for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value end end) self.mobileSession1:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS"}) end function Test:Precondition_Suspend() self.hmiConnection:SendNotification("BasicCommunication.OnExitAllApplications", { reason = "SUSPEND" }) EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLPersistenceComplete") end function Test:Precondition_IGNITION_OFF() StopSDL() self.hmiConnection:SendNotification("BasicCommunication.OnExitAllApplications", { reason = "IGNITION_OFF" }) EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLClose") EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered"):Times(2) end function Test:Precondtion_StartSDL() StartSDL(config.pathToSDL, config.ExitOnCrash, self) end function Test:Precondtion_initHMI() self:initHMI() end function Test:Precondtion_initHMI_onReady() self:initHMI_onReady() end function Test:Precondtion_ConnectMobile() self:connectMobile() end function Test:Precondtion_CreateSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end -- [[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PTU_NotSuccessful_AppID_ListedPT_NewIgnCycle() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application1.appName } }) :Do(function(_,_) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}) testCasesForPolicyTableSnapshot:verify_PTS(true, {config.application1.registerAppInterfaceParams.appID, config.application2.registerAppInterfaceParams.appID}, {config.deviceMAC}, {hmi_app_id1, hmi_app_id2}) local timeout_after_x_seconds = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds") local seconds_between_retries = {} for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value end end) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS"}) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop_SDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Policy Table Update in case of failed retry strategy during previous IGN_ON -- [HMI API] PolicyUpdate request/response -- Description: -- SDL should request in case of failed retry strategy during previour IGN_ON -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- Connect mobile phone over WiFi. -- Register new application. -- Successful PTU. -- Register new application. -- PTU is requested. -- IGN OFF -- 2. Performed steps -- IGN ON. -- Connect device. Application is registered. -- -- Expected result: -- PTU is requested. PTS is created. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') --[[ General Precondition before ATF start ]] config.defaultProtocolVersion = 2 commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_HTTP_Successful_Flow () commonFunctions:check_ptu_sequence_partly(self, "files/ptu_general.json", "ptu_general.json") end function Test:Precondition_StartNewSession() self.mobileSession1 = mobile_session.MobileSession( self, self.mobileConnection) self.mobileSession1:StartService(7) end function Test:Precondition_RegisterNewApplication() local correlationId = self.mobileSession1:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application2.registerAppInterfaceParams.appName } }) self.mobileSession1:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) end function Test:Precondition_Suspend() self.hmiConnection:SendNotification("BasicCommunication.OnExitAllApplications", { reason = "SUSPEND" }) EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLPersistenceComplete") end function Test:Precondition_IGNITION_OFF() StopSDL() self.hmiConnection:SendNotification("BasicCommunication.OnExitAllApplications", { reason = "IGNITION_OFF" }) EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLClose") EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered"):Times(2) end function Test:Precondtion_StartSDL() StartSDL(config.pathToSDL, config.ExitOnCrash, self) end function Test:Precondtion_initHMI() self:initHMI() end function Test:Precondtion_initHMI_onReady() self:initHMI_onReady() end function Test:Precondtion_ConnectMobile() self:connectMobile() end function Test:Precondtion_CreateSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end -- [[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PTU_NotSuccessful_AppID_ListedPT_NewIgnCycle() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop_SDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
4625171ab714927799e599c9e8c35d9f0abbffb7
includes/bootstrap.lua
includes/bootstrap.lua
local version = { core = 'Ophal', number = '0.1', revision = 'alpha11', homepage = 'ophal.org', } -- Jailed environment functions and modules env = { io = io, os = os, tonumber = tonumber, type = type, module = module, pcall = pcall, loadstring = loadstring, setfenv = setfenv, getfenv = getfenv, assert = assert, table = table, require = require, unpack = unpack, pairs = pairs, ipairs = ipairs, rawset = rawset, rawget = rawget, error = error, debug = debug, package = package, string = string, math = math, next = next, tostring = tostring, setmetatable = setmetatable, getmetatable = getmetatable, select = select, _SERVER = os.getenv, _SESSION = nil, lfs = nil, lpeg = nil, uuid = nil, socket = nil, theme = {}, mobile = {}, base = { system_root = '', route = '/', url = '', path = '', }, output_buffer = {}, ophal = { version = nil, modules = {}, routes = {}, aliases = {}, blocks = {}, regions = {}, title = '', header_title = '', cookies = {}, header = nil, session = nil, }, } -- Load settings settings = { version = { core = true, number = true, revision = true, }, slash = string.sub(package.config,1,1), modules = {}, } do local _, vault = pcall(require, 'vault') local _, settings_builder = pcall(require, 'settings') if type(settings_builder) == 'function' then settings_builder(settings, vault) end env.settings = settings end -- Build version if settings.version.core then if settings.version.number then if settings.version.revision then env.ophal.version = ('%s %s-%s (%s)'):format(version.core, version.number, version.revision, version.homepage) else env.ophal.version = ('%s %s (%s)'):format(version.core, version.number, version.homepage) end else env.ophal.version = ('%s (%s)'):format(version.core, version.homepage) end end -- Detect nginx if ngx then env.ngx = ngx for k, v in pairs(getfenv(0, ngx)) do env[k] = v end end -- The actual module local setfenv, type, env = setfenv, type, env module 'ophal' function bootstrap(phase, main) if type(main) ~= 'function' then main = function() end end local status, err, exit_bootstrap -- Jail setfenv(0, env) -- global environment setfenv(1, env) -- bootstrap environment setfenv(main, env) -- script environment env._G = env env.env = env local phases = { -- 1. Lua and Seawolf libraries function () env.lfs = require 'lfs' env.lpeg = require 'lpeg' env.uuid = require 'uuid' env.socket = require 'socket' env.socket.url = require 'socket.url' require 'seawolf.variable' require 'seawolf.fs' require 'seawolf.text' require 'seawolf.behaviour' require 'seawolf.contrib' end, -- 2. Debug API function () if settings.debugapi then require 'includes.debug' end end, -- 3. Load native server API function () if ngx then require 'includes.server.nginx' else require 'includes.server.cgi' end end, -- 4. Mobile API, function () if settings.mobile then require 'includes.mobile' end end, -- 5. Load Ophal server API function () require 'includes.server.init' end, -- 6. Check installer function () if (_SERVER 'SCRIPT_NAME' or '/index.cgi') == base.route .. 'index.cgi' and not seawolf.fs.is_file 'settings.lua' then redirect(('%s%sinstall.cgi'):format(base.system_root, base.route)) require 'includes.common' return -1 end end, -- 7. Session API, function () if settings.sessionapi then require 'includes.session' session_start() end end, -- 8. Route API, function () require 'includes.route' build_base() end, -- 9. Core API, function () require 'includes.common' require 'includes.module' require 'includes.theme' require 'includes.pager' if settings.formapi then require 'includes.form' require 'includes.file' end end, -- 10. Modules, function () local status, err for k, v in pairs(settings.modules) do if v then status, err = pcall(require, 'modules.' .. k .. '.init') if not status then print('bootstrap: ' .. err) end end end end, -- 11. Boot, function () module_invoke_all 'boot' end, -- 12. Database API, function () if settings.db ~= nil then require 'includes.database' if settings.db.default ~= nil then db_connect() if settings.route_aliases_storage then route_aliases_load() end end end end, -- 13. Init, function () module_invoke_all 'init' end, -- 14. Full, function () -- call hook route to load handlers -- TODO: implement route cache ophal.routes = route_build_routes() theme_blocks_load() theme_regions_load() -- process current route init_route() end, } -- Loop over phase for p = 1, (phase or #phases) do status, err = pcall(phases[p]) if not status then io.write(([[ bootstrap[%s]: %s]]):format(p, err or '')) exit_bootstrap = true break elseif err == -1 then exit_bootstrap = true break end end -- execute script if not exit_bootstrap then status, err = pcall(main) if not status then io.write([[ bootstrap[main]: ]] .. (err or '')) end end -- The end exit_ophal() end
local version = { core = 'Ophal', number = '0.1', revision = 'alpha11', homepage = 'ophal.org', } -- Jailed environment functions and modules env = { io = io, os = os, tonumber = tonumber, type = type, module = module, pcall = pcall, loadstring = loadstring, setfenv = setfenv, getfenv = getfenv, assert = assert, table = table, require = require, unpack = unpack, pairs = pairs, ipairs = ipairs, rawset = rawset, rawget = rawget, error = error, debug = debug, package = package, string = string, math = math, next = next, tostring = tostring, setmetatable = setmetatable, getmetatable = getmetatable, select = select, _SERVER = os.getenv, _SESSION = nil, lfs = nil, lpeg = nil, uuid = nil, socket = nil, theme = {}, mobile = {}, base = { system_root = '', route = '/', url = '', path = '', }, output_buffer = {}, ophal = { version = nil, modules = {}, routes = {}, aliases = {}, blocks = {}, regions = {}, title = '', header_title = '', cookies = {}, header = nil, session = nil, }, } -- Load settings settings = { version = { core = true, number = true, revision = true, }, slash = string.sub(package.config,1,1), modules = {}, } do local _, vault = pcall(require, 'vault') local _, settings_builder = pcall(require, 'settings') if type(settings_builder) == 'function' then settings_builder(settings, vault) end env.settings = settings end -- Build version if settings.version.core then if settings.version.number then if settings.version.revision then env.ophal.version = ('%s %s-%s (%s)'):format(version.core, version.number, version.revision, version.homepage) else env.ophal.version = ('%s %s (%s)'):format(version.core, version.number, version.homepage) end else env.ophal.version = ('%s (%s)'):format(version.core, version.homepage) end end -- Detect nginx if ngx then env.ngx = ngx for k, v in pairs(getfenv(0, ngx)) do env[k] = v end end -- The actual module local setfenv, type, env = setfenv, type, env module 'ophal' function bootstrap(phase, main) if type(main) ~= 'function' then main = function() end end local status, err, exit_bootstrap -- Jail setfenv(0, env) -- global environment setfenv(1, env) -- bootstrap environment setfenv(main, env) -- script environment env._G = env env.env = env local phases = { -- 1. Lua and Seawolf libraries function () env.lfs = require 'lfs' env.lpeg = require 'lpeg' env.uuid = require 'uuid' env.socket = require 'socket' env.socket.url = require 'socket.url' require 'seawolf.variable' require 'seawolf.fs' require 'seawolf.text' require 'seawolf.behaviour' require 'seawolf.contrib' end, -- 2. Debug API function () if settings.debugapi then require 'includes.debug' end end, -- 3. Load native server API function () if ngx then require 'includes.server.nginx' else require 'includes.server.cgi' end end, -- 4. Mobile API, function () if settings.mobile then require 'includes.mobile' end end, -- 5. Load Ophal server API function () require 'includes.server.init' end, -- 6. Check installer function () if (_SERVER 'SCRIPT_NAME' or '/index.cgi') == base.route .. 'index.cgi' and not seawolf.fs.is_file 'settings.lua' then require 'includes.common' redirect(('%s%sinstall.cgi'):format(base.system_root, base.route)) return -1 end end, -- 7. Session API, function () if settings.sessionapi then require 'includes.session' session_start() end end, -- 8. Route API, function () require 'includes.route' build_base() end, -- 9. Core API, function () require 'includes.common' require 'includes.module' require 'includes.theme' require 'includes.pager' if settings.formapi then require 'includes.form' require 'includes.file' end end, -- 10. Modules, function () local status, err for k, v in pairs(settings.modules) do if v then status, err = pcall(require, 'modules.' .. k .. '.init') if not status then print('bootstrap: ' .. err) end end end end, -- 11. Boot, function () module_invoke_all 'boot' end, -- 12. Database API, function () if settings.db ~= nil then require 'includes.database' if settings.db.default ~= nil then db_connect() if settings.route_aliases_storage then route_aliases_load() end end end end, -- 13. Init, function () module_invoke_all 'init' end, -- 14. Full, function () -- call hook route to load handlers -- TODO: implement route cache ophal.routes = route_build_routes() theme_blocks_load() theme_regions_load() -- process current route init_route() end, } -- Loop over phase for p = 1, (phase or #phases) do status, err = pcall(phases[p]) if not status then io.write(([[ bootstrap[%s]: %s]]):format(p, err or '')) exit_bootstrap = true break elseif err == -1 then exit_bootstrap = true break end end -- execute script if not exit_bootstrap then status, err = pcall(main) if not status then io.write([[ bootstrap[main]: ]] .. (err or '')) end end -- The end exit_ophal() end
Bug fix: redirect to Installation Wizard not working on nginx.
Bug fix: redirect to Installation Wizard not working on nginx.
Lua
agpl-3.0
coinzen/coinage,coinzen/coinage,ophal/core,coinzen/coinage,ophal/core,ophal/core
0853d110051fdea1698b0f1bd118d26e9fc91a71
lib/gsmake/gsmake/init.lua
lib/gsmake/gsmake/init.lua
local fs = require "lemoon.fs" local class = require "lemoon.class" local filepath = require "lemoon.filepath" local logsink = require "lemoon.logsink" local logger = class.new("lemoon.log","gsmake") local console = class.new("lemoon.log","console") local module = {} local openlog = function(gsmake) local name = "gsmake" .. os.date("-%Y-%m-%d-%H_%M_%S") local path = filepath.join(gsmake.Config.Workspace,gsmake.Config.TempDirName,"log") if not fs.exists(path) then fs.mkdir(path,true) end logsink.file_sink( "gsmake", path, name, ".log", false, 1024*1024*10) end -- create new gsmake runtimes -- @arg workspace gsmake workspace function module.ctor(workspace,env) local gsmake = { Config = class.clone(require "config") ; -- global config table Remotes = class.clone(require "remotes") ; -- remote lists Loaders = {} ; -- package loader's table } -- set the gsmake home path gsmake.Config.Home = os.getenv(env) -- set the machine scope package cached directory gsmake.Config.GlobalRepo = gsmake.Config.GlobalRepo or filepath.join(gsmake.Config.Home,".repo") -- set the project workspace gsmake.Config.Workspace = workspace openlog(gsmake) if not fs.exists(filepath.join(workspace ,gsmake.Config.PackageFileName)) then gsmake.Config.Workspace = gsmake.Config.Home end if not fs.exists(gsmake.Config.GlobalRepo) then fs.mkdir(gsmake.Config.GlobalRepo,true) -- create repo directories end gsmake.Repo = class.new("gsmake.repo",gsmake,gsmake.Config.GlobalRepo) -- cache builtin plugins module.load_system_plugins(gsmake,filepath.join(gsmake.Config.Home,"lib/gsmake/plugin")) -- create root package loader local loader = class.new("gsmake.loader",gsmake,gsmake.Config.Workspace) gsmake.Loaders[string.format("%s:%s",loader.Package.Name,loader.Package.Version)] = loader gsmake.Package = loader.Package -- load builtin system commands module.load_system_commands(gsmake,gsmake.Package,filepath.join(gsmake.Config.Home,"lib/gsmake/cmd")) loader:load() loader:setup() return gsmake end function module:load_system_commands(rootPackage,dir) if fs.exists(filepath.join(dir,self.Config.PackageFileName)) then local package = class.new("gsmake.loader",self,dir).Package self.Repo:save_source(package.Name,package.Version,dir,dir,true) local plugin = class.new("gsmake.plugin",package.Name,rootPackage) rootPackage.Plugins[package.Name] = plugin return end fs.list(dir,function(entry) if entry == "." or entry == ".." then return end local path = filepath.join(dir,entry) if fs.isdir(path) then module.load_system_commands(self,rootPackage,path) end end) end function module:load_system_plugins(dir) if fs.exists(filepath.join(dir,self.Config.PackageFileName)) then local package = class.new("gsmake.loader",self,dir).Package self.Repo:save_source(package.Name,package.Version,dir,dir,true) return end fs.list(dir,function(entry) if entry == "." or entry == ".." then return end local path = filepath.join(dir,entry) if fs.isdir(path) then module.load_system_plugins(self,path) end end) end function module:run (...) self.Package.Loader:run(...) end return module
local fs = require "lemoon.fs" local class = require "lemoon.class" local filepath = require "lemoon.filepath" local logsink = require "lemoon.logsink" local logger = class.new("lemoon.log","gsmake") local console = class.new("lemoon.log","console") local module = {} local openlog = function(gsmake) local name = "gsmake" .. os.date("-%Y-%m-%d-%H_%M_%S") local path = filepath.join(gsmake.Config.Workspace,gsmake.Config.TempDirName,"log") if not fs.exists(path) then fs.mkdir(path,true) end logsink.file_sink( "gsmake", path, name, ".log", false, 1024*1024*10) end -- create new gsmake runtimes -- @arg workspace gsmake workspace function module.ctor(workspace,env) local gsmake = { Config = class.clone(require "config") ; -- global config table Remotes = class.clone(require "remotes") ; -- remote lists Loaders = {} ; -- package loader's table } -- set the gsmake home path gsmake.Config.Home = os.getenv(env) -- set the machine scope package cached directory gsmake.Config.GlobalRepo = gsmake.Config.GlobalRepo or filepath.join(gsmake.Config.Home,".repo") -- set the project workspace gsmake.Config.Workspace = workspace if not fs.exists(filepath.join(workspace ,gsmake.Config.PackageFileName)) then gsmake.Config.Workspace = gsmake.Config.Home end openlog(gsmake) if not fs.exists(gsmake.Config.GlobalRepo) then fs.mkdir(gsmake.Config.GlobalRepo,true) -- create repo directories end gsmake.Repo = class.new("gsmake.repo",gsmake,gsmake.Config.GlobalRepo) -- cache builtin plugins module.load_system_plugins(gsmake,filepath.join(gsmake.Config.Home,"lib/gsmake/plugin")) -- create root package loader local loader = class.new("gsmake.loader",gsmake,gsmake.Config.Workspace) gsmake.Loaders[string.format("%s:%s",loader.Package.Name,loader.Package.Version)] = loader gsmake.Package = loader.Package -- load builtin system commands module.load_system_commands(gsmake,gsmake.Package,filepath.join(gsmake.Config.Home,"lib/gsmake/cmd")) loader:load() loader:setup() return gsmake end function module:load_system_commands(rootPackage,dir) if fs.exists(filepath.join(dir,self.Config.PackageFileName)) then local package = class.new("gsmake.loader",self,dir).Package self.Repo:save_source(package.Name,package.Version,dir,dir,true) local plugin = class.new("gsmake.plugin",package.Name,rootPackage) rootPackage.Plugins[package.Name] = plugin return end fs.list(dir,function(entry) if entry == "." or entry == ".." then return end local path = filepath.join(dir,entry) if fs.isdir(path) then module.load_system_commands(self,rootPackage,path) end end) end function module:load_system_plugins(dir) if fs.exists(filepath.join(dir,self.Config.PackageFileName)) then local package = class.new("gsmake.loader",self,dir).Package self.Repo:save_source(package.Name,package.Version,dir,dir,true) return end fs.list(dir,function(entry) if entry == "." or entry == ".." then return end local path = filepath.join(dir,entry) if fs.isdir(path) then module.load_system_plugins(self,path) end end) end function module:run (...) self.Package.Loader:run(...) end return module
fix log output bug
fix log output bug
Lua
mit
gsmake/gsmake,gsmake/gsmake
40e5541951e6553c98337a735730b02f0c5bc85b
src/premake/Test.lua
src/premake/Test.lua
local testname = ... local sdl2_dir = (path.getabsolute("../../../SDKs/") .. "/SDL2-2.0.3/") project(testname) kind "ConsoleApp" includedirs { "../PGTA", "../tests/Common" } links "PGTALib" defines "SDL_MAIN_HANDLED" files { "../tests/"..testname.."/**.h", "../tests/"..testname.."/**.cpp", "../tests/Common/**.h", "../tests/Common/**.cpp" } filter "platforms:x32" targetsuffix "_x32" filter "platforms:x64" targetsuffix "_x64" filter "system:macosx or system:linux" includedirs "/usr/local/include/SDL2/" links "SDL2" filter {} if (os.get() == "windows") then -- include sdl2 copy_sdl_dll = true dofile (sdl2_dir .. "premake5_include.lua") end postbuildcommands{ MKDIR("../../../bin/"), COPY(testname.."_*", "../../../bin/") } project "*"
local testname = ... target_dir = path.getabsolute("../../bin/") .. "/" local sdl2_dir = (path.getabsolute("../../../SDKs/") .. "/SDL2-2.0.3/") project(testname) kind "ConsoleApp" includedirs { "../PGTA", "../tests/Common" } links "PGTALib" defines "SDL_MAIN_HANDLED" files { "../tests/"..testname.."/**.h", "../tests/"..testname.."/**.cpp", "../tests/Common/**.h", "../tests/Common/**.cpp" } filter "platforms:x32" targetsuffix "_x32" filter "platforms:x64" targetsuffix "_x64" filter "system:macosx or system:linux" includedirs "/usr/local/include/SDL2/" links "SDL2" filter {} if (os.get() == "windows") then -- include sdl2 copy_sdl_dll = true dofile (sdl2_dir .. "premake5_include.lua") end postbuildcommands{ MKDIR("../../../bin/"), COPY(testname.."_*", "../../../bin/") } project "*"
Issue #14, fixing windows build.
Issue #14, fixing windows build.
Lua
mit
PGTA/PGTA,PGTA/PGTA,PGTA/PGTA
fc3a12e777d10bded39c022fd83dc15eec54c3f2
MMOCoreORB/bin/scripts/object/tangible/loot/quest/rifle_quest_tusken.lua
MMOCoreORB/bin/scripts/object/tangible/loot/quest/rifle_quest_tusken.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_loot_quest_rifle_quest_tusken = object_tangible_loot_quest_shared_rifle_quest_tusken:new { } ObjectTemplates:addTemplate(object_tangible_loot_quest_rifle_quest_tusken, "object/tangible/loot/quest/rifle_quest_tusken.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_loot_quest_rifle_quest_tusken = object_tangible_loot_quest_shared_rifle_quest_tusken:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/ithorian_male.iff", "object/creature/player/ithorian_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/wookiee_male.iff", "object/creature/player/wookiee_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff" }, -- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK, -- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK attackType = RANGEDATTACK, -- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, FORCE, LIGHTSABER damageType = ENERGY, -- NONE, LIGHT, MEDIUM, HEAVY armorPiercing = NONE, -- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine -- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general, -- combat_meleespecialize_twohandlightsaber, combat_meleespecialize_polearmlightsaber, combat_meleespecialize_onehandlightsaber xpType = "combat_rangedspecialize_rifle", certificationsRequired = { "cert_rifle_tusken" }, creatureAccuracyModifiers = { "rifle_accuracy" }, creatureAimModifiers = { "rifle_aim", "aim" }, defenderDefenseModifiers = { "ranged_defense" }, defenderSecondaryDefenseModifiers = { "block" }, speedModifiers = { "rifle_speed" }, damageModifiers = { }, -- The values below are the default values. To be used for blue frog objects primarily healthAttackCost = 25, actionAttackCost = 35, mindAttackCost = 75, forceCost = 0, pointBlankRange = 0, pointBlankAccuracy = -60, idealRange = 60, idealAccuracy = 20, maxRange = 64, maxRangeAccuracy = -50, minDamage = 50, maxDamage = 100, attackSpeed = 10, woundsRatio = 3, numberExperimentalProperties = {1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2}, experimentalProperties = {"XX", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ", "XX", "XX", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ"}, experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "expDamage", "expDamage", "expDamage", "expDamage", "expEffeciency", "exp_durability", "null", "null", "null", "expRange", "expEffeciency", "expEffeciency", "expEffeciency"}, experimentalSubGroupTitles = {"null", "null", "mindamage", "maxdamage", "attackspeed", "woundchance", "roundsused", "hitpoints", "zerorangemod", "maxrangemod", "midrange", "midrangemod", "attackhealthcost", "attackactioncost", "attackmindcost"}, experimentalMin = {0, 0, 50, 100, 10, 3, 30, 750, -60, -50, 60, 0, 25, 35, 75}, experimentalMax = {0, 0, 100, 150, 7, 8, 65, 1500, -60, -50, 60, 20, 15, 20, 45}, experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, experimentalCombineType = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, } ObjectTemplates:addTemplate(object_tangible_loot_quest_rifle_quest_tusken, "object/tangible/loot/quest/rifle_quest_tusken.iff")
[Fixed] tusken king rifle - mantis 6625
[Fixed] tusken king rifle - mantis 6625 Change-Id: I01366cbe0c1002c1caa61cdfb1f7409e8bd18ed7
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
8c0503196c8b7bca585997e465443c48be1f7e45
scheduled/factionLeader.lua
scheduled/factionLeader.lua
--Checks if the playable faction leaders is logged in and thus the NPC needs to be out of player sight require("base.common") module("scheduled.factionLeader", package.seeall) function checkFactionLeader() players=world:getPlayersOnline() for index, playerName in pairs(players) do if playerName == "Rosaline Edwards" then npcPositions = {position(122, 521, 0), position(237, 104, 0)}; updatePosition(npcPositions) elseif playerName == "Valerio Guilianni" then npcPositions = {position(337, 215, 0), position(238, 104, 0)}; updatePosition(npcPositions) elseif playerName == "Elvaine Morgan" then npcPositions = {position(898, 775, 2), position(239, 104, 0)}; updatePosition(npcPositions) end end end function updatePosition(npcPositions) if world:isCharacterOnField(npcPositions[1]) == true then npcCharObject = world:getCharacterOnField(npcPositions[1]); npcCharObject:forceWarp(npcPositions[2]); end end
--Checks if the playable faction leaders is logged in and thus the NPC needs to be out of player sight require("base.common") module("scheduled.factionLeader", package.seeall) function checkFactionLeader() players=world:getPlayersOnline() for index, player in pairs(players) do if player.name == "Rosaline Edwards" then npcPositions = {usualPosition=position(122, 521, 0), newPosition=position(237, 104, 0)}; updatePosition(npcPositions) elseif player.name == "Valerio Guilianni" then npcPositions = {usualPosition=position(337, 215, 0), newPosition=position(238, 104, 0)}; updatePosition(npcPositions) elseif player.name == "Elvaine Morgan" then npcPositions = {usualPosition=position(898, 775, 2), newPosition=position(239, 104, 0)}; updatePosition(npcPositions) end end end function updatePosition(npcPositions) if world:isCharacterOnField(npcPositions.usualPosition) == true then npcCharObject = world:getCharacterOnField(npcPositions.usualPosition); npcCharObject:forceWarp(npcPositions.newPosition); end end
fixed if statement..i think
fixed if statement..i think
Lua
agpl-3.0
KayMD/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
88d2252d76b5554a68d9ba162b2fc110d4a1255e
tools/utils/BPE.lua
tools/utils/BPE.lua
local unicode = require './unicode' local BPE = torch.class('BPE') function BPE:__init(codesfile_path) local codes = {} local f = assert(io.open(codesfile_path, "r")) local t=f:read("*line") local i=1 while not(t == nil) do l=string.split(t," ") if (#l==2) then codes[t]=i i=i+1 end t=f:read("*line") end self.codes = codes end local function getPairs(word) local pairs = {} for i=1, #word-1, 1 do table.insert(pairs, word[i]..' '..word[i+1]) end return pairs end local function str2word(l) local word = {} for v, c in unicode.utf8_iter(l) do table.insert(word, c) end table.insert(word, '</w>') return word end function BPE:minPair(pairsTable) mintmp = 100000 minpair = '' for i=1, #pairsTable, 1 do pair_cur = pairsTable[i] if (self.codes[pair_cur] ~= nil) then scoretmp = self.codes[pair_cur] if (scoretmp < mintmp) then mintmp = scoretmp minpair = pair_cur end end end return minpair end function BPE:encode(l) local nextv, nextc = unicode._utf8_to_cp(l, 1) if #l <= #nextc then return l end local word = str2word(l) local pairs = getPairs(word) while (true) do local bigram = self:minPair(pairs) if (bigram == '') then break end bigram = string.split(bigram," ") local new_word = {} local merge = false for ii, xx in ipairs(word) do if (merge) then if (bigram[2] == xx) then table.insert(new_word, bigram[1]..bigram[2]) else table.insert(new_word, bigram[1]) end merge = false else if (bigram[1] == xx ) then merge = true else table.insert(new_word, xx) end end end word = new_word if #word == 1 then break else pairs = getPairs(word) end end if word[#word] == '</w>' then table.remove(word, #word) elseif (string.sub(word[#word],-string.len('</w>'))=='</w>') then word[#word] = string.sub(word[#word], 1, string.len('</w>')) end return word end return BPE
local unicode = require './unicode' local BPE = torch.class('BPE') function BPE:__init(codesfile_path) local codes = {} local f = assert(io.open(codesfile_path, "r")) local t=f:read("*line") local i=1 while not(t == nil) do local l=string.split(t," ") if (#l==2) then codes[t]=i i=i+1 end t=f:read("*line") end self.codes = codes end local function getPairs(word) local pairs = {} for i=1, #word-1, 1 do table.insert(pairs, word[i]..' '..word[i+1]) end return pairs end local function str2word(l) local word = {} for v, c in unicode.utf8_iter(l) do table.insert(word, c) end table.insert(word, '</w>') return word end function BPE:minPair(pairsTable) local mintmp = 100000 local minpair = '' for i=1, #pairsTable, 1 do local pair_cur = pairsTable[i] if (self.codes[pair_cur] ~= nil) then scoretmp = self.codes[pair_cur] if (scoretmp < mintmp) then mintmp = scoretmp minpair = pair_cur end end end return minpair end function BPE:encode(l) local nextv, nextc = unicode._utf8_to_cp(l, 1) if #l <= #nextc then local w = {} table.insert(w, l) return w end local word = str2word(l) local pairs = getPairs(word) while (true) do local bigram = self:minPair(pairs) if (bigram == '') then break end bigram = string.split(bigram," ") local new_word = {} local merge = false for ii, xx in ipairs(word) do if (merge) then if (bigram[2] == xx) then table.insert(new_word, bigram[1]..bigram[2]) else table.insert(new_word, bigram[1]) end merge = false else if (bigram[1] == xx ) then merge = true else table.insert(new_word, xx) end end end word = new_word if #word == 1 then break else pairs = getPairs(word) end end if word[#word] == '</w>' then table.remove(word, #word) elseif (string.sub(word[#word],-string.len('</w>'))=='</w>') then word[#word] = string.sub(word[#word], 1, -string.len('</w>')-1) end return word end return BPE
fix end of token <\w> replacement error
fix end of token <\w> replacement error
Lua
mit
jsenellart/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,srush/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,cservan/OpenNMT_scores_0.2.0,jsenellart-systran/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,da03/OpenNMT
7775940177cea8a268c266e8d6a9690b0a317753
modules/farming_module.lua
modules/farming_module.lua
------------------------------------------------------------ -- Copyright (c) 2016 tacigar -- https://github.com/tacigar/maidroid ------------------------------------------------------------ local _aux = maidroid.modules._aux local state = { walk = 0, punch = 1, plant = 2, walk_to_plant = 3, walk_to_soil = 4, } local max_punch_time = 20 local max_plant_time = 15 local search_lenvec = {x = 3, y = 0, z = 3} -- find max size of each plants local target_plants_list = {} minetest.after(0, function() local max = {} for name, node in pairs(minetest.registered_nodes) do if minetest.get_item_group(name, "plant") > 0 then local s, i = string.match(name, "(.+)_(%d+)") if max[s] == nil or max[s] < i then max[s] = i end end end for s, i in pairs(max) do table.insert(target_plants_list, s.."_"..i) end end) -- check the maidroid has seed items local function has_seed_item(self) local inv = maidroid._aux.get_maidroid_inventory(self) local stacks = inv:get_list("main") for _, stack in ipairs(stacks) do local item_name = stack:get_name() if minetest.get_item_group(item_name, "seed") > 0 then return true end end return false end -- check can plant plants. local function can_plant(self, pos) local node = minetest.get_node(pos) local upos = _aux.get_under_pos(pos) local unode = minetest.get_node(upos) return node.name == "air" and minetest.get_item_group(unode.name, "wet") > 0 and has_seed_item(self) end -- check can punch plant local function can_punch(self, pos) local node = minetest.get_node(pos) return maidroid.util.table_find_value(target_plants_list, node.name) end -- change state to walk local function to_walk(self) self.state = state.walk self.destination = nil self.object:set_animation(maidroid.animations.walk, 15, 0) self.time_count = 0 _aux.change_dir(self) end maidroid.register_module("maidroid:farming_module", { description = "Maidroid Module : Farming", inventory_image = "maidroid_farming_module.png", initialize = function(self) self.object:set_animation(maidroid.animations.walk, 15, 0) self.object:setacceleration{x = 0, y = -10, z = 0} self.state = state.walk self.preposition = self.object:getpos() self.time_count = 0 self.destination = nil -- for walk_to_* _aux.change_dir(self) end, finalize = function(self) self.state = nil self.preposition = nil self.time_count = nil self.destination = nil self.object:setvelocity{x = 0, y = 0, z = 0} end, on_step = function(self, dtime) local pos = self.object:getpos() local rpos = vector.round(pos) local upos = _aux.get_under_pos(pos) local yaw = self.object:getyaw() _aux.pickup_item(self, 1.5, function(itemstring) -- pickup droped seed items return minetest.get_item_group(itemstring, "seed") > 0 end) if self.state == state.walk then -- searching plants or spaces local b1, dest1 = _aux.search_surrounding(self, search_lenvec, can_plant) local b2, dest2 = _aux.search_surrounding(self, search_lenvec, can_punch) -- search soil node near if b1 then -- to soil self.state = state.walk_to_soil self.destination = dest1 _aux.change_dir_to(self, dest1) elseif b2 then self.state = state.walk_to_plant self.destination = dest2 _aux.change_dir_to(self, dest2) elseif pos.x == self.preposition.x or pos.z == self.preposition.z then _aux.change_dir(self) end elseif self.state == state.punch then if self.time_count >= max_punch_time then if can_punch(self, self.destination) then local destnode = minetest.get_node(self.destination) minetest.remove_node(self.destination) local inv = minetest.get_inventory{type = "detached", name = self.invname} local stacks = minetest.get_node_drops(destnode.name) for _, stack in ipairs(stacks) do local leftover = inv:add_item("main", stack) minetest.add_item(self.destination, leftover) end end to_walk(self) else self.time_count = self.time_count + 1 end elseif self.state == state.plant then if self.time_count >= max_plant_time then if can_plant(self, self.destination) then local inv = minetest.get_inventory{type = "detached", name = self.invname} local stacks = inv:get_list("main") for idx, stack in ipairs(stacks) do local item_name = stack:get_name() if minetest.get_item_group(item_name, "seed") > 0 then minetest.add_node(self.destination, {name = item_name, param2 = 1}) stack:take_item(1) inv:set_stack("main", idx, stack) break end end end to_walk(self) else self.time_count = self.time_count + 1 end elseif self.state == state.walk_to_soil then if vector.distance(pos, self.destination) < 1.5 then -- to plant state local destnode = minetest.get_node(self.destination) if (can_plant(self, self.destination)) then self.state = state.plant self.object:set_animation(maidroid.animations.mine, 15, 0) self.object:setvelocity{x = 0, y = 0, z = 0} else to_walk(self) end else if pos.x == self.preposition.x or pos.z == self.preposition.z then to_walk(self) end end elseif self.state == state.walk_to_plant then if vector.distance(pos, self.destination) < 1.5 then local destnode = minetest.get_node(self.destination) if maidroid.util.table_find_value(target_plants_list, destnode.name) then self.state = state.punch self.object:set_animation(maidroid.animations.mine, 15, 0) self.object:setvelocity{x = 0, y = 0, z = 0} else to_walk(self) end else if pos.x == self.preposition.x or pos.z == self.preposition.z then to_walk(self) end end end self.preposition = pos return end })
------------------------------------------------------------ -- Copyright (c) 2016 tacigar -- https://github.com/tacigar/maidroid ------------------------------------------------------------ local _aux = maidroid.modules._aux local state = { walk = 0, punch = 1, plant = 2, walk_to_plant = 3, walk_to_soil = 4, walk_avoid = 5, } local max_punch_time = 20 local max_plant_time = 15 local max_avoid_time = 15 local search_lenvec = {x = 3, y = 0, z = 3} -- find max size of each plants local target_plants_list = {} minetest.after(0, function() local max = {} for name, node in pairs(minetest.registered_nodes) do if minetest.get_item_group(name, "plant") > 0 then local s, i = string.match(name, "(.+)_(%d+)") if max[s] == nil or max[s] < i then max[s] = i end end end for s, i in pairs(max) do table.insert(target_plants_list, s.."_"..i) end end) -- check the maidroid has seed items local function has_seed_item(self) local inv = maidroid._aux.get_maidroid_inventory(self) local stacks = inv:get_list("main") for _, stack in ipairs(stacks) do local item_name = stack:get_name() if minetest.get_item_group(item_name, "seed") > 0 then return true end end return false end -- check can plant plants. local function can_plant(self, pos) local node = minetest.get_node(pos) local upos = _aux.get_under_pos(pos) local unode = minetest.get_node(upos) return node.name == "air" and minetest.get_item_group(unode.name, "wet") > 0 and has_seed_item(self) end -- check can punch plant local function can_punch(self, pos) local node = minetest.get_node(pos) return maidroid.util.table_find_value(target_plants_list, node.name) end -- change state to walk local function to_walk(self) self.state = state.walk self.destination = nil self.object:set_animation(maidroid.animations.walk, 15, 0) self.time_count = 0 _aux.change_dir(self) end local function to_walk_avoid(self) to_walk(self) self.state = state.walk_avoid end maidroid.register_module("maidroid:farming_module", { description = "Maidroid Module : Farming", inventory_image = "maidroid_farming_module.png", initialize = function(self) self.object:set_animation(maidroid.animations.walk, 15, 0) self.object:setacceleration{x = 0, y = -10, z = 0} self.state = state.walk self.preposition = self.object:getpos() self.time_count = 0 self.destination = nil -- for walk_to_* _aux.change_dir(self) end, finalize = function(self) self.state = nil self.preposition = nil self.time_count = nil self.destination = nil self.object:setvelocity{x = 0, y = 0, z = 0} end, on_step = function(self, dtime) local pos = self.object:getpos() local rpos = vector.round(pos) local upos = _aux.get_under_pos(pos) local yaw = self.object:getyaw() _aux.pickup_item(self, 1.5, function(itemstring) -- pickup droped seed items return minetest.get_item_group(itemstring, "seed") > 0 end) if self.state == state.walk then -- searching plants or spaces local b1, dest1 = _aux.search_surrounding(self, search_lenvec, can_plant) local b2, dest2 = _aux.search_surrounding(self, search_lenvec, can_punch) -- search soil node near if b1 then -- to soil self.state = state.walk_to_soil self.destination = dest1 _aux.change_dir_to(self, dest1) elseif b2 then self.state = state.walk_to_plant self.destination = dest2 _aux.change_dir_to(self, dest2) elseif pos.x == self.preposition.x or pos.z == self.preposition.z then _aux.change_dir(self) end elseif self.state == state.punch then if self.time_count >= max_punch_time then if can_punch(self, self.destination) then local destnode = minetest.get_node(self.destination) minetest.remove_node(self.destination) local inv = minetest.get_inventory{type = "detached", name = self.invname} local stacks = minetest.get_node_drops(destnode.name) for _, stack in ipairs(stacks) do local leftover = inv:add_item("main", stack) minetest.add_item(self.destination, leftover) end end to_walk(self) else self.time_count = self.time_count + 1 end elseif self.state == state.plant then if self.time_count >= max_plant_time then if can_plant(self, self.destination) then local inv = minetest.get_inventory{type = "detached", name = self.invname} local stacks = inv:get_list("main") for idx, stack in ipairs(stacks) do local item_name = stack:get_name() if minetest.get_item_group(item_name, "seed") > 0 then minetest.add_node(self.destination, {name = item_name, param2 = 1}) stack:take_item(1) inv:set_stack("main", idx, stack) break end end end to_walk(self) else self.time_count = self.time_count + 1 end elseif self.state == state.walk_to_soil then if vector.distance(pos, self.destination) < 1.5 then -- to plant state local destnode = minetest.get_node(self.destination) if (can_plant(self, self.destination)) then self.state = state.plant self.object:set_animation(maidroid.animations.mine, 15, 0) self.object:setvelocity{x = 0, y = 0, z = 0} else to_walk(self) end else if pos.x == self.preposition.x or pos.z == self.preposition.z then to_walk_avoid(self) end end elseif self.state == state.walk_to_plant then if vector.distance(pos, self.destination) < 1.5 then local destnode = minetest.get_node(self.destination) if maidroid.util.table_find_value(target_plants_list, destnode.name) then self.state = state.punch self.object:set_animation(maidroid.animations.mine, 15, 0) self.object:setvelocity{x = 0, y = 0, z = 0} else to_walk(self) end else if pos.x == self.preposition.x or pos.z == self.preposition.z then to_walk_avoid(self) end end elseif self.state == state.walk_avoid then if self.time_count > max_avoid_time then self.state = state.walk self.time_count = 0 else self.time_count = self.time_count + 1 end end self.preposition = pos return end })
Fix farming module
Fix farming module
Lua
lgpl-2.1
tacigar/maidroid
405434e0f7bee0a157cb05c223afd1d4cf7f7cb8
game/scripts/vscripts/modules/SimpleAI/SimpleAI.lua
game/scripts/vscripts/modules/SimpleAI/SimpleAI.lua
AI_THINK_INTERVAL = 0.3 AI_STATE_IDLE = 0 AI_STATE_AGGRESSIVE = 1 AI_STATE_RETURNING = 2 AI_STATE_CASTING = 3 AI_STATE_ORDER = 4 ModuleLinkLuaModifier(..., "modifier_simple_ai") SimpleAI = {} SimpleAI.__index = SimpleAI function SimpleAI:new( unit, profile, params ) local ai = {} setmetatable( ai, SimpleAI ) ai.unit = unit ai.ThinkEnabled = true ai.Thinkers = {} ai.state = AI_STATE_IDLE ai.profile = profile if profile == "boss" then ai.stateThinks = { [AI_STATE_IDLE] = 'IdleThink', [AI_STATE_AGGRESSIVE] = 'AggressiveThink', [AI_STATE_RETURNING] = 'ReturningThink', [AI_STATE_CASTING] = 'CastingThink', [AI_STATE_ORDER] = 'OrderThink', } ai.spawnPos = params.spawnPos or unit:GetAbsOrigin() ai.aggroRange = params.aggroRange or unit:GetAcquisitionRange() ai.leashRange = params.leashRange or 1000 ai.abilityCastCallback = params.abilityCastCallback end if profile == "tower" then ai.stateThinks = { [AI_STATE_IDLE] = 'IdleThink', [AI_STATE_AGGRESSIVE] = 'AggressiveThink', [AI_STATE_CASTING] = 'CastingThink', [AI_STATE_ORDER] = 'OrderThink', } ai.spawnPos = params.spawnPos or unit:GetAbsOrigin() ai.aggroRange = unit:GetAttackRange() ai.leashRange = ai.aggroRange ai.abilityCastCallback = params.abilityCastCallback end unit:AddNewModifier(unit, nil, "modifier_simple_ai", {}) Timers:CreateTimer( ai.GlobalThink, ai ) if unit.ai then unit.ai:Destroy() end unit.ai = ai return ai end function SimpleAI:SwitchState(newState) if self.stateThinks[newState] then self.state = newState if newState == AI_STATE_RETURNING then self.unit:MoveToPosition(self.spawnPos) end else self:SwitchState(AI_STATE_IDLE) end end function SimpleAI:GlobalThink() if self.MarkedForDestroy or not self.unit:IsAlive() then return end if self.ThinkEnabled then Dynamic_Wrap(SimpleAI, self.stateThinks[ self.state ])(self) if self.abilityCastCallback and self.state ~= AI_STATE_CASTING then self.abilityCastCallback(self) end end for k,_ in pairs(self.Thinkers) do if not k() then self.Thinkers[k] = nil end end return AI_THINK_INTERVAL end --Boss Thinkers function SimpleAI:IdleThink() --local units = Dynamic_Wrap(SimpleAI, "FindUnitsNearby")(self, self.aggroRange, false, true) local units = self:FindUnitsNearby(self.aggroRange, false, true, nil, DOTA_UNIT_TARGET_FLAG_NO_INVIS) if #units > 0 then self.unit:MoveToTargetToAttack( units[1] ) self.aggroTarget = units[1] self:SwitchState(AI_STATE_AGGRESSIVE) return end end function SimpleAI:AggressiveThink() local aggroTarget = self.aggroTarget if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() > self.leashRange or not IsValidEntity(aggroTarget) or not aggroTarget:IsAlive() or (aggroTarget.IsInvisible and aggroTarget:IsInvisible()) or (aggroTarget.IsInvulnerable and aggroTarget:IsInvulnerable()) or (aggroTarget.IsAttackImmune and aggroTarget:IsAttackImmune()) or (self.profile == "tower" and (self.spawnPos - aggroTarget:GetAbsOrigin()):Length2D() > self.leashRange) then self:SwitchState(AI_STATE_RETURNING) return else -- Pretty dirty hack to forecefully update target self.unit:MoveToTargetToAttack(self.unit) self.unit:MoveToTargetToAttack(self.aggroTarget) end end function SimpleAI:ReturningThink() self.unit:MoveToPosition(self.spawnPos) -- If movement order was interrupted for some reason (Force Staff) if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() < 10 then self:SwitchState(AI_STATE_IDLE) return end end function SimpleAI:CastingThink() end function SimpleAI:OrderThink() local orderEnd = false if self.ExecutingOrder.OrderType == DOTA_UNIT_ORDER_MOVE_TO_POSITION then if (self.ExecutingOrder.Position - self.unit:GetAbsOrigin()):Length2D() < 10 then orderEnd = true end end if orderEnd then self.ExecutingOrder = nil self:SwitchState(AI_STATE_RETURNING) end end --Utils function SimpleAI:OnTakeDamage(attacker) if (self.state == AI_STATE_IDLE or self.state == AI_STATE_RETURNING) and (self.spawnPos - attacker:GetAbsOrigin()):Length2D() < self.leashRange then self.unit:MoveToTargetToAttack( attacker ) self.aggroTarget = attacker self:SwitchState(AI_STATE_AGGRESSIVE) end end function SimpleAI:AddThink(func) self.Thinkers[func] = true end --Legacy function SimpleAI:FindUnitsNearby(radius, bAllies, bEnemies, targettype, flags) local teamfilter = DOTA_UNIT_TARGET_TEAM_NONE if bAllies then teamfilter = teamfilter + DOTA_UNIT_TARGET_TEAM_FRIENDLY end if bEnemies then teamfilter = teamfilter + DOTA_UNIT_TARGET_TEAM_ENEMY end local units = FindUnitsInRadius(self.unit:GetTeam(), self.unit:GetAbsOrigin(), nil, radius, teamfilter or DOTA_UNIT_TARGET_TEAM_ENEMY, targettype or DOTA_UNIT_TARGET_ALL, flags or DOTA_UNIT_TARGET_FLAG_NONE, FIND_CLOSEST, false) return units end function SimpleAI:FindUnitsNearbyForAbility(ability) local selfAbs = self.unit:GetAbsOrigin() return FindUnitsInRadius(self.unit:GetTeam(), selfAbs, nil, ability:GetCastRange(selfAbs, nil), ability:GetAbilityTargetTeam(), ability:GetAbilityTargetType(), ability:GetAbilityTargetFlags(), FIND_CLOSEST, false) end function SimpleAI:UseAbility(ability, target) if self.state ~= AI_STATE_CASTING and ability:IsFullyCastable() then self:SwitchState(AI_STATE_CASTING) if ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_NO_TARGET) then self.unit:CastAbilityNoTarget(ability, -1) elseif ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_UNIT_TARGET) then self.unit:CastAbilityOnTarget(target, ability, -1) elseif ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_POINT) then self.unit:CastAbilityOnPosition(target, ability, -1) end local endtime = GameRules:GetGameTime() + ability:GetCastPoint() + 0.1 self:AddThink(function() if GameRules:GetGameTime() >= endtime and not self.unit:IsChanneling() then self:SwitchState(AI_STATE_RETURNING) return false end return true end) end end function SimpleAI:ExecuteOrder(order) self.ExecutingOrder = order ExecuteOrderFromTable(order) self:SwitchState(AI_STATE_ORDER) end function SimpleAI:SetThinkEnabled(state) self.ThinkEnabled = state end function SimpleAI:AreUnitsInLineAround(width, length, teamFilter, typeFilter, flagFilter, min_unit_count) local line_count = 360/width for i = 1, line_count do local newLoc = self.unit:GetAbsOrigin() + (RotatePosition(Vector(0,0,0),QAngle(0,i*line_count,0),Vector(1,1,0))):Normalized() * speed local units = FindUnitsInLine(self.unit:GetTeam(), self.unit:GetAbsOrigin(), newLoc, nil, width, teamFilter or DOTA_UNIT_TARGET_TEAM_ENEMY, typeFilter or DOTA_UNIT_TARGET_ALL, flagFilter or DOTA_UNIT_TARGET_FLAG_NONE) if not min_unit_count or #units > min_unit_count then return units end end end function SimpleAI:Destroy() self.MarkedForDestroy = true end
AI_THINK_INTERVAL = 0.3 AI_STATE_IDLE = 0 AI_STATE_AGGRESSIVE = 1 AI_STATE_RETURNING = 2 AI_STATE_CASTING = 3 AI_STATE_ORDER = 4 ModuleLinkLuaModifier(..., "modifier_simple_ai") SimpleAI = {} SimpleAI.__index = SimpleAI function SimpleAI:new( unit, profile, params ) local ai = {} setmetatable( ai, SimpleAI ) ai.unit = unit ai.ThinkEnabled = true ai.Thinkers = {} ai.state = AI_STATE_IDLE ai.profile = profile if profile == "boss" then ai.stateThinks = { [AI_STATE_IDLE] = 'IdleThink', [AI_STATE_AGGRESSIVE] = 'AggressiveThink', [AI_STATE_RETURNING] = 'ReturningThink', [AI_STATE_CASTING] = 'CastingThink', [AI_STATE_ORDER] = 'OrderThink', } ai.spawnPos = params.spawnPos or unit:GetAbsOrigin() ai.aggroRange = params.aggroRange or unit:GetAcquisitionRange() ai.leashRange = params.leashRange or 1000 ai.abilityCastCallback = params.abilityCastCallback end if profile == "tower" then ai.stateThinks = { [AI_STATE_IDLE] = 'IdleThink', [AI_STATE_AGGRESSIVE] = 'AggressiveThink', [AI_STATE_CASTING] = 'CastingThink', [AI_STATE_ORDER] = 'OrderThink', } ai.spawnPos = params.spawnPos or unit:GetAbsOrigin() ai.aggroRange = unit:GetAttackRange() ai.leashRange = ai.aggroRange ai.abilityCastCallback = params.abilityCastCallback end unit:AddNewModifier(unit, nil, "modifier_simple_ai", {}) Timers:CreateTimer( ai.GlobalThink, ai ) if unit.ai then unit.ai:Destroy() end unit.ai = ai return ai end function SimpleAI:SwitchState(newState) if self.stateThinks[newState] then self.state = newState if newState == AI_STATE_RETURNING then self.unit:MoveToPosition(self.spawnPos) end else self:SwitchState(AI_STATE_IDLE) end end function SimpleAI:GlobalThink() if self.MarkedForDestroy or not self.unit:IsAlive() then return end if self.ThinkEnabled then Dynamic_Wrap(SimpleAI, self.stateThinks[ self.state ])(self) if self.abilityCastCallback and self.state ~= AI_STATE_CASTING then self.abilityCastCallback(self) end end for k,_ in pairs(self.Thinkers) do if not k() then self.Thinkers[k] = nil end end return AI_THINK_INTERVAL end --Boss Thinkers function SimpleAI:IdleThink() --local units = Dynamic_Wrap(SimpleAI, "FindUnitsNearby")(self, self.aggroRange, false, true) local units = self:FindUnitsNearby(self.aggroRange, false, true, nil, DOTA_UNIT_TARGET_FLAG_NO_INVIS) if #units > 0 then self.unit:MoveToTargetToAttack( units[1] ) self.aggroTarget = units[1] self:SwitchState(AI_STATE_AGGRESSIVE) return end if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() > 10 then self:SwitchState(AI_STATE_RETURNING) return end end function SimpleAI:AggressiveThink() local aggroTarget = self.aggroTarget if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() > self.leashRange or not IsValidEntity(aggroTarget) or not aggroTarget:IsAlive() or (aggroTarget.IsInvisible and aggroTarget:IsInvisible()) or (aggroTarget.IsInvulnerable and aggroTarget:IsInvulnerable()) or (aggroTarget.IsAttackImmune and aggroTarget:IsAttackImmune()) or (self.profile == "tower" and (self.spawnPos - aggroTarget:GetAbsOrigin()):Length2D() > self.leashRange) then self:SwitchState(AI_STATE_RETURNING) return else -- Pretty dirty hack to forecefully update target self.unit:MoveToTargetToAttack(self.unit) self.unit:MoveToTargetToAttack(self.aggroTarget) end end function SimpleAI:ReturningThink() self.unit:MoveToPosition(self.spawnPos) -- If movement order was interrupted for some reason (Force Staff) if (self.spawnPos - self.unit:GetAbsOrigin()):Length2D() < 10 then self:SwitchState(AI_STATE_IDLE) return end end function SimpleAI:CastingThink() end function SimpleAI:OrderThink() local orderEnd = false if self.ExecutingOrder.OrderType == DOTA_UNIT_ORDER_MOVE_TO_POSITION then if (self.ExecutingOrder.Position - self.unit:GetAbsOrigin()):Length2D() < 10 then orderEnd = true end end if orderEnd then self.ExecutingOrder = nil self:SwitchState(AI_STATE_RETURNING) end end --Utils function SimpleAI:OnTakeDamage(attacker) if (self.state == AI_STATE_IDLE or self.state == AI_STATE_RETURNING) and (self.spawnPos - attacker:GetAbsOrigin()):Length2D() < self.leashRange then self.unit:MoveToTargetToAttack( attacker ) self.aggroTarget = attacker self:SwitchState(AI_STATE_AGGRESSIVE) end end function SimpleAI:AddThink(func) self.Thinkers[func] = true end --Legacy function SimpleAI:FindUnitsNearby(radius, bAllies, bEnemies, targettype, flags) local teamfilter = DOTA_UNIT_TARGET_TEAM_NONE if bAllies then teamfilter = teamfilter + DOTA_UNIT_TARGET_TEAM_FRIENDLY end if bEnemies then teamfilter = teamfilter + DOTA_UNIT_TARGET_TEAM_ENEMY end local units = FindUnitsInRadius(self.unit:GetTeam(), self.unit:GetAbsOrigin(), nil, radius, teamfilter or DOTA_UNIT_TARGET_TEAM_ENEMY, targettype or DOTA_UNIT_TARGET_ALL, flags or DOTA_UNIT_TARGET_FLAG_NONE, FIND_CLOSEST, false) return units end function SimpleAI:FindUnitsNearbyForAbility(ability) local selfAbs = self.unit:GetAbsOrigin() return FindUnitsInRadius(self.unit:GetTeam(), selfAbs, nil, ability:GetCastRange(selfAbs, nil), ability:GetAbilityTargetTeam(), ability:GetAbilityTargetType(), ability:GetAbilityTargetFlags(), FIND_CLOSEST, false) end function SimpleAI:UseAbility(ability, target) if self.state ~= AI_STATE_CASTING and ability:IsFullyCastable() then self:SwitchState(AI_STATE_CASTING) if ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_NO_TARGET) then self.unit:CastAbilityNoTarget(ability, -1) elseif ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_UNIT_TARGET) then self.unit:CastAbilityOnTarget(target, ability, -1) elseif ability:HasBehavior(DOTA_ABILITY_BEHAVIOR_POINT) then self.unit:CastAbilityOnPosition(target, ability, -1) end local endtime = GameRules:GetGameTime() + ability:GetCastPoint() + 0.1 self:AddThink(function() if GameRules:GetGameTime() >= endtime and not self.unit:IsChanneling() then self:SwitchState(AI_STATE_RETURNING) return false end return true end) end end function SimpleAI:ExecuteOrder(order) self.ExecutingOrder = order ExecuteOrderFromTable(order) self:SwitchState(AI_STATE_ORDER) end function SimpleAI:SetThinkEnabled(state) self.ThinkEnabled = state end function SimpleAI:AreUnitsInLineAround(width, length, teamFilter, typeFilter, flagFilter, min_unit_count) local line_count = 360/width for i = 1, line_count do local newLoc = self.unit:GetAbsOrigin() + (RotatePosition(Vector(0,0,0),QAngle(0,i*line_count,0),Vector(1,1,0))):Normalized() * speed local units = FindUnitsInLine(self.unit:GetTeam(), self.unit:GetAbsOrigin(), newLoc, nil, width, teamFilter or DOTA_UNIT_TARGET_TEAM_ENEMY, typeFilter or DOTA_UNIT_TARGET_ALL, flagFilter or DOTA_UNIT_TARGET_FLAG_NONE) if not min_unit_count or #units > min_unit_count then return units end end end function SimpleAI:Destroy() self.MarkedForDestroy = true end
fix(SimpleAI): abilities which are not dealing damage not triggering boss from idle state
fix(SimpleAI): abilities which are not dealing damage not triggering boss from idle state Fixes #32.
Lua
mit
ark120202/aabs
741e4e3b249eb9324209727dc7f8393ee7b06d9b
nova/object.lua
nova/object.lua
--- LuaNova's object module. -- This module is used to create objects from prototypes, through the use of -- the nova.object:new() method. It also defines a reference to a nil object, -- which may be acquired with nova.object.nilref(). module ("nova.object", package.seeall) do --- Local instance of the "nil object". local nilref_ = {} --- Returns the representation of the nil object. -- @return An object reference to the nil object. function nilref() return nilref_ end -- Recursive initialization. local function init (obj, super) if not super then return end init(obj, super:__super()) if super.__init then local init_type = type(super.__init) if init_type == "function" then super.__init(obj) elseif init_type == "table" then for k,v in pairs(super.__init) do obj[k] = clone(v) end end end end --- Creates a new object from a prototype. -- If the self object has an <code>__init</code> field as a function, it will -- be applied to the new object. If it has an <code>__init</code> field as a -- table, its contents will be cloned into the new object. -- @param prototype A table containing the object's methods and the default -- values of its attributes. function nova.object:new (prototype) prototype = prototype or {} self.__index = rawget(self, "__index") or self setmetatable(prototype, self) init(prototype, self) return prototype; end --- Clones an object. -- @return A clone of this object. function nova.object:clone () if type(self) ~= "table" then return self end print "cloning..." table.foreach(self, print) local cloned = {} for k,v in pairs(self) do cloned[k] = clone(v) end local super = __super(self) return super and super.new and super:new(cloned) or cloned end --- Returns the super class of an object. -- @return The super class of an object. function nova.object:__super () return self ~= nova.object and getmetatable(self) or nil end --- Makes a class module inherit from a table. -- This function is to be used only when declaring modules, like this: -- <p><code> -- module ("my.module", nova.object.inherit(some_table)) -- </code></p> -- This essentially makes the module inherit everything indexable from the -- given table. It also turns the module into an object. -- @param super A table from which the module will inherit. function inherit (super) return function (class) class.__index = super nova.object:new(class) end end end
--- LuaNova's object module. -- This module is used to create objects from prototypes, through the use of -- the nova.object:new() method. It also defines a reference to a nil object, -- which may be acquired with nova.object.nilref(). module ("nova.object", package.seeall) do --- Local instance of the "nil object". local nilref_ = {} --- Returns the representation of the nil object. -- @return An object reference to the nil object. function nilref() return nilref_ end -- Recursive initialization. local function init (obj, super) if not super then return end init(obj, super:__super()) if super.__init then local init_type = type(super.__init) if init_type == "function" then super.__init(obj) elseif init_type == "table" then for k,v in pairs(super.__init) do if not obj[k] then obj[k] = clone(v) end end end end end --- Creates a new object from a prototype. -- If the self object has an <code>__init</code> field as a function, it will -- be applied to the new object. If it has an <code>__init</code> field as a -- table, its contents will be cloned into the new object. -- @param prototype A table containing the object's methods and the default -- values of its attributes. function nova.object:new (prototype) prototype = prototype or {} self.__index = rawget(self, "__index") or self setmetatable(prototype, self) init(prototype, self) return prototype; end --- Clones an object. -- @return A clone of this object. function nova.object:clone () if type(self) ~= "table" then return self end print "cloning..." table.foreach(self, print) local cloned = {} for k,v in pairs(self) do cloned[k] = clone(v) end local super = __super(self) return super and super.new and super:new(cloned) or cloned end --- Returns the super class of an object. -- @return The super class of an object. function nova.object:__super () return self ~= nova.object and getmetatable(self) or nil end --- Makes a class module inherit from a table. -- This function is to be used only when declaring modules, like this: -- <p><code> -- module ("my.module", nova.object.inherit(some_table)) -- </code></p> -- This essentially makes the module inherit everything indexable from the -- given table. It also turns the module into an object. -- @param super A table from which the module will inherit. function inherit (super) return function (class) class.__index = super nova.object:new(class) end end end
Init overwriting prototype fields fixed.
Init overwriting prototype fields fixed.
Lua
mit
Kazuo256/luxproject
c96aa183961beccb743757aaa1e672ba9996b37b
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() -------------------- View -------------------- f = SimpleForm("siitwizward", "4over6-Assistent", "Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.") mode = f:field(ListValue, "mode", "Betriebsmodus") mode:value("gateway", "Gateway") mode:value("client", "Client") dev = f:field(ListValue, "device", "WLAN-Gerät") uci:foreach("wireless", "wifi-device", function(section) dev:value(section[".name"]) end) lanip = f:field(Value, "ipaddr", "LAN IP Adresse") lanip.value = "127.23.1.1" lanmsk = f:field(Value, "netmask", "LAN Netzmaske") lanmsk.value = "255.255.0.0" -------------------- Control -------------------- LL_PREFIX = luci.ip.IPv6("fe80::/64") -- -- find link-local address -- function find_ll() for _, r in ipairs(luci.sys.net.routes6()) do if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then return r.dest:sub(LL_PREFIX) end end return luci.ip.IPv6("::") end function f.handle(self, state, data) if state == FORM_VALID then luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes")) return false elseif state == FORM_INVALID then self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen." end return true end function mode.write(self, section, value) -- -- Configure wifi device -- local wifi_device = dev:formvalue(section) local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net" local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be" local wifi_channel = uci:get("siit", "wifi", "channel") or "1" -- nuke old device definition uci:delete_all("wireless", "wifi-iface", function(s) return s.device == wifi_device end ) uci:delete_all("network", "interface", function(s) return s['.name'] == wifi_device end ) -- create wifi device definition uci:tset("wireless", wifi_device, { disabled = 0, channel = wifi_channel, -- txantenna = 1, -- rxantenna = 1, -- diversity = 0 }) uci:section("wireless", "wifi-iface", nil, { encryption = "none", mode = "adhoc", network = wifi_device, device = wifi_device, ssid = wifi_essid, bssid = wifi_bssid, }) -- -- Determine defaults -- local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::" local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000" -- Find wifi interface local device = dev:formvalue(section) -- -- Generate ULA -- local ula = luci.ip.IPv6("::/64") for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do ula = ula:add(luci.ip.IPv6(prefix)) end ula = ula:add(find_ll()) -- -- Gateway mode -- -- * wan port is dhcp, lan port is 172.23.1.1/24 -- * siit0 gets a dummy address: 169.254.42.42 -- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64 -- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation. -- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space. -- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger. if value == "gateway" then uci:set("network", "wan", "mtu", 1400) -- use full siit subnet siit_route = luci.ip.IPv6(siit_prefix .. "/96") -- -- Client mode -- -- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0. -- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation. -- * same route as HNA6 announcement to catch the traffic out of the mesh. -- * Also, MTU on LAN reduced to 1400. else -- lan interface local lan_net = luci.ip.IPv4( lanip:formvalue(section) or "192.168.1.1", lanmsk:formvalue(section) or "255.255.255.0" ) uci:tset("network", "lan", { mtu = 1400, ipaddr = lan_net:host():string(), netmask = lan_net:mask():string() }) -- derive siit subnet from lan config siit_route = luci.ip.IPv6( siit_prefix .. "/" .. (96 + lan_net:prefix()) ):add(lan_net[2]) end -- siit0 interface uci:delete_all("network", "interface", function(s) return ( s.ifname == "siit0" ) end) uci:section("network", "interface", "siit0", { ifname = "siit0", proto = "static", ipaddr = "169.254.42.42", netmask = "255.255.255.0" }) -- siit0 route uci:delete_all("network", "route6", function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end) uci:section("network", "route6", nil, { interface = "siit0", target = siit_route:string() }) -- create wifi network interface uci:section("network", "interface", wifi_device, { proto = "static", mtu = 1400, ip6addr = ula:string() }) -- nuke old olsrd interfaces uci:delete_all("olsrd", "Interface", function(s) return s.interface == wifi_device end) -- configure olsrd interface uci:foreach("olsrd", "olsrd", function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end) uci:section("olsrd", "Interface", nil, { ignore = 0, interface = wifi_device, Ip6AddrType = "global" }) -- hna6 uci:delete_all("olsrd", "Hna6", function(s) if s.netaddr and s.prefix then return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix)) end end) uci:section("olsrd", "Hna6", nil, { netaddr = siit_route:host():string(), prefix = siit_route:prefix() }) uci:save("wireless") uci:save("network") uci:save("olsrd") end return f
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() -------------------- View -------------------- f = SimpleForm("siitwizward", "4over6-Assistent", "Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.") mode = f:field(ListValue, "mode", "Betriebsmodus") mode:value("gateway", "Gateway") mode:value("client", "Client") dev = f:field(ListValue, "device", "WLAN-Gerät") uci:foreach("wireless", "wifi-device", function(section) dev:value(section[".name"]) end) lanip = f:field(Value, "ipaddr", "LAN IP Adresse") lanip.value = "172.23.1.1" lanip:depends("mode", "client") lanmsk = f:field(Value, "netmask", "LAN Netzmaske") lanmsk.value = "255.255.0.0" lanmsk:depends("mode", "client") -------------------- Control -------------------- LL_PREFIX = luci.ip.IPv6("fe80::/64") -- -- find link-local address -- function find_ll() for _, r in ipairs(luci.sys.net.routes6()) do if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then return r.dest:sub(LL_PREFIX) end end return luci.ip.IPv6("::") end function f.handle(self, state, data) if state == FORM_VALID then luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes")) return false elseif state == FORM_INVALID then self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen." end return true end function mode.write(self, section, value) -- -- Configure wifi device -- local wifi_device = dev:formvalue(section) local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net" local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be" local wifi_channel = uci:get("siit", "wifi", "channel") or "1" -- nuke old device definition uci:delete_all("wireless", "wifi-iface", function(s) return s.device == wifi_device end ) uci:delete_all("network", "interface", function(s) return s['.name'] == wifi_device end ) -- create wifi device definition uci:tset("wireless", wifi_device, { disabled = 0, channel = wifi_channel, -- txantenna = 1, -- rxantenna = 1, -- diversity = 0 }) uci:section("wireless", "wifi-iface", nil, { encryption = "none", mode = "adhoc", network = wifi_device, device = wifi_device, ssid = wifi_essid, bssid = wifi_bssid, }) -- -- Determine defaults -- local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::" local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000" -- Find wifi interface local device = dev:formvalue(section) -- -- Generate ULA -- local ula = luci.ip.IPv6("::/64") for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do ula = ula:add(luci.ip.IPv6(prefix)) end ula = ula:add(find_ll()) -- -- Gateway mode -- -- * wan port is dhcp, lan port is 172.23.1.1/24 -- * siit0 gets a dummy address: 169.254.42.42 -- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64 -- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation. -- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space. -- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger. if value == "gateway" then uci:set("network", "wan", "mtu", 1400) -- use full siit subnet siit_route = luci.ip.IPv6(siit_prefix .. "/96") -- -- Client mode -- -- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0. -- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation. -- * same route as HNA6 announcement to catch the traffic out of the mesh. -- * Also, MTU on LAN reduced to 1400. else -- lan interface local lan_net = luci.ip.IPv4( lanip:formvalue(section) or "192.168.1.1", lanmsk:formvalue(section) or "255.255.255.0" ) uci:tset("network", "lan", { mtu = 1400, ipaddr = lan_net:host():string(), netmask = lan_net:mask():string() }) -- derive siit subnet from lan config siit_route = luci.ip.IPv6( siit_prefix .. "/" .. (96 + lan_net:prefix()) ):add(lan_net[2]) end -- siit0 interface uci:delete_all("network", "interface", function(s) return ( s.ifname == "siit0" ) end) uci:section("network", "interface", "siit0", { ifname = "siit0", proto = "static", ipaddr = "169.254.42.42", netmask = "255.255.255.0" }) -- siit0 route uci:delete_all("network", "route6", function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end) uci:section("network", "route6", nil, { interface = "siit0", target = siit_route:string() }) -- create wifi network interface uci:section("network", "interface", wifi_device, { proto = "static", mtu = 1400, ip6addr = ula:string() }) -- nuke old olsrd interfaces uci:delete_all("olsrd", "Interface", function(s) return s.interface == wifi_device end) -- configure olsrd interface uci:foreach("olsrd", "olsrd", function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end) uci:section("olsrd", "Interface", nil, { ignore = 0, interface = wifi_device, Ip6AddrType = "global" }) -- hna6 uci:delete_all("olsrd", "Hna6", function(s) if s.netaddr and s.prefix then return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix)) end end) uci:section("olsrd", "Hna6", nil, { netaddr = siit_route:host():string(), prefix = siit_route:prefix() }) uci:save("wireless") uci:save("network") uci:save("olsrd") end return f
applications/siitwizard: - fix default lan ip - make ip and netmask depend on client mode
applications/siitwizard: - fix default lan ip - make ip and netmask depend on client mode git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@3923 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
414df0e01c4c81ba138c52e830f3164467b3da8f
mock/tools/Stat.lua
mock/tools/Stat.lua
module 'mock' CLASS: Stat () :MODEL{} function Stat:__init( data ) self.values = {} self.changeListeners = {} self.changeSignals = {} self.allowNotifyChanges = true self.globalChangeSignal = false self.globalChangeListenerList = {} self.changeListeners[ '*' ] = self.globalChangeListenerList if data then self:update( data ) end local accessorMT = { __index = function( t, k ) return self:get( k ) end, __newindex = function( t, k, v ) return self:set( k, v ) end } self.accessor = setmetatable( {}, accessorMT ) end function Stat:disableNotifyChanges() self.allowNotifyChanges = true end function Stat:enableNotifyChanges( enabled ) self.allowNotifyChanges = enabled ~= false end function Stat:getAccessor() return self.accessor end function Stat:getValues() return self.values end function Stat:update( data ) if data then local t = self.values for k, v in pairs( data ) do t[ k ] = v end end end function Stat:clear() self.values = {} end function Stat:get( n, default ) local values = self.values local v = values[n] return v == nil and default or v end function Stat:add( n, v ) local values = self.values return self:set( n, ( values[n] or 0 ) + ( v or 1 ) ) end function Stat:sub( n, v ) return self:add( n, -v ) end function Stat:setRaw( n, v ) self.values[n] = v end function Stat:set( n, v, notify ) local values = self.values local v0 = values[n] if v0 == v then return end values[n] = v if not self.allowNotifyChanges then return end for func in pairs( self.globalChangeListenerList ) do func( n, v, v0 ) end local changeListenerList = self.changeListeners[ n ] if changeListenerList then for func in pairs( changeListenerList ) do func( n, v, v0 ) end end local sig = self.changeSignals[ n ] if sig then emitSignal( sig, n , v, v0 ) end if self.globalChangeSignal then emitSignal( self.globalChangeSignal, n, v, v0 ) end end function Stat:setMax( n, v ) if self:isMax( n, v ) then return self:set( n, v ) end end function Stat:setMin( n, v ) if self:isMin( n, v ) then return self:set( n, v ) end end function Stat:isMax( n, v ) local values = self.values local v0 = values[n] return not v0 or v > v0 end function Stat:isMin( n, v ) local values = self.values local v0 = values[n] return not v0 or v < v0 end function Stat:addChangeListener( key, func ) local l = self.changeListeners[ key ] if not l then l = {} self.changeListeners[ key ] = l end l[ func ] = true end function Stat:removeChangeListener( a, b ) local key, func if a and b then key, func = a, b local l = self.changeListeners[ key ] if not l then return end l[ func ] = nil elseif type( a ) == 'function' then for _, l in pairs( self.changeListeners ) do l[ a ] = nil end end end function Stat:setGlobalChangeSignal( sigName ) self.globalChangeSignal = sigName end function Stat:setChangeSignal( key, sigName ) if self.changeSignals[ key ] and sigName then _warn( 'duplicated change singal for stat key:', key ) end self.changeSignals[ key ] = sigName end function Stat:setChangeSignalList( t ) for i, entry in ipairs( t ) do local key, sig = unpack( entry ) self:setChangeSignal( key, sig ) end end function Stat:serialize() return MOAIJsonParser.decode( MOAIJsonParser.encode( self.values ) ) end function Stat:deserialize( values ) self.values = values end
module 'mock' CLASS: Stat () :MODEL{} function Stat:__init( data ) self.values = {} self.changeListeners = {} self.changeSignals = {} self.allowNotifyChanges = true self.globalChangeSignal = false self.globalChangeListenerList = {} self.changeListeners[ '*' ] = self.globalChangeListenerList if data then self:update( data ) end local accessorMT = { __index = function( t, k ) return self:get( k ) end, __newindex = function( t, k, v ) return self:set( k, v ) end } self.accessor = setmetatable( {}, accessorMT ) end function Stat:disableNotifyChanges() self.allowNotifyChanges = true end function Stat:enableNotifyChanges( enabled ) self.allowNotifyChanges = enabled ~= false end function Stat:getAccessor() return self.accessor end function Stat:getValues() return self.values end function Stat:update( data ) if data then local t = self.values for k, v in pairs( data ) do t[ k ] = v end end end function Stat:clear() self.values = {} end function Stat:get( n, default ) local values = self.values local v = values[n] return v == nil and default or v end function Stat:add( n, v ) local values = self.values return self:set( n, ( values[n] or 0 ) + ( v or 1 ) ) end function Stat:sub( n, v ) return self:add( n, -v ) end function Stat:setRaw( n, v ) self.values[n] = v end function Stat:set( n, v, notify ) local values = self.values local v0 = values[n] if v0 == v then return end values[n] = v if not self.allowNotifyChanges then return end for func in pairs( self.globalChangeListenerList ) do func( n, v, v0 ) end local changeListenerList = self.changeListeners[ n ] if changeListenerList then for func in pairs( changeListenerList ) do func( n, v, v0 ) end end local sig = self.changeSignals[ n ] if sig then emitSignal( sig, n , v, v0 ) end if self.globalChangeSignal then emitSignal( self.globalChangeSignal, n, v, v0 ) end end function Stat:setMax( n, v ) if self:isMax( n, v ) then return self:set( n, v ) end end function Stat:setMin( n, v ) if self:isMin( n, v ) then return self:set( n, v ) end end function Stat:isMax( n, v ) local values = self.values local v0 = values[n] return not v0 or v > v0 end function Stat:isMin( n, v ) local values = self.values local v0 = values[n] return not v0 or v < v0 end function Stat:addChangeListener( key, func ) local l = self.changeListeners[ key ] if not l then l = {} self.changeListeners[ key ] = l end l[ func ] = true end function Stat:removeChangeListener( a, b ) local key, func if a and b then key, func = a, b local l = self.changeListeners[ key ] if not l then return end l[ func ] = nil elseif type( a ) == 'function' then for _, l in pairs( self.changeListeners ) do l[ a ] = nil end end end function Stat:setGlobalChangeSignal( sigName ) self.globalChangeSignal = sigName end function Stat:setChangeSignal( key, sigName ) if self.changeSignals[ key ] and sigName then _warn( 'duplicated change singal for stat key:', key ) end self.changeSignals[ key ] = sigName end function Stat:setChangeSignalList( t ) for i, entry in ipairs( t ) do local key, sig = unpack( entry ) self:setChangeSignal( key, sig ) end end local function valueTableCopy( t ) MOAIJsonParser.decode( MOAIJsonParser.encode( t ) ) end function Stat:serialize() return valueTableCopy( self.values ) end function Stat:deserialize( values ) self.values = valueTableCopy( values ) end
-fix Stat deserialization
-fix Stat deserialization
Lua
mit
tommo/mock
56742558edb757f3839855b1b73f26f4b87e70ff
UCDworld/c_world.lua
UCDworld/c_world.lua
setBlurLevel(0) setBirdsEnabled(false) --[[function setWaterColour(cmd, r, g, b) if not (r) then outputChatBox("You must enter 3 numbers between 0 and 255") return end setWaterColor(tonumber(r), tonumber(g), tonumber(b)) outputChatBox("You changed the water colour to: "..r..", "..g..", "..b.."") end addCommandHandler("water", setWaterColour) function setWeatherToNumber(cmd, id) if not id then outputChatBox("You must enter a number") return end setWeather(tonumber(id)) outputChatBox("Weather changed to: "..id.."") end addCommandHandler("weather", setWeatherToNumber)]]-- -- Backup --[[ function setClientTime(cmd, newTime) newTime = tonumber(newTime) if not newTime then outputChatBox("Enter a number between 0 and 23") return end if (newTime > 23) or (newTime < 0) then outputChatBox("You must enter a number between 0 and 23.") return end setTime(tonumber(newTime), 0) end addCommandHandler("settime", setClientTime) --]] function setClientTime(cmd, newHr, newMin) newHr, newMin = tonumber(newHr), tonumber(newMin) if (not newHr) then exports.UCDdx:new("You must enter a new time", 255, 0, 0) return false end if (newHr > 24) or (newHr < 0) then exports.UCDdx:new("There's 24 hours in a day...", 255, 0, 0) return false end if (newMin) and (not newHr) then -- This is probably really fucking stupid so idk why it's in here return false end setTime(newHr, newMin) end addCommandHandler("settime", setClientTime) function movePlayerHead() for k, players in ipairs (getElementsByType("player")) do local w, h = guiGetScreenSize() local lookatX, lookatY, lookatZ = getWorldFromScreenPosition(w/2, h/2, 10) setPedLookAt(players, lookatX, lookatY, lookatZ) end end addEventHandler("onClientRender", root, movePlayerHead) -----------------------------------------
setBlurLevel(0) setBirdsEnabled(false) --[[function setWaterColour(cmd, r, g, b) if not (r) then outputChatBox("You must enter 3 numbers between 0 and 255") return end setWaterColor(tonumber(r), tonumber(g), tonumber(b)) outputChatBox("You changed the water colour to: "..r..", "..g..", "..b.."") end addCommandHandler("water", setWaterColour) function setWeatherToNumber(cmd, id) if not id then outputChatBox("You must enter a number") return end setWeather(tonumber(id)) outputChatBox("Weather changed to: "..id.."") end addCommandHandler("weather", setWeatherToNumber)]]-- -- Backup --[[ function setClientTime(cmd, newTime) newTime = tonumber(newTime) if not newTime then outputChatBox("Enter a number between 0 and 23") return end if (newTime > 23) or (newTime < 0) then outputChatBox("You must enter a number between 0 and 23.") return end setTime(tonumber(newTime), 0) end addCommandHandler("settime", setClientTime) --]] function setClientTime(cmd, newHr, newMin) newHr, newMin = tonumber(newHr), tonumber(newMin) if (not newHr) then exports.UCDdx:new("You must enter a new time", 255, 0, 0) return false end if (newHr > 24) or (newHr < 0) then exports.UCDdx:new("There's 24 hours in a day...", 255, 0, 0) return false end if (newMin) and (not newHr) then -- This is probably really fucking stupid so idk why it's in here return false end setTime(newHr, newMin) end addCommandHandler("settime", setClientTime) function movePlayerHead() for _, players in ipairs(Element.getAllByType("player")) do local w, h = guiGetScreenSize() local lookatX, lookatY, lookatZ = getWorldFromScreenPosition(w / 2, h / 2, 10) if (type(lookatX) ~= "number" or type(lookatY) ~= "number" or type(lookatZ) ~= "number") then return end setPedLookAt(players, lookatX, lookatY, lookatZ) end end addEventHandler("onClientRender", root, movePlayerHead) -----------------------------------------
Fixed a debug error
Fixed a debug error
Lua
mit
nokizorque/ucd,nokizorque/ucd
0566dce6819a90832e0f3b5cf6dbc46b9c6f8557
nvim/lua/config.lua
nvim/lua/config.lua
local helper = require('helper') vim.o.background = "dark" -- dark or "light" for light mode vim.g.everforest_background = 'soft' -- vim.cmd([[colorscheme apprentice]]) --vim.cmd([[colorscheme gruvbox-material]]) --vim.g.everforest_better_performance = 1 vim.cmd([[colorscheme everforest]]) -- vim.cmd([[colorscheme gruvbox-material]]) -- vim.cmd([[colorscheme gruvbox]]) -- Copy with: "*y vim.o.clipboard = 'unnamed' -- Autospell check document vim.cmd([[autocmd BufRead,BufNewFile *.adoc setlocal spell]]) vim.cmd([[autocmd BufRead,BufNewFile *.md setlocal spell]]) --[[ Configure completion ]]-- -- LSP config (the mappings used in the default file don't quite work right) helper.map(helper.MODE.NMAP, 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, '<C-n>', '<cmd>lua vim.lsp.buf.goto_prev()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, '<C-p>', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', { noremap = true, silent = true}) vim.cmd([[autocmd BufWritePre *.py lua vim.lsp.buf.formatting_sync(nil, 100)]]) vim.o.completeopt = "menuone,noselect" require'lualine'.setup { options = { theme = 'everforest' } } require'compe'.setup { enabled = true; autocomplete = true; debug = false; min_length = 1; preselect = 'enable'; throttle_time = 80; source_timeout = 200; incomplete_delay = 400; max_abbr_width = 100; max_kind_width = 100; max_menu_width = 100; documentation = false; source = { path = true; buffer = true; calc = true; vsnip = true; nvim_lsp = true; nvim_lua = true; spell = true; tags = true; snippets_nvim = true; treesitter = true; }; } local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local check_back_space = function() local col = vim.fn.col('.') - 1 if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then return true else return false end end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G.tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-n>" elseif vim.fn.call("vsnip#available", {1}) == 1 then return t "<Plug>(vsnip-expand-or-jump)" elseif check_back_space() then return t "<Tab>" else return vim.fn['compe#complete']() end end _G.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-p>" elseif vim.fn.call("vsnip#jumpable", {-1}) == 1 then return t "<Plug>(vsnip-jump-prev)" else -- If <S-Tab> is not working in your terminal, change it to <C-h> return t "<S-Tab>" end end -- Zig require'lspconfig'.zls.setup{} -- Go require'lspconfig'.gopls.setup{} -- Python --require'lspconfig'.pylsp.setup{ } require'lspconfig'.pyright.setup{} -- Bash require'lspconfig'.bashls.setup{} -- SQL require'lspconfig'.sqls.setup{ picker = 'telescope', on_attach = function(client) client.resolved_capabilities.execute_command = true require'sqls'.setup{} end } require('lspkind').init({ })
local helper = require('helper') vim.o.background = "dark" -- dark or "light" for light mode vim.g.everforest_background = 'soft' -- vim.cmd([[colorscheme apprentice]]) --vim.cmd([[colorscheme gruvbox-material]]) --vim.g.everforest_better_performance = 1 vim.cmd([[colorscheme everforest]]) -- vim.cmd([[colorscheme gruvbox-material]]) -- vim.cmd([[colorscheme gruvbox]]) -- Copy with: "*y vim.o.clipboard = 'unnamed' -- Autospell check document vim.cmd([[autocmd BufRead,BufNewFile *.adoc setlocal spell]]) vim.cmd([[autocmd BufRead,BufNewFile *.md setlocal spell]]) --[[ Configure completion ]]-- -- LSP config (the mappings used in the default file don't quite work right) helper.map(helper.MODE.NMAP, 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, '<C-n>', '<cmd>lua vim.lsp.buf.goto_prev()<CR>', { noremap = true, silent = true}) helper.map(helper.MODE.NMAP, '<C-p>', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', { noremap = true, silent = true}) vim.cmd([[autocmd BufWritePre *.py lua vim.lsp.buf.formatting_sync(nil, 100)]]) vim.o.completeopt = "menuone,noselect" require'lualine'.setup { options = { theme = 'everforest' } } vim.g.go_list_type = "quickfix" require'compe'.setup { enabled = true; autocomplete = true; debug = false; min_length = 1; preselect = 'enable'; throttle_time = 80; source_timeout = 200; incomplete_delay = 400; max_abbr_width = 100; max_kind_width = 100; max_menu_width = 100; documentation = false; source = { path = true; buffer = true; calc = true; vsnip = true; nvim_lsp = true; nvim_lua = true; spell = true; tags = true; snippets_nvim = true; treesitter = true; }; } local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local check_back_space = function() local col = vim.fn.col('.') - 1 if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then return true else return false end end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G.tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-n>" elseif vim.fn.call("vsnip#available", {1}) == 1 then return t "<Plug>(vsnip-expand-or-jump)" elseif check_back_space() then return t "<Tab>" else return vim.fn['compe#complete']() end end _G.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-p>" elseif vim.fn.call("vsnip#jumpable", {-1}) == 1 then return t "<Plug>(vsnip-jump-prev)" else -- If <S-Tab> is not working in your terminal, change it to <C-h> return t "<S-Tab>" end end -- Zig require'lspconfig'.zls.setup{} -- Go require'lspconfig'.gopls.setup{} -- Python --require'lspconfig'.pylsp.setup{ } require'lspconfig'.pyright.setup{} -- Bash require'lspconfig'.bashls.setup{} -- SQL require'lspconfig'.sqls.setup{ picker = 'telescope', on_attach = function(client) client.resolved_capabilities.execute_command = true require'sqls'.setup{} end } require('lspkind').init({ })
Try quickfix
Try quickfix
Lua
bsd-2-clause
lateefj/side
9c3450b995e4371b3a9373782184d823d2d3dd5f
src/npge/io/ReadFromBs.lua
src/npge/io/ReadFromBs.lua
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. local function insertFragment( blockname2fragments, name, blockname, text ) local parseId = require 'npge.fragment.parseId' local seqname, start, stop, ori = parseId(name) if not blockname2fragments[blockname] then blockname2fragments[blockname] = {} end local fr_desc = {seqname, start, stop, ori, text} table.insert(blockname2fragments[blockname], fr_desc) return fr_desc end local function readWithReference(bs1) return function(generator) local blockname2fragments = {} local ev = require 'npge.util.extractValue' for name, description, text in generator do local blockname = ev(description, "block") if blockname then insertFragment(blockname2fragments, name, blockname, text) end end return bs1:sequences(), blockname2fragments end end local function isParted(start, stop, ori) local diff = stop - start return diff * ori < 0 end local function getParts(seqname, start, stop, ori, text) local toAtgcn = require 'npge.alignment.toAtgcn' local text = toAtgcn(text) local length = #text local length1, length2 if ori == 1 then length2 = stop + 1 length1 = length - length2 else length1 = start + 1 length2 = length - length1 end local start1 = start local stop1 = start1 + (length1 - 1) * ori local stop2 = stop local start2 = stop2 - (length2 - 1) * ori local text1 = text:sub(1, length1) local text2 = text:sub(length1 + 1) assert(#text1 == length1) assert(#text2 == length2) assert(start1 >= 0) assert(start2 >= 0) return {seqname, start1, stop1, ori, text1}, {seqname, start2, stop2, ori, text2} end local function makeSequence(seqname, parts) local parts2 = {} for _, part in ipairs(parts) do local seqname1, start, stop, ori, text = unpack(part) assert(seqname1 == seqname) if isParted(start, stop, ori) then local part1, part2 = getParts(seqname, start, stop, ori, text) table.insert(parts2, part1) table.insert(parts2, part2) else table.insert(parts2, part) end end table.sort(parts2, function(part1, part2) local seqname1, start1, stop1, ori1 = unpack(part1) local seqname2, start2, stop2, ori2 = unpack(part2) assert(seqname1 == seqname) assert(seqname2 == seqname) assert(not isParted(start1, stop1, ori1)) assert(not isParted(start2, stop2, ori2)) return math.min(start1, stop1) < math.min(start2, stop2) end) local toAtgcn = require 'npge.alignment.toAtgcn' local complement = require 'npge.alignment.complement' local texts = {} local last = -1 for _, part in ipairs(parts2) do local _, start, stop, ori, text = unpack(part) local first = math.min(start, stop) assert(first == last + 1, "The blockset is not a partition") if ori == -1 then text = complement(text) end table.insert(texts, toAtgcn(text)) last = math.max(start, stop) end local text = table.concat(texts) local Sequence = require 'npge.model.Sequence' return Sequence(seqname, text) end local function readWithoutReference(generator) local blockname2fragments = {} local seqname2seq = {} local seqname2parts = {} local ev = require 'npge.util.extractValue' local Sequence = require 'npge.model.Sequence' local parseId = require 'npge.fragment.parseId' for name, description, text in generator do local blockname = ev(description, "block") if blockname then -- fragment local fr_desc = insertFragment(blockname2fragments, name, blockname, text) local seqname = fr_desc[1] -- insertFragment if not seqname2seq[seqname] then if not seqname2parts[seqname] then seqname2parts[seqname] = {} end table.insert(seqname2parts[seqname], fr_desc) end else -- sequence local seq = Sequence(name, text, description) assert(not seqname2seq[name]) seqname2seq[name] = seq -- remove useless records from seqname2parts seqname2parts[name] = nil end end -- create sequences from seqname2parts local unpack = require 'npge.util.unpack' for seqname, parts in pairs(seqname2parts) do assert(not seqname2seq[seqname]) local seq = makeSequence(seqname, parts) seqname2seq[seqname] = seq collectgarbage() -- large text end local sequences = {} for name, seq in pairs(seqname2seq) do table.insert(sequences, seq) end return sequences, blockname2fragments end local function makeBlock(bs1, fr_descs) local alignment = {} local unpack = require 'npge.util.unpack' local Fragment = require 'npge.model.Fragment' for _, fr_desc in ipairs(fr_descs) do local seqname, start, stop, ori, text = unpack(fr_desc) local seq = assert(bs1:sequenceByName(seqname)) local fragment = Fragment(seq, start, stop, ori) table.insert(alignment, {fragment, text}) end local Block = require 'npge.model.Block' return Block(alignment) end return function(lines, blockset_with_sequences) -- lines is iterator (like file:lines()) or string if type(lines) == 'string' then local util = require 'npge.util' lines = util.textToIt(lines) end local fromFasta = require 'npge.util.fromFasta' local f if blockset_with_sequences then f = readWithReference(blockset_with_sequences) else f = readWithoutReference end local sequences, blockname2fragments = f(fromFasta(lines)) local BlockSet = require 'npge.model.BlockSet' local bs1 = BlockSet(sequences, {}) local blocks = {} for blockname, fr_descs in pairs(blockname2fragments) do local Block = require 'npge.model.Block' blocks[blockname] = makeBlock(bs1, fr_descs) end return BlockSet(sequences, blocks) end
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. local function insertFragment( blockname2fragments, name, blockname, text ) local parseId = require 'npge.fragment.parseId' local seqname, start, stop, ori = parseId(name) if not blockname2fragments[blockname] then blockname2fragments[blockname] = {} end local fr_desc = {seqname, start, stop, ori, text} table.insert(blockname2fragments[blockname], fr_desc) return fr_desc end local function readWithReference(bs1) return function(generator) local blockname2fragments = {} local ev = require 'npge.util.extractValue' for name, description, text in generator do local blockname = ev(description, "block") if blockname then insertFragment(blockname2fragments, name, blockname, text) end end return bs1:sequences(), blockname2fragments end end local function isParted(start, stop, ori) local diff = stop - start return diff * ori < 0 end local function getParts(seqname, start, stop, ori, text) local toAtgcn = require 'npge.alignment.toAtgcn' local text = toAtgcn(text) local length = #text local length1, length2 if ori == 1 then length2 = stop + 1 length1 = length - length2 else length1 = start + 1 length2 = length - length1 end local start1 = start local stop1 = start1 + (length1 - 1) * ori local stop2 = stop local start2 = stop2 - (length2 - 1) * ori local text1 = text:sub(1, length1) local text2 = text:sub(length1 + 1) assert(#text1 == length1) assert(#text2 == length2) assert(start1 >= 0) assert(start2 >= 0) return {seqname, start1, stop1, ori, text1}, {seqname, start2, stop2, ori, text2} end local function makeSequence(seqname, parts) local unpack = require 'npge.util.unpack' local parts2 = {} for _, part in ipairs(parts) do local seqname1, start, stop, ori, text = unpack(part) assert(seqname1 == seqname) if isParted(start, stop, ori) then local part1, part2 = getParts(seqname, start, stop, ori, text) table.insert(parts2, part1) table.insert(parts2, part2) else table.insert(parts2, part) end end table.sort(parts2, function(part1, part2) local seqname1, start1, stop1, ori1 = unpack(part1) local seqname2, start2, stop2, ori2 = unpack(part2) assert(seqname1 == seqname) assert(seqname2 == seqname) assert(not isParted(start1, stop1, ori1)) assert(not isParted(start2, stop2, ori2)) return math.min(start1, stop1) < math.min(start2, stop2) end) local toAtgcn = require 'npge.alignment.toAtgcn' local complement = require 'npge.alignment.complement' local texts = {} local last = -1 for _, part in ipairs(parts2) do local _, start, stop, ori, text = unpack(part) local first = math.min(start, stop) assert(first == last + 1, "The blockset is not a partition") if ori == -1 then text = complement(text) end table.insert(texts, toAtgcn(text)) last = math.max(start, stop) end local text = table.concat(texts) local Sequence = require 'npge.model.Sequence' return Sequence(seqname, text) end local function readWithoutReference(generator) local blockname2fragments = {} local seqname2seq = {} local seqname2parts = {} local ev = require 'npge.util.extractValue' local Sequence = require 'npge.model.Sequence' local parseId = require 'npge.fragment.parseId' for name, description, text in generator do local blockname = ev(description, "block") if blockname then -- fragment local fr_desc = insertFragment(blockname2fragments, name, blockname, text) local seqname = fr_desc[1] -- insertFragment if not seqname2seq[seqname] then if not seqname2parts[seqname] then seqname2parts[seqname] = {} end table.insert(seqname2parts[seqname], fr_desc) end else -- sequence local seq = Sequence(name, text, description) assert(not seqname2seq[name]) seqname2seq[name] = seq -- remove useless records from seqname2parts seqname2parts[name] = nil end end -- create sequences from seqname2parts for seqname, parts in pairs(seqname2parts) do assert(not seqname2seq[seqname]) local seq = makeSequence(seqname, parts) seqname2seq[seqname] = seq collectgarbage() -- large text end local sequences = {} for name, seq in pairs(seqname2seq) do table.insert(sequences, seq) end return sequences, blockname2fragments end local function makeBlock(bs1, fr_descs) local alignment = {} local unpack = require 'npge.util.unpack' local Fragment = require 'npge.model.Fragment' for _, fr_desc in ipairs(fr_descs) do local seqname, start, stop, ori, text = unpack(fr_desc) local seq = assert(bs1:sequenceByName(seqname)) local fragment = Fragment(seq, start, stop, ori) table.insert(alignment, {fragment, text}) end local Block = require 'npge.model.Block' return Block(alignment) end return function(lines, blockset_with_sequences) -- lines is iterator (like file:lines()) or string if type(lines) == 'string' then local util = require 'npge.util' lines = util.textToIt(lines) end local fromFasta = require 'npge.util.fromFasta' local f if blockset_with_sequences then f = readWithReference(blockset_with_sequences) else f = readWithoutReference end local sequences, blockname2fragments = f(fromFasta(lines)) local BlockSet = require 'npge.model.BlockSet' local bs1 = BlockSet(sequences, {}) local blocks = {} for blockname, fr_descs in pairs(blockname2fragments) do local Block = require 'npge.model.Block' blocks[blockname] = makeBlock(bs1, fr_descs) end return BlockSet(sequences, blocks) end
ReadFromBs: fix for Lua >= 5.2 (unpack)
ReadFromBs: fix for Lua >= 5.2 (unpack) https://travis-ci.org/npge/lua-npge/jobs/91505883#L2354
Lua
mit
npge/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge,starius/lua-npge
b4df0092399a1296cb96350fc98ff7248e43b9b7
spec/unit/statics_spec.lua
spec/unit/statics_spec.lua
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should parse a correct configuration", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog # Nginx prefix path directory nginx_working_dir: /usr/local/kong/ # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # Sends anonymous error reports send_anonymous_reports: true # Cache configuration cache: expiration: 5 # in seconds nginx: | worker_processes auto; error_log logs/error.log info; daemon on; # Set "worker_rlimit_nofile" to a high value # worker_rlimit_nofile 65536; env KONG_CONF; events { # Set "worker_connections" to a high value worker_connections 1024; } http { # Generic Settings resolver 8.8.8.8; charset UTF-8; # Logs access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen 8000; location / { # Assigns the default MIME-type to be used for files where the # standard MIME map doesn't specify anything. default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen 8001; location / { default_type application/json; content_by_lua ' require("lapis").serve("kong.web.app") '; } location /static/ { alias static/; } location /admin/ { alias admin/; } location /favicon.ico { alias static/favicon.ico; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } } } ]], configuration) end) end) end)
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should parse a correct configuration", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog # Nginx prefix path directory nginx_working_dir: /usr/local/kong/ # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # Sends anonymous error reports send_anonymous_reports: true # Nginx Plus Status nginx_plus_status: false # Cache configuration cache: expiration: 5 # in seconds nginx: | worker_processes auto; error_log logs/error.log info; daemon on; # Set "worker_rlimit_nofile" to a high value # worker_rlimit_nofile 65536; env KONG_CONF; events { # Set "worker_connections" to a high value worker_connections 1024; } http { # Generic Settings resolver 8.8.8.8; charset UTF-8; # Logs access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen 8000; location / { # Assigns the default MIME-type to be used for files where the # standard MIME map doesn't specify anything. default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen 8001; location / { default_type application/json; content_by_lua ' require("lapis").serve("kong.web.app") '; } location /static/ { alias static/; } location /admin/ { alias admin/; } location /favicon.ico { alias static/favicon.ico; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } # Do not remove the following comment # plugin_configuration_placeholder } } ]], configuration) end) end) end)
fixing test
fixing test
Lua
apache-2.0
Mashape/kong,akh00/kong,kyroskoh/kong,ccyphers/kong,shiprabehera/kong,vzaramel/kong,streamdataio/kong,kyroskoh/kong,Kong/kong,icyxp/kong,vzaramel/kong,isdom/kong,ajayk/kong,smanolache/kong,ind9/kong,rafael/kong,jebenexer/kong,li-wl/kong,Kong/kong,Kong/kong,jerizm/kong,ejoncas/kong,Vermeille/kong,salazar/kong,ind9/kong,streamdataio/kong,ejoncas/kong,xvaara/kong,isdom/kong,beauli/kong,rafael/kong
a204f5abc89ae5faa9c1875b3fe9acba34bc1c5d
util/hashes.lua
util/hashes.lua
local softreq = function (...) return select(2, pcall(require, ...)); end local error = error; module "hashes" local md5 = softreq("md5"); if md5 then if md5.digest then local md5_digest = md5.digest; local sha1_digest = sha1.digest; function _M.md5(input) return md5_digest(input); end function _M.sha1(input) return sha1_digest(input); end elseif md5.sumhexa then local md5_sumhexa = md5.sumhexa; function _M.md5(input) return md5_sumhexa(input); end else error("md5 library found, but unrecognised... no hash functions will be available", 0); end end return _M;
local softreq = function (...) return select(2, pcall(require, ...)); end local error = error; module "hashes" local md5 = softreq("md5"); if md5 then if md5.digest then local md5_digest = md5.digest; local sha1_digest = sha1.digest; function _M.md5(input) return md5_digest(input); end function _M.sha1(input) return sha1_digest(input); end elseif md5.sumhexa then local md5_sumhexa = md5.sumhexa; function _M.md5(input) return md5_sumhexa(input); end else error("md5 library found, but unrecognised... no hash functions will be available", 0); end else error("No md5 library found. Install md5 using luarocks, for example", 0); end return _M;
Fix MD5 loading check
Fix MD5 loading check
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
333156a16222e768f8dcb94e504bbf2ead8c3f6d
packages/lime-system/files/usr/lib/lua/lime/network.lua
packages/lime-system/files/usr/lib/lua/lime/network.lua
#!/usr/bin/lua network = {} local bit = require "nixio".bit local ip = require "luci.ip" local function hex(x) return string.format("%02x", x) end local function split(string, sep) local ret = {} for token in string.gmatch(string, "[^"..sep.."]+") do table.insert(ret, token) end return ret end function network.eui64(mac) local function flip_7th_bit(x) return hex(bit.bxor(tonumber(x, 16), 2)) end local t = split(mac, ":") t[1] = flip_7th_bit(t[1]) return string.format("%s%s:%sff:fe%s:%s%s", t[1], t[2], t[3], t[4], t[5], t[6]) end function network.generate_host(ipprefix, hexsuffix) -- use only the 8 rightmost nibbles for IPv4, or 32 nibbles for IPv6 hexsuffix = hexsuffix:sub((ipprefix[1] == 4) and -8 or -32) -- convert hexsuffix into a cidr instance, using same prefix and family of ipprefix local ipsuffix = ip.Hex(hexsuffix, ipprefix:prefix(), ipprefix[1]) local ipaddress = ipprefix -- if it's a network prefix, fill in host bits with ipsuffix if ipprefix:equal(ipprefix:network()) then for i in ipairs(ipprefix[2]) do -- reset ipsuffix netmask bits to 0 ipsuffix[2][i] = bit.bxor(ipsuffix[2][i],ipsuffix:network()[2][i]) -- fill in ipaddress host part, with ipsuffix bits ipaddress[2][i] = bit.bor(ipaddress[2][i],ipsuffix[2][i]) end end return ipaddress end function network.generate_address(p, n) local id = n local m4, m5, m6 = node_id() local n1, n2, n3 = network_id() local ipv4_template = assert(uci:get("lime", "network", "ipv4_net")) local ipv6_template = assert(uci:get("lime", "network", "ipv6_net")) ipv6_template = ipv6_template:gsub("N1", hex(n1)):gsub("N2", hex(n2)):gsub("N3", hex(n3)) ipv4_template = ipv4_template:gsub("N1", n1):gsub("N2", n2):gsub("N3", n3) hexsuffix = hex((m4 * 256*256 + m5 * 256 + m6) + id) return network.generate_host(ip.IPv4(ipv4_template), hexsuffix), network.generate_host(ip.IPv6(ipv6_template), hexsuffix) end function network.setup_lan(ipv4, ipv6) uci:set("network", "lan", "ip6addr", ipv6:string()) uci:set("network", "lan", "ipaddr", ipv4:host():string()) uci:set("network", "lan", "netmask", ipv4:mask():string()) uci:set("network", "lan", "ifname", "eth0 bat0") uci:save("network") end function network.setup_anygw(ipv4, ipv6) local n1, n2, n3 = network_id() -- anygw macvlan interface print("Adding macvlan interface to uci network...") local anygw_mac = string.format("aa:aa:aa:%02x:%02x:%02x", n1, n2, n3) local anygw_ipv6 = ipv6:minhost() local anygw_ipv4 = ipv4:minhost() anygw_ipv6[3] = 64 -- SLAAC only works with a /64, per RFC anygw_ipv4[3] = ipv4:prefix() uci:set("network", "lm_anygw_dev", "device") uci:set("network", "lm_anygw_dev", "type", "macvlan") uci:set("network", "lm_anygw_dev", "name", "anygw") uci:set("network", "lm_anygw_dev", "ifname", "@lan") uci:set("network", "lm_anygw_dev", "macaddr", anygw_mac) uci:set("network", "lm_anygw_if", "interface") uci:set("network", "lm_anygw_if", "proto", "static") uci:set("network", "lm_anygw_if", "ifname", "anygw") uci:set("network", "lm_anygw_if", "ip6addr", anygw_ipv6:string()) uci:set("network", "lm_anygw_if", "ipaddr", anygw_ipv4:host():string()) uci:set("network", "lm_anygw_if", "netmask", anygw_ipv4:mask():string()) local content = { insert = table.insert, concat = table.concat } for line in io.lines("/etc/firewall.user") do if not line:match("^ebtables ") then content:insert(line) end end content:insert("ebtables -A FORWARD -j DROP -d " .. anygw_mac) content:insert("ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac) fs.writefile("/etc/firewall.user", content:concat("\n").."\n") -- IPv6 router advertisement for anygw interface print("Enabling RA in dnsmasq...") local content = { } table.insert(content, "enable-ra") table.insert(content, string.format("dhcp-range=tag:anygw, %s, ra-names", anygw_ipv6:network(64):string())) table.insert(content, "dhcp-option=tag:anygw, option6:domain-search, lan") table.insert(content, string.format("address=/anygw/%s", anygw_ipv6:host():string())) table.insert(content, string.format("dhcp-option=tag:anygw, option:router, %s", anygw_ipv4:host():string())) table.insert(content, string.format("dhcp-option=tag:anygw, option:dns-server, %s", anygw_ipv4:host():string())) table.insert(content, "no-dhcp-interface=br-lan") fs.writefile("/etc/dnsmasq.conf", table.concat(content, "\n").."\n") -- and disable 6relayd print("Disabling 6relayd...") fs.writefile("/etc/config/6relayd", "") end function network.clean() print("Clearing network config...") uci:foreach("network", "interface", function(s) if s[".name"]:match("^lm_") then uci:delete("network", s[".name"]) end end) end function network.init() -- TODO end function network.configure() local protocols = assert(uci:get("lime", "network", "protos")) local vlans = assert(uci:get("lime", "network", "vlans")) local n1, n2, n3 = network_id() local m4, m5, m6 = node_id() local ipv4, ipv6 = network.generate_address(1, 0) -- for br-lan network.clean() network.setup_lan(ipv4, ipv6) network.setup_anygw(ipv4, ipv6) -- For layer2 use a vlan based off network_id, between 16 and 255, if uci doesn't specify a vlan if not vlans[2] then vlans[2] = math.floor(16 + ((tonumber(n1) / 255) * (255 - 16))) end -- TODO: -- for each net ; if protocols = wan or lan ; setup_network_interface_lan -- elsif protocols = bmx6 or batadv ; setup_network_interface_ .. protocol -- FIXME: currently adds vlan interfaces on top of ethernet, for each proto (batadv or bmx6). -- Eg. lm_eth_batadv local n for n = 1, #protocols do local interface = "lm_eth_" .. protocols[n] local ifname = string.format("eth1.%d", vlans[n]) local ipv4, ipv6 = network.generate_address(n, 0) local proto = require("lime.proto." .. protocols[n]) proto.configure(ipv4, ipv6) proto.setup_interface(interface, ifname, ipv4, ipv6) end end function network.apply() -- TODO (i.e. /etc/init.d/network restart) end return network
#!/usr/bin/lua network = {} local bit = require "nixio".bit local ip = require "luci.ip" local function hex(x) return string.format("%02x", x) end local function split(string, sep) local ret = {} for token in string.gmatch(string, "[^"..sep.."]+") do table.insert(ret, token) end return ret end function network.eui64(mac) local function flip_7th_bit(x) return hex(bit.bxor(tonumber(x, 16), 2)) end local t = split(mac, ":") t[1] = flip_7th_bit(t[1]) return string.format("%s%s:%sff:fe%s:%s%s", t[1], t[2], t[3], t[4], t[5], t[6]) end function network.generate_host(ipprefix, hexsuffix) -- use only the 8 rightmost nibbles for IPv4, or 32 nibbles for IPv6 hexsuffix = hexsuffix:sub((ipprefix[1] == 4) and -8 or -32) -- convert hexsuffix into a cidr instance, using same prefix and family of ipprefix local ipsuffix = ip.Hex(hexsuffix, ipprefix:prefix(), ipprefix[1]) local ipaddress = ipprefix -- if it's a network prefix, fill in host bits with ipsuffix if ipprefix:equal(ipprefix:network()) then for i in ipairs(ipprefix[2]) do -- reset ipsuffix netmask bits to 0 ipsuffix[2][i] = bit.bxor(ipsuffix[2][i],ipsuffix:network()[2][i]) -- fill in ipaddress host part, with ipsuffix bits ipaddress[2][i] = bit.bor(ipaddress[2][i],ipsuffix[2][i]) end end return ipaddress end function network.generate_address(p, n) local id = n local m4, m5, m6 = node_id() local n1, n2, n3 = network_id() local ipv4_template = assert(uci:get("lime", "network", "ipv4_net")) local ipv6_template = assert(uci:get("lime", "network", "ipv6_net")) ipv6_template = ipv6_template:gsub("N1", hex(n1)):gsub("N2", hex(n2)):gsub("N3", hex(n3)) ipv4_template = ipv4_template:gsub("N1", n1):gsub("N2", n2):gsub("N3", n3) hexsuffix = hex((m4 * 256*256 + m5 * 256 + m6) + id) return network.generate_host(ip.IPv4(ipv4_template), hexsuffix), network.generate_host(ip.IPv6(ipv6_template), hexsuffix) end function network.setup_lan(ipv4, ipv6) uci:set("network", "lan", "ip6addr", ipv6:string()) uci:set("network", "lan", "ipaddr", ipv4:host():string()) uci:set("network", "lan", "netmask", ipv4:mask():string()) uci:set("network", "lan", "ifname", "eth0 bat0") uci:save("network") end function network.setup_anygw(ipv4, ipv6) local n1, n2, n3 = network_id() -- anygw macvlan interface print("Adding macvlan interface to uci network...") local anygw_mac = string.format("aa:aa:aa:%02x:%02x:%02x", n1, n2, n3) local anygw_ipv6 = ipv6:minhost() local anygw_ipv4 = ipv4:minhost() anygw_ipv6[3] = 64 -- SLAAC only works with a /64, per RFC anygw_ipv4[3] = ipv4:prefix() uci:set("network", "lm_anygw_dev", "device") uci:set("network", "lm_anygw_dev", "type", "macvlan") uci:set("network", "lm_anygw_dev", "name", "anygw") uci:set("network", "lm_anygw_dev", "ifname", "@lan") uci:set("network", "lm_anygw_dev", "macaddr", anygw_mac) uci:set("network", "lm_anygw_if", "interface") uci:set("network", "lm_anygw_if", "proto", "static") uci:set("network", "lm_anygw_if", "ifname", "anygw") uci:set("network", "lm_anygw_if", "ip6addr", anygw_ipv6:string()) uci:set("network", "lm_anygw_if", "ipaddr", anygw_ipv4:host():string()) uci:set("network", "lm_anygw_if", "netmask", anygw_ipv4:mask():string()) local content = { insert = table.insert, concat = table.concat } for line in io.lines("/etc/firewall.user") do if not line:match("^ebtables ") then content:insert(line) end end content:insert("ebtables -A FORWARD -j DROP -d " .. anygw_mac) content:insert("ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac) fs.writefile("/etc/firewall.user", content:concat("\n").."\n") -- IPv6 router advertisement for anygw interface print("Enabling RA in dnsmasq...") local content = { } table.insert(content, "enable-ra") table.insert(content, string.format("dhcp-range=tag:anygw, %s, ra-names", anygw_ipv6:network(64):string())) table.insert(content, "dhcp-option=tag:anygw, option6:domain-search, lan") table.insert(content, string.format("address=/anygw/%s", anygw_ipv6:host():string())) table.insert(content, string.format("dhcp-option=tag:anygw, option:router, %s", anygw_ipv4:host():string())) table.insert(content, string.format("dhcp-option=tag:anygw, option:dns-server, %s", anygw_ipv4:host():string())) table.insert(content, "dhcp-broadcast=tag:anygw") table.insert(content, "no-dhcp-interface=br-lan") fs.writefile("/etc/dnsmasq.conf", table.concat(content, "\n").."\n") -- and disable 6relayd print("Disabling 6relayd...") fs.writefile("/etc/config/6relayd", "") end function network.clean() print("Clearing network config...") uci:foreach("network", "interface", function(s) if s[".name"]:match("^lm_") then uci:delete("network", s[".name"]) end end) end function network.init() -- TODO end function network.configure() local protocols = assert(uci:get("lime", "network", "protos")) local vlans = assert(uci:get("lime", "network", "vlans")) local n1, n2, n3 = network_id() local m4, m5, m6 = node_id() local ipv4, ipv6 = network.generate_address(1, 0) -- for br-lan network.clean() network.setup_lan(ipv4, ipv6) network.setup_anygw(ipv4, ipv6) -- For layer2 use a vlan based off network_id, between 16 and 255, if uci doesn't specify a vlan if not vlans[2] then vlans[2] = math.floor(16 + ((tonumber(n1) / 255) * (255 - 16))) end -- TODO: -- for each net ; if protocols = wan or lan ; setup_network_interface_lan -- elsif protocols = bmx6 or batadv ; setup_network_interface_ .. protocol -- FIXME: currently adds vlan interfaces on top of ethernet, for each proto (batadv or bmx6). -- Eg. lm_eth_batadv local n for n = 1, #protocols do local interface = "lm_eth_" .. protocols[n] local ifname = string.format("eth1.%d", vlans[n]) local ipv4, ipv6 = network.generate_address(n, 0) local proto = require("lime.proto." .. protocols[n]) proto.configure(ipv4, ipv6) proto.setup_interface(interface, ifname, ipv4, ipv6) end end function network.apply() -- TODO (i.e. /etc/init.d/network restart) end return network
use dhcp-broadcast in anygw DHCPv4 to workaround dnsmasq bug
use dhcp-broadcast in anygw DHCPv4 to workaround dnsmasq bug
Lua
agpl-3.0
p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages
08a4c7be5c70fe4f3cb7e4757bbbc4576a8f9fc1
packages/pirania/files/usr/lib/lua/voucher/hooks.lua
packages/pirania/files/usr/lib/lua/voucher/hooks.lua
#!/usr/bin/lua local config = require('voucher.config') local fs = require("nixio.fs") local hooks = function(action) local hookPath = config.hooksDir..action..'/' local files = fs.dir(hookPath) or pairs({}) for file in files do os.execute("(( sh "..hookPath..file.." 0<&- &>/dev/null &) &)") end end if debug.getinfo(2).name == nil then local arguments = { ... } if (arguments ~= nil and arguments[1] ~= nil) then hooks(arguments[1]) end end return hooks
#!/usr/bin/lua local config = require('voucher.config') local fs = require("nixio.fs") local hooks = function(action) local hookPath = config.hooksDir..action..'/' local files = fs.dir(hookPath) if files then for file in files do os.execute("(( sh "..hookPath..file.." 0<&- &>/dev/null &) &)") end end end if debug.getinfo(2).name == nil then local arguments = { ... } if (arguments ~= nil and arguments[1] ~= nil) then hooks(arguments[1]) end end return hooks
pirania: fix hooks with empty directory
pirania: fix hooks with empty directory
Lua
agpl-3.0
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
5f0b1ce0059567de378916ca3a6f4332ff9ece23
modules/android/tests/test_android_project.lua
modules/android/tests/test_android_project.lua
local p = premake local suite = test.declare("test_android_project") local vc2010 = p.vstudio.vc2010 -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2015") wks, prj = test.createWorkspace() end local function prepare() system "android" local cfg = test.getconfig(prj, "Debug", platform) vc2010.clCompile(cfg) end function suite.noOptions() prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.rttiOff() rtti "Off" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.rttiOn() rtti "On" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <RuntimeTypeInfo>true</RuntimeTypeInfo> ]] end function suite.exceptionHandlingOff() exceptionhandling "Off" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.exceptionHandlingOn() exceptionhandling "On" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <ExceptionHandling>Enabled</ExceptionHandling> ]] end function suite.cppdialect_cpp11() cppdialect "C++11" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++11</CppLanguageStandard> ]] end function suite.cppdialect_cpp14() cppdialect "C++14" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++1y</CppLanguageStandard> ]] end function suite.cppdialect_cpp17() cppdialect "C++17" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++1z</CppLanguageStandard> ]] end
local p = premake local suite = test.declare("test_android_project") local vc2010 = p.vstudio.vc2010 local android = p.modules.android -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2015") wks, prj = test.createWorkspace() end local function prepare() system "android" local cfg = test.getconfig(prj, "Debug", platform) vc2010.clCompile(cfg) end local function preparePropertyGroup() system "android" local cfg = test.getconfig(prj, "Debug", platform) vc2010.propertyGroup(cfg) android.androidApplicationType(cfg) end function suite.minVisualStudioVersion() preparePropertyGroup() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Android'"> <Keyword>Android</Keyword> <RootNamespace>MyProject</RootNamespace> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> <ApplicationType>Android</ApplicationType> <ApplicationTypeRevision>2.0</ApplicationTypeRevision>]] end function suite.noOptions() prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.rttiOff() rtti "Off" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.rttiOn() rtti "On" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <RuntimeTypeInfo>true</RuntimeTypeInfo> ]] end function suite.exceptionHandlingOff() exceptionhandling "Off" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.exceptionHandlingOn() exceptionhandling "On" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <ExceptionHandling>Enabled</ExceptionHandling> ]] end function suite.cppdialect_cpp11() cppdialect "C++11" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++11</CppLanguageStandard> ]] end function suite.cppdialect_cpp14() cppdialect "C++14" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++1y</CppLanguageStandard> ]] end function suite.cppdialect_cpp17() cppdialect "C++17" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++1z</CppLanguageStandard> ]] end
Fix android test case for minVSversion
Fix android test case for minVSversion
Lua
bsd-3-clause
mandersan/premake-core,LORgames/premake-core,premake/premake-core,starkos/premake-core,noresources/premake-core,dcourtois/premake-core,LORgames/premake-core,mandersan/premake-core,premake/premake-core,starkos/premake-core,LORgames/premake-core,starkos/premake-core,noresources/premake-core,premake/premake-core,starkos/premake-core,mandersan/premake-core,sleepingwit/premake-core,sleepingwit/premake-core,sleepingwit/premake-core,dcourtois/premake-core,LORgames/premake-core,dcourtois/premake-core,premake/premake-core,dcourtois/premake-core,noresources/premake-core,starkos/premake-core,noresources/premake-core,premake/premake-core,dcourtois/premake-core,dcourtois/premake-core,sleepingwit/premake-core,LORgames/premake-core,dcourtois/premake-core,sleepingwit/premake-core,premake/premake-core,mandersan/premake-core,noresources/premake-core,noresources/premake-core,premake/premake-core,noresources/premake-core,starkos/premake-core,mandersan/premake-core,starkos/premake-core
1cffc37ec84cae21bab3e58f2aedbb4a154f4184
MMOCoreORB/bin/scripts/mobile/yavin4/serverobjects.lua
MMOCoreORB/bin/scripts/mobile/yavin4/serverobjects.lua
includeFile("yavin4/acklay.lua") includeFile("yavin4/alert_droideka.lua") includeFile("yavin4/ancient_mamien.lua") includeFile("yavin4/angler_be.lua") includeFile("yavin4/angler_hatchling.lua") includeFile("yavin4/angler.lua") includeFile("yavin4/angler_recluse.lua") includeFile("yavin4/biogenic_assistant.lua") includeFile("yavin4/biogenic_construction.lua") includeFile("yavin4/biogenic_crazyguy.lua") includeFile("yavin4/biogenic_engineertech.lua") includeFile("yavin4/biogenic_scientist_generic_01.lua") includeFile("yavin4/biogenic_scientist_generic_02.lua") includeFile("yavin4/biogenic_scientist_geonosian.lua") includeFile("yavin4/biogenic_scientist_human.lua") includeFile("yavin4/biogenic_securitytech.lua") includeFile("yavin4/blood_fanged_gackle_bat.lua") includeFile("yavin4/bone_angler.lua") includeFile("yavin4/captain_eso.lua") includeFile("yavin4/choku_be.lua") includeFile("yavin4/choku_female.lua") includeFile("yavin4/choku_hunter.lua") includeFile("yavin4/choku.lua") includeFile("yavin4/choku_male.lua") includeFile("yavin4/choku_packmaster.lua") includeFile("yavin4/choku_pup.lua") includeFile("yavin4/crazed_geonosian_guard.lua") includeFile("yavin4/crystal_snake.lua") includeFile("yavin4/cx_425.lua") includeFile("yavin4/deadly_tanc_mite.lua") includeFile("yavin4/drenn_zebber.lua") includeFile("yavin4/elder_mamien.lua") includeFile("yavin4/enhanced_force_kliknik.lua") includeFile("yavin4/enhanced_gaping_spider.lua") includeFile("yavin4/enhanced_kliknik.lua") includeFile("yavin4/enhanced_kwi.lua") includeFile("yavin4/enraged_tybis.lua") includeFile("yavin4/female_mamien.lua") includeFile("yavin4/female_mawgax.lua") includeFile("yavin4/female_tybis.lua") includeFile("yavin4/feral_mutant_gackle_stalker.lua") includeFile("yavin4/frenzied_choku.lua") includeFile("yavin4/gackle_bat_hunter.lua") includeFile("yavin4/gackle_bat.lua") includeFile("yavin4/gackle_bat_myrmidon_lord.lua") includeFile("yavin4/geonosian_scientist.lua") includeFile("yavin4/geonosian_technical_assistant.lua") includeFile("yavin4/geonosian_worker.lua") includeFile("yavin4/giant_angler.lua") includeFile("yavin4/giant_crystal_snake.lua") includeFile("yavin4/giant_gackle_bat.lua") includeFile("yavin4/giant_mawgax.lua") includeFile("yavin4/giant_spined_puc.lua") includeFile("yavin4/giant_stintaril.lua") includeFile("yavin4/giant_tanc_mite.lua") includeFile("yavin4/gins_darone.lua") includeFile("yavin4/grand_tybis.lua") includeFile("yavin4/hooded_crystal_snake.lua") includeFile("yavin4/hutt_expeditionary_force_surveyor.lua") includeFile("yavin4/hutt_expeditonary_force_leader.lua") includeFile("yavin4/hutt_expeditonary_force_member.lua") includeFile("yavin4/imperial_observer.lua") includeFile("yavin4/jazeen_thurmm.lua") includeFile("yavin4/kai_tok_bloodreaver.lua") includeFile("yavin4/kai_tok_prowler.lua") includeFile("yavin4/kai_tok_scavenger.lua") includeFile("yavin4/kai_tok_slayer.lua") includeFile("yavin4/kliknik_be.lua") includeFile("yavin4/kliknik_dark_defender.lua") includeFile("yavin4/kliknik_dark_hunter.lua") includeFile("yavin4/kliknik_dark_queen.lua") includeFile("yavin4/kliknik_dark_warrior.lua") includeFile("yavin4/kliknik_dark_worker.lua") includeFile("yavin4/kliknik_defender.lua") includeFile("yavin4/kliknik_hatchling.lua") includeFile("yavin4/kliknik_hunter.lua") includeFile("yavin4/kliknik.lua") includeFile("yavin4/kliknik_mantis.lua") includeFile("yavin4/kliknik_queen_harvester.lua") includeFile("yavin4/kliknik_queen.lua") includeFile("yavin4/kliknik_scout.lua") includeFile("yavin4/kliknik_shredder_guardian.lua") includeFile("yavin4/kliknik_warrior.lua") includeFile("yavin4/kliknik_worker.lua") includeFile("yavin4/lurking_angler.lua") includeFile("yavin4/mad_angler.lua") includeFile("yavin4/majestic_whisper_bird.lua") includeFile("yavin4/male_mamien.lua") includeFile("yavin4/male_mawgax.lua") includeFile("yavin4/male_tybis.lua") includeFile("yavin4/mamien_jungle_lord.lua") includeFile("yavin4/mamien_matriarch.lua") includeFile("yavin4/mamien_youth.lua") includeFile("yavin4/mawgax_be.lua") includeFile("yavin4/mawgax_raptor.lua") includeFile("yavin4/mawgax_youth.lua") includeFile("yavin4/megan_drlar.lua") includeFile("yavin4/mercenary_sentry.lua") includeFile("yavin4/ominous_skreeg.lua") includeFile("yavin4/poisonous_spined_puc.lua") includeFile("yavin4/puny_gackle_bat.lua") includeFile("yavin4/puny_stintaril.lua") includeFile("yavin4/puny_tanc_mite.lua") includeFile("yavin4/ravaging_gackle_bat.lua") includeFile("yavin4/skreeg_adolescent.lua") includeFile("yavin4/skreeg_female.lua") includeFile("yavin4/skreeg_gatherer.lua") includeFile("yavin4/skreeg_hunter.lua") includeFile("yavin4/skreeg_infant.lua") includeFile("yavin4/skreeg_male.lua") includeFile("yavin4/skreeg_scout.lua") includeFile("yavin4/skreeg_warrior_elite.lua") includeFile("yavin4/skreeg_warrior.lua") includeFile("yavin4/spined_puc.lua") includeFile("yavin4/stintaril_fleshripper.lua") includeFile("yavin4/stintaril.lua") includeFile("yavin4/stintaril_prowler.lua") includeFile("yavin4/stintaril_ravager.lua") includeFile("yavin4/stintaril_scavenger.lua") includeFile("yavin4/stranded_imperial_officer.lua") includeFile("yavin4/stranded_imperial_pilot.lua") includeFile("yavin4/stranded_imperial_soldier.lua") includeFile("yavin4/stranded_rebel_officer.lua") includeFile("yavin4/stranded_rebel_pilot.lua") includeFile("yavin4/stranded_rebel_soldier.lua") includeFile("yavin4/stunted_woolamander.lua") includeFile("yavin4/swarming_kliknik.lua") includeFile("yavin4/tanc_mite.lua") includeFile("yavin4/tanc_mite_warrior.lua") includeFile("yavin4/theme_park_rebel_supervisor.lua") includeFile("yavin4/tybis_be.lua") includeFile("yavin4/tybis.lua") includeFile("yavin4/tybis_youth.lua") includeFile("yavin4/vraker_orde.lua") includeFile("yavin4/yith_seenath.lua")
includeFile("yavin4/acklay.lua") includeFile("yavin4/alert_droideka.lua") includeFile("yavin4/ancient_mamien.lua") includeFile("yavin4/angler_be.lua") includeFile("yavin4/angler_hatchling.lua") includeFile("yavin4/angler.lua") includeFile("yavin4/angler_recluse.lua") includeFile("yavin4/biogenic_assistant.lua") includeFile("yavin4/biogenic_construction.lua") includeFile("yavin4/biogenic_crazyguy.lua") includeFile("yavin4/biogenic_engineertech.lua") includeFile("yavin4/biogenic_scientist_generic_01.lua") includeFile("yavin4/biogenic_scientist_generic_02.lua") includeFile("yavin4/biogenic_scientist_geonosian.lua") includeFile("yavin4/biogenic_scientist_human.lua") includeFile("yavin4/biogenic_securitytech.lua") includeFile("yavin4/blood_fanged_gackle_bat.lua") includeFile("yavin4/bone_angler.lua") includeFile("yavin4/captain_eso.lua") includeFile("yavin4/choku_be.lua") includeFile("yavin4/choku_female.lua") includeFile("yavin4/choku_hunter.lua") includeFile("yavin4/choku.lua") includeFile("yavin4/choku_male.lua") includeFile("yavin4/choku_packmaster.lua") includeFile("yavin4/choku_pup.lua") includeFile("yavin4/crazed_geonosian_guard.lua") includeFile("yavin4/crystal_snake.lua") includeFile("yavin4/cx_425.lua") includeFile("yavin4/deadly_tanc_mite.lua") includeFile("yavin4/drenn_zebber.lua") includeFile("yavin4/elder_mamien.lua") includeFile("yavin4/enhanced_force_kliknik.lua") includeFile("yavin4/enhanced_gaping_spider.lua") includeFile("yavin4/enhanced_kliknik.lua") includeFile("yavin4/enhanced_kwi.lua") includeFile("yavin4/enraged_tybis.lua") includeFile("yavin4/female_mamien.lua") includeFile("yavin4/female_mawgax.lua") includeFile("yavin4/female_tybis.lua") includeFile("yavin4/feral_mutant_gackle_stalker.lua") includeFile("yavin4/frenzied_choku.lua") includeFile("yavin4/gackle_bat_hunter.lua") includeFile("yavin4/gackle_bat.lua") includeFile("yavin4/gackle_bat_myrmidon_lord.lua") includeFile("yavin4/geonosian_scientist.lua") includeFile("yavin4/geonosian_technical_assistant.lua") includeFile("yavin4/geonosian_worker.lua") includeFile("yavin4/giant_angler.lua") includeFile("yavin4/giant_crystal_snake.lua") includeFile("yavin4/giant_gackle_bat.lua") includeFile("yavin4/giant_mawgax.lua") includeFile("yavin4/giant_spined_puc.lua") includeFile("yavin4/giant_stintaril.lua") includeFile("yavin4/giant_tanc_mite.lua") includeFile("yavin4/gins_darone.lua") includeFile("yavin4/grand_tybis.lua") includeFile("yavin4/hooded_crystal_snake.lua") includeFile("yavin4/hutt_expeditionary_force_surveyor.lua") includeFile("yavin4/hutt_expeditonary_force_leader.lua") includeFile("yavin4/hutt_expeditonary_force_member.lua") includeFile("yavin4/imperial_observer.lua") includeFile("yavin4/jazeen_thurmm.lua") includeFile("yavin4/kai_tok_bloodreaver.lua") includeFile("yavin4/kai_tok_prowler.lua") includeFile("yavin4/kai_tok_scavenger.lua") includeFile("yavin4/kai_tok_slayer.lua") includeFile("yavin4/kliknik_be.lua") includeFile("yavin4/kliknik_dark_defender.lua") includeFile("yavin4/kliknik_dark_hunter.lua") includeFile("yavin4/kliknik_dark_queen.lua") includeFile("yavin4/kliknik_dark_warrior.lua") includeFile("yavin4/kliknik_dark_worker.lua") includeFile("yavin4/kliknik_defender.lua") includeFile("yavin4/kliknik_hatchling.lua") includeFile("yavin4/kliknik_hunter.lua") includeFile("yavin4/kliknik.lua") includeFile("yavin4/kliknik_mantis.lua") includeFile("yavin4/kliknik_queen_harvester.lua") includeFile("yavin4/kliknik_queen.lua") includeFile("yavin4/kliknik_scout.lua") includeFile("yavin4/kliknik_shredder_guardian.lua") includeFile("yavin4/kliknik_warrior.lua") includeFile("yavin4/kliknik_worker.lua") includeFile("yavin4/lurking_angler.lua") includeFile("yavin4/mad_angler.lua") includeFile("yavin4/majestic_whisper_bird.lua") includeFile("yavin4/male_mamien.lua") includeFile("yavin4/male_mawgax.lua") includeFile("yavin4/male_tybis.lua") includeFile("yavin4/mamien_jungle_lord.lua") includeFile("yavin4/mamien_matriarch.lua") includeFile("yavin4/mamien_youth.lua") includeFile("yavin4/mawgax_be.lua") includeFile("yavin4/mawgax_raptor.lua") includeFile("yavin4/mawgax_youth.lua") includeFile("yavin4/megan_drlar.lua") includeFile("yavin4/mercenary_sentry.lua") includeFile("yavin4/ominous_skreeg.lua") includeFile("yavin4/poisonous_spined_puc.lua") includeFile("yavin4/puny_gackle_bat.lua") includeFile("yavin4/puny_stintaril.lua") includeFile("yavin4/puny_tanc_mite.lua") includeFile("yavin4/ravaging_gackle_bat.lua") includeFile("yavin4/skreeg_adolescent.lua") includeFile("yavin4/skreeg_female.lua") includeFile("yavin4/skreeg_gatherer.lua") includeFile("yavin4/skreeg_hunter.lua") includeFile("yavin4/skreeg_infant.lua") includeFile("yavin4/skreeg_male.lua") includeFile("yavin4/skreeg_scout.lua") includeFile("yavin4/skreeg_warrior_elite.lua") includeFile("yavin4/skreeg_warrior.lua") includeFile("yavin4/spined_puc.lua") includeFile("yavin4/stintaril_fleshripper.lua") includeFile("yavin4/stintaril.lua") includeFile("yavin4/stintaril_prowler.lua") includeFile("yavin4/stintaril_ravager.lua") includeFile("yavin4/stintaril_scavenger.lua") includeFile("yavin4/stranded_imperial_officer.lua") includeFile("yavin4/stranded_imperial_pilot.lua") includeFile("yavin4/stranded_imperial_soldier.lua") includeFile("yavin4/stranded_rebel_officer.lua") includeFile("yavin4/stranded_rebel_pilot.lua") includeFile("yavin4/stranded_rebel_soldier.lua") includeFile("yavin4/stunted_woolamander.lua") includeFile("yavin4/swarming_kliknik.lua") includeFile("yavin4/tanc_mite.lua") includeFile("yavin4/tanc_mite_warrior.lua") includeFile("yavin4/theme_park_rebel_big_creature.lua") includeFile("yavin4/theme_park_rebel_big_creature_cage.lua") includeFile("yavin4/theme_park_rebel_supervisor.lua") includeFile("yavin4/tybis_be.lua") includeFile("yavin4/tybis.lua") includeFile("yavin4/tybis_youth.lua") includeFile("yavin4/vraker_orde.lua") includeFile("yavin4/yith_seenath.lua")
(unstable) [fixed] luke mission 2.
(unstable) [fixed] luke mission 2. git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5958 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
6568c947dae211ac4ea23b9b874f2f396d4210b7
MMOCoreORB/bin/scripts/mobile/corellia/minor_gubbur.lua
MMOCoreORB/bin/scripts/mobile/corellia/minor_gubbur.lua
minor_gubbur = Creature:new { objectName = "@mob/creature_names:minor_gubbur", socialGroup = "gubbur", pvpFaction = "", faction = "", level = 4, chanceHit = 0.24, damageMin = 40, damageMax = 45, baseXp = 62, baseHAM = 113, baseHAMmax = 135, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "meat_carnivore", meatAmount = 3, hideType = "hide_leathery", hideAmount = 2, boneType = "bone_mammal", boneAmount = 2, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = HERD, optionsBitmask = 128, diet = CARNIVORE, templates = {"object/mobile/minor_gubbur.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = merge(brawlernovice,marksmannovice) } CreatureTemplates:addCreatureTemplate(minor_gubbur, "minor_gubbur")
minor_gubbur = Creature:new { objectName = "@mob/creature_names:minor_gubbur", socialGroup = "gubbur", pvpFaction = "", faction = "", level = 4, chanceHit = 0.24, damageMin = 40, damageMax = 45, baseXp = 62, baseHAM = 113, baseHAMmax = 135, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "meat_carnivore", meatAmount = 3, hideType = "hide_leathery", hideAmount = 2, boneType = "bone_mammal", boneAmount = 2, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = HERD, optionsBitmask = 128, diet = CARNIVORE, templates = {"object/mobile/minor_gubbur.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { } } CreatureTemplates:addCreatureTemplate(minor_gubbur, "minor_gubbur")
[Fixed] minor gubbur attacks - mantis 4318
[Fixed] minor gubbur attacks - mantis 4318 Change-Id: I8e2f8d5fcf46fff73d98c03eb00011ae68ec65ea
Lua
agpl-3.0
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
0dd209a389f16efb08e0b0f53cdb7f8591e6d070
kong/pdk/service/response.lua
kong/pdk/service/response.lua
--- -- Manipulation of the response from the Service -- @module kong.service.response local phase_checker = require "kong.pdk.private.phases" local ngx = ngx local sub = string.sub local fmt = string.format local gsub = string.gsub local type = type local error = error local lower = string.lower local tonumber = tonumber local getmetatable = getmetatable local check_phase = phase_checker.check local PHASES = phase_checker.phases local header_body_log = phase_checker.new(PHASES.header_filter, PHASES.body_filter, PHASES.log) local function headers(response_headers, err) local mt = getmetatable(response_headers) local index = mt.__index mt.__index = function(_, name) if type(name) == "string" then local var = fmt("upstream_http_%s", gsub(lower(name), "-", "_")) if not ngx.var[var] then return nil end end return index(response_headers, name) end return response_headers, err end local function new(pdk, major_version) local response = {} local MIN_HEADERS = 1 local MAX_HEADERS_DEFAULT = 100 local MAX_HEADERS = 1000 --- -- Returns the HTTP status code of the response from the Service as a Lua number. -- -- @function kong.service.response.get_status -- @phases `header_filter`, `body_filter`, `log` -- @treturn number|nil the status code from the response from the Service, or `nil` -- if the request was not proxied (i.e. `kong.response.get_source()` returned -- anything other than `"service"`. -- @usage -- kong.log.inspect(kong.service.response.get_status()) -- 418 function response.get_status() check_phase(header_body_log) return tonumber(sub(ngx.var.upstream_status or "", -3)) end --- -- Returns a Lua table holding the headers from the response from the Service. Keys are -- header names. Values are either a string with the header value, or an array of -- strings if a header was sent multiple times. Header names in this table are -- case-insensitive and dashes (`-`) can be written as underscores (`_`); that is, -- the header `X-Custom-Header` can also be retrieved as `x_custom_header`. -- -- Unlike `kong.response.get_headers()`, this function will only return headers that -- were present in the response from the Service (ignoring headers added by Kong itself). -- If the request was not proxied to a Service (e.g. an authentication plugin rejected -- a request and produced an HTTP 401 response), then the returned `headers` value -- might be `nil`, since no response from the Service has been received. -- -- By default, this function returns up to **100** headers. The optional -- `max_headers` argument can be specified to customize this limit, but must be -- greater than **1** and not greater than **1000**. -- @function kong.service.response.get_headers -- @phases `header_filter`, `body_filter`, `log` -- @tparam[opt] number max_headers customize the headers to parse -- @treturn table the response headers in table form -- @treturn string err If more headers than `max_headers` were present, a -- string with the error `"truncated"`. -- @usage -- -- Given a response with the following headers: -- -- X-Custom-Header: bla -- -- X-Another: foo bar -- -- X-Another: baz -- local headers = kong.service.response.get_headers() -- if headers then -- kong.log.inspect(headers.x_custom_header) -- "bla" -- kong.log.inspect(headers.x_another[1]) -- "foo bar" -- kong.log.inspect(headers["X-Another"][2]) -- "baz" -- end function response.get_headers(max_headers) check_phase(header_body_log) if max_headers == nil then return headers(ngx.resp.get_headers(MAX_HEADERS_DEFAULT)) end if type(max_headers) ~= "number" then error("max_headers must be a number", 2) elseif max_headers < MIN_HEADERS then error("max_headers must be >= " .. MIN_HEADERS, 2) elseif max_headers > MAX_HEADERS then error("max_headers must be <= " .. MAX_HEADERS, 2) end return headers(ngx.resp.get_headers(max_headers)) end --- -- Returns the value of the specified response header. -- -- Unlike `kong.response.get_header()`, this function will only return a header -- if it was present in the response from the Service (ignoring headers added by Kong -- itself). -- -- @function kong.service.response.get_header -- @phases `header_filter`, `body_filter`, `log` -- @tparam string name The name of the header. -- -- Header names in are case-insensitive and are normalized to lowercase, and -- dashes (`-`) can be written as underscores (`_`); that is, the header -- `X-Custom-Header` can also be retrieved as `x_custom_header`. -- -- @treturn string|nil The value of the header, or `nil` if a header with -- `name` was not found in the response. If a header with the same name is present -- multiple times in the response, this function will return the value of the -- first occurrence of this header. -- @usage -- -- Given a response with the following headers: -- -- X-Custom-Header: bla -- -- X-Another: foo bar -- -- X-Another: baz -- -- kong.log.inspect(kong.service.response.get_header("x-custom-header")) -- "bla" -- kong.log.inspect(kong.service.response.get_header("X-Another")) -- "foo bar" function response.get_header(name) check_phase(header_body_log) if type(name) ~= "string" then error("name must be a string", 2) end local header_value = response.get_headers()[name] if type(header_value) == "table" then return header_value[1] end return header_value end function response.get_raw_body() -- TODO: implement end function response.get_body() -- TODO: implement end return response end return { new = new, }
--- -- Manipulation of the response from the Service -- @module kong.service.response local phase_checker = require "kong.pdk.private.phases" local ngx = ngx local sub = string.sub local fmt = string.format local gsub = string.gsub local type = type local error = error local lower = string.lower local tonumber = tonumber local getmetatable = getmetatable local setmetatable = setmetatable local check_phase = phase_checker.check local PHASES = phase_checker.phases local header_body_log = phase_checker.new(PHASES.header_filter, PHASES.body_filter, PHASES.log) local attach_resp_headers_mt do local resp_headers_orig_mt_index local resp_headers_mt = { __index = function(t, name) if type(name) == "string" then local var = fmt("upstream_http_%s", gsub(lower(name), "-", "_")) if not ngx.var[var] then return nil end end return resp_headers_orig_mt_index(t, name) end, } attach_resp_headers_mt = function(response_headers, err) if not resp_headers_orig_mt_index then local mt = getmetatable(response_headers) resp_headers_orig_mt_index = mt.__index end setmetatable(response_headers, resp_headers_mt) return response_headers, err end end local function new(pdk, major_version) local response = {} local MIN_HEADERS = 1 local MAX_HEADERS_DEFAULT = 100 local MAX_HEADERS = 1000 --- -- Returns the HTTP status code of the response from the Service as a Lua number. -- -- @function kong.service.response.get_status -- @phases `header_filter`, `body_filter`, `log` -- @treturn number|nil the status code from the response from the Service, or `nil` -- if the request was not proxied (i.e. `kong.response.get_source()` returned -- anything other than `"service"`. -- @usage -- kong.log.inspect(kong.service.response.get_status()) -- 418 function response.get_status() check_phase(header_body_log) return tonumber(sub(ngx.var.upstream_status or "", -3)) end --- -- Returns a Lua table holding the headers from the response from the Service. Keys are -- header names. Values are either a string with the header value, or an array of -- strings if a header was sent multiple times. Header names in this table are -- case-insensitive and dashes (`-`) can be written as underscores (`_`); that is, -- the header `X-Custom-Header` can also be retrieved as `x_custom_header`. -- -- Unlike `kong.response.get_headers()`, this function will only return headers that -- were present in the response from the Service (ignoring headers added by Kong itself). -- If the request was not proxied to a Service (e.g. an authentication plugin rejected -- a request and produced an HTTP 401 response), then the returned `headers` value -- might be `nil`, since no response from the Service has been received. -- -- By default, this function returns up to **100** headers. The optional -- `max_headers` argument can be specified to customize this limit, but must be -- greater than **1** and not greater than **1000**. -- @function kong.service.response.get_headers -- @phases `header_filter`, `body_filter`, `log` -- @tparam[opt] number max_headers customize the headers to parse -- @treturn table the response headers in table form -- @treturn string err If more headers than `max_headers` were present, a -- string with the error `"truncated"`. -- @usage -- -- Given a response with the following headers: -- -- X-Custom-Header: bla -- -- X-Another: foo bar -- -- X-Another: baz -- local headers = kong.service.response.get_headers() -- if headers then -- kong.log.inspect(headers.x_custom_header) -- "bla" -- kong.log.inspect(headers.x_another[1]) -- "foo bar" -- kong.log.inspect(headers["X-Another"][2]) -- "baz" -- end function response.get_headers(max_headers) check_phase(header_body_log) if max_headers == nil then return attach_resp_headers_mt(ngx.resp.get_headers(MAX_HEADERS_DEFAULT)) end if type(max_headers) ~= "number" then error("max_headers must be a number", 2) elseif max_headers < MIN_HEADERS then error("max_headers must be >= " .. MIN_HEADERS, 2) elseif max_headers > MAX_HEADERS then error("max_headers must be <= " .. MAX_HEADERS, 2) end return attach_resp_headers_mt(ngx.resp.get_headers(max_headers)) end --- -- Returns the value of the specified response header. -- -- Unlike `kong.response.get_header()`, this function will only return a header -- if it was present in the response from the Service (ignoring headers added by Kong -- itself). -- -- @function kong.service.response.get_header -- @phases `header_filter`, `body_filter`, `log` -- @tparam string name The name of the header. -- -- Header names in are case-insensitive and are normalized to lowercase, and -- dashes (`-`) can be written as underscores (`_`); that is, the header -- `X-Custom-Header` can also be retrieved as `x_custom_header`. -- -- @treturn string|nil The value of the header, or `nil` if a header with -- `name` was not found in the response. If a header with the same name is present -- multiple times in the response, this function will return the value of the -- first occurrence of this header. -- @usage -- -- Given a response with the following headers: -- -- X-Custom-Header: bla -- -- X-Another: foo bar -- -- X-Another: baz -- -- kong.log.inspect(kong.service.response.get_header("x-custom-header")) -- "bla" -- kong.log.inspect(kong.service.response.get_header("X-Another")) -- "foo bar" function response.get_header(name) check_phase(header_body_log) if type(name) ~= "string" then error("name must be a string", 2) end local header_value = response.get_headers()[name] if type(header_value) == "table" then return header_value[1] end return header_value end function response.get_raw_body() -- TODO: implement end function response.get_body() -- TODO: implement end return response end return { new = new, }
fix(pdk) prevent a memory leak with in 'service.response' module
fix(pdk) prevent a memory leak with in 'service.response' module Introduced in eb204989233b148397eb7751c1a58ed82123eaab, this index metamethod attachment for response headers tables maintains a references to itself. This was verified by increasing upvalues, functions, and table object counts increasing when using this API over time. The newer implementation is also more efficient and avoids creating closures at runtime. Fix #4143
Lua
apache-2.0
Kong/kong,Mashape/kong,Kong/kong,Kong/kong
e04db91800e2ff89aece41a737b73e0dbbf926b2
plugins/get.lua
plugins/get.lua
local function get_variables_hash(msg, global) if global then if not redis:get(msg.to.id .. ':gvariables') then return 'gvariables' end return false else if msg.to.type == 'channel' then return 'channel:' .. msg.to.id .. ':variables' end if msg.to.type == 'chat' then return 'chat:' .. msg.to.id .. ':variables' end if msg.to.type == 'user' then return 'user:' .. msg.from.id .. ':variables' end return false end end local function get_value(msg, var_name) var_name = var_name:gsub(' ', '_') if not redis:get(msg.to.id .. ':gvariables') then local hash = get_variables_hash(msg, true) if hash then local value = redis:hget(hash, var_name) if value then return value end end end local hash = get_variables_hash(msg, false) if hash then local value = redis:hget(hash, var_name) if value then return value end end end local function list_variables(msg, global) local hash = nil if global then hash = get_variables_hash(msg, true) else hash = get_variables_hash(msg, false) end if hash then local names = redis:hkeys(hash) local text = '' for i = 1, #names do text = text .. names[i]:gsub('_', ' ') .. '\n' end return text end end local function run(msg, matches) if (matches[1]:lower() == 'get' or matches[1]:lower() == 'getlist' or matches[1]:lower() == 'sasha lista') then return list_variables(msg, false) end if (matches[1]:lower() == 'getglobal' or matches[1]:lower() == 'getgloballist' or matches[1]:lower() == 'sasha lista globali') then return list_variables(msg, true) end if matches[1]:lower() == 'enableglobal' then redis:del(msg.to.id .. ':gvariables') end if matches[1]:lower() == 'disableglobal' then redis:set(msg.to.id .. ':gvariables', true) end end local function pre_process(msg, matches) if msg.text then if not string.match(msg.text, "^[#!/][Uu][Nn][Ss][Ee][Tt] ([^%s]+)") and not string.match(msg.text, "^[Uu][Nn][Ss][Ee][Tt][Tt][Aa] ([^%s]+)") and not string.match(msg.text, "^[Ss][Aa][Ss][Hh][Aa] [Uu][Nn][Ss][Ee][Tt][Tt][Aa] ([^%s]+)") then local vars = list_variables(msg) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local temp = word:lower() if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then local value = get_value(msg, word:lower()) if value then if not string.match(value, "^(.*)user%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)chat%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)channel%.(%d+)%.variables(.*)$") then -- if not media reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false) elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.jpg$") then -- if picture if io.popen('find ' .. value):read("*all") ~= '' then send_photo(get_receiver(msg), value, ok_cb, false) end elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.ogg$") then -- if audio if io.popen('find ' .. value):read("*all") ~= '' then send_audio(get_receiver(msg), value, ok_cb, false) end end end end end end end end return msg end return { description = "GET", patterns = { "^[#!/]([Gg][Ee][Tt][Ll][Ii][Ss][Tt])$", "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll][Ll][Ii][Ss][Tt])$", "^[#!/]([Ee][Nn][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", "^[#!/]([Dd][Ii][Ss][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", -- getlist "^[#!/]([Gg][Ee][Tt])$", "^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa])$", -- getgloballist "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll])$", "^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa] [Gg][Ll][Oo][Bb][Aa][Ll][Ii])$", }, pre_process = pre_process, run = run, min_rank = 0 -- usage -- (#getlist|#get|sasha lista) -- (#getgloballist|#getglobal|sasha lista globali) -- OWNER -- #enableglobal -- #disableglobal }
local function get_variables_hash(msg, global) if global then if not redis:get(msg.to.id .. ':gvariables') then return 'gvariables' end return false else if msg.to.type == 'channel' then return 'channel:' .. msg.to.id .. ':variables' end if msg.to.type == 'chat' then return 'chat:' .. msg.to.id .. ':variables' end if msg.to.type == 'user' then return 'user:' .. msg.from.id .. ':variables' end return false end end local function get_value(msg, var_name) var_name = var_name:gsub(' ', '_') if not redis:get(msg.to.id .. ':gvariables') then local hash = get_variables_hash(msg, true) if hash then local value = redis:hget(hash, var_name) if value then return value end end end local hash = get_variables_hash(msg, false) if hash then local value = redis:hget(hash, var_name) if value then return value end end end local function list_variables(msg, global) local hash = nil if global then hash = get_variables_hash(msg, true) else hash = get_variables_hash(msg, false) end if hash then local names = redis:hkeys(hash) local text = '' for i = 1, #names do text = text .. names[i]:gsub('_', ' ') .. '\n' end return text end end local function run(msg, matches) if (matches[1]:lower() == 'get' or matches[1]:lower() == 'getlist' or matches[1]:lower() == 'sasha lista') then return list_variables(msg, false) end if (matches[1]:lower() == 'getglobal' or matches[1]:lower() == 'getgloballist' or matches[1]:lower() == 'sasha lista globali') then return list_variables(msg, true) end if matches[1]:lower() == 'enableglobal' then redis:del(msg.to.id .. ':gvariables') end if matches[1]:lower() == 'disableglobal' then redis:set(msg.to.id .. ':gvariables', true) end end local function pre_process(msg, matches) if msg.text then if not string.match(msg.text, "^[#!/][Uu][Nn][Ss][Ee][Tt] ([^%s]+)") and not string.match(msg.text, "^[Uu][Nn][Ss][Ee][Tt][Tt][Aa] ([^%s]+)") and not string.match(msg.text, "^[Ss][Aa][Ss][Hh][Aa] [Uu][Nn][Ss][Ee][Tt][Tt][Aa] ([^%s]+)") and not string.match(msg.text, "^[Uu][Nn][Ss][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll] ([^%s]+)") then local vars = list_variables(msg, true) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local temp = word:lower() if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then local value = get_value(msg, word:lower()) if value then reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false) end end end end local vars = list_variables(msg, false) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local temp = word:lower() if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then local value = get_value(msg, word:lower()) if value then if not string.match(value, "^(.*)user%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)chat%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)channel%.(%d+)%.variables(.*)$") then -- if not media reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false) elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.jpg$") then -- if picture if io.popen('find ' .. value):read("*all") ~= '' then send_photo(get_receiver(msg), value, ok_cb, false) end elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.ogg$") then -- if audio if io.popen('find ' .. value):read("*all") ~= '' then send_audio(get_receiver(msg), value, ok_cb, false) end end end end end end end end return msg end return { description = "GET", patterns = { "^[#!/]([Gg][Ee][Tt][Ll][Ii][Ss][Tt])$", "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll][Ll][Ii][Ss][Tt])$", "^[#!/]([Ee][Nn][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", "^[#!/]([Dd][Ii][Ss][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", -- getlist "^[#!/]([Gg][Ee][Tt])$", "^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa])$", -- getgloballist "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll])$", "^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa] [Gg][Ll][Oo][Bb][Aa][Ll][Ii])$", }, pre_process = pre_process, run = run, min_rank = 0 -- usage -- (#getlist|#get|sasha lista) -- (#getgloballist|#getglobal|sasha lista globali) -- OWNER -- #enableglobal -- #disableglobal }
fix pre_process for global gets
fix pre_process for global gets
Lua
agpl-3.0
xsolinsx/AISasha
19496b9f53bc4e111ae2a1415d5998628eb0939e
usr/product/sigma-firmware/rules.lua
usr/product/sigma-firmware/rules.lua
-- Sigma rules -- base define_rule { 'ast-files' } define_rule { 'cmake-modules' } define_rule { 'linux' } define_rule { 'xsdk' } define_rule { 'ucode', 'target', { 'install' } } -- host define_rule { 'utils', 'host' } define_rule { 'karaoke-player', 'host', requires = { 'chicken-eggs', 'ffmpeg', 'libuv', }, { 'configure', { 'astindex', 'unpack' }, } } define_rule { 'astindex', { 'unpack', { 'karaoke-player', 'unpack' } } } -- kernel local kernel_rule_template = { config = 'target', { 'configure', { 'kernel', 'compile', 'target' } } } local function define_kernel_rule(r) r.template = kernel_rule_template define_rule(r) end define_rule { 'kernel', 'target', { 'configure', { 'linux', 'unpack' }, }, { 'install', -- for genzbf and other utils { 'rootfs', 'compile', 'target' } }, { 'image' } } define_kernel_rule { 'loop-aes' } define_kernel_rule { 'ralink' } -- rootfs define_rule { 'rootfs', 'target', requires = { 'busybox', 'gnupg', 'loop-aes', 'mrua', 'ntpclient', 'ralink', 'util-linux', 'utils', }, { 'configure', { 'ast-files', 'unpack' }, { 'xsdk', 'unpack' }, { 'toolchain', 'install', 'target' }, }, { 'compile' }, { 'install' } } define_rule { 'mrua', 'target', { 'compile', { 'kernel', 'compile', 'target' } }, { 'install' }, } define_rule { 'busybox', 'target', install = { root = '$jagen_sdk_initfs_dir', prefix = '' }, { 'patch', { 'ast-files', 'unpack' } } } define_rule { 'utils', 'target', requires = { 'gpgme' }, { 'configure', { 'dbus', 'install', 'target' } } } define_rule { 'ezboot', 'target', requires = { 'rootfs' } } -- firmware local firmware_rule_template = { config = 'target', install = { prefix = '$jagen_firmware_install_prefix' }, { 'install', { 'firmware', 'unpack' } } } local function define_firmware_rule(r) r.template = firmware_rule_template define_rule(r) end define_rule { 'firmware', 'target', pass_template = firmware_rule_template, requires = { 'ezboot', 'karaoke-player', 'kernel', 'mrua', 'rsync', 'ucode', 'wpa_supplicant', }, install = { prefix = '$jagen_firmware_install_prefix' }, { 'compile' }, { 'install' } } define_firmware_rule { 'karaoke-player', requires = { 'chicken-eggs', 'connman', 'dbus', 'ffmpeg', 'freetype', 'libass', 'libpng', 'libuv', 'mrua', 'soundtouch', 'sqlite', }, { 'configure', { 'astindex', 'unpack' }, { 'chicken-eggs', 'install', 'host' } } } -- additional packages should come last to apply all templates defined here require 'chicken'
-- Sigma rules -- base define_rule { 'ast-files' } define_rule { 'cmake-modules' } define_rule { 'linux' } define_rule { 'xsdk' } define_rule { 'ucode', 'target', { 'install' } } -- host define_rule { 'utils', 'host' } define_rule { 'karaoke-player', 'host', requires = { 'chicken-eggs', 'ffmpeg', 'libuv', }, { 'configure', { 'astindex', 'unpack' }, } } define_rule { 'astindex', { 'unpack', { 'karaoke-player', 'unpack' } } } -- kernel local kernel_rule_template = { config = 'target', { 'configure', { 'kernel', 'compile', 'target' } }, { 'install', { 'kernel', 'install', 'target' } } } local function define_kernel_rule(r) r.template = kernel_rule_template define_rule(r) end define_rule { 'kernel', 'target', { 'configure', { 'linux', 'unpack' }, }, { 'install', -- for genzbf and other utils { 'rootfs', 'compile', 'target' } }, { 'image', requires = { 'rootfs' } } } define_kernel_rule { 'loop-aes' } define_kernel_rule { 'ralink' } -- rootfs define_rule { 'rootfs', 'target', requires = { 'busybox', 'gnupg', 'mrua', 'ntpclient', 'util-linux', 'utils', }, { 'configure', { 'ast-files', 'unpack' }, { 'xsdk', 'unpack' }, { 'toolchain', 'install', 'target' }, }, { 'compile' }, { 'install', requires = { 'loop-aes', 'ralink', } } } define_rule { 'mrua', 'target', { 'compile', { 'kernel', 'compile', 'target' } }, { 'install' }, } define_rule { 'busybox', 'target', install = { root = '$jagen_sdk_initfs_dir', prefix = '' }, { 'patch', { 'ast-files', 'unpack' } } } define_rule { 'utils', 'target', requires = { 'gpgme' }, { 'configure', { 'dbus', 'install', 'target' } } } define_rule { 'ezboot', 'target', requires = { 'rootfs' } } -- firmware local firmware_rule_template = { config = 'target', install = { prefix = '$jagen_firmware_install_prefix' }, { 'install', { 'firmware', 'unpack' } } } local function define_firmware_rule(r) r.template = firmware_rule_template define_rule(r) end define_rule { 'firmware', 'target', pass_template = firmware_rule_template, requires = { 'ezboot', 'karaoke-player', 'kernel', 'mrua', 'rsync', 'ucode', 'wpa_supplicant', }, install = { prefix = '$jagen_firmware_install_prefix' }, { 'compile' }, { 'install' } } define_firmware_rule { 'karaoke-player', requires = { 'chicken-eggs', 'connman', 'dbus', 'ffmpeg', 'freetype', 'libass', 'libpng', 'libuv', 'mrua', 'soundtouch', 'sqlite', }, { 'configure', { 'astindex', 'unpack' }, { 'chicken-eggs', 'install', 'host' } } } -- additional packages should come last to apply all templates defined here require 'chicken'
sigma: fixing dependencies for packages installing modules
sigma: fixing dependencies for packages installing modules
Lua
mit
bazurbat/jagen
46f57e695d0f5b3f9a20300cd4c648d052a7999e
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo.lua
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo.lua
--[[ netdiscover_devinfo - SIP Device Information (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.netdiscover_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("l_d_d_nd_netdiscover_to_devinfo_descr")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.netdiscover_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", false, debug) luci.controller.luci_diag.netdiscover_common.action_links(m, false) return m
--[[ netdiscover_devinfo - SIP Device Information (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.netdiscover_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scans for devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.netdiscover_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", false, debug) luci.controller.luci_diag.netdiscover_common.action_links(m, false) return m
applications/luci-diag-devinfo: fix lost description in netdiscover_devinfo.lua, patch by "BasicXP" <[email protected]>
applications/luci-diag-devinfo: fix lost description in netdiscover_devinfo.lua, patch by "BasicXP" <[email protected]> git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9051 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
zwhfly/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,ch3n2k/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,8devices/carambola2-luci,ch3n2k/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,ch3n2k/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,vhpham80/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,Canaan-Creative/luci,ch3n2k/luci,8devices/carambola2-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,phi-psi/luci,ch3n2k/luci,gwlim/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,8devices/carambola2-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,vhpham80/luci,yeewang/openwrt-luci,phi-psi/luci,ch3n2k/luci,freifunk-gluon/luci,ch3n2k/luci,zwhfly/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,gwlim/luci,gwlim/luci,gwlim/luci
b9efd615b614e7bdc30212649c1174bc75e07906
game/scripts/vscripts/modules/structures/structures.lua
game/scripts/vscripts/modules/structures/structures.lua
Structures = Structures or class({}) ModuleRequire(..., "data") ModuleRequire(..., "shops") ModuleLinkLuaModifier(..., "modifier_arena_healer") ModuleLinkLuaModifier(..., "modifier_arena_courier") ModuleLinkLuaModifier(..., "modifier_fountain_aura_arena") ModuleLinkLuaModifier(..., "modifier_fountain_aura_invulnerability", "modifier_fountain_aura_arena") ModuleLinkLuaModifier(..., "modifier_fountain_aura_enemy") function Structures:AddHealers() for _,v in ipairs(Entities:FindAllByClassname("npc_dota_healer")) do local model = TEAM_HEALER_MODELS[v:GetTeamNumber()] v:SetOriginalModel(model.mdl) v:SetModel(model.mdl) if model.color then v:SetRenderColor(unpack(model.color)) end v:RemoveModifierByName("modifier_invulnerable") v:AddNewModifier(v, nil, "modifier_arena_healer", nil) end end function Structures:GiveCourier(hero) local pid = hero:GetPlayerID() local tn = hero:GetTeamNumber() local cour_item = hero:AddItem(CreateItem("item_courier", hero, hero)) TEAMS_COURIERS[hero:GetTeamNumber()] = true Timers:CreateTimer(0.03, function() for _,courier in ipairs(Entities:FindAllByClassname("npc_dota_courier")) do local owner = courier:GetOwner() if IsValidEntity(owner) and owner:GetPlayerID() == pid then courier:SetOwner(nil) courier:UpgradeToFlyingCourier() courier:AddNewModifier(courier, nil, "modifier_arena_courier", nil) courier:RemoveAbility("courier_burst") TEAMS_COURIERS[tn] = courier end end end) end
Structures = Structures or class({}) ModuleRequire(..., "data") ModuleRequire(..., "shops") ModuleLinkLuaModifier(..., "modifier_arena_healer") ModuleLinkLuaModifier(..., "modifier_arena_courier") ModuleLinkLuaModifier(..., "modifier_fountain_aura_arena") ModuleLinkLuaModifier(..., "modifier_fountain_aura_invulnerability", "modifier_fountain_aura_arena") ModuleLinkLuaModifier(..., "modifier_fountain_aura_enemy") function Structures:AddHealers() for _,v in ipairs(Entities:FindAllByClassname("npc_dota_healer")) do local model = TEAM_HEALER_MODELS[v:GetTeamNumber()] v:SetOriginalModel(model.mdl) v:SetModel(model.mdl) if model.color then v:SetRenderColor(unpack(model.color)) end v:RemoveModifierByName("modifier_invulnerable") v:AddNewModifier(v, nil, "modifier_arena_healer", nil) end end function Structures:GiveCourier(hero) local pid = hero:GetPlayerID() local tn = hero:GetTeamNumber() local cour_item = hero:AddItem(CreateItem("item_courier", hero, hero)) TEAMS_COURIERS[hero:GetTeamNumber()] = true Timers:CreateTimer(0.03, function() for _,courier in ipairs(Entities:FindAllByClassname("npc_dota_courier")) do local owner = courier:GetOwner() if IsValidEntity(owner) and owner:GetPlayerID() == pid then courier:SetOwner(nil) courier:UpgradeToFlyingCourier() courier:AddNewModifier(courier, nil, "modifier_arena_courier", nil) TEAMS_COURIERS[tn] = courier end end end) end
fix(structures): no longer removing courier_burst ability, which was removed in 7.07
fix(structures): no longer removing courier_burst ability, which was removed in 7.07
Lua
mit
ark120202/aabs
e999322bfd207896de7e70b874062395cbea73c8
Resources/Scripts/Modules/PilotAI.lua
Resources/Scripts/Modules/PilotAI.lua
--import('Math') --import('GlobalVars') function Think(object) if CanThink(object.base.attributes) then local target = object.ai.objectives.target or object.ai.objectives.dest local dist if target ~= nil then dist = hypot2(object.physics.position, target.physics.position) if object.base.attributes.isGuided == true then object.ai.mode = "goto" elseif dist < 350 and target.ai.owner ~= object.ai.owner and target.base.attributes.hated == true then object.ai.mode = "engage" elseif dist > 200 and object.ai.mode == "wait" then object.ai.mode = "goto" elseif dist < 150 and object.ai.mode == "goto" then object.ai.mode = "wait" end else object.ai.mode = "wait" end if object.ai.mode ~= "engage" then object.control.beam = false object.control.pulse = false object.control.special = false end if object.ai.mode == "wait" then object.control.accel = false object.control.decel = true object.control.left = false object.control.right = false elseif object.ai.mode == "goto" then object.control.accel = true object.control.decel = false TurnToward(object,target) elseif object.ai.mode == "evade" then TurnAway(object, target) elseif object.ai.mode == "engage" then if target ~= nil then TurnToward(object, target) if dist > 200 then object.control.accel = true object.control.decel = false else object.control.accel = false object.control.decel = true end else object.control.accel = true object.control.decel = false end object.control.beam = true object.control.pulse = true object.control.special = true end if object.ai.mode == "goto" then if dist >= math.sqrt(object.base.warpOutDistance) * 1.1 or target.control.warp then object.control.warp = true else object.control.warp = false end end else object.control.accel = true end end function CanThink(attr) return attr.canEngange or attr.canEvade or attr.canAcceptDestination end function TurnAway(object, target) local ang = find_angle(target.physics.position,object.physics.position) - object.physics.angle ang = radian_range(ang) if ang <= 0.95 * math.pi then object.control.left = false object.control.right = true elseif ang >= 1.05 * math.pi then object.control.left = true object.control.right = false else object.control.left = false object.control.right = false end end function TurnToward(object, target) local ang = AimFixed(object.physics,target.physics, hypot1(object.physics.velocity)) - object.physics.angle ang = radian_range(ang) if math.abs(ang-math.pi) >= math.pi * 0.95 then object.control.left = false object.control.right = false elseif ang <= math.pi * 0.95 then object.control.left = true object.control.right = false else object.control.left = false object.control.right = true end end function AimFixed(parent, target, bulletVel) --Grrrr if getmetatable(target.position) == nil then return parent.angle end local distance = hypot2(parent.position,target.position) local time = distance/bulletVel local initialOffset = target.position - parent.position local velocityDiff = target.velocity - parent.velocity local finalOffset = initialOffset + velocityDiff * time local absAngle = math.atan2(finalOffset.y,finalOffset.x) return absAngle end --Used to calculate absolute angle at which to fire the turret. function AimTurret(gun, target, bulletVel) local gPos = gun.position local tPos = target.position local rPos = tPos - gPos local rVel = target.velocity - gun.velocity local A = -bulletVel^2 + rVel * rVel local B = 2 * (rPos * rVel) local C = rPos * rPos --Assumes bullet is faster than target --use -b + math.sqrt(... --if target is faster local t = (-B - math.sqrt(B^2 - 4 * A * C))/(2*A) local slope = rPos + rVel * t local theta = math.atan2(slope.y, slope.x) return theta end
--import('Math') --import('GlobalVars') function Think(object) if CanThink(object.base.attributes) then local target = object.ai.objectives.target or object.ai.objectives.dest local dist if target ~= nil then dist = hypot2(object.physics.position, target.physics.position) if object.base.attributes.isGuided == true then object.ai.mode = "goto" elseif dist < 350 and target.ai.owner ~= object.ai.owner and target.base.attributes.hated == true then object.ai.mode = "engage" elseif dist > 200 and object.ai.mode == "wait" then object.ai.mode = "goto" elseif dist < 150 and object.ai.mode == "goto" then object.ai.mode = "wait" end else object.ai.mode = "wait" end if object.ai.mode ~= "engage" then object.control.beam = false object.control.pulse = false object.control.special = false end if object.ai.mode == "wait" then object.control.accel = false object.control.decel = true object.control.left = false object.control.right = false elseif object.ai.mode == "goto" then object.control.accel = true object.control.decel = false TurnToward(object,target) elseif object.ai.mode == "evade" then TurnAway(object, target) elseif object.ai.mode == "engage" then if target ~= nil then TurnToward(object, target) if dist > 200 then object.control.accel = true object.control.decel = false else object.control.accel = false object.control.decel = true end else object.control.accel = true object.control.decel = false end object.control.beam = true object.control.pulse = true object.control.special = true end if object.ai.mode == "goto" then if dist >= math.sqrt(object.base.warpOutDistance) * 1.1 or target.control.warp then object.control.warp = true else object.control.warp = false end end else object.control.accel = true end end function CanThink(attr) return attr.canEngange or attr.canEvade or attr.canAcceptDestination end function TurnAway(object, target) local ang = find_angle(target.physics.position,object.physics.position) - object.physics.angle ang = radian_range(ang) if ang <= 0.95 * math.pi then object.control.left = false object.control.right = true elseif ang >= 1.05 * math.pi then object.control.left = true object.control.right = false else object.control.left = false object.control.right = false end end function TurnToward(object, target) local ang = AimFixed(object.physics,target.physics, hypot1(object.physics.velocity)) - object.physics.angle ang = radian_range(ang) if math.abs(ang-math.pi) >= math.pi * 0.95 then object.control.left = false object.control.right = false elseif ang <= math.pi * 0.95 then object.control.left = true object.control.right = false else object.control.left = false object.control.right = true end end function AimFixed(parent, target, bulletVel) --Grrrr if getmetatable(target.position) == nil then return parent.angle end local distance = hypot2(parent.position,target.position) local time = distance/bulletVel local initialOffset = target.position - parent.position local velocityDiff = target.velocity - parent.velocity local finalOffset = initialOffset + velocityDiff * time local absAngle = math.atan2(finalOffset.y,finalOffset.x) return absAngle end --Used to calculate absolute angle at which to fire the turret. function AimTurret(gun, target, bulletVel) local gPos = gun.position local tPos = target.position local rPos = tPos - gPos local rVel = target.velocity - gun.velocity local A = -bulletVel^2 + rVel * rVel local B = 2 * (rPos * rVel) local C = rPos * rPos --Assumes bullet is faster than target --use -b + math.sqrt(... --if target is faster local t = (-B - math.sqrt(B^2 - 4 * A * C))/(2*A) local slope = rPos + rVel * t local theta = math.atan2(slope.y, slope.x) return theta end
Fixed an unindented code block.
Fixed an unindented code block. Signed-off-by: Scott McClaugherty <[email protected]>
Lua
mit
adam000/xsera,prophile/xsera,prophile/xsera,adam000/xsera,prophile/xsera,adam000/xsera,prophile/xsera,prophile/xsera,adam000/xsera