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
a3c3f884bdd77c6e7c7dc71e0854a7e75a885fd3
item/id_9_saw.lua
item/id_9_saw.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/>. ]] -- UPDATE items SET itm_script='item.id_9_saw' WHERE itm_id IN (9); local sawing = require("craft.intermediate.sawing") local metal = require("item.general.metal") local M = {} M.LookAtItem = metal.LookAtItem function M.UseItem(User, SourceItem, ltstate) local _, _, change, willpower, essence, intelligence = string.find(User.lastSpokenText,"(%a+) (%d+) (%d+) (%d+)") if change == "attributes" then User:setAttrib("willpower", tonumber(willpower)) User:setAttrib("essence", tonumber(essence)) User:setAttrib("intelligence", tonumber(intelligence)) User:inform("Set willpower, essence, intelligence to") User:inform(User:increaseAttrib("willpower", 0)) User:inform(User:increaseAttrib("essence", 0)) User:inform(User:increaseAttrib("intelligence", 0)) elseif change == "class" then User:setMagicType(tonumber(willpower)) User:inform("class is") User:inform(User:getMagicType()) end sawing.sawing:showDialog(User, SourceItem) 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/>. ]] -- UPDATE items SET itm_script='item.id_9_saw' WHERE itm_id IN (9); local sawing = require("craft.intermediate.sawing") local metal = require("item.general.metal") local M = {} M.LookAtItem = metal.LookAtItem function M.UseItem(User, SourceItem, ltstate) local _, _, change, willpower, essence, intelligence = string.find(User.lastSpokenText,"(%a+) (%d+) (%d+) (%d+)") if change == "attributes" then User:setAttrib("willpower", tonumber(willpower)) User:setAttrib("essence", tonumber(essence)) User:setAttrib("intelligence", tonumber(intelligence)) User:inform("Set willpower, essence, intelligence to") User:inform("" .. User:increaseAttrib("willpower", 0)) User:inform("" .. User:increaseAttrib("essence", 0)) User:inform("" .. User:increaseAttrib("intelligence", 0)) elseif change == "class" then User:inform("change class") User:setMagicType(tonumber(willpower)) User:inform("class is") User:inform(User:getMagicType()) end sawing.sawing:showDialog(User, SourceItem) end return M
Fix testing function
Fix testing function
Lua
agpl-3.0
KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
c0745c508826c3feb49b1a35d7a9a9ebdfe11ba5
kong/cmd/quit.lua
kong/cmd/quit.lua
local nginx_signals = require "kong.cmd.utils.nginx_signals" local conf_loader = require "kong.conf_loader" local pl_path = require "pl.path" local kill = require "kong.cmd.utils.kill" local log = require "kong.cmd.utils.log" local function execute(args) log.disable() -- retrieve default prefix or use given one local default_conf = assert(conf_loader(nil, { prefix = args.prefix })) log.enable() assert(pl_path.exists(default_conf.prefix), "no such prefix: " .. default_conf.prefix) -- load <PREFIX>/kong.conf containing running node's config local conf = assert(conf_loader(default_conf.kong_env)) -- try graceful shutdown (QUIT) assert(nginx_signals.quit(conf)) log.verbose("waiting for nginx to finish processing requests") local tstart = ngx.time() local texp, running = tstart + math.max(args.timeout, 1) -- min 1s timeout repeat ngx.sleep(0.2) running = kill.is_running(conf.nginx_pid) until not running or ngx.time() >= texp if running then log.verbose("nginx is still running at %s, forcing shutdown", conf.prefix) assert(nginx_signals.stop(conf)) end log("Kong stopped (gracefully)") end local lapp = [[ Usage: kong quit [OPTIONS] Gracefully quit a running Kong node (Nginx and other configured services) in given prefix directory. This command sends a SIGQUIT signal to Nginx, meaning all requests will finish processing before shutting down. If the timeout delay is reached, the node will be forcefully stopped (SIGTERM). Options: -p,--prefix (optional string) prefix Kong is running at -t,--timeout (default 10) timeout before forced shutdown ]] return { lapp = lapp, execute = execute }
local nginx_signals = require "kong.cmd.utils.nginx_signals" local conf_loader = require "kong.conf_loader" local pl_path = require "pl.path" local kill = require "kong.cmd.utils.kill" local log = require "kong.cmd.utils.log" local function execute(args) log.disable() -- retrieve default prefix or use given one local default_conf = assert(conf_loader(nil, { prefix = args.prefix })) log.enable() assert(pl_path.exists(default_conf.prefix), "no such prefix: " .. default_conf.prefix) -- load <PREFIX>/kong.conf containing running node's config local conf = assert(conf_loader(default_conf.kong_env)) -- try graceful shutdown (QUIT) assert(nginx_signals.quit(conf)) log.verbose("waiting for nginx to finish processing requests") local tstart = ngx.time() local texp, running = tstart + math.max(args.timeout, 1) -- min 1s timeout repeat ngx.sleep(0.2) running = kill.is_running(conf.nginx_pid) until not running or ngx.time() >= texp if running then log.verbose("nginx is still running at %s, forcing shutdown", conf.prefix) assert(nginx_signals.stop(conf)) log("Timeout, Kong stopped forcefully") return end log("Kong stopped (gracefully)") end local lapp = [[ Usage: kong quit [OPTIONS] Gracefully quit a running Kong node (Nginx and other configured services) in given prefix directory. This command sends a SIGQUIT signal to Nginx, meaning all requests will finish processing before shutting down. If the timeout delay is reached, the node will be forcefully stopped (SIGTERM). Options: -p,--prefix (optional string) prefix Kong is running at -t,--timeout (default 10) timeout before forced shutdown ]] return { lapp = lapp, execute = execute }
fix(cli) log forceful shutdown message upon SIGQUIT timeout
fix(cli) log forceful shutdown message upon SIGQUIT timeout The CLI `quit` command would even on a forceful exit still print a 'graceful shutdown' message. From #3061
Lua
apache-2.0
Kong/kong,jebenexer/kong,Kong/kong,Kong/kong,Mashape/kong
1a8ead3db02a88c5527f15ef878288b6d82c0811
mods/BeardLib-Editor/EditorCore.lua
mods/BeardLib-Editor/EditorCore.lua
if not _G.BeardLibEditor then _G.BeardLibEditor = ModCore:new(ModPath .. "mod_config.xml") local self = BeardLibEditor self.HooksDirectory = self.ModPath .. "Hooks/" self.ClassDirectory = self.ModPath .. "Classes/" self.managers = {} self._replace_script_data = {} self.DBPaths = {} self.DBEntries = {} self.classes = { "EditorParts/ElementEditor.lua", "EditorParts/UnitEditor.lua", "EditorParts/GameOptions.lua", "EditorParts/SaveOptions.lua", "EditorParts/EditorWidgets.lua", "EditorParts/SpawnSearch.lua", "EnvironmentEditorManager.lua", "EnvironmentEditorHandler.lua", "ScriptDataConverterManager.lua", "MapEditor.lua", "OptionCallbacks.lua" } self.hook_files = { ["core/lib/managers/mission/coremissionmanager"] = "Coremissionmanager.lua", ["core/lib/utils/dev/editor/coreworlddefinition"] = "Coreworlddefinition.lua", ["lib/setups/gamesetup"] = "Gamesetup.lua", ["lib/managers/navigationmanager"] = "Navigationmanager.lua", ["lib/managers/navfieldbuilder"] = "Navfieldbuilder.lua" } end function BeardLibEditor:_init() self:LoadClasses() self:init_modules() if not PackageManager:loaded("core/packages/editor") then PackageManager:load("core/packages/editor") end self.managers.EnvironmentEditor = EnvironmentEditorManager:new() self.managers.ScriptDataConveter = ScriptDataConveterManager:new() self:LoadHashlist() end function BeardLibEditor:LoadClasses() for _, clss in pairs(self.classes) do dofile(self.ClassDirectory .. clss) end end function BeardLibEditor:LoadHashlist() local file = DB:open("idstring_lookup", "idstring_lookup") self:log("Loading Hashlist") local function AddPathEntry(line, typ) local path_split = string.split(line, "/") local curr_tbl = self.DBEntries local filename = table.remove(path_split) for _, part in pairs(path_split) do curr_tbl[part] = curr_tbl[part] or {} curr_tbl = curr_tbl[part] end table.insert(curr_tbl, { path = line, name = filename, file_type = typ }) end local types = clone(BeardLib.script_data_types) table.insert(types, "unit") if file ~= nil then --Iterate through each string which contains _ or /, which should include all the filepaths in the idstring_lookup for line in string.gmatch(file:read(), "[%w_/]+%z") do --Remove the Zero byte at the end of the path line = string.sub(line, 1, #line - 1) for _, typ in pairs(types) do self.DBPaths[typ] = self.DBPaths[typ] or {} if DB:has(typ, line) then table.insert(self.DBPaths[typ], line) AddPathEntry(line, typ) --I wish I could break so we don't have to iterate more than needed, but some files exist with the same name but a different type --break end end end file:close() end for typ, filetbl in pairs(self.DBPaths) do self:log(typ .. " Count: " .. #filetbl) end self:log("Hashlist Loaded") end if RequiredScript then local requiredScript = RequiredScript:lower() if BeardLibEditor.hook_files[requiredScript] then dofile( BeardLibEditor.HooksDirectory .. BeardLibEditor.hook_files[requiredScript] ) end end function BeardLibEditor:update(t, dt) for _, manager in pairs(self.managers) do if manager.update then manager:update(t, dt) end end end function BeardLibEditor:paused_update(t, dt) for _, manager in pairs(self.managers) do if manager.paused_update then manager:paused_update(t, dt) end end end if Hooks then Hooks:Add("MenuUpdate", "BeardLibEditorMenuUpdate", function( t, dt ) BeardLibEditor:update(t, dt) end) Hooks:Add("GameSetupUpdate", "BeardLibEditorGameSetupUpdate", function( t, dt ) BeardLibEditor:update(t, dt) end) Hooks:Add("GameSetupPauseUpdate", "BeardLibEditorGameSetupPausedUpdate", function(t, dt) BeardLibEditor:paused_update(t, dt) end) Hooks:Add("LocalizationManagerPostInit", "BeardLibEditorLocalization", function(loc) LocalizationManager:add_localized_strings({ ["BeardLibEditorEnvMenu"] = "Environment Mod Menu", ["BeardLibEditorEnvMenuHelp"] = "Modify the params of the current Environment", ["BeardLibEditorSaveEnvTable_title"] = "Save Current modifications", ["BeardLibEditorResetEnv_title"] = "Reset Values", ["BeardLibEditorScriptDataMenu_title"] = "ScriptData Converter" }) end) Hooks:Add("MenuManagerSetupCustomMenus", "Base_SetupBeardLibEditorMenu", function( menu_manager, nodes ) --I'm going to leave this here, but I really don't like it being here BeardLibEditor.managers.MapEditor = MapEditor:new() BeardLibEditor.managers.Dialog = MenuDialog:new() local main_node = MenuHelperPlus:GetNode(nil, BeardLib.MainMenu) BeardLibEditor.managers.EnvironmentEditor:BuildNode(main_node) BeardLibEditor.managers.ScriptDataConveter:BuildNode(main_node) end) function BeardLibEditor:ProcessScriptData(data, path, extension, name) for _, sub_data in ipairs(data) do if sub_data._meta == "param" then local next_data_path = name and name .. "/" .. sub_data.key or sub_data.key local next_data_path_key = next_data_path:key() BeardLibEditor.managers.EnvironmentEditor:AddHandlerValue(path:key(), next_data_path_key, sub_data.value, next_data_path) else local next_data_path = name and name .. "/" .. sub_data._meta or sub_data._meta self:ProcessScriptData(sub_data, path, extension, next_data_path) end end end Hooks:Add("BeardLibPreProcessScriptData", "BeardLibEditorLoadEnvParams", function(PackManager, filepath, extension, data) if extension ~= Idstring("environment") then return end if not data or (data and not data.data) then return end BeardLibEditor:ProcessScriptData(data.data, filepath, extension) end) end if not BeardLibEditor.setup then BeardLibEditor:_init() BeardLibEditor.setup = true end
if not _G.BeardLibEditor then _G.BeardLibEditor = ModCore:new(ModPath .. "mod_config.xml") local self = BeardLibEditor self.HooksDirectory = self.ModPath .. "Hooks/" self.ClassDirectory = self.ModPath .. "Classes/" self.managers = {} self._replace_script_data = {} self.DBPaths = {} self.DBEntries = {} self.classes = { "EditorParts/ElementEditor.lua", "EditorParts/UnitEditor.lua", "EditorParts/GameOptions.lua", "EditorParts/SaveOptions.lua", "EditorParts/EditorWidgets.lua", "EditorParts/SpawnSearch.lua", "EnvironmentEditorManager.lua", "EnvironmentEditorHandler.lua", "ScriptDataConverterManager.lua", "MapEditor.lua", "OptionCallbacks.lua" } self.hook_files = { ["core/lib/managers/mission/coremissionmanager"] = "Coremissionmanager.lua", ["core/lib/utils/dev/editor/coreworlddefinition"] = "Coreworlddefinition.lua", ["lib/setups/gamesetup"] = "Gamesetup.lua", ["lib/managers/navigationmanager"] = "Navigationmanager.lua", ["lib/managers/navfieldbuilder"] = "Navfieldbuilder.lua" } end function BeardLibEditor:_init() self:LoadClasses() self:init_modules() if not PackageManager:loaded("core/packages/editor") then PackageManager:load("core/packages/editor") end self.managers.EnvironmentEditor = EnvironmentEditorManager:new() self.managers.ScriptDataConveter = ScriptDataConveterManager:new() self:LoadHashlist() end function BeardLibEditor:LoadClasses() for _, clss in pairs(self.classes) do dofile(self.ClassDirectory .. clss) end end function BeardLibEditor:LoadHashlist() if not DB:has("idstring_lookup", "idstring_lookup") then return end local file = DB:open("idstring_lookup", "idstring_lookup") self:log("Loading Hashlist") local function AddPathEntry(line, typ) local path_split = string.split(line, "/") local curr_tbl = self.DBEntries local filename = table.remove(path_split) for _, part in pairs(path_split) do curr_tbl[part] = curr_tbl[part] or {} curr_tbl = curr_tbl[part] end table.insert(curr_tbl, { path = line, name = filename, file_type = typ }) end local types = clone(BeardLib.script_data_types) table.insert(types, "unit") if file ~= nil then --Iterate through each string which contains _ or /, which should include all the filepaths in the idstring_lookup for line in string.gmatch(file:read(), "[%w_/]+%z") do --Remove the Zero byte at the end of the path line = string.sub(line, 1, #line - 1) for _, typ in pairs(types) do self.DBPaths[typ] = self.DBPaths[typ] or {} if DB:has(typ, line) then table.insert(self.DBPaths[typ], line) AddPathEntry(line, typ) --I wish I could break so we don't have to iterate more than needed, but some files exist with the same name but a different type --break end end end file:close() end for typ, filetbl in pairs(self.DBPaths) do self:log(typ .. " Count: " .. #filetbl) end self:log("Hashlist Loaded") end if RequiredScript then local requiredScript = RequiredScript:lower() if BeardLibEditor.hook_files[requiredScript] then dofile( BeardLibEditor.HooksDirectory .. BeardLibEditor.hook_files[requiredScript] ) end end function BeardLibEditor:update(t, dt) for _, manager in pairs(self.managers) do if manager.update then manager:update(t, dt) end end end function BeardLibEditor:paused_update(t, dt) for _, manager in pairs(self.managers) do if manager.paused_update then manager:paused_update(t, dt) end end end if Hooks then Hooks:Add("MenuUpdate", "BeardLibEditorMenuUpdate", function( t, dt ) BeardLibEditor:update(t, dt) end) Hooks:Add("GameSetupUpdate", "BeardLibEditorGameSetupUpdate", function( t, dt ) BeardLibEditor:update(t, dt) end) Hooks:Add("GameSetupPauseUpdate", "BeardLibEditorGameSetupPausedUpdate", function(t, dt) BeardLibEditor:paused_update(t, dt) end) Hooks:Add("LocalizationManagerPostInit", "BeardLibEditorLocalization", function(loc) LocalizationManager:add_localized_strings({ ["BeardLibEditorEnvMenu"] = "Environment Mod Menu", ["BeardLibEditorEnvMenuHelp"] = "Modify the params of the current Environment", ["BeardLibEditorSaveEnvTable_title"] = "Save Current modifications", ["BeardLibEditorResetEnv_title"] = "Reset Values", ["BeardLibEditorScriptDataMenu_title"] = "ScriptData Converter" }) end) Hooks:Add("MenuManagerSetupCustomMenus", "Base_SetupBeardLibEditorMenu", function( menu_manager, nodes ) --I'm going to leave this here, but I really don't like it being here BeardLibEditor.managers.MapEditor = MapEditor:new() BeardLibEditor.managers.Dialog = MenuDialog:new() local main_node = MenuHelperPlus:GetNode(nil, BeardLib.MainMenu) BeardLibEditor.managers.EnvironmentEditor:BuildNode(main_node) BeardLibEditor.managers.ScriptDataConveter:BuildNode(main_node) end) function BeardLibEditor:ProcessScriptData(data, path, extension, name) for _, sub_data in ipairs(data) do if sub_data._meta == "param" then local next_data_path = name and name .. "/" .. sub_data.key or sub_data.key local next_data_path_key = next_data_path:key() BeardLibEditor.managers.EnvironmentEditor:AddHandlerValue(path:key(), next_data_path_key, sub_data.value, next_data_path) else local next_data_path = name and name .. "/" .. sub_data._meta or sub_data._meta self:ProcessScriptData(sub_data, path, extension, next_data_path) end end end Hooks:Add("BeardLibPreProcessScriptData", "BeardLibEditorLoadEnvParams", function(PackManager, filepath, extension, data) if extension ~= Idstring("environment") then return end if not data or (data and not data.data) then return end BeardLibEditor:ProcessScriptData(data.data, filepath, extension) end) end if not BeardLibEditor.setup then BeardLibEditor:_init() BeardLibEditor.setup = true end
Fix crash due to missing hashlist
Fix crash due to missing hashlist
Lua
mit
simon-wh/PAYDAY-2-BeardLib-Editor
41045dab992ed26828916d21e889102ded4df1e4
frontend/device/kobo/powerd.lua
frontend/device/kobo/powerd.lua
local BasePowerD = require("device/generic/powerd") local KoboPowerD = BasePowerD:new{ fl_min = 0, fl_max = 100, flIntensity = 20, restore_settings = true, fl = nil, batt_capacity_file = "/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/capacity", is_charging_file = "/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/charge_now", battCapacity = nil, is_charging = nil, } function KoboPowerD:init() if self.device.hasFrontlight() then local kobolight = require("ffi/kobolight") local ok, light = pcall(kobolight.open) if ok then self.fl = light end end end function KoboPowerD:toggleFrontlight() if self.fl ~= nil then self.fl:toggle() end end function KoboPowerD:setIntensityHW() if self.fl ~= nil then self.fl:setBrightness(self.flIntensity) end end function KoboPowerD:setIntensitySW() if self.fl ~= nil then self.fl:restoreBrightness(self.flIntensity) end end function KoboPowerD:getCapacityHW() self.battCapacity = self:read_int_file(self.batt_capacity_file) return self.battCapacity end function KoboPowerD:isChargingHW() self.is_charging = self:read_int_file(self.is_charging_file) return self.is_charging == 1 end return KoboPowerD
local BasePowerD = require("device/generic/powerd") local KoboPowerD = BasePowerD:new{ fl_min = 0, fl_max = 100, flIntensity = 20, restore_settings = true, fl = nil, batt_capacity_file = "/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/capacity", is_charging_file = "/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/status", battCapacity = nil, is_charging = nil, } function KoboPowerD:init() if self.device.hasFrontlight() then local kobolight = require("ffi/kobolight") local ok, light = pcall(kobolight.open) if ok then self.fl = light end end end function KoboPowerD:toggleFrontlight() if self.fl ~= nil then self.fl:toggle() end end function KoboPowerD:setIntensityHW() if self.fl ~= nil then self.fl:setBrightness(self.flIntensity) end end function KoboPowerD:setIntensitySW() if self.fl ~= nil then self.fl:restoreBrightness(self.flIntensity) end end function KoboPowerD:getCapacityHW() self.battCapacity = self:read_int_file(self.batt_capacity_file) return self.battCapacity end function KoboPowerD:isChargingHW() self.is_charging = self:read_str_file(self.is_charging_file) == "Charging\n" return self.is_charging end return KoboPowerD
Fix charging detection for Kobo devices
Fix charging detection for Kobo devices I've tested this on a N905C. I assume this implementation never worked (since charge_now is supposed to show state of charge), but it would be useful to get a confirmation.
Lua
agpl-3.0
koreader/koreader,lgeek/koreader,Frenzie/koreader,Markismus/koreader,mihailim/koreader,koreader/koreader,robert00s/koreader,chrox/koreader,Hzj-jie/koreader,Frenzie/koreader,poire-z/koreader,frankyifei/koreader,ashhher3/koreader,poire-z/koreader,noname007/koreader,ashang/koreader,chihyang/koreader,NickSavage/koreader,pazos/koreader,mwoz123/koreader,NiLuJe/koreader,apletnev/koreader,houqp/koreader,NiLuJe/koreader
daac965de5a85233dd2c9e2097441be7969ca8c4
ffi/framebuffer_linux.lua
ffi/framebuffer_linux.lua
local ffi = require("ffi") local bit = require("bit") local BB = require("ffi/blitbuffer") require("ffi/linux_fb_h") require("ffi/posix_h") local framebuffer = { device_node = "/dev/fb0", fd = -1, fb_size = nil, data = nil, } --[[ The raw framebuffer memory is managed through Blitbuffer. When creating the Blitbuffer, we bind it to a framebuffer memory size of `vinfo.xres * finfo.line_length` assuming portrait mode by default. Here are couple interesting framebuffer attributes to watch out when porting to new devices: * vinfo.bits_per_pixel: Size of each pixel, for example, 16bits, 32bits, etc. * finfo.smem_len: Size of the actual framebuffer memory provided by the kernel. * finfo.line_length: Size of each row for the framebuffer. Usually, it would be close to `vinfo.xres_virtual * vinfo.bits_per_pixel / 8`. * vinfo.xres: Number of pixels in one row on physical screen, i.e. physical screen width * vinfo.yres: Number of pixels in one column on physical screen, i.e. physical screen height * vinfo.xres_virtual: Number of pixels in one row on scrollable virtual screen, for fb_pan_display. Usually `vinfo.xres_virtual` >= `vinfo.xres`. * vinfo.yres_virtual: Number of pixels in one column on scrollable virtual screen, for fb_pan_display. Usually `vinfo.yres_virtual` >= `vinfo.yres`. NOTE for Kobo: By definition, `finfo.smem_len` should always be larger than or equal to `vinfo.xres_virtual * vinfo.yres_virtual * vinfo.bits_per_pixel / 8`. However, turns out this is not the case on Kobo when the framebuffer is operating at 32bits mode. On Kobo Aura One, under 16bits mode, we got: finfo.line_length: 2816 finfo.smem_len: 10813440 vinfo.bits_per_pixel: 16 vinfo.xres: 1404 vinfo.yres: 1872 vinfo.xres_virtual: 1408 vinfo.yres_virtual: 3840 But under 32bits mode, we got: finfo.line_length: 5632 finfo.smem_len: 10813440 vinfo.bits_per_pixel: 32 vinfo.xres: 1404 vinfo.yres: 1872 vinfo.xres_virtual: 1408 vinfo.yres_virtual: 3840 The only settings that got changed are `finfo.line_length` and `vinfo.bits_per_pixel`. `finfo.smem_len` still remains at 10813440. --]] function framebuffer:init() local finfo = ffi.new("struct fb_fix_screeninfo") local vinfo = ffi.new("struct fb_var_screeninfo") self.fd = ffi.C.open(self.device_node, ffi.C.O_RDWR) assert(self.fd ~= -1, "cannot open framebuffer") -- Get fixed screen information assert(ffi.C.ioctl(self.fd, ffi.C.FBIOGET_FSCREENINFO, finfo) == 0, "cannot get screen info") assert(ffi.C.ioctl(self.fd, ffi.C.FBIOGET_VSCREENINFO, vinfo) == 0, "cannot get variable screen info") assert(finfo.type == ffi.C.FB_TYPE_PACKED_PIXELS, "video type not supported") assert(vinfo.xres_virtual > 0 and vinfo.yres_virtual > 0, "invalid framebuffer resolution") -- Classic eink framebuffer (Kindle 2, 3, DXG, 4) if ffi.string(finfo.id, 7) == "eink_fb" then self.fb_size = vinfo.xres_virtual * vinfo.yres_virtual * vinfo.bits_per_pixel / 8 -- Newer eink framebuffer (Kindle Touch, Paperwhite, Kobo) elseif ffi.string(finfo.id, 11) == "mxc_epdc_fb" then -- it seems that finfo.smem_len is unreliable on kobo -- Figure out the size of the screen in bytes self.fb_size = vinfo.xres_virtual * vinfo.yres_virtual * vinfo.bits_per_pixel / 8 -- Kobo hasn't updated smem_len when the depth was changed from 16 to 32 if vinfo.bits_per_pixel == 32 then self.fb_size = finfo.smem_len end -- PocketBook eink framebuffer seems to have no finfo.id elseif string.byte(ffi.string(finfo.id, 16), 1, 1) == 0 then -- finfo.line_length needs to be 16-bytes aligned finfo.line_length = bit.band(finfo.line_length * vinfo.bits_per_pixel / 8 + 15, bit.bnot(15)) self.fb_size = finfo.line_length * vinfo.yres_virtual else error("framebuffer model not supported"); end self.data = ffi.C.mmap(nil, self.fb_size, bit.bor(ffi.C.PROT_READ, ffi.C.PROT_WRITE), ffi.C.MAP_SHARED, self.fd, 0) assert(self.data ~= ffi.C.MAP_FAILED, "can not mmap() framebuffer") if vinfo.bits_per_pixel == 32 then self.bb = BB.new(vinfo.xres, vinfo.yres, BB.TYPE_BBRGB32, self.data, finfo.line_length) elseif vinfo.bits_per_pixel == 16 then self.bb = BB.new(vinfo.xres, vinfo.yres, BB.TYPE_BBRGB16, self.data, finfo.line_length) elseif vinfo.bits_per_pixel == 8 then self.bb = BB.new(vinfo.xres, vinfo.yres, BB.TYPE_BB8, self.data, finfo.line_length) elseif vinfo.bits_per_pixel == 4 then self.bb = BB.new(vinfo.xres, vinfo.yres, BB.TYPE_BB4, self.data, finfo.line_length) else error("unknown bpp value for the eink driver") end if ffi.string(finfo.id, 7) == "eink_fb" then -- classic eink framebuffer driver has grayscale values inverted (i.e. 0xF = black, 0 = white) self.bb:invert() end self.bb:fill(BB.COLOR_WHITE) framebuffer.parent.init(self) end function framebuffer:close() if self.bb ~= nil then self.bb:free() self.bb = nil end if self.data then ffi.C.munmap(self.data, self.fb_size) self.data = nil end if self.fd ~= -1 then ffi.C.close(self.fd) self.fd = -1 end end return require("ffi/framebuffer"):extend(framebuffer)
local ffi = require("ffi") local bit = require("bit") local BB = require("ffi/blitbuffer") require("ffi/linux_fb_h") require("ffi/posix_h") local framebuffer = { device_node = "/dev/fb0", fd = -1, fb_size = nil, data = nil, } --[[ The raw framebuffer memory is managed through Blitbuffer. When creating the Blitbuffer, we bind it to a framebuffer memory size of `vinfo.xres * finfo.line_length` assuming portrait mode by default. Here are couple interesting framebuffer attributes to watch out when porting to new devices: * vinfo.bits_per_pixel: Size of each pixel, for example, 16bits, 32bits, etc. * finfo.smem_len: Size of the actual framebuffer memory provided by the kernel. * finfo.line_length: Size of each row for the framebuffer. Usually, it would be close to `vinfo.xres_virtual * vinfo.bits_per_pixel / 8`. * vinfo.xres: Number of pixels in one row on physical screen, i.e. physical screen width * vinfo.yres: Number of pixels in one column on physical screen, i.e. physical screen height * vinfo.xres_virtual: Number of pixels in one row on scrollable virtual screen, for fb_pan_display. Usually `vinfo.xres_virtual` >= `vinfo.xres`. * vinfo.yres_virtual: Number of pixels in one column on scrollable virtual screen, for fb_pan_display. Usually `vinfo.yres_virtual` >= `vinfo.yres`. NOTE for Kobo: By definition, `finfo.smem_len` should always be larger than or equal to `vinfo.xres_virtual * vinfo.yres_virtual * vinfo.bits_per_pixel / 8`. However, turns out this is not the case on Kobo when the framebuffer is operating at 32bits mode. On Kobo Aura One, under 16bits mode, we got: finfo.line_length: 2816 finfo.smem_len: 10813440 vinfo.bits_per_pixel: 16 vinfo.xres: 1404 vinfo.yres: 1872 vinfo.xres_virtual: 1408 vinfo.yres_virtual: 3840 But under 32bits mode, we got: finfo.line_length: 5632 finfo.smem_len: 10813440 vinfo.bits_per_pixel: 32 vinfo.xres: 1404 vinfo.yres: 1872 vinfo.xres_virtual: 1408 vinfo.yres_virtual: 3840 The only settings that got changed are `finfo.line_length` and `vinfo.bits_per_pixel`. `finfo.smem_len` still remains at 10813440. --]] function framebuffer:init() local finfo = ffi.new("struct fb_fix_screeninfo") local vinfo = ffi.new("struct fb_var_screeninfo") self.fd = ffi.C.open(self.device_node, ffi.C.O_RDWR) assert(self.fd ~= -1, "cannot open framebuffer") -- Get fixed screen information assert(ffi.C.ioctl(self.fd, ffi.C.FBIOGET_FSCREENINFO, finfo) == 0, "cannot get screen info") assert(ffi.C.ioctl(self.fd, ffi.C.FBIOGET_VSCREENINFO, vinfo) == 0, "cannot get variable screen info") assert(finfo.type == ffi.C.FB_TYPE_PACKED_PIXELS, "video type not supported") assert(vinfo.xres_virtual > 0 and vinfo.yres_virtual > 0, "invalid framebuffer resolution") -- Classic eink framebuffer (Kindle 2, 3, DXG, 4) if ffi.string(finfo.id, 7) == "eink_fb" then self.fb_size = vinfo.xres_virtual * vinfo.yres_virtual * vinfo.bits_per_pixel / 8 -- Newer eink framebuffer (Kindle Touch, Paperwhite, Kobo) elseif ffi.string(finfo.id, 11) == "mxc_epdc_fb" then -- it seems that finfo.smem_len is unreliable on kobo -- Figure out the size of the screen in bytes self.fb_size = vinfo.xres_virtual * vinfo.yres_virtual * vinfo.bits_per_pixel / 8 -- Kobo hasn't updated smem_len when the depth was changed from 16 to 32 if vinfo.bits_per_pixel == 32 then self.fb_size = finfo.smem_len end -- PocketBook eink framebuffer seems to have no finfo.id elseif string.byte(ffi.string(finfo.id, 16), 1, 1) == 0 then -- finfo.line_length needs to be 16-bytes aligned finfo.line_length = bit.band(finfo.line_length * vinfo.bits_per_pixel / 8 + 15, bit.bnot(15)) self.fb_size = finfo.line_length * vinfo.yres_virtual else error("framebuffer model not supported"); end self.data = ffi.C.mmap(nil, self.fb_size, bit.bor(ffi.C.PROT_READ, ffi.C.PROT_WRITE), ffi.C.MAP_SHARED, self.fd, 0) assert(tonumber(ffi.cast("intptr_t", self.data)) ~= ffi.C.MAP_FAILED, "can not mmap() framebuffer") if vinfo.bits_per_pixel == 32 then self.bb = BB.new(vinfo.xres, vinfo.yres, BB.TYPE_BBRGB32, self.data, finfo.line_length) elseif vinfo.bits_per_pixel == 16 then self.bb = BB.new(vinfo.xres, vinfo.yres, BB.TYPE_BBRGB16, self.data, finfo.line_length) elseif vinfo.bits_per_pixel == 8 then self.bb = BB.new(vinfo.xres, vinfo.yres, BB.TYPE_BB8, self.data, finfo.line_length) elseif vinfo.bits_per_pixel == 4 then self.bb = BB.new(vinfo.xres, vinfo.yres, BB.TYPE_BB4, self.data, finfo.line_length) else error("unknown bpp value for the eink driver") end if ffi.string(finfo.id, 7) == "eink_fb" then -- classic eink framebuffer driver has grayscale values inverted (i.e. 0xF = black, 0 = white) self.bb:invert() end self.bb:fill(BB.COLOR_WHITE) framebuffer.parent.init(self) end function framebuffer:close() if self.bb ~= nil then self.bb:free() self.bb = nil end if self.data then ffi.C.munmap(self.data, self.fb_size) self.data = nil end if self.fd ~= -1 then ffi.C.close(self.fd) self.fd = -1 end end return require("ffi/framebuffer"):extend(framebuffer)
framebuffer_linux(fix): compare pointer properly in mmap assert
framebuffer_linux(fix): compare pointer properly in mmap assert
Lua
agpl-3.0
Frenzie/koreader-base,koreader/koreader-base,apletnev/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,koreader/koreader-base,koreader/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,apletnev/koreader-base,apletnev/koreader-base,houqp/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base
1d0218df9840b90c387f8c94ca2166feb07a8385
xmake/platforms/mingw/load.lua
xmake/platforms/mingw/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- -- imports import("core.project.config") -- load it function main(platform) -- init flags for architecture local archflags = nil local arch = config.get("arch") if arch then if arch == "x86_64" then archflags = "-m64" elseif arch == "i386" then archflags = "-m32" else archflags = "-arch " .. arch end end if archflags then platform:add("cxflags", archflags) platform:add("asflags", archflags) platform:add("ldflags", archflags) platform:add("shflags", archflags) end -- add bin search library for loading some dependent .dll files windows local bindir = config.get("bin") if bindir and is_host("windows") then os.addenv("PATH", bindir) end end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- -- imports import("core.project.config") -- load it function main(platform) -- init flags for architecture local archflags = nil local arch = config.get("arch") if arch then if arch == "x86_64" then archflags = "-m64" elseif arch == "i386" then archflags = "-m32" else archflags = "-arch " .. arch end end if archflags then platform:add("cxflags", archflags) platform:add("asflags", archflags) platform:add("ldflags", archflags) platform:add("shflags", archflags) end -- init flags for asm platform:add("yasm.asflags", "-f", arch == "x86_64" and "win64" or "win32") -- add bin search library for loading some dependent .dll files windows local bindir = config.get("bin") if bindir and is_host("windows") then os.addenv("PATH", bindir) end end
fix yasm arch for mingw
fix yasm arch for mingw
Lua
apache-2.0
tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake
c914ec09d85ee9265b52f3a413464a54d00272d9
nyagos.d/open.lua
nyagos.d/open.lua
nyagos.alias("open",function(args) local count=0 for i=1,#args do local list=nyagos.glob(args[i]) if list and #list >= 1 then for i=1,#list do local fd = io.open(list[i]) if fd then fd:close() assert(nyagos.shellexecute("open",list[i])) else nyagos.writerr(list[i]..": not found.\n") end end else local fd = io.open(args[i]) if fd then fd:close() assert(nyagos.shellexecute("open",args[i])) else print(args[i] .. ": not found.\n") end end count = count +1 end if count <= 0 then local fd = io.open("open.cmd") if fd then fd:close() nyagos.exec("open.cmd") else assert(nyagos.shellexecute("open",".")) end end end)
nyagos.alias("open",function(args) local count=0 for i=1,#args do local list=nyagos.glob(args[i]) if list and #list >= 1 then for i=1,#list do assert(nyagos.shellexecute("open",list[i])) end else if nyagos.access(args[i],0) then assert(nyagos.shellexecute("open",args[i])) else print(args[i] .. ": can not get status") end end count = count +1 end if count <= 0 then if nyagos.access(".\\open.cmd",0) then nyagos.exec("open.cmd") else assert(nyagos.shellexecute("open",".")) end end end)
Fixed open.lua could not open folders
Fixed open.lua could not open folders Revert "Fixed open.lua did not print error when wildcard did not match anyfiles." This reverts commit 119a5b069b9aaba108c4eef7ff817e952eb2a2f9.
Lua
bsd-3-clause
hattya/nyagos,zetamatta/nyagos,kissthink/nyagos,kissthink/nyagos,nocd5/nyagos,tyochiai/nyagos,tsuyoshicho/nyagos,kissthink/nyagos,hattya/nyagos,hattya/nyagos
66e6e4575f730b2b5221ac058ae2b6aea667f5a2
lua/entities/gmod_wire_starfall_processor/init.lua
lua/entities/gmod_wire_starfall_processor/init.lua
AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') include("starfall/SFLib.lua") include("libtransfer/libtransfer.lua") assert(SF, "Starfall didn't load correctly!") local context = SF.CreateContext() function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.Inputs = WireLib.CreateInputs(self, {}) self.Outputs = WireLib.CreateOutputs(self, {}) self:UpdateName("Inactive (No code)") local r,g,b,a = self:GetColor() self:SetColor(255, 0, 0, a) end function ENT:UpdateName(state) if state ~= "" then state = "\n"..state end if self.instance and self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then self:SetOverlayText("Starfall Processor\n"..tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])..state) else self:SetOverlayText("Starfall Processor"..state) end end function ENT:OnRestore() end function ENT:Compile(codetbl, mainfile) if self.instance then self.instance:deinitialize() end local ok, instance = SF.Compiler.Compile(codetbl,context,mainfile,self.owner) if not ok then self:Error(instance) return end self.instance = instance instance.data.entity = self local ok, msg = instance:initialize() if not ok then self:Error(msg) return end self:UpdateName("") local r,g,b,a = self:GetColor() self:SetColor(255, 255, 255, a) end function ENT:Error(msg, override) ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n") WireLib.ClientError(msg, self.owner) if self.instance then self.instance:deinitialize() self.instance = nil end self:UpdateName("Inactive (Error)") local r,g,b,a = self:GetColor() self:SetColor(255, 0, 0, a) end function ENT:CodeSent(ply, task) if ply ~= self.owner then return end self:Compile(task.files, task.mainfile) end function ENT:Think() self.BaseClass.Think(self) self:NextThink(CurTime()) if self.instance and not self.instance.error then self.instance:resetOps() self:RunScriptHook("think") end return true end function ENT:OnRemove() if not self.instance then return end self.instance:deinitialize() self.instance = nil end function ENT:TriggerInput(key, value) self:RunScriptHook("input",key, SF.Wire.InputConverters[self.Inputs[key].Type](value)) end function ENT:ReadCell(address) return tonumber(self:RunScriptHookForResult("readcell",address)) or 0 end function ENT:WriteCell(address, data) self:RunScriptHook("writecell",address,data) end function ENT:RunScriptHook(hook, ...) if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then local ok, rt = self.instance:runScriptHook(hook, ...) if not ok then self:Error(rt) end end end function ENT:RunScriptHookForResult(hook,...) if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then local ok, rt = self.instance:runScriptHookForResult(hook, ...) if not ok then self:Error(rt) else return rt end end end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if self.instance then info.starfall = SF.SerializeCode(self.instance.source, self.instance.mainfile) end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.owner = ply if info.starfall then local code, main = SF.DeserializeCode(info.starfall) self:Compile(code, main) end end
AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') include("starfall/SFLib.lua") include("libtransfer/libtransfer.lua") assert(SF, "Starfall didn't load correctly!") ENT.WireDebugName = "Starfall Processor" ENT.OverlayDelay = 0 local context = SF.CreateContext() local name = nil function ENT:UpdateState(state) if name then self:SetOverlayText("Starfall Processor\n"..name.."\n"..state) else self:SetOverlayText("Starfall Processor\n"..state) end end function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.Inputs = WireLib.CreateInputs(self, {}) self.Outputs = WireLib.CreateOutputs(self, {}) self:UpdateState("Inactive (No code)") local r,g,b,a = self:GetColor() self:SetColor(255, 0, 0, a) end function ENT:Compile(codetbl, mainfile) if self.instance then self.instance:deinitialize() end local ok, instance = SF.Compiler.Compile(codetbl,context,mainfile,self.owner) if not ok then self:Error(instance) return end self.instance = instance instance.data.entity = self local ok, msg = instance:initialize() if not ok then self:Error(msg) return end if self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then name = tostring(self.instance.ppdata.scriptnames[self.instance.mainfile]) end if not name or string.len(name) <= 0 then name = "generic" end self:UpdateState("(None)") local r,g,b,a = self:GetColor() self:SetColor(255, 255, 255, a) end function ENT:Error(msg, override) ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n") WireLib.ClientError(msg, self.owner) if self.instance then self.instance:deinitialize() self.instance = nil end self:UpdateState("Inactive (Error)") local r,g,b,a = self:GetColor() self:SetColor(255, 0, 0, a) end function ENT:CodeSent(ply, task) if ply ~= self.owner then return end self:Compile(task.files, task.mainfile) end function ENT:Think() self.BaseClass.Think(self) if self.instance and not self.instance.error then self:UpdateState(tostring(self.instance.ops).." ops, "..tostring(math.floor(self.instance.ops / self.instance.context.ops * 100)).."%") self.instance:resetOps() self:RunScriptHook("think") end self:NextThink(CurTime()) return true end function ENT:OnRemove() if not self.instance then return end self.instance:deinitialize() self.instance = nil end function ENT:TriggerInput(key, value) self:RunScriptHook("input",key, SF.Wire.InputConverters[self.Inputs[key].Type](value)) end function ENT:ReadCell(address) return tonumber(self:RunScriptHookForResult("readcell",address)) or 0 end function ENT:WriteCell(address, data) self:RunScriptHook("writecell",address,data) end function ENT:RunScriptHook(hook, ...) if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then local ok, rt = self.instance:runScriptHook(hook, ...) if not ok then self:Error(rt) end end end function ENT:RunScriptHookForResult(hook,...) if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then local ok, rt = self.instance:runScriptHookForResult(hook, ...) if not ok then self:Error(rt) else return rt end end end function ENT:OnRestore() end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if self.instance then info.starfall = SF.SerializeCode(self.instance.source, self.instance.mainfile) end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.owner = ply if info.starfall then local code, main = SF.DeserializeCode(info.starfall) self:Compile(code, main) end end
Processor's overlay fix. Made it show current ops.
Processor's overlay fix. Made it show current ops.
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Xandaros/Starfall
257e3ca0c2f2bda24b79efe110f8e996c2889237
src/roslua/publisher.lua
src/roslua/publisher.lua
---------------------------------------------------------------------------- -- publisher.lua - Topic publisher -- -- Created: Mon Jul 27 17:04:24 2010 (at Intel Research, Pittsburgh) -- License: BSD, cf. LICENSE file of roslua -- Copyright 2010 Tim Niemueller [www.niemueller.de] -- 2010 Carnegie Mellon University -- 2010 Intel Research Pittsburgh ---------------------------------------------------------------------------- --- Topic publisher. -- This module contains the Publisher class to publish to a ROS topic. The -- class is used to publish messages to a specified topic. It is created using -- the function <code>roslua.publisher()</code>. -- <br /><br /> -- The main interaction for applications is using the <code>publish()</code> -- method to send new messages. The publisher spins automatically when created -- using <code>roslua.publisher()</code>. -- @copyright Tim Niemueller, Carnegie Mellon University, Intel Research Pittsburgh -- @release Released under BSD license module("roslua.publisher", package.seeall) require("roslua") require("roslua.msg_spec") Publisher = {DEBUG = false} --- Constructor. -- Create a new publisher instance. -- @param topic topic to publish to -- @param type type of the topic function Publisher:new(topic, type) local o = {} setmetatable(o, self) self.__index = self o.topic = topic o.latching = o.latching or false if roslua.msg_spec.is_msgspec(type) then o.type = type.type o.msgspec = type else o.type = type o.msgspec = roslua.get_msgspec(type) end assert(o.topic, "Topic name is missing") assert(o.type, "Topic type is missing") o.subscribers = {} -- connect to all publishers o:start_server() return o end --- Finalize instance. function Publisher:finalize() for uri, s in pairs(self.subscribers) do s.connection:close() end self.subscribers = {} end --- Start the internal TCP server to accept ROS subscriber connections. function Publisher:start_server() self.server = roslua.tcpros.TcpRosPubSubConnection:new() self.server:bind() self.address, self.port = self.server:get_ip_port() end --- Wait for a subscriber to connect. function Publisher:wait_for_subscriber() local have_subscriber = false repeat assert(not roslua.quit, "Aborted while waiting for subscriber for topic " .. self.topic) for _, _ in pairs(self.subscribers) do have_subscriber = true break end roslua.spin() until have_subscriber end -- (internal) Called by spin() to accept new connections. function Publisher:accept_connections() local conns = self.server:accept() for _, c in ipairs(conns) do local md5sum = self.msgspec:md5() c:send_header{callerid=roslua.node_name, topic=self.topic, type=self.type, md5sum=md5sum} local ok, error = pcall(c.receive_header, c) if (ok and self.DEBUG) then print_debug("Publisher[%s::%s]: subscriber connection from %s (%s:%d)", self.topic, self.type, c.header.callerid, c.socket:getpeername()) end if not ok then print_warn("Publisher[%s::%s]: accepting connection failed: %s", self.topic, self.type, error) c:close() elseif c.header.md5sum ~= "*" and c.header.md5sum ~= md5sum then print_warn("Publisher[%s::%s]: received non-matching MD5 ".. "(here: %s there: %s) sum from %s, disconnecting and ignoring", self.topic, self.type, md5sum, c.header.md5sum, c.header.callerid) c:close() else if self.latched and self.latched_message then local ok, error = pcall(c.send, c, self.latched_message.serialized) if not ok then local ip, port = c:get_ip_port() print_warn("Publisher[%s::%s]: failed sending to %s:%s for latched message (%s)", self.type, self.topic, ip, port, error) self.subscribers[uri].connection:close() self.subscribers[uri] = nil end end --print("Accepted connection from " .. c.header.callerid) self.subscribers[c.header.callerid] = {uri=c.header.callerid, connection=c} end end end --- Get statistics about this publisher. -- @return an array containing the topic name as the first entry, and another array -- as the second entry. This array contains itself tables with four fields each: -- the remote caller ID of the connection, the number of bytes sent, number of -- messages sent and connection aliveness (always true). Suitable for -- getBusStats of slave API. function Publisher:get_stats() local conns = {} for callerid, s in pairs(self.subscribers) do local bytes_rcvd, bytes_sent, age, msgs_rcvd, msgs_sent = s.connection:get_stats() local stats = {callerid, bytes_sent, msgs_sent, true} table.insert(conns, stats) end return {self.topic, conns} end --- Publish message to topic. -- The messages are sent immediately. Busy or bad network connections or a large number -- of subscribers can slow down this method. -- @param message message to publish function Publisher:publish(message) --assert(message.spec.type == self.type, "Message of invalid type cannot be published " -- .. " (topic " .. self.topic .. ", " .. self.type .. " vs. " .. message.spec.type) local sm = message:serialize() if self.latching then self.latched_message = {message=message, serialized=sm} end local uri, s if not next(self.subscribers) and self.topic ~= "/rosout" then if self.DEBUG then print_warn("Publisher[%s::%s]: cannot send message, no subscribers", self.type, self.topic) end else for uri, s in pairs(self.subscribers) do local ok, error = pcall(s.connection.send, s.connection, sm) if self.DEBUG and self.topic ~= "/rosout" then if ok then print_warn("Publisher[%s::%s]: sent to %s", self.type, self.topic, s.connection.header.callerid) else print_warn("Publisher[%s::%s]: failed to send to %s", self.type, self.topic, s.connection.header.callerid) end end if not ok then self.subscribers[uri].connection:close() self.subscribers[uri] = nil end end end end --- Spin function. -- While spinning the publisher accepts new connections. function Publisher:spin() self:accept_connections() end
---------------------------------------------------------------------------- -- publisher.lua - Topic publisher -- -- Created: Mon Jul 27 17:04:24 2010 (at Intel Research, Pittsburgh) -- License: BSD, cf. LICENSE file of roslua -- Copyright 2010 Tim Niemueller [www.niemueller.de] -- 2010 Carnegie Mellon University -- 2010 Intel Research Pittsburgh ---------------------------------------------------------------------------- --- Topic publisher. -- This module contains the Publisher class to publish to a ROS topic. The -- class is used to publish messages to a specified topic. It is created using -- the function <code>roslua.publisher()</code>. -- <br /><br /> -- The main interaction for applications is using the <code>publish()</code> -- method to send new messages. The publisher spins automatically when created -- using <code>roslua.publisher()</code>. -- @copyright Tim Niemueller, Carnegie Mellon University, Intel Research Pittsburgh -- @release Released under BSD license module("roslua.publisher", package.seeall) require("roslua") require("roslua.msg_spec") Publisher = {DEBUG = false} --- Constructor. -- Create a new publisher instance. -- @param topic topic to publish to -- @param type type of the topic function Publisher:new(topic, type) local o = {} setmetatable(o, self) self.__index = self o.topic = topic o.latching = o.latching or false if roslua.msg_spec.is_msgspec(type) then o.type = type.type o.msgspec = type else o.type = type o.msgspec = roslua.get_msgspec(type) end assert(o.topic, "Topic name is missing") assert(o.type, "Topic type is missing") o.subscribers = {} -- connect to all publishers o:start_server() return o end --- Finalize instance. function Publisher:finalize() for uri, s in pairs(self.subscribers) do s.connection:close() end self.subscribers = {} end --- Start the internal TCP server to accept ROS subscriber connections. function Publisher:start_server() self.server = roslua.tcpros.TcpRosPubSubConnection:new() self.server:bind() self.address, self.port = self.server:get_ip_port() end --- Wait for a subscriber to connect. function Publisher:wait_for_subscriber() local have_subscriber = false repeat assert(not roslua.quit, "Aborted while waiting for subscriber for topic " .. self.topic) for _, _ in pairs(self.subscribers) do have_subscriber = true break end roslua.spin() until have_subscriber end -- (internal) Called by spin() to accept new connections. function Publisher:accept_connections() local conns = self.server:accept() for _, c in ipairs(conns) do local md5sum = self.msgspec:md5() c:send_header{callerid=roslua.node_name, topic=self.topic, type=self.type, md5sum=md5sum} local ok, error = pcall(c.receive_header, c) if (ok and self.DEBUG) then print_debug("Publisher[%s::%s]: subscriber connection from %s (%s:%d)", self.topic, self.type, c.header.callerid, c.socket:getpeername()) end if not ok then print_warn("Publisher[%s::%s]: accepting connection failed: %s", self.topic, self.type, error) c:close() elseif c.header.md5sum ~= "*" and c.header.md5sum ~= md5sum then print_warn("Publisher[%s::%s]: received non-matching MD5 ".. "(here: %s there: %s) sum from %s, disconnecting and ignoring", self.topic, self.type, md5sum, c.header.md5sum, c.header.callerid) c:close() else if self.latching and self.latched_message then if self.DEBUG then print_warn("Publisher[%s::%s]: sending latched message", self.type, self.topic) end local ok, error = pcall(c.send, c, self.latched_message.serialized) if not ok then local ip, port = c:get_ip_port() print_warn("Publisher[%s::%s]: failed sending to %s:%s for latched message (%s)", self.type, self.topic, ip, port, error) self.subscribers[uri].connection:close() self.subscribers[uri] = nil end end --print("Accepted connection from " .. c.header.callerid) self.subscribers[c.header.callerid] = {uri=c.header.callerid, connection=c} end end end --- Get statistics about this publisher. -- @return an array containing the topic name as the first entry, and another array -- as the second entry. This array contains itself tables with four fields each: -- the remote caller ID of the connection, the number of bytes sent, number of -- messages sent and connection aliveness (always true). Suitable for -- getBusStats of slave API. function Publisher:get_stats() local conns = {} for callerid, s in pairs(self.subscribers) do local bytes_rcvd, bytes_sent, age, msgs_rcvd, msgs_sent = s.connection:get_stats() local stats = {callerid, bytes_sent, msgs_sent, true} table.insert(conns, stats) end return {self.topic, conns} end --- Publish message to topic. -- The messages are sent immediately. Busy or bad network connections or a large number -- of subscribers can slow down this method. -- @param message message to publish function Publisher:publish(message) --assert(message.spec.type == self.type, "Message of invalid type cannot be published " -- .. " (topic " .. self.topic .. ", " .. self.type .. " vs. " .. message.spec.type) local sm = message:serialize() if self.latching then self.latched_message = {message=message, serialized=sm} end local uri, s if not next(self.subscribers) and self.topic ~= "/rosout" then if self.DEBUG then print_warn("Publisher[%s::%s]: cannot send message, no subscribers", self.type, self.topic) end else for uri, s in pairs(self.subscribers) do local ok, error = pcall(s.connection.send, s.connection, sm) if self.DEBUG and self.topic ~= "/rosout" then if ok then print_warn("Publisher[%s::%s]: sent to %s", self.type, self.topic, s.connection.header.callerid) else print_warn("Publisher[%s::%s]: failed to send to %s", self.type, self.topic, s.connection.header.callerid) end end if not ok then self.subscribers[uri].connection:close() self.subscribers[uri] = nil end end end end --- Spin function. -- While spinning the publisher accepts new connections. function Publisher:spin() self:accept_connections() end
publisher: fix latching (typo)
publisher: fix latching (typo)
Lua
bsd-3-clause
timn/roslua
87ea426a55defb0842fbef13fb2fd7e2e22fe9c6
nodes/status_bar/node.lua
nodes/status_bar/node.lua
--RasPegacy v0.1 --Status Bar Child --Git is painful... gl.setup(720, 40) node.alias("status_bar") -- good place to display Raspberry Pi and/or Subaru logo(s) bg = resource.load_image("bg_bottom.png") RPi = resource.load_image("RPi_small.png") Subaru = resource.load_image("Subaru_Logo.png") local font = resource.load_font("Exo2.otf") util.data_mapper{ ["sbar/msg"] = function(new_msg) --print("MSG", new_msg) if new_msg ~= nil then msg = new_msg else msg = " " end end; } function node.render() gl.clear(0, 0, 0, 1) -- If I implement time based color swapping, will need to pass time here as well --if tonumber(clk) < 2000 then -- gl.clear(0, 0, 0, 0) --end -- Draw background and logo(s) bg:draw(0, 0, 720, 40, 1) RPi:draw(681, 1, 719, 39, 1) Subaru:draw(608, 1, 676, 39, 1) -- Write status message font:write(10, 2, msg, 18, 1, 1, 1, 1) end
--RasPegacy v0.1 --Status Bar Child --Git is painful... gl.setup(720, 40) node.alias("status_bar") -- good place to display Raspberry Pi and/or Subaru logo(s) bg = resource.load_image("bg_bottom.png") RPi = resource.load_image("RPi_small.png") Subaru = resource.load_image("Subaru_Logo.png") local font = resource.load_font("Exo2.otf") local msg = " " util.data_mapper{ ["sbar/msg"] = function(new_msg) --print("MSG", new_msg) msg = new_msg end; } function node.render() gl.clear(0, 0, 0, 1) -- If I implement time based color swapping, will need to pass time here as well --if tonumber(clk) < 2000 then -- gl.clear(0, 0, 0, 0) --end -- Draw background and logo(s) bg:draw(0, 0, 720, 40, 1) RPi:draw(681, 1, 719, 39, 1) Subaru:draw(608, 1, 676, 39, 1) -- Write status message if msg then font:write(10, 2, msg, 18, 1, 1, 1, 1) end end
fixed undefined locals and truthed msg
fixed undefined locals and truthed msg
Lua
apache-2.0
sommersoft/RasPegacy
56e2ecc9687dd8756d3ed1a0cc1ec331a3ba4d04
spec/parsers/source_spec.lua
spec/parsers/source_spec.lua
local parser = require("fusion.core.parsers.source") local lexer = require("fusion.core.lexer") describe("parsers/source", function() it("can compile FusionScript code", function() local input_stream = coroutine.wrap(function() coroutine.yield(lexer:match("print('test');")[1]) end) parser.compile(input_stream, function(output) assert.same("print(\"test\")", output) end) end) it("can compile FusionScript files", function() local input = [[ print("test") ]] assert.same(input, parser.read_file("spec/in/basic.fuse")) end) it("can load FusionScript files", function() local old_print = print _G['print'] = function(text) assert.same("test", text) end assert(parser.load_file("spec/in/basic.fuse"), "unable to load file")() _G['print'] = old_print end) it("can load a searcher into the module loading system", function() assert.same(true, parser.inject_loader()) assert.same(parser.search_for, (package.loaders or package.searchers)[2]) assert.same(false, parser.inject_loader()) -- false if already run end) it("can run FusionScript files", function() assert.same(0xDEADBEEF, require("spec.misc")) end) end)
local parser = require("fusion.core.parsers.source") local lexer = require("fusion.core.lexer") describe("parsers/source", function() it("can compile FusionScript code", function() parser.compile(lexer:match("print('test');"), function(output) assert.same("print(\"test\")", output) end) end) it("can compile FusionScript files", function() local input = [[ print("test") ]] assert.same(input, parser.read_file("spec/in/basic.fuse")) end) it("can load FusionScript files", function() local old_print = print _G['print'] = function(text) assert.same("test", text) end assert(parser.load_file("spec/in/basic.fuse"), "unable to load file")() _G['print'] = old_print end) it("can load a searcher into the module loading system", function() assert.same(true, parser.inject_loader()) assert.same(parser.search_for, (package.loaders or package.searchers)[2]) assert.same(false, parser.inject_loader()) -- false if already run end) it("can run FusionScript files", function() assert.same(0xDEADBEEF, require("spec.misc")) end) end)
parsers/source_spec: fix .compile()
parsers/source_spec: fix .compile()
Lua
mit
RyanSquared/FusionScript
886548d99ba775b13a890373db577ccb0a22ef30
src/api-umbrella/cli/run.lua
src/api-umbrella/cli/run.lua
local path = require "pl.path" local setup = require "api-umbrella.cli.setup" local unistd = require "posix.unistd" local function start_perp(config, options) local perp_base = path.join(config["etc_dir"], "perp") local args = { "-0", "api-umbrella (perpboot)", "-P", "/tmp/perpboot.lock", "perpboot", perp_base } if options and options["background"] then table.insert(args, "-d") end unistd.execp("runtool", args) -- execp should replace the current process, so we've gotten this far it -- means execp failed, likely due to the "runtool" command not being found. print("Error: runtool command was not found") os.exit(1) end return function(options) local config = setup() start_perp(config, options) end
local path = require "pl.path" local setup = require "api-umbrella.cli.setup" local unistd = require "posix.unistd" local function start_perp(config, options) local perp_base = path.join(config["etc_dir"], "perp") local args = { "-0", "api-umbrella (perpboot)", "-P", "/tmp/perpboot.lock", "perpboot", } if options and options["background"] then table.insert(args, "-d") end table.insert(args, perp_base) unistd.execp("runtool", args) -- execp should replace the current process, so we've gotten this far it -- means execp failed, likely due to the "runtool" command not being found. print("Error: runtool command was not found") os.exit(1) end return function(options) local config = setup() start_perp(config, options) end
Fix backgrounding for "api-umbrella start" command.
Fix backgrounding for "api-umbrella start" command.
Lua
mit
apinf/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,apinf/api-umbrella
335994f0d74d0a647c40e27d0995519122739dc3
otouto/plugins/luarun.lua
otouto/plugins/luarun.lua
local luarun = {} function luarun:init(config) luarun.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('lua', true):t('return', true).table if config.luarun_serpent then serpent = require('serpent') luarun.serialize = function(t) return serpent.block(t, {comment=false}) end else JSON = require('dkjson') luarun.serialize = function(t) return JSON.encode(t, {indent=true}) end end end function luarun:action(msg, config) if not is_sudo(msg, config) then return true end local input = utilities.input(msg.text) if not input then utilities.send_reply(msg, 'Please enter a string to load.') return end if msg.text_lower:match('^'..config.cmd_pat..'return') then input = 'return ' .. input end local output = loadstring( [[ local bot = require('otouto.bot') local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local drua = require('otouto.drua-tg') local JSON = require('dkjson') local URL = require('socket.url') local HTTP = require('socket.http') local HTTPS = require('ssl.https') return function (msg, config) ]] .. input .. [[ end ]] )()(msg, config) if output == nil then output = 'Done!' else if type(output) == 'table' then local s = luarun.serialize(output) if URL.escape(s):len() < 4000 then output = s end end output = '```\n' .. tostring(output) .. '\n```' end utilities.send_message(msg.chat.id, output, true, msg.message_id, true) end return luarun
local luarun = {} function luarun:init(config) luarun.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('lua', true):t('return', true).table if config.luarun_serpent then serpent = require('serpent') luarun.serialize = function(t) return serpent.block(t, {comment=false}) end else JSON = require('dkjson') luarun.serialize = function(t) return JSON.encode(t, {indent=true}) end end end function luarun:action(msg, config) if not is_sudo(msg, config) then return true end local input = utilities.input(msg.text) if not input then utilities.send_reply(self, msg, 'Bitte gebe einen Befehl ein.') return end if msg.text_lower:match('^'..config.cmd_pat..'return') then input = 'return ' .. input end local output = loadstring( [[ local bot = require('otouto.bot') local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local json = require('dkjson') local URL = require('socket.url') local http = require('socket.http') local https = require('ssl.https') return function (self, msg, config) ]] .. input .. [[ end ]] )()(self, msg, config) if output == nil then output = 'Ausgeführt!' else if type(output) == 'table' then local s = luarun.serialize(output) if URL.escape(s):len() < 4000 then output = s end end output = '```\n' .. tostring(output) .. '\n```' end utilities.send_message(self, msg.chat.id, output, true, msg.message_id, true) end return luarun
Fixe Luarun
Fixe Luarun
Lua
agpl-3.0
Brawl345/Brawlbot-v2
0d7a4b3429eaffac4a5a60db8ca466ab04f33acb
lunaci/tasks/build.lua
lunaci/tasks/build.lua
-- LunaCI build task -- Part of the LuaDist project - http://luadist.org -- Author: Martin Srank, hello@smasty.net -- License: MIT module("lunaci.tasks.build", package.seeall) local build_package = function(package, target, deploy_dir, manifest) local config = require "lunaci.config" local utils = require "lunaci.utils" local ok, code, out, err = utils.dir_exec(deploy_dir, "bin/lua lib/lua/luadist.lua install '" .. package .. "'") local msg = "Output:\n" .. out .. "\n" if not ok then msg = msg .. ("\nError:\n%s\nExit code: %d\n"):format(err, code) end if code == 1 then return config.STATUS_INT, "Manifest retrieval failed.\n" .. msg, false elseif code == 3 then return config.STATUS_INT, "Package download failed.\n" .. msg, false elseif code == 4 then return config.STATUS_FAIL, "Installation of requested package failed.\n" .. msg, false elseif code == 5 then return config.STATUS_DEP, "Installation of a dependency failed.\n" .. msg, false else return config.STATUS_FAIL, msg, false end return config.STATUS_OK, msg, true end return build_package
-- LunaCI build task -- Part of the LuaDist project - http://luadist.org -- Author: Martin Srank, hello@smasty.net -- License: MIT module("lunaci.tasks.build", package.seeall) local build_package = function(package, target, deploy_dir, manifest) local config = require "lunaci.config" local utils = require "lunaci.utils" local ok, code, out, err = utils.dir_exec(deploy_dir, "bin/lua lib/lua/luadist.lua install '" .. package .. "'") local msg = ("Output:\n%s\n%sExit code: %d\n", out, (err and (err .. "\n") or ""), code) if ok then return config.STATUS_OK, msg, true end if code == 3 then return config.STATUS_INT, "Package download failed.\n" .. msg, false elseif code == 4 then return config.STATUS_FAIL, "Installation of requested package failed.\n" .. msg, false elseif code == 5 then return config.STATUS_DEP, "Installation of a dependency failed.\n" .. msg, false else return config.STATUS_FAIL, msg, false end end return build_package
Fix build task error handling
Fix build task error handling
Lua
mit
smasty/LunaCI,smasty/LunaCI
57dc5697711b96b9370a148ae36cf3a7929dd790
Quadtastic/common.lua
Quadtastic/common.lua
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local libquadtastic = require(current_folder.. ".libquadtastic") -- Utility functions that don't deserve their own module local common = {} -- Load imagedata from outside the game's source and save folder function common.load_imagedata(filepath) local filehandle, err = io.open(filepath, "rb") if err then error(err, 0) end local filecontent = filehandle:read("*a") filehandle:close() return love.image.newImageData( love.filesystem.newFileData(filecontent, 'img', 'file')) end -- Load an image from outside the game's source and save folder function common.load_image(filepath) local imagedata = common.load_imagedata(filepath) return love.graphics.newImage(imagedata) end -- Split a filepath into the path of the containing directory and a filename. -- Note that a trailing slash will result in an empty filename function common.split(filepath) local dirname, basename = string.gmatch(filepath, "(.*/)([^/]*)")() return dirname, basename end -- Returns the filename without extension as the first return value, and the -- extension as the second return value function common.split_extension(filename) return string.gmatch(filename, "(.*)%.([^%.]*)")() end local function export_quad(handle, quadtable) handle(string.format( "{x = %d, y = %d, w = %d, h = %d}", quadtable.x, quadtable.y, quadtable.w, quadtable.h)) end local function export_table_content(handle, tab, indentation) local numeric_keys = {} local string_keys = {} for k in pairs(tab) do if type(k) == "number" then table.insert(numeric_keys, k) elseif type(k) == "string" then table.insert(string_keys, k) end end table.sort(numeric_keys) table.sort(string_keys) local function export_pair(k, v) handle(string.rep(" ", indentation)) if type(k) == "string" then handle(string.format("%s = ", k)) elseif type(k) ~= "number" then error("Cannot handle table keys of type "..type(k)) end if type(v) == "table" then -- Check if it is a quad table, in which case we use a simpler function if libquadtastic.is_quad(v) then export_quad(handle, v) else handle("{\n") export_table_content(handle, v, indentation+1) handle(string.rep(" ", indentation)) handle("}") end elseif type(v) == "number" then handle(tostring(v)) elseif type(v) == "string" then handle("\"", v, "\"") else error("Cannot handle table values of type "..type(v)) end handle(",\n") end for _, k in ipairs(numeric_keys) do local v = tab[k] export_pair(k, v) end for _, k in ipairs(string_keys) do local v = tab[k] export_pair(k, v) end end function common.export_table_content(handle, tab) handle("return {\n") export_table_content(handle, tab, 1) handle("}\n") end function common.export_table_to_file(filehandle, tab) local function handle(...) filehandle:write(...) end common.export_table_content(handle, tab) filehandle:close() end function common.serialize_table(tab) local strings = {} local function handle(...) for _,string in ipairs({...}) do table.insert(strings, string) end end common.export_table_content(handle, tab) return table.concat(strings) end return common
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local libquadtastic = require(current_folder.. ".libquadtastic") -- Utility functions that don't deserve their own module local common = {} -- Load imagedata from outside the game's source and save folder function common.load_imagedata(filepath) local filehandle, err = io.open(filepath, "rb") if err then error(err, 0) end local filecontent = filehandle:read("*a") filehandle:close() return love.image.newImageData( love.filesystem.newFileData(filecontent, 'img', 'file')) end -- Load an image from outside the game's source and save folder function common.load_image(filepath) local imagedata = common.load_imagedata(filepath) return love.graphics.newImage(imagedata) end -- Split a filepath into the path of the containing directory and a filename. -- Note that a trailing slash will result in an empty filename function common.split(filepath) local dirname, basename = string.gmatch(filepath, "(.*/)([^/]*)")() return dirname, basename end -- Returns the filename without extension as the first return value, and the -- extension as the second return value function common.split_extension(filename) return string.gmatch(filename, "(.*)%.([^%.]*)")() end local function export_quad(handle, quadtable) handle(string.format( "{x = %d, y = %d, w = %d, h = %d}", quadtable.x, quadtable.y, quadtable.w, quadtable.h)) end local function escape(str) str = string.gsub(str, "\\", "\\\\") str = string.gsub(str, "\"", "\\\"") return str end local function export_table_content(handle, tab, keys) keys = keys or "" local numeric_keys = {} local string_keys = {} for k in pairs(tab) do if type(k) == "number" then table.insert(numeric_keys, k) elseif type(k) == "string" then table.insert(string_keys, k) end end table.sort(numeric_keys) table.sort(string_keys) local function export_pair(k, v) local new_keys if type(k) == "string" then new_keys = keys .. string.format("[\"%s\"]", escape(k)) elseif type(k) == "number" then new_keys = keys .. string.format("[%s]", k) else error("Cannot handle table keys of type "..type(k)) end handle("t", new_keys, " = ") if type(v) == "table" then -- Check if it is a quad table, in which case we use a simpler function if libquadtastic.is_quad(v) then export_quad(handle, v) else handle("{}\n") export_table_content(handle, v, new_keys) end elseif type(v) == "number" then handle(tostring(v)) elseif type(v) == "string" then handle("\"", escape(v), "\"") else error("Cannot handle table values of type "..type(v)) end handle("\n") end for _, k in ipairs(numeric_keys) do local v = tab[k] export_pair(k, v) end for _, k in ipairs(string_keys) do local v = tab[k] export_pair(k, v) end end function common.export_table_content(handle, tab) handle("local t = {}\n") export_table_content(handle, tab, "") handle("return t\n") end function common.export_table_to_file(filehandle, tab) local function handle(...) filehandle:write(...) end common.export_table_content(handle, tab) filehandle:close() end function common.serialize_table(tab) local strings = {} local function handle(...) for _,string in ipairs({...}) do table.insert(strings, string) end end common.export_table_content(handle, tab) return table.concat(strings) end return common
Fix exporter not being able to handle keys with non-alphanumeric characters
Fix exporter not being able to handle keys with non-alphanumeric characters
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
ec4145a3efd3b94277ac861d3a733619b2a48b31
SpatialMaxPooling.lua
SpatialMaxPooling.lua
local C = ccn2.C local SpatialMaxPooling, parent = torch.class('ccn2.SpatialMaxPooling', 'nn.Module') function SpatialMaxPooling:__init(kW, dW) parent.__init(self) self.kW = kW self.dW = dW or kW self.output = torch.Tensor() self.gradInput = torch.Tensor() self:cuda() end function SpatialMaxPooling:updateOutput(input) ccn2.typecheck(input) ccn2.inputcheck(input) local nBatch = input:size(4) local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4)) local outputX = math.floor((input:size(2) - self.kW)/self.dW + 1) C['convLocalMaxPool'](inputC:cdata(), self.output:cdata(), input:size(1), self.kW, 0, self.dW, outputX) local ims = math.sqrt(self.output:size(1)/input:size(1)) self.output = self.output:view(input:size(1), ims, ims, nBatch) return self.output end function SpatialMaxPooling:updateGradInput(input, gradOutput) ccn2.typecheck(input); ccn2.typecheck(gradOutput); ccn2.inputcheck(input); ccn2.inputcheck(gradOutput); local nBatch = input:size(4) local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4)) local gradOutputC = gradOutput:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4)) local outputC = self.output:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4)) self.gradInput:resize(inputC:size()) local outputX = math.floor((input:size(2) - self.kW)/self.dW + 1) C['convLocalMaxUndo'](inputC:cdata(), gradOutputC:cdata(), outputC:cdata(), self.gradInput:cdata(), self.kW, 0, self.dW, outputX) self.gradInput = self.gradInput:view(input:size(1), input:size(2), input:size(3), input:size(4)) return self.gradInput end
local C = ccn2.C local SpatialMaxPooling, parent = torch.class('ccn2.SpatialMaxPooling', 'nn.Module') function SpatialMaxPooling:__init(kW, dW) parent.__init(self) self.kW = kW self.dW = dW or kW self.output = torch.Tensor() self.gradInput = torch.Tensor() self:cuda() end function SpatialMaxPooling:updateOutput(input) ccn2.typecheck(input) ccn2.inputcheck(input) local nBatch = input:size(4) local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4)) local outputX = math.ceil((input:size(2) - self.kW)/self.dW + 1) C['convLocalMaxPool'](inputC:cdata(), self.output:cdata(), input:size(1), self.kW, 0, self.dW, outputX) local ims = math.sqrt(self.output:size(1)/input:size(1)) self.output = self.output:view(input:size(1), ims, ims, nBatch) return self.output end function SpatialMaxPooling:updateGradInput(input, gradOutput) ccn2.typecheck(input); ccn2.typecheck(gradOutput); ccn2.inputcheck(input); ccn2.inputcheck(gradOutput); local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4)) local gradOutputC = gradOutput:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4)) local outputC = self.output:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4)) self.gradInput:resize(inputC:size()) local outputX = math.ceil((input:size(2) - self.kW)/self.dW + 1) C['convLocalMaxUndo'](inputC:cdata(), gradOutputC:cdata(), outputC:cdata(), self.gradInput:cdata(), self.kW, 0, self.dW, outputX) self.gradInput = self.gradInput:view(input:size(1), input:size(2), input:size(3), input:size(4)) return self.gradInput end
removed unused local fixed stride bug - outputX should be ceiled instead of floored
removed unused local fixed stride bug - outputX should be ceiled instead of floored
Lua
apache-2.0
monikajhuria/cuda-convnet2.torch-master_update,szagoruyko/cuda-convnet2.torch,szagoruyko/cuda-convnet2.torch,szagoruyko/cuda-convnet2.torch,monikajhuria/cuda-convnet2.torch-master_update,ajtao/my_ccn2_t,soumith/cuda-convnet2.torch,monikajhuria/cuda-convnet2.torch-master_update,soumith/cuda-convnet2.torch,soumith/cuda-convnet2.torch,szagoruyko/cuda-convnet2.torch,ajtao/my_ccn2_t,ajtao/my_ccn2_t
653bbbfec00a12ff7783cc74a4315cb7151fe064
src/cosy/configuration/init.lua
src/cosy/configuration/init.lua
local Loader = require "cosy.loader" local I18n = require "cosy.i18n" local Logger = require "cosy.logger" local Layer = require "layeredata" local layers = require "cosy.configuration.layers" local i18n = I18n.load "cosy.configuration" layers.default.locale = "en" layers.default.__label__ = "configuration" local Configuration = {} function Configuration.load (t) if type (t) ~= "table" then t = { t } end for _, name in ipairs (t) do require (name .. ".conf") end end local Metatable = {} function Metatable.__index (_, key) return layers.whole [key] end function Metatable.__newindex (_, key, value) layers.whole [key] = value end setmetatable (Configuration, Metatable) local files = { etc = "/etc/cosy.conf", home = os.getenv "HOME" .. "/.cosy/cosy.conf", pwd = os.getenv "PWD" .. "/cosy.conf", } if not _G.js then package.searchers [#package.searchers+1] = function (name) local result, err = io.open (name, "r") if not result then return nil, err end result, err = loadfile (name) if not result then return nil, err end return result, name end for key, name in pairs (files) do local result = Loader.hotswap.try_require (name) if result then Logger.debug { _ = i18n ["use"], path = name, locale = Configuration.locale or "en", } Layer.replacewith (layers [key], result) else Logger.warning { _ = i18n ["skip"], path = name, locale = Configuration.locale or "en", } end end end return Configuration
local Loader = require "cosy.loader" local I18n = require "cosy.i18n" local Logger = require "cosy.logger" local Layer = require "layeredata" local layers = require "cosy.configuration.layers" local Lfs = require "lfs" local i18n = I18n.load "cosy.configuration" layers.default.locale = "en" layers.default.__label__ = "configuration" local Configuration = {} function Configuration.load (t) if type (t) ~= "table" then t = { t } end for _, name in ipairs (t) do require (name .. ".conf") end end local Metatable = {} function Metatable.__index (_, key) return layers.whole [key] end function Metatable.__newindex (_, key, value) layers.whole [key] = value end setmetatable (Configuration, Metatable) -- Compute prefix: local main = package.searchpath ("cosy.configuration", package.path) if main:sub (1, 1) == "." then main = Lfs.currentdir () .. "/" .. main end local prefix = main:gsub ("/share/lua/5.1/cosy/configuration/.*", "/etc") local files = { etc = prefix .. "/cosy.conf", home = os.getenv "HOME" .. "/.cosy/cosy.conf", pwd = os.getenv "PWD" .. "/cosy.conf", } if not _G.js then package.searchers [#package.searchers+1] = function (name) local result, err = io.open (name, "r") if not result then return nil, err end result, err = loadfile (name) if not result then return nil, err end return result, name end for key, name in pairs (files) do local result = Loader.hotswap.try_require (name) if result then Logger.debug { _ = i18n ["use"], path = name, locale = Configuration.locale or "en", } Layer.replacewith (layers [key], result) else Logger.warning { _ = i18n ["skip"], path = name, locale = Configuration.locale or "en", } end end end return Configuration
Compute /etc/cosy.conf path using prefix.
Compute /etc/cosy.conf path using prefix.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
1776136d37e8f9983984bca18fae4c2198091af7
premake.lua
premake.lua
-- TODO: Because there is plenty ... -- 1. What about other IDE's that Premake supports? e.g. codeblocks, xcode -- 2. x86/x64 switching -- 3. get macosx library for zlib -- 4. actually test linux/mac build configurations -- 5. clean this file up because I'm sure it could be organized better -- -- NOTE: I am intentionally leaving out a "windows+gmake" configuration -- as trying to compile against the FBX SDK using MinGW results in -- compile errors. Some quick googling seems to indicate MinGW is -- not supported by the FBX SDK? -- If you try to use this script to build with MinGW you will end -- up with a Makefile that has god knows what in it FBX_SDK_ROOT = os.getenv("FBX_SDK_ROOT") if not FBX_SDK_ROOT then printf("ERROR: Environment variable FBX_SDK_ROOT is not set.") printf("Set it to something like: C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2013.3") os.exit() end BUILD_DIR = "build" if _ACTION == "clean" then os.rmdir(BUILD_DIR) end solution "fbx-conv" configurations { "Debug", "Release" } location (BUILD_DIR .. "/" .. _ACTION) project "fbx-conv" --- GENERAL STUFF FOR ALL PLATFORMS -------------------------------- kind "ConsoleApp" language "C++" location (BUILD_DIR .. "/" .. _ACTION) files { "./src/**.c*", "./src/**.h", } includedirs { (FBX_SDK_ROOT .. "/include"), "./libs/libpng/include", "./libs/zlib/include", } defines { "FBXSDK_NEW_API", } debugdir "." configuration "Debug" defines { "DEBUG", } flags { "Symbols" } configuration "Release" defines { "NDEBUG", } flags { "Optimize" } --- VISUAL STUDIO -------------------------------------------------- configuration "vs*" flags { "NoPCH", "NoMinimalRebuild" } buildoptions { "/MP" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86"), "./libs/libpng/lib/windows/x86", "./libs/zlib/lib/windows/x86", } links { "libpng14", "zlib", } configuration { "vs*", "Debug" } links { "fbxsdk-2013.3-mdd", } configuration { "vs*", "Release" } links { "fbxsdk-2013.3-md", } --- LINUX (GCC+MAKE) ----------------------------------------------- configuration { "linux" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x86"), "./libs/libpng/lib/linux/x86", "./libs/zlib/lib/linux/x86", } links { "libpng", "libz", } configuration { "linux", "Debug" } links { "fbxsdk-2013-staticd", } configuration { "linux", "Release" } links { "fbxsdk-2013-static", } --- MAC (GCC+MAKE) ------------------------------------------------- configuration { "macosx" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub"), "./libs/libpng/lib/macosx", "./libs/zlib/lib/macosx", } links { "png", "z", "CoreFoundation.framework", } configuration { "macosx", "Debug" } links { "fbxsdk-2013.3-staticd", } configuration { "macosx", "Release" } links { "fbxsdk-2013.3-static", }
-- TODO: Because there is plenty ... -- 1. x86/x64 switching -- 2. actually test linux build configuration -- 3. clean this file up because I'm sure it could be organized better -- 4. consider maybe switching to CMake because of the ugly hack below -- -- NOTE: I am intentionally leaving out a "windows+gmake" configuration -- as trying to compile against the FBX SDK using MinGW results in -- compile errors. Some quick googling seems to indicate MinGW is -- not supported by the FBX SDK? -- If you try to use this script to build with MinGW you will end -- up with a Makefile that has god knows what in it FBX_SDK_ROOT = os.getenv("FBX_SDK_ROOT") if not FBX_SDK_ROOT then printf("ERROR: Environment variable FBX_SDK_ROOT is not set.") printf("Set it to something like: C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2013.3") os.exit() end -- avert your eyes children! if string.find(_ACTION, "xcode") then -- TODO: i'm sure we could do some string search+replace trickery to make -- this more general-purpose -- take care of the most common case where the FBX SDK is installed to the -- default location and part of the path contains a space -- god help you if you install the FBX SDK using a totally different path -- that contains a space AND you want to use Xcode -- Premake + Xcode combined fuck this up so badly making it nigh-impossible -- to do any kind of _proper_ path escaping here (I wasted an hour on this) -- (maybe I should have used CMake ....) FBX_SDK_ROOT = string.gsub(FBX_SDK_ROOT, "FBX SDK", "'FBX SDK'") end -- ok, you can look again BUILD_DIR = "build" if _ACTION == "clean" then os.rmdir(BUILD_DIR) end solution "fbx-conv" configurations { "Debug", "Release" } location (BUILD_DIR .. "/" .. _ACTION) project "fbx-conv" --- GENERAL STUFF FOR ALL PLATFORMS -------------------------------- kind "ConsoleApp" language "C++" location (BUILD_DIR .. "/" .. _ACTION) files { "./src/**.c*", "./src/**.h", } includedirs { (FBX_SDK_ROOT .. "/include"), "./libs/libpng/include", "./libs/zlib/include", } defines { "FBXSDK_NEW_API", } debugdir "." configuration "Debug" defines { "DEBUG", } flags { "Symbols" } configuration "Release" defines { "NDEBUG", } flags { "Optimize" } --- VISUAL STUDIO -------------------------------------------------- configuration "vs*" flags { "NoPCH", "NoMinimalRebuild" } buildoptions { "/MP" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86"), "./libs/libpng/lib/windows/x86", "./libs/zlib/lib/windows/x86", } links { "libpng14", "zlib", } configuration { "vs*", "Debug" } links { "fbxsdk-2013.3-mdd", } configuration { "vs*", "Release" } links { "fbxsdk-2013.3-md", } --- LINUX (GCC+MAKE) ----------------------------------------------- configuration { "linux" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x86"), "./libs/libpng/lib/linux/x86", "./libs/zlib/lib/linux/x86", } links { "libpng", "libz", } configuration { "linux", "Debug" } links { "fbxsdk-2013-staticd", } configuration { "linux", "Release" } links { "fbxsdk-2013-static", } --- MAC (GCC+MAKE) ------------------------------------------------- configuration { "macosx" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub"), "./libs/libpng/lib/macosx", "./libs/zlib/lib/macosx", } links { "png", "z", "CoreFoundation.framework", } configuration { "macosx", "Debug" } links { "fbxsdk-2013.3-staticd", } configuration { "macosx", "Release" } links { "fbxsdk-2013.3-static", }
add ugly hack for FBX SDK path containing spaces when generating Xcode project files
add ugly hack for FBX SDK path containing spaces when generating Xcode project files I need to fix this up so it's more general-purpose or switch to using CMake instad
Lua
apache-2.0
lvlonggame/fbx-conv,xoppa/fbx-conv,andyvand/fbx-conv,davidedmonds/fbx-conv,reduz/fbx-conv,iichenbf/fbx-conv,cocos2d-x/fbx-conv,super626/fbx-conv,cocos2d-x/fbx-conv,Maxwolf/Multimap.FBXConv,xoppa/fbx-conv,arisecbf/fbx-conv,lvlonggame/fbx-conv,super626/fbx-conv,Maxwolf/Multimap.FBXConv,davidedmonds/fbx-conv,andyvand/fbx-conv,andyvand/fbx-conv,davidedmonds/fbx-conv,reduz/fbx-conv,arisecbf/fbx-conv,iichenbf/fbx-conv,reduz/fbx-conv,cocos2d-x/fbx-conv,iichenbf/fbx-conv,xoppa/fbx-conv,super626/fbx-conv,arisecbf/fbx-conv,lvlonggame/fbx-conv
38a70f0dc8bf66596bc8408ff9982a9b076d9131
src_trunk/resources/admin-system/c_overlay.lua
src_trunk/resources/admin-system/c_overlay.lua
local sx, sy = guiGetScreenSize() local localPlayer = getLocalPlayer() local statusLabel = nil local openReports = 0 local handledReports = 0 local unansweredReports = {} local ownReports = {} -- Admin Titles function getAdminTitle(thePlayer) local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0 local text = ({ "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" })[adminLevel] or "Player" local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0 if (hiddenAdmin==1) then text = text .. " (Hidden)" end return text end function getAdminCount() local online, duty, lead, leadduty = 0, 0, 0, 0 for key, value in ipairs(getElementsByType("player")) do if (isElement(value)) then local level = getElementData( value, "adminlevel" ) if level >= 1 then online = online + 1 local aod = getElementData( value, "adminduty" ) if aod == 1 then duty = duty + 1 end if level >= 4 then lead = lead + 1 if aod == 1 then leadduty = leadduty + 1 end end end end end return online, duty, lead, leadduty end -- update the labels local function updateGUI() if statusLabel then local online, duty, lead, leadduty = getAdminCount() local reporttext = "" if #unansweredReports > 0 then reporttext = ": #" .. table.concat(unansweredReports, ", #") end local ownreporttext = "" if #ownReports > 0 then ownreporttext = ": #" .. table.concat(ownReports, ", #") end local onduty = "Off Duty" if getElementData( localPlayer, "adminduty" ) and getElementData( localPlayer, "adminduty" ) == 1 then onduty = "On Duty" end guiSetText( statusLabel, getAdminTitle( localPlayer ) .. " :: " .. onduty .. " :: " .. getElementData( localPlayer, "gameaccountusername" ) .. " :: " .. duty .. "/" .. online .. " Admins :: " .. leadduty .. "/" .. lead .. " Lead+ Admins :: " .. ( openReports - handledReports ) .. " unanswered reports" .. reporttext .. " :: " .. handledReports .. " handled reports" .. ownreporttext ) end end -- create the gui local function createGUI() if statusLabel then destroyElement(statusLabel) statusLabel = nil end local adminlevel = getElementData( localPlayer, "adminlevel" ) if adminlevel then if adminlevel > 0 then statusLabel = guiCreateLabel( 5, sy - 20, sx - 10, 15, "", false ) updateGUI() --guiCreateLabel ( float x, float y, float width, float height, string text, bool relative, [element parent = nil] ) end end end addEventHandler( "onClientResourceStart", getResourceRootElement(), createGUI, false ) addEventHandler( "onClientElementDataChange", localPlayer, function(n) if n == "adminlevel" or n == "hiddenadmin" then createGUI() end end, false ) addEventHandler( "onClientElementDataChange", getRootElement(), function(n) if getElementType(source) == "player" and ( n == "adminlevel" or n == "adminduty" ) then updateGUI() end end ) addEvent( "updateReportsCount", true ) addEventHandler( "updateReportsCount", getLocalPlayer(), function( open, handled, unanswered, own ) openReports = open handledReports = handled unansweredReports = unanswered ownReports = own or {} updateGUI() end, false ) addEventHandler( "onClientPlayerQuit", getRootElement(), updateGUI )
local sx, sy = guiGetScreenSize() local localPlayer = getLocalPlayer() local statusLabel = nil local openReports = 0 local handledReports = 0 local unansweredReports = {} local ownReports = {} -- Admin Titles function getAdminTitle(thePlayer) local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0 local text = ({ "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" })[adminLevel] or "Player" local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0 if (hiddenAdmin==1) then text = text .. " (Hidden)" end return text end function getAdminCount() local online, duty, lead, leadduty = 0, 0, 0, 0 for key, value in ipairs(getElementsByType("player")) do if (isElement(value)) then local level = getElementData( value, "adminlevel" ) or 0 if level >= 1 then online = online + 1 local aod = getElementData( value, "adminduty" ) or 0 if aod == 1 then duty = duty + 1 end if level >= 4 then lead = lead + 1 if aod == 1 then leadduty = leadduty + 1 end end end end end return online, duty, lead, leadduty end -- update the labels local function updateGUI() if statusLabel then local online, duty, lead, leadduty = getAdminCount() local reporttext = "" if #unansweredReports > 0 then reporttext = ": #" .. table.concat(unansweredReports, ", #") end local ownreporttext = "" if #ownReports > 0 then ownreporttext = ": #" .. table.concat(ownReports, ", #") end local onduty = "Off Duty" if getElementData( localPlayer, "adminduty" ) == 1 then onduty = "On Duty" end guiSetText( statusLabel, getAdminTitle( localPlayer ) .. " :: " .. onduty .. " :: " .. getElementData( localPlayer, "gameaccountusername" ) .. " :: " .. duty .. "/" .. online .. " Admins :: " .. leadduty .. "/" .. lead .. " Lead+ Admins :: " .. ( openReports - handledReports ) .. " unanswered reports" .. reporttext .. " :: " .. handledReports .. " handled reports" .. ownreporttext ) end end -- create the gui local function createGUI() if statusLabel then destroyElement(statusLabel) statusLabel = nil end local adminlevel = getElementData( localPlayer, "adminlevel" ) if adminlevel then if adminlevel > 0 then statusLabel = guiCreateLabel( 5, sy - 20, sx - 10, 15, "", false ) updateGUI() --guiCreateLabel ( float x, float y, float width, float height, string text, bool relative, [element parent = nil] ) end end end addEventHandler( "onClientResourceStart", getResourceRootElement(), createGUI, false ) addEventHandler( "onClientElementDataChange", localPlayer, function(n) if n == "adminlevel" or n == "hiddenadmin" then createGUI() end end, false ) addEventHandler( "onClientElementDataChange", getRootElement(), function(n) if getElementType(source) == "player" and ( n == "adminlevel" or n == "adminduty" ) then updateGUI() end end ) addEvent( "updateReportsCount", true ) addEventHandler( "updateReportsCount", getLocalPlayer(), function( open, handled, unanswered, own ) openReports = open handledReports = handled unansweredReports = unanswered ownReports = own or {} updateGUI() end, false ) addEventHandler( "onClientPlayerQuit", getRootElement(), updateGUI )
bugfix
bugfix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1932 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
7360cfb4cf2c7dd8c73adf45e31a04811a745250
spec/cache_spec.lua
spec/cache_spec.lua
local cache = require "luacheck.cache" local fs = require "luacheck.fs" local lfs = require "lfs" local sha1 = require "luacheck.vendor.sha1" setup(function() end) describe("cache", function() describe("get_default_dir", function() it("returns a string", function() assert.is_string(cache.get_default_dir()) end) end) describe("new", function() it("returns nil, error message on failure to init cache", function() local c, err = cache.new("LICENSE") assert.is_nil(c) assert.is_string(err) end) it("returns Cache object on success", function() local c = cache.new("src") assert.is_table(c) end) end) describe("Cache", function() local filename = "spec/caches/file.lua" local normalized_filename = fs.normalize(fs.join(fs.get_current_dir(), filename)) local cache_dir = "spec/caches" local cache_filename = fs.join(cache_dir, sha1.sha1(normalized_filename)) local c before_each(function() c = cache.new(cache_dir) assert.is_table(c) end) after_each(function() os.remove(filename) os.remove(cache_filename) end) local function make_report(code) return { warnings = { code and {code = code} }, inline_options = {}, line_lengths = {} } end describe("put", function() it("returns nil on failure to store cache", function() lfs.mkdir(cache_filename) local ok = c:put(filename, make_report()) assert.is_nil(ok) end) it("returns true on successfull cache store", function() local ok = c:put(filename, make_report()) assert.is_true(ok) end) end) describe("get", function() it("returns nil on cache miss", function() local report, err = c:get(filename) assert.is_nil(report) assert.is_nil(err) end) it("returns nil on outdated cache", function() assert.is_true(c:put(filename, make_report())) io.open(filename, "w"):close() assert.is_true(lfs.touch(filename, os.time() + 100000)) local report, err = c:get(filename) assert.is_nil(report) assert.is_nil(err) end) it("returns report on success", function() local original_report = make_report("111") assert.is_true(c:put(filename, original_report)) io.open(filename, "w"):close() assert.is_true(lfs.touch(filename, os.time() - 100000)) local cached_report = c:get(filename) assert.same(original_report, cached_report) end) end) end) end)
local cache = require "luacheck.cache" local fs = require "luacheck.fs" local lfs = require "lfs" local sha1 = require "luacheck.vendor.sha1" setup(function() end) describe("cache", function() describe("get_default_dir", function() it("returns a string", function() assert.is_string(cache.get_default_dir()) end) end) describe("new", function() it("returns nil, error message on failure to init cache", function() local c, err = cache.new("LICENSE") assert.is_nil(c) assert.is_string(err) end) it("returns Cache object on success", function() local c = cache.new("src") assert.is_table(c) end) end) describe("Cache", function() local filename = "spec/caches/file.lua" local normalized_filename = fs.normalize(fs.join(fs.get_current_dir(), filename)) local cache_dir = "spec/caches" local cache_filename = fs.join(cache_dir, sha1.sha1(normalized_filename)) local c before_each(function() c = cache.new(cache_dir) assert.is_table(c) end) after_each(function() os.remove(filename) if lfs.attributes(cache_filename, "mode") == "directory" then lfs.rmdir(cache_filename) else os.remove(cache_filename) end end) local function make_report(code) return { warnings = { code and {code = code} }, inline_options = {}, line_lengths = {} } end describe("put", function() it("returns nil on failure to store cache", function() lfs.mkdir(cache_filename) local ok = c:put(filename, make_report()) assert.is_nil(ok) end) it("returns true on successfull cache store", function() local ok = c:put(filename, make_report()) assert.is_true(ok) end) end) describe("get", function() it("returns nil on cache miss", function() local report, err = c:get(filename) assert.is_nil(report) assert.is_nil(err) end) it("returns nil on outdated cache", function() assert.is_true(c:put(filename, make_report())) io.open(filename, "w"):close() assert.is_true(lfs.touch(filename, os.time() + 100000)) local report, err = c:get(filename) assert.is_nil(report) assert.is_nil(err) end) it("returns report on success", function() local original_report = make_report("111") assert.is_true(c:put(filename, original_report)) io.open(filename, "w"):close() assert.is_true(lfs.touch(filename, os.time() - 100000)) local cached_report = c:get(filename) assert.same(original_report, cached_report) end) end) end) end)
Fix spec for windows
Fix spec for windows
Lua
mit
mpeterv/luacheck,xpol/luacheck,xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,xpol/luacheck
e7d71c4ab698a20c560f43545704d3b7609dfd59
objects/internal/scrollable/scrollbody.lua
objects/internal/scrollable/scrollbody.lua
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2012-2014 Kenny Shields -- --]]------------------------------------------------ -- scrollbar class local newobject = loveframes.NewObject("scrollbody", "loveframes_object_scrollbody", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize(parent, bartype) self.type = "scrollbody" self.bartype = bartype self.parent = parent self.x = 0 self.y = 0 self.internal = true self.internals = {} if self.bartype == "vertical" then self.width = 16 self.height = self.parent.height self.staticx = self.parent.width - self.width self.staticy = 0 elseif self.bartype == "horizontal" then self.width = self.parent.width self.height = 16 self.staticx = 0 self.staticy = self.parent.height - self.height end table.insert(self.internals, loveframes.objects["scrollarea"]:new(self, bartype)) local bar = self.internals[1].internals[1] if self.bartype == "vertical" then local upbutton = loveframes.objects["scrollbutton"]:new("up") upbutton.staticx = 0 + self.width - upbutton.width upbutton.staticy = 0 upbutton.parent = self upbutton.Update = function(object, dt) upbutton.staticx = 0 + self.width - upbutton.width upbutton.staticy = 0 if object.down and object.hover then local dtscrolling = self.parent.dtscrolling if dtscrolling then local dt = love.timer.getDelta() bar:Scroll(-self.parent.buttonscrollamount * dt) else bar:Scroll(-self.parent.buttonscrollamount) end end end local downbutton = loveframes.objects["scrollbutton"]:new("down") downbutton.parent = self downbutton.staticx = 0 + self.width - downbutton.width downbutton.staticy = 0 + self.height - downbutton.height downbutton.Update = function(object, dt) downbutton.staticx = 0 + self.width - downbutton.width downbutton.staticy = 0 + self.height - downbutton.height if object.down and object.hover then local dtscrolling = self.parent.dtscrolling if dtscrolling then local dt = love.timer.getDelta() bar:Scroll(self.parent.buttonscrollamount * dt) else bar:Scroll(self.parent.buttonscrollamount) end end end table.insert(self.internals, upbutton) table.insert(self.internals, downbutton) elseif self.bartype == "horizontal" then local leftbutton = loveframes.objects["scrollbutton"]:new("left") leftbutton.parent = self leftbutton.staticx = 0 leftbutton.staticy = 0 leftbutton.Update = function(object, dt) leftbutton.staticx = 0 leftbutton.staticy = 0 if object.down and object.hover then local dtscrolling = self.parent.dtscrolling if dtscrolling then local dt = love.timer.getDelta() bar:Scroll(-self.parent.buttonscrollamount * dt) else bar:Scroll(-self.parent.buttonscrollamount) end end end local rightbutton = loveframes.objects["scrollbutton"]:new("right") rightbutton.parent = self rightbutton.staticx = 0 + self.width - rightbutton.width rightbutton.staticy = 0 rightbutton.Update = function(object, dt) rightbutton.staticx = 0 + self.width - rightbutton.width rightbutton.staticy = 0 if object.down and object.hover then local dtscrolling = self.parent.dtscrolling if dtscrolling then local dt = love.timer.getDelta() bar:Scroll(self.parent.buttonscrollamount * dt) else bar:Scroll(self.parent.buttonscrollamount) end end end table.insert(self.internals, leftbutton) table.insert(self.internals, rightbutton) end local parentstate = parent.state self:SetState(parentstate) -- apply template properties to the object loveframes.templates.ApplyToObject(self) end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end self:CheckHover() local parent = self.parent local base = loveframes.base local update = self.Update local internals = self.internals -- move to parent if there is a parent if parent ~= base then self.x = parent.x + self.staticx self.y = parent.y + self.staticy end for k, v in ipairs(internals) do v:update(dt) end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local visible = self.visible if not visible then return end local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawScrollBody or skins[defaultskin].DrawScrollBody local draw = self.Draw local drawcount = loveframes.drawcount local internals = self.internals -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end for k, v in ipairs(internals) do v:draw() end end --[[--------------------------------------------------------- - func: GetScrollBar() - desc: gets the object's scroll bar --]]--------------------------------------------------------- function newobject:GetScrollBar() return self.internals[1].internals[1] end
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2012-2014 Kenny Shields -- --]]------------------------------------------------ -- scrollbar class local newobject = loveframes.NewObject("scrollbody", "loveframes_object_scrollbody", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize(parent, bartype) self.type = "scrollbody" self.bartype = bartype self.parent = parent self.x = 0 self.y = 0 self.internal = true self.internals = {} if self.bartype == "vertical" then self.width = 16 self.height = self.parent.height self.staticx = self.parent.width - self.width self.staticy = 0 elseif self.bartype == "horizontal" then self.width = self.parent.width self.height = 16 self.staticx = 0 self.staticy = self.parent.height - self.height end table.insert(self.internals, loveframes.objects["scrollarea"]:new(self, bartype)) local bar = self.internals[1].internals[1] if self.bartype == "vertical" then local upbutton = loveframes.objects["scrollbutton"]:new("up") upbutton.staticx = 0 + self.width - upbutton.width upbutton.staticy = 0 upbutton.parent = self upbutton.Update = function(object, dt) upbutton.staticx = 0 + self.width - upbutton.width upbutton.staticy = 0 if object.down and object.hover then local dtscrolling = self.parent.dtscrolling if dtscrolling then local dt = love.timer.getDelta() bar:Scroll(-self.parent.buttonscrollamount * dt) else bar:Scroll(-self.parent.buttonscrollamount) end end end local downbutton = loveframes.objects["scrollbutton"]:new("down") downbutton.parent = self downbutton.staticx = 0 + self.width - downbutton.width downbutton.staticy = 0 + self.height - downbutton.height downbutton.Update = function(object, dt) downbutton.staticx = 0 + self.width - downbutton.width downbutton.staticy = 0 + self.height - downbutton.height downbutton.x = downbutton.parent.x + downbutton.staticx downbutton.y = downbutton.parent.y + downbutton.staticy if object.down and object.hover then local dtscrolling = self.parent.dtscrolling if dtscrolling then local dt = love.timer.getDelta() bar:Scroll(self.parent.buttonscrollamount * dt) else bar:Scroll(self.parent.buttonscrollamount) end end end table.insert(self.internals, upbutton) table.insert(self.internals, downbutton) elseif self.bartype == "horizontal" then local leftbutton = loveframes.objects["scrollbutton"]:new("left") leftbutton.parent = self leftbutton.staticx = 0 leftbutton.staticy = 0 leftbutton.Update = function(object, dt) leftbutton.staticx = 0 leftbutton.staticy = 0 if object.down and object.hover then local dtscrolling = self.parent.dtscrolling if dtscrolling then local dt = love.timer.getDelta() bar:Scroll(-self.parent.buttonscrollamount * dt) else bar:Scroll(-self.parent.buttonscrollamount) end end end local rightbutton = loveframes.objects["scrollbutton"]:new("right") rightbutton.parent = self rightbutton.staticx = 0 + self.width - rightbutton.width rightbutton.staticy = 0 rightbutton.Update = function(object, dt) rightbutton.staticx = 0 + self.width - rightbutton.width rightbutton.staticy = 0 rightbutton.x = rightbutton.parent.x + rightbutton.staticx rightbutton.y = rightbutton.parent.y + rightbutton.staticy if object.down and object.hover then local dtscrolling = self.parent.dtscrolling if dtscrolling then local dt = love.timer.getDelta() bar:Scroll(self.parent.buttonscrollamount * dt) else bar:Scroll(self.parent.buttonscrollamount) end end end table.insert(self.internals, leftbutton) table.insert(self.internals, rightbutton) end local parentstate = parent.state self:SetState(parentstate) -- apply template properties to the object loveframes.templates.ApplyToObject(self) end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end self:CheckHover() local parent = self.parent local base = loveframes.base local update = self.Update local internals = self.internals -- move to parent if there is a parent if parent ~= base then self.x = parent.x + self.staticx self.y = parent.y + self.staticy end for k, v in ipairs(internals) do v:update(dt) end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local visible = self.visible if not visible then return end local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawScrollBody or skins[defaultskin].DrawScrollBody local draw = self.Draw local drawcount = loveframes.drawcount local internals = self.internals -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end for k, v in ipairs(internals) do v:draw() end end --[[--------------------------------------------------------- - func: GetScrollBar() - desc: gets the object's scroll bar --]]--------------------------------------------------------- function newobject:GetScrollBar() return self.internals[1].internals[1] end
Fix scrollbutton positioning issues
Fix scrollbutton positioning issues
Lua
mit
SimLeek/the-Open-Source-Pony-Game
d39fcf298c8ad026c92ba5fe600769706a5c9b0b
data/level.lua
data/level.lua
photon.gui.set_message("first I want you to gather 12 tnt...", 4) photon.player.set_location(5, 2) photon.level.set_victory_condition(function() if photon.player.get_item_count("tnt") >= 12 then photon.player.snap_to_beam(false) photon.gui.set_message("good work! now destroy all the targets...", 4) -- photon.level.set_victory_condition(function() if photon.level.get_item_count("target") < 1 then photon.gui.set_message("congradulations you have won!\nnow leave the level using a reciever.", 4) return 1; end return 0 end) end return 0 end)
-- sets the popup message with a timeout of 4 seconds. photon.gui.set_message("first I want you to gather 12 tnt...", 4) -- sets the photon's location. photon.player.set_location(5, 2) -- victory condition function returns > 0 on victory, < 0 on defeat and 0 otherwise. photon.level.set_victory_condition(function() if photon.player.get_item_count("tnt") >= 12 then -- enables free movement. photon.player.snap_to_beam(false) photon.gui.set_message("good work! now destroy all the targets...", 4) -- sets a new victory condition. (objective 2) photon.level.set_victory_condition(function() if photon.level.get_item_count("target") < 1 then photon.gui.set_message("congratulations you have won!\nnow leave the level using a reciever.", 4) return 1; end return 0 end) end return 0 end)
added comments to level.lua fixed spelling of "congratulations"
added comments to level.lua fixed spelling of "congratulations"
Lua
mit
chipgw/photon-legacy,chipgw/photon-legacy
7d1828ea8d5b1417bb95f5b6679f572d68956774
busted/outputHandlers/junit.lua
busted/outputHandlers/junit.lua
local xml = require 'pl.xml' local hostname = assert(io.popen('uname -n')):read('*l') return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) local node handler.testEnd = function(element, parent, status) node.attr.tests = node.attr.tests + 1 node:addtag('testcase', { classname = element.trace.short_src .. ':' .. element.trace.currentline, name = element.name }) if status == 'failure' then node.attr.failures = node.attr.failures + 1 end return nil, true end handler.suiteStart = function(name, parent) node = xml.new('testsuite', { tests = 0, errors = 0, failures = 0, skip = 0, header = 'Busted Suite', hostname = hostname, timestamp = os.time() }) return nil, true end handler.suiteEnd = function(name, parent) local ms = handler.getDuration() node.attr.time = ms print(xml.tostring(node, '', '\t')) return nil, true end handler.error = function(element, parent, message, trace) node:addtag('failure', { message = message }):text(trace.traceback):up() return nil, true end busted.subscribe({ 'test', 'end' }, handler.testEnd) busted.subscribe({ 'suite', 'start' }, handler.suiteStart) busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) busted.subscribe({ 'error', 'file' }, handler.error) busted.subscribe({ 'error', 'describe' }, handler.error) return handler end
local xml = require 'pl.xml' local socket = require("socket") local string = require("string") return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) local xml_doc local suiteStartTime, suiteEndTime handler.suiteStart = function() suiteStartTime = socket.gettime() xml_doc = xml.new('testsuite', { tests = 0, errors = 0, failures = 0, skip = 0, }) return nil, true end local function now() return string.format("%.2f", (socket.gettime() - suiteStartTime)) end handler.suiteEnd = function() xml_doc.attr.time = now() print(xml.tostring(xml_doc, '', '\t', nil, false)) return nil, true end handler.testEnd = function(element, parent, status) xml_doc.attr.tests = xml_doc.attr.tests + 1 local testcase_node = xml.new('testcase', { classname = element.trace.short_src .. ':' .. element.trace.currentline, name = handler.getFullName(element), time = now() }) xml_doc:add_direct_child(testcase_node) if status == 'failure' then xml_doc.attr.failures = xml_doc.attr.failures + 1 testcase_node:addtag('failure') testcase_node:text(element.trace.traceback) testcase_node:up() end return nil, true end handler.errorFile = function() if status == 'failure' then xml_doc.attr.errors = xml_doc.attr.errors + 1 end xml_doc:addtag('failure', {}):text(trace.traceback):up() return nil, true end busted.subscribe({ 'suite', 'start' }, handler.suiteStart) busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) busted.subscribe({ 'test', 'end' }, handler.testEnd) busted.subscribe({ 'error', 'file' }, handler.errorFile) return handler end
Fix junit -- @benbarbour
Fix junit -- @benbarbour
Lua
mit
leafo/busted,sobrinho/busted,Olivine-Labs/busted,DorianGray/busted,istr/busted,xyliuke/busted,o-lim/busted,nehz/busted,ryanplusplus/busted,mpeterv/busted
0a9d0cbd4e602936d76168c75099ffaeaf157a60
genie.lua
genie.lua
function linkMono() libdirs {[[c:/Program Files/Mono/lib/]]} end project "lumixengine_csharp" libType() files { "src/**.c", "src/api.txt", "src/**.cpp", "src/**.h", "src/**.inl", "genie.lua" } includedirs { "../lumixengine_csharp/src", [[c:/Program Files/Mono/include/mono-2.0]] } buildoptions { "/wd4267", "/wd4244" } defines { "BUILDING_CSHARP" } links { "engine" } useLua() defaultConfigurations() postbuildcommands { "xcopy /Y \"c:\\Program Files\\Mono\\bin\\mono-2.0-sgen.dll\" \"$(SolutionDir)bin\\Debug\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\mscorlib.dll\" \"$(SolutionDir)bin\\Debug\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\system.dll\" \"$(SolutionDir)bin\\Debug\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\system.configuration.dll\" \"$(SolutionDir)bin\\Debug\"", } table.insert(build_app_callbacks, linkMono) table.insert(build_studio_callbacks, linkMono)
function linkMono() libdirs {[[c:/Program Files/Mono/lib/]]} end project "lumixengine_csharp" libType() files { "src/**.c", "src/api.txt", "src/**.cpp", "src/**.h", "src/**.inl", "genie.lua" } includedirs { "../lumixengine_csharp/src", [[c:/Program Files/Mono/include/mono-2.0]] } buildoptions { "/wd4267", "/wd4244" } defines { "BUILDING_CSHARP" } links { "engine" } useLua() defaultConfigurations() configuration { "Debug" } postbuildcommands { "xcopy /Y \"c:\\Program Files\\Mono\\bin\\mono-2.0-sgen.dll\" \"$(SolutionDir)bin\\Debug\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\mscorlib.dll\" \"$(SolutionDir)bin\\Debug\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\system.dll\" \"$(SolutionDir)bin\\Debug\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\system.configuration.dll\" \"$(SolutionDir)bin\\Debug\"", } configuration { "RelWithDebInfo" } postbuildcommands { "xcopy /Y \"c:\\Program Files\\Mono\\bin\\mono-2.0-sgen.dll\" \"$(SolutionDir)bin\\RelWithDebInfo\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\mscorlib.dll\" \"$(SolutionDir)bin\\RelWithDebInfo\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\system.dll\" \"$(SolutionDir)bin\\RelWithDebInfo\"", "xcopy /Y \"c:\\Program Files\\Mono\\lib\\mono\\4.5\\system.configuration.dll\" \"$(SolutionDir)bin\\RelWithDebInfo\"", } table.insert(build_app_callbacks, linkMono) table.insert(build_studio_callbacks, linkMono)
fixed release build
fixed release build
Lua
mit
nem0/lumixengine_csharp,nem0/lumixengine_csharp
ff9da6cb7657704b07ed35b4ffb17b9d2bece43d
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/conntrack.lua
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/conntrack.lua
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.conntrack",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { title = "%H: Conntrack entries", vlabel = "Count", number_format = "%5.0lf", data = { sources = { conntrack = { "value" } }, options = { conntrack = { color = "0000ff", title = "Tracked connections" } } } } end
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.conntrack",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { title = "%H: Conntrack entries", vlabel = "Count", number_format = "%5.0lf", data = { -- collectd 5.5+: specify "" to exclude "max" instance instances = { conntrack = { "" } }, sources = { conntrack = { "value" } }, options = { conntrack = { color = "0000ff", title = "Tracked connections" } } } } end
statistics: fix conntrack regression caused by collectd 5.5.0
statistics: fix conntrack regression caused by collectd 5.5.0 Collectd 5.5.0 introduced new data to conntrack plugin: In addition to the number of tracked connections there is also the static max conntrack value and the calculated use percentage. Luci's conntrack plugin intrepretes "conntrack-max" as a new data instance and includes it in the graph in addition to the real "conntrack" number. Eliminate "max" from graph by specifying empty "" instance as data source. Signed-off-by: Hannu Nyman <ab53a3387de93e31696058c104e6f769cd83fd1b@iki.fi>
Lua
apache-2.0
LuttyYang/luci,hnyman/luci,cshore/luci,bright-things/ionic-luci,artynet/luci,maxrio/luci981213,kuoruan/lede-luci,wongsyrone/luci-1,LuttyYang/luci,981213/luci-1,cappiewu/luci,artynet/luci,chris5560/openwrt-luci,zhaoxx063/luci,kuoruan/luci,ollie27/openwrt_luci,jorgifumi/luci,remakeelectric/luci,daofeng2015/luci,cappiewu/luci,tobiaswaldvogel/luci,hnyman/luci,forward619/luci,nmav/luci,taiha/luci,cshore/luci,nmav/luci,thess/OpenWrt-luci,jchuang1977/luci-1,openwrt/luci,jlopenwrtluci/luci,teslamint/luci,wongsyrone/luci-1,oyido/luci,wongsyrone/luci-1,taiha/luci,ff94315/luci-1,oneru/luci,joaofvieira/luci,urueedi/luci,aa65535/luci,kuoruan/lede-luci,Wedmer/luci,jlopenwrtluci/luci,rogerpueyo/luci,forward619/luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,openwrt/luci,jorgifumi/luci,Wedmer/luci,chris5560/openwrt-luci,thesabbir/luci,oyido/luci,Noltari/luci,ff94315/luci-1,tobiaswaldvogel/luci,ff94315/luci-1,rogerpueyo/luci,cshore-firmware/openwrt-luci,hnyman/luci,wongsyrone/luci-1,Wedmer/luci,Wedmer/luci,bright-things/ionic-luci,bittorf/luci,daofeng2015/luci,thesabbir/luci,Noltari/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,dwmw2/luci,jlopenwrtluci/luci,teslamint/luci,mumuqz/luci,forward619/luci,forward619/luci,jchuang1977/luci-1,openwrt-es/openwrt-luci,mumuqz/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,nmav/luci,bittorf/luci,hnyman/luci,jorgifumi/luci,schidler/ionic-luci,Wedmer/luci,obsy/luci,mumuqz/luci,teslamint/luci,Hostle/luci,kuoruan/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,joaofvieira/luci,oyido/luci,marcel-sch/luci,jlopenwrtluci/luci,urueedi/luci,schidler/ionic-luci,bright-things/ionic-luci,remakeelectric/luci,kuoruan/lede-luci,cappiewu/luci,artynet/luci,obsy/luci,marcel-sch/luci,joaofvieira/luci,schidler/ionic-luci,dwmw2/luci,shangjiyu/luci-with-extra,cshore/luci,LuttyYang/luci,jchuang1977/luci-1,cappiewu/luci,daofeng2015/luci,bittorf/luci,openwrt-es/openwrt-luci,nmav/luci,taiha/luci,joaofvieira/luci,thesabbir/luci,bittorf/luci,kuoruan/lede-luci,cshore-firmware/openwrt-luci,cshore/luci,joaofvieira/luci,urueedi/luci,jlopenwrtluci/luci,forward619/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,LuttyYang/luci,remakeelectric/luci,Hostle/luci,teslamint/luci,dwmw2/luci,maxrio/luci981213,maxrio/luci981213,cshore/luci,MinFu/luci,oyido/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,openwrt/luci,kuoruan/luci,chris5560/openwrt-luci,rogerpueyo/luci,rogerpueyo/luci,nmav/luci,obsy/luci,remakeelectric/luci,ff94315/luci-1,oneru/luci,jlopenwrtluci/luci,bittorf/luci,rogerpueyo/luci,daofeng2015/luci,openwrt/luci,NeoRaider/luci,MinFu/luci,joaofvieira/luci,zhaoxx063/luci,chris5560/openwrt-luci,bright-things/ionic-luci,Hostle/luci,Noltari/luci,oyido/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,dwmw2/luci,marcel-sch/luci,oneru/luci,MinFu/luci,maxrio/luci981213,taiha/luci,artynet/luci,marcel-sch/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,tobiaswaldvogel/luci,cappiewu/luci,tobiaswaldvogel/luci,Hostle/luci,oneru/luci,hnyman/luci,chris5560/openwrt-luci,artynet/luci,oneru/luci,thesabbir/luci,kuoruan/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,chris5560/openwrt-luci,thess/OpenWrt-luci,schidler/ionic-luci,MinFu/luci,maxrio/luci981213,kuoruan/lede-luci,dwmw2/luci,obsy/luci,LuttyYang/luci,thesabbir/luci,teslamint/luci,maxrio/luci981213,rogerpueyo/luci,kuoruan/luci,aa65535/luci,zhaoxx063/luci,oneru/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,Noltari/luci,Noltari/luci,jorgifumi/luci,joaofvieira/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,forward619/luci,marcel-sch/luci,jorgifumi/luci,shangjiyu/luci-with-extra,teslamint/luci,urueedi/luci,marcel-sch/luci,mumuqz/luci,NeoRaider/luci,openwrt/luci,jlopenwrtluci/luci,oyido/luci,kuoruan/luci,oneru/luci,aa65535/luci,Noltari/luci,Wedmer/luci,daofeng2015/luci,NeoRaider/luci,nmav/luci,oyido/luci,bittorf/luci,zhaoxx063/luci,dwmw2/luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,mumuqz/luci,jlopenwrtluci/luci,981213/luci-1,kuoruan/luci,remakeelectric/luci,Hostle/luci,NeoRaider/luci,marcel-sch/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,maxrio/luci981213,thesabbir/luci,taiha/luci,lbthomsen/openwrt-luci,artynet/luci,cshore-firmware/openwrt-luci,urueedi/luci,mumuqz/luci,Wedmer/luci,Wedmer/luci,artynet/luci,kuoruan/lede-luci,daofeng2015/luci,ff94315/luci-1,jorgifumi/luci,obsy/luci,jchuang1977/luci-1,mumuqz/luci,thesabbir/luci,artynet/luci,remakeelectric/luci,Noltari/luci,cshore/luci,teslamint/luci,openwrt/luci,oneru/luci,cshore/luci,bittorf/luci,kuoruan/lede-luci,taiha/luci,981213/luci-1,jchuang1977/luci-1,thesabbir/luci,LuttyYang/luci,cappiewu/luci,Hostle/luci,bright-things/ionic-luci,dwmw2/luci,urueedi/luci,ff94315/luci-1,NeoRaider/luci,schidler/ionic-luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,NeoRaider/luci,LuttyYang/luci,hnyman/luci,ollie27/openwrt_luci,maxrio/luci981213,urueedi/luci,thess/OpenWrt-luci,mumuqz/luci,NeoRaider/luci,urueedi/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,MinFu/luci,taiha/luci,nmav/luci,obsy/luci,schidler/ionic-luci,daofeng2015/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,wongsyrone/luci-1,Noltari/luci,aa65535/luci,obsy/luci,aa65535/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,marcel-sch/luci,nmav/luci,remakeelectric/luci,dwmw2/luci,bittorf/luci,hnyman/luci,oyido/luci,openwrt/luci,remakeelectric/luci,LuttyYang/luci,forward619/luci,thess/OpenWrt-luci,NeoRaider/luci,zhaoxx063/luci,MinFu/luci,teslamint/luci,shangjiyu/luci-with-extra,zhaoxx063/luci,tobiaswaldvogel/luci,cappiewu/luci,cappiewu/luci,cshore-firmware/openwrt-luci,obsy/luci,nmav/luci,Noltari/luci,jchuang1977/luci-1,bright-things/ionic-luci,MinFu/luci,rogerpueyo/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,zhaoxx063/luci,openwrt/luci,kuoruan/luci,lbthomsen/openwrt-luci,MinFu/luci,981213/luci-1,Hostle/luci,kuoruan/lede-luci,ollie27/openwrt_luci,ff94315/luci-1,thess/OpenWrt-luci,aa65535/luci,981213/luci-1,thess/OpenWrt-luci,schidler/ionic-luci,hnyman/luci,rogerpueyo/luci,aa65535/luci,jorgifumi/luci,chris5560/openwrt-luci,aa65535/luci,chris5560/openwrt-luci,forward619/luci,daofeng2015/luci,joaofvieira/luci,bright-things/ionic-luci,Hostle/luci,taiha/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,981213/luci-1,artynet/luci,bright-things/ionic-luci,jorgifumi/luci,981213/luci-1,cshore/luci,ff94315/luci-1
9523035bc9ec53dfc30dbf092525fcf213eff126
Modules/Utility/Binder.lua
Modules/Utility/Binder.lua
--- Bind class to Roblox Instance -- @classmod Binder local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local CollectionService = game:GetService("CollectionService") local Maid = require("Maid") local fastSpawn = require("fastSpawn") local Binder = {} Binder.__index = Binder Binder.ClassName = "Binder" function Binder.new(tagName, class) local self = setmetatable({}, Binder) self._maid = Maid.new() self._tagName = tagName or error("No tagName") self._class = class or error("No class") for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do fastSpawn(function() self:_add(inst) end) end self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(self._tagName):Connect(function(inst) self:_add(inst) end)) self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(self._tagName):Connect(function(inst) self:_remove(inst) end)) return self end function Binder:Bind(inst) CollectionService:AddTag(inst, self._tagName) return self:Get(inst) end function Binder:Get(inst) return self._maid[inst] end function Binder:_add(inst) if self._maid[inst] then return end if type(self._class) == "function" then self._maid[inst] = self._class(inst) elseif self._class.Create then self._maid[inst] = self._class:Create(inst) else self._maid[inst] = self._class.new(inst) end end function Binder:_remove(inst) self._maid[inst] = nil end function Binder:Destroy() self._maid:DoCleaning() end return Binder
--- Bind class to Roblox Instance -- @classmod Binder local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local CollectionService = game:GetService("CollectionService") local Maid = require("Maid") local fastSpawn = require("fastSpawn") local Binder = {} Binder.__index = Binder Binder.ClassName = "Binder" function Binder.new(tagName, class) local self = setmetatable({}, Binder) self._maid = Maid.new() self._tagName = tagName or error("No tagName") self._class = class or error("No class") self._loading = setmetatable({}, {__mode = "kv"}) for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do fastSpawn(function() self:_add(inst) end) end self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(self._tagName):Connect(function(inst) self:_add(inst) end)) self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(self._tagName):Connect(function(inst) self:_remove(inst) end)) return self end function Binder:GetAll() local all = {} for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do table.insert(all, self._maid[inst]) end return all end function Binder:Bind(inst) CollectionService:AddTag(inst, self._tagName) return self:Get(inst) end function Binder:Get(inst) return self._maid[inst] end function Binder:_add(inst) if self._loading[inst] then return end self._loading[inst] = true if type(self._class) == "function" then self._maid[inst] = self._class(inst) elseif self._class.Create then self._maid[inst] = self._class:Create(inst) else self._maid[inst] = self._class.new(inst) end end function Binder:_remove(inst) self._maid[inst] = nil self._loading[inst] = nil end function Binder:Destroy() self._maid:DoCleaning() end return Binder
Fix binder with stuff that takes a while to load and fix spaces -> tabs
Fix binder with stuff that takes a while to load and fix spaces -> tabs
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
21ab12d9e566e1265b2940b149516b888b4bf6ab
lua/framework/graphics/mesh.lua
lua/framework/graphics/mesh.lua
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local GL = require( "opengl" ) local ffi = require( "ffi" ) class( "framework.graphics.mesh" ) local mesh = framework.graphics.mesh function mesh:mesh( vertices, count, textures ) self.vbo = ffi.new( "GLuint[1]" ) GL.glGenBuffers( 1, self.vbo ) GL.glBindBuffer( GL.GL_ARRAY_BUFFER, self.vbo[0] ) local size = ffi.sizeof( vertices ) GL.glBufferData( GL.GL_ARRAY_BUFFER, size, vertices, GL.GL_STATIC_DRAW ) self.vertices = vertices self.count = count for type, filename in pairs( textures ) do textures[ type ] = framework.graphics.newImage( filename ) end self.textures = textures setproxy( self ) end function mesh:draw( x, y, r, sx, sy, ox, oy, kx, ky ) local shader = framework.graphics.getShader() local position = GL.glGetAttribLocation( shader, "position" ) local stride = ( 3 + 3 + 3 + 2 ) * ffi.sizeof( "GLfloat" ) local pointer = ffi.cast( "GLvoid *", 3 * ffi.sizeof( "GLfloat" ) ) local normal = GL.glGetAttribLocation( shader, "normal" ) local tangent = GL.glGetAttribLocation( shader, "tangent" ) local texcoord = GL.glGetAttribLocation( shader, "texcoord" ) local defaultTexture = framework.graphics.getDefaultTexture() local textures = self.textures local diffuse = textures.diffuse or defaultTexture GL.glBindBuffer( GL.GL_ARRAY_BUFFER, self.vbo[0] ) GL.glVertexAttribPointer( position, 3, GL.GL_FLOAT, 0, stride, nil ) GL.glVertexAttribPointer( normal, 3, GL.GL_FLOAT, 0, stride, pointer ) pointer = ffi.cast( "GLvoid *", ( 3 + 3 ) * ffi.sizeof( "GLfloat" ) ) GL.glVertexAttribPointer( tangent, 3, GL.GL_FLOAT, 0, stride, pointer ) pointer = ffi.cast( "GLvoid *", ( 3 + 3 + 3 ) * ffi.sizeof( "GLfloat" ) ) GL.glVertexAttribPointer( texcoord, 2, GL.GL_FLOAT, 0, stride, pointer ) framework.graphics.updateTransformations() GL.glBindTexture( GL.GL_TEXTURE_2D, diffuse[0] ) framework.graphics.drawArrays( GL.GL_TRIANGLES, 0, self.count ) end function mesh:__gc() GL.glDeleteBuffers( 1, self.vbo ) end
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local GL = require( "opengl" ) local ffi = require( "ffi" ) class( "framework.graphics.mesh" ) local mesh = framework.graphics.mesh function mesh:mesh( vertices, count, textures ) self.vbo = ffi.new( "GLuint[1]" ) GL.glGenBuffers( 1, self.vbo ) GL.glBindBuffer( GL.GL_ARRAY_BUFFER, self.vbo[0] ) local size = ffi.sizeof( vertices ) GL.glBufferData( GL.GL_ARRAY_BUFFER, size, vertices, GL.GL_STATIC_DRAW ) self.vertices = vertices self.count = count for type, filename in pairs( textures ) do textures[ type ] = framework.graphics.newImage( filename ) end self.textures = textures setproxy( self ) end function mesh:draw( x, y, r, sx, sy, ox, oy, kx, ky ) local shader = framework.graphics.getShader() local position = GL.glGetAttribLocation( shader, "position" ) local stride = ( 3 + 3 + 3 + 2 ) * ffi.sizeof( "GLfloat" ) local pointer = ffi.cast( "GLvoid *", 3 * ffi.sizeof( "GLfloat" ) ) local normal = GL.glGetAttribLocation( shader, "normal" ) local tangent = GL.glGetAttribLocation( shader, "tangent" ) local texcoord = GL.glGetAttribLocation( shader, "texcoord" ) local defaultTexture = framework.graphics.getDefaultTexture() local textures = self.textures local diffuse = textures.diffuse and textures.diffuse.texture or defaultTexture GL.glBindBuffer( GL.GL_ARRAY_BUFFER, self.vbo[0] ) GL.glVertexAttribPointer( position, 3, GL.GL_FLOAT, 0, stride, nil ) GL.glVertexAttribPointer( normal, 3, GL.GL_FLOAT, 0, stride, pointer ) pointer = ffi.cast( "GLvoid *", ( 3 + 3 ) * ffi.sizeof( "GLfloat" ) ) GL.glVertexAttribPointer( tangent, 3, GL.GL_FLOAT, 0, stride, pointer ) pointer = ffi.cast( "GLvoid *", ( 3 + 3 + 3 ) * ffi.sizeof( "GLfloat" ) ) GL.glVertexAttribPointer( texcoord, 2, GL.GL_FLOAT, 0, stride, pointer ) framework.graphics.updateTransformations() GL.glBindTexture( GL.GL_TEXTURE_2D, diffuse[0] ) framework.graphics.drawArrays( GL.GL_TRIANGLES, 0, self.count ) end function mesh:__gc() GL.glDeleteBuffers( 1, self.vbo ) end
Fix crash in mesh:draw()
Fix crash in mesh:draw()
Lua
mit
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
fa1f4c42a6e73483d8ed6284b177e5648f44a114
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/apcups.lua
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/apcups.lua
-- Copyright 2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.apcups",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) local voltagesdc = { title = "%H: Voltages on APC UPS - Battery", vlabel = "Volts DC", alt_autoscale = true, number_format = "%5.1lfV", data = { instances = { voltage = { "battery" } }, options = { voltage = { title = "Battery voltage", noarea=true } } } } local voltages = { title = "%H: Voltages on APC UPS - AC", vlabel = "Volts AC", alt_autoscale = true, number_format = "%5.1lfV", data = { instances = { voltage = { "input", "output" } }, options = { voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true }, voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true } } } } local percentload = { title = "%H: Load on APC UPS ", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { sources = { percent_load = { "value" } }, instances = { percent = "load" }, options = { percent_load = { color = "00ff00", title = "Load level" } } } } local charge_percent = { title = "%H: Battery charge on APC UPS ", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { types = { "charge" }, options = { charge = { color = "00ff0b", title = "Charge level" } } } } local temperature = { title = "%H: Battery temperature on APC UPS ", vlabel = "\176C", number_format = "%5.1lf\176C", data = { types = { "temperature" }, options = { temperature = { color = "ffb000", title = "Battery temperature" } } } } local timeleft = { title = "%H: Time left on APC UPS ", vlabel = "Minutes", number_format = "%.1lfm", data = { sources = { timeleft = { "value" } }, options = { timeleft = { color = "0000ff", title = "Time left" } } } } local frequency = { title = "%H: Incoming line frequency on APC UPS ", vlabel = "Hz", number_format = "%5.0lfhz", data = { sources = { frequency_input = { "value" } }, instances = { frequency = "frequency" }, options = { frequency_frequency = { color = "000fff", title = "Line frequency" } } } } return { voltages, voltagesdc, percentload, charge_percent, temperature, timeleft, frequency } end
-- Copyright 2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.apcups",package.seeall) function rrdargs( graph, plugin, plugin_instance ) local lu = require("luci.util") local rv = { } -- Types and instances supported by APC UPS -- e.g. ups_types -> { 'timeleft', 'charge', 'percent', 'voltage' } -- e.g. ups_inst['voltage'] -> { 'input', 'battery' } local ups_types = graph.tree:data_types( plugin, plugin_instance ) local ups_inst = {} for _, t in ipairs(ups_types) do ups_inst[t] = graph.tree:data_instances( plugin, plugin_instance, t ) end -- Check if hash table or array is empty or nil-filled local function empty( t ) for _, v in pairs(t) do if type(v) then return false end end return true end -- Append graph definition but only types/instances which are -- supported and available to the plugin and UPS. local function add_supported( t, defs ) local def_inst = defs['data']['instances'] if type(def_inst) == "table" then for k, v in pairs( def_inst ) do if lu.contains( ups_types, k) then for j = #v, 1, -1 do if not lu.contains( ups_inst[k], v[j] ) then table.remove( v, j ) end end if #v == 0 then def_inst[k] = nil -- can't assign v: immutable end else def_inst[k] = nil -- can't assign v: immutable end end if empty(def_inst) then return end end table.insert( t, defs ) end -- Graph definitions for APC UPS measurements MUST use only 'instances': -- e.g. instances = { voltage = { "input", "output" } } local voltagesdc = { title = "%H: Voltages on APC UPS - Battery", vlabel = "Volts DC", alt_autoscale = true, number_format = "%5.1lfV", data = { instances = { voltage = { "battery" } }, options = { voltage = { title = "Battery voltage", noarea=true } } } } add_supported( rv, voltagesdc ) local voltagesac = { title = "%H: Voltages on APC UPS - AC", vlabel = "Volts AC", alt_autoscale = true, number_format = "%5.1lfV", data = { instances = { voltage = { "input", "output" } }, options = { voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true }, voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true } } } } add_supported( rv, voltagesac ) local percentload = { title = "%H: Load on APC UPS ", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { instances = { percent = { "load" } }, options = { percent_load = { color = "00ff00", title = "Load level" } } } } add_supported( rv, percentload ) local charge_percent = { title = "%H: Battery charge on APC UPS ", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { instances = { charge = { "" } }, options = { charge = { color = "00ff0b", title = "Charge level" } } } } add_supported( rv, charge_percent ) local temperature = { title = "%H: Battery temperature on APC UPS ", vlabel = "\176C", number_format = "%5.1lf\176C", data = { instances = { temperature = { "" } }, options = { temperature = { color = "ffb000", title = "Battery temperature" } } } } add_supported( rv, temperature ) local timeleft = { title = "%H: Time left on APC UPS ", vlabel = "Minutes", number_format = "%.1lfm", data = { instances = { timeleft = { "" } }, options = { timeleft = { color = "0000ff", title = "Time left" } } } } add_supported( rv, timeleft ) local frequency = { title = "%H: Incoming line frequency on APC UPS ", vlabel = "Hz", number_format = "%5.0lfhz", data = { instances = { frequency = { "input" } }, options = { frequency_input = { color = "000fff", title = "Line frequency" } } } } add_supported( rv, frequency ) return rv end
luci-app-statistics: only graph data supported by APC UPS
luci-app-statistics: only graph data supported by APC UPS Some graph definitions rely on data not supported across all APC UPSes. Due to recent upstream changes in collectd, the daemon no longer creates a NaN-filled .rrd file corresponding to any missing UPS data. Depending on the connected UPS, this may result in some "broken" graphs on the Luci Statistics page since rrdtool cannot find the expected .rrd file. Include the add_supported() function to determine the UPS data available at runtime and update any definitions of graphs to include only supported data. For example, the whole chart stack of AC input and output voltages will normally be "broken" if the UPS only measures AC input voltage. With these changes, the output voltage graph definition is stripped out, allowing the chart to render. Make consistent use of data types and instances in graph definitions. All definitions now use the same format with the 'instances' key. Unnecessary 'types' and 'sources' keys are removed. Fix the definition of 'line frequency' graph, based on upstream collectd apcups plugin code: type is 'frequency' but instance should be 'input'. This also includes some code and whitespace cleanup. Signed-off-by: Tony Ambardar <bbfa239b825380bdb0e5c28c3e9e3aefb0799170@yahoo.com>
Lua
apache-2.0
chris5560/openwrt-luci,artynet/luci,tobiaswaldvogel/luci,rogerpueyo/luci,nmav/luci,hnyman/luci,artynet/luci,chris5560/openwrt-luci,kuoruan/luci,openwrt-es/openwrt-luci,hnyman/luci,openwrt-es/openwrt-luci,hnyman/luci,artynet/luci,remakeelectric/luci,Noltari/luci,openwrt/luci,kuoruan/lede-luci,kuoruan/luci,tobiaswaldvogel/luci,remakeelectric/luci,openwrt/luci,nmav/luci,artynet/luci,wongsyrone/luci-1,981213/luci-1,nmav/luci,hnyman/luci,nmav/luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,artynet/luci,kuoruan/lede-luci,Noltari/luci,remakeelectric/luci,openwrt/luci,lbthomsen/openwrt-luci,artynet/luci,hnyman/luci,openwrt-es/openwrt-luci,kuoruan/luci,rogerpueyo/luci,kuoruan/lede-luci,981213/luci-1,tobiaswaldvogel/luci,tobiaswaldvogel/luci,artynet/luci,981213/luci-1,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,hnyman/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,hnyman/luci,openwrt/luci,wongsyrone/luci-1,chris5560/openwrt-luci,openwrt/luci,kuoruan/luci,artynet/luci,chris5560/openwrt-luci,openwrt/luci,remakeelectric/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,Noltari/luci,kuoruan/lede-luci,981213/luci-1,Noltari/luci,openwrt/luci,kuoruan/luci,remakeelectric/luci,tobiaswaldvogel/luci,981213/luci-1,nmav/luci,remakeelectric/luci,wongsyrone/luci-1,wongsyrone/luci-1,lbthomsen/openwrt-luci,artynet/luci,981213/luci-1,kuoruan/luci,nmav/luci,rogerpueyo/luci,kuoruan/luci,wongsyrone/luci-1,nmav/luci,remakeelectric/luci,rogerpueyo/luci,chris5560/openwrt-luci,kuoruan/luci,remakeelectric/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,nmav/luci,wongsyrone/luci-1,Noltari/luci,kuoruan/lede-luci,Noltari/luci,tobiaswaldvogel/luci,Noltari/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,Noltari/luci,rogerpueyo/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,Noltari/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,kuoruan/lede-luci,981213/luci-1,rogerpueyo/luci,nmav/luci,kuoruan/lede-luci
16c5d0e0df2506791614c87eacbf0332e5b32921
packages/lime-system/files/usr/lib/lua/lime/config.lua
packages/lime-system/files/usr/lib/lua/lime/config.lua
#!/usr/bin/lua --! LibreMesh is modular but this doesn't mean parallel, modules are executed --! sequencially, so we don't need to worry about transactionality and all other --! stuff that affects parrallels database, at moment we don't need parallelism --! as this is just some configuration stuff and is not performance critical. local fs = require("nixio.fs") local libuci = require("uci") config = {} function config.log(...) print(...) end config.uci = nil config.hooksDir = "/etc/hotplug.d/lime-config" function config.get_uci_cursor() if config.uci == nil then config.uci = libuci:cursor() end return config.uci end function config.set_uci_cursor(cursor) config.uci = cursor end config.uci = config.get_uci_cursor() config.UCI_AUTOGEN_NAME = 'lime-autogen' config.UCI_NODE_NAME = 'lime-node' config.UCI_COMMUNITY_NAME = 'lime-community' config.UCI_DEFAULTS_NAME = 'lime-defaults' config.UCI_CONFIG_NAME = config.UCI_AUTOGEN_NAME function config.get_config_path() return config.uci:get_confdir() .. '/' .. config.UCI_CONFIG_NAME end function config.reset_node_config() config.initialize_config_file(config.UCI_NODE_NAME) end function config.initialize_config_file(config_name) local lime_path = config.uci:get_confdir() .. "/" .. config_name os.execute(string.format('cp /usr/share/lime/configs/%s %s', config_name, lime_path)) end function config.get(sectionname, option, fallback) local limeconf = config.uci:get(config.UCI_CONFIG_NAME, sectionname, option) if limeconf then return limeconf end if ( fallback ~= nil ) then config.log("Use fallback value for "..sectionname.."."..option..": "..tostring(fallback)) return fallback else config.log("WARNING: Attempt to access undeclared default for: "..sectionname.."."..option) config.log(debug.traceback()) return nil end end --! Execute +callback+ for each config of type +configtype+ found in --! +/etc/config/lime-autogen+. function config.foreach(configtype, callback) return config.uci:foreach(config.UCI_CONFIG_NAME, configtype, callback) end function config.get_all(sectionname) return config.uci:get_all(config.UCI_CONFIG_NAME, sectionname) end function config.get_bool(sectionname, option, default) local val = config.get(sectionname, option, default) return (val and ((val == '1') or (val == 'on') or (val == 'true') or (val == 'enabled') or (val == 1) or (val == true))) end config.batched = false function config.init_batch() config.batched = true end function config.set(...) local aty = type(arg[3]) if (aty ~= "nil" and aty ~= "string" and aty ~= "table") then arg[3] = tostring(arg[3]) end config.uci:set(config.UCI_CONFIG_NAME, unpack(arg)) if(not config.batched) then config.uci:save(config.UCI_CONFIG_NAME) end end function config.delete(...) config.uci:delete(config.UCI_CONFIG_NAME, unpack(arg)) if(not config.batched) then config.uci:save(config.UCI_CONFIG_NAME) end end function config.end_batch() if(config.batched) then config.uci:save(config.UCI_CONFIG_NAME) config.batched = false end end function config.autogenerable(section_name) return ( (not config.get_all(section_name)) or config.get_bool(section_name, "autogenerated") ) end --! Merge two uci files. If an option exists in both files the value of high_prio is selected function config.uci_merge_files(high_prio, low_prio, output) local uci = config.get_uci_cursor() local high_pt = uci:get_all(high_prio) local low_pt = uci:get_all(low_prio) --! populate high_prio with low_prio values that are not in high_prio for section_name, section in pairs(low_pt) do local high_section = high_pt[section_name] if high_section ~= nil then --! copy only some attributes for option_name, option in pairs(section) do --! if the options starts with a dot it is not a real options it is an attribute --! like .name, .type, .anonymous and .index if option_name[1] ~= '.' and high_section[option_name] == nil then high_section[option_name] = option end end else high_pt[section_name] = section end end --! populate output from high_prio using uci for section_name, section in pairs(high_pt) do local section_type = section['.type'] uci:set(output, section_name, section_type) for option_name, option in pairs(section) do --! if the options starts with a dot it is not a real options it is an attribute --! like .name, .type, .anonymous and .index if option_name[1] ~= '.' then local otype = type(option) if (otype ~= "nil" and otype ~= "string" and otype ~= "table") then option = tostring(option) end uci:set(output, section_name, option_name, option) end end end uci:commit(output) end function config.uci_autogen() --! start clearing the config local f = io.open(config.get_config_path(), "w") f:write('') f:close() --! clean uci cache local uci = config.get_uci_cursor() uci:load(config.UCI_AUTOGEN_NAME) for _, cfg_name in pairs({config.UCI_DEFAULTS_NAME, config.UCI_COMMUNITY_NAME, config.UCI_NODE_NAME}) do local cfg = io.open(config.uci:get_confdir() .. '/' .. cfg_name) if cfg ~= nil then config.uci_merge_files(cfg_name, config.UCI_AUTOGEN_NAME, config.UCI_AUTOGEN_NAME) end end uci:load(config.UCI_AUTOGEN_NAME) end --! commit all uci changes not yet commited function config.uci_commit_all() local uci = config.get_uci_cursor() for k, _ in pairs(uci:changes()) do assert(uci:commit(k)) end end function config.main() --! Populate the default template configs if lime-node and lime-community --! are not found in /etc/config for _, cfg_name in pairs({config.UCI_COMMUNITY_NAME, config.UCI_NODE_NAME}) do local lime_path = config.uci:get_confdir() .. "/" .. cfg_name local cf = io.open(lime_path) if not cf then config.initialize_config_file(cfg_name) else cf:close() end end config.uci_autogen() local modules_name = { "hardware_detection", "wireless", "network", "firewall", "system", "generic_config" } local modules = {} for i, name in pairs(modules_name) do modules[i] = require("lime."..name) end for _,module in pairs(modules) do xpcall(module.clean, function(errmsg) print(errmsg) ; print(debug.traceback()) end) end for _,module in pairs(modules) do xpcall(module.configure, function(errmsg) print(errmsg) ; print(debug.traceback()) end) end for hook in fs.dir(config.hooksDir) do local hookCmd = config.hooksDir.."/"..hook.." after" print("executed hook:", hookCmd, os.execute(hookCmd)) end local utils = require("lime.utils") -- here to break circular require local cfgpath = config.get_config_path() local autogen_content = utils.read_file(cfgpath) or '' notice_message = ('# DO NOT EDIT THIS FILE!. This is autogenerated by lime-config!\n' .. '# Instead please edit /etc/config/lime-node and/or /etc/config/lime-community files\n' .. '# and then regenerate this file executing lime-config\n\n') local uci = config.get_uci_cursor() uci:commit(config.UCI_CONFIG_NAME) utils.write_file(cfgpath, notice_message .. autogen_content) end return config
#!/usr/bin/lua --! LibreMesh is modular but this doesn't mean parallel, modules are executed --! sequencially, so we don't need to worry about transactionality and all other --! stuff that affects parrallels database, at moment we don't need parallelism --! as this is just some configuration stuff and is not performance critical. local fs = require("nixio.fs") local libuci = require("uci") config = {} function config.log(...) print(...) end config.uci = nil config.hooksDir = "/etc/hotplug.d/lime-config" function config.get_uci_cursor() if config.uci == nil then config.uci = libuci:cursor() end return config.uci end function config.set_uci_cursor(cursor) config.uci = cursor end config.uci = config.get_uci_cursor() config.UCI_AUTOGEN_NAME = 'lime-autogen' config.UCI_NODE_NAME = 'lime-node' config.UCI_COMMUNITY_NAME = 'lime-community' config.UCI_DEFAULTS_NAME = 'lime-defaults' config.UCI_CONFIG_NAME = config.UCI_AUTOGEN_NAME function config.get_config_path() return config.uci:get_confdir() .. '/' .. config.UCI_CONFIG_NAME end function config.reset_node_config() config.initialize_config_file(config.UCI_NODE_NAME) end function config.initialize_config_file(config_name) local lime_path = config.uci:get_confdir() .. "/" .. config_name os.execute(string.format('cp /usr/share/lime/configs/%s %s', config_name, lime_path)) end function config.get(sectionname, option, fallback) local limeconf = config.uci:get(config.UCI_CONFIG_NAME, sectionname, option) if limeconf then return limeconf end if ( fallback ~= nil ) then config.log("Use fallback value for "..sectionname.."."..option..": "..tostring(fallback)) return fallback else config.log("WARNING: Attempt to access undeclared default for: "..sectionname.."."..option) config.log(debug.traceback()) return nil end end --! Execute +callback+ for each config of type +configtype+ found in --! +/etc/config/lime-autogen+. function config.foreach(configtype, callback) return config.uci:foreach(config.UCI_CONFIG_NAME, configtype, callback) end function config.get_all(sectionname) return config.uci:get_all(config.UCI_CONFIG_NAME, sectionname) end function config.get_bool(sectionname, option, default) local val = config.get(sectionname, option, default) return (val and ((val == '1') or (val == 'on') or (val == 'true') or (val == 'enabled') or (val == 1) or (val == true))) end config.batched = false function config.init_batch() config.batched = true end function config.set(...) local aty = type(arg[3]) if (aty ~= "nil" and aty ~= "string" and aty ~= "table") then arg[3] = tostring(arg[3]) end config.uci:set(config.UCI_CONFIG_NAME, unpack(arg)) if(not config.batched) then config.uci:save(config.UCI_CONFIG_NAME) end end function config.delete(...) config.uci:delete(config.UCI_CONFIG_NAME, unpack(arg)) if(not config.batched) then config.uci:save(config.UCI_CONFIG_NAME) end end function config.end_batch() if(config.batched) then config.uci:save(config.UCI_CONFIG_NAME) config.batched = false end end function config.autogenerable(section_name) return ( (not config.get_all(section_name)) or config.get_bool(section_name, "autogenerated") ) end --! Merge two uci files. If an option exists in both files the value of high_prio is selected function config.uci_merge_files(high_prio, low_prio, output) local uci = config.get_uci_cursor() local high_pt = uci:get_all(high_prio) local low_pt = uci:get_all(low_prio) --! populate high_prio with low_prio values that are not in high_prio for section_name, section in pairs(low_pt) do local high_section = high_pt[section_name] if high_section ~= nil then --! copy only some attributes for option_name, option in pairs(section) do --! if the options starts with a dot it is not a real options it is an attribute --! like .name, .type, .anonymous and .index if option_name[1] ~= '.' and high_section[option_name] == nil then high_section[option_name] = option end end else high_pt[section_name] = section end end --! populate output from high_prio using uci for section_name, section in pairs(high_pt) do local section_type = section['.type'] uci:set(output, section_name, section_type) for option_name, option in pairs(section) do --! if the options starts with a dot it is not a real options it is an attribute --! like .name, .type, .anonymous and .index if option_name[1] ~= '.' then local otype = type(option) if (otype ~= "nil" and otype ~= "string" and otype ~= "table") then option = tostring(option) end uci:set(output, section_name, option_name, option) end end end uci:commit(output) end function config.uci_autogen() --! start clearing the config local f = io.open(config.get_config_path(), "w") f:write('') f:close() --! clean uci cache local uci = config.get_uci_cursor() uci:load(config.UCI_AUTOGEN_NAME) for _, cfg_name in pairs({config.UCI_DEFAULTS_NAME, config.UCI_COMMUNITY_NAME, config.UCI_NODE_NAME}) do local cfg = io.open(config.uci:get_confdir() .. '/' .. cfg_name) if cfg ~= nil then config.uci_merge_files(cfg_name, config.UCI_AUTOGEN_NAME, config.UCI_AUTOGEN_NAME) end end uci:load(config.UCI_AUTOGEN_NAME) end --! commit all uci changes not yet commited function config.uci_commit_all() local uci = config.get_uci_cursor() for k, _ in pairs(uci:changes()) do assert(uci:commit(k)) end end function config.main() --! Populate the default template configs if lime-node and lime-community --! are not found in /etc/config for _, cfg_name in pairs({config.UCI_COMMUNITY_NAME, config.UCI_NODE_NAME}) do local lime_path = config.uci:get_confdir() .. "/" .. cfg_name local cf = io.open(lime_path) if not cf then config.initialize_config_file(cfg_name) else cf:close() end end config.uci_autogen() local modules_name = { "hardware_detection", "wireless", "network", "firewall", "system", "generic_config" } local modules = {} for i, name in pairs(modules_name) do modules[i] = require("lime."..name) end for _,module in pairs(modules) do xpcall(module.clean, function(errmsg) print(errmsg) ; print(debug.traceback()) end) end for _,module in pairs(modules) do xpcall(module.configure, function(errmsg) print(errmsg) ; print(debug.traceback()) end) end for hook in fs.dir(config.hooksDir) do local hookCmd = config.hooksDir.."/"..hook.." after" print("executed hook:", hookCmd, os.execute(hookCmd)) end local utils = require("lime.utils") -- here to break circular require local cfgpath = config.get_config_path() --! flush all config changes local uci = config.get_uci_cursor() uci:commit(config.UCI_CONFIG_NAME) local autogen_content = utils.read_file(cfgpath) or '' notice_message = ('# DO NOT EDIT THIS FILE!. This is autogenerated by lime-config!\n' .. '# Instead please edit /etc/config/lime-node and/or /etc/config/lime-community files\n' .. '# and then regenerate this file executing lime-config\n\n') utils.write_file(cfgpath, notice_message .. autogen_content) end return config
lime-system: flush autogen before modifying it
lime-system: flush autogen before modifying it This fixes a bug that prevented configs that were autogenerated to be present in the lime-autogen file. This behaviour is very confusing as reading the lime-autogen was measlieading.
Lua
agpl-3.0
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
e6a89b30c26bdaa92fb7c5bee3441fad03fa8f27
xmake.lua
xmake.lua
set_project("UBWindow") if is_mode("debug") then add_defines("DEBUG") set_symbols("debug") set_optimize("none") end if is_mode("release") then add_defines("NDEBUG") set_symbols("hidden") set_optimize("fastest") set_strip("all") end add_includedirs("include") target("ubwindow") set_kind("static") set_targetdir("lib") add_includedirs("src") add_files("src/*.c") if is_plat("macosx") then add_files("src/*.m") end target("demo_blank") add_deps("ubwindow") set_kind("binary") set_targetdir("bin") add_linkdirs("lib") add_files("demo/*.c") add_links("ubwindow") if is_plat("windows") then add_links("user32") end if is_plat("mingw") then add_ldflags("-static") end if is_plat("linux") then add_links("X11") end if is_plat("macosx") then add_ldflags("-framework Cocoa") end
set_project("UBWindow") if is_mode("debug") then add_defines("DEBUG") set_symbols("debug") set_optimize("none") end if is_mode("release") then add_defines("NDEBUG") set_symbols("hidden") set_optimize("fastest") set_strip("all") end add_includedirs("include") target("ubwindow") set_kind("static") set_targetdir("lib") add_includedirs("src") add_files("src/*.c") if is_plat("macosx") then add_files("src/*.m") end if is_plat("mingw") then after_build(function () os.run("mv ./lib/ubwindow.lib ./lib/libubwindow.a") end) end target("demo_blank") add_deps("ubwindow") set_kind("binary") set_targetdir("bin") add_linkdirs("lib") add_files("demo/*.c") add_links("ubwindow") if is_plat("windows") then add_links("user32") end if is_plat("mingw") then add_ldflags("-static") end if is_plat("linux") then add_links("X11") end if is_plat("macosx") then add_ldflags("-framework Cocoa") end
Fixed xmake.lua
Fixed xmake.lua
Lua
mit
yulon/pwre
405b8e0be24efeab24ff6e842bdb903bf9c005fc
frontend/apps/reader/modules/readercropping.lua
frontend/apps/reader/modules/readercropping.lua
local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local Geom = require("ui/geometry") local Event = require("ui/event") local Screen = require("device").screen local LeftContainer = require("ui/widget/container/leftcontainer") local RightContainer = require("ui/widget/container/rightcontainer") local FrameContainer = require("ui/widget/container/framecontainer") local VerticalGroup = require("ui/widget/verticalgroup") local HorizontalGroup = require("ui/widget/horizontalgroup") local BBoxWidget = require("ui/widget/bboxwidget") local HorizontalSpan = require("ui/widget/horizontalspan") local Button = require("ui/widget/button") local Math = require("optmath") local DEBUG = require("dbg") local Blitbuffer = require("ffi/blitbuffer") local PageCropDialog = VerticalGroup:new{ ok_text = "OK", cancel_text = "Cancel", ok_callback = function() end, cancel_callback = function() end, button_width = math.floor(Screen:scaleByDPI(70)), } function PageCropDialog:init() local horizontal_group = HorizontalGroup:new{} local ok_button = Button:new{ text = self.ok_text, callback = self.ok_callback, width = self.button_width, bordersize = 2, radius = 7, text_font_face = "cfont", text_font_size = 20, show_parent = self, } local cancel_button = Button:new{ text = self.cancel_text, callback = self.cancel_callback, width = self.button_width, bordersize = 2, radius = 7, text_font_face = "cfont", text_font_size = 20, show_parent = self, } local ok_container = RightContainer:new{ dimen = Geom:new{ w = Screen:getWidth()*0.33, h = Screen:getHeight()/12}, ok_button, } local cancel_container = LeftContainer:new{ dimen = Geom:new{ w = Screen:getWidth()*0.33, h = Screen:getHeight()/12}, cancel_button, } table.insert(horizontal_group, ok_container) table.insert(horizontal_group, HorizontalSpan:new{ width = Screen:getWidth()*0.34}) table.insert(horizontal_group, cancel_container) self[2] = FrameContainer:new{ horizontal_group, background = Blitbuffer.COLOR_WHITE, bordersize = 0, padding = 0, } end local ReaderCropping = InputContainer:new{} function ReaderCropping:onPageCrop(mode) if mode == "auto" then return end self.ui:handleEvent(Event:new("CloseConfigMenu")) -- backup original view dimen self.orig_view_dimen = Geom:new{w = self.view.dimen.w, h = self.view.dimen.h} -- backup original view bgcolor self.orig_view_bgcolor = self.view.outer_page_color self.view.outer_page_color = Blitbuffer.gray(0.5) -- gray bgcolor -- backup original zoom mode as cropping use "page" zoom mode self.orig_zoom_mode = self.view.zoom_mode -- backup original page scroll self.orig_page_scroll = self.view.page_scroll self.view.page_scroll = false -- backup and disable original hinting state self.ui:handleEvent(Event:new("DisableHinting")) -- backup original reflow mode as cropping use non-reflow mode self.orig_reflow_mode = self.document.configurable.text_wrap if self.orig_reflow_mode == 1 then self.document.configurable.text_wrap = 0 -- if we are in reflow mode, then we are already in page -- mode, just force readerview to recalculate visible_area self.view:recalculate() else self.ui:handleEvent(Event:new("SetZoomMode", "page", "cropping")) end self.ui:handleEvent(Event:new("SetDimensions", Geom:new{w = Screen:getWidth(), h = Screen:getHeight()*11/12}) ) self.bbox_widget = BBoxWidget:new{ crop = self, ui = self.ui, view = self.view, document = self.document, } self.crop_dialog = PageCropDialog:new{ self.bbox_widget, ok_callback = function() self:onConfirmPageCrop() end, cancel_callback = function() self:onCancelPageCrop() end, } UIManager:show(self.crop_dialog) return true end function ReaderCropping:onConfirmPageCrop() --DEBUG("new bbox", new_bbox) UIManager:close(self.crop_dialog) local new_bbox = self.bbox_widget:getModifiedPageBBox() self.ui:handleEvent(Event:new("BBoxUpdate", new_bbox)) local pageno = self.view.state.page self.document.bbox[pageno] = new_bbox self.document.bbox[Math.oddEven(pageno)] = new_bbox self:exitPageCrop(true) return true end function ReaderCropping:onCancelPageCrop() UIManager:close(self.crop_dialog) self:exitPageCrop(false) return true end function ReaderCropping:exitPageCrop(confirmed) -- restore hinting state self.ui:handleEvent(Event:new("RestoreHinting")) -- restore page scroll self.view.page_scroll = self.orig_page_scroll -- restore view bgcolor self.view.outer_page_color = self.orig_view_bgcolor -- restore reflow mode self.document.configurable.text_wrap = self.orig_reflow_mode -- restore view dimens self.ui:handleEvent(Event:new("RestoreDimensions", self.orig_view_dimen)) self.view:recalculate() -- Exiting should have the same look and feel with entering. if self.orig_reflow_mode == 1 then self.ui:handleEvent(Event:new("RestoreZoomMode")) else if confirmed then -- if original zoom mode is not "content", set zoom mode to "contentwidth" self.ui:handleEvent(Event:new("SetZoomMode", self.orig_zoom_mode:find("content") and self.orig_zoom_mode or "contentwidth")) self.ui:handleEvent(Event:new("InitScrollPageStates")) else self.ui:handleEvent(Event:new("SetZoomMode", self.orig_zoom_mode)) end end UIManager.repaint_all = true end function ReaderCropping:onReadSettings(config) self.document.bbox = config:readSetting("bbox") end function ReaderCropping:onSaveSettings() self.ui.doc_settings:saveSetting("bbox", self.document.bbox) end return ReaderCropping
local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local Geom = require("ui/geometry") local Event = require("ui/event") local Screen = require("device").screen local LeftContainer = require("ui/widget/container/leftcontainer") local RightContainer = require("ui/widget/container/rightcontainer") local FrameContainer = require("ui/widget/container/framecontainer") local VerticalGroup = require("ui/widget/verticalgroup") local HorizontalGroup = require("ui/widget/horizontalgroup") local BBoxWidget = require("ui/widget/bboxwidget") local HorizontalSpan = require("ui/widget/horizontalspan") local Button = require("ui/widget/button") local Math = require("optmath") local DEBUG = require("dbg") local Blitbuffer = require("ffi/blitbuffer") local PageCropDialog = VerticalGroup:new{ ok_text = "OK", cancel_text = "Cancel", ok_callback = function() end, cancel_callback = function() end, button_width = math.floor(Screen:scaleByDPI(70)), } function PageCropDialog:init() local horizontal_group = HorizontalGroup:new{} local ok_button = Button:new{ text = self.ok_text, callback = self.ok_callback, width = self.button_width, bordersize = 2, radius = 7, text_font_face = "cfont", text_font_size = 20, show_parent = self, } local cancel_button = Button:new{ text = self.cancel_text, callback = self.cancel_callback, width = self.button_width, bordersize = 2, radius = 7, text_font_face = "cfont", text_font_size = 20, show_parent = self, } local ok_container = RightContainer:new{ dimen = Geom:new{ w = Screen:getWidth()*0.33, h = Screen:getHeight()/12}, ok_button, } local cancel_container = LeftContainer:new{ dimen = Geom:new{ w = Screen:getWidth()*0.33, h = Screen:getHeight()/12}, cancel_button, } table.insert(horizontal_group, ok_container) table.insert(horizontal_group, HorizontalSpan:new{ width = Screen:getWidth()*0.34}) table.insert(horizontal_group, cancel_container) self[2] = FrameContainer:new{ horizontal_group, background = Blitbuffer.COLOR_WHITE, bordersize = 0, padding = 0, } end local ReaderCropping = InputContainer:new{} function ReaderCropping:onPageCrop(mode) self.ui:handleEvent(Event:new("CloseConfigMenu")) -- backup original zoom mode as cropping use "page" zoom mode self.orig_zoom_mode = self.view.zoom_mode if mode == "auto" then self:setCropZoomMode(true) return end -- backup original view dimen self.orig_view_dimen = Geom:new{w = self.view.dimen.w, h = self.view.dimen.h} -- backup original view bgcolor self.orig_view_bgcolor = self.view.outer_page_color self.view.outer_page_color = Blitbuffer.gray(0.5) -- gray bgcolor -- backup original page scroll self.orig_page_scroll = self.view.page_scroll self.view.page_scroll = false -- backup and disable original hinting state self.ui:handleEvent(Event:new("DisableHinting")) -- backup original reflow mode as cropping use non-reflow mode self.orig_reflow_mode = self.document.configurable.text_wrap if self.orig_reflow_mode == 1 then self.document.configurable.text_wrap = 0 -- if we are in reflow mode, then we are already in page -- mode, just force readerview to recalculate visible_area self.view:recalculate() else self.ui:handleEvent(Event:new("SetZoomMode", "page", "cropping")) end self.ui:handleEvent(Event:new("SetDimensions", Geom:new{w = Screen:getWidth(), h = Screen:getHeight()*11/12}) ) self.bbox_widget = BBoxWidget:new{ crop = self, ui = self.ui, view = self.view, document = self.document, } self.crop_dialog = PageCropDialog:new{ self.bbox_widget, ok_callback = function() self:onConfirmPageCrop() end, cancel_callback = function() self:onCancelPageCrop() end, } UIManager:show(self.crop_dialog) return true end function ReaderCropping:onConfirmPageCrop() --DEBUG("new bbox", new_bbox) UIManager:close(self.crop_dialog) local new_bbox = self.bbox_widget:getModifiedPageBBox() self.ui:handleEvent(Event:new("BBoxUpdate", new_bbox)) local pageno = self.view.state.page self.document.bbox[pageno] = new_bbox self.document.bbox[Math.oddEven(pageno)] = new_bbox self:exitPageCrop(true) return true end function ReaderCropping:onCancelPageCrop() UIManager:close(self.crop_dialog) self:exitPageCrop(false) return true end function ReaderCropping:exitPageCrop(confirmed) -- restore hinting state self.ui:handleEvent(Event:new("RestoreHinting")) -- restore page scroll self.view.page_scroll = self.orig_page_scroll -- restore view bgcolor self.view.outer_page_color = self.orig_view_bgcolor -- restore reflow mode self.document.configurable.text_wrap = self.orig_reflow_mode -- restore view dimens self.ui:handleEvent(Event:new("RestoreDimensions", self.orig_view_dimen)) self.view:recalculate() -- Exiting should have the same look and feel with entering. if self.orig_reflow_mode == 1 then self.ui:handleEvent(Event:new("RestoreZoomMode")) else self:setCropZoomMode(confirmed) end UIManager.repaint_all = true end function ReaderCropping:setCropZoomMode(confirmed) if confirmed then -- if original zoom mode is not "content", set zoom mode to "contentwidth" self.ui:handleEvent(Event:new("SetZoomMode", self.orig_zoom_mode:find("content") and self.orig_zoom_mode or "contentwidth")) self.ui:handleEvent(Event:new("InitScrollPageStates")) else self.ui:handleEvent(Event:new("SetZoomMode", self.orig_zoom_mode)) end end function ReaderCropping:onReadSettings(config) self.document.bbox = config:readSetting("bbox") end function ReaderCropping:onSaveSettings() self.ui.doc_settings:saveSetting("bbox", self.document.bbox) end return ReaderCropping
fix #1070 by associating conentwidth zoom mode to auto cropping
fix #1070 by associating conentwidth zoom mode to auto cropping
Lua
agpl-3.0
apletnev/koreader,NiLuJe/koreader,robert00s/koreader,pazos/koreader,chihyang/koreader,Hzj-jie/koreader,lgeek/koreader,houqp/koreader,chrox/koreader,koreader/koreader,Frenzie/koreader,poire-z/koreader,frankyifei/koreader,koreader/koreader,mihailim/koreader,ashhher3/koreader,poire-z/koreader,Markismus/koreader,noname007/koreader,Frenzie/koreader,NiLuJe/koreader,NickSavage/koreader,mwoz123/koreader,ashang/koreader
99815793c848a60213174adb2f2dae3eaeac7cd5
UCDchat/instantMessaging.lua
UCDchat/instantMessaging.lua
-- Cancel in-built MTA messaging addEventHandler("onPlayerPrivateMessage", root, function () exports.UCDdx:new(source, "This function is not depracated. Use /im <message> instead.", 255, 174, 0) cancelEvent() end ) local antiSpam = {} local antiSpamTimer = 1000 function clearAntiSpam(plr) if (antiSpam[plr]) then antiSpam[plr] = nil end end addEventHandler("onPlayerQuit", root, clearAntiSpam) -- This is the function we use to send the IM function instantMessage(plr, _, target, ...) -- If they have already sent a message if (antiSpam[plr]) then exports.UCDdx:new(plr, "Your last IM was sent less than one second ago!", 255, 0, 0) return false end -- Actual messaging function if (not target) then exports.UCDdx:new(plr, "You must specify a player", 255, 0, 0) return end local recipient = exports.UCDutil:getPlayerFromPartialName(target) -- If we found a recipient if recipient then local msg = table.concat({...}, " ") if (msg == "" or msg == " " or msg:gsub(" ", "") == "") then return end if (msg:find("ucd")) then msg = msg:gsub("ucd", "UCD") end if (recipient.name == plr.name) then exports.UCDdx:new(plr, "You cannot send an IM to yourself", 255, 0, 0) return end local imTo = outputChatBox("[IM to "..recipient.name.."] "..msg, plr, 200, 30, 200, true) local imFrom = outputChatBox("[IM from "..plr.name.."] " .. msg, recipient, 200, 30, 200, true) --exports.UCDlogging:new(plr, "IM", msg, ) else exports.UCDdx:new(plr, "There is no player named "..target.." online", 255, 0, 0) end end addCommandHandler("im", instantMessage, false, false) addCommandHandler("instantmessage", instantMessage, false, false) addCommandHandler("imsg", instantMessage, false, false) addCommandHandler("imessage", instantMessage, false, false) addCommandHandler("instantmsg", instantMessage, false, false)
-- Cancel in-built MTA messaging addEventHandler("onPlayerPrivateMessage", root, function () exports.UCDdx:new(source, "This function is depracated. Use /im <player> <message> instead.", 255, 174, 0) cancelEvent() end ) -- People will use /sms addCommandHandler("sms", function (plr) exports.UCDdx:new(plr, "This function is depracated. Use /im <player> <message> instead.", 255, 174, 0) end ) local antiSpam = {} local antiSpamTimer = 1000 -- This is the function we use to send the IM function instantMessage(plr, _, target, ...) -- Actual messaging function if (not target) then exports.UCDdx:new(plr, "You must specify a player", 255, 0, 0) return end local recipient = exports.UCDutil:getPlayerFromPartialName(target) -- If we found a recipient if recipient then local msg = table.concat({...}, " ") if (msg == "" or msg == " " or msg:gsub(" ", "") == "") then return end if (msg:find("ucd")) then msg = msg:gsub("ucd", "UCD") end if (recipient.name == plr.name) then exports.UCDdx:new(plr, "You cannot send an IM to yourself", 255, 0, 0) return end outputChatBox("[IM to "..recipient.name.."] "..msg, plr, 255, 174, 0, true) outputChatBox("[IM from "..plr.name.."] "..msg, recipient, 255, 174, 0, true) -- source = player who got the msg, plr = player who sent it, msg = the message sent triggerEvent("onPlayerReceiveIM", recipient, plr, msg) triggerClientEvent(plr, "UCDphone.appendMessage", plr, false, recipient.name, msg) triggerClientEvent(recipient, "UCDphone.appendMessage", recipient, true, plr.name, msg) --exports.UCDlogging:new(plr, "IM", msg, ) else exports.UCDdx:new(plr, "There is no player named "..target.." online", 255, 0, 0) end end addCommandHandler("im", instantMessage, false, false) addCommandHandler("instantmessage", instantMessage, false, false) addCommandHandler("imsg", instantMessage, false, false) addCommandHandler("imessage", instantMessage, false, false) addCommandHandler("instantmsg", instantMessage, false, false) addEvent("UCDchat.onSendIMFromPhone", true) addEventHandler("UCDchat.onSendIMFromPhone", root, function (plrName, message) instantMessage(client, nil, plrName, message) end ) local lastMsg = {} function onReceiveIM(sender, message) lastMsg[source] = sender end addEvent("onPlayerReceiveIM") addEventHandler("onPlayerReceiveIM", root, onReceiveIM) function quickReply(plr, _, ...) if (lastMsg[plr]) then local recipient = lastMsg[plr] local msg = table.concat({...}, " ") if (msg == "" or msg == " " or msg:gsub(" ", "") == "") then return end if (msg:find("UCD")) then msg = msg:gsub("ucd", "UCD") end instantMessage(plr, nil, recipient.name, msg) else exports.UCDdx:new(plr, "The last person to IM you is offline", 255, 0, 0) end end addCommandHandler("re", quickReply, false, false) addCommandHandler("r", quickReply, false, false) function clear() if (lastMsg[source]) then lastMsg[source] = nil end for i, plr in pairs(lastMsg) do if (plr == source) then lastMsg[i] = nil end end end addEventHandler("onPlayerQuit", root, clear)
UCDchat
UCDchat - Fixed message that informs players that /pm and /sms are depracated and to use /im. - Added quick reply (/r and /re) - Messages are now added to the phone IM gui.
Lua
mit
nokizorque/ucd,nokizorque/ucd
a07c5f3c480ccfb075ba1cecf9cb90e54b402df3
kong/plugins/session/schema.lua
kong/plugins/session/schema.lua
local typedefs = require "kong.db.schema.typedefs" local Schema = require "kong.db.schema" local utils = require("kong.tools.utils") local char = string.char local rand = math.random local encode_base64 = ngx.encode_base64 local samesite = Schema.define { type = "string", default = "Strict", one_of = { "Strict", "Lax", "off", } } --- kong.utils.random_string with 32 bytes instead -- @returns random string of length 44 local function random_string() return encode_base64(utils.get_rand_bytes(32, true)) :gsub("/", char(rand(48, 57))) -- 0 - 10 :gsub("+", char(rand(65, 90))) -- A - Z :gsub("=", char(rand(97, 122))) -- a - z end return { name = "session", fields = { { config = { type = "record", fields = { { consumer = typedefs.no_consumer }, { secret = { type = "string", required = false, default = random_string(), }, }, { cookie_name = { type = "string", default = "session" } }, { cookie_lifetime = { type = "number", default = 3600 } }, { cookie_renew = { type = "number", default = 600 } }, { cookie_path = { type = "string", default = "/" } }, { cookie_domain = { type = "string" } }, { cookie_samesite = samesite }, { cookie_httponly = { type = "boolean", default = true } }, { cookie_secure = { type = "boolean", default = true } }, { cookie_discard = { type = "number", default = 10 } }, { storage = { required = false, type = "string", one_of = { "cookie", "kong", }, default = "cookie", } }, { logout_methods = { type = "array", elements = { type = "string", one_of = { "GET", "POST", "DELETE" }, }, default = { "POST", "DELETE" }, } }, { logout_query_arg = { required = false, type = "string", default = "session_logout", } }, { logout_post_arg = { required = false, type = "string", default = "session_logout", }, }, }, }, }, }, }
local typedefs = require "kong.db.schema.typedefs" local Schema = require "kong.db.schema" local utils = require("kong.tools.utils") local char = string.char local rand = math.random local encode_base64 = ngx.encode_base64 local samesite = Schema.define { type = "string", default = "Strict", one_of = { "Strict", "Lax", "off", } } --- kong.utils.random_string with 32 bytes instead -- @returns random string of length 44 local function random_string() return encode_base64(utils.get_rand_bytes(32, true)) :gsub("/", char(rand(48, 57))) -- 0 - 10 :gsub("+", char(rand(65, 90))) -- A - Z :gsub("=", char(rand(97, 122))) -- a - z end return { name = "session", fields = { { consumer = typedefs.no_consumer }, { config = { type = "record", fields = { { secret = { type = "string", required = false, default = random_string(), }, }, { cookie_name = { type = "string", default = "session" } }, { cookie_lifetime = { type = "number", default = 3600 } }, { cookie_renew = { type = "number", default = 600 } }, { cookie_path = { type = "string", default = "/" } }, { cookie_domain = { type = "string" } }, { cookie_samesite = samesite }, { cookie_httponly = { type = "boolean", default = true } }, { cookie_secure = { type = "boolean", default = true } }, { cookie_discard = { type = "number", default = 10 } }, { storage = { required = false, type = "string", one_of = { "cookie", "kong", }, default = "cookie", } }, { logout_methods = { type = "array", elements = { type = "string", one_of = { "GET", "POST", "DELETE" }, }, default = { "POST", "DELETE" }, } }, { logout_query_arg = { required = false, type = "string", default = "session_logout", } }, { logout_post_arg = { required = false, type = "string", default = "session_logout", }, }, }, }, }, }, }
fix(session) add no_consumer to correct fields
fix(session) add no_consumer to correct fields
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
ef4bf9ea5e551cde69caddc38db84f9adfb8fe38
mod_register_redirect/mod_register_redirect.lua
mod_register_redirect/mod_register_redirect.lua
-- (C) 2010-2011 Marco Cirillo (LW.Org) -- (C) 2011 Kim Alvefur -- -- Registration Redirect module for Prosody -- -- Redirects IP addresses not in the whitelist to a web page or another method to complete the registration. local st = require "util.stanza" local cman = configmanager function reg_redirect(event) local stanza, origin = event.stanza, event.origin local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" } local url = module:get_option_string("registration_url", nil) local inst_text = module:get_option_string("registration_text", nil) local oob = module:get_option_boolean("registration_oob", true) local admins_g = cman.get("*", "core", "admins") local admins_l = cman.get(module:get_host(), "core", "admins") local no_wl = module:get_option_boolean("no_registration_whitelist", false) local test_ip = false if type(admins_g) ~= "table" then admins_g = nil end if type(admins_l) ~= "table" then admins_l = nil end -- perform checks to set default responses and sanity checks. if not inst_text then if url and oob then if url:match("^%w+[:].*$") then if url:match("^(%w+)[:].*$") == "http" or url:match("^(%w+)[:].*$") == "https" then inst_text = "Please visit "..url.." to register an account on this server." elseif url:match("^(%w+)[:].*$") == "mailto" then inst_text = "Please send an e-mail at "..url:match("^%w+[:](.*)$").." to register an account on this server." elseif url:match("^(%w+)[:].*$") == "xmpp" then inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..url:match("^%w+[:](.*)$") else module:log("error", "This module supports only http/https, mailto or xmpp as URL formats.") module:log("error", "If you want to use personalized instructions without an Out-Of-Band method,") module:log("error", "specify: register_oob = false; -- in your configuration along your banner string (register_text).") origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request. end else module:log("error", "Please check your configuration, the URL you specified is invalid") origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request. end else if admins_l then local ajid; for _,v in ipairs(admins_l) do ajid = v ; break end inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid else if admins_g then local ajid; for _,v in ipairs(admins_g) do ajid = v ; break end inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid else module:log("error", "Please be sure to, _at the very least_, configure one server administrator either global or hostwise...") module:log("error", "if you want to use this module, or read it's configuration wiki at: http://code.google.com/p/prosody-modules/wiki/mod_register_redirect") origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request. end end end elseif inst_text and url and oob then if not url:match("^%w+[:].*$") then module:log("error", "Please check your configuration, the URL specified is not valid.") origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request. end end if not no_wl then for i,ip in ipairs(ip_wl) do if origin.ip == ip then test_ip = true end break end end -- Prepare replies. local reply = st.reply(event.stanza) if oob then reply:query("jabber:iq:register") :tag("instructions"):text(inst_text):up() :tag("x", {xmlns = "jabber:x:oob"}) :tag("url"):text(url); else reply:query("jabber:iq:register") :tag("instructions"):text(inst_text):up() end if stanza.attr.type == "get" then origin.send(reply) else origin.send(st.error_reply(stanza, "cancel", "not-authorized")) end return true end module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10)
-- (C) 2010-2011 Marco Cirillo (LW.Org) -- (C) 2011 Kim Alvefur -- -- Registration Redirect module for Prosody -- -- Redirects IP addresses not in the whitelist to a web page or another method to complete the registration. local st = require "util.stanza" local cman = configmanager function reg_redirect(event) local stanza, origin = event.stanza, event.origin local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" } local url = module:get_option_string("registration_url", nil) local inst_text = module:get_option_string("registration_text", nil) local oob = module:get_option_boolean("registration_oob", true) local admins_g = cman.get("*", "core", "admins") local admins_l = cman.get(module:get_host(), "core", "admins") local no_wl = module:get_option_boolean("no_registration_whitelist", false) local test_ip = false if type(admins_g) ~= "table" then admins_g = nil end if type(admins_l) ~= "table" then admins_l = nil end -- perform checks to set default responses and sanity checks. if not inst_text then if url and oob then if url:match("^%w+[:].*$") then if url:match("^(%w+)[:].*$") == "http" or url:match("^(%w+)[:].*$") == "https" then inst_text = "Please visit "..url.." to register an account on this server." elseif url:match("^(%w+)[:].*$") == "mailto" then inst_text = "Please send an e-mail at "..url:match("^%w+[:](.*)$").." to register an account on this server." elseif url:match("^(%w+)[:].*$") == "xmpp" then inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..url:match("^%w+[:](.*)$") else module:log("error", "This module supports only http/https, mailto or xmpp as URL formats.") module:log("error", "If you want to use personalized instructions without an Out-Of-Band method,") module:log("error", "specify: register_oob = false; -- in your configuration along your banner string (register_text).") return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request. end else module:log("error", "Please check your configuration, the URL you specified is invalid") return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request. end else if admins_l then local ajid; for _,v in ipairs(admins_l) do ajid = v ; break end inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid else if admins_g then local ajid; for _,v in ipairs(admins_g) do ajid = v ; break end inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid else module:log("error", "Please be sure to, _at the very least_, configure one server administrator either global or hostwise...") module:log("error", "if you want to use this module, or read it's configuration wiki at: http://code.google.com/p/prosody-modules/wiki/mod_register_redirect") return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request. end end end elseif inst_text and url and oob then if not url:match("^%w+[:].*$") then module:log("error", "Please check your configuration, the URL specified is not valid.") return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request. end end if not no_wl then for i,ip in ipairs(ip_wl) do if origin.ip == ip then test_ip = true end break end end -- Prepare replies. local reply = st.reply(event.stanza) if oob then reply:query("jabber:iq:register") :tag("instructions"):text(inst_text):up() :tag("x", {xmlns = "jabber:x:oob"}) :tag("url"):text(url); else reply:query("jabber:iq:register") :tag("instructions"):text(inst_text):up() end if stanza.attr.type == "get" then return origin.send(reply) else return origin.send(st.error_reply(stanza, "cancel", "not-authorized")) end end module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10)
mod_register_redirect: rebacked in changeset c6f1427da79d (behaviour fixed).
mod_register_redirect: rebacked in changeset c6f1427da79d (behaviour fixed).
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
99e7449395e61063af3ac5580c6cd3045177297c
plugins/shout.lua
plugins/shout.lua
local command = 'shout <text>' local doc = [[``` /shout <text> Shouts something. ```]] local triggers = { '^/shout[@'..bot.username..']*' } local action = function(msg) local input = msg.text:input() if not input then sendMessage(msg.chat.id, doc, true, msg.message_id, true) return end input = input:trim() if input:len() > 20 then input = input:sub(1,20) end input = input:upper() local output = '' local inc = 0 for match in input:gmatch('.') do output = output .. match .. ' ' end output = output .. '\n' for match in input:sub(2):gmatch('.') do local spacing = '' for i = 1, inc do spacing = spacing .. ' ' end inc = inc + 1 output = output .. match .. ' ' .. spacing .. match .. '\n' end output = '```\n' .. output:trim() .. '\n```' sendMessage(msg.chat.id, output, true, false, true) end return { action = action, triggers = triggers, doc = doc, command = command }
local command = 'shout <text>' local doc = [[``` /shout <text> Shouts something. ```]] local triggers = { '^/shout[@'..bot.username..']*' } local action = function(msg) local input = msg.text:input() if not input then sendMessage(msg.chat.id, doc, true, msg.message_id, true) return end input = input:trim() if input:len() > 20 then input = input:sub(1,20) end input = input:upper() local output = '' local inc = 0 for match in input:gmatch('([%z\1-\127\194-\244][\128-\191]*)') do output = output .. match .. ' ' end output = output .. '\n' for match in input:sub(2):gmatch('([%z\1-\127\194-\244][\128-\191]*)') do local spacing = '' for i = 1, inc do spacing = spacing .. ' ' end inc = inc + 1 output = output .. match .. ' ' .. spacing .. match .. '\n' end output = '```\n' .. output:trim() .. '\n```' sendMessage(msg.chat.id, output, true, false, true) end return { action = action, triggers = triggers, doc = doc, command = command }
FIX shout
FIX shout
Lua
agpl-3.0
TiagoDanin/SiD,Brawl345/Brawlbot-v2,bb010g/otouto,topkecleon/otouto,barreeeiroo/BarrePolice
a48593c14516ef8a953eed9c36f2d57d5cc9fa00
module/admin-core/src/controller/admin/index.lua
module/admin-core/src/controller/admin/index.lua
module("ffluci.controller.admin.index", package.seeall) function action_wizard() if ffluci.http.formvalue("ip") then return configure_freifunk() end local ifaces = {} local wldevs = ffluci.model.uci.show("wireless") if wldevs then for k, v in pairs(wldevs.wireless) do if v[".type"] == "wifi-device" then table.insert(ifaces, k) end end end ffluci.template.render("admin_index/wizard", {ifaces=ifaces}) end function configure_freifunk() local ip = ffluci.http.formvalue("ip") local uci = ffluci.model.uci.Session() -- Configure FF-Interface uci:del("network", "ff") uci:del("network", "ffdhcp") uci:set("network", "ff", nil, "interface") uci:set("network", "ff", "type", "bridge") uci:set("network", "ff", "proto", "static") uci:set("network", "ff", "ipaddr", ip) uci:set("network", "ff", "netmask", uci:get("freifunk", "community", "mask")) uci:set("network", "ff", "dns", uci:get("freifunk", "community", "dns")) -- Enable internal routing uci:set("freifunk", "routing", "internal", "1") -- Enable internet routing if ffluci.http.formvalue("shareinet") then uci:set("freifunk", "routing", "internet", "1") else uci:set("freifunk", "routing", "internet", "0") end -- Configure DHCP if ffluci.http.formvalue("dhcp") then local dhcpnet = uci:get("freifunk", "community", "dhcp"):match("^([0-9]+)") local dhcpip = ip:gsub("^[0-9]+", dhcpnet) uci:set("network", "ffdhcp", nil, "interface") uci:set("network", "ffdhcp", "proto", "static") uci:set("network", "ffdhcp", "ifname", "br-ff:dhcp") uci:set("network", "ffdhcp", "ipaddr", dhcpip) uci:set("network", "ffdhcp", "netmask", uci:get("freifunk", "community", "dhcpmask")) end -- Configure OLSR if ffluci.http.formvalue("olsr") and uci:show("olsr") then for k, v in pairs(uci:show("olsr").olsr) do if v[".type"] == "Interface" or v[".type"] == "LoadPlugin" then uci:del("olsr", "k") end end if ffluci.http.formvalue("shareinet") then uci:set("olsr", "dyn_gw", nil, "LoadPlugin") uci:set("olsr", "dyn_gw", "Library", "olsrd_dyn_gw.so.0.4") end uci:set("olsr", "nameservice", nil, "LoadPlugin") uci:set("olsr", "nameservice", "Library", "olsrd_nameservice.so.0.3") uci:set("olsr", "nameservice", "name", ip:gsub("%.", "-")) uci:set("olsr", "nameservice", "hosts_file", "/var/etc/hosts") uci:set("olsr", "nameservice", "suffix", ".olsr") uci:set("olsr", "nameservice", "latlon_infile", "/tmp/latlon.txt") uci:set("olsr", "txtinfo", nil, "LoadPlugin") uci:set("olsr", "txtinfo", "Library", "olsrd_txtinfo.so.0.1") uci:set("olsr", "txtinfo", "Accept", "127.0.0.1") local oif = uci:add("olsr", "Interface") uci:set("olsr", oif, "Interface", "ff") uci:set("olsr", oif, "HelloInterval", "6.0") uci:set("olsr", oif, "HelloValidityTime", "108.0") uci:set("olsr", oif, "TcInterval", "4.0") uci:set("olsr", oif, "TcValidityTime", "324.0") uci:set("olsr", oif, "MidInterval", "18.0") uci:set("olsr", oif, "MidValidityTime", "324.0") uci:set("olsr", oif, "HnaInterval", "18.0") uci:set("olsr", oif, "HnaValidityTime", "108.0") end -- Configure Wifi local wifi = ffluci.http.formvalue("wifi") local wcfg = uci:show("wireless") if type(wifi) == "table" and wcfg then for iface, v in pairs(wifi) do if wcfg[iface] then -- Cleanup for k, v in pairs(wcfg.wireless) do if v[".type"] == "wifi-iface" and v.device == iface then uci:del("wireless", k) end end uci:set("wireless", iface, "disabled", "0") uci:set("wireless", iface, "mode", "11g") uci:set("wireless", iface, "txantenna", 1) uci:set("wireless", iface, "rxantenna", 1) uci:set("wireless", iface, "channel", uci:get("freifunk", "community", "channel")) local wif = uci:add("wireless", "wifi-iface") uci:set("wireless", wif, "device", iface) uci:set("wireless", wif, "network", "ff") uci:set("wireless", wif, "mode", "adhoc") uci:set("wireless", wif, "ssid", uci:get("freifunk", "community", "essid")) uci:set("wireless", wif, "bssid", uci:get("freifunk", "community", "bssid")) uci:set("wireless", wif, "txpower", 13) end end end ffluci.http.request_redirect("admin", "uci", "changes") end
module("ffluci.controller.admin.index", package.seeall) function action_wizard() if ffluci.http.formvalue("ip") then return configure_freifunk() end local ifaces = {} local wldevs = ffluci.model.uci.show("wireless") if wldevs then for k, v in pairs(wldevs.wireless) do if v[".type"] == "wifi-device" then table.insert(ifaces, k) end end end ffluci.template.render("admin_index/wizard", {ifaces=ifaces}) end function configure_freifunk() local ip = ffluci.http.formvalue("ip") local uci = ffluci.model.uci.Session() -- Configure FF-Interface uci:del("network", "ff") uci:del("network", "ffdhcp") uci:set("network", "ff", nil, "interface") uci:set("network", "ff", "type", "bridge") uci:set("network", "ff", "proto", "static") uci:set("network", "ff", "ipaddr", ip) uci:set("network", "ff", "netmask", uci:get("freifunk", "community", "mask")) uci:set("network", "ff", "dns", uci:get("freifunk", "community", "dns")) -- Enable internal routing uci:set("freifunk", "routing", "internal", "1") -- Enable internet routing if ffluci.http.formvalue("shareinet") then uci:set("freifunk", "routing", "internet", "1") else uci:set("freifunk", "routing", "internet", "0") end -- Configure DHCP if ffluci.http.formvalue("dhcp") then local dhcpnet = uci:get("freifunk", "community", "dhcp"):match("^([0-9]+)") local dhcpip = ip:gsub("^[0-9]+", dhcpnet) uci:set("network", "ffdhcp", nil, "interface") uci:set("network", "ffdhcp", "proto", "static") uci:set("network", "ffdhcp", "ifname", "br-ff:dhcp") uci:set("network", "ffdhcp", "ipaddr", dhcpip) uci:set("network", "ffdhcp", "netmask", uci:get("freifunk", "community", "dhcpmask")) local splash = uci:show("luci_splash") if splash then for k, v in pairs(splash.luci_splash) do if v[".type"] == "iface" then uci:del("luci_splash", k) end end local sk = uci:add("luci_splash", "iface") uci:set("luci_splash", sk, "network", "ffdhcp") end end -- Configure OLSR if ffluci.http.formvalue("olsr") and uci:show("olsr") then for k, v in pairs(uci:show("olsr").olsr) do if v[".type"] == "Interface" or v[".type"] == "LoadPlugin" then uci:del("olsr", k) end end if ffluci.http.formvalue("shareinet") then uci:set("olsr", "dyn_gw", nil, "LoadPlugin") uci:set("olsr", "dyn_gw", "Library", "olsrd_dyn_gw.so.0.4") end uci:set("olsr", "nameservice", nil, "LoadPlugin") uci:set("olsr", "nameservice", "Library", "olsrd_nameservice.so.0.3") uci:set("olsr", "nameservice", "name", ip:gsub("%.", "-")) uci:set("olsr", "nameservice", "hosts_file", "/var/etc/hosts") uci:set("olsr", "nameservice", "suffix", ".olsr") uci:set("olsr", "nameservice", "latlon_infile", "/tmp/latlon.txt") uci:set("olsr", "txtinfo", nil, "LoadPlugin") uci:set("olsr", "txtinfo", "Library", "olsrd_txtinfo.so.0.1") uci:set("olsr", "txtinfo", "Accept", "127.0.0.1") local oif = uci:add("olsr", "Interface") uci:set("olsr", oif, "Interface", "ff") uci:set("olsr", oif, "HelloInterval", "6.0") uci:set("olsr", oif, "HelloValidityTime", "108.0") uci:set("olsr", oif, "TcInterval", "4.0") uci:set("olsr", oif, "TcValidityTime", "324.0") uci:set("olsr", oif, "MidInterval", "18.0") uci:set("olsr", oif, "MidValidityTime", "324.0") uci:set("olsr", oif, "HnaInterval", "18.0") uci:set("olsr", oif, "HnaValidityTime", "108.0") end -- Configure Wifi local wifi = ffluci.http.formvalue("wifi") local wcfg = uci:show("wireless") if type(wifi) == "table" and wcfg then for iface, v in pairs(wifi) do if wcfg[iface] then -- Cleanup for k, v in pairs(wcfg.wireless) do if v[".type"] == "wifi-iface" and v.device == iface then uci:del("wireless", k) end end uci:set("wireless", iface, "disabled", "0") uci:set("wireless", iface, "mode", "11g") uci:set("wireless", iface, "txantenna", 1) uci:set("wireless", iface, "rxantenna", 1) uci:set("wireless", iface, "channel", uci:get("freifunk", "community", "channel")) local wif = uci:add("wireless", "wifi-iface") uci:set("wireless", wif, "device", iface) uci:set("wireless", wif, "network", "ff") uci:set("wireless", wif, "mode", "adhoc") uci:set("wireless", wif, "ssid", uci:get("freifunk", "community", "essid")) uci:set("wireless", wif, "bssid", uci:get("freifunk", "community", "bssid")) uci:set("wireless", wif, "txpower", 13) end end end ffluci.http.request_redirect("admin", "uci", "changes") end
* Fixed Freifunk wizard
* Fixed Freifunk wizard
Lua
apache-2.0
ollie27/openwrt_luci,cshore/luci,maxrio/luci981213,taiha/luci,thess/OpenWrt-luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci,Sakura-Winkey/LuCI,teslamint/luci,jchuang1977/luci-1,oyido/luci,aa65535/luci,artynet/luci,Noltari/luci,jlopenwrtluci/luci,florian-shellfire/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,mumuqz/luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,tcatm/luci,kuoruan/lede-luci,daofeng2015/luci,cappiewu/luci,thess/OpenWrt-luci,thess/OpenWrt-luci,Hostle/luci,joaofvieira/luci,kuoruan/luci,maxrio/luci981213,slayerrensky/luci,david-xiao/luci,nwf/openwrt-luci,jorgifumi/luci,wongsyrone/luci-1,thesabbir/luci,bright-things/ionic-luci,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,daofeng2015/luci,teslamint/luci,nwf/openwrt-luci,taiha/luci,openwrt-es/openwrt-luci,joaofvieira/luci,joaofvieira/luci,keyidadi/luci,forward619/luci,thess/OpenWrt-luci,dwmw2/luci,jorgifumi/luci,RuiChen1113/luci,kuoruan/lede-luci,forward619/luci,rogerpueyo/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,Sakura-Winkey/LuCI,marcel-sch/luci,florian-shellfire/luci,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,dismantl/luci-0.12,male-puppies/luci,oneru/luci,hnyman/luci,MinFu/luci,oyido/luci,RuiChen1113/luci,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,obsy/luci,Kyklas/luci-proto-hso,RedSnake64/openwrt-luci-packages,Wedmer/luci,Hostle/luci,tobiaswaldvogel/luci,openwrt/luci,cshore-firmware/openwrt-luci,bittorf/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,MinFu/luci,sujeet14108/luci,cappiewu/luci,wongsyrone/luci-1,dismantl/luci-0.12,thess/OpenWrt-luci,Kyklas/luci-proto-hso,joaofvieira/luci,teslamint/luci,sujeet14108/luci,wongsyrone/luci-1,aa65535/luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,ff94315/luci-1,Wedmer/luci,harveyhu2012/luci,hnyman/luci,MinFu/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,LuttyYang/luci,zhaoxx063/luci,jlopenwrtluci/luci,taiha/luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,oyido/luci,oyido/luci,chris5560/openwrt-luci,palmettos/cnLuCI,kuoruan/luci,kuoruan/luci,kuoruan/luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,lcf258/openwrtcn,remakeelectric/luci,jorgifumi/luci,slayerrensky/luci,thess/OpenWrt-luci,jchuang1977/luci-1,daofeng2015/luci,schidler/ionic-luci,marcel-sch/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,thess/OpenWrt-luci,zhaoxx063/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,palmettos/cnLuCI,obsy/luci,dwmw2/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,chris5560/openwrt-luci,harveyhu2012/luci,cshore-firmware/openwrt-luci,nmav/luci,dwmw2/luci,kuoruan/luci,nmav/luci,aa65535/luci,aa65535/luci,sujeet14108/luci,Wedmer/luci,marcel-sch/luci,LuttyYang/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,cappiewu/luci,cappiewu/luci,fkooman/luci,Hostle/luci,sujeet14108/luci,palmettos/test,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,male-puppies/luci,david-xiao/luci,oneru/luci,florian-shellfire/luci,harveyhu2012/luci,MinFu/luci,sujeet14108/luci,rogerpueyo/luci,tobiaswaldvogel/luci,male-puppies/luci,Wedmer/luci,fkooman/luci,mumuqz/luci,981213/luci-1,openwrt/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,opentechinstitute/luci,tobiaswaldvogel/luci,rogerpueyo/luci,deepak78/new-luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,remakeelectric/luci,urueedi/luci,ReclaimYourPrivacy/cloak-luci,nmav/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,tcatm/luci,nwf/openwrt-luci,jlopenwrtluci/luci,palmettos/cnLuCI,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,male-puppies/luci,zhaoxx063/luci,Kyklas/luci-proto-hso,remakeelectric/luci,jlopenwrtluci/luci,kuoruan/luci,dismantl/luci-0.12,lbthomsen/openwrt-luci,lcf258/openwrtcn,forward619/luci,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,NeoRaider/luci,tcatm/luci,harveyhu2012/luci,opentechinstitute/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,taiha/luci,jorgifumi/luci,sujeet14108/luci,slayerrensky/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,oneru/luci,zhaoxx063/luci,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,taiha/luci,dismantl/luci-0.12,male-puppies/luci,remakeelectric/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,ollie27/openwrt_luci,palmettos/cnLuCI,Noltari/luci,hnyman/luci,jorgifumi/luci,981213/luci-1,obsy/luci,david-xiao/luci,palmettos/test,LuttyYang/luci,florian-shellfire/luci,kuoruan/lede-luci,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,openwrt-es/openwrt-luci,cshore/luci,Sakura-Winkey/LuCI,oneru/luci,bright-things/ionic-luci,Kyklas/luci-proto-hso,aa65535/luci,ff94315/luci-1,Hostle/luci,palmettos/cnLuCI,jlopenwrtluci/luci,ollie27/openwrt_luci,kuoruan/luci,florian-shellfire/luci,jchuang1977/luci-1,palmettos/test,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,sujeet14108/luci,cappiewu/luci,teslamint/luci,deepak78/new-luci,zhaoxx063/luci,opentechinstitute/luci,cshore/luci,dismantl/luci-0.12,MinFu/luci,ff94315/luci-1,mumuqz/luci,lcf258/openwrtcn,palmettos/test,dwmw2/luci,oneru/luci,marcel-sch/luci,981213/luci-1,palmettos/test,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,openwrt/luci,taiha/luci,ff94315/luci-1,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,jchuang1977/luci-1,Noltari/luci,forward619/luci,palmettos/cnLuCI,nwf/openwrt-luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,maxrio/luci981213,artynet/luci,joaofvieira/luci,Noltari/luci,nmav/luci,remakeelectric/luci,fkooman/luci,urueedi/luci,openwrt/luci,harveyhu2012/luci,cappiewu/luci,dismantl/luci-0.12,keyidadi/luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,nmav/luci,bright-things/ionic-luci,marcel-sch/luci,MinFu/luci,LuttyYang/luci,jlopenwrtluci/luci,Wedmer/luci,florian-shellfire/luci,aa65535/luci,male-puppies/luci,male-puppies/luci,shangjiyu/luci-with-extra,Kyklas/luci-proto-hso,bright-things/ionic-luci,thess/OpenWrt-luci,ollie27/openwrt_luci,schidler/ionic-luci,Hostle/luci,deepak78/new-luci,chris5560/openwrt-luci,Hostle/luci,male-puppies/luci,dwmw2/luci,schidler/ionic-luci,slayerrensky/luci,hnyman/luci,thesabbir/luci,chris5560/openwrt-luci,obsy/luci,lbthomsen/openwrt-luci,artynet/luci,obsy/luci,cshore/luci,david-xiao/luci,cshore/luci,jchuang1977/luci-1,ollie27/openwrt_luci,Wedmer/luci,jlopenwrtluci/luci,urueedi/luci,fkooman/luci,nwf/openwrt-luci,oneru/luci,aa65535/luci,aa65535/luci,keyidadi/luci,bright-things/ionic-luci,joaofvieira/luci,david-xiao/luci,NeoRaider/luci,981213/luci-1,artynet/luci,nmav/luci,david-xiao/luci,thesabbir/luci,981213/luci-1,nmav/luci,fkooman/luci,tcatm/luci,jchuang1977/luci-1,LuttyYang/luci,openwrt/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,remakeelectric/luci,tobiaswaldvogel/luci,artynet/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,ff94315/luci-1,RedSnake64/openwrt-luci-packages,RedSnake64/openwrt-luci-packages,ReclaimYourPrivacy/cloak-luci,bittorf/luci,daofeng2015/luci,ff94315/luci-1,florian-shellfire/luci,daofeng2015/luci,chris5560/openwrt-luci,nmav/luci,openwrt/luci,jorgifumi/luci,kuoruan/luci,forward619/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,maxrio/luci981213,Noltari/luci,obsy/luci,cappiewu/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,forward619/luci,rogerpueyo/luci,bittorf/luci,981213/luci-1,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,RuiChen1113/luci,palmettos/test,jorgifumi/luci,oyido/luci,thesabbir/luci,rogerpueyo/luci,deepak78/new-luci,palmettos/test,dwmw2/luci,palmettos/cnLuCI,thesabbir/luci,chris5560/openwrt-luci,981213/luci-1,harveyhu2012/luci,nwf/openwrt-luci,wongsyrone/luci-1,urueedi/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,NeoRaider/luci,Noltari/luci,marcel-sch/luci,mumuqz/luci,chris5560/openwrt-luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,oyido/luci,daofeng2015/luci,remakeelectric/luci,openwrt/luci,slayerrensky/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,oyido/luci,wongsyrone/luci-1,artynet/luci,joaofvieira/luci,lcf258/openwrtcn,RuiChen1113/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,LuttyYang/luci,lcf258/openwrtcn,hnyman/luci,palmettos/cnLuCI,shangjiyu/luci-with-extra,obsy/luci,openwrt-es/openwrt-luci,cshore/luci,joaofvieira/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,cshore-firmware/openwrt-luci,MinFu/luci,slayerrensky/luci,lcf258/openwrtcn,urueedi/luci,jchuang1977/luci-1,NeoRaider/luci,oneru/luci,Hostle/openwrt-luci-multi-user,forward619/luci,MinFu/luci,fkooman/luci,bittorf/luci,Kyklas/luci-proto-hso,lcf258/openwrtcn,rogerpueyo/luci,RuiChen1113/luci,opentechinstitute/luci,keyidadi/luci,david-xiao/luci,oyido/luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,cshore/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,taiha/luci,teslamint/luci,cappiewu/luci,slayerrensky/luci,mumuqz/luci,obsy/luci,teslamint/luci,ollie27/openwrt_luci,zhaoxx063/luci,maxrio/luci981213,fkooman/luci,NeoRaider/luci,tcatm/luci,forward619/luci,chris5560/openwrt-luci,Hostle/luci,dwmw2/luci,thesabbir/luci,maxrio/luci981213,taiha/luci,deepak78/new-luci,artynet/luci,tobiaswaldvogel/luci,fkooman/luci,harveyhu2012/luci,ff94315/luci-1,openwrt/luci,marcel-sch/luci,deepak78/new-luci,Wedmer/luci,teslamint/luci,cshore/luci,slayerrensky/luci,RedSnake64/openwrt-luci-packages,tcatm/luci,florian-shellfire/luci,tcatm/luci,deepak78/new-luci,teslamint/luci,schidler/ionic-luci,tcatm/luci,nwf/openwrt-luci,lcf258/openwrtcn,jorgifumi/luci,maxrio/luci981213,shangjiyu/luci-with-extra,artynet/luci,opentechinstitute/luci,kuoruan/lede-luci,hnyman/luci,schidler/ionic-luci,sujeet14108/luci,Hostle/luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,oneru/luci,ff94315/luci-1,bittorf/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,marcel-sch/luci,zhaoxx063/luci,lcf258/openwrtcn,RuiChen1113/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,dismantl/luci-0.12,mumuqz/luci,keyidadi/luci,hnyman/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,remakeelectric/luci,bittorf/luci,thesabbir/luci,keyidadi/luci,daofeng2015/luci,Noltari/luci
febe973b5b91d5bbf9c11a5e0650335fc37bd966
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(node, dt, mtv_x, mtv_y) if not (node.floor_pushback or node.wall_pushback) then return end local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = node.bb:bbox() local distance = math.abs(node.velocity.y * dt) + 0.10 if self.bb.polyline and node.floor_pushback and node.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 -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles node:floor_pushback(self, (py1 - 4) + mtv_y) return end if mtv_x ~= 0 and node.wall_pushback and wy1 + 2 < node.position.y + node.height then --prevent horizontal movement node:wall_pushback(self, node.position.x + mtv_x) end if mtv_y < 0 and node.floor_pushback then --push back up node:floor_pushback(self, wy1 - node.height) end -- floor doesn't support a ceiling_pushback 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(node, dt, mtv_x, mtv_y) if not (node.floor_pushback or node.wall_pushback) then return end if node.velocity.y < 0 and mtv_x == 0 then -- don't collide when the player is going upwards above the floor -- This happens when enemies hit the player return end local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = node.bb:bbox() local distance = math.abs(node.velocity.y * dt) + 0.10 if self.bb.polyline and node.floor_pushback and node.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 -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles node:floor_pushback(self, (py1 - 4) + mtv_y) return end if mtv_x ~= 0 and node.wall_pushback and wy1 + 2 < node.position.y + node.height then --prevent horizontal movement node:wall_pushback(self, node.position.x + mtv_x) end if mtv_y < 0 and node.floor_pushback then --push back up node:floor_pushback(self, wy1 - node.height) end -- floor doesn't support a ceiling_pushback end return Floor
Fix #585. Players are now flinged correctly
Fix #585. Players are now flinged correctly
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua
4018371abb8133b633b8395cd354b35c6577f78f
mod_smacks/mod_smacks.lua
mod_smacks/mod_smacks.lua
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.send; function session.send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.reply(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = queue[i]; if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, queue[i]); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end end return _destroy_session(session, err); end
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.sends2s or session.send; local function new_send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.reply(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end if session.sends2s then session.sends2s = new_send; else session.send = new_send; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> (origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = queue[i]; if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, queue[i]); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end end return _destroy_session(session, err); end
mod_smacks: Fix to reply to stream for s2s sessions
mod_smacks: Fix to reply to stream for s2s sessions
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
6de204cc2254234f8c1caa418ac36d75ee3b0488
init.lua
init.lua
---------------------------------------------------------------------- -- sys - a package that provides simple system (unix) tools ---------------------------------------------------------------------- local os = require 'os' local io = require 'io' local paths = require 'paths' sys = {} -------------------------------------------------------------------------------- -- load all functions from lib -------------------------------------------------------------------------------- local _lib = require 'libsys' for k,v in pairs(_lib) do sys[k] = v end -------------------------------------------------------------------------------- -- tic/toc (matlab-like) timers -------------------------------------------------------------------------------- local __t__ function sys.tic() __t__ = sys.clock() end function sys.toc(verbose) local __dt__ = sys.clock() - __t__ if verbose then print(__dt__) end return __dt__ end -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -------------------------------------------------------------------------------- local function execute(cmd) local cmd = cmd .. ' 2>&1' local f = io.popen(cmd) local s = f:read('*all') f:close() s = s:gsub('^%s*',''):gsub('%s*$','') return s end sys.execute = execute -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -- side effect: file in /tmp -- this call is typically more robust than the one above (on some systems) -------------------------------------------------------------------------------- function sys.fexecute(cmd, readwhat) local tmpfile = os.tmpname() local cmd = cmd .. ' 1>'.. tmpfile..' 2>' .. tmpfile os.execute(cmd) local file = _G.assert(io.open(tmpfile)) local s = file:read('*all') file:close() s = s:gsub('^%s*',''):gsub('%s*$','') os.execute('rm ' .. tmpfile) return s end -------------------------------------------------------------------------------- -- returns the name of the OS in use -- warning, this method is extremely dumb, and should be replaced by something -- more reliable -------------------------------------------------------------------------------- function sys.uname() if paths.dirp('C:\\') then return 'windows' else local os = execute('uname -a') if os:find('Linux') then return 'linux' elseif os:find('Darwin') then return 'macos' else return '?' end end end sys.OS = sys.uname() -------------------------------------------------------------------------------- -- ls (list dir) -------------------------------------------------------------------------------- sys.ls = function(d) d = d or ' ' return execute('ls ' ..d) end sys.ll = function(d) d = d or ' ' return execute('ls -l ' ..d) end sys.la = function(d) d = d or ' ' return execute('ls -a ' ..d) end sys.lla = function(d) d = d or ' ' return execute('ls -la '..d) end -------------------------------------------------------------------------------- -- prefix -------------------------------------------------------------------------------- sys.prefix = execute('which lua'):gsub('//','/'):gsub('/bin/lua\n','') -------------------------------------------------------------------------------- -- always returns the path of the file running -------------------------------------------------------------------------------- sys.fpath = require 'sys.fpath' -------------------------------------------------------------------------------- -- split string based on pattern pat -------------------------------------------------------------------------------- function sys.split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, last_end) while s do if s ~= 1 or cap ~= "" then _G.table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) _G.table.insert(t, cap) end return t end -------------------------------------------------------------------------------- -- check if a number is NaN -------------------------------------------------------------------------------- function sys.isNaN(number) -- We rely on the property that NaN is the only value that doesn't equal itself. return (number ~= number) end -------------------------------------------------------------------------------- -- sleep -------------------------------------------------------------------------------- function sys.sleep(seconds) sys.usleep(seconds*1000000) end -------------------------------------------------------------------------------- -- colors, can be used to print things in color -------------------------------------------------------------------------------- sys.COLORS = require 'sys.colors' -------------------------------------------------------------------------------- -- backward compat -------------------------------------------------------------------------------- sys.dirname = paths.dirname sys.concat = paths.concat return sys
---------------------------------------------------------------------- -- sys - a package that provides simple system (unix) tools ---------------------------------------------------------------------- local os = require 'os' local io = require 'io' local paths = require 'paths' sys = {} -------------------------------------------------------------------------------- -- load all functions from lib -------------------------------------------------------------------------------- local _lib = require 'libsys' for k,v in pairs(_lib) do sys[k] = v end -------------------------------------------------------------------------------- -- tic/toc (matlab-like) timers -------------------------------------------------------------------------------- local __t__ function sys.tic() __t__ = sys.clock() end function sys.toc(verbose) local __dt__ = sys.clock() - __t__ if verbose then print(__dt__) end return __dt__ end -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -------------------------------------------------------------------------------- local function execute(cmd) local cmd = cmd .. ' 2>&1' local f = io.popen(cmd) local s = f:read('*all') f:close() s = s:gsub('^%s*',''):gsub('%s*$','') return s end sys.execute = execute -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -- side effect: file in /tmp -- this call is typically more robust than the one above (on some systems) -------------------------------------------------------------------------------- function sys.fexecute(cmd, readwhat) readwhat = readwhat or '*all' local tmpfile = os.tmpname() local cmd = cmd .. ' 1>'.. tmpfile..' 2>' .. tmpfile os.execute(cmd) local file = _G.assert(io.open(tmpfile)) local s= file:read(readwhat) file:close() s = s:gsub('^%s*',''):gsub('%s*$','') os.execute('rm ' .. tmpfile) return s end -------------------------------------------------------------------------------- -- returns the name of the OS in use -- warning, this method is extremely dumb, and should be replaced by something -- more reliable -------------------------------------------------------------------------------- function sys.uname() if paths.dirp('C:\\') then return 'windows' else local os = execute('uname -a') if os:find('Linux') then return 'linux' elseif os:find('Darwin') then return 'macos' else return '?' end end end sys.OS = sys.uname() -------------------------------------------------------------------------------- -- ls (list dir) -------------------------------------------------------------------------------- sys.ls = function(d) d = d or ' ' return execute('ls ' ..d) end sys.ll = function(d) d = d or ' ' return execute('ls -l ' ..d) end sys.la = function(d) d = d or ' ' return execute('ls -a ' ..d) end sys.lla = function(d) d = d or ' ' return execute('ls -la '..d) end -------------------------------------------------------------------------------- -- prefix -------------------------------------------------------------------------------- sys.prefix = execute('which lua'):gsub('//','/'):gsub('/bin/lua\n','') -------------------------------------------------------------------------------- -- always returns the path of the file running -------------------------------------------------------------------------------- sys.fpath = require 'sys.fpath' -------------------------------------------------------------------------------- -- split string based on pattern pat -------------------------------------------------------------------------------- function sys.split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, last_end) while s do if s ~= 1 or cap ~= "" then _G.table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) _G.table.insert(t, cap) end return t end -------------------------------------------------------------------------------- -- check if a number is NaN -------------------------------------------------------------------------------- function sys.isNaN(number) -- We rely on the property that NaN is the only value that doesn't equal itself. return (number ~= number) end -------------------------------------------------------------------------------- -- sleep -------------------------------------------------------------------------------- function sys.sleep(seconds) sys.usleep(seconds*1000000) end -------------------------------------------------------------------------------- -- colors, can be used to print things in color -------------------------------------------------------------------------------- sys.COLORS = require 'sys.colors' -------------------------------------------------------------------------------- -- backward compat -------------------------------------------------------------------------------- sys.dirname = paths.dirname sys.concat = paths.concat return sys
fixing readwhat option
fixing readwhat option
Lua
bsd-3-clause
torch/sys
24f17b1446d10bdf1638ff1d84f6dce66be45add
home/.hammerspoon/windows.lua
home/.hammerspoon/windows.lua
-- copied and (lightly) adapted from -- https://github.com/jasonrudolph/keyboard/blob/master/hammerspoon/windows.lua hs.window.animationDuration = 0 -- +-----------------+ -- | | | -- | HERE | | -- | | | -- +-----------------+ function hs.window.left(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end -- +-----------------+ -- | | | -- | | HERE | -- | | | -- +-----------------+ function hs.window.right(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end -- +-----------------+ -- | HERE | -- +-----------------+ -- | | -- +-----------------+ function hs.window.up(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.w = max.w f.y = max.y f.h = max.h / 2 win:setFrame(f) end -- +-----------------+ -- | | -- +-----------------+ -- | HERE | -- +-----------------+ function hs.window.down(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.w = max.w f.y = max.y + (max.h / 2) f.h = max.h / 2 win:setFrame(f) end -- +-----------------+ -- | HERE | | -- +--------+ | -- | | -- +-----------------+ function hs.window.upLeft(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x f.y = max.y f.w = max.w/2 f.h = max.h/2 win:setFrame(f) end -- +-----------------+ -- | | -- +--------+ | -- | HERE | | -- +-----------------+ function hs.window.downLeft(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x f.y = max.y + (max.h / 2) f.w = max.w/2 f.h = max.h/2 win:setFrame(f) end -- +-----------------+ -- | | -- | +--------| -- | | HERE | -- +-----------------+ function hs.window.downRight(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x + (max.w / 2) f.y = max.y + (max.h / 2) f.w = max.w/2 f.h = max.h/2 win:setFrame(f) end -- +-----------------+ -- | | HERE | -- | +--------| -- | | -- +-----------------+ function hs.window.upRight(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w/2 f.h = max.h/2 win:setFrame(f) end -- +--------------+ -- | | | | -- | | HERE | | -- | | | | -- +---------------+ function hs.window.centerWithFullHeight(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x + (max.w / 8) f.w = max.w * 3/4 f.y = max.y f.h = max.h win:setFrame(f) end -- +-----------------+ -- | | | -- | HERE | | -- | | | -- +-----------------+ function hs.window.left40(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w * 0.4 f.h = max.h win:setFrame(f) end -- +-----------------+ -- | | | -- | | HERE | -- | | | -- +-----------------+ function hs.window.right60(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w * 0.4) f.y = max.y f.w = max.w * 0.6 f.h = max.h win:setFrame(f) end function hs.window.exit(win) end function hs.window.nextScreen(win) local currentScreen = win:screen() local allScreens = hs.screen.allScreens() currentScreenIndex = hs.fnutils.indexOf(allScreens, currentScreen) nextScreenIndex = currentScreenIndex + 1 if allScreens[nextScreenIndex] then win:moveToScreen(allScreens[nextScreenIndex]) else win:moveToScreen(allScreens[1]) end end windowLayoutMode = hs.hotkey.modal.new({}, 'F16') windowLayoutMode.entered = function() windowLayoutMode.statusMessage:show() end windowLayoutMode.exited = function() windowLayoutMode.statusMessage:hide() end -- Bind the given key to call the given function and exit WindowLayout mode function windowLayoutMode.bindWithAutomaticExit(mode, modifiers, key, fn) mode:bind(modifiers, key, function() mode:exit() fn() end) end local status, windowMappings = pcall(require, 'windows-bindings') local modifiers = windowMappings.modifiers local showHelp = windowMappings.showHelp local trigger = windowMappings.trigger local mappings = windowMappings.mappings function getModifiersStr(modifiers) local modMap = { shift = '⇧', ctrl = '⌃', alt = '⌥', cmd = '⌘' } local retVal = '' for i, v in ipairs(modifiers) do retVal = retVal .. modMap[v] end return retVal end local msgStr = getModifiersStr(modifiers) msgStr = 'Window Layout Mode (' .. msgStr .. (string.len(msgStr) > 0 and '+' or '') .. trigger .. ')' for i, mapping in ipairs(mappings) do local modifiers, trigger, winFunction = table.unpack(mapping) local hotKeyStr = getModifiersStr(modifiers) if showHelp == true then if string.len(hotKeyStr) > 0 then msgStr = msgStr .. (string.format('\n%10s+%s => %s', hotKeyStr, trigger, winFunction)) else msgStr = msgStr .. (string.format('\n%11s => %s', trigger, winFunction)) end end windowLayoutMode:bindWithAutomaticExit(modifiers, trigger, function() --example: hs.window.focusedWindow():upRight() local fw = hs.window.focusedWindow() fw[winFunction](fw) end) end local message = require('status-message') windowLayoutMode.statusMessage = message.new(msgStr) -- Use modifiers+trigger to toggle WindowLayout Mode hs.hotkey.bind(modifiers, trigger, function() windowLayoutMode:enter() end) windowLayoutMode:bind(modifiers, trigger, function() windowLayoutMode:exit() end)
-- copied and (lightly) adapted from -- https://github.com/jasonrudolph/keyboard/blob/master/hammerspoon/windows.lua -- then I applied https://github.com/jasonrudolph/keyboard/pull/73 manually -- what a mess hs.window.animationDuration = 0 window = hs.getObjectMetatable("hs.window") -- +-----------------+ -- | | | -- | HERE | | -- | | | -- +-----------------+ function window.left(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end -- +-----------------+ -- | | | -- | | HERE | -- | | | -- +-----------------+ function window.right(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end -- +-----------------+ -- | HERE | -- +-----------------+ -- | | -- +-----------------+ function window.up(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.w = max.w f.y = max.y f.h = max.h / 2 win:setFrame(f) end -- +-----------------+ -- | | -- +-----------------+ -- | HERE | -- +-----------------+ function window.down(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.w = max.w f.y = max.y + (max.h / 2) f.h = max.h / 2 win:setFrame(f) end -- +-----------------+ -- | HERE | | -- +--------+ | -- | | -- +-----------------+ function window.upLeft(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x f.y = max.y f.w = max.w/2 f.h = max.h/2 win:setFrame(f) end -- +-----------------+ -- | | -- +--------+ | -- | HERE | | -- +-----------------+ function window.downLeft(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x f.y = max.y + (max.h / 2) f.w = max.w/2 f.h = max.h/2 win:setFrame(f) end -- +-----------------+ -- | | -- | +--------| -- | | HERE | -- +-----------------+ function window.downRight(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x + (max.w / 2) f.y = max.y + (max.h / 2) f.w = max.w/2 f.h = max.h/2 win:setFrame(f) end -- +-----------------+ -- | | HERE | -- | +--------| -- | | -- +-----------------+ function window.upRight(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w/2 f.h = max.h/2 win:setFrame(f) end -- +--------------+ -- | | | | -- | | HERE | | -- | | | | -- +---------------+ function window.centerWithFullHeight(win) local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x + (max.w / 8) f.w = max.w * 3/4 f.y = max.y f.h = max.h win:setFrame(f) end -- +-----------------+ -- | | | -- | HERE | | -- | | | -- +-----------------+ function window.left40(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w * 0.4 f.h = max.h win:setFrame(f) end -- +-----------------+ -- | | | -- | | HERE | -- | | | -- +-----------------+ function window.right60(win) local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w * 0.4) f.y = max.y f.w = max.w * 0.6 f.h = max.h win:setFrame(f) end function window.exit(win) end function window.nextScreen(win) local currentScreen = win:screen() local allScreens = hs.screen.allScreens() currentScreenIndex = hs.fnutils.indexOf(allScreens, currentScreen) nextScreenIndex = currentScreenIndex + 1 if allScreens[nextScreenIndex] then win:moveToScreen(allScreens[nextScreenIndex]) else win:moveToScreen(allScreens[1]) end end windowLayoutMode = hs.hotkey.modal.new({}, 'F16') windowLayoutMode.entered = function() windowLayoutMode.statusMessage:show() end windowLayoutMode.exited = function() windowLayoutMode.statusMessage:hide() end -- Bind the given key to call the given function and exit WindowLayout mode function windowLayoutMode.bindWithAutomaticExit(mode, modifiers, key, fn) mode:bind(modifiers, key, function() mode:exit() fn() end) end local status, windowMappings = pcall(require, 'windows-bindings') local modifiers = windowMappings.modifiers local showHelp = windowMappings.showHelp local trigger = windowMappings.trigger local mappings = windowMappings.mappings function getModifiersStr(modifiers) local modMap = { shift = '⇧', ctrl = '⌃', alt = '⌥', cmd = '⌘' } local retVal = '' for i, v in ipairs(modifiers) do retVal = retVal .. modMap[v] end return retVal end local msgStr = getModifiersStr(modifiers) msgStr = 'Window Layout Mode (' .. msgStr .. (string.len(msgStr) > 0 and '+' or '') .. trigger .. ')' for i, mapping in ipairs(mappings) do local modifiers, trigger, winFunction = table.unpack(mapping) local hotKeyStr = getModifiersStr(modifiers) if showHelp == true then if string.len(hotKeyStr) > 0 then msgStr = msgStr .. (string.format('\n%10s+%s => %s', hotKeyStr, trigger, winFunction)) else msgStr = msgStr .. (string.format('\n%11s => %s', trigger, winFunction)) end end windowLayoutMode:bindWithAutomaticExit(modifiers, trigger, function() --example: hs.window.focusedWindow():upRight() local fw = hs.window.focusedWindow() fw[winFunction](fw) end) end local message = require('status-message') windowLayoutMode.statusMessage = message.new(msgStr) -- Use modifiers+trigger to toggle WindowLayout Mode hs.hotkey.bind(modifiers, trigger, function() windowLayoutMode:enter() end) windowLayoutMode:bind(modifiers, trigger, function() windowLayoutMode:exit() end)
🐛 fix issues w/hammerspoon after hs upgrade
🐛 fix issues w/hammerspoon after hs upgrade
Lua
bsd-3-clause
jacobian/dotfiles,jacobian/dotfiles,jacobian/dotfiles,jacobian/dotfiles
73344eac0f5cb651724b22f2620320b253783872
src/common/premake.lua
src/common/premake.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] -- Handy little helper function os.outputoff(...) return os.outputof(string.format(...)) end function os.fexecutef(...) local result, f, code = os.executef(...) if code ~= 0 then printf("Failed to execute command '%s' exited with code '%s'!", string.format(...), code) os.exit(1) end end premake.override(os, "execute", function(base, exec) if _OPTIONS["verbose"] then print(os.getcwd() .. "\t" .. exec) end return base(exec) end ) premake.override(os, "outputof", function(base, exec) if _OPTIONS["verbose"] then print(os.getcwd() .. "\t" .. exec) end return base(exec) end ) premake.override(os, "getenv", function(base, varname, default) local val = base(varname) if val == nil and default ~= nil then val = default end return val end ) -- Unfortunately premake normalises most paths, -- which results in some links like http:// to be -- reduced to http:/ which of course is incorrect premake.override(path, "normalize", function(base, p) if not zpm.util.hasGitUrl(p) and not zpm.util.hasUrl(p) and not p:contains("\\\"") then return base(p) end return p end ) premake.override(premake.main, "preAction", function() local action = premake.action.current() end ) -- this was taken from -- https://github.com/premake/premake-core/blob/785671fad5946a129300ffcd0f61561f690bddb4/src/_premake_main.lua premake.override(premake.main, "processCommandLine", function() -- Process special options if (_OPTIONS["version"]) then printf("ZPM (Zefiros Package Manager) %s", zpm._VERSION) printf("premake5 (Premake Build Script Generator) %s", _PREMAKE_VERSION) os.exit(0) end if (_OPTIONS["help"] and _ACTION ~= "run") then premake.showhelp() os.exit(1) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options local ok, err = premake.option.validate(_OPTIONS) if not ok then printf("Error: %s", err) os.exit(1) end -- If no further action is possible, show a short help message if not _OPTIONS.interactive then if not _ACTION then print("Type 'zpm --help' for help") os.exit(1) end local action = premake.action.current() if not action then printf("Error: no such action '%s'", _ACTION) os.exit(1) end if premake.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then printf("No zpm script (%s) found!", path.getname(_MAIN_SCRIPT)) os.exit(1) end end end) premake.override(premake.main, "postAction", function(base) if zpm.cli.profile() then if profiler then profiler:stop() profiler:report(io.open(path.join(_MAIN_SCRIPT_DIR, "profile.txt"), 'w')) elseif ProFi then ProFi:stop() ProFi:writeReport(path.join(_MAIN_SCRIPT_DIR, "profile.txt")) end end base() end) premake.override(premake.main, "locateUserScript", function() local defaults = { "zpm.lua", "premake5.lua", "premake4.lua" } for _, default in ipairs(defaults) do if os.isfile(default) then _MAIN_SCRIPT = default break end end if not _MAIN_SCRIPT then _MAIN_SCRIPT = defaults[1] end if _OPTIONS.file then _MAIN_SCRIPT = _OPTIONS.file end _MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT) _MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT) end) premake.override(_G, "workspace", function(base, name) if not zpm.meta.exporting then if name then zpm.meta.workspace = name else zpm.meta.project = "" end end return base(name) end) premake.override(_G, "project", function(base, name) if name then zpm.meta.project = name if not zpm.meta.building and not zpm.meta.exporting then zpm.util.insertTable(zpm.loader.project.builder.cursor, {"projects", name, "workspaces"}, zpm.meta.workspace) end end return base(name) end) premake.override(_G, "cppdialect", function(base, dialect) if dialect then if not zpm.meta.building then zpm.loader.project.builder.cursor.cppdialect = base if zpm.meta.project ~= "" then tab = zpm.util.insertTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "cppdialects"}, dialect) else tab = zpm.util.insertTable(zpm.loader.project.builder.cursor, {"cppdialects"}, dialect) end end end end) premake.override(_G, "group", function(base, name) if (name or name == "") and not zpm.meta.exporting then zpm.meta.group = name end return base(name) end) premake.override(_G, "filter", function(base, fltr) if (fltr or fltr == "") then zpm.meta.filter = fltr end return base(fltr) end) premake.override(_G, "kind", function(base, knd) if kind and not zpm.meta.exporting then zpm.meta.kind = knd if not zpm.meta.building then zpm.util.setTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "kind"}, knd) end end return base(knd) end) premake.override(premake.main, "preBake", function(base) if zpm.loader and not zpm.util.isMainScriptDisabled() then zpm.loader.project.builder:walkDependencies() end return base() end)
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] -- Handy little helper function os.outputoff(...) return os.outputof(string.format(...)) end function os.fexecutef(...) local result, f, code = os.executef(...) if code ~= 0 then printf("Failed to execute command '%s' exited with code '%s'!", string.format(...), code) os.exit(1) end end premake.override(os, "execute", function(base, exec) if _OPTIONS["verbose"] then print(os.getcwd() .. "\t" .. exec) end return base(exec) end ) premake.override(os, "outputof", function(base, exec) if _OPTIONS["verbose"] then print(os.getcwd() .. "\t" .. exec) end return base(exec) end ) premake.override(os, "getenv", function(base, varname, default) local val = base(varname) if val == nil and default ~= nil then val = default end return val end ) -- Unfortunately premake normalises most paths, -- which results in some links like http:// to be -- reduced to http:/ which of course is incorrect premake.override(path, "normalize", function(base, p) if not zpm.util.hasGitUrl(p) and not zpm.util.hasUrl(p) and not p:contains("\\\"") then return base(p) end return p end ) premake.override(premake.main, "preAction", function() local action = premake.action.current() end ) -- this was taken from -- https://github.com/premake/premake-core/blob/785671fad5946a129300ffcd0f61561f690bddb4/src/_premake_main.lua premake.override(premake.main, "processCommandLine", function() -- Process special options if (_OPTIONS["version"]) then printf("ZPM (Zefiros Package Manager) %s", zpm._VERSION) printf("premake5 (Premake Build Script Generator) %s", _PREMAKE_VERSION) os.exit(0) end if (_OPTIONS["help"] and _ACTION ~= "run") then premake.showhelp() os.exit(1) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options local ok, err = premake.option.validate(_OPTIONS) if not ok then printf("Error: %s", err) os.exit(1) end -- If no further action is possible, show a short help message if not _OPTIONS.interactive then if not _ACTION then print("Type 'zpm --help' for help") os.exit(1) end local action = premake.action.current() if not action then printf("Error: no such action '%s'", _ACTION) os.exit(1) end if premake.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then printf("No zpm script (%s) found!", path.getname(_MAIN_SCRIPT)) os.exit(1) end end end) premake.override(premake.main, "postAction", function(base) if zpm.cli.profile() then if profiler then profiler:stop() profiler:report(io.open(path.join(_MAIN_SCRIPT_DIR, "profile.txt"), 'w')) elseif ProFi then ProFi:stop() ProFi:writeReport(path.join(_MAIN_SCRIPT_DIR, "profile.txt")) end end base() end) premake.override(premake.main, "locateUserScript", function() local defaults = { "zpm.lua", "premake5.lua", "premake4.lua" } for _, default in ipairs(defaults) do if os.isfile(default) then _MAIN_SCRIPT = default break end end if not _MAIN_SCRIPT then _MAIN_SCRIPT = defaults[1] end if _OPTIONS.file then _MAIN_SCRIPT = _OPTIONS.file end _MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT) _MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT) end) premake.override(_G, "workspace", function(base, name) if not zpm.meta.exporting then if name then zpm.meta.workspace = name else zpm.meta.project = "" end end return base(name) end) premake.override(_G, "project", function(base, name) if name then zpm.meta.project = name if not zpm.meta.building and not zpm.meta.exporting then zpm.util.insertTable(zpm.loader.project.builder.cursor, {"projects", name, "workspaces"}, zpm.meta.workspace) end end return base(name) end) premake.override(_G, "cppdialect", function(base, dialect) if dialect then if not zpm.meta.building then zpm.loader.project.builder.cursor.cppdialect = base if zpm.meta.project ~= "" then tab = zpm.util.insertTable(zpm.loader.project.builder.cursor, {"workspaces", zpm.meta.workspace, "projects", zpm.meta.project, "cppdialects"}, dialect) else tab = zpm.util.insertTable(zpm.loader.project.builder.cursor, {"cppdialects"}, dialect) end end end end) premake.override(_G, "group", function(base, name) if (name or name == "") and not zpm.meta.exporting then zpm.meta.group = name end return base(name) end) premake.override(_G, "filter", function(base, fltr) if (fltr or fltr == "") then zpm.meta.filter = fltr end return base(fltr) end) premake.override(_G, "kind", function(base, knd) if kind and not zpm.meta.exporting then zpm.meta.kind = knd if not zpm.meta.building then zpm.util.setTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "kind"}, knd) end end return base(knd) end) premake.override(premake.main, "preBake", function(base) if zpm.loader and not zpm.util.isMainScriptDisabled() then zpm.loader.project.builder:walkDependencies() end return base() end)
Fix cpp dialects insert path
Fix cpp dialects insert path
Lua
mit
Zefiros-Software/ZPM
02cade60f8f40b84c8d65ea2616a317b1fa9590e
SpatialBatchNormalization.lua
SpatialBatchNormalization.lua
local SpatialBatchNormalization, parent = torch.class('cudnn.SpatialBatchNormalization', 'nn.SpatialBatchNormalization') local ffi = require 'ffi' local errcheck = cudnn.errcheck function SpatialBatchNormalization:__init(nFeature, eps, momentum, affine) parent.__init(self, nFeature, eps, momentum, affine) self.mode = 'CUDNN_BATCHNORM_SPATIAL' self.nFeature = nFeature self.save_mean = torch.Tensor(nFeature) self.save_std = torch.Tensor(nFeature) end function SpatialBatchNormalization:createIODescriptors(input) assert(input:dim() == 4) assert(torch.typename(self.weight) == 'torch.CudaTensor' and torch.typename(self.bias) == 'torch.CudaTensor', 'Only CUDA tensors are supported for cudnn.SpatialBatchNormalization!') if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then self.iSize = input:size() self.output:resizeAs(input) self.gradInput:resizeAs(input) self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) self.sDesc = cudnn.toDescriptor(self.bias:view(1, self.nFeature, 1, 1)) end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); local scaleTens = torch.FloatTensor(1); function SpatialBatchNormalization:updateOutput(input) self:createIODescriptors(input) if self.train then errcheck('cudnnBatchNormalizationForwardTraining', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.oDesc[0], self.output:data(), self.sDesc[0], self.weight:data(), self.bias:data(), self.momentum, self.running_mean:data(), self.running_var:data(), self.eps, self.save_mean:data(), self.save_std:data()); else errcheck('cudnnBatchNormalizationForwardInference', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.oDesc[0], self.output:data(), self.sDesc[0], self.weight:data(), self.bias:data(), self.running_mean:data(), self.running_var:data(), self.eps); end return self.output end local function backward(self,input,gradOutput, scale) assert(gradOutput:isContiguous()) self:createIODescriptors(input) scale = scale or 1 scaleTens:fill(scale) errcheck('cudnnBatchNormalizationBackward', cudnn.getHandle(), self.mode, one:data(), zero:data(), scaleTens:data(), one:data(), self.iDesc[0], input:data(), self.iDesc[0], gradOutput:data(), self.iDesc[0], self.gradInput:data(), -- input is bottom, gradOutput is topDiff, self.gradInput is resultBottomDiff self.sDesc[0], self.weight:data(), self.gradWeight:data(), self.gradBias:data(), self.eps, self.save_mean:data(), self.save_std:data()); return self.gradInput end function SpatialBatchNormalization:updateGradInput(input, gradOutput, scale) -- will in fact update gradWeight and gradBias too, accGradParameters call is empty return backward(self, input,gradOutput, scale) end function SpatialBatchNormalization:backward(input, gradOutput, scale) return backward(self, input,gradOutput, scale) end function SpatialBatchNormalization:accGradParameters(input, gradOutput, scale) end function SpatialBatchNormalization:write(f) self.iDesc = nil self.oDesc = nil self.sDesc = nil local var = {} for k,v in pairs(self) do var[k] = v end f:writeObject(var) end
local SpatialBatchNormalization, parent = torch.class('cudnn.SpatialBatchNormalization', 'nn.SpatialBatchNormalization') local ffi = require 'ffi' local errcheck = cudnn.errcheck SpatialBatchNormalization.__version = 2 function SpatialBatchNormalization:__init(nFeature, eps, momentum, affine) parent.__init(self, nFeature, eps, momentum, affine) self.mode = 'CUDNN_BATCHNORM_SPATIAL' self.nFeature = nFeature self.save_mean = torch.Tensor(nFeature) self.save_std = torch.Tensor(nFeature) end function SpatialBatchNormalization:createIODescriptors(input) assert(input:dim() == 4) assert(torch.typename(self.weight) == 'torch.CudaTensor' and torch.typename(self.bias) == 'torch.CudaTensor', 'Only CUDA tensors are supported for cudnn.SpatialBatchNormalization!') if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then self.iSize = input:size() self.output:resizeAs(input) self.gradInput:resizeAs(input) self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) self.sDesc = cudnn.toDescriptor(self.bias:view(1, self.nFeature, 1, 1)) end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); local scaleTens = torch.FloatTensor(1); function SpatialBatchNormalization:updateOutput(input) self:createIODescriptors(input) if self.train then errcheck('cudnnBatchNormalizationForwardTraining', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.oDesc[0], self.output:data(), self.sDesc[0], self.weight:data(), self.bias:data(), self.momentum, self.running_mean:data(), self.running_var:data(), self.eps, self.save_mean:data(), self.save_std:data()); else errcheck('cudnnBatchNormalizationForwardInference', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.oDesc[0], self.output:data(), self.sDesc[0], self.weight:data(), self.bias:data(), self.running_mean:data(), self.running_var:data(), self.eps); end return self.output end local function backward(self,input,gradOutput, scale) assert(gradOutput:isContiguous()) self:createIODescriptors(input) scale = scale or 1 scaleTens:fill(scale) errcheck('cudnnBatchNormalizationBackward', cudnn.getHandle(), self.mode, one:data(), zero:data(), scaleTens:data(), one:data(), self.iDesc[0], input:data(), self.iDesc[0], gradOutput:data(), self.iDesc[0], self.gradInput:data(), -- input is bottom, gradOutput is topDiff, self.gradInput is resultBottomDiff self.sDesc[0], self.weight:data(), self.gradWeight:data(), self.gradBias:data(), self.eps, self.save_mean:data(), self.save_std:data()); return self.gradInput end function SpatialBatchNormalization:updateGradInput(input, gradOutput, scale) -- will in fact update gradWeight and gradBias too, accGradParameters call is empty return backward(self, input,gradOutput, scale) end function SpatialBatchNormalization:backward(input, gradOutput, scale) return backward(self, input,gradOutput, scale) end function SpatialBatchNormalization:accGradParameters(input, gradOutput, scale) end function SpatialBatchNormalization:write(f) self.iDesc = nil self.oDesc = nil self.sDesc = nil local var = {} for k,v in pairs(self) do var[k] = v end f:writeObject(var) end function SpatialBatchNormalization:read(file, version) parent.read(self, file) if version < 2 then if self.running_std then -- for models before https://github.com/soumith/cudnn.torch/pull/101 self.running_var = self.running_std:pow(-2):add(-self.eps) self.running_std = nil end end end
serialization fix for older models
serialization fix for older models
Lua
bsd-3-clause
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
627de484c7d08b7e3f61b5d0c19fd60cbb32aea5
files/hammerspoon.lua
files/hammerspoon.lua
-- Global Quake mode for Alacritty on Mac OS; Refs: -- https://github.com/alacritty/alacritty/issues/862 -- https://gist.github.com/programus/d3bf9c6b8f9b7648891d1f59b665b35e -- https://world.hey.com/jonash/alacritty-drop-down-guake-quake-style-terminal-setup-on-macos-6eef7d73 -- This package needs to be extracted/installed at ~/.hammerspoon -- to get this script to work; package repo: -- https://github.com/asmagill/hs._asm.undocumented.spaces local spaces = require('hs._asm.undocumented.spaces') -- Switch alacritty hs.hotkey.bind({'ctrl','alt'}, 'space', function () local APP_NAME = 'Alacritty' function moveWindow(alacritty, space, mainScreen) -- move to main space local win = nil while win == nil do win = alacritty:mainWindow() end print(win) print(space) print(win:screen()) print(mainScreen) local fullScreen = not win:isStandard() if fullScreen then hs.eventtap.keyStroke('cmd', 'return', 0, alacritty) end winFrame = win:frame() scrFrame = mainScreen:fullFrame() print(winFrame) print(scrFrame) winFrame.w = scrFrame.w winFrame.y = scrFrame.y winFrame.x = scrFrame.x print(winFrame) win:setFrame(winFrame, 0) print(win:frame()) win:spacesMoveTo(space) if fullScreen then hs.eventtap.keyStroke('cmd', 'return', 0, alacritty) end win:focus() end local alacritty = hs.application.get(APP_NAME) if alacritty ~= nil and alacritty:isFrontmost() then alacritty:hide() else local space = spaces.activeSpace() local mainScreen = hs.screen.find(spaces.mainScreenUUID()) if alacritty == nil and hs.application.launchOrFocus(APP_NAME) then local appWatcher = nil print('create app watcher') appWatcher = hs.application.watcher.new(function(name, event, app) print(name) print(event) if event == hs.application.watcher.launched and name == APP_NAME then app:hide() moveWindow(app, space, mainScreen) appWatcher:stop() end end) print('start watcher') appWatcher:start() end if alacritty ~= nil then moveWindow(alacritty, space, mainScreen) end end end) -- Hide alacritty if not in focus -- hs.window.filter.default:subscribe(hs.window.filter.windowFocused, function(window, appName) -- local alacritty = hs.application.get('Alacritty') -- if alacritty ~= nil then -- alacritty:hide() -- end -- end)
-- Global Quake mode for Alacritty on Mac OS; Refs: -- https://github.com/alacritty/alacritty/issues/862 -- https://gist.github.com/programus/d3bf9c6b8f9b7648891d1f59b665b35e -- https://world.hey.com/jonash/alacritty-drop-down-guake-quake-style-terminal-setup-on-macos-6eef7d73 -- This package needs to be extracted/installed at ~/.hammerspoon -- to get this script to work; package repo: -- https://github.com/asmagill/hs._asm.undocumented.spaces local spaces = require('hs._asm.undocumented.spaces') -- Switch alacritty hs.hotkey.bind({'alt'}, '\'', function () local APP_NAME = 'Alacritty' function moveWindow(alacritty, space, mainScreen) -- move to main space local win = nil while win == nil do win = alacritty:mainWindow() end print(win) print(space) print(win:screen()) print(mainScreen) local fullScreen = not win:isStandard() if fullScreen then hs.eventtap.keyStroke('cmd', 'return', 0, alacritty) end winFrame = win:frame() scrFrame = mainScreen:fullFrame() print(winFrame) print(scrFrame) winFrame.w = scrFrame.w winFrame.y = scrFrame.y winFrame.x = scrFrame.x print(winFrame) win:setFrame(winFrame, 0) print(win:frame()) win:spacesMoveTo(space) if fullScreen then hs.eventtap.keyStroke('cmd', 'return', 0, alacritty) end win:focus() end local alacritty = hs.application.get(APP_NAME) if alacritty ~= nil and alacritty:isFrontmost() then alacritty:hide() else local space = spaces.activeSpace() local mainScreen = hs.screen.find(spaces.mainScreenUUID()) if alacritty == nil and hs.application.launchOrFocus(APP_NAME) then local appWatcher = nil print('create app watcher') appWatcher = hs.application.watcher.new(function(name, event, app) print(name) print(event) if event == hs.application.watcher.launched and name == APP_NAME then app:hide() moveWindow(app, space, mainScreen) appWatcher:stop() end end) print('start watcher') appWatcher:start() end if alacritty ~= nil then moveWindow(alacritty, space, mainScreen) end end end) -- Hide alacritty if not in focus -- hs.window.filter.default:subscribe(hs.window.filter.windowFocused, function(window, appName) -- local alacritty = hs.application.get('Alacritty') -- if alacritty ~= nil then -- alacritty:hide() -- end -- end) -- emacs-everywhere Shortcut hyper = {"ctrl", "shift"} hs.hotkey.bindSpec({hyper, "e"}, function () print("Running emacs-everywhere") hs.task.new("/bin/bash", nil, { "-l", "-c", "emacsclient --eval '(emacs-everywhere)'" }):start() end )
Hammerspoon emacs-everywhere
Hammerspoon emacs-everywhere Kinda buggy
Lua
unlicense
gabrielalmeida/dotfiles
5136f2b4bf6626313aeeda2bab7245a3ae0840f1
app/commands/run.lua
app/commands/run.lua
local uv = require('uv') local co = coroutine.running() local env = require('env') local newEnv = {} local keys = env.keys() for i = 1, #keys do local key = keys[i] local value = env.get(key) if key ~= "LUVI_APP" then newEnv[#newEnv + 1] = key .. "=" .. value end end newEnv[#newEnv + 1] = "LUVI_APP=" .. uv.cwd() local child = uv.spawn(uv.exepath(), { args = args, env = newEnv, stdio = {0,1,2} }, function (...) coroutine.resume(co, ...) end); coroutine.yield()
local uv = require('uv') local co = coroutine.running() local env = require('env') local newEnv = {} local keys = env.keys() for i = 1, #keys do local key = keys[i] local value = env.get(key) if key ~= "LUVI_APP" then newEnv[#newEnv + 1] = key .. "=" .. value end end newEnv[#newEnv + 1] = "LUVI_APP=" .. uv.cwd() local newArgs = {} for i = 2, #args do newArgs[i - 1] = args[i] end local child = uv.spawn(uv.exepath(), { args = newArgs, env = newEnv, stdio = {0,1,2} }, function (...) coroutine.resume(co, ...) end); coroutine.yield()
Fix argument passing in lit run
Fix argument passing in lit run
Lua
apache-2.0
1yvT0s/lit,kaustavha/lit,luvit/lit,james2doyle/lit,squeek502/lit,zhaozg/lit,kidaa/lit,lduboeuf/lit,DBarney/lit
3ac83e8cd3d9d3fe76263501fbafd092a9a47a03
test/tools.lua
test/tools.lua
odbc = require "odbc" require "config" function run_test(arg) local _, emsg = xpcall(function() lunit.main(arg) end, debug.traceback) if emsg then print(emsg) os.exit(1) end if lunit.stats.failed > 0 then os.exit(1) end end function is_dsn_exists(env, dsn_name) local cnt, d = return_count(env:datasources(function(dsn) if dsn:upper() == dsn_name:upper() then return dsn end end)) assert((cnt == 0) or ( d:upper() == dsn_name:upper() )) return d end function return_count(...) return select('#', ...), ... end unpack = unpack or table.unpack function do_connect() local env, cnn local err env,err = odbc.environment() if env then cnn,err = env:connection() if cnn then local ok ok, err = cnn:driverconnect(CNN_DRV) if ok then return env, cnn end end end if cnn then cnn:destroy() end if env then env:destroy() end return nil, err end function exec_ddl(cnn, cmd) local stmt, err = cnn:statement() if not stmt then return nil, err end local ok, err = stmt:execute (cmd) stmt:destroy() return ok, err end function define_table (n) local t = {} for i = 1, n do table.insert (t, "f"..i.." "..DEFINITION_STRING_TYPE_NAME) end return "create table " .. TEST_TABLE_NAME .. " ("..table.concat (t, ',')..")" end function create_table (cnn) return exec_ddl(cnn, define_table(TOTAL_FIELDS)) end function drop_table(cnn) return exec_ddl(cnn, 'drop table ' .. TEST_TABLE_NAME) end function table_exists(cnn) local stmt, err = cnn:tables() if not stmt then return nil, err end local found, err = stmt:foreach(function(_,_,t) if t:lower() == TEST_TABLE_NAME:lower() then return true end end) stmt:destroy() if (not found) and (not err) then found = false end return found, err end function ensure_table(cnn) if table_exists(cnn) then drop_table(cnn) end return create_table(cnn) end function proc_exists(cnn) local stmt, err = cnn:procedures() if not stmt then return nil, err end local found, err = stmt:foreach(function(_,_,t) if t:lower() == TEST_PROC_NAME:lower() then return true end end) stmt:destroy() if (not found) and (not err) then found = false end return found, err end function create_proc (cnn) return exec_ddl(cnn, TEST_PROC_CREATE) end function drop_proc(cnn) return exec_ddl(cnn, TEST_PROC_DROP) end function ensure_proc(cnn) if proc_exists(cnn) then drop_proc(cnn) end return create_proc(cnn) end local lunit = require "lunit" local IS_LUA52 = _VERSION >= 'Lua 5.2' TEST_CASE = function (name) if not IS_LUA52 then module(name, package.seeall, lunit.testcase) setfenv(2, _M) else return lunit.module(name, 'seeall') end end
odbc = require "odbc" require "config" IS_LUA52 = _VERSION >= 'Lua 5.2' function run_test(arg) local _, emsg = xpcall(function() lunit.main(arg) end, debug.traceback) if emsg then print(emsg) os.exit(1) end if lunit.stats.failed > 0 then os.exit(1) end end function is_dsn_exists(env, dsn_name) local cnt, d = return_count(env:datasources(function(dsn) if dsn:upper() == dsn_name:upper() then return dsn end end)) assert((cnt == 0) or ( d:upper() == dsn_name:upper() )) return d end function return_count(...) return select('#', ...), ... end unpack = unpack or table.unpack function do_connect() local env, cnn local err env,err = odbc.environment() if env then cnn,err = env:connection() if cnn then local ok ok, err = cnn:driverconnect(CNN_DRV) if ok then return env, cnn end end end if cnn then cnn:destroy() end if env then env:destroy() end return nil, err end function exec_ddl(cnn, cmd) local stmt, err = cnn:statement() if not stmt then return nil, err end local ok, err = stmt:execute (cmd) stmt:destroy() return ok, err end function define_table (n) local t = {} for i = 1, n do table.insert (t, "f"..i.." "..DEFINITION_STRING_TYPE_NAME) end return "create table " .. TEST_TABLE_NAME .. " ("..table.concat (t, ',')..")" end function create_table (cnn) return exec_ddl(cnn, define_table(TOTAL_FIELDS)) end function drop_table(cnn) return exec_ddl(cnn, 'drop table ' .. TEST_TABLE_NAME) end function table_exists(cnn) local stmt, err = cnn:tables() if not stmt then return nil, err end local found, err = stmt:foreach(function(_,_,t) if t:lower() == TEST_TABLE_NAME:lower() then return true end end) stmt:destroy() if (not found) and (not err) then found = false end return found, err end function ensure_table(cnn) if table_exists(cnn) then drop_table(cnn) end return create_table(cnn) end function proc_exists(cnn) local stmt, err = cnn:procedures() if not stmt then return nil, err end local found, err = stmt:foreach(function(_,_,t) if t:lower() == TEST_PROC_NAME:lower() then return true end end) stmt:destroy() if (not found) and (not err) then found = false end return found, err end function create_proc (cnn) return exec_ddl(cnn, TEST_PROC_CREATE) end function drop_proc(cnn) return exec_ddl(cnn, TEST_PROC_DROP) end function ensure_proc(cnn) if proc_exists(cnn) then drop_proc(cnn) end return create_proc(cnn) end function TEST_CASE (name) local lunit = require"lunit" if not IS_LUA52 then module(name, package.seeall, lunit.testcase) setfenv(2, _M) else return lunit.module(name, 'seeall') end end
Fix. Test can be run one by one.
Fix. Test can be run one by one.
Lua
mit
moteus/lua-odbc,moteus/lua-odbc,moteus/lua-odbc
85f4ad7eebf5e7778c487cf6edbd8dc97fb0f40c
src/plugins/lua/fann_scores.lua
src/plugins/lua/fann_scores.lua
--[[ Copyright (c) 2015, Vsevolod Stakhov <vsevolod@highsecure.ru> 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. ]]-- -- This plugin is a concept of FANN scores adjustment -- NOT FOR PRODUCTION USE so far local rspamd_logger = require "rspamd_logger" local rspamd_fann = require "rspamd_fann" local rspamd_util = require "rspamd_util" local fann_symbol = 'FANN_SCORE' local ucl = require "ucl" -- Module vars local fann local fann_train local fann_file local ntrains = 0 local max_trains = 1000 local epoch = 0 local max_epoch = 100 local fann_mtime = 0 local opts = rspamd_config:get_all_opt("fann_scores") local function load_fann() local err,st = rspamd_util.stat(fann_file) if err then return false end fann = rspamd_fann.load(fann_file) if fann then local n = rspamd_config:get_symbols_count() if n ~= fann:get_inputs() then rspamd_logger.infox(rspamd_config, 'fann has incorrect number of inputs: %s, %s symbols' .. ' is found in the cache', fann:get_inputs(), n) fann = nil else rspamd_logger.infox(rspamd_config, 'loaded fann from %s', fann_file) return true end end return false end local function check_fann() local n = rspamd_config:get_symbols_count() if fann then local n = rspamd_config:get_symbols_count() if n ~= fann:get_inputs() then rspamd_logger.infox(rspamd_config, 'fann has incorrect number of inputs: %s, %s symbols' .. ' is found in the cache', fann:get_inputs(), n) fann = nil end end local err,st = rspamd_util.stat(fann_file) if not err then local mtime = st['mtime'] if mtime > fann_mtime then fann_mtime = mtime fann = nil end end end local function fann_scores_filter(task) check_fann() if fann then local fann_input = {} for sym,idx in pairs(symbols) do if task:has_symbol(sym) then fann_input[idx + 1] = 1 else fann_input[idx + 1] = 0 end end local out = fann:test(nsymbols, fann_input) local result = rspamd_util.tanh(2 * (out[1] - 0.5)) local symscore = string.format('%.3f', out[1]) rspamd_logger.infox(task, 'fann score: %s', symscore) task:insert_result(fann_symbol, result, symscore) else if load_fann() then fann_scores_filter(task) end end end local function create_train_fann(n) fann_train = rspamd_fann.create(3, n, n / 2, 1) ntrains = 0 epoch = 0 end local function fann_train(score, required_score,results, cf, opts) local n = cf:get_symbols_count() if not fann_train then create_train_fann(n) end if fann_train:get_inputs() ~= n then rspamd_logger.infox(cf, 'fann has incorrect number of inputs: %s, %s symbols' .. ' is found in the cache', fann_train:get_inputs(), n) create_train_fann(n) end if ntrains > max_trains then -- Store fann on disk res = fann_train:save(fann_file) if not res then rspamd_logger.errx(cf, 'cannot save fann in %s', fann_file) else ntrains = 0 epoch = epoch + 1 end end if epoch > max_epoch then -- Re-create fann rspamd_logger.infox(cf, 'create new fann in %s after %s epoches', fann_file, max_epoch) create_train_fann(n) end local learn_spam, learn_ham = false, false if opts['spam_score'] then learn_spam = score >= opts['spam_score'] else learn_spam = score >= required_score end if opts['ham_score'] then learn_ham = score <= opts['ham_score'] else learn_ham = score < 0 end if learn_spam or learn_ham then local learn_data = {} local matched_symbols = {} for _,sym in ipairs(results) do matched_symbols[sym[1] + 1] = 1 end for i=1,(n + 1) do if matched_symbols[i] then learn_data[i] = 1 else learn_data[i] = 0 end end if learn_spam then fann_train:train(learn_data, 1.0) else fann_train:train(learn_data, 0.0) end trains = trains + 1 end end if not rspamd_fann.is_enabled() then rspamd_logger.errx(rspamd_config, 'fann is not compiled in rspamd, this ' .. 'module is eventually disabled') else if not opts['fann_file'] then rspamd_logger.errx(rspamd_config, 'fann_scores module requires ' .. '`fann_file` to be specified') else fann_file = opts['fann_file'] rspamd_config:set_metric_symbol(fann_symbol, 3.0, 'Experimental FANN adjustment') rspamd_config:register_post_filter(fann_scores_filter) if opts['train'] then rspamd_config:add_on_load(function(cfg) if opts['train']['max_train'] then max_trains = opts['train']['max_train'] end if opts['train']['max_epoch'] then max_trains = opts['train']['max_epoch'] end cfg:register_worker_script("log_helper", function(score, req_score, results, cf) fann_train(score, req_score, results, cf, opts['train']) end) end) end end end
--[[ Copyright (c) 2015, Vsevolod Stakhov <vsevolod@highsecure.ru> 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. ]]-- -- This plugin is a concept of FANN scores adjustment -- NOT FOR PRODUCTION USE so far local rspamd_logger = require "rspamd_logger" local rspamd_fann = require "rspamd_fann" local rspamd_util = require "rspamd_util" local fann_symbol = 'FANN_SCORE' require "fun" () local ucl = require "ucl" -- Module vars local fann = nil local fann_train = nil local fann_file local ntrains = 0 local max_trains = 1000 local epoch = 0 local max_epoch = 100 local fann_mtime = 0 local opts = rspamd_config:get_all_opt("fann_scores") local function symbols_to_fann_vector(syms) local learn_data = {} local matched_symbols = {} local n = rspamd_config:get_symbols_count() each(function(s) matched_symbols[s + 1] = 1 end, syms) for i=1,n do if matched_symbols[i] then learn_data[i] = 1 else learn_data[i] = 0 end end return learn_data end local function load_fann() local err,st = rspamd_util.stat(fann_file) if err then return false end fann = rspamd_fann.load(fann_file) if fann then local n = rspamd_config:get_symbols_count() if n ~= fann:get_inputs() then rspamd_logger.infox(rspamd_config, 'fann has incorrect number of inputs: %s, %s symbols' .. ' is found in the cache', fann:get_inputs(), n) fann = nil else rspamd_logger.infox(rspamd_config, 'loaded fann from %s', fann_file) return true end end return false end local function check_fann() if fann then local n = rspamd_config:get_symbols_count() if n ~= fann:get_inputs() then rspamd_logger.infox(rspamd_config, 'fann has incorrect number of inputs: %s, %s symbols' .. ' is found in the cache', fann:get_inputs(), n) fann = nil end end local err,st = rspamd_util.stat(fann_file) if not err then local mtime = st['mtime'] if mtime > fann_mtime then fann_mtime = mtime fann = nil end end end local function fann_scores_filter(task) check_fann() if fann then local symbols = task:get_symbols_numeric() local fann_data = symbols_to_fann_vector(symbols) local out = fann:test(fann_data) local result = rspamd_util.tanh(2 * (out[1] - 0.5)) local symscore = string.format('%.3f', out[1]) rspamd_logger.infox(task, 'fann score: %s', symscore) task:insert_result(fann_symbol, result, symscore) else if load_fann() then fann_scores_filter(task) end end end local function create_train_fann(n) fann_train = rspamd_fann.create(3, n, n / 2, 1) ntrains = 0 epoch = 0 end local function fann_train_callback(score, required_score,results, cf, opts) local n = cf:get_symbols_count() if not fann_train then create_train_fann(n) end if fann_train:get_inputs() ~= n then rspamd_logger.infox(cf, 'fann has incorrect number of inputs: %s, %s symbols' .. ' is found in the cache', fann_train:get_inputs(), n) create_train_fann(n) end if ntrains > max_trains then -- Store fann on disk res = fann_train:save(fann_file) if not res then rspamd_logger.errx(cf, 'cannot save fann in %s', fann_file) else ntrains = 0 epoch = epoch + 1 end end if epoch > max_epoch then -- Re-create fann rspamd_logger.infox(cf, 'create new fann in %s after %s epoches', fann_file, max_epoch) create_train_fann(n) end local learn_spam, learn_ham = false, false if opts['spam_score'] then learn_spam = score >= opts['spam_score'] else learn_spam = score >= required_score end if opts['ham_score'] then learn_ham = score <= opts['ham_score'] else learn_ham = score < 0 end if learn_spam or learn_ham then local learn_data = symbols_to_fann_vector( map(function(r) return r[1] end, results) ) if learn_spam then fann_train:train(learn_data, {1.0}) else fann_train:train(learn_data, {0.0}) end ntrains = ntrains + 1 end end if not rspamd_fann.is_enabled() then rspamd_logger.errx(rspamd_config, 'fann is not compiled in rspamd, this ' .. 'module is eventually disabled') else if not opts['fann_file'] then rspamd_logger.errx(rspamd_config, 'fann_scores module requires ' .. '`fann_file` to be specified') else fann_file = opts['fann_file'] rspamd_config:set_metric_symbol(fann_symbol, 3.0, 'Experimental FANN adjustment') rspamd_config:register_post_filter(fann_scores_filter) if opts['train'] then rspamd_config:add_on_load(function(cfg) if opts['train']['max_train'] then max_trains = opts['train']['max_train'] end if opts['train']['max_epoch'] then max_trains = opts['train']['max_epoch'] end cfg:register_worker_script("log_helper", function(score, req_score, results, cf) fann_train_callback(score, req_score, results, cf, opts['train']) end) end) end end end
[Fix] Rework fann learning
[Fix] Rework fann learning
Lua
bsd-2-clause
AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd
875ba15c4c2196f08926ce84c4839ae6c3d3edb2
kong/templates/nginx_kong_stream.lua
kong/templates/nginx_kong_stream.lua
return [[ log_format basic '$remote_addr [$time_local] ' '$protocol $status $bytes_sent $bytes_received ' '$session_time'; lua_package_path '${{LUA_PACKAGE_PATH}};;'; lua_package_cpath '${{LUA_PACKAGE_CPATH}};;'; lua_socket_pool_size ${{LUA_SOCKET_POOL_SIZE}}; lua_socket_log_errors off; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}}; > if lua_ssl_trusted_certificate_combined then lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE_COMBINED}}'; > end lua_shared_dict stream_kong 5m; lua_shared_dict stream_kong_locks 8m; lua_shared_dict stream_kong_healthchecks 5m; lua_shared_dict stream_kong_process_events 5m; lua_shared_dict stream_kong_cluster_events 5m; lua_shared_dict stream_kong_rate_limiting_counters 12m; lua_shared_dict stream_kong_core_db_cache ${{MEM_CACHE_SIZE}}; lua_shared_dict stream_kong_core_db_cache_miss 12m; lua_shared_dict stream_kong_db_cache ${{MEM_CACHE_SIZE}}; lua_shared_dict stream_kong_db_cache_miss 12m; > if database == "off" then lua_shared_dict stream_kong_core_db_cache_2 ${{MEM_CACHE_SIZE}}; lua_shared_dict stream_kong_core_db_cache_miss_2 12m; lua_shared_dict stream_kong_db_cache_2 ${{MEM_CACHE_SIZE}}; lua_shared_dict stream_kong_db_cache_miss_2 12m; > end > if database == "cassandra" then lua_shared_dict stream_kong_cassandra 5m; > end > if ssl_ciphers then ssl_ciphers ${{SSL_CIPHERS}}; > end # injected nginx_stream_* directives > for _, el in ipairs(nginx_stream_directives) do $(el.name) $(el.value); > end init_by_lua_block { -- shared dictionaries conflict between stream/http modules. use a prefix. local shared = ngx.shared ngx.shared = setmetatable({}, { __index = function(t, k) return shared["stream_" .. k] end, }) Kong = require 'kong' Kong.init() } init_worker_by_lua_block { Kong.init_worker() } upstream kong_upstream { server 0.0.0.1:1; balancer_by_lua_block { Kong.balancer() } # injected nginx_supstream_* directives > for _, el in ipairs(nginx_supstream_directives) do $(el.name) $(el.value); > end } > if #stream_listeners > 0 then server { > for _, entry in ipairs(stream_listeners) do listen $(entry.listener); > end access_log ${{PROXY_STREAM_ACCESS_LOG}}; error_log ${{PROXY_STREAM_ERROR_LOG}} ${{LOG_LEVEL}}; > for _, ip in ipairs(trusted_ips) do set_real_ip_from $(ip); > end # injected nginx_sproxy_* directives > for _, el in ipairs(nginx_sproxy_directives) do $(el.name) $(el.value); > end > if stream_proxy_ssl_enabled then > for i = 1, #ssl_cert do ssl_certificate $(ssl_cert[i]); ssl_certificate_key $(ssl_cert_key[i]); > end ssl_session_cache shared:StreamSSL:10m; ssl_certificate_by_lua_block { Kong.ssl_certificate() } > end preread_by_lua_block { Kong.preread() } proxy_ssl on; proxy_ssl_server_name on; > if client_ssl then proxy_ssl_certificate ${{CLIENT_SSL_CERT}}; proxy_ssl_certificate_key ${{CLIENT_SSL_CERT_KEY}}; > end proxy_pass kong_upstream; log_by_lua_block { Kong.log() } } > if database == "off" then server { listen unix:${{PREFIX}}/stream_config.sock; error_log ${{ADMIN_ERROR_LOG}} ${{LOG_LEVEL}}; content_by_lua_block { Kong.stream_config_listener() } } > end -- database == "off" server { # ignore (and close }, to ignore content) listen unix:${{PREFIX}}/stream_rpc.sock udp; error_log ${{ADMIN_ERROR_LOG}} ${{LOG_LEVEL}}; content_by_lua_block { Kong.stream_api() } } > end -- #stream_listeners > 0 ]]
return [[ log_format basic '$remote_addr [$time_local] ' '$protocol $status $bytes_sent $bytes_received ' '$session_time'; lua_package_path '${{LUA_PACKAGE_PATH}};;'; lua_package_cpath '${{LUA_PACKAGE_CPATH}};;'; lua_socket_pool_size ${{LUA_SOCKET_POOL_SIZE}}; lua_socket_log_errors off; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}}; > if lua_ssl_trusted_certificate_combined then lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE_COMBINED}}'; > end lua_shared_dict stream_kong 5m; lua_shared_dict stream_kong_locks 8m; lua_shared_dict stream_kong_healthchecks 5m; lua_shared_dict stream_kong_process_events 5m; lua_shared_dict stream_kong_cluster_events 5m; lua_shared_dict stream_kong_rate_limiting_counters 12m; lua_shared_dict stream_kong_core_db_cache ${{MEM_CACHE_SIZE}}; lua_shared_dict stream_kong_core_db_cache_miss 12m; lua_shared_dict stream_kong_db_cache ${{MEM_CACHE_SIZE}}; lua_shared_dict stream_kong_db_cache_miss 12m; > if database == "off" then lua_shared_dict stream_kong_core_db_cache_2 ${{MEM_CACHE_SIZE}}; lua_shared_dict stream_kong_core_db_cache_miss_2 12m; lua_shared_dict stream_kong_db_cache_2 ${{MEM_CACHE_SIZE}}; lua_shared_dict stream_kong_db_cache_miss_2 12m; > end > if database == "cassandra" then lua_shared_dict stream_kong_cassandra 5m; > end > if ssl_ciphers then ssl_ciphers ${{SSL_CIPHERS}}; > end # injected nginx_stream_* directives > for _, el in ipairs(nginx_stream_directives) do $(el.name) $(el.value); > end init_by_lua_block { -- shared dictionaries conflict between stream/http modules. use a prefix. local shared = ngx.shared local stream_shdict_prefix = "stream_" ngx.shared = setmetatable({}, { __pairs = function() local i return function() local k, v = next(shared, i) i = k if k and k:sub(1, #stream_shdict_prefix) == stream_shdict_prefix then k = k:sub(#stream_shdict_prefix + 1) end return k, v end end, __index = function(t, k) return shared[stream_shdict_prefix .. k] end, }) Kong = require 'kong' Kong.init() } init_worker_by_lua_block { Kong.init_worker() } upstream kong_upstream { server 0.0.0.1:1; balancer_by_lua_block { Kong.balancer() } # injected nginx_supstream_* directives > for _, el in ipairs(nginx_supstream_directives) do $(el.name) $(el.value); > end } > if #stream_listeners > 0 then server { > for _, entry in ipairs(stream_listeners) do listen $(entry.listener); > end access_log ${{PROXY_STREAM_ACCESS_LOG}}; error_log ${{PROXY_STREAM_ERROR_LOG}} ${{LOG_LEVEL}}; > for _, ip in ipairs(trusted_ips) do set_real_ip_from $(ip); > end # injected nginx_sproxy_* directives > for _, el in ipairs(nginx_sproxy_directives) do $(el.name) $(el.value); > end > if stream_proxy_ssl_enabled then > for i = 1, #ssl_cert do ssl_certificate $(ssl_cert[i]); ssl_certificate_key $(ssl_cert_key[i]); > end ssl_session_cache shared:StreamSSL:10m; ssl_certificate_by_lua_block { Kong.ssl_certificate() } > end preread_by_lua_block { Kong.preread() } proxy_ssl on; proxy_ssl_server_name on; > if client_ssl then proxy_ssl_certificate ${{CLIENT_SSL_CERT}}; proxy_ssl_certificate_key ${{CLIENT_SSL_CERT_KEY}}; > end proxy_pass kong_upstream; log_by_lua_block { Kong.log() } } > if database == "off" then server { listen unix:${{PREFIX}}/stream_config.sock; error_log ${{ADMIN_ERROR_LOG}} ${{LOG_LEVEL}}; content_by_lua_block { Kong.stream_config_listener() } } > end -- database == "off" server { # ignore (and close }, to ignore content) listen unix:${{PREFIX}}/stream_rpc.sock udp; error_log ${{ADMIN_ERROR_LOG}} ${{LOG_LEVEL}}; content_by_lua_block { Kong.stream_api() } } > end -- #stream_listeners > 0 ]]
fix(template) fix iterator in stream shdict (#7078)
fix(template) fix iterator in stream shdict (#7078) `kong.pdk.node` iterrates through ngx.shared magic table to get list of shdict metrics, implement the __pairs metamethod so it's happy. Co-authored-by: Datong Sun <88ea7fe5b18d86dd626610096bab9e86520f1a58@konghq.com>
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
79c8a8023da5c9eee3d37de3ecce533977458c9d
kong/templates/nginx_kong.lua
kong/templates/nginx_kong.lua
return [[ charset UTF-8; > if anonymous_reports then ${{SYSLOG_REPORTS}} > end error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}}; > if nginx_optimizations then >-- send_timeout 60s; # default value >-- keepalive_timeout 75s; # default value >-- client_body_timeout 60s; # default value >-- client_header_timeout 60s; # default value >-- tcp_nopush on; # disabled until benchmarked >-- proxy_buffer_size 128k; # disabled until benchmarked >-- proxy_buffers 4 256k; # disabled until benchmarked >-- proxy_busy_buffers_size 256k; # disabled until benchmarked >-- reset_timedout_connection on; # disabled until benchmarked > end client_max_body_size ${{CLIENT_MAX_BODY_SIZE}}; proxy_ssl_server_name on; underscores_in_headers on; lua_package_path '${{LUA_PACKAGE_PATH}};;'; lua_package_cpath '${{LUA_PACKAGE_CPATH}};;'; lua_socket_pool_size ${{LUA_SOCKET_POOL_SIZE}}; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict kong 5m; lua_shared_dict kong_cache ${{MEM_CACHE_SIZE}}; lua_shared_dict kong_db_cache_miss 12m; lua_shared_dict kong_process_events 5m; lua_shared_dict kong_cluster_events 5m; lua_shared_dict kong_healthchecks 5m; lua_shared_dict kong_rate_limiting_counters 12m; > if database == "cassandra" then lua_shared_dict kong_cassandra 5m; > end lua_socket_log_errors off; > if lua_ssl_trusted_certificate then lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}'; lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}}; > end # injected nginx_http_* directives > for k, v in pairs(nginx_http_directives) do $(k) $(v); > end init_by_lua_block { kong = require 'kong' kong.init() } init_worker_by_lua_block { kong.init_worker() } > if #proxy_listeners > 0 then upstream kong_upstream { server 0.0.0.1; balancer_by_lua_block { kong.balancer() } keepalive ${{UPSTREAM_KEEPALIVE}}; } server { server_name kong; > for i = 1, #proxy_listeners do listen $(proxy_listeners[i].listener); > end error_page 400 404 408 411 412 413 414 417 494 /kong_error_handler; error_page 500 502 503 504 /kong_error_handler; access_log ${{PROXY_ACCESS_LOG}}; error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}}; client_body_buffer_size ${{CLIENT_BODY_BUFFER_SIZE}}; > if proxy_ssl_enabled then ssl_certificate ${{SSL_CERT}}; ssl_certificate_key ${{SSL_CERT_KEY}}; ssl_protocols TLSv1.1 TLSv1.2; ssl_certificate_by_lua_block { kong.ssl_certificate() } ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_prefer_server_ciphers on; ssl_ciphers ${{SSL_CIPHERS}}; > end > if client_ssl then proxy_ssl_certificate ${{CLIENT_SSL_CERT}}; proxy_ssl_certificate_key ${{CLIENT_SSL_CERT_KEY}}; > end real_ip_header ${{REAL_IP_HEADER}}; real_ip_recursive ${{REAL_IP_RECURSIVE}}; > for i = 1, #trusted_ips do set_real_ip_from $(trusted_ips[i]); > end # injected nginx_proxy_* directives > for k, v in pairs(nginx_proxy_directives) do $(k) $(v); > end location / { set $ctx_ref ''; set $upstream_host ''; set $upstream_upgrade ''; set $upstream_connection ''; set $upstream_scheme ''; set $upstream_uri ''; set $upstream_x_forwarded_for ''; set $upstream_x_forwarded_proto ''; set $upstream_x_forwarded_host ''; set $upstream_x_forwarded_port ''; rewrite_by_lua_block { kong.rewrite() } access_by_lua_block { kong.access() } proxy_http_version 1.1; proxy_set_header Host $upstream_host; proxy_set_header Upgrade $upstream_upgrade; proxy_set_header Connection $upstream_connection; proxy_set_header X-Forwarded-For $upstream_x_forwarded_for; proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto; proxy_set_header X-Forwarded-Host $upstream_x_forwarded_host; proxy_set_header X-Forwarded-Port $upstream_x_forwarded_port; proxy_set_header X-Real-IP $remote_addr; proxy_pass_header Server; proxy_pass_header Date; proxy_ssl_name $upstream_host; proxy_pass $upstream_scheme://kong_upstream$upstream_uri; header_filter_by_lua_block { kong.header_filter() } body_filter_by_lua_block { kong.body_filter() } log_by_lua_block { kong.log() } } location = /kong_error_handler { internal; uninitialized_variable_warn off; content_by_lua_block { kong.handle_error() } header_filter_by_lua_block { kong.header_filter() } body_filter_by_lua_block { kong.body_filter() } log_by_lua_block { kong.log() } } } > end > if #admin_listeners > 0 then server { server_name kong_admin; > for i = 1, #admin_listeners do listen $(admin_listeners[i].listener); > end access_log ${{ADMIN_ACCESS_LOG}}; error_log ${{ADMIN_ERROR_LOG}} ${{LOG_LEVEL}}; client_max_body_size 10m; client_body_buffer_size 10m; > if admin_ssl_enabled then ssl_certificate ${{ADMIN_SSL_CERT}}; ssl_certificate_key ${{ADMIN_SSL_CERT_KEY}}; ssl_protocols TLSv1.1 TLSv1.2; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_prefer_server_ciphers on; ssl_ciphers ${{SSL_CIPHERS}}; > end # injected nginx_admin_* directives > for k, v in pairs(nginx_admin_directives) do $(k) $(v); > end location / { default_type application/json; content_by_lua_block { kong.serve_admin_api() } } location /nginx_status { internal; access_log off; stub_status; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } } > end ]]
return [[ charset UTF-8; > if anonymous_reports then ${{SYSLOG_REPORTS}} > end error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}}; > if nginx_optimizations then >-- send_timeout 60s; # default value >-- keepalive_timeout 75s; # default value >-- client_body_timeout 60s; # default value >-- client_header_timeout 60s; # default value >-- tcp_nopush on; # disabled until benchmarked >-- proxy_buffer_size 128k; # disabled until benchmarked >-- proxy_buffers 4 256k; # disabled until benchmarked >-- proxy_busy_buffers_size 256k; # disabled until benchmarked >-- reset_timedout_connection on; # disabled until benchmarked > end client_max_body_size ${{CLIENT_MAX_BODY_SIZE}}; proxy_ssl_server_name on; underscores_in_headers on; lua_package_path '${{LUA_PACKAGE_PATH}};;'; lua_package_cpath '${{LUA_PACKAGE_CPATH}};;'; lua_socket_pool_size ${{LUA_SOCKET_POOL_SIZE}}; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict kong 5m; lua_shared_dict kong_cache ${{MEM_CACHE_SIZE}}; lua_shared_dict kong_db_cache_miss 12m; lua_shared_dict kong_process_events 5m; lua_shared_dict kong_cluster_events 5m; lua_shared_dict kong_healthchecks 5m; lua_shared_dict kong_rate_limiting_counters 12m; > if database == "cassandra" then lua_shared_dict kong_cassandra 5m; > end lua_socket_log_errors off; > if lua_ssl_trusted_certificate then lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}'; lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}}; > end # injected nginx_http_* directives > for k, v in pairs(nginx_http_directives) do $(k) $(v); > end init_by_lua_block { kong = require 'kong' kong.init() } init_worker_by_lua_block { kong.init_worker() } > if #proxy_listeners > 0 then upstream kong_upstream { server 0.0.0.1; balancer_by_lua_block { kong.balancer() } keepalive ${{UPSTREAM_KEEPALIVE}}; } server { server_name kong; > for i = 1, #proxy_listeners do listen $(proxy_listeners[i].listener); > end error_page 400 404 408 411 412 413 414 417 494 /kong_error_handler; error_page 500 502 503 504 /kong_error_handler; access_log ${{PROXY_ACCESS_LOG}}; error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}}; client_body_buffer_size ${{CLIENT_BODY_BUFFER_SIZE}}; > if proxy_ssl_enabled then ssl_certificate ${{SSL_CERT}}; ssl_certificate_key ${{SSL_CERT_KEY}}; ssl_protocols TLSv1.1 TLSv1.2; ssl_certificate_by_lua_block { kong.ssl_certificate() } ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_prefer_server_ciphers on; ssl_ciphers ${{SSL_CIPHERS}}; > end > if client_ssl then proxy_ssl_certificate ${{CLIENT_SSL_CERT}}; proxy_ssl_certificate_key ${{CLIENT_SSL_CERT_KEY}}; > end real_ip_header ${{REAL_IP_HEADER}}; real_ip_recursive ${{REAL_IP_RECURSIVE}}; > for i = 1, #trusted_ips do set_real_ip_from $(trusted_ips[i]); > end # injected nginx_proxy_* directives > for k, v in pairs(nginx_proxy_directives) do $(k) $(v); > end location / { default_type ''; set $ctx_ref ''; set $upstream_host ''; set $upstream_upgrade ''; set $upstream_connection ''; set $upstream_scheme ''; set $upstream_uri ''; set $upstream_x_forwarded_for ''; set $upstream_x_forwarded_proto ''; set $upstream_x_forwarded_host ''; set $upstream_x_forwarded_port ''; rewrite_by_lua_block { kong.rewrite() } access_by_lua_block { kong.access() } proxy_http_version 1.1; proxy_set_header Host $upstream_host; proxy_set_header Upgrade $upstream_upgrade; proxy_set_header Connection $upstream_connection; proxy_set_header X-Forwarded-For $upstream_x_forwarded_for; proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto; proxy_set_header X-Forwarded-Host $upstream_x_forwarded_host; proxy_set_header X-Forwarded-Port $upstream_x_forwarded_port; proxy_set_header X-Real-IP $remote_addr; proxy_pass_header Server; proxy_pass_header Date; proxy_ssl_name $upstream_host; proxy_pass $upstream_scheme://kong_upstream$upstream_uri; header_filter_by_lua_block { kong.header_filter() } body_filter_by_lua_block { kong.body_filter() } log_by_lua_block { kong.log() } } location = /kong_error_handler { internal; uninitialized_variable_warn off; content_by_lua_block { kong.handle_error() } header_filter_by_lua_block { kong.header_filter() } body_filter_by_lua_block { kong.body_filter() } log_by_lua_block { kong.log() } } } > end > if #admin_listeners > 0 then server { server_name kong_admin; > for i = 1, #admin_listeners do listen $(admin_listeners[i].listener); > end access_log ${{ADMIN_ACCESS_LOG}}; error_log ${{ADMIN_ERROR_LOG}} ${{LOG_LEVEL}}; client_max_body_size 10m; client_body_buffer_size 10m; > if admin_ssl_enabled then ssl_certificate ${{ADMIN_SSL_CERT}}; ssl_certificate_key ${{ADMIN_SSL_CERT_KEY}}; ssl_protocols TLSv1.1 TLSv1.2; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_prefer_server_ciphers on; ssl_ciphers ${{SSL_CIPHERS}}; > end # injected nginx_admin_* directives > for k, v in pairs(nginx_admin_directives) do $(k) $(v); > end location / { default_type application/json; content_by_lua_block { kong.serve_admin_api() } } location /nginx_status { internal; access_log off; stub_status; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } } > end ]]
fix(nginx-conf) add missing 'default_type' directive (#3542)
fix(nginx-conf) add missing 'default_type' directive (#3542) Likely the result of a merge gone wrong, since this value was added in cbe4a612ee85b395d176ab85b38561a3839db183.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
acbec658adfe01fd22470533594a47175b1bc0fd
src/tools/msc.lua
src/tools/msc.lua
-- -- msc.lua -- Interface for the MS C/C++ compiler. -- Copyright (c) 2009-2013 Jason Perkins and the Premake project -- premake.tools.msc = {} local msc = premake.tools.msc local project = premake.project local config = premake.config -- -- Returns list of C preprocessor flags for a configuration. -- function msc.getcppflags(cfg) return {} end -- -- Returns list of C compiler flags for a configuration. -- msc.cflags = { flags = { SEH = "/EHa /EHsc", Symbols = "/Z7", }, optimize = { Off = "/Od", Speed = "/O2", } } function msc.getcflags(cfg) local flags = config.mapFlags(cfg, msc.cflags) local runtime = iif(cfg.flags.StaticRuntime, "/MT", "/MD") if config.isDebugBuild(cfg) then runtime = runtime .. "d" end table.insert(flags, runtime) return flags end -- -- Returns list of C++ compiler flags for a configuration. -- msc.cxxflags = { } function msc.getcxxflags(cfg) return table.translate(cfg.flags, msc.cxxflags) end msc.ldflags = { Symbols = "/DEBUG", } -- -- Decorate defines for the MSVC command line. -- function msc.getdefines(defines) local result = {} for _, define in ipairs(defines) do table.insert(result, '-D' .. define) end return result end -- -- Returns a list of forced include files, decorated for the compiler -- command line. -- -- @param cfg -- The project configuration. -- @return -- An array of force include files with the appropriate flags. -- function msc.getforceincludes(cfg) local result = {} table.foreachi(cfg.forceincludes, function(value) local fn = project.getrelative(cfg.project, value) table.insert(result, "/FI" .. premake.quoted(fn)) end) return result end -- -- Decorate include file search paths for the MSVC command line. -- function msc.getincludedirs(cfg, dirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. premake.quoted(dir)) end return result end -- -- Return a list of linker flags for a specific configuration. -- msc.ldflags = { Symbols = "/DEBUG", } function msc.getldflags(cfg) local flags = table.translate(cfg.flags, msc.ldflags) if not cfg.flags.NoManifest and cfg.kind ~= premake.STATICLIB then table.insert(flags, "/MANIFEST") end if config.isOptimizedBuild(cfg) then table.insert(flags, "/OPT:REF /OPT:ICF") end for _, libdir in ipairs(project.getrelative(cfg.project, cfg.libdirs)) do table.insert(flags, '/LIBPATH:"' .. libdir .. '"') end return flags end -- -- Return the list of libraries to link, decorated with flags as needed. -- function msc.getlinks(cfg) local links = config.getlinks(cfg, "system", "fullpath") return links end -- -- Returns makefile-specific configuration rules. -- function msc.getmakesettings(cfg) return nil end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "cc" for the C compiler, "cxx" for -- the C++ compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- function msc.gettoolname(cfg, tool) return nil end
-- -- msc.lua -- Interface for the MS C/C++ compiler. -- Copyright (c) 2009-2013 Jason Perkins and the Premake project -- premake.tools.msc = {} local msc = premake.tools.msc local project = premake.project local config = premake.config -- -- Returns list of C preprocessor flags for a configuration. -- function msc.getcppflags(cfg) return {} end -- -- Returns list of C compiler flags for a configuration. -- msc.cflags = { flags = { SEH = "/EHa", Symbols = "/Z7", }, optimize = { Off = "/Od", Speed = "/O2", } } function msc.getcflags(cfg) local flags = config.mapFlags(cfg, msc.cflags) local runtime = iif(cfg.flags.StaticRuntime, "/MT", "/MD") if config.isDebugBuild(cfg) then runtime = runtime .. "d" end table.insert(flags, runtime) if not cfg.flags.SEH then table.insert(flags, "/EHsc") end return flags end -- -- Returns list of C++ compiler flags for a configuration. -- msc.cxxflags = { } function msc.getcxxflags(cfg) return table.translate(cfg.flags, msc.cxxflags) end msc.ldflags = { Symbols = "/DEBUG", } -- -- Decorate defines for the MSVC command line. -- function msc.getdefines(defines) local result = {} for _, define in ipairs(defines) do table.insert(result, '-D' .. define) end return result end -- -- Returns a list of forced include files, decorated for the compiler -- command line. -- -- @param cfg -- The project configuration. -- @return -- An array of force include files with the appropriate flags. -- function msc.getforceincludes(cfg) local result = {} table.foreachi(cfg.forceincludes, function(value) local fn = project.getrelative(cfg.project, value) table.insert(result, "/FI" .. premake.quoted(fn)) end) return result end -- -- Decorate include file search paths for the MSVC command line. -- function msc.getincludedirs(cfg, dirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. premake.quoted(dir)) end return result end -- -- Return a list of linker flags for a specific configuration. -- msc.ldflags = { Symbols = "/DEBUG", } function msc.getldflags(cfg) local flags = table.translate(cfg.flags, msc.ldflags) if not cfg.flags.NoManifest and cfg.kind ~= premake.STATICLIB then table.insert(flags, "/MANIFEST") end if config.isOptimizedBuild(cfg) then table.insert(flags, "/OPT:REF /OPT:ICF") end for _, libdir in ipairs(project.getrelative(cfg.project, cfg.libdirs)) do table.insert(flags, '/LIBPATH:"' .. libdir .. '"') end return flags end -- -- Return the list of libraries to link, decorated with flags as needed. -- function msc.getlinks(cfg) local links = config.getlinks(cfg, "system", "fullpath") return links end -- -- Returns makefile-specific configuration rules. -- function msc.getmakesettings(cfg) return nil end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "cc" for the C compiler, "cxx" for -- the C++ compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- function msc.gettoolname(cfg, tool) return nil end
Fix broken MSC exception handling flag
Fix broken MSC exception handling flag
Lua
bsd-3-clause
sleepingwit/premake-core,Tiger66639/premake-core,prapin/premake-core,soundsrc/premake-core,CodeAnxiety/premake-core,prapin/premake-core,tvandijck/premake-core,mendsley/premake-core,LORgames/premake-core,noresources/premake-core,noresources/premake-core,jsfdez/premake-core,sleepingwit/premake-core,mendsley/premake-core,jstewart-amd/premake-core,akaStiX/premake-core,soundsrc/premake-core,Yhgenomics/premake-core,starkos/premake-core,TurkeyMan/premake-core,xriss/premake-core,LORgames/premake-core,Blizzard/premake-core,mandersan/premake-core,TurkeyMan/premake-core,grbd/premake-core,felipeprov/premake-core,premake/premake-core,TurkeyMan/premake-core,lizh06/premake-core,martin-traverse/premake-core,dcourtois/premake-core,starkos/premake-core,TurkeyMan/premake-core,Meoo/premake-core,bravnsgaard/premake-core,jsfdez/premake-core,premake/premake-core,aleksijuvani/premake-core,lizh06/premake-core,resetnow/premake-core,resetnow/premake-core,mendsley/premake-core,akaStiX/premake-core,saberhawk/premake-core,premake/premake-core,Zefiros-Software/premake-core,Tiger66639/premake-core,starkos/premake-core,LORgames/premake-core,bravnsgaard/premake-core,resetnow/premake-core,Meoo/premake-core,Zefiros-Software/premake-core,saberhawk/premake-core,prapin/premake-core,Tiger66639/premake-core,Meoo/premake-core,jsfdez/premake-core,tvandijck/premake-core,saberhawk/premake-core,kankaristo/premake-core,dcourtois/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,martin-traverse/premake-core,jsfdez/premake-core,kankaristo/premake-core,lizh06/premake-core,premake/premake-core,Yhgenomics/premake-core,premake/premake-core,tritao/premake-core,mandersan/premake-core,Meoo/premake-core,PlexChat/premake-core,LORgames/premake-core,martin-traverse/premake-core,bravnsgaard/premake-core,soundsrc/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,sleepingwit/premake-core,mandersan/premake-core,resetnow/premake-core,noresources/premake-core,tritao/premake-core,aleksijuvani/premake-core,tritao/premake-core,mendsley/premake-core,martin-traverse/premake-core,CodeAnxiety/premake-core,starkos/premake-core,Blizzard/premake-core,TurkeyMan/premake-core,alarouche/premake-core,mandersan/premake-core,sleepingwit/premake-core,xriss/premake-core,premake/premake-core,jstewart-amd/premake-core,prapin/premake-core,jstewart-amd/premake-core,noresources/premake-core,felipeprov/premake-core,starkos/premake-core,grbd/premake-core,kankaristo/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,LORgames/premake-core,Yhgenomics/premake-core,saberhawk/premake-core,tvandijck/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,aleksijuvani/premake-core,resetnow/premake-core,noresources/premake-core,bravnsgaard/premake-core,CodeAnxiety/premake-core,soundsrc/premake-core,felipeprov/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,xriss/premake-core,alarouche/premake-core,dcourtois/premake-core,PlexChat/premake-core,sleepingwit/premake-core,dcourtois/premake-core,starkos/premake-core,Blizzard/premake-core,alarouche/premake-core,bravnsgaard/premake-core,Tiger66639/premake-core,noresources/premake-core,premake/premake-core,tvandijck/premake-core,grbd/premake-core,starkos/premake-core,dcourtois/premake-core,mendsley/premake-core,tvandijck/premake-core,PlexChat/premake-core,Blizzard/premake-core,alarouche/premake-core,xriss/premake-core,lizh06/premake-core,jstewart-amd/premake-core,noresources/premake-core,mandersan/premake-core,kankaristo/premake-core,tritao/premake-core,dcourtois/premake-core,akaStiX/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,felipeprov/premake-core,PlexChat/premake-core,grbd/premake-core,akaStiX/premake-core,xriss/premake-core
1570ee6835919e53d789e5b0d8519e3664818bf2
test/bench.lua
test/bench.lua
#!/usr/bin/env lua local basemem = collectgarbage("count") local document, duration do local parse = require "gumbo.parse" local have_socket, socket = pcall(require, "socket") local clock = have_socket and socket.gettime or os.clock local filename = assert(arg[1], "arg[1] is nil; expecting filename") local file = assert(io.open(filename)) local text = assert(file:read("*a")) file:close() io.stderr:write("Parsing ", filename, "...\n") local start_time = clock() document = parse(text) local stop_time = clock() assert(document) assert(document.documentElement.childNodes[2].localName == "body") duration = stop_time - start_time end collectgarbage() local memory = collectgarbage("count") - basemem local s = "Parse time: %.2fs\nLua memory usage: %dKB\n" io.write(string.format(s, duration, memory))
#!/usr/bin/env lua local basemem = collectgarbage("count") local document, duration do local parse = require "gumbo.parse" local have_socket, socket = pcall(require, "socket") local clock = have_socket and socket.gettime or os.clock local filename = assert(arg[1], "arg[1] is nil; expecting filename") local file = assert(io.open(filename)) local text = assert(file:read("*a")) file:close() io.stderr:write("Parsing ", filename, "...\n") local start_time = clock() document = parse(text) local stop_time = clock() assert(document and document.documentElement) duration = stop_time - start_time end collectgarbage() local memory = collectgarbage("count") - basemem local s = "Parse time: %.2fs\nLua memory usage: %dKB\n" io.write(string.format(s, duration, memory))
Fix assertion in test/bench.lua
Fix assertion in test/bench.lua
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
f1be0e8b1f59e2a378a4e82a43414c4fa7f62603
onmt/modules/BiEncoder.lua
onmt/modules/BiEncoder.lua
local function reverseInput(batch) batch.sourceInput, batch.sourceInputRev = batch.sourceInputRev, batch.sourceInput batch.sourceInputFeatures, batch.sourceInputRevFeatures = batch.sourceInputRevFeatures, batch.sourceInputFeatures batch.sourceInputPadLeft, batch.sourceInputRevPadLeft = batch.sourceInputRevPadLeft, batch.sourceInputPadLeft end --[[ BiEncoder is a bidirectional Sequencer used for the source language. `netFwd` h_1 => h_2 => h_3 => ... => h_n | | | | . . . . | | | | h_1 => h_2 => h_3 => ... => h_n | | | | | | | | x_1 x_2 x_3 x_n `netBwd` h_1 <= h_2 <= h_3 <= ... <= h_n | | | | . . . . | | | | h_1 <= h_2 <= h_3 <= ... <= h_n | | | | | | | | x_1 x_2 x_3 x_n Inherits from [onmt.Sequencer](onmt+modules+Sequencer). --]] local BiEncoder, parent = torch.class('onmt.BiEncoder', 'nn.Container') --[[ Create a bi-encoder. Parameters: * `input` - input neural network. * `rnn` - recurrent template module. * `merge` - fwd/bwd merge operation {"concat", "sum"} ]] function BiEncoder:__init(input, rnn, merge) parent.__init(self) self.fwd = onmt.Encoder.new(input, rnn) self.bwd = onmt.Encoder.new(input:clone('weight', 'bias', 'gradWeight', 'gradBias'), rnn:clone()) self.args = {} self.args.merge = merge self.args.rnnSize = rnn.outputSize self.args.numEffectiveLayers = rnn.numEffectiveLayers if self.args.merge == 'concat' then self.args.hiddenSize = self.args.rnnSize * 2 else self.args.hiddenSize = self.args.rnnSize end self:add(self.fwd) self:add(self.bwd) self:resetPreallocation() end --[[ Return a new BiEncoder using the serialized data `pretrained`. ]] function BiEncoder.load(pretrained) local self = torch.factory('onmt.BiEncoder')() parent.__init(self) self.fwd = onmt.Encoder.load(pretrained.modules[1]) self.bwd = onmt.Encoder.load(pretrained.modules[2]) self.args = pretrained.args self:add(self.fwd) self:add(self.bwd) self:resetPreallocation() return self end --[[ Return data to serialize. ]] function BiEncoder:serialize() return { modules = self.modules, args = self.args } end function BiEncoder:resetPreallocation() -- Prototype for preallocated full context vector. self.contextProto = torch.Tensor() -- Prototype for preallocated full hidden states tensors. self.stateProto = torch.Tensor() -- Prototype for preallocated gradient of the backward context self.gradContextBwdProto = torch.Tensor() end function BiEncoder:maskPadding() self.fwd:maskPadding() self.bwd:maskPadding() end function BiEncoder:forward(batch) if self.statesProto == nil then self.statesProto = onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers, self.stateProto, { batch.size, self.args.hiddenSize }) end local states = onmt.utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, self.args.hiddenSize }) local context = onmt.utils.Tensor.reuseTensor(self.contextProto, { batch.size, batch.sourceLength, self.args.hiddenSize }) local fwdStates, fwdContext = self.fwd:forward(batch) reverseInput(batch) local bwdStates, bwdContext = self.bwd:forward(batch) reverseInput(batch) if self.args.merge == 'concat' then for i = 1, #fwdStates do states[i]:narrow(2, 1, self.args.rnnSize):copy(fwdStates[i]) states[i]:narrow(2, self.args.rnnSize + 1, self.args.rnnSize):copy(bwdStates[i]) end for t = 1, batch.sourceLength do context[{{}, t}]:narrow(2, 1, self.args.rnnSize) :copy(fwdContext[{{}, t}]) context[{{}, t}]:narrow(2, self.args.rnnSize + 1, self.args.rnnSize) :copy(bwdContext[{{}, batch.sourceLength - t + 1}]) end elseif self.args.merge == 'sum' then for i = 1, #states do states[i]:copy(fwdStates[i]) states[i]:add(bwdStates[i]) end for t = 1, batch.sourceLength do context[{{}, t}]:copy(fwdContext[{{}, t}]) context[{{}, t}]:add(bwdContext[{{}, batch.sourceLength - t + 1}]) end end return states, context end function BiEncoder:backward(batch, gradStatesOutput, gradContextOutput) gradStatesOutput = gradStatesOutput or onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers, onmt.utils.Cuda.convert(torch.Tensor()), { batch.size, self.args.rnnSize*2 }) local gradContextOutputFwd local gradContextOutputBwd local gradStatesOutputFwd = {} local gradStatesOutputBwd = {} if self.args.merge == 'concat' then local gradContextOutputSplit = gradContextOutput:chunk(2, 3) gradContextOutputFwd = gradContextOutputSplit[1] gradContextOutputBwd = gradContextOutputSplit[2] for i = 1, #gradStatesOutput do local statesSplit = gradStatesOutput[i]:chunk(2, 2) table.insert(gradStatesOutputFwd, statesSplit[1]) table.insert(gradStatesOutputBwd, statesSplit[2]) end elseif self.args.merge == 'sum' then gradContextOutputFwd = gradContextOutput gradContextOutputBwd = gradContextOutput gradStatesOutputFwd = gradStatesOutput gradStatesOutputBwd = gradStatesOutput end local gradInputFwd = self.fwd:backward(batch, gradStatesOutputFwd, gradContextOutputFwd) -- reverse gradients of the backward context local gradContextBwd = onmt.utils.Tensor.reuseTensor(self.gradContextBwdProto, { batch.size, batch.sourceLength, self.args.rnnSize }) for t = 1, batch.sourceLength do gradContextBwd[{{}, t}]:copy(gradContextOutputBwd[{{}, batch.sourceLength - t + 1}]) end local gradInputBwd = self.bwd:backward(batch, gradStatesOutputBwd, gradContextBwd) -- gradInput for t = 1, batch.sourceLength do gradInputFwd[t]:add(gradInputBwd[batch.sourceLength-t+1]) end return gradInputFwd end
local function reverseInput(batch) batch.sourceInput, batch.sourceInputRev = batch.sourceInputRev, batch.sourceInput batch.sourceInputFeatures, batch.sourceInputRevFeatures = batch.sourceInputRevFeatures, batch.sourceInputFeatures batch.sourceInputPadLeft, batch.sourceInputRevPadLeft = batch.sourceInputRevPadLeft, batch.sourceInputPadLeft end --[[ BiEncoder is a bidirectional Sequencer used for the source language. `netFwd` h_1 => h_2 => h_3 => ... => h_n | | | | . . . . | | | | h_1 => h_2 => h_3 => ... => h_n | | | | | | | | x_1 x_2 x_3 x_n `netBwd` h_1 <= h_2 <= h_3 <= ... <= h_n | | | | . . . . | | | | h_1 <= h_2 <= h_3 <= ... <= h_n | | | | | | | | x_1 x_2 x_3 x_n Inherits from [onmt.Sequencer](onmt+modules+Sequencer). --]] local BiEncoder, parent = torch.class('onmt.BiEncoder', 'nn.Container') --[[ Create a bi-encoder. Parameters: * `input` - input neural network. * `rnn` - recurrent template module. * `merge` - fwd/bwd merge operation {"concat", "sum"} ]] function BiEncoder:__init(input, rnn, merge) parent.__init(self) self.fwd = onmt.Encoder.new(input, rnn) self.bwd = onmt.Encoder.new(input:clone('weight', 'bias', 'gradWeight', 'gradBias'), rnn:clone()) self.args = {} self.args.merge = merge self.args.rnnSize = rnn.outputSize self.args.numEffectiveLayers = rnn.numEffectiveLayers if self.args.merge == 'concat' then self.args.hiddenSize = self.args.rnnSize * 2 else self.args.hiddenSize = self.args.rnnSize end self:add(self.fwd) self:add(self.bwd) self:resetPreallocation() end --[[ Return a new BiEncoder using the serialized data `pretrained`. ]] function BiEncoder.load(pretrained) local self = torch.factory('onmt.BiEncoder')() parent.__init(self) self.fwd = onmt.Encoder.load(pretrained.modules[1]) self.bwd = onmt.Encoder.load(pretrained.modules[2]) self.args = pretrained.args self:add(self.fwd) self:add(self.bwd) self:resetPreallocation() return self end --[[ Return data to serialize. ]] function BiEncoder:serialize() return { modules = self.modules, args = self.args } end function BiEncoder:resetPreallocation() -- Prototype for preallocated full context vector. self.contextProto = torch.Tensor() -- Prototype for preallocated full hidden states tensors. self.stateProto = torch.Tensor() -- Prototype for preallocated gradient of the backward context self.gradContextBwdProto = torch.Tensor() end function BiEncoder:maskPadding() self.fwd:maskPadding() self.bwd:maskPadding() end function BiEncoder:forward(batch) if self.statesProto == nil then self.statesProto = onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers, self.stateProto, { batch.size, self.args.hiddenSize }) end local states = onmt.utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, self.args.hiddenSize }) local context = onmt.utils.Tensor.reuseTensor(self.contextProto, { batch.size, batch.sourceLength, self.args.hiddenSize }) local fwdStates, fwdContext = self.fwd:forward(batch) reverseInput(batch) local bwdStates, bwdContext = self.bwd:forward(batch) reverseInput(batch) if self.args.merge == 'concat' then for i = 1, #fwdStates do states[i]:narrow(2, 1, self.args.rnnSize):copy(fwdStates[i]) states[i]:narrow(2, self.args.rnnSize + 1, self.args.rnnSize):copy(bwdStates[i]) end for t = 1, batch.sourceLength do context[{{}, t}]:narrow(2, 1, self.args.rnnSize) :copy(fwdContext[{{}, t}]) context[{{}, t}]:narrow(2, self.args.rnnSize + 1, self.args.rnnSize) :copy(bwdContext[{{}, batch.sourceLength - t + 1}]) end elseif self.args.merge == 'sum' then for i = 1, #states do states[i]:copy(fwdStates[i]) states[i]:add(bwdStates[i]) end for t = 1, batch.sourceLength do context[{{}, t}]:copy(fwdContext[{{}, t}]) context[{{}, t}]:add(bwdContext[{{}, batch.sourceLength - t + 1}]) end end return states, context end function BiEncoder:backward(batch, gradStatesOutput, gradContextOutput) gradStatesOutput = gradStatesOutput or onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers, onmt.utils.Cuda.convert(torch.Tensor()), { batch.size, self.args.rnnSize*2 }) local gradContextOutputFwd local gradContextOutputBwd local gradStatesOutputFwd = {} local gradStatesOutputBwd = {} if self.args.merge == 'concat' then local gradContextOutputSplit = gradContextOutput:chunk(2, 3) gradContextOutputFwd = gradContextOutputSplit[1] gradContextOutputBwd = gradContextOutputSplit[2] for i = 1, #gradStatesOutput do local statesSplit = gradStatesOutput[i]:chunk(2, 2) table.insert(gradStatesOutputFwd, statesSplit[1]) table.insert(gradStatesOutputBwd, statesSplit[2]) end elseif self.args.merge == 'sum' then gradContextOutputFwd = gradContextOutput gradContextOutputBwd = gradContextOutput gradStatesOutputFwd = gradStatesOutput gradStatesOutputBwd = gradStatesOutput end local gradInputFwd = self.fwd:backward(batch, gradStatesOutputFwd, gradContextOutputFwd) -- reverse gradients of the backward context local gradContextBwd = onmt.utils.Tensor.reuseTensor(self.gradContextBwdProto, { batch.size, batch.sourceLength, self.args.rnnSize }) for t = 1, batch.sourceLength do gradContextBwd[{{}, t}]:copy(gradContextOutputBwd[{{}, batch.sourceLength - t + 1}]) end local gradInputBwd = self.bwd:backward(batch, gradStatesOutputBwd, gradContextBwd) for t = 1, batch.sourceLength do local revIndex = batch.sourceLength - t + 1 if torch.isTensor(gradInputFwd[t]) then gradInputFwd[t]:add(gradInputBwd[revIndex]) else for i = 1, #gradInputFwd[t] do gradInputFwd[t][i]:add(gradInputBwd[revIndex][i]) end end end return gradInputFwd end
fix brnn gradInput with additional features
fix brnn gradInput with additional features
Lua
mit
jsenellart/OpenNMT,cservan/OpenNMT_scores_0.2.0,jungikim/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,srush/OpenNMT
fe9c48334b2d75cb0faf85ba121806fe9f0ce774
lib/lua/lunarender/reader.lua
lib/lua/lunarender/reader.lua
-- part of LunaRender -- (c) 2015 Mikoláš Štrajt -- MIT licensed local lxp = require 'lxp' local dkjson = require 'dkjson' local push = table.insert local _M = {} -- reads OSM XML using luaExpat -- -- output is one big self-referencing table -- function _M.read_osm(fname) local current, data, p data = { nodes = {}, ways = {} } local function StartElement(p, el, attr) if el == 'bounds' then data.minlon = attr.minlon data.maxlon = attr.maxlon data.minlat = attr.minlat data.maxlat = attr.maxlat elseif el == 'node' then if attr.visible then current = { lat=tonumber(attr.lat), lon=tonumber(attr.lon), tags={}} data.nodes[ tonumber(attr.id) ] = current end elseif el == 'way' then if attr.visible then current = { tags={}, closed=false } data.ways[ tonumber(attr.id) ] = current end elseif el =='tag' then if current and current.tags then current.tags[attr.k] = attr.v end elseif el == 'nd' then if current then push(current, data.nodes[ tonumber(attr.ref) ] or die('Missing node id='..attr.ref) ) end end end local function EndElement(p, el) if el=='way' and current[1]==current[#current] then current.closed = true end if el=='node' or el=='way' then current = nil end end p = lxp.new{ StartElement=StartElement, EndElement=EndElement } for l in io.lines(fname) do -- iterate lines p:parse(l) -- parses the line p:parse("\n") -- parses the end of line end p:parse() -- finishes the document p:close() -- closes the parser return data end -- reads overpass api json output function _M.read_overpass_json(fname) local fh, content, json local data = {nodes = {}, ways={} } fh = io.open(fname, 'r') or die('File '..fname..' cannot be read.') content = fh:read('*a') fh:close() json = dkjson.decode(content) if not json then die 'Invalid input file.' end if not json.bounds then die 'Missing bounds in Overpass file.' end data.minlon = json.bounds.minlon data.maxlon = json.bounds.maxlon data.minlat = json.bounds.minlat data.maxlat = json.bounds.maxlat for _, node in pairs(json.elements) do if node.type=='node' then -- AAAAAAARRRRRGH! seems nodes can be output more times on certain queries if not data.nodes[node.id] then data.nodes[node.id] = { lat=node.lat, lon=node.lon, tags = node.tags or {} } end end end for _, way in pairs(json.elements) do local nodes = {} if way.type=='way' then for _, id in ipairs(way.nodes or {}) do push(nodes, data.nodes[id] or die('Node id'..id..' missing in Overpass file.')) end nodes.tags = way.tags or {} data.ways[way.id] = nodes end end return data end return _M
-- part of LunaRender -- (c) 2015 Mikoláš Štrajt -- MIT licensed local lxp = require 'lxp' local dkjson = require 'dkjson' local push = table.insert local _M = {} -- reads OSM XML using luaExpat -- -- output is one big self-referencing table -- function _M.read_osm(fname) local current, data, p data = { nodes = {}, ways = {} } local function StartElement(p, el, attr) if el == 'bounds' then data.minlon = attr.minlon data.maxlon = attr.maxlon data.minlat = attr.minlat data.maxlat = attr.maxlat elseif el == 'node' then if attr.visible then current = { lat=tonumber(attr.lat), lon=tonumber(attr.lon), tags={}} data.nodes[ tonumber(attr.id) ] = current end elseif el == 'way' then if attr.visible then current = { tags={}, closed=false } data.ways[ tonumber(attr.id) ] = current end elseif el =='tag' then if current and current.tags then current.tags[attr.k] = attr.v end elseif el == 'nd' then if current then push(current, data.nodes[ tonumber(attr.ref) ] or die('Missing node id='..attr.ref) ) end end end local function EndElement(p, el) if el=='way' and current[1]==current[#current] then current.closed = true end if el=='node' or el=='way' then current = nil end end p = lxp.new{ StartElement=StartElement, EndElement=EndElement } for l in io.lines(fname) do -- iterate lines p:parse(l) -- parses the line p:parse("\n") -- parses the end of line end p:parse() -- finishes the document p:close() -- closes the parser return data end -- reads overpass api json output function _M.read_overpass_json(fname) local fh, content, json local data = {nodes = {}, ways={} } fh = io.open(fname, 'r') or die('File '..fname..' cannot be read.') content = fh:read('*a') fh:close() json = dkjson.decode(content) if not json then die 'Invalid input file.' end if not json.bounds then die 'Missing bounds in Overpass file.' end data.minlon = json.bounds.minlon data.maxlon = json.bounds.maxlon data.minlat = json.bounds.minlat data.maxlat = json.bounds.maxlat for _, node in ipairs(json.elements) do if node.type=='node' then -- AAAAAAARRRRRGH! seems nodes can be output more times on certain queries if not data.nodes[node.id] then data.nodes[node.id] = { lat=node.lat, lon=node.lon, tags = node.tags or {} } end end end for _, way in pairs(json.elements) do local nodes = {} if way.type=='way' then for _, id in ipairs(way.nodes or {}) do push(nodes, data.nodes[id] or die('Node id'..id..' missing in Overpass file.')) end nodes.closed = false if #way.nodes>1 and way.nodes[1]==way.nodes[#way.nodes] then nodes.closed = true end nodes.tags = way.tags or {} data.ways[way.id] = nodes end end return data end return _M
fixes in reading overpass json
fixes in reading overpass json
Lua
mit
severak/lunarender,severak/lunarender,severak/lunarender
7e43179f3fc0299ebdbfb349452460925db4b566
lua/starfall/preprocessor.lua
lua/starfall/preprocessor.lua
------------------------------------------------------------------------------- -- SF Preprocessor. -- Processes code for compile time directives. -- @author Colonel Thirty Two ------------------------------------------------------------------------------- -- TODO: Make an @include-only parser SF.Preprocessor = {} SF.Preprocessor.directives = {} --- Sets a global preprocessor directive. -- @param directive The directive to set. -- @param func The callback. Takes the directive arguments, the file name, and instance.data function SF.Preprocessor.SetGlobalDirective(directive, func) SF.Preprocessor.directives[directive] = func end local function FindComments( line ) local ret, count, pos, found = {}, 0, 1 repeat found = line:find( '["%-%[%]]', pos ) if (found) then -- We found something local oldpos = pos local char = line:sub(found,found) if char == "-" then if line:sub(found,found+1) == "--" then -- Comment beginning if line:sub(found,found+3) == "--[[" then -- Block Comment beginning count = count + 1 ret[count] = {type = "start", pos = found} pos = found + 4 else -- Line comment beginning count = count + 1 ret[count] = {type = "line", pos = found} pos = found + 2 end else pos = found + 1 end elseif char == "[" then local level = line:sub(found+1):match("^(=*)") if level then level = string.len(level) else level = 0 end if line:sub(found+level+1, found+level+1) == "[" then -- Block string start count = count + 1 ret[count] = {type = "stringblock", pos = found, level = level} pos = found + level + 2 else pos = found + 1 end elseif char == "]" then local level = line:sub(found+1):match("^(=*)") if level then level = string.len(level) else level = 0 end if line:sub(found+level+1,found+level+1) == "]" then -- Ending count = count + 1 ret[count] = {type = "end", pos = found, level = level} pos = found + level + 2 else pos = found + 1 end elseif char == "\"" then if line:sub(found-1,found-1) == "\\" and line:sub(found-2,found-1) ~= "\\\\" then -- Escaped character pos = found+1 else -- String count = count + 1 ret[count] = {type = "string", pos = found} pos = found + 1 end end if oldpos == pos then error("Regex found something, but nothing handled it") end end until not found return ret, count end --- Parses a source file for directives. -- @param filename The file name of the source code -- @param source The source code to parse. -- @param directives A table of additional directives to use. -- @param data The data table passed to the directives. function SF.Preprocessor.ParseDirectives(filename, source, directives, data) local ending = nil local endingLevel = nil local str = source while str ~= "" do local line line, str = string.match(str,"^([^\n]*)\n?(.*)$") for _,comment in ipairs(FindComments(line)) do if ending then if comment.type ~= ending then continue end if endingLevel then if comment.level and comment.level == endingLevel then ending = nil endingLevel = nil end else ending = nil end elseif comment.type == "start" then ending = "end" elseif comment.type == "string" then ending = "string" elseif comment.type == "stringblock" then ending = "end" endingLevel = comment.level elseif comment.type == "line" then local directive, args = string.match(line,"--@([^ ]+)%s*(.*)$") local func = directives[directive] or SF.Preprocessor.directives[directive] if func then func(args, filename, data) end end end if ending == "newline" then ending = nil end end end local function directive_include(args, filename, data) if not data.includes then data.includes = {} end if not data.includes[filename] then data.includes[filename] = {} end local incl = data.includes[filename] incl[#incl+1] = args end SF.Preprocessor.SetGlobalDirective("include",directive_include) local function directive_name(args, filename, data) if not data.scriptnames then data.scriptnames = {} end data.scriptnames[filename] = args end SF.Preprocessor.SetGlobalDirective("name",directive_name)
------------------------------------------------------------------------------- -- SF Preprocessor. -- Processes code for compile time directives. -- @author Colonel Thirty Two ------------------------------------------------------------------------------- -- TODO: Make an @include-only parser SF.Preprocessor = {} SF.Preprocessor.directives = {} --- Sets a global preprocessor directive. -- @param directive The directive to set. -- @param func The callback. Takes the directive arguments, the file name, and instance.data function SF.Preprocessor.SetGlobalDirective(directive, func) SF.Preprocessor.directives[directive] = func end local function FindComments( line ) local ret, count, pos, found = {}, 0, 1 repeat found = line:find( '["%-%[%]]', pos ) if (found) then -- We found something local oldpos = pos local char = line:sub(found,found) if char == "-" then if line:sub(found,found+1) == "--" then -- Comment beginning if line:sub(found,found+3) == "--[[" then -- Block Comment beginning count = count + 1 ret[count] = {type = "start", pos = found} pos = found + 4 else -- Line comment beginning count = count + 1 ret[count] = {type = "line", pos = found} pos = found + 2 end else pos = found + 1 end elseif char == "[" then local level = line:sub(found+1):match("^(=*)") if level then level = string.len(level) else level = 0 end if line:sub(found+level+1, found+level+1) == "[" then -- Block string start count = count + 1 ret[count] = {type = "stringblock", pos = found, level = level} pos = found + level + 2 else pos = found + 1 end elseif char == "]" then local level = line:sub(found+1):match("^(=*)") if level then level = string.len(level) else level = 0 end if line:sub(found+level+1,found+level+1) == "]" then -- Ending count = count + 1 ret[count] = {type = "end", pos = found, level = level} pos = found + level + 2 else pos = found + 1 end elseif char == "\"" then if line:sub(found-1,found-1) == "\\" and line:sub(found-2,found-1) ~= "\\\\" then -- Escaped character pos = found+1 else -- String count = count + 1 ret[count] = {type = "string", pos = found} pos = found + 1 end end if oldpos == pos then error("Regex found something, but nothing handled it") end end until not found return ret, count end --- Parses a source file for directives. -- @param filename The file name of the source code -- @param source The source code to parse. -- @param directives A table of additional directives to use. -- @param data The data table passed to the directives. function SF.Preprocessor.ParseDirectives(filename, source, directives, data) local ending = nil local endingLevel = nil local str = source while str ~= "" do local line line, str = string.match(str,"^([^\n]*)\n?(.*)$") for _,comment in ipairs(FindComments(line)) do if ending then if comment.type == ending then if endingLevel then if comment.level and comment.level == endingLevel then ending = nil endingLevel = nil end else ending = nil end end elseif comment.type == "start" then ending = "end" elseif comment.type == "string" then ending = "string" elseif comment.type == "stringblock" then ending = "end" endingLevel = comment.level elseif comment.type == "line" then local directive, args = string.match(line,"--@([^ ]+)%s*(.*)$") local func = directives[directive] or SF.Preprocessor.directives[directive] if func then func(args, filename, data) end end end if ending == "newline" then ending = nil end end end local function directive_include(args, filename, data) if not data.includes then data.includes = {} end if not data.includes[filename] then data.includes[filename] = {} end local incl = data.includes[filename] incl[#incl+1] = args end SF.Preprocessor.SetGlobalDirective("include",directive_include) local function directive_name(args, filename, data) if not data.scriptnames then data.scriptnames = {} end data.scriptnames[filename] = args end SF.Preprocessor.SetGlobalDirective("name",directive_name)
Fixed GM13 related stuff (continue)
Fixed GM13 related stuff (continue)
Lua
bsd-3-clause
Jazzelhawk/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall
2e6546059f5a9509b7af70bb01c817490680cb82
CastBarZ/CastBarZ.lua
CastBarZ/CastBarZ.lua
local AddonName, Addon = ... local AceDB = LibStub("AceDB-3.0") local AceConfigRegistry = LibStub("AceConfigRegistry-3.0") _G[AddonName] = LibStub("AceAddon-3.0"):NewAddon(Addon, AddonName, "AceConsole-3.0") local Addon = Addon local OptionTable = { name = AddonName .. " Options", type = "group", childGroups = "tab", handler = Addon, args = { player = { name = "General", type = "group", desc = "Enable/Disable", args = { width = { name = "Width", type = "range", min = 1, softMax = 500, step = 1, order = 1, set = "SetWidth", get = "GetWidth", width = 1.5 }, height = { name = "Height", type = "range", min = 0, softMax = 50, step = 1, order = 2, set = "SetHeight", get = "GetHeight", width = 1.5 }, xoffset = { name = "X offset", type = "range", softMin = -2000, softMax = 2000, step = 1, order = 3, set = "SetXOffset", get = "GetXOffset", width = 1.5 }, yoffset = { name = "Y offet", type = "range", softMin = -2000, softMax = 2000, step = 1, order = 4, set = "SetYOffset", get = "GetYOffset", width = 1.5 } } } } } local defaults = { profile = { player = { show_name = true, show_timer = true, show_latency = true, status_bar_texture = "", status_bar_color = {r = 0, g = 0.4, b = 0.8, a = 1}, background_color = {r = 0, g = 0, b = 0, a = 1}, width = 220, height = 24, xoffset = 0, yoffset = 190 } } } function Addon:OnInitialize() _G.CastingBarFrame:UnregisterAllEvents() self.db = AceDB:New(AddonName .. "DB", defaults) AceConfigRegistry:RegisterOptionsTable(AddonName, OptionTable) self:RegisterChatCommand("castbarz", "ChatCommand") self:RegisterChatCommand("cbz", "ChatCommand") self.testMode = false end function Addon:OnEnable() self.player = self:CreateCastingBar3D("player") end function Addon:ChatCommand(input) if LoadAddOn(AddonName .. "_Config") then self:OpenConfigDialog() else LibStub("AceConfigCmd-3.0").HandleCommand(Addon, "castbarz", AddonName, input) end end -- Callbacks only support player castbar right now function Addon:SetWidth(info, value) self.db.profile.player.width = value self.player:SetWidth(value) end function Addon:SetHeight(info, value) self.db.profile.player.height = value self.player:SetHeight(value) end function Addon:SetXOffset(info, value) self.db.profile.player.xoffset = value local point, relativeTo, relativePoint, _, yOfs = self.player:GetPoint() self.player:SetPoint(point, relativeTo, relativePoint, value, yOfs) end function Addon:SetYOffset(info, value) self.db.profile.player.yoffset = value local point, relativeTo, relativePoint, xOfs = self.player:GetPoint() self.player:SetPoint(point, relativeTo, relativePoint, xOfs, value) end function Addon:GetWidth(info) return self.db.profile.player.width end function Addon:GetHeight(info) return self.db.profile.player.height end function Addon:GetXOffset(info) return self.db.profile.player.xoffset end function Addon:GetYOffset(info) return self.db.profile.player.yoffset end
local AddonName, Addon = ... local AceDB = LibStub("AceDB-3.0") local AceConfigRegistry = LibStub("AceConfigRegistry-3.0") _G[AddonName] = LibStub("AceAddon-3.0"):NewAddon(Addon, AddonName, "AceConsole-3.0") local Addon = Addon local OptionTable = { name = AddonName .. " Options", type = "group", childGroups = "tab", handler = Addon, args = { player = { name = "General", type = "group", desc = "Enable/Disable", args = { width = { name = "Width", type = "range", min = 1, softMax = 500, step = 1, order = 1, set = "SetWidth", get = "GetWidth", width = 1.5 }, height = { name = "Height", type = "range", min = 0, softMax = 50, step = 1, order = 2, set = "SetHeight", get = "GetHeight", width = 1.5 }, xoffset = { name = "X offset", type = "range", softMin = -2000, softMax = 2000, step = 1, order = 3, set = "SetXOffset", get = "GetXOffset", width = 1.5 }, yoffset = { name = "Y offet", type = "range", softMin = -2000, softMax = 2000, step = 1, order = 4, set = "SetYOffset", get = "GetYOffset", width = 1.5 } } } } } local defaults = { profile = { player = { show_name = true, show_timer = true, show_latency = true, status_bar_texture = "", status_bar_color = {r = 0, g = 0.4, b = 0.8, a = 1}, background_color = {r = 0, g = 0, b = 0, a = 1}, width = 220, height = 24, xoffset = 0, yoffset = 190 } } } function Addon:OnInitialize() _G.CastingBarFrame:UnregisterAllEvents() self.db = AceDB:New(AddonName .. "DB", defaults) AceConfigRegistry:RegisterOptionsTable(AddonName, OptionTable) self:RegisterChatCommand("castbarz", "ChatCommand") self:RegisterChatCommand("cbz", "ChatCommand") self.testMode = false end function Addon:OnEnable() self.player = self:CreateCastingBar3D("player") LoadAddOn(AddonName .. "_Config") end function Addon:ChatCommand(input) if LoadAddOn(AddonName .. "_Config") then self:OpenConfigDialog() else LibStub("AceConfigCmd-3.0").HandleCommand(Addon, "castbarz", AddonName, input) end end -- Callbacks only support player castbar right now function Addon:SetWidth(info, value) self.db.profile.player.width = value self.player:SetWidth(value) end function Addon:SetHeight(info, value) self.db.profile.player.height = value self.player:SetHeight(value) end function Addon:SetXOffset(info, value) self.db.profile.player.xoffset = value local point, relativeTo, relativePoint, _, yOfs = self.player:GetPoint() self.player:SetPoint(point, relativeTo, relativePoint, value, yOfs) end function Addon:SetYOffset(info, value) self.db.profile.player.yoffset = value local point, relativeTo, relativePoint, xOfs = self.player:GetPoint() self.player:SetPoint(point, relativeTo, relativePoint, xOfs, value) end function Addon:GetWidth(info) return self.db.profile.player.width end function Addon:GetHeight(info) return self.db.profile.player.height end function Addon:GetXOffset(info) return self.db.profile.player.xoffset end function Addon:GetYOffset(info) return self.db.profile.player.yoffset end
Fix loading config addon
Fix loading config addon
Lua
unlicense
Guema/gCastBars,Guema/GuemUICastBars
058c34e82ae9037a6dd4e09595dd1f736964b412
focuspoints.lrdevplugin/ExifUtils.lua
focuspoints.lrdevplugin/ExifUtils.lua
--[[ Copyright 2016 Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local LrTasks = import 'LrTasks' local LrFileUtils = import 'LrFileUtils' local LrPathUtils = import 'LrPathUtils' local LrStringUtils = import "LrStringUtils" local LrSystemInfo = import "LrSystemInfo" local LrUUID = import "LrUUID" ExifUtils = {} exiftool = LrPathUtils.child( _PLUGIN.path, "bin" ) exiftool = LrPathUtils.child(exiftool, "exiftool") exiftool = LrPathUtils.child(exiftool, "exiftool") exiftoolWindows = LrPathUtils.child( _PLUGIN.path, "bin" ) exiftoolWindows = LrPathUtils.child(exiftoolWindows, "exiftool.exe") function ExifUtils.getExifCmd(targetPhoto) local path = targetPhoto:getRawMetadata("path") local metaDataFile = LrPathUtils.child(LrPathUtils.getStandardFilePath("temp"), LrUUID.generateUUID() .. ".txt") local cmd = "'"..exiftool .. "' -a -u -sort '" .. path .. "' > '" .. metaDataFile .. "'"; if (WIN_ENV) then -- windows needs " around the entire command and then " around each path -- example: ""C:\Users\Joshua\Desktop\Focus Points\focuspoints.lrdevplugin\bin\exiftool.exe" -a -u -sort "C:\Users\Joshua\Desktop\DSC_4636.NEF" > "C:\Users\Joshua\Desktop\DSC_4636-metadata.txt"" cmd = '""' .. exiftoolWindows .. '" -a -u -sort ' .. '"'.. path .. '" > "' .. metaDataFile .. '""'; end return cmd, metaDataFile end function ExifUtils.readMetaData(targetPhoto) local cmd, metaDataFile = ExifUtils.getExifCmd(targetPhoto) LrTasks.execute(cmd) local fileInfo = LrFileUtils.readFile(metaDataFile) LrFileUtils.delete(metaDataFile) return fileInfo end --[[ -- Transforms the output of ExifUtils.readMetaData and returns a key/value lua Table -- targetPhoto - LrPhoto to extract the Exif from --]] function ExifUtils.readMetaDataAsTable(targetPhoto) local metaData = ExifUtils.readMetaData(targetPhoto) if metaData == nil then return nil end local parsedTable = {} for keyword, value in string.gmatch(metaData, "([^\:]+)\:([^\r\n]*)\r?\n") do keyword = LrStringUtils.trimWhitespace(keyword) value = LrStringUtils.trimWhitespace(value) parsedTable[keyword] = value logDebug("ExifUtils", "Parsed '" .. keyword .. "' = '" .. value .. "'") end return parsedTable end --[[ -- Returns the first value of "keys" that could be found within the metaDataTable table -- Ignores nil and "(none)" as valid values -- metaDataTable - the medaData key/value table -- keys - the keys to be search for in order of importance -- return 1. value of the first key match, 2. which key was used --]] function ExifUtils.findFirstMatchingValue(metaDataTable, keys) local exifValue = nil for key, value in pairs(keys) do -- value in the keys table is the current exif keyword to be searched exifValue = metaDataTable[value] if exifValue ~= nil and exifValue ~= "(none)" then logInfo("ExifUtils", "Searching for " .. value .. " -> " .. exifValue) return exifValue, key end end logInfo("ExifUtils", "Searching for { " .. table.concat(keys, " ") .. " } returned nothing") return nil end function ExifUtils.filterInput(str) local result = string.gsub(str, "[^a-zA-Z0-9 ,\\./;'\\<>\\?:\\\"\\{\\}\\|!@#\\$%\\^\\&\\*\\(\\)_\\+\\=-\\[\\]~`]", "?"); -- FIXME: doesn't strip - or ] correctly --local result = string.gsub(str, "[^a-zA-Z0-9 ,\\./;'\\<>\\?:\\\"\\{\\}\\|!@#\\$%\\^\\&\\*\\(\\)_\\+\\=\\-\\[\\\n\\\t~`-]", "?"); return result end
--[[ Copyright 2016 Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local LrTasks = import 'LrTasks' local LrFileUtils = import 'LrFileUtils' local LrPathUtils = import 'LrPathUtils' local LrStringUtils = import "LrStringUtils" local LrSystemInfo = import "LrSystemInfo" local LrUUID = import "LrUUID" ExifUtils = {} exiftool = LrPathUtils.child( _PLUGIN.path, "bin" ) exiftool = LrPathUtils.child(exiftool, "exiftool") exiftool = LrPathUtils.child(exiftool, "exiftool") exiftoolWindows = LrPathUtils.child( _PLUGIN.path, "bin" ) exiftoolWindows = LrPathUtils.child(exiftoolWindows, "exiftool.exe") function ExifUtils.getExifCmd(targetPhoto) local path = targetPhoto:getRawMetadata("path") local metaDataFile = LrPathUtils.child(LrPathUtils.getStandardFilePath("temp"), LrUUID.generateUUID() .. ".txt") local cmd if (WIN_ENV) then -- windows needs " around the entire command and then " around each path -- example: ""C:\Users\Joshua\Desktop\Focus Points\focuspoints.lrdevplugin\bin\exiftool.exe" -a -u -sort "C:\Users\Joshua\Desktop\DSC_4636.NEF" > "C:\Users\Joshua\Desktop\DSC_4636-metadata.txt"" cmd = '""' .. exiftoolWindows .. '" -a -u -sort ' .. '"'.. path .. '" > "' .. metaDataFile .. '""'; else cmd = "'"..exiftool .. "' -a -u -sort '" .. string.gsub(path, "'", '\'"\'"\'') .. "' > '" .. metaDataFile .. "'"; end -- logDebug("ExifUtils", "Command: " .. cmd) return cmd, metaDataFile end function ExifUtils.readMetaData(targetPhoto) local cmd, metaDataFile = ExifUtils.getExifCmd(targetPhoto) LrTasks.execute(cmd) local fileInfo = LrFileUtils.readFile(metaDataFile) LrFileUtils.delete(metaDataFile) return fileInfo end --[[ -- Transforms the output of ExifUtils.readMetaData and returns a key/value lua Table -- targetPhoto - LrPhoto to extract the Exif from --]] function ExifUtils.readMetaDataAsTable(targetPhoto) local metaData = ExifUtils.readMetaData(targetPhoto) if metaData == nil then return nil end local parsedTable = {} for keyword, value in string.gmatch(metaData, "([^\:]+)\:([^\r\n]*)\r?\n") do keyword = LrStringUtils.trimWhitespace(keyword) value = LrStringUtils.trimWhitespace(value) parsedTable[keyword] = value logDebug("ExifUtils", "Parsed '" .. keyword .. "' = '" .. value .. "'") end return parsedTable end --[[ -- Returns the first value of "keys" that could be found within the metaDataTable table -- Ignores nil and "(none)" as valid values -- metaDataTable - the medaData key/value table -- keys - the keys to be search for in order of importance -- return 1. value of the first key match, 2. which key was used --]] function ExifUtils.findFirstMatchingValue(metaDataTable, keys) local exifValue = nil for key, value in pairs(keys) do -- value in the keys table is the current exif keyword to be searched exifValue = metaDataTable[value] if exifValue ~= nil and exifValue ~= "(none)" then logInfo("ExifUtils", "Searching for " .. value .. " -> " .. exifValue) return exifValue, key end end logInfo("ExifUtils", "Searching for { " .. table.concat(keys, " ") .. " } returned nothing") return nil end function ExifUtils.filterInput(str) local result = string.gsub(str, "[^a-zA-Z0-9 ,\\./;'\\<>\\?:\\\"\\{\\}\\|!@#\\$%\\^\\&\\*\\(\\)_\\+\\=-\\[\\]~`]", "?"); -- FIXME: doesn't strip - or ] correctly --local result = string.gsub(str, "[^a-zA-Z0-9 ,\\./;'\\<>\\?:\\\"\\{\\}\\|!@#\\$%\\^\\&\\*\\(\\)_\\+\\=\\-\\[\\\n\\\t~`-]", "?"); return result end
Fix call to exiftool on OS/X if image path contains single quotes.
Fix call to exiftool on OS/X if image path contains single quotes.
Lua
apache-2.0
project802/Focus-Points,project802/Focus-Points,musselwhizzle/Focus-Points,rderimay/Focus-Points,musselwhizzle/Focus-Points,mkjanke/Focus-Points,rderimay/Focus-Points,mkjanke/Focus-Points,project802/Focus-Points,philmoz/Focus-Points,project802/Focus-Points,philmoz/Focus-Points
c6f993428ec97de5dd8fa6006e70d88dfe29536b
lualib/sharemap.lua
lualib/sharemap.lua
local stm = require "stm" local sprotoloader = require "sprotoloader" local sproto = require "sproto" local setmetatable = setmetatable local sharemap = {} function sharemap.register(protofile) -- use global slot 0 for type define sprotoloader.register(protofile, 0) end local sprotoobj local function loadsp() if sprotoobj == nil then sprotoobj = sprotoloader.load(0) end return sprotoobj end function sharemap:commit() self.__obj(sprotoobj:encode(self.__typename, self.__data)) end function sharemap:copy() return stm.copy(self.__obj) end function sharemap.writer(typename, obj) local sp = loadsp() obj = obj or {} local stmobj = stm.new(sp:encode(typename,obj)) obj.__typename = typename obj.__obj = stmobj obj.__data = obj obj.commit = sharemap.commit obj.copy = sharemap.copy return setmetatable(obj, { __index = obj.__data, __newindex = obj.__data }) end local function decode(msg, sz, self) local data = self.__data for k in pairs(data) do data[k] = nil end return sprotoobj:decode(self.__typename, msg, sz, data) end function sharemap:update() return self.__obj(decode, self) end function sharemap.reader(typename, stmcpy) local sp = loadsp() local stmobj = stm.newcopy(stmcpy) local _, data = stmobj(function(msg, sz) return sp:decode(typename, msg, sz) end) local obj = { __typename = typename, __obj = stmobj, __data = data, update = sharemap.update, } return setmetatable(obj, { __index = obj.__data, __newindex = error }) end return sharemap
local stm = require "stm" local sprotoloader = require "sprotoloader" local sproto = require "sproto" local setmetatable = setmetatable local sharemap = {} function sharemap.register(protofile) -- use global slot 0 for type define sprotoloader.register(protofile, 0) end local sprotoobj local function loadsp() if sprotoobj == nil then sprotoobj = sprotoloader.load(0) end return sprotoobj end function sharemap:commit() self.__obj(sprotoobj:encode(self.__typename, self.__data)) end function sharemap:copy() return stm.copy(self.__obj) end function sharemap.writer(typename, obj) local sp = loadsp() obj = obj or {} local stmobj = stm.new(sp:encode(typename,obj)) local ret = { __typename = typename, __obj = stmobj, __data = obj, commit = sharemap.commit, copy = sharemap.copy, } return setmetatable(ret, { __index = obj, __newindex = obj }) end local function decode(msg, sz, self) local data = self.__data for k in pairs(data) do data[k] = nil end return sprotoobj:decode(self.__typename, msg, sz, data) end function sharemap:update() return self.__obj(decode, self) end function sharemap.reader(typename, stmcpy) local sp = loadsp() local stmobj = stm.newcopy(stmcpy) local _, data = stmobj(function(msg, sz) return sp:decode(typename, msg, sz) end) local obj = { __typename = typename, __obj = stmobj, __data = data, update = sharemap.update, } return setmetatable(obj, { __index = data, __newindex = error }) end return sharemap
bugfix #257
bugfix #257
Lua
mit
kebo/skynet,lc412/skynet,yinjun322/skynet,boyuegame/skynet,harryzeng/skynet,your-gatsby/skynet,icetoggle/skynet,letmefly/skynet,korialuo/skynet,ypengju/skynet_comment,microcai/skynet,vizewang/skynet,ludi1991/skynet,liuxuezhan/skynet,lc412/skynet,czlc/skynet,codingabc/skynet,yinjun322/skynet,felixdae/skynet,zhangshiqian1214/skynet,sdgdsffdsfff/skynet,matinJ/skynet,cuit-zhaxin/skynet,asanosoyokaze/skynet,zhangshiqian1214/skynet,chenjiansnail/skynet,letmefly/skynet,xinjuncoding/skynet,sundream/skynet,QuiQiJingFeng/skynet,korialuo/skynet,liuxuezhan/skynet,JiessieDawn/skynet,catinred2/skynet,cuit-zhaxin/skynet,enulex/skynet,winglsh/skynet,Ding8222/skynet,samael65535/skynet,icetoggle/skynet,chuenlungwang/skynet,lawnight/skynet,fhaoquan/skynet,asanosoyokaze/skynet,zzh442856860/skynet,pigparadise/skynet,kebo/skynet,zhouxiaoxiaoxujian/skynet,hongling0/skynet,ruleless/skynet,icetoggle/skynet,bigrpg/skynet,KittyCookie/skynet,iskygame/skynet,Markal128/skynet,zhaijialong/skynet,kyle-wang/skynet,sanikoyes/skynet,JiessieDawn/skynet,lawnight/skynet,zhoukk/skynet,boyuegame/skynet,codingabc/skynet,Zirpon/skynet,sdgdsffdsfff/skynet,nightcj/mmo,letmefly/skynet,rainfiel/skynet,bigrpg/skynet,hongling0/skynet,hongling0/skynet,JiessieDawn/skynet,MetSystem/skynet,wangyi0226/skynet,cloudwu/skynet,u20024804/skynet,KAndQ/skynet,ludi1991/skynet,pichina/skynet,winglsh/skynet,javachengwc/skynet,cpascal/skynet,lynx-seu/skynet,xcjmine/skynet,sanikoyes/skynet,plsytj/skynet,xinjuncoding/skynet,puXiaoyi/skynet,chenjiansnail/skynet,leezhongshan/skynet,zzh442856860/skynet-Note,zzh442856860/skynet-Note,catinred2/skynet,cuit-zhaxin/skynet,enulex/skynet,winglsh/skynet,ruleless/skynet,kyle-wang/skynet,chuenlungwang/skynet,cloudwu/skynet,zzh442856860/skynet-Note,kyle-wang/skynet,cdd990/skynet,asanosoyokaze/skynet,ilylia/skynet,matinJ/skynet,Ding8222/skynet,zhangshiqian1214/skynet,your-gatsby/skynet,bttscut/skynet,xcjmine/skynet,chfg007/skynet,MoZhonghua/skynet,Markal128/skynet,sundream/skynet,catinred2/skynet,yinjun322/skynet,ilylia/skynet,leezhongshan/skynet,harryzeng/skynet,fhaoquan/skynet,u20024804/skynet,togolwb/skynet,xjdrew/skynet,KAndQ/skynet,fztcjjl/skynet,bttscut/skynet,great90/skynet,helling34/skynet,longmian/skynet,dymx101/skynet,jxlczjp77/skynet,yunGit/skynet,u20024804/skynet,ypengju/skynet_comment,Markal128/skynet,rainfiel/skynet,jxlczjp77/skynet,jiuaiwo1314/skynet,zhaijialong/skynet,gitfancode/skynet,zzh442856860/skynet,xinjuncoding/skynet,chuenlungwang/skynet,jxlczjp77/skynet,lc412/skynet,LiangMa/skynet,chfg007/skynet,lynx-seu/skynet,helling34/skynet,wangyi0226/skynet,sanikoyes/skynet,boyuegame/skynet,helling34/skynet,liuxuezhan/skynet,firedtoad/skynet,vizewang/skynet,MoZhonghua/skynet,lawnight/skynet,togolwb/skynet,javachengwc/skynet,chenjiansnail/skynet,ag6ag/skynet,ludi1991/skynet,rainfiel/skynet,MRunFoss/skynet,yunGit/skynet,firedtoad/skynet,cpascal/skynet,lawnight/skynet,bingo235/skynet,iskygame/skynet,ypengju/skynet_comment,zhouxiaoxiaoxujian/skynet,pichina/skynet,cdd990/skynet,nightcj/mmo,zhoukk/skynet,ilylia/skynet,Zirpon/skynet,bingo235/skynet,MetSystem/skynet,plsytj/skynet,jiuaiwo1314/skynet,puXiaoyi/skynet,cmingjian/skynet,longmian/skynet,leezhongshan/skynet,pigparadise/skynet,korialuo/skynet,sdgdsffdsfff/skynet,pigparadise/skynet,MetSystem/skynet,iskygame/skynet,fhaoquan/skynet,bttscut/skynet,MRunFoss/skynet,wangjunwei01/skynet,codingabc/skynet,fztcjjl/skynet,zhaijialong/skynet,zhoukk/skynet,chfg007/skynet,zhangshiqian1214/skynet,dymx101/skynet,enulex/skynet,zhangshiqian1214/skynet,kebo/skynet,bingo235/skynet,felixdae/skynet,czlc/skynet,puXiaoyi/skynet,QuiQiJingFeng/skynet,KittyCookie/skynet,cloudwu/skynet,gitfancode/skynet,wangyi0226/skynet,samael65535/skynet,your-gatsby/skynet,MoZhonghua/skynet,vizewang/skynet,great90/skynet,harryzeng/skynet,fztcjjl/skynet,ag6ag/skynet,yunGit/skynet,QuiQiJingFeng/skynet,letmefly/skynet,liuxuezhan/skynet,felixdae/skynet,lynx-seu/skynet,xjdrew/skynet,firedtoad/skynet,cmingjian/skynet,longmian/skynet,zhouxiaoxiaoxujian/skynet,microcai/skynet,xcjmine/skynet,dymx101/skynet,pichina/skynet,cmingjian/skynet,samael65535/skynet,ludi1991/skynet,sundream/skynet,microcai/skynet,zzh442856860/skynet-Note,bigrpg/skynet,wangjunwei01/skynet,javachengwc/skynet,LiangMa/skynet,nightcj/mmo,MRunFoss/skynet,KittyCookie/skynet,zzh442856860/skynet,Zirpon/skynet,matinJ/skynet,cdd990/skynet,czlc/skynet,cpascal/skynet,wangjunwei01/skynet,ruleless/skynet,zhangshiqian1214/skynet,togolwb/skynet,xjdrew/skynet,ag6ag/skynet,plsytj/skynet,great90/skynet,Ding8222/skynet,LiangMa/skynet,gitfancode/skynet,jiuaiwo1314/skynet,KAndQ/skynet
e234044290f33bc0632bc0e6ea72d1903ba3edb9
build/scripts/actions/package.lua
build/scripts/actions/package.lua
newoption({ trigger = "pack-libdir", description = "Specifiy the subdirectory in lib/ to be used when packaging the project" }) ACTION.Name = "Package" ACTION.Description = "Pack Nazara binaries/include/lib together" ACTION.Function = function () local libDir = _OPTIONS["pack-libdir"] if (not libDir or #libDir == 0) then local libDirs = os.matchdirs("../lib/*") if (#libDirs > 1) then error("More than one subdirectory was found in the lib directory, please use the --pack-libdir command to clarify which directory should be used") elseif (#libDirs == 0) then error("No subdirectory was found in the lib directory, have you built the engine yet?") else libDir = path.getname(libDirs[1]) print("No directory was set by the --pack-libdir command, \"" .. libDir .. "\" will be used") end end local realLibDir = "../lib/" .. libDir .. "/" if (not os.isdir(realLibDir)) then error(string.format("\"%s\" doesn't seem to be an existing directory", realLibDir)) end local archEnabled = { ["x64"] = false, ["x86"] = false } for k,v in pairs(os.matchdirs(realLibDir .. "*")) do local arch = path.getname(v) if (archEnabled[arch] ~= nil) then archEnabled[arch] = true print(arch .. " arch found") else print("Unknown directory " .. v .. " found, ignored") end end local packageDir = "../package/" local copyTargets = { { -- Engine headers Masks = {"**.hpp", "**.inl"}, Source = "../include/", Target = "include/" }, { -- SDK headers Masks = {"**.hpp", "**.inl"}, Source = "../SDK/include/", Target = "include/" }, { -- Examples files Masks = {"**.hpp", "**.inl", "**.cpp"}, Source = "../examples/", Target = "examples/" }, { -- Demo resources Masks = {"**.*"}, Source = "../examples/bin/resources/", Target = "examples/bin/resources/" }, -- Unit test sources { Masks = {"**.hpp", "**.inl", "**.cpp"}, Source = "../tests/", Target = "tests/src/" }, -- Unit test resources { Masks = {"**.*"}, Source = "../tests/resources/", Target = "tests/resources/" } } local binFileMasks local libFileMasks if (os.is("windows")) then binFileMasks = {"**.dll"} libFileMasks = {"**.lib", "**.a"} elseif (os.is("macosx")) then binFileMasks = {"**.dynlib"} libFileMasks = {"**.a"} else binFileMasks = {"**.so"} libFileMasks = {"**.a"} end local enabledArchs = {} for arch, enabled in pairs(archEnabled) do if (enabled) then local archLibSrc = realLibDir .. arch .. "/" local arch3rdPartyBinSrc = "../extlibs/lib/common/" .. arch .. "/" local archBinDst = "bin/" .. arch .. "/" local archLibDst = "lib/" .. arch .. "/" -- Engine/SDK binaries table.insert(copyTargets, { Masks = binFileMasks, Source = archLibSrc, Target = archBinDst }) -- Engine/SDK libraries table.insert(copyTargets, { Masks = libFileMasks, Source = archLibSrc, Target = archLibDst }) -- 3rd party binary dep table.insert(copyTargets, { Masks = binFileMasks, Source = arch3rdPartyBinSrc, Target = archBinDst }) table.insert(enabledArchs, arch) end end if (os.is("windows")) then -- Demo executable (Windows) table.insert(copyTargets, { Masks = {"Demo*.exe"}, Source = "../examples/bin/", Target = "examples/bin/" }) -- Unit test (Windows) table.insert(copyTargets, { Masks = {"*.exe"}, Source = "../tests/", Target = "tests/" }) elseif (os.is("macosx")) then -- Demo executable (OS X) table.insert(copyTargets, { Masks = {"Demo*"}, Filter = function (filePath) return path.getextension(filePath) == "" end, Source = "../examples/bin/", Target = "examples/bin/" }) -- Unit test (OS X) table.insert(copyTargets, { Masks = {"*.*"}, Filter = function (filePath) return path.getextension(filePath) == "" end, Source = "../tests/", Target = "tests/" }) else -- Demo executable (Linux) table.insert(copyTargets, { Masks = {"Demo*"}, Filter = function (filePath) return path.getextension(filePath) == "" end, Source = "../examples/bin/", Target = "examples/bin/" }) -- Unit test (Linux) table.insert(copyTargets, { Masks = {"*.*"}, Filter = function (filePath) return path.getextension(filePath) == "" end, Source = "../tests/", Target = "tests/" }) end -- Processing os.mkdir(packageDir) local size = 0 for k,v in pairs(copyTargets) do local target = packageDir .. v.Target local includePrefix = v.Source local targetFiles = {} for k, mask in pairs(v.Masks) do print(includePrefix .. mask .. " => " .. target) local files = os.matchfiles(includePrefix .. mask) if (v.Filter) then for k,path in pairs(files) do if (not v.Filter(path)) then files[k] = nil end end end targetFiles = table.join(targetFiles, files) end for k,v in pairs(targetFiles) do local relPath = v:sub(#includePrefix + 1) local targetPath = target .. relPath local targetDir = path.getdirectory(targetPath) if (not os.isdir(targetDir)) then local ok, err = os.mkdir(targetDir) if (not ok) then print("Failed to create directory \"" .. targetDir .. "\": " .. err) end end local ok, err if (os.is("windows")) then ok, err = os.copyfile(v, targetPath) else -- Workaround: As premake is translating this to "cp %s %s", it fails if there are space in the paths. ok, err = os.copyfile(string.format("\"%s\"", v), string.format("\"%s\"", targetPath)) end if (not ok) then print("Failed to copy \"" .. v .. "\" to \"" .. targetPath .. "\": " .. err) end local stat = os.stat(targetPath) if (stat) then size = size + stat.size end end end local config = libDir .. " - " .. table.concat(enabledArchs, ", ") print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size / (1024 * 1024), config)) end
newoption({ trigger = "pack-libdir", description = "Specifiy the subdirectory in lib/ to be used when packaging the project" }) ACTION.Name = "Package" ACTION.Description = "Pack Nazara binaries/include/lib together" ACTION.Function = function () local libDir = _OPTIONS["pack-libdir"] if (not libDir or #libDir == 0) then local libDirs = os.matchdirs("../lib/*") if (#libDirs > 1) then error("More than one subdirectory was found in the lib directory, please use the --pack-libdir command to clarify which directory should be used") elseif (#libDirs == 0) then error("No subdirectory was found in the lib directory, have you built the engine yet?") else libDir = path.getname(libDirs[1]) print("No directory was set by the --pack-libdir command, \"" .. libDir .. "\" will be used") end end local realLibDir = "../lib/" .. libDir .. "/" if (not os.isdir(realLibDir)) then error(string.format("\"%s\" doesn't seem to be an existing directory", realLibDir)) end local archEnabled = { ["x64"] = false, ["x86"] = false } local enabledArchs = {} for k,v in pairs(os.matchdirs(realLibDir .. "*")) do local arch = path.getname(v) if (archEnabled[arch] ~= nil) then archEnabled[arch] = true table.insert(enabledArchs, arch) else print("Unknown directory " .. v .. " found, ignored") end end enabledArchs = table.concat(enabledArchs, ", ") print(enabledArchs .. " arch found") local packageDir = "../package/" local copyTargets = { { -- Engine headers Masks = {"**.hpp", "**.inl"}, Source = "../include/", Target = "include/" }, { -- SDK headers Masks = {"**.hpp", "**.inl"}, Source = "../SDK/include/", Target = "include/" }, { -- Examples files Masks = {"**.hpp", "**.inl", "**.cpp"}, Source = "../examples/", Target = "examples/" }, { -- Demo resources Masks = {"**.*"}, Source = "../examples/bin/resources/", Target = "examples/bin/resources/" }, -- Unit test sources { Masks = {"**.hpp", "**.inl", "**.cpp"}, Source = "../tests/", Target = "tests/src/" }, -- Unit test resources { Masks = {"**.*"}, Source = "../tests/resources/", Target = "tests/resources/" } } local binFileMasks local libFileMasks local exeFileExt local exeFilterFunc if (os.is("windows")) then binFileMasks = {"**.dll"} libFileMasks = {"**.lib", "**.a"} exeFileExt = ".exe" exeFilterFunc = function (filePath) return true end elseif (os.is("macosx")) then binFileMasks = {"**.dynlib"} libFileMasks = {"**.a"} exeFileExt = "" exeFilterFunc = function (filePath) return path.getextension(filePath):contains('/') end else binFileMasks = {"**.so"} libFileMasks = {"**.a"} exeFileExt = "" exeFilterFunc = function (filePath) return path.getextension(filePath):contains('/') end end for arch, enabled in pairs(archEnabled) do if (enabled) then local archLibSrc = realLibDir .. arch .. "/" local arch3rdPartyBinSrc = "../extlibs/lib/common/" .. arch .. "/" local archBinDst = "bin/" .. arch .. "/" local archLibDst = "lib/" .. arch .. "/" -- Engine/SDK binaries table.insert(copyTargets, { Masks = binFileMasks, Source = archLibSrc, Target = archBinDst }) -- Engine/SDK libraries table.insert(copyTargets, { Masks = libFileMasks, Source = archLibSrc, Target = archLibDst }) -- 3rd party binary dep table.insert(copyTargets, { Masks = binFileMasks, Source = arch3rdPartyBinSrc, Target = archBinDst }) end end -- Demo executable table.insert(copyTargets, { Masks = {"Demo*" .. exeFileExt}, Filter = exeFilterFunc, Source = "../examples/bin/", Target = "examples/bin/" }) -- Unit test table.insert(copyTargets, { Masks = {"*" .. exeFileExt}, Filter = exeFilterFunc, Source = "../tests/", Target = "tests/" }) -- Processing os.mkdir(packageDir) local size = 0 for k,v in pairs(copyTargets) do local target = packageDir .. v.Target local includePrefix = v.Source local targetFiles = {} for k, mask in pairs(v.Masks) do print(includePrefix .. mask .. " => " .. target) local files = os.matchfiles(includePrefix .. mask) if (v.Filter) then for k,path in pairs(files) do if (not v.Filter(path)) then files[k] = nil end end end targetFiles = table.join(targetFiles, files) end for k,v in pairs(targetFiles) do local relPath = v:sub(#includePrefix + 1) local targetPath = target .. relPath local targetDir = path.getdirectory(targetPath) if (not os.isdir(targetDir)) then local ok, err = os.mkdir(targetDir) if (not ok) then print("Failed to create directory \"" .. targetDir .. "\": " .. err) end end local ok, err if (os.is("windows")) then ok, err = os.copyfile(v, targetPath) else -- Workaround: As premake is translating this to "cp %s %s", it fails if space are presents in source/destination paths. ok, err = os.copyfile(string.format("\"%s\"", v), string.format("\"%s\"", targetPath)) end if (not ok) then print("Failed to copy \"" .. v .. "\" to \"" .. targetPath .. "\": " .. err) end local stat = os.stat(targetPath) if (stat) then size = size + stat.size end end end local config = libDir .. " - " .. enabledArchs print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size / (1024 * 1024), config)) end
Build/Package: Fix executable binaries not being packaged under Linux (Close #77)
Build/Package: Fix executable binaries not being packaged under Linux (Close #77) Former-commit-id: 5c885f70af44968f33ee1dbd93646293bcea5d2e [formerly 8edfc3654005393c28e27f8c6cbe427a43152f3f] [formerly b66fb4ef5b275e63c649c336170f22bd3155f67b [formerly ac7655fa1c6e2e4d429dca86c5fd78a499481fd6]] Former-commit-id: 0cf284996de8d81ddec55cbabda9d950d45f4d1b [formerly f11faabb2157f8f546a51ed27484b8d5859fbf7e] Former-commit-id: 2a5c0b57a2451980b89c4dbe36e089dd13fabc3a
Lua
mit
DigitalPulseSoftware/NazaraEngine
0131e9df3b91e95c4dd05d4a64aca7f3f1c6dcf5
nyagos.d/suffix.lua
nyagos.d/suffix.lua
nyagos.suffixes={} function suffix(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not nyagos.suffixes[suffix] then local orgpathext = nyagos.getenv("PATHEXT") local newext="."..suffix if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.setenv("PATHEXT",orgpathext..";"..newext) end end nyagos.suffixes[suffix]=cmdline end nyagos.argsfilter = function(args) local path=nyagos.which(args[0]) if not path then return end local m = string.match(path,"%.(%w+)$") if not m then return end local cmdline = nyagos.suffixes[ string.lower(m) ] if not cmdline then return end local newargs={} for i=1,#cmdline do newargs[i-1]=cmdline[i] end newargs[#cmdline] = path for i=1,#args do newargs[#cmdline+i] = args[i] end return newargs end alias{ suffix=function(args) if #args < 2 then print "Usage: suffix SUFFIX COMMAND" else suffix(args[1],args[2]) end end } suffix(".pl",{"perl"}) suffix(".py",{"ipy"}) suffix(".rb",{"ruby"}) suffix(".lua",{"lua"}) suffix(".awk",{"awk","-f"}) suffix(".js",{"cscript","//nologo"}) suffix(".vbs",{"cscript","//nologo"}) suffix(".ps1",{"powershell","-file"})
nyagos.suffixes={} function suffix(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not nyagos.suffixes[suffix] then local orgpathext = nyagos.getenv("PATHEXT") local newext="."..suffix if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.setenv("PATHEXT",orgpathext..";"..newext) end end nyagos.suffixes[suffix]=cmdline end local org_filter=nyagos.argsfilter nyagos.argsfilter = function(args) if org_filter then local args_ = org_filter(args) if args_ then args = args_ end end local path=nyagos.which(args[0]) if not path then return end local m = string.match(path,"%.(%w+)$") if not m then return end local cmdline = nyagos.suffixes[ string.lower(m) ] if not cmdline then return end local newargs={} for i=1,#cmdline do newargs[i-1]=cmdline[i] end newargs[#cmdline] = path for i=1,#args do newargs[#cmdline+i] = args[i] end return newargs end alias{ suffix=function(args) if #args < 2 then print "Usage: suffix SUFFIX COMMAND" else suffix(args[1],args[2]) end end } suffix(".pl",{"perl"}) suffix(".py",{"ipy"}) suffix(".rb",{"ruby"}) suffix(".lua",{"lua"}) suffix(".awk",{"awk","-f"}) suffix(".js",{"cscript","//nologo"}) suffix(".vbs",{"cscript","//nologo"}) suffix(".ps1",{"powershell","-file"})
suffix.lua call previous nyagos.argsfilter if it exists.
suffix.lua call previous nyagos.argsfilter if it exists.
Lua
bsd-3-clause
hattya/nyagos,kissthink/nyagos,zetamatta/nyagos,tyochiai/nyagos,hattya/nyagos,nocd5/nyagos,kissthink/nyagos,tsuyoshicho/nyagos,hattya/nyagos,kissthink/nyagos
9d582f5ea4ef772c70b10b8638ab2c189c5b467f
lua/lualine/themes/hydrangea.lua
lua/lualine/themes/hydrangea.lua
-- Palette (LCH values were measured in GIMP 2.10.4) local base03 = ("#171c26", 235) # L = 10, C = 8, H = 270 local base02 = ("#232833", 236) # L = 16, C = 8, H = 270 local base01 = ("#303540", 238) # L = 22, C = 8, H = 270 local base00 = ("#4b505d", 241) # L = 28, C = 8, H = 270 local base0 = ("#465166", 252) # L = 34, C = 14, H = 270 local base1 = ("#8791a9", 252) # L = 60, C = 14, H = 270 local base2 = ("#cdd8f1", 252) # L = 86, C = 14, H = 270 local red01 = ("#681c36", 52) # L = ?, C = ?, H = ? local red1 = ("#e91e63", 161) # L = ?, C = ?, H = ? local green1 = ("#98bf00", 106) # L = ?, C = ?, H = ? local teal01 = ("#013435", 23) # L = ?, C = ?, H = ? local teal2 = ("#019c9c", 44) # L = ?, C = ?, H = ? local cyan01 = ("#023342", 23) # L = 19, C = 18, H = 232 local cyan1 = ("#1398bf", 38) # L = 58, C = 38, H = 232 local cyan3 = ("#9bdffc", 153) # L = 85, C = 27, H = 232 local blue1 = ("#3a69bf", 68) # L = ?, C = ?, H = ? local blue2 = ('#8baafe', 111) # L = ?, C = ?, H = ? local blue3 = ('#c9d4fd', 189) # L = ?, C = ?, H = ? local violet1 = ("#996ddb", 98) # L = ?, C = ?, H = ? local violet2 = ("#c398fe", 183) # L = ?, C = ?, H = ? local violet3 = ("#e2ccfe", 225) # L = ?, C = ?, H = ? local magenta01 = ("#491f38", 89) # L = 19, C = 30, H = 343 local magenta1 = ("#c44597", 162) # L = 50, C = 60, H = 343 local magenta3 = ("#ffc3e4", 218) # L = 85, C = 27, H = 343 return { normal = { a = { fg = base03, bg = base2, gui = 'bold' }, b = { fg = base03, bg = base1 }, c = { fg = base03, bg = base0 }, }, insert = { a = { fg = base03, bg = cyan1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, visual = { a = { fg = base03, bg = green1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, replace = { a = { fg = base03, bg = violet1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, inactive = { a = { fg = base03, bg = base1, gui = 'bold' }, b = { fg = base03, bg = base1 }, c = { fg = base03, bg = base0 }, }, }
-- Palette (LCH values were measured in GIMP 2.10.4) local base03 = ("#171c26", 235) -- L = 10, C = 8, H = 270 local base02 = ("#232833", 236) -- L = 16, C = 8, H = 270 local base01 = ("#303540", 238) -- L = 22, C = 8, H = 270 local base00 = ("#4b505d", 241) -- L = 28, C = 8, H = 270 local base0 = ("#465166", 252) -- L = 34, C = 14, H = 270 local base1 = ("#8791a9", 252) -- L = 60, C = 14, H = 270 local base2 = ("#cdd8f1", 252) -- L = 86, C = 14, H = 270 local red01 = ("#681c36", 52) -- L = ?, C = ?, H = ? local red1 = ("#e91e63", 161) -- L = ?, C = ?, H = ? local green1 = ("#98bf00", 106) -- L = ?, C = ?, H = ? local teal01 = ("#013435", 23) -- L = ?, C = ?, H = ? local teal2 = ("#019c9c", 44) -- L = ?, C = ?, H = ? local cyan01 = ("#023342", 23) -- L = 19, C = 18, H = 232 local cyan1 = ("#1398bf", 38) -- L = 58, C = 38, H = 232 local cyan3 = ("#9bdffc", 153) -- L = 85, C = 27, H = 232 local blue1 = ("#3a69bf", 68) -- L = ?, C = ?, H = ? local blue2 = ('#8baafe', 111) -- L = ?, C = ?, H = ? local blue3 = ('#c9d4fd', 189) -- L = ?, C = ?, H = ? local violet1 = ("#996ddb", 98) -- L = ?, C = ?, H = ? local violet2 = ("#c398fe", 183) -- L = ?, C = ?, H = ? local violet3 = ("#e2ccfe", 225) -- L = ?, C = ?, H = ? local magenta01 = ("#491f38", 89) -- L = 19, C = 30, H = 343 local magenta1 = ("#c44597", 162) -- L = 50, C = 60, H = 343 local magenta3 = ("#ffc3e4", 218) -- L = 85, C = 27, H = 343 return { normal = { a = { fg = base03, bg = base2, gui = 'bold' }, b = { fg = base03, bg = base1 }, c = { fg = base03, bg = base0 }, }, insert = { a = { fg = base03, bg = cyan1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, visual = { a = { fg = base03, bg = green1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, replace = { a = { fg = base03, bg = violet1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, inactive = { a = { fg = base03, bg = base1, gui = 'bold' }, b = { fg = base03, bg = base1 }, c = { fg = base03, bg = base0 }, }, }
Fix the way to comment
Fix the way to comment
Lua
mit
yuttie/hydrangea-vim
1189b3f8e2596a05b5b7787eb00f93b1a1c6f31b
ExamTip/src/MY_ExamTip.lua
ExamTip/src/MY_ExamTip.lua
-- -- ƾ -- by @ ˫ @ ݶ -- Build 20140730 -- -- Ҫ: ƾ -- local _L = MY.LoadLangPack(MY.GetAddonInfo().szRoot.."ExamTip/lang/") local _Cache = { szQueryUrl = "http://jx3.derzh.com/exam/?l=%s&q=%s", szSubmitUrl = "http://jx3.derzh.com/exam/submit.php?l=%s&d=%s", tCached = {}, tLastQu = "", } MY_ExamTip = {} -- ȡĿʹ MY_ExamTip.QueryData = function(szQues) if _Cache.tLastQu == szQues then return nil end _Cache.tLastQu = szQues MY_ExamTip.ShowResult(szQues, nil, _L["Querying, please wait..."]) local _, _, szLang, _ = GetVersion() MY.RemoteRequest(string.format(_Cache.szQueryUrl, szLang, MY.String.UrlEncode(szQues)), function(szTitle, szContent) local data = MY.Json.Decode(szContent) if not data then return nil end local szTip = '' local UrlDecode = function(szText) return szText:gsub("+", " "):gsub("%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end) end for _, p in ipairs(data.result) do szTip = szTip .. p.szQues .. '\n' .. p.szAnsw end szTip = UrlDecode(szTip) if #data.result == 0 then szTip = _L["No result found. Here's from open search engine:"].."\n" .. szTip else MY_ExamTip.ShowResult(UrlDecode(data.question), UrlDecode(data.result[1].szAnsw), szTip) end end, function() MY_ExamTip.ShowResult(_Cache.tLastQu, nil, _L['Loading failed.']) _Cache.tLastQu = "" end, 10000) end -- ύȷ -- Դ MY_ExamTip.SubmitData = function() local _, _, szLang, _ = GetVersion() MY_Anmerkungen.szNotePanelContent = string.format(_Cache.szSubmitUrl, szLang, MY.String.UrlEncode(MY.Json.Encode(_Cache.tCached))) MY.RemoteRequest(string.format(_Cache.szSubmitUrl, szLang, MY.String.UrlEncode(MY.Json.Encode(_Cache.tCached))), function(szTitle, szContent) local r = MY.Json.Decode(szContent) MY.Sysmsg({_L('%s record(s) commited, %s record(s) accepted!', r.received, r.accepted)}, _L['exam tip']) end) end -- ʾ MY_ExamTip.ShowResult = function(szQues, szAnsw, szTip) local hQues = Station.Lookup("Normal/ExaminationPanel/","Handle_ExamContents"):Lookup(0) local hTxt1 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No1",'Text_T1No1') local hChk1 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No1") local hTxt2 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No2",'Text_T1No2') local hChk2 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No2") local hTxt3 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No3",'Text_T1No3') local hChk3 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No3") local hTxt4 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No4",'Text_T1No4') local hChk4 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No4") if hQues:GetText() ~= szQues then return false end hTxt1:SetFontColor(0, 0, 0) hTxt2:SetFontColor(0, 0, 0) hTxt3:SetFontColor(0, 0, 0) hTxt4:SetFontColor(0, 0, 0) if hTxt1:GetText() == szAnsw then hTxt1:SetFontColor(255, 255, 0) hChk1:Check(true) elseif hTxt2:GetText() == szAnsw then hTxt2:SetFontColor(255, 255, 0) hChk2:Check(true) elseif hTxt3:GetText() == szAnsw then hTxt3:SetFontColor(255, 255, 0) hChk3:Check(true) elseif hTxt4:GetText() == szAnsw then hTxt4:SetFontColor(255, 255, 0) hChk4:Check(true) end end -- ռ MY_ExamTip.CollectResult = function() local hQues = Station.Lookup("Normal/ExaminationPanel/","Handle_ExamContents"):Lookup(0) local hTxt1 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No1",'Text_T1No1') local hChk1 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No1") local hTxt2 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No2",'Text_T1No2') local hChk2 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No2") local hTxt3 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No3",'Text_T1No3') local hChk3 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No3") local hTxt4 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No4",'Text_T1No4') local hChk4 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No4") local szQues = hQues:GetText() local szAnsw if hChk1:IsCheckBoxChecked() then szAnsw = hTxt1:GetText() elseif hChk2:IsCheckBoxChecked() then szAnsw = hTxt2:GetText() elseif hChk3:IsCheckBoxChecked() then szAnsw = hTxt3:GetText() elseif hChk4:IsCheckBoxChecked() then szAnsw = hTxt4:GetText() end if szQues and szAnsw then _Cache.tCached[szQues] = szAnsw end end -- ʱӼ _Cache.OnFrameBreathe = function() local frame = Station.Lookup("Normal/ExaminationPanel") if not (frame and frame:IsVisible()) then return nil end local szQues = Station.Lookup("Normal/ExaminationPanel/","Handle_ExamContents"):Lookup(0):GetText() MY_ExamTip.QueryData(szQues) MY_ExamTip.CollectResult(szQues) _Cache.nExamPrintRemainSpace = GetClientPlayer().GetExamPrintRemainSpace() end -- עINIT¼ MY.RegisterInit(function() MY.BreatheCall(_Cache.OnFrameBreathe) MY.RegisterEvent("BAG_ITEM_UPDATE", function() local item = GetClientPlayer().GetItem(arg0, arg1) if item.szName == '' then MY.DelayCall(function(nExamPrintRemainSpace) if nExamPrintRemainSpace - GetClientPlayer().GetExamPrintRemainSpace() == 100 then MY_ExamTip.SubmitData() end end, { _Cache.nExamPrintRemainSpace }, 5000) end end) end)
-- -- ƾ -- by @ ˫ @ ݶ -- Build 20140730 -- -- Ҫ: ƾ -- local _L = MY.LoadLangPack(MY.GetAddonInfo().szRoot.."ExamTip/lang/") local _Cache = { szQueryUrl = "http://jx3.derzh.com/exam/?l=%s&q=%s", szSubmitUrl = "http://jx3.derzh.com/exam/submit.php?l=%s&d=%s", tCached = {}, tLastQu = "", } MY_ExamTip = {} -- ȡĿʹ MY_ExamTip.QueryData = function(szQues) if _Cache.tLastQu == szQues then return nil end _Cache.tLastQu = szQues MY_ExamTip.ShowResult(szQues, nil, _L["Querying, please wait..."]) local _, _, szLang, _ = GetVersion() MY.RemoteRequest(string.format(_Cache.szQueryUrl, szLang, MY.String.UrlEncode(szQues)), function(szTitle, szContent) local data = MY.Json.Decode(szContent) if not data then return nil end local szTip = '' local UrlDecode = function(szText) return szText:gsub("+", " "):gsub("%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end) end for _, p in ipairs(data.result) do szTip = szTip .. p.szQues .. '\n' .. p.szAnsw end szTip = UrlDecode(szTip) if #data.result == 0 then szTip = _L["No result found. Here's from open search engine:"].."\n" .. szTip else MY_ExamTip.ShowResult(UrlDecode(data.question), UrlDecode(data.result[1].szAnsw), szTip) end end, function() MY_ExamTip.ShowResult(_Cache.tLastQu, nil, _L['Loading failed.']) _Cache.tLastQu = "" end, 10000) end -- ύȷ -- Դ MY_ExamTip.SubmitData = function() local _, _, szLang, _ = GetVersion() MY_Anmerkungen.szNotePanelContent = string.format(_Cache.szSubmitUrl, szLang, MY.String.UrlEncode(MY.Json.Encode(_Cache.tCached))) MY.RemoteRequest(string.format(_Cache.szSubmitUrl, szLang, MY.String.UrlEncode(MY.Json.Encode(_Cache.tCached))), function(szTitle, szContent) local r = MY.Json.Decode(szContent) MY.Sysmsg({_L('%s record(s) commited, %s record(s) accepted!', r.received, r.accepted)}, _L['exam tip']) end) end -- ʾ MY_ExamTip.ShowResult = function(szQues, szAnsw, szTip) local hQues = Station.Lookup("Normal/ExaminationPanel/","Handle_ExamContents"):Lookup(0) local hTxt1 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No1",'Text_T1No1') local hChk1 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No1") local hTxt2 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No2",'Text_T1No2') local hChk2 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No2") local hTxt3 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No3",'Text_T1No3') local hChk3 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No3") local hTxt4 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No4",'Text_T1No4') local hChk4 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No4") if hQues:GetText() ~= szQues then return false end hTxt1:SetFontColor(0, 0, 0) hTxt2:SetFontColor(0, 0, 0) hTxt3:SetFontColor(0, 0, 0) hTxt4:SetFontColor(0, 0, 0) if hTxt1:GetText() == szAnsw then hTxt1:SetFontColor(255, 255, 0) hChk1:Check(true) elseif hTxt2:GetText() == szAnsw then hTxt2:SetFontColor(255, 255, 0) hChk2:Check(true) elseif hTxt3:GetText() == szAnsw then hTxt3:SetFontColor(255, 255, 0) hChk3:Check(true) elseif hTxt4:GetText() == szAnsw then hTxt4:SetFontColor(255, 255, 0) hChk4:Check(true) end end -- ռ MY_ExamTip.CollectResult = function() local hQues = Station.Lookup("Normal/ExaminationPanel/","Handle_ExamContents"):Lookup(0) local hTxt1 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No1",'Text_T1No1') local hChk1 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No1") local hTxt2 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No2",'Text_T1No2') local hChk2 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No2") local hTxt3 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No3",'Text_T1No3') local hChk3 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No3") local hTxt4 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No4",'Text_T1No4') local hChk4 = Station.Lookup("Normal/ExaminationPanel/Wnd_Type1/CheckBox_T1No4") local szQues = hQues:GetText() local szAnsw if hChk1:IsCheckBoxChecked() then szAnsw = hTxt1:GetText() elseif hChk2:IsCheckBoxChecked() then szAnsw = hTxt2:GetText() elseif hChk3:IsCheckBoxChecked() then szAnsw = hTxt3:GetText() elseif hChk4:IsCheckBoxChecked() then szAnsw = hTxt4:GetText() end if szQues and szAnsw then _Cache.tCached[szQues] = szAnsw end end -- ʱӼ _Cache.OnFrameBreathe = function() local frame = Station.Lookup("Normal/ExaminationPanel") if not (frame and frame:IsVisible()) then return nil end local szQues = Station.Lookup("Normal/ExaminationPanel/","Handle_ExamContents"):Lookup(0):GetText() MY_ExamTip.QueryData(szQues) MY_ExamTip.CollectResult(szQues) _Cache.nExamPrintRemainSpace = GetClientPlayer().GetExamPrintRemainSpace() end -- עINIT¼ MY.RegisterInit(function() MY.BreatheCall(_Cache.OnFrameBreathe) MY.RegisterEvent("BAG_ITEM_UPDATE", function() local item = GetClientPlayer().GetItem(arg0, arg1) if item and item.szName == '' then local nExamPrintRemainSpace = _Cache.nExamPrintRemainSpace MY.DelayCall(function() if nExamPrintRemainSpace - GetClientPlayer().GetExamPrintRemainSpace() == 100 then MY_ExamTip.SubmitData() end end, 2000) end end) end)
科举助手BUG修复
科举助手BUG修复
Lua
bsd-3-clause
tinymins/MY
40b98e5feca95fc5afd48e48059beefc5f27123d
source-code/server.lua
source-code/server.lua
local deviceXML = require("ssdp") local srv = net.createServer(net.TCP, 10) local port = math.floor(node.chipid()/1000) + 8000 print("Heap: ", node.heap(), "HTTP: ", "Starting server at http://" .. wifi.sta.getip() .. ":" .. port) srv:listen(port, function(conn) conn:on("receive", function( sck, data ) local request = require("httpd_req").new(data) local response = require("httpd_res").new(sck) if request.path == "/" then response.file("http_index.html") end if request.path == "/favicon.ico" then response.contentType("image/x-icon") response.file("http_favicon.ico") end if request.path == "/Device.xml" then response.send(deviceXML, "text/xml") end if request.path == "/settings" then print("Heap: ", node.heap(), "HTTP: ", "Settings") require("server_settings").process(request,response) end if request.path == "/device" then print("Heap: ", node.heap(), "HTTP: ", "Device") require("server_device").process(request,response) end if request.path == "/status" then print("Heap: ", node.heap(), "HTTP: ", "Status") require("server_status").process(request,response) end end) end)
local deviceXML = require("ssdp") local srv = net.createServer(net.TCP, 10) local port = math.floor(node.chipid()/1000) + 8000 print("Heap: ", node.heap(), "HTTP: ", "Starting server at http://" .. wifi.sta.getip() .. ":" .. port) srv:listen(port, function(conn) conn:on("receive", function( sck, data ) local request = require("httpd_req").new(data) local response = require("httpd_res").new(sck) if request.path == "/" then response.file("http_index.html") end if request.path == "/favicon.ico" then response.file("http_favicon.ico", "image/x-icon") end if request.path == "/Device.xml" then response.send(deviceXML, "text/xml") end if request.path == "/settings" then print("Heap: ", node.heap(), "HTTP: ", "Settings") require("server_settings").process(request,response) end if request.path == "/device" then print("Heap: ", node.heap(), "HTTP: ", "Device") require("server_device").process(request,response) end if request.path == "/status" then print("Heap: ", node.heap(), "HTTP: ", "Status") require("server_status").process(request,response) end end) end)
bug fix
bug fix
Lua
apache-2.0
konnected-io/konnected-security,konnected-io/konnected-security
a84fce6a21771bf1e3816ebe0cddaffcb285e2ba
level_select_view.lua
level_select_view.lua
-- imports local active_screen = require 'active_screen' local game_view = require 'game_view' local level_list = require 'level_list' function exports() local instance = {} local backButton = love.graphics.newImage('level_select/back.png') local backX = 20 local backY = 600 local backWidth = 300 local backHeight = 100 local levelButton = love.graphics.newImage('placeholders/watcher.png') local levelStartX = 50 local levelStartY = 100 local levels = level_list.get_levels() function instance:update() local mouse_x, mouse_y = love.mouse.getPosition() if love.mouse.isDown('l') then if mouse_x >= backX and mouse_y >= backY and mouse_x < backX + backWidth and mouse_y < backY + backHeight then active_screen.set(require('initial_menu_view')()) end local x = levelStartX local y = levelStartY for i = 1, #levels do active_screen.set(game_view(levels[i])) end end end function instance:draw() love.graphics.setColor(255, 255, 255) love.graphics.rectangle('fill', 0, 0, 1280, 720) love.graphics.draw(backButton, backX, backY) local x = levelStartX local y = levelStartY for i = 1, #levels do love.graphics.draw(levelButton, x, y) end end return instance end return exports
-- imports local active_screen = require 'active_screen' local game_view = require 'game_view' local level_list = require 'level_list' function exports() local instance = {} local backButton = love.graphics.newImage('level_select/back.png') local backX = 20 local backY = 600 local backWidth = 300 local backHeight = 100 local levelButton = love.graphics.newImage('placeholders/watcher.png') local levelStartX = 50 local levelStartY = 100 local levels = level_list.get_levels() local lastFrameMouseClicked = true function instance:update() local mouse_x, mouse_y = love.mouse.getPosition() local mouseClicked = love.mouse.isDown('l') if mouseClicked and not lastFrameMouseClicked then if mouse_x >= backX and mouse_y >= backY and mouse_x < backX + backWidth and mouse_y < backY + backHeight then active_screen.set(require('initial_menu_view')()) end local x = levelStartX local y = levelStartY for i = 1, #levels do x = x + 32 if mouse_x >= x and mouse_y >= y and mouse_x < x + 32 and mouse_y < y + 32 then active_screen.set(game_view(levels[i])) end end end lastFrameMouseClicked = mouseClicked end function instance:draw() love.graphics.setColor(255, 255, 255) love.graphics.rectangle('fill', 0, 0, 1280, 720) love.graphics.draw(backButton, backX, backY) local x = levelStartX local y = levelStartY for i = 1, #levels do x = x + 32 love.graphics.draw(levelButton, x, y) end end return instance end return exports
Fixed level select view
Fixed level select view
Lua
mit
NamefulTeam/PortoGameJam2015
bcdbd5c93d222adc1055c4c17fb65a2ed3368f84
rapidshare.lua
rapidshare.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(newurl) if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then table.insert(urls, { url=newurl }) addedtolist[newurl] = true end end if string.match(url, "https?://rapid%-search%-engine%.com/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://rapidshare%.com/[^"]+)"') do check(newurl) local newurl1 = string.gsub(newurl, "/files/[0-9]", "/files/") check(newurl1) end for newurl in string.gmatch(html, '"(https?://www%.rapidshare%.com/[^"]+)"') do check(newurl) local newurl1 = string.gsub(newurl, "/files/[0-9]", "/files/") check(newurl1) end end if string.match(url, "rapidshare%.com/files/[0-9]+/") then html = read_file(file) for newurl in string.gmatch(html, 'location="(https?://[^%.]+%.rapidshare%.com/cgi%-bin/[^"]+)"') do check(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] local html = nil last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if http_stat["orig_file_size"] < 100000 then io.stdout:write("Check. \n") io.stdout:flush() html = read_file(file) if string.match(html, "Daily.traffic.exhausted") then io.stdout:write("ERROR: Daily traffic exhausted. \n") io.stdout:flush() return wget.actions.ABORT end end if (status_code >= 200 and status_code <= 399) then downloaded[url["url"]] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = math.random(1, 5) -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end size_file = function(file) if file then local f = assert(io.open(file)) local data = f:seek("end") f:close() return data else return "" end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(newurl) if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then table.insert(urls, { url=newurl }) addedtolist[newurl] = true end end if string.match(url, "https?://rapid%-search%-engine%.com/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://rapidshare%.com/[^"]+)"') do check(newurl) local newurl1 = string.gsub(newurl, "/files/[0-9]", "/files/") check(newurl1) end for newurl in string.gmatch(html, '"(https?://www%.rapidshare%.com/[^"]+)"') do check(newurl) local newurl1 = string.gsub(newurl, "/files/[0-9]", "/files/") check(newurl1) end end if string.match(url, "rapidshare%.com/files/[0-9]+/") then html = read_file(file) for newurl in string.gmatch(html, 'location="(https?://[^%.]+%.rapidshare%.com/cgi%-bin/[^"]+)"') do check(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] local size = size_file(http_stat["local_file"]) local html = nil url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if size < 100000 then html = read_file(http_stat["local_file"]) if string.match(html, "/desktop/error/") then io.stdout:write("ERROR: Daily traffic exhausted. Aborting item in 2 hours. \n") io.stdout:flush() os.execute("sleep "..7200) return wget.actions.ABORT end end if (status_code >= 200 and status_code <= 399) then downloaded[url["url"]] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
rapidshare.lua: fixes, abort if traffic exhausted
rapidshare.lua: fixes, abort if traffic exhausted
Lua
unlicense
ArchiveTeam/rapidshare-grab,ArchiveTeam/rapidshare-grab
81260e9adb2fee69d0cadd1b0f6ec4f73b8f8c87
announce.lua
announce.lua
local mod = EPGP:NewModule("EPGP_Announce") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local function Announce(fmt, ...) local medium = EPGP.db.profile.announce_medium local channel = EPGP.db.profile.announce_channel or 0 local msg = string.format(fmt, ...) local str = "EPGP:" for _,s in pairs({strsplit(" ", msg)}) do if #str + #s >= 250 then SendChatMessage(str, medium, nil, GetChannelName(channel)) str = "EPGP:" end str = str .. " " .. s end SendChatMessage(str, medium, nil, GetChannelName(channel)) end local function AnnounceEPAward(event_name, name, reason, amount, mass) if mass or not EPGP.db.profile.announce then return end Announce(L["%+d EP (%s) to %s"], amount, reason, name) end local function AnnounceGPAward(event_name, name, reason, amount, mass) if mass or not EPGP.db.profile.announce then return end Announce(L["%+d GP (%s) to %s"], amount, reason, name) end local function AnnounceMassEPAward(event_name, names, reason, amount) if not EPGP.db.profile.announce then return end local first = true local awarded for name in pairs(names) do if first then awarded = name first = false else awarded = awarded..", "..name end end Announce(L["%+d EP (%s) to %s"], amount, reason, awarded) if EPGP.db.profile.auto_standby_whispers and UnitInRaid("player") then Announce(L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"]) end end local function AnnounceDecay(event_name, decay_p) Announce(L["Decay of EP/GP by %d%%"], decay_p) end local function AnnounceStartRecurringAward(event_name, reason, amount, mins) local fmt, val = SecondsToTimeAbbrev(mins * 60) Announce(L["Start recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val)) end local function AnnounceStopRecurringAward(event_name) Announce(L["Stop recurring award"]) end local function AnnounceEPGPReset(event_name) Announce(L["EP/GP are reset"]) end function mod:OnEnable() EPGP.RegisterCallback(self, "EPAward", AnnounceEPAward) EPGP.RegisterCallback(self, "MassEPAward", AnnounceMassEPAward) EPGP.RegisterCallback(self, "GPAward", AnnounceGPAward) EPGP.RegisterCallback(self, "Decay", AnnounceDecay) EPGP.RegisterCallback(self, "StartRecurringAward", AnnounceStartRecurringAward) EPGP.RegisterCallback(self, "StopRecurringAward", AnnounceStopRecurringAward) EPGP.RegisterCallback(self, "EPGPReset", AnnounceEPGPReset) end
local mod = EPGP:NewModule("EPGP_Announce") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local function Announce(fmt, ...) local medium = EPGP.db.profile.announce_medium local channel = EPGP.db.profile.announce_channel or 0 -- Override raid and party if we are not grouped if medium == "RAID" and not UnitInRaid("player") then medium = "GUILD" elseif medium == "PARTY" and not UnitInRaid("player") then medium = "GUILD" end local msg = string.format(fmt, ...) local str = "EPGP:" for _,s in pairs({strsplit(" ", msg)}) do if #str + #s >= 250 then SendChatMessage(str, medium, nil, GetChannelName(channel)) str = "EPGP:" end str = str .. " " .. s end SendChatMessage(str, medium, nil, GetChannelName(channel)) end local function AnnounceEPAward(event_name, name, reason, amount, mass) if mass or not EPGP.db.profile.announce then return end Announce(L["%+d EP (%s) to %s"], amount, reason, name) end local function AnnounceGPAward(event_name, name, reason, amount, mass) if mass or not EPGP.db.profile.announce then return end Announce(L["%+d GP (%s) to %s"], amount, reason, name) end local function AnnounceMassEPAward(event_name, names, reason, amount) if not EPGP.db.profile.announce then return end local first = true local awarded for name in pairs(names) do if first then awarded = name first = false else awarded = awarded..", "..name end end Announce(L["%+d EP (%s) to %s"], amount, reason, awarded) if EPGP.db.profile.auto_standby_whispers and UnitInRaid("player") then Announce(L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"]) end end local function AnnounceDecay(event_name, decay_p) Announce(L["Decay of EP/GP by %d%%"], decay_p) end local function AnnounceStartRecurringAward(event_name, reason, amount, mins) local fmt, val = SecondsToTimeAbbrev(mins * 60) Announce(L["Start recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val)) end local function AnnounceStopRecurringAward(event_name) Announce(L["Stop recurring award"]) end local function AnnounceEPGPReset(event_name) Announce(L["EP/GP are reset"]) end function mod:OnEnable() EPGP.RegisterCallback(self, "EPAward", AnnounceEPAward) EPGP.RegisterCallback(self, "MassEPAward", AnnounceMassEPAward) EPGP.RegisterCallback(self, "GPAward", AnnounceGPAward) EPGP.RegisterCallback(self, "Decay", AnnounceDecay) EPGP.RegisterCallback(self, "StartRecurringAward", AnnounceStartRecurringAward) EPGP.RegisterCallback(self, "StopRecurringAward", AnnounceStopRecurringAward) EPGP.RegisterCallback(self, "EPGPReset", AnnounceEPGPReset) end
Override raid and party announces and send them to the raid if the EPGP master is not in party or in raid respectively.
Override raid and party announces and send them to the raid if the EPGP master is not in party or in raid respectively. This fixes issue 245.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,hayword/tfatf_epgp,ceason/epgp-tfatf,sheldon/epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,hayword/tfatf_epgp
cad7ac5a8259f6374001e6b2b40cee2765bb966e
test_scripts/Polices/App_Permissions/021_ATF_P_TC_General_Result_Codes_Disallowed_In_Case_App_Current_Hmi_Level_Is_Not_Listed_In_Assigned_Policies.lua
test_scripts/Polices/App_Permissions/021_ATF_P_TC_General_Result_Codes_Disallowed_In_Case_App_Current_Hmi_Level_Is_Not_Listed_In_Assigned_Policies.lua
--------------------------------------------------------------------------------------------- -- UNREADY: Only 6 RPCs are covered -- Requirement summary: -- HMI Levels the notification is allowed to be processed in -- -- Description: -- SDL must not send/ transfer (in case got from HMI) notification to mobile application, -- in case Policy Table doesn't contain current application's HMILevel -- defined in Policy Table "functional_groupings" section for a specified notification -- -- Preconditions: -- 1. Application with <appID> is registered on SDL. -- 2. Current HMILevel for application is HMILevel_1 -- 3. Policy Table contains section "functional_groupings", -- in which for a specified PRC there're defined HMILevels: HMILevel_2, HMILevel_3 -- Steps: -- 1. App -> SDL: RPC (params) -- -- Expected result: -- SDL -> App: RPC (DISALLOWED, success: "false") --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Local Functions ]] local function verifyResponse(test, corId) test.mobileSession:ExpectResponse(corId) :ValidIf(function(_, d) local exp = {success = false, resultCode = "DISALLOWED"} if (d.payload.success == exp.success) and (d.payload.resultCode == exp.resultCode) then return true else return false, "Expected: {success = '" .. tostring(exp.success) .. "', resultCode = '" .. exp.resultCode .. "'}, got: {success = '" .. tostring(d.payload.success) .. "', resultCode = '" .. d.payload.resultCode .. "'}" end end) end --[[ Required Shared libraries ]] local testCasesForPolicyAppIdManagament = require("user_modules/shared_testcases/testCasesForPolicyAppIdManagament") local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForBuildingSDLPolicyFlag = require('user_modules/shared_testcases/testCasesForBuildingSDLPolicyFlag') --[[ General Precondition before ATF start ]] testCasesForBuildingSDLPolicyFlag:CheckPolicyFlagAfterBuild("EXTERNAL_PROPRIETARY") commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:UpdatePolicy() testCasesForPolicyAppIdManagament:updatePolicyTable(self, "files/jsons/Policies/App_Permissions/ptu_021.json") end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:SendRPC_AddCommand() local corId = self.mobileSession:SendRPC("AddCommand", {cmdID = 1,menuParams = {menuName = "Options"}, vrCommands = {"Options"} }) verifyResponse(self, corId) end function Test:SendRPC_AddSubMenu() local corId = self.mobileSession:SendRPC("AddSubMenu", {menuID = 1000, position = 500, menuName ="SubMenupositive"}) verifyResponse(self, corId) end function Test:SendRPC_Alert() local corId = self.mobileSession:SendRPC("Alert", {alertText1 = "alertText1"}) verifyResponse(self, corId) end function Test:SendRPC_Show() local corId = self.mobileSession:SendRPC("Show", {mainField1 = "mainField1"}) verifyResponse(self, corId) end function Test:SendRPC_SystemRequest() local corId = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) verifyResponse(self, corId) end function Test:SendRPC_UnregisterAppInterface() local corId = self.mobileSession:SendRPC("UnregisterAppInterface",{}) verifyResponse(self, corId) end return Test
--------------------------------------------------------------------------------------------- -- UNREADY: Only 6 RPCs are covered -- Requirement summary: -- [GeneralResultCodes] DISALLOWED in case app's current HMI Level is not listed in assigned policies -- -- Description: -- SDL must return DISALLOWED resultCode and success = "false" to the RPC requested by the application -- in case Policy Table doesn't contain current application's HMILevel -- defined in Policy Table "functional_groupings" section for a specified RPC -- -- Preconditions: -- 1. Application with <appID> is registered on SDL. -- 2. Current HMILevel for application is HMILevel_1 -- 3. Policy Table contains section "functional_groupings", -- in which for a specified PRC there're defined HMILevels: HMILevel_2, HMILevel_3 -- Steps: -- 1. Send RPC App -> SDL -- 2. Verify status of response -- -- Expected result: -- SDL -> App: RPC (DISALLOWED, success: "false") --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Local Functions ]] local function verifyResponse(test, corId) test.mobileSession:ExpectResponse(corId) :ValidIf(function(_, d) local exp = {success = false, resultCode = "DISALLOWED"} if (d.payload.success == exp.success) and (d.payload.resultCode == exp.resultCode) then return true else return false, "Expected: {success = '" .. tostring(exp.success) .. "', resultCode = '" .. exp.resultCode .. "'}, got: {success = '" .. tostring(d.payload.success) .. "', resultCode = '" .. d.payload.resultCode .. "'}" end end) end --[[ Required Shared libraries ]] local testCasesForPolicyAppIdManagament = require("user_modules/shared_testcases/testCasesForPolicyAppIdManagament") local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForBuildingSDLPolicyFlag = require('user_modules/shared_testcases/testCasesForBuildingSDLPolicyFlag') --[[ General Precondition before ATF start ]] testCasesForBuildingSDLPolicyFlag:CheckPolicyFlagAfterBuild("EXTERNAL_PROPRIETARY") commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:UpdatePolicy() testCasesForPolicyAppIdManagament:updatePolicyTable(self, "files/jsons/Policies/App_Permissions/ptu_021.json") end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:SendRPC_AddCommand() local corId = self.mobileSession:SendRPC("AddCommand", {cmdID = 1,menuParams = {menuName = "Options"}, vrCommands = {"Options"} }) verifyResponse(self, corId) end function Test:SendRPC_AddSubMenu() local corId = self.mobileSession:SendRPC("AddSubMenu", {menuID = 1000, position = 500, menuName ="SubMenupositive"}) verifyResponse(self, corId) end function Test:SendRPC_Alert() local corId = self.mobileSession:SendRPC("Alert", {alertText1 = "alertText1"}) verifyResponse(self, corId) end function Test:SendRPC_Show() local corId = self.mobileSession:SendRPC("Show", {mainField1 = "mainField1"}) verifyResponse(self, corId) end function Test:SendRPC_SystemRequest() local corId = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) verifyResponse(self, corId) end function Test:SendRPC_UnregisterAppInterface() local corId = self.mobileSession:SendRPC("UnregisterAppInterface",{}) verifyResponse(self, corId) end return Test
Fixed description
Fixed description
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
8c08fb6e361178eaf2b2fdbebefcbe17e8c07067
src/lpeg2c/codegen.lua
src/lpeg2c/codegen.lua
local numtab = {} for i = 0, 255 do numtab[string.char(i)] = ("%3d,"):format(i) end local function bin2c(str) str = str .. '\0' return str:gsub(".", numtab):gsub(("."):rep(80), "%0\n") end local function parsePattern(pattern) local lpeg = require 'lpeg' local parse = require 'lpeg2c.parseLpegByteCode' local pattern = lpeg.P(pattern) return parse(pattern) end local function rawYield(text) coroutine.yield(text) end local function yield(text, ...) rawYield(text:format(...) .. '\n') end local function functionName(code) return code.name .. code.offset end local function functionDecl(name) local decl = [[static const char* %s(const char* s, MatchState* mstate)]] return decl:format(name) end local function declareFunctions(codes) for _, code in ipairs(codes) do local name = functionName(code) yield(functionDecl(name) .. ';') end end local functions = {} functions['end'] = function(code) yield('mstate->capture[mstate->captop].kind = Cclose;') yield('mstate->capture[mstate->captop].s = NULL;') yield('return s;') end function functions.giveup(code) yield('return NULL;') end function functions.ret(code) yield('return s;') end function functions.any(code) yield('if (s < mstate->e) {') yield('return %s(s+1, mstate);', functionName(code.next)) yield('} else {') yield('return LPEG2C_FAIL;') yield('}') end function functions.testany(code) yield('if (s < mstate->e) {') yield('return %s(s, mstate);', functionName(code.next)) yield('} else {') yield('return %s(s, mstate);', functionName(code.pointed)) yield('}') end function functions.char(code) yield('if (s < mstate->e && *s == %d) {', code.char:byte()) yield('return %s(s+1, mstate);', functionName(code.next)) yield('} else {') yield('return LPEG2C_FAIL;') yield('}') end function functions.testchar(code) yield('if (s < mstate->e && *s == %d) {', code.char:byte()) yield('return %s(s, mstate);', functionName(code.next)) yield('} else {') yield('return %s(s, mstate);', functionName(code.pointed)) yield('}') end function functions.set(code) yield('if (s < mstate->e && testchar({%s}, *s)) {', bin2c(code.charset)) yield('return %s(s+1, mstate);', functionName(code.next)) yield('} else {') yield('return LPEG2C_FAIL;') yield('}') end function functions.testset(code) yield('if (s < mstate->e && testchar({%s}, *s)) {', bin2c(code.charset)) yield('return %s(s, mstate);', functionName(code.next)) yield('} else {') yield('return %s(s, mstate);', functionName(code.pointed)) yield('}') end function functions.behind(code) yield('if (%d > s - mstate->o) {', code.n) yield('return LPEG2C_FAIL;') yield('} else {') yield('return %s(s-%d, mstate);', functionName(code.next), code.n) yield('}') end function functions.span(code) yield('for (; s < mstate->e; s++) {') yield('if (!testchar({%s}, *s)) {', bin2c(code.charset)) yield('break;') yield('}') yield('}') yield('return %s(s, mstate);', functionName(code.next)) end function functions.jmp(code) yield('return %s(s, mstate);', functionName(code.pointed)) end function functions.choice(code) yield('int captop = mstate->captop;') yield('const char* try1 = %s(s, mstate);', functionName(code.next)) yield('if (try1 == LPEG2C_FAIL) {') yield('mstate->captop = captop;') yield('return %s(s, mstate);', functionName(code.pointed)) yield('} else {') yield('return try1;') yield('}') end function functions.call(code) yield('const char* try1 = %s(s, mstate);', functionName(code.pointed)) yield('if (try1 == LPEG2C_FAIL) {') yield('return LPEG2C_FAIL;') yield('} else {') yield('return %s(try1, mstate);', functionName(code.next)) yield('}') end local function defineFunction(code) local name = functionName(code) local decl = functionDecl(name) yield(decl) yield('{') -- define body local name = code.name local f = assert(functions[name]) f(code) yield('}') end local function defineFunctions(codes) for _, code in ipairs(codes) do defineFunction(code) end end local function defineMatcher(codes) local first = assert(codes[1]) yield('static const char* lpeg2c_match(MatchState* mstate)') yield('{') yield('const char* r = %s(mstate->s, mstate);', functionName(first)) yield('if (r == LPEG2C_FAIL) {') yield('r = NULL;') yield('}') yield('return r;') yield('}') end local function setPointers(codes) for _, code in ipairs(codes) do code.next = codes[_ + 1] end local offset2code = {} for _, code in ipairs(codes) do offset2code[code.offset] = code end for _, code in ipairs(codes) do if code.ref then code.pointed = assert(offset2code[code.ref]) end end end local function generate(pattern) return coroutine.wrap(function() local codes = parsePattern(pattern) setPointers(codes) rawYield(require 'lpeg2c.prologue_c') yield('') declareFunctions(codes) yield('') defineFunctions(codes) yield('') defineMatcher(codes) yield('') rawYield(require 'lpeg2c.epilogue_c') end) end return function(pattern) local t = {} for text in generate(pattern) do table.insert(t, text) end return table.concat(t) end
local numtab = {} for i = 0, 255 do numtab[string.char(i)] = ("%3d,"):format(i) end local function bin2c(str) str = str .. '\0' return str:gsub(".", numtab):gsub(("."):rep(80), "%0\n") end local function parsePattern(pattern) local lpeg = require 'lpeg' local parse = require 'lpeg2c.parseLpegByteCode' local pattern = lpeg.P(pattern) return parse(pattern) end local function rawYield(text) coroutine.yield(text) end local function yield(text, ...) rawYield(text:format(...) .. '\n') end local function functionName(code) return code.name .. code.offset end local function functionDecl(name) local decl = [[static const char* %s(const char* s, MatchState* mstate)]] return decl:format(name) end local function declareFunctions(codes) for _, code in ipairs(codes) do local name = functionName(code) yield(functionDecl(name) .. ';') end end local functions = {} functions['end'] = function(code) yield('mstate->capture[mstate->captop].kind = Cclose;') yield('mstate->capture[mstate->captop].s = NULL;') yield('return s;') end function functions.giveup(code) yield('return NULL;') end function functions.ret(code) yield('return s;') end function functions.any(code) yield('if (s < mstate->e) {') yield('return %s(s+1, mstate);', functionName(code.next)) yield('} else {') yield('return LPEG2C_FAIL;') yield('}') end function functions.testany(code) yield('if (s < mstate->e) {') yield('return %s(s, mstate);', functionName(code.next)) yield('} else {') yield('return %s(s, mstate);', functionName(code.pointed)) yield('}') end function functions.char(code) yield('if (s < mstate->e && *s == %d) {', code.char:byte()) yield('return %s(s+1, mstate);', functionName(code.next)) yield('} else {') yield('return LPEG2C_FAIL;') yield('}') end function functions.testchar(code) yield('if (s < mstate->e && *s == %d) {', code.char:byte()) yield('return %s(s, mstate);', functionName(code.next)) yield('} else {') yield('return %s(s, mstate);', functionName(code.pointed)) yield('}') end function functions.set(code) yield('static const unsigned char B1[]={%s};', bin2c(code.charset)) yield('if (s < mstate->e && testchar(B1, *s)) {') yield('return %s(s+1, mstate);', functionName(code.next)) yield('} else {') yield('return LPEG2C_FAIL;') yield('}') end function functions.testset(code) yield('static const unsigned char B1[]={%s};', bin2c(code.charset)) yield('if (s < mstate->e && testchar(B1, *s)) {', bin2c(code.charset)) yield('return %s(s, mstate);', functionName(code.next)) yield('} else {') yield('return %s(s, mstate);', functionName(code.pointed)) yield('}') end function functions.behind(code) yield('if (%d > s - mstate->o) {', code.n) yield('return LPEG2C_FAIL;') yield('} else {') yield('return %s(s-%d, mstate);', functionName(code.next), code.n) yield('}') end function functions.span(code) yield('static const unsigned char B1[]={%s};', bin2c(code.charset)) yield('for (; s < mstate->e; s++) {') yield('if (!testchar(B1, *s)) {') yield('break;') yield('}') yield('}') yield('return %s(s, mstate);', functionName(code.next)) end function functions.jmp(code) yield('return %s(s, mstate);', functionName(code.pointed)) end function functions.choice(code) yield('int captop = mstate->captop;') yield('const char* try1 = %s(s, mstate);', functionName(code.next)) yield('if (try1 == LPEG2C_FAIL) {') yield('mstate->captop = captop;') yield('return %s(s, mstate);', functionName(code.pointed)) yield('} else {') yield('return try1;') yield('}') end function functions.call(code) yield('const char* try1 = %s(s, mstate);', functionName(code.pointed)) yield('if (try1 == LPEG2C_FAIL) {') yield('return LPEG2C_FAIL;') yield('} else {') yield('return %s(try1, mstate);', functionName(code.next)) yield('}') end local function defineFunction(code) local name = functionName(code) local decl = functionDecl(name) yield(decl) yield('{') -- define body local name = code.name local f = assert(functions[name]) f(code) yield('}') end local function defineFunctions(codes) for _, code in ipairs(codes) do defineFunction(code) end end local function defineMatcher(codes) local first = assert(codes[1]) yield('static const char* lpeg2c_match(MatchState* mstate)') yield('{') yield('const char* r = %s(mstate->s, mstate);', functionName(first)) yield('if (r == LPEG2C_FAIL) {') yield('r = NULL;') yield('}') yield('return r;') yield('}') end local function setPointers(codes) for _, code in ipairs(codes) do code.next = codes[_ + 1] end local offset2code = {} for _, code in ipairs(codes) do offset2code[code.offset] = code end for _, code in ipairs(codes) do if code.ref then code.pointed = assert(offset2code[code.ref]) end end end local function generate(pattern) return coroutine.wrap(function() local codes = parsePattern(pattern) setPointers(codes) rawYield(require 'lpeg2c.prologue_c') yield('') declareFunctions(codes) yield('') defineFunctions(codes) yield('') defineMatcher(codes) yield('') rawYield(require 'lpeg2c.epilogue_c') end) end return function(pattern) local t = {} for text in generate(pattern) do table.insert(t, text) end return table.concat(t) end
fix compilation of charset codes
fix compilation of charset codes
Lua
mit
starius/lpeg2c,starius/lpeg2c,starius/lpeg2c
6ed626fc19a1693bafbf12c8ce5d155d301893da
awesome/aweror.lua
awesome/aweror.lua
-- aweror.lua -- Save this file as "aweror.lua" in awesome's system library directory "/usr/local/share/awesome/lib", -- "/usr/share/awesome/lib", or your own config directory "~/.config/awesome/". -- You will also need a "ror.lua" file (contains your key bindings) in your config directory. -- Now you need to generate and add the keybindings in your ~/.config/awesome/rc.lua -- In the rc.lua file there will be a "root.keys(globalkeys)" command that sets -- your keys, you need to add the following lines just before that command: -- -- local ror = require("aweror") -- globalkeys = awful.util.table.join(globalkeys, ror.genkeys(modkey)) -- get our key bindings from separate ror.lua file require("ror") local awful= require("awful") local client=client local pairs=pairs local table=table local allt1=table5 local print=print local USE_T = true --local USE_T = false local aweror = {} function aweror.run_or_raise(cmd, properties) local clients = client.get() local focused = awful.client.next(0) local findex = 0 local matched_clients = {} local n = 0 for i, c in pairs(clients) do --make an array of matched clients if match(properties, c) then n = n + 1 matched_clients[n] = c if c == focused then findex = n end end end if n > 0 then local c = matched_clients[1] -- if the focused window matched switch focus to next in list if 0 < findex and findex < n then c = matched_clients[findex+1] end local ctags = c:tags() if #ctags == 0 then -- ctags is empty, show client on current tag local curtag = awful.tag.selected() awful.client.movetotag(curtag, c) else -- Otherwise, pop to first tag client is visible on awful.tag.viewonly(ctags[1]) end -- And then focus the client client.focus = c c:raise() return end awful.util.spawn(cmd) end -- Returns true if all pairs in table1 are present in table2 function match (table1, table2) for k, v in pairs(table1) do if table2[k] == nil or (table2[k] ~= v and not table2[k]:find(v)) then return false end end return true end function genfun(t3) local cmd=t3[1] local rule=t3[2] local flag=t3[3] local table1={} s1="class" if flag then s1=flag end table1[s1]=rule return function() aweror.run_or_raise(cmd,table1) end end function aweror.genkeys(mod1) rorkeys = awful.util.table.join() for i,v in pairs(allt1) do modifier="" if i:len() > 1 then modifier=i:sub(1, i:find("-")-1) i=i:sub(-1,-1) end rorkeys = awful.util.table.join(rorkeys, awful.key({ mod1, modifier}, i, genfun(v))) end return rorkeys end return aweror
-- aweror.lua -- Save this file as "aweror.lua" in awesome's system library directory "/usr/local/share/awesome/lib", -- "/usr/share/awesome/lib", or your own config directory "~/.config/awesome/". -- You will also need a "ror.lua" file (contains your key bindings) in your config directory. -- Now you need to generate and add the keybindings in your ~/.config/awesome/rc.lua -- In the rc.lua file there will be a "root.keys(globalkeys)" command that sets -- your keys, you need to add the following lines just before that command: -- -- local ror = require("aweror") -- globalkeys = awful.util.table.join(globalkeys, ror.genkeys(modkey)) -- get our key bindings from separate ror.lua file require("ror") local awful= require("awful") local client=client local pairs=pairs local table=table local allt1=table5 local print=print local USE_T = true --local USE_T = false local aweror = {} function aweror.run_or_raise(cmd, properties) local clients = client.get() local focused = awful.client.next(0) local findex = 0 local matched_clients = {} local n = 0 for i, c in pairs(clients) do --make an array of matched clients if aweror.match(properties, c) then n = n + 1 matched_clients[n] = c if c == focused then findex = n end end end if n > 0 then local c = matched_clients[1] -- if the focused window matched switch focus to next in list if 0 < findex and findex < n then c = matched_clients[findex+1] end local ctags = c:tags() if #ctags == 0 then -- ctags is empty, show client on current tag local curtag = awful.tag.selected() awful.client.movetotag(curtag, c) else -- Otherwise, pop to first tag client is visible on awful.tag.viewonly(ctags[1]) end -- And then focus the client client.focus = c c:raise() return end awful.util.spawn(cmd) end -- Returns true if all pairs in table1 are present in table2 function aweror.match (table1, table2) for k, v in pairs(table1) do if table2[k] == nil or (table2[k] ~= v and not table2[k]:find(v)) then return false end end return true end function genfun(t3) local cmd=t3[1] local rule=t3[2] local flag=t3[3] local table1={} s1="class" if flag then s1=flag end table1[s1]=rule return function() aweror.run_or_raise(cmd,table1) end end function aweror.genkeys(mod1) rorkeys = awful.util.table.join() for i,v in pairs(allt1) do modifier="" if i:len() > 1 then modifier=i:sub(1, i:find("-")-1) i=i:sub(-1,-1) end rorkeys = awful.util.table.join(rorkeys, awful.key({ mod1, modifier}, i, genfun(v))) end return rorkeys end return aweror
fix indentation, namespace bug
fix indentation, namespace bug
Lua
mit
sarumont/xfiles,sarumont/xfiles,sarumont/xfiles,sarumont/xfiles
ebb41b5612cacb95513f41ebc439f60262a54e0a
spec/fs_spec.lua
spec/fs_spec.lua
local fs = require "luacheck.fs" describe("fs", function() describe("is_dir", function() it("returns true for directories", function() assert.is_true(fs.is_dir("spec/folder")) end) it("returns false for files", function() assert.is_false(fs.is_dir("spec/folder/foo")) end) it("returns false for non-existent paths", function() assert.is_false(fs.is_dir("spec/folder/non-existent")) end) end) describe("is_file", function() it("returns true for files", function() assert.is_true(fs.is_file("spec/folder/foo")) end) it("returns false for directories", function() assert.is_false(fs.is_file("spec/folder")) end) it("returns false for non-existent paths", function() assert.is_false(fs.is_file("spec/folder/non-existent")) end) end) describe("extract_files", function() it("returns sorted list of files in a directory matching pattern", function() assert.same({ "spec/folder/folder1/fail", "spec/folder/folder1/file", "spec/folder/foo" }, fs.extract_files("spec/folder", "^f")) end) end) describe("mtime", function() it("returns modification time as a number", function() assert.number(fs.mtime("spec/folder/foo")) end) it("returns nil for non-existent files", function() assert.is_nil(fs.mtime("spec/folder/non-existent")) end) end) describe("current_dir", function() it("returns absolute path to current directory", function() local current_dir = fs.current_dir() assert.string(current_dir) assert.equal("/", current_dir:sub(1, 1)) assert.is_true(fs.is_file(current_dir .. "spec/folder/foo")) end) end) describe("find_file", function() it("finds file in a directory", function() local path = fs.current_dir() .. "spec/folder" assert.equal(path, fs.find_file(path, "foo")) end) it("finds file in a parent directory", function() local path = fs.current_dir() .. "spec/folder" assert.equal(path, fs.find_file(path .. "/folder1", "foo")) end) it("returns nil if can't find file", function() assert.is_nil(fs.find_file(fs.current_dir(), "this file shouldn't exist or it will make luacheck testsuite break")) end) end) end)
local fs = require "luacheck.fs" local P = fs.normalize describe("fs", function() describe("is_dir", function() it("returns true for directories", function() assert.is_true(fs.is_dir("spec/folder")) end) it("returns false for files", function() assert.is_false(fs.is_dir("spec/folder/foo")) end) it("returns false for non-existent paths", function() assert.is_false(fs.is_dir("spec/folder/non-existent")) end) end) describe("is_file", function() it("returns true for files", function() assert.is_true(fs.is_file("spec/folder/foo")) end) it("returns false for directories", function() assert.is_false(fs.is_file("spec/folder")) end) it("returns false for non-existent paths", function() assert.is_false(fs.is_file("spec/folder/non-existent")) end) end) describe("extract_files", function() it("returns sorted list of files in a directory matching pattern", function() assert.same({ P"spec/folder/folder1/fail", P"spec/folder/folder1/file", P"spec/folder/foo" }, fs.extract_files(P"spec/folder", "^f")) end) end) describe("mtime", function() it("returns modification time as a number", function() assert.number(fs.mtime("spec/folder/foo")) end) it("returns nil for non-existent files", function() assert.is_nil(fs.mtime("spec/folder/non-existent")) end) end) describe("current_dir", function() it("returns absolute path to current directory", function() local current_dir = fs.current_dir() assert.string(current_dir) assert.not_equal("", (fs.split_base(current_dir))) assert.is_true(fs.is_file(current_dir .. "spec/folder/foo")) end) end) describe("find_file", function() it("finds file in a directory", function() local path = fs.current_dir() .. P"spec/folder" assert.equal(path, fs.find_file(path, "foo")) end) it("finds file in a parent directory", function() local path = fs.current_dir() .. P"spec/folder" assert.equal(path, fs.find_file(path .. P"/folder1", "foo")) end) it("returns nil if can't find file", function() assert.is_nil(fs.find_file(fs.current_dir(), "this file shouldn't exist or it will make luacheck testsuite break")) end) end) end)
Windows compat fixes for fs tests
Windows compat fixes for fs tests
Lua
mit
mpeterv/luacheck,xpol/luacheck,xpol/luacheck,linuxmaniac/luacheck,xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,linuxmaniac/luacheck
141ef25a738ea24844a18895c3911018294c70cd
lib/switchboard_modules/lua_script_debugger/premade_scripts/advanced_scripts/13_pid_example.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/advanced_scripts/13_pid_example.lua
--[[ Name: 13_pid_example.lua Desc: This script sets a DAC0 output according to a PID controller Note: Requires FW 1.0282 or greater on the T7 Gets a setpoint from a host computer. Host computer writes new setpoint to modbus address 46000 --]] print("This is a PID example script that sets a DAC0 output.") -- timestep of the loop in ms, change according to your process (see theory on -- sampling rate in PID control) local timestep = 2000 local vin = 0 local setpoint = 0 local vout = 0 -- Change the PID terms according to your process local kp = 1 local ki = 0.05 local kd = 0.5 -- Output polarity +1 or -1, i.e. for a positive error, negative output: -1 local polout = 1 -- Bounds for the output value local minout = 0 local maxout = 5 local outputcheck = 0 local lastin = 0 local intterm = 0 local difterm = 0 print("Running PID control on AIN2 with setpoint out at DAC0") -- Configure an interval for the timestep LJ.IntervalConfig(0, timestep) -- First, set the output on the DAC to +5V MB.writeName("DAC0", 5.0) i = 0 while true do -- If a timestep interval is done if LJ.CheckInterval(0) then i = i + 1 -- Read AIN2 as the feedback source vin = MB.readName("AIN2") -- DAC0 connected to AIN0 as well outputcheck = MB.readName("AIN0") -- Get a new setpoint from USER_RAM0_F32 setpoint = MB.readName("USER_RAM0_F32") print("AIN0 = DAC0 = ", outputcheck, "V") print("AIN2 =", vin, "V") intterm = setpoint err = setpoint - vin print("The error is ", err) intterm = intterm + ki * err intterm = intterm * polout if intterm > maxout then intterm = maxout elseif intterm < minout then intterm = minout end print("The Int term is ", intterm) difterm = vin - lastin difterm = polout * difterm print("The Diff term is ", difterm * kd) vout = polout* kp * err + intterm + kd * difterm if vout > maxout then vout = maxout elseif vout < minout then vout = minout end print("The output is ", vout) -- Write vout to DAC0 MB.writeName("DAC0", vout) lastin = vin print("") end end
--[[ Name: 13_pid_example.lua Desc: This is a PID example script that sets a DAC0 output using AIN2 for feedback Note: Gets a setpoint from a host computer. Host computer writes the new setpoint to modbus address 46000 (USER_RAM0_F32) Requires FW 1.0282 or greater on the T7 --]] print("This is a PID example script that sets a DAC0 output using AIN2 for feedback.") print("Write a non-zero value to USER_RAM0_F32 to change the set point.") -- Timestep of the loop in ms. Change according to your process -- (see theory on sampling rate in PID control) local timestep = 100 local setpoint = 0 local vin = 0 local vout = 0 -- Change the PID terms according to your process local kp = 0.1 local ki = 0.1 local kd = 0.01 -- Bounds for the output value local minout = 0 local maxout = 5 local lastin = 0 local intterm = 0 local difterm = 0 -- Configure the timestep interval LJ.IntervalConfig(0, timestep) setpoint = MB.readName("USER_RAM0_F32") if setpoint > maxout then setpoint = maxout MB.writeName("USER_RAM0_F32", setpoint) elseif setpoint < minout then setpoint = minout MB.writeName("USER_RAM0_F32", setpoint) end -- First set the output on the DAC to +3V -- This will allow a user to see the PID loop in action -- on first-run. This needs to be deleted for most -- use cases of a PID loop. MB.writeName("DAC0", 3) local i = 0 while true do -- If an interval is done if LJ.CheckInterval(0) then i = i + 1 -- Get a new setpoint from USER_RAM0_F32 setpoint = MB.readName("USER_RAM0_F32") if setpoint > maxout then setpoint = maxout MB.writeName("USER_RAM0_F32", setpoint) elseif setpoint < minout then setpoint = minout MB.writeName("USER_RAM0_F32", setpoint) end print("Setpoint: ", setpoint) -- Read AIN2 as the feedback source vin = MB.readName("AIN2") print("AIN2 =", vin, "V") err = setpoint - vin print("The error is ", err) intterm = intterm + ki * err -- Limit the integral term if intterm > maxout then intterm = maxout elseif intterm < minout then intterm = minout end print("The Int term is ", intterm) difterm = vin - lastin print("The Diff term is ", difterm) vout = kp * err + intterm - kd * difterm -- Limit the maximum output voltage if vout > maxout then vout = maxout elseif vout < minout then vout = minout end print("The output is ", vout) -- Write the output voltage to DAC0 MB.writeName("DAC0", vout) lastin = vin print("") end end
Fixed up the PID example
Fixed up the PID example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
f332906fd75b2f28c2a477016f6d18bebc531fd7
apicast/src/resty/http_ng.lua
apicast/src/resty/http_ng.lua
------------ --- HTTP NG module -- Implements HTTP client. -- @module http_ng --- HTTP Client -- @type HTTP local type = type local unpack = unpack local assert = assert local tostring = tostring local setmetatable = setmetatable local rawset = rawset local upper = string.upper local rawget = rawget local pack = table.pack local next = next local pairs = pairs local concat = table.concat local resty_backend = require 'resty.http_ng.backend.resty' local json = require 'cjson' local request = require 'resty.http_ng.request' local resty_url = require 'resty.url' local DEFAULT_PATH = '' local http = { request = request } local function merge(...) local all = pack(...) if #all == 1 then return all[next(all)] end local res for i = 1, all.n do local t = all[i] if type(t) == 'table' then res = res or {} for k,v in pairs(t) do res[k] = merge(res[k], v) end elseif type(t) ~= 'nil' then res = t end end return res end local function get_request_params(method, client, url, options) local opts = {} local scheme, user, pass, host, port, path = unpack(assert(resty_url.split(url))) if port then host = concat({host, port}, ':') end opts.headers = { ['Host'] = host } if user or pass then opts.headers.Authorization = "Basic " .. ngx.encode_base64(concat({ user or '', pass or '' }, ':')) end return { url = concat({ scheme, '://', host, path or DEFAULT_PATH }, ''), method = method, options = merge(opts, rawget(client, 'options'), options), client = client, serializer = client.serializer or http.serializers.default } end http.method = function(method, client) assert(method) assert(client) return function(url, options) if type(url) == 'table' and not options then options = url url = unpack(url) end assert(url, 'url as first parameter is required') local req_params = get_request_params(method, client, url, options) local req = http.request.new(req_params) return client.backend.send(req) end end http.method_with_body = function(method, client) assert(method) assert(client) return function(url, body, options) if type(url) == 'table' and not body and not options then options = url url, body = unpack(url) end assert(url, 'url as first parameter is required') assert(body, 'body as second parameter is required') local req_params = get_request_params(method, client, url, options) req_params.body = body local req = http.request.new(req_params) return client.backend.send(req) end end --- Make GET request. -- @param[type=string] url -- @param[type=options] options -- @return[type=response] a response -- @function http.get http.GET = http.method --- Make HEAD request. -- @param[type=string] url -- @param[type=options] options -- @return[type=response] a response -- @function http.head http.HEAD = http.method --- Make DELETE request. -- @param[type=string] url -- @param[type=options] options -- @return[type=response] a response -- @function http.delete http.DELETE = http.method --- Make OPTIONS request. -- @param[type=string] url -- @param[type=options] options -- @return[type=response] a response -- @function http.options http.OPTIONS = http.method --- Make PUT request. -- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer. -- @param[type=string] url -- @param[type=string|table] body -- @param[type=options] options -- @return[type=response] a response -- @function http.put http.PUT = http.method_with_body --- Make POST request. -- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer. -- @param[type=string] url -- @param[type=string|table] body -- @param[type=options] options -- @return[type=response] a response -- @function http.post http.POST = http.method_with_body --- Make PATCH request. -- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer. -- @param[type=string] url -- @param[type=string|table] body -- @param[type=options] options -- @return[type=response] a response -- @function http.patch http.PATCH = http.method_with_body http.TRACE = http.method_with_body http.serializers = {} --- Urlencoded serializer -- Serializes your data to `application/x-www-form-urlencoded` format -- and sets correct Content-Type header. -- @http HTTP.urlencoded -- @usage http.urlencoded.post(url, { example = 'table' }) http.serializers.urlencoded = function(req) req.body = ngx.encode_args(req.body) req.headers.content_type = req.headers.content_type or 'application/x-www-form-urlencoded' http.serializers.string(req) end http.serializers.string = function(req) req.body = tostring(req.body) req.headers['Content-Length'] = #req.body end --- JSON serializer -- Converts the body to JSON unless it is already a string -- and sets correct Content-Type `application/json`. -- @http HTTP.json -- @usage http.json.post(url, { example = 'table' }) -- @see http.post http.serializers.json = function(req) if type(req.body) ~= 'string' then req.body = json.encode(req.body) end req.headers.content_type = req.headers.content_type or 'application/json' http.serializers.string(req) end http.serializers.default = function(req) if req.body then if type(req.body) ~= 'string' then http.serializers.urlencoded(req) else http.serializers.string(req) end end end local function add_http_method(client, method) local m = upper(method) local cached = rawget(client, m) if cached then return cached end local generator = http[m] if generator then local func = generator(m, client) rawset(client, m, func) return func end end local function chain_serializer(client, format) local serializer = http.serializers[format] if serializer then return http.new{ backend = client.backend, serializer = serializer } end end local function generate_client_method(client, method_or_format) return add_http_method(client, method_or_format) or chain_serializer(client, method_or_format) end function http.new(client) client = client or { } client.backend = client.backend or resty_backend return setmetatable(client, { __index = generate_client_method }) end return http
------------ --- HTTP NG module -- Implements HTTP client. -- @module http_ng --- HTTP Client -- @type HTTP local type = type local unpack = unpack local assert = assert local tostring = tostring local setmetatable = setmetatable local getmetatable = getmetatable local rawset = rawset local upper = string.upper local rawget = rawget local pack = table.pack local next = next local pairs = pairs local concat = table.concat local resty_backend = require 'resty.http_ng.backend.resty' local json = require 'cjson' local request = require 'resty.http_ng.request' local resty_url = require 'resty.url' local http_headers = require 'resty.http_ng.headers' local DEFAULT_PATH = '' local http = { request = request } local function merge(...) local all = pack(...) if #all == 1 then return all[next(all)] end local res for i = 1, all.n do local t = all[i] if type(t) == 'table' then res = res or setmetatable({}, getmetatable(t)) for k,v in pairs(t) do res[k] = merge(res[k], v) end elseif type(t) ~= 'nil' then res = t end end return res end local function get_request_params(method, client, url, options) local opts = {} local scheme, user, pass, host, port, path = unpack(assert(resty_url.split(url))) if port then host = concat({host, port}, ':') end opts.headers = http_headers.new() opts.headers.host = host if user or pass then opts.headers.authorization = "Basic " .. ngx.encode_base64(concat({ user or '', pass or '' }, ':')) end return { url = concat({ scheme, '://', host, path or DEFAULT_PATH }, ''), method = method, options = merge(opts, rawget(client, 'options'), options), client = client, serializer = client.serializer or http.serializers.default } end http.method = function(method, client) assert(method) assert(client) return function(url, options) if type(url) == 'table' and not options then options = url url = unpack(url) end assert(url, 'url as first parameter is required') local req_params = get_request_params(method, client, url, options) local req = http.request.new(req_params) return client.backend.send(req) end end http.method_with_body = function(method, client) assert(method) assert(client) return function(url, body, options) if type(url) == 'table' and not body and not options then options = url url, body = unpack(url) end assert(url, 'url as first parameter is required') assert(body, 'body as second parameter is required') local req_params = get_request_params(method, client, url, options) req_params.body = body local req = http.request.new(req_params) return client.backend.send(req) end end --- Make GET request. -- @param[type=string] url -- @param[type=options] options -- @return[type=response] a response -- @function http.get http.GET = http.method --- Make HEAD request. -- @param[type=string] url -- @param[type=options] options -- @return[type=response] a response -- @function http.head http.HEAD = http.method --- Make DELETE request. -- @param[type=string] url -- @param[type=options] options -- @return[type=response] a response -- @function http.delete http.DELETE = http.method --- Make OPTIONS request. -- @param[type=string] url -- @param[type=options] options -- @return[type=response] a response -- @function http.options http.OPTIONS = http.method --- Make PUT request. -- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer. -- @param[type=string] url -- @param[type=string|table] body -- @param[type=options] options -- @return[type=response] a response -- @function http.put http.PUT = http.method_with_body --- Make POST request. -- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer. -- @param[type=string] url -- @param[type=string|table] body -- @param[type=options] options -- @return[type=response] a response -- @function http.post http.POST = http.method_with_body --- Make PATCH request. -- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer. -- @param[type=string] url -- @param[type=string|table] body -- @param[type=options] options -- @return[type=response] a response -- @function http.patch http.PATCH = http.method_with_body http.TRACE = http.method_with_body http.serializers = {} --- Urlencoded serializer -- Serializes your data to `application/x-www-form-urlencoded` format -- and sets correct Content-Type header. -- @http HTTP.urlencoded -- @usage http.urlencoded.post(url, { example = 'table' }) http.serializers.urlencoded = function(req) req.body = ngx.encode_args(req.body) req.headers.content_type = req.headers.content_type or 'application/x-www-form-urlencoded' http.serializers.string(req) end http.serializers.string = function(req) req.body = tostring(req.body) req.headers['Content-Length'] = #req.body end --- JSON serializer -- Converts the body to JSON unless it is already a string -- and sets correct Content-Type `application/json`. -- @http HTTP.json -- @usage http.json.post(url, { example = 'table' }) -- @see http.post http.serializers.json = function(req) if type(req.body) ~= 'string' then req.body = json.encode(req.body) end req.headers.content_type = req.headers.content_type or 'application/json' http.serializers.string(req) end http.serializers.default = function(req) if req.body then if type(req.body) ~= 'string' then http.serializers.urlencoded(req) else http.serializers.string(req) end end end local function add_http_method(client, method) local m = upper(method) local cached = rawget(client, m) if cached then return cached end local generator = http[m] if generator then local func = generator(m, client) rawset(client, m, func) return func end end local function chain_serializer(client, format) local serializer = http.serializers[format] if serializer then return http.new{ backend = client.backend, serializer = serializer } end end local function generate_client_method(client, method_or_format) return add_http_method(client, method_or_format) or chain_serializer(client, method_or_format) end function http.new(client) client = client or { } client.backend = client.backend or resty_backend return setmetatable(client, { __index = generate_client_method }) end return http
[http] fix merging options on openresty 1.11.2.3
[http] fix merging options on openresty 1.11.2.3
Lua
mit
3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/apicast,3scale/apicast,3scale/docker-gateway
3d73bd93a62f54cafb8a963ffffa1906f9064e7e
src/items/recipes.lua
src/items/recipes.lua
----------------------------------------- -- recipes.lua -- Contains all the crafting recipies that the player can use -- Created by HazardousPeach ----------------------------------------- return { { { type='material', name='rock' }, { type='material', name='stick' }, { type='weapon', name='throwingknife' } }, { { type='material', name='rock' }, { type='material', name='rock' }, { type='weapon', name='mace' } }, { { type='material', name='leaf' }, { type='material', name='leaf' }, { type='weapon', name='torch' } }, { { type='material', name='stick' }, { type='material', name='stick' }, { type='weapon', name='sword' } }, { { type='material', name='leaf' }, { type='material', name='rock' }, { type='weapon', name='mallet' } }, }
----------------------------------------- -- recipes.lua -- Contains all the crafting recipies that the player can use -- Created by HazardousPeach ----------------------------------------- return { { { type='material', name='rock' }, { type='material', name='stick' }, { type='weapon', name='throwingknife' } }, { { type='material', name='rock' }, { type='material', name='rock' }, { type='weapon', name='mace' } }, { { type='material', name='leaf' }, { type='material', name='leaf' }, { type='weapon', name='torch' } }, { { type='material', name='stick' }, { type='material', name='stick' }, { type='weapon', name='sword' } }, { { type='material', name='leaf' }, { type='material', name='rock' }, { type='weapon', name='mallet' } }, }
fixed master discrepancy
fixed master discrepancy
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua
18dd214b488da0a20187ce6857bfe7d8ed2cfaf7
lua/starfall/libs_sh/vmatrix.lua
lua/starfall/libs_sh/vmatrix.lua
-- Credits to Radon & Xandaros SF.VMatrix = {} --- VMatrix type local vmatrix_methods, vmatrix_metamethods = SF.Typedef("VMatrix") local wrap, unwrap = SF.CreateWrapper( vmatrix_metamethods, true, false ) local vunwrap = SF.UnwrapObject SF.VMatrix.Methods = vmatrix_methods SF.VMatrix.Metatable = vmatrix_metamethods SF.VMatrix.Wrap = wrap SF.VMatrix.Unwrap = unwrap --- Returns a new VMatrix -- @return New VMatrix SF.DefaultEnvironment.Matrix = function() return wrap(Matrix()) end --- Returns angles -- @return Angles function vmatrix_methods:getAngles() return SF.WrapObject( unwrap( self ):GetAngles() ) end --- Returns scale -- @return Scale function vmatrix_methods:getScale() return unwrap(self):GetScale() end --- Returns translation -- @return Translation function vmatrix_methods:getTranslation() return unwrap(self):GetTranslation() end --- Rotate the matrix -- @param ang Angle to rotate by function vmatrix_methods:rotate( ang ) SF.CheckType( ang, SF.Types[ "Angle" ] ) local v = unwrap(self) v:Rotate( SF.WrapObject( ang ) ) end --- Scale the matrix -- @param vec Vector to scale by function vmatrix_methods:scale ( vec ) SF.CheckType( vec, SF.Type[ "Vector" ] ) local vec = vunwrap( vec ) local v = unwrap( self ) v:Scale( vec ) end --- Scales the absolute translation -- @param num Amount to scale by function vmatrix_methods:scaleTranslation ( num ) SF.CheckType( num, "Number" ) local v = unwrap( self ) v:ScaleTranslation( num ) end --- Sets the angles -- @param ang New angles function vmatrix_methods:setAngles( ang ) SF.CheckType( ang, SF.Types[ "Angle" ] ) local v = unwrap(self) v:SetAngles( SF.WrapObject( ang ) ) end --- Sets the translation -- @param vec New translation function vmatrix_methods:setTranslation ( vec ) SF.CheckType( vec, SF.Types[ "Vector" ] ) local vec = vunwrap( vec ) local v = unwrap(self) v:SetTranslation( vec ) end --- Translate the matrix -- @param vec Vector to translate by function vmatrix_methods:translate ( vec ) SF.CheckType( vec, SF.Types[ "Vector" ] ) local vec = vunwrap( vec ) local v = unwrap( self ) v:Translate( vec ) end function vmatrix_metamethods.__mul( lhs, rhs ) SF.CheckType( rhs, vmatrix_metamethods ) return wrap(unwrap(lhs) * unwrap(rhs)) end
-- Credits to Radon & Xandaros SF.VMatrix = {} --- VMatrix type local vmatrix_methods, vmatrix_metamethods = SF.Typedef( "VMatrix" ) local wrap, unwrap = SF.CreateWrapper( vmatrix_metamethods, true, false ) local vunwrap = SF.UnwrapObject SF.VMatrix.Methods = vmatrix_methods SF.VMatrix.Metatable = vmatrix_metamethods SF.VMatrix.Wrap = wrap SF.VMatrix.Unwrap = unwrap --- Returns a new VMatrix -- @return New VMatrix SF.DefaultEnvironment.Matrix = function () return wrap( Matrix() ) end --- Returns angles -- @return Angles function vmatrix_methods:getAngles () return SF.WrapObject( unwrap( self ):GetAngles() ) end --- Returns scale -- @return Scale function vmatrix_methods:getScale () return SF.WrapObject( unwrap( self ):GetScale() ) end --- Returns translation -- @return Translation function vmatrix_methods:getTranslation () return SF.WrapObject( unwrap( self ):GetTranslation() ) end --- Rotate the matrix -- @param ang Angle to rotate by function vmatrix_methods:rotate ( ang ) SF.CheckType( ang, SF.Types[ "Angle" ] ) local v = unwrap( self ) v:Rotate( SF.UnwrapObject( ang ) ) end --- Scale the matrix -- @param vec Vector to scale by function vmatrix_methods:scale ( vec ) SF.CheckType( vec, SF.Types[ "Vector" ] ) local vec = vunwrap( vec ) local v = unwrap( self ) v:Scale( vec ) end --- Scales the absolute translation -- @param num Amount to scale by function vmatrix_methods:scaleTranslation ( num ) SF.CheckType( num, "Number" ) local v = unwrap( self ) v:ScaleTranslation( num ) end --- Sets the angles -- @param ang New angles function vmatrix_methods:setAngles ( ang ) SF.CheckType( ang, SF.Types[ "Angle" ] ) local v = unwrap( self ) v:SetAngles( SF.UnwrapObject( ang ) ) end --- Sets the translation -- @param vec New translation function vmatrix_methods:setTranslation ( vec ) SF.CheckType( vec, SF.Types[ "Vector" ] ) local vec = vunwrap( vec ) local v = unwrap( self ) v:SetTranslation( vec ) end --- Translate the matrix -- @param vec Vector to translate by function vmatrix_methods:translate ( vec ) SF.CheckType( vec, SF.Types[ "Vector" ] ) local vec = vunwrap( vec ) local v = unwrap( self ) v:Translate( vec ) end function vmatrix_metamethods.__mul ( lhs, rhs ) SF.CheckType( rhs, vmatrix_metamethods ) return wrap( unwrap( lhs ) * unwrap( rhs ) ) end
Fixed some issues with vmatrix vec/ang type
Fixed some issues with vmatrix vec/ang type Also fixed some codestyle in VMatrix.
Lua
bsd-3-clause
Jazzelhawk/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,INPStarfall/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall
cf544183b4235355377fc17e31627b431467ef06
kong/plugins/acl/migrations/001_14_to_15.lua
kong/plugins/acl/migrations/001_14_to_15.lua
return { postgres = { up = [[ DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "acls" ADD "cache_key" TEXT UNIQUE; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; ALTER TABLE IF EXISTS ONLY "acls" ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC', ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'; DO $$ BEGIN ALTER INDEX IF EXISTS "acls_consumer_id" RENAME TO "acls_consumer_id_idx"; EXCEPTION WHEN DUPLICATE_TABLE THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER INDEX IF EXISTS "acls_group" RENAME TO "acls_group_idx"; EXCEPTION WHEN DUPLICATE_TABLE THEN -- Do nothing, accept existing state END; $$; ]], teardown = function(connector, helpers) assert(connector:connect_migrations()) for rows, err in connector:iterate('SELECT * FROM "acls" ORDER BY "created_at";') do if err then return nil, err end for i = 1, #rows do local row = rows[i] local cache_key = string.format("%s:%s:%s:::", "acls", row.consumer_id or "", row.group or "") local sql = string.format([[ UPDATE "acls" SET "cache_key" = '%s' WHERE "id" = '%s'; ]], cache_key, row.id) assert(connector:query(sql)) end end end, }, cassandra = { up = [[ ALTER TABLE acls ADD cache_key text; CREATE INDEX IF NOT EXISTS acls_cache_key_idx ON acls(cache_key); ]], teardown = function(connector, helpers) local coordinator = assert(connector:connect_migrations()) for rows, err in coordinator:iterate("SELECT * FROM acls") do if err then return nil, err end for i = 1, #rows do local row = rows[i] local cache_key = string.format("%s:%s:%s:::", "acls", row.consumer_id or "", row.group or "") local cql = string.format([[ UPDATE acls SET cache_key = '%s' WHERE id = '%s' ]], cache_key, row.id) assert(connector:query(cql)) end end end, }, }
return { postgres = { up = [[ DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "acls" ADD "cache_key" TEXT UNIQUE; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; ALTER TABLE IF EXISTS ONLY "acls" ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC', ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'; DO $$ BEGIN ALTER INDEX IF EXISTS "acls_consumer_id" RENAME TO "acls_consumer_id_idx"; EXCEPTION WHEN DUPLICATE_TABLE THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER INDEX IF EXISTS "acls_group" RENAME TO "acls_group_idx"; EXCEPTION WHEN DUPLICATE_TABLE THEN -- Do nothing, accept existing state END; $$; ]], teardown = function(connector, helpers) assert(connector:connect_migrations()) for rows, err in connector:iterate('SELECT * FROM "acls" ORDER BY "created_at";') do if err then return nil, err end for i = 1, #rows do local row = rows[i] local cache_key = string.format("%s:%s:%s:::", "acls", row.consumer_id or "", row.group or "") local sql = string.format([[ UPDATE "acls" SET "cache_key" = '%s' WHERE "id" = '%s'; ]], cache_key, row.id) assert(connector:query(sql)) end end end, }, cassandra = { up = [[ ALTER TABLE acls ADD cache_key text; CREATE INDEX IF NOT EXISTS acls_cache_key_idx ON acls(cache_key); ]], teardown = function(connector, helpers) local cassandra = require "cassandra" local coordinator = assert(connector:connect_migrations()) for rows, err in coordinator:iterate("SELECT * FROM acls") do if err then return nil, err end for i = 1, #rows do local row = rows[i] local cache_key = string.format("%s:%s:%s:::", "acls", row.consumer_id or "", row.group or "") assert(connector:query("UPDATE acls SET cache_key = ? WHERE id = ?", { cache_key, cassandra.uuid(row.id), })) end end end, }, }
fix(acl) prevent 014_to_015 migration from throwing an error
fix(acl) prevent 014_to_015 migration from throwing an error The `id` column is a UUID, but given as a string, producing the error: [Cassandra error] failed to run migration '001_14_to_15' teardown: ...are/lua/5.1/kong/plugins/acl/migrations/001_14_to_15.lua:81: [Invalid] Invalid STRING constant (c8b871b7-7a18-45a9-9cd3-aa0a78c6073d) for "id" of type uuid See #3924 From #3953
Lua
apache-2.0
Kong/kong,Mashape/kong,Kong/kong,Kong/kong
311e7f2c3154f4f6d289674d537fc341d80ee1bd
src/api/libraries.lua
src/api/libraries.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] zpm.api.libraries = { export = {}, global = {} } function zpm.api.libraries.default(env, package) for name, func in pairs(premake.field._list) do if not env[name] then if name:contains("command") then env[name] = function(command) local c = function() _G[name](command) end local no = function() warningf("Command not accepted, build may not work properly!") end zpm.cli.askConfirmation(("Allow usage of command '%s'"):format(command), c, no) end else if func.kind == "list:directory" or func.kind == "list:file" then env[name] = function(...) local args = ... if type(args) ~= "table" then args = { args } end for i, dir in ipairs(args) do args[i] = path.join(package.location, dir) end _G[name](args) end if _G["remove" .. name] ~= nil then env["remove" .. name] = function(...) local args = ... if type(args) ~= "table" then args = { args } end for i, dir in ipairs(args) do args[i] = path.join(package.location, dir) end _G["remove" .. name](args) end end else env[name] = function(...) _G[name](...) end if _G["remove" .. name] ~= nil then env["remove" .. name] = function(...) _G["remove" .. name](...) end end end end end end end function zpm.api.libraries.global.project(package) return function(name) local version = iif(package.version == nil, package.tag, package.version) local alias = string.format("%s-%s-%s", name, version, string.sha1(package.name):sub(0,5)) project(alias) filename(name) zpm.util.setTable(package, {"aliases", name}, alias) location(path.join(package.location, ".zpm" )) targetdir(path.join(package.bindir, package.name)) objdir(path.join(package.objdir, package.name)) targetname(name) warnings "Off" -- make sure we can actually 'compile' header only libraries -- (lame I know) if not os.isdir(path.join(package.location, ".zpm")) then os.mkdir(path.join(package.location, ".zpm")) end local ignore = path.join(package.location, ".zpm/.gitignore") if not os.isfile(ignore) then os.writefile_ifnotequal("*", ignore) end local dummyFile = path.join(package.location, ".zpm/dummy.cpp") os.writefile_ifnotequal(("void Dummy%s(){ return; }"):format(string.sha1(dummyFile)), dummyFile) files(dummyFile) end end function zpm.api.libraries.global.links(package) return function(libraries) local fltr = table.deepcopy(zpm.meta.filter) local found = true if type(libraries) ~= "table" then libraries = {libraries} end for _, library in ipairs(libraries) do zpm.util.setTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "links", library}, fltr) end end end function zpm.api.libraries.global.filter(package) return filter end function zpm.api.libraries.export.uses(package) return zpm.uses end function zpm.api.libraries.export.has(package) return zpm.has end function zpm.api.libraries.export.setting(package) return zpm.setting end function zpm.api.libraries.export.configuration(package) return zpm.configuration end function zpm.api.libraries.export.export(package) return zpm.export end
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] zpm.api.libraries = { export = {}, global = {} } function zpm.api.libraries.default(env, package) for name, func in pairs(premake.field._list) do if not env[name] then if name:contains("command") then env[name] = function(command) local c = function() _G[name](command) end local no = function() warningf("Command not accepted, build may not work properly!") end zpm.cli.askConfirmation(("Allow usage of command '%s'"):format(command), c, no) end else if func.kind == "list:directory" or func.kind == "list:file" then env[name] = function(...) local args = ... if type(args) ~= "table" then args = { args } end for i, dir in ipairs(args) do args[i] = path.join(package.location, dir) end _G[name](args) end if _G["remove" .. name] ~= nil then env["remove" .. name] = function(...) local args = ... if type(args) ~= "table" then args = { args } end for i, dir in ipairs(args) do args[i] = path.join(package.location, dir) end _G["remove" .. name](args) end end else env[name] = function(...) _G[name](...) end if _G["remove" .. name] ~= nil then env["remove" .. name] = function(...) _G["remove" .. name](...) end end end end end end end function zpm.api.libraries.global.project(package) return function(name) local version = iif(package.version == nil, package.tag, package.version) local alias = string.format("%s-%s-%s", name, version, string.sha1(package.name):sub(0,5)) project(alias) filename(name) zpm.util.setTable(package, {"aliases", name}, alias) location(path.join(package.location, ".zpm" )) targetdir(package.bindir) objdir(package.objdir) targetname(name) warnings "Off" -- make sure we can actually 'compile' header only libraries -- (lame I know) if not os.isdir(path.join(package.location, ".zpm")) then os.mkdir(path.join(package.location, ".zpm")) end local ignore = path.join(package.location, ".zpm/.gitignore") if not os.isfile(ignore) then os.writefile_ifnotequal("*", ignore) end local dummyFile = path.join(package.location, ".zpm/dummy.cpp") os.writefile_ifnotequal(("void Dummy%s(){ return; }"):format(string.sha1(dummyFile)), dummyFile) files(dummyFile) end end function zpm.api.libraries.global.links(package) return function(libraries) local fltr = table.deepcopy(zpm.meta.filter) local found = true if type(libraries) ~= "table" then libraries = {libraries} end for _, library in ipairs(libraries) do zpm.util.setTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "links", library}, fltr) end end end function zpm.api.libraries.global.filter(package) return filter end function zpm.api.libraries.export.uses(package) return zpm.uses end function zpm.api.libraries.export.has(package) return zpm.has end function zpm.api.libraries.export.setting(package) return zpm.setting end function zpm.api.libraries.export.configuration(package) return zpm.configuration end function zpm.api.libraries.export.export(package) return zpm.export end
Fix the twice package name in target dir
Fix the twice package name in target dir
Lua
mit
Zefiros-Software/ZPM
28f70289ee9a98348b6183f5214b45087937ad22
core/loader.lua
core/loader.lua
-- Copyright (C) Dejiang Zhu (doujiang24) local corehelper = require "system.helper.core" local filehelper = require "system.helper.file" local ltp = require "system.library.ltp.template" local setmetatable = setmetatable local pcall = pcall local assert = assert local loadfile = loadfile local type = type local setfenv = setfenv local concat = table.concat local show_error = corehelper.show_error local get_instance = get_instance local fexists = filehelper.exists local fread_all = filehelper.read_all local ltp_load = ltp.load_template local ltp_execute = ltp.execute_template local _G = _G local cache_module = {} local _M = { _VERSION = '0.01' } local mt = { __index = _M } function _M.new(self) local dp = get_instance() local m = { APPNAME = dp.APPNAME, APPPATH = dp.APPPATH, } return setmetatable(m, mt) end local function _get_cache(appname, module) return cache_module[appname] and cache_module[appname][module] end local function _set_cache(appname, name, val) if not cache_module[appname] then cache_module[appname] = {} end cache_module[appname][name] = val end local function _load_module(self, dir, name) local appname = self.APPNAME local file = dir .. "." .. name local cache = _get_cache(appname, file) if cache == nil then local ok, module = pcall(require, appname .. "." .. file) if not ok then -- get_instance().debug:log_debug('failed to load: ', file, ' err: ', module) end _set_cache(self, file, module or false) return module end return cache end function _M.core(self, cr) return _load_module(self, "core", cr) end function _M.controller(self, contr) return _load_module(self, "controller", contr) end function _M.model(self, mod, ...) local m = _load_module(self, "model", mod) return m and type(m.new) == "function" and m:new(...) or m end function _M.config(self, conf) return _load_module(self, "config", conf) end function _M.library(self, lib) return _load_module(self, "library", lib) end local function _ltp_function(self, tpl) local appname = self.APPNAME local cache = _get_cache(appname, tpl) if cache == nil then local tplfun = false local filename = self.APPPATH .. tpl if fexists(filename) then local fdata = fread_all(filename) tplfun = ltp_load(fdata, '<?lua','?>') else show_error("failed to load tpl:", filename) end _set_cache(appname, tpl, tplfun) return tplfun end return cache end function _M.view(self, tpl, data) local template, data = "views/" .. tpl .. ".tpl", data or {} local tplfun = _ltp_function(self, template) local output = {} setmetatable(data, { __index = _G }) ltp_execute(tplfun, data, output) return output end return _M
-- Copyright (C) Dejiang Zhu (doujiang24) local corehelper = require "system.helper.core" local filehelper = require "system.helper.file" local ltp = require "system.library.ltp.template" local setmetatable = setmetatable local pcall = pcall local assert = assert local loadfile = loadfile local type = type local setfenv = setfenv local concat = table.concat local show_error = corehelper.show_error local get_instance = get_instance local fexists = filehelper.exists local fread_all = filehelper.read_all local ltp_load = ltp.load_template local ltp_execute = ltp.execute_template local _G = _G local cache_module = {} local _M = { _VERSION = '0.01' } local mt = { __index = _M } function _M.new(self) local dp = get_instance() local m = { APPNAME = dp.APPNAME, APPPATH = dp.APPPATH, } return setmetatable(m, mt) end local function _get_cache(appname, module) return cache_module[appname] and cache_module[appname][module] end local function _set_cache(appname, name, val) if not cache_module[appname] then cache_module[appname] = {} end cache_module[appname][name] = val end local function _load_module(self, dir, name) local appname = self.APPNAME local file = dir .. "." .. name local cache = _get_cache(appname, file) if cache == nil then local ok, module = pcall(require, appname .. "." .. file) if not ok then -- get_instance().debug:log_debug('failed to load: ', file, ' err: ', module) end _set_cache(self, file, module or false) return module end return cache end function _M.core(self, cr) return _load_module(self, "core", cr) end function _M.controller(self, contr) return _load_module(self, "controller", contr) end function _M.model(self, mod, ...) local m = _load_module(self, "model", mod) if m and type(m.new) == "function" then return m:new(...) end return m end function _M.config(self, conf) return _load_module(self, "config", conf) end function _M.library(self, lib) return _load_module(self, "library", lib) end local function _ltp_function(self, tpl) local appname = self.APPNAME local cache = _get_cache(appname, tpl) if cache == nil then local tplfun = false local filename = self.APPPATH .. tpl if fexists(filename) then local fdata = fread_all(filename) tplfun = ltp_load(fdata, '<?lua','?>') else show_error("failed to load tpl:", filename) end _set_cache(appname, tpl, tplfun) return tplfun end return cache end function _M.view(self, tpl, data) local template, data = "views/" .. tpl .. ".tpl", data or {} local tplfun = _ltp_function(self, template) local output = {} setmetatable(data, { __index = _G }) ltp_execute(tplfun, data, output) return output end return _M
bugfix: load:model return m when model:new return nil
bugfix: load:model return m when model:new return nil
Lua
mit
doujiang24/durap-system
120218dcddfcb4b8db358346d7adaa6760f25c4d
sys/lua/warmod/modules/core/stats.lua
sys/lua/warmod/modules/core/stats.lua
--[[--------------------------------------------------------------------------- Warmod Project Dev(s): x[N]ir, Hajt, BCG2000 File: modules/core/stats.lua Description: player stats tracker --]]--------------------------------------------------------------------------- warmod.dmg = {} warmod.total_dmg = {} function warmod.reset_mvp(all) local team_a = warmod.team_a local team_b = warmod.team_b -- This way I'm checking the boolean only once -- Not on every player since this value can't change if all then for i = 1, #team_a do local id = team_a[i] if player(id, "exists") then warmod.dmg[id] = 0 warmod.total_dmg[id] = 0 end end for i = 1, #team_b do local id = team_b[i] if player(id, "exists") then warmod.dmg[id] = 0 warmod.total_dmg[id] = 0 end end else for i = 1, #team_a do local id = team_a[i] if player(id, "exists") then warmod.dmg[id] = 0 end end for i = 1, #team_b do local id = team_b[i] if player(id, "exists") then warmod.dmg[id] = 0 end end end end function warmod.display_mvp() local max_dmg, mvp for id, dmg in pairs(warmod.dmg) do if dmg > 0 and (not max_dmg or dmg > max_dmg) then mvp = id max_dmg = dmg end end if not mvp then return end msg("\169255255255[DMG] MVP " .. player(mvp, "name") .. " with " .. max_dmg .. " HP") local players = player(0, "table") for k, id in pairs(players) do if player(id, "team") > 0 then warmod.total_dmg[id] = warmod.total_dmg[id] + warmod.dmg[id] msg2(id, "\169255255255[DMG] This round: " .. warmod.dmg[id] .. " HP") msg2(id, "\169255255255[DMG] Total: " .. warmod.total_dmg[id] .. " HP") end end end
--[[--------------------------------------------------------------------------- Warmod Project Dev(s): x[N]ir, Hajt, BCG2000 File: modules/core/stats.lua Description: player stats tracker --]]--------------------------------------------------------------------------- -- MVP Variables warmod.dmg = {} warmod.total_dmg = {} -- Mix Stats warmod.kills = {} warmod.bomb_plants = {} warmod.bomb_defusals = {} warmod.double_kills = {} warmod.triple_kills = {} warmod.quadra_kills = {} warmod.penta_kills = {} function warmod.reset_mvp(all) local players = player(0, "table") -- This way I'm checking the boolean only once -- Not on every player since this value can't change if all then for k, v in pairs(players) do warmod.dmg[id] = 0 warmod.total_dmg[id] = 0 end else for k, v in pairs(players) do warmod.dmg[id] = 0 end end end function warmod.display_mvp() local max_dmg, mvp for id, dmg in pairs(warmod.dmg) do if dmg > 0 and (not max_dmg or dmg > max_dmg) then mvp = id max_dmg = dmg end end if not mvp then return end msg("\169255255255[DMG] MVP " .. player(mvp, "name") .. " with " .. max_dmg .. " HP") local players = player(0, "table") for k, id in pairs(players) do if player(id, "team") > 0 then warmod.total_dmg[id] = warmod.total_dmg[id] + warmod.dmg[id] msg2(id, "\169255255255[DMG] This round: " .. warmod.dmg[id] .. " HP") msg2(id, "\169255255255[DMG] Total: " .. warmod.total_dmg[id] .. " HP") end end end
Fixed MVP
Fixed MVP
Lua
apache-2.0
codneutro/warmod
1e2b5a8b7dce3d5e4281844a1d8878bb196d2f4e
test/bench.lua
test/bench.lua
local gumbo = require "gumbo" local parse = gumbo.parse local open, write, stderr = io.open, io.write, io.stderr local clock, assert, collectgarbage = os.clock, assert, collectgarbage local filename = assert(arg[1], "arg[1] is nil; expecting filename") local _ENV = nil local document, duration collectgarbage() local basemem = collectgarbage("count") do local file = assert(open(filename)) local text = assert(file:read("*a")) file:close() stderr:write("Parsing ", filename, "...\n") local start_time = clock() document = parse(text) local stop_time = clock() assert(document and document.body) duration = stop_time - start_time end collectgarbage() local memory = collectgarbage("count") - basemem write(("Parse time: %.2fs\nLua memory usage: %dKB\n"):format(duration, memory))
local gumbo = require "gumbo" local parse = assert(gumbo.parse) local open, write, stderr = io.open, io.write, io.stderr local clock, assert, collectgarbage = os.clock, assert, collectgarbage local filename = assert(arg[1], "arg[1] is nil; expecting filename") local _ENV = nil collectgarbage() local basemem = collectgarbage("count") local document, duration do local file = assert(open(filename)) local text = assert(file:read("*a")) file:close() stderr:write("Parsing ", filename, "...\n") local start_time = clock() document = parse(text) local stop_time = clock() assert(document and document.body) duration = stop_time - start_time end collectgarbage() local memory = collectgarbage("count") - basemem local summary = "Parse time: %.2fs\nLua memory usage: %.0fKB\n" write(summary:format(duration, memory))
Make test/bench.lua compatible with Lua 5.3...
Make test/bench.lua compatible with Lua 5.3... Changes the %d format specifier to %.0f to fix the "number has no integer representation" error.
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
f0a50e067af07ee912a088283992bf20f6b44040
lte/diet.lua
lte/diet.lua
-- Long Time Effect Script: Diet System -- Effect ID: 12 require("item.food"); require("base.common"); module("lte.diet", package.seeall) GermanAttributes = { ["constitution"] = "Ausdauer", ["strength"] = "Strke", ["dexterity"] = "Geschicklichkeit", ["agility"] = "Schnelligkeit", ["intelligence"] = "Intelligenz", ["willpower"] = "Willenskraft", ["perception"] = "Wahrnehmung", ["essence"] = "Essenz" }; function addEffect(dietEffect,Character) InformPlayer(dietEffect,Character); end function callEffect(dietEffect,Character) local curStamp = base.common.GetCurrentTimestamp(); local foundExpire, buffExpireStamp = dietEffect:findValue("buffExpireStamp"); if (not foundExpire) then Character:inform("[ERROR] No expire stamp found in callEffect. Removing buff. Please inform a developer."); return false; end if (curStamp >= buffExpireStamp) then return false; end dietEffect.nextCalled = (buffExpireStamp - curStamp)*10; return true; end function removeEffect(dietEffect,Character) -- inform the player that the buff ends base.common.InformNLS(Character, "[Ernhrung] Die Wirkung des guten Essens vergeht.", "[Diet] The effect of the good food vanishes."); local foundBuff, buffType = dietEffect:findValue("buffType"); if (foundBuff) then local foundBuffAmount, buffAmount = dietEffect:findValue("buffAmount"); if (not foundBuffAmount) then -- should not happen Character:inform("[ERROR] Found buffType, but no buffAmount. Set to 1. Please inform a developer."); buffAmount = 1; end -- reset again the attributes for i=1,buffAmount do local attrib = item.food.BUFFS[buffType][i]; Character:setAttrib(attrib,math.max(1,Character:increaseAttrib(attrib,0)-1)); end end end function loadEffect(dietEffect,Character) -- check for old values and remove them if dietEffect:findValue("constMod") then dietEffect:removeValue("constMod"); dietEffect.nextCalled = 5; end if dietEffect:findValue("dom") then dietEffect:removeValue("dom"); dietEffect.nextCalled = 5; end local foundBuff, buffType = dietEffect:findValue("buffType"); if (foundBuff) then local foundBuffAmount, buffAmount = dietEffect:findValue("buffAmount"); if (not foundBuffAmount) then -- should not happen Character:inform("[ERROR] Found buffType, but no buffAmount. Set to 1. Please inform a developer."); buffAmount = 1; end -- add 1 for each attribute of this buff for i=1,buffAmount do local attrib = item.food.BUFFS[buffType][i]; Character:setAttrib(attrib,Character:increaseAttrib(attrib,0)+1); end else dietEffect.nextCalled = 5; end end function InformPlayer(dietEffect, Character) local foundBuff, buffType = dietEffect:findValue("buffType"); if (foundBuff) then local foundBuffAmount, buffAmount = dietEffect:findValue("buffAmount"); if (not foundBuffAmount) then -- should not happen Character:inform("[Error] Found buffType, but no buffAmount. Set to 1. Please inform a developer."); buffAmount = 1; end if (buffAmount == 1) then local attrib = item.food.BUFFS[buffType][1]; local gText = "[Ernhrung] Durch das gute Essen erhht sich vorbergehend folgendes Attribut um 1: "; if (GermanAttributes[attrib] ~= nil) then gText = gText .. GermanAttributes[attrib]; else gText = gText .. attrib; end local eText = "[Diet] Due to your good food, the following attribute is temporarily increased by 1: " .. attrib; base.common.InformNLS(Character,gText,eText); else local attrib = item.food.BUFFS[buffType]; local gText = "[Ernhrung] Durch das gute Essen erhhen sich vorbergehend folgende Attribute um 1: "; local eText = "[Diet] Due to your good food, the following attributes are temporarily increased by 1: "; local attrib = item.food.BUFFS[buffType][1]; eText = eText .. attrib; if (GermanAttributes[attrib] ~= nil) then gText = gText .. GermanAttributes[attrib]; else gText = gText .. attrib; end attrib = item.food.BUFFS[buffType][2]; eText = eText .. " and " .. attrib; if (GermanAttributes[attrib] ~= nil) then gText = gText .. " und " .. GermanAttributes[attrib]; else gText = gText .. " und " .. attrib; end base.common.InformNLS(Character,gText,eText); end end end
-- Long Time Effect Script: Diet System -- Effect ID: 12 require("item.food"); require("base.common"); module("lte.diet", package.seeall) GermanAttributes = { ["constitution"] = "Ausdauer", ["strength"] = "Strke", ["dexterity"] = "Geschicklichkeit", ["agility"] = "Schnelligkeit", ["intelligence"] = "Intelligenz", ["willpower"] = "Willenskraft", ["perception"] = "Wahrnehmung", ["essence"] = "Essenz" }; function addEffect(dietEffect,Character) InformPlayer(dietEffect,Character); end function callEffect(dietEffect,Character) local curStamp = base.common.GetCurrentTimestamp(); local foundExpire, buffExpireStamp = dietEffect:findValue("buffExpireStamp"); if (not foundExpire) then Character:inform("[ERROR] No expire stamp found in callEffect. Removing buff. Please inform a developer."); return false; end if (curStamp >= buffExpireStamp) then return false; end dietEffect.nextCalled = (buffExpireStamp - curStamp)*10; return true; end function removeEffect(dietEffect,Character) -- inform the player that the buff ends base.common.InformNLS(Character, "[Ernhrung] Die Wirkung des guten Essens vergeht.", "[Diet] The effect of the good food vanishes."); local foundBuff, buffType = dietEffect:findValue("buffType"); if (foundBuff) then local foundBuffAmount, buffAmount = dietEffect:findValue("buffAmount"); if (not foundBuffAmount) then -- should not happen Character:inform("[ERROR] Found buffType, but no buffAmount. Set to 1. Please inform a developer."); buffAmount = 1; end -- reset again the attributes for i=1,buffAmount do local attrib = item.food.BUFFS[buffType][i]; Character:setAttrib(attrib,math.max(1,Character:increaseAttrib(attrib,0)-1)); end end end function loadEffect(dietEffect,Character) -- check for old values and remove them if dietEffect:findValue("constMod") then dietEffect:removeValue("constMod"); dietEffect.nextCalled = 5; end if dietEffect:findValue("dom") then dietEffect:removeValue("dom"); dietEffect.nextCalled = 5; end local foundBuff, buffType = dietEffect:findValue("buffType"); if (foundBuff) then local foundBuffAmount, buffAmount = dietEffect:findValue("buffAmount"); if (not foundBuffAmount) then -- should not happen Character:inform("[ERROR] Found buffType, but no buffAmount. Set to 1. Please inform a developer."); buffAmount = 1; end -- add 1 for each attribute of this buff for i=1,buffAmount do local attrib = item.food.BUFFS[buffType][i]; Character:setAttrib(attrib,Character:increaseAttrib(attrib,0)+1); end else dietEffect.nextCalled = 5; end end function InformPlayer(dietEffect, Character) local foundBuff, buffType = dietEffect:findValue("buffType"); if (foundBuff) then local foundBuffAmount, buffAmount = dietEffect:findValue("buffAmount"); if (not foundBuffAmount) then -- should not happen Character:inform("[Error] Found buffType, but no buffAmount. Set to 1. Please inform a developer."); buffAmount = 1; end if (buffAmount == 1) then local attrib = item.food.BUFFS[buffType][1]; Character:setAttrib(attrib,Character:increaseAttrib(attrib,0)+1); local gText = "[Ernhrung] Durch das gute Essen erhht sich vorbergehend folgendes Attribut um 1: "; if (GermanAttributes[attrib] ~= nil) then gText = gText .. GermanAttributes[attrib]; else gText = gText .. attrib; end local eText = "[Diet] Due to your good food, the following attribute is temporarily increased by 1: " .. attrib; base.common.InformNLS(Character,gText,eText); else local attrib = item.food.BUFFS[buffType]; local gText = "[Ernhrung] Durch das gute Essen erhhen sich vorbergehend folgende Attribute um 1: "; local eText = "[Diet] Due to your good food, the following attributes are temporarily increased by 1: "; local attrib = item.food.BUFFS[buffType][1]; Character:setAttrib(attrib,Character:increaseAttrib(attrib,0)+1); eText = eText .. attrib; if (GermanAttributes[attrib] ~= nil) then gText = gText .. GermanAttributes[attrib]; else gText = gText .. attrib; end attrib = item.food.BUFFS[buffType][2]; Character:setAttrib(attrib,Character:increaseAttrib(attrib,0)+1); eText = eText .. " and " .. attrib; if (GermanAttributes[attrib] ~= nil) then gText = gText .. " und " .. GermanAttributes[attrib]; else gText = gText .. " und " .. attrib; end base.common.InformNLS(Character,gText,eText); end end end
Fix that buffs to certain attributes are removed but never given mantis #9132
Fix that buffs to certain attributes are removed but never given mantis #9132
Lua
agpl-3.0
KayMD/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content
3fc5fc2ab074a67652bece7a1654088ada624e2d
lua/talk.lua
lua/talk.lua
-- parses incoming messages to populate dictionary function talk_parse(event, origin, params) local word1,word2 local words = str_split(params[2], " ") for i=1,(#words+1) do local word = words[i] if word1 ~= nil then if word2 ~= nil then local temp = word if temp == nil then temp = "" end sql_fquery( "INSERT INTO `dictionary` (`Word1`, `Word2`, `Word3`, `DateAdded`) " .. "VALUES('"..sql_escape(word2).."','"..sql_escape(word1).."','"..sql_escape(temp).."','"..os.time().."')" ) end word2 = word1 end word1 = word end end register_callback("CHANNEL", "talk_parse") -- operates on tree node and state table to help generate text function extend_tree(working_node, data_table) local w1 = working_node.parent.value local w2 = working_node.value -- if we reached max depth, stop if working_node.depth + 1 > data_table.max_depth then if working_node.depth > data_table.best_depth and #(data_table.end_nodes) < data_table.max_entries/2 then data_table.best_depth = working_node.depth data_table.end_nodes[#(data_table.end_nodes)+1] = working_node end return end -- if we reached max entries, stop if #(data_table.end_nodes)+1 > data_table.max_entries then return end -- attempt to extend phrase local rows = sql_query_fetch( "SELECT `Index`,`Word3` FROM `dictionary` WHERE `Word1` = '"..sql_escape(w1).."' ".. "AND `Word2` = '"..sql_escape(w2).."' ORDER BY RAND() LIMIT 0,2" ) -- 2 options (recursive magic!) if #rows > 1 and data_table.hit_nodes[rows[2].Index] == nil then local new_node = {subnodes={},parent=working_node,value=rows[2].Word3,depth=working_node.depth+1} working_node.subnodes[#(working_node.subnodes)+1] = new_node data_table.hit_nodes[rows[2].Index] = true extend_tree(new_node, data_table) end -- at least 1 option (recursive magic!) if #rows > 0 and data_table.hit_nodes[rows[1].Index] == nil then local new_node = {subnodes={},parent=working_node,value=rows[1].Word3,depth=working_node.depth+1} working_node.subnodes[#(working_node.subnodes)+1] = new_node data_table.hit_nodes[rows[1].Index] = true extend_tree(new_node, data_table) -- found nothing else if working_node.depth > data_table.best_depth * .75 then data_table.best_depth = working_node.depth data_table.end_nodes[#(data_table.end_nodes)+1] = working_node end end end -- collapses a run of the tree into a phrase function climb_tree(leaf) local phrase = "" while leaf ~= nil do if leaf.value ~= nil then if phrase:len() then phrase = leaf.value .. " " .. phrase else phrase = leaf.value end end leaf = leaf.parent end return phrase end -- generates text and either returns it or sends it to the channel function talk(channel, retmode, seed) local phrase = "" local working_node local root_node -- parameters for building the tree local data_table = { hit_nodes={}, -- track indices already used to prevent repeats/loops node_count=0, -- count nodes in tree end_nodes={}, -- track leaves representing complete strings max_depth=35, -- maximum word count best_depth=0, -- current top word count max_entries=10 -- maximum number of leaves to complete before stopping } local rows = nil -- initial seed if seed == nil then rows = sql_query_fetch("SELECT `Word1`,`Word2`,`Word3` FROM `dictionary` WHERE `Word3` != '' ORDER BY RAND() LIMIT 0,1") else rows = sql_query_fetch( "SELECT `Word1`,`Word2`,`Word3` FROM `dictionary` WHERE (`Word3` != '') AND ".. "(`Word1`='"..sql_escape(seed).."' OR `Word2`='"..sql_escape(seed).."' OR `Word3`='"..sql_escape(seed).."') ORDER BY RAND() LIMIT 0,1" ) end if #rows < 1 then return nil end local w1 = rows[1].Word1 local w2 = rows[1].Word2 local w3 = rows[1].Word3 local num_steps = 0 local hit_end = false local t = NewStack() t:push(w3) t:push(w2) t:push(w1) -- attempt to build backward (use temporary stack) -- maybe we should throw out the content of the stack and attempt to build the tree from the first (last) 2 entries we find -- that strategy would not work if seed~=nil so maybe just build another tree backwards while not hit_end and num_steps < data_table.max_depth do local _w2 = t:pop() local _w3 = t:pop() t:push(_w3) t:push(_w2) local rows = sql_query_fetch( "SELECT `Index`,`Word1` FROM `dictionary` WHERE `Word2` = '"..sql_escape(_w2).."' ".. "AND `Word3`='"..sql_escape(_w3).."' ORDER BY RAND()" ) if #rows == 0 then hit_end = true else local selected_row = 1 while data_table.hit_nodes[rows[selected_row].Index] ~= nil do selected_row = selected_row + 1 end if selected_row > #rows then hit_end = true else t:push(rows[1].Word1) data_table.hit_nodes[rows[1].Index] = true end end num_steps = num_steps + 1 end -- add the contents of temp stack into main tree in reverse order root_node = {subnodes={},parent=nil,value=nil,depth=0} working_node = root_node while #t > 0 do new_node = {subnodes={},parent=working_node,value=t:pop(),depth=working_node.depth+1} working_node.subnodes[#(working_node.subnodes)+1] = new_node working_node = new_node end -- build tree down from end of initial run extend_tree(working_node, data_table) -- select random leaf and collapse the run into a phrase phrase = climb_tree(data_table.end_nodes[math.random(1,#(data_table.end_nodes))]) -- additional processing for ctcp actions local isAction=false if phrase:sub(0,8)=="ACTION " then isAction=true end phrase = phrase:gsub("","") if isAction then phrase = ""..phrase.."" end -- return or send if retmode == nil then irc_msg(channel,phrase) else return phrase end end
-- parses incoming messages to populate dictionary function talk_parse(event, origin, params) local word1,word2 local words = str_split(params[2], " ") for i=1,(#words+1) do local word = words[i] if word1 ~= nil then if word2 ~= nil then local temp = word if temp == nil then temp = "" end sql_fquery( "INSERT INTO `dictionary` (`Word1`, `Word2`, `Word3`, `DateAdded`) " .. "VALUES('"..sql_escape(word2).."','"..sql_escape(word1).."','"..sql_escape(temp).."','"..os.time().."')" ) end word2 = word1 end word1 = word end end register_callback("CHANNEL", "talk_parse") -- operates on tree node and state table to help generate text function extend_tree(working_node, data_table) local w1 = working_node.parent.value local w2 = working_node.value -- if we reached max depth, stop if working_node.depth + 1 > data_table.max_depth then if working_node.depth > data_table.best_depth and #(data_table.end_nodes) < data_table.max_entries/2 then data_table.best_depth = working_node.depth data_table.end_nodes[#(data_table.end_nodes)+1] = working_node end return end -- if we reached max entries, stop if #(data_table.end_nodes)+1 > data_table.max_entries then return end -- attempt to extend phrase local rows = sql_query_fetch( "SELECT `Index`,`Word3` FROM `dictionary` WHERE `Word1` = '"..sql_escape(w1).."' ".. "AND `Word2` = '"..sql_escape(w2).."' ORDER BY RAND() LIMIT 0,2" ) -- 2 options (recursive magic!) if #rows > 1 and data_table.hit_nodes[rows[2].Index] == nil then local new_node = {subnodes={},parent=working_node,value=rows[2].Word3,depth=working_node.depth+1} working_node.subnodes[#(working_node.subnodes)+1] = new_node data_table.hit_nodes[rows[2].Index] = true extend_tree(new_node, data_table) end -- at least 1 option (recursive magic!) if #rows > 0 and data_table.hit_nodes[rows[1].Index] == nil then local new_node = {subnodes={},parent=working_node,value=rows[1].Word3,depth=working_node.depth+1} working_node.subnodes[#(working_node.subnodes)+1] = new_node data_table.hit_nodes[rows[1].Index] = true extend_tree(new_node, data_table) -- found nothing else if working_node.depth > data_table.best_depth * .75 then data_table.best_depth = working_node.depth data_table.end_nodes[#(data_table.end_nodes)+1] = working_node end end end -- collapses a run of the tree into a phrase function climb_tree(leaf) local phrase = "" while leaf ~= nil do if leaf.value ~= nil then if phrase:len() then phrase = leaf.value .. " " .. phrase else phrase = leaf.value end end leaf = leaf.parent end return phrase end -- generates text and either returns it or sends it to the channel function talk(channel, retmode, seed) local phrase = "" local working_node local root_node -- parameters for building the tree local data_table = { hit_nodes={}, -- track indices already used to prevent repeats/loops node_count=0, -- count nodes in tree end_nodes={}, -- track leaves representing complete strings max_depth=35, -- maximum word count best_depth=0, -- current top word count max_entries=10 -- maximum number of leaves to complete before stopping } local rows = nil -- initial seed if seed == nil then rows = sql_query_fetch("SELECT `Word1`,`Word2`,`Word3` FROM `dictionary` WHERE `Word3` != '' ORDER BY RAND() LIMIT 0,1") else rows = sql_query_fetch( "SELECT `Word1`,`Word2`,`Word3` FROM `dictionary` WHERE (`Word3` != '') AND ".. "(`Word1`='"..sql_escape(seed).."' OR `Word2`='"..sql_escape(seed).."' OR `Word3`='"..sql_escape(seed).."') ORDER BY RAND() LIMIT 0,1" ) end if #rows < 1 then return nil end local w1 = rows[1].Word1 local w2 = rows[1].Word2 local w3 = rows[1].Word3 local num_steps = 0 local hit_end = false local t = NewStack() t:push(w3) t:push(w2) t:push(w1) -- attempt to build backward (use temporary stack) -- maybe we should throw out the content of the stack and attempt to build the tree from the first (last) 2 entries we find -- that strategy would not work if seed~=nil so maybe just build another tree backwards while not hit_end and num_steps < data_table.max_depth do local _w2 = t:pop() local _w3 = t:pop() t:push(_w3) t:push(_w2) local rows = sql_query_fetch( "SELECT `Index`,`Word1` FROM `dictionary` WHERE `Word2` = '"..sql_escape(_w2).."' ".. "AND `Word3`='"..sql_escape(_w3).."' ORDER BY RAND()" ) if #rows == 0 then hit_end = true else local selected_row = 1 while selected_row <= #rows and data_table.hit_nodes[rows[selected_row].Index] ~= nil do selected_row = selected_row + 1 end if selected_row > #rows then hit_end = true else t:push(rows[1].Word1) data_table.hit_nodes[rows[1].Index] = true end end num_steps = num_steps + 1 end -- add the contents of temp stack into main tree in reverse order root_node = {subnodes={},parent=nil,value=nil,depth=0} working_node = root_node while #t > 0 do new_node = {subnodes={},parent=working_node,value=t:pop(),depth=working_node.depth+1} working_node.subnodes[#(working_node.subnodes)+1] = new_node working_node = new_node end -- build tree down from end of initial run extend_tree(working_node, data_table) -- select random leaf and collapse the run into a phrase phrase = climb_tree(data_table.end_nodes[math.random(1,#(data_table.end_nodes))]) -- additional processing for ctcp actions local isAction=false if phrase:sub(0,8)=="ACTION " then isAction=true end phrase = phrase:gsub("","") if isAction then phrase = ""..phrase.."" end -- return or send if retmode == nil then irc_msg(channel,phrase) else return phrase end end
fix error condition
fix error condition
Lua
mit
wetfish/denice,pielover88888/denice
98a7956e67231fc3bced6517da88de5aa8cf7754
net/http.lua
net/http.lua
local socket = require "socket" local mime = require "mime" local url = require "socket.url" local server = require "net.server" local connlisteners_get = require "net.connlisteners".get; local listener = connlisteners_get("httpclient") or error("No httpclient listener!"); local t_insert, t_concat = table.insert, table.concat; local tonumber, tostring, pairs, xpcall, select, debug_traceback = tonumber, tostring, pairs, xpcall, select, debug.traceback; local log = require "util.logger".init("http"); local print = function () end local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end module "http" local function expectbody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end local function request_reader(request, data, startpos) if not data then if request.body then log("debug", "Connection closed, but we have data, calling callback..."); request.callback(t_concat(request.body), request.code, request); elseif request.state ~= "completed" then -- Error.. connection was closed prematurely request.callback("connection-closed", 0, request); end destroy_request(request); request.body = nil; request.state = "completed"; return; end if request.state == "body" and request.state ~= "completed" then print("Reading body...") if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end if startpos then data = data:sub(startpos, -1) end t_insert(request.body, data); if request.bodylength then request.havebodylength = request.havebodylength + #data; if request.havebodylength >= request.bodylength then -- We have the body log("debug", "Have full body, calling callback"); if request.callback then request.callback(t_concat(request.body), request.code, request); end request.body = nil; request.state = "completed"; else print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength); end end elseif request.state == "headers" then print("Reading headers...") local pos = startpos; local headers = request.responseheaders or {}; for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do startpos = startpos + #line + 2; local k, v = line:match("(%S+): (.+)"); if k and v then headers[k:lower()] = v; print("Header: "..k:lower().." = "..v); elseif #line == 0 then request.responseheaders = headers; break; else print("Unhandled header line: "..line); end end -- Reached the end of the headers request.state = "body"; if #data > startpos then return request_reader(request, data, startpos); end elseif request.state == "status" then print("Reading status...") local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos); code = tonumber(code); if not code then return request.callback("invalid-status-line", 0, request); end request.code, request.responseversion = code, http; if request.onlystatus or not expectbody(request, code) then if request.callback then request.callback(nil, code, request); end destroy_request(request); return; end request.state = "headers"; if #data > linelen then return request_reader(request, data, linelen); end end end local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end function request(u, ex, callback) local req = url.parse(u); local custom_headers, body; local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" } if req.userinfo then default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo); end if ex then custom_headers = ex.custom_headers; req.onlystatus = ex.onlystatus; body = ex.body; if body then req.method = "POST "; default_headers["Content-Length"] = tostring(#body); default_headers["Content-Type"] = "application/x-www-form-urlencoded"; end if ex.method then req.method = ex.method; end end req.handler, req.conn = server.wraptcpclient(listener, socket.tcp(), req.host, req.port or 80, 0, "*a"); req.write = req.handler.write; req.conn:settimeout(0); local ok, err = req.conn:connect(req.host, req.port or 80); if not ok and err ~= "timeout" then return nil, err; end req.write((req.method or "GET ")..req.path.." HTTP/1.0\r\n"); local t = { [2] = ": ", [4] = "\r\n" }; if custom_headers then for k, v in pairs(custom_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end end for k, v in pairs(default_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end req.write("\r\n"); if body then req.write(body); end req.callback = function (content, code, request) log("debug", "Calling callback, code %s content: %s", code or "---", content or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end req.reader = request_reader; req.state = "status"; listener.register_request(req.handler, req); return req; end function destroy_request(request) if request.conn then request.handler.close() listener.disconnect(request.conn, "closed"); end end _M.urlencode = urlencode; return _M;
local socket = require "socket" local mime = require "mime" local url = require "socket.url" local server = require "net.server" local connlisteners_get = require "net.connlisteners".get; local listener = connlisteners_get("httpclient") or error("No httpclient listener!"); local t_insert, t_concat = table.insert, table.concat; local tonumber, tostring, pairs, xpcall, select, debug_traceback = tonumber, tostring, pairs, xpcall, select, debug.traceback; local log = require "util.logger".init("http"); local print = function () end local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end module "http" local function expectbody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end local function request_reader(request, data, startpos) if not data then if request.body then log("debug", "Connection closed, but we have data, calling callback..."); request.callback(t_concat(request.body), request.code, request); elseif request.state ~= "completed" then -- Error.. connection was closed prematurely request.callback("connection-closed", 0, request); end destroy_request(request); request.body = nil; request.state = "completed"; return; end if request.state == "body" and request.state ~= "completed" then print("Reading body...") if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end if startpos then data = data:sub(startpos, -1) end t_insert(request.body, data); if request.bodylength then request.havebodylength = request.havebodylength + #data; if request.havebodylength >= request.bodylength then -- We have the body log("debug", "Have full body, calling callback"); if request.callback then request.callback(t_concat(request.body), request.code, request); end request.body = nil; request.state = "completed"; else print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength); end end elseif request.state == "headers" then print("Reading headers...") local pos = startpos; local headers = request.responseheaders or {}; for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do startpos = startpos + #line + 2; local k, v = line:match("(%S+): (.+)"); if k and v then headers[k:lower()] = v; print("Header: "..k:lower().." = "..v); elseif #line == 0 then request.responseheaders = headers; break; else print("Unhandled header line: "..line); end end -- Reached the end of the headers request.state = "body"; if #data > startpos then return request_reader(request, data, startpos); end elseif request.state == "status" then print("Reading status...") local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos); code = tonumber(code); if not code then return request.callback("invalid-status-line", 0, request); end request.code, request.responseversion = code, http; if request.onlystatus or not expectbody(request, code) then if request.callback then request.callback(nil, code, request); end destroy_request(request); return; end request.state = "headers"; if #data > linelen then return request_reader(request, data, linelen); end end end local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end function request(u, ex, callback) local req = url.parse(u); local custom_headers, body; local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" } if req.userinfo then default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo); end if ex then custom_headers = ex.custom_headers; req.onlystatus = ex.onlystatus; body = ex.body; if body then req.method = "POST "; default_headers["Content-Length"] = tostring(#body); default_headers["Content-Type"] = "application/x-www-form-urlencoded"; end if ex.method then req.method = ex.method; end end req.handler, req.conn = server.wraptcpclient(listener, socket.tcp(), req.host, req.port or 80, 0, "*a"); req.write = req.handler.write; req.conn:settimeout(0); local ok, err = req.conn:connect(req.host, req.port or 80); if not ok and err ~= "timeout" then return nil, err; end local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" }; if req.query then t_insert(request_line, 4, "?"); t_insert(request_line, 5, req.query); end req.write(t_concat(request_line)); local t = { [2] = ": ", [4] = "\r\n" }; if custom_headers then for k, v in pairs(custom_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end end for k, v in pairs(default_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end req.write("\r\n"); if body then req.write(body); end req.callback = function (content, code, request) log("debug", "Calling callback, code %s content: %s", code or "---", content or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end req.reader = request_reader; req.state = "status"; listener.register_request(req.handler, req); return req; end function destroy_request(request) if request.conn then request.handler.close() listener.disconnect(request.conn, "closed"); end end _M.urlencode = urlencode; return _M;
net.http: Fix to send query part of URL to server
net.http: Fix to send query part of URL to server
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
d1ead78b92556cac49e4b37bd7730cd32ca472dd
modules/corepkg/src/main/resources/moe/lymia/princess/core/pkg/core.pedit-pkg/_princess/predef/core/sandbox.lua
modules/corepkg/src/main/resources/moe/lymia/princess/core/pkg/core.pedit-pkg/_princess/predef/core/sandbox.lua
-- Copyright (c) 2017 Lymia Alusyia <lymia@lymiahugs.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- Copyright (c) 2017 Lymia Alusyia <lymia@lymiahugs.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local _princess = ... local core = _princess.core local ipairs, pairs, error, type, _G = ipairs, pairs, error, type, _G local log, TRACE, where = core.log, core.LogLevel.TRACE, core.where ----------------------------------- -- Remove non-whitelisted functions local function trace(str) local loc = where(1) if loc then loc = "script "..loc end return log(TRACE, loc, function() return str end) end local function set(t) local n = {} for _, v in ipairs(t) do n[v] = true end return n end core.set = set -- TODO: Maybe define this somewhere nicer? local absoluteWhitelist = set { "assert", "error", "getmetatable", "next", "pairs", "pcall", "rawequal", "rawget", "rawset", "select", "setmetatable", "tonumber", "tostring", "type", "unpack", "_VERSION", "xpcall", "ipairs", -- tables "_G", } local tableWhitelist = { coroutine = set { "create", "resume", "running", "status", "wrap", "yield" }, string = set { "byte", "char", "dump", "find", "format", "gmatch", "gfind", "gsub", "len", "lower", "match", "rep", "reverse", "sub", "upper" }, table = set { "concat", "insert", "maxn", "remove", "sort" }, math = set { "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "cosh", "deg", "exp", "floor", "fmod", "frexp", "huge", "ldexp", "log", "log10", "max", "min", "modf", "pi", "pow", "rad", "random", "randomseed", "sin", "sinh", "sqrt", "tan", "tanh" }, os = set { "clock", "date", "difftime", "time" }, } local function cleanTable(name) local table = _G[name] if not table then error("Expected "..name.." in environment, but value not found.") end local expected = tableWhitelist[name] for k, _ in pairs(expected) do if not table[k] then error("Expected "..name.."."..k.." in environment, but value not found.") end end for k, _ in pairs(table) do if not expected[k] then trace("Removing "..name.."."..k.." from environment.") table[k] = nil end end end for k, _ in pairs(absoluteWhitelist) do if not _G[k] then error("Expected "..k.." in environment, but value not found.") end end for k, _ in pairs(_G) do if absoluteWhitelist[k] then -- do nothing elseif tableWhitelist[k] then cleanTable(k) else trace("Removing "..k.." from environment.") _G[k] = nil end end -------------------- -- Metatable wrapper local sys_setmetatable, sys_getmetatable = setmetatable, getmetatable core.setmetatable = sys_setmetatable core.getmetatable = sys_getmetatable local function checkMetatableType(obj) local t = type(obj) if not (t == "table" or t == "userdata") then error("cannot modify metatables for type "..t) end end function setmetatable(obj, mt) checkMetatableType(obj) return sys_setmetatable(obj, mt) end function getmetatable(obj) checkMetatableType(obj) return sys_getmetatable(obj) end
-- Copyright (c) 2017 Lymia Alusyia <lymia@lymiahugs.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- Copyright (c) 2017 Lymia Alusyia <lymia@lymiahugs.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local _princess = ... local core = _princess.core local ipairs, pairs, error, type, _G = ipairs, pairs, error, type, _G local log, TRACE, where = core.log, core.LogLevel.TRACE, core.where ----------------------------------- -- Remove non-whitelisted functions local function trace(str) return log(TRACE, where(1), function() return str end) end local function set(t) local n = {} for _, v in ipairs(t) do n[v] = true end return n end core.set = set -- TODO: Maybe define this somewhere nicer? local absoluteWhitelist = set { "assert", "error", "getmetatable", "next", "pairs", "pcall", "rawequal", "rawget", "rawset", "select", "setmetatable", "tonumber", "tostring", "type", "unpack", "_VERSION", "xpcall", "ipairs", -- tables "_G", } local tableWhitelist = { coroutine = set { "create", "resume", "running", "status", "wrap", "yield" }, string = set { "byte", "char", "dump", "find", "format", "gmatch", "gfind", "gsub", "len", "lower", "match", "rep", "reverse", "sub", "upper" }, table = set { "concat", "insert", "maxn", "remove", "sort" }, math = set { "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "cosh", "deg", "exp", "floor", "fmod", "frexp", "huge", "ldexp", "log", "log10", "max", "min", "modf", "pi", "pow", "rad", "random", "randomseed", "sin", "sinh", "sqrt", "tan", "tanh" }, os = set { "clock", "date", "difftime", "time" }, } local function cleanTable(name) local table = _G[name] if not table then error("Expected "..name.." in environment, but value not found.") end local expected = tableWhitelist[name] for k, _ in pairs(expected) do if not table[k] then error("Expected "..name.."."..k.." in environment, but value not found.") end end for k, _ in pairs(table) do if not expected[k] then trace("Removing "..name.."."..k.." from environment.") table[k] = nil end end end for k, _ in pairs(absoluteWhitelist) do if not _G[k] then error("Expected "..k.." in environment, but value not found.") end end for k, _ in pairs(_G) do if absoluteWhitelist[k] then -- do nothing elseif tableWhitelist[k] then cleanTable(k) else trace("Removing "..k.." from environment.") _G[k] = nil end end -------------------- -- Metatable wrapper local sys_setmetatable, sys_getmetatable = setmetatable, getmetatable core.setmetatable = sys_setmetatable core.getmetatable = sys_getmetatable local function checkMetatableType(obj) local t = type(obj) if not (t == "table" or t == "userdata") then error("cannot modify metatables for type "..t) end end function setmetatable(obj, mt) checkMetatableType(obj) return sys_setmetatable(obj, mt) end function getmetatable(obj) checkMetatableType(obj) return sys_getmetatable(obj) end
Fix source in sandbox.lua
Fix source in sandbox.lua
Lua
mit
Lymia/PrincessEdit,Lymia/PrincessEdit,Lymia/PrincessEdit
971a0312c170a8c94332db16b00ba14ff47feb5c
lua/entities/gmod_wire_simple_explosive/init.lua
lua/entities/gmod_wire_simple_explosive/init.lua
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include('shared.lua') ENT.WireDebugName = "Simple Explosive" function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end self.NormInfo = "" self.Inputs = Wire_CreateInputs(self, { "Detonate" }) end function ENT:Setup( key, damage, removeafter, radius, nocollide ) self.key = key self.damage = math.Min(damage, 1500) self.removeafter = removeafter self.radius = math.Clamp(radius, 1, 10000) self.nocollide = nocollide self.Exploded = false if (self.nocollide) then self:SetCollisionGroup(COLLISION_GROUP_DEBRIS_TRIGGER) else self:SetCollisionGroup(COLLISION_GROUP_NONE) end if (self.damage > 0) then self.NormInfo = "Damage: " .. math.floor(self.damage) .. "\nRadius: " .. math.floor(self.radius) else self.NormInfo = "Radius: " .. math.floor(self.radius) end self:ShowOutput() end function ENT:OnTakeDamage( dmginfo ) self:TakePhysicsDamage( dmginfo ) end function ENT:TriggerInput(iname, value) if (iname == "Detonate") then if (!self.Exploded) and ( math.abs(value) == self.key ) then self:Explode() elseif (value == 0) then self.Exploded = false end end end function ENT:Explode( ) if ( !self:IsValid() ) then return end if (self.Exploded) then return end ply = self:GetPlayer() or self if ( self.damage > 0 ) then util.BlastDamage( self, ply, self:GetPos(), self.radius, self.damage ) end local effectdata = EffectData() effectdata:SetOrigin( self:GetPos() ) util.Effect( "Explosion", effectdata, true, true ) self.Exploded = true self:ShowOutput() if ( self.removeafter ) then self:Remove() return end end function ENT:ShowOutput( ) if (self.Exploded) then self:SetOverlayText("Exploded\n"..self.NormInfo) else self:SetOverlayText("Explosive\n"..self.NormInfo) end end function MakeWireSimpleExplosive(pl, Pos, Ang, model, key, damage, removeafter, radius, nocollide ) if ( !pl:CheckLimit( "wire_simple_explosives" ) ) then return nil end local explosive = ents.Create( "gmod_wire_simple_explosive" ) explosive:SetModel( model ) explosive:SetPos( Pos ) explosive:SetAngles( Ang ) explosive:Spawn() explosive:Activate() explosive:Setup( key, damage, removeafter, radius, nocollide ) explosive:SetPlayer( pl ) explosive.pl = pl pl:AddCount( "wire_simple_explosive", explosive ) pl:AddCleanup( "gmod_wire_simple_explosive", explosive ) return explosive end duplicator.RegisterEntityClass( "gmod_wire_simple_explosive", MakeWireSimpleExplosive, "Pos", "Ang", "Model", "key", "damage", "removeafter", "radius", "nocollide" )
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include('shared.lua') ENT.WireDebugName = "Simple Explosive" function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end self.NormInfo = "" self.Inputs = Wire_CreateInputs(self, { "Detonate" }) end function ENT:Setup( key, damage, removeafter, radius, nocollide ) self.key = key self.damage = math.Min(damage, 1500) self.removeafter = removeafter self.radius = math.Clamp(radius, 1, 10000) self.nocollide = nocollide self.Exploded = false if (self.nocollide) then self:SetCollisionGroup(COLLISION_GROUP_DEBRIS_TRIGGER) else self:SetCollisionGroup(COLLISION_GROUP_NONE) end if (self.damage > 0) then self.NormInfo = "Damage: " .. math.floor(self.damage) .. "\nRadius: " .. math.floor(self.radius) else self.NormInfo = "Radius: " .. math.floor(self.radius) end self:ShowOutput() end function ENT:OnTakeDamage( dmginfo ) self:TakePhysicsDamage( dmginfo ) end function ENT:TriggerInput(iname, value) if (iname == "Detonate") then if (!self.Exploded) and ( math.abs(value) == self.key ) then self:Explode() elseif (value == 0) then self.Exploded = false end end end function ENT:Explode( ) if ( !self:IsValid() ) then return end if (self.Exploded) then return end local ply = self:GetPlayer() if not IsValid(ply) then ply = self end if ( self.damage > 0 ) then util.BlastDamage( self, ply, self:GetPos(), self.radius, self.damage ) end local effectdata = EffectData() effectdata:SetOrigin( self:GetPos() ) util.Effect( "Explosion", effectdata, true, true ) self.Exploded = true self:ShowOutput() if ( self.removeafter ) then self:Remove() return end end function ENT:ShowOutput( ) if (self.Exploded) then self:SetOverlayText("Exploded\n"..self.NormInfo) else self:SetOverlayText("Explosive\n"..self.NormInfo) end end function MakeWireSimpleExplosive(pl, Pos, Ang, model, key, damage, removeafter, radius, nocollide ) if ( !pl:CheckLimit( "wire_simple_explosives" ) ) then return nil end local explosive = ents.Create( "gmod_wire_simple_explosive" ) explosive:SetModel( model ) explosive:SetPos( Pos ) explosive:SetAngles( Ang ) explosive:Spawn() explosive:Activate() explosive:Setup( key, damage, removeafter, radius, nocollide ) explosive:SetPlayer( pl ) explosive.pl = pl pl:AddCount( "wire_simple_explosive", explosive ) pl:AddCleanup( "gmod_wire_simple_explosive", explosive ) return explosive end duplicator.RegisterEntityClass( "gmod_wire_simple_explosive", MakeWireSimpleExplosive, "Pos", "Ang", "Model", "key", "damage", "removeafter", "radius", "nocollide" )
Fixes #135
Fixes #135
Lua
apache-2.0
rafradek/wire,CaptainPRICE/wire,sammyt291/wire,immibis/wiremod,bigdogmat/wire,dvdvideo1234/wire,plinkopenguin/wiremod,mms92/wire,mitterdoo/wire,notcake/wire,wiremod/wire,Grocel/wire,Python1320/wire,thegrb93/wire,garrysmodlua/wire,NezzKryptic/Wire
a08c0788207b2c07947e56737ad4452bf30e9f5d
mods/christmas_craft/settings.lua
mods/christmas_craft/settings.lua
print (" ---- Overrider christmas_craft = true! ---- ") local dirttiles = {"snow.png", "default_dirt.png", {name = "default_dirt.png^grass_w_snow_side.png", tileable_vertical = false}} local snowballdrop = {items = {'default:snow'}, rarity = 0} local add_drop = function (def) if type(def.drop) == "table" then if def.drop.max_items then def.drop.max_items = def.drop.max_items + 1 end table.insert(def.drop.items, snowballdrop) elseif type(def.drop) == "string" then def.drop = { items = { {items = {def.drop}, rarity = 0}, snowballdrop } } else def.drop = { items = { snowballdrop } } end end local dirt_with_grass = minetest.registered_items["default:dirt_with_grass"] minetest.override_item("default:dirt_with_grass", {tiles = dirttiles}) add_drop(dirt_with_grass) local dirt_with_dry_grass = minetest.registered_items["default:dirt_with_dry_grass"] minetest.override_item("default:dirt_with_dry_grass", {tiles = dirttiles}) add_drop(dirt_with_dry_grass) local leavetiles = {"snow.png", "christmas_craft_leaves_top.png", "christmas_craft_leaves_side.png"} -- Replace leaves minetest.override_item("default:leaves", {tiles = leavetiles}) -- Replace jungleleaves minetest.override_item("default:jungleleaves", {tiles = leavetiles}) -- Replace grass for i=1,5 do minetest.override_item("default:grass_" .. i, {tiles = {"christmas_grass_"..i..".png"}}) end -- Replace youngtrees if minetest.registered_items["youngtrees:youngtree_top"] then minetest.override_item("youngtrees:youngtree_top", {tiles = {"christmas_youngtree16xa.png"}}) minetest.override_item("youngtrees:youngtree_middle", {tiles = {"christmas_youngtree16xb.png"}}) end -- Replace woodsoils if minetest.registered_items["woodsoils:grass_with_leaves_1"] then minetest.override_item("woodsoils:grass_with_leaves_1", {tiles = {"snow.png", "default_dirt.png", "default_dirt.png^grass_w_snow_side.png"}}) add_drop(minetest.registered_items["woodsoils:grass_with_leaves_1"]) end if minetest.registered_items["woodsoils:grass_with_leaves_2"] then minetest.override_item("woodsoils:grass_with_leaves_2", {tiles = {"snow.png", "default_dirt.png", "default_dirt.png^grass_w_snow_side.png"}}) add_drop(minetest.registered_items["woodsoils:grass_with_leaves_2"]) end if minetest.registered_items["woodsoils:dirt_with_leaves_1"] then minetest.override_item("woodsoils:dirt_with_leaves_1", {tiles = {"snow.png", "default_dirt.png", "default_dirt.png^grass_w_snow_side.png^woodsoils_ground_cover_side.png"}}) add_drop(minetest.registered_items["woodsoils:dirt_with_leaves_1"]) end if minetest.registered_items["woodsoils:dirt_with_leaves_2"] then minetest.override_item("woodsoils:dirt_with_leaves_2", {tiles = {"snow.png", "default_dirt.png", "default_dirt.png^grass_w_snow_side.png^woodsoils_ground_cover_side.png"}}) add_drop(minetest.registered_items["woodsoils:dirt_with_leaves_2"]) end print (" ---- Overrider christmas_craft [OK] ---- ")
print (" ---- Overrider christmas_craft = true! ---- ") local dirttiles = {"snow.png", "default_dirt.png", {name = "default_dirt.png^grass_w_snow_side.png", tileable_vertical = false}} local snowballdrop = {items = {'default:snow'}, rarity = 0} local add_drop = function (def) if type(def.drop) == "table" then if def.drop.max_items then def.drop.max_items = def.drop.max_items + 1 end table.insert(def.drop.items, snowballdrop) elseif type(def.drop) == "string" then def.drop = { items = { {items = {def.drop}, rarity = 0}, snowballdrop } } else def.drop = { items = { snowballdrop } } end end local dirt_with_grass = minetest.registered_items["default:dirt_with_grass"] minetest.override_item("default:dirt_with_grass", {tiles = dirttiles}) add_drop(dirt_with_grass) local dirt_with_dry_grass = minetest.registered_items["default:dirt_with_dry_grass"] minetest.override_item("default:dirt_with_dry_grass", {tiles = dirttiles}) add_drop(dirt_with_dry_grass) local nodebox = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5} } } local leavesoverride = { drawtype = "nodebox", visual_scale = 1, tiles = {"snow.png", "christmas_craft_leaves_top.png", "christmas_craft_leaves_side.png"}, paramtype = "light", node_box = nodebox, selection_box = nodebox } -- Replace leaves minetest.override_item("default:leaves", leavesoverride) -- Replace jungleleaves minetest.override_item("default:jungleleaves", leavesoverride) -- Replace grass for i=1,5 do minetest.override_item("default:grass_" .. i, {tiles = {"christmas_grass_"..i..".png"}}) end -- Replace youngtrees if minetest.registered_items["youngtrees:youngtree_top"] then minetest.override_item("youngtrees:youngtree_top", {tiles = {"christmas_youngtree16xa.png"}}) minetest.override_item("youngtrees:youngtree_middle", {tiles = {"christmas_youngtree16xb.png"}}) end -- Replace woodsoils if minetest.registered_items["woodsoils:grass_with_leaves_1"] then minetest.override_item("woodsoils:grass_with_leaves_1", {tiles = {"snow.png", "default_dirt.png", "default_dirt.png^grass_w_snow_side.png"}}) add_drop(minetest.registered_items["woodsoils:grass_with_leaves_1"]) end if minetest.registered_items["woodsoils:grass_with_leaves_2"] then minetest.override_item("woodsoils:grass_with_leaves_2", {tiles = {"snow.png", "default_dirt.png", "default_dirt.png^grass_w_snow_side.png"}}) add_drop(minetest.registered_items["woodsoils:grass_with_leaves_2"]) end if minetest.registered_items["woodsoils:dirt_with_leaves_1"] then minetest.override_item("woodsoils:dirt_with_leaves_1", {tiles = {"snow.png", "default_dirt.png", "default_dirt.png^grass_w_snow_side.png^woodsoils_ground_cover_side.png"}}) add_drop(minetest.registered_items["woodsoils:dirt_with_leaves_1"]) end if minetest.registered_items["woodsoils:dirt_with_leaves_2"] then minetest.override_item("woodsoils:dirt_with_leaves_2", {tiles = {"snow.png", "default_dirt.png", "default_dirt.png^grass_w_snow_side.png^woodsoils_ground_cover_side.png"}}) add_drop(minetest.registered_items["woodsoils:dirt_with_leaves_2"]) end print (" ---- Overrider christmas_craft [OK] ---- ")
[chistmas_craft] Fix leaves (were full snow)
[chistmas_craft] Fix leaves (were full snow) Today I learned Minetests only displays one texture when drawtype is allfaces_optional. Nowhere in the doc this is even mentionned. Minetest is really a fucking damn dipshit game engine.
Lua
unlicense
sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server
f682be7f251914cf1e8a0be89bad4477140ec409
Modules/QuentyAdminCommands/AuthenticationServiceServer.lua
Modules/QuentyAdminCommands/AuthenticationServiceServer.lua
local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local qString = LoadCustomLibrary("qString") local QACSettings = LoadCustomLibrary("QACSettings") local qPlayer = LoadCustomLibrary("qPlayer") -- This script handles authenticating players who, well, I want authenticated, and defining permissions -- AuthenticationServiceServer.lua -- @author Quenty -- Last Modified February 6th, 2014 local AuthenticationService = {} do local Authorized = QACSettings.Authorized local RequestStream = NevermoreEngine.GetRemoteFunction("AuthenticationServiceRequestor") local EventStream = NevermoreEngine.GetRemoteEvent("AuthenticationServiceEventStream") RequestStream.OnServerInvoke = (function(Player, Request, Data) Player = Player or Players.LocalPlayer if Request == "IsAuthorized" then return AuthenticationService.IsAuthorized(Data or Player) else error("[AuthenticationService] - Unknown request") end end) local function IsAuthorized(PlayerName) PlayerName = tostring(PlayerName) -- Incase they send in a player for _, AuthenticationString in pairs(Authorized) do if qString.CompareStrings(tostring(AuthenticationString), PlayerName) then return true end end return false end AuthenticationService.IsAuthorized = IsAuthorized AuthenticationService.isAuthorized = IsAuthorized local function Authorize(PlayerName) PlayerName = tostring(PlayerName) -- Incase they send in a player if not IsAuthorized(PlayerName) then -- Authorized[PlayerName] = true Authorized[#Authorized+1] = PlayerName local Player = qPlayer.GetPlayerFromName(PlayerName) if Player then EventStream:FireClient(Player, "Authorized") end end end AuthenticationService.Authorize = Authorize AuthenticationService.authorize = Authorize local function Deauthorize(PlayerName) PlayerName = tostring(PlayerName) -- Incase they send in a player for Index, AuthenticationString in pairs(Authorized) do if qString.CompareStrings(tostring(AuthenticationString), PlayerName) then table.remove(Authorized, Index) local Player = qPlayer.GetPlayerFromName(PlayerName) if Player then EventStream:FireClient(Player, "Deauthorized") else print("[AuthenticationService] [Deauthorize] - Could not find deauthorized player '" .. PlayerName .. "', did not send deauthorization event.") end break end end end AuthenticationService.Deauthorize = Deauthorize AuthenticationService.deauthorize = Deauthorize end return AuthenticationService
local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local qString = LoadCustomLibrary("qString") local QACSettings = LoadCustomLibrary("QACSettings") local qPlayer = LoadCustomLibrary("qPlayer") -- This script handles authenticating players who, well, I want authenticated, and defining permissions -- AuthenticationServiceServer.lua -- @author Quenty -- Last Modified February 6th, 2014 local AuthenticationService = {} do local Authorized = QACSettings.Authorized local RequestStream = NevermoreEngine.GetRemoteFunction("AuthenticationServiceRequestor") local EventStream = NevermoreEngine.GetRemoteEvent("AuthenticationServiceEventStream") local function IsAuthorized(PlayerName) PlayerName = tostring(PlayerName) -- Incase they send in a player for _, AuthenticationString in pairs(Authorized) do if qString.CompareStrings(tostring(AuthenticationString), PlayerName) then return true end end return false end AuthenticationService.IsAuthorized = IsAuthorized AuthenticationService.isAuthorized = IsAuthorized local function Authorize(PlayerName) PlayerName = tostring(PlayerName) -- Incase they send in a player if not IsAuthorized(PlayerName) then -- Authorized[PlayerName] = true Authorized[#Authorized+1] = PlayerName local Player = qPlayer.GetPlayerFromName(PlayerName) if Player then EventStream:FireClient(Player, "Authorized") end end end AuthenticationService.Authorize = Authorize AuthenticationService.authorize = Authorize local function Deauthorize(PlayerName) PlayerName = tostring(PlayerName) -- Incase they send in a player for Index, AuthenticationString in pairs(Authorized) do if qString.CompareStrings(tostring(AuthenticationString), PlayerName) then table.remove(Authorized, Index) local Player = qPlayer.GetPlayerFromName(PlayerName) if Player then EventStream:FireClient(Player, "Deauthorized") else print("[AuthenticationService] [Deauthorize] - Could not find deauthorized player '" .. PlayerName .. "', did not send deauthorization event.") end break end end end AuthenticationService.Deauthorize = Deauthorize AuthenticationService.deauthorize = Deauthorize RequestStream.OnServerInvoke = (function(Player, Request, Data) Player = Player or Players.LocalPlayer if Request == "IsAuthorized" then return AuthenticationService.IsAuthorized(Data or Player) else error("[AuthenticationService] - Unknown request") end end) end return AuthenticationService
Fix queue issue.
Fix queue issue.
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
95cbfc50d8f7fc492f6def60720e355fdd0f62c1
mods/stairs/init.lua
mods/stairs/init.lua
-- Minetest 0.4 mod: stairs -- See README.txt for licensing and other information. stairs = {} -- Node will be called modname:stair_<subname> function stairs.register_stair(subname, recipeitem, groups, images, description, sounds) local modname = minetest.get_current_modname() minetest.register_node(modname..":stair_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end local p0 = pointed_thing.under local p1 = pointed_thing.above if p0.y-1 == p1.y then local fakestack = ItemStack(modname..":stair_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_node(modname..":stair_" .. subname.."upside_down", { drop = modname..":stair_" .. subname, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = { {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, {-0.5, -0.5, 0, 0.5, 0, 0.5}, }, }, }) minetest.register_craft({ output = modname..':stair_' .. subname .. ' 4', recipe = { {recipeitem, "", ""}, {recipeitem, recipeitem, ""}, {recipeitem, recipeitem, recipeitem}, }, }) -- Flipped recipe for the silly minecrafters minetest.register_craft({ output = modname..':stair_' .. subname .. ' 4', recipe = { {"", "", recipeitem}, {"", recipeitem, recipeitem}, {recipeitem, recipeitem, recipeitem}, }, }) end -- Node will be called modname:slab_<subname> function stairs.register_slab(subname, recipeitem, groups, images, description, sounds) local modname = minetest.get_current_modname() minetest.register_node(modname..":slab_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end -- If it's being placed on an another similar one, replace it with -- a full block local slabpos = nil local slabnode = nil local p0 = pointed_thing.under local p1 = pointed_thing.above local n0 = minetest.env:get_node(p0) if n0.name == modname..":slab_" .. subname and p0.y+1 == p1.y then slabpos = p0 slabnode = n0 end if slabpos then -- Remove the slab at slabpos minetest.env:remove_node(slabpos) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = slabpos fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(slabpos, slabnode) end return itemstack end -- Upside down slabs if p0.y-1 == p1.y then -- Turn into full block if pointing at a existing slab if n0.name == modname..":slab_" .. subname.."upside_down" then -- Remove the slab at the position of the slab minetest.env:remove_node(p0) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = p0 fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(p0, n0) end return itemstack end -- Place upside down slab local fakestack = ItemStack(modname..":slab_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- If pointing at the side of a upside down slab if n0.name == modname..":slab_" .. subname.."upside_down" and p0.y+1 ~= p1.y then -- Place upside down slab local fakestack = ItemStack(modname..":slab_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_node(modname..":slab_" .. subname.."upside_down", { drop = modname..":slab_"..subname, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, }, }) minetest.register_craft({ output = modname..':slab_' .. subname .. ' 3', recipe = { {recipeitem, recipeitem, recipeitem}, }, }) end -- Nodes will be called modname:{stair,slab}_<subname> function stairs.register_stair_and_slab(subname, recipeitem, groups, images, desc_stair, desc_slab, sounds) stairs.register_stair(subname, recipeitem, groups, images, desc_stair, sounds) stairs.register_slab(subname, recipeitem, groups, images, desc_slab, sounds) end stairs.register_stair_and_slab("wood", "default:wood", {snappy=2,choppy=2,oddly_breakable_by_hand=2}, {"default_wood.png"}, "Wooden stair", "Wooden slab", default.node_sound_wood_defaults()) stairs.register_stair_and_slab("stone", "default:stone", {cracky=3}, {"default_stone.png"}, "Stone stair", "Stone slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("cobble", "default:cobble", {cracky=3}, {"default_cobble.png"}, "Cobble stair", "Cobble slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("brick", "default:brick", {cracky=3}, {"default_brick.png"}, "Brick stair", "Brick slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("sandstone", "default:sandstone", {crumbly=2,cracky=2}, {"default_sandstone.png"}, "Sandstone stair", "Sandstone slab", default.node_sound_stone_defaults())
-- Minetest 0.4 mod: stairs -- See README.txt for licensing and other information. stairs = {} -- Node will be called stairs:stair_<subname> function stairs.register_stair(subname, recipeitem, groups, images, description, sounds) minetest.register_node(":stairs:stair_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end local p0 = pointed_thing.under local p1 = pointed_thing.above if p0.y-1 == p1.y then local fakestack = ItemStack("stairs:stair_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_node(":stairs:stair_" .. subname.."upside_down", { drop = "stairs:stair_" .. subname, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = { {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, {-0.5, -0.5, 0, 0.5, 0, 0.5}, }, }, }) minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 4', recipe = { {recipeitem, "", ""}, {recipeitem, recipeitem, ""}, {recipeitem, recipeitem, recipeitem}, }, }) -- Flipped recipe for the silly minecrafters minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 4', recipe = { {"", "", recipeitem}, {"", recipeitem, recipeitem}, {recipeitem, recipeitem, recipeitem}, }, }) end -- Node will be called stairs:slab_<subname> function stairs.register_slab(subname, recipeitem, groups, images, description, sounds) minetest.register_node(":stairs:slab_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end -- If it's being placed on an another similar one, replace it with -- a full block local slabpos = nil local slabnode = nil local p0 = pointed_thing.under local p1 = pointed_thing.above local n0 = minetest.env:get_node(p0) if n0.name == "stairs:slab_" .. subname and p0.y+1 == p1.y then slabpos = p0 slabnode = n0 end if slabpos then -- Remove the slab at slabpos minetest.env:remove_node(slabpos) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = slabpos fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(slabpos, slabnode) end return itemstack end -- Upside down slabs if p0.y-1 == p1.y then -- Turn into full block if pointing at a existing slab if n0.name == "stairs:slab_" .. subname.."upside_down" then -- Remove the slab at the position of the slab minetest.env:remove_node(p0) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = p0 fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(p0, n0) end return itemstack end -- Place upside down slab local fakestack = ItemStack("stairs:slab_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- If pointing at the side of a upside down slab if n0.name == "stairs:slab_" .. subname.."upside_down" and p0.y+1 ~= p1.y then -- Place upside down slab local fakestack = ItemStack("stairs:slab_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_node(":stairs:slab_" .. subname.."upside_down", { drop = "stairs:slab_"..subname, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, }, }) minetest.register_craft({ output = 'stairs:slab_' .. subname .. ' 3', recipe = { {recipeitem, recipeitem, recipeitem}, }, }) end -- Nodes will be called stairs:{stair,slab}_<subname> function stairs.register_stair_and_slab(subname, recipeitem, groups, images, desc_stair, desc_slab, sounds) stairs.register_stair(subname, recipeitem, groups, images, desc_stair, sounds) stairs.register_slab(subname, recipeitem, groups, images, desc_slab, sounds) end stairs.register_stair_and_slab("wood", "default:wood", {snappy=2,choppy=2,oddly_breakable_by_hand=2}, {"default_wood.png"}, "Wooden stair", "Wooden slab", default.node_sound_wood_defaults()) stairs.register_stair_and_slab("stone", "default:stone", {cracky=3}, {"default_stone.png"}, "Stone stair", "Stone slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("cobble", "default:cobble", {cracky=3}, {"default_cobble.png"}, "Cobble stair", "Cobble slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("brick", "default:brick", {cracky=3}, {"default_brick.png"}, "Brick stair", "Brick slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("sandstone", "default:sandstone", {crumbly=2,cracky=2}, {"default_sandstone.png"}, "Sandstone stair", "Sandstone slab", default.node_sound_stone_defaults())
Fix incorrect slabs to full block transformation by changing the modname to 'stairs' for all stairs and slabs
Fix incorrect slabs to full block transformation by changing the modname to 'stairs' for all stairs and slabs
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
a07ad48fd152b15f2a50596dd2399f6489c6196d
plugins/mod_ping.lua
plugins/mod_ping.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 st = require "util.stanza"; module:add_feature("urn:xmpp:ping"); module:add_iq_handler({"c2s", "s2sin"}, "urn:xmpp:ping", function(session, stanza) if stanza.attr.type == "get" then session.send(st.reply(stanza)); end end);
-- 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 st = require "util.stanza"; module:add_feature("urn:xmpp:ping"); local function ping_handler(event) if event.stanza.attr.type == "get" then event.origin.send(st.reply(event.stanza)); return true; end end module:hook("iq/bare/urn:xmpp:ping:ping", ping_handler); module:hook("iq/host/urn:xmpp:ping:ping", ping_handler);
mod_ping: Updated to use events (which also fixes a few minor issues).
mod_ping: Updated to use events (which also fixes a few minor issues).
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
fb7aed881a972e01d4ad07ef209b688a3443b1df
mod_register_web/mod_register_web.lua
mod_register_web/mod_register_web.lua
local captcha_options = module:get_option("captcha_options", {}); local nodeprep = require "util.encodings".stringprep.nodeprep; local usermanager = require "core.usermanager"; local http = require "util.http"; function template(data) -- Like util.template, but deals with plain text return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end } end local function get_template(name) local fh = assert(module:load_resource("templates/"..name..".html")); local data = assert(fh:read("*a")); fh:close(); return template(data); end local function render(template, data) return tostring(template.apply(data)); end local register_tpl = get_template "register"; local success_tpl = get_template "success"; if next(captcha_options) ~= nil then local recaptcha_tpl = get_template "recaptcha"; function generate_captcha(display_options) return recaptcha_tpl.apply(setmetatable({ recaptcha_display_error = display_options and display_options.recaptcha_error and ("&error="..display_options.recaptcha_error) or ""; }, { __index = function (t, k) if captcha_options[k] then return captcha_options[k]; end module:log("error", "Missing parameter from captcha_options: %s", k); end })); end function verify_captcha(form, callback) http.request("https://www.google.com/recaptcha/api/verify", { body = http.formencode { privatekey = captcha_options.recaptcha_private_key; remoteip = request.conn:ip(); challenge = form.recaptcha_challenge_field; response = form.recaptcha_response_field; }; }, function (verify_result, code) local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)"); if verify_ok == "true" then callback(true); else callback(false, verify_err) end end); end else module:log("debug", "No Recaptcha options set, using fallback captcha") local hmac_sha1 = require "util.hashes".hmac_sha1; local secret = require "util.uuid".generate() local ops = { '+', '-' }; local captcha_tpl = get_template "simplecaptcha"; function generate_captcha() local op = ops[math.random(1, #ops)]; local x, y = math.random(1, 9) repeat y = math.random(1, 9); until x ~= y; local answer; if op == '+' then answer = x + y; elseif op == '-' then if x < y then -- Avoid negative numbers x, y = y, x; end answer = x - y; end local challenge = hmac_sha1(secret, answer, true); return captcha_tpl.apply { op = op, x = x, y = y, challenge = challenge; }; end function verify_captcha(form, callback) if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then callback(true); else callback(false, "Captcha verification failed"); end end end function generate_page(event, display_options) local request = event.request; return render(register_tpl, { path = request.path; hostname = module.host; notice = display_options and display_options.register_error or ""; captcha = generate_captcha(display_options); }) end function register_user(form) local prepped_username = nodeprep(form.username); if usermanager.user_exists(prepped_username, module.host) then return nil, "user-exists"; end return usermanager.create_user(prepped_username, form.password, module.host); end function generate_success(event, form) return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host }); end function generate_register_response(event, form, ok, err) local message; if ok then return generate_success(event, form); else return generate_page(event, { register_error = err }); end end function handle_form(event) local request, response = event.request, event.response; local form = http.formdecode(request.body); verify_captcha(form, function (ok, err) if ok then local register_ok, register_err = register_user(form); response:send(generate_register_response(event, form, register_ok, register_err)); else response:send(generate_page(event, { register_error = err })); end end); return true; -- Leave connection open until we respond above end module:provides("http", { route = { GET = generate_page; POST = handle_form; }; });
local captcha_options = module:get_option("captcha_options", {}); local nodeprep = require "util.encodings".stringprep.nodeprep; local usermanager = require "core.usermanager"; local http = require "util.http"; function template(data) -- Like util.template, but deals with plain text return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end } end local function get_template(name) local fh = assert(module:load_resource("templates/"..name..".html")); local data = assert(fh:read("*a")); fh:close(); return template(data); end local function render(template, data) return tostring(template.apply(data)); end local register_tpl = get_template "register"; local success_tpl = get_template "success"; if next(captcha_options) ~= nil then local recaptcha_tpl = get_template "recaptcha"; function generate_captcha(display_options) return recaptcha_tpl.apply(setmetatable({ recaptcha_display_error = display_options and display_options.recaptcha_error and ("&error="..display_options.recaptcha_error) or ""; }, { __index = function (t, k) if captcha_options[k] then return captcha_options[k]; end module:log("error", "Missing parameter from captcha_options: %s", k); end })); end function verify_captcha(form, callback) http.request("https://www.google.com/recaptcha/api/verify", { body = http.formencode { privatekey = captcha_options.recaptcha_private_key; remoteip = request.conn:ip(); challenge = form.recaptcha_challenge_field; response = form.recaptcha_response_field; }; }, function (verify_result, code) local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)"); if verify_ok == "true" then callback(true); else callback(false, verify_err) end end); end else module:log("debug", "No Recaptcha options set, using fallback captcha") local hmac_sha1 = require "util.hashes".hmac_sha1; local secret = require "util.uuid".generate() local ops = { '+', '-' }; local captcha_tpl = get_template "simplecaptcha"; function generate_captcha() local op = ops[math.random(1, #ops)]; local x, y = math.random(1, 9) repeat y = math.random(1, 9); until x ~= y; local answer; if op == '+' then answer = x + y; elseif op == '-' then if x < y then -- Avoid negative numbers x, y = y, x; end answer = x - y; end local challenge = hmac_sha1(secret, answer, true); return captcha_tpl.apply { op = op, x = x, y = y, challenge = challenge; }; end function verify_captcha(form, callback) if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then callback(true); else callback(false, "Captcha verification failed"); end end end function generate_page(event, display_options) local request = event.request; return render(register_tpl, { path = request.path; hostname = module.host; notice = display_options and display_options.register_error or ""; captcha = generate_captcha(display_options); }) end function register_user(form) local prepped_username = nodeprep(form.username); if usermanager.user_exists(prepped_username, module.host) then return nil, "user-exists"; end return usermanager.create_user(prepped_username, form.password, module.host); end function generate_success(event, form) return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host }); end function generate_register_response(event, form, ok, err) local message; if ok then return generate_success(event, form); else return generate_page(event, { register_error = err }); end end function handle_form(event) local request, response = event.request, event.response; local form = http.formdecode(request.body); verify_captcha(form, function (ok, err) if ok then local register_ok, register_err = register_user(form); response:send(generate_register_response(event, form, register_ok, register_err)); else response:send(generate_page(event, { register_error = err })); end end); return true; -- Leave connection open until we respond above end module:provides("http", { route = { GET = generate_page; POST = handle_form; }; });
mod_register_web: Indentation fix
mod_register_web: Indentation fix
Lua
mit
crunchuser/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,olax/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,vfedoroff/prosody-modules,joewalker/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,NSAKEY/prosody-modules,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,asdofindia/prosody-modules,apung/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,softer/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,jkprg/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,1st8/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,amenophis1er/prosody-modules,amenophis1er/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,syntafin/prosody-modules,1st8/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules
387bcc7c26b6e5ea93e318e8ae42a523641096c2
prosody/mod_groups_wordpress.lua
prosody/mod_groups_wordpress.lua
-- Prosody Wordpress UAM Group local rostermanager = require "core.rostermanager"; local datamanager = require "util.datamanager"; local jid = require "util.jid"; local DBI; local connection; local bare_sessions = bare_sessions; local params = module:get_option("wordpress"); local module_host = module:get_host(); function load_contacts() local groups = { default = {} }; local members = { }; local load_groups_sql = string.format("select ID id, groupname name from %suam_accessgroups", params.prefix); local load_groups_stmt = connection:prepare(load_groups_sql); if load_groups_stmt then load_groups_stmt:execute(); -- Fetch groups for group_row in load_groups_stmt:rows(true) do groups[group_row.name] = {}; module:log("debug", "New group: %s", tostring(group_row.name)); -- Match user with group local object_id_sql = string.format("select object_id from %suam_accessgroup_to_object where `group_id` = ?;", params.prefix); local object_id_stmt = connection:prepare(object_id_sql); if object_id_stmt then object_id_stmt:execute(group_row.id); for object_row in object_id_stmt:rows(true) do -- Fetch user information local user_sql = string.format("select user_login, display_name from %susers where `ID` = ?;", params.prefix); local user_stmt = connection:prepare(user_sql); if user_stmt then user_stmt:execute(object_row.object_id); if user_stmt:rowcount() > 0 then local user_row = user_stmt:fetch(true); bare_jid = string.format("%s@%s", user_row.user_login, module_host); groups[group_row.name][bare_jid] = user_row.display_name or false; members[bare_jid] = members[bare_jid] or {}; members[bare_jid][#members[bare_jid] + 1] = group_row.name; module:log("debug", "New member of %s: %s", group_row.name, bare_jid); end user_stmt:close(); end end object_id_stmt:close(); end end load_groups_stmt:close(); end module:log("info", "Groups loaded successfully"); return groups, members; end function inject_roster_contacts(username, host, roster) local groups, members = load_contacts(); local user_jid = username.."@"..host; module:log("debug", "Injecting group members to roster %s", user_jid); if not members[user_jid] and not members[false] then return; end -- Not a member of any groups local function import_jids_to_roster(group_name, groups) for member_jid in pairs(groups[group_name]) do -- Add them to roster module:log("debug", "processing jid %s in group %s", tostring(member_jid), tostring(group_name)); if member_jid ~= user_jid then if not roster[member_jid] then roster[member_jid] = {}; end roster[member_jid].subscription = "both"; if groups[group_name][member_jid] then roster[member_jid].name = groups[group_name][member_jid]; end if not roster[member_jid].groups then roster[member_jid].groups = { [group_name] = true }; end roster[member_jid].groups[group_name] = true; roster[member_jid].persist = false; end end end -- Find groups this JID is a member of if members[user_jid] then for _, group_name in ipairs(members[user_jid]) do module:log("debug", "Importing group %s", group_name); import_jids_to_roster(group_name, groups); end end -- Import public groups if members[false] then for _, group_name in ipairs(members[false]) do module:log("debug", "Importing group %s", group_name); import_jids_to_roster(group_name, groups); end end for online_jid, user in pairs(bare_sessions) do if (online_jid ~= user_jid) and roster[online_jid] then local other_roster = user.roster; if not other_roster[user_jid] then local node, host, resource = jid.split(user_jid); module:log("debug", "push %s to %s@%s", online_jid, node, host); rostermanager.roster_push(node, host, online_jid); end end end if roster[false] then roster[false].version = true; end end function remove_virtual_contacts(username, host, datastore, data) if host == module_host and datastore == "roster" then local new_roster = {}; for jid, contact in pairs(data) do if contact.persist ~= false then new_roster[jid] = contact; end end if new_roster[false] then new_roster[false].version = nil; -- Version is void end return username, host, datastore, new_roster; end return username, host, datastore, data; end function module.load() if params == nil then -- Don't load this module to virtual host doesn't have wordpress option return; end; initial_connection(); groups_wordpress_enable = params.groups if not groups_wordpress_enable then return; end module:hook("roster-load", inject_roster_contacts); datamanager.add_callback(remove_virtual_contacts); end function module.unload() datamanager.remove_callback(remove_virtual_contacts); end -- database methods from mod_storage_sql.lua local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( "MySQL", params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(false); -- don't commit automatically connection = dbh; return connection; end end function initial_connection() local ok; prosody.unlock_globals(); ok, DBI = pcall(require, "DBI"); if not ok then package.loaded["DBI"] = {}; module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI); module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi"); end prosody.lock_globals(); if not ok or not DBI.Connect then return; -- Halt loading of this module end params.host = params.host or "localhost"; params.port = params.port or 3306; params.database = params.database or "wordpress"; params.username = params.username or "root"; params.password = params.password or ""; params.prefix = params.prefix or "wp_"; params.groups = params.groups or false; assert(connect()); end
-- Prosody Wordpress UAM Group local rostermanager = require "core.rostermanager"; local datamanager = require "util.datamanager"; local jid = require "util.jid"; local DBI; local connection; local bare_sessions = bare_sessions; local params = module:get_option("wordpress"); local module_host = module:get_host(); function load_contacts() local groups = { default = {} }; local members = { }; local load_groups_sql = string.format("select ID id, groupname name from %suam_accessgroups", params.prefix); local load_groups_stmt = connection:prepare(load_groups_sql); if load_groups_stmt then load_groups_stmt:execute(); -- Fetch groups for group_row in load_groups_stmt:rows(true) do groups[group_row.name] = {}; module:log("debug", "New group: %s", tostring(group_row.name)); -- Match user with group local object_id_sql = string.format("select object_id from %suam_accessgroup_to_object where `group_id` = ?;", params.prefix); local object_id_stmt = connection:prepare(object_id_sql); if object_id_stmt then object_id_stmt:execute(group_row.id); for object_row in object_id_stmt:rows(true) do -- Fetch user information local user_sql = string.format("select user_login, display_name from %susers where `ID` = ?;", params.prefix); local user_stmt = connection:prepare(user_sql); if user_stmt then user_stmt:execute(object_row.object_id); if user_stmt:rowcount() > 0 then local user_row = user_stmt:fetch(true); bare_jid = string.format("%s@%s", user_row.user_login, module_host); groups[group_row.name][bare_jid] = user_row.display_name or false; members[bare_jid] = members[bare_jid] or {}; members[bare_jid][#members[bare_jid] + 1] = group_row.name; module:log("debug", "New member of %s: %s", group_row.name, bare_jid); end user_stmt:close(); end end object_id_stmt:close(); end end load_groups_stmt:close(); end module:log("info", "Groups loaded successfully"); return groups, members; end function inject_roster_contacts(username, host, roster) local groups, members = load_contacts(); local user_jid = username.."@"..host; module:log("debug", "Injecting group members to roster %s", user_jid); if not members[user_jid] and not members[false] then return; end -- Not a member of any groups local function import_jids_to_roster(group_name, groups) for member_jid in pairs(groups[group_name]) do -- Add them to roster module:log("debug", "processing jid %s in group %s", tostring(member_jid), tostring(group_name)); if member_jid ~= user_jid then if not roster[member_jid] then roster[member_jid] = {}; end roster[member_jid].subscription = "both"; if groups[group_name][member_jid] then roster[member_jid].name = groups[group_name][member_jid]; end if not roster[member_jid].groups then roster[member_jid].groups = { [group_name] = true }; end roster[member_jid].groups[group_name] = true; roster[member_jid].persist = false; end end end -- Find groups this JID is a member of if members[user_jid] then for _, group_name in ipairs(members[user_jid]) do module:log("debug", "Importing group %s", group_name); import_jids_to_roster(group_name, groups); end end -- Import public groups if members[false] then for _, group_name in ipairs(members[false]) do module:log("debug", "Importing group %s", group_name); import_jids_to_roster(group_name, groups); end end for online_jid, user in pairs(bare_sessions) do if (online_jid ~= user_jid) and roster[online_jid] then local other_roster = user.roster; if not other_roster[user_jid] then -- Don't need to make online user see new user but new user can see online user. other_roster[user_jid] = { subscription = "both"; persist = false; }; end end end if roster[false] then roster[false].version = true; end end function remove_virtual_contacts(username, host, datastore, data) if host == module_host and datastore == "roster" then local new_roster = {}; for jid, contact in pairs(data) do if contact.persist ~= false then new_roster[jid] = contact; end end if new_roster[false] then new_roster[false].version = nil; -- Version is void end return username, host, datastore, new_roster; end return username, host, datastore, data; end function module.load() if params == nil then -- Don't load this module to virtual host doesn't have wordpress option return; end; initial_connection(); groups_wordpress_enable = params.groups if not groups_wordpress_enable then return; end module:hook("roster-load", inject_roster_contacts); datamanager.add_callback(remove_virtual_contacts); end function module.unload() datamanager.remove_callback(remove_virtual_contacts); end -- database methods from mod_storage_sql.lua local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( "MySQL", params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(false); -- don't commit automatically connection = dbh; return connection; end end function initial_connection() local ok; prosody.unlock_globals(); ok, DBI = pcall(require, "DBI"); if not ok then package.loaded["DBI"] = {}; module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI); module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi"); end prosody.lock_globals(); if not ok or not DBI.Connect then return; -- Halt loading of this module end params.host = params.host or "localhost"; params.port = params.port or 3306; params.database = params.database or "wordpress"; params.username = params.username or "root"; params.password = params.password or ""; params.prefix = params.prefix or "wp_"; params.groups = params.groups or false; assert(connect()); end
Add roster to online contact. fixes #2
Add roster to online contact. fixes #2
Lua
mit
llun/wordpress-authenticator
ab0353aab82e359bab559aa1ab9dcfe9fa7dbd89
perf/fetch_add.lua
perf/fetch_add.lua
#!/usr/bin/env lua -- Measure add-fetch-notification throughput and the impact of a growing -- number of fetchers (which dont match). -- The time is measured for adding and removing <count> states. -- Afterwards, the number of fetchers is incremented by 20 and the test is repeated. -- This (unrealistic) setup can not benefit from message batches. --local profiler = require'profiler' local jet = require'jet' local ev = require'ev' local step = require'step' local cjson = require'cjson' local port = 10112 local daemon = jet.daemon.new({ port = port, crit = print }) daemon:start() local fetch_peer = jet.peer.new({ port = port }) local count = 10000 local long_path_prefix = string.rep('foobar',10) local add_remove = function(done) local state_peer = jet.peer.new({ port = port, log = function(...) print('problem',...) end, on_connect = function(state_peer) local last_path = long_path_prefix..tostring(count) local states = {} local added local t_start state_peer:fetch('^'..last_path..'$',function(path,event,value,fetcher) assert(path == last_path) if event == 'add' then assert(not added) added = true state_peer:batch(function() for i,state in ipairs(states) do state:remove() end end) elseif event == 'remove' then fetcher:unfetch({ success = function() local t_end = socket.gettime() state_peer:close() collectgarbage() done(t_end - t_start) end, error = function() assert(false,'arg') end }) end end) t_start = socket.gettime() state_peer:batch(function() for i=1,count do states[i] = state_peer:state({ path = long_path_prefix..i, value = 123 }) end end) end }) end local fetchers = 1 local print_and_increment_fetchers = function(dt) print(math.floor(count/dt),'add-remove/sec @'..fetchers..' fetchers') for i=1,20 do fetch_peer:fetch('^'..long_path_prefix..fetchers..'f$',function() end) fetchers = fetchers + 1 end end local tries = {} for i=1,10 do tries[i] = function(step) add_remove(function(dt) print_and_increment_fetchers(dt) step.success() end) end end step.new({ try = tries, finally = function() fetch_peer:close() daemon:stop() end, catch = function(step,...) print(cjson.encode({...})) end })() --profiler.start() ev.Loop.default:loop() --profiler.stop()
#!/usr/bin/env lua -- Measure add-fetch-notification throughput and the impact of a growing -- number of fetchers (which dont match). -- The time is measured for adding and removing <count> states. -- Afterwards, the number of fetchers is incremented by 20 and the test is repeated. -- Note that the add/remove peer stuff benefits from batching messages! --local profiler = require'profiler' local jet = require'jet' local ev = require'ev' local step = require'step' local cjson = require'cjson' local port = 10112 local daemon = jet.daemon.new({ port = port, crit = print }) daemon:start() local fetch_peer = jet.peer.new({ port = port }) local count = 10000 local long_path_prefix = string.rep('foobar',10) local add_remove = function(done) local state_peer = jet.peer.new({ port = port, log = function(...) print('problem',...) end, on_connect = function(state_peer) local last_path = long_path_prefix..tostring(count) local states = {} local added local t_start state_peer:fetch('^'..last_path..'$',function(path,event,value,fetcher) assert(path == last_path) if event == 'add' then assert(not added) added = true for i,state in ipairs(states) do state:remove() end elseif event == 'remove' then fetcher:unfetch({ success = function() local t_end = socket.gettime() state_peer:close() collectgarbage() done(t_end - t_start) end, error = function() assert(false,'arg') end }) end end) t_start = socket.gettime() for i=1,count do states[i] = state_peer:state({ path = long_path_prefix..i, value = 123 }) end end }) end local fetchers = 1 local print_and_increment_fetchers = function(dt) print(math.floor(count/dt),'add-remove/sec @'..fetchers..' fetchers') for i=1,20 do fetch_peer:fetch('^'..long_path_prefix..fetchers..'f$',function() end) fetchers = fetchers + 1 end end local tries = {} for i=1,10 do tries[i] = function(step) add_remove(function(dt) print_and_increment_fetchers(dt) step.success() end) end end step.new({ try = tries, finally = function() fetch_peer:close() daemon:stop() end, catch = function(step,...) print(cjson.encode({...})) end })() --profiler.start() ev.Loop.default:loop() --profiler.stop()
remove explicit batching, fix comment on batching
remove explicit batching, fix comment on batching
Lua
mit
lipp/lua-jet
52af622c1093c038e600feae7cc65e10e7f93025
luasrc/mch/response.lua
luasrc/mch/response.lua
#!/usr/bin/env lua -- -*- lua -*- -- Copyright 2012 Appwill Inc. -- Author : KDr2 -- -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- module('mch.response',package.seeall) mchutil=require('mch.util') functional=require('mch.functional') ltp=require("ltp.template") Response={ltp=ltp} function Response:new() local ret={ headers=ngx.header, _cookies={}, _output={} } setmetatable(ret,self) self.__index=self return ret end function Response:write(content) table.insert(self._output,content) end function Response:writeln(content) table.insert(self._output,content) table.insert(self._output,"\r\n") end function Response:redirect(url, status) ngx.redirect(url, status) end function Response:_set_cookie(key, value, encrypt, duration, path) if not value then return nil end if not key or key=="" or not value then return end if not duration or duration<=0 then duration=86400 end if not path or path=="" then path = "/" end if value and value~="" and encrypt==true then value=ndk.set_var.set_encrypt_session(value) value=ndk.set_var.set_encode_base64(value) end local expiretime=ngx.time()+duration expiretime = ngx.cookie_time(expiretime) return table.concat({key, "=", value, "; expires=", expiretime, "; path=", path}) end function Response:set_cookie(key, value, encrypt, duration, path) local cookie=self:_set_cookie(key, value, encrypt, duration, path) self._cookies[key]=cookie ngx.header["Set-Cookie"]=mch.functional.table_values(self._cookies) end --[[ LTP Template Support --]] ltp_templates_cache={} function ltp_function(template) ret=ltp_templates_cache[template] if ret then return ret end local tdata=mchutil.read_all(MOOCHINE_APP_PATH .. "/templates/" .. template) if not tdata then tdata=mchutil.read_all(MOOCHINE_EXTRA_APP_PATH .. "/templates/" .. template) end local rfun = ltp.load_template(tdata, '<?lua','?>') ltp_templates_cache[template]=rfun return rfun end function Response:ltp(template,data) local rfun=ltp_function(template) local output = {} local mt={__index=_G} setmetatable(data,mt) ltp.execute_template(rfun, data, output) table.insert(self._output,output) end
#!/usr/bin/env lua -- -*- lua -*- -- Copyright 2012 Appwill Inc. -- Author : KDr2 -- -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- module('mch.response',package.seeall) local mchutil=require('mch.util') local functional=require('mch.functional') local ltp=require("ltp.template") local MOOCHINE_APP_PATH = ngx.var.MOOCHINE_APP local MOOCHINE_EXTRA_APP_PATH = ngx.var.MOOCHINE_APP_EXTRA Response={ltp=ltp} function Response:new() local ret={ headers=ngx.header, _cookies={}, _output={} } setmetatable(ret,self) self.__index=self return ret end function Response:write(content) table.insert(self._output,content) end function Response:writeln(content) table.insert(self._output,content) table.insert(self._output,"\r\n") end function Response:redirect(url, status) ngx.redirect(url, status) end function Response:_set_cookie(key, value, encrypt, duration, path) if not value then return nil end if not key or key=="" or not value then return end if not duration or duration<=0 then duration=86400 end if not path or path=="" then path = "/" end if value and value~="" and encrypt==true then value=ndk.set_var.set_encrypt_session(value) value=ndk.set_var.set_encode_base64(value) end local expiretime=ngx.time()+duration expiretime = ngx.cookie_time(expiretime) return table.concat({key, "=", value, "; expires=", expiretime, "; path=", path}) end function Response:set_cookie(key, value, encrypt, duration, path) local cookie=self:_set_cookie(key, value, encrypt, duration, path) self._cookies[key]=cookie ngx.header["Set-Cookie"]=mch.functional.table_values(self._cookies) end --[[ LTP Template Support --]] ltp_templates_cache={} function ltp_function(template) ret=ltp_templates_cache[template] if ret then return ret end local tdata=mchutil.read_all(MOOCHINE_APP_PATH .. "/templates/" .. template) if not tdata then tdata=mchutil.read_all(MOOCHINE_EXTRA_APP_PATH .. "/templates/" .. template) end local rfun = ltp.load_template(tdata, '<?lua','?>') ltp_templates_cache[template]=rfun return rfun end function Response:ltp(template,data) local rfun=ltp_function(template) local output = {} local mt={__index=_G} setmetatable(data,mt) ltp.execute_template(rfun, data, output) table.insert(self._output,output) end
fixed MOOCHINE_APP_PATH and MOOCHINE_EXTRA_APP_PATH
fixed MOOCHINE_APP_PATH and MOOCHINE_EXTRA_APP_PATH
Lua
apache-2.0
appwilldev/moochine,appwilldev/moochine,lilien1010/moochine,lilien1010/moochine,lilien1010/moochine
522e9fce277e0a3b99ccc39d41fb7dbfb5ce58ff
durden/tools/flair/destroy.lua
durden/tools/flair/destroy.lua
local destroy_shid; local shaders = { -- a more ambitious version would use a LUT to give a perlin-noise -- like distribution, weight that with the contents and the distance -- to the last known mouse cursor position, with an edge gradient -- using yellow-red-blacks for the burn. burn = {nil, nil, [[ uniform sampler2D map_tu0; varying vec2 texco; uniform float trans_blend; void main() { vec4 col = texture2D(map_tu0, texco); float intens = (col.r + col.g + col.b) / 3.0; if (intens < trans_blend) discard; col.a = 1.0; gl_FragColor = col; } ]], "destroy_burn" }, }; -- on-demand compile shaders local function synch_shader(key) local sk = shaders[key]; assert(sk); if (sk[1]) then return sk[1]; else sk[1] = build_shader(sk[2], sk[3], sk[4]); return sk[1]; end end -- generic runner for creating a canvas copy and dispatching a -- shader, can be re-used for all effects that don't require special -- details like window specific uniforms local function run_shader(key, wm, wnd, space, space_active, popup) if (not space_active) then return; end local props = image_surface_resolve(wnd.canvas); local vid = null_surface(props.width, props.height); show_image(vid); move_image(vid, props.x, props.y); image_sharestorage(wnd.canvas, vid); expire_image(vid, gconfig_get("flair_speed")+1); blend_image(vid, 0.0, gconfig_get("flair_speed")); image_shader(vid, synch_shader("dissolve")); end return { dissolve = function(...) run_shader("dissolve", ...); end };
local destroy_shid; local shaders = { -- a more ambitious version would use a LUT to give a perlin-noise -- like distribution, weight that with the contents and the distance -- to the last known mouse cursor position, with an edge gradient -- using yellow-red-blacks for the burn. dissolve = {nil, nil, [[ uniform sampler2D map_tu0; varying vec2 texco; uniform float trans_blend; void main() { vec4 col = texture2D(map_tu0, texco); float intens = (col.r + col.g + col.b) / 3.0; if (intens < trans_blend) discard; col.a = 1.0; gl_FragColor = col; } ]], "destroy_burn" }, }; -- on-demand compile shaders local function synch_shader(key) print("try to synch:", key); local sk = shaders[key]; assert(sk); if (sk[1]) then return sk[1]; else sk[1] = build_shader(sk[2], sk[3], sk[4]); return sk[1]; end end -- generic runner for creating a canvas copy and dispatching a -- shader, can be re-used for all effects that don't require special -- details like window specific uniforms local function run_shader(key, wm, wnd, space, space_active, popup) if (not space_active) then return; end local props = image_surface_resolve(wnd.canvas); local vid = null_surface(props.width, props.height); show_image(vid); move_image(vid, props.x, props.y); image_sharestorage(wnd.canvas, vid); expire_image(vid, gconfig_get("flair_speed")+1); blend_image(vid, 0.0, gconfig_get("flair_speed")); image_shader(vid, synch_shader("dissolve")); end return { dissolve = function(...) run_shader("dissolve", ...); end };
fix typo in destroy flair
fix typo in destroy flair
Lua
bsd-3-clause
letoram/durden
519f1e9b1feb9d2eb83aa7d0859c903feaa9c321
scripts/lua/policies/mapping.lua
scripts/lua/policies/mapping.lua
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- --- @module mapping -- Process mapping object, turning implementation details into request transformations local logger = require "lib/logger" local utils = require "lib/utils" local cjson = require "cjson.safe" local _M = {} local body local query local headers local path --- Implementation for the mapping policy. -- @param map The mapping object that contains details about request tranformations function processMap(map) getRequestParams() for k, v in pairs(map) do if v.action == "insert" then insertParam(v) elseif v.action == "remove" then removeParam(v) elseif v.action == "transform" then transformParam(v) elseif v.action == "default" then checkDefault(v) else logger.err(utils.concatStrings({'Map action not recognized. Skipping... ', v.action})) end end finalize() end --- Get request body, params, and headers from incoming requests function getRequestParams() ngx.req.read_body() body = ngx.req.get_body_data() if body ~= nil then -- decode body if json decoded, err = cjson.decode(body) if err == nil then body = decoded end else body = {} end headers = ngx.req.get_headers() path = ngx.var.uri query = parseUrl(ngx.var.backendUrl) local incomingQuery = ngx.req.get_uri_args() for k, v in pairs (incomingQuery) do query[k] = v end end --- Insert parameter value to header, body, or query params into request -- @param m Parameter value to add to request function insertParam(m) local v local k = m.to.name if m.from.value ~= nil then v = m.from.value elseif m.from.location == 'header' then v = headers[m.from.name] elseif m.from.location == 'query' then v = query[m.from.name] elseif m.from.location == 'body' then v = body[m.from.name] elseif m.from.location == 'path' then v = ngx.ctx[m.from.name] end -- determine to where if m.to.location == 'header' then insertHeader(k, v) elseif m.to.location == 'query' then insertQuery(k, v) elseif m.to.location == 'body' then insertBody(k, v) elseif m.to.location == 'path' then insertPath(k,v) end end --- Remove parameter value to header, body, or query params from request -- @param m Parameter value to remove from request function removeParam(m) if m.from.location == "header" then removeHeader(m.from.name) elseif m.from.location == "query" then removeQuery(m.from.name) elseif m.from.location == "body" then removeBody(m.from.name) end end --- Move parameter value from one location to another in the request -- @param m Parameter value to move within request function transformParam(m) if m.from.name == '*' then transformAllParams(m.from.location, m.to.location) else insertParam(m) removeParam(m) end end --- Checks if the header has been set, and sets the header to a value if found to be null. -- @param m Header name and value to be set, if header is null. function checkDefault(m) if m.to.location == "header" and headers[m.to.name] == nil then insertHeader(m.to.name, m.from.value) elseif m.to.location == "query" and query[m.to.name] == nil then insertQuery(m.to.name, m.from.value) elseif m.to.location == "body" and body[m.to.name] == nil then insertBody(m.to.name, m.from.value) end end --- Function to handle wildcarding in the transform process. -- If the value in the from object is '*', this function will pull all values from the incoming request -- and move them to the location provided in the to object -- @param s The source object from which we pull all parameters -- @param d The destination object that we will move all found parameters to. function transformAllParams(s, d) if s == 'query' then for k, v in pairs(query) do local t = {} t.from = {} t.from.name = k t.from.location = s t.to = {} t.to.name = k t.to.location = d insertParam(t) removeParam(t) end elseif s == 'header' then for k, v in pairs(headers) do local t = {} t.from = {} t.from.name = k t.from.location = s t.to = {} t.to.name = k t.to.location = d insertParam(t) removeParam(t) end elseif s == 'body' then for k, v in pairs(body) do local t = {} t.from = {} t.from.name = k t.from.location = s t.to = {} t.to.name = k t.to.location = d insertParam(t) removeParam(t) end elseif s == 'path' then for k, v in pairs(path) do local t = {} t.from = {} t.from.name = k t.from.location = s t.to = {} t.to.name = k t.to.location = d insertParam(t) removeParam(t) end end end function finalize() if type(body) == 'table' and next(body) ~= nil then local bodyJson = cjson.encode(body) ngx.req.set_body_data(bodyJson) end ngx.req.set_uri_args(query) end function insertHeader(k, v) ngx.req.set_header(k, v) headers[k] = v end function insertQuery(k, v) query[k] = v end function insertBody(k, v) body[k] = v end function insertPath(k, v) v = ngx.unescape_uri(v) path = path:gsub(utils.concatStrings({"%{", k ,"%}"}), v) ngx.req.set_uri(path) end function removeHeader(k) ngx.req.clear_header(k) end function removeQuery(k) query[k] = nil end function removeBody(k) body[k] = nil end function parseUrl(url) local map = {} for k,v in url:gmatch('([^&=?]+)=([^&=?]+)') do map[ k ] = decodeQuery(v) end return map end function decodeQuery(param) local decoded = param:gsub('+', ' '):gsub('%%(%x%x)', function(hex) return string.char(tonumber(hex, 16)) end) return decoded end _M.processMap = processMap return _M
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- --- @module mapping -- Process mapping object, turning implementation details into request transformations local logger = require "lib/logger" local utils = require "lib/utils" local cjson = require "cjson.safe" cjson.decode_array_with_array_mt(true) local _M = {} local body local query local headers local path --- Implementation for the mapping policy. -- @param map The mapping object that contains details about request tranformations function processMap(map) getRequestParams() for k, v in pairs(map) do if v.action == "insert" then insertParam(v) elseif v.action == "remove" then removeParam(v) elseif v.action == "transform" then transformParam(v) elseif v.action == "default" then checkDefault(v) else logger.err(utils.concatStrings({'Map action not recognized. Skipping... ', v.action})) end end finalize() end --- Get request body, params, and headers from incoming requests function getRequestParams() ngx.req.read_body() body = ngx.req.get_body_data() if body ~= nil then -- decode body if json decoded, err = cjson.decode(body) if err == nil then body = decoded end else body = {} end headers = ngx.req.get_headers() path = ngx.var.uri query = parseUrl(ngx.var.backendUrl) local incomingQuery = ngx.req.get_uri_args() for k, v in pairs (incomingQuery) do query[k] = v end end --- Insert parameter value to header, body, or query params into request -- @param m Parameter value to add to request function insertParam(m) local v local k = m.to.name if m.from.value ~= nil then v = m.from.value elseif m.from.location == 'header' then v = headers[m.from.name] elseif m.from.location == 'query' then v = query[m.from.name] elseif m.from.location == 'body' then v = body[m.from.name] elseif m.from.location == 'path' then v = ngx.ctx[m.from.name] end -- determine to where if m.to.location == 'header' then insertHeader(k, v) elseif m.to.location == 'query' then insertQuery(k, v) elseif m.to.location == 'body' then insertBody(k, v) elseif m.to.location == 'path' then insertPath(k,v) end end --- Remove parameter value to header, body, or query params from request -- @param m Parameter value to remove from request function removeParam(m) if m.from.location == "header" then removeHeader(m.from.name) elseif m.from.location == "query" then removeQuery(m.from.name) elseif m.from.location == "body" then removeBody(m.from.name) end end --- Move parameter value from one location to another in the request -- @param m Parameter value to move within request function transformParam(m) if m.from.name == '*' then transformAllParams(m.from.location, m.to.location) else insertParam(m) removeParam(m) end end --- Checks if the header has been set, and sets the header to a value if found to be null. -- @param m Header name and value to be set, if header is null. function checkDefault(m) if m.to.location == "header" and headers[m.to.name] == nil then insertHeader(m.to.name, m.from.value) elseif m.to.location == "query" and query[m.to.name] == nil then insertQuery(m.to.name, m.from.value) elseif m.to.location == "body" and body[m.to.name] == nil then insertBody(m.to.name, m.from.value) end end --- Function to handle wildcarding in the transform process. -- If the value in the from object is '*', this function will pull all values from the incoming request -- and move them to the location provided in the to object -- @param s The source object from which we pull all parameters -- @param d The destination object that we will move all found parameters to. function transformAllParams(s, d) if s == 'query' then for k, v in pairs(query) do local t = {} t.from = {} t.from.name = k t.from.location = s t.to = {} t.to.name = k t.to.location = d insertParam(t) removeParam(t) end elseif s == 'header' then for k, v in pairs(headers) do local t = {} t.from = {} t.from.name = k t.from.location = s t.to = {} t.to.name = k t.to.location = d insertParam(t) removeParam(t) end elseif s == 'body' then for k, v in pairs(body) do local t = {} t.from = {} t.from.name = k t.from.location = s t.to = {} t.to.name = k t.to.location = d insertParam(t) removeParam(t) end elseif s == 'path' then for k, v in pairs(path) do local t = {} t.from = {} t.from.name = k t.from.location = s t.to = {} t.to.name = k t.to.location = d insertParam(t) removeParam(t) end end end function finalize() if type(body) == 'table' and next(body) ~= nil then local bodyJson = cjson.encode(body) ngx.req.set_body_data(bodyJson) end ngx.req.set_uri_args(query) end function insertHeader(k, v) ngx.req.set_header(k, v) headers[k] = v end function insertQuery(k, v) query[k] = v end function insertBody(k, v) body[k] = v end function insertPath(k, v) v = ngx.unescape_uri(v) path = path:gsub(utils.concatStrings({"%{", k ,"%}"}), v) ngx.req.set_uri(path) end function removeHeader(k) ngx.req.clear_header(k) end function removeQuery(k) query[k] = nil end function removeBody(k) body[k] = nil end function parseUrl(url) local map = {} for k,v in url:gmatch('([^&=?]+)=([^&=?]+)') do map[ k ] = decodeQuery(v) end return map end function decodeQuery(param) local decoded = param:gsub('+', ' '):gsub('%%(%x%x)', function(hex) return string.char(tonumber(hex, 16)) end) return decoded end _M.processMap = processMap return _M
Fix array handling during mapping operations (#359)
Fix array handling during mapping operations (#359)
Lua
unknown
openwhisk/openwhisk-apigateway,openwhisk/apigateway,openwhisk/openwhisk-apigateway,openwhisk/openwhisk-apigateway,openwhisk/apigateway,openwhisk/apigateway
a0c56a163baf43344d81f99213abbef5cc31d2f6
nvim/lua/config/cmp.lua
nvim/lua/config/cmp.lua
local has_words_before = function() if vim.api.nvim_buf_get_option(0, 'buftype') == 'prompt' then return false end local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match('%s') == nil end local feedkey = function(key, mode) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true) end local cmp = require('cmp') cmp.setup({ snippet = { expand = function(args) -- For `vsnip` user. -- vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` user. -- For `luasnip` user. -- require('luasnip').lsp_expand(args.body) -- For `ultisnips` user. -- vim.fn["UltiSnips#Anon"](args.body) end, }, mapping = { ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm({ select = true }), ['<Tab>'] = cmp.mapping(function(fallback) if vim.fn.pumvisible() == 1 then feedkey('<C-n>', 'n') elseif vim.fn['vsnip#available']() == 1 then feedkey('<Plug>(vsnip-expand-or-jump)', '') elseif has_words_before() then cmp.complete() else fallback() -- The fallback function sends a already mapped key. In this case, it's probably `<Tab>`. end end, { 'i', 's', }), ['<S-Tab>'] = cmp.mapping(function() if vim.fn.pumvisible() == 1 then feedkey('<C-p>', 'n') elseif vim.fn['vsnip#jumpable'](-1) == 1 then feedkey('<Plug>(vsnip-jump-prev)', '') end end, { 'i', 's', }), }, sources = { { name = 'nvim_lsp' }, -- For vsnip user. -- { name = 'vsnip' }, -- For luasnip user. -- { name = 'luasnip' }, -- For ultisnips user. -- { name = 'ultisnips' }, { name = 'buffer' }, { name = 'nvim_lua' }, }, })
local has_words_before = function() if vim.api.nvim_buf_get_option(0, 'buftype') == 'prompt' then return false end local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match('%s') == nil end local feedkey = function(key, mode) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true) end local cmp = require('cmp') cmp.setup({ snippet = { expand = function(args) -- For `vsnip` user. -- vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` user. -- For `luasnip` user. -- require('luasnip').lsp_expand(args.body) -- For `ultisnips` user. -- vim.fn["UltiSnips#Anon"](args.body) end, }, mapping = { ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm({ select = true }), ['<Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif vim.fn['vsnip#available'](1) == 1 then feedkey('<Plug>(vsnip-expand-or-jump)', '') elseif has_words_before() then cmp.complete() else fallback() -- The fallback function sends a already mapped key. In this case, it's probably `<Tab>`. end end, { 'i', 's', }), ['<S-Tab>'] = cmp.mapping(function() if cmp.visible() then cmp.select_prev_item() elseif vim.fn['vsnip#jumpable'](-1) == 1 then feedkey('<Plug>(vsnip-jump-prev)', '') end end, { 'i', 's', }), }, sources = { { name = 'nvim_lsp' }, -- For vsnip user. -- { name = 'vsnip' }, -- For luasnip user. -- { name = 'luasnip' }, -- For ultisnips user. -- { name = 'ultisnips' }, { name = 'buffer' }, { name = 'nvim_lua' }, }, })
fix: nvim-cmp for tab/s-tab
fix: nvim-cmp for tab/s-tab
Lua
mit
drmohundro/dotfiles
fd438e983afbae2192a4f109eef748d9329abf30
packages/textcase/init.lua
packages/textcase/init.lua
local base = require("packages.base") local package = pl.class(base) package._name = "tetxcase" local icu = require("justenoughicu") local uppercase = function (class, input, extraArgs) if type(class) ~= "table" or class.type ~= "class" then input, extraArgs = class, input end if not extraArgs then extraArgs = {} end if not extraArgs.options then extraArgs.options = {} end local lang = extraArgs.options.language or SILE.settings:get("document.language") return icu.case(input, lang, "upper") end local lowercase = function (class, input, extraArgs) if type(class) == "table" and class.type ~= "class" then input, extraArgs = class, input end if not extraArgs then extraArgs = {} end if not extraArgs.options then extraArgs.options = {} end local lang = extraArgs.options.language or SILE.settings:get("document.language") return icu.case(input, lang, "lower") end local titlecase = function (class, input, extraArgs) if type(class) == "table" and class.type ~= "class" then input, extraArgs = class, input end if not extraArgs then extraArgs = {} end if not extraArgs.options then extraArgs.options = {} end local lang = extraArgs.options.language or SILE.settings:get("document.language") return icu.case(input, lang, "title") end function package:_init () base._init(self) self.class:loadPackage("inputfilter") self:deprecatedExport("uppercase", uppercase) self:deprecatedExport("lowercase", lowercase) self:deprecatedExport("titlecase", titlecase) end function package:registerCommands () self:registerCommand("uppercase", function(options, content) SILE.process(self.class.packages.inputfilter:transformContent(content, uppercase, options)) end, "Typeset the enclosed text as uppercase") self:registerCommand("lowercase", function(options, content) SILE.process(self.class.packages.inputfilter:transformContent(content, lowercase, options)) end, "Typeset the enclosed text as lowercase") self:registerCommand("titlecase", function(options, content) SILE.process(self.class.packages.inputfilter:transformContent(content, titlecase, options)) end, "Typeset the enclosed text as titlecase") end package.documentation = [[ \begin{document} \use[module=packages.textcase] The \autodoc:package{textcase} package provides commands for language-aware case conversion of input text. For example, when language is set to English, then \autodoc:command{\uppercase{hij}} will return \examplefont{\uppercase{hij}}. However, when language is set to Turkish, it will return \examplefont{\font[language=tr]{\uppercase{hij}}}. As well as \autodoc:command{\uppercase}, the package provides the commands \autodoc:command{\lowercase} and \autodoc:command{\titlecase}. \end{document} ]] return package
local base = require("packages.base") local package = pl.class(base) package._name = "tetxcase" local icu = require("justenoughicu") function package:uppercase (input, extraArgs) if type(self) ~= "table" or (self.type ~= "class" and self.type ~= "package") then input, extraArgs = self, input end if not extraArgs then extraArgs = {} end if not extraArgs.options then extraArgs.options = {} end local lang = extraArgs.options.language or SILE.settings:get("document.language") return icu.case(input, lang, "upper") end function package:lowercase (input, extraArgs) if type(self) ~= "table" or (self.type ~= "class" and self.type ~= "package") then input, extraArgs = self, input end if not extraArgs then extraArgs = {} end if not extraArgs.options then extraArgs.options = {} end local lang = extraArgs.options.language or SILE.settings:get("document.language") return icu.case(input, lang, "lower") end function package:titlecase (input, extraArgs) if type(self) ~= "table" or (self.type ~= "class" and self.type ~= "package") then input, extraArgs = self, input end if not extraArgs then extraArgs = {} end if not extraArgs.options then extraArgs.options = {} end local lang = extraArgs.options.language or SILE.settings:get("document.language") return icu.case(input, lang, "title") end function package:_init () base._init(self) self.class:loadPackage("inputfilter") self:deprecatedExport("uppercase", self.uppercase) self:deprecatedExport("lowercase", self.lowercase) self:deprecatedExport("titlecase", self.titlecase) end function package:registerCommands () self:registerCommand("uppercase", function(options, content) SILE.process(self.class.packages.inputfilter:transformContent(content, self.uppercase, options)) end, "Typeset the enclosed text as uppercase") self:registerCommand("lowercase", function(options, content) SILE.process(self.class.packages.inputfilter:transformContent(content, self.lowercase, options)) end, "Typeset the enclosed text as lowercase") self:registerCommand("titlecase", function(options, content) SILE.process(self.class.packages.inputfilter:transformContent(content, self.titlecase, options)) end, "Typeset the enclosed text as titlecase") end package.documentation = [[ \begin{document} \use[module=packages.textcase] The \autodoc:package{textcase} package provides commands for language-aware case conversion of input text. For example, when language is set to English, then \autodoc:command{\uppercase{hij}} will return \examplefont{\uppercase{hij}}. However, when language is set to Turkish, it will return \examplefont{\font[language=tr]{\uppercase{hij}}}. As well as \autodoc:command{\uppercase}, the package provides the commands \autodoc:command{\lowercase} and \autodoc:command{\titlecase}. \end{document} ]] return package
fix(packages): Correct (and improve scope of) exported testcase functions
fix(packages): Correct (and improve scope of) exported testcase functions The internal uppercase() function was exported using the deprecated export mechanism, but lowercase() and titlecase() were tripping over their own shim logic. This fixes the shim logic but also exports them as package functions which should be used going forward.
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
7a0bc4bd85c3c3fc20aea34e6bd4efbe695cde97
tools/ejabberdsql2prosody.lua
tools/ejabberdsql2prosody.lua
#!/usr/bin/env 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. -- package.path = package.path ..";../?.lua"; local serialize = require "util.serialization".serialize; local st = require "util.stanza"; package.loaded["util.logger"] = {init = function() return function() end; end} local dm = require "util.datamanager" dm.set_data_path("data"); function parseFile(filename) ------ local file = nil; local last = nil; local function read(expected) local ch; if last then ch = last; last = nil; else ch = file:read(1); end if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil")); end return ch; end local function pushback(ch) if last then error(); end last = ch; end local function peek() if not last then last = read(); end return last; end local function unescape(s) if s == "\\'" then return "'"; end if s == "\\n" then return "\n"; end error("Unknown escape sequence: "..s); end local function readString() read("'"); local s = ""; while true do local ch = peek(); if ch == "\\" then s = s..unescape(read()..read()); elseif ch == "'" then break; else s = s..read(); end end read("'"); return s; end local function readNonString() local s = ""; while true do if peek() == "," or peek() == ")" then break; else s = s..read(); end end return tonumber(s); end local function readItem() if peek() == "'" then return readString(); else return readNonString(); end end local function readTuple() local items = {} read("("); while peek() ~= ")" do table.insert(items, readItem()); if peek() == ")" then break; end read(","); end read(")"); return items; end local function readTuples() if peek() ~= "(" then read("("); end local tuples = {}; while true do table.insert(tuples, readTuple()); if peek() == "," then read() end if peek() == ";" then break; end end return tuples; end local function readTableName() local tname = ""; while peek() ~= "`" do tname = tname..read(); end return tname; end local function readInsert() if peek() == nil then return nil; end for ch in ("INSERT INTO `"):gmatch(".") do -- find line starting with this if peek() == ch then read(); -- found else -- match failed, skip line while peek() and read() ~= "\n" do end return nil; end end local tname = readTableName(); for ch in ("` VALUES "):gmatch(".") do read(ch); end -- expect this local tuples = readTuples(); read(";"); read("\n"); return tname, tuples; end local function readFile(filename) file = io.open(filename); if not file then error("File not found: "..filename); os.exit(0); end local t = {}; while true do local tname, tuples = readInsert(); if tname then t[tname] = tuples; elseif peek() == nil then break; end end return t; end return readFile(filename); ------ end local arg, host = ...; local help = "/? -? ? /h -h /help -help --help"; if not(arg and host) or help:find(arg, 1, true) then print([[ejabberd SQL DB dump importer for Prosody Usage: ejabberdsql2prosody.lua filename.txt hostname The file can be generated using mysqldump: mysqldump db_name > filename.txt]]); os.exit(1); end local map = { ["last"] = {"username", "seconds", "state"}; ["privacy_default_list"] = {"username", "name"}; ["privacy_list"] = {"username", "name", "id"}; ["privacy_list_data"] = {"id", "t", "value", "action", "ord", "match_all", "match_iq", "match_message", "match_presence_in", "match_presence_out"}; ["private_storage"] = {"username", "namespace", "data"}; ["rostergroups"] = {"username", "jid", "grp"}; ["rosterusers"] = {"username", "jid", "nick", "subscription", "ask", "askmessage", "server", "subscribe", "type"}; ["spool"] = {"username", "xml", "seq"}; ["users"] = {"username", "password"}; ["vcard"] = {"username", "vcard"}; --["vcard_search"] = {}; } local NULL = {}; local t = parseFile(arg); for name, data in pairs(t) do local m = map[name]; if m then for i=1,#data do local row = data[i]; for j=1,#row do row[m[j]] = row[j]; row[j] = nil; end end end end --print(serialize(t)); for i, row in ipairs(t["users"] or NULL) do local node, password = row.username, row.password; local ret, err = dm.store(node, host, "accounts", {password = password}); print("["..(err or "success").."] accounts: "..node.."@"..host.." = "..password); end function roster(node, host, jid, item) local roster = dm.load(node, host, "roster") or {}; roster[jid] = item; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid); end function roster_pending(node, host, jid) local roster = dm.load(node, host, "roster") or {}; roster.pending = roster.pending or {}; roster.pending[jid] = true; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid); end function roster_group(node, host, jid, group) local roster = dm.load(node, host, "roster") or {}; local item = roster[jid]; if not item then print("Warning: No roster item "..jid.." for user "..user..", can't put in group "..group); return; end item.groups[group] = true; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid); end for i, row in ipairs(t["rosterusers"] or NULL) do local node, contact = row.username, row.jid; local name = row.nick; if name == "" then name = nil; end local subscription = row.subscription; if subscription == "N" then subscription = "none" elseif subscription == "B" then subscription = "both" elseif subscription == "F" then subscription = "from" elseif subscription == "T" then subscription = "to" else error("Unknown subscription type: "..subscription) end; local ask = row.ask; if ask == "N" then ask = nil; elseif ask == "O" then ask = "subscribe"; elseif ask == "I" then roster_pending(node, host, contact); return; else error("Unknown ask type: "..ask); end local item = {name = name, ask = ask, subscription = subscription, groups = {}}; roster(node, host, contact, item); end for i, row in ipairs(t["rostergroups"] or NULL) do roster_group(row.username, host, row.jid, row.grp); end
#!/usr/bin/env 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. -- package.path = package.path ..";../?.lua"; local serialize = require "util.serialization".serialize; local st = require "util.stanza"; package.loaded["util.logger"] = {init = function() return function() end; end} local dm = require "util.datamanager" dm.set_data_path("data"); function parseFile(filename) ------ local file = nil; local last = nil; local function read(expected) local ch; if last then ch = last; last = nil; else ch = file:read(1); end if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil")); end return ch; end local function pushback(ch) if last then error(); end last = ch; end local function peek() if not last then last = read(); end return last; end local function unescape(s) if s == "\\'" then return "'"; end if s == "\\n" then return "\n"; end error("Unknown escape sequence: "..s); end local function readString() read("'"); local s = ""; while true do local ch = peek(); if ch == "\\" then s = s..unescape(read()..read()); elseif ch == "'" then break; else s = s..read(); end end read("'"); return s; end local function readNonString() local s = ""; while true do if peek() == "," or peek() == ")" then break; else s = s..read(); end end return tonumber(s); end local function readItem() if peek() == "'" then return readString(); else return readNonString(); end end local function readTuple() local items = {} read("("); while peek() ~= ")" do table.insert(items, readItem()); if peek() == ")" then break; end read(","); end read(")"); return items; end local function readTuples() if peek() ~= "(" then read("("); end local tuples = {}; while true do table.insert(tuples, readTuple()); if peek() == "," then read() end if peek() == ";" then break; end end return tuples; end local function readTableName() local tname = ""; while peek() ~= "`" do tname = tname..read(); end return tname; end local function readInsert() if peek() == nil then return nil; end for ch in ("INSERT INTO `"):gmatch(".") do -- find line starting with this if peek() == ch then read(); -- found else -- match failed, skip line while peek() and read() ~= "\n" do end return nil; end end local tname = readTableName(); for ch in ("` VALUES "):gmatch(".") do read(ch); end -- expect this local tuples = readTuples(); read(";"); read("\n"); return tname, tuples; end local function readFile(filename) file = io.open(filename); if not file then error("File not found: "..filename); os.exit(0); end local t = {}; while true do local tname, tuples = readInsert(); if tname then t[tname] = tuples; elseif peek() == nil then break; end end return t; end return readFile(filename); ------ end local arg, host = ...; local help = "/? -? ? /h -h /help -help --help"; if not(arg and host) or help:find(arg, 1, true) then print([[ejabberd SQL DB dump importer for Prosody Usage: ejabberdsql2prosody.lua filename.txt hostname The file can be generated using mysqldump: mysqldump db_name > filename.txt]]); os.exit(1); end local map = { ["last"] = {"username", "seconds", "state"}; ["privacy_default_list"] = {"username", "name"}; ["privacy_list"] = {"username", "name", "id"}; ["privacy_list_data"] = {"id", "t", "value", "action", "ord", "match_all", "match_iq", "match_message", "match_presence_in", "match_presence_out"}; ["private_storage"] = {"username", "namespace", "data"}; ["rostergroups"] = {"username", "jid", "grp"}; ["rosterusers"] = {"username", "jid", "nick", "subscription", "ask", "askmessage", "server", "subscribe", "type"}; ["spool"] = {"username", "xml", "seq"}; ["users"] = {"username", "password"}; ["vcard"] = {"username", "vcard"}; --["vcard_search"] = {}; } local NULL = {}; local t = parseFile(arg); for name, data in pairs(t) do local m = map[name]; if m then for i=1,#data do local row = data[i]; for j=1,#row do row[m[j]] = row[j]; row[j] = nil; end end end end --print(serialize(t)); for i, row in ipairs(t["users"] or NULL) do local node, password = row.username, row.password; local ret, err = dm.store(node, host, "accounts", {password = password}); print("["..(err or "success").."] accounts: "..node.."@"..host.." = "..password); end function roster(node, host, jid, item) local roster = dm.load(node, host, "roster") or {}; roster[jid] = item; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid); end function roster_pending(node, host, jid) local roster = dm.load(node, host, "roster") or {}; roster.pending = roster.pending or {}; roster.pending[jid] = true; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster-pending: " ..node.."@"..host.." - "..jid); end function roster_group(node, host, jid, group) local roster = dm.load(node, host, "roster") or {}; local item = roster[jid]; if not item then print("Warning: No roster item "..jid.." for user "..user..", can't put in group "..group); return; end item.groups[group] = true; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster-group: " ..node.."@"..host.." - "..jid.." - "..group); end for i, row in ipairs(t["rosterusers"] or NULL) do local node, contact = row.username, row.jid; local name = row.nick; if name == "" then name = nil; end local subscription = row.subscription; if subscription == "N" then subscription = "none" elseif subscription == "B" then subscription = "both" elseif subscription == "F" then subscription = "from" elseif subscription == "T" then subscription = "to" else error("Unknown subscription type: "..subscription) end; local ask = row.ask; if ask == "N" then ask = nil; elseif ask == "O" then ask = "subscribe"; elseif ask == "I" then roster_pending(node, host, contact); else error("Unknown ask type: "..ask); end local item = {name = name, ask = ask, subscription = subscription, groups = {}}; roster(node, host, contact, item); end for i, row in ipairs(t["rostergroups"] or NULL) do roster_group(row.username, host, row.jid, row.grp); end
ejabberdsql2prosody: Fixed: pending-in subscriptions could halt processing
ejabberdsql2prosody: Fixed: pending-in subscriptions could halt processing
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
b13613a0e15fa30eac8e1e218ef08de528e7cf7a
share/ioncorelib-mplexfns.lua
share/ioncorelib-mplexfns.lua
-- -- ion/share/ioncorelib-mplexfns.lua -- Misc. functions for WMPlex:s -- -- Copyright (c) Tuomo Valkonen 2003. -- -- Ion is free software; you can redistribute it and/or modify it under -- the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 2.1 of the License, or -- (at your option) any later version. -- -- Callback creation {{{ --DOC -- Create a \type{WMPlex}-bindable function with arguments -- (\code{mplex [, sub]}) that calls \var{fn} with parameter chosen -- as the first match from the following steps: -- \begin{enumerate} -- \item The current input in \var{mplex} (see \fnref{WMPlex.current_input}) -- if one exists and \var{noinput} is not set. -- \item \var{sub} if it is not nil. -- \item The currently displayed object in \var{mplex} -- (see \fnref{WMPlex.current}), if not nil. -- \item \var{mplex} itself, if \var{noself} is not set. -- \end{enumerate} -- Additionally, if \var{cwincheck} is set, the function is only -- called if the object selected above is of type \var{WClientWin}. function make_mplex_sub_or_self_fn(fn, noself, noinput, cwincheck) if not fn then warn("nil parameter to make_mplex_sub_or_self_fn") end return function(mplex, tgt) if not tgt and not noinput then tgt=mplex:current_input() end if not tgt then tgt=mplex:current() end if not tgt then if noself then return end tgt=mplex end if (not cwincheck) or obj_is(tgt, "WClientWin") then fn(tgt) end end end --DOC -- Create a \type{WMPlex}-bindable function with arguments -- (\code{mplex [, sub]}) that calls \var{fn} with parameter chosen -- as \var{sub} if it is not nil and otherwise \code{mplex:current()}. -- -- Calling this functino is equivalent to -- \fnref{make_mplex_sub_or_self_fn}\code{(fn, true, true, false)}. function make_mplex_sub_fn(fn) return make_mplex_sub_or_self_fn(fn, true, true, false) end --DOC -- Create a \type{WMPlex}-bindable function with arguments -- (\code{mplex [, sub]}) that chooses parameter for \var{fn} -- as \var{sub} if it is not nil and otherwise \code{mplex:current()}, -- and calls \var{fn} if the object chosen is of type \fnref{WClientWin}. -- -- Calling this functino is equivalent to -- \fnref{make_mplex_sub_or_self_fn}\code{(fn, true, true, true)}. function make_mplex_clientwin_fn(fn) return make_mplex_sub_or_self_fn(fn, true, true, true) end -- Backwards compatibility. make_current_fn=make_mplex_sub_fn make_current_clientwin_fn=make_mplex_clientwin_fn -- }}} -- Managed object indexing {{{ --DOC -- Returns the index of \var{mgd} in \var{mplex}'s managed list or -- -1 if not on list. function WMPlex.managed_index(mplex, mgd) local list=mplex:managed_list() for idx, mgd2 in list do if mgd2==mgd then return idx end end return -1 end --DOC -- Returns the index of \fnref{WMPlex.current} in a \var{mplex}'s -- managed list or -1 if there is no current managed object. function WMPlex.current_index(mplex) return mplex:managed_index(mplex:current()) end --DOC -- Move currently viewed object left within mplex; same as -- \code{mplex:move_left(mplex:current())}. function WMPlex.move_current_to_next_index(mplex) local c=mplex:current() if c then mplex:move_to_next_index(c) end end --DOC -- Move currently viewed object right within mplex; same as -- \code{mplex:move_left(mplex:current())}. function WMPlex.move_current_to_prev_index(mplex) local c=mplex:current() if c then mplex:move_to_prev_index(c) end end -- }}}
-- -- ion/share/ioncorelib-mplexfns.lua -- Misc. functions for WMPlex:s -- -- Copyright (c) Tuomo Valkonen 2003. -- -- Ion is free software; you can redistribute it and/or modify it under -- the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 2.1 of the License, or -- (at your option) any later version. -- -- Callback creation {{{ --DOC -- Create a \type{WMPlex}-bindable function with arguments -- (\code{mplex [, sub]}) that calls \var{fn} with parameter chosen -- as the first match from the following steps: -- \begin{enumerate} -- \item \var{sub} if it is not nil. -- \item The current input in \var{mplex} (see \fnref{WMPlex.current_input}) -- if one exists and \var{noinput} is not set. -- \item The currently displayed object in \var{mplex} -- (see \fnref{WMPlex.current}), if not nil. -- \item \var{mplex} itself, if \var{noself} is not set. -- \end{enumerate} -- Additionally, if \var{cwincheck} is set, the function is only -- called if the object selected above is of type \var{WClientWin}. function make_mplex_sub_or_self_fn(fn, noself, noinput, cwincheck) if not fn then warn("nil parameter to make_mplex_sub_or_self_fn") end return function(mplex, tgt) if not tgt and not noinput then tgt=mplex:current_input() end if not tgt then tgt=mplex:current() end if not tgt then if noself then return end tgt=mplex end if (not cwincheck) or obj_is(tgt, "WClientWin") then fn(tgt) end end end --DOC -- Create a \type{WMPlex}-bindable function with arguments -- (\code{mplex [, sub]}) that calls \var{fn} with parameter chosen -- as \var{sub} if it is not nil and otherwise \code{mplex:current()}. -- -- Calling this functino is equivalent to -- \fnref{make_mplex_sub_or_self_fn}\code{(fn, true, true, false)}. function make_mplex_sub_fn(fn) return make_mplex_sub_or_self_fn(fn, true, true, false) end --DOC -- Create a \type{WMPlex}-bindable function with arguments -- (\code{mplex [, sub]}) that chooses parameter for \var{fn} -- as \var{sub} if it is not nil and otherwise \code{mplex:current()}, -- and calls \var{fn} if the object chosen is of type \fnref{WClientWin}. -- -- Calling this functino is equivalent to -- \fnref{make_mplex_sub_or_self_fn}\code{(fn, true, true, true)}. function make_mplex_clientwin_fn(fn) return make_mplex_sub_or_self_fn(fn, true, true, true) end -- Backwards compatibility. make_current_fn=make_mplex_sub_fn make_current_clientwin_fn=make_mplex_clientwin_fn -- }}} -- Managed object indexing {{{ --DOC -- Returns the index of \var{mgd} in \var{mplex}'s managed list or -- -1 if not on list. function WMPlex.managed_index(mplex, mgd) local list=mplex:managed_list() for idx, mgd2 in list do if mgd2==mgd then return idx end end return -1 end --DOC -- Returns the index of \fnref{WMPlex.current} in a \var{mplex}'s -- managed list or -1 if there is no current managed object. function WMPlex.current_index(mplex) return mplex:managed_index(mplex:current()) end --DOC -- Move currently viewed object left within mplex; same as -- \code{mplex:move_left(mplex:current())}. function WMPlex.move_current_to_next_index(mplex) local c=mplex:current() if c then mplex:move_to_next_index(c) end end --DOC -- Move currently viewed object right within mplex; same as -- \code{mplex:move_left(mplex:current())}. function WMPlex.move_current_to_prev_index(mplex) local c=mplex:current() if c then mplex:move_to_prev_index(c) end end -- }}}
trunk: changeset 1017
trunk: changeset 1017 Small documentation fix. darcs-hash:20031129143140-e481e-3f47a8ecb1e78a04acc5a986a0ce2dca5762e149.gz
Lua
lgpl-2.1
knixeur/notion,dkogan/notion.xfttest,dkogan/notion,raboof/notion,p5n/notion,p5n/notion,dkogan/notion,p5n/notion,knixeur/notion,p5n/notion,anoduck/notion,anoduck/notion,raboof/notion,dkogan/notion,knixeur/notion,knixeur/notion,neg-serg/notion,anoduck/notion,anoduck/notion,dkogan/notion.xfttest,anoduck/notion,neg-serg/notion,raboof/notion,dkogan/notion.xfttest,raboof/notion,p5n/notion,dkogan/notion.xfttest,dkogan/notion,neg-serg/notion,dkogan/notion,neg-serg/notion,knixeur/notion
68d5d58019d47f0f9ad15a8862f077f001305abc
l2l.lua
l2l.lua
local input, output = arg[1] or "test.lsp", arg[2] or "out.lua" setmt, tostr, getmt = setmetatable, tostring, getmetatable function id(a)return a end -- list list_mt = {__tostring=function(self)return "list("..sep(self,quote)..")" end ,__eq=function(s,o) return s[1]==o[1] and s[2]==o[2] end} function list(v,...)return setmt({v,...~=nil and list(...) or nil},list_mt) end function unlist(l,f)f=f or id if l then return f(l[1]), unlist(l[2], f) end end function sep(l, f) return table.concat({unlist(l, f)}, ",") end -- symbol sym_mt = {__tostring = function(self) return self.n end} function sym(n) return setmt({n=n}, sym_mt) end function hash(v)return v:gsub("%W",function(a) if a ~= "." then return "_c"..a:byte().."_" else return "." end end) end -- operator op_mt = {__call = function(self,...) return self.f(...)end} function op(f) return setmt({f=f}, op_mt) end -- parser & compiler function tolua(l) if type(l) == "string" then return "[["..l.."]]" elseif type(l) == "number" then return tostring(l) elseif getmt(l) == sym_mt then return hash(tostring(l)) elseif getmt(l) == list_mt then local fst = l[1]; if not fst then return nil end if getmt(fst) == sym_mt and getmt(_G[hash(tostring(fst))]) == op_mt then return _G[hash(tostring(fst))](unlist(l[2], id)) elseif getmt(fst) == sym_mt then return hash(tostring(fst)) .."("..sep(l[2],tolua)..")" end return tolua(fst).."("..sep(l[2],tolua)..")" end end function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end function parse(src) src = trim(src) local open, close = src:find("%b()") if open == 1 then return list(parse(src:sub(2, close-1))), parse(src:sub(close+1)) elseif src:sub(1, 1) == ";" then local rest = src:sub(2):match("%s*.-\n(.*)") if rest then return parse(rest) end elseif src:sub(1, 1) == "'" then local rest = src:sub(2):match("%s*(.*)") local r = list(parse(rest)) return list(sym("quote"), r[1]), unlist(r[2]) elseif src:sub(1, 1) == "\"" then local esc, i = false, 2 while esc == true or src:sub(i, i)~="\"" do if esc then esc = false end if src:sub(i, i) == "\\" then esc = true end i = i + 1 end return src:sub(2, i-1), parse(src:sub(i+1)) elseif #src > 0 then local first = src:match("(%S+)") local rest = src:match("%S+%s+(.*)") return tonumber(first) or sym(first), parse(rest or "") end end function compile(ret, s,...) local c = tolua(s)..(ret and " " or "\n") if ... then return c .. compile(ret, ...) end if ret then return "return ".. c else return c end end -- primitives _G[hash("*")] = op(function(a, b) return "("..tolua(a).."*"..tolua(b)..")" end) _G[hash("/")] = op(function(a, b) return "("..tolua(a).."/"..tolua(b)..")" end) _G[hash("+")] = op(function(a, b) return "("..tolua(a).."+"..tolua(b)..")" end) _G[hash("-")] = op(function(a, b) return "("..tolua(a).."-"..tolua(b)..")" end) cons = op(function(a, b)return"setmt({"..sep(list(a,b),tolua).."},list_mt)"end) atom = op(function(a) return "(getmt("..tolua(a)..")~=list_mt)" end) car = op(function(a) return tolua(a).."[1]" end) cdr = op(function(a) return tolua(a).."[2]" end) eq = op(function(a, b) return tolua(a) .. "==" .. tolua(b) end) defun = op(function(n,a,...) return hash(tostr(n)).."="..lambda(a, ...)end) lambda = op(function(a, ...) local def, r = "function("..sep(a, tostr)..") ", "return " for i,v in ipairs({...}) do def=def..(i==#{...}and r or"")..tolua(v).." " end return def.."end" end) cond = op(function(...) local def, r = "(function()", "return " for i,v in ipairs({...}) do def=def.."\n if "..tolua(v[1]).. " then ".. compile(true, unlist(v[2])) .. "end" end return def.."\n end)()" end) quote = op(function(l) if type(l) == "string" then return "[["..l.."]]" elseif type(l) == "number" then return tostring(l) elseif getmt(l) == sym_mt then return "sym(\""..tostring(l).."\")" elseif getmt(l) == list_mt and l[1] == nil and l[2] == nil then return "nil" elseif getmt(l) == list_mt then return "list("..sep(l, quote)..")" end end) -- write lua if not input or not output then return end inf=io.open(input, "r") src = inf:read("*all") inf:close() of=io.open(output, "w") lf=io.open("l2l.lua", "r") for i=1,94 do of:write(lf:read("*line").."\n") end lf:close() of:write(compile(false, parse(src)).."\n") of:close()
local input, output = arg[1] or "test.lsp", arg[2] or "out.lua" setmt, tostr, getmt = setmetatable, tostring, getmetatable function id(a)return a end -- list list_mt = {__tostring=function(self)return "list("..sep(self,quote)..")" end ,__eq=function(s,o) return s[1]==o[1] and s[2]==o[2] end} function list(v,...)return setmt({v,...~=nil and list(...) or nil},list_mt) end function unlist(l,f)f=f or id if l then return f(l[1]), unlist(l[2], f) end end function sep(l, f) return table.concat({unlist(l, f)}, ",") end -- symbol & operator sym_mt = {__tostring = function(self) return self.n end} function sym(n) return setmt({n=n}, sym_mt) end function hash(v)return v:gsub("%W",function(a) if a ~= "." then return "_c"..a:byte().."_" else return "." end end) end op_mt = {__call = function(self,...) return self.f(...)end} function op(f) return setmt({f=f}, op_mt) end -- parser & compiler function tolua(l) if type(l) == "string" then return "[["..l.."]]" elseif type(l) == "number" then return tostring(l) elseif getmt(l) == sym_mt then return hash(tostring(l)) elseif getmt(l) == list_mt then local fst = l[1]; if not fst then return nil end if getmt(fst) == sym_mt and getmt(_G[hash(tostring(fst))]) == op_mt then return _G[hash(tostring(fst))](unlist(l[2], id)) elseif getmt(fst) == sym_mt then return hash(tostring(fst)) .."("..sep(l[2],tolua)..")" end return tolua(fst).."("..sep(l[2],tolua)..")" end end function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end function parse(src) src = trim(src) local open, close = src:find("%b()") if open == 1 then return list(parse(src:sub(2, close-1))), parse(src:sub(close+1)) elseif src:sub(1, 1) == ";" then local rest = src:sub(2):match("%s*.-\n(.*)") if rest then return parse(rest) end elseif src:sub(1, 1) == "'" then local rest = src:sub(2):match("%s*(.*)") local r = list(parse(rest)) return list(sym("quote"), r[1]), unlist(r[2]) elseif src:sub(1, 1) == "\"" then local esc, i = false, 2 while esc == true or src:sub(i, i)~="\"" do if esc then esc = false end if src:sub(i, i) == "\\" then esc = true end i = i + 1 end return src:sub(2, i-1), parse(src:sub(i+1)) elseif #src > 0 then local first = src:match("(%S+)") local rest = src:match("%S+%s+(.*)") return tonumber(first) or sym(first), parse(rest or "") end end function compile(ret, s,...) local c = tolua(s)..(ret and " " or "\n") if ... then return c .. compile(ret, ...) end if ret then return "return ".. c else return c end end -- primitives _G[hash("*")] = op(function(a, b) return "("..tolua(a).."*"..tolua(b)..")" end) _G[hash("/")] = op(function(a, b) return "("..tolua(a).."/"..tolua(b)..")" end) _G[hash("+")] = op(function(a, b) return "("..tolua(a).."+"..tolua(b)..")" end) _G[hash("-")] = op(function(a, b) return "("..tolua(a).."-"..tolua(b)..")" end) cons = op(function(a, b)return"setmt({"..sep(list(a,b),tolua).."},list_mt)"end) atom = op(function(a) return "(getmt("..tolua(a)..")~=list_mt)" end) car = op(function(a) return tolua(a).."[1]" end) cdr = op(function(a) return tolua(a).."[2]" end) eq = op(function(a, b) return tolua(a) .. "==" .. tolua(b) end) defun = op(function(n,a,...) return hash(tostr(n)).."="..lambda(a, ...)end) lambda = op(function(a, ...) local def, r = "function("..(a[1] and sep(a, tostr) or "")..") ", "return " for i,v in ipairs({...}) do def=def..(i==#{...}and r or"")..tolua(v).." " end return def.."end" end) cond = op(function(...) local def, r = "(function()", "return " for i,v in ipairs({...}) do def=def.."\n if "..tolua(v[1]).. " then ".. compile(true, unlist(v[2])) .. "end" end return def.."\n end)()" end) quote = op(function(l) if type(l) == "string" then return "[["..l.."]]" elseif type(l) == "number" then return tostring(l) elseif getmt(l) == sym_mt then return "sym(\""..tostring(l).."\")" elseif getmt(l) == list_mt and l[1] == nil and l[2] == nil then return "nil" elseif getmt(l) == list_mt then return "list("..sep(l, quote)..")" end end) -- write lua if not input or not output then return end inf=io.open(input, "r") src = inf:read("*all") inf:close() of=io.open(output, "w") lf=io.open("l2l.lua", "r") for i=1,94 do of:write(lf:read("*line").."\n") end lf:close() of:write(compile(false, parse(src)).."\n") of:close()
Fix defun for zero argument functions
Fix defun for zero argument functions
Lua
bsd-2-clause
carloscm/l2l,tst2005/l2l,meric/l2l,technomancy/l2l
1ce4bd7dbeef5e61433e6f6893c20953e0867fe0
nyagos.d/trash.lua
nyagos.d/trash.lua
if not nyagos.ole then local status status,nyagos.ole = pcall(require,"nyole") if not status then nyagos.ole = nil end end if nyagos.ole then local fsObj = nyagos.ole.create_object_utf8("Scripting.FileSystemObject") local shellApp = nyagos.ole.create_object_utf8("Shell.Application") local trashBox = shellApp:NameSpace(math.tointeger(10)) if trashBox.MoveHere then nyagos.alias.trash = function(args) args = nyagos.glob(table.unpack(args)) for i=1,#args do trashBox:MoveHere(fsObj:GetAbsolutePathName(args[i])) end end else nyagos.writerr("Warning: trash.lua requires nyaole.dll 0.0.0.5 or later\n") end end
if not nyagos.ole then local status status,nyagos.ole = pcall(require,"nyole") if not status then nyagos.ole = nil end end if nyagos.ole then local fsObj = nyagos.ole.create_object_utf8("Scripting.FileSystemObject") local shellApp = nyagos.ole.create_object_utf8("Shell.Application") local trashBox = shellApp:NameSpace(math.tointeger(10)) if trashBox.MoveHere then nyagos.alias.trash = function(args) if #args <= 0 then nyagos.writerr("Move files or directories to Windows Trashbox\n") nyagos.writerr("Usage: trash file(s)...\n") return end args = nyagos.glob(table.unpack(args)) for i=1,#args do if fsObj:FileExists(args[i]) or fsObj:FolderExists(args[i]) then trashBox:MoveHere(fsObj:GetAbsolutePathName(args[i])) else nyagos.writerr(args[i]..": such a file or directory not found.\n") end end end else nyagos.writerr("Warning: trash.lua requires nyaole.dll 0.0.0.5 or later\n") end end
Fixed trash.lua never printed error as if file(s) did not exists.
Fixed trash.lua never printed error as if file(s) did not exists.
Lua
bsd-3-clause
hattya/nyagos,tyochiai/nyagos,kissthink/nyagos,hattya/nyagos,nocd5/nyagos,hattya/nyagos,zetamatta/nyagos,kissthink/nyagos,tsuyoshicho/nyagos,kissthink/nyagos
eacf487a223d090745d13cd81e9ed4977e4c97a6
AceConsole-3.0/AceConsole-3.0.lua
AceConsole-3.0/AceConsole-3.0.lua
--[[ $Id$ ]] local MAJOR,MINOR = "AceConsole-3.0", 0 local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceConsole then return end -- No upgrade needed AceConsole.embeds = AceConsole.embeds or {} -- table containing objects AceConsole is embedded in. AceConsole.commands = AceConsole.commands or {} -- table containing commands registered AceConsole.weakcommands = AceConsole.weakcommands or {} -- table containing self, command => func references for weak commands that don't persist through enable/disable -- AceConsole:Print( [chatframe,] ... ) -- -- Print to DEFAULT_CHAT_FRAME or given chatframe (anything with an .AddMessage member) function AceConsole:Print(...) local text = "" if self ~= AceConsole then text = tostring( self )..": " end local frame = select(1, ...) if not ( type(frame) == "table" and frame.AddMessage ) then -- Is first argument something with an .AddMessage member? frame=nil end for i=(frame and 2 or 1), select("#", ...) do text = text .. tostring( select( i, ...) ) .." " end (frame or DEFAULT_CHAT_FRAME):AddMessage( text ) end -- AceConsole:RegisterChatCommand(. command, func, persist ) -- -- command (string) - chat command to be registered. does not require / in front -- func (string|function) - function to call, if a string is used then the member of self is used as a string. -- persist (boolean) - if true is passed the command will not be soft disabled/enabled when aceconsole is used as a mixin -- silent (boolean) - don't whine if command already exists, silently fail -- -- Register a simple chat command function AceConsole:RegisterChatCommand( command, func, persist, silent ) local name = "ACECONSOLE_"..command:upper() if SlashCmdList[name] then if not silent then geterrorhandler()(tostring(self) ": Chat Command '"..command.."' already exists, will not overwrite.") end return end if type( func ) == "string" then SlashCmdList[name] = function(input) self[func](self, input) end else SlashCmdList[name] = func end setglobal("SLASH_"..name.."1", "/"..command:lower()) AceConsole.commands[command] = name -- non-persisting commands are registered for enabling disabling if not persist then AceConsole.weakcommands[self][command] = func end end -- AceConsole:UnregisterChatCommand( command ) -- -- Unregister a chatcommand function AceConsole:UnregisterChatCommand( command ) local name = AceConsole.commands[command] if name then SlashCmdList[name] = nil setglobal("SLASH_"..name.."1", nil) hash_SlashCmdList["/" .. command:upper()] = nil AceConsole.commands[command] = nil end end local function nils(n, ...) if n>1 then return nil, nils(n-1, ...) elseif n==1 then return nil, ... else return ... end end -- AceConsole:GetArgs(string, numargs, startpos) -- -- Retreive one or more space-separated arguments from a string. -- Treats quoted strings and itemlinks as non-spaced. -- -- string - The raw argument string -- numargs - How many arguments to get (default 1) -- startpos - Where in the string to start scanning (default 1) -- -- Returns arg1, arg2, ..., nextposition -- Missing arguments will be returned as nils. 'nextposition' is returned as 1e99 at the end of the string. function AceConsole:GetArgs(str, numargs, startpos) numargs = numargs or 1 startpos = max(startpos or 1, 1) local pos=startpos -- find start of new arg pos = strfind(str, "[^ ]", pos) if not pos then -- whoops, end of string return nils(numargs, 1e99) end if numargs<1 then return pos end -- quoted or space separated? find out which pattern to use local delim_or_pipe local ch = strsub(str, pos, pos) if ch=='"' then pos = pos + 1 delim_or_pipe='([|"])' elseif ch=="'" then pos = pos + 1 delim_or_pipe="([|'])" else delim_or_pipe="([| ])" end startpos = pos while true do -- find delimiter or hyperlink local ch,_ pos,_,ch = strfind(str, delim_or_pipe, pos) if not pos then break end if ch=="|" then -- some kind of escape if strsub(str,pos,pos+1)=="|H" then -- It's a |H....|hhyper link!|h pos=strfind(str, "|h", pos+2) -- first |h if not pos then break end pos=strfind(str, "|h", pos+2) -- second |h if not pos then break end end pos=pos+2 -- skip past this escape (last |h if it was a hyperlink) else -- found delimiter, done with this arg return strsub(str, startpos, pos-1), AceConsole:GetArgs(str, numargs-1, pos+1) end end -- search aborted, we hit end of string. return it all as one argument. (yes, even if it's an unterminated quote or hyperlink) return strsub(str, startpos), nils(numargs-1, 1e99) end --- embedding and embed handling local mixins = { "Print", "RegisterChatCommand", "UnregisterChatCommand", "GetArgs", } -- AceConsole:Embed( target ) -- target (object) - target object to embed AceBucket in -- -- Embeds AceConsole into the target object making the functions from the mixins list available on target:.. function AceConsole:Embed( target ) for k, v in pairs( mixins ) do target[v] = self[v] end self.embeds[target] = true end function AceConsole:OnEmbedEnable( target ) if AceConsole.weakcommands[target] then for command, func in pairs( AceConsole.weakcommands[target] ) do target:RegisterChatCommand( command, func, false, true ) -- nonpersisting and silent registry end end end function AceConsole:OnEmbedDisable( target ) if AceConsole.weakcommands[target] then for command, func in pairs( AceConsole.weakcommands[target] ) do target:UnregisterChatCommand( command ) -- TODO: this could potentially unregister a command from another application in case of command conflicts. Do we care? end end end for addon in pairs(AceConsole.embeds) do AceConsole:Embed(addon) end
--[[ $Id$ ]] local MAJOR,MINOR = "AceConsole-3.0", 0 local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceConsole then return end -- No upgrade needed AceConsole.embeds = AceConsole.embeds or {} -- table containing objects AceConsole is embedded in. AceConsole.commands = AceConsole.commands or {} -- table containing commands registered AceConsole.weakcommands = AceConsole.weakcommands or {} -- table containing self, command => func references for weak commands that don't persist through enable/disable -- AceConsole:Print( [chatframe,] ... ) -- -- Print to DEFAULT_CHAT_FRAME or given chatframe (anything with an .AddMessage member) function AceConsole:Print(...) local text = "" if self ~= AceConsole then text = tostring( self )..": " end local frame = select(1, ...) if not ( type(frame) == "table" and frame.AddMessage ) then -- Is first argument something with an .AddMessage member? frame=nil end for i=(frame and 2 or 1), select("#", ...) do text = text .. tostring( select( i, ...) ) .." " end (frame or DEFAULT_CHAT_FRAME):AddMessage( text ) end -- AceConsole:RegisterChatCommand(. command, func, persist ) -- -- command (string) - chat command to be registered WITHOUT leading "/" -- func (function|membername) - function to call, or self[membername](self, ...) call -- persist (boolean) - false: the command will be soft disabled/enabled when aceconsole is used as a mixin (default: true) -- silent (boolean) - don't whine if command already exists, silently fail -- -- Register a simple chat command function AceConsole:RegisterChatCommand( command, func, persist, silent ) if type(command)~="string" then error([[Usage: AceConsole:RegisterChatCommand( "command", func[, persist[, silent] ]): 'command' - expected a string]], 2) end if persist==nil then persist=true end -- I'd rather have my addon's "/addon enable" around if the author screws up. Having some extra slash regged when it shouldnt be isn't as destructive. True is a better default. /Mikk local name = "ACECONSOLE_"..command:upper() if SlashCmdList[name] then if not silent then geterrorhandler()(tostring(self)..": Chat Command '"..command.."' already exists, will not overwrite.") end return end if type( func ) == "string" then SlashCmdList[name] = function(input) self[func](self, input) end else SlashCmdList[name] = func end _G["SLASH_"..name.."1"] = "/"..command:lower() AceConsole.commands[command] = name -- non-persisting commands are registered for enabling disabling if not persist then AceConsole.weakcommands[self][command] = func end end -- AceConsole:UnregisterChatCommand( command ) -- -- Unregister a chatcommand function AceConsole:UnregisterChatCommand( command ) local name = AceConsole.commands[command] if name then SlashCmdList[name] = nil setglobal("SLASH_"..name.."1", nil) hash_SlashCmdList["/" .. command:upper()] = nil AceConsole.commands[command] = nil end end local function nils(n, ...) if n>1 then return nil, nils(n-1, ...) elseif n==1 then return nil, ... else return ... end end -- AceConsole:GetArgs(string, numargs, startpos) -- -- Retreive one or more space-separated arguments from a string. -- Treats quoted strings and itemlinks as non-spaced. -- -- string - The raw argument string -- numargs - How many arguments to get (default 1) -- startpos - Where in the string to start scanning (default 1) -- -- Returns arg1, arg2, ..., nextposition -- Missing arguments will be returned as nils. 'nextposition' is returned as 1e99 at the end of the string. function AceConsole:GetArgs(str, numargs, startpos) numargs = numargs or 1 startpos = max(startpos or 1, 1) local pos=startpos -- find start of new arg pos = strfind(str, "[^ ]", pos) if not pos then -- whoops, end of string return nils(numargs, 1e99) end if numargs<1 then return pos end -- quoted or space separated? find out which pattern to use local delim_or_pipe local ch = strsub(str, pos, pos) if ch=='"' then pos = pos + 1 delim_or_pipe='([|"])' elseif ch=="'" then pos = pos + 1 delim_or_pipe="([|'])" else delim_or_pipe="([| ])" end startpos = pos while true do -- find delimiter or hyperlink local ch,_ pos,_,ch = strfind(str, delim_or_pipe, pos) if not pos then break end if ch=="|" then -- some kind of escape if strsub(str,pos,pos+1)=="|H" then -- It's a |H....|hhyper link!|h pos=strfind(str, "|h", pos+2) -- first |h if not pos then break end pos=strfind(str, "|h", pos+2) -- second |h if not pos then break end end pos=pos+2 -- skip past this escape (last |h if it was a hyperlink) else -- found delimiter, done with this arg return strsub(str, startpos, pos-1), AceConsole:GetArgs(str, numargs-1, pos+1) end end -- search aborted, we hit end of string. return it all as one argument. (yes, even if it's an unterminated quote or hyperlink) return strsub(str, startpos), nils(numargs-1, 1e99) end --- embedding and embed handling local mixins = { "Print", "RegisterChatCommand", "UnregisterChatCommand", "GetArgs", } -- AceConsole:Embed( target ) -- target (object) - target object to embed AceBucket in -- -- Embeds AceConsole into the target object making the functions from the mixins list available on target:.. function AceConsole:Embed( target ) for k, v in pairs( mixins ) do target[v] = self[v] end self.embeds[target] = true end function AceConsole:OnEmbedEnable( target ) if AceConsole.weakcommands[target] then for command, func in pairs( AceConsole.weakcommands[target] ) do target:RegisterChatCommand( command, func, false, true ) -- nonpersisting and silent registry end end end function AceConsole:OnEmbedDisable( target ) if AceConsole.weakcommands[target] then for command, func in pairs( AceConsole.weakcommands[target] ) do target:UnregisterChatCommand( command ) -- TODO: this could potentially unregister a command from another application in case of command conflicts. Do we care? end end end for addon in pairs(AceConsole.embeds) do AceConsole:Embed(addon) end
Ace3 - AceConsole: - Fix error in errormessage - Add type check for slashcommand string - Change "persist"'s default to true. I'd rather have my "/addon enable" available when the dev screws up by default I think.
Ace3 - AceConsole: - Fix error in errormessage - Add type check for slashcommand string - Change "persist"'s default to true. I'd rather have my "/addon enable" available when the dev screws up by default I think. git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@223 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
40612d91555f0a88cdc41e1f7fde8cb37a214827
packages/rebox.lua
packages/rebox.lua
SILE.registerCommand("rebox", function (options, content) local box = SILE.Commands["hbox"]({}, content) if options.width then box.width = SILE.toPoints(options.width) end if options.height then box.height = SILE.toPoints(options.height) end if options.depth then box.depth = SILE.toPoints(options.depth) end if options.phantom then box.outputYourself = function (self, typesetter, line) typesetter.frame:moveX(self:scaledWidth(line)) end end table.insert(SILE.typesetter.state.nodes, box) }) end, "Place the output within a box of specified width, height, depth and visibility")
SILE.registerCommand("rebox", function (options, content) local box = SILE.Commands["hbox"]({}, content) if options.width then box.width = SILE.length.new({length = SILE.toPoints(options.width)}) end if options.height then box.height = SILE.toPoints(options.height) end if options.depth then box.depth = SILE.toPoints(options.depth) end if options.phantom then box.outputYourself = function (self, typesetter, line) typesetter.frame:moveX(self:scaledWidth(line)) end end table.insert(SILE.typesetter.state.nodes, box) end, "Place the output within a box of specified width, height, depth and visibility")
Some fixes.
Some fixes.
Lua
mit
anthrotype/sile,alerque/sile,anthrotype/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,simoncozens/sile,neofob/sile,neofob/sile,anthrotype/sile,neofob/sile,alerque/sile,simoncozens/sile,neofob/sile,anthrotype/sile