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
d1191601ff9b4243c228ddddcbdf23b1c2f92e02
nvim/.config/nvim/lua/gb/finder.lua
nvim/.config/nvim/lua/gb/finder.lua
local actions = require("telescope.actions") local trouble = require("trouble.providers.telescope") require("telescope").setup { defaults = { prompt_prefix = "  ", selection_caret = " ", entry_prefix = " ", scroll_strategy = "cycle", file_ignore_patterns = {"%.git", "node%_modules"}, initial_mode = "insert", selection_strategy = "reset", sorting_strategy = "ascending", layout_strategy = "horizontal", layout_config = { prompt_position = "top" }, path_display = {"absolute"}, mappings = { i = { ["<C-f>"] = actions.smart_send_to_qflist + actions.open_qflist, ["<esc>"] = actions.close, ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous, ["<C-t>"] = trouble.open_with_trouble } }, vimgrep_arguments = { "rg", "--color=never", "--no-heading", "--with-filename", "--line-number", "--column", "--smart-case", "--hidden", }, winblend = 0, border = {}, borderchars = { "" }, color_devicons = true, }, pickers = { find_files = { hidden = string.find(vim.fn.getcwd(), ".dotfiles"), sort_lastused = true, previewer = false }, live_grep = { hidden = string.find(vim.fn.getcwd(), ".dotfiles"), sort_lastused = true, previewer = false }, buffers = { sort_lastused = true, previewer = false, mappings = { i = { ["<c-d>"] = require("telescope.actions").delete_buffer, -- Right hand side can also be the name of the action as a string ["<c-d>"] = "delete_buffer" }, n = { ["<c-d>"] = require("telescope.actions").delete_buffer } } }, lsp_references = { layout_strategy = "vertical", layout_config = { mirror = true } } }, extensions = { fzf = { override_generic_sorter = true, override_file_sorter = true, case_mode = "smart_case" }, fzf_writer = { minimum_grep_characters = 2 } } } require("telescope").load_extension("fzf") require("telescope").load_extension("fzf_writer") require("telescope").load_extension("ui-select") function _G.gb_grep_files() require("telescope").extensions.fzf_writer.staged_grep { previewer = false } end vim.keymap.set("n", "<leader>a", "<cmd>Telescope live_grep<cr>") vim.keymap.set("n", "<leader>p", "<cmd>Telescope find_files<cr>") vim.keymap.set("n", "<leader>b", "<cmd>Telescope buffers<cr>") -- Create a new vsplit, switch to it and open CtrlP vim.keymap.set("n", "<leader>w", "<C-w>v") -- Create a new split, switch to it and open CtrlP vim.keymap.set("n", "<leader>s", "<C-w>s<C-w>j")
local actions = require("telescope.actions") local trouble = require("trouble.providers.telescope") require("telescope").setup { defaults = { prompt_prefix = "  ", selection_caret = " ", entry_prefix = " ", scroll_strategy = "cycle", file_ignore_patterns = {"%.git", "node%_modules"}, initial_mode = "insert", selection_strategy = "reset", sorting_strategy = "ascending", layout_strategy = "horizontal", layout_config = { prompt_position = "top" }, path_display = {"smart"}, mappings = { i = { ["<C-f>"] = actions.smart_send_to_qflist + actions.open_qflist, ["<esc>"] = actions.close, ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous, ["<C-t>"] = trouble.open_with_trouble } }, vimgrep_arguments = { "rg", "--color=never", "--no-heading", "--with-filename", "--line-number", "--column", "--smart-case", "--hidden", }, winblend = 0, border = {}, borderchars = { "" }, }, pickers = { find_files = { hidden = string.find(vim.fn.getcwd(), ".dotfiles"), sort_lastused = true, previewer = false }, live_grep = { hidden = string.find(vim.fn.getcwd(), ".dotfiles"), sort_lastused = true, previewer = false }, buffers = { sort_lastused = true, previewer = false, mappings = { i = { ["<c-d>"] = require("telescope.actions").delete_buffer, -- Right hand side can also be the name of the action as a string ["<c-d>"] = "delete_buffer" }, n = { ["<c-d>"] = require("telescope.actions").delete_buffer } } }, lsp_references = { fname_width = 0.5, include_current_line = true, layout_strategy = "vertical", layout_config = { mirror = true } } }, extensions = { fzf = { override_generic_sorter = true, override_file_sorter = true, case_mode = "smart_case" }, fzf_writer = { minimum_grep_characters = 2 } } } require("telescope").load_extension("fzf") require("telescope").load_extension("fzf_writer") require("telescope").load_extension("ui-select") function _G.gb_grep_files() require("telescope").extensions.fzf_writer.staged_grep { previewer = false } end vim.keymap.set("n", "<leader>a", "<cmd>Telescope live_grep<cr>") vim.keymap.set("n", "<leader>p", "<cmd>Telescope find_files<cr>") vim.keymap.set("n", "<leader>b", "<cmd>Telescope buffers<cr>") -- Create a new vsplit, switch to it and open CtrlP vim.keymap.set("n", "<leader>w", "<C-w>v") -- Create a new split, switch to it and open CtrlP vim.keymap.set("n", "<leader>s", "<C-w>s<C-w>j")
Fixup telescope paths for lsp_references
Fixup telescope paths for lsp_references
Lua
mit
gblock0/dotfiles
8bf3b3532f49b37afc729a70c1ad903f353875f6
mod_auth_dovecot/mod_auth_dovecot.lua
mod_auth_dovecot/mod_auth_dovecot.lua
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010 Javier Torres -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- local socket_unix = require "socket.unix"; local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_dovecot"); local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local base64 = require "util.encodings".base64; local pposix = require "util.pposix"; local prosody = _G.prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_default_provider(host) local provider = { name = "dovecot", c = nil }; log("debug", "initializing dovecot authentication provider for host '%s'", host); -- Closes the socket function provider.close(self) if (provider.c ~= nil) then provider.c:close(); end provider.c = nil; end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); provider.c = socket.unix(); -- Create a connection to dovecot socket local r, e = provider.c:connect(socket_path); if (not r) then log("warn", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, e); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); if not provider:send("VERSION\t1\t1\n") then return false end if (not provider:send("CPID\t" .. pid .. "\n")) then return false end -- Parse Dovecot's handshake local done = false; while (not done) do local l = provider:receive(); if (not l) then return false; end parts = string.gmatch(l, "[^\t]+"); first = parts(); if (first == "VERSION") then -- Version should be 1.1 local v1 = parts(); local v2 = parts(); if (not (v1 == "1" and v2 == "1")) then log("warn", "server version is not 1.1. it is %s.%s", v1, v2); provider:close(); return false; end elseif (first == "MECH") then -- Mechanisms should include PLAIN local ok = false; for p in parts do if p == "PLAIN" then ok = true; end end if (not ok) then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", l); provider:close(); return false; end elseif (first == "DONE") then done = true; end end return true; end -- Wrapper for send(). Handles errors function provider.send(self, data) local r, e = provider.c:send(data); if (not r) then log("warn", "error sending '%s' to dovecot. error was '%s'", data, e); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local r, e = provider.c:receive(); if (not r) then log("warn", "error receiving data from dovecot. error was '%s'", socket, e); provider:close(); return false; end return r; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local tries = 0; if (provider.c == nil or tries > 0) then if (not provider:connect()) then return nil, "Auth failed. Dovecot communications error"; end end -- Send auth data username = username .. "@" .. module.host; -- FIXME: this is actually a hack for my server local b64 = base64.encode(username .. "\0" .. username .. "\0" .. password); local id = "54321"; -- FIXME: probably can just be a fixed value if making one request per connection if (not provider:send("AUTH\t" .. id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64 .. "\n")) then return nil, "Auth failed. Dovecot communications error"; end -- Get response local l = provider:receive(); if (not l) then return nil, "Auth failed. Dovecot communications error"; end local parts = string.gmatch(l, "[^\t]+"); -- Check response if (parts() == "OK") then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Cannot get_password in dovecot backend."; end function provider.set_password(username, password) return nil, "Cannot set_password in dovecot backend."; end function provider.user_exists(username) --TODO: Send an auth request. If it returns FAIL <id> user=<user> then user exists. return nil, "user_exists not yet implemented in dovecot backend."; end function provider.create_user(username, password) return nil, "Cannot create_user in dovecot backend."; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local getpass_authentication_profile = { plain_test = function(username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, realm, password), true; end }; return new_sasl(realm, getpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_default_provider(module.host));
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010 Javier Torres -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- local socket_unix = require "socket.unix"; local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_dovecot"); local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local base64 = require "util.encodings".base64; local pposix = require "util.pposix"; local prosody = _G.prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_default_provider(host) local provider = { name = "dovecot", c = nil, request_id = 0 }; log("debug", "initializing dovecot authentication provider for host '%s'", host); -- Closes the socket function provider.close(self) if (provider.c ~= nil) then provider.c:close(); end provider.c = nil; end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); provider.c = socket.unix(); -- Create a connection to dovecot socket local r, e = provider.c:connect(socket_path); if (not r) then log("warn", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, e); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); if not provider:send("VERSION\t1\t1\n") then return false end if (not provider:send("CPID\t" .. pid .. "\n")) then return false end -- Parse Dovecot's handshake local done = false; while (not done) do local l = provider:receive(); if (not l) then return false; end parts = string.gmatch(l, "[^\t]+"); first = parts(); if (first == "VERSION") then -- Version should be 1.1 local v1 = parts(); local v2 = parts(); if (not (v1 == "1" and v2 == "1")) then log("warn", "server version is not 1.1. it is %s.%s", v1, v2); provider:close(); return false; end elseif (first == "MECH") then -- Mechanisms should include PLAIN local ok = false; for p in parts do if p == "PLAIN" then ok = true; end end if (not ok) then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", l); provider:close(); return false; end elseif (first == "DONE") then done = true; end end return true; end -- Wrapper for send(). Handles errors function provider.send(self, data) local r, e = provider.c:send(data); if (not r) then log("warn", "error sending '%s' to dovecot. error was '%s'", data, e); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local r, e = provider.c:receive(); if (not r) then log("warn", "error receiving data from dovecot. error was '%s'", socket, e); provider:close(); return false; end return r; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local tries = 0; if (provider.c == nil or tries > 0) then if (not provider:connect()) then return nil, "Auth failed. Dovecot communications error"; end end -- Send auth data username = username .. "@" .. module.host; -- FIXME: this is actually a hack for my server local b64 = base64.encode(username .. "\0" .. username .. "\0" .. password); provider.request_id = provider.request_id + 1 if (not provider:send("AUTH\t" .. provider.request_id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64 .. "\n")) then return nil, "Auth failed. Dovecot communications error"; end -- Get response local l = provider:receive(); if (not l) then return nil, "Auth failed. Dovecot communications error"; end local parts = string.gmatch(l, "[^\t]+"); -- Check response if (parts() == "OK") then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Cannot get_password in dovecot backend."; end function provider.set_password(username, password) return nil, "Cannot set_password in dovecot backend."; end function provider.user_exists(username) --TODO: Send an auth request. If it returns FAIL <id> user=<user> then user exists. return nil, "user_exists not yet implemented in dovecot backend."; end function provider.create_user(username, password) return nil, "Cannot create_user in dovecot backend."; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local getpass_authentication_profile = { plain_test = function(username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, realm, password), true; end }; return new_sasl(realm, getpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_default_provider(module.host));
mod_auth_dovecot: Use sequential (instead of fixed) id for messages
mod_auth_dovecot: Use sequential (instead of fixed) id for messages
Lua
mit
asdofindia/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,softer/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,prosody-modules/import,either1/prosody-modules,prosody-modules/import,softer/prosody-modules,apung/prosody-modules,olax/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,olax/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,heysion/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,1st8/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,crunchuser/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,Craige/prosody-modules,mmusial/prosody-modules
bef5be991c0d39ba24adbb732278e72c3aa01ff2
config/nvim/lua/init/telescope.lua
config/nvim/lua/init/telescope.lua
local telescope = require('telescope') local actions = require('telescope.actions') local builtin = require('telescope.builtin') telescope.setup({defaults = {mappings = {i = {["<esc>"] = actions.close}}}}) local options = {noremap = true} vim.api.nvim_set_keymap('n', '<leader>b', [[<cmd>lua require('telescope.builtin').buffers()<cr>]], options) vim.api.nvim_set_keymap('n', '<leader>c', [[<cmd>lua require('telescope.builtin').command_history()<cr>]], options) vim.api.nvim_set_keymap('n', '<leader>f', [[<cmd>lua require('init.telescope').find_files()<cr>]], options) vim.api.nvim_set_keymap('n', '<leader>g', [[<cmd>lua require('telescope.builtin').live_grep()<cr>]], options) vim.api.nvim_set_keymap('n', '<leader>r', [[<cmd>lua require('telescope.builtin').git_files({use_git_root=true})<cr>]], options) return { find_files = function() if not pcall(builtin.git_files) then builtin.find_files() end end }
local telescope = require('telescope') local actions = require('telescope.actions') local builtin = require('telescope.builtin') telescope.setup({defaults = {mappings = {i = {["<esc>"] = actions.close}}}}) local options = {noremap = true} vim.api.nvim_set_keymap('n', '<leader>b', [[<cmd>lua require('telescope.builtin').buffers()<cr>]], options) vim.api.nvim_set_keymap('n', '<leader>c', [[<cmd>lua require('telescope.builtin').command_history()<cr>]], options) vim.api.nvim_set_keymap('n', '<leader>f', [[<cmd>lua require('init.telescope').find_files()<cr>]], options) vim.api.nvim_set_keymap('n', '<leader>g', [[<cmd>lua require('telescope.builtin').live_grep()<cr>]], options) vim.api.nvim_set_keymap('n', '<leader>r', [[<cmd>lua require('telescope.builtin').git_files({use_git_root=true})<cr>]], options) return { find_files = function() if not pcall(builtin.git_files, {use_git_root = false}) then builtin.find_files() end end }
Fix <leader>f command
Fix <leader>f command
Lua
unlicense
raviqqe/dotfiles
b182796b875387668636d859c9f0fb6251eb124f
tag/tag.lua
tag/tag.lua
local mp = require 'MessagePack' local module = {} local log = ngx.log local ERR = ngx.ERR local format = string.format module._VERSION = '0.0.1' local function explode(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, 1) while s do if s ~= 1 or cap ~= "" then 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) table.insert(t, cap) end return t end local function build_key(key, variants) if variants == nil then return key end local tags = variants.tags if tags == nil then return key end local nkey = key; for tag, value in pairs(tags) do nkey = tag .. '=' .. value .. ' ' .. nkey end return nkey end local function get_variants(key) local pac = module.variants[key] if pac == nil then return nil end return mp.unpack(pac) end local function update_variants(key, what, data) local vars = get_variants(key) if vars == nil then vars = {} end vars[what] = data module.variants[key] = mp.pack(vars) return vars end local function get_tags(header) local tags = {} if header == nil then return tags end local values = explode(header, ',') for i, value in pairs(values) do local pair = explode(value, '=') tags[pair[1]] = pair[2] end return tags end function module.get(key) return build_key(key, get_variants(key)) end function module.set(key, headers) local tags = get_tags(headers["X-Cache-Tag"]) for tag, value in pairs(tags) do module.tags[tag] = value end local variants = update_variants(key, 'tags', tags) return build_key(key, variants) end return module;
local mp = require 'MessagePack' local module = {} local log = ngx.log local ERR = ngx.ERR local format = string.format module._VERSION = '0.0.1' local function explode(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, 1) while s do if s ~= 1 or cap ~= "" then 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) table.insert(t, cap) end return t end local function build_key(key, variants) if variants == nil then return key end local tags = variants.tags if tags == nil then return key end local nkey = key local tagsDict = module.tags local value for i, tag in pairs(tags) do value = tagsDict[tag] if value ~= nil then nkey = tag .. '=' .. value .. ' ' .. nkey end end return nkey end local function get_variants(key) local pac = module.variants[key] if pac == nil then return nil end return mp.unpack(pac) end local function update_variants(key, what, data) local vars = get_variants(key) if vars == nil then vars = {} end vars[what] = data module.variants[key] = mp.pack(vars) return vars end local function get_tags(header) local tags = {} if header == nil then return tags end local values = explode(header, ',') for i, value in pairs(values) do local pair = explode(value, '=') tags[pair[1]] = pair[2] end return tags end function module.get(key) return build_key(key, get_variants(key)) end function module.set(key, headers) local tags = get_tags(headers["X-Cache-Tag"]) local taglist = {}; for tag, value in pairs(tags) do table.insert(taglist, tag) module.tags[tag] = value end local variants = update_variants(key, 'tags', taglist) return build_key(key, variants) end return module;
Fix new tag implementation
Fix new tag implementation
Lua
mit
kapouer/cache-protocols,kapouer/upcache
55d5bdd32520a50731e918de42c4b4b2ca2ae788
src/tbox/micro.lua
src/tbox/micro.lua
-- add target target("tbox") -- make as a static library set_kind("static") -- add defines add_defines("__tb_prefix__=\"tbox\"") -- set the auto-generated config.h set_configdir("$(buildir)/$(plat)/$(arch)/$(mode)") add_configfiles("tbox.config.h.in") -- add include directories add_includedirs("..", {public = true}) add_includedirs("$(buildir)/$(plat)/$(arch)/$(mode)", {public = true}) -- add the header files for installing add_headerfiles("../(tbox/**.h)|**/impl/**.h") add_headerfiles("../(tbox/prefix/**/prefix.S)") add_headerfiles("../(tbox/math/impl/*.h)") add_headerfiles("../(tbox/utils/impl/*.h)") add_headerfiles("$(buildir)/$(plat)/$(arch)/$(mode)/tbox.config.h", {prefixdir = "tbox"}) -- add options add_options("info", "float", "wchar", "micro", "coroutine") -- add the source files add_files("tbox.c") add_files("libc/string/memset.c") add_files("libc/string/memmov.c") add_files("libc/string/memcpy.c") add_files("libc/string/strstr.c") add_files("libc/string/strdup.c") add_files("libc/string/strlen.c") add_files("libc/string/strnlen.c") add_files("libc/string/strcmp.c") add_files("libc/string/strncmp.c") add_files("libc/string/stricmp.c") add_files("libc/string/strnicmp.c") add_files("libc/string/strlcpy.c") add_files("libc/string/strncpy.c") add_files("libc/stdio/vsnprintf.c") add_files("libc/stdio/snprintf.c") add_files("libc/stdio/printf.c") add_files("libc/stdlib/stdlib.c") add_files("libc/impl/libc.c") add_files("libm/impl/libm.c") add_files("math/impl/math.c") add_files("utils/used.c") add_files("utils/bits.c") add_files("utils/trace.c") add_files("utils/singleton.c") add_files("memory/allocator.c") add_files("memory/native_allocator.c") add_files("memory/static_allocator.c") add_files("memory/impl/static_large_allocator.c") add_files("memory/impl/memory.c") add_files("network/ipv4.c") add_files("network/ipv6.c") add_files("network/ipaddr.c") add_files("network/impl/network.c") add_files("platform/page.c") add_files("platform/time.c") add_files("platform/file.c") add_files("platform/path.c") add_files("platform/sched.c") add_files("platform/print.c") add_files("platform/memory.c") add_files("platform/thread.c") add_files("platform/socket.c") add_files("platform/addrinfo.c") add_files("platform/poller.c") add_files("platform/impl/sockdata.c") add_files("platform/impl/platform.c") add_files("container/iterator.c") add_files("container/list_entry.c") add_files("container/single_list_entry.c") -- add the source files for debug mode if is_mode("debug") then add_files("utils/dump.c") add_files("memory/impl/prefix.c") add_files("platform/backtrace.c") end -- add the source files for float if has_config("float") then add_files("libm/isinf.c") add_files("libm/isinff.c") add_files("libm/isnan.c") add_files("libm/isnanf.c") end -- add the source for the windows if is_os("windows") then add_files("libc/stdlib/mbstowcs.c") add_files("platform/dynamic.c") add_files("platform/windows/interface/ws2_32.c") add_files("platform/windows/interface/mswsock.c") add_files("platform/windows/interface/kernel32.c") if is_mode("debug") then add_files("platform/windows/interface/dbghelp.c") end end -- add the source files for coroutine if has_config("coroutine") then add_files("coroutine/stackless/*.c") add_files("coroutine/impl/stackless/*.c") end -- check interfaces check_interfaces()
-- add target target("tbox") -- make as a static library set_kind("static") -- add defines add_defines("__tb_prefix__=\"tbox\"") -- set the auto-generated config.h set_configdir("$(buildir)/$(plat)/$(arch)/$(mode)") add_configfiles("tbox.config.h.in") -- add include directories add_includedirs("..", {public = true}) add_includedirs("$(buildir)/$(plat)/$(arch)/$(mode)", {public = true}) -- add the header files for installing add_headerfiles("../(tbox/**.h)|**/impl/**.h") add_headerfiles("../(tbox/prefix/**/prefix.S)") add_headerfiles("../(tbox/math/impl/*.h)") add_headerfiles("../(tbox/utils/impl/*.h)") add_headerfiles("$(buildir)/$(plat)/$(arch)/$(mode)/tbox.config.h", {prefixdir = "tbox"}) -- add options add_options("info", "float", "wchar", "micro", "coroutine") -- add the source files add_files("tbox.c") add_files("libc/string/memset.c") add_files("libc/string/memmov.c") add_files("libc/string/memcpy.c") add_files("libc/string/strstr.c") add_files("libc/string/strdup.c") add_files("libc/string/strlen.c") add_files("libc/string/strnlen.c") add_files("libc/string/strcmp.c") add_files("libc/string/strncmp.c") add_files("libc/string/stricmp.c") add_files("libc/string/strnicmp.c") add_files("libc/string/strlcpy.c") add_files("libc/string/strncpy.c") add_files("libc/stdio/vsnprintf.c") add_files("libc/stdio/snprintf.c") add_files("libc/stdio/printf.c") add_files("libc/stdlib/stdlib.c") add_files("libc/impl/libc.c") add_files("libm/impl/libm.c") add_files("math/impl/math.c") add_files("utils/used.c") add_files("utils/bits.c") add_files("utils/trace.c") add_files("utils/singleton.c") add_files("memory/allocator.c") add_files("memory/native_allocator.c") add_files("memory/static_allocator.c") add_files("memory/impl/static_large_allocator.c") add_files("memory/impl/memory.c") add_files("network/ipv4.c") add_files("network/ipv6.c") add_files("network/ipaddr.c") add_files("network/impl/network.c") add_files("platform/page.c") add_files("platform/time.c") add_files("platform/file.c") add_files("platform/path.c") add_files("platform/sched.c") add_files("platform/print.c") add_files("platform/thread.c") add_files("platform/socket.c") add_files("platform/addrinfo.c") add_files("platform/poller.c") add_files("platform/native_memory.c") add_files("platform/impl/sockdata.c") add_files("platform/impl/platform.c") add_files("container/iterator.c") add_files("container/list_entry.c") add_files("container/single_list_entry.c") -- add the source files for debug mode if is_mode("debug") then add_files("utils/dump.c") add_files("memory/impl/prefix.c") add_files("platform/backtrace.c") end -- add the source files for float if has_config("float") then add_files("libm/isinf.c") add_files("libm/isinff.c") add_files("libm/isnan.c") add_files("libm/isnanf.c") end -- add the source for the windows if is_os("windows") then add_files("libc/stdlib/mbstowcs.c") add_files("platform/dynamic.c") add_files("platform/windows/interface/ws2_32.c") add_files("platform/windows/interface/mswsock.c") add_files("platform/windows/interface/kernel32.c") if is_mode("debug") then add_files("platform/windows/interface/dbghelp.c") end end -- add the source files for coroutine if has_config("coroutine") then add_files("coroutine/stackless/*.c") add_files("coroutine/impl/stackless/*.c") end -- check interfaces check_interfaces()
fix compile errors
fix compile errors
Lua
apache-2.0
waruqi/tbox,tboox/tbox,tboox/tbox,waruqi/tbox
b3bf9880d4479f68aa07cf89df1301c804848143
premake4.lua
premake4.lua
solution "litehtml" configurations { "Release", "Debug" } defines { "LITEHTML_UTF8" } targetname "litehtml" language "C++" kind "StaticLib" files { "src/**.c", "src/**.cpp", "src/**.h" } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } targetsuffix "_d" configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } configuration "windows" defines { "WIN32" } project "litehtml" configuration "Debug" targetdir "bin/debug" configuration "Release" targetdir "bin/release" if not os.is("windows") then buildoptions { "-std=c++11 -Wno-error=unused-variable -Wno-error=unused-parameter" } end
solution "litehtml" configurations { "Release", "Debug" } defines { "LITEHTML_UTF8" } targetname "litehtml" language "C++" kind "StaticLib" files { "src/**.c", "src/**.cpp", "src/**.h" } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } targetsuffix "_d" configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } configuration "windows" defines { "WIN32" } project "litehtml" if not os.is("windows") then buildoptions { "-std=c++11 -Wno-error=unused-variable -Wno-error=unused-parameter" } end configuration "Debug" targetdir "bin/debug" configuration "Release" targetdir "bin/release"
fixed debug compilation of litehtml
fixed debug compilation of litehtml
Lua
bsd-3-clause
FishingCactus/litehtml,FishingCactus/litehtml
860f4dfa209b47795adcf5a16c3ac02979647041
controller/utils.lua
controller/utils.lua
-- some utility methods for the space probe function log(message) print(os.date() .. " " .. tostring(message)) end function round(n) return math.floor(n+0.5) end -- translate a raw value through a lookup table of { {rawval, translation} } -- interpolating between closest values function translate(rawval, lookup_table) low_p = { 0, 0 } high_p = { 100000000, 0 } -- hacky big number here(!) for idx,kv in ipairs(lookup_table) do k = kv[1] if k < rawval and k > low_p[1] then low_p = kv end if k > rawval and k < high_p[1] then high_p = kv end end -- now rawval is bounded between low_p[1] and high_p[1], with equivalent lookup values return (rawval - low_p[1]) * (high_p[2] - low_p[2]) / (high_p[1] - low_p[1]) + low_p[2] end
-- some utility methods for the space probe function log(message) print(os.date() .. " " .. tostring(message)) end function round(n) return math.floor(n+0.5) end -- translate a raw value through a lookup table of { {rawval, translation} } -- interpolating between closest values function translate(rawval, lookup_table) low_p = { 0, 0 } high_p = { 100000000, 0 } -- hacky big number here(!) for idx,kv in ipairs(lookup_table) do -- kv is a table of {rawval, translation} here k = kv[1] if rawval == k then return kv[2] end -- shortcut exact matches (helps with zero) if k < rawval and k > low_p[1] then low_p = kv end if k > rawval and k < high_p[1] then high_p = kv end end -- now rawval is bounded between low_p[1] and high_p[1], with equivalent lookup values return (rawval - low_p[1]) * (high_p[2] - low_p[2]) / (high_p[1] - low_p[1]) + low_p[2] end
Fix bug w/ lookup table exact matches & zero interpolation bugs
Fix bug w/ lookup table exact matches & zero interpolation bugs
Lua
mit
makehackvoid/MHV-Space-Probe
d3a6b8d80bb9ac98154bd582d7dbcdc1ceef5d74
lualib/skynet/multicast.lua
lualib/skynet/multicast.lua
local skynet = require "skynet" local mc = require "skynet.multicast.core" local multicastd local multicast = {} local dispatch = {} local chan = {} local chan_meta = { __index = chan, __gc = function(self) self:unsubscribe() end, __tostring = function (self) return string.format("[Multicast:%x]",self.channel) end, } function multicast.new(conf) assert(multicastd, "Init first") local self = {} conf = conf or self self.channel = conf.channel if self.channel == nil then self.channel = skynet.call(multicastd, "lua", "NEW") end self.__pack = conf.pack or skynet.pack self.__unpack = conf.unpack or skynet.unpack self.__dispatch = conf.dispatch return setmetatable(self, chan_meta) end function chan:delete() local c = assert(self.channel) skynet.send(multicastd, "lua", "DEL", c) self.channel = nil self.__subscribe = nil end function chan:publish(...) local c = assert(self.channel) skynet.call(multicastd, "lua", "PUB", c, mc.pack(self.__pack(...))) end function chan:subscribe() local c = assert(self.channel) if self.__subscribe then -- already subscribe return end skynet.call(multicastd, "lua", "SUB", c) self.__subscribe = true dispatch[c] = self end function chan:unsubscribe() if not self.__subscribe then -- already unsubscribe return end local c = assert(self.channel) skynet.send(multicastd, "lua", "USUB", c) self.__subscribe = nil dispatch[c] = nil end local function dispatch_subscribe(channel, source, pack, msg, sz) -- channel as session, do need response skynet.ignoreret() local self = dispatch[channel] if not self then mc.close(pack) error ("Unknown channel " .. channel) end if self.__subscribe then local ok, err = pcall(self.__dispatch, self, source, self.__unpack(msg, sz)) mc.close(pack) assert(ok, err) else -- maybe unsubscribe first, but the message is send out. drop the message unneed mc.close(pack) end end local function init() multicastd = skynet.uniqueservice "multicastd" skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = mc.unpack, dispatch = dispatch_subscribe, } end skynet.init(init, "multicast") return multicast
local skynet = require "skynet" local mc = require "skynet.multicast.core" local multicastd local multicast = {} local dispatch = {} local chan = {} local chan_meta = { __index = chan, __gc = function(self) self:unsubscribe() end, __tostring = function (self) return string.format("[Multicast:%x]",self.channel) end, } function multicast.new(conf) assert(multicastd, "Init first") local self = {} conf = conf or self self.channel = conf.channel if self.channel == nil then self.channel = skynet.call(multicastd, "lua", "NEW") end self.__pack = conf.pack or skynet.pack self.__unpack = conf.unpack or skynet.unpack self.__dispatch = conf.dispatch return setmetatable(self, chan_meta) end function chan:delete() local c = assert(self.channel) skynet.send(multicastd, "lua", "DEL", c) self.channel = nil self.__subscribe = nil end function chan:publish(...) local c = assert(self.channel) skynet.call(multicastd, "lua", "PUB", c, mc.pack(self.__pack(...))) end function chan:subscribe() local c = assert(self.channel) if self.__subscribe then -- already subscribe return end skynet.call(multicastd, "lua", "SUB", c) self.__subscribe = true dispatch[c] = self end function chan:unsubscribe() if not self.__subscribe then -- already unsubscribe return end local c = assert(self.channel) skynet.send(multicastd, "lua", "USUB", c) self.__subscribe = nil dispatch[c] = nil end local function dispatch_subscribe(channel, source, pack, msg, sz) -- channel as session, do need response skynet.ignoreret() local self = dispatch[channel] if not self then mc.close(pack) -- This channel may unsubscribe first, see #1141 return end if self.__subscribe then local ok, err = pcall(self.__dispatch, self, source, self.__unpack(msg, sz)) mc.close(pack) assert(ok, err) else -- maybe unsubscribe first, but the message is send out. drop the message unneed mc.close(pack) end end local function init() multicastd = skynet.uniqueservice "multicastd" skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = mc.unpack, dispatch = dispatch_subscribe, } end skynet.init(init, "multicast") return multicast
fix #1141
fix #1141
Lua
mit
cloudwu/skynet,pigparadise/skynet,icetoggle/skynet,xcjmine/skynet,sanikoyes/skynet,hongling0/skynet,xjdrew/skynet,ag6ag/skynet,JiessieDawn/skynet,icetoggle/skynet,hongling0/skynet,xcjmine/skynet,hongling0/skynet,cloudwu/skynet,korialuo/skynet,bigrpg/skynet,wangyi0226/skynet,xjdrew/skynet,JiessieDawn/skynet,JiessieDawn/skynet,wangyi0226/skynet,ag6ag/skynet,pigparadise/skynet,bigrpg/skynet,korialuo/skynet,cloudwu/skynet,bigrpg/skynet,icetoggle/skynet,sanikoyes/skynet,wangyi0226/skynet,sanikoyes/skynet,ag6ag/skynet,korialuo/skynet,pigparadise/skynet,xcjmine/skynet,xjdrew/skynet
2f51dd606dc72095814fb53cf2ba625957791ed5
src/networkownerservice/src/Server/NetworkOwnerService.lua
src/networkownerservice/src/Server/NetworkOwnerService.lua
--- Tracks a stack of owners so ownership isn't reverted or overwritten in delayed network owner set -- @module NetworkOwnerService local NetworkOwnerService = {} local WEAK_METATABLE = { __mode = "kv" } local SERVER_FLAG = "server" function NetworkOwnerService:Init() assert(not self._partOwnerData, "Already initialized") self._partOwnerData = setmetatable({}, { __mode="k" }) end function NetworkOwnerService:AddSetNetworkOwnerHandle(part, player) assert(self._partOwnerData, "Not initialized") assert(typeof(part) == "Instance" and part:IsA("BasePart"), "Bad part") assert(typeof(player) == "Instance" and player:IsA("Player") or player == nil, "Bad player") if player == nil then player = SERVER_FLAG end -- wrap in table so we have unique value local data = { player = player; } self:_addOwnerData(part, data) self:_updateOwner(part) -- closure keeps a reference to part, so we can set _partOwnerData to __mode="k" return function() if not self:_removeOwner(part, data) then warn("[NetworkOwnerService] - Failed to remove owner data") return end self:_updateOwner(part) end end function NetworkOwnerService:_addOwnerData(part, data) local ownerDataStack = self._partOwnerData[part] if not ownerDataStack then ownerDataStack = setmetatable({}, WEAK_METATABLE) self._partOwnerData[part] = ownerDataStack end if #ownerDataStack > 5 then warn("[NetworkOwnerService] - Possibly a memory leak, lots of owners") end table.insert(ownerDataStack, data) end function NetworkOwnerService:_removeOwner(part, toRemove) local ownerDataStack = self._partOwnerData[part] if not ownerDataStack then warn("[NetworkOwnerService] - No data for part") return false end for index, item in pairs(ownerDataStack) do if item == toRemove then table.remove(ownerDataStack, index) if #ownerDataStack == 0 then self._partOwnerData[part] = nil end return true end end return false end function NetworkOwnerService:_updateOwner(part) local ownerDataStack = self._partOwnerData[part] if not ownerDataStack then self:_setNetworkOwnershipAuto(part) return end -- Prefer last set local player = ownerDataStack[#ownerDataStack].player if player == SERVER_FLAG then player = nil end self:_setNetworkOwner(part, player) end function NetworkOwnerService:_setNetworkOwner(part, player) local canSet, err = part:CanSetNetworkOwnership() if not canSet then warn("[NetworkOwnerService] - Cannot set network ownership:", err, part:GetFullName()) return end part:SetNetworkOwner(player) end function NetworkOwnerService:_setNetworkOwnershipAuto(part) local canSet, err = part:CanSetNetworkOwnership() if not canSet then warn("[NetworkOwnerService] - Cannot set network ownership:", err, part:GetFullName()) return end part:SetNetworkOwnershipAuto() end return NetworkOwnerService
--- Tracks a stack of owners so ownership isn't reverted or overwritten in delayed network owner set -- @module NetworkOwnerService local NetworkOwnerService = {} local WEAK_METATABLE = { __mode = "kv" } local SERVER_FLAG = "server" function NetworkOwnerService:Init() assert(not self._partOwnerData, "Already initialized") self._partOwnerData = setmetatable({}, { __mode="k" }) end function NetworkOwnerService:AddSetNetworkOwnerHandle(part, player) assert(self ~= NetworkOwnerService, "Make sure to retrieve NetworkOwnerService from a ServiceBag") assert(self._partOwnerData, "Not initialized") assert(typeof(part) == "Instance" and part:IsA("BasePart"), "Bad part") assert(typeof(player) == "Instance" and player:IsA("Player") or player == nil, "Bad player") if player == nil then player = SERVER_FLAG end -- wrap in table so we have unique value local data = { player = player; } self:_addOwnerData(part, data) self:_updateOwner(part) -- closure keeps a reference to part, so we can set _partOwnerData to __mode="k" return function() if not self:_removeOwner(part, data) then warn("[NetworkOwnerService] - Failed to remove owner data") return end self:_updateOwner(part) end end function NetworkOwnerService:_addOwnerData(part, data) local ownerDataStack = self._partOwnerData[part] if not ownerDataStack then ownerDataStack = setmetatable({}, WEAK_METATABLE) self._partOwnerData[part] = ownerDataStack end if #ownerDataStack > 5 then warn("[NetworkOwnerService] - Possibly a memory leak, lots of owners") end table.insert(ownerDataStack, data) end function NetworkOwnerService:_removeOwner(part, toRemove) local ownerDataStack = self._partOwnerData[part] if not ownerDataStack then warn("[NetworkOwnerService] - No data for part") return false end for index, item in pairs(ownerDataStack) do if item == toRemove then table.remove(ownerDataStack, index) if #ownerDataStack == 0 then self._partOwnerData[part] = nil end return true end end return false end function NetworkOwnerService:_updateOwner(part) local ownerDataStack = self._partOwnerData[part] if not ownerDataStack then self:_setNetworkOwnershipAuto(part) return end -- Prefer last set local player = ownerDataStack[#ownerDataStack].player if player == SERVER_FLAG then player = nil end self:_setNetworkOwner(part, player) end function NetworkOwnerService:_setNetworkOwner(part, player) local canSet, err = part:CanSetNetworkOwnership() if not canSet then warn("[NetworkOwnerService] - Cannot set network ownership:", err, part:GetFullName()) return end part:SetNetworkOwner(player) end function NetworkOwnerService:_setNetworkOwnershipAuto(part) local canSet, err = part:CanSetNetworkOwnership() if not canSet then warn("[NetworkOwnerService] - Cannot set network ownership:", err, part:GetFullName()) return end part:SetNetworkOwnershipAuto() end return NetworkOwnerService
fix: NetworkOwnerService provides good errors
fix: NetworkOwnerService provides good errors
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
8caa6f045d2104b92fb376827e20bf1d7a0d41b1
xmake/platforms/mingw/load.lua
xmake/platforms/mingw/load.lua
--!The Make-like 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 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- -- imports import("core.project.config") -- load it function main() -- init the file formats _g.formats = {} _g.formats.static = {"", ".lib"} _g.formats.object = {"", ".obj"} _g.formats.shared = {"", ".dll"} _g.formats.binary = {"", ".exe"} _g.formats.symbol = {"", ".pdb"} -- 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 _g.cxflags = { archflags } _g.asflags = { archflags } _g.ldflags = { archflags } _g.shflags = { archflags } -- init linkdirs and includedirs local sdkdir = config.get("sdk") if sdkdir then _g.includedirs = {path.join(sdkdir, "include")} _g.linkdirs = {path.join(sdkdir, "lib")} end -- ok return _g end
--!The Make-like 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 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- -- imports import("core.project.config") -- load it function main() -- init the file formats _g.formats = {} _g.formats.static = {"lib", ".a"} _g.formats.object = {"", ".o"} _g.formats.shared = {"lib", ".so"} _g.formats.binary = {"", ".exe"} _g.formats.symbol = {"", ".pdb"} -- 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 _g.cxflags = { archflags } _g.asflags = { archflags } _g.ldflags = { archflags } _g.shflags = { archflags } -- init linkdirs and includedirs local sdkdir = config.get("sdk") if sdkdir then _g.includedirs = {path.join(sdkdir, "include")} _g.linkdirs = {path.join(sdkdir, "lib")} end -- ok return _g end
fix mingw link issue for *.lib
fix mingw link issue for *.lib
Lua
apache-2.0
waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
5e1410627b0f6e12c89a32b6ffb89980cb4ac6da
src/main.lua
src/main.lua
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local camera = require 'camera' local menu = require 'menu' local scale = 2 function love.load() -- costume loading love.filesystem.mkdir('costumes') love.filesystem.mkdir('costumes/troy') love.filesystem.mkdir('costumes/abed') love.filesystem.mkdir('costumes/annie') love.filesystem.mkdir('costumes/shirley') love.filesystem.mkdir('costumes/pierce') love.filesystem.mkdir('costumes/jeff') love.filesystem.mkdir('costumes/britta') -- tileset loading Level.load_tileset('studyroom.tmx') Level.load_tileset('hallway.tmx') Level.load_tileset('forest2.tmx') Level.load_tileset('town.tmx') -- load images Level.load_image('images/cow.png') Level.load_image('images/hippy.png') love.graphics.setDefaultImageFilter('nearest', 'nearest') camera:setScale(1 / scale , 1 / scale) love.graphics.setMode(love.graphics:getWidth() * scale, love.graphics:getHeight() * scale) Gamestate.switch(menu) end function love.update(dt) Gamestate.update(dt) end function love.keyreleased(key) Gamestate.keyreleased(key) end function love.keypressed(key) Gamestate.keypressed(key) end function love.draw() camera:set() Gamestate.draw() camera:unset() love.graphics.print(love.timer.getFPS() .. ' FPS', 10, 10) end
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local camera = require 'camera' local menu = require 'menu' local scale = 2 local paused = false function love.load() -- costume loading love.filesystem.mkdir('costumes') love.filesystem.mkdir('costumes/troy') love.filesystem.mkdir('costumes/abed') love.filesystem.mkdir('costumes/annie') love.filesystem.mkdir('costumes/shirley') love.filesystem.mkdir('costumes/pierce') love.filesystem.mkdir('costumes/jeff') love.filesystem.mkdir('costumes/britta') -- tileset loading Level.load_tileset('studyroom.tmx') Level.load_tileset('hallway.tmx') Level.load_tileset('forest2.tmx') Level.load_tileset('town.tmx') -- load images Level.load_image('images/cow.png') Level.load_image('images/hippy.png') love.graphics.setDefaultImageFilter('nearest', 'nearest') camera:setScale(1 / scale , 1 / scale) love.graphics.setMode(love.graphics:getWidth() * scale, love.graphics:getHeight() * scale) Gamestate.switch(menu) end function love.update(dt) if paused then return end dt = math.min(0.033333333, dt) Gamestate.update(dt) end function love.keyreleased(key) Gamestate.keyreleased(key) end function love.focus(f) paused = not f end function love.keypressed(key) Gamestate.keypressed(key) end function love.draw() camera:set() Gamestate.draw() camera:unset() if paused then love.graphics.setColor(75, 75, 75, 125) love.graphics.rectangle('fill', 0, 0, love.graphics:getWidth(), love.graphics:getHeight()) love.graphics.setColor(255, 255, 255, 255) end love.graphics.print(love.timer.getFPS() .. ' FPS', 10, 10) end
Add a minimum framerate. Pause the game when not in use
Add a minimum framerate. Pause the game when not in use Many people complained of falling through the floor at odd times. A minimum framerate fixes these things. However, the game might now feel 'slow' for some users on lower-end computers. There isn't a better way to fix this, so apologies in advance. The game will now pause when it loses focus. No more getting attacked by hippies when you minimize the window.
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua
028abb6eb0a895bb05d687420825f9bb94f88fa2
modules/data/tabread.lua
modules/data/tabread.lua
sptbl["tabread"] = { files = { module = "tabread.c", header = "tabread.h", example = "ex_tabread.c", }, func = { create = "sp_tabread_create", destroy = "sp_tabread_destroy", init = "sp_tabread_init", compute = "sp_tabread_compute", }, params = { mandatory = { { name = "ft", type = "sp_ftbl *", description = "A properly allocated table (using a function like sp_gen_file).", default = "N/A" }, { name = "mode", type = "SPFLOAT", description ="1 = scaled index, 0 = unscaled index", default = 1.0 }, }, optional = { { name = "index", type = "SPFLOAT", description ="index position, either scaled or unscaled with mode parameter", default = 0 }, { name = "offset", type = "SPFLOAT", description ="Offset from beginning of ftable. If the mode is scaled, then it is in range 0-1, other wise it is the index position.", default = 1.0 }, { name = "wrap", type = "SPFLOAT", description ="Enable wraparound. 1 = on; 0 = 0ff.", default = 1.0 } } }, modtype = "module", description = [[Table Read through an sp_ftbl with linear interpolation. ]], ninputs = 0, noutputs = 1, inputs = { }, outputs = { { name = "out", description = "Signal output." }, } }
sptbl["tabread"] = { files = { module = "tabread.c", header = "tabread.h", example = "ex_tabread.c", }, func = { create = "sp_tabread_create", destroy = "sp_tabread_destroy", init = "sp_tabread_init", compute = "sp_tabread_compute", }, params = { mandatory = { { name = "ft", type = "sp_ftbl *", description = "A properly allocated table (using a function like sp_gen_file).", default = "N/A" }, { name = "mode", type = "SPFLOAT", description ="1 = scaled index, 0 = unscaled index", default = 1.0 }, }, optional = { { name = "index", type = "SPFLOAT", description ="index position, either scaled or unscaled with mode parameter", default = 0 }, { name = "offset", type = "SPFLOAT", description ="Offset from beginning of ftable. If the mode is scaled, then it is in range 0-1, other wise it is the index position.", default = 1.0 }, { name = "wrap", type = "SPFLOAT", description ="Enable wraparound. 1 = on; 0 = 0ff.", default = 1.0 } } }, modtype = "module", description = [[Table Read through an sp_ftbl with linear interpolation. ]], ninputs = 0, noutputs = 1, inputs = { { name = "in", description = "Signal in." }, }, outputs = { { name = "out", description = "Signal output." }, } }
tabread: fixed documentation issue
tabread: fixed documentation issue
Lua
mit
aure/Soundpipe,aure/Soundpipe,aure/Soundpipe,narner/Soundpipe,narner/Soundpipe,narner/Soundpipe,narner/Soundpipe,aure/Soundpipe
e19d2e1e843bd139b6c1583e4b5d40466e8279b3
otouto/plugins/patterns.lua
otouto/plugins/patterns.lua
local patterns = {} local utilities = require('otouto.utilities') patterns.triggers = { '^/?s/.-/.-$' } function patterns:action(msg) if not msg.reply_to_message then return true end local output = msg.reply_to_message.text if msg.reply_to_message.from.id == self.info.id then output = output:gsub('Did you mean:\n"', '') output = output:gsub('"$', '') end local m1, m2 = msg.text:match('^/?s/(.-)/(.-)/?$') if not m2 then return true end local res res, output = pcall( function() return output:gsub(m1, m2) end ) if res == false then utilities.send_reply(self, msg, 'Malformed pattern!') else output = output:sub(1, 4000) output = 'Did you mean:\n"' .. output .. '"' utilities.send_reply(self, msg.reply_to_message, output) end end return patterns
local patterns = {} local utilities = require('otouto.utilities') patterns.triggers = { '^/?s/.-/.-$' } function patterns:action(msg) if not msg.reply_to_message then return true end local output = msg.reply_to_message.text if msg.reply_to_message.from.id == self.info.id then output = output:gsub('Did you mean:\n"', '') output = output:gsub('"$', '') end local m1, m2 = msg.text:match('^/?s/(.-)/(.-)/?$') if not m2 then return true end local res res, output = pcall( function() return output:gsub(m1, m2) end ) if res == false then utilities.send_reply(self, msg, 'Malformed pattern!') else output = output:sub(1, 4000) output = '*Did you mean:*\n"' .. utilities.md_escape(utilities.trim(output)) .. '"' utilities.send_reply(self, msg.reply_to_message, output, true) end end return patterns
patterns.lua Trim whitespace off the ends of strings (partial fix for https://github.com/topkecleon/otouto/issues/74). Make output style consistent with translate.lua.
patterns.lua Trim whitespace off the ends of strings (partial fix for https://github.com/topkecleon/otouto/issues/74). Make output style consistent with translate.lua.
Lua
agpl-3.0
bb010g/otouto,Brawl345/Brawlbot-v2,topkecleon/otouto,barreeeiroo/BarrePolice
dd83ca82f7441389cb742b136e19cad1cb2eaddf
src/grammar.lua
src/grammar.lua
--[[ grammar.lua A simple LPeg grammar for scheme. In order to be as flexible as possible, this grammar only parses tokens from input. All interpretation and evaluation tasks are handled by the interpreter which is provided as an argument to the main function returned by this module. Copyright (c) 2014, Joshua Ballanco. Licensed under the BSD 2-Clause License. See COPYING for full license details. --]] local lp = require("lpeg") local re = require("re") local P, R, S, V, C, Cg, Ct, locale = lp.P, lp.R, lp.S, lp.V, lp.C, lp.Cg, lp.Ct, lp.locale local function grammar(parse) -- Use locale for matching; generates rules: alnum, alpha, cntrl, digit, graph, lower, -- print, punct, space, upper, and xdigit re.updatelocale() return re.compile([[ -- "Program" is the top-level construct in Scheme, but for now we're using it to proxy -- to other forms for testing... Program <- CommandOrDefinition -- TODO: need to add the "...OrDefinition" part. For now just proxying through to -- forms we want to test... CommandOrDefinition <- Command Command <- Expression -- "Expression" encompases most valid forms, including everything that counts as a -- "Datum" for processing by the REPL. More elements will be added to this list as -- more of the grammar is defined. Expression <- Literal -- TODO: Literal should come after Symbol -- ...just here to test suffix for now / Symbol -- Synonymous with "Identifier" Literal <- SelfEvaluating SelfEvaluating <- suffix -- just putting this here for an interim test... / String / Number explicit_sign <- [+-] exp_value <- {:value: digit+ :} open <- [(] close <- [)] quote <- ["] not_quote <- [^"] backslash <- [\\] escaped_quote <- backslash quote dot <- [.] minus <- [-] -- Rules for the R7RS numeric tower suffix <- {:exp: {| exp_marker sign exp_value |} :} exp_marker <- [eE] sign <- {:sign: explicit_sign? :} exactness <- ([#] ([iI] / [eE]))? bradix <- [#] [bB] oradix <- [#] [oO] radix <- ([#] [dD])? xradix <- [#] [xX] bdigit <- [01] odigit <- [0-7] digit <- %digit xdigit <- %xdigit -- Other basic elements initial <- %alpha / special_initial special_initial <- [!$%&*/:<=>?^_~] subsequent <- initial / digit / special_subsequent special_subsequent <- explicit_sign / [.@] vertical_line <- [|] xscalar <- xdigit+ inline_hex_escape <- backslash [x] xscalar [;] mnemonic_escape <- backslash [abtnr] symbol_element <- [^|\\] / inline_hex_escape / mnemonic_escape / "\\|" -- Parsing constructs String <- { quote (escaped_quote / not_quote)* quote } -> parse_string Symbol <- { %alpha %alnum* } -> parse_symbol Number <- { sign digit+ (dot digit*)? } -> parse_number -- Simple forms Car <- Symbol Cdr <- List+ / Symbol / Number List <- {| open %space* {:car: Car :} %space+ {:cdr: Cdr :} %space* close |} -> parse_list ]], parse) end return grammar
--[[ grammar.lua A simple LPeg grammar for scheme. In order to be as flexible as possible, this grammar only parses tokens from input. All interpretation and evaluation tasks are handled by the interpreter which is provided as an argument to the main function returned by this module. Copyright (c) 2014, Joshua Ballanco. Licensed under the BSD 2-Clause License. See COPYING for full license details. --]] local lp = require("lpeg") local re = require("re") local P, R, S, V, C, Cg, Ct, locale = lp.P, lp.R, lp.S, lp.V, lp.C, lp.Cg, lp.Ct, lp.locale local function grammar(parse) -- Use locale for matching; generates rules: alnum, alpha, cntrl, digit, graph, lower, -- print, punct, space, upper, and xdigit re.updatelocale() return re.compile([[ -- "Program" is the top-level construct in Scheme, but for now we're using it to proxy -- to other forms for testing... Program <- CommandOrDefinition -- TODO: need to add the "...OrDefinition" part. For now just proxying through to -- forms we want to test... CommandOrDefinition <- Command Command <- Expression -- "Expression" encompases most valid forms, including everything that counts as a -- "Datum" for processing by the REPL. More elements will be added to this list as -- more of the grammar is defined. Expression <- Literal -- TODO: Literal should come after Symbol -- ...just here to test suffix for now / Symbol -- Synonymous with "Identifier" Literal <- SelfEvaluating SelfEvaluating <- suffix -- just putting this here for an interim test... / String / Number explicit_sign <- [+-] open <- [(] close <- [)] quote <- ["] not_quote <- [^"] backslash <- [\\] escaped_quote <- backslash quote dot <- [.] minus <- [-] -- Rules for the R7RS numeric tower suffix <- {:exp: exp_marker {| {:sign: sign :} {:value: digit+ :} |} :}? exp_marker <- [eE] sign <- explicit_sign? exactness <- ([#] ([iI] / [eE]))? bradix <- [#] [bB] oradix <- [#] [oO] radix <- ([#] [dD])? xradix <- [#] [xX] bdigit <- [01] odigit <- [0-7] digit <- %digit xdigit <- %xdigit -- Other basic elements initial <- %alpha / special_initial special_initial <- [!$%&*/:<=>?^_~] subsequent <- initial / digit / special_subsequent special_subsequent <- explicit_sign / [.@] vertical_line <- [|] xscalar <- xdigit+ inline_hex_escape <- backslash [x] xscalar [;] mnemonic_escape <- backslash [abtnr] symbol_element <- [^|\\] / inline_hex_escape / mnemonic_escape / "\\|" -- Parsing constructs String <- { quote (escaped_quote / not_quote)* quote } -> parse_string Symbol <- { %alpha %alnum* } -> parse_symbol Number <- { sign digit+ (dot digit*)? suffix } -> parse_number -- Simple forms Car <- Symbol Cdr <- List+ / Symbol / Number List <- {| open %space* {:car: Car :} %space+ {:cdr: Cdr :} %space* close |} -> parse_list ]], parse) end return grammar
Reorg suffix rule moving names into suffix
Reorg suffix rule moving names into suffix
Lua
bsd-2-clause
jballanc/aydede
b66f1b78bf8c1ecb67813eb40c30591934cf0ea1
src/conf/RepositoryHandler.lua
src/conf/RepositoryHandler.lua
local FILE_NAME = 'repositories.cfg'; -- ------------------------------------------------ -- Module -- ------------------------------------------------ local RepositoryHandler = {}; -- ------------------------------------------------ -- Local Variables -- ------------------------------------------------ local repositories = {}; -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ --- -- Checks if the repository file exists on the user's system. -- @return (boolean) Wether the file exists or not. -- local function hasRepositoryFile() return love.filesystem.isFile( FILE_NAME ); end --- -- Loads the repository file. -- @return (table) The repository file as a lua table. -- local function load() for line in love.filesystem.lines( FILE_NAME ) do if line == '' or line:find( ';' ) == 1 then -- Ignore comments and empty lines. else -- Store values in the section. -- TODO: Expand pattern to match names with whitespaces: '(([%g]+[%s]*)+)%s+=%s+(.+)'; local key, value = line:match( '^([%g]+)%s+=%s+(.+)' ); repositories[key] = value; end end end --- -- Saves the repositories-table to the hard disk. -- local function save() local file = love.filesystem.newFile( FILE_NAME, 'w' ); file:write( '; This file keeps track of the paths where the repositories\r\n' ); file:write( '; are located on the user\'s hard drive.\r\n' ); file:write( '; Name = Path\r\n' ); for key, value in pairs( repositories ) do local line = string.format( '%s = %s\r\n', key, value ); file:write( line ); end file:close(); end -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ --- -- Initialises the handler and creates an empty repository file on the hard -- disk if it doesn't exist already. -- function RepositoryHandler.init() if not hasRepositoryFile() then save(); -- Create empty file. end load(); end --- -- Adds a new repository to the list of repositories and saves the data to the -- hard drive. -- @param name (string) The repository's name. -- @param path (string) The repository's location. -- function RepositoryHandler.add( name, path ) repositories[name] = path; save(); end --- -- Removes a repository from the list of repositories and saves the data to the -- hard drive. -- @param name (string) The repository's name. -- function RepositoryHandler.remove( name ) repositories[name] = nil; save(); end --- -- Returns the repositories-table. -- @return (table) The repositories. -- function RepositoryHandler.getRepositories() return repositories; end return RepositoryHandler;
local FILE_NAME = 'repositories.cfg'; -- ------------------------------------------------ -- Module -- ------------------------------------------------ local RepositoryHandler = {}; -- ------------------------------------------------ -- Local Variables -- ------------------------------------------------ local repositories = {}; -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ --- -- Checks if the repository file exists on the user's system. -- @return (boolean) Wether the file exists or not. -- local function hasRepositoryFile() return love.filesystem.isFile( FILE_NAME ); end --- -- Loads the repository file. -- @return (table) The repository file as a lua table. -- local function load() for line in love.filesystem.lines( FILE_NAME ) do if line == '' or line:find( ';' ) == 1 then -- Ignore comments and empty lines. else -- Store values in the section. local key, value = line:match( '^%s*([%g%s]*%g)%s*=%s*(.+)$' ); repositories[key] = value; end end end --- -- Saves the repositories-table to the hard disk. -- local function save() local file = love.filesystem.newFile( FILE_NAME, 'w' ); file:write( '; This file keeps track of the paths where the repositories\r\n' ); file:write( '; are located on the user\'s hard drive.\r\n' ); file:write( '; Name = Path\r\n' ); for key, value in pairs( repositories ) do local line = string.format( '%s = %s\r\n', key, value ); file:write( line ); end file:close(); end -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ --- -- Initialises the handler and creates an empty repository file on the hard -- disk if it doesn't exist already. -- function RepositoryHandler.init() if not hasRepositoryFile() then save(); -- Create empty file. end load(); end --- -- Adds a new repository to the list of repositories and saves the data to the -- hard drive. -- @param name (string) The repository's name. -- @param path (string) The repository's location. -- function RepositoryHandler.add( name, path ) repositories[name] = path; save(); end --- -- Removes a repository from the list of repositories and saves the data to the -- hard drive. -- @param name (string) The repository's name. -- function RepositoryHandler.remove( name ) repositories[name] = nil; save(); end --- -- Returns the repositories-table. -- @return (table) The repositories. -- function RepositoryHandler.getRepositories() return repositories; end return RepositoryHandler;
Fix pattern to allow whitespace in folder names
Fix pattern to allow whitespace in folder names Thanks to @s-ol for providing the fix!
Lua
mit
rm-code/logivi
80e33bc4f25fd1f6c117527393db9afd5ed20c20
regress/71-empty-cqueue.lua
regress/71-empty-cqueue.lua
#!/bin/sh _=[[ . "${0%%/*}/regress.sh" exec runlua "$0" "$@" ]] require"regress".export".*" -- -- Issue #71A -- After the addition of alerts, cqueue:loop waited indefinitely -- on an empty queue when the original, more desirable behavior was that it -- should immediately return. -- -- Issue #71B -- cqueue:step did not clear an alert, causing the cqueue to -- continually poll as ready even after calling cqueue:step. -- local function check_71A() info"testing issue 71A" -- run loop from top-level so we're not testing the nested :step logic local grace = 3 local fh = check(io.popen(string.format([[ GRACE=%d run_and_wait() { . "${CQUEUES_SRCDIR}/regress/regress.sh" || exit 1; runlua - <<-EOF & require"regress".export".*" assert(cqueues.new():loop()) io.stdout:write"OK\n" EOF PID="$!" sleep ${GRACE} set +e # disable strict errors kill -9 "${PID}" 2>&- wait "${PID}" RC="$?" printf "RC=%%d\n" "${RC}" } exec </dev/null run_and_wait & ]], grace), "r")) check(cqueues.new():wrap(function () local con = check(fileresult(socket.dup(fh))) local ln, why = fileresult(con:xread("*l", grace + 1)) check(ln, "%s", why or "End of file") check(ln == "OK", "expected \"OK\", got \"%s\"", tostring(ln)) end):loop()) info"71A OK" end local function check_71B() info"testing 71B" local outer = cqueues.new() local inner = cqueues.new() local cv = condition.new() outer:wrap(function () info"setting alert on inner loop" check(inner:alert()) info"stepping inner loop" check(inner:step()) info"polling inner loop" local e1, e2 = cqueues.poll(inner, 0) check(e1 ~= inner and e2 ~= inner, "alert not cleared") cv:signal() end) outer:wrap(function () check(cv:wait(3), "timeout before inner loop test completed") end) check(outer:loop()) info"71B OK" end check_71A() check_71B() say"OK"
#!/bin/sh _=[[ . "${0%%/*}/regress.sh" exec runlua "$0" "$@" ]] require"regress".export".*" -- -- Issue #71A -- After the addition of alerts, cqueue:loop waited indefinitely -- on an empty queue when the original, more desirable behavior was that it -- should immediately return. -- -- Issue #71B -- cqueue:step did not clear an alert, causing the cqueue to -- continually poll as ready even after calling cqueue:step. -- local function check_71A() info"testing issue 71A" -- run loop from top-level so we're not testing the nested :step logic local grace = 3 local fh = check(io.popen(string.format([[ GRACE=%d run_and_wait() { . "${CQUEUES_SRCDIR}/regress/regress.sh" || exit 1; runlua - <<-EOF & require"regress".export".*" assert(cqueues.new():loop()) io.stdout:write"OK\n" EOF PID="$!" sleep ${GRACE} set +e # disable strict errors kill -9 "${PID}" 2>&- wait "${PID}" RC="$?" printf "RC=%%d\n" "${RC}" } exec </dev/null run_and_wait & ]], grace), "r")) check(cqueues.new():wrap(function () local con = check(fileresult(socket.dup(fh))) local ln, why = fileresult(con:xread("*l", grace + 1)) check(ln, "%s", why or "End of file") check(ln == "OK", "expected \"OK\", got \"%s\"", tostring(ln)) end):loop()) info"71A OK" end local function check_71B() info"testing 71B" local outer = cqueues.new() local inner = cqueues.new() local cv = condition.new() outer:wrap(function () info"setting alert on inner loop" check(inner:alert()) -- -- NOTE: A kqueue descriptor will continue polling as -- readable until kevent(2) returns 0 events. As of -- 2016-06-01, cqueue:step does not iteratively call kevent. -- That may change in the future, but for now on BSDs code -- must :step twice for an alert to clear such that a queue -- stops polling as ready. -- local count = 0 local clear = false while not clear and count < 3 do count = count + 1 info"stepping inner loop" check(inner:step()) info"polling inner loop" cqueues.poll(inner, 0) local e1, e2 = cqueues.poll(inner, 0) clear = e1 ~= inner and e2 ~= inner end check(clear, "alert not cleared") info("alert cleared after %d steppings", count) cv:signal() end) outer:wrap(function () check(cv:wait(3), "timeout before inner loop test completed") end) check(outer:loop()) info"71B OK" end check_71A() check_71B() say"OK"
fix #71 regression test on BSD
fix #71 regression test on BSD
Lua
mit
daurnimator/cqueues,wahern/cqueues,wahern/cqueues,daurnimator/cqueues
f04acc4b948a45bcfbd22f219df001f96064edf7
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") local has_rdate = false m.uci:foreach("system", "rdate", function() has_rdate = true return false end) s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:taboption("general", DummyValue, "_system", translate("System")).value = system s:taboption("general", DummyValue, "_cpu", translate("Processor")).value = model s:taboption("general", DummyValue, "_kernel", translate("Kernel")).value = luci.util.exec("uname -r") or "?" local load1, load5, load15 = luci.sys.loadavg() s:taboption("general", DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:taboption("general", DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("cached")), 100 * membuffers / memtotal, tostring(translate("buffered")), 100 * memfree / memtotal, tostring(translate("free")) ) s:taboption("general", DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:taboption("general", DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:taboption("general", Value, "hostname", translate("Hostname")) hn.datatype = "hostname" function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:taboption("general", ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(7, translate("Debug")) o:value(6, translate("Info")) o:value(5, translate("Notice")) o:value(4, translate("Warning")) o:value(3, translate("Error")) o:value(2, translate("Critical")) o:value(1, translate("Alert")) o:value(0, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- Rdate -- if has_rdate then m3= Map("timeserver", translate("Time Server (rdate)")) s = m3:section(TypedSection, "timeserver") s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s.rmempty = true s:option(Value, "hostname", translate("Name")) i = s:option(ListValue, "interface", translate("Interface")) i:value("", translate("Default")) m3.uci:foreach("network", "interface", function (section) local ifc = section[".name"] if ifc ~= "loopback" then i:value(ifc) end end ) end m2 = Map("luci") f = m2:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware")) f:tab("detected", translate("Detected Files"), translate("The following files are detected by the system and will be kept automatically during sysupgrade")) f:tab("custom", translate("Custom Files"), translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade")) d = f:taboption("detected", DummyValue, "_detected", translate("Detected files")) d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end c = f:taboption("custom", TextValue, "_custom", translate("Custom files")) c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) value = value:gsub("\r\n?", "\n") return nixio.fs.writefile("/etc/sysupgrade.conf", value) end return m, m3, m2
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") local has_rdate = false m.uci:foreach("system", "rdate", function() has_rdate = true return false end) s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:taboption("general", DummyValue, "_system", translate("System")).value = system s:taboption("general", DummyValue, "_cpu", translate("Processor")).value = model s:taboption("general", DummyValue, "_kernel", translate("Kernel")).value = luci.util.exec("uname -r") or "?" local load1, load5, load15 = luci.sys.loadavg() s:taboption("general", DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:taboption("general", DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("cached")), 100 * membuffers / memtotal, tostring(translate("buffered")), 100 * memfree / memtotal, tostring(translate("free")) ) s:taboption("general", DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:taboption("general", DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:taboption("general", Value, "hostname", translate("Hostname")) hn.datatype = "hostname" function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:taboption("general", ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(7, translate("Debug")) o:value(6, translate("Info")) o:value(5, translate("Notice")) o:value(4, translate("Warning")) o:value(3, translate("Error")) o:value(2, translate("Critical")) o:value(1, translate("Alert")) o:value(0, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- Rdate -- if has_rdate then m3= Map("timeserver", translate("Time Server (rdate)")) s = m3:section(TypedSection, "timeserver") s.anonymous = true s.addremove = true s.template = "cbi/tblsection" h = s:option(Value, "hostname", translate("Name")) h.rmempty = true h.datatype = host i = s:option(ListValue, "interface", translate("Interface")) i.rmempty = true i:value("", translate("Default")) m3.uci:foreach("network", "interface", function (section) local ifc = section[".name"] if ifc ~= "loopback" then i:value(ifc) end end ) end m2 = Map("luci") f = m2:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware")) f:tab("detected", translate("Detected Files"), translate("The following files are detected by the system and will be kept automatically during sysupgrade")) f:tab("custom", translate("Custom Files"), translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade")) d = f:taboption("detected", DummyValue, "_detected", translate("Detected files")) d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end c = f:taboption("custom", TextValue, "_custom", translate("Custom files")) c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) value = value:gsub("\r\n?", "\n") return nixio.fs.writefile("/etc/sysupgrade.conf", value) end return m, m3, m2
modules/admin-full: Fixes for rdate config
modules/admin-full: Fixes for rdate config
Lua
apache-2.0
joaofvieira/luci,lbthomsen/openwrt-luci,keyidadi/luci,ollie27/openwrt_luci,oyido/luci,bright-things/ionic-luci,keyidadi/luci,dwmw2/luci,dismantl/luci-0.12,jlopenwrtluci/luci,joaofvieira/luci,dismantl/luci-0.12,cshore/luci,teslamint/luci,remakeelectric/luci,taiha/luci,schidler/ionic-luci,Hostle/luci,david-xiao/luci,rogerpueyo/luci,deepak78/new-luci,remakeelectric/luci,nmav/luci,thess/OpenWrt-luci,oneru/luci,palmettos/cnLuCI,cappiewu/luci,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,palmettos/test,palmettos/test,lbthomsen/openwrt-luci,jchuang1977/luci-1,mumuqz/luci,wongsyrone/luci-1,bright-things/ionic-luci,schidler/ionic-luci,981213/luci-1,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,kuoruan/lede-luci,bittorf/luci,oneru/luci,slayerrensky/luci,teslamint/luci,Kyklas/luci-proto-hso,NeoRaider/luci,cshore-firmware/openwrt-luci,jorgifumi/luci,tobiaswaldvogel/luci,forward619/luci,kuoruan/lede-luci,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,Kyklas/luci-proto-hso,opentechinstitute/luci,forward619/luci,hnyman/luci,kuoruan/luci,artynet/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,NeoRaider/luci,zhaoxx063/luci,RedSnake64/openwrt-luci-packages,dismantl/luci-0.12,opentechinstitute/luci,maxrio/luci981213,Sakura-Winkey/LuCI,marcel-sch/luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,openwrt/luci,aa65535/luci,ff94315/luci-1,openwrt-es/openwrt-luci,chris5560/openwrt-luci,LuttyYang/luci,MinFu/luci,NeoRaider/luci,bright-things/ionic-luci,jlopenwrtluci/luci,taiha/luci,Wedmer/luci,981213/luci-1,Noltari/luci,zhaoxx063/luci,bright-things/ionic-luci,thesabbir/luci,schidler/ionic-luci,tcatm/luci,palmettos/test,palmettos/cnLuCI,jchuang1977/luci-1,teslamint/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,florian-shellfire/luci,opentechinstitute/luci,keyidadi/luci,LuttyYang/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,chris5560/openwrt-luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,jorgifumi/luci,nwf/openwrt-luci,Noltari/luci,lbthomsen/openwrt-luci,MinFu/luci,zhaoxx063/luci,rogerpueyo/luci,Noltari/luci,kuoruan/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,slayerrensky/luci,bittorf/luci,teslamint/luci,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,LuttyYang/luci,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,forward619/luci,kuoruan/lede-luci,chris5560/openwrt-luci,cshore/luci,shangjiyu/luci-with-extra,db260179/openwrt-bpi-r1-luci,rogerpueyo/luci,lcf258/openwrtcn,Wedmer/luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,thesabbir/luci,kuoruan/luci,male-puppies/luci,wongsyrone/luci-1,RuiChen1113/luci,opentechinstitute/luci,schidler/ionic-luci,fkooman/luci,oneru/luci,maxrio/luci981213,artynet/luci,male-puppies/luci,marcel-sch/luci,openwrt/luci,deepak78/new-luci,david-xiao/luci,sujeet14108/luci,fkooman/luci,lcf258/openwrtcn,oneru/luci,joaofvieira/luci,urueedi/luci,remakeelectric/luci,palmettos/cnLuCI,tobiaswaldvogel/luci,RuiChen1113/luci,taiha/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,oyido/luci,obsy/luci,RedSnake64/openwrt-luci-packages,thesabbir/luci,LuttyYang/luci,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,MinFu/luci,zhaoxx063/luci,urueedi/luci,jlopenwrtluci/luci,male-puppies/luci,harveyhu2012/luci,kuoruan/lede-luci,obsy/luci,openwrt-es/openwrt-luci,slayerrensky/luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,david-xiao/luci,tcatm/luci,Noltari/luci,Hostle/luci,Noltari/luci,hnyman/luci,jchuang1977/luci-1,sujeet14108/luci,urueedi/luci,bittorf/luci,jorgifumi/luci,artynet/luci,urueedi/luci,sujeet14108/luci,urueedi/luci,harveyhu2012/luci,tobiaswaldvogel/luci,obsy/luci,dismantl/luci-0.12,tcatm/luci,forward619/luci,cappiewu/luci,nmav/luci,mumuqz/luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,obsy/luci,dwmw2/luci,fkooman/luci,tcatm/luci,lcf258/openwrtcn,jorgifumi/luci,palmettos/test,oyido/luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,thess/OpenWrt-luci,artynet/luci,joaofvieira/luci,openwrt-es/openwrt-luci,keyidadi/luci,remakeelectric/luci,ollie27/openwrt_luci,rogerpueyo/luci,maxrio/luci981213,opentechinstitute/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,Wedmer/luci,aa65535/luci,wongsyrone/luci-1,cshore-firmware/openwrt-luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,jchuang1977/luci-1,ollie27/openwrt_luci,tcatm/luci,ff94315/luci-1,dwmw2/luci,harveyhu2012/luci,teslamint/luci,cappiewu/luci,artynet/luci,jorgifumi/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,Kyklas/luci-proto-hso,bittorf/luci,deepak78/new-luci,joaofvieira/luci,cappiewu/luci,Noltari/luci,nwf/openwrt-luci,bright-things/ionic-luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,openwrt/luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,lcf258/openwrtcn,marcel-sch/luci,palmettos/test,chris5560/openwrt-luci,artynet/luci,dismantl/luci-0.12,cshore-firmware/openwrt-luci,daofeng2015/luci,hnyman/luci,nwf/openwrt-luci,chris5560/openwrt-luci,fkooman/luci,keyidadi/luci,jchuang1977/luci-1,cshore/luci,forward619/luci,keyidadi/luci,Hostle/luci,maxrio/luci981213,openwrt/luci,palmettos/cnLuCI,wongsyrone/luci-1,thesabbir/luci,teslamint/luci,RedSnake64/openwrt-luci-packages,thess/OpenWrt-luci,remakeelectric/luci,marcel-sch/luci,kuoruan/lede-luci,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,wongsyrone/luci-1,sujeet14108/luci,tobiaswaldvogel/luci,daofeng2015/luci,daofeng2015/luci,deepak78/new-luci,urueedi/luci,aircross/OpenWrt-Firefly-LuCI,chris5560/openwrt-luci,Sakura-Winkey/LuCI,RuiChen1113/luci,shangjiyu/luci-with-extra,florian-shellfire/luci,david-xiao/luci,maxrio/luci981213,urueedi/luci,slayerrensky/luci,tcatm/luci,wongsyrone/luci-1,teslamint/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,aa65535/luci,nwf/openwrt-luci,LuttyYang/luci,palmettos/test,remakeelectric/luci,teslamint/luci,nmav/luci,thesabbir/luci,Wedmer/luci,openwrt/luci,oyido/luci,joaofvieira/luci,oyido/luci,sujeet14108/luci,david-xiao/luci,daofeng2015/luci,slayerrensky/luci,nmav/luci,remakeelectric/luci,ff94315/luci-1,kuoruan/luci,thess/OpenWrt-luci,hnyman/luci,jlopenwrtluci/luci,cshore/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,male-puppies/luci,MinFu/luci,hnyman/luci,wongsyrone/luci-1,cshore/luci,cshore-firmware/openwrt-luci,ff94315/luci-1,jlopenwrtluci/luci,thess/OpenWrt-luci,forward619/luci,Hostle/openwrt-luci-multi-user,nwf/openwrt-luci,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,wongsyrone/luci-1,Sakura-Winkey/LuCI,thess/OpenWrt-luci,Kyklas/luci-proto-hso,opentechinstitute/luci,marcel-sch/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,thesabbir/luci,keyidadi/luci,Hostle/luci,MinFu/luci,palmettos/cnLuCI,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,opentechinstitute/luci,dwmw2/luci,harveyhu2012/luci,daofeng2015/luci,tcatm/luci,maxrio/luci981213,shangjiyu/luci-with-extra,MinFu/luci,david-xiao/luci,Wedmer/luci,male-puppies/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,nmav/luci,deepak78/new-luci,fkooman/luci,daofeng2015/luci,cappiewu/luci,florian-shellfire/luci,Sakura-Winkey/LuCI,kuoruan/luci,nmav/luci,taiha/luci,ollie27/openwrt_luci,kuoruan/luci,rogerpueyo/luci,chris5560/openwrt-luci,jlopenwrtluci/luci,jlopenwrtluci/luci,aa65535/luci,cshore/luci,artynet/luci,harveyhu2012/luci,slayerrensky/luci,remakeelectric/luci,MinFu/luci,florian-shellfire/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,Hostle/luci,ff94315/luci-1,jlopenwrtluci/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,daofeng2015/luci,david-xiao/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,dwmw2/luci,ollie27/openwrt_luci,slayerrensky/luci,Kyklas/luci-proto-hso,bittorf/luci,mumuqz/luci,LuttyYang/luci,harveyhu2012/luci,jchuang1977/luci-1,slayerrensky/luci,deepak78/new-luci,fkooman/luci,maxrio/luci981213,cappiewu/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,oyido/luci,LazyZhu/openwrt-luci-trunk-mod,zhaoxx063/luci,keyidadi/luci,Hostle/luci,taiha/luci,male-puppies/luci,zhaoxx063/luci,bittorf/luci,thesabbir/luci,981213/luci-1,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,Sakura-Winkey/LuCI,LuttyYang/luci,981213/luci-1,daofeng2015/luci,aa65535/luci,deepak78/new-luci,artynet/luci,chris5560/openwrt-luci,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,oyido/luci,openwrt/luci,mumuqz/luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,bittorf/luci,aa65535/luci,jorgifumi/luci,tobiaswaldvogel/luci,NeoRaider/luci,ff94315/luci-1,aa65535/luci,oneru/luci,lcf258/openwrtcn,artynet/luci,tcatm/luci,obsy/luci,Kyklas/luci-proto-hso,bittorf/luci,RuiChen1113/luci,hnyman/luci,thess/OpenWrt-luci,Kyklas/luci-proto-hso,openwrt-es/openwrt-luci,oneru/luci,nmav/luci,MinFu/luci,maxrio/luci981213,nmav/luci,fkooman/luci,hnyman/luci,harveyhu2012/luci,hnyman/luci,taiha/luci,Hostle/openwrt-luci-multi-user,981213/luci-1,mumuqz/luci,Noltari/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,marcel-sch/luci,lbthomsen/openwrt-luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,forward619/luci,schidler/ionic-luci,cshore/luci,ff94315/luci-1,NeoRaider/luci,nwf/openwrt-luci,zhaoxx063/luci,cshore-firmware/openwrt-luci,kuoruan/luci,obsy/luci,rogerpueyo/luci,Wedmer/luci,oneru/luci,sujeet14108/luci,urueedi/luci,lcf258/openwrtcn,Noltari/luci,Wedmer/luci,RedSnake64/openwrt-luci-packages,ff94315/luci-1,sujeet14108/luci,david-xiao/luci,schidler/ionic-luci,mumuqz/luci,cshore/luci,openwrt/luci,cappiewu/luci,joaofvieira/luci,981213/luci-1,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,dwmw2/luci,Wedmer/luci,palmettos/cnLuCI,forward619/luci,male-puppies/luci,dwmw2/luci,jorgifumi/luci,opentechinstitute/luci,Noltari/luci,marcel-sch/luci,jchuang1977/luci-1,dwmw2/luci,Sakura-Winkey/LuCI,981213/luci-1,NeoRaider/luci,obsy/luci,thess/OpenWrt-luci,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,thesabbir/luci,joaofvieira/luci,shangjiyu/luci-with-extra,taiha/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,oyido/luci,mumuqz/luci
a87392761994df8c22c5e5aed3b2f2f5e753e47b
assets/services/1-load-font.lua
assets/services/1-load-font.lua
local charcodes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,:;!?()&/-' font = MOAIFont.new() --font:load('assets/static/Casper.ttf') font:load('assets/static/arial-rounded.TTF') font:preloadGlyphs(charcodes, 8) font:preloadGlyphs(charcodes, 12) font:preloadGlyphs(charcodes, 16) font:preloadGlyphs(charcodes, 24) font:preloadGlyphs(charcodes, 32) font:preloadGlyphs(charcodes, 42) font:preloadGlyphs(charcodes, 56) font:preloadGlyphs(charcodes, 64) font:preloadGlyphs(charcodes, 72) font:preloadGlyphs(charcodes, 76) --[[local image = MOAIImage.new() image:load('assets/static/casper.png', 0) font:setCache() font:setReader() font:setImage(image)]]
local charcodes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,:;!?()&/-' font = MOAIFont.new() --font:load('assets/static/Casper.ttf') font:load('assets/static/arial-rounded.TTF') font:preloadGlyphs(charcodes, 8) font:preloadGlyphs(charcodes, 12) font:preloadGlyphs(charcodes, 14) font:preloadGlyphs(charcodes, 16) font:preloadGlyphs(charcodes, 24) font:preloadGlyphs(charcodes, 32) font:preloadGlyphs(charcodes, 42) font:preloadGlyphs(charcodes, 56) font:preloadGlyphs(charcodes, 64) font:preloadGlyphs(charcodes, 72) font:preloadGlyphs(charcodes, 76) --[[local image = MOAIImage.new() image:load('assets/static/casper.png', 0) font:setCache() font:setReader() font:setImage(image)]]
Fixed a performance bug in the cached glyphs
Fixed a performance bug in the cached glyphs The default font didn't have preloaded glyphs in the default size for labels - this meant every label shown would allocate a new set of glyphs ~1MB in size
Lua
mit
isovector/adventure,isovector/adventure
eb5380d4985af02d30d1b5bd1c4e7bc02d050e23
classes/book.lua
classes/book.lua
local plain = SILE.require("classes/plain"); local book = plain { id = "book" }; book:loadPackage("masters") book:defineMaster({ id = "right", firstContentFrame = "content", frames = { content = {left = "8.3%", right = "86%", top = "11.6%", bottom = "top(footnotes)" }, folio = {left = "left(content)", right = "right(content)", top = "bottom(footnotes)+3%",bottom = "bottom(footnotes)+5%" }, runningHead = {left = "left(content)", right = "right(content)", top = "top(content) - 8%", bottom = "top(content)-3%" }, footnotes = { left="left(content)", right = "right(content)", height = "0", bottom="83.3%"} }}) book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }); book:mirrorMaster("right", "left") book:loadPackage("tableofcontents") if not(SILE.scratch.headers) then SILE.scratch.headers = {}; end book.pageTemplate = SILE.scratch.masters["right"] book.init = function(self) book:loadPackage("footnotes", { insertInto = "footnotes", stealFrom = {"content"} } ) return plain.init(self) end book.newPage = function(self) book:switchPage() return plain.newPage(self) end book.finish = function () book:writeToc() return plain:finish() end book.endPage = function(self) book:outputInsertions() book:moveTocNodes() book:newPageInfo() if (book:oddPage() and SILE.scratch.headers.right) then SILE.typesetNaturally(SILE.getFrame("runningHead"), function() SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.process(SILE.scratch.headers.right) end) elseif (not(book:oddPage()) and SILE.scratch.headers.left) then SILE.typesetNaturally(SILE.getFrame("runningHead"), function() SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.process(SILE.scratch.headers.left) end) end return plain.endPage(book); end; SILE.registerCommand("left-running-head", function(options, content) local closure = SILE.settings.wrap() SILE.scratch.headers.left = function () closure(content) end end, "Text to appear on the top of the left page"); SILE.registerCommand("right-running-head", function(options, content) local closure = SILE.settings.wrap() SILE.scratch.headers.right = function () closure(content) end end, "Text to appear on the top of the right page"); SILE.registerCommand("chapter", function (options, content) SILE.call("open-double-page") SILE.call("noindent") SILE.scratch.headers.right = nil SILE.Commands["set-counter"]({id = "section", value = 0}); SILE.Commands["set-counter"]({id = "footnote", value = 1}); SILE.Commands["increment-counter"]({id = "chapter"}) SILE.Commands["book:chapterfont"]({}, {"Chapter "..SILE.formatCounter(SILE.scratch.counters.chapter)}); SILE.typesetter:leaveHmode() SILE.Commands["book:chapterfont"]({}, content); SILE.Commands["left-running-head"]({}, content) SILE.call("tocentry", {level = 1}, content) SILE.call("bigskip") SILE.call("nofoliosthispage") end, "Begin a new chapter"); SILE.registerCommand("section", function (options, content) SILE.typesetter:leaveHmode() SILE.call("goodbreak") SILE.call("noindent") SILE.call("set-counter", {id="subsection", value=0 }) SILE.call("increment-counter", {id="section" }) SILE.call("bigskip") SILE.Commands["book:sectionfont"]({}, function() SILE.call("show-counter", {id ="chapter"}) SILE.typesetter:typeset(".") SILE.call("show-counter", {id="section"}) SILE.typesetter:typeset(" ") SILE.process(content) end) SILE.call("tocentry", {level = 2}, content) if not SILE.scratch.counters.folio.off then SILE.Commands["right-running-head"]({}, function() SILE.call("hss") SILE.settings.temporarily(function() SILE.settings.set("font.style", "italic") SILE.call("show-counter", {id ="chapter"}) SILE.typesetter:typeset(".") SILE.call("show-counter", {id="section"}) SILE.typesetter:typeset(" ") SILE.process(content) end) end); end SILE.call("novbreak") SILE.call("bigskip") SILE.call("novbreak") end, "Begin a new section") SILE.registerCommand("subsection", function (options, content) SILE.typesetter:leaveHmode() SILE.call("goodbreak") SILE.call("noindent") SILE.call("increment-counter", {id="subsection" }) SILE.call("medskip") SILE.Commands["book:subsectionfont"]({}, function() SILE.call("show-counter", {id ="chapter"}) SILE.typesetter:typeset(".") SILE.call("show-counter", {id="section"}) SILE.typesetter:typeset(".") SILE.call("show-counter", {id="subsection"}) SILE.typesetter:typeset(" ") SILE.process(content) end) SILE.typesetter:leaveHmode() SILE.call("novbreak") SILE.call("medskip") SILE.call("novbreak") end, "Begin a new subsection") SILE.registerCommand("book:chapterfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="22pt"}, content) end) end) SILE.registerCommand("book:sectionfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="15pt"}, content) end) end) SILE.registerCommand("book:subsectionfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="12pt"}, content) end) end) SILE.registerCommand("open-double-page", function() SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); if book:oddPage() then SILE.typesetter:typeset("") SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); end end) return book
local plain = SILE.require("classes/plain"); local book = plain { id = "book" }; book:loadPackage("masters") book:defineMaster({ id = "right", firstContentFrame = "content", frames = { content = {left = "8.3%", right = "86%", top = "11.6%", bottom = "top(footnotes)" }, folio = {left = "left(content)", right = "right(content)", top = "bottom(footnotes)+3%",bottom = "bottom(footnotes)+5%" }, runningHead = {left = "left(content)", right = "right(content)", top = "top(content) - 8%", bottom = "top(content)-3%" }, footnotes = { left="left(content)", right = "right(content)", height = "0", bottom="83.3%"} }}) book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }); book:mirrorMaster("right", "left") book:loadPackage("tableofcontents") if not(SILE.scratch.headers) then SILE.scratch.headers = {}; end book.pageTemplate = SILE.scratch.masters["right"] book.init = function(self) book:loadPackage("footnotes", { insertInto = "footnotes", stealFrom = {"content"} } ) return plain.init(self) end book.newPage = function(self) book:switchPage() return plain.newPage(self) end book.finish = function () book:writeToc() return plain:finish() end book.endPage = function(self) book:outputInsertions() book:moveTocNodes() book:newPageInfo() if (book:oddPage() and SILE.scratch.headers.right) then SILE.typesetNaturally(SILE.getFrame("runningHead"), function() SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.process(SILE.scratch.headers.right) SILE.call("par") end) elseif (not(book:oddPage()) and SILE.scratch.headers.left) then SILE.typesetNaturally(SILE.getFrame("runningHead"), function() SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.process(SILE.scratch.headers.left) SILE.call("par") end) end return plain.endPage(book); end; SILE.registerCommand("left-running-head", function(options, content) local closure = SILE.settings.wrap() SILE.scratch.headers.left = function () closure(content) end end, "Text to appear on the top of the left page"); SILE.registerCommand("right-running-head", function(options, content) local closure = SILE.settings.wrap() SILE.scratch.headers.right = function () closure(content) end end, "Text to appear on the top of the right page"); SILE.registerCommand("chapter", function (options, content) SILE.call("open-double-page") SILE.call("noindent") SILE.scratch.headers.right = nil SILE.Commands["set-counter"]({id = "section", value = 0}); SILE.Commands["set-counter"]({id = "footnote", value = 1}); SILE.Commands["increment-counter"]({id = "chapter"}) SILE.Commands["book:chapterfont"]({}, {"Chapter "..SILE.formatCounter(SILE.scratch.counters.chapter)}); SILE.typesetter:leaveHmode() SILE.Commands["book:chapterfont"]({}, content); SILE.Commands["left-running-head"]({}, content) SILE.call("tocentry", {level = 1}, content) SILE.call("bigskip") SILE.call("nofoliosthispage") end, "Begin a new chapter"); SILE.registerCommand("section", function (options, content) SILE.typesetter:leaveHmode() SILE.call("goodbreak") SILE.call("noindent") SILE.call("set-counter", {id="subsection", value=0 }) SILE.call("increment-counter", {id="section" }) SILE.call("bigskip") SILE.Commands["book:sectionfont"]({}, function() SILE.call("show-counter", {id ="chapter"}) SILE.typesetter:typeset(".") SILE.call("show-counter", {id="section"}) SILE.typesetter:typeset(" ") SILE.process(content) end) SILE.call("tocentry", {level = 2}, content) if not SILE.scratch.counters.folio.off then SILE.Commands["right-running-head"]({}, function() SILE.call("hss") SILE.settings.temporarily(function() SILE.settings.set("font.style", "italic") SILE.call("show-counter", {id ="chapter"}) SILE.typesetter:typeset(".") SILE.call("show-counter", {id="section"}) SILE.typesetter:typeset(" ") SILE.process(content) end) end); end SILE.call("novbreak") SILE.call("bigskip") SILE.call("novbreak") end, "Begin a new section") SILE.registerCommand("subsection", function (options, content) SILE.typesetter:leaveHmode() SILE.call("goodbreak") SILE.call("noindent") SILE.call("increment-counter", {id="subsection" }) SILE.call("medskip") SILE.Commands["book:subsectionfont"]({}, function() SILE.call("show-counter", {id ="chapter"}) SILE.typesetter:typeset(".") SILE.call("show-counter", {id="section"}) SILE.typesetter:typeset(".") SILE.call("show-counter", {id="subsection"}) SILE.typesetter:typeset(" ") SILE.process(content) end) SILE.typesetter:leaveHmode() SILE.call("novbreak") SILE.call("medskip") SILE.call("novbreak") end, "Begin a new subsection") SILE.registerCommand("book:chapterfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="22pt"}, content) end) end) SILE.registerCommand("book:sectionfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="15pt"}, content) end) end) SILE.registerCommand("book:subsectionfont", function (options, content) SILE.settings.temporarily(function() SILE.Commands["font"]({weight=800, size="12pt"}, content) end) end) SILE.registerCommand("open-double-page", function() SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); if book:oddPage() then SILE.typesetter:typeset("") SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); end end) return book
Ensure paragraph is ended while parskipglue is zero, fixes #39.
Ensure paragraph is ended while parskipglue is zero, fixes #39.
Lua
mit
alerque/sile,Nathan22Miles/sile,anthrotype/sile,neofob/sile,simoncozens/sile,alerque/sile,anthrotype/sile,simoncozens/sile,neofob/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,Nathan22Miles/sile,anthrotype/sile,Nathan22Miles/sile,alerque/sile,simoncozens/sile,neofob/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,shirat74/sile,neofob/sile,shirat74/sile,shirat74/sile,alerque/sile,WAKAMAZU/sile_fe,simoncozens/sile,Nathan22Miles/sile,shirat74/sile,anthrotype/sile
d3ae2b5e9e84a07bd4465978a8575c93868c6415
projects/shared/scripts/cam_ctrl.lua
projects/shared/scripts/cam_ctrl.lua
local bzutils = require("bzutils") local rx = require("rx") local runtimeController = bzutils.runtime.runtimeController local easing = require("easing") local easeOutBackV = easing.easeOutBackV local local2Global = bzutils.utils.local2Global local global2Local = bzutils.utils.global2Local local interpolatedNormal = easing.interpolatedNormal local net = bzutils.net.net CameraController = bzutils.utils.createClass("CameraController", { new = function(self, terminate) self.terminate = terminate self.base = nil self:setBase(nil, SetVector(0,0,0)) self.destroySubject = rx.Subject.create() end, routineWasCreated = function(self, base, offset, target, easingFunc) self:setBase(base, offset) self:setTarget(target) self.easingFunc = easingFunc or easeOutBackV end, setBase = function(self, base, offset) self.base = base self.offset = offset or self.offset or SetVector(0, 0, 0) if IsValid(self.dummy) then --SetPosition(self.dummy, GetPosition(self.base)) --self.prev = GetPosition(self.dummy) end end, setTarget = function(self, target) self.target = target or self.base end, onDestroyed = function(self) return self.destroySubject end, postInit = function(self) self.dummy = BuildLocal("dummy", 0, GetPosition(self.base)) self.prev = GetPosition(self.dummy) CameraReady() end, update = function(self, dtime) local offset = self.offset local cc = CameraCancelled() offset = global2Local(offset, GetTransform(self.base)) local actualOffset = offset + GetPosition(self.base) local h, normal = GetFloorHeightAndNormal(actualOffset + SetVector(0,10,0)) offset.y = offset.y + math.max(h - actualOffset.y, 0) offset = global2Local(offset, GetTransform(self.base)) if (not IsValid(self.base)) or CameraObject( self.base, offset.z * 100, offset.y * 100, offset.x * 100, self.base) or cc then self.terminate(cc) else local pos = GetPosition(self.dummy) SetTransform(self.dummy, GetTransform(self.base)) SetPosition(self.dummy, self.easingFunc(self.prev, GetPosition(self.base), dtime*4)) self.prev = self.easingFunc(self.prev, GetPosition(self.dummy), dtime*4) end end, routineWasDestroyed = function(self, cc) CameraFinish() RemoveObject(self.dummy) self.destroySubject:onNext(not cc) end }) -- controller for spectating players SpectateController = bzutils.utils.createClass("SpectateController", { new = function(self, terminate) self.terminate = terminate self.playerIdx = 1 self.retry = 0 self.players = {} self.cameraRoutineId = -1 end, routineWasCreated = function(self, players, offset) self.playerIdx = (offset > 0 and offset <= #players and offset) or self.playerIdx self.players = players end, setPlayer = function(self, offset) self.playerIdx = (offset > 0 and offset <= #self.players and offset) or self.playerIdx self:updatePlayer() end, nextPlayer = function(self) self.playerIdx = (self.playerIdx % #self.players) + 1 self.retry = self.retry + 1 if self.retry <= #self.players then self:updatePlayer() else self.terminate() end end, updatePlayer = function(self) --self.playerIdx = (self.playerIdx % #self.players) + 1 local ph = self.players[self.playerIdx] and net:getPlayerHandle(self.players[self.playerIdx].team) --GetPlayerHandle(self.players[self.playerIdx].team) if not IsValid(ph) then self:nextPlayer() return end self.retry = 0 local r = runtimeController:getRoutine(self.cameraRoutineId) if r==nil then self.cameraRoutineId, camctrl = runtimeController:createRoutine(CameraController, ph, SetVector(-20,10,0)) self.sub = camctrl:onDestroyed():subscribe(function(a) if a then self:updatePlayer() else self.terminate() end end) else r:setBase(ph) end end, postInit = function(self) self:updatePlayer() end, update = function(self) end, routineWasDestroyed = function(self) if self.sub then self.sub:unsubscribe() end runtimeController:clearRoutine(self.cameraRoutineId) end }) return { CameraController = CameraController, SpectateController = SpectateController }
local bzutils = require("bzutils") local rx = require("rx") local runtimeController = bzutils.runtime.runtimeController local easing = require("easing") local easeOutBackV = easing.easeOutBackV local local2Global = bzutils.utils.local2Global local global2Local = bzutils.utils.global2Local local interpolatedNormal = easing.interpolatedNormal local net = bzutils.net.net CameraController = bzutils.utils.createClass("CameraController", { new = function(self, terminate) self.terminate = terminate self.base = nil self:setBase(nil, SetVector(0,0,0)) self.destroySubject = rx.Subject.create() end, routineWasCreated = function(self, base, offset, target, easingFunc) self:setBase(base, offset) self:setTarget(target) self.easingFunc = easingFunc or easeOutBackV end, setBase = function(self, base, offset) self.base = base self.offset = offset or self.offset or SetVector(0, 0, 0) if IsValid(self.dummy) then --SetPosition(self.dummy, GetPosition(self.base)) --self.prev = GetPosition(self.dummy) end end, setTarget = function(self, target) self.target = target or self.base end, onDestroyed = function(self) return self.destroySubject end, postInit = function(self) --self.dummy = BuildLocal("dummy", 0, GetPosition(self.base)) --self.prev = GetPosition(self.dummy) CameraReady() end, update = function(self, dtime) local offset = self.offset local cc = CameraCancelled() offset = local2Global(offset, GetTransform(self.base)) local actualOffset = offset + GetPosition(self.base) local h, normal = GetFloorHeightAndNormal(actualOffset + SetVector(0,5,0)) actualOffset.y = math.max(actualOffset.y, h + 5) offset = actualOffset - GetPosition(self.base) offset = global2Local(offset, GetTransform(self.base)) if (not IsValid(self.base)) or CameraObject( self.base, offset.z * 100, offset.y * 100, offset.x * 100, self.base) or cc then self.terminate(cc) else --local pos = GetPosition(self.dummy) --SetTransform(self.dummy, GetTransform(self.base)) --SetPosition(self.dummy, self.easingFunc(self.prev, GetPosition(self.base), dtime*4)) --self.prev = self.easingFunc(self.prev, GetPosition(self.dummy), dtime*4) end end, routineWasDestroyed = function(self, cc) CameraFinish() --RemoveObject(self.dummy) self.destroySubject:onNext(not cc) end }) -- controller for spectating players SpectateController = bzutils.utils.createClass("SpectateController", { new = function(self, terminate) self.terminate = terminate self.playerIdx = 1 self.retry = 0 self.players = {} self.cameraRoutineId = -1 end, routineWasCreated = function(self, players, offset) self.playerIdx = (offset > 0 and offset <= #players and offset) or self.playerIdx self.players = players end, setPlayer = function(self, offset) self.playerIdx = (offset > 0 and offset <= #self.players and offset) or self.playerIdx self:updatePlayer() end, nextPlayer = function(self) self.playerIdx = (self.playerIdx % #self.players) + 1 self.retry = self.retry + 1 if self.retry <= #self.players then self:updatePlayer() else self.terminate() end end, updatePlayer = function(self) --self.playerIdx = (self.playerIdx % #self.players) + 1 local ph = self.players[self.playerIdx] and net:getPlayerHandle(self.players[self.playerIdx].team) --GetPlayerHandle(self.players[self.playerIdx].team) if not IsValid(ph) then self:nextPlayer() return end self.retry = 0 local r = runtimeController:getRoutine(self.cameraRoutineId) if r==nil then self.cameraRoutineId, camctrl = runtimeController:createRoutine(CameraController, ph, SetVector(-20,10,0)) self.sub = camctrl:onDestroyed():subscribe(function(a) if a then self:updatePlayer() else self.terminate() end end) else r:setBase(ph) end end, postInit = function(self) self:updatePlayer() end, update = function(self) end, routineWasDestroyed = function(self) if self.sub then self.sub:unsubscribe() end runtimeController:clearRoutine(self.cameraRoutineId) end }) return { CameraController = CameraController, SpectateController = SpectateController }
Fixed issue with offset not being set correctly
Fixed issue with offset not being set correctly
Lua
apache-2.0
Heracles-Brigade/bz-community
3a50c9bead1b564b471e5f81ddb315b784775230
src_trunk/resources/saveplayer-system/s_saveplayer_system.lua
src_trunk/resources/saveplayer-system/s_saveplayer_system.lua
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do triggerEvent("savePlayer", value, "Save All") end if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// function saveWeapons(thePlayer) local weapons = getElementData(thePlayer, "weapons") local ammo = getElementData(thePlayer, "ammo") if (weapons~=false) and (ammo~=false) then local query = mysql_query(handler, "UPDATE characters SET weapons='" .. weapons .. "', ammo='" .. ammo .. "' WHERE charactername='" .. getPlayerName(source) .. "'") mysql_free_result(query) end end function saveAllPlayers() for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do triggerEvent("savePlayer", value, "Save All") end end function savePlayer(reason, player) local logged = getElementData(source, "loggedin") if (logged==1) then saveWeapons(source) local vehicle = getPedOccupiedVehicle(source) if (vehicle) then local seat = getPedOccupiedVehicleSeat(source) triggerEvent("onVehicleExit", vehicle, source, seat) end local x, y, z, rot, tag, health, armour, interior, dimension, pmblocked, username, cuffed, skin, muted, hiddenAdmin, radiochannel, duty, adminduty, globalooc, fightstyle, blur, casualskin, adminreports, warns, hoursplayed, timeinserver, job username = getPlayerName(source) x, y, z = getElementPosition(source) rot = getPedRotation(source) health = getElementHealth(source) armor = getPedArmor(source) interior = getElementInterior(source) dimension = getElementDimension(source) money = getElementData(source, "money") + ( getElementData(source, "stevie.money") or 0 ) cuffed = getElementData(source, "restrain") skin = getElementModel(source) muted = getElementData(source, "muted") hiddenAdmin = getElementData(source, "hiddenadmin") pmblocked = getElementData(source, "pmblocked") local restrainedby = getElementData(source, "restrainedBy") if not (restrainedby) then restrainedby=-1 end local restrainedobj = getElementData(source, "restrainedObj") if not (restrainedobj) then restrainedobj=-1 end fightstyle = getPedFightingStyle(source) local dutyskin = getElementData(source, "dutyskin") radiochannel = getElementData(source, "radiochannel") duty = getElementData(source, "duty") adminduty = getElementData(source, "adminduty") globalooc = getElementData(source, "globalooc") blur = getElementData(source, "blur") adminreports = getElementData(source, "adminreports") casualskin = getElementData(source, "casualskin") warns = getElementData(source, "warns") timeinserver = getElementData(source, "timeinserver") local bankmoney = getElementData(source, "bankmoney") + ( getElementData(source, "businessprofit") or 0 ) local gameAccountUsername = getElementData(source, "gameaccountusername") local safegameAccountUsername = mysql_escape_string(handler, gameAccountUsername) local items = getElementData(source, "items") local itemvalues = getElementData(source, "itemvalues") job = getElementData(source, "job") tag = getElementData(source, "tag") hoursplayed = getElementData(source, "hoursplayed") if not (items) then items = "" end if not (itemvalues) then itemvalues = "" end if not (duty) then duty = 0 end -- LAST LOGIN local time = getRealTime() local yearday = time.yearday local year = (1900+time.year) -- LAST AREA local zone = getElementZoneName(source) if not (job) then job = 0 end local update = mysql_query(handler, "UPDATE characters SET casualskin='" .. casualskin .. "', x='" .. x .. "', y='" .. y .. "', z='" .. z .. "', rotation='" .. rot .. "', health='" .. health .. "', armor='" .. armor .. "', skin='" .. skin .. "', dimension_id='" .. dimension .. "', interior_id='" .. interior .. "', money='" .. money .. "', cuffed='" .. cuffed .. "', radiochannel='" .. radiochannel .. "', duty='" .. duty .. "', fightstyle='" .. fightstyle .. "', yearday='" .. yearday .. "', year='" .. year .. "', lastarea='" .. zone .. "', items='" .. items .. "', itemvalues='" .. itemvalues .. "', bankmoney='" .. bankmoney .. "', tag='" .. tag .. "', hoursplayed='" .. hoursplayed .. "', timeinserver='" .. timeinserver .. "', restrainedobj='" .. restrainedobj .. "', restrainedby='" .. restrainedby .. "', dutyskin='" .. dutyskin .. "', job='" .. job .. "' WHERE charactername='" .. username .. "'") local update2 = mysql_query(handler, "UPDATE accounts SET muted='" .. muted .. "', hiddenadmin='" .. hiddenAdmin .. "', adminduty='" .. adminduty .. "', globalooc='" .. globalooc .. "', blur='" .. blur .. "', adminreports='" .. adminreports .. "', pmblocked='" .. pmblocked .. "', warns='" .. warns .. "' WHERE username='" .. tostring(safegameAccountUsername) .. "'") if (update) then mysql_free_result(update) end if (update2) then mysql_free_result(update2) end outputDebugString("Saved player '" .. getPlayerName(source) .. "' [" .. reason .. "].") end end addEventHandler("onPlayerQuit", getRootElement(), savePlayer) addEvent("savePlayer", false) addEventHandler("savePlayer", getRootElement(), savePlayer) setTimer(saveAllPlayers, 3600000, 0)
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do triggerEvent("savePlayer", value, "Save All") end if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// function saveWeapons(thePlayer) local weapons = getElementData(thePlayer, "weapons") local ammo = getElementData(thePlayer, "ammo") if (weapons~=false) and (ammo~=false) then local query = mysql_query(handler, "UPDATE characters SET weapons='" .. weapons .. "', ammo='" .. ammo .. "' WHERE charactername='" .. getPlayerName(source) .. "'") mysql_free_result(query) end end function saveAllPlayers() for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do triggerEvent("savePlayer", value, "Save All") end end function savePlayer(reason, player) local logged = getElementData(source, "loggedin") if (logged==1) then saveWeapons(source) local vehicle = getPedOccupiedVehicle(source) if (vehicle) then local seat = getPedOccupiedVehicleSeat(source) triggerEvent("onVehicleExit", vehicle, source, seat) end local x, y, z, rot, tag, health, armour, interior, dimension, pmblocked, username, cuffed, skin, muted, hiddenAdmin, radiochannel, duty, adminduty, globalooc, fightstyle, blur, casualskin, adminreports, warns, hoursplayed, timeinserver, job username = getPlayerName(source) x, y, z = getElementPosition(source) rot = getPedRotation(source) health = getElementHealth(source) armor = getPedArmor(source) interior = getElementInterior(source) dimension = getElementDimension(source) money = getElementData(source, "money") + ( getElementData(source, "stevie.money") or 0 ) cuffed = getElementData(source, "restrain") skin = getElementModel(source) -- Fix for #0000984 local businessprofit = tonumber(getElementData(source, "businessprofit")) if (businessprofit) then money = money + businessprofit end muted = getElementData(source, "muted") hiddenAdmin = getElementData(source, "hiddenadmin") pmblocked = getElementData(source, "pmblocked") local restrainedby = getElementData(source, "restrainedBy") if not (restrainedby) then restrainedby=-1 end local restrainedobj = getElementData(source, "restrainedObj") if not (restrainedobj) then restrainedobj=-1 end fightstyle = getPedFightingStyle(source) local dutyskin = getElementData(source, "dutyskin") radiochannel = getElementData(source, "radiochannel") duty = getElementData(source, "duty") adminduty = getElementData(source, "adminduty") globalooc = getElementData(source, "globalooc") blur = getElementData(source, "blur") adminreports = getElementData(source, "adminreports") casualskin = getElementData(source, "casualskin") warns = getElementData(source, "warns") timeinserver = getElementData(source, "timeinserver") local bankmoney = getElementData(source, "bankmoney") + ( getElementData(source, "businessprofit") or 0 ) local gameAccountUsername = getElementData(source, "gameaccountusername") local safegameAccountUsername = mysql_escape_string(handler, gameAccountUsername) local items = getElementData(source, "items") local itemvalues = getElementData(source, "itemvalues") job = getElementData(source, "job") tag = getElementData(source, "tag") hoursplayed = getElementData(source, "hoursplayed") if not (items) then items = "" end if not (itemvalues) then itemvalues = "" end if not (duty) then duty = 0 end -- LAST LOGIN local time = getRealTime() local yearday = time.yearday local year = (1900+time.year) -- LAST AREA local zone = getElementZoneName(source) if not (job) then job = 0 end local update = mysql_query(handler, "UPDATE characters SET casualskin='" .. casualskin .. "', x='" .. x .. "', y='" .. y .. "', z='" .. z .. "', rotation='" .. rot .. "', health='" .. health .. "', armor='" .. armor .. "', skin='" .. skin .. "', dimension_id='" .. dimension .. "', interior_id='" .. interior .. "', money='" .. money .. "', cuffed='" .. cuffed .. "', radiochannel='" .. radiochannel .. "', duty='" .. duty .. "', fightstyle='" .. fightstyle .. "', yearday='" .. yearday .. "', year='" .. year .. "', lastarea='" .. zone .. "', items='" .. items .. "', itemvalues='" .. itemvalues .. "', bankmoney='" .. bankmoney .. "', tag='" .. tag .. "', hoursplayed='" .. hoursplayed .. "', timeinserver='" .. timeinserver .. "', restrainedobj='" .. restrainedobj .. "', restrainedby='" .. restrainedby .. "', dutyskin='" .. dutyskin .. "', job='" .. job .. "' WHERE charactername='" .. username .. "'") local update2 = mysql_query(handler, "UPDATE accounts SET muted='" .. muted .. "', hiddenadmin='" .. hiddenAdmin .. "', adminduty='" .. adminduty .. "', globalooc='" .. globalooc .. "', blur='" .. blur .. "', adminreports='" .. adminreports .. "', pmblocked='" .. pmblocked .. "', warns='" .. warns .. "' WHERE username='" .. tostring(safegameAccountUsername) .. "'") if (update) then mysql_free_result(update) end if (update2) then mysql_free_result(update2) end outputDebugString("Saved player '" .. getPlayerName(source) .. "' [" .. reason .. "].") end end addEventHandler("onPlayerQuit", getRootElement(), savePlayer) addEvent("savePlayer", false) addEventHandler("savePlayer", getRootElement(), savePlayer) setTimer(saveAllPlayers, 3600000, 0)
Fixed 0000984: Business Profit
Fixed 0000984: Business Profit git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1260 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
ad467af5f6e4d10b14c13ee8a76ddb0bd84e7103
fusion/stdlib/iterable.lua
fusion/stdlib/iterable.lua
local fnl = require("fusion.stdlib.functional") local table = require("fusion.stdlib.table") local unpack = unpack or table.unpack -- luacheck: ignore 113 local function iter(input, iterator) if not iterator then return iter(input, pairs) end if type(input) == "function" then return input else return iterator(input) end end local function mk_gen(fn) return function(...) local a = {...} return coroutine.wrap(function() return fn(unpack(a)) end) end end -- Infinite generators local function count(start, step) if not step then return count(start, 1) end if not start then return count(1, step) end while true do coroutine.yield(start) start = start + step end end local function cycle(pattern) while true do for k, v in pairs(pattern) do coroutine.yield(k, v) end end end local function icycle(pattern) while true do for k, v in pairs(pattern) do coroutine.yield(k, v) end end end local function rep(element, n) if n then for i=1, n do -- luacheck: ignore 213 coroutine.yield(element) end else while true do coroutine.yield(element) end end end -- Terminating generators local function range(start, stop, step) if not step then return range(start, stop, 1) elseif not stop then return range(1, start, 1) else for i=start, stop, step do coroutine.yield(i) end end end local function add(x, y) return x + y end local xrange = mk_gen(range) local function accumulate(input, fn) if not fn then return accumulate(input, add) end for i in xrange(#input) do local t0 = {} for j in xrange(1, i) do t0[j] = input[j] end coroutine.yield(fnl.reduce(fn, t0)) end end local function chain(...) for k, v in pairs({...}) do -- luacheck: ignore 213 if type(v) == "function" then for val in v do coroutine.yield(val) end else for _k, _v in pairs(v) do -- luacheck: ignore 213 coroutine.yield(_v) end end end end local function ichain(...) for i, v in ipairs({...}) do -- luacheck: ignore 213 if type(v) == "function" then for val in v do coroutine.yield(val) end else for _k, _v in ipairs(v) do -- luacheck: ignore 213 coroutine.yield(_v) end end end end local function compress(input, selectors) for i=1, math.max(#input, #selectors) do if not input[i] then return else if selectors[i] then coroutine.yield(input[i]) end end end end local function groupby(input) local _prev, _gen for k, v in iter(input) do -- luacheck: ignore 213 _gen = {} if _prev == nil then _prev = v end if _prev == v then table.insert(_gen, v) else coroutine.yield(_prev, pairs(_gen)) _prev = v _gen = {v} end end coroutine.yield(_prev, pairs(_gen)) end local function igroupby(input) local _prev, _gen for k, v in iter(input, ipairs) do -- luacheck: ignore 213 _gen = {} if _prev == nil then _prev = v end if _prev == v then table.insert(_gen, v) else coroutine.yield(_prev, pairs(_gen)) _prev = v _gen = {v} end end coroutine.yield(_prev, pairs(_gen)) end local function slice(input, start, stop, step) if not step then return slice(input, start, stop, 1) elseif not stop then return slice(input, start, #input, 1) end for i in xrange(start, stop, step) do coroutine.yield(input[i]) end end local function zip(input0, input1, default) for i=1, math.max(#input0, #input1) do coroutine.yield(input0[i], input1[i] or default) end end -- Extended module local xslice = mk_gen(slice) local function take(n, input) return table.from_generator(xslice(input, 1, n)) end local xcount = mk_gen(count) local function tabulate(fn, start) for n in xcount(start or 0) do fn(n) end end local function tail(n, input) return table.from_generator(xslice(input, n)) end local function consume(iterator, n) for i in xrange(n) do -- luacheck: ignore 213 iterator() end return iterator end local function nth(n, input, default) return input[n] or default end local xgroupby = mk_gen(groupby) local function allequal(input) local _iter = xgroupby(input) _iter() -- capture first input if not _iter() then return true else return false end end local function truthy(val) return not not val end local function quantify(input, fn) if not fn then return quantify(input, truthy) end local _val = 0 for _, n in iter(fnl.map(fn, table.copy(input))) do if n then _val = _val + 1 end end return _val end local xrep = mk_gen(rep) local xchain = mk_gen(chain) local function padnil(input) return xchain(input, xrep(nil)) end local function dotproduct(t0, t1) return fnl.sum(fnl.map((function(a, b) return a * b end), table.copy(t0), t1)) end return table.join(fnl.map(mk_gen, { count = count; cycle = cycle; icycle = icycle; rep = rep; range = range; accumulate = accumulate; chain = chain; ichain = ichain; compress = compress; groupby = groupby; igroupby = igroupby; slice = slice; zip = zip; }), { take = take; tabulate = tabulate; tail = tail; consume = consume; nth = nth; allequal = allequal; quantify = quantify; padnil = padnil; dotproduct = dotproduct; })
local fnl = require("fusion.stdlib.functional") local table = require("fusion.stdlib.table") local unpack = unpack or table.unpack -- luacheck: ignore 113 local function iter(input, iterator) if not iterator then return iter(input, pairs) end if type(input) == "function" then return input else return iterator(input) end end local function mk_gen(fn) return function(...) local a = {...} return coroutine.wrap(function() return fn(unpack(a)) end) end end -- Infinite generators local function count(start, step) if not step then return count(start, 1) end if not start then return count(1, step) end while true do coroutine.yield(start) start = start + step end end local function cycle(pattern) while true do for k, v in pairs(pattern) do coroutine.yield(k, v) end end end local function icycle(pattern) while true do for k, v in pairs(pattern) do coroutine.yield(k, v) end end end local function rep(element, n) if n then for i=1, n do -- luacheck: ignore 213 coroutine.yield(element) end else while true do coroutine.yield(element) end end end -- Terminating generators local function range(start, stop, step) if not step then return range(start, stop, 1) elseif not stop then return range(1, start, 1) else for i=start, stop, step do coroutine.yield(i) end end end local function add(x, y) return x + y end local xrange = mk_gen(range) local function accumulate(input, fn) if not fn then return accumulate(input, add) end for i in xrange(#input) do local t0 = {} for j in xrange(1, i) do t0[j] = input[j] end coroutine.yield(fnl.reduce(fn, t0)) end end local function chain(...) for k, v in pairs({...}) do -- luacheck: ignore 213 if type(v) == "function" then while true do local x = {v()} if x[1] then coroutine.yield(unpack(x)) else break end end else for _k, _v in pairs(v) do -- luacheck: ignore 213 coroutine.yield(_k, _v) end end end end local function ichain(...) for k, v in ipairs({...}) do -- luacheck: ignore 213 if type(v) == "function" then while true do local x = {v()} if x[1] then coroutine.yield(unpack(x)) else break end end else for _k, _v in ipairs(v) do -- luacheck: ignore 213 coroutine.yield(_k, _v) end end end end local function compress(input, selectors) for i=1, math.max(#input, #selectors) do if not input[i] then return else if selectors[i] then coroutine.yield(input[i]) end end end end local function groupby(input) local _prev, _gen for k, v in iter(input) do -- luacheck: ignore 213 _gen = {} if _prev == nil then _prev = v end if _prev == v then table.insert(_gen, v) else coroutine.yield(_prev, pairs(_gen)) _prev = v _gen = {v} end end coroutine.yield(_prev, pairs(_gen)) end local function igroupby(input) local _prev, _gen for k, v in iter(input, ipairs) do -- luacheck: ignore 213 _gen = {} if _prev == nil then _prev = v end if _prev == v then table.insert(_gen, v) else coroutine.yield(_prev, pairs(_gen)) _prev = v _gen = {v} end end coroutine.yield(_prev, pairs(_gen)) end local function slice(input, start, stop, step) if not step then return slice(input, start, stop, 1) elseif not stop then return slice(input, start, #input, 1) end for i in xrange(start, stop, step) do coroutine.yield(input[i]) end end local function zip(input0, input1, default) for i=1, math.max(#input0, #input1) do coroutine.yield(input0[i], input1[i] or default) end end -- Extended module local xslice = mk_gen(slice) local function take(n, input) return table.from_generator(xslice(input, 1, n)) end local xcount = mk_gen(count) local function tabulate(fn, start) for n in xcount(start or 0) do fn(n) end end local function tail(n, input) return table.from_generator(xslice(input, n)) end local function consume(iterator, n) for i in xrange(n) do -- luacheck: ignore 213 iterator() end return iterator end local function nth(n, input, default) return input[n] or default end local xgroupby = mk_gen(groupby) local function allequal(input) local _iter = xgroupby(input) _iter() -- capture first input if not _iter() then return true else return false end end local function truthy(val) return not not val end local function quantify(input, fn) if not fn then return quantify(input, truthy) end local _val = 0 for _, n in iter(fnl.map(fn, table.copy(input))) do if n then _val = _val + 1 end end return _val end local xrep = mk_gen(rep) local xchain = mk_gen(chain) local function padnil(input) return xchain(input, xrep(nil)) end local function dotproduct(t0, t1) return fnl.sum(fnl.map((function(a, b) return a * b end), table.copy(t0), t1)) end return table.from_generator(xchain(fnl.map(mk_gen, { count = count; cycle = cycle; icycle = icycle; rep = rep; range = range; accumulate = accumulate; chain = chain; ichain = ichain; compress = compress; groupby = groupby; igroupby = igroupby; slice = slice; zip = zip; }), { take = take; tabulate = tabulate; tail = tail; consume = consume; nth = nth; allequal = allequal; quantify = quantify; padnil = padnil; dotproduct = dotproduct; }))
iterable: fix; use fnl better
iterable: fix; use fnl better
Lua
mit
RyanSquared/FusionScript
df2be8d374699b86c213abb13b6759f931dca7f0
lua_modules/luvit-rackspace-monitoring-client/lib/client.lua
lua_modules/luvit-rackspace-monitoring-client/lib/client.lua
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local JSON = require('json') local Object = require('core').Object local string = require('string') local fmt = require('string').format local https = require('https') local url = require('url') local table = require('table') local Error = require('core').Error local async = require('async') local misc = require('./misc') local errors = require('./errors') local KeystoneClient = require('keystone').Client local MAAS_CLIENT_KEYSTONE_URL = 'https://identity.api.rackspacecloud.com/v2.0' local MAAS_CLIENT_DEFAULT_HOST = 'monitoring.api.rackspacecloud.com' local MAAS_CLIENT_DEFAULT_VERSION = 'v1.0' --[[ ClientBase ]]-- local ClientBase = Object:extend() function ClientBase:initialize(host, port, version, apiType, options) local headers = {} self.host = host self.port = port self.version = version self.apiType = apiType self.tenantId = nil if self.apiType == 'public' then headers['User-Agent'] = 'agent/virgo' end self.headers = headers self.options = misc.merge({}, options) self.headers['Accept'] = 'application/json' self.headers['Content-Type'] = 'application/json' end function ClientBase:setToken(token, expiry) self.token = token self.headers['X-Auth-Token'] = token self._tokenExpiry = expiry end function ClientBase:setTenantId(tenantId) self.tenantId = tenantId end function ClientBase:_parseResponse(data, callback) local parsed = JSON.parse(data) callback(nil, parsed) end function ClientBase:_parseData(data) local res = { xpcall(function() return JSON.parse(data) end, function(e) return e end) } if res[1] == false then return res[2] else return JSON.parse(res[2]) end end function ClientBase:request(method, path, payload, expectedStatusCode, callback) local options local headers local extraHeaders = {} -- setup payload if payload then if type(payload) == 'table' and self.headers['Content-Type'] == 'application/json' then payload = JSON.stringify(payload) end extraHeaders['Content-Length'] = #payload else extraHeaders['Content-Length'] = 0 end -- setup path if self.tenantId then path = fmt('/%s/%s%s', self.version, self.tenantId, path) else path = fmt('/%s%s', self.version, path) end headers = misc.merge(self.headers, extraHeaders) options = { host = self.host, port = self.port, path = path, headers = headers, method = method } local req = https.request(options, function(res) local data = '' res:on('data', function(chunk) data = data .. chunk end) res:on('end', function() self._lastRes = res if res.statusCode ~= expectedStatusCode then data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) else if res.statusCode == 200 then self:_parseResponse(data, callback) elseif res.statusCode == 201 or res.statusCode == 204 then callback(nil, res.headers['location']) else data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) end end end) end) if payload then req:write(payload) end req:done() end --[[ Client ]]-- local Client = ClientBase:extend() function Client:initialize(userId, key, options) options = options or {} self.userId = userId self.key = key self.authUrl = options.authUrl self.entities = {} self.agent_tokens = {} self:_init() ClientBase.initialize(self, MAAS_CLIENT_DEFAULT_HOST, 443, MAAS_CLIENT_DEFAULT_VERSION, 'public', options) end function Client:_init() self.entities.get = function(callback) self:request('GET', '/entities', nil, 200, callback) end self.agent_tokens.get = function(callback) self:request('GET', '/agent_tokens', nil, 200, callback) end self.agent_tokens.create = function(options, callback) local body = {} body['label'] = options.label self:request('POST', '/agent_tokens', body, 201, function(err, tokenUrl) if err then callback(err) return end callback(nil, string.match(tokenUrl, 'agent_tokens/(.*)')) end) end end function Client:auth(authUrl, username, keyOrPassword, callback) local apiKeyClient = KeystoneClient:new(authUrl, { username = self.userId, apikey = keyOrPassword }) local passwordClient = KeystoneClient:new(authUrl, { username = self.userId, password = keyOrPassword }) local errors = {} local responses = {} function iterator(client, callback) client:tenantIdAndToken(function(err, obj) if err then table.insert(errors, err) callback() else table.insert(responses, obj) callback() end end) end async.forEach({ apiKeyClient, passwordClient }, iterator, function() if #responses > 0 then callback(nil, responses[1]) else callback(errors) end end) end --[[ The request. callback.function(err, results) ]]-- function Client:request(method, path, payload, expectedStatusCode, callback) local authUrl = self.authUrl or MAAS_CLIENT_KEYSTONE_URL local authPayload local results async.waterfall({ function(callback) if self:tokenValid() then callback() return end self:auth(authUrl, self.userId, self.key, function(err, obj) if err then callback(err) return end self:setToken(obj.token, obj.expires) self:setTenantId(obj.tenantId) callback() end) end, function(callback) ClientBase.request(self, method, path, payload, expectedStatusCode, function(err, obj) if not err then results = obj end callback(err) end) end }, function(err) callback(err, results) end) end function Client:tokenValid() if self.token then return true end -- TODO add support for expiry return nil end local exports = {} exports.Client = Client return exports
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local JSON = require('json') local Object = require('core').Object local string = require('string') local fmt = require('string').format local https = require('https') local url = require('url') local table = require('table') local Error = require('core').Error local async = require('async') local misc = require('./misc') local errors = require('./errors') local KeystoneClient = require('keystone').Client local MAAS_CLIENT_KEYSTONE_URL = 'https://identity.api.rackspacecloud.com/v2.0' local MAAS_CLIENT_DEFAULT_HOST = 'monitoring.api.rackspacecloud.com' local MAAS_CLIENT_DEFAULT_VERSION = 'v1.0' --[[ ClientBase ]]-- local ClientBase = Object:extend() function ClientBase:initialize(host, port, version, apiType, options) local headers = {} self.host = host self.port = port self.version = version self.apiType = apiType self.tenantId = nil if self.apiType == 'public' then headers['User-Agent'] = 'agent/virgo' end self.headers = headers self.options = misc.merge({}, options) self.headers['Accept'] = 'application/json' self.headers['Content-Type'] = 'application/json' end function ClientBase:setToken(token, expiry) self.token = token self.headers['X-Auth-Token'] = token self._tokenExpiry = expiry end function ClientBase:setTenantId(tenantId) self.tenantId = tenantId end function ClientBase:_parseResponse(data, callback) local parsed = JSON.parse(data) callback(nil, parsed) end function ClientBase:_parseData(data) local res = { xpcall(function() return JSON.parse(data) end, function(e) return e end) } if res[1] == false then return res[2] else return JSON.parse(res[2]) end end function ClientBase:request(method, path, payload, expectedStatusCode, callback) local options local headers local extraHeaders = {} -- setup payload if payload then if type(payload) == 'table' and self.headers['Content-Type'] == 'application/json' then payload = JSON.stringify(payload) end extraHeaders['Content-Length'] = #payload else extraHeaders['Content-Length'] = 0 end -- setup path if self.tenantId then path = fmt('/%s/%s%s', self.version, self.tenantId, path) else path = fmt('/%s%s', self.version, path) end headers = misc.merge(self.headers, extraHeaders) options = { host = self.host, port = self.port, path = path, headers = headers, method = method } local req = https.request(options, function(res) local data = '' res:on('data', function(chunk) data = data .. chunk end) res:on('end', function() self._lastRes = res if res.statusCode ~= expectedStatusCode then callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) else if res.statusCode == 200 then self:_parseResponse(data, callback) elseif res.statusCode == 201 or res.statusCode == 204 then callback(nil, res.headers['location']) else data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) end end end) end) if payload then req:write(payload) end req:done() end --[[ Client ]]-- local Client = ClientBase:extend() function Client:initialize(userId, key, options) options = options or {} self.userId = userId self.key = key self.authUrl = options.authUrl self.entities = {} self.agent_tokens = {} self:_init() ClientBase.initialize(self, MAAS_CLIENT_DEFAULT_HOST, 443, MAAS_CLIENT_DEFAULT_VERSION, 'public', options) end function Client:_init() self.entities.get = function(callback) self:request('GET', '/entities', nil, 200, callback) end self.agent_tokens.get = function(callback) self:request('GET', '/agent_tokens', nil, 200, callback) end self.agent_tokens.create = function(options, callback) local body = {} body['label'] = options.label self:request('POST', '/agent_tokens', body, 201, function(err, tokenUrl) if err then callback(err) return end callback(nil, string.match(tokenUrl, 'agent_tokens/(.*)')) end) end end function Client:auth(authUrl, username, keyOrPassword, callback) local apiKeyClient = KeystoneClient:new(authUrl, { username = self.userId, apikey = keyOrPassword }) local passwordClient = KeystoneClient:new(authUrl, { username = self.userId, password = keyOrPassword }) local errors = {} local responses = {} function iterator(client, callback) client:tenantIdAndToken(function(err, obj) if err then table.insert(errors, err) callback() else table.insert(responses, obj) callback() end end) end async.forEach({ apiKeyClient, passwordClient }, iterator, function() if #responses > 0 then callback(nil, responses[1]) else callback(errors) end end) end --[[ The request. callback.function(err, results) ]]-- function Client:request(method, path, payload, expectedStatusCode, callback) local authUrl = self.authUrl or MAAS_CLIENT_KEYSTONE_URL local authPayload local results async.waterfall({ function(callback) if self:tokenValid() then callback() return end self:auth(authUrl, self.userId, self.key, function(err, obj) if err then callback(err) return end self:setToken(obj.token, obj.expires) self:setTenantId(obj.tenantId) callback() end) end, function(callback) ClientBase.request(self, method, path, payload, expectedStatusCode, function(err, obj) if not err then results = obj end callback(err) end) end }, function(err) callback(err, results) end) end function Client:tokenValid() if self.token then return true end -- TODO add support for expiry return nil end local exports = {} exports.Client = Client return exports
rackspace-monitoring-client: bump client for parse fix
rackspace-monitoring-client: bump client for parse fix
Lua
apache-2.0
kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent
9b717c36054a3463c50a2ffc38cc4a5f3e2dde13
lgi/override/Gdk.lua
lgi/override/Gdk.lua
------------------------------------------------------------------------------ -- -- LGI Gdk3 override module. -- -- Copyright (c) 2011, 2014 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local select, type, pairs, unpack, rawget = select, type, pairs, unpack, rawget local lgi = require 'lgi' local core = require 'lgi.core' local ffi = require 'lgi.ffi' local ti = ffi.types local Gdk = lgi.Gdk local cairo = lgi.cairo -- Take over internal GDK synchronization lock. core.registerlock(core.gi.Gdk.resolve.gdk_threads_set_lock_functions) Gdk.threads_init() -- Gdk.Rectangle does not exist at all, because it is aliased to -- cairo.RectangleInt. Make sure that we have it exists, because it -- is very commonly used in API documentation. Gdk.Rectangle = lgi.cairo.RectangleInt Gdk.Rectangle._method = rawget(Gdk.Rectangle, '_method') or {} Gdk.Rectangle._method.intersect = Gdk.rectangle_intersect Gdk.Rectangle._method.union = Gdk.rectangle_union -- Declare GdkAtoms which are #define'd in Gdk sources and not -- introspected in gir. local _ = Gdk.KEY_0 for name, val in pairs { SELECTION_PRIMARY = 1, SELECTION_SECONDARY = 2, SELECTION_CLIPBOARD = 69, TARGET_BITMAP = 5, TARGET_COLORMAP = 7, TARGET_DRAWABLE = 17, TARGET_PIXMAP = 20, TARGET_STRING = 31, SELECTION_TYPE_ATOM = 4, SELECTION_TYPE_BITMAP = 5, SELECTION_TYPE_COLORMAP = 7, SELECTION_TYPE_DRAWABLE = 17, SELECTION_TYPE_INTEGER = 19, SELECTION_TYPE_PIXMAP = 20, SELECTION_TYPE_WINDOW = 33, SELECTION_TYPE_STRING = 31, } do Gdk._constant[name] = Gdk.Atom(val) end -- Easier-to-use Gdk.RGBA.parse() override. if Gdk.RGBA then local parse = Gdk.RGBA.parse function Gdk.RGBA.parse(arg1, arg2) if Gdk.RGBA:is_type_of(arg1) then -- Standard member method. return parse(arg1, arg2) else -- Static constructor variant. local rgba = Gdk.RGBA() return parse(rgba, arg1) and rgba or nil end end end -- Gdk.Window.destroy() actually consumes 'self'. Prepare workaround -- with override doing ref on input arg first. local destroy = Gdk.Window.destroy local ref = core.callable.new { addr = core.gi.GObject.resolve.g_object_ref, ret = ti.ptr, ti.ptr } function Gdk.Window:destroy() ref(self._native) destroy(self) end -- Better integrate Gdk cairo helpers. Gdk.Window.cairo_create = Gdk.cairo_create cairo.Region.create_from_surface = Gdk.cairo_region_create_from_surface local cairo_set_source_rgba = cairo.Context.set_source_rgba function cairo.Context:set_source_rgba(...) if select('#', ...) == 1 then return Gdk.cairo_set_source_rgba(self, ...) else return cairo_set_source_rgba(self, ...) end end local cairo_rectangle = cairo.Context.rectangle function cairo.Context:rectangle(...) if select('#', ...) == 1 then return Gdk.cairo_rectangle(self, ...) else return cairo_rectangle(self, ...) end end for _, name in pairs { 'get_clip_rectangle', 'set_source_color', 'set_source_pixbuf', 'set_source_window', 'region' } do cairo.Context._method[name] = Gdk['cairo_' .. name] end for _, name in pairs { 'clip_rectangle', 'source_color', 'source_pixbuf', 'source_window' } do cairo.Context._attribute[name] = { get = cairo.Context._method['get_' .. name], set = cairo.Context._method['set_' .. name], } end -- Gdk events have strange hierarchy; GdkEvent is union of all known -- GdkEventXxx specific types. This means that generic gdk_event_xxx -- methods are not available on GdkEventXxxx specific types. Work -- around this by setting GdkEvent as parent for GdkEventXxxx specific -- types. for _, event_type in pairs { 'Any', 'Expose', 'Visibility', 'Motion', 'Button', 'Touch', 'Scroll', 'Key', 'Crossing', 'Focus', 'Configure', 'Property', 'Selection', 'OwnerChange', 'Proximity', 'DND', 'WindowState', 'Setting', 'GrabBroken' } do local event = Gdk['Event' .. event_type] if event then event._parent = Gdk.Event end end
------------------------------------------------------------------------------ -- -- LGI Gdk3 override module. -- -- Copyright (c) 2011, 2014 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local select, type, pairs, unpack, rawget = select, type, pairs, unpack, rawget local lgi = require 'lgi' local core = require 'lgi.core' local ffi = require 'lgi.ffi' local ti = ffi.types local Gdk = lgi.Gdk local cairo = lgi.cairo -- Take over internal GDK synchronization lock. core.registerlock(core.gi.Gdk.resolve.gdk_threads_set_lock_functions) Gdk.threads_init() -- Gdk.Rectangle does not exist at all in older GOI, because it is -- aliased to cairo.RectangleInt. Make sure that we have it exists, -- because it is very commonly used in API documentation. if not Gdk.Rectangle then Gdk.Rectangle = lgi.cairo.RectangleInt Gdk.Rectangle._method = rawget(Gdk.Rectangle, '_method') or {} Gdk.Rectangle._method.intersect = Gdk.rectangle_intersect Gdk.Rectangle._method.union = Gdk.rectangle_union end -- Declare GdkAtoms which are #define'd in Gdk sources and not -- introspected in gir. local _ = Gdk.KEY_0 for name, val in pairs { SELECTION_PRIMARY = 1, SELECTION_SECONDARY = 2, SELECTION_CLIPBOARD = 69, TARGET_BITMAP = 5, TARGET_COLORMAP = 7, TARGET_DRAWABLE = 17, TARGET_PIXMAP = 20, TARGET_STRING = 31, SELECTION_TYPE_ATOM = 4, SELECTION_TYPE_BITMAP = 5, SELECTION_TYPE_COLORMAP = 7, SELECTION_TYPE_DRAWABLE = 17, SELECTION_TYPE_INTEGER = 19, SELECTION_TYPE_PIXMAP = 20, SELECTION_TYPE_WINDOW = 33, SELECTION_TYPE_STRING = 31, } do Gdk._constant[name] = Gdk.Atom(val) end -- Easier-to-use Gdk.RGBA.parse() override. if Gdk.RGBA then local parse = Gdk.RGBA.parse function Gdk.RGBA.parse(arg1, arg2) if Gdk.RGBA:is_type_of(arg1) then -- Standard member method. return parse(arg1, arg2) else -- Static constructor variant. local rgba = Gdk.RGBA() return parse(rgba, arg1) and rgba or nil end end end -- Gdk.Window.destroy() actually consumes 'self'. Prepare workaround -- with override doing ref on input arg first. local destroy = Gdk.Window.destroy local ref = core.callable.new { addr = core.gi.GObject.resolve.g_object_ref, ret = ti.ptr, ti.ptr } function Gdk.Window:destroy() ref(self._native) destroy(self) end -- Better integrate Gdk cairo helpers. Gdk.Window.cairo_create = Gdk.cairo_create cairo.Region.create_from_surface = Gdk.cairo_region_create_from_surface local cairo_set_source_rgba = cairo.Context.set_source_rgba function cairo.Context:set_source_rgba(...) if select('#', ...) == 1 then return Gdk.cairo_set_source_rgba(self, ...) else return cairo_set_source_rgba(self, ...) end end local cairo_rectangle = cairo.Context.rectangle function cairo.Context:rectangle(...) if select('#', ...) == 1 then return Gdk.cairo_rectangle(self, ...) else return cairo_rectangle(self, ...) end end for _, name in pairs { 'get_clip_rectangle', 'set_source_color', 'set_source_pixbuf', 'set_source_window', 'region' } do cairo.Context._method[name] = Gdk['cairo_' .. name] end for _, name in pairs { 'clip_rectangle', 'source_color', 'source_pixbuf', 'source_window' } do cairo.Context._attribute[name] = { get = cairo.Context._method['get_' .. name], set = cairo.Context._method['set_' .. name], } end -- Gdk events have strange hierarchy; GdkEvent is union of all known -- GdkEventXxx specific types. This means that generic gdk_event_xxx -- methods are not available on GdkEventXxxx specific types. Work -- around this by setting GdkEvent as parent for GdkEventXxxx specific -- types. for _, event_type in pairs { 'Any', 'Expose', 'Visibility', 'Motion', 'Button', 'Touch', 'Scroll', 'Key', 'Crossing', 'Focus', 'Configure', 'Property', 'Selection', 'OwnerChange', 'Proximity', 'DND', 'WindowState', 'Setting', 'GrabBroken' } do local event = Gdk['Event' .. event_type] if event then event._parent = Gdk.Event end end
Fix Gdk.Rectangle override
Fix Gdk.Rectangle override Because newer GOI/GDK includes actual definition of Gdk.Rectangle, stop defining our own aliased version of it, which actually broke things (namely pixbuf demo in gtk-demo).
Lua
mit
pavouk/lgi,psychon/lgi
b58c8610d3e725dbf3d538f2e3ce8958207c410d
classes/jbook.lua
classes/jbook.lua
local book = SILE.require("book", "classes") local jbook = book { id = "jbook", base = book } SILE.call("bidi-off") jbook:declareOption("layout", "yoko") jbook:loadPackage("masters") jbook:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }) jbook:mirrorMaster("right", "left") jbook:loadPackage("hanmenkyoshi") function jbook:init() jbook:defineMaster({ id = "right", firstContentFrame = "content", frames = { runningHead = {left = "left(content) + 9pt", right = "right(content) - 9pt", height = "20pt", bottom = "top(content)-9pt" }, content = self:declareHanmenFrame( "content", { left = "8.3%pw", top = "12%ph", gridsize = 10, linegap = 7, linelength = 40, linecount = 35, tate = self.options.layout() == "tate" }), folio = {left = "left(content)", right = "right(content)", top = "bottom(footnotes)+3%ph",bottom = "bottom(footnotes)+5%ph" }, footnotes = { left="left(content)", right = "right(content)", height = "0", bottom="83.3%ph"} } }) book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }) book:mirrorMaster("right", "left") self.pageTemplate.firstContentFrame = self.pageTemplate.frames.content return self.base.init(self) end function jbook:registerCommands() self.base:registerCommands() SILE.call("language", { main = "ja" }) end SILE.settings.set("document.parindent",SILE.nodefactory.newGlue("10pt")) return jbook
local book = SILE.require("book", "classes") local jbook = book { id = "jbook", base = book } SILE.call("bidi-off") jbook:declareOption("layout", "yoko") jbook:loadPackage("masters") function jbook:init() jbook:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }) jbook:mirrorMaster("right", "left") jbook:loadPackage("hanmenkyoshi") jbook:defineMaster({ id = "right", firstContentFrame = "content", frames = { runningHead = {left = "left(content) + 9pt", right = "right(content) - 9pt", height = "20pt", bottom = "top(content)-9pt" }, content = self:declareHanmenFrame( "content", { left = "8.3%pw", top = "12%ph", gridsize = 10, linegap = 7, linelength = 40, linecount = 35, tate = self.options.layout() == "tate" }), folio = {left = "left(content)", right = "right(content)", top = "bottom(footnotes)+3%ph",bottom = "bottom(footnotes)+5%ph" }, footnotes = { left="left(content)", right = "right(content)", height = "0", bottom="83.3%ph"} } }) book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }) book:mirrorMaster("right", "left") self.pageTemplate.firstContentFrame = self.pageTemplate.frames.content return book.init(self) end function jbook:registerCommands() book:registerCommands() SILE.call("language", { main = "ja" }) end SILE.settings.set("document.parindent",SILE.nodefactory.newGlue("10pt")) return jbook
fix(classes): Don't try to load layout modules until init()
fix(classes): Don't try to load layout modules until init()
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
638c5e1ae92fe735560f1e78b3b6ab5c2d6c0ad9
otouto/plugins/afk.lua
otouto/plugins/afk.lua
-- original plugin by Akamaru [https://ponywave.de] -- I added Redis and automatic online switching back in 2015 local afk = {} function afk:init(config) afk.triggers = { "^/([A|a][F|f][K|k])$", "^/([A|a][F|f][K|k]) (.*)$" } afk.doc = [[* ]]..config.cmd_pat..[[afk* _[Text]_: Setzt Status auf AFK mit optionalem Text]] end afk.command = 'afk [Text]' function afk:is_offline(hash) local afk = redis:hget(hash, 'afk') if afk == "true" then return true else return false end end function afk:get_afk_text(hash) local afk_text = redis:hget(hash, 'afk_text') if afk_text ~= nil and afk_text ~= "" and afk_text ~= "false" then return afk_text else return false end end function afk:switch_afk(user_name, user_id, chat_id, timestamp, text) local hash = 'afk:'..chat_id..':'..user_id if afk:is_offline(hash) then local afk_text = afk:get_afk_text(hash) if afk_text then return 'Du bist bereits AFK ('..afk_text..')!' else return 'Du bist bereits AFK!' end end print('Setting redis hash afk in '..hash..' to true') redis:hset(hash, 'afk', true) print('Setting redis hash timestamp in '..hash..' to '..timestamp) redis:hset(hash, 'time', timestamp) if text then print('Setting redis hash afk_text in '..hash..' to '..text) redis:hset(hash, 'afk_text', text) return user_name..' ist AFK ('..text..')' else return user_name..' ist AFK' end end function afk:pre_process(msg, self) if msg.chat.type == "private" then -- Ignore return end local user_name = get_name(msg) local user_id = msg.from.id local chat_id = msg.chat.id local hash = 'afk:'..chat_id..':'..user_id local uhash = 'user:'..user_id if afk:is_offline(hash) then local afk_text = afk:get_afk_text(hash) -- calculate afk time local timestamp = redis:hget(hash, 'time') local current_timestamp = msg.date local afk_time = current_timestamp - timestamp local duration = makeHumanTime(afk_time) redis:hset(hash, 'afk', false) local show_afk_keyboard = redis:hget(uhash, 'afk_keyboard') if afk_text then redis:hset(hash, 'afk_text', false) if show_afk_keyboard == 'true' then utilities.send_reply(self, msg, user_name..' ist wieder da (war: <b>'..afk_text..'</b> für '..duration..')!', 'HTML', '{"hide_keyboard":true,"selective":true}') else utilities.send_message(self, chat_id, user_name..' ist wieder da (war: <b>'..afk_text..'</b> für '..duration..')!', true, nil, 'HTML') end else if show_afk_keyboard == 'true' then utilities.send_reply(self, msg, user_name..' ist wieder da (war '..duration..' weg)!', nil, '{"hide_keyboard":true,"selective":true}') else utilities.send_message(self, chat_id, user_name..' ist wieder da (war '..duration..' weg)!') end end end return msg end function afk:action(msg) if msg.chat.type == "private" then utilities.send_reply(self, msg, "Mir ist's egal, ob du AFK bist ._.") return end local user_id = msg.from.id local chat_id = msg.chat.id local user_name = get_name(msg) local timestamp = msg.date local uhash = 'user:'..msg.from.id local show_afk_keyboard = redis:hget(uhash, 'afk_keyboard') if show_afk_keyboard == 'true' then keyboard = '{"keyboard":[[{"text":"Wieder da."}]], "one_time_keyboard":true, "selective":true, "resize_keyboard":true}' else keyboard = nil end utilities.send_reply(self, msg, afk:switch_afk(user_name, user_id, chat_id, timestamp, matches[2]), false, keyboard) end return afk
-- original plugin by Akamaru [https://ponywave.de] -- I added Redis and automatic online switching back in 2015 local afk = {} function afk:init(config) afk.triggers = { "^/([A|a][F|f][K|k]) (.*)$", "^/([A|a][F|f][K|k])$" } afk.doc = [[* ]]..config.cmd_pat..[[afk* _[Text]_: Setzt Status auf AFK mit optionalem Text]] end afk.command = 'afk [Text]' function afk:is_offline(hash) local afk = redis:hget(hash, 'afk') if afk == "true" then return true else return false end end function afk:get_afk_text(hash) local afk_text = redis:hget(hash, 'afk_text') if afk_text ~= nil and afk_text ~= "" and afk_text ~= "false" then return afk_text else return false end end function afk:switch_afk(user_name, user_id, chat_id, timestamp, text) local hash = 'afk:'..chat_id..':'..user_id if afk:is_offline(hash) then local afk_text = afk:get_afk_text(hash) if afk_text then return 'Du bist bereits AFK ('..afk_text..')!' else return 'Du bist bereits AFK!' end end print('Setting redis hash afk in '..hash..' to true') redis:hset(hash, 'afk', true) print('Setting redis hash timestamp in '..hash..' to '..timestamp) redis:hset(hash, 'time', timestamp) if text then print('Setting redis hash afk_text in '..hash..' to '..text) redis:hset(hash, 'afk_text', text) return user_name..' ist AFK ('..text..')' else return user_name..' ist AFK' end end function afk:pre_process(msg, self) if msg.chat.type == "private" then -- Ignore return end local user_name = get_name(msg) local user_id = msg.from.id local chat_id = msg.chat.id local hash = 'afk:'..chat_id..':'..user_id local uhash = 'user:'..user_id if afk:is_offline(hash) then local afk_text = afk:get_afk_text(hash) -- calculate afk time local timestamp = redis:hget(hash, 'time') local current_timestamp = msg.date local afk_time = current_timestamp - timestamp local duration = makeHumanTime(afk_time) redis:hset(hash, 'afk', false) local show_afk_keyboard = redis:hget(uhash, 'afk_keyboard') if afk_text then redis:hset(hash, 'afk_text', false) if show_afk_keyboard == 'true' then utilities.send_reply(self, msg, user_name..' ist wieder da (war: <b>'..afk_text..'</b> für '..duration..')!', 'HTML', '{"hide_keyboard":true,"selective":true}') else utilities.send_message(self, chat_id, user_name..' ist wieder da (war: <b>'..afk_text..'</b> für '..duration..')!', true, nil, 'HTML') end else if show_afk_keyboard == 'true' then utilities.send_reply(self, msg, user_name..' ist wieder da (war '..duration..' weg)!', nil, '{"hide_keyboard":true,"selective":true}') else utilities.send_message(self, chat_id, user_name..' ist wieder da (war '..duration..' weg)!') end end end return msg end function afk:action(msg, config, matches) if msg.chat.type == "private" then utilities.send_reply(self, msg, "Mir ist's egal, ob du AFK bist ._.") return end local user_id = msg.from.id local chat_id = msg.chat.id local user_name = get_name(msg) local timestamp = msg.date local uhash = 'user:'..msg.from.id local show_afk_keyboard = redis:hget(uhash, 'afk_keyboard') if show_afk_keyboard == 'true' then keyboard = '{"keyboard":[[{"text":"Wieder da."}]], "one_time_keyboard":true, "selective":true, "resize_keyboard":true}' else keyboard = nil end utilities.send_reply(self, msg, afk:switch_afk(user_name, user_id, chat_id, timestamp, matches[2]), false, keyboard) end return afk
Bugfix für AFK-Patterns
Bugfix für AFK-Patterns
Lua
agpl-3.0
Brawl345/Brawlbot-v2
3f1f0d68eb14a86a88f73ac1acfaff02100f4a43
MMOCoreORB/bin/scripts/managers/jedi/village/intro/old_man_conv_handler.lua
MMOCoreORB/bin/scripts/managers/jedi/village/intro/old_man_conv_handler.lua
local VillageJediManagerCommon = require("managers.jedi.village.village_jedi_manager_common") local OldManIntroEncounter = require("managers.jedi.village.intro.old_man_intro_encounter") local QuestManager = require("managers.quest.quest_manager") local MellichaeOutroTheater = require("managers.jedi.village.outro.mellichae_outro_theater") oldManIntroConvoHandler = Object:new {} function oldManIntroConvoHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc) local pConversationSession = CreatureObject(pPlayer):getConversationSession() local pLastConversationScreen = nil if (pConversationSession ~= nil) then local conversationSession = LuaConversationSession(pConversationSession) pLastConversationScreen = conversationSession:getLastConversationScreen() end local conversationTemplate = LuaConversationTemplate(pConversationTemplate) if (pLastConversationScreen ~= nil) then local lastConversationScreen = LuaConversationScreen(pLastConversationScreen) local optionLink = lastConversationScreen:getOptionLink(selectedOption) return conversationTemplate:getScreen(optionLink) end return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate) end function oldManIntroConvoHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate) local convoTemplate = LuaConversationTemplate(pConversationTemplate) if OldManIntroEncounter:doesOldManBelongToThePlayer(pPlayer, pNpc) then if (VillageJediManagerCommon.hasJediProgressionScreenPlayState(pPlayer, VILLAGE_JEDI_PROGRESSION_COMPLETED_VILLAGE)) then return convoTemplate:getScreen("intro_mellichae") else return convoTemplate:getScreen("intro") end else return convoTemplate:getScreen("nothing_to_discuss") end end function oldManIntroConvoHandler:runScreenHandlers(pConversationTemplate, pConversingPlayer, pConversingNpc, selectedOption, pConversationScreen) local screen = LuaConversationScreen(pConversationScreen) local screenID = screen:getScreenID() if screenID == "perhaps_meet_again" or screenID == "perhaps_another_time" then OldManIntroEncounter:scheduleDespawnOfOldMan(pConversingPlayer) CreatureObject(pConversingNpc):setOptionsBitmask(128) elseif screenID == "here_is_the_crystal" then OldManIntroEncounter:scheduleDespawnOfOldMan(pConversingPlayer) OldManIntroEncounter:giveForceCrystalToPlayer(pConversingPlayer) CreatureObject(pConversingNpc):setOptionsBitmask(128) elseif screenID == "where_camp" then QuestManager.completeQuest(pConversingPlayer, QuestManager.quests.OLD_MAN_FINAL) MellichaeOutroTheater:start(pConversingPlayer) CreatureObject(pConversingNpc):setOptionsBitmask(128) end return pConversationScreen end
local VillageJediManagerCommon = require("managers.jedi.village.village_jedi_manager_common") local OldManIntroEncounter = require("managers.jedi.village.intro.old_man_intro_encounter") local OldManOutroEncounter = require("managers.jedi.village.outro.old_man_outro_encounter") local QuestManager = require("managers.quest.quest_manager") local MellichaeOutroTheater = require("managers.jedi.village.outro.mellichae_outro_theater") oldManIntroConvoHandler = Object:new {} function oldManIntroConvoHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc) local pConversationSession = CreatureObject(pPlayer):getConversationSession() local pLastConversationScreen = nil if (pConversationSession ~= nil) then local conversationSession = LuaConversationSession(pConversationSession) pLastConversationScreen = conversationSession:getLastConversationScreen() end local conversationTemplate = LuaConversationTemplate(pConversationTemplate) if (pLastConversationScreen ~= nil) then local lastConversationScreen = LuaConversationScreen(pLastConversationScreen) local optionLink = lastConversationScreen:getOptionLink(selectedOption) return conversationTemplate:getScreen(optionLink) end return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate) end function oldManIntroConvoHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate) local convoTemplate = LuaConversationTemplate(pConversationTemplate) if OldManOutroEncounter:doesOldManBelongToThePlayer(pPlayer, pNpc) then return convoTemplate:getScreen("intro_mellichae") elseif OldManIntroEncounter:doesOldManBelongToThePlayer(pPlayer, pNpc) then return convoTemplate:getScreen("intro") else return convoTemplate:getScreen("nothing_to_discuss") end end function oldManIntroConvoHandler:runScreenHandlers(pConversationTemplate, pConversingPlayer, pConversingNpc, selectedOption, pConversationScreen) local screen = LuaConversationScreen(pConversationScreen) local screenID = screen:getScreenID() if screenID == "perhaps_meet_again" or screenID == "perhaps_another_time" then OldManIntroEncounter:scheduleDespawnOfOldMan(pConversingPlayer) CreatureObject(pConversingNpc):setOptionsBitmask(128) elseif screenID == "here_is_the_crystal" then OldManIntroEncounter:scheduleDespawnOfOldMan(pConversingPlayer) OldManIntroEncounter:giveForceCrystalToPlayer(pConversingPlayer) CreatureObject(pConversingNpc):setOptionsBitmask(128) elseif screenID == "where_camp" then QuestManager.completeQuest(pConversingPlayer, QuestManager.quests.OLD_MAN_FINAL) MellichaeOutroTheater:start(pConversingPlayer) CreatureObject(pConversingNpc):setOptionsBitmask(128) end return pConversationScreen end
[fixed] Old man not having anything to discuss with players for outro part
[fixed] Old man not having anything to discuss with players for outro part Change-Id: Ic07ce49714cf195b06ee793e75c311e8a9c8a384
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
2103199fdfddeb3326fe713a05a558e2296cd48a
.vim/lua/pluginconfig/telescope.lua
.vim/lua/pluginconfig/telescope.lua
local actions = require('telescope.actions') local config = require('telescope.config') local pickers = require('telescope.pickers') local finders = require('telescope.finders') local make_entry = require('telescope.make_entry') local previewers = require('telescope.previewers') local utils = require('telescope.utils') local conf = require('telescope.config').values local telescope_builtin = require 'telescope.builtin' require('telescope').setup{ defaults = { vimgrep_arguments = { 'rg', '--color=never', '--no-heading', '--with-filename', '--line-number', '--column', '--smart-case' }, prompt_position = "bottom", prompt_prefix = ">", selection_strategy = "reset", sorting_strategy = "descending", layout_strategy = "horizontal", layout_defaults = { -- TODO add builtin options. }, file_sorter = require'telescope.sorters'.get_fuzzy_file, file_ignore_patterns = {}, generic_sorter = require'telescope.sorters'.get_generic_fuzzy_sorter, shorten_path = true, winblend = 0, width = 0.75, preview_cutoff = 120, results_height = 1, results_width = 0.8, border = {}, borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'}, color_devicons = true, use_less = true, set_env = { ['COLORTERM'] = 'truecolor' }, -- default { }, currently unsupported for shells like cmd.exe / powershell.exe file_previewer = require'telescope.previewers'.cat.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_cat.new` grep_previewer = require'telescope.previewers'.vimgrep.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_vimgrep.new` qflist_previewer = require'telescope.previewers'.qflist.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_qflist.new` -- Developer configurations: Not meant for general override buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker, mappings = { i = { ["<c-x>"] = false, ["<c-s>"] = actions.goto_file_selection_split, } } } } telescope_builtin.my_mru = function(opts) local results = vim.tbl_filter(function(val) return 0 ~= vim.fn.filereadable(val) end, vim.v.oldfiles) local cmd = "git ls-files --exclude-standard --cached --others" local results = vim.split(utils.get_os_command_output(cmd), '\n') pickers.new(opts, { prompt_title = 'MRU', finder = finders.new_table{ results = results, entry_maker = opts.entry_maker or make_entry.gen_from_file(opts), }, sorter = conf.file_sorter(opts), previewer = conf.file_previewer(opts), }):find() end
local actions = require('telescope.actions') local config = require('telescope.config') local pickers = require('telescope.pickers') local finders = require('telescope.finders') local make_entry = require('telescope.make_entry') local previewers = require('telescope.previewers') local utils = require('telescope.utils') local conf = require('telescope.config').values local telescope_builtin = require 'telescope.builtin' require('telescope').setup{ defaults = { vimgrep_arguments = { 'rg', '--color=never', '--no-heading', '--with-filename', '--line-number', '--column', '--smart-case' }, prompt_position = "bottom", prompt_prefix = ">", selection_strategy = "reset", sorting_strategy = "descending", layout_strategy = "horizontal", layout_defaults = { -- TODO add builtin options. }, file_sorter = require'telescope.sorters'.get_fuzzy_file, file_ignore_patterns = {}, generic_sorter = require'telescope.sorters'.get_generic_fuzzy_sorter, shorten_path = true, winblend = 0, width = 0.75, preview_cutoff = 120, results_height = 1, results_width = 0.8, border = {}, borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'}, color_devicons = true, use_less = true, set_env = { ['COLORTERM'] = 'truecolor' }, -- default { }, currently unsupported for shells like cmd.exe / powershell.exe file_previewer = require'telescope.previewers'.cat.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_cat.new` grep_previewer = require'telescope.previewers'.vimgrep.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_vimgrep.new` qflist_previewer = require'telescope.previewers'.qflist.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_qflist.new` -- Developer configurations: Not meant for general override buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker, mappings = { i = { ["<c-x>"] = false, ["<c-s>"] = actions.goto_file_selection_split, } } } } function tprint (tbl, indent) if not indent then indent = 0 end for k, v in pairs(tbl) do formatting = string.rep(" ", indent) .. k .. ": " if type(v) == "table" then print(formatting) tprint(v, indent+1) else print(formatting .. v) end end end telescope_builtin.my_mru = function(opts) local results = vim.tbl_filter(function(val) return 0 ~= vim.fn.filereadable(val) end, vim.v.oldfiles) local show_untracked = utils.get_default(opts.show_untracked, true) local recurse_submodules = utils.get_default(opts.recurse_submodules, false) if show_untracked and recurse_submodules then error("Git does not suppurt both --others and --recurse-submodules") end local cmd = {"git", "ls-files", "--exclude-standard", "--cached", show_untracked and "--others" or nil, recurse_submodules and "--recurse-submodules" or nil} local results2 = utils.get_os_command_output({"git", "ls-files"}) for k,v in pairs(results2) do table.insert(results, v) end pickers.new(opts, { prompt_title = 'MRU', finder = finders.new_table{ results = results, entry_maker = opts.entry_maker or make_entry.gen_from_file(opts), }, sorter = conf.file_sorter(opts), previewer = conf.file_previewer(opts), }):find() end
vim: Fix my_mru for telescope
vim: Fix my_mru for telescope
Lua
mit
yutakatay/dotfiles,yutakatay/dotfiles
9df94c7ee64f34ff9621316b5ef25d94200c6e32
lua_modules/dht_lib/dht_lib.lua
lua_modules/dht_lib/dht_lib.lua
-- *************************************************************************** -- DHTxx(11,21,22) module for ESP8266 with nodeMCU -- -- Written by Javier Yanez mod by Martin -- but based on a script of Pigs Fly from ESP8266.com forum -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** --Support list: --DHT11 Tested ->read11 --DHT21 Not Tested->read22 --DHT22 Tested->read22 --==========================Module Part====================== local moduleName = ... local M = {} _G[moduleName] = M --==========================Local the UMI and TEMP=========== local humidity local temperature --==========================Local the bitStream============== local bitStream = {} ---------------------------Read bitStream from DHTXX-------------------------- local function read(pin) local bitlength = 0 humidity = 0 temperature = 0 -- Use Markus Gritsch trick to speed up read/write on GPIO local gpio_read = gpio.read for j = 1, 40, 1 do bitStream[j] = 0 end -- Step 1: send out start signal to DHT22 gpio.mode(pin, gpio.OUTPUT) gpio.write(pin, gpio.HIGH) tmr.delay(100) gpio.write(pin, gpio.LOW) tmr.delay(20000) gpio.write(pin, gpio.HIGH) gpio.mode(pin, gpio.INPUT) -- Step 2: Receive bitStream from DHT11/22 -- bus will always let up eventually, don't bother with timeout while (gpio_read(pin) == 0 ) do end local c=0 while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end -- bus will always let up eventually, don't bother with timeout while (gpio_read(pin) == 0 ) do end c=0 while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end -- Step 3: DHT22 send data for j = 1, 40, 1 do while (gpio_read(pin) == 1 and bitlength < 10 ) do bitlength = bitlength + 1 end bitStream[j] = bitlength bitlength = 0 -- bus will always let up eventually, don't bother with timeout while (gpio_read(pin) == 0) do end end end ---------------------------Convert the bitStream into Number through DHT11 Ways-------------------------- local function bit2DHT11() --As for DHT11 40Bit is consisit of 5Bytes --First byte->Humidity Data's Int part --Sencond byte->Humidity Data's Float Part(Which should be empty) --Third byte->Temp Data;s Intpart --Forth byte->Temp Data's Float Part(Which should be empty) --Fifth byte->SUM Byte, Humi+Temp local checksum = 0 local checksumTest --DHT data acquired, process. for i = 1, 8, 1 do -- Byte[0] if (bitStream[i] > 3) then humidity = humidity + 2 ^ (8 - i) end end for i = 1, 8, 1 do -- Byte[2] if (bitStream[i + 16] > 3) then temperature = temperature + 2 ^ (8 - i) end end for i = 1, 8, 1 do --Byte[4] if (bitStream[i + 32] > 3) then checksum = checksum + 2 ^ (8 - i) end end if(checksum ~= humidity+temperature) then humidity = nil temperature = nil end end ---------------------------Convert the bitStream into Number through DHT22 Ways-------------------------- local function bit2DHT22() --As for DHT22 40Bit is consisit of 5Bytes --First byte->Humidity Data's High Bit --Sencond byte->Humidity Data's Low Bit(And if over 0x8000, use complement) --Third byte->Temp Data's High Bit --Forth byte->Temp Data's Low Bit --Fifth byte->SUM Byte local checksum = 0 local checksumTest --DHT data acquired, process. for i = 1, 16, 1 do if (bitStream[i] > 3) then humidity = humidity + 2 ^ (16 - i) end end for i = 1, 16, 1 do if (bitStream[i + 16] > 3) then temperature = temperature + 2 ^ (16 - i) end end for i = 1, 8, 1 do if (bitStream[i + 32] > 3) then checksum = checksum + 2 ^ (8 - i) end end checksumTest = (bit.band(humidity, 0xFF) + bit.rshift(humidity, 8) + bit.band(temperature, 0xFF) + bit.rshift(temperature, 8)) checksumTest = bit.band(checksumTest, 0xFF) if temperature > 0x8000 then -- convert to negative format temperature = -(temperature - 0x8000) end -- conditions compatible con float point and integer if (checksumTest - checksum >= 1) or (checksum - checksumTest >= 1) then humidity = nil end end ---------------------------Check out the data-------------------------- ----Auto Select the DHT11/DHT22 By check the byte[1] && byte[3]AND --- ---------------Which is empty when using DHT11------------------------- function M.read(pin) read(pin) local byte_1 = 0 local byte_2 = 0 for i = 1, 8, 1 do -- Byte[1] if (bitStream[i+8] > 3) then byte_1 = byte_1 + 2 ^ (8 - i) end end for i = 1, 8, 1 do -- Byte[1] if (bitStream[i+24] > 3) then byte_2 = byte_2 + 2 ^ (8 - i) end end if byte_1==0 and byte_2 == 0 then bit2DHT11() else bit2DHT22() end end function M.getTemperature() return temperature end function M.getHumidity() return humidity end return M
-- *************************************************************************** -- DHTxx(11,21,22) module for ESP8266 with nodeMCU -- -- Written by Javier Yanez mod by Martin -- but based on a script of Pigs Fly from ESP8266.com forum -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** --Support list: --DHT11 Tested --DHT21 Not Test yet --DHT22(AM2302) Tested --AM2320 Not Test yet --Output format-> Real temperature times 10(or DHT22 will miss it float part in Int Version) --For example, the data read form DHT2x is 24.3 degree C, and the output will be 243 ---------------the data read form DHT1x is 27 degree C, and the output will be 270 --==========================Module Part====================== local moduleName = ... local M = {} _G[moduleName] = M --==========================Local the UMI and TEMP=========== local humidity local temperature --==========================Local the bitStream============== local bitStream = {} ---------------------------Read bitStream from DHTXX-------------------------- local function read(pin) local bitlength = 0 humidity = 0 temperature = 0 -- Use Markus Gritsch trick to speed up read/write on GPIO local gpio_read = gpio.read for j = 1, 40, 1 do bitStream[j] = 0 end -- Step 1: send out start signal to DHT22 gpio.mode(pin, gpio.OUTPUT) gpio.write(pin, gpio.HIGH) tmr.delay(100) gpio.write(pin, gpio.LOW) tmr.delay(20000) gpio.write(pin, gpio.HIGH) gpio.mode(pin, gpio.INPUT) -- Step 2: Receive bitStream from DHT11/22 -- bus will always let up eventually, don't bother with timeout while (gpio_read(pin) == 0 ) do end local c=0 while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end -- bus will always let up eventually, don't bother with timeout while (gpio_read(pin) == 0 ) do end c=0 while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end -- Step 3: DHT22 send data for j = 1, 40, 1 do while (gpio_read(pin) == 1 and bitlength < 10 ) do bitlength = bitlength + 1 end bitStream[j] = bitlength bitlength = 0 -- bus will always let up eventually, don't bother with timeout while (gpio_read(pin) == 0) do end end end ---------------------------Convert the bitStream into Number through DHT11 Ways-------------------------- local function bit2DHT11() --As for DHT11 40Bit is consisit of 5Bytes --First byte->Humidity Data's Int part --Sencond byte->Humidity Data's Float Part(Which should be empty) --Third byte->Temp Data;s Intpart --Forth byte->Temp Data's Float Part(Which should be empty) --Fifth byte->SUM Byte, Humi+Temp local checksum = 0 local checksumTest --DHT data acquired, process. for i = 1, 8, 1 do -- Byte[0] if (bitStream[i] > 3) then humidity = humidity + 2 ^ (8 - i) end end for i = 1, 8, 1 do -- Byte[2] if (bitStream[i + 16] > 3) then temperature = temperature + 2 ^ (8 - i) end end for i = 1, 8, 1 do --Byte[4] if (bitStream[i + 32] > 3) then checksum = checksum + 2 ^ (8 - i) end end if(checksum ~= humidity+temperature) then humidity = nil temperature = nil else humidity = humidity *10 -- In order to universe the DHT22 temperature = temperature *10 end end ---------------------------Convert the bitStream into Number through DHT22 Ways-------------------------- local function bit2DHT22() --As for DHT22 40Bit is consisit of 5Bytes --First byte->Humidity Data's High Bit --Sencond byte->Humidity Data's Low Bit(And if over 0x8000, use complement) --Third byte->Temp Data's High Bit --Forth byte->Temp Data's Low Bit --Fifth byte->SUM Byte local checksum = 0 local checksumTest --DHT data acquired, process. for i = 1, 16, 1 do if (bitStream[i] > 3) then humidity = humidity + 2 ^ (16 - i) end end for i = 1, 16, 1 do if (bitStream[i + 16] > 3) then temperature = temperature + 2 ^ (16 - i) end end for i = 1, 8, 1 do if (bitStream[i + 32] > 3) then checksum = checksum + 2 ^ (8 - i) end end checksumTest = (bit.band(humidity, 0xFF) + bit.rshift(humidity, 8) + bit.band(temperature, 0xFF) + bit.rshift(temperature, 8)) checksumTest = bit.band(checksumTest, 0xFF) if temperature > 0x8000 then -- convert to negative format temperature = -(temperature - 0x8000) end -- conditions compatible con float point and integer if (checksumTest - checksum >= 1) or (checksum - checksumTest >= 1) then humidity = nil end end ---------------------------Check out the data-------------------------- ----Auto Select the DHT11/DHT22 by checking the byte[1]==0 && byte[3]==0 --- ---------------Which is empty when using DHT11------------------------- function M.read(pin) read(pin) local byte_1 = 0 local byte_2 = 0 for i = 1, 8, 1 do -- Byte[1] if (bitStream[i+8] > 3) then byte_1 = byte_1 + 2 ^ (8 - i) end end for i = 1, 8, 1 do -- Byte[1] if (bitStream[i+24] > 3) then byte_2 = byte_2 + 2 ^ (8 - i) end end if byte_1==0 and byte_2 == 0 then bit2DHT11() else bit2DHT22() end end --------------API for geting the data out------------------ function M.getTemperature() return temperature end function M.getHumidity() return humidity end -------------Return Index------------------------------------ return M
Really Fix the BUGs, add come comment
Really Fix the BUGs, add come comment Sorry for the mistake, I forgot to save the file when gitting...
Lua
mit
cs8425/nodemcu-firmware,eku/nodemcu-firmware,Alkorin/nodemcu-firmware,fetchbot/nodemcu-firmware,vowstar/nodemcu-firmware,romanchyla/nodemcu-firmware,FrankX0/nodemcu-firmware,zhujunsan/nodemcu-firmware,devsaurus/nodemcu-firmware,fetchbot/nodemcu-firmware,christakahashi/nodemcu-firmware,xatanais/nodemcu-firmware,digitalloggers/nodemcu-firmware,shangwudong/MyNodeMcu,vsky279/nodemcu-firmware,zerog2k/nodemcu-firmware,funshine/nodemcu-firmware,cs8425/nodemcu-firmware,dnc40085/nodemcu-firmware,weera00/nodemcu-firmware,fetchbot/nodemcu-firmware,karrots/nodemcu-firmware,dnc40085/nodemcu-firmware,vsky279/nodemcu-firmware,kbeckmann/nodemcu-firmware,ktosiu/nodemcu-firmware,yurenyong123/nodemcu-firmware,daned33/nodemcu-firmware,karrots/nodemcu-firmware,dscoolx6/MyESP8266,yurenyong123/nodemcu-firmware,HEYAHONG/nodemcu-firmware,ciufciuf57/nodemcu-firmware,marcelstoer/nodemcu-firmware,funshine/nodemcu-firmware,noahchense/nodemcu-firmware,mikeller/nodemcu-firmware,oyooyo/nodemcu-firmware,shangwudong/MyNodeMcu,zhujunsan/nodemcu-firmware,daned33/nodemcu-firmware,nwf/nodemcu-firmware,TerryE/nodemcu-firmware,zerog2k/nodemcu-firmware,funshine/nodemcu-firmware,luizfeliperj/nodemcu-firmware,bhrt/nodeMCU,FrankX0/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,nodemcu/nodemcu-firmware,eku/nodemcu-firmware,Kisaua/nodemcu-firmware,Alkorin/nodemcu-firmware,nodemcu/nodemcu-firmware,filug/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,petrkr/nodemcu-firmware,SmartArduino/nodemcu-firmware,Alkorin/nodemcu-firmware,noahchense/nodemcu-firmware,danronco/nodemcu-firmware,xatanais/nodemcu-firmware,vowstar/nodemcu-firmware,HEYAHONG/nodemcu-firmware,petrkr/nodemcu-firmware,marktsai0316/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,raburton/nodemcu-firmware,cs8425/nodemcu-firmware,oyooyo/nodemcu-firmware,FelixPe/nodemcu-firmware,anusornc/nodemcu-firmware,jmattsson/nodemcu-firmware,marktsai0316/nodemcu-firmware,flexiti/nodemcu-firmware,HEYAHONG/nodemcu-firmware,marcelstoer/nodemcu-firmware,nwf/nodemcu-firmware,marcelstoer/nodemcu-firmware,petrkr/nodemcu-firmware,abgoyal/nodemcu-firmware,FrankX0/nodemcu-firmware,zerog2k/nodemcu-firmware,jmattsson/nodemcu-firmware,abgoyal/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,petrkr/nodemcu-firmware,radiojam11/nodemcu-firmware,karrots/nodemcu-firmware,TerryE/nodemcu-firmware,anusornc/nodemcu-firmware,natetrue/nodemcu-firmware,anusornc/nodemcu-firmware,bhrt/nodeMCU,djphoenix/nodemcu-firmware,remspoor/nodemcu-firmware,vowstar/nodemcu-firmware,shangwudong/MyNodeMcu,marktsai0316/nodemcu-firmware,bhrt/nodeMCU,eku/nodemcu-firmware,klukonin/nodemcu-firmware,benwolfe/nodemcu-firmware,luizfeliperj/nodemcu-firmware,dnc40085/nodemcu-firmware,iotcafe/nodemcu-firmware,FelixPe/nodemcu-firmware,bogvak/nodemcu-firmware,nwf/nodemcu-firmware,FelixPe/nodemcu-firmware,devsaurus/nodemcu-firmware,Kisaua/nodemcu-firmware,marcelstoer/nodemcu-firmware,sowbug/nodemcu-firmware,karrots/nodemcu-firmware,radiojam11/nodemcu-firmware,abgoyal/nodemcu-firmware,nwf/nodemcu-firmware,shangwudong/MyNodeMcu,luizfeliperj/nodemcu-firmware,weera00/nodemcu-firmware,SmartArduino/nodemcu-firmware,devsaurus/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,dnc40085/nodemcu-firmware,ciufciuf57/nodemcu-firmware,mikeller/nodemcu-firmware,bogvak/nodemcu-firmware,jmattsson/nodemcu-firmware,digitalloggers/nodemcu-firmware,makefu/nodemcu-firmware,bhrt/nodeMCU,makefu/nodemcu-firmware,bhrt/nodeMCU,remspoor/nodemcu-firmware,remspoor/nodemcu-firmware,christakahashi/nodemcu-firmware,vsky279/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,Alkorin/nodemcu-firmware,filug/nodemcu-firmware,Alkorin/nodemcu-firmware,FrankX0/nodemcu-firmware,jmattsson/nodemcu-firmware,makefu/nodemcu-firmware,djphoenix/nodemcu-firmware,romanchyla/nodemcu-firmware,flexiti/nodemcu-firmware,xatanais/nodemcu-firmware,flexiti/nodemcu-firmware,borromeotlhs/nodemcu-firmware,FelixPe/nodemcu-firmware,robertfoss/nodemcu-firmware,christakahashi/nodemcu-firmware,devsaurus/nodemcu-firmware,raburton/nodemcu-firmware,nodemcu/nodemcu-firmware,kbeckmann/nodemcu-firmware,FelixPe/nodemcu-firmware,robertfoss/nodemcu-firmware,christakahashi/nodemcu-firmware,benwolfe/nodemcu-firmware,SmartArduino/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,funshine/nodemcu-firmware,ktosiu/nodemcu-firmware,iotcafe/nodemcu-firmware,ruisebastiao/nodemcu-firmware,kbeckmann/nodemcu-firmware,eku/nodemcu-firmware,TerryE/nodemcu-firmware,romanchyla/nodemcu-firmware,remspoor/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,kbeckmann/nodemcu-firmware,iotcafe/nodemcu-firmware,nwf/nodemcu-firmware,nodemcu/nodemcu-firmware,danronco/nodemcu-firmware,digitalloggers/nodemcu-firmware,shangwudong/MyNodeMcu,zhujunsan/nodemcu-firmware,borromeotlhs/nodemcu-firmware,fetchbot/nodemcu-firmware,bogvak/nodemcu-firmware,robertfoss/nodemcu-firmware,radiojam11/nodemcu-firmware,FrankX0/nodemcu-firmware,vsky279/nodemcu-firmware,funshine/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,TerryE/nodemcu-firmware,jmattsson/nodemcu-firmware,nodemcu/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,klukonin/nodemcu-firmware,natetrue/nodemcu-firmware,HEYAHONG/nodemcu-firmware,ktosiu/nodemcu-firmware,djphoenix/nodemcu-firmware,daned33/nodemcu-firmware,klukonin/nodemcu-firmware,sowbug/nodemcu-firmware,TerryE/nodemcu-firmware,oyooyo/nodemcu-firmware,ruisebastiao/nodemcu-firmware,yurenyong123/nodemcu-firmware,dscoolx6/MyESP8266,raburton/nodemcu-firmware,weera00/nodemcu-firmware,natetrue/nodemcu-firmware,remspoor/nodemcu-firmware,christakahashi/nodemcu-firmware,sowbug/nodemcu-firmware,oyooyo/nodemcu-firmware,HEYAHONG/nodemcu-firmware,luizfeliperj/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,ciufciuf57/nodemcu-firmware,devsaurus/nodemcu-firmware,marcelstoer/nodemcu-firmware,mikeller/nodemcu-firmware,danronco/nodemcu-firmware,dscoolx6/MyESP8266,rickvanbodegraven/nodemcu-firmware,Kisaua/nodemcu-firmware,vsky279/nodemcu-firmware,ruisebastiao/nodemcu-firmware,filug/nodemcu-firmware,dnc40085/nodemcu-firmware,noahchense/nodemcu-firmware,petrkr/nodemcu-firmware,borromeotlhs/nodemcu-firmware,benwolfe/nodemcu-firmware,djphoenix/nodemcu-firmware,kbeckmann/nodemcu-firmware,karrots/nodemcu-firmware
ed8c555dc623874cf71fd9f725fd06b7141d81e7
deps/coro-tls.lua
deps/coro-tls.lua
exports.name = "creationix/coro-tls" exports.version = "1.1.2" local openssl = require('openssl') local bit = require('bit') -- Given a read/write pair, return a new read/write pair for plaintext exports.wrap = function (read, write, options) if not options then options = {} end local ctx = openssl.ssl.ctx_new("TLSv1_2") local key, cert, ca if options.key then key = assert(openssl.pkey.read(options.key, true, 'pem')) end if options.cert then cert = assert(openssl.x509.read(options.cert)) end if options.ca then ca = assert(openssl.x509.read(options.ca)) end if key and cert then assert(ctx:use(key, cert)) end if ca then local store = openssl.x509.store:new() assert(store:add(ca)) ctx:cert_store(store) else ctx:verify_mode({"none"}) end ctx:options(bit.bor( openssl.ssl.no_sslv2, openssl.ssl.no_sslv3, openssl.ssl.no_compression)) local bin, bout = openssl.bio.mem(8192), openssl.bio.mem(8192) local ssl = ctx:ssl(bin, bout, false) local function flush() while bout:pending() > 0 do write(bout:read()) end end -- Do handshake while true do if ssl:handshake() then break end flush() bin:write(read()) end local done = false local function shutdown() if done then return end done = true ssl:shutdown() flush() write() end local function plainRead() while true do local chunk = ssl:read() if chunk then return chunk end local cipher = read() if not cipher then return end bin:write(cipher) end end local function plainWrite(plain) if not plain then return shutdown() end ssl:write(plain) flush() end return plainRead, plainWrite end
exports.name = "creationix/coro-tls" exports.version = "1.1.3" local openssl = require('openssl') local bit = require('bit') -- Given a read/write pair, return a new read/write pair for plaintext exports.wrap = function (read, write, options) if not options then options = {} end local ctx = openssl.ssl.ctx_new("TLSv1_2") local key, cert, ca if options.key then key = assert(openssl.pkey.read(options.key, true, 'pem')) end if options.cert then cert = assert(openssl.x509.read(options.cert)) end if options.ca then ca = assert(openssl.x509.read(options.ca)) end if key and cert then assert(ctx:use(key, cert)) end if ca then local store = openssl.x509.store:new() assert(store:add(ca)) ctx:cert_store(store) else ctx:verify_mode({"none"}) end ctx:options(bit.bor( openssl.ssl.no_sslv2, openssl.ssl.no_sslv3, openssl.ssl.no_compression)) local bin, bout = openssl.bio.mem(8192), openssl.bio.mem(8192) local ssl = ctx:ssl(bin, bout, options.server and true or false) local function flush() while bout:pending() > 0 do write(bout:read()) end end -- Do handshake while true do if ssl:handshake() then break end flush() local chunk = read() if chunk then bin:write(chunk) else error("disconnect while handshaking") end end flush() local done = false local function shutdown() if done then return end done = true ssl:shutdown() flush() write() end local function plainRead() while true do local chunk = ssl:read() if chunk then return chunk end local cipher = read() if not cipher then return end bin:write(cipher) end end local function plainWrite(plain) if not plain then return shutdown() end ssl:write(plain) flush() end return plainRead, plainWrite end
coro-tls: Fix server side
coro-tls: Fix server side
Lua
apache-2.0
DBarney/lit,squeek502/lit,zhaozg/lit,kidaa/lit,james2doyle/lit,1yvT0s/lit,lduboeuf/lit,kaustavha/lit,luvit/lit
f6f57ec2fc5903de33a4453b3af24372852576ee
Modules/Utility/os.lua
Modules/Utility/os.lua
-- @author Narrev local function date(formatString, unix) --- Allows you to use os.date in RobloxLua! -- date ([format [, time]]) -- This doesn't include the explanations for the math. If you want to see how the numbers work, see the following: -- http://howardhinnant.github.io/date_algorithms.html#weekday_from_days -- -- @param string formatString -- If present, function date returns a string formatted by the tags in formatString. -- If formatString starts with "!", date is formatted in UTC. -- If formatString is "*t", date returns a table -- Placing "_" in the middle of a tag (e.g. "%_d" "%_I") removes padding -- String Reference: https://github.com/Narrev/NevermoreEngine/blob/patch-5/Modules/Utility/readme.md -- @default "%c" -- -- @param number unix -- If present, unix is the time to be formatted. Otherwise, date formats the current time. -- The amount of seconds since 1970 (negative numbers are occasionally supported) -- @default tick() -- @returns a string or a table containing date and time, formatted according to the given string format. If called without arguments, returns the equivalent of date("%c"). -- Localize functions local floor, sub, find, gsub, format = math.floor, string.sub, string.find, string.gsub, string.format -- Find whether formatString was used if formatString then if type(formatString) == "number" then -- If they didn't pass a formatString, and only passed unix through assert(type(unix) ~= "string", "Invalid parameters passed to os.date. Your parameters might be in the wrong order") unix, formatString = formatString, "%c" elseif type(formatString) == "string" then assert(find(formatString, "*t") or find(formatString, "%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date") local UTC formatString, UTC = gsub(formatString, "^!", "") -- If formatString begins in '!', use os.time() assert(UTC == 0 or not unix, "Cannot determine time to format for os.date. Use either an \"!\" at the beginning of the string or pass a time parameter") unix = UTC == 1 and os.time() or unix end else -- If they did not pass a formatting string formatString = "%c" end -- Set unix local unix = type(tonumber(unix)) == "number" and unix or tick() -- Get hours, minutes, and seconds local hours, minutes, seconds = floor(unix / 3600 % 24), floor(unix / 60 % 60), floor(unix % 60) -- Get days, month and year local days = floor(unix / 86400) + 719468 local wday = (days + 3) % 7 local year = floor((days >= 0 and days or days - 146096) / 146097) -- 400 Year bracket days = (days - year * 146097) -- Days into 400 year bracket [0, 146096] local years = floor((days - floor(days/1460) + floor(days/36524) - floor(days/146096))/365) -- Years into 400 Year bracket[0, 399] days = days - (365*years + floor(years/4) - floor(years/100)) -- Days into year (March 1st is first day) [0, 365] local month = floor((5*days + 2)/153) -- Month of year (March is month 0) [0, 11] local yDay = days -- Hi readers :) days = days - floor((153*month + 2)/5) + 1 -- Days into month [1, 31] month = month + (month < 10 and 3 or -9) -- Real life month [1, 12] year = years + year*400 + (month < 3 and 1 or 0) -- Actual year (Shift 1st month from March to January) if formatString == "*t" then -- Return a table if "*t" was used return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds} end -- Necessary string tables local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} -- Return formatted string return (gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(formatString, "%%c", "%%x %%X"), "%%_c", "%%_x %%_X"), "%%x", "%%m/%%d/%%y"), "%%_x", "%%_m/%%_d/%%y"), "%%X", "%%H:%%M:%%S"), "%%_X", "%%_H:%%M:%%S"), "%%T", "%%I:%%M %%p"), "%%_T", "%%_I:%%M %%p"), "%%r", "%%I:%%M:%%S %%p"), "%%_r", "%%_I:%%M:%%S %%p"), "%%R", "%%H:%%M"), "%%_R", "%%_H:%%M"), "%%a", sub(dayNames[wday + 1], 1, 3)), "%%A", dayNames[wday + 1]), "%%b", sub(months[month], 1, 3)), "%%B", months[month]), "%%d", format("%02d", days)), "%%_d", days), "%%H", format("%02d", hours)), "%%_H", hours), "%%I", format("%02d", hours > 12 and hours - 12 or hours == 0 and 12 or hours)), "%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours), "%%j", format("%02d", yDay)), "%%_j", yDay), "%%M", format("%02d", minutes)), "%%_M", minutes), "%%m", format("%02d", month)), "%%_m", month), "%%n", "\n"), "%%p", hours >= 12 and "pm" or "am"), "%%_p", hours >= 12 and "PM" or "AM"), "%%s", (days < 21 and days > 3 or days > 23 and days < 31) and "th" or ({"st", "nd", "rd"})[days % 10]), "%%S", format("%02d", seconds)), "%%_S", seconds), "%%t", "\t"), "%%u", wday == 0 and 7 or wday), "%%w", wday), "%%Y", year), "%%y", format("%02d", year % 100)), "%%_y", year % 100), "%%%%", "%%") ) end local function clock() local timeYielded, timeServerHasBeenRunning = wait() return timeServerHasBeenRunning end return setmetatable({date = date, clock = clock}, {__index = os})
-- @author Narrev local function date(formatString, unix) --- Allows you to use os.date in RobloxLua! -- date ([format [, time]]) -- This doesn't include the explanations for the math. If you want to see how the numbers work, see the following: -- http://howardhinnant.github.io/date_algorithms.html#weekday_from_days -- -- @param string formatString -- If present, function date returns a string formatted by the tags in formatString. -- If formatString starts with "!", date is formatted in UTC. -- If formatString is "*t", date returns a table -- Placing "_" in the middle of a tag (e.g. "%_d" "%_I") removes padding -- String Reference: https://github.com/Narrev/NevermoreEngine/blob/patch-5/Modules/Utility/readme.md -- @default "%c" -- -- @param number unix -- If present, unix is the time to be formatted. Otherwise, date formats the current time. -- The amount of seconds since 1970 (negative numbers are occasionally supported) -- @default tick() -- @returns a string or a table containing date and time, formatted according to the given string format. If called without arguments, returns the equivalent of date("%c"). -- Localize functions local floor, sub, find, gsub, format = math.floor, string.sub, string.find, string.gsub, string.format -- Find whether formatString was used if formatString then if type(formatString) == "number" then -- If they didn't pass a formatString, and only passed unix through assert(type(unix) ~= "string", "Invalid parameters passed to os.date. Your parameters might be in the wrong order") unix, formatString = formatString, "%c" elseif type(formatString) == "string" then assert(find(formatString, "*t") or find(formatString, "%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date") local UTC formatString, UTC = gsub(formatString, "^!", "") -- If formatString begins in '!', use os.time() assert(UTC == 0 or not unix, "Cannot determine time to format for os.date. Use either an \"!\" at the beginning of the string or pass a time parameter") unix = UTC == 1 and os.time() or unix end else -- If they did not pass a formatting string formatString = "%c" end -- Set unix local unix = type(tonumber(unix)) == "number" and unix or tick() -- Get hours, minutes, and seconds local hours, minutes, seconds = floor(unix / 3600 % 24), floor(unix / 60 % 60), floor(unix % 60) -- Get days, month and year local days = floor(unix / 86400) + 719468 local wday = (days + 3) % 7 local year = floor((days >= 0 and days or days - 146096) / 146097) -- 400 Year bracket days = (days - year * 146097) -- Days into 400 year bracket [0, 146096] local years = floor((days - floor(days/1460) + floor(days/36524) - floor(days/146096))/365) -- Years into 400 Year bracket[0, 399] days = days - (365*years + floor(years/4) - floor(years/100)) -- Days into year with March 1st @0 [0, 365] local month = floor((5*days + 2)/153) -- Month with March @0 [0, 11] local yDay = days days = days - floor((153*month + 2)/5) + 1 -- Days into month [1, 31] month = month + (month < 10 and 3 or -9) -- Actual month [1, 12] year = years + year*400 + (month < 3 and 1 or 0) -- Actual Year if formatString == "*t" then -- Return a table if "*t" was used return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds} end -- Necessary string tables local dayNames = {[0] = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} -- Return formatted string return (gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(formatString, "%%c", "%%x %%X"), "%%_c", "%%_x %%_X"), "%%x", "%%m/%%d/%%y"), "%%_x", "%%_m/%%_d/%%y"), "%%X", "%%H:%%M:%%S"), "%%_X", "%%_H:%%M:%%S"), "%%T", "%%I:%%M %%p"), "%%_T", "%%_I:%%M %%p"), "%%r", "%%I:%%M:%%S %%p"), "%%_r", "%%_I:%%M:%%S %%p"), "%%R", "%%H:%%M"), "%%_R", "%%_H:%%M"), "%%a", sub(dayNames[wday], 1, 3)), "%%A", dayNames[wday]), "%%b", sub(months[month], 1, 3)), "%%B", months[month]), "%%d", format("%02d", days)), "%%_d", days), "%%H", format("%02d", hours)), "%%_H", hours), "%%I", format("%02d", hours > 12 and hours - 12 or hours == 0 and 12 or hours)), "%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours), "%%j", format("%02d", yDay)), "%%_j", yDay), "%%M", format("%02d", minutes)), "%%_M", minutes), "%%m", format("%02d", month)), "%%_m", month), "%%n", "\n"), "%%p", hours >= 12 and "pm" or "am"), "%%_p", hours >= 12 and "PM" or "AM"), "%%s", (days < 21 and days > 3 or days > 23 and days < 31) and "th" or ({"st", "nd", "rd"})[days % 10]), "%%S", format("%02d", seconds)), "%%_S", seconds), "%%t", "\t"), "%%u", wday == 0 and 7 or wday), "%%w", wday), "%%Y", year), "%%y", format("%02d", year % 100)), "%%_y", year % 100), "%%%%", "%%") ) end local function clock() local timeYielded, timeServerHasBeenRunning = wait() return timeServerHasBeenRunning end return setmetatable({date = date, clock = clock}, {__index = os})
Small upgrade and annotation fix
Small upgrade and annotation fix
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
6f2255071cf0d1979a12d8372ba0e6d5dd654ff6
modules/game_questlog/questlog.lua
modules/game_questlog/questlog.lua
questLogButton = nil questLineWindow = nil function init() g_ui.importStyle('questlogwindow.otui') g_ui.importStyle('questlinewindow.otui') questLogButton = TopMenu.addLeftGameButton('questLogButton', tr('Quest Log'), 'questlog.png', function() g_game.requestQuestLog() end) connect(g_game, { onQuestLog = onGameQuestLog, onQuestLine = onGameQuestLine, onGameEnd = destroyWindows}) end function terminate() disconnect(g_game, { onQuestLog = onGameQuestLog, onQuestLine = onGameQuestLine, onGameEnd = destroyWindows}) destroyWindows() end function destroyWindows() if questLogWindow then questLogWindow:destroy() questLogWindow = nil end if questLineWindow then questLineWindow:destroy() questLineWindow = nil end end function onGameQuestLog(quests) destroyWindows() questLogWindow = g_ui.createWidget('QuestLogWindow', rootWidget) local questList = questLogWindow:getChildById('questList') for i,questEntry in pairs(quests) do local id, name, completed = unpack(questEntry) local questLabel = g_ui.createWidget('QuestLabel', questList) questLabel:setOn(completed) questLabel:setText(name) questLabel.onDoubleClick = function() questLogWindow:hide() g_game.requestQuestLine(id) end end questLogWindow.onDestroy = function() questLogWindow = nil end end function onGameQuestLine(questId, questMissions) if questLogWindow then questLogWindow:hide() end if questLineWindow then questLineWindow:destroy() end questLineWindow = g_ui.createWidget('QuestLineWindow', rootWidget) local missionList = questLineWindow:getChildById('missionList') local missionDescription = questLineWindow:getChildById('missionDescription') connect(missionList, { onChildFocusChange = function(self, focusedChild) if focusedChild == nil then return end missionDescription:setText(focusedChild.description) end }) for i,questMission in pairs(questMissions) do local name, description = unpack(questMission) local missionLabel = g_ui.createWidget('MissionLabel', missionList) missionLabel:setText(name) missionLabel.description = description end questLineWindow.onDestroy = function() if questLogWindow then questLogWindow:show() end questLineWindow = nil end end
questLogButton = nil questLineWindow = nil function init() g_ui.importStyle('questlogwindow.otui') g_ui.importStyle('questlinewindow.otui') questLogButton = TopMenu.addLeftGameButton('questLogButton', tr('Quest Log'), 'questlog.png', function() g_game.requestQuestLog() end) connect(g_game, { onQuestLog = onGameQuestLog, onQuestLine = onGameQuestLine, onGameEnd = destroyWindows}) end function terminate() disconnect(g_game, { onQuestLog = onGameQuestLog, onQuestLine = onGameQuestLine, onGameEnd = destroyWindows}) destroyWindows() end function destroyWindows() if questLogWindow then questLogWindow:destroy() questLogWindow = nil end if questLineWindow then questLineWindow:destroy() questLineWindow = nil end end function onGameQuestLog(quests) destroyWindows() questLogWindow = g_ui.createWidget('QuestLogWindow', rootWidget) local questList = questLogWindow:getChildById('questList') for i,questEntry in pairs(quests) do local id, name, completed = unpack(questEntry) local questLabel = g_ui.createWidget('QuestLabel', questList) questLabel:setOn(completed) questLabel:setText(name) questLabel.onDoubleClick = function() questLogWindow:hide() g_game.requestQuestLine(id) end end questLogWindow.onDestroy = function() questLogWindow = nil end questList:focusChild(questList:getFirstChild()) end function onGameQuestLine(questId, questMissions) if questLogWindow then questLogWindow:hide() end if questLineWindow then questLineWindow:destroy() end questLineWindow = g_ui.createWidget('QuestLineWindow', rootWidget) local missionList = questLineWindow:getChildById('missionList') local missionDescription = questLineWindow:getChildById('missionDescription') connect(missionList, { onChildFocusChange = function(self, focusedChild) if focusedChild == nil then return end missionDescription:setText(focusedChild.description) end }) for i,questMission in pairs(questMissions) do local name, description = unpack(questMission) local missionLabel = g_ui.createWidget('MissionLabel') missionLabel:setText(name) missionLabel.description = description missionList:addChild(missionLabel) end questLineWindow.onDestroy = function() if questLogWindow then questLogWindow:show() end questLineWindow = nil end missionList:focusChild(missionList:getFirstChild()) end
Fix issue #86
Fix issue #86
Lua
mit
dreamsxin/otclient,Cavitt/otclient_mapgen,gpedro/otclient,Radseq/otclient,Cavitt/otclient_mapgen,EvilHero90/otclient,EvilHero90/otclient,gpedro/otclient,dreamsxin/otclient,gpedro/otclient,kwketh/otclient,kwketh/otclient,Radseq/otclient,dreamsxin/otclient
a55cdea9a43aed54330aae4f47e6644bb18c8d63
plugins/giphy.lua
plugins/giphy.lua
local giphy = {} local HTTPS = require('ssl.https') local JSON = require('dkjson') function giphy:init(configuration) giphy.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('gif', true).table giphy.inline_triggers = giphy.triggers end function giphy:inline_callback(inline_query, configuration, matches) local input = inline_query.query:gsub('/gif ', '') local url = HTTPS.request('https://api.giphy.com/v1/gifs/search?q='..URL.escape(input)..'&api_key=dc6zaTOxFJmzC') local jdat = JSON.decode(url) local results = '[' local id = 50 for n in pairs(jdat.data) do results = results..'{"type":"mpeg4_gif","id":"'..id..'","mpeg4_url":"'..jdat.data[n].images.original.mp4..'","thumb_url":"'..jdat.data[n].images.fixed_height.url..'","mpeg4_width":'..jdat.data[n].images.original.width..',"mp4_height":'..jdat.data[n].images.original.height..'}' id = id + 1 if n < #jdat.data then results = results..',' end end local results = results..']' functions.answer_inline_query(inline_query, results, 3600) end function giphy:action() end return giphy
local giphy = {} local HTTPS = require('ssl.https') local JSON = require('dkjson') function giphy:init(configuration) giphy.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('gif', true).table giphy.inline_triggers = giphy.triggers end function giphy:inline_callback(inline_query, configuration) local jstr = HTTPS.request('https://api.giphy.com/v1/gifs/search?q=' .. inline_query.query:gsub('/gif ', '') .. '&api_key=dc6zaTOxFJmzC') local jdat = JSON.decode(jstr) local results = '[' local id = 50 for n in pairs(jdat.data) do results = results..'{"type":"mpeg4_gif","id":"'..id..'","mpeg4_url":"'..jdat.data[n].images.original.mp4..'","thumb_url":"'..jdat.data[n].images.fixed_height.url..'","mpeg4_width":'..jdat.data[n].images.original.width..',"mp4_height":'..jdat.data[n].images.original.height..'}' id = id + 1 if n < #jdat.data then results = results..',' end end local results = results..']' functions.answer_inline_query(inline_query, results, 3600) end function giphy:action() end return giphy
Minor bug fix
Minor bug fix The inline command '@mattatabot /gif <query>' now works as expected
Lua
mit
barreeeiroo/BarrePolice
cd9b1c1bf5bc60a5eeda86e96fa3f8671a1c5d15
lua/decoders/opentsdb_raw.lua
lua/decoders/opentsdb_raw.lua
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Parses an OpenTSDB (or TCollector) formatted message into Heka message Fields. Should work with various inputs, such as existing TCollector collectors spawned from ProcessInputs, or FileInputs, UdpInputs etc. Strips any (optional) leading "put "s, adds the timestamp to Heka's `Timestamp` field, the metric name and value to configurable fields (Fields[name] and Fields[data.value] by default) and any tags into separate dynamic Fields (with an optional prefix for the field name). Config: - payload_keep (bool, default false) If true, maintain the original Payload in the new message. - msg_type (string, optional default "opentsdb") Sets the message 'Type' header to the specified value. - name_field (string, optional, default "name") Field name to use for the metric name - value_field (string, optional, default "data.value") Field name to use for the metric value - tagname_prefix (string, options, default "tags.") Prefix to add to any Fields derived from tags, to make Field idenitication further down the pipeline easier. *Example Heka Configuration* .. code-block:: ini [OpenTsdbDecoder] type = "SandboxDecoder" filename = "lua_decoders/opentsdb_raw.lua" [OpenTsdbDecoder.config] payload_keep = true *Example Heka Message* 2014/12/03 19:07:52 :Timestamp: Thu Dec 18 12:24:11 +0000 UTC :Type: metric :Hostname: test.example.com :Pid: 25348 :Uuid: 190633d6-b11a-424c-ae73-3bcfb67c31fb :Logger: ProcessInput :Payload: put my.wonderful.metric 1418905451 42 product=wibble :EnvVersion: :Severity: 7 :Fields: | name:"name" type:string value:"my.wonderful.metric" | name:"tags.product" type:string value:"wibble" | name:"data.value" type:double value:42 --]] local l = require 'lpeg' local dt = require 'date_time' local tagname_prefix = read_config("tagname_prefix") or "tags." local name_field = read_config("name_field") or "name" local value_field = read_config("value_field") or "data.value" local msg_type = read_config("msg_type") or "opentsdb" local payload_keep = read_config("payload_keep") local function tagprefix(tag) if tagname_prefix then return tagname_prefix .. tag end return tag end l.locale(l) local space = l.space^1 local name = (l.alnum + l.S"-._/") ^1 local integer = l.S("-")^-1 * l.digit^1 local double = integer * ("." * integer)^0 local number = double * (l.S("Ee") * integer)^0 / tonumber local timestamp = double / dt.seconds_to_ns local metric = l.P("put ")^0 * l.Cg(name, "metric") local ts = space * l.Cg(timestamp, "timestamp") local value = space * l.Cg(number, "value") local pair = space * l.Cg(name / tagprefix * "=" * l.C(name)) local tagset = l.Cg(l.Cf(l.Ct("") * pair^0, rawset), "tags") local grammar = l.Ct(metric * ts * value * tagset) function process_message () local msg = { Type = msg_type, Fields = {} } local line = read_message("Payload") local fields = grammar:match(line) if not fields then return -1 end msg.Timestamp = fields.timestamp msg.Fields = fields.tags msg.Fields[name_field] = fields.metric msg.Fields[value_field] = fields.value if payload_keep then msg.Payload = line end inject_message(msg) return 0 end
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Parses an OpenTSDB (or TCollector) formatted message into Heka message Fields. Should work with various inputs, such as existing TCollector collectors spawned from ProcessInputs, or FileInputs, UdpInputs etc. Strips any (optional) leading "put "s, adds the timestamp to Heka's `Timestamp` field, the metric name and value to configurable fields (Fields[Metric] and Fields[Value] by default) and any "tags" into separate dynamic Fields (with an optional prefix for the field name). Config: - metric_field (string, optional, default "Metric") Field name to use for the metric name - value_field (string, optional, default "Value") Field name to use for the metric value - tag_prefix (string, options, default "") Prefix to add to any Fields derived from tags, to make Field identification further down the pipeline easier. - payload_keep (bool, default false) If true, maintain the original Payload in the new message. - msg_type (string, optional default "opentsdb") Sets the message 'Type' header to the specified value. *Example Heka Configuration* .. code-block:: ini [OpenTsdbDecoder] type = "SandboxDecoder" filename = "lua_decoders/opentsdb_raw.lua" [OpenTsdbDecoder.config] payload_keep = true *Example Heka Message* 2014/12/03 19:07:52 :Timestamp: Thu Dec 18 12:24:11 +0000 UTC :Type: metric :Hostname: test.example.com :Pid: 25348 :Uuid: 190633d6-b11a-424c-ae73-3bcfb67c31fb :Logger: ProcessInput :Payload: put my.wonderful.metric 1418905451 42 product=wibble :EnvVersion: :Severity: 7 :Fields: | name:"Metric" type:string value:"my.wonderful.metric" | name:"Value" type:double value:42 | name:"product" type:string value:"wibble" --]] local l = require 'lpeg' local dt = require 'date_time' local metric_field = read_config("metric_field") or "Metric" local value_field = read_config("value_field") or "Value" local tag_prefix = read_config("tag_prefix") local msg_type = read_config("msg_type") or "opentsdb" local payload_keep = read_config("payload_keep") local function tagprefix(tag) if tag_prefix then return tag_prefix .. tag end return tag end l.locale(l) local space = l.space^1 local name = (l.alnum + l.S"-._/") ^1 local integer = l.S("-")^-1 * l.digit^1 local double = integer * ("." * integer)^0 local number = double * (l.S("Ee") * integer)^0 / tonumber local timestamp = double / dt.seconds_to_ns local metric = l.P("put ")^0 * l.Cg(name, "metric") local ts = space * l.Cg(timestamp, "timestamp") local value = space * l.Cg(number, "value") local pair = space * l.Cg(name / tagprefix * "=" * l.C(name)) local tagset = l.Cg(l.Cf(l.Ct("") * pair^0, rawset), "tags") local grammar = l.Ct(metric * ts * value * tagset) function process_message () local msg = { Type = msg_type, Fields = {} } local line = read_message("Payload") local fields = grammar:match(line) if not fields then return -1 end msg.Timestamp = fields.timestamp msg.Fields = fields.tags msg.Fields[metric_field] = fields.metric msg.Fields[value_field] = fields.value if payload_keep then msg.Payload = line end inject_message(msg) return 0 end
Make some fields/configs more consistent
Make some fields/configs more consistent Other plugins in this repo use 'Metric', 'Value' and 'tag_prefix'.
Lua
mpl-2.0
timurb/heka-tsutils-plugins,hynd/heka-tsutils-plugins
193fded67edb7d33f65e3ebeb7b571285da5a8cd
packages/tate.lua
packages/tate.lua
-- Japaneese language support defines units which are useful here SILE.call("language", { main = "ja" }, {}) SILE.tateFramePrototype = pl.class({ _base = SILE.framePrototype, direction = "TTB-RTL", enterHooks = { function (self) self.oldtypesetter = SILE.typesetter SILE.typesetter.leadingFor = function(_, v) v.height = SILE.length("1zw"):absolute() local bls = SILE.settings.get("document.baselineskip") local d = bls.height:absolute() - v.height local len = SILE.length(d.length, bls.height.stretch, bls.height.shrink) return SILE.nodefactory.vglue({height = len}) end SILE.typesetter.breakIntoLines = SILE.require("packages/break-firstfit") end }, leaveHooks = { function (self) SILE.typesetter = self.oldtypesetter end } }) SILE.newTateFrame = function (spec) return SILE.newFrame(spec, SILE.tateFramePrototype) end SILE.registerCommand("tate-frame", function (options, _) SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newTateFrame(options) end, "Declares (or re-declares) a frame on this page.") local outputLatinInTate = function (self, typesetter, line) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.measurement("-0.5zw")) typesetter.frame:advancePageDirection(SILE.measurement("0.25zw")) local vorigin = -typesetter.frame.state.cursorY self:oldOutputYourself(typesetter,line) typesetter.frame.state.cursorY = -vorigin typesetter.frame:advanceWritingDirection(self:lineContribution()) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.measurement("0.5zw") ) typesetter.frame:advancePageDirection(-SILE.measurement("0.25zw")) end local outputTateChuYoko = function (self, typesetter, line) -- My baseline moved local em = SILE.measurement("1zw") typesetter.frame:advanceWritingDirection(-em + em/4 - self:lineContribution()/2) typesetter.frame:advancePageDirection(2*self.height - self.width/2) self:oldOutputYourself(typesetter,line) typesetter.frame:advanceWritingDirection(-self:lineContribution()*1.5+self.height*3/4) end -- Eventually will be automatically called by script detection, but for now -- called manually SILE.registerCommand("latin-in-tate", function (_, content) local nodes local oldT = SILE.typesetter local prevDirection = oldT.frame.direction if oldT.frame:writingDirection() ~= "TTB" then return SILE.process(content) end SILE.require("packages/rotate") SILE.settings.temporarily(function() local latinT = SILE.defaultTypesetter {} latinT.frame = SILE.framePrototype({}, true) -- not fully initialized, just a dummy latinT:initState() SILE.typesetter = latinT SILE.settings.set("document.language", "und") SILE.settings.set("font.direction", "LTR") SILE.process(content) nodes = SILE.typesetter.state.nodes SILE.typesetter:shapeAllNodes(nodes) SILE.typesetter.frame.direction = prevDirection end) SILE.typesetter = oldT SILE.typesetter:pushGlue({ width = SILE.length("0.5zw", "0.25zw", "0.25zw"):absolute() }) for i = 1,#nodes do if SILE.typesetter.frame:writingDirection() ~= "TTB" then SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i].is_glue then nodes[i].width = nodes[i].width SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i]:lineContribution():tonumber() > 0 then SILE.call("hbox", {}, function () SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] end) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.oldOutputYourself = n.outputYourself n.outputYourself = outputLatinInTate end end end, "Typeset rotated Western text in vertical Japanese") SILE.registerCommand("tate-chu-yoko", function (_, content) if SILE.typesetter.frame:writingDirection() ~= "TTB" then return SILE.process(content) end -- SILE.typesetter:pushGlue({ -- width = SILE.length.new({length = SILE.toPoints("0.5zw"), -- stretch = SILE.toPoints("0.25zw"), -- shrink = SILE.toPoints("0.25zw") -- }) -- }) SILE.settings.temporarily(function() SILE.settings.set("document.language", "und") SILE.settings.set("font.direction", "LTR") SILE.call("rotate",{angle =-90}, function () SILE.call("hbox", {}, content) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.misfit = true n.oldOutputYourself = n.outputYourself n.outputYourself = outputTateChuYoko end) end) -- SILE.typesetter:pushGlue({ -- width = SILE.length.new({length = SILE.toPoints("0.5zw"), -- stretch = SILE.toPoints("0.25zw"), -- shrink = SILE.toPoints("0.25zw") -- }) -- }) end)
-- Japaneese language support defines units which are useful here SILE.languageSupport.loadLanguage("ja") SILE.tateFramePrototype = pl.class({ _base = SILE.framePrototype, direction = "TTB-RTL", enterHooks = { function (self) self.oldtypesetter = SILE.typesetter SILE.typesetter.leadingFor = function(_, v) v.height = SILE.length("1zw"):absolute() local bls = SILE.settings.get("document.baselineskip") local d = bls.height:absolute() - v.height local len = SILE.length(d.length, bls.height.stretch, bls.height.shrink) return SILE.nodefactory.vglue({height = len}) end SILE.typesetter.breakIntoLines = SILE.require("packages/break-firstfit") end }, leaveHooks = { function (self) SILE.typesetter = self.oldtypesetter end } }) SILE.newTateFrame = function (spec) return SILE.newFrame(spec, SILE.tateFramePrototype) end SILE.registerCommand("tate-frame", function (options, _) SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newTateFrame(options) end, "Declares (or re-declares) a frame on this page.") local outputLatinInTate = function (self, typesetter, line) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.measurement("-0.5zw")) typesetter.frame:advancePageDirection(SILE.measurement("0.25zw")) local vorigin = -typesetter.frame.state.cursorY self:oldOutputYourself(typesetter,line) typesetter.frame.state.cursorY = -vorigin typesetter.frame:advanceWritingDirection(self:lineContribution()) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.measurement("0.5zw") ) typesetter.frame:advancePageDirection(-SILE.measurement("0.25zw")) end local outputTateChuYoko = function (self, typesetter, line) -- My baseline moved local em = SILE.measurement("1zw") typesetter.frame:advanceWritingDirection(-em + em/4 - self:lineContribution()/2) typesetter.frame:advancePageDirection(2*self.height - self.width/2) self:oldOutputYourself(typesetter,line) typesetter.frame:advanceWritingDirection(-self:lineContribution()*1.5+self.height*3/4) end -- Eventually will be automatically called by script detection, but for now -- called manually SILE.registerCommand("latin-in-tate", function (_, content) local nodes local oldT = SILE.typesetter local prevDirection = oldT.frame.direction if oldT.frame:writingDirection() ~= "TTB" then return SILE.process(content) end SILE.require("packages/rotate") SILE.settings.temporarily(function() local latinT = SILE.defaultTypesetter {} latinT.frame = SILE.framePrototype({}, true) -- not fully initialized, just a dummy latinT:initState() SILE.typesetter = latinT SILE.settings.set("document.language", "und") SILE.settings.set("font.direction", "LTR") SILE.process(content) nodes = SILE.typesetter.state.nodes SILE.typesetter:shapeAllNodes(nodes) SILE.typesetter.frame.direction = prevDirection end) SILE.typesetter = oldT SILE.typesetter:pushGlue({ width = SILE.length("0.5zw", "0.25zw", "0.25zw"):absolute() }) for i = 1,#nodes do if SILE.typesetter.frame:writingDirection() ~= "TTB" then SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i].is_glue then nodes[i].width = nodes[i].width SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i]:lineContribution():tonumber() > 0 then SILE.call("hbox", {}, function () SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] end) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.oldOutputYourself = n.outputYourself n.outputYourself = outputLatinInTate end end end, "Typeset rotated Western text in vertical Japanese") SILE.registerCommand("tate-chu-yoko", function (_, content) if SILE.typesetter.frame:writingDirection() ~= "TTB" then return SILE.process(content) end -- SILE.typesetter:pushGlue({ -- width = SILE.length.new({length = SILE.toPoints("0.5zw"), -- stretch = SILE.toPoints("0.25zw"), -- shrink = SILE.toPoints("0.25zw") -- }) -- }) SILE.settings.temporarily(function() SILE.settings.set("document.language", "und") SILE.settings.set("font.direction", "LTR") SILE.call("rotate",{angle =-90}, function () SILE.call("hbox", {}, content) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.misfit = true n.oldOutputYourself = n.outputYourself n.outputYourself = outputTateChuYoko end) end) -- SILE.typesetter:pushGlue({ -- width = SILE.length.new({length = SILE.toPoints("0.5zw"), -- stretch = SILE.toPoints("0.25zw"), -- shrink = SILE.toPoints("0.25zw") -- }) -- }) end)
fix(packages): Tate should not affect document language (#932)
fix(packages): Tate should not affect document language (#932)
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
6587769e23532a721dcc214a2db86a3ffc431d9d
GameServer/Content/Data/LeagueSandbox-Default/Champions/Lucian/E.lua
GameServer/Content/Data/LeagueSandbox-Default/Champions/Lucian/E.lua
Vector2 = require 'Vector2' -- include 2d vector lib function onFinishCasting() local current = Vector2:new(getOwnerX(), getOwnerY()) local to = (Vector2:new(getSpellToX(), getSpellToY()) - current):normalize() local range = to * 445 local trueCoords = current + range printChat("You used E"); addParticle(getOwner(), "Lucian_E_Buf.troy", getOwnerX(), getOwnerY()); addParticleTarget(getOwner(), "Lucian_E_Buf.troy", getOwner()) -- ============================================================================== -- WARNING WARNING WARNING WARNING -- DASHTO HAS A VISUAL BUG WHICH TELEPORTS THE PLAYER TO THE MIDDLE OF THE MAP -- WHEN YOU CLICK TO MOVE THE VISUAL BUG DISSAPEARS -- ============================================================================== dashTo(getOwner(), trueCoords.x, trueCoords.y, 1000); spellAnimation("Spell3", getOwner()) end function applyEffects() destroyProjectile() end
Vector2 = require 'Vector2' -- include 2d vector lib function onFinishCasting() local current = Vector2:new(getOwnerX(), getOwnerY()) local to = (Vector2:new(getSpellToX(), getSpellToY()) - current):normalize() local range = to * 445 local trueCoords = current + range printChat("You used EV3") -- ============================================================================== -- WARNING WARNING WARNING WARNING -- DASHTO HAS A VISUAL BUG WHICH TELEPORTS THE PLAYER TO THE MIDDLE OF THE MAP -- WHEN YOU CLICK TO MOVE THE VISUAL BUG DISSAPEARS -- ============================================================================== dashTo(getOwner(), trueCoords.x, trueCoords.y, 1000) spellAnimation("Spell3", getOwner()) end function applyEffects() end
E works perfect with "dash-fix"
E works perfect with "dash-fix" E works perfect with "dash-fix" except the effects (which never worked)
Lua
agpl-3.0
LeagueSandbox/GameServer
27423ca7bc65ff95b51c21bfc1fe709d151c963e
projects/premake4.lua
projects/premake4.lua
solution "ElTrazadoDeRayos" language "C++" location("./" .. _ACTION) -- Where to put the project files. includedirs {"../include", "../include/glm", "../src/**"} libdirs {"../lib"} flags {"StaticRuntime"} -- Add the c++ 11 standard if we use gmake. if (_ACTION == "gmake") then buildoptions {"-std=c++0x -std=gnu++0x"} end -- Define which OS we use. if os.get() == "windows" then defines {"WINDOWS"} elseif os.get() == "linux" then defines {"LINUX"} elseif os.get() == "macosx" then defines {"MACOSX"} end -- Configurations. configurations {"Release", "Debug", "Profile"} -- Platforms platforms { "native", "universal" } -- platforms {"x32", "x64"} configuration "Release" defines {"NDEBUG", "PASTEL_ENABLE_OMP" } flags {"Optimize"} targetdir "../bin/release" configuration { "gmake", "release" } buildoptions { "-fopenmp" } links { "gomp" } configuration "Debug" defines {"DEBUG"} flags {"Symbols"} targetdir "../bin/debug" links { "gomp" } configuration "Profile" defines {"PROF", "PASTEL_ENABLE_OMP"} flags {"Symbols", "Optimize"} buildoptions{ "-pg", "-fopenmp" } links { "gomp" } linkoptions( "-pg" ) targetdir "../bin/prof" -- Enable openmp for visual studio project files. configuration { "vs*", "release" } buildoptions { "/openmp" } -- Projects. project "ElTrazadoDeRayosLib" files {"../src/RayTracerLib/**"} kind "StaticLib" if os.get() == "windows" then postbuildcommands { "py ..\\cpplintHelper.py --root=src ..\\..\\src\\RayTracerLib" } elseif os.get() == "linux" then postbuildcommands { "-@python2 ../cpplintHelper.py --root=src ../../src/RayTracerLib > /dev/null" } end -- This is nice to have so VS always uses the same uuids in its project files. -- Generated via http://www.uuidgenerator.net uuid("f2a30267-2beb-426c-9fc1-cc24c4ba9d21") project "ConsoleMain" files {"../src/ConsoleMain/**"} kind "ConsoleApp" links {"ElTrazadoDeRayosLib"} if os.get() == "windows" then postbuildcommands { "py ..\\cpplintHelper.py --root=src ..\\..\\src\\ConsoleMain" } elseif os.get() == "linux" then postbuildcommands { "-@python2 ../cpplintHelper.py --root=src ../../src/ConsoleMain > /dev/null" } end -- This is nice to have so VS always uses the same uuids in its project files. -- Generated via http://www.uuidgenerator.net uuid("865dfdb0-97ae-4dce-b70f-9d4a11413162")
solution "ElTrazadoDeRayos" language "C++" location("./" .. _ACTION) -- Where to put the project files. includedirs {"../include", "../include/glm", "../src/**"} libdirs {"../lib"} flags {"StaticRuntime"} -- Add the c++ 11 standard if we use gmake. if (_ACTION == "gmake") then buildoptions {"-std=c++0x -std=gnu++0x"} end -- Define which OS we use. if os.get() == "windows" then defines {"WINDOWS"} elseif os.get() == "linux" then defines {"LINUX"} elseif os.get() == "macosx" then defines {"MACOSX"} end -- Configurations. configurations {"Release", "Debug", "Profile"} -- Platforms platforms { "native", "universal" } -- platforms {"x32", "x64"} configuration "Release" defines {"NDEBUG", "PASTEL_ENABLE_OMP" } flags {"Optimize"} targetdir "../bin/release" configuration { "gmake", "release" } buildoptions { "-fopenmp" } links { "gomp" } configuration "Debug" defines {"DEBUG"} flags {"Symbols"} targetdir "../bin/debug" configuration { "gmake", "Debug" } links { "gomp" } configuration "Profile" defines {"PROF", "PASTEL_ENABLE_OMP"} flags {"Symbols", "Optimize"} targetdir "../bin/prof" configuration { "gmake", "Profile" } buildoptions{ "-pg", "-fopenmp" } links { "gomp" } linkoptions( "-pg" ) -- Enable openmp for visual studio project files. configuration { "vs*", "release" } buildoptions { "/openmp" } -- Projects. project "ElTrazadoDeRayosLib" files {"../src/RayTracerLib/**"} kind "StaticLib" if os.get() == "windows" then postbuildcommands { "py ..\\cpplintHelper.py --root=src ..\\..\\src\\RayTracerLib" } elseif os.get() == "linux" then postbuildcommands { "-@python2 ../cpplintHelper.py --root=src ../../src/RayTracerLib > /dev/null" } end -- This is nice to have so VS always uses the same uuids in its project files. -- Generated via http://www.uuidgenerator.net uuid("f2a30267-2beb-426c-9fc1-cc24c4ba9d21") project "ConsoleMain" files {"../src/ConsoleMain/**"} kind "ConsoleApp" links {"ElTrazadoDeRayosLib"} if os.get() == "windows" then postbuildcommands { "py ..\\cpplintHelper.py --root=src ..\\..\\src\\ConsoleMain" } elseif os.get() == "linux" then postbuildcommands { "-@python2 ../cpplintHelper.py --root=src ../../src/ConsoleMain > /dev/null" } end -- This is nice to have so VS always uses the same uuids in its project files. -- Generated via http://www.uuidgenerator.net uuid("865dfdb0-97ae-4dce-b70f-9d4a11413162")
fixed some linux only commands in debug and profile configuration
fixed some linux only commands in debug and profile configuration
Lua
mit
CantTouchDis/ElTrazadoDeRayos,CantTouchDis/ElTrazadoDeRayos,CantTouchDis/ElTrazadoDeRayos,CantTouchDis/ElTrazadoDeRayos,CantTouchDis/ElTrazadoDeRayos
1fd25814aaa4149c0b12ba64f60d09f2c9069aad
plugins/shell.lua
plugins/shell.lua
local triggers = { '^/run[@'..bot.username..']*' } local action = function(msg) if msg.from.id ~= config.admin then return end local input = msg.text:input() if not input then sendReply(msg, 'Please specify a command to run.') return end local output = io.popen(input):read('*all') if output:len() == 0 then output = 'Done!' else output = '```\n' .. output .. '\n```' end sendMessage(msg.chat.id, output, true, msg.message_id, true) end return { action = action, triggers = triggers }
local triggers = { '^/run[@'..bot.username..']*' } local action = function(msg) if msg.from.id ~= config.admin then return end local input = msg.text:input() input = input:gsub('—', '--') if not input then sendReply(msg, 'Please specify a command to run.') return end local output = io.popen(input):read('*all') if output:len() == 0 then output = 'Done!' else output = '```\n' .. output .. '\n```' end sendMessage(msg.chat.id, output, true, msg.message_id, true) end return { action = action, triggers = triggers }
FIX Shell
FIX Shell
Lua
mit
barreeeiroo/BarrePolice,TiagoDanin/SiD,Brawl345/Brawlbot-v2,topkecleon/otouto,bb010g/otouto
f252439e4a85da2acd58fa5edbcce6db28de664c
lib/datatypes.lua
lib/datatypes.lua
local LXSC = require 'lib/lxsc' LXSC.OrderedSet = {_kind='OrderedSet'}; LXSC.OrderedSet.__meta = {__index=LXSC.OrderedSet} setmetatable(LXSC.OrderedSet,{__call=function(o) return setmetatable({},o.__meta) end}) function LXSC.OrderedSet:add(e) if not self[e] then local idx = #self+1 self[idx] = e self[e] = idx end end function LXSC.OrderedSet:delete(e) local index = self[e] if index then table.remove(self,index) self[e] = nil for i,o in ipairs(self) do self[o]=i end -- Store new indexes end end function LXSC.OrderedSet:union(set2) local i=#self for _,e in ipairs(set2) do if not self[e] then i = i+1 self[i] = e self[e] = i end end end function LXSC.OrderedSet:isMember(e) return self[e] end function LXSC.OrderedSet:some(f) for _,o in ipairs(self) do if f(o) then return true end end end function LXSC.OrderedSet:isEmpty() return not self[1] end function LXSC.OrderedSet:clear() for k,v in pairs(self) do self[k]=nil end end function LXSC.OrderedSet:toList() return LXSC.List(unpack(self)) end function LXSC.OrderedSet:hasIntersection(set2) for e,_ in pairs(self) do if set2[e] then return true end end return false end function LXSC.OrderedSet:inspect() local t = {} for i,v in ipairs(self) do t[i] = v.inspect and v:inspect() or tostring(v) end return t[1] and "{ "..table.concat(t,', ').." }" or '{}' end -- ******************************************************************* LXSC.List = {_kind='List'}; LXSC.List.__meta = {__index=LXSC.List} setmetatable(LXSC.List,{__call=function(o,...) return setmetatable({...},o.__meta) end}) function LXSC.List:head() return self[1] end function LXSC.List:tail() local l = LXSC.List(unpack(self)) table.remove(l,1) return l end function LXSC.List:append(...) local len=#self for i,v in ipairs{...} do self[len+i] = v end return self end function LXSC.List:filter(f) local t={} local i=1 for _,v in ipairs(self) do if f(v) then t[i]=v; i=i+1 end end return LXSC.List(unpack(t)) end function LXSC.List:some(f) for _,v in ipairs(self) do if f(v) then return true end end end function LXSC.List:every(f) for _,v in ipairs(self) do if not f(v) then return false end end return true end function LXSC.List:sort(f) table.sort(self,f) return self end LXSC.List.inspect = LXSC.OrderedSet.inspect -- ******************************************************************* LXSC.Queue = {_kind='Queue'}; LXSC.Queue.__meta = {__index=LXSC.Queue} setmetatable(LXSC.Queue,{__call=function(o) return setmetatable({},o.__meta) end}) function LXSC.Queue:enqueue(e) self[#self+1] = e end function LXSC.Queue:dequeue() return table.remove(self,1) end function LXSC.Queue:isEmpty() return not self[1] end LXSC.Queue.inspect = LXSC.OrderedSet.inspect
local LXSC = require 'lib/lxsc' LXSC.OrderedSet = {_kind='OrderedSet'}; LXSC.OrderedSet.__meta = {__index=LXSC.OrderedSet} setmetatable(LXSC.OrderedSet,{__call=function(o) return setmetatable({},o.__meta) end}) function LXSC.OrderedSet:add(e) if not self[e] then local idx = #self+1 self[idx] = e self[e] = idx end end function LXSC.OrderedSet:delete(e) local index = self[e] if index then table.remove(self,index) self[e] = nil for i,o in ipairs(self) do self[o]=i end -- Store new indexes end end function LXSC.OrderedSet:union(set2) local i=#self for _,e in ipairs(set2) do if not self[e] then i = i+1 self[i] = e self[e] = i end end end function LXSC.OrderedSet:isMember(e) return self[e] end function LXSC.OrderedSet:some(f) for _,o in ipairs(self) do if f(o) then return true end end end function LXSC.OrderedSet:isEmpty() return not self[1] end function LXSC.OrderedSet:clear() for k,v in pairs(self) do self[k]=nil end end function LXSC.OrderedSet:toList() return LXSC.List(unpack(self)) end function LXSC.OrderedSet:hasIntersection(set2) if #self<#set2 then for _,e in ipairs(self) do if set2[e] then return true end end else for _,e in ipairs(set2) do if self[e] then return true end end end return false end function LXSC.OrderedSet:inspect() local t = {} for i,v in ipairs(self) do t[i] = v.inspect and v:inspect() or tostring(v) end return t[1] and "{ "..table.concat(t,', ').." }" or '{}' end -- ******************************************************************* LXSC.List = {_kind='List'}; LXSC.List.__meta = {__index=LXSC.List} setmetatable(LXSC.List,{__call=function(o,...) return setmetatable({...},o.__meta) end}) function LXSC.List:head() return self[1] end function LXSC.List:tail() local l = LXSC.List(unpack(self)) table.remove(l,1) return l end function LXSC.List:append(...) local len=#self for i,v in ipairs{...} do self[len+i] = v end return self end function LXSC.List:filter(f) local t={} local i=1 for _,v in ipairs(self) do if f(v) then t[i]=v; i=i+1 end end return LXSC.List(unpack(t)) end function LXSC.List:some(f) for _,v in ipairs(self) do if f(v) then return true end end end function LXSC.List:every(f) for _,v in ipairs(self) do if not f(v) then return false end end return true end function LXSC.List:sort(f) table.sort(self,f) return self end LXSC.List.inspect = LXSC.OrderedSet.inspect -- ******************************************************************* LXSC.Queue = {_kind='Queue'}; LXSC.Queue.__meta = {__index=LXSC.Queue} setmetatable(LXSC.Queue,{__call=function(o) return setmetatable({},o.__meta) end}) function LXSC.Queue:enqueue(e) self[#self+1] = e end function LXSC.Queue:dequeue() return table.remove(self,1) end function LXSC.Queue:isEmpty() return not self[1] end LXSC.Queue.inspect = LXSC.OrderedSet.inspect
Fix serious bug in OrderedSet:hasIntersection()
Fix serious bug in OrderedSet:hasIntersection()
Lua
mit
Phrogz/LXSC
30fbac75ac7f48cf50dcf9c628c020b59d26c764
modules/luci-mod-freifunk/luasrc/model/cbi/freifunk/basics.lua
modules/luci-mod-freifunk/luasrc/model/cbi/freifunk/basics.lua
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Manuel Munz <freifunk at somakoma de> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local util = require "luci.util" local uci = require "luci.model.uci".cursor() local profiles = "/etc/config/profile_*" m = Map("freifunk", translate ("Community")) c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router.")) community = c:option(ListValue, "name", translate ("Community")) community.rmempty = false local profile for profile in fs.glob(profiles) do local name = uci:get_first(profile, "community", "name") or "?" community:value(profile, name) end n = Map("system", translate("Basic system settings")) function n.on_after_commit(self) luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics")) end b = n:section(TypedSection, "system") b.anonymous = true hn = b:option(Value, "hostname", translate("Hostname")) hn.rmempty = false hn.datatype = "hostname" loc = b:option(Value, "location", translate("Location")) loc.rmempty = false loc.datatype = "minlength(1)" lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345") lat.datatype = "float" lat.rmempty = false lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345") lon.datatype = "float" lon.rmempty = false --[[ Opens an OpenStreetMap iframe or popup Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js ]]-- local class = util.class local ff = uci:get("freifunk", "community", "name") or "" local co = "profile_" .. ff local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52 local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10 local zoom = 12 if ( deflat == 52 and deflon == 10 ) then zoom = 4 end OpenStreetMapLonLat = luci.util.class(AbstractValue) function OpenStreetMapLonLat.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/osmll_value" self.latfield = nil self.lonfield = nil self.centerlat = "" self.centerlon = "" self.zoom = "0" self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100" self.height = "600" self.popup = false self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap self.hidetext="X" -- text on button, that hides OSMap end osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet.")) osm.latfield = "latitude" osm.lonfield = "longitude" osm.centerlat = uci:get_first("system", "system", "latitude") or deflat osm.centerlon = uci:get_first("system", "system", "longitude") or deflon osm.zoom = zoom osm.width = "100%" osm.height = "600" osm.popup = false osm.displaytext=translate("Show OpenStreetMap") osm.hidetext=translate("Hide OpenStreetMap") return m, n
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Manuel Munz <freifunk at somakoma de> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local util = require "luci.util" local uci = require "luci.model.uci".cursor() local profiles = "/etc/config/profile_*" m = Map("freifunk", translate ("Community")) c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router.")) community = c:option(ListValue, "name", translate ("Community")) community.rmempty = false local profile for profile in fs.glob(profiles) do local name = uci:get_first(profile, "community", "name") or "?" community:value(string.gsub(profile, "/etc/config/profile_", ""), name) end n = Map("system", translate("Basic system settings")) function n.on_after_commit(self) luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics")) end b = n:section(TypedSection, "system") b.anonymous = true hn = b:option(Value, "hostname", translate("Hostname")) hn.rmempty = false hn.datatype = "hostname" loc = b:option(Value, "location", translate("Location")) loc.rmempty = false loc.datatype = "minlength(1)" lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345") lat.datatype = "float" lat.rmempty = false lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345") lon.datatype = "float" lon.rmempty = false --[[ Opens an OpenStreetMap iframe or popup Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js ]]-- local class = util.class local ff = uci:get("freifunk", "community", "name") or "" local co = "profile_" .. ff local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52 local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10 local zoom = 12 if ( deflat == 52 and deflon == 10 ) then zoom = 4 end OpenStreetMapLonLat = luci.util.class(AbstractValue) function OpenStreetMapLonLat.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/osmll_value" self.latfield = nil self.lonfield = nil self.centerlat = "" self.centerlon = "" self.zoom = "0" self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100" self.height = "600" self.popup = false self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap self.hidetext="X" -- text on button, that hides OSMap end osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet.")) osm.latfield = "latitude" osm.lonfield = "longitude" osm.centerlat = uci:get_first("system", "system", "latitude") or deflat osm.centerlon = uci:get_first("system", "system", "longitude") or deflon osm.zoom = zoom osm.width = "100%" osm.height = "600" osm.popup = false osm.displaytext=translate("Show OpenStreetMap") osm.hidetext=translate("Hide OpenStreetMap") return m, n
luci-mod-freifunk: fix lookup of community-name
luci-mod-freifunk: fix lookup of community-name restore the lookup of the freifunk community-name stored in uci "freifunk.community.name". In https://github.com/openwrt/luci/commit/9780ee382e72f8a5fb69e337a3fcc51fc0914883 the value changed to the complete path of the community-profile, e.g. "/etc/config/profile_berlin". This causes lookup problems on other pages, like "mod-freifunk -> overview -> index" (view/freifunk/index.htm line37, line 54). And as the option suggests it's the community-name not the community-profile path. This is a backport of https://github.com/openwrt/luci/commit/61c7157a66b4bbce7d110cc0de8164bd2bd57798 Signed-off-by: Sven Roederer <f304a8489b18cb178859c91cbdfec17ca74fbd64@geroedel.de>
Lua
apache-2.0
db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,RuiChen1113/luci,RuiChen1113/luci,RuiChen1113/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci
f44e086e70cb219e15ecfcab1005e2ec94c9007c
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
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.") --Requires FW 1.0166 or greater on the T7 --Gets a setpoint from a host computer. Host computer writes new setpoint to modbus address 46000 local timeStep = 100 --timestep of the loop in ms, change according to your process (see theory on sampling rate in PID control) local setpoint = 0 local inputV = 0 local outputV = 0 local kp = 0.1 --change the PID terms according to your process local ki = 0.1 local kd = 0.01 local outputMin = 0 --bounds for the output value local outputMax = 5 local lastInput = 0 local intterm = 0 local difterm = 0 LJ.IntervalConfig(0, timeStep) --set interval to 100 for 100ms local checkInterval = LJ.CheckInterval --create local functions setpoint = MB.readName("USER_RAM0_F32") if setpoint > outputMax then setpoint = outputMax MB.writeName("USER_RAM0_F32", setpoint) elseif setpoint < outputMin then setpoint = outputMin 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) --Set DAC0 i = 0 while true do if checkInterval(0) then --interval completed i = i + 1 setpoint = MB.readName("USER_RAM0_F32") --get new setpoint from USER_RAM0_F32, address 46000 if setpoint > outputMax then setpoint = outputMax MB.writeName("USER_RAM0_F32", setpoint) elseif setpoint < outputMin then setpoint = outputMin MB.writeName("USER_RAM0_F32", setpoint) end print("Setpoint: ", setpoint) inputV = MB.readName("AIN2") --read AIN2 as the feedback source print("AIN2 =", inputV, "V") err = setpoint - inputV print("The error is ", err) intterm = intterm + ki * err if intterm > outputMax then intterm = outputMax elseif intterm < outputMin then intterm = outputMin end print("The Int term is ", intterm) difterm = inputV - lastInput print("The Diff term is ", difterm) outputV = kp * err + intterm - kd * difterm if outputV > outputMax then outputV = outputMax elseif outputV < outputMin then outputV = outputMin end print("The output is ", outputV) MB.writeName("DAC0") --Set DAC0 lastInput = inputV 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 formatting of the PID example
Fixed formatting of the PID example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
398dd163dd55ee165c23e420b39ce1beac6bf29d
src/core/main.lua
src/core/main.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Default to not using any Lua code on the filesystem. -- (Can be overridden with -P argument: see below.) package.path = '' local STP = require("lib.lua.StackTracePlus") local ffi = require("ffi") local zone = require("jit.zone") local lib = require("core.lib") local shm = require("core.shm") local C = ffi.C -- Load ljsyscall early to help detect conflicts -- (e.g. FFI type name conflict between Snabb and ljsyscall) local S = require("syscall") require("lib.lua.strict") require("lib.lua.class") -- Reserve names that we want to use for global module. -- (This way we avoid errors from the 'strict' module.) _G.config, _G.engine, _G.memory, _G.link, _G.packet, _G.timer, _G.main = nil ffi.cdef[[ extern int argc; extern char** argv; ]] _G.developer_debug = lib.getenv("SNABB_DEBUG") and true debug_on_error = _G.developer_debug function main () zone("startup") require "lib.lua.strict" -- Warn on unsupported platforms if ffi.arch ~= 'x64' or ffi.os ~= 'Linux' then error("fatal: "..ffi.os.."/"..ffi.arch.." is not a supported platform\n") end initialize() local program, args = select_program(parse_command_line()) if not lib.have_module(modulename(program)) then print("unsupported program: "..program:gsub("_", "-")) usage(1) else require(modulename(program)).run(args) end end -- Take the program name from the first argument, unless the first -- argument is "snabb", in which case pop it off, handle any options -- passed to snabb itself, and use the next argument. function select_program (args) local program = programname(table.remove(args, 1)) if program == 'snabb' then while #args > 0 and args[1]:match('^-') do local opt = table.remove(args, 1) if opt == '-h' or opt == '--help' then usage(0) else print("unrecognized option: "..opt) usage(1) end end if #args == 0 then usage(1) end program = programname(table.remove(args, 1)) end return program, args end function usage (status) print("Usage: "..ffi.string(C.argv[0]).." <program> ...") local programs = require("programs_inc"):gsub("%S+", " %1") print() print("This snabb executable has the following programs built in:") print(programs) print("For detailed usage of any program run:") print(" snabb <program> --help") print() print("If you rename (or copy or symlink) this executable with one of") print("the names above then that program will be chosen automatically.") os.exit(status) end function programname (name) return name:gsub("^.*/", "") :gsub("-[0-9.]+[-%w]+$", "") :gsub("-", "_") :gsub("^snabb_", "") end function modulename (program) program = programname(program) return ("program.%s.%s"):format(program, program) end -- Return all command-line paramters (argv) in an array. function parse_command_line () local array = {} for i = 0, C.argc - 1 do table.insert(array, ffi.string(C.argv[i])) end return array end function exit (status) os.exit(status) end --- Globally initialize some things. Module can depend on this being done. function initialize () require("core.lib") require("core.clib_h") require("core.lib_h") -- Global API _G.config = require("core.config") _G.engine = require("core.app") _G.memory = require("core.memory") _G.link = require("core.link") _G.packet = require("core.packet") _G.timer = require("core.timer") _G.main = getfenv() end function handler (reason) print(reason) print(debug.traceback()) if debug_on_error then debug.debug() end os.exit(1) end -- Cleanup after Snabb process. function shutdown (pid) if not _G.developer_debug then shm.unlink("//"..pid) end end function selftest () print("selftest") assert(programname("/bin/snabb-1.0") == "snabb", "Incorrect program name parsing") assert(programname("/bin/snabb-1.0-alpha2") == "snabb", "Incorrect program name parsing") assert(programname("/bin/snabb-nfv") == "nfv", "Incorrect program name parsing") assert(programname("/bin/nfv-1.0") == "nfv", "Incorrect program name parsing") assert(modulename("nfv-sync-master-2.0") == "program.nfv_sync_master.nfv_sync_master", "Incorrect module name parsing") local pn = programname -- snabb foo => foo assert(select_program({ 'foo' }) == "foo", "Incorrect program name selected") -- snabb-foo => foo assert(select_program({ 'snabb-foo' }) == "foo", "Incorrect program name selected") -- snabb snabb-foo => foo assert(select_program({ 'snabb', 'snabb-foo' }) == "foo", "Incorrect program name selected") end -- Fork into worker process and supervisor local worker_pid = S.fork() if worker_pid == 0 then -- Worker: Use prctl to ensure we are killed (SIGHUP) when our parent quits -- and run main. S.prctl("set_pdeathsig", "hup") xpcall(main, handler) else -- Supervisor: Queue exit_signals using signalfd, prevent them from killing -- us instantly using sigprocmask. local exit_signals = "hup, int, quit, term, chld" local signalfd = S.signalfd(exit_signals) S.sigprocmask("block", exit_signals) while true do -- Read signals from signalfd. Only process the first signal because any -- signal causes shutdown. local signals, err = S.util.signalfd_read(signalfd) assert(signals, tostring(err)) for i = 1, #signals do local exit_status if signals[i].chld then -- SIGCHILD means worker state changed: retrieve its status using -- waitpid and set exit status accordingly. local status, err, worker = S.waitpid(worker_pid, "stopped,continued") assert(status, tostring(err)) if worker.WIFEXITED then exit_status = worker.EXITSTATUS elseif worker.WIFSIGNALED then exit_status = 128 + worker.WTERMSIG -- WIFSTOPPED and WIFCONTINUED are ignored. else goto ignore_signal end else -- Supervisor received exit signal: kill worker by sending SIGHUP -- and and set exit status accordingly. S.kill(worker_pid, "hup") exit_status = 128 + signals[i].signo end -- Run shutdown routine and exit. shutdown(worker_pid) os.exit(exit_status) ::ignore_signal:: end end end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Default to not using any Lua code on the filesystem. -- (Can be overridden with -P argument: see below.) package.path = '' local STP = require("lib.lua.StackTracePlus") local ffi = require("ffi") local zone = require("jit.zone") local lib = require("core.lib") local shm = require("core.shm") local C = ffi.C -- Load ljsyscall early to help detect conflicts -- (e.g. FFI type name conflict between Snabb and ljsyscall) local S = require("syscall") require("lib.lua.strict") require("lib.lua.class") -- Reserve names that we want to use for global module. -- (This way we avoid errors from the 'strict' module.) _G.config, _G.engine, _G.memory, _G.link, _G.packet, _G.timer, _G.main = nil ffi.cdef[[ extern int argc; extern char** argv; ]] -- Enable developer-level debug if SNABB_DEBUG env variable is set. _G.developer_debug = lib.getenv("SNABB_DEBUG") ~= nil debug_on_error = _G.developer_debug function main () zone("startup") require "lib.lua.strict" -- Warn on unsupported platforms if ffi.arch ~= 'x64' or ffi.os ~= 'Linux' then error("fatal: "..ffi.os.."/"..ffi.arch.." is not a supported platform\n") end initialize() local program, args = select_program(parse_command_line()) if not lib.have_module(modulename(program)) then print("unsupported program: "..program:gsub("_", "-")) usage(1) else require(modulename(program)).run(args) end end -- Take the program name from the first argument, unless the first -- argument is "snabb", in which case pop it off, handle any options -- passed to snabb itself, and use the next argument. function select_program (args) local program = programname(table.remove(args, 1)) if program == 'snabb' then while #args > 0 and args[1]:match('^-') do local opt = table.remove(args, 1) if opt == '-h' or opt == '--help' then usage(0) else print("unrecognized option: "..opt) usage(1) end end if #args == 0 then usage(1) end program = programname(table.remove(args, 1)) end return program, args end function usage (status) print("Usage: "..ffi.string(C.argv[0]).." <program> ...") local programs = require("programs_inc"):gsub("%S+", " %1") print() print("This snabb executable has the following programs built in:") print(programs) print("For detailed usage of any program run:") print(" snabb <program> --help") print() print("If you rename (or copy or symlink) this executable with one of") print("the names above then that program will be chosen automatically.") os.exit(status) end function programname (name) return name:gsub("^.*/", "") :gsub("-[0-9.]+[-%w]+$", "") :gsub("-", "_") :gsub("^snabb_", "") end function modulename (program) program = programname(program) return ("program.%s.%s"):format(program, program) end -- Return all command-line paramters (argv) in an array. function parse_command_line () local array = {} for i = 0, C.argc - 1 do table.insert(array, ffi.string(C.argv[i])) end return array end function exit (status) os.exit(status) end --- Globally initialize some things. Module can depend on this being done. function initialize () require("core.lib") require("core.clib_h") require("core.lib_h") -- Global API _G.config = require("core.config") _G.engine = require("core.app") _G.memory = require("core.memory") _G.link = require("core.link") _G.packet = require("core.packet") _G.timer = require("core.timer") _G.main = getfenv() end function handler (reason) print(reason) print(debug.traceback()) if debug_on_error then debug.debug() end os.exit(1) end -- Cleanup after Snabb process. function shutdown (pid) if not _G.developer_debug then shm.unlink("//"..pid) end end function selftest () print("selftest") assert(programname("/bin/snabb-1.0") == "snabb", "Incorrect program name parsing") assert(programname("/bin/snabb-1.0-alpha2") == "snabb", "Incorrect program name parsing") assert(programname("/bin/snabb-nfv") == "nfv", "Incorrect program name parsing") assert(programname("/bin/nfv-1.0") == "nfv", "Incorrect program name parsing") assert(modulename("nfv-sync-master-2.0") == "program.nfv_sync_master.nfv_sync_master", "Incorrect module name parsing") local pn = programname -- snabb foo => foo assert(select_program({ 'foo' }) == "foo", "Incorrect program name selected") -- snabb-foo => foo assert(select_program({ 'snabb-foo' }) == "foo", "Incorrect program name selected") -- snabb snabb-foo => foo assert(select_program({ 'snabb', 'snabb-foo' }) == "foo", "Incorrect program name selected") end -- Fork into worker process and supervisor local worker_pid = S.fork() if worker_pid == 0 then -- Worker: Use prctl to ensure we are killed (SIGHUP) when our parent quits -- and run main. S.prctl("set_pdeathsig", "hup") xpcall(main, handler) else -- Supervisor: Queue exit_signals using signalfd, prevent them from killing -- us instantly using sigprocmask. local exit_signals = "hup, int, quit, term, chld" local signalfd = S.signalfd(exit_signals) S.sigprocmask("block", exit_signals) while true do -- Read signals from signalfd. Only process the first signal because any -- signal causes shutdown. local signals, err = S.util.signalfd_read(signalfd) assert(signals, tostring(err)) for i = 1, #signals do local exit_status if signals[i].chld then -- SIGCHILD means worker state changed: retrieve its status using -- waitpid and set exit status accordingly. local status, err, worker = S.waitpid(worker_pid, "stopped,continued") assert(status, tostring(err)) if worker.WIFEXITED then exit_status = worker.EXITSTATUS elseif worker.WIFSIGNALED then exit_status = 128 + worker.WTERMSIG -- WIFSTOPPED and WIFCONTINUED are ignored. else goto ignore_signal end else -- Supervisor received exit signal: kill worker by sending SIGHUP -- and and set exit status accordingly. S.kill(worker_pid, "hup") exit_status = 128 + signals[i].signo end -- Run shutdown routine and exit. shutdown(worker_pid) os.exit(exit_status) ::ignore_signal:: end end end
core.main: Fix bug in SNABB_DEBUG env var handling
core.main: Fix bug in SNABB_DEBUG env var handling Bug was to set _G.developer_debug to nil when debugging is disabled. In Lua you cannot use nil as a table value and should use false instead. Further discussion at: https://github.com/snabbco/snabb/pull/956#issuecomment-229893468
Lua
apache-2.0
Igalia/snabbswitch,Igalia/snabbswitch,wingo/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,wingo/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,heryii/snabb,eugeneia/snabb,heryii/snabb,eugeneia/snabb,Igalia/snabb,kbara/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,dpino/snabbswitch,Igalia/snabb,kbara/snabb,alexandergall/snabbswitch,Igalia/snabb,heryii/snabb,wingo/snabb,alexandergall/snabbswitch,Igalia/snabb,wingo/snabb,dpino/snabb,dpino/snabb,wingo/snabb,snabbco/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,dpino/snabb,alexandergall/snabbswitch,mixflowtech/logsensor,dpino/snabb,kbara/snabb,eugeneia/snabbswitch,dpino/snabb,dpino/snabb,eugeneia/snabb,mixflowtech/logsensor,eugeneia/snabb,mixflowtech/logsensor,Igalia/snabb,Igalia/snabb,wingo/snabbswitch,heryii/snabb,kbara/snabb,alexandergall/snabbswitch,wingo/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,dpino/snabb,heryii/snabb,wingo/snabb,Igalia/snabb,mixflowtech/logsensor,snabbco/snabb,heryii/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,wingo/snabb,kbara/snabb,wingo/snabb,kbara/snabb,mixflowtech/logsensor,Igalia/snabb,eugeneia/snabbswitch,dpino/snabbswitch,dpino/snabbswitch,snabbco/snabb,Igalia/snabbswitch,eugeneia/snabb
f491bf288fad0944e32fa910fcfcbe0819b181db
modules/game_textwindow/textwindow.lua
modules/game_textwindow/textwindow.lua
function init() g_ui.importStyle('textwindow.otui') connect(g_game, { onEditText = onGameEditText, onEditList = onGameEditList, onGameEnd = destroy }) end function terminate() disconnect(g_game, { onEditText = onGameEditText, onEditList = onGameEditList, onGameEnd = destroy }) destroy() end function destroy() if textWindow then textWindow:destroy() textWindow = nil end end function onGameEditText(id, itemId, maxLength, text, writter, time) if textWindow then return end textWindow = g_ui.createWidget('TextWindow', rootWidget) local writeable = (maxLength ~= #text) and maxLength > 0 local textItem = textWindow:getChildById('textItem') local description = textWindow:getChildById('description') local textEdit = textWindow:getChildById('text') local okButton = textWindow:getChildById('okButton') local cancelButton = textWindow:getChildById('cancelButton') textItem:setItemId(itemId) textEdit:setMaxLength(maxLength) textEdit:setText(text) textEdit:setEnabled(writeable) local desc = '' if #writter > 0 then desc = tr('You read the following, written by \n%s\n', writter) if #time > 0 then desc = desc .. tr('on %s.\n', time) end elseif #time > 0 then desc = tr('You read the following, written on %s.\n', time) end if #text == 0 and not writeable then desc = tr("It is empty.\n") elseif writeable then desc = desc .. tr('You can enter new text.') end description:setText(desc) if not writeable then textWindow:setText(tr('Show Text')) cancelButton:hide() else textWindow:setText(tr('Edit Text')) end doneFunc = function() if writeable then g_game.editText(id, textEdit:getText()) end textEdit = nil destroy() end okButton.onClick = doneFunc textWindow.onEnter = doneFunc textWindow.onEscape = destroy end function onGameEditList(id, doorId, text) if textWindow then return end textWindow = g_ui.createWidget('TextWindow', rootWidget) local textEdit = textWindow:getChildById('text') local description = textWindow:getChildById('description') local okButton = textWindow:getChildById('okButton') local cancelButton = textWindow:getChildById('cancelButton') textEdit:setMaxLength(8192) textEdit:setText(text) textEdit:setEnabled(true) description:setText(tr('Enter one name per line.')) textWindow:setText(tr('Edit List')) doneFunc = function() g_game.editList(id, doorId, textEdit:getText()) destroy() end okButton.onClick = doneFunc textWindow.onEnter = doneFunc textWindow.onEscape = destroy end
function init() g_ui.importStyle('textwindow.otui') connect(g_game, { onEditText = onGameEditText, onEditList = onGameEditList, onGameEnd = destroy }) end function terminate() disconnect(g_game, { onEditText = onGameEditText, onEditList = onGameEditList, onGameEnd = destroy }) destroy() end function destroy() if textWindow then textWindow:destroy() textWindow = nil end end function onGameEditText(id, itemId, maxLength, text, writter, time) if textWindow then return end textWindow = g_ui.createWidget('TextWindow', rootWidget) local writeable = (maxLength ~= #text) and maxLength > 0 local textItem = textWindow:getChildById('textItem') local description = textWindow:getChildById('description') local textEdit = textWindow:getChildById('text') local okButton = textWindow:getChildById('okButton') local cancelButton = textWindow:getChildById('cancelButton') textItem:setItemId(itemId) textEdit:setMaxLength(maxLength) textEdit:setText(text) textEdit:setEnabled(writeable) local desc = '' if #writter > 0 then desc = tr('You read the following, written by \n%s\n', writter) if #time > 0 then desc = desc .. tr('on %s.\n', time) end elseif #time > 0 then desc = tr('You read the following, written on \n%s.\n', time) end if #text == 0 and not writeable then desc = tr("It is empty.") elseif writeable then desc = desc .. tr('You can enter new text.') end local lines = #{string.find(desc, '\n')} if lines < 2 then desc = desc .. '\n' end description:setText(desc) if not writeable then textWindow:setText(tr('Show Text')) --textEdit:wrapText() cancelButton:hide() cancelButton:setWidth(0) okButton:setMarginRight(0) else textWindow:setText(tr('Edit Text')) end local doneFunc = function() if writeable then g_game.editText(id, textEdit:getText()) end destroy() end okButton.onClick = doneFunc cancelButton.onClick = destroy --textWindow.onEnter = doneFunc -- this should be '\n' textWindow.onEscape = destroy end function onGameEditList(id, doorId, text) if textWindow then return end textWindow = g_ui.createWidget('TextWindow', rootWidget) local textEdit = textWindow:getChildById('text') local description = textWindow:getChildById('description') local okButton = textWindow:getChildById('okButton') local cancelButton = textWindow:getChildById('cancelButton') textEdit:setMaxLength(8192) textEdit:setText(text) textEdit:setEnabled(true) description:setText(tr('Enter one name per line.')) textWindow:setText(tr('Edit List')) doneFunc = function() g_game.editList(id, doorId, textEdit:getText()) destroy() end okButton.onClick = doneFunc textWindow.onEnter = doneFunc textWindow.onEscape = destroy end function onGameEditList(id, doorId, text) if textWindow then return end textWindow = g_ui.createWidget('TextWindow', rootWidget) local textEdit = textWindow:getChildById('text') local description = textWindow:getChildById('description') local okButton = textWindow:getChildById('okButton') local cancelButton = textWindow:getChildById('cancelButton') textEdit:setMaxLength(8192) textEdit:setText(text) textEdit:setEnabled(true) description:setText(tr('Enter one name per line.')) textWindow:setText(tr('Edit List')) doneFunc = function() g_game.editList(id, doorId, textEdit:getText()) destroy() end okButton.onClick = doneFunc textWindow.onEnter = doneFunc textWindow.onEscape = destroy end
Fix some issues in text window
Fix some issues in text window
Lua
mit
kwketh/otclient,dreamsxin/otclient,kwketh/otclient,EvilHero90/otclient,Radseq/otclient,Cavitt/otclient_mapgen,gpedro/otclient,gpedro/otclient,EvilHero90/otclient,Radseq/otclient,dreamsxin/otclient,gpedro/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen
73f561495a7533a9699451e6d80a2d7728a8595a
HexChat/mymsg.lua
HexChat/mymsg.lua
hexchat.register('MyMessage', '2', 'Properly show your own messages in ZNC playback') hexchat.hook_print('Capability List', function (args) if args[2]:find('znc.in/self%-message') then hexchat.command('CAP REQ znc.in/self-message') local ctx = hexchat.props.context hexchat.hook_timer(1, function () -- Emit right after this event if ctx:set() then hexchat.emit_print('Capability Request', 'znc.in/self-message') end end) end end) local function prefix_is_channel (prefix) local chantypes = hexchat.props['chantypes'] for i = 1, #chantypes do if chantypes[i] == prefix then return true end end return false end hexchat.hook_server_attrs('PRIVMSG', function (word, word_eol, attrs) -- Only want private messages if prefix_is_channel(word[3]:sub(1, 1)) then return end local mynick = hexchat.get_info('nick') local sender = word[1]:match('^:([^!]+)') local recipient = word[3] if hexchat.nickcmp(sender, mynick) == 0 and hexchat.nickcmp(recipient, mynick) ~= 0 then hexchat.command('query -nofocus ' .. recipient) local ctx = hexchat.find_context(hexchat.get_info('network'), recipient) local message = word_eol[4] if message:sub(1, 1) == ':' then message = message:sub(2) end if message:sub(1, 8) == '\001ACTION ' then local action = message:sub(9, #message-1) ctx:emit_print_attrs(attrs, 'Your Action', mynick, action) else ctx:emit_print_attrs(attrs, 'Your Message', mynick, message) end return hexchat.EAT_ALL end end)
hexchat.register('MyMessage', '2', 'Properly show your own messages in ZNC playback') local function get_server_ctx() local id = hexchat.prefs['id'] for chan in hexchat.iterate('channels') do if chan.type == 1 and chan.id == id then return chan.context end end return hexchat.props.context end hexchat.hook_print('Capability List', function (args) if args[2]:find('znc.in/self%-message') then hexchat.command('CAP REQ znc.in/self-message') local ctx = get_server_ctx() hexchat.hook_timer(1, function () -- Emit right after this event if ctx:set() then hexchat.emit_print('Capability Request', 'znc.in/self-message') end end) end end) local function prefix_is_channel (prefix) local chantypes = hexchat.props['chantypes'] for i = 1, #chantypes do if chantypes[i] == prefix then return true end end return false end hexchat.hook_server_attrs('PRIVMSG', function (word, word_eol, attrs) -- Only want private messages if prefix_is_channel(word[3]:sub(1, 1)) then return end local mynick = hexchat.get_info('nick') local sender = word[1]:match('^:([^!]+)') local recipient = word[3] if hexchat.nickcmp(sender, mynick) == 0 and hexchat.nickcmp(recipient, mynick) ~= 0 then hexchat.command('query -nofocus ' .. recipient) local ctx = hexchat.find_context(hexchat.get_info('network'), recipient) local message = word_eol[4] if message:sub(1, 1) == ':' then message = message:sub(2) end if message:sub(1, 8) == '\001ACTION ' then local action = message:sub(9, #message-1) ctx:emit_print_attrs(attrs, 'Your Action', mynick, action) else ctx:emit_print_attrs(attrs, 'Your Message', mynick, message) end return hexchat.EAT_ALL end end)
mymsg.lua: Fix cap request printing in wrong tab
mymsg.lua: Fix cap request printing in wrong tab
Lua
mit
TingPing/plugins,TingPing/plugins
0fb7330a09985834cf89f932b8d7ada9fdfb8598
server/logout.lua
server/logout.lua
require("base.keys") require("base.common") module("server.logout", package.seeall) function onLogout( theChar ) if false then return true; end world:gfx(31,theChar.pos); --A nice GFX that announces clearly: A player logged out. -- begin newbie island if (theChar:getQuestProgress(2) == 320) then -- Der Char. ist ein Newb und befindet sich gerade auf der Newbieinsel am Kaempfen theChar:setQuestProgress(2,322); elseif (theChar:getQuestProgress(2) == 35) then -- Der Char. ist ein Newb und befindet sich gerade auf der Newbieinsel am Kaempfen theChar:setQuestProgress(2,36); end -- end newbie island -- begin tying local foundEffect, Tying = theChar.effects:find(24); if foundEffect then -- Char is a captive, save logout time Tying:addValue("logout",1); Tying:addValue("logyears",world:getTime("year")); Tying:addValue("logmonths",world:getTime("month")); Tying:addValue("logdays",world:getTime("day")); Tying:addValue("loghours",world:getTime("hour")); Tying:addValue("logminutes",world:getTime("minute")+3); Tying:addValue("logseconds",world:getTime("second")); foundCapturer, Capturer = Tying:findValue("Capturer"); local logText = os.date()..": "..theChar.name.." has logged out."..(foundCapturer and " Capturer: "..Capturer or "") coldLog,errMsg=io.open("/home/nitram/logs/tying_log.txt","a"); if (coldLog~=nil) then coldLog:write(logText.."\n"); coldLog:close(); end end -- end tying if theChar.name == ("Valerio Guilianni" or "Rosaline Edwards" or "Elvaine Morgan") then exchangeFactionLeader( theChar.name ) end end -- Function to exchange the faction leader of a town. -- @factionLeaderName Name of the faction leader -- @npcPositions Array of position {default position, new position} function exchangeFactionLeader( factionLeaderName ) if factionLeaderName == "Rosaline Edwards" then npcPositions = {position(122, 521, 0), position(237, 104, 0)}; elseif factionLeaderName == "Valerio Guilianni" then npcPositions = {position(337, 215, 0), position(238, 104, 0)}; else npcPositions = {position(898, 775, 2), position(239, 104, 0)}; end if world:isCharacterOnField(npcPositions[2]) == true then npcCharObject = world:getCharacterOnField(npcPositions[2]); npcCharObject:forceWarp(npcPositions[1]); end end
require("base.keys") require("base.common") module("server.logout", package.seeall) function onLogout( theChar ) if false then return true; end world:gfx(31,theChar.pos); --A nice GFX that announces clearly: A player logged out. -- begin newbie island if (theChar:getQuestProgress(2) == 320) then -- Der Char. ist ein Newb und befindet sich gerade auf der Newbieinsel am Kaempfen theChar:setQuestProgress(2,322); elseif (theChar:getQuestProgress(2) == 35) then -- Der Char. ist ein Newb und befindet sich gerade auf der Newbieinsel am Kaempfen theChar:setQuestProgress(2,36); end -- end newbie island -- begin tying local foundEffect, Tying = theChar.effects:find(24); if foundEffect then -- Char is a captive, save logout time Tying:addValue("logout",1); Tying:addValue("logyears",world:getTime("year")); Tying:addValue("logmonths",world:getTime("month")); Tying:addValue("logdays",world:getTime("day")); Tying:addValue("loghours",world:getTime("hour")); Tying:addValue("logminutes",world:getTime("minute")+3); Tying:addValue("logseconds",world:getTime("second")); foundCapturer, Capturer = Tying:findValue("Capturer"); local logText = os.date()..": "..theChar.name.." has logged out."..(foundCapturer and " Capturer: "..Capturer or "") coldLog,errMsg=io.open("/home/nitram/logs/tying_log.txt","a"); if (coldLog~=nil) then coldLog:write(logText.."\n"); coldLog:close(); end end -- end tying if theChar.name == "Valerio Guilianni" or theChar.name == "Rosaline Edwards" or theChar.name == "Elvaine Morgan" then exchangeFactionLeader( theChar.name ) end end -- Function to exchange the faction leader of a town. -- @factionLeaderName Name of the faction leader -- @npcPositions Array of position {default position, new position} function exchangeFactionLeader( factionLeaderName ) if factionLeaderName == "Rosaline Edwards" then npcPositions = {position(122, 521, 0), position(237, 104, 0)}; elseif factionLeaderName == "Valerio Guilianni" then npcPositions = {position(337, 215, 0), position(238, 104, 0)}; else npcPositions = {position(898, 775, 2), position(239, 104, 0)}; end if world:isCharacterOnField(npcPositions[2]) == true then npcCharObject = world:getCharacterOnField(npcPositions[2]); npcCharObject:forceWarp(npcPositions[1]); end end
fixed if statement
fixed if statement
Lua
agpl-3.0
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content
0739253c0ea1d49142cd5d61922e83a33080ac22
game_view.lua
game_view.lua
background_color = {240, 240, 240} grid_normal_color = {180, 230, 255} grid_block_color = {100, 200, 250} grid_line_width = 0.5 grid_unit_size = 32 grid_big_border = 5 -- mouse variables mouse_x = 0; mouse_y = 0; mouseClicked = false; -- glider variables rectanglesToDraw = {} numberOfGliders = 0 function draw_line(grid_num, x1, y1, x2, y2) local is_main = grid_num % grid_big_border == 0 local color = is_main and grid_block_color or grid_normal_color local width = grid_line_width love.graphics.setLineWidth(width) love.graphics.setColor(color[1], color[2], color[3]) love.graphics.line(x1, y1, x2, y2) end function exports() local instance = {} local block_size = grid_unit_size * grid_big_border local xoffsets = 1280 % block_size if xoffsets == 0 then xoffsets = block_size end local xoffset = xoffsets / 2 local xcount = (1280 - xoffsets) / grid_unit_size local yoffsets = 720 % block_size local yoffset = yoffsets / 2 local ycount = (720 - yoffsets) / grid_unit_size function instance:draw() love.graphics.setColor(background_color[1], background_color[2], background_color[3]) love.graphics.rectangle('fill', 0, 0, 1280, 720) -- Draw Grid local current_x = xoffset local grid_num = 0 local drawGliderX = 0 local drawGliderY = 0 while grid_num <= xcount do draw_line(grid_num, current_x, yoffset, current_x, 720 - yoffset) if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then drawGliderX = current_x end current_x = current_x + grid_unit_size grid_num = grid_num + 1 end local current_y = yoffset grid_num = 0 while grid_num <= ycount do draw_line(grid_num, xoffset, current_y, 1280 - xoffset, current_y) if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then drawGliderY = current_y end current_y = current_y + grid_unit_size grid_num = grid_num + 1 end if mouseClicked then local pos = {} local posX = "x" local posY = "y" pos[posX] = drawGliderX pos[posY] = drawGliderY numberOfGliders = numberOfGliders + 1 rectanglesToDraw[numberOfGliders] = pos end for i,rect in ipairs(rectanglesToDraw) do love.graphics.setColor(255,0,0) love.graphics.rectangle('fill', rect["x"], rect["y"], grid_unit_size, grid_unit_size) end end function instance:update() mouse_x, mouse_y = love.mouse.getPosition() mouseClicked = love.mouse.isDown("l") end return instance end return exports
-- imports grid_state = require 'grid_state' background_color = {240, 240, 240} grid_normal_color = {180, 230, 255} grid_block_color = {100, 200, 250} grid_line_width = 0.5 grid_unit_size = 32 grid_big_border = 5 -- mouse variables mouse_x = 0; mouse_y = 0; mouseClicked = false; -- glider variables rectanglesToDraw = {} numberOfGliders = 0 -- grid state function draw_line(grid_num, x1, y1, x2, y2) local is_main = grid_num % grid_big_border == 0 local color = is_main and grid_block_color or grid_normal_color local width = grid_line_width love.graphics.setLineWidth(width) love.graphics.setColor(color[1], color[2], color[3]) love.graphics.line(x1, y1, x2, y2) end function exports() local instance = {} local block_size = grid_unit_size * grid_big_border local xoffsets = 1280 % block_size if xoffsets == 0 then xoffsets = block_size end local xoffset = xoffsets / 2 local xcount = (1280 - xoffsets) / grid_unit_size local yoffsets = 720 % block_size local yoffset = yoffsets / 2 local ycount = (720 - yoffsets) / grid_unit_size instance.grid_state = grid_state(xcount, ycount) function instance:draw() love.graphics.setColor(background_color[1], background_color[2], background_color[3]) love.graphics.rectangle('fill', 0, 0, 1280, 720) -- Draw Grid local current_x = xoffset local grid_num = 0 local drawGliderX = -1 local drawGliderY = -1 while grid_num <= xcount do draw_line(grid_num, current_x, yoffset, current_x, 720 - yoffset) if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then drawGliderX = grid_num end current_x = current_x + grid_unit_size grid_num = grid_num + 1 end local current_y = yoffset grid_num = 0 while grid_num <= ycount do draw_line(grid_num, xoffset, current_y, 1280 - xoffset, current_y) if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then drawGliderY = grid_num end current_y = current_y + grid_unit_size grid_num = grid_num + 1 end if mouseClicked and drawGliderX >= 0 and drawGliderY >= 0 and drawGliderX < xcount and drawGliderY < ycount then local pos = {} local posX = "x" local posY = "y" pos[posX] = drawGliderX * grid_unit_size + xoffset pos[posY] = drawGliderY * grid_unit_size + yoffset numberOfGliders = numberOfGliders + 1 rectanglesToDraw[numberOfGliders] = pos end for i,rect in ipairs(rectanglesToDraw) do love.graphics.setColor(255,0,0) love.graphics.rectangle('fill', rect["x"], rect["y"], grid_unit_size, grid_unit_size) end end function instance:update() mouse_x, mouse_y = love.mouse.getPosition() mouseClicked = love.mouse.isDown("l") end return instance end return exports
bug in placing glider corrected
bug in placing glider corrected
Lua
mit
NamefulTeam/PortoGameJam2015
5bc4c8b4f04fe7b1dce95d750051454c2d723fb8
src/lpeg.lua
src/lpeg.lua
local lpjit_lpeg = {} local lpjit = require 'lpjit' local lpeg = require 'lpeg' local mt = {} local compiled = {} mt.__index = lpjit_lpeg local function rawWrap(pattern) local obj = {value = pattern} if newproxy and debug.setfenv then -- Lua 5.1 doesn't support __len for tables local obj2 = newproxy(true) debug.setmetatable(obj2, mt) debug.setfenv(obj2, obj) assert(debug.getfenv(obj2) == obj) return obj2 else return setmetatable(obj, mt) end end local function rawUnwrap(obj) if type(obj) == 'table' then return obj.value else return debug.getfenv(obj).value end end local function wrapPattern(pattern) if getmetatable(pattern) == mt then -- already wrapped return pattern else return rawWrap(pattern) end end local function unwrapPattern(obj) if getmetatable(obj) == mt then return rawUnwrap(obj) else return obj end end local function wrapGenerator(E) return function(obj, ...) if type(obj) == 'table' and getmetatable(obj) ~= mt then -- P { grammar } -- unwrap all values local obj2 = {} for k, v in pairs(obj) do obj2[k] = unwrapPattern(v) end obj = obj2 else obj = unwrapPattern(obj) end return wrapPattern(E(obj, ...)) end end for _, E in ipairs {'B', 'S', 'R', 'Cf', 'Cs', 'Cmt', 'Carg', 'Ct', 'P', 'Cc', 'Cp', 'Cg', 'Cb', 'V', 'C'} do lpjit_lpeg[E] = wrapGenerator(lpeg[E]) end for _, binop in ipairs {'__unm', '__mul', '__add', '__sub', '__div', '__pow', '__len'} do mt[binop] = function(a, b) a = unwrapPattern(a) b = unwrapPattern(b) local f = getmetatable(a)[binop] or getmetatable(b)[binop] return wrapPattern(f(a, b)) end end function lpjit_lpeg.match(obj, ...) if not compiled[obj] then compiled[obj] = lpjit.compile(unwrapPattern(obj)) end return compiled[obj]:match(...) end function lpjit_lpeg.setmaxstack(...) lpeg.setmaxstack(...) -- clear cache ot compiled patterns compiled = {} end function lpjit_lpeg.locale(t) local funcs0 = lpeg.locale() local funcs = t or {} for k, v in pairs(funcs0) do funcs[k] = wrapPattern(v) end return funcs end function lpjit_lpeg.version(t) return "lpjit with lpeg " .. lpeg.version() end function lpjit_lpeg.type(obj) if getmetatable(obj) == mt then return "pattern" end if lpeg.type(obj) then return "pattern" end return nil end if lpeg.pcode then function lpjit_lpeg.pcode(obj) return lpeg.pcode(unwrapPattern(obj)) end end if lpeg.ptree then function lpjit_lpeg.ptree(obj) return lpeg.ptree(unwrapPattern(obj)) end end return lpjit_lpeg
local lpjit_lpeg = {} local lpjit = require 'lpjit' local lpeg = require 'lpeg' local mt = {} local compiled = {} mt.__index = lpjit_lpeg local function rawWrap(pattern) local obj = {value = pattern} if newproxy and debug.setfenv then -- Lua 5.1 doesn't support __len for tables local obj2 = newproxy(true) debug.setmetatable(obj2, mt) debug.setfenv(obj2, obj) assert(debug.getfenv(obj2) == obj) return obj2 else return setmetatable(obj, mt) end end local function rawUnwrap(obj) if type(obj) == 'table' then return obj.value else return debug.getfenv(obj).value end end local function wrapPattern(pattern) if getmetatable(pattern) == mt then -- already wrapped return pattern else return rawWrap(pattern) end end local function unwrapPattern(obj) if getmetatable(obj) == mt then return rawUnwrap(obj) else return obj end end local function wrapGenerator(E) return function(obj, ...) if type(obj) == 'table' and getmetatable(obj) ~= mt then -- P { grammar } -- unwrap all values local obj2 = {} for k, v in pairs(obj) do obj2[k] = unwrapPattern(v) end obj = obj2 else obj = unwrapPattern(obj) end return wrapPattern(E(obj, ...)) end end for _, E in ipairs {'B', 'S', 'R', 'Cf', 'Cs', 'Cmt', 'Carg', 'Ct', 'P', 'Cc', 'Cp', 'Cg', 'Cb', 'V', 'C'} do lpjit_lpeg[E] = wrapGenerator(lpeg[E]) end for _, binop in ipairs {'__unm', '__mul', '__add', '__sub', '__div', '__pow', '__len'} do mt[binop] = function(a, b) a = unwrapPattern(a) b = unwrapPattern(b) local f = getmetatable(a)[binop] or getmetatable(b)[binop] return wrapPattern(f(a, b)) end end function lpjit_lpeg.match(obj, ...) if not compiled[obj] then obj = unwrapPattern(obj) if lpeg.type(obj) ~= 'pattern' then obj = lpeg.P(obj) end compiled[obj] = lpjit.compile(obj) end return compiled[obj]:match(...) end function lpjit_lpeg.setmaxstack(...) lpeg.setmaxstack(...) -- clear cache ot compiled patterns compiled = {} end function lpjit_lpeg.locale(t) local funcs0 = lpeg.locale() local funcs = t or {} for k, v in pairs(funcs0) do funcs[k] = wrapPattern(v) end return funcs end function lpjit_lpeg.version(t) return "lpjit with lpeg " .. lpeg.version() end function lpjit_lpeg.type(obj) if getmetatable(obj) == mt then return "pattern" end if lpeg.type(obj) then return "pattern" end return nil end if lpeg.pcode then function lpjit_lpeg.pcode(obj) return lpeg.pcode(unwrapPattern(obj)) end end if lpeg.ptree then function lpjit_lpeg.ptree(obj) return lpeg.ptree(unwrapPattern(obj)) end end return lpjit_lpeg
fix lpeg wrapper, function match
fix lpeg wrapper, function match Fix error when called with non-pattern Example: lpeg.match(3, 'aaa')
Lua
mit
starius/lpjit,starius/lpjit
2455d23dc18f075cf8a8140f3f98b6bc7cbd86e7
libs/term.lua
libs/term.lua
local prev, luv, T, stdin = ... local _colors = { [1] = "white"; [2] = "orange"; [4] = "magenta"; [8] = "lightBlue"; [16] = "yellow"; [32] = "lime"; [64] = "pink"; [128] = "gray"; [256] = "lightGray"; [512] = "cyan"; [1024] = "purple"; [2048] = "blue"; [4096] = "brown"; [8192] = "green"; [16384] = "red"; [32768] = "black"; } local ansiColors = { white = {7, false}; -- white orange = {1, true}; -- bright red magenta = {5, false}; -- magenta lightBlue = {4, true}; -- bright blue yellow = {3, true}; -- bright yellow lime = {2, true}; -- bright green pink = {5, false}; -- magenta gray = {0, false}; -- black lightGray = {0, false}; -- black cyan = {6, false}; -- cyan purple = {5, false}; -- magenta blue = {4, false}; -- blue brown = {3, false}; -- yellow green = {2, false}; -- green red = {1, false}; -- red black = {0, false}; -- black } local hex = { ['a'] = 10; ['b'] = 11; ['c'] = 12; ['d'] = 13; ['e'] = 14; ['f'] = 15; } for i = 0, 9 do hex[tostring(i)] = i end local cursorX, cursorY = 1, 1 local textColor, backColor = 0, 15 local log2 = math.log(2) local function ccColorFor(c) if type(c) ~= 'number' or c < 0 or c > 15 then error('that\'s not a valid color: ' .. tostring(c)) end return math.pow(2, c) end local function fromHexColor(h) return hex[h] or error('not a hex color: ' .. tostring(h)) end local termNat termNat = { clear = function() prev.io.write(T.clear()) end; clearLine = function() termNat.setCursorPos(cursorY, 1) prev.io.write(T.el()) termNat.setCursorPos(cursorY, cursorX) end; isColour = function() return true end; isColor = function() return true end; getSize = function() return luv.tty_get_winsize(stdin) -- return 52, 19 end; getCursorPos = function() return cursorX, cursorY end; setCursorPos = function(x, y) if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end cursorX, cursorY = x, y prev.io.write(T.cup(cursorY - 1, cursorX - 1)) end; setTextColour = function(...) return termNat.setTextColor(...) end; setTextColor = function(c) textColor = math.log(c) / log2 local color = ansiColors[_colors[c] ] prev.io.write(T[color[2] and 'bold' or 'sgr0']()) prev.io.write(T.setaf(color[1])) end; getTextColour = function(...) return termNat.getTextColor(...) end; getTextColor = function() return ccColorFor(textColor) end; setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end; setBackgroundColor = function(c) backColor = math.log(c) / log2 prev.io.write(T.setab(ansiColors[_colors[c] ][1])) end; getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end; getBackgroundColor = function() return ccColorFor(backColor) end; write = function(text) text = tostring(text or '') text = text:gsub('[\n\r]', '?') prev.io.write(text) termNat.setCursorPos(cursorX + #text, cursorY) end; blit = function(text, textColors, backColors) text = text:gsub('[\n\r]', '?') if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end for i = 1, #text do termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i)))) termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i)))) prev.io.write(text:sub(i, i)) end cursorX = cursorX + #text end; setCursorBlink = function() end; scroll = function(n) n = n or 1 local w, h = luv.tty_get_winsize(stdin) prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w)) local txt = T[n < 0 and 'ri' or 'ind']() prev.io.write(txt:rep(math.abs(n))) if n > 0 then prev.io.write(T.cup(h - n, 0)) prev.io.write(T.clr_eos()) elseif n < 0 then for i = 0, n do prev.io.write(T.cup(i, 0)) prev.io.write(T.clr_eol()) end end termNat.setCursorPos(cursorX, cursorY) end } return termNat
local prev, luv, T, stdin = ... local _colors = { [1] = "white"; [2] = "orange"; [4] = "magenta"; [8] = "lightBlue"; [16] = "yellow"; [32] = "lime"; [64] = "pink"; [128] = "gray"; [256] = "lightGray"; [512] = "cyan"; [1024] = "purple"; [2048] = "blue"; [4096] = "brown"; [8192] = "green"; [16384] = "red"; [32768] = "black"; } local ansiColors = { white = {7, false}; -- white orange = {1, true}; -- bright red magenta = {5, false}; -- magenta lightBlue = {4, true}; -- bright blue yellow = {3, true}; -- bright yellow lime = {2, true}; -- bright green pink = {5, false}; -- magenta gray = {0, false}; -- black lightGray = {0, false}; -- black cyan = {6, false}; -- cyan purple = {5, false}; -- magenta blue = {4, false}; -- blue brown = {3, false}; -- yellow green = {2, false}; -- green red = {1, false}; -- red black = {0, false}; -- black } local hex = { ['a'] = 10; ['b'] = 11; ['c'] = 12; ['d'] = 13; ['e'] = 14; ['f'] = 15; } for i = 0, 9 do hex[tostring(i)] = i end local cursorX, cursorY = 1, 1 local textColor, backColor = 0, 15 local log2 = math.log(2) local function ccColorFor(c) if type(c) ~= 'number' or c < 0 or c > 15 then error('that\'s not a valid color: ' .. tostring(c)) end return math.pow(2, c) end local function fromHexColor(h) return hex[h] or error('not a hex color: ' .. tostring(h)) end local termNat termNat = { clear = function() prev.io.write(T.clear()) end; clearLine = function() prev.io.write(T.cup(cursorY - 1, 0)) prev.io.write(T.clr_eol()) termNat.setCursorPos(cursorX, cursorY) end; isColour = function() return true end; isColor = function() return true end; getSize = function() return luv.tty_get_winsize(stdin) -- return 52, 19 end; getCursorPos = function() return cursorX, cursorY end; setCursorPos = function(x, y) if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end cursorX, cursorY = x, y prev.io.write(T.cup(cursorY - 1, cursorX - 1)) end; setTextColour = function(...) return termNat.setTextColor(...) end; setTextColor = function(c) textColor = math.log(c) / log2 local color = ansiColors[_colors[c] ] prev.io.write(T[color[2] and 'bold' or 'sgr0']()) prev.io.write(T.setaf(color[1])) end; getTextColour = function(...) return termNat.getTextColor(...) end; getTextColor = function() return ccColorFor(textColor) end; setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end; setBackgroundColor = function(c) backColor = math.log(c) / log2 prev.io.write(T.setab(ansiColors[_colors[c] ][1])) end; getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end; getBackgroundColor = function() return ccColorFor(backColor) end; write = function(text) text = tostring(text or '') text = text:gsub('[\n\r]', '?') prev.io.write(text) termNat.setCursorPos(cursorX + #text, cursorY) end; blit = function(text, textColors, backColors) text = text:gsub('[\n\r]', '?') if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end for i = 1, #text do termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i)))) termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i)))) prev.io.write(text:sub(i, i)) end cursorX = cursorX + #text end; setCursorBlink = function() end; scroll = function(n) n = n or 1 local w, h = luv.tty_get_winsize(stdin) prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w)) local txt = T[n < 0 and 'ri' or 'ind']() prev.io.write(txt:rep(math.abs(n))) if n > 0 then prev.io.write(T.cup(h - n, 0)) prev.io.write(T.clr_eos()) elseif n < 0 then for i = 0, n do prev.io.write(T.cup(i, 0)) prev.io.write(T.clr_eol()) end end termNat.setCursorPos(cursorX, cursorY) end } return termNat
Fix term.clearLine
Fix term.clearLine
Lua
mit
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
e467771ed39da800bbd40312adc5a1bc608efb09
test_scripts/Polices/build_options/P_ATF_Register_NewApp_not_exist_inLocalPT_FinishPTU_PROPRIETARY.lua
test_scripts/Polices/build_options/P_ATF_Register_NewApp_not_exist_inLocalPT_FinishPTU_PROPRIETARY.lua
-- Requirement summary: -- [PolicyTableUpdate] New application has registered and doesn't yet exist in Local PT during PTU in progress -- -- Note: Copy attached ptu.json on this way: /tmp/fs/mp/images/ivsu_cache/, for line 111 and for line 121 -- -- Description: -- PoliciesManager must add the appID of the newly registered app to the Local PT in case -- such appID does not yet exist in Local PT and PoliciesManager has sent the PT Snapshot and has not received the PT Update yet. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- Performed steps -- 1. MOB-SDL - Register Application default. -- 2. PTU in progress. PoliciesManager has sent the PT Snapshot and has not received the PT Update yet -- 3. MOB-SDL - app_2 -> SDL:RegisterAppInterface -- 4. SDL send UP_TO_DATE for first application -- -- Expected result: -- 1. PoliciesManager validates the updated PT (policyFile) e.i. verifyes, saves the updated fields and everything that is defined with related requirements) -- 2. On validation success: SDL->HMI:OnStatusUpdate("UP_TO_DATE") -- 3. SDL replaces the following sections of the Local Policy Table with the corresponding sections from PTU: module_config, functional_groupings, app_policies -- 4. app_2 added to Local PT during PT Exchange process left after merge in LocalPT (not being lost on merge) ------------------------------------------------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.defaultProtocolVersion = 2 config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') --[[ Local Functions ]] local registerAppInterfaceParams = { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "Media Application", isMediaApplication = true, languageDesired = 'EN-US', hmiDisplayLanguageDesired = 'EN-US', appHMIType = {"NAVIGATION"}, appID = "MyTestApp", deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } } --[[ General Precondition before ATF start]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup ("Preconditions") function Test:Precondition_PolicyUpdateStarted() local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestIdGetURLS,{result = {code = 0, method = "SDL.GetURLS", urls = {{url = "http://policies.telematics.ford.com/api/policies"}}}}) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", url = "http://policies.telematics.ford.com/api/policies", appID = self.applications ["Test Application"], fileName = "sdl_snapshot.json" }) end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY" }) end function Test:Precondition_OpenNewSession() self.mobileSession2 = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession2:StartService(7) end --[[ Test ]] commonFunctions:newTestCasesGroup ("Test") function Test:TestStep_RAI_NewSession() local corId = self.mobileSession2:SendRPC("RegisterAppInterface", registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = "Media Application" }}) self.mobileSession2:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) self.mobileSession2:ExpectNotification("OnPermissionsChange") end function Test:TestStep_FinishPTU_ForAppId1() local CorIdSystemRequest = self.mobileSession:SendRPC ("SystemRequest", { requestType = "PROPRIETARY", fileName = "ptu.json" }, "files/ptu.json" ) EXPECT_HMICALL("BasicCommunication.SystemRequest") :Do(function(_,data) self.hmiConnection:SendResponse(data.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) end) EXPECT_RESPONSE(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = "/tmp/fs/mp/images/ivsu_cache/ptu.json" }) -- PTU will be restarted because of new AppID is registered EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}, {status = "UPDATE_NEEDED"}) end) end function Test:TestStep_CheckThatAppID_Present_In_DataBase() local PolicyDBPath = nil if commonSteps:file_exists(tostring(config.pathToSDL) .. "/storage/policy.sqlite") == true then PolicyDBPath = tostring(config.pathToSDL) .. "/storage/policy.sqlite" end if commonSteps:file_exists(tostring(config.pathToSDL) .. "/storage/policy.sqlite") == false then commonFunctions:userPrint(31, "policy.sqlite file is not found") self:FailTestCase("PolicyTable is not avaliable" .. tostring(PolicyDBPath)) end -- os.execute(" sleep 2 ") local AppId_2 = "sqlite3 " .. tostring(PolicyDBPath) .. "\"SELECT id FROM application WHERE id = '"..tostring(registerAppInterfaceParams.appID).."'\"" local bHandle = assert( io.popen(AppId_2, 'r')) local AppIdValue_2 = bHandle:read( '*l' ) if AppIdValue_2 == nil then self:FailTestCase("Value in DB is unexpected value " .. tostring(AppIdValue_2)) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
-- Requirement summary: -- [PolicyTableUpdate] New application has registered and doesn't yet exist in Local PT during PTU in progress -- -- Note: Copy attached ptu.json on this way: /tmp/fs/mp/images/ivsu_cache/, for line 111 and for line 121 -- -- Description: -- PoliciesManager must add the appID of the newly registered app to the Local PT in case -- such appID does not yet exist in Local PT and PoliciesManager has sent the PT Snapshot and has not received the PT Update yet. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- Performed steps -- 1. MOB-SDL - Register Application default. -- 2. PTU in progress. PoliciesManager has sent the PT Snapshot and has not received the PT Update yet -- 3. MOB-SDL - app_2 -> SDL:RegisterAppInterface -- 4. SDL send UP_TO_DATE for first application -- -- Expected result: -- 1. PoliciesManager validates the updated PT (policyFile) e.i. verifyes, saves the updated fields and everything that is defined with related requirements) -- 2. On validation success: SDL->HMI:OnStatusUpdate("UP_TO_DATE") -- 3. SDL replaces the following sections of the Local Policy Table with the corresponding sections from PTU: module_config, functional_groupings, app_policies -- 4. app_2 added to Local PT during PT Exchange process left after merge in LocalPT (not being lost on merge) ------------------------------------------------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.defaultProtocolVersion = 2 config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] Test = require('connecttest') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Local Functions ]] local registerAppInterfaceParams = { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "Media Application", isMediaApplication = true, languageDesired = 'EN-US', hmiDisplayLanguageDesired = 'EN-US', appHMIType = {"NAVIGATION"}, appID = "MyTestApp", deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } } --[[ General Precondition before ATF start]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ Preconditions ]] commonFunctions:newTestCasesGroup ("Preconditions") function Test:Precondition_PolicyUpdateStarted() local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestIdGetURLS,{result = {code = 0, method = "SDL.GetURLS", urls = {{url = "http://policies.telematics.ford.com/api/policies"}}}}) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", url = "http://policies.telematics.ford.com/api/policies", appID = self.applications ["Test Application"], fileName = "sdl_snapshot.json" }) end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY" }) end function Test:Precondition_OpenNewSession() self.mobileSession2 = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession2:StartService(7) end --[[ Test ]] commonFunctions:newTestCasesGroup ("Test") function Test:TestStep_RAI_NewSession() local corId = self.mobileSession2:SendRPC("RegisterAppInterface", registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = "Media Application" }}) self.mobileSession2:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) self.mobileSession2:ExpectNotification("OnPermissionsChange") end function Test:TestStep_FinishPTU_ForAppId1() local CorIdSystemRequest = self.mobileSession:SendRPC ("SystemRequest", { requestType = "PROPRIETARY", fileName = "ptu.json" }, "files/ptu.json" ) EXPECT_HMICALL("BasicCommunication.SystemRequest") :Do(function(_,data) self.hmiConnection:SendResponse(data.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) end) EXPECT_RESPONSE(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = "/tmp/fs/mp/images/ivsu_cache/ptu.json" }) -- PTU will be restarted because of new AppID is registered EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}, {status = "UPDATE_NEEDED"}) end) end function Test:TestStep_CheckThatAppID_Present_In_DataBase() local PolicyDBPath = nil if commonSteps:file_exists(tostring(config.pathToSDL) .. "/storage/policy.sqlite") == true then PolicyDBPath = tostring(config.pathToSDL) .. "/storage/policy.sqlite" else commonFunctions:userPrint(31, "policy.sqlite file is not found") self:FailTestCase("PolicyTable is not avaliable " .. tostring(PolicyDBPath)) end local select_value = "SELECT id FROM application WHERE id = '"..tostring(registerAppInterfaceParams.appID).."'" local result = commonFunctions:is_db_contains(PolicyDBPath, select_value, {tostring(registerAppInterfaceParams.appID)}) if result == false then self:FailTestCase("DB doesn't contain special id") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
Fix accessing to policy db Use common function for check value in table
Fix accessing to policy db Use common function for check value in table
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
c4c09413502cd4402d53a22d4718544cb9a6c203
src/lua/sdini.lua
src/lua/sdini.lua
-- -- sdini.lua -- speedata publisher -- -- Copyright 2010-2011 Patrick Gundlach. -- See file COPYING in the root directory for license info. -- -- BUG on windows: http://lua-users.org/lists/lua-l/2012-08/msg00052.html -- ! in LUA_PATH gets replaced by $PWD package.path=os.getenv("LUA_PATH") texio.write_nl("Loading file sdini.lua ...") callback.register('start_run',function() return true end) texconfig.kpse_init=false texconfig.max_print_line=99999 texconfig.formatname="sd-format" texconfig.trace_file_names = false local basedir=os.getenv("PUBLISHER_BASE_PATH") local extra_dirs = os.getenv("SD_EXTRA_DIRS") kpse = {} function file_start( filename ) if log then log("Load file: %q ...",filename) end end function file_end( filename ) if log then log("Load file: %q ... done",filename) end end function dirtree(dir) assert(dir and dir ~= "", "directory parameter is missing or empty") if string.sub(dir, -1) == "/" then dir=string.sub(dir, 1, -2) end local function yieldtree(dir) for entry in lfs.dir(dir) do if not entry:match("^%.") then entry=dir.."/"..entry local attr=lfs.attributes(entry) if attr then if attr.mode ~= "directory" then coroutine.yield(entry,attr) end if attr.mode == "directory" then yieldtree(entry) end end end end end return coroutine.wrap(function() yieldtree(dir) end) end kpse.filelist = {} local jobname = os.getenv("SP_JOBNAME") local currentdir = lfs.currentdir() local function add_dir( dir ) for i in dirtree(dir) do local filename = i:gsub(".*/([^/]+)$","%1") if i == currentdir .. "/" .. jobname .. ".pdf" then -- ignore else kpse.filelist[filename] = i end end end add_dir(basedir) if os.type == "windows" then path_separator = ";" else path_separator = ":" end if extra_dirs then for _,d in ipairs(string.explode(extra_dirs,path_separator)) do if lfs.attributes(d,"mode")=="directory" then add_dir(d) end end end function kpse.find_file(filename,what) if not filename then return nil end return kpse.filelist[filename] or kpse.filelist[filename .. ".tex"] end function do_luafile(filename) local a = kpse.find_file(filename) assert(a,string.format("Can't find file %q",filename)) return dofile(a) end do_luafile("sd-debug.lua") do_luafile("sd-callbacks.lua") texio.write_nl("Loading file sdini.lua ... done\n")
-- -- sdini.lua -- speedata publisher -- -- Copyright 2010-2011 Patrick Gundlach. -- See file COPYING in the root directory for license info. -- -- BUG on windows: http://lua-users.org/lists/lua-l/2012-08/msg00052.html -- ! in LUA_PATH gets replaced by $PWD package.path=os.getenv("LUA_PATH") texio.write_nl("Loading file sdini.lua ...") callback.register('start_run',function() return true end) texconfig.kpse_init=false texconfig.max_print_line=99999 texconfig.formatname="sd-format" texconfig.trace_file_names = false local basedir=os.getenv("PUBLISHER_BASE_PATH") local extra_dirs = os.getenv("SD_EXTRA_DIRS") kpse = {} function file_start( filename ) if log then log("Load file: %q ...",filename) end end function file_end( filename ) if log then log("Load file: %q ... done",filename) end end function dirtree(dir) assert(dir and dir ~= "", "directory parameter is missing or empty") if string.sub(dir, -1) == "/" then dir=string.sub(dir, 1, -2) end local function yieldtree(dir) for entry in lfs.dir(dir) do if not entry:match("^%.") then entry=dir.."/"..entry local attr=lfs.attributes(entry) if attr then if attr.mode ~= "directory" then coroutine.yield(entry,attr) end if attr.mode == "directory" then yieldtree(entry) end end end end end return coroutine.wrap(function() yieldtree(dir) end) end kpse.filelist = {} -- only set when running the publisher, not with list-fonts -- so jobname can be nil local jobname = os.getenv("SP_JOBNAME") local currentdir = lfs.currentdir() local function add_dir( dir ) for i in dirtree(dir) do local filename = i:gsub(".*/([^/]+)$","%1") if jobname and ( i == currentdir .. "/" .. jobname .. ".pdf" ) then -- ignore else kpse.filelist[filename] = i end end end add_dir(basedir) if os.type == "windows" then path_separator = ";" else path_separator = ":" end if extra_dirs then for _,d in ipairs(string.explode(extra_dirs,path_separator)) do if lfs.attributes(d,"mode")=="directory" then add_dir(d) end end end function kpse.find_file(filename,what) if not filename then return nil end return kpse.filelist[filename] or kpse.filelist[filename .. ".tex"] end function do_luafile(filename) local a = kpse.find_file(filename) assert(a,string.format("Can't find file %q",filename)) return dofile(a) end do_luafile("sd-debug.lua") do_luafile("sd-callbacks.lua") texio.write_nl("Loading file sdini.lua ... done\n")
Tiny bugfix for 'sp list-fonts' and jobname
Tiny bugfix for 'sp list-fonts' and jobname When running 'list-fonts', the environment variable SP_JOBNAME is not set und thus nil which can't be used to construct a string value.
Lua
agpl-3.0
speedata/publisher,speedata/publisher,speedata/publisher,speedata/publisher
0a913d9177d72e35325eb10ef601ccbfc75bfd76
src/nodes/pot.lua
src/nodes/pot.lua
local anim8 = require 'vendor/anim8' local Helper = require 'helper' local Pot = {} Pot.__index = Pot local potImage = love.graphics.newImage('images/pot.png') local potExplode= love.graphics.newImage('images/pot_asplode.png') local g = anim8.newGrid(41, 30, potExplode:getWidth(), potExplode:getHeight()) function Pot.new(node, collider) local pot = {} setmetatable(pot, Pot) pot.image = potImage pot.bb = collider:addRectangle(node.x, node.y, node.width, node.height) pot.bb.node = pot pot.collider = collider pot.collider:setPassive(pot.bb) pot.explode = anim8.newAnimation('once', g('1-5,1'), .10) pot.position = { x = node.x, y = node.y } pot.velocity = { x = 0, y = 0 } pot.floor = 0 pot.die = false pot.thrown = false pot.held = false pot.width = node.width pot.height = node.height return pot end function Pot:draw() if self.die then self.explode:draw(potExplode, self.position.x, self.position.y) else love.graphics.draw(self.image, self.position.x, self.position.y) end end function Pot:collide(player, dt, mtv_x, mtv_y) if not player.holding then player:registerHoldable(self) end end function Pot:collide_end(player, dt) end function Pot:update(dt, player) if self.held then self.position.x = math.floor(player.position.x + (self.width / 2)) + 2 self.position.y = math.floor(player.position.y + player.hand_offset - self.height) self:moveBoundingBox() return end if self.die and self.explode.position ~= 5 then self.explode:update(dt) self.position.x = self.position.x + (self.velocity.x > 0 and 1 or -1) * 50 * dt return end if not (self.thrown or self.held) then return end self.velocity.y = self.velocity.y + 0.21875 * 10000 * dt if not self.held then self.position.x = self.position.x + self.velocity.x * dt self.position.y = self.position.y + self.velocity.y * dt self:moveBoundingBox() end if self.position.x < 0 then self.position.x = 0 self.thrown = false end if self.position.x > 400 then self.position.x = 400 self.thrown = false end if self.thrown and self.position.y > self.floor then self.position.y = self.floor self.thrown = false self.die = true end end function Pot:moveBoundingBox() Helper.moveBoundingBox(self) end function Pot:keypressed(key, player) if (key == "rshift" or key == "lshift") and player.holdable == self then if player.holding == nil then player.walk_state = 'holdwalk' player.gaze_state = 'holdwalk' player.crouch_state = 'holdwalk' player.holding = true self.held = true self.velocity.y = 0 self.velocity.x = 0 else player.holding = nil player.walk_state = 'walk' player.crouch_state = 'crouchwalk' player.gaze_state = 'gazewalk' self.held = false self.thrown = true self.floor = player.position.y + player.height - self.height self.velocity.x = ((player.direction == "left") and -1 or 1) * 500 self.velocity.y = 0 self.collider:setGhost(self.bb) player:cancelHoldable(self) end end end return Pot
local anim8 = require 'vendor/anim8' local Helper = require 'helper' local Pot = {} Pot.__index = Pot local potImage = love.graphics.newImage('images/pot.png') local potExplode= love.graphics.newImage('images/pot_asplode.png') local g = anim8.newGrid(41, 30, potExplode:getWidth(), potExplode:getHeight()) function Pot.new(node, collider) local pot = {} setmetatable(pot, Pot) pot.image = potImage pot.bb = collider:addRectangle(node.x, node.y, node.width, node.height) pot.bb.node = pot pot.collider = collider pot.collider:setPassive(pot.bb) pot.explode = anim8.newAnimation('once', g('1-5,1'), .10) pot.position = { x = node.x, y = node.y } pot.velocity = { x = 0, y = 0 } pot.floor = 0 pot.die = false pot.thrown = false pot.held = false pot.width = node.width pot.height = node.height return pot end function Pot:draw() if self.die then self.explode:draw(potExplode, self.position.x, self.position.y) else love.graphics.draw(self.image, self.position.x, self.position.y) end end function Pot:collide(player, dt, mtv_x, mtv_y) if not player.holding then player:registerHoldable(self) end end function Pot:collide_end(player, dt) player:cancelHoldable(self) end function Pot:update(dt, player) if self.held then self.position.x = math.floor(player.position.x + (self.width / 2)) + 2 self.position.y = math.floor(player.position.y + player.hand_offset - self.height) self:moveBoundingBox() return end if self.die and self.explode.position ~= 5 then self.explode:update(dt) self.position.x = self.position.x + (self.velocity.x > 0 and 1 or -1) * 50 * dt return end if not (self.thrown or self.held) then return end self.velocity.y = self.velocity.y + 0.21875 * 10000 * dt if not self.held then self.position.x = self.position.x + self.velocity.x * dt self.position.y = self.position.y + self.velocity.y * dt self:moveBoundingBox() end if self.position.x < 0 then self.velocity.x = -self.velocity.x end if self.position.x > 400 then self.velocity.x = -self.velocity.x end if self.thrown and self.position.y > self.floor then self.position.y = self.floor self.thrown = false self.die = true end end function Pot:moveBoundingBox() Helper.moveBoundingBox(self) end function Pot:keypressed(key, player) if (key == "rshift" or key == "lshift") and player.holdable == self then if player.holding == nil then player.walk_state = 'holdwalk' player.gaze_state = 'holdwalk' player.crouch_state = 'holdwalk' player.holding = true self.held = true self.velocity.y = 0 self.velocity.x = 0 else player.holding = nil player.walk_state = 'walk' player.crouch_state = 'crouchwalk' player.gaze_state = 'gazewalk' self.held = false self.thrown = true self.floor = player.position.y + player.height - self.height self.velocity.x = ((player.direction == "left") and -1 or 1) * 500 self.velocity.y = 0 self.collider:setGhost(self.bb) player:cancelHoldable(self) end end end return Pot
Fixes #231. Pot issues
Fixes #231. Pot issues
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua
12d207d4b0247363c3b5d07b339bcc35d743495e
sample.lua
sample.lua
require 'torch' require 'image' require 'paths' require 'pl' require 'layers.cudnnSpatialConvolutionUpsample' NN_UTILS = require 'utils.nn_utils' OPT = lapp[[ --save_base (default "logs") directory in which the networks are saved --save_c2f32 (default "logs") --G_base (default "adversarial.net") --D_base (default "adversarial.net") --G_c2f32 (default "adversarial_c2f_16_to_32.net") --D_c2f32 (default "adversarial_c2f_16_to_32.net") --writeto (default "samples") directory to save the images to --seed (default 1) --gpu (default 0) GPU to run on --runs (default 3) How often to sample and save images --noiseDim (default 100) --batchSize (default 16) ]] print(OPT) if OPT.gpu < 0 then print("[ERROR] Sample script currently only runs on GPU, set --gpu=x where x is between 0 and 3.") exit() end torch.manualSeed(OPT.seed) print("Starting gpu support...") require 'cutorch' require 'cunn' torch.setdefaulttensortype('torch.FloatTensor') math.randomseed(OPT.seed) torch.manualSeed(OPT.seed) cutorch.setDevice(OPT.gpu + 1) cutorch.manualSeed(OPT.seed) function main() MODEL_G, MODEL_D, MODEL_G_C2F_32, MODEL_D_C2F_32 = loadModels() MODEL_G = NN_UTILS.activateCuda(MODEL_G) MODEL_D = NN_UTILS.activateCuda(MODEL_D) MODEL_G_C2F_32 = NN_UTILS.activateCuda(MODEL_G_C2F_32) MODEL_D_C2F_32 = NN_UTILS.activateCuda(MODEL_D_C2F_32) print("Sampling...") for run=1,OPT.runs do local images = NN_UTILS.createImages(1000, false) local imagesBest, predictions = NN_UTILS.sortImagesByPrediction(images, false, 64) local imagesWorst, predictions = NN_UTILS.sortImagesByPrediction(images, true, 64) local imagesRandom = selectRandomImagesFrom(images, 64) image.save(paths.concat(OPT.writeto, string.format('best_%04d_base.jpg', run)), toGrid(imagesBest, 8)) image.save(paths.concat(OPT.writeto, string.format('worst_%04d_base.jpg', run)), toGrid(imagesWorst, 8)) image.save(paths.concat(OPT.writeto, string.format('random_%04d_base.jpg', run)), toGrid(imagesRandom, 8)) local imagesBestC2F32 = c2f(imagesBest, MODEL_G_C2F_32, MODEL_D_C2F_32, 32) local imagesWorstC2F32 = c2f(imagesWorst, MODEL_G_C2F_32, MODEL_D_C2F_32, 32) local imagesRandomC2F32 = c2f(imagesRandom, MODEL_G_C2F_32, MODEL_D_C2F_32, 32) image.save(paths.concat(OPT.writeto, string.format('best_%04d_c2f_32.jpg', run)), toGrid(imagesBestC2F32, 8)) image.save(paths.concat(OPT.writeto, string.format('worst_%04d_c2f_32.jpg', run)), toGrid(imagesWorstC2F32, 8)) image.save(paths.concat(OPT.writeto, string.format('random_%04d_c2f_32.jpg', run)), toGrid(imagesRandomC2F32, 8)) xlua.progress(run, OPT.runs) end print("Finished.") end function c2f(images, G, D, fineSize) local triesPerImage = 10 local result = {} for i=1,#images do local imgTensor = torch.Tensor(triesPerImage, images[1]:size(1), fineSize, fineSize) local img = images[i]:clone() local height = img:size(2) local width = img:size(3) if height ~= fineSize or width ~= fineSize then img = image.scale(img, fineSize, fineSize) end for j=1,triesPerImage do imgTensor[j] = img:clone() end local noiseInputs = torch.Tensor(triesPerImage, 1, fineSize, fineSize) noiseInputs:uniform(-1, 1) local diffs = G:forward({noiseInputs, imgTensor}) --diffs:float() local predictions = D:forward({diffs, imgTensor}) local maxval = nil local maxdiff = nil for j=1,triesPerImage do if maxval == nil or predictions[j][1] > maxval then maxval = predictions[j][1] maxdiff = diffs[j] end end local imgRefined = torch.add(img, maxdiff) table.insert(result, imgRefined) end return result end function blur(img) print(img:size()) local ker = torch.ones(5) local m = nn.SpatialSubtractiveNormalization(1, ker) local processed = m:forward(img) image.display(img) image.display(processed) io.read() return processed end function toGrid(images, nrow) return image.toDisplayTensor{input=images, nrow=nrow} end function selectRandomImagesFrom(tensor, n) local shuffle = torch.randperm(tensor:size(1)) local result = {} for i=1,math.min(n, tensor:size(1)) do table.insert(result, tensor[ shuffle[i] ]) end return result end function loadModels() local file -- load G base file = torch.load(paths.concat(OPT.save_base, OPT.G_base)) local G = file.G -- load D base if OPT.D_base ~= OPT.G_base then file = torch.load(paths.concat(OPT.save_base, OPT.D_base)) end local D = file.D:float() -- load G c2f size 32 file = torch.load(paths.concat(OPT.save_c2f32, OPT.G_c2f32)) local G_c2f32 = file.G -- load D c2f size 32 if OPT.D_c2f32 ~= OPT.G_c2f32 then file = torch.load(paths.concat(OPT.save_c2f32, OPT.D_c2f32)) end local D_c2f32 = file.D return G, D, G_c2f32, D_c2f32 end main()
require 'torch' require 'image' require 'paths' require 'pl' require 'layers.cudnnSpatialConvolutionUpsample' NN_UTILS = require 'utils.nn_utils' OPT = lapp[[ --save_base (default "logs") directory in which the networks are saved --save_c2f32 (default "logs") --G_base (default "adversarial.net") --D_base (default "adversarial.net") --G_c2f32 (default "adversarial_c2f_16_to_32.net") --D_c2f32 (default "adversarial_c2f_16_to_32.net") --writeto (default "samples") directory to save the images to --seed (default 1) --gpu (default 0) GPU to run on --runs (default 3) How often to sample and save images --noiseDim (default 100) --batchSize (default 16) ]] print(OPT) if OPT.gpu < 0 then print("[ERROR] Sample script currently only runs on GPU, set --gpu=x where x is between 0 and 3.") exit() end torch.manualSeed(OPT.seed) print("Starting gpu support...") require 'cutorch' require 'cunn' torch.setdefaulttensortype('torch.FloatTensor') math.randomseed(OPT.seed) torch.manualSeed(OPT.seed) cutorch.setDevice(OPT.gpu + 1) cutorch.manualSeed(OPT.seed) function main() MODEL_G, MODEL_D, MODEL_G_C2F_32, MODEL_D_C2F_32 = loadModels() MODEL_G = NN_UTILS.activateCuda(MODEL_G) MODEL_D = NN_UTILS.activateCuda(MODEL_D) MODEL_G_C2F_32 = NN_UTILS.activateCuda(MODEL_G_C2F_32) MODEL_D_C2F_32 = NN_UTILS.activateCuda(MODEL_D_C2F_32) print("Sampling...") for run=1,OPT.runs do local images = NN_UTILS.createImages(1000, false) local imagesBest, predictions = NN_UTILS.sortImagesByPrediction(images, false, 64) local imagesWorst, predictions = NN_UTILS.sortImagesByPrediction(images, true, 64) local imagesRandom = selectRandomImagesFrom(images, 64) image.save(paths.concat(OPT.writeto, string.format('best_%04d_base.jpg', run)), toGrid(imagesBest, 8)) image.save(paths.concat(OPT.writeto, string.format('worst_%04d_base.jpg', run)), toGrid(imagesWorst, 8)) image.save(paths.concat(OPT.writeto, string.format('random_%04d_base.jpg', run)), toGrid(imagesRandom, 8)) local imagesBestC2F32 = c2f(imagesBest, MODEL_G_C2F_32, MODEL_D_C2F_32, 32) local imagesWorstC2F32 = c2f(imagesWorst, MODEL_G_C2F_32, MODEL_D_C2F_32, 32) local imagesRandomC2F32 = c2f(imagesRandom, MODEL_G_C2F_32, MODEL_D_C2F_32, 32) image.save(paths.concat(OPT.writeto, string.format('best_%04d_c2f_32.jpg', run)), toGrid(imagesBestC2F32, 8)) image.save(paths.concat(OPT.writeto, string.format('worst_%04d_c2f_32.jpg', run)), toGrid(imagesWorstC2F32, 8)) image.save(paths.concat(OPT.writeto, string.format('random_%04d_c2f_32.jpg', run)), toGrid(imagesRandomC2F32, 8)) xlua.progress(run, OPT.runs) end print("Finished.") end function c2f(images, G, D, fineSize) local triesPerImage = 10 local result = {} for i=1,#images do local imgTensor = torch.Tensor(triesPerImage, images[1]:size(1), fineSize, fineSize) local img = images[i]:clone() local height = img:size(2) local width = img:size(3) if height ~= fineSize or width ~= fineSize then img = image.scale(img, fineSize, fineSize) end for j=1,triesPerImage do imgTensor[j] = img:clone() end local noiseInputs = torch.Tensor(triesPerImage, 1, fineSize, fineSize) noiseInputs:uniform(-1, 1) local diffs = G:forward({noiseInputs, imgTensor}) --diffs:float() local predictions = D:forward({diffs, imgTensor}) local maxval = nil local maxdiff = nil for j=1,triesPerImage do if maxval == nil or predictions[j][1] > maxval then maxval = predictions[j][1] maxdiff = diffs[j] end end local imgRefined = torch.add(img, maxdiff) table.insert(result, imgRefined) end return result end function blur(img) local img2 = image.convolve(img:clone(), image.gaussian(3), "same") return img2 end function toGrid(images, nrow) return image.toDisplayTensor{input=images, nrow=nrow} end function selectRandomImagesFrom(tensor, n) local shuffle = torch.randperm(tensor:size(1)) local result = {} for i=1,math.min(n, tensor:size(1)) do table.insert(result, tensor[ shuffle[i] ]) end return result end function loadModels() local file -- load G base file = torch.load(paths.concat(OPT.save_base, OPT.G_base)) local G = file.G -- load D base if OPT.D_base ~= OPT.G_base then file = torch.load(paths.concat(OPT.save_base, OPT.D_base)) end local D = file.D:float() -- load G c2f size 32 file = torch.load(paths.concat(OPT.save_c2f32, OPT.G_c2f32)) local G_c2f32 = file.G -- load D c2f size 32 if OPT.D_c2f32 ~= OPT.G_c2f32 then file = torch.load(paths.concat(OPT.save_c2f32, OPT.D_c2f32)) end local D_c2f32 = file.D return G, D, G_c2f32, D_c2f32 end main()
Fix blur function
Fix blur function
Lua
mit
aleju/face-generator
4630c27bc3cc46b382d93b7d4917f856cddfe025
lib/hpcpf.lua
lib/hpcpf.lua
--- for detection platform (return "Windows", "Darwin" or "Linux") function getPlatform() --- command capture function captureRedirectErr(cmd) local f = assert(io.popen(cmd .. ' 2>&1' , 'r')) local s = assert(f:read('*a')) f:close() s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end local plf = captureRedirectErr('uname') if string.sub(plf,1,8) == "'uname' " then -- not found 'uname' cmd return 'Windows' else return plf -- 'Darwin', 'Linux' end end -- force buffer flush function if getPlatform() == 'Windows' then orgPrint = print print = function(...) orgPrint(...) io.stdout:flush() end end -- File/Dir Utility fuctions function compressFile(srcname, tarname, verbose, opt) local tarcmd local optcmd = opt and opt or '' local option = (verbose == true) and '-czvf' or '-czf' if (getPlatform() == 'Windows') then local TAR_CMD = HPCPF_BIN_DIR .. '/tar.exe' tarcmd = TAR_CMD .. ' ' .. optcmd .. ' ' .. option .. ' ' .. tarname .. ' ' .. srcname else local TAR_CMD = 'tar' tarcmd = TAR_CMD .. ' ' .. optcmd .. ' ' .. option .. ' ' .. tarname .. ' ' .. srcname end print(tarcmd) local handle = io.popen(tarcmd) local result = handle:read("*a") handle:close() return result end function extractFile(tarname, verbose, opt) local tarcmd local optcmd = opt and opt or '' local option = verbose and '-xvf' or '-xf' if (getPlatform() == 'Windows') then local TAR_CMD = HPCPF_BIN_DIR .. '/tar.exe' tarcmd = TAR_CMD .. ' ' .. optcmd .. ' '.. option .. ' ' .. tarname else local TAR_CMD = 'tar' tarcmd = TAR_CMD .. ' ' .. optcmd .. ' '.. option .. ' ' .. tarname end print(tarcmd) local handle = io.popen(tarcmd) local result = handle:read("*a") handle:close() return result end function deleteFile(filename) local rmcmd if (getPlatform() == 'Windows') then rmcmd = 'del /Q' else rmcmd = 'rm ' end local cmd = rmcmd .. ' ' .. filename local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end function deleteDir(dirname) local rmcmd if (getPlatform() == 'Windows') then rmcmd = 'rd /q /s' else rmcmd = 'rm -rf' end local cmd = rmcmd .. ' ' .. dirname local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end function moveFile(fromFile, toFile) local mvcmd if (getPlatform() == 'Windows') then mvcmd = 'move' else mvcmd = 'mv' end local cmd = mvcmd .. ' ' .. fromFile .. ' ' .. toFile local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end function copyFile(fromFile, toFile) local cpcmd if (getPlatform() == 'Windows') then cpcmd = 'copy' else cpcmd = 'cp' end local cmd = cpcmd .. ' ' .. fromFile .. ' ' .. toFile local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end function makeDir(dirpath) local mkcmd = 'mkdir' local cmd = mkcmd .. ' ' .. dirpath local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end --- Lua Utility function dumpTable(t,prefix) if (prefix==nil) then prefix="" end for i,v in pairs(t) do print(prefix,i,v) if (type(v)=='table') then dumpTable(v,prefix.."-") end end end --- execution for CASE local s_base_path="" function setBasePath(dir) s_base_path = dir end function getBasePath() return s_base_path end function execmd(command) local handle = io.popen(command,"r") local content = handle:read("*all") handle:close() return content end function getCurrentDir() local pwdcmd if (getPlatform() == 'Windows') then pwdcmd = 'cd' else pwdcmd = 'pwd' end return execmd(pwdcmd):gsub('\n','') end function executeCASE(casename,...) local args_table = {...} --print("num="..#args_table) local cf = loadfile('./'..casename..'/cwf.lua'); if (cf == nil) then print("Can't find Case work flow:"..casename) print("or can't find " .. casename..'/cwf.lua') else print("--- Start CASE: "..casename.." ---") setBasePath('/' .. casename) local oldPackagePath = package.path package.path = "./" .. casename .. "/?.lua;" .. oldPackagePath cf(args_table) package.path = oldPackagePath setBasePath('') print("--- End CASE: "..casename.." ---") end end --- JSON loader local json = require('dkjson') function readJSON(filename) local filestr = '' local fp = io.open(s_base_path..filename,'r'); local jst = nil if (fp) then filestr = fp:read("*all") jst = json.decode (filestr, 1, nil) end return jst; end --- Sleep function sleep(n) if getPlatform() == 'Windows' then --os.execute("timeout /NOBREAK /T " .. math.floor(tonumber(n)) .. ' > nul') local cmd = HPCPF_BIN_DIR .. '/sleeper.exe ' .. math.floor(n) os.execute(cmd) else os.execute("sleep " .. tonumber(n)) end end -- xjob require('xjob')
--- for detection platform (return "Windows", "Darwin" or "Linux") function getPlatform() --- command capture function captureRedirectErr(cmd) local f = assert(io.popen(cmd .. ' 2>&1' , 'r')) local s = assert(f:read('*a')) f:close() s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end if package.config:sub(1,1) == "\\" then return 'Windows' else local plf = captureRedirectErr('uname') return plf -- 'Darwin', 'Linux' end end -- force buffer flush function if getPlatform() == 'Windows' then orgPrint = print print = function(...) orgPrint(...) io.stdout:flush() end end -- File/Dir Utility fuctions function compressFile(srcname, tarname, verbose, opt) local tarcmd local optcmd = opt and opt or '' local option = (verbose == true) and '-czvf' or '-czf' if (getPlatform() == 'Windows') then local TAR_CMD = HPCPF_BIN_DIR .. '/tar.exe' tarcmd = TAR_CMD .. ' ' .. optcmd .. ' ' .. option .. ' ' .. tarname .. ' ' .. srcname else local TAR_CMD = 'tar' tarcmd = TAR_CMD .. ' ' .. optcmd .. ' ' .. option .. ' ' .. tarname .. ' ' .. srcname end print(tarcmd) local handle = io.popen(tarcmd) local result = handle:read("*a") handle:close() return result end function extractFile(tarname, verbose, opt) local tarcmd local optcmd = opt and opt or '' local option = verbose and '-xvf' or '-xf' if (getPlatform() == 'Windows') then local TAR_CMD = HPCPF_BIN_DIR .. '/tar.exe' tarcmd = TAR_CMD .. ' ' .. optcmd .. ' '.. option .. ' ' .. tarname else local TAR_CMD = 'tar' tarcmd = TAR_CMD .. ' ' .. optcmd .. ' '.. option .. ' ' .. tarname end print(tarcmd) local handle = io.popen(tarcmd) local result = handle:read("*a") handle:close() return result end function deleteFile(filename) local rmcmd if (getPlatform() == 'Windows') then rmcmd = 'del /Q' else rmcmd = 'rm ' end local cmd = rmcmd .. ' ' .. filename local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end function deleteDir(dirname) local rmcmd if (getPlatform() == 'Windows') then rmcmd = 'rd /q /s' else rmcmd = 'rm -rf' end local cmd = rmcmd .. ' ' .. dirname local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end function moveFile(fromFile, toFile) local mvcmd if (getPlatform() == 'Windows') then mvcmd = 'move' else mvcmd = 'mv' end local cmd = mvcmd .. ' ' .. fromFile .. ' ' .. toFile local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end function copyFile(fromFile, toFile) local cpcmd if (getPlatform() == 'Windows') then cpcmd = 'copy' else cpcmd = 'cp' end local cmd = cpcmd .. ' ' .. fromFile .. ' ' .. toFile local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end function makeDir(dirpath) local mkcmd = 'mkdir' local cmd = mkcmd .. ' ' .. dirpath local handle = io.popen(cmd) local result = handle:read("*a") handle:close() return result end --- Lua Utility function dumpTable(t,prefix) if (prefix==nil) then prefix="" end for i,v in pairs(t) do print(prefix,i,v) if (type(v)=='table') then dumpTable(v,prefix.."-") end end end --- execution for CASE local s_base_path="" function setBasePath(dir) s_base_path = dir end function getBasePath() return s_base_path end function execmd(command) local handle = io.popen(command,"r") local content = handle:read("*all") handle:close() return content end function getCurrentDir() local pwdcmd if (getPlatform() == 'Windows') then pwdcmd = 'cd' else pwdcmd = 'pwd' end return execmd(pwdcmd):gsub('\n','') end function executeCASE(casename,...) local args_table = {...} --print("num="..#args_table) local cf = loadfile('./'..casename..'/cwf.lua'); if (cf == nil) then print("Can't find Case work flow:"..casename) print("or can't find " .. casename..'/cwf.lua') else print("--- Start CASE: "..casename.." ---") setBasePath('/' .. casename) local oldPackagePath = package.path package.path = "./" .. casename .. "/?.lua;" .. oldPackagePath cf(args_table) package.path = oldPackagePath setBasePath('') print("--- End CASE: "..casename.." ---") end end --- JSON loader local json = require('dkjson') function readJSON(filename) local filestr = '' local fp = io.open(s_base_path..filename,'r'); local jst = nil if (fp) then filestr = fp:read("*all") jst = json.decode (filestr, 1, nil) end return jst; end --- Sleep function sleep(n) if getPlatform() == 'Windows' then --os.execute("timeout /NOBREAK /T " .. math.floor(tonumber(n)) .. ' > nul') local cmd = HPCPF_BIN_DIR .. '/sleeper.exe ' .. math.floor(n) os.execute(cmd) else os.execute("sleep " .. tonumber(n)) end end -- xjob require('xjob')
fix windows platform detection
fix windows platform detection
Lua
bsd-2-clause
avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI,avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI,digirea/hpcpfGUI,avr-aics-riken/hpcpfGUI
c06edde57b047f96897eb54b7bea801a1d09703c
rbxmk/testdata/path/rel.lua
rbxmk/testdata/path/rel.lua
-- https://github.com/golang/go/blob/9cd1818a7d019c02fa4898b3e45a323e35033290/src/path/filepath/path_test.go#L1188-L1240 local tests = { -- base , target , result { "a/b" , "a/b" , "." }, { "a/b/." , "a/b" , "." }, { "a/b" , "a/b/." , "." }, { "./a/b" , "a/b" , "." }, { "a/b" , "./a/b" , "." }, { "ab/cd" , "ab/cde" , "../cde" }, { "ab/cd" , "ab/c" , "../c" }, { "a/b" , "a/b/c/d" , "c/d" }, { "a/b" , "a/b/../c" , "../c" }, { "a/b/../c" , "a/b" , "../b" }, { "a/b/c" , "a/c/d" , "../../c/d" }, { "a/b" , "c/d" , "../../c/d" }, { "a/b/c/d" , "a/b" , "../.." }, { "a/b/c/d" , "a/b/" , "../.." }, { "a/b/c/d/" , "a/b" , "../.." }, { "a/b/c/d/" , "a/b/" , "../.." }, { "../../a/b" , "../../a/b/c/d" , "c/d" }, { "/a/b" , "/a/b" , "." }, { "/a/b/." , "/a/b" , "." }, { "/a/b" , "/a/b/." , "." }, { "/ab/cd" , "/ab/cde" , "../cde" }, { "/ab/cd" , "/ab/c" , "../c" }, { "/a/b" , "/a/b/c/d" , "c/d" }, { "/a/b" , "/a/b/../c" , "../c" }, { "/a/b/../c" , "/a/b" , "../b" }, { "/a/b/c" , "/a/c/d" , "../../c/d" }, { "/a/b" , "/c/d" , "../../c/d" }, { "/a/b/c/d" , "/a/b" , "../.." }, { "/a/b/c/d" , "/a/b/" , "../.." }, { "/a/b/c/d/" , "/a/b" , "../.." }, { "/a/b/c/d/" , "/a/b/" , "../.." }, { "/../../a/b" , "/../../a/b/c/d" , "c/d" }, { "." , "a/b" , "a/b" }, { "." , ".." , ".." }, {".." , "." , nil }, {".." , "a" , nil }, {"../.." , ".." , nil }, {"a" , "/a" , nil }, {"/a" , "a" , nil }, {[[C:a\b\c]] , [[C:a/b/d]] , [[..\d]] }, {[[C:\]] , [[D:\]] , nil }, {[[C:]] , [[D:]] , nil }, {[[C:\Projects]] , [[c:\projects\src]] , [[src]] }, {[[C:\Projects]] , [[c:\projects]] , [[.]] }, {[[C:\Projects\a\..]] , [[c:\projects]] , [[.]] }, {[[\\host\share]] , [[\\host\share\file.txt]] , [[file.txt]] }, } for i, test in ipairs(tests) do local result = path.rel(test[1], test[2]) if result then T.Pass(result == path.clean(test[3]), string.format("test %d: expected %q, got %q", i, path.clean(test[3]), result)) else T.Pass(result == test[3], "test " .. i .. ": nil result does not match") end end
-- https://github.com/golang/go/blob/9cd1818a7d019c02fa4898b3e45a323e35033290/src/path/filepath/path_test.go#L1188-L1240 local tests = { -- base , target , result { "a/b" , "a/b" , "." }, { "a/b/." , "a/b" , "." }, { "a/b" , "a/b/." , "." }, { "./a/b" , "a/b" , "." }, { "a/b" , "./a/b" , "." }, { "ab/cd" , "ab/cde" , "../cde" }, { "ab/cd" , "ab/c" , "../c" }, { "a/b" , "a/b/c/d" , "c/d" }, { "a/b" , "a/b/../c" , "../c" }, { "a/b/../c" , "a/b" , "../b" }, { "a/b/c" , "a/c/d" , "../../c/d" }, { "a/b" , "c/d" , "../../c/d" }, { "a/b/c/d" , "a/b" , "../.." }, { "a/b/c/d" , "a/b/" , "../.." }, { "a/b/c/d/" , "a/b" , "../.." }, { "a/b/c/d/" , "a/b/" , "../.." }, { "../../a/b" , "../../a/b/c/d" , "c/d" }, { "/a/b" , "/a/b" , "." }, { "/a/b/." , "/a/b" , "." }, { "/a/b" , "/a/b/." , "." }, { "/ab/cd" , "/ab/cde" , "../cde" }, { "/ab/cd" , "/ab/c" , "../c" }, { "/a/b" , "/a/b/c/d" , "c/d" }, { "/a/b" , "/a/b/../c" , "../c" }, { "/a/b/../c" , "/a/b" , "../b" }, { "/a/b/c" , "/a/c/d" , "../../c/d" }, { "/a/b" , "/c/d" , "../../c/d" }, { "/a/b/c/d" , "/a/b" , "../.." }, { "/a/b/c/d" , "/a/b/" , "../.." }, { "/a/b/c/d/" , "/a/b" , "../.." }, { "/a/b/c/d/" , "/a/b/" , "../.." }, { "/../../a/b" , "/../../a/b/c/d" , "c/d" }, { "." , "a/b" , "a/b" }, { "." , ".." , ".." }, {".." , "." , nil }, {".." , "a" , nil }, {"../.." , ".." , nil }, {"a" , "/a" , nil }, {"/a" , "a" , nil }, {win=true, [[C:a\b\c]] , [[C:a/b/d]] , [[..\d]] }, {win=true, [[C:\]] , [[D:\]] , nil }, {win=true, [[C:]] , [[D:]] , nil }, {win=true, [[C:\Projects]] , [[c:\projects\src]] , [[src]] }, {win=true, [[C:\Projects]] , [[c:\projects]] , [[.]] }, {win=true, [[C:\Projects\a\..]] , [[c:\projects]] , [[.]] }, {win=true, [[\\host\share]] , [[\\host\share\file.txt]] , [[file.txt]] }, } local windows = path.clean("/") == "\\" for i, test in ipairs(tests) do if not not test.win == windows then local result = path.rel(test[1], test[2]) if result then local expected = path.clean(test[3]) T.Pass(result == expected, string.format("test %d: expected %q, got %q", i, expected, result)) else T.Pass(result == test[3], "test " .. i .. ": nil result does not match") end end end
Fix windows tests.
Fix windows tests.
Lua
mit
Anaminus/rbxmk,Anaminus/rbxmk
4aedb356781d2c0f238621bf0d5d71efb2d898ef
lexers/markdown.lua
lexers/markdown.lua
-- Copyright 2006-2015 Mitchell mitchell.att.foicica.com. See LICENSE. -- Markdown LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'markdown'} -- Whitespace. local ws = token(l.WHITESPACE, S(' \t\v')^1) local newline = token(l.WHITESPACE, S('\r\n\f')^1) -- Block elements. local header = token('h6', l.starts_line('######') * l.nonnewline^0) + token('h5', l.starts_line('#####') * l.nonnewline^0) + token('h4', l.starts_line('####') * l.nonnewline^0) + token('h3', l.starts_line('###') * l.nonnewline^0) + token('h2', l.starts_line('##') * l.nonnewline^0) + token('h1', l.starts_line('#') * l.nonnewline^0) local blockquote = token(l.STRING, lpeg.Cmt(l.starts_line(S(' \t')^0 * '>'), function(input, index) local _, e = input:find('\n[ \t]*\r?\n', index) return (e or #input) + 1 end)) local blockcode = token('code', l.starts_line(P(' ')^4 + P('\t')) * -P('<') * l.nonnewline^0) local hr = token('hr', lpeg.Cmt(l.starts_line(S(' \t')^0 * lpeg.C(S('*-_'))), function(input, index, c) local line = input:match('[^\n]*', index) line = line:gsub('[ \t]', '') if line:find('[^'..c..']') or #line < 2 then return nil end return (input:find('\n', index) or #input) + 1 end)) -- Span elements. local dq_str = token(l.STRING, l.delimited_range('"', false, true)) local sq_str = token(l.STRING, l.delimited_range("'", false, true)) local paren_str = token(l.STRING, l.delimited_range('()')) local link = token('link', P('!')^-1 * l.delimited_range('[]') * (P('(') * (l.any - S(') \t'))^0 * (S(' \t')^1 * l.delimited_range('"', false, true))^-1 * ')' + S(' \t')^0 * l.delimited_range('[]')) + P('http://') * (l.any - l.space)^1) local link_label = ws^0 * token('link_label', l.delimited_range('[]') * ':') * ws * token('link_url', (l.any - l.space)^1) * (ws * (dq_str + sq_str + paren_str))^-1 local strong = token('strong', (P('**') * (l.any - '**')^0 * P('**')^-1) + (P('__') * (l.any - '__')^0 * P('__')^-1)) local em = token('em', l.delimited_range('*', true) + l.delimited_range('_', true)) local code = token('code', (P('``') * (l.any - '``')^0 * P('``')^-1) + l.delimited_range('`', true)) local escape = token(l.DEFAULT, P('\\') * 1) local list = token('list', l.starts_line(S(' \t')^0 * (S('*+-') + R('09')^1 * '.')) * S(' \t')) M._rules = { {'header', header}, {'blockquote', blockquote}, {'blockcode', blockcode}, {'hr', hr}, {'list', list}, {'whitespace', ws + newline}, {'link_label', link_label}, {'escape', escape}, {'link', link}, {'strong', strong}, {'em', em}, {'code', code}, } local font_size = 10 local hstyle = 'fore:$(color.red)' M._tokenstyles = { h6 = hstyle, h5 = hstyle..',size:'..(font_size + 1), h4 = hstyle..',size:'..(font_size + 2), h3 = hstyle..',size:'..(font_size + 3), h2 = hstyle..',size:'..(font_size + 4), h1 = hstyle..',size:'..(font_size + 5), code = l.STYLE_EMBEDDED..',eolfilled', hr = 'back:$(color.black),eolfilled', link = 'underlined', link_url = 'underlined', link_label = l.STYLE_LABEL, strong = 'bold', em = 'italics', list = l.STYLE_CONSTANT, } -- Embedded HTML. local html = l.load('html') local start_rule = token('tag', l.starts_line(S(' \t')^0 * '<')) local end_rule = token(l.DEFAULT, P('\n')) -- TODO: l.WHITESPACE causes errors l.embed_lexer(M, html, start_rule, end_rule) return M
-- Copyright 2006-2015 Mitchell mitchell.att.foicica.com. See LICENSE. -- Markdown LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'markdown'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Block elements. local header = token('h6', l.starts_line('######') * l.nonnewline^0) + token('h5', l.starts_line('#####') * l.nonnewline^0) + token('h4', l.starts_line('####') * l.nonnewline^0) + token('h3', l.starts_line('###') * l.nonnewline^0) + token('h2', l.starts_line('##') * l.nonnewline^0) + token('h1', l.starts_line('#') * l.nonnewline^0) local blockquote = token(l.STRING, lpeg.Cmt(l.starts_line(S(' \t')^0 * '>'), function(input, index) local _, e = input:find('\n[ \t]*\r?\n', index) return (e or #input) + 1 end)) local blockcode = token('code', l.starts_line(P(' ')^4 + P('\t')) * -P('<') * l.nonnewline^0) local hr = token('hr', lpeg.Cmt(l.starts_line(S(' \t')^0 * lpeg.C(S('*-_'))), function(input, index, c) local line = input:match('[^\n]*', index) line = line:gsub('[ \t]', '') if line:find('[^'..c..']') or #line < 2 then return nil end return (input:find('\n', index) or #input) + 1 end)) -- Span elements. local dq_str = token(l.STRING, l.delimited_range('"', false, true)) local sq_str = token(l.STRING, l.delimited_range("'", false, true)) local paren_str = token(l.STRING, l.delimited_range('()')) local link = token('link', P('!')^-1 * l.delimited_range('[]') * (P('(') * (l.any - S(') \t'))^0 * (S(' \t')^1 * l.delimited_range('"', false, true))^-1 * ')' + S(' \t')^0 * l.delimited_range('[]')) + P('http://') * (l.any - l.space)^1) local link_label = token('link_label', l.delimited_range('[]') * ':') * ws * token('link_url', (l.any - l.space)^1) * (ws * (dq_str + sq_str + paren_str))^-1 local strong = token('strong', (P('**') * (l.any - '**')^0 * P('**')^-1) + (P('__') * (l.any - '__')^0 * P('__')^-1)) local em = token('em', l.delimited_range('*', true) + l.delimited_range('_', true)) local code = token('code', (P('``') * (l.any - '``')^0 * P('``')^-1) + l.delimited_range('`', true, true)) local escape = token(l.DEFAULT, P('\\') * 1) local list = token('list', l.starts_line(S(' \t')^0 * (S('*+-') + R('09')^1 * '.')) * S(' \t')) M._rules = { {'header', header}, {'blockquote', blockquote}, {'blockcode', blockcode}, {'hr', hr}, {'list', list}, {'whitespace', ws}, {'link_label', link_label}, {'escape', escape}, {'link', link}, {'strong', strong}, {'em', em}, {'code', code}, } local font_size = 10 local hstyle = 'fore:$(color.red)' M._tokenstyles = { h6 = hstyle, h5 = hstyle..',size:'..(font_size + 1), h4 = hstyle..',size:'..(font_size + 2), h3 = hstyle..',size:'..(font_size + 3), h2 = hstyle..',size:'..(font_size + 4), h1 = hstyle..',size:'..(font_size + 5), code = l.STYLE_EMBEDDED..',eolfilled', hr = 'back:$(color.black),eolfilled', link = 'underlined', link_url = 'underlined', link_label = l.STYLE_LABEL, strong = 'bold', em = 'italics', list = l.STYLE_CONSTANT, } -- Embedded HTML. local html = l.load('html') local start_rule = token('tag', l.starts_line(S(' \t')^0 * '<')) local end_rule = token(l.DEFAULT, P('\n')) -- TODO: l.WHITESPACE causes errors l.embed_lexer(M, html, start_rule, end_rule) return M
Fixed Markdown lexer corner-cases; lexers/markdown.lua Thanks to Giovanni Salmeri.
Fixed Markdown lexer corner-cases; lexers/markdown.lua Thanks to Giovanni Salmeri.
Lua
mit
rgieseke/scintillua
f4efdb3607a2fef4d7f126cd04f31530e2a969a2
lib/MySQL.lua
lib/MySQL.lua
MySQL = { Async = {}, Sync = {}, } local function safeParameters(params) if nil == params then return {[''] = ''} end assert(type(params) == "table", "A table is expected") assert(params[1] == nil, "Parameters should not be an array, but a map (key / value pair) instead") if next(params) == nil then return {[''] = ''} end return params end --- -- Execute a query with no result required, sync version -- -- @param query -- @param params -- -- @return int Number of rows updated -- function MySQL.Sync.execute(query, params) assert(type(query) == "string", "The SQL Query must be a string") local res = 0 local finishedQuery = false exports['mysql-async']:mysql_execute(query, safeParameters(params), function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a query and fetch all results in an sync way -- -- @param query -- @param params -- -- @return table Query results -- function MySQL.Sync.fetchAll(query, params) assert(type(query) == "string", "The SQL Query must be a string") local res = {} local finishedQuery = false exports['mysql-async']:mysql_fetch_all(query, safeParameters(params), function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a query and fetch the first column of the first row, sync version -- Useful for count function by example -- -- @param query -- @param params -- -- @return mixed Value of the first column in the first row -- function MySQL.Sync.fetchScalar(query, params) assert(type(query) == "string", "The SQL Query must be a string") local res = '' local finishedQuery = false exports['mysql-async']:mysql_fetch_scalar(query, safeParameters(params), function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a query and retrieve the last id insert, sync version -- -- @param query -- @param params -- -- @return mixed Value of the last insert id -- function MySQL.Sync.insert(query, params) assert(type(query) == "string", "The SQL Query must be a string") local res = 0 local finishedQuery = false exports['mysql-async']:mysql_insert(query, safeParameters(params), function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Stores a query for later execution -- -- @param query -- function MySQL.Sync.store(query) assert(type(query) == "string", "The SQL Query must be a string") local res = -1 local finishedQuery = false exports['mysql-async']:mysql_store(query, function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a List of querys and returns bool true when all are executed successfully -- -- @param querys -- @param params -- -- @return bool if the transaction was successful -- function MySQL.Sync.transaction(querys, params) local res = 0 local finishedQuery = false exports['mysql-async']:mysql_transaction(querys, params, function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a query with no result required, async version -- -- @param query -- @param params -- @param func(int) -- function MySQL.Async.execute(query, params, func) assert(type(query) == "string", "The SQL Query must be a string") exports['mysql-async']:mysql_execute(query, safeParameters(params), func) end --- -- Execute a query and fetch all results in an async way -- -- @param query -- @param params -- @param func(table) -- function MySQL.Async.fetchAll(query, params, func) assert(type(query) == "string", "The SQL Query must be a string") exports['mysql-async']:mysql_fetch_all(query, safeParameters(params), func) end --- -- Execute a query and fetch the first column of the first row, async version -- Useful for count function by example -- -- @param query -- @param params -- @param func(mixed) -- function MySQL.Async.fetchScalar(query, params, func) assert(type(query) == "string", "The SQL Query must be a string") exports['mysql-async']:mysql_fetch_scalar(query, safeParameters(params), func) end --- -- Execute a query and retrieve the last id insert, async version -- -- @param query -- @param params -- @param func(string) -- function MySQL.Async.insert(query, params, func) assert(type(query) == "string", "The SQL Query must be a string") exports['mysql-async']:mysql_insert(query, safeParameters(params), func) end --- -- Stores a query for later execution -- -- @param query -- @param func(number) -- function MySQL.Async.store(query, func) assert(type(query) == "string", "The SQL Query must be a string") exports['mysql-async']:mysql_store(query, func) end --- -- Execute a List of querys and returns bool true when all are executed successfully -- -- @param querys -- @param params -- @param func(bool) -- function MySQL.Async.transaction(querys, params, func) return exports['mysql-async']:mysql_transaction(querys, params, func) end function MySQL.ready (callback) Citizen.CreateThread(function () -- add some more error handling while GetResourceState('mysql-async') ~= 'started' do Citizen.Wait(0) end while not exports['mysql-async']:is_ready() do Citizen.Wait(0) end callback() end) end
MySQL = { Async = {}, Sync = {}, } local function safeParameters(params) if nil == params then return {[''] = ''} end assert(type(params) == "table", "A table is expected") if next(params) == nil then return {[''] = ''} end return params end --- -- Execute a query with no result required, sync version -- -- @param query -- @param params -- -- @return int Number of rows updated -- function MySQL.Sync.execute(query, params) assert(type(query) == "string" or type(query) == "number", "The SQL Query must be a string") local res = 0 local finishedQuery = false exports['mysql-async']:mysql_execute(query, safeParameters(params), function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a query and fetch all results in an sync way -- -- @param query -- @param params -- -- @return table Query results -- function MySQL.Sync.fetchAll(query, params) assert(type(query) == "string" or type(query) == "number", "The SQL Query must be a string") local res = {} local finishedQuery = false exports['mysql-async']:mysql_fetch_all(query, safeParameters(params), function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a query and fetch the first column of the first row, sync version -- Useful for count function by example -- -- @param query -- @param params -- -- @return mixed Value of the first column in the first row -- function MySQL.Sync.fetchScalar(query, params) assert(type(query) == "string" or type(query) == "number", "The SQL Query must be a string") local res = '' local finishedQuery = false exports['mysql-async']:mysql_fetch_scalar(query, safeParameters(params), function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a query and retrieve the last id insert, sync version -- -- @param query -- @param params -- -- @return mixed Value of the last insert id -- function MySQL.Sync.insert(query, params) assert(type(query) == "string" or type(query) == "number", "The SQL Query must be a string") local res = 0 local finishedQuery = false exports['mysql-async']:mysql_insert(query, safeParameters(params), function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Stores a query for later execution -- -- @param query -- function MySQL.Sync.store(query) assert(type(query) == "string", "The SQL Query must be a string") local res = -1 local finishedQuery = false exports['mysql-async']:mysql_store(query, function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a List of querys and returns bool true when all are executed successfully -- -- @param querys -- @param params -- -- @return bool if the transaction was successful -- function MySQL.Sync.transaction(querys, params) local res = 0 local finishedQuery = false exports['mysql-async']:mysql_transaction(querys, params, function (result) res = result finishedQuery = true end) repeat Citizen.Wait(0) until finishedQuery == true return res end --- -- Execute a query with no result required, async version -- -- @param query -- @param params -- @param func(int) -- function MySQL.Async.execute(query, params, func) assert(type(query) == "string" or type(query) == "number", "The SQL Query must be a string") exports['mysql-async']:mysql_execute(query, safeParameters(params), func) end --- -- Execute a query and fetch all results in an async way -- -- @param query -- @param params -- @param func(table) -- function MySQL.Async.fetchAll(query, params, func) assert(type(query) == "string" or type(query) == "number", "The SQL Query must be a string") exports['mysql-async']:mysql_fetch_all(query, safeParameters(params), func) end --- -- Execute a query and fetch the first column of the first row, async version -- Useful for count function by example -- -- @param query -- @param params -- @param func(mixed) -- function MySQL.Async.fetchScalar(query, params, func) assert(type(query) == "string" or type(query) == "number", "The SQL Query must be a string") exports['mysql-async']:mysql_fetch_scalar(query, safeParameters(params), func) end --- -- Execute a query and retrieve the last id insert, async version -- -- @param query -- @param params -- @param func(string) -- function MySQL.Async.insert(query, params, func) assert(type(query) == "string" or type(query) == "number", "The SQL Query must be a string") exports['mysql-async']:mysql_insert(query, safeParameters(params), func) end --- -- Stores a query for later execution -- -- @param query -- @param func(number) -- function MySQL.Async.store(query, func) assert(type(query) == "string", "The SQL Query must be a string") exports['mysql-async']:mysql_store(query, func) end --- -- Execute a List of querys and returns bool true when all are executed successfully -- -- @param querys -- @param params -- @param func(bool) -- function MySQL.Async.transaction(querys, params, func) return exports['mysql-async']:mysql_transaction(querys, params, func) end function MySQL.ready (callback) Citizen.CreateThread(function () -- add some more error handling while GetResourceState('mysql-async') ~= 'started' do Citizen.Wait(0) end while not exports['mysql-async']:is_ready() do Citizen.Wait(0) end callback() end) end
fix: store
fix: store
Lua
mit
brouznouf/fivem-mysql-async,brouznouf/fivem-mysql-async,brouznouf/fivem-mysql-async
36ab992a3c80081cee7cf2120f2c0a2e4b9d3a4c
scen_edit/view/trigger/areas_window.lua
scen_edit/view/trigger/areas_window.lua
SB.Include(Path.Join(SB_VIEW_DIR, "editor.lua")) AreasWindow = Editor:extends{} Editor.Register({ name = "areasWindow", editor = AreasWindow, tab = "Logic", caption = "Area", tooltip = "Edit areas", image = SB_IMG_DIR .. "bolivia.png", order = 0, }) function AreasWindow:init() self:super("init") self.btnAddArea = TabbedPanelButton({ x = 0, y = 0, tooltip = "Add area", children = { TabbedPanelImage({ file = SB_IMG_DIR .. "area-add.png" }), TabbedPanelLabel({ caption = "Add" }), }, OnClick = { function() SB.stateManager:SetState(AddRectState(self)) end }, }) self:AddDefaultKeybinding({ self.btnAddArea }) self.areasPanel = StackPanel:New { itemMargin = {0, 0, 0, 0}, width = "100%", autosize = true, resizeItems = false, } local children = { ScrollPanel:New { x = 0, y = 80, bottom = 30, right = 0, borderColor = {0,0,0,0}, horizontalScrollbar = false, children = { self.areasPanel }, }, self.btnAddArea, } self:Populate() local areaManagerListener = AreaManagerListenerWidget(self) SB.model.areaManager:addListener(areaManagerListener) self:Finalize(children) end function AreasWindow:Populate() self.areasPanel:ClearChildren() local areas = SB.model.areaManager:getAllAreas() for _, areaID in pairs(areas) do local areaStackPanel = MakeComponentPanel(self.areasPanel) areaStackPanel.areaID = areaID local lblArea = Label:New { caption = "Area ID: " .. tostring(areaID), right = SB.conf.B_HEIGHT + 10, x = 1, height = SB.conf.B_HEIGHT, _toggle = nil, parent = areaStackPanel, } local btnFindArea = Button:New { caption = "", right = SB.conf.B_HEIGHT + 8, width = SB.conf.B_HEIGHT, height = SB.conf.B_HEIGHT, parent = areaStackPanel, padding = {0, 0, 0, 0}, tooltip = "Center camera on area", children = { Image:New { file = SB_IMG_DIR .. "position-marker.png", height = SB.conf.B_HEIGHT, width = SB.conf.B_HEIGHT, padding = {0, 0, 0, 0}, margin = {0, 0, 0, 0}, }, }, OnClick = { function() local area = SB.model.areaManager:getArea(areaID) if area ~= nil then local x = (area[1] + area[3]) / 2 local z = (area[2] + area[4]) / 2 local y = Spring.GetGroundHeight(x, z) Spring.SetCameraTarget(x, y, z) end end }, } local btnRemoveArea = Button:New { caption = "", right = 0, width = SB.conf.B_HEIGHT, height = SB.conf.B_HEIGHT, parent = areaStackPanel, padding = {2, 2, 2, 2}, tooltip = "Remove area", classname = "negative_button", children = { Image:New { file = SB_IMG_DIR .. "cancel.png", height = "100%", width = "100%", }, }, OnClick = { function() local cmd = RemoveAreaCommand(areaID) SB.commandManager:execute(cmd) end }, } end end function AreasWindow:IsValidState(state) return state:is_A(AddRectState) end function AreasWindow:OnLeaveState(state) for _, btn in pairs({self.btnAddArea}) do btn:SetPressedState(false) end end function AreasWindow:OnEnterState(state) self.btnAddArea:SetPressedState(true) end AreaManagerListenerWidget = AreaManagerListener:extends{} function AreaManagerListenerWidget:init(areaWindow) self.areaWindow = areaWindow end function AreaManagerListenerWidget:onAreaAdded(areaID) self.areaWindow:Populate() end function AreaManagerListenerWidget:onAreaRemoved(areaID) self.areaWindow:Populate() end function AreaManagerListenerWidget:onAreaChange(areaID, area) self.areaWindow:Populate() end
SB.Include(Path.Join(SB_VIEW_DIR, "editor.lua")) AreasWindow = Editor:extends{} Editor.Register({ name = "areasWindow", editor = AreasWindow, tab = "Logic", caption = "Area", tooltip = "Edit areas", image = SB_IMG_DIR .. "bolivia.png", order = 0, }) function AreasWindow:init() self:super("init") self.btnAddArea = TabbedPanelButton({ x = 0, y = 0, tooltip = "Add area", children = { TabbedPanelImage({ file = SB_IMG_DIR .. "area-add.png" }), TabbedPanelLabel({ caption = "Add" }), }, OnClick = { function() SB.stateManager:SetState(AddRectState(self)) end }, }) self:AddDefaultKeybinding({ self.btnAddArea }) self.areasPanel = StackPanel:New { itemMargin = {0, 0, 0, 0}, width = "100%", autosize = true, resizeItems = false, } local children = { ScrollPanel:New { x = 0, y = 80, bottom = 30, right = 0, borderColor = {0,0,0,0}, horizontalScrollbar = false, children = { self.areasPanel }, }, self.btnAddArea, } self:Populate() local areaManagerListener = AreaManagerListenerWidget(self) SB.model.areaManager:addListener(areaManagerListener) self:Finalize(children) end function AreasWindow:Populate() self.areasPanel:ClearChildren() local areas = SB.model.areaManager:getAllAreas() for _, areaID in pairs(areas) do local areaStackPanel = MakeComponentPanel(self.areasPanel) areaStackPanel.areaID = areaID local lblArea = Label:New { caption = "Area ID: " .. tostring(areaID), right = SB.conf.B_HEIGHT + 10, x = 1, height = SB.conf.B_HEIGHT, _toggle = nil, parent = areaStackPanel, } local btnFindArea = Button:New { caption = "", right = SB.conf.B_HEIGHT + 8, width = SB.conf.B_HEIGHT, height = SB.conf.B_HEIGHT, parent = areaStackPanel, padding = {0, 0, 0, 0}, tooltip = "Center camera on area", children = { Image:New { file = SB_IMG_DIR .. "position-marker.png", height = SB.conf.B_HEIGHT, width = SB.conf.B_HEIGHT, padding = {0, 0, 0, 0}, margin = {0, 0, 0, 0}, }, }, OnClick = { function() local area = SB.model.areaManager:getArea(areaID) if area ~= nil then local x = (area[1] + area[3]) / 2 local z = (area[2] + area[4]) / 2 local y = Spring.GetGroundHeight(x, z) Spring.SetCameraTarget(x, y, z) end end }, } local btnRemoveArea = Button:New { caption = "", right = 0, width = SB.conf.B_HEIGHT, height = SB.conf.B_HEIGHT, parent = areaStackPanel, padding = {2, 2, 2, 2}, tooltip = "Remove area", classname = "negative_button", children = { Image:New { file = SB_IMG_DIR .. "cancel.png", height = "100%", width = "100%", }, }, OnClick = { function() local cmd = RemoveObjectCommand(areaBridge.name, areaID) -- local cmd = RemoveAreaCommand(areaID) SB.commandManager:execute(cmd) end }, } end end function AreasWindow:IsValidState(state) return state:is_A(AddRectState) end function AreasWindow:OnLeaveState(state) for _, btn in pairs({self.btnAddArea}) do btn:SetPressedState(false) end end function AreasWindow:OnEnterState(state) self.btnAddArea:SetPressedState(true) end AreaManagerListenerWidget = AreaManagerListener:extends{} function AreaManagerListenerWidget:init(areaWindow) self.areaWindow = areaWindow end function AreaManagerListenerWidget:onAreaAdded(areaID) self.areaWindow:Populate() end function AreaManagerListenerWidget:onAreaRemoved(areaID) self.areaWindow:Populate() end function AreaManagerListenerWidget:onAreaChange(areaID, area) self.areaWindow:Populate() end
Fixed area removal
Fixed area removal
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
9fb780197455f8b7c53aedae1c75cef00a413a67
frontend/ui/data/optionsutil.lua
frontend/ui/data/optionsutil.lua
--[[-- This module contains miscellaneous helper functions for the creoptions and koptoptions. ]] local Device = require("device") local InfoMessage = require("ui/widget/infomessage") local UIManager = require("ui/uimanager") local _ = require("gettext") local Screen = Device.screen local T = require("ffi/util").template local optionsutil = {} function optionsutil.enableIfEquals(configurable, option, value) return configurable[option] == value end function optionsutil.showValues(configurable, option, prefix) local default = G_reader_settings:readSetting(prefix.."_"..option.name) local current = configurable[option.name] local value_default, value_current local suffix = option.name_text_suffix or "" if option.name == "screen_mode" then current = Screen:getScreenMode() end local arg_table = {} if option.toggle and option.values then for i=1,#option.toggle do arg_table[option.values[i]] = option.toggle[i] end end if not default then default = "not set" if option.toggle and option.values then value_current = current current = arg_table[current] end elseif option.toggle and option.values then value_current = current value_default = default default = arg_table[default] current = arg_table[current] end if option.labels and option.values then for i=1,#option.labels do if default == option.values[i] then default = option.labels[i] break end end for i=1,#option.labels do if current == option.values[i] then current = option.labels[i] break end end end local help_text = "" if option.help_text then help_text = T("\n%1\n", option.help_text) end local text if option.name_text_true_values and option.toggle and option.values and value_default then text = T(_("%1:\n%2\nCurrent value: %3 (%6%5)\nDefault value: %4 (%7%5)"), option.name_text, help_text, current, default, suffix, value_current, value_default) elseif option.name_text_true_values and option.toggle and option.values and not value_default then text = T(_("%1\n%2\nCurrent value: %3 (%6%5)\nDefault value: %4"), option.name_text, help_text, current, default, suffix, value_current) else text = T(_("%1\n%2\nCurrent value: %3%5\nDefault value: %4%5"), option.name_text, help_text, current, default, suffix) end UIManager:show(InfoMessage:new{ text=text }) end local function tableComp(a,b) if #a ~= #b then return false end for i=1,#a do if a[i] ~= b[i] then return false end end return true end function optionsutil.showValuesMargins(configurable, option) local default = G_reader_settings:readSetting("copt_"..option.name) local current = configurable[option.name] local current_string for i=1,#option.toggle do if tableComp(current, option.values[i]) then current_string = option.toggle[i] break end end if not default then UIManager:show(InfoMessage:new{ text = T(_([[ %1: Current value: %2 left: %3 top: %4 right: %5 bottom: %6 Default value: not set]]), option.name_text, current_string, current[1], current[2], current[3], current[4]) }) else local default_string for i=1,#option.toggle do if tableComp(default, option.values[i]) then default_string = option.toggle[i] break end end UIManager:show(InfoMessage:new{ text = T(_([[ %1: Current value: %2 left: %3 top: %4 right: %5 bottom: %6 Default value: %7 left: %8 top: %9 right: %10 bottom: %11]]), option.name_text, current_string, current[1], current[2], current[3], current[4], default_string, default[1], default[2], default[3], default[4]) }) end end return optionsutil
--[[-- This module contains miscellaneous helper functions for the creoptions and koptoptions. ]] local Device = require("device") local InfoMessage = require("ui/widget/infomessage") local UIManager = require("ui/uimanager") local _ = require("gettext") local Screen = Device.screen local T = require("ffi/util").template local optionsutil = {} function optionsutil.enableIfEquals(configurable, option, value) return configurable[option] == value end function optionsutil.showValues(configurable, option, prefix) local default = G_reader_settings:readSetting(prefix.."_"..option.name) local current = configurable[option.name] local value_default, value_current local suffix = option.name_text_suffix or "" if option.name == "screen_mode" then current = Screen:getScreenMode() end local arg_table = {} if option.toggle and option.values then for i=1,#option.toggle do arg_table[option.values[i]] = option.toggle[i] end end if not default then default = "not set" if option.toggle and option.values then value_current = current current = arg_table[current] end elseif option.toggle and option.values then value_current = current value_default = default default = arg_table[default] current = arg_table[current] end if option.labels and option.values then for i=1,#option.labels do if default == option.values[i] then default = option.labels[i] break end end for i=1,#option.labels do if current == option.values[i] then current = option.labels[i] break end end end local help_text = "" if option.help_text then help_text = T("\n%1\n", option.help_text) end local text if option.name_text_true_values and option.toggle and option.values and value_default then text = T(_("%1:\n%2\nCurrent value: %3 (%6%5)\nDefault value: %4 (%7%5)"), option.name_text, help_text, current, default, suffix, value_current, value_default) elseif option.name_text_true_values and option.toggle and option.values and not value_default then text = T(_("%1\n%2\nCurrent value: %3 (%6%5)\nDefault value: %4"), option.name_text, help_text, current, default, suffix, value_current) else text = T(_("%1\n%2\nCurrent value: %3%5\nDefault value: %4%5"), option.name_text, help_text, current, default, suffix) end UIManager:show(InfoMessage:new{ text=text }) end function optionsutil.showValuesMargins(configurable, option) local default = G_reader_settings:readSetting("copt_"..option.name) local current = configurable[option.name] if not default then UIManager:show(InfoMessage:new{ text = T(_([[ Current margin: left: %1 top: %2 right: %3 bottom: %4 Default margin: not set]]), current[1], current[2], current[3], current[4]) }) else UIManager:show(InfoMessage:new{ text = T(_([[ Current margin: left: %1 top: %2 right: %3 bottom: %4 Default margin: left: %5 top: %6 right: %7 bottom: %8]]), current[1], current[2], current[3], current[4], default[1], default[2], default[3], default[4]) }) end end return optionsutil
[fix] ConfigMenu cre margins hold action (#4702)
[fix] ConfigMenu cre margins hold action (#4702) See https://github.com/koreader/koreader/pull/4691#issuecomment-468905263
Lua
agpl-3.0
pazos/koreader,Hzj-jie/koreader,koreader/koreader,Frenzie/koreader,Markismus/koreader,NiLuJe/koreader,houqp/koreader,koreader/koreader,poire-z/koreader,mwoz123/koreader,mihailim/koreader,poire-z/koreader,NiLuJe/koreader,Frenzie/koreader
2de3e4abebae290b24b229a4c40cf408e57e820f
packages/folio.lua
packages/folio.lua
-- Folios class SILE.require("packages/counters"); SILE.scratch.counters.folio = { value= 1, display= "arabic" }; SILE.registerCommand("folios", function () SILE.scratch.counters.folio.off = false end) SILE.registerCommand("nofolios", function () SILE.scratch.counters.folio.off = true end) SILE.registerCommand("nofoliosthispage", function () SILE.scratch.counters.folio.off = 2 end) return { init = function () end, exports = { outputFolio = function (this, frame) if not frame then frame = "folio" end if SILE.scratch.counters.folio.off then if SILE.scratch.counters.folio.off == 2 then SILE.scratch.counters.folio.off = false end SILE.scratch.counters.folio.value = SILE.scratch.counters.folio.value + 1 return end io.write("["..SILE.formatCounter(SILE.scratch.counters.folio).."] "); local f = SILE.getFrame("folio"); if (f) then SILE.typesetNaturally(f, function() SILE.settings.pushState() SILE.settings.reset() SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.call("hss") SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.folio)) SILE.call("hss") SILE.settings.popState() end) end SILE.scratch.counters.folio.value = SILE.scratch.counters.folio.value + 1 end } }
-- Folios class SILE.require("packages/counters"); SILE.scratch.counters.folio = { value= 1, display= "arabic" }; SILE.registerCommand("folios", function () SILE.scratch.counters.folio.off = false end) SILE.registerCommand("nofolios", function () SILE.scratch.counters.folio.off = true end) SILE.registerCommand("nofoliosthispage", function () SILE.scratch.counters.folio.off = 2 end) return { init = function () end, exports = { outputFolio = function (this, frame) if not frame then frame = "folio" end if SILE.scratch.counters.folio.off then if SILE.scratch.counters.folio.off == 2 then SILE.scratch.counters.folio.off = false end SILE.scratch.counters.folio.value = SILE.scratch.counters.folio.value + 1 return end io.write("["..SILE.formatCounter(SILE.scratch.counters.folio).."] "); local f = SILE.getFrame("folio"); if (f) then SILE.typesetNaturally(f, function() SILE.settings.pushState() SILE.settings.reset() SILE.call("center", {}, function() SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.folio)) end) SILE.typesetter:leaveHmode() SILE.settings.popState() end) end SILE.scratch.counters.folio.value = SILE.scratch.counters.folio.value + 1 end } }
Use \center{} command for folios. Fixes #113.
Use \center{} command for folios. Fixes #113.
Lua
mit
alerque/sile,simoncozens/sile,anthrotype/sile,anthrotype/sile,alerque/sile,anthrotype/sile,WAKAMAZU/sile_fe,anthrotype/sile,neofob/sile,simoncozens/sile,neofob/sile,WAKAMAZU/sile_fe,alerque/sile,WAKAMAZU/sile_fe,neofob/sile,neofob/sile,simoncozens/sile,WAKAMAZU/sile_fe,simoncozens/sile,alerque/sile
a938ae74c9abb89bf8c7e351c03a02fc3c72e1f2
hammerspoon/modules/homebrew.lua
hammerspoon/modules/homebrew.lua
-- Homebrew menubar local Homebrew = { menubar = hs.menubar.new(), items = {}, disabled = false, notified = false, } function Homebrew:loadOutdated() self.items = {} local pipe = io.popen('/usr/local/bin/brew outdated -v | grep -v pinned | cut -f 1 -d " "', 'r') for item in pipe:lines() do table.insert(self.items, item) end pipe:close() if next(self.items) == nil then self.disabled = true self.notified = false self.menubar:removeFromMenuBar() else local msg = string.format("%d updated formula%s available", #self.items, plural(self.items)) self.disabled = false self.menubar:returnToMenuBar() self.menubar:setIcon('./assets/cask.pdf') self.menubar:setTooltip(msg) if not self.notified then hs.notify.show('Homebrew', msg, table.concat(self.items, ', ')) self.notified = true end end end function Homebrew:getMenu() local menu = { {title=string.format("Update %s formula%s", #self.items, plural(self.items)), fn=function() self.disabled = true; hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, table.merge({'upgrade'}, self.items)):start() end, disabled=self.disabled}, {title='-'}, } for _, item in ipairs(self.items) do table.insert(menu, {title=item, fn=function() self.disabled = true; hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'upgrade', item}):start() end, disabled=self.disabled}) end return menu end function Homebrew:update() print('Updating Homebrew') hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'update'}):start() end function table.merge(t1, t2) for k,v in ipairs(t2) do table.insert(t1, v) end return t1 end function plural(a) local suffix = '' if #a > 1 then suffix = 's' end return suffix end if Homebrew then Homebrew.menubar:setIcon('./assets/cask.pdf') Homebrew.menubar:setTooltip('Homebrew') Homebrew.menubar:removeFromMenuBar() Homebrew.menubar:setMenu(function() return Homebrew:getMenu() end) Homebrew:update(); hs.timer.doEvery(3600, function() Homebrew:update() end) end
-- Homebrew menubar local Homebrew = { menubar = hs.menubar.new(), items = {}, disabled = false, notified = false, } function Homebrew:showMenu() self.menubar:returnToMenuBar() self.menubar:setIcon('./assets/cask.pdf') self.menubar:setTooltip(string.format("%d updated formula%s available", #self.items, plural(self.items))) end function Homebrew:hideMenu() self.menubar:removeFromMenuBar() end function Homebrew:loadOutdated() self.items = {} local pipe = io.popen('/usr/local/bin/brew outdated -v | grep -v pinned | cut -f 1 -d " "', 'r') for item in pipe:lines() do table.insert(self.items, item) end pipe:close() if next(self.items) == nil then self.disabled = true self.notified = false self:hideMenu() else self.disabled = false self:showMenu() if not self.notified then hs.notify.show('Homebrew', msg, table.concat(self.items, ', ')) self.notified = true end end end function Homebrew:getMenu() local menu = { {title=string.format("Update %s formula%s", #self.items, plural(self.items)), fn=function() self.disabled = true; hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, table.merge({'upgrade'}, self.items)):start() end, disabled=self.disabled}, {title='-'}, } for _, item in ipairs(self.items) do table.insert(menu, {title=item, fn=function() self.disabled = true; hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'upgrade', item}):start() end, disabled=self.disabled}) end return menu end function Homebrew:update() print('Updating Homebrew') hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'update'}):start() end function table.merge(t1, t2) for k,v in ipairs(t2) do table.insert(t1, v) end return t1 end function plural(a) local suffix = '' if #a > 1 then suffix = 's' end return suffix end if Homebrew then Homebrew:hideMenu() Homebrew.menubar:setMenu(function() return Homebrew:getMenu() end) Homebrew:update(); hs.timer.doEvery(3600, function() Homebrew:update() end) end
Fix disappearing menubar icon in homebrew/hammerspoon
Fix disappearing menubar icon in homebrew/hammerspoon
Lua
mit
sebastianmarkow/dotfiles
f0ccb4ae9515f0a44d122905c72993df01350c43
heka/sandbox/encoders/es_fields.lua
heka/sandbox/encoders/es_fields.lua
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Elasticsearch encoder to index only specific fields. Config: - index (string, optional, default "heka-%{%Y.%m.%d}") String to use as the `_index` key's value in the generated JSON. Supports field interpolation as described below. - type_name (string, optional, default "message") String to use as the `_type` key's value in the generated JSON. Supports field interpolation as described below. - id (string, optional) String to use as the `_id` key's value in the generated JSON. Supports field interpolation as described below. - es_index_from_timestamp (boolean, optional) If true, then any time interpolation (often used to generate the ElasticSeach index) will use the timestamp from the processed message rather than the system time. - fields (string, required) JSON array of fields to index. Field interpolation: Data from the current message can be interpolated into any of the string arguments listed above. A `%{}` enclosed field name will be replaced by the field value from the current message. Supported default field names are "Type", "Hostname", "Pid", "UUID", "Logger", "EnvVersion", and "Severity". Any other values will be checked against the defined dynamic message fields. If no field matches, then a `C strftime <http://man7.org/linux/man-pages/man3/strftime.3.html>`_ (on non-Windows platforms) or `C89 strftime <http://msdn.microsoft.com/en- us/library/fe06s4ak.aspx>`_ (on Windows) time substitution will be attempted. *Example Heka Configuration* .. code-block:: ini [es_fields] type = "SandboxEncoder" filename = "lua_encoders/es_fields.lua" [es_fields.config] es_index_from_timestamp = true index = "%{Logger}-%{%Y.%m.%d}" type_name = "%{Type}-%{Hostname}" fields = '["Payload", "Fields[docType]"]' [ElasticSearchOutput] message_matcher = "Type == 'mytype'" encoder = "es_fields" *Example Output* .. code-block:: json {"index":{"_index":"mylogger-2014.06.05","_type":"mytype-host.domain.com"}} {"Payload":"data","docType":"main"} --]] require "cjson" require "string" require "os" local elasticsearch = require "elasticsearch" local ts_from_message = read_config("es_index_from_timestamp") local index = read_config("index") or "heka-%{%Y.%m.%d}" local type_name = read_config("type_name") or "message" local id = read_config("id") local fields = cjson.decode(read_config("fields") or error("fields must be specified")) local interp_fields = { Type = "Type", Hostname = "Hostname", Pid = "Pid", UUID = "Uuid", Logger = "Logger", EnvVersion = "EnvVersion", Severity = "Severity", Timestamp = "Timestamp", Logger = "Logger" } local static_fields = {} local dynamic_fields = {} local function key(str) return str:match("Fields%[(.+)%]") or str end for i, field in ipairs(fields) do local fname = interp_fields[field] if fname then static_fields[#static_fields+1] = field else dynamic_fields[#dynamic_fields+1] = key(field) end end function process_message() local ns if ts_from_message then ns = read_message("Timestamp") end local idx_json = elasticsearch.bulkapi_index_json(index, type_name, id, ns) local tbl = {} for i, field in ipairs(static_fields) do if field == "Timestamp" and ts_from_message then tbl[field] = os.date("!%Y-%m-%dT%XZ", ns / 1e9) else tbl[field] = read_message(field) end end for i, field in ipairs(dynamic_fields) do local f = string.format("Fields[%s]", field) local z = 0 local v = read_message(f, nil, z) while v do if z == 0 then tbl[field] = v elseif z == 1 then tbl[field] = {tbl[field], v} elseif z > 1 then tbl[field][#tbl[field]+1] = v end z = z + 1 v = read_message(field, nil, z) end end if tbl.creationTimestamp then -- tbl.Latency = (ns - tbl.creationTimestamp) / 1e9 -- FIXME probably a good idea to generalize time fields tbl.creationTimestamp = os.date("!%Y-%m-%dT%XZ", tbl.creationTimestamp / 1e9) end add_to_payload(idx_json, "\n", cjson.encode(tbl), "\n") inject_payload() return 0 end
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Elasticsearch encoder to index only specific fields. Config: - index (string, optional, default "heka-%{%Y.%m.%d}") String to use as the `_index` key's value in the generated JSON. Supports field interpolation as described below. - type_name (string, optional, default "message") String to use as the `_type` key's value in the generated JSON. Supports field interpolation as described below. - id (string, optional) String to use as the `_id` key's value in the generated JSON. Supports field interpolation as described below. - es_index_from_timestamp (boolean, optional) If true, then any time interpolation (often used to generate the ElasticSeach index) will use the timestamp from the processed message rather than the system time. - fields (string, required) JSON array of fields to index. Field interpolation: Data from the current message can be interpolated into any of the string arguments listed above. A `%{}` enclosed field name will be replaced by the field value from the current message. Supported default field names are "Type", "Hostname", "Pid", "UUID", "Logger", "EnvVersion", and "Severity". Any other values will be checked against the defined dynamic message fields. If no field matches, then a `C strftime <http://man7.org/linux/man-pages/man3/strftime.3.html>`_ (on non-Windows platforms) or `C89 strftime <http://msdn.microsoft.com/en- us/library/fe06s4ak.aspx>`_ (on Windows) time substitution will be attempted. *Example Heka Configuration* .. code-block:: ini [es_fields] type = "SandboxEncoder" filename = "lua_encoders/es_fields.lua" [es_fields.config] es_index_from_timestamp = true index = "%{Logger}-%{%Y.%m.%d}" type_name = "%{Type}-%{Hostname}" fields = '["Payload", "Fields[docType]"]' [ElasticSearchOutput] message_matcher = "Type == 'mytype'" encoder = "es_fields" *Example Output* .. code-block:: json {"index":{"_index":"mylogger-2014.06.05","_type":"mytype-host.domain.com"}} {"Payload":"data","docType":"main"} --]] require "cjson" require "string" require "os" local elasticsearch = require "elasticsearch" local ts_from_message = read_config("es_index_from_timestamp") local index = read_config("index") or "heka-%{%Y.%m.%d}" local type_name = read_config("type_name") or "message" local id = read_config("id") local fields = cjson.decode(read_config("fields") or error("fields must be specified")) local interp_fields = { Type = "Type", Hostname = "Hostname", Pid = "Pid", UUID = "Uuid", Logger = "Logger", EnvVersion = "EnvVersion", Severity = "Severity", Timestamp = "Timestamp", Logger = "Logger" } local static_fields = {} local dynamic_fields = {} local function key(str) return str:match("Fields%[(.+)%]") or error("invalid field name: " .. str) end for i, field in ipairs(fields) do local fname = interp_fields[field] if fname then static_fields[#static_fields+1] = field else dynamic_fields[#dynamic_fields+1] = key(field) end end function process_message() local ns if ts_from_message then ns = read_message("Timestamp") end local idx_json = elasticsearch.bulkapi_index_json(index, type_name, id, ns) local tbl = {} for i, field in ipairs(static_fields) do if field == "Timestamp" then tbl[field] = os.date("!%Y-%m-%dT%XZ", ns and ns / 1e9) else tbl[field] = read_message(field) end end for i, field in ipairs(dynamic_fields) do local f = string.format("Fields[%s]", field) local z = 0 local v = read_message(f, nil, z) while v do if z == 0 then tbl[field] = v elseif z == 1 then tbl[field] = {tbl[field], v} elseif z > 1 then tbl[field][#tbl[field]+1] = v end z = z + 1 v = read_message(f, nil, z) end end if tbl.creationTimestamp then -- tbl.Latency = (ns - tbl.creationTimestamp) / 1e9 -- FIXME probably a good idea to generalize time fields tbl.creationTimestamp = os.date("!%Y-%m-%dT%XZ", tbl.creationTimestamp / 1e9) end add_to_payload(idx_json, "\n", cjson.encode(tbl), "\n") inject_payload() return 0 end
Error early and fix es_index_from_timestamp semantics
Error early and fix es_index_from_timestamp semantics
Lua
mpl-2.0
sapohl/data-pipeline,acmiyaguchi/data-pipeline,kparlante/data-pipeline,sapohl/data-pipeline,acmiyaguchi/data-pipeline,nathwill/data-pipeline,mozilla-services/data-pipeline,whd/data-pipeline,mozilla-services/data-pipeline,nathwill/data-pipeline,kparlante/data-pipeline,acmiyaguchi/data-pipeline,nathwill/data-pipeline,whd/data-pipeline,nathwill/data-pipeline,acmiyaguchi/data-pipeline,mozilla-services/data-pipeline,whd/data-pipeline,mozilla-services/data-pipeline,sapohl/data-pipeline,kparlante/data-pipeline,sapohl/data-pipeline,kparlante/data-pipeline,whd/data-pipeline
5cd74a5fa1b3ced56b9b004a838077bb02409b4b
pud/kit/Rect.lua
pud/kit/Rect.lua
require 'pud.util' local Class = require 'lib.hump.class' -- Rect -- provides position and size of a rectangle -- Note: coordinates are not floored or rounded and may be floats local Rect = Class{name='Rect', function(self, x, y, w, h) x = x or 0 y = y or 0 w = w or 0 h = h or 0 self:setPosition(x, y) self:setSize(w, h) end } -- destructor function Rect:destroy() self._x = nil self._y = nil self._w = nil self._h = nil self._cx = nil self._cy = nil end -- private function to calculate and store the center coords local function _calcCenter(self) if self._x and self._y and self._w and self._h then self._cx = self._x + (self._w/2) self._cy = self._y + (self._h/2) end end -- get and set position function Rect:getX() return self._x end function Rect:setX(x) verify('number', x) self._x = x _calcCenter(self) end function Rect:getY() return self._y end _calcCenter(self) function Rect:setY(y) verify('number', y) self._y = y end function Rect:getPosition() return self:getX(), self:getY() end function Rect:setPosition(x, y) self:setX(x) self:setY(y) end -- get and set center coords function Rect:getCenter() return self._cx, self._cy end function Rect:setCenter(x, y) verify('number', x, y) self._cx = x self._cy = y self._x = self._cx - (self._w/2) self._y = self._cy - (self._h/2) end -- get (no set) bounding box coordinates function Rect:getBBox() local x, y = self:getPosition() local w, h = self:getSize() return x, y, x+w, y+h end -- get and set size function Rect:getWidth() return self._w end function Rect:setWidth(w) verify('number', w) self._w = w _calcCenter(self) end function Rect:getHeight() return self._h end function Rect:setHeight(h) verify('number', h) self._h = h _calcCenter(self) end function Rect:getSize() return self:getWidth(), self:getHeight() end function Rect:setSize(w, h) self:setWidth(w) self:setHeight(h) end -- the class return Rect
require 'pud.util' local Class = require 'lib.hump.class' local round = function(x) return math.floor(x + 0.5) end -- Rect -- provides position and size of a rectangle -- Note: coordinates are not floored or rounded and may be floats local Rect = Class{name='Rect', function(self, x, y, w, h) x = x or 0 y = y or 0 w = w or 0 h = h or 0 self:setPosition(x, y) self:setSize(w, h) end } -- destructor function Rect:destroy() self._x = nil self._y = nil self._w = nil self._h = nil self._cx = nil self._cy = nil end -- get and set position function Rect:getX() return self._x end function Rect:setX(x) verify('number', x) self._x = x end function Rect:getY() return self._y end function Rect:setY(y) verify('number', y) self._y = y end function Rect:getPosition() return self:getX(), self:getY() end function Rect:setPosition(x, y) self:setX(x) self:setY(y) end -- get and set center coords, rounding to nearest number if requested function Rect:getCenter(doRound) local x, y = self:getPosition() local w, h = self:getSize() w = doRound and round(w/2) or w/2 h = doRound and round(h/2) or h/2 return x + w, y + h end function Rect:setCenter(x, y, doRound) verify('number', x, y) local w, h = self:getSize() w = doRound and round(w/2) or w/2 h = doRound and round(h/2) or h/2 self:setX(x - w) self:setY(y - h) end -- get (no set) bounding box coordinates function Rect:getBBox() local x, y = self:getPosition() local w, h = self:getSize() return x, y, x+w, y+h end -- get and set size function Rect:getWidth() return self._w end function Rect:setWidth(w) verify('number', w) self._w = w end function Rect:getHeight() return self._h end function Rect:setHeight(h) verify('number', h) self._h = h end function Rect:getSize() return self:getWidth(), self:getHeight() end function Rect:setSize(w, h) self:setWidth(w) self:setHeight(h) end -- the class return Rect
fix center calculation and add flag for rounding
fix center calculation and add flag for rounding
Lua
mit
scottcs/wyx
b7b351d5337b64600fb5a792726adf6875306742
nvim/init.lua
nvim/init.lua
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local fn = vim.fn -- to call Vim functions e.g. fn.bufnr() local g = vim.g -- a table to access global variables local opt = vim.opt -- to set options if not g.vscode then require('plugins') end require('options') require('mappings') require('config.treesitter') require('config.lualine') require('config.formatter') require('config.lspconfig') require('config.compe') require('config.telescope') cmd( [[ augroup FormatAutogroup autocmd! autocmd BufWritePost *.js,*.rs,*.lua FormatWrite augroup END ]], true ) if not g.vscode then opt.termguicolors = true require('onedark').setup() end
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local fn = vim.fn -- to call Vim functions e.g. fn.bufnr() local g = vim.g -- a table to access global variables local opt = vim.opt -- to set options if not g.vscode then require('plugins') end require('options') require('mappings') if not g.vscode then require('config.treesitter') require('config.lualine') require('config.formatter') require('config.lspconfig') require('config.compe') require('config.telescope') end cmd( [[ augroup FormatAutogroup autocmd! autocmd BufWritePost *.js,*.rs,*.lua FormatWrite augroup END ]], true ) if not g.vscode then opt.termguicolors = true require('onedark').setup() end
fix: nvim vscode fix for highlighting
fix: nvim vscode fix for highlighting
Lua
mit
drmohundro/dotfiles
4c67419d3c789d953dc99863ce5199a1a56a175d
AceSerializer-3.0/AceSerializer-3.0.lua
AceSerializer-3.0/AceSerializer-3.0.lua
local MAJOR,MINOR = "AceSerializer-3.0", 1 local AceSerializer, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceSerializer then return end local strbyte=string.byte local strchar=string.char local tconcat=table.concat local gsub=string.gsub local gmatch=string.gmatch local pcall=pcall ----------------------------------------------------------------------- -- Serialization functions local function SerializeStringHelper(ch) -- Used by SerializeValue for strings -- We use \126 ("~") as an escape character for all nonprints plus a few more local n = strbyte(ch) if n<=32 then -- nonprint + space return "\126"..strchar(n+64) elseif n==94 then -- value separator return "\126\125" elseif n==126 then -- our own escape character return "\126\124" elseif n==127 then -- nonprint (DEL) return "\126\123" else assert(false) -- can't be reached if caller uses a sane regex end end local function SerializeValue(v, res, nres) -- We use "^" as a value separator, followed by one byte for type indicator local t=type(v) if t=="string" then -- ^S = string (escaped to remove nonprints, "^"s, etc) res[nres+1] = "^S" res[nres+2] = gsub(v,"[%c \94\126\127]", SerializeStringHelper) nres=nres+2 elseif t=="number" then -- ^N = number (just tostring()ed) res[nres+1] = "^N" res[nres+2] = tostring(v) nres=nres+2 elseif t=="table" then -- ^T...^t = table (list of key,value pairs) nres=nres+1 res[nres] = "^T" for k,v in pairs(v) do nres = SerializeValue(k, res, nres) nres = SerializeValue(v, res, nres) end nres=nres+1 res[nres] = "^t" elseif t=="boolean" then -- ^B = true, ^b = false nres=nres+1 if v then res[nres] = "^B" -- true else res[nres] = "^b" -- false end elseif t=="nil" then -- ^Z = nil (zero, "N" was taken :P) nres=nres+1 res[nres] = "^Z" else error(MAJOR..": Cannot serialize a value of type '"..t.."'") -- can't produce error on right level, this is wildly recursive end return nres end ----------------------------------------------------------------------- -- API Serialize(...) -- -- Takes a list of values (strings, numbers, booleans, nils, tables) -- and returns it in serialized form (a string). -- May throw errors on invalid data types. -- local serializeTbl = { "^1" } -- "^1" = Hi, I'm data serialized by AceSerializer protocol rev 1 function AceSerializer:Serialize(...) local nres = 1 for i=1,select("#", ...) do local v = select(i, ...) nres = SerializeValue(v, serializeTbl, nres) end serializeTbl[nres+1] = "^^" -- "^^" = End of serialized data return tconcat(serializeTbl, "", 1, nres+1) end ----------------------------------------------------------------------- -- Deserialization functions local function DeserializeStringHelper(escape) if escape<"~\123" then return strchar(strbyte(escape,2,2)-64) elseif escape=="~\123" then return "\127" elseif escape=="~\124" then return "\126" elseif escape=="~\125" then return "\94" end print("oof") return "" end local function DeserializeNumberHelper(number) if number == tostring(0/0) then return 0/0 elseif number == tostring(-1/0) then return -1/0 elseif number == tostring(1/0) then return 1/0 else return tonumber(number) end end -- DeserializeValue: worker function for :Deserialize() -- It works in two modes: -- Main (top-level) mode: Deserialize a list of values and return them all -- Recursive (table) mode: Deserialize only a single value (_may_ of course be another table with lots of subvalues in it) -- -- The function _always_ works recursively due to having to build a list of values to return -- -- Callers are expected to pcall(DeserializeValue) to trap errors local function DeserializeValue(iter,single,ctl,data) if not single then ctl,data = iter() end if not ctl then error("Supplied data misses AceSerializer terminator ('^^')") end if ctl=="^^" then -- ignore extraneous data return end local res if ctl=="^S" then res = gsub(data, "~.", DeserializeStringHelper) elseif ctl=="^N" then res = DeserializeNumberHelper(data) if not res then error("Invalid serialized number: '"..data.."'") end elseif ctl=="^B" then -- yeah yeah ignore data portion res = true elseif ctl=="^b" then -- yeah yeah ignore data portion res = false elseif ctl=="^Z" then -- yeah yeah ignore data portion res = nil elseif ctl=="^T" then -- ignore ^T's data, future extensibility? res = {} local k,v while true do ctl,data = iter() if ctl=="^t" then break end -- ignore ^t's data k = DeserializeValue(iter,true,ctl,data) if not k then error("Invalid AceSerializer table format (no table end marker)") end ctl,data = iter() v = DeserializeValue(iter,true,ctl,data) if not v then error("Invalid AceSerializer table format (no table end marker)") end res[k]=v end else error("Invalid AceSerializer control code '"..ctl.."'") end if not single then return res,DeserializeValue(iter) else return res end end ----------------------------------------------------------------------- -- API Deserialize(str) -- -- Accepts serialized data, ignoring all control characters and whitespace. -- -- Returns true followed by a list of values, OR false followed by a message -- function AceSerializer:Deserialize(str) str = gsub(str, "[%c ]", "") -- ignore all control characters; nice for embedding in email and stuff local iter = string.gmatch(str, "(^.)([^^]*)") -- Any ^x followed by string of non-^ local ctl,data = iter() if not ctl or ctl~="^1" then -- we purposefully ignore the data portion of the start code, it can be used as an extension mechanism return false, "Supplied data is not AceSerializer data (rev 1)" end return pcall(DeserializeValue, iter) end ---------------------------------------- -- Base library stuff ---------------------------------------- AceSerializer.internals = { -- for test scripts SerializeValue = SerializeValue, SerializeStringHelper = SerializeStringHelper, } local mixins = { "Serialize", "Deserialize", } AceSerializer.embeds = AceSerializer.embeds or {} function AceSerializer:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true return target end -- Update embeds for target, v in pairs(AceSerializer.embeds) do AceSerializer:Embed(target) end
local MAJOR,MINOR = "AceSerializer-3.0", 1 local AceSerializer, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceSerializer then return end local strbyte=string.byte local strchar=string.char local tconcat=table.concat local gsub=string.gsub local gmatch=string.gmatch local pcall=pcall ----------------------------------------------------------------------- -- Serialization functions local function SerializeStringHelper(ch) -- Used by SerializeValue for strings -- We use \126 ("~") as an escape character for all nonprints plus a few more local n = strbyte(ch) if n<=32 then -- nonprint + space return "\126"..strchar(n+64) elseif n==94 then -- value separator return "\126\125" elseif n==126 then -- our own escape character return "\126\124" elseif n==127 then -- nonprint (DEL) return "\126\123" else assert(false) -- can't be reached if caller uses a sane regex end end local function SerializeValue(v, res, nres) -- We use "^" as a value separator, followed by one byte for type indicator local t=type(v) if t=="string" then -- ^S = string (escaped to remove nonprints, "^"s, etc) res[nres+1] = "^S" res[nres+2] = gsub(v,"[%c \94\126\127]", SerializeStringHelper) nres=nres+2 elseif t=="number" then -- ^N = number (just tostring()ed) res[nres+1] = "^N" res[nres+2] = tostring(v) nres=nres+2 elseif t=="table" then -- ^T...^t = table (list of key,value pairs) nres=nres+1 res[nres] = "^T" for k,v in pairs(v) do nres = SerializeValue(k, res, nres) nres = SerializeValue(v, res, nres) end nres=nres+1 res[nres] = "^t" elseif t=="boolean" then -- ^B = true, ^b = false nres=nres+1 if v then res[nres] = "^B" -- true else res[nres] = "^b" -- false end elseif t=="nil" then -- ^Z = nil (zero, "N" was taken :P) nres=nres+1 res[nres] = "^Z" else error(MAJOR..": Cannot serialize a value of type '"..t.."'") -- can't produce error on right level, this is wildly recursive end return nres end ----------------------------------------------------------------------- -- API Serialize(...) -- -- Takes a list of values (strings, numbers, booleans, nils, tables) -- and returns it in serialized form (a string). -- May throw errors on invalid data types. -- local serializeTbl = { "^1" } -- "^1" = Hi, I'm data serialized by AceSerializer protocol rev 1 function AceSerializer:Serialize(...) local nres = 1 for i=1,select("#", ...) do local v = select(i, ...) nres = SerializeValue(v, serializeTbl, nres) end serializeTbl[nres+1] = "^^" -- "^^" = End of serialized data return tconcat(serializeTbl, "", 1, nres+1) end ----------------------------------------------------------------------- -- Deserialization functions local function DeserializeStringHelper(escape) if escape<"~\123" then return strchar(strbyte(escape,2,2)-64) elseif escape=="~\123" then return "\127" elseif escape=="~\124" then return "\126" elseif escape=="~\125" then return "\94" end error("DeserializeStringHelper got called for '"..escape.."'?!?") -- can't be reached unless regex is screwed up end local function DeserializeNumberHelper(number) if number == tostring(0/0) then return 0/0 elseif number == tostring(-1/0) then return -1/0 elseif number == tostring(1/0) then return 1/0 else return tonumber(number) end end -- DeserializeValue: worker function for :Deserialize() -- It works in two modes: -- Main (top-level) mode: Deserialize a list of values and return them all -- Recursive (table) mode: Deserialize only a single value (_may_ of course be another table with lots of subvalues in it) -- -- The function _always_ works recursively due to having to build a list of values to return -- -- Callers are expected to pcall(DeserializeValue) to trap errors local function DeserializeValue(iter,single,ctl,data) if not single then ctl,data = iter() end if not ctl then error("Supplied data misses AceSerializer terminator ('^^')") end if ctl=="^^" then -- ignore extraneous data return end local res if ctl=="^S" then res = gsub(data, "~.", DeserializeStringHelper) elseif ctl=="^N" then res = DeserializeNumberHelper(data) if not res then error("Invalid serialized number: '"..data.."'") end elseif ctl=="^B" then -- yeah yeah ignore data portion res = true elseif ctl=="^b" then -- yeah yeah ignore data portion res = false elseif ctl=="^Z" then -- yeah yeah ignore data portion res = nil elseif ctl=="^T" then -- ignore ^T's data, future extensibility? res = {} local k,v while true do ctl,data = iter() if ctl=="^t" then break end -- ignore ^t's data k = DeserializeValue(iter,true,ctl,data) if not k then error("Invalid AceSerializer table format (no table end marker)") end ctl,data = iter() v = DeserializeValue(iter,true,ctl,data) if not v then error("Invalid AceSerializer table format (no table end marker)") end res[k]=v end else error("Invalid AceSerializer control code '"..ctl.."'") end if not single then return res,DeserializeValue(iter) else return res end end ----------------------------------------------------------------------- -- API Deserialize(str) -- -- Accepts serialized data, ignoring all control characters and whitespace. -- -- Returns true followed by a list of values, OR false followed by a message -- function AceSerializer:Deserialize(str) str = gsub(str, "[%c ]", "") -- ignore all control characters; nice for embedding in email and stuff local iter = string.gmatch(str, "(^.)([^^]*)") -- Any ^x followed by string of non-^ local ctl,data = iter() if not ctl or ctl~="^1" then -- we purposefully ignore the data portion of the start code, it can be used as an extension mechanism return false, "Supplied data is not AceSerializer data (rev 1)" end return pcall(DeserializeValue, iter) end ---------------------------------------- -- Base library stuff ---------------------------------------- AceSerializer.internals = { -- for test scripts SerializeValue = SerializeValue, SerializeStringHelper = SerializeStringHelper, } local mixins = { "Serialize", "Deserialize", } AceSerializer.embeds = AceSerializer.embeds or {} function AceSerializer:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true return target end -- Update embeds for target, v in pairs(AceSerializer.embeds) do AceSerializer:Embed(target) end
Ace3 - AceSerializer: - Fix an error message for something that can never happen, so a bit pointless but ohwell :)
Ace3 - AceSerializer: - Fix an error message for something that can never happen, so a bit pointless but ohwell :) git-svn-id: d324031ee001e5fbb202928c503a4bc65708d41c@450 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
8a05fba439e96f1992b59ee99f5b22439f19aa8b
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 = tonumber, tostring, pairs; 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 request.callback(t_concat(request.body), request.code, request); else -- Error.. connection was closed prematurely request.callback("connection-closed", 0, request); end destroy_request(request); return; end if request.state == "body" 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 if request.callback then request.callback(t_concat(request.body), request.code, request); end end print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength); 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 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 = callback; 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 = tonumber, tostring, pairs; 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); return; end if request.state == "body" 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 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 = callback; 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;
Fix to prevent calling HTTP request callback twice with the same data
Fix to prevent calling HTTP request callback twice with the same data
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
8e96bf411d003a20cefb4de3f877fe7e3067d992
tests/gio.lua
tests/gio.lua
--[[-------------------------------------------------------------------------- LGI testsuite, GIo test suite. Copyright (c) 2016 Uli Schlachter Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- local type = type local lgi = require 'lgi' local core = require 'lgi.core' local check = testsuite.check local checkv = testsuite.checkv local gio = testsuite.group.new('gio') function gio.read() local GLib, Gio = lgi.GLib, lgi.Gio -- Prepare the input to read local input input = "line" input = Gio.MemoryInputStream.new_from_data(input) input = Gio.DataInputStream.new(input) local line, length -- Read line line, length = input:read_line() checkv(line, "line", "string") checkv(length, 4, "number") -- Read EOF line, length = input:read_line() checkv(line, nil, "nil") checkv(length, 0, "number") end function gio.async_access() local Gio = lgi.Gio local res res = Gio.DBusProxy.async_new check(res ~= nil) check(type(res) == 'function') res = Gio.DBusProxy.async_call check(res ~= nil) check(type(res) == 'function') res = Gio.async_bus_get check(res ~= nil) check(type(res) == 'function') local file = Gio.File.new_for_path('.') res = Gio.Async.call(function(target) return target:async_query_info('standard::size', 'NONE') end)(file) check(res ~= nil) local b = Gio.Async.call(function() return Gio.async_bus_get('SESSION') end)() check(Gio.DBusConnection:is_type_of(b)) local proxy = Gio.Async.call(function(bus) return Gio.DBusProxy.async_new( bus, 'NONE', nil, 'org.freedesktop.DBus', '/', 'org.freedesktop.DBus') end)(b) check(Gio.DBusProxy:is_type_of(proxy)) end
--[[-------------------------------------------------------------------------- LGI testsuite, GIo test suite. Copyright (c) 2016 Uli Schlachter Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- local type = type local lgi = require 'lgi' local core = require 'lgi.core' local check = testsuite.check local checkv = testsuite.checkv local gio = testsuite.group.new('gio') function gio.read() local GLib, Gio = lgi.GLib, lgi.Gio -- Prepare the input to read local input input = "line" input = Gio.MemoryInputStream.new_from_data(input) input = Gio.DataInputStream.new(input) local line, length -- Read line line, length = input:read_line() checkv(line, "line", "string") checkv(length, 4, "number") -- Read EOF line, length = input:read_line() checkv(line, nil, "nil") checkv(length, 0, "number") end function gio.async_access() local Gio = lgi.Gio local res res = Gio.DBusProxy.async_new check(res ~= nil) check(type(res) == 'function') res = Gio.DBusProxy.async_call check(res ~= nil) check(type(res) == 'function') res = Gio.async_bus_get check(res ~= nil) check(type(res) == 'function') local file = Gio.File.new_for_path('.') res = Gio.Async.call(function(target) return target:async_query_info('standard::size', 'NONE') end)(file) check(res ~= nil) local b = Gio.Async.call(function() return Gio.async_bus_get('SESSION') end)() check(Gio.DBusConnection:is_type_of(b)) -- Disable randomly crashing test until issue with random dbus -- crashes is resolved. if false then local proxy = Gio.Async.call(function(bus) return Gio.DBusProxy.async_new( bus, 'NONE', nil, 'org.freedesktop.DBus', '/', 'org.freedesktop.DBus') end)(b) check(Gio.DBusProxy:is_type_of(proxy)) end end
Disable crashing test until underlying issue is fixed
Disable crashing test until underlying issue is fixed
Lua
mit
pavouk/lgi,psychon/lgi
2dd5ab923cf2c22c98acded25a58f7c459af472e
packages/lime-system/files/usr/lib/lua/lime/network.lua
packages/lime-system/files/usr/lib/lua/lime/network.lua
#!/usr/bin/lua network = {} local bit = require "nixio".bit local ip = require "luci.ip" local function hex(x) return string.format("%02x", x) end local function split(string, sep) local ret = {} for token in string.gmatch(string, "[^"..sep.."]+") do table.insert(ret, token) end return ret end function network.eui64(mac) local function flip_7th_bit(x) return hex(bit.bxor(tonumber(x, 16), 2)) end local t = split(mac, ":") t[1] = flip_7th_bit(t[1]) return string.format("%s%s:%sff:fe%s:%s%s", t[1], t[2], t[3], t[4], t[5], t[6]) end --! @DEPRECATED function network.generate_host(ipprefix, hexsuffix) -- use only the 8 rightmost nibbles for IPv4, or 32 nibbles for IPv6 hexsuffix = hexsuffix:sub((ipprefix[1] == 4) and -8 or -32) -- convert hexsuffix into a cidr instance, using same prefix and family of ipprefix local ipsuffix = ip.Hex(hexsuffix, ipprefix:prefix(), ipprefix[1]) local ipaddress = ipprefix -- if it's a network prefix, fill in host bits with ipsuffix if ipprefix:equal(ipprefix:network()) then for i in ipairs(ipprefix[2]) do -- reset ipsuffix netmask bits to 0 ipsuffix[2][i] = bit.bxor(ipsuffix[2][i],ipsuffix:network()[2][i]) -- fill in ipaddress host part, with ipsuffix bits ipaddress[2][i] = bit.bor(ipaddress[2][i],ipsuffix[2][i]) end end return ipaddress end function network.generate_address(p, n) local ipv4_template = assert(uci:get("lime", "network", "ipv4_address")) local ipv6_template = assert(uci:get("lime", "network", "ipv6_address")) local pm = primary_mac() for i=1,6,1 do ipv6_template = ipv6_template:gsub("M" .. i, pm[i]) ipv4_template = ipv4_template:gsub("M" .. i, tonumber(pm[i], 16)) end return ip.IPv4(ipv4_template), ip.IPv6(ipv6_template) end function network.setup_lan(ipv4, ipv6) uci:set("network", "lan", "ip6addr", ipv6:string()) uci:set("network", "lan", "ipaddr", ipv4:host():string()) uci:set("network", "lan", "netmask", ipv4:mask():string()) uci:set("network", "lan", "ifname", "eth0 bat0") uci:save("network") end function network.setup_anygw(ipv4, ipv6) local n1, n2, n3 = network_id() -- anygw macvlan interface print("Adding macvlan interface to uci network...") local anygw_mac = string.format("aa:aa:aa:%02x:%02x:%02x", n1, n2, n3) local anygw_ipv6 = ipv6:minhost() local anygw_ipv4 = ipv4:minhost() anygw_ipv6[3] = 64 -- SLAAC only works with a /64, per RFC anygw_ipv4[3] = ipv4:prefix() uci:set("network", "lm_anygw_dev", "device") uci:set("network", "lm_anygw_dev", "type", "macvlan") uci:set("network", "lm_anygw_dev", "name", "anygw") uci:set("network", "lm_anygw_dev", "ifname", "@lan") uci:set("network", "lm_anygw_dev", "macaddr", anygw_mac) uci:set("network", "lm_anygw_if", "interface") uci:set("network", "lm_anygw_if", "proto", "static") uci:set("network", "lm_anygw_if", "ifname", "anygw") uci:set("network", "lm_anygw_if", "ip6addr", anygw_ipv6:string()) uci:set("network", "lm_anygw_if", "ipaddr", anygw_ipv4:host():string()) uci:set("network", "lm_anygw_if", "netmask", anygw_ipv4:mask():string()) local content = { insert = table.insert, concat = table.concat } for line in io.lines("/etc/firewall.user") do if not line:match("^ebtables ") then content:insert(line) end end content:insert("ebtables -A FORWARD -j DROP -d " .. anygw_mac) content:insert("ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac) fs.writefile("/etc/firewall.user", content:concat("\n").."\n") -- IPv6 router advertisement for anygw interface print("Enabling RA in dnsmasq...") local content = { } table.insert(content, "enable-ra") table.insert(content, string.format("dhcp-range=tag:anygw, %s, ra-names", anygw_ipv6:network(64):string())) table.insert(content, "dhcp-option=tag:anygw, option6:domain-search, lan") table.insert(content, string.format("address=/anygw/%s", anygw_ipv6:host():string())) table.insert(content, string.format("dhcp-option=tag:anygw, option:router, %s", anygw_ipv4:host():string())) table.insert(content, string.format("dhcp-option=tag:anygw, option:dns-server, %s", anygw_ipv4:host():string())) table.insert(content, "dhcp-broadcast=tag:anygw") table.insert(content, "no-dhcp-interface=br-lan") fs.writefile("/etc/dnsmasq.conf", table.concat(content, "\n").."\n") -- and disable 6relayd print("Disabling 6relayd...") fs.writefile("/etc/config/6relayd", "") end function network.setup_rp_filter() local sysctl_file_path = "/etc/sysctl.conf"; local sysctl_options = ""; local sysctl_file = io.open(sysctl_file_path, "r"); while sysctl_file:read(0) do local sysctl_line = sysctl_file:read(); if not string.find(sysctl_line, ".rp_filter") then sysctl_options = sysctl_options .. sysctl_line .. "\n" end end sysctl_file:close() sysctl_options = sysctl_options .. "net.ipv4.conf.default.rp_filter=2\nnet.ipv4.conf.all.rp_filter=2\n"; sysctl_file = io.open(sysctl_file_path, "w"); sysctl_file:write(sysctl_options); sysctl_file:close(); end function network.clean() print("Clearing network config...") uci:foreach("network", "interface", function(s) if s[".name"]:match("^lm_") then uci:delete("network", s[".name"]) end end) end function network.init() -- TODO end function network.configure() local protocols = assert(uci:get("lime", "network", "protos")) local vlans = assert(uci:get("lime", "network", "vlans")) local n1, n2, n3 = network_id() local m4, m5, m6 = node_id() local ipv4, ipv6 = network.generate_address(1, 0) -- for br-lan network.clean() network.setup_rp_filter() network.setup_lan(ipv4, ipv6) network.setup_anygw(ipv4, ipv6) -- For layer2 use a vlan based off network_id, between 16 and 255, if uci doesn't specify a vlan if not vlans[2] then vlans[2] = math.floor(16 + ((tonumber(n1) / 255) * (255 - 16))) end -- TODO: -- for each net ; if protocols = wan or lan ; setup_network_interface_lan -- elsif protocols = bmx6 or batadv ; setup_network_interface_ .. protocol -- FIXME: currently adds vlan interfaces on top of ethernet, for each proto (batadv or bmx6). -- Eg. lm_eth_batadv local n for n = 1, #protocols do local interface = "lm_eth_" .. protocols[n] local ifname = string.format("eth1.%d", vlans[n]) local ipv4, ipv6 = network.generate_address(n, 0) local proto = require("lime.proto." .. protocols[n]) proto.configure(ipv4, ipv6) proto.setup_interface(interface, ifname, ipv4, ipv6) end end function network.apply() -- TODO (i.e. /etc/init.d/network restart) end return network
#!/usr/bin/lua network = {} local bit = require "nixio".bit local ip = require "luci.ip" local function hex(x) return string.format("%02x", x) end local function split(string, sep) local ret = {} for token in string.gmatch(string, "[^"..sep.."]+") do table.insert(ret, token) end return ret end function network.eui64(mac) local function flip_7th_bit(x) return hex(bit.bxor(tonumber(x, 16), 2)) end local t = split(mac, ":") t[1] = flip_7th_bit(t[1]) return string.format("%s%s:%sff:fe%s:%s%s", t[1], t[2], t[3], t[4], t[5], t[6]) end --! @DEPRECATED function network.generate_host(ipprefix, hexsuffix) -- use only the 8 rightmost nibbles for IPv4, or 32 nibbles for IPv6 hexsuffix = hexsuffix:sub((ipprefix[1] == 4) and -8 or -32) -- convert hexsuffix into a cidr instance, using same prefix and family of ipprefix local ipsuffix = ip.Hex(hexsuffix, ipprefix:prefix(), ipprefix[1]) local ipaddress = ipprefix -- if it's a network prefix, fill in host bits with ipsuffix if ipprefix:equal(ipprefix:network()) then for i in ipairs(ipprefix[2]) do -- reset ipsuffix netmask bits to 0 ipsuffix[2][i] = bit.bxor(ipsuffix[2][i],ipsuffix:network()[2][i]) -- fill in ipaddress host part, with ipsuffix bits ipaddress[2][i] = bit.bor(ipaddress[2][i],ipsuffix[2][i]) end end return ipaddress end function network.generate_address(p, n) local ipv4_template = assert(uci:get("lime", "network", "ipv4_address")) local ipv6_template = assert(uci:get("lime", "network", "ipv6_address")) local pm = primary_mac() for i=1,6,1 do ipv6_template = ipv6_template:gsub("M" .. i, pm[i]) ipv4_template = ipv4_template:gsub("M" .. i, tonumber(pm[i], 16)) end return ip.IPv4(ipv4_template), ip.IPv6(ipv6_template) end function network.setup_lan(ipv4, ipv6) uci:set("network", "lan", "ip6addr", ipv6:string()) uci:set("network", "lan", "ipaddr", ipv4:host():string()) uci:set("network", "lan", "netmask", ipv4:mask():string()) uci:set("network", "lan", "ifname", "eth0 bat0") uci:save("network") end function network.setup_anygw(ipv4, ipv6) local n1, n2, n3 = network_id() -- anygw macvlan interface print("Adding macvlan interface to uci network...") local anygw_mac = string.format("aa:aa:aa:%02x:%02x:%02x", n1, n2, n3) local anygw_ipv6 = ipv6:minhost() local anygw_ipv4 = ipv4:minhost() anygw_ipv6[3] = 64 -- SLAAC only works with a /64, per RFC anygw_ipv4[3] = ipv4:prefix() uci:set("network", "lm_anygw_dev", "device") uci:set("network", "lm_anygw_dev", "type", "macvlan") uci:set("network", "lm_anygw_dev", "name", "anygw") uci:set("network", "lm_anygw_dev", "ifname", "@lan") uci:set("network", "lm_anygw_dev", "macaddr", anygw_mac) uci:set("network", "lm_anygw_if", "interface") uci:set("network", "lm_anygw_if", "proto", "static") uci:set("network", "lm_anygw_if", "ifname", "anygw") uci:set("network", "lm_anygw_if", "ip6addr", anygw_ipv6:string()) uci:set("network", "lm_anygw_if", "ipaddr", anygw_ipv4:host():string()) uci:set("network", "lm_anygw_if", "netmask", anygw_ipv4:mask():string()) local content = { insert = table.insert, concat = table.concat } for line in io.lines("/etc/firewall.user") do if not line:match("^ebtables ") then content:insert(line) end end content:insert("ebtables -A FORWARD -j DROP -d " .. anygw_mac) content:insert("ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac) fs.writefile("/etc/firewall.user", content:concat("\n").."\n") -- IPv6 router advertisement for anygw interface print("Enabling RA in dnsmasq...") local content = { } table.insert(content, "enable-ra") table.insert(content, string.format("dhcp-range=tag:anygw, %s, ra-names", anygw_ipv6:network(64):string())) table.insert(content, "dhcp-option=tag:anygw, option6:domain-search, lan") table.insert(content, string.format("address=/anygw/%s", anygw_ipv6:host():string())) table.insert(content, string.format("dhcp-option=tag:anygw, option:router, %s", anygw_ipv4:host():string())) table.insert(content, string.format("dhcp-option=tag:anygw, option:dns-server, %s", anygw_ipv4:host():string())) table.insert(content, "dhcp-broadcast=tag:anygw") table.insert(content, "no-dhcp-interface=br-lan") fs.writefile("/etc/dnsmasq.conf", table.concat(content, "\n").."\n") -- and disable 6relayd print("Disabling 6relayd...") fs.writefile("/etc/config/6relayd", "") end function network.setup_rp_filter() local sysctl_file_path = "/etc/sysctl.conf"; local sysctl_options = ""; local sysctl_file = io.open(sysctl_file_path, "r"); while sysctl_file:read(0) do local sysctl_line = sysctl_file:read(); if not string.find(sysctl_line, ".rp_filter") then sysctl_options = sysctl_options .. sysctl_line .. "\n" end end sysctl_file:close() sysctl_options = sysctl_options .. "net.ipv4.conf.default.rp_filter=2\nnet.ipv4.conf.all.rp_filter=2\n"; sysctl_file = io.open(sysctl_file_path, "w"); sysctl_file:write(sysctl_options); sysctl_file:close(); end function network.clean() print("Clearing network config...") uci:delete("network", "globals", "ula_prefix") uci:foreach("network", "interface", function(s) if s[".name"]:match("^lm_") then uci:delete("network", s[".name"]) end end) end function network.init() -- TODO end function network.configure() local protocols = assert(uci:get("lime", "network", "protos")) local vlans = assert(uci:get("lime", "network", "vlans")) local n1, n2, n3 = network_id() local m4, m5, m6 = node_id() local ipv4, ipv6 = network.generate_address(1, 0) -- for br-lan network.clean() network.setup_rp_filter() network.setup_lan(ipv4, ipv6) network.setup_anygw(ipv4, ipv6) -- For layer2 use a vlan based off network_id, between 16 and 255, if uci doesn't specify a vlan if not vlans[2] then vlans[2] = math.floor(16 + ((tonumber(n1) / 255) * (255 - 16))) end -- TODO: -- for each net ; if protocols = wan or lan ; setup_network_interface_lan -- elsif protocols = bmx6 or batadv ; setup_network_interface_ .. protocol -- FIXME: currently adds vlan interfaces on top of ethernet, for each proto (batadv or bmx6). -- Eg. lm_eth_batadv local n for n = 1, #protocols do local interface = "lm_eth_" .. protocols[n] local ifname = string.format("eth1.%d", vlans[n]) local ipv4, ipv6 = network.generate_address(n, 0) local proto = require("lime.proto." .. protocols[n]) proto.configure(ipv4, ipv6) proto.setup_interface(interface, ifname, ipv4, ipv6) end end function network.apply() -- TODO (i.e. /etc/init.d/network restart) end return network
Disable ipv6 ula_prefix
Disable ipv6 ula_prefix
Lua
agpl-3.0
p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages
d6d95156bf61b43c6e4d8041811cc1fbfcbacb45
src/apps/intel/intel_app.lua
src/apps/intel/intel_app.lua
module(...,package.seeall) local app = require("core.app") local buffer = require("core.buffer") local packet = require("core.packet") local lib = require("core.lib") local register = require("lib.hardware.register") local intel10g = require("apps.intel.intel10g") Intel82599 = {} -- Create an Intel82599 App for the device with 'pciaddress'. function Intel82599:new (pciaddress) local a = app.new(Intel82599) a.dev = intel10g.new(pciaddress) setmetatable(a, {__index = Intel82599 }) intel10g.open_for_loopback_test(a.dev) return a end -- Pull in packets from the network and queue them on our 'tx' link. function Intel82599:pull () local l = self.output.tx if l == nil then return end self.dev:sync_receive() while not app.full(l) and self.dev:can_receive() do app.transmit(l, self.dev:receive()) end while self.dev:can_add_receive_buffer() do self.dev:add_receive_buffer(buffer.allocate()) end end -- Push packets from our 'rx' link onto the network. function Intel82599:push () local l = self.input.rx if l == nil then return end while not app.empty(l) and self.dev:can_transmit() do local p = app.receive(l) self.dev:transmit(p) packet.deref(p) end self.dev:sync_transmit() end -- Report on relevant status and statistics. function Intel82599:report () print("report on intel device", self.dev.pciaddress) --register.dump(self.dev.r) register.dump(self.dev.s, true) end function selftest () -- Create a pieline: -- Source --> Intel82599(loopback) --> Sink -- and push packets through it. app.apps.intel10g = Intel82599:new("0000:01:00.0") app.apps.source = app.new(app.Source) app.apps.sink = app.new(app.Sink) app.connect("source", "out", "intel10g", "rx") app.connect("intel10g", "tx", "sink", "in") app.relink() buffer.preallocate(100000) local deadline = lib.timer(1e9) repeat app.breathe() until deadline() app.report() end
module(...,package.seeall) local app = require("core.app") local basic_apps = require("apps.basic.basic_apps") local buffer = require("core.buffer") local packet = require("core.packet") local lib = require("core.lib") local register = require("lib.hardware.register") local intel10g = require("apps.intel.intel10g") Intel82599 = {} -- Create an Intel82599 App for the device with 'pciaddress'. function Intel82599:new (pciaddress) local a = app.new(Intel82599) a.dev = intel10g.new(pciaddress) setmetatable(a, {__index = Intel82599 }) intel10g.open_for_loopback_test(a.dev) return a end -- Pull in packets from the network and queue them on our 'tx' link. function Intel82599:pull () local l = self.output.tx if l == nil then return end self.dev:sync_receive() while not app.full(l) and self.dev:can_receive() do app.transmit(l, self.dev:receive()) end while self.dev:can_add_receive_buffer() do self.dev:add_receive_buffer(buffer.allocate()) end end -- Push packets from our 'rx' link onto the network. function Intel82599:push () local l = self.input.rx if l == nil then return end while not app.empty(l) and self.dev:can_transmit() do local p = app.receive(l) self.dev:transmit(p) packet.deref(p) end self.dev:sync_transmit() end -- Report on relevant status and statistics. function Intel82599:report () print("report on intel device", self.dev.pciaddress) --register.dump(self.dev.r) register.dump(self.dev.s, true) end function selftest () -- Create a pieline: -- Source --> Intel82599(loopback) --> Sink -- and push packets through it. app.apps.intel10g = Intel82599:new("0000:01:00.0") app.apps.source = app.new(basic_apps.Source) app.apps.sink = app.new(basic_apps.Sink) app.connect("source", "out", "intel10g", "rx") app.connect("intel10g", "tx", "sink", "in") app.relink() buffer.preallocate(100000) local deadline = lib.timer(1e9) repeat app.breathe() until deadline() app.report() end
intel_app: Fixed selftest() function.
intel_app: Fixed selftest() function. Needed to be updated after changes to the app module interface.
Lua
apache-2.0
wingo/snabb,dpino/snabb,wingo/snabbswitch,Igalia/snabb,virtualopensystems/snabbswitch,kbara/snabb,fhanik/snabbswitch,wingo/snabbswitch,pirate/snabbswitch,heryii/snabb,heryii/snabb,justincormack/snabbswitch,hb9cwp/snabbswitch,kellabyte/snabbswitch,hb9cwp/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,wingo/snabbswitch,snabbnfv-goodies/snabbswitch,hb9cwp/snabbswitch,wingo/snabb,dpino/snabbswitch,dwdm/snabbswitch,heryii/snabb,fhanik/snabbswitch,plajjan/snabbswitch,aperezdc/snabbswitch,andywingo/snabbswitch,SnabbCo/snabbswitch,snabbnfv-goodies/snabbswitch,aperezdc/snabbswitch,dpino/snabbswitch,mixflowtech/logsensor,mixflowtech/logsensor,alexandergall/snabbswitch,plajjan/snabbswitch,lukego/snabb,dpino/snabb,wingo/snabb,dwdm/snabbswitch,heryii/snabb,Igalia/snabbswitch,xdel/snabbswitch,kbara/snabb,snabbnfv-goodies/snabbswitch,eugeneia/snabb,pirate/snabbswitch,virtualopensystems/snabbswitch,mixflowtech/logsensor,andywingo/snabbswitch,kbara/snabb,eugeneia/snabb,snabbco/snabb,justincormack/snabbswitch,pavel-odintsov/snabbswitch,eugeneia/snabbswitch,heryii/snabb,Igalia/snabb,alexandergall/snabbswitch,fhanik/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,dpino/snabbswitch,pirate/snabbswitch,javierguerragiraldez/snabbswitch,lukego/snabbswitch,Igalia/snabbswitch,Igalia/snabbswitch,dwdm/snabbswitch,andywingo/snabbswitch,plajjan/snabbswitch,heryii/snabb,virtualopensystems/snabbswitch,Igalia/snabb,Igalia/snabb,lukego/snabb,Igalia/snabb,dpino/snabbswitch,justincormack/snabbswitch,lukego/snabb,javierguerragiraldez/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,plajjan/snabbswitch,Igalia/snabb,dpino/snabb,dpino/snabb,lukego/snabbswitch,alexandergall/snabbswitch,pavel-odintsov/snabbswitch,dpino/snabb,alexandergall/snabbswitch,aperezdc/snabbswitch,Igalia/snabb,lukego/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,lukego/snabbswitch,eugeneia/snabb,kellabyte/snabbswitch,mixflowtech/logsensor,SnabbCo/snabbswitch,aperezdc/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,kellabyte/snabbswitch,andywingo/snabbswitch,hb9cwp/snabbswitch,dpino/snabb,wingo/snabb,snabbco/snabb,mixflowtech/logsensor,snabbnfv-goodies/snabbswitch,wingo/snabb,kbara/snabb,SnabbCo/snabbswitch,xdel/snabbswitch,dpino/snabb,xdel/snabbswitch,snabbco/snabb,wingo/snabb,kbara/snabb,justincormack/snabbswitch,wingo/snabbswitch,snabbco/snabb,javierguerragiraldez/snabbswitch,eugeneia/snabbswitch,pavel-odintsov/snabbswitch,snabbco/snabb,kbara/snabb,SnabbCo/snabbswitch,lukego/snabb,Igalia/snabb,eugeneia/snabb
2e077d8eda6f12cc818134c2a2125411d9b2ae37
SVUI_UnitFrames/libs/Plugins/oUF_WarlockShards/oUF_WarlockShards.lua
SVUI_UnitFrames/libs/Plugins/oUF_WarlockShards/oUF_WarlockShards.lua
--GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; --MATH local math = _G.math; local floor = math.floor --BLIZZARD API local UnitPower = _G.UnitPower; local UnitPowerMax = _G.UnitPowerMax; local UnitHasVehicleUI = _G.UnitHasVehicleUI; local GetSpecialization = _G.GetSpecialization; if select(2, UnitClass('player')) ~= "WARLOCK" then return end local _, ns = ... local oUF = ns.oUF or oUF assert(oUF, 'oUF_WarlockShards was unable to locate oUF install') local shardColor = { [1] = {0,0.72,0.1}, [2] = {0.57,0.08,1}, [3] = {1,0.25,0} } local Update = function(self, event, unit, powerType) local bar = self.WarlockShards; if(bar.PreUpdate) then bar:PreUpdate(unit) end if UnitHasVehicleUI("player") then bar:Hide() else bar:Show() end local spec = GetSpecialization() if spec then local colors = shardColor[spec] local numShards = UnitPower("player", SPELL_POWER_SOUL_SHARDS); bar.MaxCount = UnitPowerMax("player", SPELL_POWER_SOUL_SHARDS); if not bar:IsShown() then bar:Show() end if((not bar.CurrentSpec) or (bar.CurrentSpec ~= spec and bar.UpdateTextures)) then bar:UpdateTextures(spec) end for i = 1, 5 do if(i > bar.MaxCount) then bar[i]:Hide() else bar[i]:Show() bar[i]:SetStatusBarColor(unpack(colors)) bar[i]:SetMinMaxValues(0, 1) local filled = (i <= numShards) and 1 or 0 bar[i]:SetValue(filled) if(bar[i].Update) then bar[i]:Update(filled) end end end else if bar:IsShown() then bar:Hide() end; end if(bar.PostUpdate) then return bar:PostUpdate(unit, spec) end end local Path = function(self, ...) return (self.WarlockShards.Override or Update) (self, ...) end local ForceUpdate = function(element) return Path(element.__owner, 'ForceUpdate', element.__owner.unit, 'SOUL_SHARDS') end local function Enable(self, unit) if(unit ~= 'player') then return end local bar = self.WarlockShards if(bar) then bar.__owner = self bar.ForceUpdate = ForceUpdate self:RegisterEvent('UNIT_POWER_UPDATE', Path) self:RegisterEvent("PLAYER_TALENT_UPDATE", Path) self:RegisterEvent("PLAYER_ENTERING_WORLD", Path) self:RegisterEvent('UNIT_DISPLAYPOWER', Path) self:RegisterEvent("UNIT_POWER_FREQUENT", Path) self:RegisterEvent("UNIT_MAXPOWER", Path) self:RegisterUnitEvent('UNIT_DISPLAYPOWER', "player") self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player") self:RegisterUnitEvent("UNIT_MAXPOWER", "player") for i = 1, 5 do if not bar[i]:GetStatusBarTexture() then bar[i]:SetStatusBarTexture([=[Interface\TargetingFrame\UI-StatusBar]=]) end bar[i]:SetFrameLevel(bar:GetFrameLevel() + 1) bar[i]:GetStatusBarTexture():SetHorizTile(false) end return true end end local function Disable(self) local bar = self.WarlockShards if(bar) then self:UnregisterEvent('UNIT_POWER_UPDATE', Path) self:UnregisterEvent("PLAYER_TALENT_UPDATE", Path) self:UnregisterEvent("PLAYER_ENTERING_WORLD", Path) self:UnregisterEvent('UNIT_DISPLAYPOWER', Path) self:UnregisterEvent("UNIT_POWER_FREQUENT", Path) self:UnregisterEvent("UNIT_MAXPOWER", Path) bar:Hide() end end oUF:AddElement('WarlockShards', Path, Enable, Disable)
--GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; --MATH local math = _G.math; local floor = math.floor --BLIZZARD API local UnitPower = _G.UnitPower; local UnitPowerMax = _G.UnitPowerMax; local UnitHasVehicleUI = _G.UnitHasVehicleUI; local GetSpecialization = _G.GetSpecialization; if select(2, UnitClass('player')) ~= "WARLOCK" then return end local _, ns = ... local oUF = ns.oUF or oUF assert(oUF, 'oUF_WarlockShards was unable to locate oUF install') local shardColor = { [1] = {0,0.72,0.1}, [2] = {0.57,0.08,1}, [3] = {1,0.25,0} } local Update = function(self, event, unit, powerType) local bar = self.WarlockShards; if(bar.PreUpdate) then bar:PreUpdate(unit) end if UnitHasVehicleUI("player") then bar:Hide() else bar:Show() end local spec = GetSpecialization() if spec then local colors = shardColor[spec] local numShards = UnitPower("player", Enum.PowerType.SoulShards); bar.MaxCount = UnitPowerMax("player", Enum.PowerType.SoulShards); if not bar:IsShown() then bar:Show() end if((not bar.CurrentSpec) or (bar.CurrentSpec ~= spec and bar.UpdateTextures)) then bar:UpdateTextures(spec) end for i = 1, 5 do if(i > bar.MaxCount) then bar[i]:Hide() else bar[i]:Show() bar[i]:SetStatusBarColor(unpack(colors)) bar[i]:SetMinMaxValues(0, 1) local filled = (i <= numShards) and 1 or 0 bar[i]:SetValue(filled) if(bar[i].Update) then bar[i]:Update(filled) end end end else if bar:IsShown() then bar:Hide() end; end if(bar.PostUpdate) then return bar:PostUpdate(unit, spec) end end local Path = function(self, ...) return (self.WarlockShards.Override or Update) (self, ...) end local ForceUpdate = function(element) return Path(element.__owner, 'ForceUpdate', element.__owner.unit, 'SOUL_SHARDS') end local function Enable(self, unit) if(unit ~= 'player') then return end local bar = self.WarlockShards if(bar) then bar.__owner = self bar.ForceUpdate = ForceUpdate self:RegisterEvent('UNIT_POWER_UPDATE', Path) self:RegisterEvent("PLAYER_TALENT_UPDATE", Path) self:RegisterEvent("PLAYER_ENTERING_WORLD", Path) self:RegisterEvent('UNIT_DISPLAYPOWER', Path) self:RegisterEvent("UNIT_POWER_FREQUENT", Path) self:RegisterEvent("UNIT_MAXPOWER", Path) self:RegisterUnitEvent('UNIT_DISPLAYPOWER', "player") self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player") self:RegisterUnitEvent("UNIT_MAXPOWER", "player") for i = 1, 5 do if not bar[i]:GetStatusBarTexture() then bar[i]:SetStatusBarTexture([=[Interface\TargetingFrame\UI-StatusBar]=]) end bar[i]:SetFrameLevel(bar:GetFrameLevel() + 1) bar[i]:GetStatusBarTexture():SetHorizTile(false) end return true end end local function Disable(self) local bar = self.WarlockShards if(bar) then self:UnregisterEvent('UNIT_POWER_UPDATE', Path) self:UnregisterEvent("PLAYER_TALENT_UPDATE", Path) self:UnregisterEvent("PLAYER_ENTERING_WORLD", Path) self:UnregisterEvent('UNIT_DISPLAYPOWER', Path) self:UnregisterEvent("UNIT_POWER_FREQUENT", Path) self:UnregisterEvent("UNIT_MAXPOWER", Path) bar:Hide() end end oUF:AddElement('WarlockShards', Path, Enable, Disable)
Warlock shards fix
Warlock shards fix
Lua
mit
FailcoderAddons/supervillain-ui,finalsliver/supervillain-ui
2cfdcfbdfdcebd2078e746daa7b9974f93cb20f4
src/apenode/plugins/ratelimiting/access.lua
src/apenode/plugins/ratelimiting/access.lua
-- Copyright (C) Mashape, Inc. local _M = {} function _M.execute(conf) local authenticated_entity_id = nil if ngx.ctx.authenticated_entity then authenticated_entity_id = ngx.ctx.authenticated_entity.id else authenticated_entity_id = ngx.var.remote_addr -- Use the IP if there is not authenticated entity end local period = conf.period local limit = conf.limit local timestamps = utils.get_timestamps(ngx.now()) local current_usage = dao.metrics:find_one({ api_id = ngx.ctx.api.id, application_id = authenticated_entity_id, name = "requests." .. period, timestamp = timestamps[period] }) if current_usage then current_usage = current_usage.value else current_usage = 0 end ngx.header["X-RateLimit-Limit"] = limit ngx.header["X-RateLimit-Remaining"] = limit - current_usage if current_usage >= limit then utils.show_error(429, "API rate limit exceeded") end -- Increment usage for all the metrics -- TODO: this could also be done asynchronously in a timer maybe if specified in the conf (more performance, less security)? for k,v in pairs(timestamps) do dao.metrics:increment_metric(ngx.ctx.api.id, authenticated_entity_id, "requests." .. k, v, 1) end end return _M
-- Copyright (C) Mashape, Inc. local _M = {} local function set_header_limit_remaining(usage) ngx.header["X-RateLimit-Remaining"] = usage end function _M.execute(conf) local authenticated_entity_id = nil if ngx.ctx.authenticated_entity then authenticated_entity_id = ngx.ctx.authenticated_entity.id else authenticated_entity_id = ngx.var.remote_addr -- Use the IP if there is not authenticated entity end local period = conf.period local limit = conf.limit local timestamps = utils.get_timestamps(ngx.now()) local current_usage = dao.metrics:find_one(ngx.ctx.api.id, authenticated_entity_id, "requests." .. period, timestamps[period]) if current_usage then current_usage = current_usage.value else current_usage = 0 end ngx.header["X-RateLimit-Limit"] = limit if current_usage >= limit then set_header_limit_remaining(limit - current_usage) utils.show_error(429, "API rate limit exceeded") else set_header_limit_remaining(limit - current_usage - 1) end -- Increment usage for all the metrics -- TODO: this could also be done asynchronously in a timer maybe if specified in the conf (more performance, less security)? for k,v in pairs(timestamps) do dao.metrics:increment_metric(ngx.ctx.api.id, authenticated_entity_id, "requests." .. k, v, 1) end end return _M
fixing ratelimiting
fixing ratelimiting
Lua
apache-2.0
Kong/kong,AnsonSmith/kong,vzaramel/kong,ind9/kong,rafael/kong,ropik/kong,isdom/kong,streamdataio/kong,ccyphers/kong,jerizm/kong,ind9/kong,akh00/kong,Vermeille/kong,ejoncas/kong,Skyscanner/kong,ejoncas/kong,paritoshmmmec/kong,jebenexer/kong,kyroskoh/kong,kyroskoh/kong,li-wl/kong,xvaara/kong,smanolache/kong,Kong/kong,wakermahmud/kong,bbalu/kong,vzaramel/kong,Kong/kong,salazar/kong,Mashape/kong,skynet/kong,beauli/kong,peterayeni/kong,vmercierfr/kong,streamdataio/kong,ChristopherBiscardi/kong,puug/kong,icyxp/kong,isdom/kong,shiprabehera/kong,sbuettner/kong,rafael/kong,chourobin/kong,ajayk/kong
383ef230d0fb3f0057a26cc2987d0e7c04c226df
vbulletin.lua
vbulletin.lua
--[[ Download script for vbulletin forums. 2012.09.14 This script walks the forum pages: forum to threads to posts. It will also download the member pages. You need Wget+Lua to run this script. Run Wget with seed URLs that point to the forum you want to download. Give the URL to the forumdisplay.php for the forum you want to have. Note: the script does not explore subforums, you have to specify the URL with forum ID for every forum you want to archive. http://example.com/forumdisplay.php?f=1 http://example.com/forumdisplay.php?f=2 ... Use --page-requisites --span-hosts, but do not use --mirror or --recursive. Example command line: ./wget-warc-lua \ --directory-prefix=files/ \ --force-directories --adjust-extension \ --user-agent="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27" \ -nv -o files/wget.log \ --page-requisites --span-hosts \ -e "robots=off" \ --keep-session-cookies --save-cookies=files/cookies.txt \ --timeout=10 --tries=3 --waitretry=5 \ --lua-script=vbulletin.lua \ --warc-max-size=200M \ --warc-header="operator: Archive Team" \ --warc-file=forums.steampowered.com-vbulletin-$( date +'%Y%m%d' ) \ --header="Cookie: bblastvisit=1495056394; __utmt=1; bblastactivity=0; bbsessionhash=03948598c9a709717277ba412e5ff352; bbforum_view=e62f44913aeb32d4ddc2ee89de61e6c886b6992da-2-%7Bi-14_i-1495057128_i-1189_i-1495057156_%7D; __utma=127613338.730818989.1493599611.1495044823.1495054243.8; __utmb=127613338.150.10.1495054243; __utmc=-127613338; __utmz=127613338.1494988830.5.3.utmcsr=chat.efnet.org:9090|utmccn=(referral)|utmcmd=referral|utmcct=/" "http://forums.steampowered.com/forums/forumdisplay.php?f=123" --]] read_file = function(file) local f = io.open(file) local data = f:read("*all") f:close() return data end url_count = 0 wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} -- progress message url_count = url_count + 1 if url_count % 25 == 0 then print(" - Downloaded "..url_count.." URLs") end base, forum_id = string.match(url, "(http://.+)/forumdisplay%.php%?f=(%d+)&amp;daysprune=-1") if base then -- a forum page: listing subforums, anouncements and/or threads -- NOTE: this step does not explore subforums html = read_file(file) -- pages for f, o, p in string.gmatch(html, "forumdisplay%.php%?f=(%d+)&amp;order=(%l+)&amp;page=(%d+)") do table.insert(urls, { url=(base.."/forumdisplay.php?f="..f.."&order="..o.."&page="..p.."&amp;daysprune=-1"), link_expect_html=1 }) end -- all announcements table.insert(urls, { url=(base.."/announcement.php?f="..forum_id), link_expect_html=1 }) -- individual announcements for f, a in string.gmatch(html, "announcement%.php%?f=(%d+)&amp;a=(%d+)") do table.insert(urls, { url=(base.."/announcement.php?f="..f.."&a="..a), link_expect_html=1 }) end -- threads for t in string.gmatch(html, "showthread%.php%?t=(%d+)") do table.insert(urls, { url=(base.."/showthread.php?t="..t), link_expect_html=1 }) table.insert(urls, { url=(base.."/misc.php?do=whoposted&t="..t), link_expect_html=1 }) end return urls end base, thread_id = string.match(url, "(http://.+)/showthread%.php%?t=(%d+)") if base then -- a thread page html = read_file(file) -- print table.insert(urls, { url=(base.."/printthread.php?t="..thread_id), link_expect_html=1 }) table.insert(urls, { url=(base.."/printthread.php?t="..thread_id.."&pp=500"), link_expect_html=1 }) -- pages for p in string.gmatch(html, "showthread%.php%?t="..thread_id.."&amp;page=(%d+)") do table.insert(urls, { url=(base.."/showthread.php?t="..thread_id.."&page="..p), link_expect_html=1 }) end -- members for u in string.gmatch(html, "member%.php%?u=(%d+)") do table.insert(urls, { url=(base.."/member.php?u="..u), link_expect_html=1 }) table.insert(urls, { url=(base.."/member.php?u="..u.."&do=vcard"), link_expect_html=1 }) end -- posts for p, c in string.gmatch(html, "showpost%.php%?p=(%d+)&amp;postcount=(%d+)\"[^>]+id=\"postcount") do table.insert(urls, { url=(base.."/showpost.php?p="..p.."&postcount="..c), link_expect_html=1 }) table.insert(urls, { url=(base.."/showthread.php?p="..p), link_expect_html=1 }) end return urls end return {} end
--[[ Download script for vbulletin forums. 2012.09.14 This script walks the forum pages: forum to threads to posts. It will also download the member pages. You need Wget+Lua to run this script. Run Wget with seed URLs that point to the forum you want to download. Give the URL to the forumdisplay.php for the forum you want to have. Note: the script does not explore subforums, you have to specify the URL with forum ID for every forum you want to archive. http://example.com/forumdisplay.php?f=1 http://example.com/forumdisplay.php?f=2 ... Use --page-requisites --span-hosts, but do not use --mirror or --recursive. Example command line: ./wget-warc-lua \ --directory-prefix=files/ \ --force-directories --adjust-extension \ --user-agent="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27" \ -nv -o files/wget.log \ --page-requisites --span-hosts \ -e "robots=off" \ --keep-session-cookies --save-cookies=files/cookies.txt \ --timeout=10 --tries=3 --waitretry=5 \ --lua-script=vbulletin.lua \ --warc-max-size=200M \ --warc-header="operator: Archive Team" \ --warc-file=forums.steampowered.com-vbulletin-$( date +'%Y%m%d' ) \ --header="Cookie: bblastvisit=1495056394; __utmt=1; bblastactivity=0; bbsessionhash=03948598c9a709717277ba412e5ff352; bbforum_view=e62f44913aeb32d4ddc2ee89de61e6c886b6992da-2-%7Bi-14_i-1495057128_i-1189_i-1495057156_%7D; __utma=127613338.730818989.1493599611.1495044823.1495054243.8; __utmb=127613338.150.10.1495054243; __utmc=-127613338; __utmz=127613338.1494988830.5.3.utmcsr=chat.efnet.org:9090|utmccn=(referral)|utmcmd=referral|utmcct=/" "http://forums.steampowered.com/forums/forumdisplay.php?f=123" --]] read_file = function(file) local f = io.open(file) local data = f:read("*all") f:close() return data end url_count = 0 wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} -- progress message url_count = url_count + 1 if url_count % 25 == 0 then print(" - Downloaded "..url_count.." URLs") end base, forum_id = string.match(url, "(http://.+)/forumdisplay%.php%?f=(%d+)") if base then -- a forum page: listing subforums, anouncements and/or threads -- NOTE: this step does not explore subforums html = read_file(file) -- pages for f, o, p in string.gmatch(html, "forumdisplay%.php%?f=(%d+)&amp;order=(%l+)&amp;daysprune=-1&amp;page=(%d+)") do table.insert(urls, { url=(base.."/forumdisplay.php?f="..f.."&order="..o.."&page="..p.."&amp;daysprune=-1"), link_expect_html=1 }) end -- all announcements table.insert(urls, { url=(base.."/announcement.php?f="..forum_id), link_expect_html=1 }) -- individual announcements for f, a in string.gmatch(html, "announcement%.php%?f=(%d+)&amp;a=(%d+)") do table.insert(urls, { url=(base.."/announcement.php?f="..f.."&a="..a), link_expect_html=1 }) end -- threads for t in string.gmatch(html, "showthread%.php%?t=(%d+)") do table.insert(urls, { url=(base.."/showthread.php?t="..t), link_expect_html=1 }) table.insert(urls, { url=(base.."/misc.php?do=whoposted&t="..t), link_expect_html=1 }) end return urls end base, thread_id = string.match(url, "(http://.+)/showthread%.php%?t=(%d+)") if base then -- a thread page html = read_file(file) -- print table.insert(urls, { url=(base.."/printthread.php?t="..thread_id), link_expect_html=1 }) table.insert(urls, { url=(base.."/printthread.php?t="..thread_id.."&pp=500"), link_expect_html=1 }) -- pages for p in string.gmatch(html, "showthread%.php%?t="..thread_id.."&amp;page=(%d+)") do table.insert(urls, { url=(base.."/showthread.php?t="..thread_id.."&page="..p), link_expect_html=1 }) end -- members for u in string.gmatch(html, "member%.php%?u=(%d+)") do table.insert(urls, { url=(base.."/member.php?u="..u), link_expect_html=1 }) table.insert(urls, { url=(base.."/member.php?u="..u.."&do=vcard"), link_expect_html=1 }) end -- posts for p, c in string.gmatch(html, "showpost%.php%?p=(%d+)&amp;postcount=(%d+)\"[^>]+id=\"postcount") do table.insert(urls, { url=(base.."/showpost.php?p="..p.."&postcount="..c), link_expect_html=1 }) table.insert(urls, { url=(base.."/showthread.php?p="..p), link_expect_html=1 }) end return urls end return {} end
Fixed vbulletin.lua
Fixed vbulletin.lua
Lua
unlicense
ArchiveTeam/spuf-grab,ArchiveTeam/spuf-grab
926516c3c4d5acba9c72b25d412200b3c75cbe08
src/lua/export.lua
src/lua/export.lua
-- © 2008 David Given. -- WordGrinder is licensed under the BSD open source license. See the COPYING -- file in this distribution for the full text. -- -- $Id$ -- $URL$ local ITALIC = wg.ITALIC local UNDERLINE = wg.UNDERLINE local ParseWord = wg.parseword local bitand = wg.bitand local bitor = wg.bitor local bitxor = wg.bitxor local bit = wg.bit local string_lower = string.lower -- Renders the document by calling the appropriate functions on the cb -- table. function ExportFileUsingCallbacks(document, cb) cb.prologue() local listmode = false local rawmode = false local italic, underline local olditalic, oldunderline local firstword local wordbreak local wordwriter = function (style, text) italic = bit(style, ITALIC) underline = bit(style, UNDERLINE) local writer if rawmode then writer = cb.rawtext else writer = cb.text end if not italic and olditalic then cb.italic_off() end if not underline and oldunderline then cb.underline_off() end if wordbreak then writer(' ') wordbreak = false end if underline and not oldunderline then cb.underline_on() end if italic and not olditalic then cb.italic_on() end writer(text) olditalic = italic oldunderline = underline end for _, paragraph in ipairs(Document) do local style = paragraph.style if (style.name == "L") or (style.name == "LB") then if not listmode then cb.list_start() listmode = true end elseif listmode then cb.list_end() listmode = false end rawmode = (style.name == "RAW") cb.paragraph_start(style.name) if (#paragraph == 1) and (#paragraph[1].text == 0) then if rawmode then cb.notext() end else firstword = true wordbreak = false olditalic = false oldunderline = false for wn, word in ipairs(paragraph) do if firstword then firstword = false else wordbreak = true end italic = false underline = false ParseWord(word.text, 0, wordwriter) -- FIXME end if italic then cb.italic_off() end if underline then cb.underline_off() end end cb.paragraph_end(style.name) end if listmode then cb.list_end() end cb.epilogue() end -- Prompts the user to export a document, and then calls -- callback(fp, document) to actually do the work. function ExportFileWithUI(filename, title, extension, callback) if not filename then filename = Document.name if filename then if not filename:find("%..-$") then filename = filename .. extension else filename = filename:gsub("%..-$", extension) end else filename = "(unnamed)" end filename = FileBrowser(title, "Export as:", true, filename) if not filename then return false end end ImmediateMessage("Exporting...") local fp, e = io.open(filename, "w") if not fp then ModalMessage(nil, "Unable to open the output file "..e..".") QueueRedraw() return false end callback(fp, Document) fp:close() QueueRedraw() return true end
-- © 2008 David Given. -- WordGrinder is licensed under the BSD open source license. See the COPYING -- file in this distribution for the full text. -- -- $Id$ -- $URL$ local ITALIC = wg.ITALIC local UNDERLINE = wg.UNDERLINE local ParseWord = wg.parseword local bitand = wg.bitand local bitor = wg.bitor local bitxor = wg.bitxor local bit = wg.bit local string_lower = string.lower -- Renders the document by calling the appropriate functions on the cb -- table. function ExportFileUsingCallbacks(document, cb) cb.prologue() local listmode = false local rawmode = false local italic, underline local olditalic, oldunderline local firstword local wordbreak local emptyword local wordwriter = function (style, text) italic = bit(style, ITALIC) underline = bit(style, UNDERLINE) local writer if rawmode then writer = cb.rawtext else writer = cb.text end if not italic and olditalic then cb.italic_off() end if not underline and oldunderline then cb.underline_off() end if wordbreak then writer(' ') wordbreak = false end if underline and not oldunderline then cb.underline_on() end if italic and not olditalic then cb.italic_on() end writer(text) emptyword = false olditalic = italic oldunderline = underline end for _, paragraph in ipairs(Document) do local style = paragraph.style if (style.name == "L") or (style.name == "LB") then if not listmode then cb.list_start() listmode = true end elseif listmode then cb.list_end() listmode = false end rawmode = (style.name == "RAW") cb.paragraph_start(style.name) if (#paragraph == 1) and (#paragraph[1].text == 0) then if rawmode then cb.notext() end else firstword = true wordbreak = false olditalic = false oldunderline = false for wn, word in ipairs(paragraph) do if firstword then firstword = false else wordbreak = true end emptyword = true italic = false underline = false ParseWord(word.text, 0, wordwriter) -- FIXME if emptyword then wordwriter(0, "") end end if italic then cb.italic_off() end if underline then cb.underline_off() end end cb.paragraph_end(style.name) end if listmode then cb.list_end() end cb.epilogue() end -- Prompts the user to export a document, and then calls -- callback(fp, document) to actually do the work. function ExportFileWithUI(filename, title, extension, callback) if not filename then filename = Document.name if filename then if not filename:find("%..-$") then filename = filename .. extension else filename = filename:gsub("%..-$", extension) end else filename = "(unnamed)" end filename = FileBrowser(title, "Export as:", true, filename) if not filename then return false end end ImmediateMessage("Exporting...") local fp, e = io.open(filename, "w") if not fp then ModalMessage(nil, "Unable to open the output file "..e..".") QueueRedraw() return false end callback(fp, Document) fp:close() QueueRedraw() return true end
Fixed to emit the right number of spaces if you put multiple spaces at the beginning of a paragraph.
Fixed to emit the right number of spaces if you put multiple spaces at the beginning of a paragraph.
Lua
mit
rodoviario/wordgrinder,NRauh/wordgrinder,rodoviario/wordgrinder,NRauh/wordgrinder,Munchotaur/wordgrinder,Munchotaur/wordgrinder
b2607802abb7d640d9fe816a7e577aecc460ac13
loot.lua
loot.lua
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local LLN = LibStub("LibLootNotify-1.0") local ignored_items = { [20725] = true, -- Nexus Crystal [22450] = true, -- Void Crystal [34057] = true, -- Abyss Crystal [29434] = true, -- Badge of Justice [40752] = true, -- Emblem of Heroism [40753] = true, -- Emblem of Valor [30311] = true, -- Warp Slicer [30312] = true, -- Infinity Blade [30313] = true, -- Staff of Disintegration [30314] = true, -- Phaseshift Bulwark [30316] = true, -- Devastation [30317] = true, -- Cosmic Infuser [30318] = true, -- Netherstrand Longbow [30319] = true, -- Nether Spikes [30320] = true, -- Bundle of Nether Spikes } local in_combat = false local loot_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopLootQueue() if in_combat then return end if #loot_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end local player, item = unpack(loot_queue[1]) -- In theory this should never happen. if not player or not item then tremove(loot_queue, 1) return end -- User is busy with other popup. if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then return end tremove(loot_queue, 1) local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(item) local r, g, b = GetItemQualityColor(itemRarity) local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", { texture = itemTexture, name = itemName, color = {r, g, b, 1}, link = itemLink }) if dialog then dialog.name = player end end local function LootReceived(event_name, player, itemLink, quantity) if IsRLorML() and CanEditOfficerNote() then local itemID = tonumber(itemLink:match("item:(%d+)") or 0) if not itemID then return end local itemRarity = select(3, GetItemInfo(itemID)) if itemRarity < mod.db.profile.threshold then return end if ignored_items[itemID] then return end tinsert(loot_queue, {player, itemLink, quantity}) if not timer then timer = mod:ScheduleRepeatingTimer("PopLootQueue", 1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end mod.dbDefaults = { profile = { enabled = true, threshold = 4, -- Epic quality items } } mod.optionsName = L["Loot"] mod.optionsDesc = L["Automatic loot tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."] }, threshold = { order = 10, type = "select", name = L["Loot tracking threshold"], desc = L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."], values = { [2] = ITEM_QUALITY2_DESC, [3] = ITEM_QUALITY3_DESC, [4] = ITEM_QUALITY4_DESC, [5] = ITEM_QUALITY5_DESC, }, }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") LLN.RegisterCallback(self, "LootReceived", LootReceived) end function mod:OnDisable() LLN.UnregisterAllCallbacks(self) end
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local LLN = LibStub("LibLootNotify-1.0") local ignored_items = { [20725] = true, -- Nexus Crystal [22450] = true, -- Void Crystal [34057] = true, -- Abyss Crystal [29434] = true, -- Badge of Justice [40752] = true, -- Emblem of Heroism [40753] = true, -- Emblem of Valor [45624] = true, -- Emblem of Conquest [30311] = true, -- Warp Slicer [30312] = true, -- Infinity Blade [30313] = true, -- Staff of Disintegration [30314] = true, -- Phaseshift Bulwark [30316] = true, -- Devastation [30317] = true, -- Cosmic Infuser [30318] = true, -- Netherstrand Longbow [30319] = true, -- Nether Spikes [30320] = true, -- Bundle of Nether Spikes } local in_combat = false local loot_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopLootQueue() if in_combat then return end if #loot_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end local player, item = unpack(loot_queue[1]) -- In theory this should never happen. if not player or not item then tremove(loot_queue, 1) return end -- User is busy with other popup. if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then return end tremove(loot_queue, 1) local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(item) local r, g, b = GetItemQualityColor(itemRarity) local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", { texture = itemTexture, name = itemName, color = {r, g, b, 1}, link = itemLink }) if dialog then dialog.name = player end end local function LootReceived(event_name, player, itemLink, quantity) if IsRLorML() and CanEditOfficerNote() then local itemID = tonumber(itemLink:match("item:(%d+)") or 0) if not itemID then return end local itemRarity = select(3, GetItemInfo(itemID)) if itemRarity < mod.db.profile.threshold then return end if ignored_items[itemID] then return end tinsert(loot_queue, {player, itemLink, quantity}) if not timer then timer = mod:ScheduleRepeatingTimer("PopLootQueue", 1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end mod.dbDefaults = { profile = { enabled = true, threshold = 4, -- Epic quality items } } mod.optionsName = L["Loot"] mod.optionsDesc = L["Automatic loot tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."] }, threshold = { order = 10, type = "select", name = L["Loot tracking threshold"], desc = L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."], values = { [2] = ITEM_QUALITY2_DESC, [3] = ITEM_QUALITY3_DESC, [4] = ITEM_QUALITY4_DESC, [5] = ITEM_QUALITY5_DESC, }, }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") LLN.RegisterCallback(self, "LootReceived", LootReceived) end function mod:OnDisable() LLN.UnregisterAllCallbacks(self) end
Ignore emblems of conquest from auto-loot. This fixes issue 398.
Ignore emblems of conquest from auto-loot. This fixes issue 398.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,sheldon/epgp,sheldon/epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded
1e030da5dc9e32c35d8ffc2f91095ad987616156
otouto/plugins/steam.lua
otouto/plugins/steam.lua
local steam = {} steam.triggers = { "store.steampowered.com/app/([0-9]+)", "steamcommunity.com/app/([0-9]+)" } local BASE_URL = 'http://store.steampowered.com/api/appdetails/' local DESC_LENTH = 400 function steam:get_steam_data(appid) local url = BASE_URL url = url..'?appids='..appid url = url..'&l=german&cc=DE' local res,code = http.request(url) if code ~= 200 then return nil end local data = json.decode(res)[appid].data return data end function steam:price_info(data) local price = '' -- If no data is empty if data then local initial = data.initial local final = data.final or data.initial local min = math.min(data.initial, data.final) price = tostring(min/100) if data.discount_percent and initial ~= final then price = price..data.currency..' ('..data.discount_percent..'% OFF)' end price = price..' €' end return price end function steam:send_steam_data(data, msg) local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...' local title = data.name local price = steam:price_info(data.price_overview) local text = '*'..title..'* _'..price..'_\n'..description local image_url = data.header_image return text, image_url end function steam:action(msg, config, matches) local data = steam:get_steam_data(matches[1]) if not data then utilities.send_reply(msg, config.errors.connection) return end local text, image_url = steam:send_steam_data(data, msg) utilities.send_typing(msg.chat.id, 'upload_photo') utilities.send_photo(msg.chat.id, image_url, nil, msg.message_id) utilities.send_reply(msg, text, true) end return steam
local steam = {} steam.triggers = { "store.steampowered.com/app/([0-9]+)", "steamcommunity.com/app/([0-9]+)" } local BASE_URL = 'http://store.steampowered.com/api/appdetails/' local DESC_LENTH = 400 function steam:get_steam_data(appid) local url = BASE_URL url = url..'?appids='..appid url = url..'&l=german&cc=DE' local res,code = http.request(url) if code ~= 200 then return nil end local data = json.decode(res)[appid].data return data end function steam:price_info(data) local price = '' -- If no data is empty if data then local initial = data.initial local final = data.final or data.initial local min = math.min(data.initial, data.final) price = tostring(min/100) if data.discount_percent and initial ~= final then price = price..data.currency..' ('..data.discount_percent..'% OFF)' end price = price..' €' end return price end function steam:send_steam_data(data, msg) local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...' local title = data.name local price = steam:price_info(data.price_overview) local text = '<b>'..title..'</b> <i>'..price..'</i>\n'..description local image_url = data.header_image return text, image_url end function steam:action(msg, config, matches) local data = steam:get_steam_data(matches[1]) if not data then utilities.send_reply(msg, config.errors.connection) return end local text, image_url = steam:send_steam_data(data, msg) utilities.send_typing(msg.chat.id, 'upload_photo') utilities.send_photo(msg.chat.id, image_url, nil, msg.message_id) print(text) utilities.send_reply(msg, text, 'HTML') end return steam
Steam: Fix
Steam: Fix
Lua
agpl-3.0
Brawl345/Brawlbot-v2
4b1c248a59e98df61fe36eb8ff0e7483c5f27389
src/pause.lua
src/pause.lua
local Gamestate = require 'vendor/gamestate' local window = require 'window' local camera = require 'camera' local fonts = require 'fonts' local sound = require 'vendor/TEsound' local controls = require 'controls' local state = Gamestate.new() local VerticalParticles = require "verticalparticles" local Timer = require 'vendor/timer' function state:init() VerticalParticles.init() self.arrow = love.graphics.newImage("images/menu/arrow.png") self.background = love.graphics.newImage("images/menu/pause.png") end function state:enter(previous) love.graphics.setBackgroundColor(0, 0, 0) sound.playMusic( "daybreak" ) fonts.set( 'big' ) camera:setPosition(0, 0) self.option = 0 if previous ~= Gamestate.get('options') and previous ~= Gamestate.get('instructions') then self.previous = previous end self.konami = { 'UP', 'UP', 'DOWN', 'DOWN', 'LEFT', 'RIGHT', 'LEFT', 'RIGHT', 'JUMP', 'ATTACK' } self.konami_idx = 0 end function state:update(dt) VerticalParticles.update(dt) Timer.update(dt) end function state:leave() fonts.reset() end function state:keypressed( button ) if button == "UP" then self.option = (self.option - 1) % 5 sound.playSfx( 'click' ) elseif button == "DOWN" then self.option = (self.option + 1) % 5 sound.playSfx( 'click' ) end if button == "START" then Gamestate.switch(self.previous) return end if self.konami[self.konami_idx + 1] == button then self.konami_idx = self.konami_idx + 1 else self.konami_idx = 0 end if self.konami_idx == #self.konami then sound.playSfx( 'reveal' ) Timer.add(1.5,function() Gamestate.switch('cheatscreen', self.previous ) end) return end if button == "ATTACK" or button == "JUMP" then sound.playSfx( 'confirm' ) if self.option == 0 then Gamestate.switch('instructions') elseif self.option == 1 then Gamestate.switch('options') elseif self.option == 2 then Gamestate.switch('overworld') elseif self.option == 3 then self.previous:quit() Gamestate.switch(Gamestate.home) elseif self.option == 4 then love.event.push("quit") end end end function state:draw() VerticalParticles.draw() love.graphics.draw(self.background, camera:getWidth() / 2 - self.background:getWidth() / 2, camera:getHeight() / 2 - self.background:getHeight() / 2) love.graphics.setColor( 0, 0, 0, 255 ) love.graphics.print('Controls', 198, 101) love.graphics.print('Options', 198, 131) love.graphics.print('Quit to Map', 198, 161) love.graphics.print('Quit to Menu', 198, 191) love.graphics.print('Quit to Desktop', 198, 221) love.graphics.setColor( 255, 255, 255, 255 ) love.graphics.draw(self.arrow, 156, 96 + 30 * self.option) local back = controls.getKey("START") .. ": BACK TO GAME" local howto = controls.getKey("ATTACK") .. " OR " .. controls.getKey("JUMP") .. ": SELECT ITEM" love.graphics.print(back, 25, 25) love.graphics.print(howto, 25, 55) end return state
local Gamestate = require 'vendor/gamestate' local window = require 'window' local camera = require 'camera' local fonts = require 'fonts' local sound = require 'vendor/TEsound' local controls = require 'controls' local state = Gamestate.new() local VerticalParticles = require "verticalparticles" local Timer = require 'vendor/timer' function state:init() VerticalParticles.init() self.arrow = love.graphics.newImage("images/menu/arrow.png") self.background = love.graphics.newImage("images/menu/pause.png") end function state:enter(previous) love.graphics.setBackgroundColor(0, 0, 0) sound.playMusic( "daybreak" ) fonts.set( 'big' ) camera:setPosition(0, 0) self.option = 0 if previous ~= Gamestate.get('options') and previous ~= Gamestate.get('instructions') then self.previous = previous end self.konami = { 'UP', 'UP', 'DOWN', 'DOWN', 'LEFT', 'RIGHT', 'LEFT', 'RIGHT', 'JUMP', 'ATTACK' } self.konami_idx = 0 end function state:update(dt) VerticalParticles.update(dt) Timer.update(dt) end function state:leave() fonts.reset() end function state:keypressed( button ) if button == "UP" then self.option = (self.option - 1) % 5 sound.playSfx( 'click' ) elseif button == "DOWN" then self.option = (self.option + 1) % 5 sound.playSfx( 'click' ) end if button == "START" then Gamestate.switch(self.previous) return end if self.konami[self.konami_idx + 1] == button then self.konami_idx = self.konami_idx + 1 if self.konami_idx ~= #self.konami then return end else self.konami_idx = 0 end if self.konami_idx == #self.konami then sound.playSfx( 'reveal' ) Timer.add(1.5,function() Gamestate.switch('cheatscreen', self.previous ) end) return end if button == "ATTACK" or button == "JUMP" then sound.playSfx( 'confirm' ) if self.option == 0 then Gamestate.switch('instructions') elseif self.option == 1 then Gamestate.switch('options') elseif self.option == 2 then Gamestate.switch('overworld') elseif self.option == 3 then self.previous:quit() Gamestate.switch(Gamestate.home) elseif self.option == 4 then love.event.push("quit") end end end function state:draw() VerticalParticles.draw() love.graphics.draw(self.background, camera:getWidth() / 2 - self.background:getWidth() / 2, camera:getHeight() / 2 - self.background:getHeight() / 2) love.graphics.setColor( 0, 0, 0, 255 ) love.graphics.print('Controls', 198, 101) love.graphics.print('Options', 198, 131) love.graphics.print('Quit to Map', 198, 161) love.graphics.print('Quit to Menu', 198, 191) love.graphics.print('Quit to Desktop', 198, 221) love.graphics.setColor( 255, 255, 255, 255 ) love.graphics.draw(self.arrow, 156, 96 + 30 * self.option) local back = controls.getKey("START") .. ": BACK TO GAME" local howto = controls.getKey("ATTACK") .. " OR " .. controls.getKey("JUMP") .. ": SELECT ITEM" love.graphics.print(back, 25, 25) love.graphics.print(howto, 25, 55) end return state
Fixes konami code
Fixes konami code
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
3d2468cf34207d2104a51833b8dafd05f872dfc8
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.on_commit(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd("root", v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end end m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 keys.rmempty = false function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) if value then fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end end return m, m2
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.on_commit(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd("root", v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end end if fs.access("/etc/config/dropbear") then m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 keys.rmempty = false function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) if value then fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end end end return m, m2
modules/admin-full: fix System -> Administration menu if dropbear is not installed
modules/admin-full: fix System -> Administration menu if dropbear is not installed
Lua
apache-2.0
aircross/OpenWrt-Firefly-LuCI,male-puppies/luci,lcf258/openwrtcn,RuiChen1113/luci,urueedi/luci,palmettos/test,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,Sakura-Winkey/LuCI,florian-shellfire/luci,tobiaswaldvogel/luci,oyido/luci,chris5560/openwrt-luci,jlopenwrtluci/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,nmav/luci,joaofvieira/luci,openwrt/luci,ReclaimYourPrivacy/cloak-luci,aa65535/luci,palmettos/cnLuCI,bright-things/ionic-luci,oneru/luci,nwf/openwrt-luci,palmettos/cnLuCI,lcf258/openwrtcn,artynet/luci,Wedmer/luci,chris5560/openwrt-luci,nwf/openwrt-luci,palmettos/test,tcatm/luci,nmav/luci,dismantl/luci-0.12,bright-things/ionic-luci,cshore/luci,jorgifumi/luci,Noltari/luci,hnyman/luci,teslamint/luci,keyidadi/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,oyido/luci,hnyman/luci,ollie27/openwrt_luci,david-xiao/luci,nwf/openwrt-luci,oyido/luci,daofeng2015/luci,jlopenwrtluci/luci,LuttyYang/luci,wongsyrone/luci-1,MinFu/luci,Hostle/luci,nwf/openwrt-luci,Kyklas/luci-proto-hso,openwrt-es/openwrt-luci,deepak78/new-luci,ff94315/luci-1,obsy/luci,Noltari/luci,palmettos/cnLuCI,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,sujeet14108/luci,rogerpueyo/luci,Noltari/luci,artynet/luci,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,Wedmer/luci,artynet/luci,jorgifumi/luci,aa65535/luci,kuoruan/luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,ff94315/luci-1,palmettos/test,tcatm/luci,marcel-sch/luci,taiha/luci,jlopenwrtluci/luci,maxrio/luci981213,mumuqz/luci,fkooman/luci,urueedi/luci,Hostle/luci,sujeet14108/luci,male-puppies/luci,deepak78/new-luci,hnyman/luci,lcf258/openwrtcn,tcatm/luci,kuoruan/luci,schidler/ionic-luci,cshore/luci,maxrio/luci981213,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,obsy/luci,RedSnake64/openwrt-luci-packages,oyido/luci,jchuang1977/luci-1,schidler/ionic-luci,deepak78/new-luci,ollie27/openwrt_luci,oneru/luci,mumuqz/luci,aa65535/luci,remakeelectric/luci,deepak78/new-luci,lbthomsen/openwrt-luci,tcatm/luci,kuoruan/lede-luci,shangjiyu/luci-with-extra,schidler/ionic-luci,cappiewu/luci,thesabbir/luci,harveyhu2012/luci,deepak78/new-luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,sujeet14108/luci,artynet/luci,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,hnyman/luci,sujeet14108/luci,harveyhu2012/luci,daofeng2015/luci,981213/luci-1,NeoRaider/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,palmettos/cnLuCI,zhaoxx063/luci,RuiChen1113/luci,mumuqz/luci,kuoruan/luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,Noltari/luci,RuiChen1113/luci,openwrt/luci,palmettos/cnLuCI,oyido/luci,jchuang1977/luci-1,sujeet14108/luci,mumuqz/luci,Kyklas/luci-proto-hso,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,bittorf/luci,thess/OpenWrt-luci,cshore-firmware/openwrt-luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,MinFu/luci,daofeng2015/luci,palmettos/cnLuCI,nmav/luci,taiha/luci,Sakura-Winkey/LuCI,opentechinstitute/luci,rogerpueyo/luci,marcel-sch/luci,keyidadi/luci,aa65535/luci,jchuang1977/luci-1,obsy/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,florian-shellfire/luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,RuiChen1113/luci,male-puppies/luci,thesabbir/luci,bright-things/ionic-luci,keyidadi/luci,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,taiha/luci,nmav/luci,chris5560/openwrt-luci,taiha/luci,daofeng2015/luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,wongsyrone/luci-1,palmettos/cnLuCI,urueedi/luci,artynet/luci,bright-things/ionic-luci,jlopenwrtluci/luci,hnyman/luci,kuoruan/lede-luci,oneru/luci,Wedmer/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,fkooman/luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,sujeet14108/luci,obsy/luci,lbthomsen/openwrt-luci,dwmw2/luci,ff94315/luci-1,maxrio/luci981213,zhaoxx063/luci,NeoRaider/luci,Sakura-Winkey/LuCI,slayerrensky/luci,MinFu/luci,david-xiao/luci,Noltari/luci,tobiaswaldvogel/luci,obsy/luci,remakeelectric/luci,urueedi/luci,schidler/ionic-luci,palmettos/test,teslamint/luci,taiha/luci,zhaoxx063/luci,obsy/luci,david-xiao/luci,hnyman/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,harveyhu2012/luci,sujeet14108/luci,jlopenwrtluci/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,nwf/openwrt-luci,oyido/luci,cappiewu/luci,981213/luci-1,kuoruan/lede-luci,Hostle/luci,RedSnake64/openwrt-luci-packages,forward619/luci,daofeng2015/luci,Hostle/luci,openwrt/luci,marcel-sch/luci,tcatm/luci,deepak78/new-luci,thess/OpenWrt-luci,cshore/luci,981213/luci-1,maxrio/luci981213,lcf258/openwrtcn,jchuang1977/luci-1,mumuqz/luci,bittorf/luci,jorgifumi/luci,oneru/luci,aa65535/luci,zhaoxx063/luci,zhaoxx063/luci,kuoruan/lede-luci,thess/OpenWrt-luci,remakeelectric/luci,keyidadi/luci,maxrio/luci981213,dwmw2/luci,Hostle/openwrt-luci-multi-user,rogerpueyo/luci,cshore/luci,tcatm/luci,Wedmer/luci,schidler/ionic-luci,NeoRaider/luci,Wedmer/luci,wongsyrone/luci-1,ff94315/luci-1,marcel-sch/luci,rogerpueyo/luci,981213/luci-1,sujeet14108/luci,opentechinstitute/luci,cappiewu/luci,hnyman/luci,kuoruan/lede-luci,NeoRaider/luci,jchuang1977/luci-1,joaofvieira/luci,MinFu/luci,jorgifumi/luci,openwrt-es/openwrt-luci,cappiewu/luci,Kyklas/luci-proto-hso,981213/luci-1,Kyklas/luci-proto-hso,cshore/luci,david-xiao/luci,remakeelectric/luci,aircross/OpenWrt-Firefly-LuCI,wongsyrone/luci-1,palmettos/cnLuCI,kuoruan/luci,obsy/luci,Sakura-Winkey/LuCI,kuoruan/luci,slayerrensky/luci,nmav/luci,teslamint/luci,cappiewu/luci,florian-shellfire/luci,taiha/luci,palmettos/test,male-puppies/luci,oyido/luci,tobiaswaldvogel/luci,bittorf/luci,ff94315/luci-1,marcel-sch/luci,tcatm/luci,Wedmer/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,joaofvieira/luci,tobiaswaldvogel/luci,marcel-sch/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,ReclaimYourPrivacy/cloak-luci,bittorf/luci,ollie27/openwrt_luci,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,bittorf/luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,cshore/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,jorgifumi/luci,openwrt/luci,joaofvieira/luci,oneru/luci,remakeelectric/luci,mumuqz/luci,harveyhu2012/luci,urueedi/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,Noltari/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,fkooman/luci,dwmw2/luci,Hostle/luci,oneru/luci,artynet/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,opentechinstitute/luci,nwf/openwrt-luci,chris5560/openwrt-luci,urueedi/luci,Hostle/luci,keyidadi/luci,thess/OpenWrt-luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,male-puppies/luci,LuttyYang/luci,obsy/luci,dismantl/luci-0.12,oyido/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,NeoRaider/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,deepak78/new-luci,thess/OpenWrt-luci,rogerpueyo/luci,joaofvieira/luci,RedSnake64/openwrt-luci-packages,tcatm/luci,taiha/luci,remakeelectric/luci,openwrt-es/openwrt-luci,thesabbir/luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,ollie27/openwrt_luci,taiha/luci,981213/luci-1,marcel-sch/luci,lcf258/openwrtcn,oneru/luci,LuttyYang/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,kuoruan/lede-luci,dismantl/luci-0.12,openwrt/luci,forward619/luci,jorgifumi/luci,dwmw2/luci,harveyhu2012/luci,bright-things/ionic-luci,daofeng2015/luci,fkooman/luci,opentechinstitute/luci,opentechinstitute/luci,dwmw2/luci,marcel-sch/luci,maxrio/luci981213,deepak78/new-luci,palmettos/test,artynet/luci,RuiChen1113/luci,forward619/luci,Kyklas/luci-proto-hso,rogerpueyo/luci,lcf258/openwrtcn,forward619/luci,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,florian-shellfire/luci,thesabbir/luci,dismantl/luci-0.12,aa65535/luci,teslamint/luci,981213/luci-1,dismantl/luci-0.12,kuoruan/luci,RuiChen1113/luci,bright-things/ionic-luci,artynet/luci,Wedmer/luci,male-puppies/luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,cshore/luci,david-xiao/luci,openwrt/luci,NeoRaider/luci,RuiChen1113/luci,thesabbir/luci,chris5560/openwrt-luci,wongsyrone/luci-1,harveyhu2012/luci,tobiaswaldvogel/luci,thesabbir/luci,mumuqz/luci,remakeelectric/luci,teslamint/luci,slayerrensky/luci,aa65535/luci,slayerrensky/luci,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,MinFu/luci,lbthomsen/openwrt-luci,ff94315/luci-1,palmettos/test,forward619/luci,openwrt/luci,jlopenwrtluci/luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,forward619/luci,keyidadi/luci,keyidadi/luci,cappiewu/luci,bright-things/ionic-luci,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,maxrio/luci981213,openwrt-es/openwrt-luci,Noltari/luci,jlopenwrtluci/luci,jorgifumi/luci,palmettos/test,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,MinFu/luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,florian-shellfire/luci,mumuqz/luci,MinFu/luci,lbthomsen/openwrt-luci,LuttyYang/luci,nmav/luci,male-puppies/luci,nwf/openwrt-luci,nmav/luci,zhaoxx063/luci,maxrio/luci981213,forward619/luci,teslamint/luci,shangjiyu/luci-with-extra,david-xiao/luci,Wedmer/luci,Noltari/luci,cappiewu/luci,schidler/ionic-luci,rogerpueyo/luci,Hostle/luci,opentechinstitute/luci,dwmw2/luci,dwmw2/luci,ollie27/openwrt_luci,slayerrensky/luci,cshore/luci,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,keyidadi/luci,forward619/luci,shangjiyu/luci-with-extra,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/luci,chris5560/openwrt-luci,kuoruan/lede-luci,bright-things/ionic-luci,fkooman/luci,nmav/luci,remakeelectric/luci,LuttyYang/luci,david-xiao/luci,kuoruan/luci,nwf/openwrt-luci,RedSnake64/openwrt-luci-packages,fkooman/luci,schidler/ionic-luci,david-xiao/luci,male-puppies/luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,opentechinstitute/luci,hnyman/luci,ff94315/luci-1,joaofvieira/luci,shangjiyu/luci-with-extra,ff94315/luci-1,ollie27/openwrt_luci,florian-shellfire/luci,openwrt/luci,aa65535/luci,tobiaswaldvogel/luci,thess/OpenWrt-luci,jchuang1977/luci-1,urueedi/luci,ollie27/openwrt_luci,bittorf/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,thesabbir/luci,jorgifumi/luci
e9e22aca73d27410572871ae2870c41b96b11a8a
modules/admin-full/luasrc/model/cbi/admin_system/fstab.lua
modules/admin-full/luasrc/model/cbi/admin_system/fstab.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") local fs = require "luci.fs" local devices = {} luci.util.update(devices, fs.glob("/dev/sd*") or {}) luci.util.update(devices, fs.glob("/dev/hd*") or {}) luci.util.update(devices, fs.glob("/dev/scd*") or {}) luci.util.update(devices, fs.glob("/dev/mmc*") or {}) local size = {} for i, dev in ipairs(devices) do local s = tonumber((luci.fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("a_s_fstab")) local mounts = luci.sys.mounts() v = m:section(Table, mounts, translate("a_s_fstab_active")) fs = v:option(DummyValue, "fs", translate("filesystem")) mp = v:option(DummyValue, "mountpoint", translate("a_s_fstab_mountpoint")) avail = v:option(DummyValue, "avail", translate("a_s_fstab_avail")) function avail.cfgvalue(self, section) return luci.tools.webadmin.byte_format( ( tonumber(mounts[section].available) or 0 ) * 1024 ) .. " / " .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].blocks) or 0 ) * 1024 ) end used = v:option(DummyValue, "used", translate("a_s_fstab_used")) function used.cfgvalue(self, section) return ( mounts[section].percent or "0%" ) .. " (" .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].used) or 0 ) * 1024 ) .. ")" end mount = m:section(TypedSection, "mount", translate("a_s_fstab_mountpoints"), translate("a_s_fstab_mountpoints1")) mount.anonymous = true mount.addremove = true mount.template = "cbi/tblsection" mount:option(Flag, "enabled", translate("enable")) dev = mount:option(Value, "device", translate("device"), translate("a_s_fstab_device1")) for i, d in ipairs(devices) do dev:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end mount:option(Value, "target", translate("a_s_fstab_mountpoint")) mount:option(Value, "fstype", translate("filesystem"), translate("a_s_fstab_fs1")) mount:option(Value, "options", translate("options"), translatef("manpage", "siehe '%s' manpage", "mount")) swap = m:section(TypedSection, "swap", "SWAP", translate("a_s_fstab_swap1")) swap.anonymous = true swap.addremove = true swap.template = "cbi/tblsection" swap:option(Flag, "enabled", translate("enable")) dev = swap:option(Value, "device", translate("device"), translate("a_s_fstab_device1")) for i, d in ipairs(devices) do dev:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") local fs = require "luci.fs" local devices = {} luci.util.update(devices, fs.glob("/dev/sd*") or {}) luci.util.update(devices, fs.glob("/dev/hd*") or {}) luci.util.update(devices, fs.glob("/dev/scd*") or {}) luci.util.update(devices, fs.glob("/dev/mmc*") or {}) local size = {} for i, dev in ipairs(devices) do local s = tonumber((luci.fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("a_s_fstab")) local mounts = luci.sys.mounts() v = m:section(Table, mounts, translate("a_s_fstab_active")) fs = v:option(DummyValue, "fs", translate("filesystem")) mp = v:option(DummyValue, "mountpoint", translate("a_s_fstab_mountpoint")) avail = v:option(DummyValue, "avail", translate("a_s_fstab_avail")) function avail.cfgvalue(self, section) return luci.tools.webadmin.byte_format( ( tonumber(mounts[section].available) or 0 ) * 1024 ) .. " / " .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].blocks) or 0 ) * 1024 ) end used = v:option(DummyValue, "used", translate("a_s_fstab_used")) function used.cfgvalue(self, section) return ( mounts[section].percent or "0%" ) .. " (" .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].used) or 0 ) * 1024 ) .. ")" end mount = m:section(TypedSection, "mount", translate("a_s_fstab_mountpoints"), translate("a_s_fstab_mountpoints1")) mount.anonymous = true mount.addremove = true mount.template = "cbi/tblsection" mount:option(Flag, "enabled", translate("enable")).rmempty = false dev = mount:option(Value, "device", translate("device"), translate("a_s_fstab_device1")) for i, d in ipairs(devices) do dev:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end mount:option(Value, "target", translate("a_s_fstab_mountpoint")) mount:option(Value, "fstype", translate("filesystem"), translate("a_s_fstab_fs1")) mount:option(Value, "options", translate("options"), translatef("manpage", "siehe '%s' manpage", "mount")) swap = m:section(TypedSection, "swap", "SWAP", translate("a_s_fstab_swap1")) swap.anonymous = true swap.addremove = true swap.template = "cbi/tblsection" swap:option(Flag, "enabled", translate("enable")).rmempty = false dev = swap:option(Value, "device", translate("device"), translate("a_s_fstab_device1")) for i, d in ipairs(devices) do dev:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end return m
Fix: Mountpoints cannot be disabled
Fix: Mountpoints cannot be disabled
Lua
apache-2.0
aa65535/luci,zhaoxx063/luci,NeoRaider/luci,remakeelectric/luci,RedSnake64/openwrt-luci-packages,oyido/luci,openwrt/luci,oneru/luci,artynet/luci,harveyhu2012/luci,remakeelectric/luci,ReclaimYourPrivacy/cloak-luci,palmettos/cnLuCI,jorgifumi/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,taiha/luci,ollie27/openwrt_luci,kuoruan/lede-luci,jlopenwrtluci/luci,teslamint/luci,wongsyrone/luci-1,MinFu/luci,marcel-sch/luci,taiha/luci,forward619/luci,marcel-sch/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,keyidadi/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,daofeng2015/luci,hnyman/luci,aa65535/luci,hnyman/luci,cshore/luci,Noltari/luci,aa65535/luci,florian-shellfire/luci,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,daofeng2015/luci,kuoruan/lede-luci,bright-things/ionic-luci,thess/OpenWrt-luci,sujeet14108/luci,db260179/openwrt-bpi-r1-luci,palmettos/test,Hostle/luci,cappiewu/luci,tcatm/luci,cshore-firmware/openwrt-luci,palmettos/test,bright-things/ionic-luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,fkooman/luci,MinFu/luci,ff94315/luci-1,lcf258/openwrtcn,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,Noltari/luci,slayerrensky/luci,thesabbir/luci,david-xiao/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,RuiChen1113/luci,ollie27/openwrt_luci,david-xiao/luci,lcf258/openwrtcn,bittorf/luci,teslamint/luci,marcel-sch/luci,thesabbir/luci,tcatm/luci,david-xiao/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,LuttyYang/luci,chris5560/openwrt-luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,Hostle/openwrt-luci-multi-user,marcel-sch/luci,palmettos/cnLuCI,RuiChen1113/luci,slayerrensky/luci,urueedi/luci,shangjiyu/luci-with-extra,dwmw2/luci,cshore-firmware/openwrt-luci,oneru/luci,male-puppies/luci,florian-shellfire/luci,nwf/openwrt-luci,schidler/ionic-luci,thesabbir/luci,ff94315/luci-1,Sakura-Winkey/LuCI,remakeelectric/luci,dismantl/luci-0.12,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,taiha/luci,joaofvieira/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,joaofvieira/luci,MinFu/luci,openwrt-es/openwrt-luci,jorgifumi/luci,rogerpueyo/luci,joaofvieira/luci,cshore-firmware/openwrt-luci,Hostle/luci,bright-things/ionic-luci,male-puppies/luci,bittorf/luci,lbthomsen/openwrt-luci,artynet/luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,sujeet14108/luci,cshore-firmware/openwrt-luci,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,shangjiyu/luci-with-extra,oneru/luci,jorgifumi/luci,forward619/luci,Sakura-Winkey/LuCI,palmettos/test,chris5560/openwrt-luci,Sakura-Winkey/LuCI,daofeng2015/luci,forward619/luci,mumuqz/luci,opentechinstitute/luci,male-puppies/luci,cshore-firmware/openwrt-luci,joaofvieira/luci,nwf/openwrt-luci,lcf258/openwrtcn,openwrt/luci,lbthomsen/openwrt-luci,hnyman/luci,lcf258/openwrtcn,jlopenwrtluci/luci,marcel-sch/luci,cshore-firmware/openwrt-luci,Hostle/luci,wongsyrone/luci-1,jorgifumi/luci,NeoRaider/luci,slayerrensky/luci,LuttyYang/luci,maxrio/luci981213,cshore/luci,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,hnyman/luci,deepak78/new-luci,Sakura-Winkey/LuCI,Wedmer/luci,tcatm/luci,Noltari/luci,kuoruan/luci,sujeet14108/luci,981213/luci-1,david-xiao/luci,openwrt-es/openwrt-luci,obsy/luci,oyido/luci,obsy/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,wongsyrone/luci-1,NeoRaider/luci,nmav/luci,ollie27/openwrt_luci,Noltari/luci,fkooman/luci,jchuang1977/luci-1,oneru/luci,palmettos/cnLuCI,slayerrensky/luci,cappiewu/luci,dismantl/luci-0.12,bittorf/luci,lcf258/openwrtcn,cappiewu/luci,keyidadi/luci,Kyklas/luci-proto-hso,cshore/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,kuoruan/lede-luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,dwmw2/luci,shangjiyu/luci-with-extra,kuoruan/luci,bright-things/ionic-luci,keyidadi/luci,bright-things/ionic-luci,rogerpueyo/luci,forward619/luci,male-puppies/luci,mumuqz/luci,zhaoxx063/luci,LuttyYang/luci,ollie27/openwrt_luci,florian-shellfire/luci,florian-shellfire/luci,Wedmer/luci,maxrio/luci981213,opentechinstitute/luci,ollie27/openwrt_luci,deepak78/new-luci,chris5560/openwrt-luci,ff94315/luci-1,981213/luci-1,keyidadi/luci,kuoruan/lede-luci,cappiewu/luci,jchuang1977/luci-1,bittorf/luci,aa65535/luci,openwrt-es/openwrt-luci,artynet/luci,daofeng2015/luci,teslamint/luci,urueedi/luci,Hostle/openwrt-luci-multi-user,artynet/luci,harveyhu2012/luci,oyido/luci,male-puppies/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,palmettos/test,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,remakeelectric/luci,jlopenwrtluci/luci,oyido/luci,nmav/luci,forward619/luci,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,MinFu/luci,mumuqz/luci,daofeng2015/luci,981213/luci-1,hnyman/luci,zhaoxx063/luci,LuttyYang/luci,LuttyYang/luci,slayerrensky/luci,Noltari/luci,dwmw2/luci,cappiewu/luci,florian-shellfire/luci,Noltari/luci,chris5560/openwrt-luci,harveyhu2012/luci,shangjiyu/luci-with-extra,maxrio/luci981213,hnyman/luci,tobiaswaldvogel/luci,thesabbir/luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,artynet/luci,Wedmer/luci,palmettos/cnLuCI,openwrt/luci,chris5560/openwrt-luci,mumuqz/luci,daofeng2015/luci,jlopenwrtluci/luci,chris5560/openwrt-luci,bittorf/luci,wongsyrone/luci-1,taiha/luci,nwf/openwrt-luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,slayerrensky/luci,tcatm/luci,harveyhu2012/luci,obsy/luci,mumuqz/luci,daofeng2015/luci,Kyklas/luci-proto-hso,openwrt/luci,LuttyYang/luci,981213/luci-1,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,urueedi/luci,artynet/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,Kyklas/luci-proto-hso,kuoruan/luci,florian-shellfire/luci,mumuqz/luci,urueedi/luci,keyidadi/luci,palmettos/test,palmettos/test,bittorf/luci,urueedi/luci,sujeet14108/luci,schidler/ionic-luci,dismantl/luci-0.12,thesabbir/luci,981213/luci-1,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,jchuang1977/luci-1,openwrt/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,LuttyYang/luci,RuiChen1113/luci,jorgifumi/luci,fkooman/luci,deepak78/new-luci,urueedi/luci,981213/luci-1,obsy/luci,rogerpueyo/luci,oneru/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,thess/OpenWrt-luci,lcf258/openwrtcn,MinFu/luci,lcf258/openwrtcn,bittorf/luci,nmav/luci,kuoruan/lede-luci,jchuang1977/luci-1,wongsyrone/luci-1,david-xiao/luci,rogerpueyo/luci,RuiChen1113/luci,ollie27/openwrt_luci,joaofvieira/luci,remakeelectric/luci,wongsyrone/luci-1,florian-shellfire/luci,harveyhu2012/luci,oyido/luci,oyido/luci,nmav/luci,nmav/luci,fkooman/luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,bright-things/ionic-luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,tobiaswaldvogel/luci,ff94315/luci-1,deepak78/new-luci,forward619/luci,sujeet14108/luci,tobiaswaldvogel/luci,Hostle/luci,keyidadi/luci,schidler/ionic-luci,obsy/luci,david-xiao/luci,nwf/openwrt-luci,oyido/luci,oyido/luci,dwmw2/luci,teslamint/luci,ff94315/luci-1,joaofvieira/luci,opentechinstitute/luci,aa65535/luci,openwrt-es/openwrt-luci,kuoruan/luci,Wedmer/luci,dwmw2/luci,slayerrensky/luci,jchuang1977/luci-1,florian-shellfire/luci,teslamint/luci,palmettos/test,Wedmer/luci,marcel-sch/luci,harveyhu2012/luci,nwf/openwrt-luci,daofeng2015/luci,kuoruan/luci,artynet/luci,cshore/luci,nwf/openwrt-luci,zhaoxx063/luci,Hostle/luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,Wedmer/luci,thesabbir/luci,RuiChen1113/luci,remakeelectric/luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,zhaoxx063/luci,jlopenwrtluci/luci,deepak78/new-luci,forward619/luci,jorgifumi/luci,hnyman/luci,tobiaswaldvogel/luci,ff94315/luci-1,rogerpueyo/luci,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,Hostle/openwrt-luci-multi-user,Noltari/luci,hnyman/luci,shangjiyu/luci-with-extra,tcatm/luci,taiha/luci,Hostle/luci,male-puppies/luci,obsy/luci,obsy/luci,urueedi/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,artynet/luci,RuiChen1113/luci,cappiewu/luci,jchuang1977/luci-1,opentechinstitute/luci,ff94315/luci-1,zhaoxx063/luci,oneru/luci,NeoRaider/luci,lbthomsen/openwrt-luci,cshore/luci,nmav/luci,openwrt/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,wongsyrone/luci-1,cshore/luci,rogerpueyo/luci,RuiChen1113/luci,remakeelectric/luci,harveyhu2012/luci,thess/OpenWrt-luci,thesabbir/luci,Sakura-Winkey/LuCI,mumuqz/luci,lcf258/openwrtcn,Wedmer/luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,MinFu/luci,fkooman/luci,cshore-firmware/openwrt-luci,male-puppies/luci,kuoruan/luci,palmettos/cnLuCI,RedSnake64/openwrt-luci-packages,david-xiao/luci,mumuqz/luci,aa65535/luci,fkooman/luci,MinFu/luci,chris5560/openwrt-luci,wongsyrone/luci-1,opentechinstitute/luci,oneru/luci,bittorf/luci,jchuang1977/luci-1,sujeet14108/luci,taiha/luci,deepak78/new-luci,aa65535/luci,urueedi/luci,cshore/luci,Wedmer/luci,dwmw2/luci,palmettos/cnLuCI,cshore/luci,dwmw2/luci,dwmw2/luci,Hostle/luci,thess/OpenWrt-luci,chris5560/openwrt-luci,oneru/luci,teslamint/luci,NeoRaider/luci,dismantl/luci-0.12,lbthomsen/openwrt-luci,RuiChen1113/luci,schidler/ionic-luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,teslamint/luci,jorgifumi/luci,openwrt/luci,thesabbir/luci,teslamint/luci,keyidadi/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,marcel-sch/luci,joaofvieira/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,sujeet14108/luci,Sakura-Winkey/LuCI,nwf/openwrt-luci,Kyklas/luci-proto-hso,artynet/luci,nmav/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,deepak78/new-luci,zhaoxx063/luci,tcatm/luci,thess/OpenWrt-luci,Kyklas/luci-proto-hso,maxrio/luci981213,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,deepak78/new-luci,RedSnake64/openwrt-luci-packages,NeoRaider/luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,sujeet14108/luci,taiha/luci,MinFu/luci,openwrt-es/openwrt-luci,maxrio/luci981213,Kyklas/luci-proto-hso,joaofvieira/luci,david-xiao/luci,Kyklas/luci-proto-hso,kuoruan/lede-luci,male-puppies/luci,remakeelectric/luci,dismantl/luci-0.12,palmettos/cnLuCI,jlopenwrtluci/luci,dismantl/luci-0.12,rogerpueyo/luci,981213/luci-1,jchuang1977/luci-1,keyidadi/luci,nmav/luci,shangjiyu/luci-with-extra,kuoruan/luci,Hostle/openwrt-luci-multi-user,forward619/luci,taiha/luci,dismantl/luci-0.12,schidler/ionic-luci
237ee90bce3b6f65db57f94132f9902795b832e8
plugins/stats.lua
plugins/stats.lua
-- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = { } local uhash = 'user:' .. user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:' .. user_id .. ':' .. chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user) .. ' [' .. user_id .. ']' return user_info end --[[ local function chat_stats(receiver, chat_id) -- Users on chat local hash = 'chat:' .. chat_id .. ':users' local users = redis:smembers(hash) local users_info = { } -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end ) local text = lang_text('usersInChat') for k, user in pairs(users_info) do text = text .. user.name .. ' = ' .. user.msgs .. '\n' end local file = io.open("./groups/lists/" .. chat_id .. "stats.txt", "w") file:write(text) file:flush() file:close() send_document(receiver, "./groups/lists/" .. chat_id .. "stats.txt", ok_cb, false) return -- text end]] local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:' .. chat_id .. ':users' local users = redis:smembers(hash) local users_info = { } -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end ) local text = lang_text('usersInChat') for k, user in pairs(users_info) do text = text .. user.name .. ' = ' .. user.msgs .. '\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:' .. our_id local r = redis:eval(redis_scan, 1, hash) local text = lang_text('users') .. r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text .. lang_text('groups') .. r return text end local function run(msg, matches) if matches[1]:lower() == 'aisasha' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name .. " [" .. msg.from.id .. "] used /aisasha ") return about end --[[ file if matches[1]:lower() == "statslist" then if not is_momod(msg) then return lang_text('require_mod') end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name .. " [" .. msg.from.id .. "] requested group stats ") return chat_stats2(chat_id) end]] -- message if matches[1]:lower() == "stats" or matches[1]:lower() == "statslist" or matches[1]:lower() == "messages" or matches[1]:lower() == "sasha statistiche" or matches[1]:lower() == "sasha lista statistiche" or matches[1]:lower() == "sasha messaggi" then if not matches[2] then if not is_momod(msg) then return lang_text('require_mod') end if msg.to.type == 'chat' or msg.to.type == 'channel' then local receiver = get_receiver(msg) local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name .. " [" .. msg.from.id .. "] requested group stats ") return chat_stats(receiver, chat_id) else return end end if matches[2]:lower() == "aisasha" and matches[1]:lower() ~= "messages" and matches[1]:lower() ~= "sasha messaggi" then -- Put everything you like :) if not is_admin1(msg) then return lang_text('require_admin') else return bot_stats() end end if matches[2]:lower() == "group" or matches[2]:lower() == "gruppo" then if not is_admin1(msg) then return lang_text('require_admin') else return chat_stats(matches[3]) end end end end return { description = "STATS", usage = { "#(stats|statslist|messages)|sasha statistiche|sasha lista statistiche|sasha messaggi: Sasha invia le statistiche della chat.", "(#(stats|statslist|messages)|sasha statistiche|sasha lista statistiche|sasha messaggi) group|gruppo <group_id>: Sasha invia le statistiche relative al gruppo specificato.", "(#(stats|statslist)|sasha statistiche|sasha lista statistiche) aisasha: Sasha invia le proprie statistiche.", "[#]aisasha: Sasha invia la propria descrizione.", }, patterns = { "^[#!/]([sS][tT][aA][tT][sS])$", "^[#!/]([sS][tT][aA][tT][sS][lL][iI][sS][tT])$", "^[#!/]([sS][tT][aA][tT][sS]) ([gG][rR][oO][uU][pP]) (%d+)", "^[#!/]([sS][tT][aA][tT][sS]) ([aA][iI][sS][aA][sS][hH][aA])",-- Put everything you like :) "^[#!/]?([aA][iI][sS][aA][sS][hH][aA])",-- Put everything you like :) -- stats "^([sS][aA][sS][hH][aA] [sS][tT][aA][tT][iI][sS][tT][iI][cC][hH][eE])$", "^([sS][aA][sS][hH][aA] [lL][iI][sS][tT][aA] [sS][tT][aA][tT][iI][sS][tT][iI][cC][hH][eE])$", "^([sS][aA][sS][hH][aA] [sS][tT][aA][tT][iI][sS][tT][iI][cC][hH][eE]) ([gG][rR][uU][pP][pP][oO]) (%d+)", "^([sS][aA][sS][hH][aA] [sS][tT][aA][tT][iI][sS][tT][iI][cC][hH][eE]) ([aA][iI][sS][aA][sS][hH][aA])",-- Put everything you like :) -- messages "^[#!/]([mM][eE][sS][sS][aA][gG][eE][sS])$", "^([sS][aA][sS][hH][aA] [mM][eE][sS][sS][aA][gG][gG][iI])$", }, run = run, min_rank = 0 }
-- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = { } local uhash = 'user:' .. user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:' .. user_id .. ':' .. chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user) .. ' [' .. user_id .. ']' return user_info end --[[ local function chat_stats(receiver, chat_id) -- Users on chat local hash = 'chat:' .. chat_id .. ':users' local users = redis:smembers(hash) local users_info = { } -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end ) local text = lang_text('usersInChat') for k, user in pairs(users_info) do text = text .. user.name .. ' = ' .. user.msgs .. '\n' end local file = io.open("./groups/lists/" .. chat_id .. "stats.txt", "w") file:write(text) file:flush() file:close() send_document(receiver, "./groups/lists/" .. chat_id .. "stats.txt", ok_cb, false) return -- text end]] local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:' .. chat_id .. ':users' local users = redis:smembers(hash) local users_info = { } -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end ) local text = lang_text('usersInChat') for k, user in pairs(users_info) do text = text .. user.name .. ' = ' .. user.msgs .. '\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:' .. our_id local r = redis:eval(redis_scan, 1, hash) local text = lang_text('users') .. r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text .. lang_text('groups') .. r return text end local function run(msg, matches) if matches[1]:lower() == 'aisasha' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name .. " [" .. msg.from.id .. "] used /aisasha ") return about end --[[ file if matches[1]:lower() == "statslist" then if not is_momod(msg) then return lang_text('require_mod') end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name .. " [" .. msg.from.id .. "] requested group stats ") return chat_stats2(chat_id) end]] -- message if matches[1]:lower() == "stats" or matches[1]:lower() == "statslist" or matches[1]:lower() == "messages" or matches[1]:lower() == "sasha statistiche" or matches[1]:lower() == "sasha lista statistiche" or matches[1]:lower() == "sasha messaggi" then if not matches[2] then if not is_momod(msg) then return lang_text('require_mod') end if msg.to.type == 'chat' or msg.to.type == 'channel' then local receiver = get_receiver(msg) local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name .. " [" .. msg.from.id .. "] requested group stats ") return chat_stats(receiver, chat_id) else return end end if matches[2]:lower() == "aisasha" and matches[1]:lower() ~= "messages" and matches[1]:lower() ~= "sasha messaggi" then -- Put everything you like :) if not is_admin1(msg) then return lang_text('require_admin') else return bot_stats() end end if matches[2]:lower() == "group" or matches[2]:lower() == "gruppo" then if not is_admin1(msg) then return lang_text('require_admin') else return chat_stats(matches[3]) end end end end return { description = "STATS", usage = { "#(stats|statslist|messages)|sasha statistiche|sasha lista statistiche|sasha messaggi: Sasha invia le statistiche della chat.", "(#(stats|statslist|messages)|sasha statistiche|sasha lista statistiche|sasha messaggi) group|gruppo <group_id>: Sasha invia le statistiche relative al gruppo specificato.", "(#(stats|statslist)|sasha statistiche|sasha lista statistiche) aisasha: Sasha invia le proprie statistiche.", "[#]aisasha: Sasha invia la propria descrizione.", }, patterns = { "^[#!/]([sS][tT][aA][tT][sS])$", "^[#!/]([sS][tT][aA][tT][sS][lL][iI][sS][tT])$", "^[#!/]([sS][tT][aA][tT][sS]) ([gG][rR][oO][uU][pP]) (%d+)$", "^[#!/]([sS][tT][aA][tT][sS]) ([aA][iI][sS][aA][sS][hH][aA])$",-- Put everything you like :) "^[#!/]?([aA][iI][sS][aA][sS][hH][aA])$",-- Put everything you like :) -- stats "^([sS][aA][sS][hH][aA] [sS][tT][aA][tT][iI][sS][tT][iI][cC][hH][eE])$", "^([sS][aA][sS][hH][aA] [lL][iI][sS][tT][aA] [sS][tT][aA][tT][iI][sS][tT][iI][cC][hH][eE])$", "^([sS][aA][sS][hH][aA] [sS][tT][aA][tT][iI][sS][tT][iI][cC][hH][eE]) ([gG][rR][uU][pP][pP][oO]) (%d+)$", "^([sS][aA][sS][hH][aA] [sS][tT][aA][tT][iI][sS][tT][iI][cC][hH][eE]) ([aA][iI][sS][aA][sS][hH][aA])$",-- Put everything you like :) -- messages "^[#!/]([mM][eE][sS][sS][aA][gG][eE][sS])$", "^([sS][aA][sS][hH][aA] [mM][eE][sS][sS][aA][gG][gG][iI])$", }, run = run, min_rank = 0 }
patterns fix
patterns fix
Lua
agpl-3.0
xsolinsx/AISasha
1c46f36afe7f57e029f3d92bb6e7a7fafe937b70
lua/entities/gmod_wire_detonator.lua
lua/entities/gmod_wire_detonator.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Detonator" ENT.WireDebugName = "Detonator" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs( self, { "Trigger" } ) self.Trigger = 0 self.damage = 0 end function ENT:TriggerInput(iname, value) if iname == "Trigger" then self:ShowOutput( value ) end end function ENT:Setup(damage) self.damage = damage self:ShowOutput( 0 ) end function ENT:ShowOutput( Trigger ) if Trigger ~= self.Trigger then self:SetOverlayText( self.damage .. " = " .. Trigger ) self.Trigger = Trigger if Trigger > 0 then self:DoDamage() end end end function ENT:DoDamage() if self.target and self.target:IsValid() and self.target:Health() > 0 then if self.target:Health() <= self.damage then self.target:SetHealth(0) self.target:Fire( "break", "", 0 ) self.target:Fire( "kill", "", 0.2 ) else self.target:SetHealth( self.target:Health() - self.damage ) end end local effectdata = EffectData() effectdata:SetOrigin( self:GetPos() ) util.Effect( "Explosion", effectdata, true, true ) self:Remove() end -- Dupe info functions added by TheApathetic function ENT:BuildDupeInfo() local info = BaseClass.BuildDupeInfo(self) or {} if self.target and self.target:IsValid() then info.target = self.target:EntIndex() end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.target = GetEntByID(info.target) end duplicator.RegisterEntityClass("gmod_wire_detonator", WireLib.MakeWireEnt, "Data", "damage")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Detonator" ENT.WireDebugName = "Detonator" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs( self, { "Trigger" } ) self.Trigger = 0 self.damage = 0 end function ENT:TriggerInput(iname, value) if iname == "Trigger" then self:ShowOutput( value ) end end function ENT:Setup(damage) self.damage = damage self:ShowOutput( 0 ) end function ENT:ShowOutput( Trigger ) if Trigger ~= self.Trigger then self:SetOverlayText( self.damage .. " = " .. Trigger ) self.Trigger = Trigger if Trigger > 0 then self:DoDamage() end end end function ENT:DoDamage() if self.target and self.target:IsValid() then self.target:TakeDamage(self.damage, self:GetPlayer(), self) end local effectdata = EffectData() effectdata:SetOrigin( self:GetPos() ) util.Effect( "Explosion", effectdata, true, true ) self:Remove() end -- Dupe info functions added by TheApathetic function ENT:BuildDupeInfo() local info = BaseClass.BuildDupeInfo(self) or {} if self.target and self.target:IsValid() then info.target = self.target:EntIndex() end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.target = GetEntByID(info.target) end duplicator.RegisterEntityClass("gmod_wire_detonator", WireLib.MakeWireEnt, "Data", "damage")
Fix bootleg detonator damaging method (#2371)
Fix bootleg detonator damaging method (#2371) * fix bootleg detonator damage method * DMG_GENERIC for detonator * shorter damage call
Lua
apache-2.0
wiremod/wire,dvdvideo1234/wire,Grocel/wire
64f237db0f4c05d80d0fb6d3fd8471014c035fad
build/Helpers.lua
build/Helpers.lua
-- This module checks for the all the project dependencies. require('vstudio') require('premake/premake.fixes') require('premake/premake.extensions') newoption { trigger = "arch", description = "Choose a particular architecture / bitness", default = "x64", allowed = { { "x86", "x86 32-bits" }, { "x64", "x64 64-bits" }, } } newoption { trigger = "no-cxx11-abi", description = "disable C++-11 ABI on GCC 4.9+" } newoption { trigger = "disable-tests", description = "disable tests from being included" } newoption { trigger = "disable-examples", description = "disable examples from being included" } newoption { trigger = "configuration", description = "Choose a configuration", default = "Release", allowed = { { "Release", "Release" }, { "Debug", "Debug" }, } } rootdir = path.getabsolute("../") srcdir = path.join(rootdir, "src"); incdir = path.join(rootdir, "include"); examplesdir = path.join(rootdir, "examples"); testsdir = path.join(rootdir, "tests"); builddir = path.join(rootdir, "build") bindir = path.join(rootdir, "bin") objsdir = path.join(builddir, "obj"); gendir = path.join(builddir, "gen"); actionbuilddir = path.join(builddir, _ACTION == "gmake2" and "gmake" or (_ACTION and _ACTION or "")); bindircfg = path.join(bindir, "%{cfg.buildcfg}_%{cfg.platform}"); prjobjdir = path.join(objsdir, "%{prj.name}", "%{cfg.buildcfg}") msvc_buildflags = { "/MP", "/wd4267" } msvc_cpp_defines = { } default_gcc_version = "9.0.0" generate_build_config = true premake.path = premake.path .. ";" .. path.join(builddir, "modules") function string.starts(str, start) if str == nil then return end return string.sub(str, 1, string.len(start)) == start end function SafePath(path) return "\"" .. path .. "\"" end function target_architecture() return _OPTIONS["arch"] end function SetupNativeProject() location (path.join(actionbuilddir, "projects")) files { "*.lua" } filter { "configurations:Debug" } defines { "DEBUG" } filter { "configurations:Release" } defines { "NDEBUG" } optimize "On" -- Compiler-specific options filter { "toolset:msc*" } buildoptions { msvc_buildflags } defines { msvc_cpp_defines } filter { "system:linux" } buildoptions { gcc_buildflags } links { "stdc++" } filter { "toolset:clang", "system:not macosx" } linkoptions { "-fuse-ld=/usr/bin/ld.lld" } filter { "toolset:clang" } buildoptions { "-fstandalone-debug" } filter { "toolset:clang", "language:C++", "system:macosx" } buildoptions { gcc_buildflags, "-stdlib=libc++" } links { "c++" } filter { "toolset:not msc*", "language:C++" } cppdialect "C++14" buildoptions { "-fpermissive" } -- OS-specific options filter { "system:windows" } defines { "WIN32", "_WINDOWS" } -- For context: https://github.com/premake/premake-core/issues/935 filter {"system:windows", "toolset:msc*"} systemversion("latest") filter {} end function SetupManagedProject() language "C#" location "." filter {} end function IncludeDir(dir) local deps = os.matchdirs(dir .. "/*") for i,dep in ipairs(deps) do local fp = path.join(dep, "premake5.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then include(dep) return end fp = path.join(dep, "premake4.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then --print(string.format(" including %s", dep)) include(dep) end end end function StaticLinksOpt(libnames) local path = table.concat(cc.configset.libdirs, ";") local formats if os.is("windows") then formats = { "%s.lib" } else formats = { "lib%s.a" } end table.insert(formats, "%s"); local existing_libnames = {} for _, libname in ipairs(libnames) do for _, fmt in ipairs(formats) do local name = string.format(fmt, libname) if os.pathsearch(name, path) then table.insert(existing_libnames, libname) end end end links(existing_libnames) end function UseClang() local cc = _OPTIONS.cc or "" local env = os.getenv("CXX") or "" return string.match(cc, "clang") or string.match(env, "clang") end function GccVersion() local compiler = os.getenv("CXX") if compiler == nil then compiler = "gcc" end local out = os.outputof(compiler.." -v") if out == nil then return default_gcc_version end local version = string.match(out, "gcc version [0-9\\.]+") if version == nil then version = string.match(out, "clang version [0-9\\.]+") end return string.sub(version, 13) end function UseCxx11ABI() if os.istarget("linux") and GccVersion() >= '4.9.0' and _OPTIONS["no-cxx11-abi"] == nil then return true end return false end function EnableNativeProjects() return not (string.starts(_ACTION, "vs") and not os.ishost("windows")) end function EnabledManagedProjects() return string.starts(_ACTION, "vs") end function EnabledCLIProjects() return EnabledManagedProjects() and os.istarget("windows") end function AddPlatformSpecificFiles(folder, filename) if os.istarget("windows") then filter { "toolset:msc*", "architecture:x86_64" } files { path.join(folder, "x86_64-pc-win32-msvc", filename) } filter { "toolset:msc*", "architecture:x86" } files { path.join(folder, "i686-pc-win32-msvc", filename) } elseif os.istarget("macosx") then filter { "architecture:x86_64" } files { path.join(folder, "x86_64-apple-darwin12.4.0", filename) } filter {"architecture:x86" } files { path.join(folder, "i686-apple-darwin12.4.0", filename) } elseif os.istarget("linux") then filter { "architecture:x86_64" } files { path.join(folder, "x86_64-linux-gnu" .. (UseCxx11ABI() and "-cxx11abi" or ""), filename) } else print "Unknown architecture" end end
-- This module checks for the all the project dependencies. require('vstudio') require('premake/premake.fixes') require('premake/premake.extensions') newoption { trigger = "arch", description = "Choose a particular architecture / bitness", default = "x64", allowed = { { "x86", "x86 32-bits" }, { "x64", "x64 64-bits" }, } } newoption { trigger = "no-cxx11-abi", description = "disable C++-11 ABI on GCC 4.9+" } newoption { trigger = "disable-tests", description = "disable tests from being included" } newoption { trigger = "disable-examples", description = "disable examples from being included" } newoption { trigger = "configuration", description = "Choose a configuration", default = "Release", allowed = { { "Release", "Release" }, { "Debug", "Debug" }, } } rootdir = path.getabsolute("../") srcdir = path.join(rootdir, "src"); incdir = path.join(rootdir, "include"); examplesdir = path.join(rootdir, "examples"); testsdir = path.join(rootdir, "tests"); builddir = path.join(rootdir, "build") bindir = path.join(rootdir, "bin") objsdir = path.join(builddir, "obj"); gendir = path.join(builddir, "gen"); actionbuilddir = path.join(builddir, _ACTION == "gmake2" and "gmake" or (_ACTION and _ACTION or "")); bindircfg = path.join(bindir, "%{cfg.buildcfg}_%{cfg.platform}"); prjobjdir = path.join(objsdir, "%{prj.name}", "%{cfg.buildcfg}") msvc_buildflags = { "/MP", "/wd4267" } msvc_cpp_defines = { } default_gcc_version = "9.0.0" generate_build_config = true premake.path = premake.path .. ";" .. path.join(builddir, "modules") function string.starts(str, start) if str == nil then return end return string.sub(str, 1, string.len(start)) == start end function SafePath(path) return "\"" .. path .. "\"" end function target_architecture() return _OPTIONS["arch"] end function SetupNativeProject() location (path.join(actionbuilddir, "projects")) files { "*.lua" } filter { "configurations:Debug" } defines { "DEBUG" } filter { "configurations:Release" } defines { "NDEBUG" } optimize "On" -- Compiler-specific options filter { "toolset:msc*" } buildoptions { msvc_buildflags } defines { msvc_cpp_defines } filter { "system:linux" } buildoptions { gcc_buildflags } links { "stdc++" } filter { "toolset:clang", "system:not macosx" } linkoptions { "-fuse-ld=/usr/bin/ld.lld" } filter { "toolset:clang" } buildoptions { "-fstandalone-debug" } filter { "toolset:clang", "language:C++", "system:macosx" } buildoptions { gcc_buildflags, "-stdlib=libc++" } links { "c++" } filter { "toolset:not msc*", "language:C++" } cppdialect "C++14" buildoptions { "-fpermissive" } -- OS-specific options filter { "system:windows" } defines { "WIN32", "_WINDOWS" } -- For context: https://github.com/premake/premake-core/issues/935 filter {"system:windows", "toolset:msc*"} systemversion("latest") filter {} end function SetupManagedProject() language "C#" location "." filter {} end function IncludeDir(dir) local deps = os.matchdirs(dir .. "/*") for i,dep in ipairs(deps) do local fp = path.join(dep, "premake5.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then include(dep) return end fp = path.join(dep, "premake4.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then --print(string.format(" including %s", dep)) include(dep) end end end function StaticLinksOpt(libnames) local path = table.concat(cc.configset.libdirs, ";") local formats if os.is("windows") then formats = { "%s.lib" } else formats = { "lib%s.a" } end table.insert(formats, "%s"); local existing_libnames = {} for _, libname in ipairs(libnames) do for _, fmt in ipairs(formats) do local name = string.format(fmt, libname) if os.pathsearch(name, path) then table.insert(existing_libnames, libname) end end end links(existing_libnames) end function UseClang() local cc = _OPTIONS.cc or "" local env = os.getenv("CXX") or "" return string.match(cc, "clang") or string.match(env, "clang") end function GccVersion() local compiler = os.getenv("CXX") if compiler == nil then compiler = "gcc" end local out = os.outputof(compiler.." -v") if out == nil then return default_gcc_version end local version = string.match(out, "gcc[ -][Vv]ersion [0-9\\.]+") if version ~= nil then return string.sub(version, 13) end version = string.match(out, "clang[ -][Vv]ersion [0-9\\.]+") return string.sub(version, 15) end function UseCxx11ABI() if os.istarget("linux") and GccVersion() >= '4.9.0' and _OPTIONS["no-cxx11-abi"] == nil then return true end return false end function EnableNativeProjects() return not (string.starts(_ACTION, "vs") and not os.ishost("windows")) end function EnabledManagedProjects() return string.starts(_ACTION, "vs") end function EnabledCLIProjects() return EnabledManagedProjects() and os.istarget("windows") end function AddPlatformSpecificFiles(folder, filename) if os.istarget("windows") then filter { "toolset:msc*", "architecture:x86_64" } files { path.join(folder, "x86_64-pc-win32-msvc", filename) } filter { "toolset:msc*", "architecture:x86" } files { path.join(folder, "i686-pc-win32-msvc", filename) } elseif os.istarget("macosx") then filter { "architecture:x86_64" } files { path.join(folder, "x86_64-apple-darwin12.4.0", filename) } filter {"architecture:x86" } files { path.join(folder, "i686-apple-darwin12.4.0", filename) } elseif os.istarget("linux") then filter { "architecture:x86_64" } files { path.join(folder, "x86_64-linux-gnu" .. (UseCxx11ABI() and "-cxx11abi" or ""), filename) } else print "Unknown architecture" end end
Fix GCC version detection
Fix GCC version detection
Lua
mit
mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp
fa787dbae4078158ea6eb8379ccd953df90d867f
src/sailor/access.lua
src/sailor/access.lua
-------------------------------------------------------------------------------- -- access.lua, v0.2.5: controls access of sailor apps -- This file is a part of Sailor project -- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net> -- License: MIT -- http://sailorproject.org -------------------------------------------------------------------------------- local session = require "sailor.session" local access = {} session.open(sailor.r) -- Uncomment to login with "demo" / "demo" -- Comment to login through db (user model) --access.default = "demo" --access.default_pass = "demo" --access.salt = "sailorisawesome" -- set to nil to use unhashed passwords local INVALID = "Invalid username or password." -- Simple hashing algorithm for encrypting passworsd function access.hash(username, password, salt) salt = salt or access.salt local hash = username .. password -- Check if bcrypt is embedded if sailor.conf.bcrypt and salt and sailor.r.htpassword then hash = sailor.r:htpassword(salt .. hash, 2, 100) -- Use bcrypt on pwd return hash -- If not, fall back to sha1 hashing else if salt and sailor.r.sha1 then for i = 1, 500 do hash = sailor.r:sha1(salt .. hash) end end end return hash end function access.is_guest() access.data = session.data return not access.data.username end function access.grant(data,time) session.setsessiontimeout (time or 604800) -- 1 week if not data.username then return false end access.data = data return session.save(data) end function access.login(username,password) local id if not access.default then local User = sailor.model("user") local u = User:find_by_attributes{ username=username } if not u then return false, INVALID end if u.password ~= access.hash(username, password, u.salt) then return false, INVALID end id = u.id else if username ~= access.default or password ~= access.default_pass then return false, INVALID end id = 1 end return access.grant({username=username,id=id}) end function access.logout() session.destroy(sailor.r) end return access
-------------------------------------------------------------------------------- -- access.lua, v0.2.5: controls access of sailor apps -- This file is a part of Sailor project -- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net> -- License: MIT -- http://sailorproject.org -------------------------------------------------------------------------------- local session = require "sailor.session" local access = {} session.open(sailor.r) -- Uncomment to login with "demo" / "demo" -- Comment to login through db (user model) --access.default = "demo" --access.default_pass = "demo" --access.salt = "sailorisawesome" -- set to nil to use unhashed passwords local INVALID = "Invalid username or password." -- Simple hashing algorithm for encrypting passworsd function access.hash(username, password, salt) salt = salt or access.salt local hash = username .. password -- Check if bcrypt is embedded if sailor.conf.bcrypt and salt and sailor.r.htpassword then hash = sailor.r:htpassword(salt .. hash, 2, 100) -- Use bcrypt on pwd return hash -- If not, fall back to sha1 hashing else if salt and sailor.r.sha1 then for i = 1, 500 do hash = sailor.r:sha1(salt .. hash) end end end return hash end function access.is_guest() if not access.data then access.data = session.data end return not access.data.username end function access.grant(data,time) session.setsessiontimeout (time or 604800) -- 1 week if not data.username then return false end access.data = data return session.save(data) end function access.login(username,password) local id if not access.default then local User = sailor.model("user") local u = User:find_by_attributes{ username=username } if not u then return false, INVALID end if u.password ~= access.hash(username, password, u.salt) then return false, INVALID end id = u.id else if username ~= access.default or password ~= access.default_pass then return false, INVALID end id = 1 end return access.grant({username=username,id=id}) end function access.logout() session.data = {} session.destroy(sailor.r) end return access
fixing some session bugs
fixing some session bugs
Lua
mit
mpeterv/sailor,mpeterv/sailor,hallison/sailor,noname007/sailor,Etiene/sailor,felipedaragon/sailor,sailorproject/sailor,ignacio/sailor,ignacio/sailor,felipedaragon/sailor,Etiene/sailor,jeary/sailor
53d2c5a56f3507f178cddfe329994da84a029b76
extensions/uielement/test_uielement.lua
extensions/uielement/test_uielement.lua
hs.uielement = require("hs.uielement") hs.window = require("hs.window") hs.timer = require("hs.timer") hs.eventtap = require("hs.eventtap") hs.application = require("hs.application") elem = nil elemEvent = nil function getPrefs() hs.openPreferences() return hs.uielement.focusedElement() end function getConsole() hs.openConsole() return hs.uielement.focusedElement() end function testHammerspoonElements() local consoleElem = getConsole() local consoleElem2 = getConsole() assertIsEqual(consoleElem, consoleElem2) assertFalse(consoleElem:isApplication()) assertFalse(consoleElem:isWindow()) assertIsEqual("AXTextField", consoleElem:role()) local prefsElem = getPrefs() assertFalse(prefsElem:isApplication()) assertTrue(prefsElem:isWindow()) assertIsEqual("AXWindow", prefsElem:role()) assertIsEqual(nil, prefsElem:selectedText()) local consoleElem2 = getConsole() assertFalse(consoleElem:isApplication()) assertFalse(consoleElem:isWindow()) assertIsEqual("AXTextField", consoleElem:role()) assertFalse(consoleElem==prefsElem) assertTrue(consoleElem==consoleElem2) assertTrue(hs.window.find("Hammerspoon Console"):close()) assertTrue(hs.window.find("Hammerspoon Preferences"):close()) return success() end function testSelectedText() local text = "abc123" local textedit = hs.application.open("com.apple.TextEdit") hs.timer.usleep(1000000) hs.eventtap.keyStroke({"cmd"}, "n") hs.timer.usleep(1000000) hs.eventtap.keyStrokes(text) hs.timer.usleep(20000) hs.eventtap.keyStroke({"cmd"}, "a") assertIsEqual(text, hs.uielement.focusedElement():selectedText()) textedit:kill9() return success() end function testWatcherValues() assertIsNotNil(elem) elem:move({1,1}) if (type(elemEvent) == "string" and elemEvent == "AXWindowMoved") then app:kill() return success() else return "Waiting for success... (" .. type(elemEvent) .. ")" end end function testWatcher() app = hs.application.open("com.apple.systempreferences", 5, true) assertIsUserdataOfType("hs.application", app) hs.window.find("System Preferences"):focus() elem = hs.window.focusedWindow() assertIsNotNil(elem) watcher = elem:newWatcher(function(element, event, thisWatcher, userdata) hs.alert.show("watcher-callback") elemEvent = event assertIsEqual(watcher, thisWatcher:stop()) end) assertIsEqual(watcher, watcher:start({hs.uielement.watcher.windowMoved})) assertIsEqual(elem, watcher:element()) return success() end
hs.uielement = require("hs.uielement") hs.window = require("hs.window") hs.timer = require("hs.timer") hs.eventtap = require("hs.eventtap") hs.application = require("hs.application") elem = nil elemEvent = nil watcher = nil function getPrefs() hs.openPreferences() return hs.uielement.focusedElement() end function getConsole() hs.openConsole() return hs.uielement.focusedElement() end function testHammerspoonElements() local consoleElem = getConsole() local consoleElem2 = getConsole() assertIsEqual(consoleElem, consoleElem2) assertFalse(consoleElem:isApplication()) assertFalse(consoleElem:isWindow()) assertIsEqual("AXTextField", consoleElem:role()) local prefsElem = getPrefs() assertFalse(prefsElem:isApplication()) assertTrue(prefsElem:isWindow()) assertIsEqual("AXWindow", prefsElem:role()) assertIsEqual(nil, prefsElem:selectedText()) local consoleElem2 = getConsole() assertFalse(consoleElem:isApplication()) assertFalse(consoleElem:isWindow()) assertIsEqual("AXTextField", consoleElem:role()) assertFalse(consoleElem==prefsElem) assertTrue(consoleElem==consoleElem2) assertTrue(hs.window.find("Hammerspoon Console"):close()) assertTrue(hs.window.find("Hammerspoon Preferences"):close()) return success() end function testSelectedText() local text = "abc123" local textedit = hs.application.open("com.apple.TextEdit") hs.timer.usleep(1000000) hs.eventtap.keyStroke({"cmd"}, "n") hs.timer.usleep(1000000) hs.eventtap.keyStrokes(text) hs.timer.usleep(20000) hs.eventtap.keyStroke({"cmd"}, "a") assertIsEqual(text, hs.uielement.focusedElement():selectedText()) textedit:kill9() return success() end function testWatcherValues() assertIsNotNil(elem) elem:move({1,1}) if (type(elemEvent) == "string" and elemEvent == "AXWindowMoved") then app:kill() return success() else return "Waiting for success... (" .. type(elem) .. ":" .. type(watcher) .. ":" .. type(elemEvent) .. ")" end end function testWatcher() app = hs.application.open("com.apple.systempreferences", 5, true) assertIsUserdataOfType("hs.application", app) hs.window.find("System Preferences"):focus() elem = hs.window.focusedWindow() assertIsNotNil(elem) watcher = elem:newWatcher(function(element, event, thisWatcher, userdata) hs.alert.show("watcher-callback") elemEvent = event assertIsEqual(watcher, thisWatcher:stop()) end) assertIsEqual(watcher, watcher:start({hs.uielement.watcher.windowMoved})) assertIsEqual(elem, watcher:element()) return success() end
Attempt to fix up hs.uielement:newWatcher() test
Attempt to fix up hs.uielement:newWatcher() test Add more debugging to uielement:newWatcher() failures
Lua
mit
Habbie/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon
263e0974a7342be66818b042dfb8995ab730a053
lib/px/utils/config_loader.lua
lib/px/utils/config_loader.lua
local _M = {} function _M.get_configuration(config_file) local http = require "resty.http" local px_constants = require "px.utils.pxconstants" local config = require(config_file) local px_logger = require("px.utils.pxlogger").load(config_file) px_logger.debug("Fetching configuration") local cjson = require "cjson" local px_server = config.configuration_server local px_port = config.configuration_server_port local path = px_constants.REMOTE_CONFIGURATIONS_PATH local checksum = config.checksum local query if checksum ~= nil then query = '?checksum=' .. checksum else query = '' end local httpc = http.new() local ok, err = httpc:connect(px_server, px_port) if not ok then px_logger.error("HTTPC connection error: " .. err) end if config.ssl_enabled == true then local session, err = httpc:ssl_handshake() if not session then px_logger.error("HTTPC SSL handshare error: " .. err) end end local res, err = httpc:request({ path = path, method = "GET", headers = { ["Content-Type"] = "application/json", ["Authorization"] = "Bearer " .. config.auth_token }, query = query }) if err ~= nil or res == nil or res.status > 204 then px_logger.error("Failed to get configurations: " .. (err ~= nil and err or '')) if (checksum == nil) then --no configs yet and can't get configs - disable module px_logger.error("Disabling PX module since no configuration is available") config.px_enabled = false end return end if res.status == 204 then px_logger.debug("Configuration was not changed") return end -- new configurations available if res.status == 200 then local body = res:read_body() px_logger.debug("Applying new configuration: " .. body) body = cjson.decode(body) config.checksum = body.checksum config.px_enabled = body.moduleEnabled config.cookie_secret = body.cookieKey config.px_appId = body.appId config.blocking_score = body.blockingScore config.sensitive_headers = body.sensitiveHeaders config.ip_headers = body.ipHeaders config.px_debug = body.debugMode config.block_enabled = body.moduleMode ~= "monitoring" config.client_timeout = body.connectTimeout config.s2s_timeout = body.riskTimeout config.report_active_config = true end end function _M.load(config_file) local config = require(config_file) local ngx_timer_at = ngx.timer.at local px_logger = require("px.utils.pxlogger").load(config_file) -- set interval local function load_on_timer() local ok, err = ngx_timer_at(config.load_interval, load_on_timer) if not ok then px_logger.error("Failed to schedule submit timer: " .. err) px_logger.error("Disabling PX module since timer failed") config.px_enabled = false else _M.get_configuration(config_file) end return end load_on_timer() end return _M
local _M = {} function _M.get_configuration(config_file) local http = require "resty.http" local px_constants = require "px.utils.pxconstants" local config = require(config_file) local px_logger = require("px.utils.pxlogger").load(config_file) px_logger.debug("Fetching configuration") local cjson = require "cjson" local px_server = config.configuration_server local px_port = config.configuration_server_port local path = px_constants.REMOTE_CONFIGURATIONS_PATH local checksum = config.checksum local query if checksum ~= nil then query = '?checksum=' .. checksum else query = '' end local httpc = http.new() local ok, err = httpc:connect(px_server, px_port) if not ok then px_logger.error("HTTPC connection error: " .. err) end if config.ssl_enabled == true then local session, err = httpc:ssl_handshake() if not session then px_logger.error("HTTPC SSL handshare error: " .. err) end end local res, err = httpc:request({ path = path, method = "GET", headers = { ["Content-Type"] = "application/json", ["Authorization"] = "Bearer " .. config.auth_token }, query = query }) if err ~= nil or res == nil or res.status > 204 then px_logger.error("Failed to get configurations: " .. (err ~= nil and err or '')) if (checksum == nil) then --no configs yet and can't get configs - disable module px_logger.error("Disabling PX module since no configuration is available") config.px_enabled = false end return end if res.status == 204 then px_logger.debug("Configuration was not changed") return end -- new configurations available if res.status == 200 then local body = res:read_body() px_logger.debug("Applying new configuration: " .. body) body = cjson.decode(body) config.checksum = body.checksum config.px_enabled = body.moduleEnabled config.cookie_secret = body.cookieKey config.px_appId = body.appId config.blocking_score = body.blockingScore config.sensitive_headers = body.sensitiveHeaders config.ip_headers = body.ipHeaders config.px_debug = body.debugMode config.block_enabled = body.moduleMode ~= "monitoring" config.client_timeout = body.connectTimeout config.s2s_timeout = body.riskTimeout config.report_active_config = true end end function _M.load(config_file) local config = require(config_file) local ngx_timer_at = ngx.timer.at local px_logger = require("px.utils.pxlogger").load(config_file) -- set interval local function load_on_timer() local ok, err = ngx_timer_at(config.load_interval, load_on_timer) if not ok then px_logger.error("Failed to schedule submit timer: " .. err) if not config.config.checksum then px_logger.error("Disabling PX module since timer failed") config.px_enabled = false end else _M.get_configuration(config_file) end return end load_on_timer() end return _M
fixed remote_config
fixed remote_config
Lua
mit
PerimeterX/perimeterx-nginx-plugin
09d0df2a7a7cb2b58d934b0759f0e287d21e4135
libs/fs.lua
libs/fs.lua
local prev, pl, dirname, dir = ... local glob = prev.require 'posix.glob'.glob local romPath = pl.path.normpath(pl.path.join(dirname, 'cc')) local function findRomFile(path) return pl.path.normpath(pl.path.join(romPath, path)) end local function betterifyPath(path) local oldPath while oldPath ~= path do oldPath = path if path:sub(1, 1) == '/' then path = path:sub(2) end if path:sub(1, 2) == './' or path == '.' then path = path:sub(2) end if path:sub(1, 3) == '../' or path == '..' then path = path:sub(3) end if path:sub(-2) == '/.' then path = path:sub(1, -3) end end return path end dir = '/' .. betterifyPath(dir) dirname = '/' .. betterifyPath(dirname) romPath = '/' .. betterifyPath(pl.path.abspath(romPath)) local function findPath(path) path = pl.path.normpath(path) path = betterifyPath(path) if path:sub(1, 3) == 'rom' then return findRomFile(path) end return pl.path.normpath(pl.path.join(dir, path)) end local function runRom(path, ...) local fn, err = prev.loadfile(findRomFile(path), 't', _G) if err then error(err) end if setfenv then setfenv(fn, _G) end return fn(...) end return { isReadOnly = function(path) return betterifyPath(path):sub(1, 3) == 'rom' end; delete = function(path) path = findPath(path) pl.file.delete(path) end; move = function(src, dest) src = findPath(src) dest = findPath(dest) pl.file.move(src, dest) end; copy = function(src, dest) src = findPath(src) dest = findPath(dest) pl.file.copy(src, dest) end; list = function(path) path = findPath(path) local files = {} if path == dir then files[#files + 1] = 'rom' end for file in pl.path.dir(path) do if file ~= '.' and file ~= '..' then files[#files + 1] = file end end table.sort(files) return files end; open = function(path, mode) local file = prev.io.open(findPath(path), mode) if file == nil then return nil end local h = {} if mode == 'r' then function h.readAll() local data = file:read('*a') if data then data = data:gsub('\13', '\n') end -- prev.print('all', pl.pretty.write(data)) return data end function h.readLine() local line = file:read('*l') if line then line = line:gsub('[\13\n\r]*$', '') end -- prev.print('line', pl.pretty.write(line)) return line end elseif mode == 'w' or mode == 'a' then function h.write(data) file:write(data) end function h.writeLine(data) file:write(data) file:write('\n') end function h.flush() file:flush() end end function h.close() file:close() end return h end; exists = function(path) return pl.path.exists(findPath(path)) ~= false end; isDir = function(path) return pl.path.isdir(findPath(path)) end; combine = function(a, b) local function doIt() if a == '' then a = '/' end if a:sub(1, 1) ~= '/' and a:sub(1, 2) ~= './' then a = '/' .. a end if b == '.' then return a end if a == '/' and b == '..' then return '..' end if a:sub(-2) == '..' and b == '..' then return a .. '/..' end return pl.path.normpath(pl.path.join(a, b)) end local res = doIt() if res:sub(1, 1) == '/' then res = res:sub(2) end return res end; getName = function(path) return pl.path.basename(path) end; find = function(pat) pat = pl.path.normpath(pat or '') pat = pat:gsub('%*%*', '*') local results = {} for _, path in ipairs(glob(findPath(pat)) or {}) do results[#results + 1] = pl.path.relpath(path, dir) end for _, path in ipairs(glob(findRomFile(pat)) or {}) do results[#results + 1] = pl.path.relpath(path, romPath) end return results end; makeDir = function(path) path = findPath(path) pl.path.mkdir(path) end; }, runRom
local prev, pl, dirname, dir = ... local glob = prev.require 'posix.glob'.glob local romPath = pl.path.normpath(pl.path.join(dirname, 'cc')) local function findRomFile(path) return pl.path.normpath(pl.path.join(romPath, path)) end local function betterifyPath(path) local oldPath while oldPath ~= path do oldPath = path if path:sub(1, 1) == '/' then path = path:sub(2) end if path:sub(1, 2) == './' or path == '.' then path = path:sub(2) end if path:sub(1, 3) == '../' or path == '..' then path = path:sub(3) end if path:sub(-2) == '/.' then path = path:sub(1, -3) end end return path end dir = '/' .. betterifyPath(dir) dirname = '/' .. betterifyPath(dirname) romPath = '/' .. betterifyPath(pl.path.abspath(romPath)) local function findPath(path) path = pl.path.normpath(path) path = betterifyPath(path) if path:sub(1, 3) == 'rom' then return findRomFile(path) end return pl.path.normpath(pl.path.join(dir, path)) end local function runRom(path, ...) local fn, err = prev.loadfile(findRomFile(path), 't', _G) if err then error(err) end if setfenv then setfenv(fn, _G) end return fn(...) end return { isReadOnly = function(path) return betterifyPath(path):sub(1, 3) == 'rom' end; delete = function(path) path = findPath(path) pl.file.delete(path) end; move = function(src, dest) src = findPath(src) dest = findPath(dest) pl.file.move(src, dest) end; copy = function(src, dest) src = findPath(src) dest = findPath(dest) pl.file.copy(src, dest) end; list = function(path) path = findPath(path) local files = {} if path == dir then files[#files + 1] = 'rom' end for file in pl.path.dir(path) do if file ~= '.' and file ~= '..' then files[#files + 1] = file end end table.sort(files) return files end; open = function(path, mode) local file = prev.io.open(findPath(path), mode) if file == nil then return nil end local h = {} if mode == 'r' then function h.readAll() local data = file:read('*a') if data then data = data:gsub('\13', '\n') -- prev.print('all', pl.pretty.write(data)) return data else return '' end end function h.readLine() local line = file:read('*l') if line then line = line:gsub('[\13\n\r]*$', '') end -- prev.print('line', pl.pretty.write(line)) return line end elseif mode == 'w' or mode == 'a' then function h.write(data) file:write(data) end function h.writeLine(data) file:write(data) file:write('\n') end function h.flush() file:flush() end end function h.close() file:close() end return h end; exists = function(path) return pl.path.exists(findPath(path)) ~= false end; isDir = function(path) return pl.path.isdir(findPath(path)) end; combine = function(a, b) local function doIt() if a == '' then a = '/' end if a:sub(1, 1) ~= '/' and a:sub(1, 2) ~= './' then a = '/' .. a end if b == '.' then return a end if a == '/' and b == '..' then return '..' end if a:sub(-2) == '..' and b == '..' then return a .. '/..' end return pl.path.normpath(pl.path.join(a, b)) end local res = doIt() if res:sub(1, 1) == '/' then res = res:sub(2) end return res end; getName = function(path) return pl.path.basename(path) end; find = function(pat) pat = pl.path.normpath(pat or '') pat = pat:gsub('%*%*', '*') local results = {} for _, path in ipairs(glob(findPath(pat)) or {}) do results[#results + 1] = pl.path.relpath(path, dir) end for _, path in ipairs(glob(findRomFile(pat)) or {}) do results[#results + 1] = pl.path.relpath(path, romPath) end return results end; makeDir = function(path) path = findPath(path) pl.path.mkdir(path) end; }, runRom
Ensure file.readAll always returns a string
Ensure file.readAll always returns a string could fix #3
Lua
mit
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
562e34122f302e30fe8362ee99e8b2e4acff4d3f
src/spring/src/Shared/Spring.lua
src/spring/src/Shared/Spring.lua
--[[ class Spring Description: A physical model of a spring, useful in many applications. Properties only evaluate upon index making this model good for lazy applications API: Spring = Spring.new(number position) Creates a new spring in 1D Spring = Spring.new(Vector3 position) Creates a new spring in 3D Spring.Position Returns the current position Spring.Velocity Returns the current velocity Spring.Target Returns the target Spring.Damper Returns the damper Spring.Speed Returns the speed Spring.Target = number/Vector3 Sets the target Spring.Position = number/Vector3 Sets the position Spring.Velocity = number/Vector3 Sets the velocity Spring.Damper = number [0, 1] Sets the spring damper, defaults to 1 Spring.Speed = number [0, infinity) Sets the spring speed, defaults to 1 Spring:TimeSkip(number DeltaTime) Instantly skips the spring forwards by that amount of now Spring:Impulse(number/Vector3 velocity) Impulses the spring, increasing velocity by the amount given Visualization (by Defaultio): https://www.desmos.com/calculator/hn2i9shxbz ]] local Spring = {} --- Creates a new spring -- @param initial A number or Vector3 (anything with * number and addition/subtraction defined) -- @param[opt=os.clock] clock function to use to update spring function Spring.new(initial, clock) local target = initial or 0 clock = clock or os.clock return setmetatable({ _clock = clock; _time0 = clock(); _position0 = target; _velocity0 = 0*target; _target = target; _damper = 1; _speed = 1; }, Spring) end --- Impulse the spring with a change in velocity -- @param velocity The velocity to impulse with function Spring:Impulse(velocity) self.Velocity = self.Velocity + velocity end --- Skip forwards in now -- @param delta now to skip forwards function Spring:TimeSkip(delta) local now = self._clock() local position, velocity = self:_positionVelocity(now+delta) self._position0 = position self._velocity0 = velocity self._time0 = now end function Spring:__index(index) if Spring[index] then return Spring[index] elseif index == "Value" or index == "Position" or index == "p" then local position, _ = self:_positionVelocity(self._clock()) return position elseif index == "Velocity" or index == "v" then local _, velocity = self:_positionVelocity(self._clock()) return velocity elseif index == "Target" or index == "t" then return self._target elseif index == "Damper" or index == "d" then return self._damper elseif index == "Speed" or index == "s" then return self._speed elseif index == "Clock" then return self._clock else error(("%q is not a valid member of Spring"):format(tostring(index)), 2) end end function Spring:__newindex(index, value) local now = self._clock() if index == "Value" or index == "Position" or index == "p" then local _, velocity = self:_positionVelocity(now) self._position0 = value self._velocity0 = velocity self._time0 = now elseif index == "Velocity" or index == "v" then local position, _ = self:_positionVelocity(now) self._position0 = position self._velocity0 = value self._time0 = now elseif index == "Target" or index == "t" then local position, velocity = self:_positionVelocity(now) self._position0 = position self._velocity0 = velocity self._target = value self._time0 = now elseif index == "Damper" or index == "d" then local position, velocity = self:_positionVelocity(now) self._position0 = position self._velocity0 = velocity self._damper = math.clamp(value, 0, 1) self._time0 = now elseif index == "Speed" or index == "s" then local position, velocity = self:_positionVelocity(now) self._position0 = position self._velocity0 = velocity self._speed = value < 0 and 0 or value self._time0 = now elseif index == "Clock" then local position, velocity = self:_positionVelocity(now) self._position0 = position self._velocity0 = velocity self._clock = value self._time0 = value() else error(("%q is not a valid member of Spring"):format(tostring(index)), 2) end end function Spring:_positionVelocity(now) local p0 = self._position0 local v0 = self._velocity0 local p1 = self._target local d = self._damper local s = self._speed local t = s*(now - self._time0) local d2 = d*d local h, si, co if d2 < 1 then h = math.sqrt(1 - d2) local ep = math.exp(-d*t)/h co, si = ep*math.cos(h*t), ep*math.sin(h*t) elseif d2 == 1 then h = 1 local ep = math.exp(-d*t)/h co, si = ep, ep*t else h = math.sqrt(d2 - 1) local u = math.exp((-d + h)*t)/(2*h) local v = math.exp((-d - h)*t)/(2*h) co, si = u + v, u - v end local a0 = h*co + d*si local a1 = 1 - (h*co + d*si) local a2 = si/s local b0 = -s*si local b1 = s*si local b2 = h*co - d*si return a0*p0 + a1*p1 + a2*v0, b0*p0 + b1*p1 + b2*v0 end return Spring
--[[ class Spring Description: A physical model of a spring, useful in many applications. Properties only evaluate upon index making this model good for lazy applications API: Spring = Spring.new(number position) Creates a new spring in 1D Spring = Spring.new(Vector3 position) Creates a new spring in 3D Spring.Position Returns the current position Spring.Velocity Returns the current velocity Spring.Target Returns the target Spring.Damper Returns the damper Spring.Speed Returns the speed Spring.Target = number/Vector3 Sets the target Spring.Position = number/Vector3 Sets the position Spring.Velocity = number/Vector3 Sets the velocity Spring.Damper = number [-infinity, infinity] Sets the spring damper, defaults to 1 Spring.Speed = number [0, infinity) Sets the spring speed, defaults to 1 Spring:TimeSkip(number DeltaTime) Instantly skips the spring forwards by that amount of now Spring:Impulse(number/Vector3 velocity) Impulses the spring, increasing velocity by the amount given Visualization (by Defaultio): https://www.desmos.com/calculator/hn2i9shxbz ]] local Spring = {} --- Creates a new spring -- @param initial A number or Vector3 (anything with * number and addition/subtraction defined) -- @param[opt=os.clock] clock function to use to update spring function Spring.new(initial, clock) local target = initial or 0 clock = clock or os.clock return setmetatable({ _clock = clock; _time0 = clock(); _position0 = target; _velocity0 = 0*target; _target = target; _damper = 1; _speed = 1; }, Spring) end --- Impulse the spring with a change in velocity -- @param velocity The velocity to impulse with function Spring:Impulse(velocity) self.Velocity = self.Velocity + velocity end --- Skip forwards in now -- @param delta now to skip forwards function Spring:TimeSkip(delta) local now = self._clock() local position, velocity = self:_positionVelocity(now+delta) self._position0 = position self._velocity0 = velocity self._time0 = now end function Spring:__index(index) if Spring[index] then return Spring[index] elseif index == "Value" or index == "Position" or index == "p" then local position, _ = self:_positionVelocity(self._clock()) return position elseif index == "Velocity" or index == "v" then local _, velocity = self:_positionVelocity(self._clock()) return velocity elseif index == "Target" or index == "t" then return self._target elseif index == "Damper" or index == "d" then return self._damper elseif index == "Speed" or index == "s" then return self._speed elseif index == "Clock" then return self._clock else error(("%q is not a valid member of Spring"):format(tostring(index)), 2) end end function Spring:__newindex(index, value) local now = self._clock() if index == "Value" or index == "Position" or index == "p" then local _, velocity = self:_positionVelocity(now) self._position0 = value self._velocity0 = velocity self._time0 = now elseif index == "Velocity" or index == "v" then local position, _ = self:_positionVelocity(now) self._position0 = position self._velocity0 = value self._time0 = now elseif index == "Target" or index == "t" then local position, velocity = self:_positionVelocity(now) self._position0 = position self._velocity0 = velocity self._target = value self._time0 = now elseif index == "Damper" or index == "d" then local position, velocity = self:_positionVelocity(now) self._position0 = position self._velocity0 = velocity self._damper = value self._time0 = now elseif index == "Speed" or index == "s" then local position, velocity = self:_positionVelocity(now) self._position0 = position self._velocity0 = velocity self._speed = value < 0 and 0 or value self._time0 = now elseif index == "Clock" then local position, velocity = self:_positionVelocity(now) self._position0 = position self._velocity0 = velocity self._clock = value self._time0 = value() else error(("%q is not a valid member of Spring"):format(tostring(index)), 2) end end function Spring:_positionVelocity(now) local p0 = self._position0 local v0 = self._velocity0 local p1 = self._target local d = self._damper local s = self._speed local t = s*(now - self._time0) local d2 = d*d local h, si, co if d2 < 1 then h = math.sqrt(1 - d2) local ep = math.exp(-d*t)/h co, si = ep*math.cos(h*t), ep*math.sin(h*t) elseif d2 == 1 then h = 1 local ep = math.exp(-d*t)/h co, si = ep, ep*t else h = math.sqrt(d2 - 1) local u = math.exp((-d + h)*t)/(2*h) local v = math.exp((-d - h)*t)/(2*h) co, si = u + v, u - v end local a0 = h*co + d*si local a1 = 1 - (h*co + d*si) local a2 = si/s local b0 = -s*si local b1 = s*si local b2 = h*co - d*si return a0*p0 + a1*p1 + a2*v0, b0*p0 + b1*p1 + b2*v0 end return Spring
fix: Spring does not have clamped damper
fix: Spring does not have clamped damper
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
3f1ae577c544c6c86ca2dd9f96fc9eff926cf921
lib/lua/utils.lua
lib/lua/utils.lua
-------------------- --- Module with utility functions -- --- @module utils -- --- Submodules: -- --- * `file`: Operations on files --- * `math`: Contains a few math functions --- * `string`: Operations on strings --- * `table`: Operations on tables util = {} --- IO Functions util.file = {} --- Opens the file at path with the given mode and format --- @param path File to be opened --- @param mode Optional mode to open file with --- @param format Optional format to read file with --- @return The content of the file function util.file.read_all(path, mode, format) assert(path ~= nil, "File path was nil") if mode == nil then mod = "*all" end local file = io.open(path) if file == nil then error("Unable to open " .. path .. "!", 2) end local data = file:read(format) file:close() return data end --- Math functions util.math = {} --- Converts a number in a range to a percentage --- @param min The minimum value in the range --- @param max The maximum value in the range --- @param value The value in the range to convert --- @return A percentage from 0 to 100 for the value function util.math.range_to_percent(min, max, value) assert(type(min) == 'number', "min: expected number") assert(type(max) == 'number', "max: expected number") assert(type(value) == 'number', "value: expected number") assert(min < max, "min value was not less than max!") value = math.min(max, value) value = math.max(min, value) return math.ceil( (value - min) / (max - min) * 100 ) end --- String functions util.string = {} --- Counts the number of lines in a string. --- @param text String to count lines of --- @return The number of lines in the string. function util.string.line_count(text) assert(type(text) == 'string', "Non-string given to string.line_count!") local count = 0 for result in text:gmatch("\n") do count = count + 1 end return count end --- Escapes backslashes and quotes in a string. -- --- Replaces " with \", ' with \', and \ with \\. --- @param text String to escape --- @return String escaped with quotes. function util.string.escape_quotes(text) assert(type(text) == 'string', "string.escape: Expected a string") text = text:gsub('\\', '\\\\') text = text:gsub('"', '\\"') text = text:gsub("'", "\\'") return text end --- Escapes strings for HTML encoding. -- --- Replaces <, >, &, ", and ' with their HTML &name; equivalents. --- @param test The text to escape --- @return HTML escaped text. function util.string.escape_html(text) assert(type(text) == 'string', "string.html_escape: Expected a string") builder = "" for i = 1, text:len() do if char == '<' then builder = builder + '&lt;' elseif char == '>' then builder = builder + '&gt;' elseif char == '&' then builder = builder + '&amp;' elseif char == '"' then builder = builder + '&quot;' elseif char == "'" then builder = builder + '&apos;' else builder = builder + text[i] end end return builder end --- Table functions util.table = {} --- Gets a random element from a numerically-indexed list. -- --- # Errors --- Function will error if the table is nil or empty, --- or if the indicies are not numbers. -- --- @param tab The list to pick from --- @return A random element from the list function util.table.get_random(tab) assert(type(tab) == 'table', "Non table given to table.get_random!") local len = #tab if len == 0 then error("Empty table given to table.get_random!", 2) elseif len == 1 then return tab[1] else return tab[math.random(1, len)] end end --- List of programs that should be spawned each start/restart. util.program = {} util.program.programs = {} --- Returns a function that spawns a program once. --- Does not update the global program spawn list. --- Used primarily for key mapping. --- @param bin The program to run. Can be an absolute path or a command to run. --- @param args The arguments (as a string) to pass to the program. function util.program.spawn_once(bin, args) assert(type(bin) == 'string', 'Non string given for program') if type(args) ~= 'string' then args = "" end os.execute(bin .. " " .. args .. " &") end --- Registers the program to spawn at startup and every time it restarts --- @param bin The program to run. Can be an absolute path or a command to run. --- @param args The arguments (as a string) to pass to the program. function util.program.spawn_at_startup(bin, args) assert(type(bin) == 'string', 'Non string given for program') table.insert(util.program.programs, { bin = bin, args = args }) end --- Spawns the startup programs function util.program.spawn_startup_programs() for index, program in ipairs(util.program.programs) do os.execute(program.bin .. " " .. program.args .. " &") end end --- Stops the startup programs. Does not remove them from the global list. function util.program.terminate_startup_programs() for index, program in ipairs(util.program.programs) do -- TODO Kill in a more fine-grained matter... -- parent joining on child process? PIDs won't work, they can be reclaimed. os.execute("pkill " .. program.bin) end end --- Stops the startup programs and then immediately starts them again. --- Useful for the "restart" command function util.program.restart_startup_programs() util.program.terminate_startup_programs() util.program.spawn_startup_programs() end
-------------------- --- Module with utility functions -- --- @module utils -- --- Submodules: -- --- * `file`: Operations on files --- * `math`: Contains a few math functions --- * `string`: Operations on strings --- * `table`: Operations on tables util = {} --- IO Functions util.file = {} --- Opens the file at path with the given mode and format --- @param path File to be opened --- @param mode Optional mode to open file with --- @param format Optional format to read file with --- @return The content of the file function util.file.read_all(path, mode, format) assert(path ~= nil, "File path was nil") if mode == nil then mod = "*all" end local file = io.open(path) if file == nil then error("Unable to open " .. path .. "!", 2) end local data = file:read(format) file:close() return data end --- Math functions util.math = {} --- Converts a number in a range to a percentage --- @param min The minimum value in the range --- @param max The maximum value in the range --- @param value The value in the range to convert --- @return A percentage from 0 to 100 for the value function util.math.range_to_percent(min, max, value) assert(type(min) == 'number', "min: expected number") assert(type(max) == 'number', "max: expected number") assert(type(value) == 'number', "value: expected number") assert(min < max, "min value was not less than max!") value = math.min(max, value) value = math.max(min, value) return math.ceil( (value - min) / (max - min) * 100 ) end --- String functions util.string = {} --- Counts the number of lines in a string. --- @param text String to count lines of --- @return The number of lines in the string. function util.string.line_count(text) assert(type(text) == 'string', "Non-string given to string.line_count!") local count = 0 for result in text:gmatch("\n") do count = count + 1 end return count end --- Escapes backslashes and quotes in a string. -- --- Replaces " with \", ' with \', and \ with \\. --- @param text String to escape --- @return String escaped with quotes. function util.string.escape_quotes(text) assert(type(text) == 'string', "string.escape: Expected a string") text = text:gsub('\\', '\\\\') text = text:gsub('"', '\\"') text = text:gsub("'", "\\'") return text end --- Escapes strings for HTML encoding. -- --- Replaces <, >, &, ", and ' with their HTML &name; equivalents. --- @param test The text to escape --- @return HTML escaped text. function util.string.escape_html(text) assert(type(text) == 'string', "string.html_escape: Expected a string") builder = "" for i = 1, text:len() do if char == '<' then builder = builder + '&lt;' elseif char == '>' then builder = builder + '&gt;' elseif char == '&' then builder = builder + '&amp;' elseif char == '"' then builder = builder + '&quot;' elseif char == "'" then builder = builder + '&apos;' else builder = builder + text[i] end end return builder end --- Table functions util.table = {} --- Gets a random element from a numerically-indexed list. -- --- # Errors --- Function will error if the table is nil or empty, --- or if the indicies are not numbers. -- --- @param tab The list to pick from --- @return A random element from the list function util.table.get_random(tab) assert(type(tab) == 'table', "Non table given to table.get_random!") local len = #tab if len == 0 then error("Empty table given to table.get_random!", 2) elseif len == 1 then return tab[1] else return tab[math.random(1, len)] end end --- List of programs that should be spawned each start/restart. util.program = {} util.program.programs = {} --- Spawns a program @param bin with the provided @param args. --- Does not update the global program spawn list. --- @param bin The program to run. Can be an absolute path or a command to run. --- @param args The arguments (as a string) to pass to the program. function util.program.spawn(bin, args) assert(type(bin) == 'string', 'Non string given for program') if type(args) ~= 'string' then args = "" end os.execute(bin .. " " .. args .. " &") end --- Returns a function that spawns a program once. --- Does not update the global program spawn list. --- Used primarily for key mapping. --- @param bin The program to run. Can be an absolute path or a command to run. --- @param args The arguments (as a string) to pass to the program. --- @return Function that calls @param bin with @param args. function util.program.spawn_once(bin, args) return function() util.program.spawn(bin, args) end end --- Registers the program to spawn at startup and every time it restarts --- @param bin The program to run. Can be an absolute path or a command to run. --- @param args The arguments (as a string) to pass to the program. function util.program.spawn_at_startup(bin, args) assert(type(bin) == 'string', 'Non string given for program') table.insert(util.program.programs, { bin = bin, args = args }) end --- Spawns the startup programs function util.program.spawn_startup_programs() for index, program in ipairs(util.program.programs) do os.execute(program.bin .. " " .. program.args .. " &") end end --- Stops the startup programs. Does not remove them from the global list. function util.program.terminate_startup_programs() for index, program in ipairs(util.program.programs) do -- TODO Kill in a more fine-grained matter... -- parent joining on child process? PIDs won't work, they can be reclaimed. os.execute("pkill " .. program.bin) end end --- Stops the startup programs and then immediately starts them again. --- Useful for the "restart" command function util.program.restart_startup_programs() util.program.terminate_startup_programs() util.program.spawn_startup_programs() end
Renamed spawn_once to spawn, + spawn_once wrapper
Renamed spawn_once to spawn, + spawn_once wrapper Fixes #255
Lua
mit
way-cooler/way-cooler,way-cooler/way-cooler,Immington-Industries/way-cooler,Immington-Industries/way-cooler,Immington-Industries/way-cooler,way-cooler/way-cooler
ed94b6da3b8a20bbbd850a988c055af4f37062be
libs/get-installed.lua
libs/get-installed.lua
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. 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 pathJoin = require('luvi').path.join local pkgQuery = require('pkg').query return function (fs, rootPath) local deps = {} local function check(dir) local iter = fs.scandir(dir) if not iter then return end for entry in iter do local baseName if entry.type == "file" then baseName = entry.name:match("^(.*)%.lua$") elseif entry.type == "directory" then baseName = entry.name end if baseName then local path, meta path = pathJoin(dir, entry.name) meta, path = pkgQuery(fs, path) if meta then meta.fs = fs meta.path = path meta.location = dir:match("[^/]+$") deps[baseName] = meta end end end end check(pathJoin(rootPath, "deps")) check(pathJoin(rootPath, "libs")) return deps end
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. 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 pathJoin = require('luvi').path.join local pkgQuery = require('pkg').query return function (fs, rootPath) local deps = {} local function check(dir) local iter = fs.scandir(dir) if not iter then return end for entry in iter do local baseName if not entry.type then local stat, err = fs.stat(pathJoin(dir, entry.name)) entry.type = stat and stat.type end if entry.type == "file" then baseName = entry.name:match("^(.*)%.lua$") elseif entry.type == "directory" then baseName = entry.name end if baseName then local path, meta path = pathJoin(dir, entry.name) meta, path = pkgQuery(fs, path) if meta then meta.fs = fs meta.path = path meta.location = dir:match("[^/]+$") deps[baseName] = meta end end end end check(pathJoin(rootPath, "deps")) check(pathJoin(rootPath, "libs")) return deps end
Fix local dependencies being ignored on file systems that don't support ftype in fs_scandir_next - See #184
Fix local dependencies being ignored on file systems that don't support ftype in fs_scandir_next - See #184
Lua
apache-2.0
luvit/lit,zhaozg/lit,james2doyle/lit
ad721d342cf95017532190257563f21349d2a51b
luasrc/mch_content.lua
luasrc/mch_content.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. -- -- mch_vars = nil mch_debug = nil function is_inited(app_name, init) -- get/set the inited flag for app_name local r_G = _G local mt = getmetatable(_G) if mt then r_G = rawget(mt, "__index") end if not r_G['moochine_inited'] then r_G['moochine_inited'] = {} end if init == nil then return r_G['moochine_inited'][app_name] else r_G['moochine_inited'][app_name] = init if init then -- put logger into _G local logger = require("mch.logger") r_G["logger"] = logger.logger() end end end function setup_app() local mch_home = ngx.var.MOOCHINE_HOME or os.getenv("MOOCHINE_HOME") local app_name = ngx.var.MOOCHINE_APP_NAME local app_path = ngx.var.MOOCHINE_APP_PATH local app_config = app_path .. "/application.lua" package.path = mch_home .. '/luasrc/?.lua;' .. package.path mch_vars = require("mch.vars") mch_debug = require("mch.debug") local mchutil = require("mch.util") -- setup vars and add to package.path mchutil.setup_app_env(mch_home, app_name, app_path, mch_vars.vars(app_name)) local logger = require("mch.logger") local config = mchutil.loadvars(app_config) if not config then config={} end mch_vars.set(app_name,"APP_CONFIG",config) is_inited(app_name, true) if type(config.subapps) == "table" then for k, t in pairs(config.subapps) do local subpath = t.path package.path = subpath .. '/app/?.lua;' .. package.path local env = setmetatable({__CURRENT_APP_NAME__ = k, __MAIN_APP_NAME__ = app_name, __LOGGER = logger.logger()}, {__index = _G}) setfenv(assert(loadfile(subpath .. "/routing.lua")), env)() end end -- load the main-app's routing local env = setmetatable({__CURRENT_APP_NAME__ = app_name, __MAIN_APP_NAME__ = app_name, __LOGGER = logger.logger()}, {__index = _G}) setfenv(assert(loadfile(app_path .. "/routing.lua")), env)() -- merge routings mchrouter = require("mch.router") mchrouter.merge_routings(app_name, config.subapps or {}) if config.debug and config.debug.on and mch_debug then debug.sethook(mch_debug.debug_hook, "cr") end end function content() if (not is_inited(ngx.var.MOOCHINE_APP_NAME)) or (not package.loaded.mch) then local ok, ret = pcall(setup_app) if not ok then ngx.status = 500 ngx.say("APP SETUP ERROR: " .. ret) return end else mch_vars = require("mch.vars") mch_debug = require("mch.debug") end if not is_inited(ngx.var.MOOCHINE_APP_NAME) then ngx.say('Can not setup MOOCHINE APP' .. ngx.var.MOOCHINE_APP_NAME) ngx.exit(501) end local uri = ngx.var.REQUEST_URI local route_map = mch_vars.get(ngx.var.MOOCHINE_APP_NAME,"ROUTE_INFO")['ROUTE_MAP'] local route_order = mch_vars.get(ngx.var.MOOCHINE_APP_NAME,"ROUTE_INFO")['ROUTE_ORDER'] local page_found = false -- match order by definition order for _, k in ipairs(route_order) do local args = string.match(uri, k) if args then page_found = true local v = route_map[k] local request = mch_vars.get(ngx.var.MOOCHINE_APP_NAME,'MOOCHINE_MODULES')['request'] local response = mch_vars.get(ngx.var.MOOCHINE_APP_NAME,'MOOCHINE_MODULES')['response'] if type(v) == "function" then local response = response.Response:new() if mch_debug then mch_debug.debug_clear() end local ok, ret = pcall(v, request.Request:new(), response, args) if not ok then response:error(ret) end response:finish() elseif type(v) == "table" then v:_handler(request.Request:new(), response.Response:new(), args) else ngx.exit(500) end break end end if not page_found then ngx.exit(404) end end ---------- content() ----------
#!/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. -- -- mch_vars = nil mch_debug = nil function is_inited(app_name, init) -- get/set the inited flag for app_name local r_G = _G local mt = getmetatable(_G) if mt then r_G = rawget(mt, "__index") end if not r_G['moochine_inited'] then r_G['moochine_inited'] = {} end if init == nil then return r_G['moochine_inited'][app_name] else r_G['moochine_inited'][app_name] = init if init then -- put logger into _G local logger = require("mch.logger") r_G["logger"] = logger.logger() end end end function setup_app() local mch_home = ngx.var.MOOCHINE_HOME or os.getenv("MOOCHINE_HOME") local app_name = ngx.var.MOOCHINE_APP_NAME local app_path = ngx.var.MOOCHINE_APP_PATH local app_config = app_path .. "/application.lua" package.path = mch_home .. '/luasrc/?.lua;' .. package.path mch_vars = require("mch.vars") mch_debug = require("mch.debug") local mchutil = require("mch.util") -- setup vars and add to package.path mchutil.setup_app_env(mch_home, app_name, app_path, mch_vars.vars(app_name)) local logger = require("mch.logger") local config = mchutil.loadvars(app_config) if not config then config={} end mch_vars.set(app_name,"APP_CONFIG",config) is_inited(app_name, true) if type(config.subapps) == "table" then for k, t in pairs(config.subapps) do local subpath = t.path package.path = subpath .. '/app/?.lua;' .. package.path local env = setmetatable({__CURRENT_APP_NAME__ = k, __MAIN_APP_NAME__ = app_name, __LOGGER = logger.logger()}, {__index = _G}) setfenv(assert(loadfile(subpath .. "/routing.lua")), env)() end end -- load the main-app's routing local env = setmetatable({__CURRENT_APP_NAME__ = app_name, __MAIN_APP_NAME__ = app_name, __LOGGER = logger.logger()}, {__index = _G}) setfenv(assert(loadfile(app_path .. "/routing.lua")), env)() -- merge routings mchrouter = require("mch.router") mchrouter.merge_routings(app_name, config.subapps or {}) if config.debug and config.debug.on and mch_debug then debug.sethook(mch_debug.debug_hook, "cr") end end function content() if (not is_inited(ngx.var.MOOCHINE_APP_NAME)) or (not package.loaded["mch.vars"]) then local ok, ret = pcall(setup_app) if not ok then ngx.status = 500 ngx.say("APP SETUP ERROR: " .. ret) return end else mch_vars = require("mch.vars") mch_debug = require("mch.debug") end if not is_inited(ngx.var.MOOCHINE_APP_NAME) then ngx.status=501 ngx.say('Can not setup MOOCHINE APP ' .. ngx.var.MOOCHINE_APP_NAME) return end local uri = ngx.var.REQUEST_URI local route_map = mch_vars.get(ngx.var.MOOCHINE_APP_NAME,"ROUTE_INFO")['ROUTE_MAP'] local route_order = mch_vars.get(ngx.var.MOOCHINE_APP_NAME,"ROUTE_INFO")['ROUTE_ORDER'] local page_found = false -- match order by definition order for _, k in ipairs(route_order) do local args = string.match(uri, k) if args then page_found = true local v = route_map[k] local request = mch_vars.get(ngx.var.MOOCHINE_APP_NAME,'MOOCHINE_MODULES')['request'] local response = mch_vars.get(ngx.var.MOOCHINE_APP_NAME,'MOOCHINE_MODULES')['response'] if type(v) == "function" then local response = response.Response:new() if mch_debug then mch_debug.debug_clear() end local ok, ret = pcall(v, request.Request:new(), response, args) if not ok then response:error(ret) end response:finish() elseif type(v) == "table" then v:_handler(request.Request:new(), response.Response:new(), args) else ngx.exit(500) end break end end if not page_found then ngx.exit(404) end end ---------- content() ----------
bugfix: inited flag
bugfix: inited flag
Lua
apache-2.0
lilien1010/moochine,lilien1010/moochine,lilien1010/moochine,appwilldev/moochine,appwilldev/moochine
d68b9e7da306cf9310c6e5b24a09441ed5df4b63
mod_s2s_reload_newcomponent/mod_s2s_reload_newcomponent.lua
mod_s2s_reload_newcomponent/mod_s2s_reload_newcomponent.lua
local modulemanager = require "core.modulemanager"; local config = require "core.configmanager"; module.host = "*"; local function reload_components() module:log ("debug", "reload_components"); local defined_hosts = config.getconfig(); for host in pairs(defined_hosts) do module:log ("debug", "found host %s", host); if (not hosts[host] and host ~= "*") then module:log ("debug", "found new host %s", host); modulemanager.load(host, configmanager.get(host, "core", "component_module")); end end; return; end module:hook("config-reloaded", reload_components);
local modulemanager = require "core.modulemanager"; local config = require "core.configmanager"; module.host = "*"; local function reload_components() local defined_hosts = config.getconfig(); for host in pairs(defined_hosts) do if (not hosts[host] and host ~= "*") then module:log ("debug", "loading new component %s", host); modulemanager.load(host, configmanager.get(host, "core", "component_module")); end end; return; end module:hook("config-reloaded", reload_components);
mod_s2s_reload_newcomponent: fix debug logs
mod_s2s_reload_newcomponent: fix debug logs
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
5583c9a513a67a07baf72b8274e99c95055ce23b
spec/demos/auth_spec.lua
spec/demos/auth_spec.lua
local request = require 'http.functional.request' local writer = require 'http.functional.response' local describe, it, assert = describe, it, assert local function signin(app) local w, req = writer.new(), request.new {path = '/signin'} app(w, req) local c = w.headers['Set-Cookie'] assert(c) c = c:match('^(_a=.-);') return w, req, c end local function secure(app) local w, req, c = signin(app) w = writer.new() req = request.new { path = '/secure', headers = {['cookie'] = c} } app(w, req) return w, req end local function test_cases(app) assert.not_nil(app) it('responds with auth cookie', function() local w, req, c = signin(app) assert.not_nil(c) end) it('responds with unauthorized status code', function() local w, req = writer.new(), request.new {path = '/secure'} app(w, req) assert.equals(401, w.status_code) w = writer.new() req = request.new { path = '/secure', cookies = {_a = 'x'} } app(w, req) assert.equals(401, w.status_code) end) it('parses auth cookie', function() local w, req = secure(app) assert.is_nil(w.status_code) end) end describe('demos.http.auth', function() local app = require 'demos.http.auth' test_cases(app) it('adds parsed security principal to request', function() local w, req = secure(app) assert.same({ id = 'john.smith', roles = {admin = true}, alias = '', extra = '' }, req.principal) end) end) describe('demos.web.auth', function() local app = require 'demos.web.auth' test_cases(app) end)
local request = require 'http.functional.request' local writer = require 'http.functional.response' local describe, it, assert = describe, it, assert local function signin(app) local w, req = writer.new(), request.new {path = '/signin'} app(w, req) local c = w.headers['Set-Cookie'] assert(c) c = c:match('^(_a=.-);') return c end local function secure(app) local c = signin(app) local w = writer.new() local req = request.new { path = '/secure', headers = {['cookie'] = c} } app(w, req) return w, req end local function test_cases(app) assert.not_nil(app) it('responds with auth cookie', function() local c = signin(app) assert.not_nil(c) end) it('responds with unauthorized status code', function() local w, req = writer.new(), request.new {path = '/secure'} app(w, req) assert.equals(401, w.status_code) w = writer.new() req = request.new { path = '/secure', cookies = {_a = 'x'} } app(w, req) assert.equals(401, w.status_code) end) it('parses auth cookie', function() local w = secure(app) assert.is_nil(w.status_code) end) end describe('demos.http.auth', function() local app = require 'demos.http.auth' test_cases(app) it('adds parsed security principal to request', function() local w, req = secure(app) assert.is_nil(w.status_code) assert.same({ id = 'john.smith', roles = {admin = true}, alias = '', extra = '' }, req.principal) end) end) describe('demos.web.auth', function() local app = require 'demos.web.auth' test_cases(app) end)
Fixed luacheck warnings.
Fixed luacheck warnings.
Lua
mit
akornatskyy/lucid
c9fc9496aa347631d2c68fc51979cb8ab1d51dcb
plugins/bookshortcuts.koplugin/main.lua
plugins/bookshortcuts.koplugin/main.lua
local ConfirmBox = require("ui/widget/confirmbox") local DataStorage = require("datastorage") local Dispatcher = require("dispatcher") local FFIUtil = require("ffi/util") local LuaSettings = require("luasettings") local PathChooser = require("ui/widget/pathchooser") local ReadHistory = require("readhistory") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local lfs = require("libs/libkoreader-lfs") local util = require("util") local _ = require("gettext") local T = FFIUtil.template local BookShortcuts = WidgetContainer:new{ name = "bookshortcuts", shortcuts = LuaSettings:open(DataStorage:getSettingsDir() .. "/bookshortcuts.lua"), updated = false, } function BookShortcuts:onDispatcherRegisterActions() for k,v in pairs(self.shortcuts.data) do if util.pathExists(k) then local title = k if lfs.attributes(k, "mode") == "file" then local directory, filename = util.splitFilePathName(k) -- luacheck: no unused title = filename end Dispatcher:registerAction(k, {category="none", event="BookShortcut", title=title, general=true, arg=k,}) end end end function BookShortcuts:onBookShortcut(path) if util.pathExists(path) then local file if lfs.attributes(path, "mode") ~= "file" then if G_reader_settings:readSetting("BookShortcuts_directory_action") == "FM" then local FileManager = require("apps/filemanager/filemanager") FileManager:showFiles(path) else file = ReadHistory:getFileByDirectory(path) end else file = path end local ReaderUI = require("apps/reader/readerui") ReaderUI:showReader(file) end end function BookShortcuts:init() self:onDispatcherRegisterActions() self.ui.menu:registerToMainMenu(self) end function BookShortcuts:onFlushSettings() if self.shortcuts and self.updated then self.shortcuts:flush() self.updated = false end end function BookShortcuts:addToMainMenu(menu_items) menu_items.book_shortcuts = { text = _("Book shortcuts"), sorting_hint = "more_tools", sub_item_table_func = function() return self:getSubMenuItems() end, } end function BookShortcuts:getSubMenuItems() local FM_text = _("file browser") local last_text = _("last book") local sub_item_table = { { text = _("New shortcut"), keep_menu_open = true, callback = function(touchmenu_instance) local path_chooser = PathChooser:new{ select_file = true, select_directory = true, detailed_file_info = true, path = G_reader_settings:readSetting("home_dir"), onConfirm = function(path) self:addShortcut(path) touchmenu_instance.item_table = self:getSubMenuItems() touchmenu_instance.page = 1 touchmenu_instance:updateItems() end } UIManager:show(path_chooser) end, }, { text_func = function() return T(_("Directory action: %1"), G_reader_settings:readSetting("BookShortcuts_directory_action", "FM") == "FM" and FM_text or last_text) end, keep_menu_open = true, sub_item_table = { { text = last_text, checked_func = function() return G_reader_settings:readSetting("BookShortcuts_directory_action") == "Last" end, callback = function() G_reader_settings:saveSetting("BookShortcuts_directory_action", "Last") end, }, { text = FM_text, checked_func = function() return G_reader_settings:readSetting("BookShortcuts_directory_action") == "FM" end, callback = function() G_reader_settings:saveSetting("BookShortcuts_directory_action", "FM") end, }, }, separator = true, } } for k,v in FFIUtil.orderedPairs(self.shortcuts.data) do table.insert(sub_item_table, { text = k, callback = function() self:onBookShortcut(k) end, hold_callback = function(touchmenu_instance) UIManager:show(ConfirmBox:new{ text = _("Do you want to delete this shortcut?"), ok_text = _("Delete"), ok_callback = function() self:deleteShortcut(k) touchmenu_instance.item_table = self:getSubMenuItems() touchmenu_instance.page = 1 touchmenu_instance:updateItems() end, }) end, }) end return sub_item_table end function BookShortcuts:addShortcut(name) self.shortcuts.data[name] = true self.updated = true self:onDispatcherRegisterActions() end function BookShortcuts:deleteShortcut(name) self.shortcuts.data[name] = nil Dispatcher:removeAction(name) self.updated = true end return BookShortcuts
local ConfirmBox = require("ui/widget/confirmbox") local DataStorage = require("datastorage") local Dispatcher = require("dispatcher") local FFIUtil = require("ffi/util") local LuaSettings = require("luasettings") local PathChooser = require("ui/widget/pathchooser") local ReadHistory = require("readhistory") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local lfs = require("libs/libkoreader-lfs") local util = require("util") local _ = require("gettext") local T = FFIUtil.template local BookShortcuts = WidgetContainer:new{ name = "bookshortcuts", shortcuts = LuaSettings:open(DataStorage:getSettingsDir() .. "/bookshortcuts.lua"), updated = false, } function BookShortcuts:onDispatcherRegisterActions() for k,v in pairs(self.shortcuts.data) do if util.pathExists(k) then local title = k if lfs.attributes(k, "mode") == "file" then local directory, filename = util.splitFilePathName(k) -- luacheck: no unused title = filename end Dispatcher:registerAction(k, {category="none", event="BookShortcut", title=title, general=true, arg=k,}) end end end function BookShortcuts:onBookShortcut(path) if util.pathExists(path) then local file if lfs.attributes(path, "mode") ~= "file" then if G_reader_settings:readSetting("BookShortcuts_directory_action") == "FM" then if self.ui.file_chooser then self.ui.file_chooser:changeToPath(path) else -- called from Reader self.ui:onClose() local FileManager = require("apps/filemanager/filemanager") if FileManager.instance then FileManager.instance:reinit(path) else FileManager:showFiles(path) end end else file = ReadHistory:getFileByDirectory(path) end else file = path end if file then local ReaderUI = require("apps/reader/readerui") ReaderUI:showReader(file) end end end function BookShortcuts:init() self:onDispatcherRegisterActions() self.ui.menu:registerToMainMenu(self) end function BookShortcuts:onFlushSettings() if self.shortcuts and self.updated then self.shortcuts:flush() self.updated = false end end function BookShortcuts:addToMainMenu(menu_items) menu_items.book_shortcuts = { text = _("Book shortcuts"), sorting_hint = "more_tools", sub_item_table_func = function() return self:getSubMenuItems() end, } end function BookShortcuts:getSubMenuItems() local FM_text = _("file browser") local last_text = _("last book") local sub_item_table = { { text = _("New shortcut"), keep_menu_open = true, callback = function(touchmenu_instance) local path_chooser = PathChooser:new{ select_file = true, select_directory = true, detailed_file_info = true, path = G_reader_settings:readSetting("home_dir"), onConfirm = function(path) self:addShortcut(path) touchmenu_instance.item_table = self:getSubMenuItems() touchmenu_instance.page = 1 touchmenu_instance:updateItems() end } UIManager:show(path_chooser) end, }, { text_func = function() return T(_("Folder action: %1"), G_reader_settings:readSetting("BookShortcuts_directory_action", "FM") == "FM" and FM_text or last_text) end, keep_menu_open = true, sub_item_table = { { text = last_text, checked_func = function() return G_reader_settings:readSetting("BookShortcuts_directory_action") == "Last" end, callback = function() G_reader_settings:saveSetting("BookShortcuts_directory_action", "Last") end, }, { text = FM_text, checked_func = function() return G_reader_settings:readSetting("BookShortcuts_directory_action") == "FM" end, callback = function() G_reader_settings:saveSetting("BookShortcuts_directory_action", "FM") end, }, }, separator = true, } } for k,v in FFIUtil.orderedPairs(self.shortcuts.data) do table.insert(sub_item_table, { text = k, callback = function() self:onBookShortcut(k) end, hold_callback = function(touchmenu_instance) UIManager:show(ConfirmBox:new{ text = _("Do you want to delete this shortcut?"), ok_text = _("Delete"), ok_callback = function() self:deleteShortcut(k) touchmenu_instance.item_table = self:getSubMenuItems() touchmenu_instance.page = 1 touchmenu_instance:updateItems() end, }) end, }) end return sub_item_table end function BookShortcuts:addShortcut(name) self.shortcuts.data[name] = true self.updated = true self:onDispatcherRegisterActions() end function BookShortcuts:deleteShortcut(name) self.shortcuts.data[name] = nil Dispatcher:removeAction(name) self.updated = true end return BookShortcuts
BookShortcuts: fix folders handling (#8795)
BookShortcuts: fix folders handling (#8795)
Lua
agpl-3.0
NiLuJe/koreader,koreader/koreader,NiLuJe/koreader,Frenzie/koreader,poire-z/koreader,Frenzie/koreader,koreader/koreader,poire-z/koreader
ad1c8044847b016e5214078ce7350d88d50e3128
AceGUI-3.0/widgets/AceGUIWidget-ScrollFrame.lua
AceGUI-3.0/widgets/AceGUIWidget-ScrollFrame.lua
local AceGUI = LibStub("AceGUI-3.0") -- Lua APIs local pairs, assert, type = pairs, assert, type local min, max, floor = math.min, math.max, math.floor -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent ------------- -- Widgets -- ------------- --[[ Widgets must provide the following functions Acquire() - Called when the object is aquired, should set everything to a default hidden state Release() - Called when the object is Released, should remove any anchors and hide the Widget And the following members frame - the frame or derivitive object that will be treated as the widget for size and anchoring purposes type - the type of the object, same as the name given to :RegisterWidget() Widgets contain a table called userdata, this is a safe place to store data associated with the wigdet It will be cleared automatically when a widget is released Placing values directly into a widget object should be avoided If the Widget can act as a container for other Widgets the following content - frame or derivitive that children will be anchored to The Widget can supply the following Optional Members ]] -------------------------- -- Scroll Frame -- -------------------------- do local Type = "ScrollFrame" local Version = 8 local function OnAcquire(self) end local function OnRelease(self) self.frame:ClearAllPoints() self.frame:Hide() self.status = nil -- do SetScroll after niling status, but before clearing localstatus -- so the scroll value isnt populated back into status, but not kept in localstatus either self:SetScroll(0) for k in pairs(self.localstatus) do self.localstatus[k] = nil end self.scrollframe:SetPoint("BOTTOMRIGHT",self.frame,"BOTTOMRIGHT",0,0) self.scrollbar:Hide() self.scrollBarShown = nil self.content.height, self.content.width = nil, nil end local function SetScroll(self, value) local status = self.status or self.localstatus local frame, child = self.scrollframe, self.content local viewheight = frame:GetHeight() local height = child:GetHeight() local offset if viewheight > height then offset = 0 else offset = floor((height - viewheight) / 1000.0 * value) end child:ClearAllPoints() child:SetPoint("TOPLEFT",frame,"TOPLEFT",0,offset) child:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,offset) status.offset = offset status.scrollvalue = value end local function MoveScroll(self, value) local status = self.status or self.localstatus local frame, child = self.scrollframe, self.content local height, viewheight = frame:GetHeight(), child:GetHeight() if height > viewheight then self.scrollbar:Hide() else self.scrollbar:Show() local diff = height - viewheight local delta = 1 if value < 0 then delta = -1 end self.scrollbar:SetValue(min(max(status.scrollvalue + delta*(1000/(diff/45)),0), 1000)) end end local function FixScroll(self) if self.updateLock then return end self.updateLock = true local status = self.status or self.localstatus local frame, child = self.scrollframe, self.content local height, viewheight = frame:GetHeight(), child:GetHeight() local offset = status.offset if not offset then offset = 0 end local curvalue = self.scrollbar:GetValue() if viewheight < height then if self.scrollBarShown then self.scrollBarShown = nil self.scrollbar:Hide() self.scrollbar:SetValue(0) self.scrollframe:SetPoint("BOTTOMRIGHT",self.frame,"BOTTOMRIGHT",0,0) self:DoLayout() end else if not self.scrollBarShown then self.scrollBarShown = true self.scrollbar:Show() self.scrollframe:SetPoint("BOTTOMRIGHT",self.frame,"BOTTOMRIGHT",-20,0) self:DoLayout() end local value = (offset / (viewheight - height) * 1000) if value > 1000 then value = 1000 end self.scrollbar:SetValue(value) self:SetScroll(value) if value < 1000 then child:ClearAllPoints() child:SetPoint("TOPLEFT",frame,"TOPLEFT",0,offset) child:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,offset) status.offset = offset end end self.updateLock = nil end local function OnMouseWheel(this,value) this.obj:MoveScroll(value) end local function OnScrollValueChanged(this, value) this.obj:SetScroll(value) end local function FixScrollOnUpdate(this) this:SetScript("OnUpdate", nil) this.obj:FixScroll() end local function OnSizeChanged(this) this:SetScript("OnUpdate", FixScrollOnUpdate) --this.obj:FixScroll() end local function LayoutFinished(self,width,height) self.content:SetHeight(height or 0 + 20) self:FixScroll() end -- called to set an external table to store status in local function SetStatusTable(self, status) assert(type(status) == "table") self.status = status if not status.scrollvalue then status.scrollvalue = 0 end end local createdcount = 0 local function OnWidthSet(self, width) local content = self.content content.width = width end local function OnHeightSet(self, height) local content = self.content content.height = height end local function Constructor() local frame = CreateFrame("Frame",nil,UIParent) local self = {} self.type = Type self.OnRelease = OnRelease self.OnAcquire = OnAcquire self.MoveScroll = MoveScroll self.FixScroll = FixScroll self.SetScroll = SetScroll self.LayoutFinished = LayoutFinished self.SetStatusTable = SetStatusTable self.OnWidthSet = OnWidthSet self.OnHeightSet = OnHeightSet self.localstatus = {} self.frame = frame frame.obj = self --Container Support local scrollframe = CreateFrame("ScrollFrame",nil,frame) local content = CreateFrame("Frame",nil,scrollframe) createdcount = createdcount + 1 local scrollbar = CreateFrame("Slider",("AceConfigDialogScrollFrame%dScrollBar"):format(createdcount),scrollframe,"UIPanelScrollBarTemplate") local scrollbg = scrollbar:CreateTexture(nil,"BACKGROUND") scrollbg:SetAllPoints(scrollbar) scrollbg:SetTexture(0,0,0,0.4) self.scrollframe = scrollframe self.content = content self.scrollbar = scrollbar scrollbar.obj = self scrollframe.obj = self content.obj = self scrollframe:SetScrollChild(content) scrollframe:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0) scrollframe:SetPoint("BOTTOMRIGHT",self.frame,"BOTTOMRIGHT",0,0) scrollframe:EnableMouseWheel(true) scrollframe:SetScript("OnMouseWheel", OnMouseWheel) scrollframe:SetScript("OnSizeChanged", OnSizeChanged) content:SetPoint("TOPLEFT",scrollframe,"TOPLEFT",0,0) content:SetPoint("TOPRIGHT",scrollframe,"TOPRIGHT",0,0) content:SetHeight(400) scrollbar:SetPoint("TOPLEFT",scrollframe,"TOPRIGHT",4,-16) scrollbar:SetPoint("BOTTOMLEFT",scrollframe,"BOTTOMRIGHT",4,16) scrollbar:SetScript("OnValueChanged", OnScrollValueChanged) scrollbar:SetMinMaxValues(0,1000) scrollbar:SetValueStep(1) scrollbar:SetValue(0) scrollbar:SetWidth(16) scrollbar:Hide() self.localstatus.scrollvalue = 0 --self:FixScroll() AceGUI:RegisterAsContainer(self) --AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
local AceGUI = LibStub("AceGUI-3.0") -- Lua APIs local pairs, assert, type = pairs, assert, type local min, max, floor = math.min, math.max, math.floor -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent ------------- -- Widgets -- ------------- --[[ Widgets must provide the following functions Acquire() - Called when the object is aquired, should set everything to a default hidden state Release() - Called when the object is Released, should remove any anchors and hide the Widget And the following members frame - the frame or derivitive object that will be treated as the widget for size and anchoring purposes type - the type of the object, same as the name given to :RegisterWidget() Widgets contain a table called userdata, this is a safe place to store data associated with the wigdet It will be cleared automatically when a widget is released Placing values directly into a widget object should be avoided If the Widget can act as a container for other Widgets the following content - frame or derivitive that children will be anchored to The Widget can supply the following Optional Members ]] -------------------------- -- Scroll Frame -- -------------------------- do local Type = "ScrollFrame" local Version = 9 local function OnAcquire(self) end local function OnRelease(self) self.frame:ClearAllPoints() self.frame:Hide() self.status = nil -- do SetScroll after niling status, but before clearing localstatus -- so the scroll value isnt populated back into status, but not kept in localstatus either self:SetScroll(0) for k in pairs(self.localstatus) do self.localstatus[k] = nil end self.scrollframe:SetPoint("BOTTOMRIGHT",self.frame,"BOTTOMRIGHT",0,0) self.scrollbar:Hide() self.scrollBarShown = nil self.content.height, self.content.width = nil, nil end local function SetScroll(self, value) local status = self.status or self.localstatus local viewheight = self.scrollframe:GetHeight() local height = self.content:GetHeight() local offset if viewheight > height then offset = 0 else offset = floor((height - viewheight) / 1000.0 * value) end self.content:ClearAllPoints() self.content:SetPoint("TOPLEFT", self.scrollframe, "TOPLEFT", 0, offset) self.content:SetPoint("TOPRIGHT", self.scrollframe, "TOPRIGHT", 0, offset) status.offset = offset status.scrollvalue = value end local function MoveScroll(self, value) local status = self.status or self.localstatus local height, viewheight = self.scrollframe:GetHeight(), self.content:GetHeight() if height > viewheight then self.scrollbar:Hide() else self.scrollbar:Show() local diff = height - viewheight local delta = 1 if value < 0 then delta = -1 end self.scrollbar:SetValue(min(max(status.scrollvalue + delta*(1000/(diff/45)),0), 1000)) end end local function FixScroll(self) if self.updateLock then return end self.updateLock = true local status = self.status or self.localstatus local height, viewheight = self.scrollframe:GetHeight(), self.content:GetHeight() local offset = status.offset or 0 local curvalue = self.scrollbar:GetValue() if viewheight < height then if self.scrollBarShown then self.scrollBarShown = nil self.scrollbar:Hide() self.scrollbar:SetValue(0) self.scrollframe:SetPoint("BOTTOMRIGHT",self.frame,"BOTTOMRIGHT",0,0) self:DoLayout() end else if not self.scrollBarShown then self.scrollBarShown = true self.scrollbar:Show() self.scrollframe:SetPoint("BOTTOMRIGHT", self.frame,"BOTTOMRIGHT",-20,0) self:DoLayout() end local value = (offset / (viewheight - height) * 1000) if value > 1000 then value = 1000 end self.scrollbar:SetValue(value) self:SetScroll(value) if value < 1000 then self.content:ClearAllPoints() self.content:SetPoint("TOPLEFT", self.scrollframe, "TOPLEFT", 0, offset) self.content:SetPoint("TOPRIGHT", self.scrollframe, "TOPRIGHT", 0, offset) status.offset = offset end end self.updateLock = nil end local function OnMouseWheel(this, value) this.obj:MoveScroll(value) end local function OnScrollValueChanged(this, value) this.obj:SetScroll(value) end local function FixScrollOnUpdate(this) this:SetScript("OnUpdate", nil) this.obj:FixScroll() end local function OnSizeChanged(this) this:SetScript("OnUpdate", FixScrollOnUpdate) end local function LayoutFinished(self, width, height) self.content:SetHeight(height or 0 + 20) self.scrollframe:SetScript("OnUpdate", FixScrollOnUpdate) end -- called to set an external table to store status in local function SetStatusTable(self, status) assert(type(status) == "table") self.status = status if not status.scrollvalue then status.scrollvalue = 0 end end local function OnWidthSet(self, width) local content = self.content content.width = width end local function OnHeightSet(self, height) local content = self.content content.height = height end local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) local self = {} self.type = Type self.OnRelease = OnRelease self.OnAcquire = OnAcquire self.MoveScroll = MoveScroll self.FixScroll = FixScroll self.SetScroll = SetScroll self.LayoutFinished = LayoutFinished self.SetStatusTable = SetStatusTable self.OnWidthSet = OnWidthSet self.OnHeightSet = OnHeightSet self.localstatus = {} self.frame = frame frame.obj = self --Container Support local scrollframe = CreateFrame("ScrollFrame", nil, frame) scrollframe.obj = self scrollframe:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, 0) scrollframe:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 0) scrollframe:EnableMouseWheel(true) scrollframe:SetScript("OnMouseWheel", OnMouseWheel) scrollframe:SetScript("OnSizeChanged", OnSizeChanged) self.scrollframe = scrollframe local content = CreateFrame("Frame", nil, scrollframe) content.obj = self content:SetPoint("TOPLEFT", scrollframe, "TOPLEFT", 0, 0) content:SetPoint("TOPRIGHT", scrollframe, "TOPRIGHT", 0, 0) content:SetHeight(400) self.content = content scrollframe:SetScrollChild(content) local num = AceGUI:GetNextWidgetNum(Type) local name = ("AceConfigDialogScrollFrame%dScrollBar"):format(num) local scrollbar = CreateFrame("Slider", name, scrollframe, "UIPanelScrollBarTemplate") scrollbar.obj = self scrollbar:SetPoint("TOPLEFT", scrollframe, "TOPRIGHT", 4, -16) scrollbar:SetPoint("BOTTOMLEFT", scrollframe, "BOTTOMRIGHT", 4, 16) scrollbar:SetScript("OnValueChanged", OnScrollValueChanged) scrollbar:SetMinMaxValues(0, 1000) scrollbar:SetValueStep(1) scrollbar:SetValue(0) scrollbar:SetWidth(16) scrollbar:Hide() self.scrollbar = scrollbar local scrollbg = scrollbar:CreateTexture(nil, "BACKGROUND") scrollbg:SetAllPoints(scrollbar) scrollbg:SetTexture(0, 0, 0, 0.4) self.localstatus.scrollvalue = 0 --self:FixScroll() AceGUI:RegisterAsContainer(self) --AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
AceGUI-3.0: ScrollFrame: Potentially fix an issue that caused the scrollframe to reset to top in certain resolution/UIScale combinations.
AceGUI-3.0: ScrollFrame: Potentially fix an issue that caused the scrollframe to reset to top in certain resolution/UIScale combinations. git-svn-id: e768786be8df873dac9515156656ebbdc6d77160@887 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
3a71e8a41eb4b7e9e9ad1109e6fbc1f22eb5ca82
src/docs/main.lua
src/docs/main.lua
local api = require 'love-api.love_api' local bodies = {} local enums = {} local maxWidth = 78 local contentWidth = 46 local index = '0.' local docName = 'love-' local function increment() index = index:gsub( '(.-)(%d+)%.$', function( a, b ) return a .. ( b + 1 ) .. '.' end ) end local function makeRef( str ) return str:gsub( '%-', '.' ) .. '' end local function rightAlign( ... ) local elements = { ... } local last = '' local width = maxWidth if elements[#elements] == true then table.remove( elements, #elements ) width = elements[#elements] table.remove( elements, #elements ) last = elements[#elements] elements[#elements] = ' ' end local length = width for i = 1, #elements - 1 do length = length - #elements[i] end return ( ( '%s' ):rep( #elements - 1 ) .. '%+' .. length .. 's' ):format( unpack( elements ) ) .. last end local function getLengthOfLongestLine( str ) local length = #str:match( '^([^\n]*)\n?' ) local last = #str:match( '\n?([^\n]*)$' ) length = length > last and length or last str:gsub( '%f[^\n].-%f[\n]', function( a ) length = #a > length and #a or length end ) return length end local function center( text ) local str = '' if type( text ) == 'string' then local longest = getLengthOfLongestLine( text ) text:gsub( 's*([^\n]+)\n?', function( a ) local len = math.floor( ( maxWidth - longest ) / 2 ) str = str .. ( ' ' ):rep( len ) .. a .. '\n' end ) else for i, v in ipairs( text ) do str = str .. center( v ) end end return str end local seps = { '==', '--', '--' } local function newSection( name, ref, shouldDotRef ) return ([[ %s %s ]]):format( seps[ ( select( 2, index:gsub( '%.', '' ) ) ) ]:rep( maxWidth / 2 ), rightAlign( name, ( shouldDotRef and makeRef or function( str ) return str end )( '*' .. docName .. ref .. '*' ) ) ) end local function printBodies() for i, v in ipairs( bodies ) do print( v[1] ) print( v[2] ) end end local function addContent( shouldDotRefs, ... ) local info = { ... } for i, v in ipairs( info ) do for ii = 1, #v, 4 do local vv = v[ii] if type( vv ) == 'string' then increment() local tabs = (' '):rep( 4 * select( 2, index:gsub( '(%.)', '%1' ) ) ) local ref = ( shouldDotRefs and makeRef or function( str ) return str end )( '|' .. docName .. v[2] .. '|' ) local name = ' ' .. v[1] print( rightAlign( tabs, index, name, ref, contentWidth, true ):gsub( '([%d%.%s]+%w+)(%s*)(%s|.*)', function( a, b, c ) return a .. ('.'):rep( #b ) .. c end ) .. '' ) table.insert( bodies, { newSection( index .. ' ' .. v[1], v[2], true ), ( v[3] or function() end )( v[1], v[2] ) } ) else index = index .. '0.' for subelement = ii, #v do addContent( v[subelement][4], v[subelement] ) end index = index:match( '^(.*%.)%d+%.$' ) break end end end end local function wrap( text, tabs, offset ) text = text .. ' ' tabs = tabs or '' local str = text:match( '^(.-%s)' ) local w = #str + ( offset or 0 ) text:gsub( '%f[%S].-%f[%s]', function( word ) word = word .. ' ' w = w + #word if w > maxWidth then w = #word word = '\n' .. tabs .. word end str = str .. word end ) return str:gsub( '~', ' ' ):sub( 1, -2 ) end local function shallowReturn( element ) local str = '\n' if not element then return 'None' else for i, v in ipairs( element ) do local temp = ( ' ' ):rep( 4 ) .. '- ' .. v.name local ref = '*' .. docName .. v.name .. '*' str = str .. rightAlign( temp, ref ) .. '\n' end return str:sub( 1, -2 ) end end local function makeVariant( index, tab, fail ) local str = '- ' .. index:gsub( '(.)(.*)', function( a, b ) return a:upper() .. b .. ':' end ) if tab[index] then for i, v in ipairs( tab[index] ) do str = str .. '\n' .. ( ' ' ):rep( 12 ).. wrap( '-~ ' .. v.name .. ': <' .. v.type .. '> ' .. v.description, ( ' ' ):rep( 14 ), 12 ) end str = str .. '\n' .. ( ' ' ):rep( 4 ) else str = str .. ' ' .. fail .. '\n ' end return str end local function generateVariants( tab ) local str = '\nVariants:\n' .. ( ' ' ):rep( 4 ) for i, v in ipairs( tab ) do str = str .. i .. ':\n' .. ( ' ' ):rep( 8 ) str = str .. makeVariant( 'arguments', v, 'None' ) .. ( ' ' ):rep( 4 ) .. makeVariant( 'returns', v, 'Nothing' ) end str = str:sub( 1, -6 ) return str end local function createFunctions( tab, funcs, n ) n = n and ( n ~= 'love' and n .. '.' ) or '' local new = {} for i, v in ipairs( funcs ) do local name = n .. v.name table.insert( new, { v.name, makeRef( name ), function() return wrap( v.description ) .. '\n' .. generateVariants( v.variants ) end, true } ) end table.insert( tab, new ) end local function prepend( parent, new ) for i, v in ipairs( new ) do table.insert( parent, i, v ) end end function love.load( a ) print( rightAlign( '*love.txt*', 'Documentation for the LOVE game framework version ' .. api.version .. '.' ), ( [[ %s %s]] ):format( center( [[ _ o__o __ __ ______ | | / __ \\ \ / // ____\ | | | | | |\ \ / / | |__ | | | | | | \ \/ / | __| | |____| |__| | \ / | |____ \______|\____/ \/ \______/ ]] ), center{ 'The complete solution for Vim with LOVE.', 'Includes highlighting and documentation.' } ) ) -- Get version string print( newSection( 'CONTENT', 'content' ) ) prepend( api.modules, { { name = 'love', description = 'General functions', functions = api.functions } } ) local tab = { 'Modules', 'modules', function() return 'The modules for LOVE, i.e. love.graphics' end, false } for i, v in ipairs( api.modules ) do table.insert( tab, { v.name, makeRef( v.name ), function() local str = v.description .. '\n\n' str = str .. '- Types: ' str = str .. shallowReturn( v.types ) str = str .. '\n- Enums: ' str = str .. shallowReturn( v.enums ) return str end, true } ) createFunctions( tab, v.functions, v.name ) end addContent( false, tab ) -- enums -- callbacks printBodies() end love.event.quit()
local api = require 'love-api.love_api' local bodies = {} local enums = {} local maxWidth = 78 local contentWidth = 46 local index = '0.' local docName = 'love-' local function increment() index = index:gsub( '(.-)(%d+)%.$', function( a, b ) return a .. ( b + 1 ) .. '.' end ) end local function makeRef( str ) return str:gsub( '%-', '.' ) .. '' end local function rightAlign( ... ) local elements = { ... } local last = '' local width = maxWidth if elements[#elements] == true then table.remove( elements, #elements ) width = elements[#elements] table.remove( elements, #elements ) last = elements[#elements] elements[#elements] = ' ' end local length = width for i = 1, #elements - 1 do length = length - #elements[i] end return ( ( '%s' ):rep( #elements - 1 ) .. '%+' .. length .. 's' ):format( unpack( elements ) ) .. last end local function getLengthOfLongestLine( str ) local length = #str:match( '^([^\n]*)\n?' ) local last = #str:match( '\n?([^\n]*)$' ) length = length > last and length or last str:gsub( '%f[^\n].-%f[\n]', function( a ) length = #a > length and #a or length end ) return length end local function center( text ) local str = '' if type( text ) == 'string' then local longest = getLengthOfLongestLine( text ) text:gsub( 's*([^\n]+)\n?', function( a ) local len = math.floor( ( maxWidth - longest ) / 2 ) str = str .. ( ' ' ):rep( len ) .. a .. '\n' end ) else for i, v in ipairs( text ) do str = str .. center( v ) end end return str end local seps = { '==', '--', '--' } local function newSection( name, ref, shouldDotRef ) return ([[ %s %s ]]):format( seps[ ( select( 2, index:gsub( '%.', '' ) ) ) ]:rep( maxWidth / 2 ), rightAlign( name, ( shouldDotRef and makeRef or function( str ) return str end )( '*' .. docName .. ref .. '*' ) ) ) end local function printBodies() for i, v in ipairs( bodies ) do print( v[1] ) print( v[2] ) end end local function addContent( shouldDotRefs, ... ) local info = { ... } for i, v in ipairs( info ) do for ii = 1, #v, 4 do local vv = v[ii] if type( vv ) == 'string' then increment() local tabs = (' '):rep( 4 * select( 2, index:gsub( '(%.)', '%1' ) ) ) local ref = ( shouldDotRefs and makeRef or function( str ) return str end )( '|' .. docName .. v[2] .. '|' ) local name = ' ' .. v[1] print( rightAlign( tabs, index, name, ref, contentWidth, true ):gsub( '([%d%.%s]+%w+)(%s*)(%s|.*)', function( a, b, c ) return a .. ('.'):rep( #b ) .. c end ) .. '' ) table.insert( bodies, { newSection( index .. ' ' .. v[1], v[2], true ), ( v[3] or function() end )( v[1], v[2] ) } ) else index = index .. '0.' for subelement = ii, #v do addContent( v[subelement][4], v[subelement] ) end index = index:match( '^(.*%.)%d+%.$' ) break end end end end local function wrap( text, tabs, offset ) text = text .. ' ' tabs = tabs or '' local str = text:match( '^(.-%s)' ) local w = #str + ( offset or 0 ) text:gsub( '%f[%S].-%f[%s]', function( word ) word = word .. ' ' w = w + #word if w > maxWidth then w = #word word = '\n' .. tabs .. word end str = str .. word end ) return str:gsub( '~', ' ' ):sub( 1, -2 ) end local function shallowReturn( element ) local str = '\n' if not element then return 'None' else for i, v in ipairs( element ) do local temp = ( ' ' ):rep( 4 ) .. '- ' .. v.name local ref = '*' .. docName .. v.name .. '*' str = str .. rightAlign( temp, ref ) .. '\n' end return str:sub( 1, -2 ) end end local function makeVariant( index, tab, fail ) local str = '- ' .. index:gsub( '(.)(.*)', function( a, b ) return a:upper() .. b .. ':' end ) if tab[index] then for i, v in ipairs( tab[index] ) do str = str .. '\n' .. ( ' ' ):rep( 12 ).. wrap( '-~ ' .. v.name .. ': <' .. v.type .. '> ' .. v.description, ( ' ' ):rep( 14 ), 12 ) end str = str .. '\n' .. ( ' ' ):rep( 4 ) else str = str .. ' ' .. fail .. '\n ' end return str end local function generateVariants( tab ) local str = '\nVariants:\n' .. ( ' ' ):rep( 4 ) for i, v in ipairs( tab ) do str = str .. i .. ':\n' .. ( ' ' ):rep( 8 ) str = str .. makeVariant( 'arguments', v, 'None' ) .. ( ' ' ):rep( 4 ) .. makeVariant( 'returns', v, 'Nothing' ) end str = str:sub( 1, -6 ) return str end local function createFunctions( tab, funcs, n ) n = n and ( n ~= 'love' and n .. '.' ) or '' local new = {} for i, v in ipairs( funcs ) do local name = n .. v.name table.insert( new, { v.name, makeRef( name ), function() return wrap( v.description ) .. '\n' .. generateVariants( v.variants ) end, true } ) end table.insert( tab, new ) end local function prepend( parent, new ) for i, v in ipairs( new ) do table.insert( parent, i, v ) end end function love.load( a ) print( rightAlign( '*love.txt*', 'Documentation for the LOVE game framework version ' .. api.version .. '.' ), ( [[ %s %s]] ):format( center( [[ _ o__o __ __ ______ | | / __ \\ \ / // ____\ | | | | | |\ \ / / | |__ | | | | | | \ \/ / | __| | |____| |__| | \ / | |____ \______|\____/ \/ \______/ ]] ), center{ 'The complete solution for Vim with LOVE.', 'Includes highlighting and documentation.' } ) ) -- Get version string print( newSection( 'CONTENT', 'content' ) ) prepend( api.modules, { { name = 'love', description = 'General functions', functions = api.functions } } ) local tab = { 'Modules', 'modules', function() return 'The modules for LOVE, i.e. love.graphics' end, false } for i, v in ipairs( api.modules ) do table.insert( tab, { v.name, makeRef( v.name ), function() local str = v.description .. '\n\n' str = str .. '- Types: ' str = str .. shallowReturn( v.types ) str = str .. '\n- Enums: ' str = str .. shallowReturn( v.enums ) return str end, true } ) createFunctions( tab, v.functions, v.name ) end addContent( false, tab ) -- enums -- callbacks printBodies() end love.event.quit()
Fixed spacing
Fixed spacing
Lua
mit
davisdude/vim-love-docs
df0f729c86fd74a997fb9a3f153bc739de1d675f
testserver/item/id_359_firefield.lua
testserver/item/id_359_firefield.lua
-- UPDATE common SET com_script='item.id_359_firefield' where com_itemid=359; -- How it works: AffectedRaces holds a list of all races that have non-standard effect (thus, consuming more than or less than 100% of damage from a field). -- AffectedStren holds a list of damage-percentages, 100 (which would be default anyway) means 100% and so on. The first entry in the Races-list corresponds -- to the first entry in the Stren-list, thus, these lists have to have EQUAL LENGTH!!!!!!!!!!!!!! require("base.common") module("item.id_359_firefield", package.seeall) function IniFireField() --Human, Dwarf, Halfling, Elf, Orc, Lizard, Drow, Troll, Mummy, Skeleton, Beholder, Blackbeholder, Transparentbeholder, Brownmummy, Bluemummy, Sheep, Spider, Redskeleton, Redspider, Greenspider, Bluespider, Pig, Brownpig, Transparentspider, Wesp, Redwesp, Stonegolem, Brownstonegolem, Redstonegolem, Silverstonegolem, Transparentstonegolem, Cow, Browncow, Wolf, Transparentwolf, Blackwolf, Greywolf, Redwolf, Redraptor, Silverbear, Blackbear, Bear, Raptor, Zombie, Hellhound, Imp, Irongolem, Ratman, Dog, Beetle, Fox, Slime, Chicken, Bonedragon, Blackbonedragon, Redbonedragon, Transparentbonedragon, Greenbonedragon, Bluebonedragon, Goldbonedragon, Redmummy, Greymummy, Blackmummy, Goldmummy, Transparentskeleton, Blueskeleton, Greenskeleton, Goldirongolem, Goldskeleton, Bluetroll, Blacktroll, Redtroll, Blackzombie, Transparentzombie, Redzombie, Blackhellhound, Transparenthellhound, Greenhellhound, Redhellhound, Redimp, Blackimp, Blueirongolem, Redratman, Greenratman, Blueratman, Reddog, Greydog, Blackdog, Greenbeetle, Copperbeetle, Redbeetle, Goldbeetle, Greyfox, Redslime, Blackslime, Transparentslime, Brownchicken, Redchicken, Blackchicken AffectedRaces={ 0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 17, 19, 20, 21, 22, 23, 26, 27, 29, 30, 31, 32, 33, 34, 39, 40, 41, 42, 43, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108}; AffectedStren={100, 80,100,100, 70,110,100,100,100,100,120, 40,100,100,100,100,100,200,130,110, 20,100, 10,100,100,100, 40,150,100, 30, 20,100,100, 0,100,100, 20,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100, 100, 100, 100, 100, 100, 100, 100, 100, 100}; end function CharacterOnField(User) -- geht los wenn ein Char auf das Feld tritt if (AffectedRaces==nil) then IniFireField(); -- Einmalige Initialisierung end if (User:increaseAttrib("hitpoints",0) == 0) then return end -- Flamme auf dem Feld suchen -- !!Eventuell gibt es Probleme, wenn sich mehrere Flammen auf einem Feld befinden!! local Items = base.common.GetItemsOnField(User.pos); local FieldItem; for i, item in pairs(Items) do if(item.id == 359) then FieldItem = item; break end end if (FieldItem.quality>100) and User.pos.z ~= 100 and User.pos.z ~= 101 and User.pos.z ~= 40 then --no harmful flames on noobia or the working camp local UserRace=User:getRace(); -- Char Rasse for i,theRace in pairs(AffectedRaces) do -- Rassenliste durchlaufen if UserRace==theRace then -- User Rasse finden found=true RaceStrenght=AffectedStren[i]; end end if not found or RaceStrenght==nil then RaceStrenght=100; end local resist=SpellResistence(User); -- Magie Resistenz prfen if (resist<FieldItem.quality*2) then -- Qualitt des Items --> Strke mit Magie Resistenz vergleichen debug("qual: "..FieldItem.quality.." resistens: "..resist.." RaceStrenght: "..RaceStrenght); local damageDealt=math.random((3/100)*math.floor((math.max(10,FieldItem.quality-resist))*RaceStrenght),(5/100)*math.floor((math.max(FieldItem.quality-resist))*RaceStrenght));--AffectedStren[i] debug("damage: "..damageDealt) User:increaseAttrib("hitpoints",-damageDealt); -- Schaden berechnen und bewirken -- Added by abcfantasy, inform user if (User:getPlayerLanguage()==0) then User:inform("Du fhlst, wie das glhend heie Feuer allmhlich deine Haut verbrennt."); else User:inform("You feel the scorching fire gradually burn your skin."); end else DeleteFlame(User,FieldItem); end else DeleteFlame(User,FieldItem); if (User:getPlayerLanguage()==0) then User:inform("Die Feuerflamme war nur eine Illusion und verpufft."); else User:inform("The fireflame was just an illusion and disappears."); end end end function SpellResistence(TargetChar) local TInt=TargetChar:increaseAttrib("intelligence",0); local TEss=TargetChar:increaseAttrib("essence",0); local TSkill=TargetChar:getSkill(Character.magicResistance); local ResTry=(((TSkill*2)+(TEss*2)+TInt)/300)*999; return math.max(0,math.min(999,math.floor(ResTry*(math.random(8,12)/10)))) end function DeleteFlame(User, FlameItem) local field = world:getField(User.pos); local count = field:countItems(); local currentitem; local items = { }; for i=0, count-1 do currentitem = world:getItemOnField(User.pos); world:erase(currentitem, currentitem.number); if(currentitem.id ~= FlameItem.id) then table.insert(items, currentitem); end end for i,item in pairs(items) do world:createItemFromItem(item, User.pos, true); end end
-- UPDATE common SET com_script='item.id_359_firefield' where com_itemid=359; -- How it works: AffectedRaces holds a list of all races that have non-standard effect (thus, consuming more than or less than 100% of damage from a field). -- AffectedStren holds a list of damage-percentages, 100 (which would be default anyway) means 100% and so on. The first entry in the Races-list corresponds -- to the first entry in the Stren-list, thus, these lists have to have EQUAL LENGTH!!!!!!!!!!!!!! require("base.common") module("item.id_359_firefield", package.seeall) function IniFireField() --Human, Dwarf, Halfling, Elf, Orc, Lizard, Drow, Troll, Mummy, Skeleton, Beholder, Blackbeholder, Transparentbeholder, Brownmummy, Bluemummy, Sheep, Spider, Redskeleton, Redspider, Greenspider, Bluespider, Pig, Brownpig, Transparentspider, Wesp, Redwesp, Stonegolem, Brownstonegolem, Redstonegolem, Silverstonegolem, Transparentstonegolem, Cow, Browncow, Wolf, Transparentwolf, Blackwolf, Greywolf, Redwolf, Redraptor, Silverbear, Blackbear, Bear, Raptor, Zombie, Hellhound, Imp, Irongolem, Ratman, Dog, Beetle, Fox, Slime, Chicken, Bonedragon, Blackbonedragon, Redbonedragon, Transparentbonedragon, Greenbonedragon, Bluebonedragon, Goldbonedragon, Redmummy, Greymummy, Blackmummy, Goldmummy, Transparentskeleton, Blueskeleton, Greenskeleton, Goldirongolem, Goldskeleton, Bluetroll, Blacktroll, Redtroll, Blackzombie, Transparentzombie, Redzombie, Blackhellhound, Transparenthellhound, Greenhellhound, Redhellhound, Redimp, Blackimp, Blueirongolem, Redratman, Greenratman, Blueratman, Reddog, Greydog, Blackdog, Greenbeetle, Copperbeetle, Redbeetle, Goldbeetle, Greyfox, Redslime, Blackslime, Transparentslime, Brownchicken, Redchicken, Blackchicken AffectedRaces={ 0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 17, 19, 20, 21, 22, 23, 26, 27, 29, 30, 31, 32, 33, 34, 39, 40, 41, 42, 43, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108}; AffectedStren={100, 80,100,100, 70,110,100,100,100,100,120, 40,100,100,100,100,100,200,130,110, 20,100, 10,100,100,100, 40,150,100, 30, 20,100,100, 0,100,100, 20,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100, 100, 100, 100, 100, 100, 100, 100, 100, 100}; end function CharacterOnField(User) -- geht los wenn ein Char auf das Feld tritt if (AffectedRaces==nil) then IniFireField(); -- Einmalige Initialisierung end if (User:increaseAttrib("hitpoints",0) == 0) then return end -- Flamme auf dem Feld suchen -- !!Eventuell gibt es Probleme, wenn sich mehrere Flammen auf einem Feld befinden!! local Items = base.common.GetItemsOnField(User.pos); local FieldItem; for i, item in pairs(Items) do if(item.id == 359) then FieldItem = item; break end end if (FieldItem.quality>100) and User.pos.z ~= 100 and User.pos.z ~= 101 and User.pos.z ~= 40 then --no harmful flames on noobia or the working camp local UserRace=User:getRace(); -- Char Rasse for i,theRace in pairs(AffectedRaces) do -- Rassenliste durchlaufen if UserRace==theRace then -- User Rasse finden found=true RaceStrenght=AffectedStren[i]; end end if not found or RaceStrenght==nil then RaceStrenght=100; end local resist=SpellResistence(User); -- Magie Resistenz prfen if (resist<FieldItem.quality*2) then -- Qualitt des Items --> Strke mit Magie Resistenz vergleichen local damageLow = (3/100)*math.floor((math.max(10,FieldItem.quality-resist))*RaceStrenght) local damageHigh = (5/100)*math.floor((math.max(FieldItem.quality-resist))*RaceStrenght) local damageDealt=math.random(math.min(damageLow,damageHigh),math.max(damageLow,damageHigh));--AffectedStren[i] User:increaseAttrib("hitpoints",-damageDealt); -- Schaden berechnen und bewirken -- Added by abcfantasy, inform user if (User:getPlayerLanguage()==0) then User:inform("Du fhlst, wie das glhend heie Feuer allmhlich deine Haut verbrennt."); else User:inform("You feel the scorching fire gradually burn your skin."); end else DeleteFlame(User,FieldItem); end else DeleteFlame(User,FieldItem); if (User:getPlayerLanguage()==0) then User:inform("Die Feuerflamme war nur eine Illusion und verpufft."); else User:inform("The fireflame was just an illusion and disappears."); end end end function SpellResistence(TargetChar) local TInt=TargetChar:increaseAttrib("intelligence",0); local TEss=TargetChar:increaseAttrib("essence",0); local TSkill=TargetChar:getSkill(Character.magicResistance); local ResTry=(((TSkill*2)+(TEss*2)+TInt)/300)*999; return math.max(0,math.min(999,math.floor(ResTry*(math.random(8,12)/10)))) end function DeleteFlame(User, FlameItem) local field = world:getField(User.pos); local count = field:countItems(); local currentitem; local items = { }; for i=0, count-1 do currentitem = world:getItemOnField(User.pos); world:erase(currentitem, currentitem.number); if(currentitem.id ~= FlameItem.id) then table.insert(items, currentitem); end end for i,item in pairs(items) do world:createItemFromItem(item, User.pos, true); end end
fix for random
fix for random
Lua
agpl-3.0
vilarion/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content
aa62d0d00f30f3fb3290d626f7f1b8b11b6ba356
openwrt/package/linkmeter/luasrc/luci/controller/linkmeter/lmdata.lua
openwrt/package/linkmeter/luasrc/luci/controller/linkmeter/lmdata.lua
module("luci.controller.linkmeter.lmdata", package.seeall) function index() entry({"lm", "hist"}, call("action_hist")).notemplate = true entry({"lm", "hmstatus"}, call("action_hmstatus")).notemplate = true entry({"lm", "rfstatus"}, call("action_rfstatus")).notemplate = true entry({"lm", "stream"}, call("action_stream")).notemplate = true entry({"lm", "conf"}, call("action_conf")).notemplate = true entry({"lm", "dluri"}, call("action_downloaduri")).notemplate = true end function lmclient_json(query, default) require "lmclient" local result, err = LmClient():query(query) result = result or default if result then luci.http.prepare_content("application/json") luci.http.header("Access-Control-Allow-Origin", "*") luci.http.write(result) return true else luci.dispatcher.error500("JSON read failed " .. query .. " error in " .. err) end end function action_hmstatus() return lmclient_json("$LMSU") end function action_rfstatus() return lmclient_json("$LMRF") end function action_conf() return lmclient_json("$LMCF", "{}") end function action_hist() local http = require "luci.http" local rrd = require "rrd" local uci = luci.model.uci.cursor() local RRD_FILE = http.formvalue("rrd") or uci:get("linkmeter", "daemon", "rrd_file") local nancnt = tonumber(http.formvalue("nancnt")) local start, step, data, soff if not nixio.fs.access(RRD_FILE) then http.status(503, "Database Unavailable") http.prepare_content("text/plain") http.write("No database: %q" % RRD_FILE) return end local now = rrd.last(RRD_FILE) if not nancnt then -- scroll through the data and find the first line that has data -- this should indicate the start of data recording on the largest -- step data. Then use that to determine the smallest step that -- includes all the data start, step, _, data = rrd.fetch(RRD_FILE, "AVERAGE", "--end", now) nancnt = 0 for _, dp in ipairs(data) do -- Output (dp[6]) should always be valid if the DB was capturing -- If val ~= val then val is a NaN, LUA doesn't have isnan() -- and NaN ~= NaN by C definition (platform-specific) if dp[6] == dp[6] then break end nancnt = nancnt + 1 end end if nancnt >= 460 then step = 10 soff = 3600 elseif nancnt >= 360 then step = 60 soff = 21600 elseif nancnt >= 240 then step = 120 soff = 43200 else step = 180 soff = 86400 end -- Make sure our end time falls on an exact previous or now time boundary now = math.floor(now/step) * step -- Only pull new data if the nancnt probe data isn't what we're looking for if step ~= 180 or not data then start, step, _, data = rrd.fetch(RRD_FILE, "AVERAGE", "--end", now, "--start", now - soff, "-r", step) end if http.formvalue("dl") == "1" then local csvfile = nixio.fs.basename(RRD_FILE:sub(1, -5)) .. ".csv" http.prepare_content("text/csv") http.header("Content-Disposition", 'attachment; filename="' .. csvfile ..'"') else http.prepare_content("text/plain") end http.header("Cache-Control", "max-age="..step) http.header("Access-Control-Allow-Origin", "*") if http.formvalue("hdr") == "1" then http.write("time,setpoint,probe0,probe1,probe2,probe3,output\n") end local seenData now = now - step for _, dp in ipairs(data) do -- Skip the first NaN rows until we actually have data and keep -- sending until we get to the 1 or 2 rows at the end that are NaN if (dp[6] == dp[6]) or (seenData and (start < now)) then http.write(("%u,%s\n"):format(start, table.concat(dp, ","))) seenData = true end start = start + step end end function action_stream() local http = require "luci.http" http.prepare_content("text/event-stream") require "lmclient" LmClient:stream("$LMSS", function (o) http.write(o) collectgarbage("collect") end) end function action_downloaduri() -- Takes a data URI input and converts it to a file download -- It is dumb that most browsers do not support saving a local data URI to file -- but this works around it by having the client generate the image and the server -- just sends it back to them. -- LuCI only supports POST data larger than 8KB in a multipart/form-data, be -- sure to use a form with encoding set to this. -- Field "uri" the data URI (including data: and metadata) -- Field "filename" (optional) filename to set as the attachment name local nixio = require "nixio" local http = require "luci.http" local mime = require "luci.http.protocol.mime" local uri = http.formvalue("uri") if (not uri or uri:sub(1, 5) ~= "data:") then http.status(400, "URI must begin with 'data:'") return end local comma = uri:find(',') if (not comma) then http.status(400, "URI missing metadata") return end local metadata = uri:sub(6, comma-1) local mimetype = "text/plain" local encoding = "" local charset = "US-ASCII" local matchcnt = 0 for meta in metadata:gmatch("[^;]+") do if matchcnt == 0 then mimetype = meta elseif meta:sub(1,8) == "charset=" then charset = meta:sub(9) else encoding = meta end matchcnt = matchcnt + 1 end local filename = http.formvalue("filename") or (os.date("%Y%m%d_%H%M%S.") .. (mime.to_ext(mimetype) or "txt")) http.prepare_content(mimetype) http.header('Content-Disposition', 'attachment; filename="' .. filename .. '"') if encoding == "base64" then uri = nixio.bin.b64decode(uri:sub(comma+1)) else uri = uri:sub(comma+1) end http.write(uri) end
module("luci.controller.linkmeter.lmdata", package.seeall) function index() entry({"lm", "hist"}, call("action_hist")).notemplate = true entry({"lm", "hmstatus"}, call("action_hmstatus")).notemplate = true entry({"lm", "rfstatus"}, call("action_rfstatus")).notemplate = true entry({"lm", "stream"}, call("action_stream")).notemplate = true entry({"lm", "conf"}, call("action_conf")).notemplate = true entry({"lm", "dluri"}, call("action_downloaduri")).notemplate = true end function lmclient_json(query, default) require "lmclient" local result, err = LmClient():query(query) result = result or default if result then luci.http.prepare_content("application/json") luci.http.header("Access-Control-Allow-Origin", "*") luci.http.write(result) return true else luci.dispatcher.error500("JSON read failed " .. query .. " error in " .. err) end end function action_hmstatus() return lmclient_json("$LMSU") end function action_rfstatus() return lmclient_json("$LMRF") end function action_conf() return lmclient_json("$LMCF", "{}") end function action_hist() local http = require("luci.http") local rrd = require("rrd") local uci = require("uci"):cursor() local RRD_FILE = http.formvalue("rrd") or uci:get("linkmeter", "daemon", "rrd_file") local nancnt = tonumber(http.formvalue("nancnt")) local start, step, data, soff if not nixio.fs.access(RRD_FILE) then http.status(503, "Database Unavailable") http.prepare_content("text/plain") http.write("No database: %q" % RRD_FILE) return end local now = rrd.last(RRD_FILE) if not nancnt then -- scroll through the data and find the first line that has data -- this should indicate the start of data recording on the largest -- step data. Then use that to determine the smallest step that -- includes all the data start, step, _, data = rrd.fetch(RRD_FILE, "AVERAGE", "--end", now) nancnt = 0 for _, dp in ipairs(data) do -- Output (dp[6]) should always be valid if the DB was capturing -- If val ~= val then val is a NaN, LUA doesn't have isnan() -- and NaN ~= NaN by C definition (platform-specific) if dp[6] == dp[6] then break end nancnt = nancnt + 1 end end if nancnt >= 460 then step = 10 soff = 3600 elseif nancnt >= 360 then step = 60 soff = 21600 elseif nancnt >= 240 then step = 120 soff = 43200 else step = 180 soff = 86400 end -- Make sure our end time falls on an exact previous or now time boundary now = math.floor(now/step) * step -- Only pull new data if the nancnt probe data isn't what we're looking for if step ~= 180 or not data then start, step, _, data = rrd.fetch(RRD_FILE, "AVERAGE", "--end", now, "--start", now - soff, "-r", step) end if http.formvalue("dl") == "1" then local csvfile = nixio.fs.basename(RRD_FILE:sub(1, -5)) .. ".csv" http.prepare_content("text/csv") http.header("Content-Disposition", 'attachment; filename="' .. csvfile ..'"') else http.prepare_content("text/plain") end if uci:get("linkmeter", "api", "allowcors") == "1" then http.header("Access-Control-Allow-Origin", "*") end http.header("Cache-Control", "max-age="..step) if http.formvalue("hdr") == "1" then http.write("time,setpoint,probe0,probe1,probe2,probe3,output\n") end local seenData now = now - step for _, dp in ipairs(data) do -- Skip the first NaN rows until we actually have data and keep -- sending until we get to the 1 or 2 rows at the end that are NaN if (dp[6] == dp[6]) or (seenData and (start < now)) then http.write(("%u,%s\n"):format(start, table.concat(dp, ","))) seenData = true end start = start + step end end function action_stream() local http = require("luci.http") local uci = require("uci"):cursor() http.prepare_content("text/event-stream") if uci:get("linkmeter", "api", "allowcors") == "1" then http.header("Access-Control-Allow-Origin", "*") end require("lmclient") LmClient:stream("$LMSS", function (o) http.write(o) collectgarbage("collect") end) end function action_downloaduri() -- Takes a data URI input and converts it to a file download -- It is dumb that most browsers do not support saving a local data URI to file -- but this works around it by having the client generate the image and the server -- just sends it back to them. -- LuCI only supports POST data larger than 8KB in a multipart/form-data, be -- sure to use a form with encoding set to this. -- Field "uri" the data URI (including data: and metadata) -- Field "filename" (optional) filename to set as the attachment name local nixio = require "nixio" local http = require "luci.http" local mime = require "luci.http.protocol.mime" local uri = http.formvalue("uri") if (not uri or uri:sub(1, 5) ~= "data:") then http.status(400, "URI must begin with 'data:'") return end local comma = uri:find(',') if (not comma) then http.status(400, "URI missing metadata") return end local metadata = uri:sub(6, comma-1) local mimetype = "text/plain" local encoding = "" local charset = "US-ASCII" local matchcnt = 0 for meta in metadata:gmatch("[^;]+") do if matchcnt == 0 then mimetype = meta elseif meta:sub(1,8) == "charset=" then charset = meta:sub(9) else encoding = meta end matchcnt = matchcnt + 1 end local filename = http.formvalue("filename") or (os.date("%Y%m%d_%H%M%S.") .. (mime.to_ext(mimetype) or "txt")) http.prepare_content(mimetype) http.header('Content-Disposition', 'attachment; filename="' .. filename .. '"') if encoding == "base64" then uri = nixio.bin.b64decode(uri:sub(comma+1)) else uri = uri:sub(comma+1) end http.write(uri) end
[lm] Enable CORS on /lm/stream and /lm/hist if allowcors is set. Fixes #53
[lm] Enable CORS on /lm/stream and /lm/hist if allowcors is set. Fixes #53
Lua
mit
CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter
4bfff3f7d3e6f317e0afe6306766071aa53e5ad8
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") m = Map("system", translate("system"), translate("a_s_desc")) s = m:section(TypedSection, "system", "") s.anonymous = true local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:option(DummyValue, "_system", translate("system")).value = system s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() s:option(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:option(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") s:option(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end s:option(Value, "log_size", nil, "kiB").optional = true s:option(Value, "log_ip").optional = true s:option(Value, "conloglevel").optional = true s:option(Value, "cronloglevel").optional = true return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") m = Map("system", translate("system"), translate("a_s_desc")) s = m:section(TypedSection, "system", "") s.anonymous = true local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:option(DummyValue, "_system", translate("system")).value = system s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() s:option(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:option(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("mem_cached", "")), 100 * membuffers / memtotal, tostring(translate("mem_buffered", "")), 100 * memfree / memtotal, tostring(translate("mem_free", "")) s:option(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end s:option(Value, "log_size", nil, "kiB").optional = true s:option(Value, "log_ip").optional = true s:option(Value, "conloglevel").optional = true s:option(Value, "cronloglevel").optional = true return m
modules/admin-full: fix udata vs. string in system.lua model
modules/admin-full: fix udata vs. string in system.lua model git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5148 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
a69667b67ff5f3009ecf18e08b3403b9f6b3ac09
etc/ioncorelib.lua
etc/ioncorelib.lua
-- -- Ioncore Lua library -- -- {{{Constants TRUE = true FALSE = false -- }}} -- {{{Functions to help construct bindmaps function submap2(kcb_, list) return {action = "kpress", kcb = kcb_, submap = list} end function submap(kcb_) local function submap_helper(list) return submap2(kcb_, list) end return submap_helper end function kpress(kcb_, func_) return {action = "kpress", kcb = kcb_, func = func_} end function kpress_waitrel(kcb_, func_) return {action = "kpress_waitrel", kcb = kcb_, func = func_} end function mact(act_, kcb_, func_, area_) local ret={ action = act_, kcb = kcb_, func = func_ } if area_ ~= nil then ret.area = area_ end return ret end function mclick(kcb_, func_, area_) return mact("mclick", kcb_, func_, area_) end function mdrag(kcb_, func_, area_) return mact("mdrag", kcb_, func_, area_) end function mdblclick(kcb_, func_, area_) return mact("mdblclick", kcb_, func_, area_) end function mpress(kcb_, func_, area_) return mact("mpress", kcb_, func_, area_) end -- }}} -- {{{Callback creation functions function make_active_leaf_fn(fn) if not fn then error("fn==nil", 2) end local function call_active_leaf(reg) lf=region_get_active_leaf(reg) fn(lf) end return call_active_leaf end function make_screen_switch_nth_fn(n) local function call_nth(scr) screen_switch_nth_on_cvp(scr, n) end return call_nth end function make_exec_fn(cmd) local function do_exec(scr) return exec_on_screen(scr, cmd) end return do_exec end -- {{{ Includes function include(file) local current_dir = "." if CURRENT_FILE ~= nil then local s, e, cdir, cfile=string.find(CURRENT_FILE, "(.*)([^/])"); if cdir ~= nil then current_dir = cdir end end -- do_include is implemented in ioncore. do_include(file, current_dir) end -- }}} -- {{{Winprops winprops={} function alternative_winprop_idents(id) local function g() for _, c in {id.class, "*"} do for _, r in {id.role, "*"} do for _, i in {id.instance, "*"} do coroutine.yield(c, r, i) end end end end return coroutine.wrap(g) end function get_winprop(cwin) local id=clientwin_get_ident(cwin) for c, r, i in alternative_winprops_idents(id) do if pcall(function() prop=winprops[c][r][i] end) then if prop then return prop end end end end function ensure_winproptab(class, role, instance) if not winprops[class] then winprops[class]={} end if not winprops[class][role] then winprops[class][role]={} end end function do_add_winprop(class, role, instance, props) ensure_winproptab(class, role, instance) print("add winprop ", class, role, instance) winprops[class][role][instance]=props end function winprop(list) local list2, class, role, instance = {}, "*", "*", "*" for k, v in list do if k == "class" then class = v elseif k == "role" then role = v elseif k == "instance" then instance = v else list2[k] = v end end do_add_winprop(class, role, instance, list2) end -- }}} -- {{{ Misc function obj_exists(obj) return (obj_typename(obj)==nil) end -- }}}
-- -- Ioncore Lua library -- -- {{{Constants TRUE = true FALSE = false -- }}} -- {{{Functions to help construct bindmaps function submap2(kcb_, list) return {action = "kpress", kcb = kcb_, submap = list} end function submap(kcb_) local function submap_helper(list) return submap2(kcb_, list) end return submap_helper end function kpress(kcb_, func_) return {action = "kpress", kcb = kcb_, func = func_} end function kpress_waitrel(kcb_, func_) return {action = "kpress_waitrel", kcb = kcb_, func = func_} end function mact(act_, kcb_, func_, area_) local ret={ action = act_, kcb = kcb_, func = func_ } if area_ ~= nil then ret.area = area_ end return ret end function mclick(kcb_, func_, area_) return mact("mclick", kcb_, func_, area_) end function mdrag(kcb_, func_, area_) return mact("mdrag", kcb_, func_, area_) end function mdblclick(kcb_, func_, area_) return mact("mdblclick", kcb_, func_, area_) end function mpress(kcb_, func_, area_) return mact("mpress", kcb_, func_, area_) end -- }}} -- {{{Callback creation functions function make_active_leaf_fn(fn) if not fn then error("fn==nil", 2) end local function call_active_leaf(reg) lf=region_get_active_leaf(reg) fn(lf) end return call_active_leaf end function make_screen_switch_nth_fn(n) local function call_nth(scr) screen_switch_nth_on_cvp(scr, n) end return call_nth end function make_exec_fn(cmd) local function do_exec(scr) return exec_on_screen(scr, cmd) end return do_exec end -- {{{ Includes function include(file) local current_dir = "." if CURRENT_FILE ~= nil then local s, e, cdir, cfile=string.find(CURRENT_FILE, "(.*)([^/])"); if cdir ~= nil then current_dir = cdir end end -- do_include is implemented in ioncore. do_include(file, current_dir) end -- }}} -- {{{Winprops winprops={} function alternative_winprop_idents(id) local function g() for _, c in {id.class, "*"} do for _, r in {id.role, "*"} do for _, i in {id.instance, "*"} do coroutine.yield(c, r, i) end end end end return coroutine.wrap(g) end function get_winprop(cwin) local id=clientwin_get_ident(cwin) for c, r, i in alternative_winprop_idents(id) do if pcall(function() prop=winprops[c][r][i] end) then if prop then return prop end end end end function ensure_winproptab(class, role, instance) if not winprops[class] then winprops[class]={} end if not winprops[class][role] then winprops[class][role]={} end end function do_add_winprop(class, role, instance, props) ensure_winproptab(class, role, instance) winprops[class][role][instance]=props end function winprop(list) local list2, class, role, instance = {}, "*", "*", "*" for k, v in list do if k == "class" then class = v elseif k == "role" then role = v elseif k == "instance" then instance = v else list2[k] = v end end do_add_winprop(class, role, instance, list2) end -- }}} -- {{{ Misc function obj_exists(obj) return (obj_typename(obj)==nil) end -- }}}
trunk: changeset 453
trunk: changeset 453 minor fixes darcs-hash:20030419201148-e481e-2ee1f282ff3b1af04b964e827baff87e81ddd1cf.gz
Lua
lgpl-2.1
p5n/notion,neg-serg/notion,raboof/notion,raboof/notion,knixeur/notion,anoduck/notion,knixeur/notion,p5n/notion,p5n/notion,knixeur/notion,dkogan/notion.xfttest,anoduck/notion,anoduck/notion,knixeur/notion,neg-serg/notion,dkogan/notion,dkogan/notion.xfttest,knixeur/notion,p5n/notion,dkogan/notion.xfttest,dkogan/notion,neg-serg/notion,dkogan/notion,dkogan/notion,raboof/notion,raboof/notion,anoduck/notion,neg-serg/notion,anoduck/notion,dkogan/notion,p5n/notion,dkogan/notion.xfttest
0be2443e92619e930dae2324e4216f1c161de3f1
src/program/snabbnfv/traffic/traffic.lua
src/program/snabbnfv/traffic/traffic.lua
module(..., package.seeall) local lib = require("core.lib") local nfvconfig = require("program.snabbnfv.nfvconfig") local usage = require("program.snabbnfv.traffic.README_inc") local ffi = require("ffi") local C = ffi.C local timer = require("core.timer") local pci = require("lib.hardware.pci") local long_opts = { benchmark = "B", help = "h", ["link-report-interval"] = "k", ["load-report-interval"] = "l", ["debug-report-interval"] = "D", ["long-help"] = "H" } function run (args) local opt = {} local benchpackets local linkreportinterval = 0 local loadreportinterval = 1 local debugreportinterval = 0 function opt.B (arg) benchpackets = tonumber(arg) end function opt.h (arg) print(short_usage()) main.exit(1) end function opt.H (arg) print(long_usage()) main.exit(1) end function opt.k (arg) linkreportinterval = tonumber(arg) end function opt.l (arg) loadreportinterval = tonumber(arg) end function opt.D (arg) debugreportinterval = tonumber(arg) end args = lib.dogetopt(args, opt, "hHB:k:l:D:", long_opts) if #args == 3 then local pciaddr, confpath, sockpath = unpack(args) local ok, info = pcall(pci.device_info, pciaddr) if not ok then print("Error: device not found " .. pciaddr) os.exit(1) end if not info.driver then print("Error: no driver for device " .. pciaddr) os.exit(1) end if loadreportinterval > 0 then local t = timer.new("nfvloadreport", engine.report_load, loadreportinterval*1e9, 'repeating') timer.activate(t) end if linkreportinterval > 0 then local t = timer.new("nfvlinkreport", engine.report_links, linkreportinterval*1e9, 'repeating') timer.activate(t) end if debugreportinterval > 0 then local t = timer.new("nfvdebugreport", engine.report_apps, debugreportinterval*1e9, 'repeating') timer.activate(t) end if benchpackets then print("snabbnfv traffic starting (benchmark mode)") bench(pciaddr, confpath, sockpath, benchpackets) else print("snabbnfv traffic starting") traffic(pciaddr, confpath, sockpath) end else print("Wrong number of arguments: " .. tonumber(#args)) print() print(short_usage()) main.exit(1) end end function short_usage () return (usage:gsub("%s*CONFIG FILE FORMAT:.*", "")) end function long_usage () return usage end -- Run in real traffic mode. function traffic (pciaddr, confpath, sockpath) engine.log = true local mtime = 0 while true do local mtime2 = C.stat_mtime(confpath) if mtime2 ~= mtime then print("Loading " .. confpath) engine.configure(nfvconfig.load(confpath, pciaddr, sockpath)) mtime = mtime2 end engine.main({duration=1, no_report=true}) -- Flush buffered log messages every 1s io.flush() end end -- Run in benchmark mode. function bench (pciaddr, confpath, sockpath, npackets) npackets = tonumber(npackets) local ports = dofile(confpath) local nic = (nfvconfig.port_name(ports[1])).."_NIC" engine.log = true engine.Hz = false print("Loading " .. confpath) engine.configure(nfvconfig.load(confpath, pciaddr, sockpath)) -- From designs/nfv local start, packets, bytes = 0, 0, 0 local done = function () local input = link.stats(engine.app_table[nic].input.rx) if start == 0 and input.rxpackets > 0 then -- started receiving, record time and packet count packets = input.rxpackets bytes = input.rxbytes start = C.get_monotonic_time() if os.getenv("NFV_PROF") then require("jit.p").start(os.getenv("NFV_PROF"), os.getenv("NFV_PROF_FILE")) else print("No LuaJIT profiling enabled ($NFV_PROF unset).") end if os.getenv("NFV_DUMP") then require("jit.dump").start(os.getenv("NFV_DUMP"), os.getenv("NFV_DUMP_FILE")) main.dumping = true else print("No LuaJIT dump enabled ($NFV_DUMP unset).") end end return input.rxpackets - packets >= npackets end engine.main({done = done, no_report = true}) local finish = C.get_monotonic_time() local runtime = finish - start local input = link.stats(engine.app_table[nic].input.rx) packets = input.rxpackets - packets bytes = input.rxbytes - bytes engine.report() print() print(("Processed %.1f million packets in %.2f seconds (%d bytes; %.2f Gbps)"):format(packets / 1e6, runtime, bytes, bytes * 8.0 / 1e9 / runtime)) print(("Made %s breaths: %.2f packets per breath; %.2fus per breath"):format(lib.comma_value(engine.breaths), packets / engine.breaths, runtime / engine.breaths * 1e6)) print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6)) require("jit.p").stop() end
module(..., package.seeall) local lib = require("core.lib") local nfvconfig = require("program.snabbnfv.nfvconfig") local usage = require("program.snabbnfv.traffic.README_inc") local ffi = require("ffi") local C = ffi.C local timer = require("core.timer") local pci = require("lib.hardware.pci") local counter = require("core.counter") local long_opts = { benchmark = "B", help = "h", ["link-report-interval"] = "k", ["load-report-interval"] = "l", ["debug-report-interval"] = "D", ["long-help"] = "H" } function run (args) local opt = {} local benchpackets local linkreportinterval = 0 local loadreportinterval = 1 local debugreportinterval = 0 function opt.B (arg) benchpackets = tonumber(arg) end function opt.h (arg) print(short_usage()) main.exit(1) end function opt.H (arg) print(long_usage()) main.exit(1) end function opt.k (arg) linkreportinterval = tonumber(arg) end function opt.l (arg) loadreportinterval = tonumber(arg) end function opt.D (arg) debugreportinterval = tonumber(arg) end args = lib.dogetopt(args, opt, "hHB:k:l:D:", long_opts) if #args == 3 then local pciaddr, confpath, sockpath = unpack(args) local ok, info = pcall(pci.device_info, pciaddr) if not ok then print("Error: device not found " .. pciaddr) os.exit(1) end if not info.driver then print("Error: no driver for device " .. pciaddr) os.exit(1) end if loadreportinterval > 0 then local t = timer.new("nfvloadreport", engine.report_load, loadreportinterval*1e9, 'repeating') timer.activate(t) end if linkreportinterval > 0 then local t = timer.new("nfvlinkreport", engine.report_links, linkreportinterval*1e9, 'repeating') timer.activate(t) end if debugreportinterval > 0 then local t = timer.new("nfvdebugreport", engine.report_apps, debugreportinterval*1e9, 'repeating') timer.activate(t) end if benchpackets then print("snabbnfv traffic starting (benchmark mode)") bench(pciaddr, confpath, sockpath, benchpackets) else print("snabbnfv traffic starting") traffic(pciaddr, confpath, sockpath) end else print("Wrong number of arguments: " .. tonumber(#args)) print() print(short_usage()) main.exit(1) end end function short_usage () return (usage:gsub("%s*CONFIG FILE FORMAT:.*", "")) end function long_usage () return usage end -- Run in real traffic mode. function traffic (pciaddr, confpath, sockpath) engine.log = true local mtime = 0 while true do local mtime2 = C.stat_mtime(confpath) if mtime2 ~= mtime then print("Loading " .. confpath) engine.configure(nfvconfig.load(confpath, pciaddr, sockpath)) mtime = mtime2 end engine.main({duration=1, no_report=true}) -- Flush buffered log messages every 1s io.flush() end end -- Run in benchmark mode. function bench (pciaddr, confpath, sockpath, npackets) npackets = tonumber(npackets) local ports = dofile(confpath) local nic = (nfvconfig.port_name(ports[1])).."_NIC" engine.log = true engine.Hz = false print("Loading " .. confpath) engine.configure(nfvconfig.load(confpath, pciaddr, sockpath)) -- From designs/nfv local start, packets, bytes = 0, 0, 0 local done = function () local input = link.stats(engine.app_table[nic].input.rx) if start == 0 and input.rxpackets > 0 then -- started receiving, record time and packet count packets = input.rxpackets bytes = input.rxbytes start = C.get_monotonic_time() if os.getenv("NFV_PROF") then require("jit.p").start(os.getenv("NFV_PROF"), os.getenv("NFV_PROF_FILE")) else print("No LuaJIT profiling enabled ($NFV_PROF unset).") end if os.getenv("NFV_DUMP") then require("jit.dump").start(os.getenv("NFV_DUMP"), os.getenv("NFV_DUMP_FILE")) main.dumping = true else print("No LuaJIT dump enabled ($NFV_DUMP unset).") end end return input.rxpackets - packets >= npackets end engine.main({done = done, no_report = true}) local finish = C.get_monotonic_time() local runtime = finish - start local breaths = tonumber(counter.read(engine.breaths)) local input = link.stats(engine.app_table[nic].input.rx) packets = input.rxpackets - packets bytes = input.rxbytes - bytes engine.report() print() print(("Processed %.1f million packets in %.2f seconds (%d bytes; %.2f Gbps)"):format(packets / 1e6, runtime, bytes, bytes * 8.0 / 1e9 / runtime)) print(("Made %s breaths: %.2f packets per breath; %.2fus per breath"):format(lib.comma_value(breaths), packets / breaths, runtime / breaths * 1e6)) print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6)) require("jit.p").stop() end
[snabbnfv traffic] Fix bug where in benchmark mode, engine.breaths was attempted to be accessed directly.
[snabbnfv traffic] Fix bug where in benchmark mode, engine.breaths was attempted to be accessed directly.
Lua
apache-2.0
eugeneia/snabb,Igalia/snabb,heryii/snabb,plajjan/snabbswitch,justincormack/snabbswitch,eugeneia/snabb,dpino/snabbswitch,alexandergall/snabbswitch,wingo/snabbswitch,dpino/snabb,justincormack/snabbswitch,mixflowtech/logsensor,Igalia/snabbswitch,dpino/snabbswitch,snabbnfv-goodies/snabbswitch,Igalia/snabb,snabbco/snabb,kellabyte/snabbswitch,dpino/snabb,snabbco/snabb,dpino/snabb,SnabbCo/snabbswitch,pirate/snabbswitch,dpino/snabb,Igalia/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,heryii/snabb,dwdm/snabbswitch,lukego/snabb,kellabyte/snabbswitch,mixflowtech/logsensor,dpino/snabb,snabbco/snabb,hb9cwp/snabbswitch,justincormack/snabbswitch,snabbco/snabb,mixflowtech/logsensor,justincormack/snabbswitch,lukego/snabb,lukego/snabbswitch,eugeneia/snabb,andywingo/snabbswitch,plajjan/snabbswitch,kellabyte/snabbswitch,dpino/snabb,xdel/snabbswitch,alexandergall/snabbswitch,pirate/snabbswitch,fhanik/snabbswitch,Igalia/snabb,eugeneia/snabb,pavel-odintsov/snabbswitch,lukego/snabb,aperezdc/snabbswitch,Igalia/snabbswitch,snabbnfv-goodies/snabbswitch,snabbco/snabb,Igalia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,kbara/snabb,snabbnfv-goodies/snabbswitch,andywingo/snabbswitch,alexandergall/snabbswitch,plajjan/snabbswitch,aperezdc/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,Igalia/snabb,eugeneia/snabb,eugeneia/snabbswitch,wingo/snabbswitch,aperezdc/snabbswitch,xdel/snabbswitch,wingo/snabb,Igalia/snabbswitch,kbara/snabb,xdel/snabbswitch,wingo/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,hb9cwp/snabbswitch,plajjan/snabbswitch,Igalia/snabb,fhanik/snabbswitch,wingo/snabb,snabbnfv-goodies/snabbswitch,Igalia/snabb,mixflowtech/logsensor,wingo/snabb,kbara/snabb,snabbco/snabb,lukego/snabbswitch,Igalia/snabb,wingo/snabbswitch,wingo/snabb,alexandergall/snabbswitch,kbara/snabb,eugeneia/snabbswitch,heryii/snabb,dpino/snabbswitch,wingo/snabb,hb9cwp/snabbswitch,pirate/snabbswitch,mixflowtech/logsensor,hb9cwp/snabbswitch,dwdm/snabbswitch,wingo/snabb,kbara/snabb,aperezdc/snabbswitch,andywingo/snabbswitch,eugeneia/snabb,pavel-odintsov/snabbswitch,dpino/snabb,kbara/snabb,fhanik/snabbswitch,heryii/snabb,dpino/snabbswitch,eugeneia/snabbswitch,pavel-odintsov/snabbswitch,alexandergall/snabbswitch,dwdm/snabbswitch,lukego/snabb,andywingo/snabbswitch,lukego/snabbswitch,snabbco/snabb,lukego/snabbswitch,heryii/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabbswitch
d962c289947f12000b3b6aa5c88280427bd04d4e
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
require "luci.sys" require "luci.tools.webadmin" local bit = require "bit" local uci = luci.model.uci.cursor_state() local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and uci:get("firewall", ffzone, "network") local ffwifs = ffznet and luci.util.split(ffznet, " ") or {} -- System -- f = SimpleForm("system", "System") f.submit = false f.reset = false local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() f:field(DummyValue, "_system", translate("system")).value = system f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() f:field(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) f:field(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") f:field(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") f:field(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) -- Wireless -- local wireless = uci:get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" and ( luci.util.contains(ffwifs, v.device) or ( #ffwifs == 0 and (not v.encryption or v.encryption == "none") ) ) then table.insert(ifaces, v) end end m = SimpleForm("wireless", "Freifunk WLAN") m.submit = false m.reset = false s = m:section(Table, ifaces, translate("networks")) link = s:option(DummyValue, "_link", translate("link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("mode")) encryption = s:option(DummyValue, "encryption", translate("iwscan_encr")) power = s:option(DummyValue, "_power", translate("power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("iwscan_link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("mode")) chan = t2:option(DummyValue, "channel", translate("channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("iwscan_encr")) t2:option(DummyValue, "Signal level", translate("iwscan_signal")) t2:option(DummyValue, "Noise level", translate("iwscan_noise")) -- Routes -- r = SimpleForm("routes", "Standardrouten") r.submit = false r.reset = false local routes = {} for i, route in ipairs(luci.sys.net.routes()) do if route.dest:prefix() == 0 then routes[#routes+1] = route end end v = r:section(Table, routes) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end local routes6 = {} for i, route in ipairs(luci.sys.net.routes6() or {}) do if route.dest:prefix() == 0 then routes6[#routes6+1] = route end end if #routes6 > 0 then v6 = r:section(Table, routes6) net = v6:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes6[section].device) or routes6[section].device end target = v6:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v6:option(DummyValue, "gateway6", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v6:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) local metr = routes6[section].metric local lower = bit.band(metr, 0xffff) local higher = bit.rshift(bit.band(metr, 0xffff0000), 16) return "%04X%04X" % {higher, lower} end end return f, m, r
require "luci.sys" require "luci.tools.webadmin" local bit = require "bit" local uci = luci.model.uci.cursor_state() local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and uci:get("firewall", ffzone, "network") local ffwifs = ffznet and luci.util.split(ffznet, " ") or {} -- System -- f = SimpleForm("system", "System") f.submit = false f.reset = false local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() f:field(DummyValue, "_system", translate("system")).value = system f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() f:field(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) f:field(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("mem_cached"), "")), 100 * membuffers / memtotal, tostring(translate("mem_buffered", "")), 100 * memfree / memtotal, tostring(translate("mem_free", "")) f:field(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") f:field(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) -- Wireless -- local wireless = uci:get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" and ( luci.util.contains(ffwifs, v.device) or ( #ffwifs == 0 and (not v.encryption or v.encryption == "none") ) ) then table.insert(ifaces, v) end end m = SimpleForm("wireless", "Freifunk WLAN") m.submit = false m.reset = false s = m:section(Table, ifaces, translate("networks")) link = s:option(DummyValue, "_link", translate("link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("mode")) encryption = s:option(DummyValue, "encryption", translate("iwscan_encr")) power = s:option(DummyValue, "_power", translate("power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("iwscan_link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("mode")) chan = t2:option(DummyValue, "channel", translate("channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("iwscan_encr")) t2:option(DummyValue, "Signal level", translate("iwscan_signal")) t2:option(DummyValue, "Noise level", translate("iwscan_noise")) -- Routes -- r = SimpleForm("routes", "Standardrouten") r.submit = false r.reset = false local routes = {} for i, route in ipairs(luci.sys.net.routes()) do if route.dest:prefix() == 0 then routes[#routes+1] = route end end v = r:section(Table, routes) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end local routes6 = {} for i, route in ipairs(luci.sys.net.routes6() or {}) do if route.dest:prefix() == 0 then routes6[#routes6+1] = route end end if #routes6 > 0 then v6 = r:section(Table, routes6) net = v6:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes6[section].device) or routes6[section].device end target = v6:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v6:option(DummyValue, "gateway6", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v6:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) local metr = routes6[section].metric local lower = bit.band(metr, 0xffff) local higher = bit.rshift(bit.band(metr, 0xffff0000), 16) return "%04X%04X" % {higher, lower} end end return f, m, r
modules/freifunk: fix same problem
modules/freifunk: fix same problem git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5150 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
phi-psi/luci,jschmidlapp/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,eugenesan/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,jschmidlapp/luci,projectbismark/luci-bismark,Canaan-Creative/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,stephank/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,jschmidlapp/luci,Flexibity/luci,stephank/luci,phi-psi/luci,freifunk-gluon/luci,phi-psi/luci,Canaan-Creative/luci,freifunk-gluon/luci,vhpham80/luci,Canaan-Creative/luci,saraedum/luci-packages-old,Flexibity/luci,stephank/luci,Canaan-Creative/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,jschmidlapp/luci,projectbismark/luci-bismark,ch3n2k/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,Flexibity/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,stephank/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ch3n2k/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,gwlim/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,vhpham80/luci,phi-psi/luci,saraedum/luci-packages-old,gwlim/luci,ch3n2k/luci,gwlim/luci,8devices/carambola2-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,saraedum/luci-packages-old,8devices/carambola2-luci,ch3n2k/luci,ThingMesh/openwrt-luci,ch3n2k/luci,gwlim/luci,Flexibity/luci,eugenesan/openwrt-luci,vhpham80/luci,8devices/carambola2-luci,phi-psi/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,8devices/carambola2-luci,Flexibity/luci,zwhfly/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,jschmidlapp/luci,gwlim/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,yeewang/openwrt-luci,jschmidlapp/luci,stephank/luci,jschmidlapp/luci,jschmidlapp/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,freifunk-gluon/luci,freifunk-gluon/luci,vhpham80/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,8devices/carambola2-luci,projectbismark/luci-bismark,freifunk-gluon/luci,gwlim/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci
1b4117b6e101463c8b381decfe4f54c5e7bd3500
kong/cmd/start.lua
kong/cmd/start.lua
local dnsmasq_signals = require "kong.cmd.utils.dnsmasq_signals" local prefix_handler = require "kong.cmd.utils.prefix_handler" local nginx_signals = require "kong.cmd.utils.nginx_signals" local serf_signals = require "kong.cmd.utils.serf_signals" local conf_loader = require "kong.conf_loader" local DAOFactory = require "kong.dao.factory" local log = require "kong.cmd.utils.log" local function execute(args) local conf = assert(conf_loader(args.conf, { prefix = args.prefix })) local dao = DAOFactory(conf) local err xpcall(function() assert(prefix_handler.prepare_prefix(conf, args.nginx_conf)) assert(dao:run_migrations()) if conf.dnsmasq then assert(dnsmasq_signals.start(conf)) end assert(serf_signals.start(conf, dao)) assert(nginx_signals.start(conf)) log("Kong started") end, function(e) log.verbose("could not start Kong, stopping services") pcall(nginx_signals.stop(conf)) pcall(serf_signals.stop(conf, dao)) if conf.dnsmasq then pcall(dnsmasq_signals.stop(conf)) end err = e -- cannot throw from this function log.verbose("stopped services") end) if err then error(err) -- report to main error handler end end local lapp = [[ Usage: kong start [OPTIONS] Start Kong (Nginx and other configured services) in the configured prefix directory. Options: -c,--conf (optional string) configuration file -p,--prefix (optional string) override prefix directory --nginx-conf (optional string) custom Nginx configuration template ]] return { lapp = lapp, execute = execute }
local dnsmasq_signals = require "kong.cmd.utils.dnsmasq_signals" local prefix_handler = require "kong.cmd.utils.prefix_handler" local nginx_signals = require "kong.cmd.utils.nginx_signals" local serf_signals = require "kong.cmd.utils.serf_signals" local conf_loader = require "kong.conf_loader" local DAOFactory = require "kong.dao.factory" local log = require "kong.cmd.utils.log" local function execute(args) local conf = assert(conf_loader(args.conf, { prefix = args.prefix })) local dao = DAOFactory(conf) local err xpcall(function() assert(prefix_handler.prepare_prefix(conf, args.nginx_conf)) assert(dao:run_migrations()) if conf.dnsmasq then assert(dnsmasq_signals.start(conf)) end assert(serf_signals.start(conf, dao)) assert(nginx_signals.start(conf)) log("Kong started") end, function(e) err = e or "" -- cannot throw from this function end) if err then log.verbose("could not start Kong, stopping services") pcall(nginx_signals.stop(conf)) pcall(serf_signals.stop(conf, dao)) if conf.dnsmasq then pcall(dnsmasq_signals.stop(conf)) end log.verbose("stopped services") error(err) -- report to main error handler end end local lapp = [[ Usage: kong start [OPTIONS] Start Kong (Nginx and other configured services) in the configured prefix directory. Options: -c,--conf (optional string) configuration file -p,--prefix (optional string) override prefix directory --nginx-conf (optional string) custom Nginx configuration template ]] return { lapp = lapp, execute = execute }
hotfix(cli) fix recursive calls to the startup errorhandler
hotfix(cli) fix recursive calls to the startup errorhandler The `pcall`s used to stop the services seem to inherit the errorhandler from the `xpcall` up on the stack. This causes a recursive call if stopping the services errors for some reason.
Lua
apache-2.0
jebenexer/kong,Kong/kong,Kong/kong,Vermeille/kong,salazar/kong,Kong/kong,ccyphers/kong,akh00/kong,shiprabehera/kong,li-wl/kong,icyxp/kong,beauli/kong,Mashape/kong