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
be6998376ec61b953fbb38b6eeceb7458752bb17
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", request_id = 0 }; log("debug", "initializing dovecot authentication provider for host '%s'", host); local conn; -- Closes the socket function provider.close(self) if conn then conn:close(); conn = nil; end end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); conn = socket.unix(); -- Create a connection to dovecot socket log("debug", "connecting to dovecot socket at '%s'", socket_path); local r, e = conn: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(); log("debug", "sending handshake to dovecot. version 1.1, cpid '%d'", pid); 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 log("debug", "dovecot handshake: '%s'", l); parts = string.gmatch(l, "[^\t]+"); first = parts(); if (first == "VERSION") then -- Version should be 1.1 local major_version = parts(); if major_version ~= "1" then log("error", "dovecot server version is not 1.x. it is %s.x", major_version); 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 = conn: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 = conn: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.send_auth_request(self, username, password) if not conn 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 % 4294967296 local msg = "AUTH\t" .. provider.request_id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64; log("debug", "sending auth request for '%s' with password '%s': '%s'", username, password, msg); if (not provider:send(msg .. "\n")) then return nil, "Auth failed. Dovecot communications error"; end -- Get response local l = provider:receive(); log("debug", "got auth response: '%s'", l); if (not l) then return nil, "Auth failed. Dovecot communications error"; end local parts = string.gmatch(l, "[^\t]+"); -- Check response local status = parts(); local resp_id = tonumber(parts()); if (resp_id ~= provider.request_id) then log("warn", "dovecot response_id(%s) doesn't match request_id(%s)", resp_id, provider.request_id); provider:close(); return nil, "Auth failed. Dovecot communications error"; end return status, parts; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local status, extra = provider:send_auth_request(username, password); if (status == "OK") then log("info", "login ok for '%s'", username); return true; else log("info", "login failed for '%s'", username); 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) log("debug", "user_exists for user %s at host %s", username, module.host); -- Send a request. If the response (FAIL) contains an extra -- parameter like user=<username> then it exists. local status, extra = provider:send_auth_request(username, ""); local param = extra(); while (param) do parts = string.gmatch(param, "[^=]+"); name = parts(); value = parts(); if (name == "user") then log("info", "user '%s' exists", username); return true; end param = extra(); end log("info", "user '%s' does not exists (or dovecot didn't send user=<username> parameter)", username); return false; 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(sasl, 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 usermanager = require "core.usermanager"; 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 = prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_provider(host) local provider = { name = "dovecot", request_id = 0 }; log("debug", "initializing dovecot authentication provider for host '%s'", host); local conn; -- Closes the socket function provider.close(self) if conn then conn:close(); conn = nil; end end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); conn = socket.unix(); -- Create a connection to dovecot socket log("debug", "connecting to dovecot socket at '%s'", socket_path); local ok, err = conn:connect(socket_path); if not ok then log("error", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, err); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); log("debug", "sending handshake to dovecot. version 1.1, cpid '%d'", pid); 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 line = provider:receive(); if not line then return false; end log("debug", "dovecot handshake: '%s'", line); local parts = line:gmatch("[^\t]+"); local first = parts(); if first == "VERSION" then -- Version should be 1.1 local major_version = parts(); if major_version ~= "1" then log("error", "dovecot server version is not 1.x. it is %s.x", major_version); provider:close(); return false; end elseif first == "MECH" then -- Mechanisms should include PLAIN local ok = false; for part in parts do if part == "PLAIN" then ok = true; end end if not ok then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", line); 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 ok, err = conn:send(data); if not ok then log("error", "error sending '%s' to dovecot. error was '%s'", data, err); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local line, err = conn:receive(); if not line then log("error", "error receiving data from dovecot. error was '%s'", err); provider:close(); return false; end return line; end function provider.send_auth_request(self, username, password) if not conn 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 % 4294967296 local msg = "AUTH\t" .. provider.request_id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64; log("debug", "sending auth request for '%s' with password '%s': '%s'", username, password, msg); if not provider:send(msg .. "\n") then return nil, "Auth failed. Dovecot communications error"; end -- Get response local line = provider:receive(); log("debug", "got auth response: '%s'", line); if not line then return nil, "Auth failed. Dovecot communications error"; end local parts = line:gmatch("[^\t]+"); -- Check response local status = parts(); local resp_id = tonumber(parts()); if resp_id ~= provider.request_id then log("warn", "dovecot response_id(%s) doesn't match request_id(%s)", resp_id, provider.request_id); provider:close(); return nil, "Auth failed. Dovecot communications error"; end return status, parts; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local status, extra = provider:send_auth_request(username, password); if status == "OK" then log("info", "login ok for '%s'", username); return true; else log("info", "login failed for '%s'", username); 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) log("debug", "user_exists for user %s at host %s", username, module.host); -- Send a request. If the response (FAIL) contains an extra -- parameter like user=<username> then it exists. local status, extra = provider:send_auth_request(username, ""); local param = extra(); while param do local parts = param:gmatch("[^=]+"); local name = parts(); local value = parts(); if name == "user" then log("debug", "user '%s' exists", username); return true; end param = extra(); end log("debug", "user '%s' does not exists (or dovecot didn't send user=<username> parameter)", username); return false; 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(sasl, 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_provider(module.host));
mod_auth_dovecot: Fix various global variable sets/gets, log levels, unclear variable names and change coding style to match more closely the rest of the Prosody code.
mod_auth_dovecot: Fix various global variable sets/gets, log levels, unclear variable names and change coding style to match more closely the rest of the Prosody code.
Lua
mit
joewalker/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,drdownload/prosody-modules,prosody-modules/import,syntafin/prosody-modules,softer/prosody-modules,apung/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,olax/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,jkprg/prosody-modules,heysion/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,Craige/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,obelisk21/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,cryptotoad/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,crunchuser/prosody-modules,jkprg/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,prosody-modules/import,stephen322/prosody-modules,heysion/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,stephen322/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,asdofindia/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,NSAKEY/prosody-modules
a885f48771898dd43280f96fa92f061ffe57679b
mod_post_msg/mod_post_msg.lua
mod_post_msg/mod_post_msg.lua
module:depends"http" local jid_split = require "util.jid".split; local jid_prep = require "util.jid".prep; local msg = require "util.stanza".message; local test_password = require "core.usermanager".test_password; local b64_decode = require "util.encodings".base64.decode; local formdecode = require "net.http".formdecode; local xml = require"util.xml"; local function require_valid_user(f) return function(event, path) local request = event.request; local response = event.response; local headers = request.headers; if not headers.authorization then response.headers.www_authenticate = ("Basic realm=%q"):format(module.host.."/"..module.name); return 401 end local from_jid, password = b64_decode(headers.authorization:match"[^ ]*$"):match"([^:]*):(.*)"; from_jid = jid_prep(from_jid); if from_jid and password then local user, host = jid_split(from_jid); local ok, err = test_password(user, host, password); if ok and user and host then module:log("debug", "Authed as %s", from_jid); return f(event, path, from_jid); elseif err then module:log("debug", "User failed authentication: %s", err); end end return 401 end end local function handle_post(event, path, authed_user) local request = event.request; local response = event.response; local headers = request.headers; local body_type = headers.content_type; local to = jid_prep(path); local message; if body_type == "text/plain" then if to and request.body then message = msg({ to = to, from = authed_user, type = "chat"},request.body); end elseif body_type == "application/x-www-form-urlencoded" then local post_body = formdecode(request.body); message = msg({ to = post_body.to or to, from = authed_user, type = post_body.type or "chat"}, post_body.body); if post_body.html then local html, err = xml.parse(post_body.html); if not html then module:log("warn", "mod_post_msg: invalid XML: %s", err); return 400; end message:tag("html", {xmlns="http://jabber.org/protocol/xhtml-im"}):add_child(html):up(); end else return 415; end if message and message.attr.to then module:log("debug", "Sending %s", tostring(message)); module:send(message); return 201; end return 422; end module:provides("http", { default_path = "/msg"; route = { ["POST /*"] = require_valid_user(handle_post); OPTIONS = function(e) local headers = e.response.headers; headers.allow = "POST"; headers.accept = "application/x-www-form-urlencoded, text/plain"; return 200; end; } });
module:depends"http" local jid_split = require "util.jid".split; local jid_prep = require "util.jid".prep; local msg = require "util.stanza".message; local test_password = require "core.usermanager".test_password; local b64_decode = require "util.encodings".base64.decode; local formdecode = require "net.http".formdecode; local xml = require"util.xml"; local function require_valid_user(f) return function(event, path) local request = event.request; local response = event.response; local headers = request.headers; if not headers.authorization then response.headers.www_authenticate = ("Basic realm=%q"):format(module.host.."/"..module.name); return 401 end local from_jid, password = b64_decode(headers.authorization:match"[^ ]*$"):match"([^:]*):(.*)"; from_jid = jid_prep(from_jid); if from_jid and password then local user, host = jid_split(from_jid); local ok, err = test_password(user, host, password); if ok and user and host then module:log("debug", "Authed as %s", from_jid); return f(event, path, from_jid); elseif err then module:log("debug", "User failed authentication: %s", err); end end return 401 end end local function handle_post(event, path, authed_user) local request = event.request; local response = event.response; local headers = request.headers; local body_type = headers.content_type; local to = jid_prep(path); local message; if body_type == "text/plain" then if to and request.body then message = msg({ to = to, from = authed_user, type = "chat"},request.body); end elseif body_type == "application/x-www-form-urlencoded" then local post_body = formdecode(request.body); message = msg({ to = post_body.to or to, from = authed_user, type = post_body.type or "chat"}, post_body.body); if post_body.html then local html, err = xml.parse(post_body.html); if not html then module:log("warn", "mod_post_msg: invalid XML: %s", err); return 400; end message:tag("html", {xmlns="http://jabber.org/protocol/xhtml-im"}):add_child(html):up(); end else return 415; end if message and message.attr.to then module:log("debug", "Sending %s", tostring(message)); module:send(message); return 201; end return 422; end module:provides("http", { default_path = "/msg"; route = { ["POST /*"] = require_valid_user(handle_post); OPTIONS = function(e) local headers = e.response.headers; headers.allow = "POST"; headers.accept = "application/x-www-form-urlencoded, text/plain"; return 200; end; } });
mod_post_msg: Fix indentation
mod_post_msg: Fix indentation
Lua
mit
mmusial/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,amenophis1er/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,drdownload/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,softer/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,apung/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,prosody-modules/import,1st8/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,olax/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,syntafin/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,either1/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules
4ba5656d7b599d1c442a8d6d9990d6caee1fb4e2
src/actions/vstudio/vs2013.lua
src/actions/vstudio/vs2013.lua
-- -- vs2013.lua -- Baseline support for Visual Studio 2013. -- Copyright (c) 2013 Jason Perkins and the Premake project -- --- -- Register a command-line action for Visual Studio 2012. --- newaction { trigger = "vs2013", shortname = "Visual Studio 2013", description = "Generate Microsoft Visual Studio 2013 project files", os = "windows", valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib" }, valid_languages = { "C", "C++", "C#"}, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, onsolution = function(sln) premake.generate(sln, "%%.sln", vstudio.sln2005.generate) end, onproject = function(prj) if premake.isdotnetproject(prj) then premake.generate(prj, "%%.csproj", vstudio.cs2005.generate) premake.generate(prj, "%%.csproj.user", vstudio.cs2005.generate_user) else premake.generate(prj, "%%.vcxproj", premake.vs2010_vcxproj) premake.generate(prj, "%%.vcxproj.user", premake.vs2010_vcxproj_user) premake.generate(prj, "%%.vcxproj.filters", vstudio.vc2010.generate_filters) end end, oncleansolution = premake.vstudio.cleansolution, oncleanproject = premake.vstudio.cleanproject, oncleantarget = premake.vstudio.cleantarget, vstudio = { solutionVersion = "12", targetFramework = "4.5", toolsVersion = "12.0", } }
-- -- vs2013.lua -- Baseline support for Visual Studio 2013. -- Copyright (c) 2013 Jason Perkins and the Premake project -- premake.vstudio.vc2013 = {} local vc2013 = premake.vstudio.vc2013 local vstudio = premake.vstudio --- -- Register a command-line action for Visual Studio 2013. --- newaction { trigger = "vs2013", shortname = "Visual Studio 2013", description = "Generate Microsoft Visual Studio 2013 project files", os = "windows", valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib" }, valid_languages = { "C", "C++", "C#"}, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, onsolution = function(sln) premake.generate(sln, "%%.sln", vstudio.sln2005.generate) end, onproject = function(prj) if premake.isdotnetproject(prj) then premake.generate(prj, "%%.csproj", vstudio.cs2005.generate) premake.generate(prj, "%%.csproj.user", vstudio.cs2005.generate_user) else premake.generate(prj, "%%.vcxproj", premake.vs2010_vcxproj) premake.generate(prj, "%%.vcxproj.user", premake.vs2010_vcxproj_user) premake.generate(prj, "%%.vcxproj.filters", vstudio.vc2010.generate_filters) end end, oncleansolution = premake.vstudio.cleansolution, oncleanproject = premake.vstudio.cleanproject, oncleantarget = premake.vstudio.cleantarget, vstudio = { solutionVersion = "12", targetFramework = "4.5", toolsVersion = "12.0", } }
Fix vs2013 action.
Fix vs2013 action.
Lua
bsd-3-clause
premake/premake-4.x,ryanjmulder/premake-4.x,premake/premake-4.x,lizh06/premake-4.x,premake/premake-4.x,lizh06/premake-4.x,lizh06/premake-4.x,premake/premake-4.x,lizh06/premake-4.x,ryanjmulder/premake-4.x,ryanjmulder/premake-4.x,ryanjmulder/premake-4.x
aa33acbb1e7d3ef308714cec585fc6a86bae0184
vrp/modules/basic_skinshop.lua
vrp/modules/basic_skinshop.lua
-- a basic skinshop implementation local cfg = require("resources/vrp/cfg/skinshops") local skinshops = cfg.skinshops -- open the skin shop for the specified ped parts -- name = partid function vRP.openSkinshop(source,parts) local user_id = vRP.getUserId(source) if user_id ~= nil then local menudata = { name="Skinshop", css={top = "75px", header_color="rgba(0,255,125,0.75)"} } local drawables = {} local textures = {} -- get old customization to compute the price local old_custom = {} vRPclient.getCustomization(source,{},function(custom) old_custom = custom custom.modelhash = nil end) local ondrawable = function(player, choice) -- change drawable local drawable = drawables[choice] drawable[1] = drawable[1]+1 if drawable[1] >= drawable[2] then drawable[1] = 0 end -- circular selection -- apply change local custom = {} custom[parts[choice]] = {drawable[1],textures[choice][1]} vRPclient.setCustomization(source,{custom}) -- update max textures number vRPclient.getDrawableTextures(source,{parts[choice],drawable[1]},function(n) textures[choice][2] = n if textures[choice][1] >= n then textures[choice][1] = 0 -- reset texture number end end) end local ontexture = function(player, choice) choice = string.sub(choice,2) -- remove star -- change texture local texture = textures[choice] texture[1] = texture[1]+1 if texture[1] >= texture[2] then texture[1] = 0 end -- circular selection -- apply change local custom = {} custom[parts[choice]] = {drawables[choice][1],texture[1]} vRPclient.setCustomization(source,{custom}) end for k,v in pairs(parts) do -- for each part, get number of drawables and build menu drawables[k] = {0,0} -- {current,max} textures[k] = {0,0} -- {current,max} vRPclient.getDrawables(source,{v},function(n) drawables[k][2] = n -- set max end) menudata[k] = {ondrawable} menudata["*"..k] = {ontexture} end menudata.onclose = function(player) -- compute price vRPclient.getCustomization(source,{},function(custom) local price = 0 custom.modelhash = nil for k,v in pairs(custom) do local old = old_custom[k] if v[1] ~= old[1] then price = price + cfg.drawable_change_price end -- change of drawable if v[2] ~= old[2] then price = price + cfg.texture_change_price end -- change of texture end if vRP.tryPayment(user_id,price) then if price > 0 then vRPclient.notify(source,{"Paid "..price.." $"}) end else vRPclient.notify(source,{"Not enough money, total price is "..price.." $"}) -- revert changes vRPclient.setCustomization(source,{old_custom}) end end) end -- open menu vRP.openMenu(source,menudata) end end local function build_client_skinshops(source) local user_id = vRP.getUserId(source) if user_id ~= nil then for k,v in pairs(skinshops) do local parts,x,y,z = table.unpack(v) local skinshop_enter = function(source) local user_id = vRP.getUserId(source) if user_id ~= nil then vRP.openSkinshop(source,parts) end end local function skinshop_leave(source) vRP.closeMenu(source) end vRPclient.addBlip(source,{x,y,z,73,3,"Skinshop"}) vRPclient.addMarker(source,{x,y,z-1,0.7,0.7,0.5,0,255,125,125,150}) vRP.setArea(source,"vRP:skinshop"..k,x,y,z,1,1.5,skinshop_enter,skinshop_leave) end end end AddEventHandler("vRP:playerSpawned",function() local user_id = vRP.getUserId(source) if user_id ~= nil and vRP.isFirstSpawn(user_id) then build_client_skinshops(source) end end)
-- a basic skinshop implementation local cfg = require("resources/vrp/cfg/skinshops") local skinshops = cfg.skinshops -- open the skin shop for the specified ped parts -- name = partid function vRP.openSkinshop(source,parts) local user_id = vRP.getUserId(source) if user_id ~= nil then -- get old customization to compute the price vRPclient.getCustomization(source,{},function(old_custom) old_custom.modelhash = nil -- start building menu local menudata = { name="Skinshop", css={top = "75px", header_color="rgba(0,255,125,0.75)"} } local drawables = {} local textures = {} local ondrawable = function(player, choice) -- change drawable local drawable = drawables[choice] drawable[1] = drawable[1]+1 if drawable[1] >= drawable[2] then drawable[1] = 0 end -- circular selection -- apply change local custom = {} custom[parts[choice]] = {drawable[1],textures[choice][1]} vRPclient.setCustomization(source,{custom}) -- update max textures number vRPclient.getDrawableTextures(source,{parts[choice],drawable[1]},function(n) textures[choice][2] = n if textures[choice][1] >= n then textures[choice][1] = 0 -- reset texture number end end) end local ontexture = function(player, choice) choice = string.sub(choice,2) -- remove star -- change texture local texture = textures[choice] texture[1] = texture[1]+1 if texture[1] >= texture[2] then texture[1] = 0 end -- circular selection -- apply change local custom = {} custom[parts[choice]] = {drawables[choice][1],texture[1]} vRPclient.setCustomization(source,{custom}) end for k,v in pairs(parts) do -- for each part, get number of drawables and build menu drawables[k] = {0,0} -- {current,max} textures[k] = {0,0} -- {current,max} -- init using old customization local old_part = old_custom[v] if old_part then drawables[k][1] = old_part[1] textures[k][1] = old_part[2] end -- get max drawables vRPclient.getDrawables(source,{v},function(n) drawables[k][2] = n -- set max end) -- get max textures for this drawable vRPclient.getDrawableTextures(source,{v,drawables[k][1]},function(n) textures[k][2] = n -- set max end) -- add menu choices menudata[k] = {ondrawable} menudata["*"..k] = {ontexture} end menudata.onclose = function(player) -- compute price vRPclient.getCustomization(source,{},function(custom) local price = 0 custom.modelhash = nil for k,v in pairs(custom) do local old = old_custom[k] if v[1] ~= old[1] then price = price + cfg.drawable_change_price end -- change of drawable if v[2] ~= old[2] then price = price + cfg.texture_change_price end -- change of texture end if vRP.tryPayment(user_id,price) then if price > 0 then vRPclient.notify(source,{"Paid "..price.." $"}) end else vRPclient.notify(source,{"Not enough money, total price is "..price.." $"}) -- revert changes vRPclient.setCustomization(source,{old_custom}) end end) end -- open menu vRP.openMenu(source,menudata) end) end end local function build_client_skinshops(source) local user_id = vRP.getUserId(source) if user_id ~= nil then for k,v in pairs(skinshops) do local parts,x,y,z = table.unpack(v) local skinshop_enter = function(source) local user_id = vRP.getUserId(source) if user_id ~= nil then vRP.openSkinshop(source,parts) end end local function skinshop_leave(source) vRP.closeMenu(source) end vRPclient.addBlip(source,{x,y,z,73,3,"Skinshop"}) vRPclient.addMarker(source,{x,y,z-1,0.7,0.7,0.5,0,255,125,125,150}) vRP.setArea(source,"vRP:skinshop"..k,x,y,z,1,1.5,skinshop_enter,skinshop_leave) end end end AddEventHandler("vRP:playerSpawned",function() local user_id = vRP.getUserId(source) if user_id ~= nil and vRP.isFirstSpawn(user_id) then build_client_skinshops(source) end end)
Fix basic skinshop issue
Fix basic skinshop issue
Lua
mit
ImagicTheCat/vRP,ENDrain/vRP-plusplus,ImagicTheCat/vRP,ENDrain/vRP-plusplus,ENDrain/vRP-plusplus
421e3ad56b8489b422cfab7844f53f3cc8077bff
lua/weapons/gmod_tool/stools/starfall.lua
lua/weapons/gmod_tool/stools/starfall.lua
TOOL.Category = "Starfall" TOOL.Name = "Starfall" TOOL.Command = nil TOOL.ConfigName = "" TOOL.Tab = "Wire" if CLIENT then language.Add( "Tool_starfall_name", "Starfall Tool (Wire)" ) language.Add( "Tool_starfall_desc", "Spawns a starfall processor" ) language.Add( "Tool_starfall_0", "Primary: Spawn, Secondary: Uploads code form sf_code_buffer" ) language.Add( "sboxlimit_starfall", "You've hit the Starfall processor limit!" ) language.Add( "undone_Wire Starfall", "Undone Starfall" ) CreateConVar("sf_code_buffer", "", {FCVAR_USERINFO}) end if SERVER then CreateConVar('sbox_maxstarfall', 10) end TOOL.ClientConVar[ "Model" ] = "models/jaanus/wiretool/wiretool_siren.mdl" cleanup.Register( "wire_starfall" ) function TOOL:LeftClick( trace ) if !trace.HitPos then return false end if trace.Entity:IsPlayer() then return false end if CLIENT then return true end if ValidEntity(trace.Entity) and trace.Entity:GetClass() == "gmod_starfall" then local code = self:GetOwner():GetInfo("sf_code_buffer") trace.Entity:Compile(code) return true end self:SetStage(0) local model = self:GetClientInfo( "Model" ) local ply = self:GetOwner() if !self:GetSWEP():CheckLimit( "wire_starfall" ) then return false end local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 local sf = MakeSF( ply, trace.HitPos, Ang, model) local min = sf:OBBMins() sf:SetPos( trace.HitPos - trace.HitNormal * min.z ) local const = WireLib.Weld(sf, trace.Entity, trace.PhysicsBone, true) undo.Create("Wire Starfall") undo.AddEntity( sf ) undo.AddEntity( const ) undo.SetPlayer( ply ) undo.Finish() ply:AddCleanup( "wire_starfall", sf ) return true end function TOOL:RightClick( trace ) if !trace.HitPos then return false end if trace.Entity:IsPlayer() then return false end if CLIENT then return true end if ValidEntity(trace.Entity) then if trace.Entity:GetClass() == "gmod_starfall" then local code = self:GetOwner():GetInfo("sf_code_buffer") trace.Entity:Compile(code) return true end end end function TOOL:Reload(trace) return false end function TOOL:DrawHUD() end if SERVER then function MakeSF( pl, Pos, Ang, model) if !pl:CheckLimit( "wire_starfall" ) then return false end local sf = ents.Create( "gmod_starfall" ) if !IsValid(sf) then return false end sf:SetAngles( Ang ) sf:SetPos( Pos ) sf:SetModel( model ) sf:Spawn() sf.player = pl pl:AddCount( "wire_starfall", sf ) return sf end end function TOOL:Think() end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool_starfall_name", Description = "#Tool_starfall_desc" }) end
TOOL.Category = "Starfall" TOOL.Name = "Starfall" TOOL.Command = nil TOOL.ConfigName = "" TOOL.Tab = "Wire" if CLIENT then language.Add( "Tool_starfall_name", "Starfall Tool (Wire)" ) language.Add( "Tool_starfall_desc", "Spawns a starfall processor" ) language.Add( "Tool_starfall_0", "Primary: Spawn, Secondary: Uploads code form sf_code_buffer" ) language.Add( "sboxlimit_starfall", "You've hit the Starfall processor limit!" ) language.Add( "undone_Wire Starfall", "Undone Starfall" ) CreateConVar("sf_code_buffer", "", {FCVAR_USERINFO}) end if SERVER then CreateConVar('sbox_maxwire_starfall', 10, {FCVAR_REPLICATED,FCVAR_NOTIFY,FCVAR_ARCHIVE}) end TOOL.ClientConVar[ "Model" ] = "models/jaanus/wiretool/wiretool_siren.mdl" cleanup.Register( "wire_starfall" ) function TOOL:LeftClick( trace ) if !trace.HitPos then return false end if trace.Entity:IsPlayer() then return false end if CLIENT then return true end if ValidEntity(trace.Entity) and trace.Entity:GetClass() == "gmod_starfall" then local code = self:GetOwner():GetInfo("sf_code_buffer") trace.Entity:Compile(code) return true end self:SetStage(0) local model = self:GetClientInfo( "Model" ) local ply = self:GetOwner() if !self:GetSWEP():CheckLimit( "wire_starfall" ) then return false end local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 local sf = MakeSF( ply, trace.HitPos, Ang, model) local min = sf:OBBMins() sf:SetPos( trace.HitPos - trace.HitNormal * min.z ) local const = WireLib.Weld(sf, trace.Entity, trace.PhysicsBone, true) undo.Create("Wire Starfall") undo.AddEntity( sf ) undo.AddEntity( const ) undo.SetPlayer( ply ) undo.Finish() ply:AddCleanup( "wire_starfall", sf ) return true end function TOOL:RightClick( trace ) if !trace.HitPos then return false end if trace.Entity:IsPlayer() then return false end if CLIENT then return true end if ValidEntity(trace.Entity) then if trace.Entity:GetClass() == "gmod_starfall" then local code = self:GetOwner():GetInfo("sf_code_buffer") trace.Entity:Compile(code) return true end end end function TOOL:Reload(trace) return false end function TOOL:DrawHUD() end if SERVER then function MakeSF( pl, Pos, Ang, model) if !pl:CheckLimit( "wire_starfall" ) then return false end local sf = ents.Create( "gmod_starfall" ) if !IsValid(sf) then return false end sf:SetAngles( Ang ) sf:SetPos( Pos ) sf:SetModel( model ) sf:Spawn() sf.player = pl pl:AddCount( "wire_starfall", sf ) return sf end end function TOOL:Think() end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool_starfall_name", Description = "#Tool_starfall_desc" }) end
[SF] Fixed not being able to spawn the processor in multiplayer
[SF] Fixed not being able to spawn the processor in multiplayer
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,Xandaros/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall
21f375186d53ace9bba5e42e9be0c9ec75cebcf3
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local admins = set.new(config.get(module:get_host(), "core", "admins")); local sessions = {}; local add_user_layout = { title= "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; dataforms_new(add_user_layout) function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("You don't have permission to add a user")); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="canceled"})); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end for _, tag in ipairs(stanza.tags[1].tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Account already exists")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="completed"}) :tag("note", {type="info"}):text("Account successfully created")); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Failed to write data to disk")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPasswords missmatch, or empy username"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Invalid data.\nPasswords missmatch, or empy username")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=sessionid, status="executing"}):add_child(add_user_layout:form())); end return true; end local descriptor = { name="Add User", node="http://jabber.org/protocol/admin#add-user", handler=add_user_command_handler }; function module.unload() module:remove_item("adhoc", descriptor); end module:add_item ("adhoc", descriptor);
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local admins = set.new(config.get(module:get_host(), "core", "admins")); local sessions = {}; local add_user_layout = dataforms_new{ title= "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("You don't have permission to add a user")); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="canceled"})); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:find_child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Account already exists")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="completed"}) :tag("note", {type="info"}):text("Account successfully created")); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Failed to write data to disk")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPassword mismatch, or empty username"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Invalid data.\nPassword mismatch, or empty username")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=sessionid, status="executing"}):add_child(add_user_layout:form())); end return true; end local descriptor = { name="Add User", node="http://jabber.org/protocol/admin#add-user", handler=add_user_command_handler }; function module.unload() module:remove_item("adhoc", descriptor); end module:add_item ("adhoc", descriptor);
mod_adhoc_cmd_admin: Fixed style, some typos, and got down to <100LOC. Perhaps we need util.adhoc?
mod_adhoc_cmd_admin: Fixed style, some typos, and got down to <100LOC. Perhaps we need util.adhoc?
Lua
mit
NSAKEY/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,olax/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,brahmi2/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,LanceJenkinZA/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,joewalker/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,apung/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,guilhem/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,prosody-modules/import,softer/prosody-modules,drdownload/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,softer/prosody-modules,Craige/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,vfedoroff/prosody-modules,joewalker/prosody-modules,prosody-modules/import,mmusial/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,mmusial/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules
52cdfcc60f2b2c5dd0491227cee42073570212b3
lua/starfall/preprocessor.lua
lua/starfall/preprocessor.lua
------------------------------------------------------------------------------- -- SF Preprocessor. -- Processes code for compile time directives. -- @author Colonel Thirty Two ------------------------------------------------------------------------------- -- TODO: Make an @include-only parser SF.Preprocessor = {} SF.Preprocessor.directives = {} --- Sets a global preprocessor directive. -- @param directive The directive to set. -- @param func The callback. Takes the directive arguments, the file name, and instance.data function SF.Preprocessor.SetGlobalDirective(directive, func) SF.Preprocessor.directives[directive] = func end local function FindComments( line ) local ret, count, pos, found = {}, 0, 1 repeat found = line:find( '["%-%[%]]', pos ) if (found) then -- We found something local oldpos = pos local char = line:sub(found,found) if char == "-" then if line:sub(found,found+1) == "--" then -- Comment beginning if line:sub(found,found+3) == "--[[" then -- Block Comment beginning count = count + 1 ret[count] = {type = "start", pos = found} pos = found + 4 else -- Line comment beginning count = count + 1 ret[count] = {type = "line", pos = found} pos = found + 2 end else pos = found + 1 end elseif char == "[" then if line:sub(found,found+1) == "[[" then -- Block string start count = count + 1 ret[count] = {type = "stringblock", pos = found} pos = found + 2 else pos = found + 1 end elseif char == "]" then if line:sub(found,found+1) == "]]" then -- Ending count = count + 1 ret[count] = {type = "end", pos = found} pos = found + 2 else pos = found + 1 end elseif char == "\"" and line:sub(found-1,found-1) ~= "\\" then -- String count = count + 1 ret[count] = {type = "string", pos = found} pos = found + 1 end if oldpos == pos then error("Regex found something, but nothing handled it") end end until not found return ret, count end --- Parses a source file for directives. -- @param filename The file name of the source code -- @param source The source code to parse. -- @param directives A table of additional directives to use. -- @param data The data table passed to the directives. function SF.Preprocessor.ParseDirectives(filename, source, directives, data) local ending = nil local str = source while str ~= "" do local line line, str = string.match(str,"^([^\n]*)\n?(.*)$") for _,comment in ipairs(FindComments(line)) do if ending then if comment.type == ending then ending = nil end elseif comment.type == "start" then ending = "end" elseif comment.type == "string" then ending = "string" elseif comment.type == "stringblock" then ending = "end" elseif comment.type == "line" then local directive, args = string.match(line,"--@([^ ]+)%s*(.*)$") local func = directives[directive] or SF.Preprocessor.directives[directive] if func then func(args, filename, data) end end end if ending == "newline" then ending = nil end end end local function directive_include(args, filename, data) if not data.includes then data.includes = {} end if not data.includes[filename] then data.includes[filename] = {} end local incl = data.includes[filename] incl[#incl+1] = args end SF.Preprocessor.SetGlobalDirective("include",directive_include) local function directive_name(args, filename, data) if not data.scriptnames then data.scriptnames = {} end data.scriptnames[filename] = args end SF.Preprocessor.SetGlobalDirective("name",directive_name)
------------------------------------------------------------------------------- -- SF Preprocessor. -- Processes code for compile time directives. -- @author Colonel Thirty Two ------------------------------------------------------------------------------- -- TODO: Make an @include-only parser SF.Preprocessor = {} SF.Preprocessor.directives = {} --- Sets a global preprocessor directive. -- @param directive The directive to set. -- @param func The callback. Takes the directive arguments, the file name, and instance.data function SF.Preprocessor.SetGlobalDirective(directive, func) SF.Preprocessor.directives[directive] = func end local function FindComments( line ) local ret, count, pos, found = {}, 0, 1 repeat found = line:find( '["%-%[%]]', pos ) if (found) then -- We found something local oldpos = pos local char = line:sub(found,found) if char == "-" then if line:sub(found,found+1) == "--" then -- Comment beginning if line:sub(found,found+3) == "--[[" then -- Block Comment beginning count = count + 1 ret[count] = {type = "start", pos = found} pos = found + 4 else -- Line comment beginning count = count + 1 ret[count] = {type = "line", pos = found} pos = found + 2 end else pos = found + 1 end elseif char == "[" then local level = line:sub(found+1):match("^(=*)") if level then level = string.len(level) else level = 0 end if line:sub(found+level+1, found+level+1) == "[" then -- Block string start count = count + 1 ret[count] = {type = "stringblock", pos = found, level = level} pos = found + level + 2 else pos = found + 1 end elseif char == "]" then local level = line:sub(found+1):match("^(=*)") if level then level = string.len(level) else level = 0 end if line:sub(found+level+1,found+level+1) == "]" then -- Ending count = count + 1 ret[count] = {type = "end", pos = found, level = level} pos = found + level + 2 else pos = found + 1 end elseif char == "\"" then if line:sub(found-1,found-1) == "\\" and line:sub(found-2,found-1) ~= "\\\\" then -- Escaped character pos = found+1 else -- String count = count + 1 ret[count] = {type = "string", pos = found} pos = found + 1 end end if oldpos == pos then error("Regex found something, but nothing handled it") end end until not found return ret, count end --- Parses a source file for directives. -- @param filename The file name of the source code -- @param source The source code to parse. -- @param directives A table of additional directives to use. -- @param data The data table passed to the directives. function SF.Preprocessor.ParseDirectives(filename, source, directives, data) local ending = nil local endingLevel = nil local str = source while str ~= "" do local line line, str = string.match(str,"^([^\n]*)\n?(.*)$") for _,comment in ipairs(FindComments(line)) do if ending then if comment.type ~= ending then continue end if endingLevel then if comment.level and comment.level == endingLevel then ending = nil endingLevel = nil end else ending = nil end elseif comment.type == "start" then ending = "end" elseif comment.type == "string" then ending = "string" elseif comment.type == "stringblock" then ending = "end" endingLevel = comment.level elseif comment.type == "line" then local directive, args = string.match(line,"--@([^ ]+)%s*(.*)$") local func = directives[directive] or SF.Preprocessor.directives[directive] if func then func(args, filename, data) end end end if ending == "newline" then ending = nil end end end local function directive_include(args, filename, data) if not data.includes then data.includes = {} end if not data.includes[filename] then data.includes[filename] = {} end local incl = data.includes[filename] incl[#incl+1] = args end SF.Preprocessor.SetGlobalDirective("include",directive_include) local function directive_name(args, filename, data) if not data.scriptnames then data.scriptnames = {} end data.scriptnames[filename] = args end SF.Preprocessor.SetGlobalDirective("name",directive_name)
Preprocessor FindComments fix and multiline strings support
Preprocessor FindComments fix and multiline strings support
Lua
bsd-3-clause
Xandaros/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall
78b89e8f8235d804ff29b45a1ec3794fa863e536
OvaleActionBar.lua
OvaleActionBar.lua
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2012 Sidoine Copyright (C) 2012, 2013, 2014 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]-------------------------------------------------------------------- -- Keep data about the player action bars (key bindings mostly) local _, Ovale = ... local OvaleActionBar = Ovale:NewModule("OvaleActionBar", "AceEvent-3.0") Ovale.OvaleActionBar = OvaleActionBar --<private-static-properties> local tonumber = tonumber local wipe = table.wipe local API_GetActionInfo = GetActionInfo local API_GetActionText = GetActionText local API_GetBindingKey = GetBindingKey local OVALE_ACTIONBAR_DEBUG = "action_bar" --</private-static-properties> --<public-static-properties> -- Maps each action slot (1..120) to the current action: action[slot] = action OvaleActionBar.action = {} -- Maps each action slot (1..120) to its current keybind: keybind[slot] = keybind OvaleActionBar.keybind = {} -- Maps each spell/macro/item ID to its current action slot. -- spell[spellId] = slot OvaleActionBar.spell = {} -- macro[macroName] = slot OvaleActionBar.macro = {} -- item[itemId] = slot OvaleActionBar.item = {} --</public-static-properties> --<private-static-methods> local function GetKeyBinding(slot) --[[ ACTIONBUTTON1..12 => primary (1..12, 13..24, 73..108) MULTIACTIONBAR1BUTTON1..12 => bottom left (61..72) MULTIACTIONBAR2BUTTON1..12 => bottom right (49..60) MULTIACTIONBAR3BUTTON1..12 => top right (25..36) MULTIACTIONBAR4BUTTON1..12 => top left (37..48) --]] local name if slot <= 24 or slot > 72 then name = "ACTIONBUTTON" .. (((slot - 1)%12) + 1) elseif slot <= 36 then name = "MULTIACTIONBAR3BUTTON" .. (slot - 24) elseif slot <= 48 then name = "MULTIACTIONBAR4BUTTON" .. (slot - 36) elseif slot <= 60 then name = "MULTIACTIONBAR2BUTTON" .. (slot - 48) else name = "MULTIACTIONBAR1BUTTON" .. (slot - 60) end local key = name and API_GetBindingKey(name) return key end --</private-static-methods> --<public-static-methods> function OvaleActionBar:OnEnable() self:RegisterEvent("ACTIONBAR_SLOT_CHANGED") self:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED", "UpdateActionSlots") self:RegisterEvent("PLAYER_ENTERING_WORLD", "UpdateActionSlots") self:RegisterEvent("PLAYER_TALENT_UPDATE", "UpdateActionSlots") self:RegisterEvent("UPDATE_BINDINGS") end function OvaleActionBar:OnDisable() self:UnregisterEvent("ACTIONBAR_SLOT_CHANGED") self:UnregisterEvent("ACTIVE_TALENT_GROUP_CHANGED") self:UnregisterEvent("PLAYER_ENTERING_WORLD") self:UnregisterEvent("PLAYER_TALENT_UPDATE") self:UnregisterEvent("UPDATE_BINDINGS") end function OvaleActionBar:ACTIONBAR_SLOT_CHANGED(event, slot) slot = tonumber(slot) if slot == 0 then self:UpdateActionSlots(event) elseif slot then self:UpdateActionSlot(slot) end end function OvaleActionBar:UPDATE_BINDINGS(event) Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "%s: Updating key bindings.", event) for slot = 1, 120 do self.keybind[slot] = GetKeyBinding(slot) end end function OvaleActionBar:UpdateActionSlots(event) Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "%s: Updating all action slot mappings.", event) wipe(self.action) wipe(self.item) wipe(self.macro) wipe(self.spell) for slot = 1, 120 do self:UpdateActionSlot(slot) end end function OvaleActionBar:UpdateActionSlot(slot) -- Clear old slot and associated actions. local action = self.action[slot] if self.spell[action] == slot then self.spell[action] = nil elseif self.item[action] == slot then self.item[action] = nil elseif self.macro[action] == slot then self.macro[action] = nil end self.action[slot] = nil -- Map the current action in the slot. local actionType, id, subType = API_GetActionInfo(slot) if actionType == "spell" then id = tonumber(id) if id then if not self.spell[id] or slot < self.spell[id] then self.spell[id] = slot end self.action[slot] = id end elseif actionType == "item" then id = tonumber(id) if id then if not self.item[id] or slot < self.item[id] then self.item[id] = slot end self.action[slot] = id end elseif actionType == "macro" then local actionText = API_GetActionText(slot) if actionText then if not self.macro[actionText] or slot < self.macro[actionText] then self.macro[actionText] = slot end self.action[slot] = actionText end end Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "Mapping button %s to %s", slot, self.action[slot]) -- Update the keybind for the slot. self.keybind[slot] = GetKeyBinding(slot) end -- Get the action slot that matches a spell ID. function OvaleActionBar:GetForSpell(spellId) return self.spell[spellId] end -- Get the action slot that matches a macro name. function OvaleActionBar:GetForMacro(macroName) return self.macro[macroName] end -- Get the action slot that matches an item ID. function OvaleActionBar:GetForItem(itemId) return self.item[itemId] end -- Get the keybinding for an action slot. function OvaleActionBar:GetBinding(slot) return self.keybind[slot] end --</public-static-methods>
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2012 Sidoine Copyright (C) 2012, 2013, 2014 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]-------------------------------------------------------------------- -- Keep data about the player action bars (key bindings mostly) local _, Ovale = ... local OvaleActionBar = Ovale:NewModule("OvaleActionBar", "AceEvent-3.0") Ovale.OvaleActionBar = OvaleActionBar --<private-static-properties> local gsub = string.gsub local strmatch = string.match local tonumber = tonumber local wipe = table.wipe local API_GetActionInfo = GetActionInfo local API_GetActionText = GetActionText local API_GetBindingKey = GetBindingKey local API_GetBonusBarIndex = GetBonusBarIndex local API_GetMacroItem = GetMacroItem local API_GetMacroSpell = GetMacroSpell local OVALE_ACTIONBAR_DEBUG = "action_bar" --</private-static-properties> --<public-static-properties> -- Maps each action slot (1..120) to the current action: action[slot] = action OvaleActionBar.action = {} -- Maps each action slot (1..120) to its current keybind: keybind[slot] = keybind OvaleActionBar.keybind = {} -- Maps each spell/macro/item ID to its current action slot. -- spell[spellId] = slot OvaleActionBar.spell = {} -- macro[macroName] = slot OvaleActionBar.macro = {} -- item[itemId] = slot OvaleActionBar.item = {} --</public-static-properties> --<private-static-methods> local function GetKeyBinding(slot) --[[ ACTIONBUTTON1..12 => primary (1..12, 13..24), bonus (73..120) MULTIACTIONBAR1BUTTON1..12 => bottom left (61..72) MULTIACTIONBAR2BUTTON1..12 => bottom right (49..60) MULTIACTIONBAR3BUTTON1..12 => top right (25..36) MULTIACTIONBAR4BUTTON1..12 => top left (37..48) --]] local name if slot <= 24 or slot > 72 then name = "ACTIONBUTTON" .. (((slot - 1)%12) + 1) elseif slot <= 36 then name = "MULTIACTIONBAR3BUTTON" .. (slot - 24) elseif slot <= 48 then name = "MULTIACTIONBAR4BUTTON" .. (slot - 36) elseif slot <= 60 then name = "MULTIACTIONBAR2BUTTON" .. (slot - 48) else name = "MULTIACTIONBAR1BUTTON" .. (slot - 60) end local key = name and API_GetBindingKey(name) return key end local function ParseHyperlink(hyperlink) local color, linkType, linkData, text = strmatch(hyperlink, "|?c?f?f?(%x*)|?H?([^:]*):?(%d+)|?h?%[?([^%[%]]*)%]?|?h?|?r?") return color, linkType, linkData, text end --</private-static-methods> --<public-static-methods> function OvaleActionBar:OnEnable() self:RegisterEvent("ACTIONBAR_SLOT_CHANGED") self:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED", "UpdateActionSlots") self:RegisterEvent("PLAYER_ENTERING_WORLD", "UpdateActionSlots") self:RegisterEvent("PLAYER_TALENT_UPDATE", "UpdateActionSlots") self:RegisterEvent("UPDATE_BINDINGS") self:RegisterEvent("UPDATE_BONUS_ACTIONBAR", "UpdateActionSlots") end function OvaleActionBar:OnDisable() self:UnregisterEvent("ACTIONBAR_SLOT_CHANGED") self:UnregisterEvent("ACTIVE_TALENT_GROUP_CHANGED") self:UnregisterEvent("PLAYER_ENTERING_WORLD") self:UnregisterEvent("PLAYER_TALENT_UPDATE") self:UnregisterEvent("UPDATE_BINDINGS") self:UnregisterEvent("UPDATE_BONUS_ACTIONBAR") end function OvaleActionBar:ACTIONBAR_SLOT_CHANGED(event, slot) slot = tonumber(slot) if slot == 0 then self:UpdateActionSlots(event) elseif slot then self:UpdateActionSlot(slot) end end function OvaleActionBar:UPDATE_BINDINGS(event) Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "%s: Updating key bindings.", event) for slot = 1, 120 do self.keybind[slot] = GetKeyBinding(slot) end end function OvaleActionBar:UpdateActionSlots(event) Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "%s: Updating all action slot mappings.", event) wipe(self.action) wipe(self.item) wipe(self.macro) wipe(self.spell) local start = 1 local bonus = tonumber(API_GetBonusBarIndex()) * 12 if bonus > 0 then start = 13 for slot = bonus - 11, bonus do self:UpdateActionSlot(slot) end end for slot = start, 72 do self:UpdateActionSlot(slot) end end function OvaleActionBar:UpdateActionSlot(slot) -- Clear old slot and associated actions. local action = self.action[slot] if self.spell[action] == slot then self.spell[action] = nil elseif self.item[action] == slot then self.item[action] = nil elseif self.macro[action] == slot then self.macro[action] = nil end self.action[slot] = nil -- Map the current action in the slot. local actionType, id, subType = API_GetActionInfo(slot) if actionType == "spell" then id = tonumber(id) if id then if not self.spell[id] or slot < self.spell[id] then self.spell[id] = slot end self.action[slot] = id end elseif actionType == "item" then id = tonumber(id) if id then if not self.item[id] or slot < self.item[id] then self.item[id] = slot end self.action[slot] = id end elseif actionType == "macro" then id = tonumber(id) if id then local actionText = API_GetActionText(slot) if actionText then if not self.macro[actionText] or slot < self.macro[actionText] then self.macro[actionText] = slot end local _, _, spellId = API_GetMacroSpell(id) if spellId then if not self.spell[spellId] or slot < self.spell[spellId] then self.spell[spellId] = slot end self.action[slot] = spellId else local _, hyperlink = API_GetMacroItem(id) if hyperlink then local _, _, linkData = ParseHyperlink(hyperlink) local itemId = gsub(linkData, ":.*", "") itemId = tonumber(itemId) if itemId then if not self.item[itemId] or slot < self.item[itemId] then self.item[itemId] = slot end self.action[slot] = itemId end end end if not self.action[slot] then self.action[slot] = actionText end end end end Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "Mapping button %s to %s", slot, self.action[slot]) -- Update the keybind for the slot. self.keybind[slot] = GetKeyBinding(slot) end -- Get the action slot that matches a spell ID. function OvaleActionBar:GetForSpell(spellId) return self.spell[spellId] end -- Get the action slot that matches a macro name. function OvaleActionBar:GetForMacro(macroName) return self.macro[macroName] end -- Get the action slot that matches an item ID. function OvaleActionBar:GetForItem(itemId) return self.item[itemId] end -- Get the keybinding for an action slot. function OvaleActionBar:GetBinding(slot) return self.keybind[slot] end --</public-static-methods>
Fix ticket 352 - Improve showing of keybindings.
Fix ticket 352 - Improve showing of keybindings. Update keybindings shown on the icon based on stance. Also update keybindings for spell/item shown in a macro based on what will be cast if it is used. Original diff by @chipzzke with extension to macro items by @jlam. git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1415 d5049fe3-3747-40f7-a4b5-f36d6801af5f
Lua
mit
eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale
6a2bb359fdb3bb6a2a2545f46d70e83d608ca49b
applications/luci-splash/luasrc/controller/splash/splash.lua
applications/luci-splash/luasrc/controller/splash/splash.lua
module("luci.controller.splash.splash", package.seeall) function index() entry({"admin", "services", "splash"}, cbi("splash/splash"), "Client-Splash") node("splash").target = call("action_dispatch") node("splash", "activate").target = call("action_activate") node("splash", "splash").target = template("splash_splash/splash") end function action_dispatch() local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or "" local status = luci.util.execl("luci-splash status "..mac)[1] if #mac > 0 and ( status == "whitelisted" or status == "lease" ) then luci.http.redirect(luci.dispatcher.build_url()) else luci.http.redirect(luci.dispatcher.build_url("splash", "splash")) end end function action_activate() local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) if mac and luci.http.formvalue("accept") then os.execute("luci-splash add "..mac.." >/dev/null 2>&1") luci.http.redirect(luci.model.uci.cursor():get("freifunk", "community", "homepage")) else luci.http.redirect(luci.dispatcher.build_url()) end end
module("luci.controller.splash.splash", package.seeall) function index() entry({"admin", "services", "splash"}, cbi("splash/splash"), "Client-Splash") node("splash").target = call("action_dispatch") node("splash", "activate").target = call("action_activate") node("splash", "splash").target = template("splash_splash/splash") end function action_dispatch() local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or "" local status = luci.util.execl("luci-splash status "..mac)[1] if #mac > 0 and ( status == "whitelisted" or status == "lease" ) then luci.http.redirect(luci.dispatcher.build_url()) else luci.http.redirect(luci.dispatcher.build_url("splash", "splash")) end end function action_activate() local ip = luci.http.getenv("REMOTE_ADDR") or "127.0.0.1" local mac = luci.sys.net.ip4mac(ip:match("^[\[::ffff:]*(%d+.%d+%.%d+%.%d+)\]*$")) if mac and luci.http.formvalue("accept") then os.execute("luci-splash add "..mac.." >/dev/null 2>&1") luci.http.redirect(luci.model.uci.cursor():get("freifunk", "community", "homepage")) else luci.http.redirect(luci.dispatcher.build_url()) end end
applications/luci-splash: properly fix mac address detection in mixed IPv4/IPv6 environments (thanks stargieg)
applications/luci-splash: properly fix mac address detection in mixed IPv4/IPv6 environments (thanks stargieg)
Lua
apache-2.0
LuttyYang/luci,nmav/luci,palmettos/test,cshore/luci,nwf/openwrt-luci,keyidadi/luci,oyido/luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,maxrio/luci981213,aa65535/luci,david-xiao/luci,oneru/luci,dismantl/luci-0.12,mumuqz/luci,shangjiyu/luci-with-extra,MinFu/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,bright-things/ionic-luci,mumuqz/luci,wongsyrone/luci-1,981213/luci-1,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/cnLuCI,ff94315/luci-1,opentechinstitute/luci,cshore-firmware/openwrt-luci,thesabbir/luci,harveyhu2012/luci,LuttyYang/luci,taiha/luci,opentechinstitute/luci,nmav/luci,cshore-firmware/openwrt-luci,keyidadi/luci,urueedi/luci,cappiewu/luci,artynet/luci,dwmw2/luci,dwmw2/luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,teslamint/luci,maxrio/luci981213,jorgifumi/luci,remakeelectric/luci,daofeng2015/luci,lcf258/openwrtcn,oneru/luci,jorgifumi/luci,thesabbir/luci,urueedi/luci,hnyman/luci,deepak78/new-luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,harveyhu2012/luci,zhaoxx063/luci,zhaoxx063/luci,rogerpueyo/luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,urueedi/luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,urueedi/luci,florian-shellfire/luci,Wedmer/luci,mumuqz/luci,daofeng2015/luci,male-puppies/luci,kuoruan/lede-luci,florian-shellfire/luci,harveyhu2012/luci,chris5560/openwrt-luci,MinFu/luci,zhaoxx063/luci,marcel-sch/luci,oneru/luci,deepak78/new-luci,kuoruan/lede-luci,thess/OpenWrt-luci,lcf258/openwrtcn,Hostle/luci,maxrio/luci981213,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,obsy/luci,cshore/luci,NeoRaider/luci,Wedmer/luci,kuoruan/luci,remakeelectric/luci,taiha/luci,schidler/ionic-luci,remakeelectric/luci,jorgifumi/luci,hnyman/luci,bright-things/ionic-luci,jchuang1977/luci-1,forward619/luci,981213/luci-1,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,cshore/luci,maxrio/luci981213,slayerrensky/luci,schidler/ionic-luci,thess/OpenWrt-luci,obsy/luci,marcel-sch/luci,deepak78/new-luci,lcf258/openwrtcn,tobiaswaldvogel/luci,remakeelectric/luci,teslamint/luci,chris5560/openwrt-luci,Hostle/luci,lbthomsen/openwrt-luci,sujeet14108/luci,LuttyYang/luci,tcatm/luci,kuoruan/lede-luci,david-xiao/luci,MinFu/luci,sujeet14108/luci,david-xiao/luci,bright-things/ionic-luci,ollie27/openwrt_luci,Noltari/luci,artynet/luci,zhaoxx063/luci,lbthomsen/openwrt-luci,aa65535/luci,thesabbir/luci,florian-shellfire/luci,palmettos/test,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,jchuang1977/luci-1,aa65535/luci,openwrt/luci,cshore/luci,tcatm/luci,kuoruan/lede-luci,jlopenwrtluci/luci,fkooman/luci,thesabbir/luci,aa65535/luci,palmettos/test,male-puppies/luci,aircross/OpenWrt-Firefly-LuCI,joaofvieira/luci,kuoruan/luci,obsy/luci,nwf/openwrt-luci,oyido/luci,harveyhu2012/luci,obsy/luci,slayerrensky/luci,david-xiao/luci,lcf258/openwrtcn,palmettos/test,ff94315/luci-1,obsy/luci,tcatm/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,cshore/luci,dismantl/luci-0.12,dismantl/luci-0.12,nmav/luci,sujeet14108/luci,Kyklas/luci-proto-hso,harveyhu2012/luci,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,cshore/luci,Hostle/luci,cshore-firmware/openwrt-luci,981213/luci-1,daofeng2015/luci,fkooman/luci,dismantl/luci-0.12,oyido/luci,mumuqz/luci,nmav/luci,nwf/openwrt-luci,teslamint/luci,cappiewu/luci,Noltari/luci,tcatm/luci,palmettos/test,slayerrensky/luci,RuiChen1113/luci,oyido/luci,openwrt/luci,LuttyYang/luci,jlopenwrtluci/luci,RedSnake64/openwrt-luci-packages,Sakura-Winkey/LuCI,bittorf/luci,981213/luci-1,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,forward619/luci,slayerrensky/luci,lbthomsen/openwrt-luci,cappiewu/luci,teslamint/luci,male-puppies/luci,forward619/luci,RuiChen1113/luci,Kyklas/luci-proto-hso,mumuqz/luci,ff94315/luci-1,Kyklas/luci-proto-hso,taiha/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,jlopenwrtluci/luci,bittorf/luci,nwf/openwrt-luci,NeoRaider/luci,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,teslamint/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,Hostle/luci,dwmw2/luci,remakeelectric/luci,lbthomsen/openwrt-luci,Hostle/luci,wongsyrone/luci-1,kuoruan/lede-luci,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,sujeet14108/luci,male-puppies/luci,artynet/luci,schidler/ionic-luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,MinFu/luci,RuiChen1113/luci,jorgifumi/luci,openwrt/luci,florian-shellfire/luci,slayerrensky/luci,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,bittorf/luci,marcel-sch/luci,jlopenwrtluci/luci,opentechinstitute/luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,remakeelectric/luci,hnyman/luci,chris5560/openwrt-luci,RuiChen1113/luci,dwmw2/luci,remakeelectric/luci,urueedi/luci,Noltari/luci,maxrio/luci981213,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,sujeet14108/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,daofeng2015/luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,marcel-sch/luci,thess/OpenWrt-luci,oneru/luci,ff94315/luci-1,florian-shellfire/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,RuiChen1113/luci,bittorf/luci,Hostle/openwrt-luci-multi-user,tobiaswaldvogel/luci,LuttyYang/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,taiha/luci,cshore/luci,dwmw2/luci,maxrio/luci981213,zhaoxx063/luci,deepak78/new-luci,dismantl/luci-0.12,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,wongsyrone/luci-1,urueedi/luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,deepak78/new-luci,kuoruan/luci,cappiewu/luci,kuoruan/luci,remakeelectric/luci,NeoRaider/luci,artynet/luci,RuiChen1113/luci,NeoRaider/luci,rogerpueyo/luci,deepak78/new-luci,slayerrensky/luci,thesabbir/luci,zhaoxx063/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,Wedmer/luci,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,openwrt-es/openwrt-luci,palmettos/cnLuCI,florian-shellfire/luci,Kyklas/luci-proto-hso,nmav/luci,thess/OpenWrt-luci,bittorf/luci,openwrt/luci,openwrt-es/openwrt-luci,teslamint/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,Noltari/luci,981213/luci-1,openwrt/luci,joaofvieira/luci,oyido/luci,male-puppies/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,Noltari/luci,forward619/luci,daofeng2015/luci,cappiewu/luci,fkooman/luci,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,rogerpueyo/luci,artynet/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,schidler/ionic-luci,keyidadi/luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,ff94315/luci-1,chris5560/openwrt-luci,fkooman/luci,NeoRaider/luci,openwrt-es/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,male-puppies/luci,david-xiao/luci,nmav/luci,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,db260179/openwrt-bpi-r1-luci,bittorf/luci,opentechinstitute/luci,RuiChen1113/luci,jorgifumi/luci,joaofvieira/luci,thess/OpenWrt-luci,rogerpueyo/luci,tcatm/luci,palmettos/cnLuCI,kuoruan/lede-luci,kuoruan/luci,MinFu/luci,keyidadi/luci,hnyman/luci,nwf/openwrt-luci,jlopenwrtluci/luci,nmav/luci,david-xiao/luci,oneru/luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,openwrt/luci,sujeet14108/luci,Wedmer/luci,lcf258/openwrtcn,lbthomsen/openwrt-luci,maxrio/luci981213,fkooman/luci,RuiChen1113/luci,aa65535/luci,jchuang1977/luci-1,981213/luci-1,bittorf/luci,dwmw2/luci,palmettos/cnLuCI,dismantl/luci-0.12,rogerpueyo/luci,MinFu/luci,hnyman/luci,Sakura-Winkey/LuCI,florian-shellfire/luci,daofeng2015/luci,bright-things/ionic-luci,forward619/luci,cshore-firmware/openwrt-luci,forward619/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,marcel-sch/luci,schidler/ionic-luci,Sakura-Winkey/LuCI,taiha/luci,opentechinstitute/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,chris5560/openwrt-luci,joaofvieira/luci,bright-things/ionic-luci,Wedmer/luci,rogerpueyo/luci,urueedi/luci,david-xiao/luci,artynet/luci,RedSnake64/openwrt-luci-packages,oyido/luci,mumuqz/luci,wongsyrone/luci-1,palmettos/test,kuoruan/luci,thess/OpenWrt-luci,tcatm/luci,lcf258/openwrtcn,slayerrensky/luci,Noltari/luci,palmettos/cnLuCI,wongsyrone/luci-1,chris5560/openwrt-luci,daofeng2015/luci,teslamint/luci,keyidadi/luci,urueedi/luci,NeoRaider/luci,ff94315/luci-1,teslamint/luci,kuoruan/luci,thesabbir/luci,ff94315/luci-1,oneru/luci,LuttyYang/luci,oyido/luci,marcel-sch/luci,NeoRaider/luci,keyidadi/luci,lcf258/openwrtcn,chris5560/openwrt-luci,taiha/luci,joaofvieira/luci,Wedmer/luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,hnyman/luci,ollie27/openwrt_luci,aa65535/luci,maxrio/luci981213,MinFu/luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,taiha/luci,tcatm/luci,LuttyYang/luci,slayerrensky/luci,jorgifumi/luci,fkooman/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,openwrt/luci,MinFu/luci,joaofvieira/luci,wongsyrone/luci-1,sujeet14108/luci,lcf258/openwrtcn,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,palmettos/cnLuCI,cshore-firmware/openwrt-luci,lcf258/openwrtcn,david-xiao/luci,keyidadi/luci,Wedmer/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,tcatm/luci,forward619/luci,forward619/luci,mumuqz/luci,joaofvieira/luci,obsy/luci,wongsyrone/luci-1,openwrt/luci,cshore/luci,zhaoxx063/luci,Kyklas/luci-proto-hso,opentechinstitute/luci,nwf/openwrt-luci,ollie27/openwrt_luci,NeoRaider/luci,harveyhu2012/luci,male-puppies/luci,wongsyrone/luci-1,jchuang1977/luci-1,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,cappiewu/luci,jchuang1977/luci-1,harveyhu2012/luci,sujeet14108/luci,male-puppies/luci,oneru/luci,deepak78/new-luci,taiha/luci,RedSnake64/openwrt-luci-packages,ReclaimYourPrivacy/cloak-luci,artynet/luci,Noltari/luci,jorgifumi/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,jorgifumi/luci,fkooman/luci,ollie27/openwrt_luci,dwmw2/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,thess/OpenWrt-luci,ollie27/openwrt_luci,981213/luci-1,keyidadi/luci,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,jlopenwrtluci/luci,palmettos/cnLuCI,daofeng2015/luci,oyido/luci,Hostle/openwrt-luci-multi-user,bittorf/luci,shangjiyu/luci-with-extra,Hostle/luci,aa65535/luci,jchuang1977/luci-1,oneru/luci,nwf/openwrt-luci,rogerpueyo/luci,kuoruan/luci,dismantl/luci-0.12,cappiewu/luci,Kyklas/luci-proto-hso,artynet/luci,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,artynet/luci
4f54218546108cc9558c191d1b1bde5f9f91a757
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 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 sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", Value, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" toport.datatype = "portrange" toport:depends("proto", "tcp") toport:depends("proto", "udp") toport:depends("proto", "tcpudp") target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "neg_ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 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 sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", Value, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" toport.datatype = "portrange" toport:depends("proto", "tcp") toport:depends("proto", "udp") toport:depends("proto", "tcpudp") target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "neg_ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection.default = reflection.enabled reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
applications/luci-firewall: fix turning off nat reflection
applications/luci-firewall: fix turning off nat reflection git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@7338 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,freifunk-gluon/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,stephank/luci,jschmidlapp/luci,phi-psi/luci,jschmidlapp/luci,saraedum/luci-packages-old,ch3n2k/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,gwlim/luci,gwlim/luci,projectbismark/luci-bismark,Flexibity/luci,projectbismark/luci-bismark,vhpham80/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,freifunk-gluon/luci,Flexibity/luci,yeewang/openwrt-luci,phi-psi/luci,8devices/carambola2-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,jschmidlapp/luci,freifunk-gluon/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,projectbismark/luci-bismark,stephank/luci,phi-psi/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,stephank/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,vhpham80/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,8devices/carambola2-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,jschmidlapp/luci,ch3n2k/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,stephank/luci,phi-psi/luci,vhpham80/luci,freifunk-gluon/luci,Flexibity/luci,Flexibity/luci,projectbismark/luci-bismark,ch3n2k/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,projectbismark/luci-bismark,yeewang/openwrt-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,stephank/luci,freifunk-gluon/luci,vhpham80/luci,ThingMesh/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,gwlim/luci,eugenesan/openwrt-luci,stephank/luci,saraedum/luci-packages-old,ch3n2k/luci,zwhfly/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,8devices/carambola2-luci,Flexibity/luci,Flexibity/luci,ThingMesh/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,ch3n2k/luci,jschmidlapp/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,Flexibity/luci
872d5d6c20a9e25990fb658e04583d8124cb0633
protocols/6x4/luasrc/model/network/proto_6x4.lua
protocols/6x4/luasrc/model/network/proto_6x4.lua
--[[ LuCI - Network model - 6to4 & 6in4 protocol extension 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local _, p for _, p in ipairs({"6in4", "6to4"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "6in4" then return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)") elseif p == "6to4" then return luci.i18n.translate("IPv6-over-IPv4") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) return p end function proto.is_installed(self) return nixio.fs.access("/lib/network/" .. p .. ".sh") end function proto.is_floating(self) return true end function proto.is_virtual(self) return true end function proto.get_interfaces(self) return nil end function proto.contains_interface(self, ifname) return (netmod:ifnameof(ifc) == self:ifname()) end netmod:register_pattern_virtual("^%s-%%w" % p) end
--[[ LuCI - Network model - 6to4 & 6in4 protocol extension 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local _, p for _, p in ipairs({"6in4", "6to4"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "6in4" then return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)") elseif p == "6to4" then return luci.i18n.translate("IPv6-over-IPv4") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) return p end function proto.is_installed(self) return nixio.fs.access("/lib/network/" .. p .. ".sh") or nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh") end function proto.is_floating(self) return true end function proto.is_virtual(self) return true end function proto.get_interfaces(self) return nil end function proto.contains_interface(self, ifname) return (netmod:ifnameof(ifc) == self:ifname()) end netmod:register_pattern_virtual("^%s-%%w" % p) end
protocols/6x4: fix install state detection with netifd
protocols/6x4: fix install state detection with netifd git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8656 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
jschmidlapp/luci,ch3n2k/luci,Flexibity/luci,ch3n2k/luci,saraedum/luci-packages-old,vhpham80/luci,8devices/carambola2-luci,phi-psi/luci,phi-psi/luci,Flexibity/luci,jschmidlapp/luci,Flexibity/luci,jschmidlapp/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,vhpham80/luci,gwlim/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,ch3n2k/luci,zwhfly/openwrt-luci,stephank/luci,freifunk-gluon/luci,yeewang/openwrt-luci,gwlim/luci,gwlim/luci,Canaan-Creative/luci,jschmidlapp/luci,8devices/carambola2-luci,jschmidlapp/luci,saraedum/luci-packages-old,stephank/luci,phi-psi/luci,ch3n2k/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,Flexibity/luci,stephank/luci,zwhfly/openwrt-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,ch3n2k/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,freifunk-gluon/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,zwhfly/openwrt-luci,jschmidlapp/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci,phi-psi/luci,stephank/luci,vhpham80/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,phi-psi/luci,gwlim/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,vhpham80/luci,Canaan-Creative/luci,yeewang/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,ch3n2k/luci,saraedum/luci-packages-old,vhpham80/luci,freifunk-gluon/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,saraedum/luci-packages-old,freifunk-gluon/luci,8devices/carambola2-luci,stephank/luci,Flexibity/luci,ThingMesh/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,Flexibity/luci
55d710904266ebbb8f98f44dda8bc23211e351e8
plugins/terminal.koplugin/main.lua
plugins/terminal.koplugin/main.lua
local DataStorage = require("datastorage") local Font = require("ui/font") local InfoMessage = require("ui/widget/infomessage") local InputDialog = require("ui/widget/inputdialog") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local logger = require("logger") local util = require("ffi/util") local _ = require("gettext") local Screen = require("device").screen local Terminal = WidgetContainer:new{ name = "terminal", dump_file = util.realpath(DataStorage:getDataDir()) .. "/terminal_output.txt", command = "", } function Terminal:init() self.ui.menu:registerToMainMenu(self) end function Terminal:start() self.input = InputDialog:new{ title = _("Enter a command and press \"Execute\""), input = self.command, para_direction_rtl = false, -- force LTR text_height = Screen:getHeight() * 0.4, input_type = "string", buttons = {{{ text = _("Cancel"), callback = function() UIManager:close(self.input) end, }, { text = _("Execute"), is_enter_default = true, callback = function() UIManager:close(self.input) self:execute() end, }}}, } UIManager:show(self.input) self.input:onShowKeyboard() end function Terminal:execute() self.command = self.input:getInputText() UIManager:show(InfoMessage:new{ text = _("Executing…"), timeout = 0.1, }) UIManager:forceRePaint() local std_out = io.popen(self.command) local entries = { self.command } if std_out then while true do local line = std_out:read() if line == nil then break end table.insert(entries, line) end std_out:close() else table.insert(entries, _("Failed to execute command.")) end self:dump(entries) table.insert(entries, _("Output will also be written to")) table.insert(entries, self.dump_file) UIManager:show(InfoMessage:new{ cface = Font:getFace("xx_smallinfofont"), text = _("Command output\n") .. table.concat(entries, "\n"), show_icon = false, width = Screen:getWidth() * 0.8, height = Screen:getHeight() * 0.8, }) end function Terminal:dump(entries) local content = table.concat(entries, "\n") local file = io.open(self.dump_file, "w") if file then file:write(content) file:close() else logger.warn("Failed to dump terminal output " .. content .. " to " .. self.dump_file) end end function Terminal:addToMainMenu(menu_items) menu_items.terminal = { text = _("Terminal emulator"), keep_menu_open = true, callback = function() self:start() end, } end return Terminal
local DataStorage = require("datastorage") local Font = require("ui/font") local InfoMessage = require("ui/widget/infomessage") local InputDialog = require("ui/widget/inputdialog") local TextViewer = require("ui/widget/textviewer") local Trapper = require("ui/trapper") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local logger = require("logger") local util = require("ffi/util") local _ = require("gettext") local Screen = require("device").screen local Terminal = WidgetContainer:new{ name = "terminal", dump_file = util.realpath(DataStorage:getDataDir()) .. "/terminal_output.txt", command = "", } function Terminal:init() self.ui.menu:registerToMainMenu(self) end function Terminal:start() self.input = InputDialog:new{ title = _("Enter a command and press \"Execute\""), input = self.command, para_direction_rtl = false, -- force LTR text_height = Screen:getHeight() * 0.4, input_type = "string", buttons = {{{ text = _("Cancel"), callback = function() UIManager:close(self.input) end, }, { text = _("Execute"), is_enter_default = true, callback = function() UIManager:close(self.input) Trapper:wrap(function() self:execute() end) end, }}}, } UIManager:show(self.input) self.input:onShowKeyboard() end function Terminal:execute() self.command = self.input:getInputText() local wait_msg = InfoMessage:new{ text = _("Executing…"), } UIManager:show(wait_msg) local entries = { self.command } local command = self.command .. " 2>&1 ; echo" -- ensure we get stderr and output something local completed, result_str = Trapper:dismissablePopen(command, wait_msg) if completed then table.insert(entries, result_str) self:dump(entries) table.insert(entries, _("Output was also written to")) table.insert(entries, self.dump_file) else table.insert(entries, _("Execution canceled.")) end UIManager:close(wait_msg) UIManager:show(TextViewer:new{ title = _("Command output"), text = table.concat(entries, "\n"), justified = false, text_face = Font:getFace("smallinfont"), }) end function Terminal:dump(entries) local content = table.concat(entries, "\n") local file = io.open(self.dump_file, "w") if file then file:write(content) file:close() else logger.warn("Failed to dump terminal output " .. content .. " to " .. self.dump_file) end end function Terminal:addToMainMenu(menu_items) menu_items.terminal = { text = _("Terminal emulator"), keep_menu_open = true, callback = function() self:start() end, } end return Terminal
Terminal plugin: a few tweaks (#5985)
Terminal plugin: a few tweaks (#5985) - Show output in a TextViewer with a monospace font. - Include stderr, so errors are shown - Use Trapper to allow interrupting command (and to fix some refresh issues)
Lua
agpl-3.0
Frenzie/koreader,Hzj-jie/koreader,Frenzie/koreader,mihailim/koreader,NiLuJe/koreader,NiLuJe/koreader,mwoz123/koreader,Markismus/koreader,poire-z/koreader,poire-z/koreader,pazos/koreader,koreader/koreader,koreader/koreader
9d8d3180801fc00940e5d75eda42f395846429a3
mod_blocking/mod_blocking.lua
mod_blocking/mod_blocking.lua
module:add_feature("urn:xmpp:blocking"); -- Add JID to default privacy list function add_blocked_jid(username, host, jid) local privacy_lists = datamanager.load(username, host, "privacy") or {}; local default_list_name = privacy_lists.default; if not default_list_name then default_list_name = "blocklist"; privacy_lists.default = default_list_name; end local default_list = privacy_lists.list[default_list_name]; if not default_list then default_list = { name = default_list_name, items = {} }; privacy_lists.lists[default_list_name] = default_list; end local items = default_list.items; local order = items[1].order; -- Must come first for i=1,#items do -- order must be unique items[i].order = items[i].order + 1; end table.insert(items, 1, { type = "jid" , action = "deny" , value = jid , message = false , ["presence-out"] = false , ["presence-in"] = false , iq = false , order = order }; datamanager.store(username, host, "privacy", privacy_lists); end -- Remove JID from default privacy list function remove_blocked_jid(username, host, jid) local privacy_lists = datamanager.load(username, host, "privacy") or {}; local default_list_name = privacy_lists.default; if not default_list_name then return; end local default_list = privacy_lists.list[default_list_name]; if not default_list then return; end local items = default_list.items; local item; for i=1,#items do -- order must be unique item = items[i]; if item.type == "jid" and item.action == "deny" and item.value == jid then table.remove(items, i); return true; end end end function get_blocked_jids(username, host) -- Return array of blocked JIDs in default privacy list local privacy_lists = datamanager.load(username, host, "privacy") or {}; local default_list_name = privacy_lists.default; if not default_list_name then return {}; end local default_list = privacy_lists.list[default_list_name]; if not default_list then return {}; end local items = default_list.items; local item; local jid_list = {}; for i=1,#items do -- order must be unique item = items[i]; if item.type == "jid" and item.action == "deny" then jid_list[#jid_list+1] = item.value; end end return jid_list; end function handle_blocking_command(session, stanza) local username, host = jid_split(stanza.attr.from); if stanza.attr.type == "set" and stanza.tags[1].name == "block" then local block = stanza.tags[1]:get_child("block"); local block_jid_list = {}; for item in block:childtags() do block_jid_list[#block_jid_list+1] = item.attr.jid; end if #block_jid_list == 0 then --FIXME: Reply bad-request else for _, jid in ipairs(block_jid_list) do add_blocked_jid(username, host, jid); end session.send(st.reply(stanza)); end elseif stanza.attr.type == "get" and stanza.tags[1].name == "blocklist" then local reply = st.reply(stanza):tag("blocklist", { xmlns = xmlns_block }); local blocked_jids = get_blocked_jids(username, host); for _, jid in ipairs(blocked_jids) do reply:tag("item", { jid = jid }):up(); end session.send(reply); else --FIXME: Need to respond with service-unavailable end end module:add_iq_handler("c2s", xmlns_blocking, handle_blocking_command);
module:add_feature("urn:xmpp:blocking"); -- Add JID to default privacy list function add_blocked_jid(username, host, jid) local privacy_lists = datamanager.load(username, host, "privacy") or {}; local default_list_name = privacy_lists.default; if not default_list_name then default_list_name = "blocklist"; privacy_lists.default = default_list_name; end local default_list = privacy_lists.list[default_list_name]; if not default_list then default_list = { name = default_list_name, items = {} }; privacy_lists.lists[default_list_name] = default_list; end local items = default_list.items; local order = items[1].order; -- Must come first for i=1,#items do -- order must be unique items[i].order = items[i].order + 1; end table.insert(items, 1, { type = "jid" , action = "deny" , value = jid , message = false , ["presence-out"] = false , ["presence-in"] = false , iq = false , order = order }; datamanager.store(username, host, "privacy", privacy_lists); end -- Remove JID from default privacy list function remove_blocked_jid(username, host, jid) local privacy_lists = datamanager.load(username, host, "privacy") or {}; local default_list_name = privacy_lists.default; if not default_list_name then return; end local default_list = privacy_lists.list[default_list_name]; if not default_list then return; end local items = default_list.items; local item; for i=1,#items do -- order must be unique item = items[i]; if item.type == "jid" and item.action == "deny" and item.value == jid then table.remove(items, i); return true; end end datamanager.store(username, host, "privacy", privacy_lists); end function remove_all_blocked_jids(username, host) local privacy_lists = datamanager.load(username, host, "privacy") or {}; local default_list_name = privacy_lists.default; if not default_list_name then return; end local default_list = privacy_lists.list[default_list_name]; if not default_list then return; end local items = default_list.items; local item; for i=#items,1 do -- order must be unique item = items[i]; if item.type == "jid" and item.action == "deny" then table.remove(items, i); end end datamanager.store(username, host, "privacy", privacy_lists); end function get_blocked_jids(username, host) -- Return array of blocked JIDs in default privacy list local privacy_lists = datamanager.load(username, host, "privacy") or {}; local default_list_name = privacy_lists.default; if not default_list_name then return {}; end local default_list = privacy_lists.list[default_list_name]; if not default_list then return {}; end local items = default_list.items; local item; local jid_list = {}; for i=1,#items do -- order must be unique item = items[i]; if item.type == "jid" and item.action == "deny" then jid_list[#jid_list+1] = item.value; end end return jid_list; end function handle_blocking_command(session, stanza) local username, host = jid_split(stanza.attr.from); if stanza.attr.type == "set" then if stanza.tags[1].name == "block" then local block = stanza.tags[1]:get_child("block"); local block_jid_list = {}; for item in block:childtags() do block_jid_list[#block_jid_list+1] = item.attr.jid; end if #block_jid_list == 0 then --FIXME: Reply bad-request else for _, jid in ipairs(block_jid_list) do add_blocked_jid(username, host, jid); end session.send(st.reply(stanza)); end elseif stanza.tags[1].name == "unblock" then remove_all_blocked_jids(username, host); session.send(st.reply(stanza)); end elseif stanza.attr.type == "get" and stanza.tags[1].name == "blocklist" then local reply = st.reply(stanza):tag("blocklist", { xmlns = xmlns_block }); local blocked_jids = get_blocked_jids(username, host); for _, jid in ipairs(blocked_jids) do reply:tag("item", { jid = jid }):up(); end session.send(reply); else --FIXME: Need to respond with service-unavailable end end module:add_iq_handler("c2s", xmlns_blocking, handle_blocking_command);
mod_blocking: Support for the "unblock all JIDs" case, and fix saving of rules after removing a JID
mod_blocking: Support for the "unblock all JIDs" case, and fix saving of rules after removing a JID
Lua
mit
olax/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,apung/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,crunchuser/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,either1/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,heysion/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,jkprg/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,softer/prosody-modules,cryptotoad/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,softer/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,prosody-modules/import,stephen322/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules
557dcec842d99b1f89cb2ecba6c35873a366aa83
modules/http/http.lua
modules/http/http.lua
module("http", package.seeall) local function str(char) return string.char(char) end local function getchar(stream) local char while true do char = stream:getchar() if char == -1 then coroutine.yield() else break end end return char end local function read_line(stream) local line = "" local char, c local read = 0 while true do c = getchar(stream) read = read+1 char = str(c) if c == 0xd then c = getchar(stream) read = read+1 if c == 0xa then return line, read else line = line .. char char = str(c) end elseif c == 0xa then return line, read end line = line .. char end end -- The comparison is broken in Lua 5.1, so we need to reimplement the -- string comparison local function string_compare(a, b) if type(a) == "string" and type(b) == "string" then local i = 1 local sa = #a local sb = #b while true do if i > sa then return false elseif i > sb then return true end if a:byte(i) < b:byte(i) then return true elseif a:byte(i) > b:byte(i) then return false end i = i+1 end return false else return a < b end end function sorted_pairs(t) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, string_compare) local i = 0 local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function dump(t, indent) for n, v in sorted_pairs(t) do if type(v) == "table" then print(indent, n) dump(v, indent .. " ") elseif type(v) ~= "thread" and type(v) ~= "userdata" and type(v) ~= "function" then print(indent, n, "=", v) end end end local function parse_header(stream, http) local total_len = 0 http.headers = {} http._headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("([^%s]+):%s*(.+)") if not name then http._invalid = string.format("invalid header '%s'", line) return end http.headers[name] = value table.insert(http._headers_order, name) line, len = read_line(stream) total_len = total_len + len end return total_len end local function parse_request(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.method, http.uri, http.version = line:match("([^%s]+) ([^%s]+) (.+)") if not http.method then http._invalid = string.format("invalid request '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = function (self) dump(self, "") end return true end local function parse_response(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.version, http.status, http.reason = line:match("([^%s]+) ([^%s]+) (.+)") if not http.version then http._invalid = string.format("invalid response '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = function (self) dump(self, "") end return true end local function build_headers(stream, headers, headers_order) local copy = headers for _, name in pairs(headers_order) do local value = copy[name] if value then copy[name] = nil stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end for name, value in pairs(copy) do if value then stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end end local function forge(http) local tcp = http._tcp_stream if tcp then if http._state == 2 and tcp.direction then http._state = 3 if haka.packet.mode() ~= haka.packet.PASSTHROUGH then tcp.stream:seek(http.request._mark, true) http.request._mark = nil tcp.stream:erase(http.request._length) tcp.stream:insert(http.request.method) tcp.stream:insert(" ") tcp.stream:insert(http.request.uri) tcp.stream:insert(" ") tcp.stream:insert(http.request.version) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.request.headers, http.request._headers_order) tcp.stream:insert("\r\n") end elseif http._state == 5 and not tcp.direction then http._state = 0 if haka.packet.mode() ~= haka.packet.PASSTHROUGH then tcp.stream:seek(http.response._mark, true) http.response._mark = nil tcp.stream:erase(http.response._length) tcp.stream:insert(http.response.version) tcp.stream:insert(" ") tcp.stream:insert(http.response.status) tcp.stream:insert(" ") tcp.stream:insert(http.response.reason) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.response.headers, http.response._headers_order) tcp.stream:insert("\r\n") end end http._tcp_stream = nil end return tcp end local function parse(http, context, f, name, next_state) if not context._co then if haka.packet.mode() ~= haka.packet.PASSTHROUGH then context._mark = http._tcp_stream.stream:mark() end context._co = coroutine.create(function () f(http._tcp_stream.stream, context) end) end coroutine.resume(context._co) if coroutine.status(context._co) == "dead" then if not context._invalid then http._state = next_state if not haka.rule_hook("http-".. name, http) then return nil end context.next_dissector = http.next_dissector else haka.log.error("http", context._invalid) http._tcp_stream:drop() return nil end end end haka.dissector { name = "http", hooks = { "http-request", "http-response" }, dissect = function (stream) if not stream.connection.data._http then local http = {} http.dissector = "http" http.next_dissector = nil http.valid = function (self) return self._tcp_stream:valid() end http.drop = function (self) return self._tcp_stream:drop() end http.reset = function (self) return self._tcp_stream:reset() end http.forge = forge http._state = 0 stream.connection.data._http = http end local http = stream.connection.data._http http._tcp_stream = stream if stream.direction then if http._state == 0 or http._state == 1 then if stream.stream:available() > 0 then if http._state == 0 then http.request = {} http.response = nil http._state = 1 end parse(http, http.request, parse_request, "request", 2) end elseif http.request then http.next_dissector = http.request.next_dissector end else if http._state == 3 or http._state == 4 then if stream.stream:available() > 0 then if http._state == 3 then http.response = {} http._state = 4 end parse(http, http.response, parse_response, "response", 5) end elseif http.response then http.next_dissector = http.response.next_dissector end end return http end }
module("http", package.seeall) local str = string.char local function getchar(stream) local char while true do char = stream:getchar() if char == -1 then coroutine.yield() else break end end return char end local function read_line(stream) local line = "" local char, c local read = 0 while true do c = getchar(stream) read = read+1 char = str(c) if c == 0xd then c = getchar(stream) read = read+1 if c == 0xa then return line, read else line = line .. char char = str(c) end elseif c == 0xa then return line, read end line = line .. char end end -- The comparison is broken in Lua 5.1, so we need to reimplement the -- string comparison local function string_compare(a, b) if type(a) == "string" and type(b) == "string" then local i = 1 local sa = #a local sb = #b while true do if i > sa then return false elseif i > sb then return true end if a:byte(i) < b:byte(i) then return true elseif a:byte(i) > b:byte(i) then return false end i = i+1 end return false else return a < b end end function sorted_pairs(t) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, string_compare) local i = 0 return function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end end local function dump(t, indent) if not indent then indent = "" end for n, v in sorted_pairs(t) do if type(v) == "table" then print(indent, n) dump(v, indent .. " ") elseif type(v) ~= "thread" and type(v) ~= "userdata" and type(v) ~= "function" then print(indent, n, "=", v) end end end local function parse_header(stream, http) local total_len = 0 http.headers = {} http._headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("([^%s]+):%s*(.+)") if not name then http._invalid = string.format("invalid header '%s'", line) return end http.headers[name] = value table.insert(http._headers_order, name) line, len = read_line(stream) total_len = total_len + len end return total_len end local function parse_request(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.method, http.uri, http.version = line:match("([^%s]+) ([^%s]+) (.+)") if not http.method then http._invalid = string.format("invalid request '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = dump return true end local function parse_response(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.version, http.status, http.reason = line:match("([^%s]+) ([^%s]+) (.+)") if not http.version then http._invalid = string.format("invalid response '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = dump return true end local function build_headers(stream, headers, headers_order) for _, name in pairs(headers_order) do local value = headers[name] if value then headers[name] = nil stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end for name, value in pairs(headers) do if value then stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end end local function forge(http) local tcp = http._tcp_stream if tcp then if http._state == 2 and tcp.direction then http._state = 3 if haka.packet.mode() ~= haka.packet.PASSTHROUGH then tcp.stream:seek(http.request._mark, true) http.request._mark = nil tcp.stream:erase(http.request._length) tcp.stream:insert(http.request.method) tcp.stream:insert(" ") tcp.stream:insert(http.request.uri) tcp.stream:insert(" ") tcp.stream:insert(http.request.version) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.request.headers, http.request._headers_order) tcp.stream:insert("\r\n") end elseif http._state == 5 and not tcp.direction then http._state = 0 if haka.packet.mode() ~= haka.packet.PASSTHROUGH then tcp.stream:seek(http.response._mark, true) http.response._mark = nil tcp.stream:erase(http.response._length) tcp.stream:insert(http.response.version) tcp.stream:insert(" ") tcp.stream:insert(http.response.status) tcp.stream:insert(" ") tcp.stream:insert(http.response.reason) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.response.headers, http.response._headers_order) tcp.stream:insert("\r\n") end end http._tcp_stream = nil end return tcp end local function parse(http, context, f, name, next_state) if not context._co then if haka.packet.mode() ~= haka.packet.PASSTHROUGH then context._mark = http._tcp_stream.stream:mark() end context._co = coroutine.create(function () f(http._tcp_stream.stream, context) end) end coroutine.resume(context._co) if coroutine.status(context._co) == "dead" then if not context._invalid then http._state = next_state if not haka.rule_hook("http-".. name, http) then return nil end context.next_dissector = http.next_dissector else haka.log.error("http", context._invalid) http._tcp_stream:drop() return nil end end end haka.dissector { name = "http", hooks = { "http-request", "http-response" }, dissect = function (stream) if not stream.connection.data._http then local http = {} http.dissector = "http" http.next_dissector = nil http.valid = function (self) return self._tcp_stream:valid() end http.drop = function (self) return self._tcp_stream:drop() end http.reset = function (self) return self._tcp_stream:reset() end http.forge = forge http._state = 0 stream.connection.data._http = http end local http = stream.connection.data._http http._tcp_stream = stream if stream.direction then if http._state == 0 or http._state == 1 then if stream.stream:available() > 0 then if http._state == 0 then http.request = {} http.response = nil http._state = 1 end parse(http, http.request, parse_request, "request", 2) end elseif http.request then http.next_dissector = http.request.next_dissector end else if http._state == 3 or http._state == 4 then if stream.stream:available() > 0 then if http._state == 3 then http.response = {} http._state = 4 end parse(http, http.response, parse_response, "response", 5) end elseif http.response then http.next_dissector = http.response.next_dissector end end return http end }
Minor fix/optimisations to http.lua
Minor fix/optimisations to http.lua
Lua
mpl-2.0
lcheylus/haka,Wingless-Archangel/haka,Wingless-Archangel/haka,haka-security/haka,haka-security/haka,LubyRuffy/haka,nabilbendafi/haka,LubyRuffy/haka,nabilbendafi/haka,lcheylus/haka,nabilbendafi/haka,lcheylus/haka,haka-security/haka
7b6a3f3cb2236fa651156bae3c1e2f10aa692a07
frontend/ui/widget/timewidget.lua
frontend/ui/widget/timewidget.lua
local Blitbuffer = require("ffi/blitbuffer") local ButtonTable = require("ui/widget/buttontable") local CenterContainer = require("ui/widget/container/centercontainer") local CloseButton = require("ui/widget/closebutton") local Device = require("device") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local Font = require("ui/font") local HorizontalGroup = require("ui/widget/horizontalgroup") local InputContainer = require("ui/widget/container/inputcontainer") local LineWidget = require("ui/widget/linewidget") local OverlapGroup = require("ui/widget/overlapgroup") local NumberPickerWidget = require("ui/widget/numberpickerwidget") local Size = require("ui/size") local TextBoxWidget = require("ui/widget/textboxwidget") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local WidgetContainer = require("ui/widget/container/widgetcontainer") local _ = require("gettext") local Screen = Device.screen local TimeWidget = InputContainer:new{ title_face = Font:getFace("x_smalltfont"), width = nil, height = nil, hour = 0, hour_max = 23, min = 0, ok_text = _("OK"), cancel_text = _("Cancel"), } function TimeWidget:init() self.medium_font_face = Font:getFace("ffont") self.light_bar = {} self.screen_width = Screen:getWidth() self.screen_height = Screen:getHeight() self.width = self.screen_width * 0.95 if Device:hasKeys() then self.key_events = { Close = { {"Back"}, doc = "close time widget" } } end if Device:isTouchDevice() then self.ges_events = { TapClose = { GestureRange:new{ ges = "tap", range = Geom:new{ w = self.screen_width, h = self.screen_height, } }, }, } end self:update() end function TimeWidget:update() local hour_widget = NumberPickerWidget:new{ show_parent = self, width = self.screen_width * 0.2, value = self.hour, value_min = 0, value_max = self.hour_max, value_step = 1, value_hold_step = 4, } local min_widget = NumberPickerWidget:new{ show_parent = self, width = self.screen_width * 0.2, value = self.min, value_min = 0, value_max = 59, value_step = 1, value_hold_step = 10, } local colon_space = TextBoxWidget:new{ text = ":", alignment = "center", face = self.title_face, bold = true, width = self.screen_width * 0.2, } local time_group = HorizontalGroup:new{ align = "center", hour_widget, colon_space, min_widget, } local time_title = FrameContainer:new{ padding = Size.padding.default, margin = Size.margin.title, bordersize = 0, TextWidget:new{ text = self.title_text, face = self.title_face, bold = true, width = self.screen_width * 0.95, }, } local time_line = LineWidget:new{ dimen = Geom:new{ w = self.width, h = Size.line.thick, } } local time_bar = OverlapGroup:new{ dimen = { w = self.width, h = time_title:getSize().h }, time_title, CloseButton:new{ window = self, padding_top = Size.margin.title, }, } local buttons = { { { text = self.cancel_text, callback = function() self:onClose() end, }, { text = self.ok_text, callback = function() if self.callback then self.hour = hour_widget:getValue() self.min = min_widget:getValue() self:callback(self) end self:onClose() end, }, } } local ok_cancel_buttons = ButtonTable:new{ width = self.width - 2*Size.padding.default, buttons = buttons, zero_sep = true, show_parent = self, } self.time_frame = FrameContainer:new{ radius = Size.radius.window, padding = 0, margin = 0, background = Blitbuffer.COLOR_WHITE, VerticalGroup:new{ align = "left", time_bar, time_line, CenterContainer:new{ dimen = Geom:new{ w = self.screen_width * 0.95, h = time_group:getSize().h * 1.2, }, time_group }, CenterContainer:new{ dimen = Geom:new{ w = self.width, h = ok_cancel_buttons:getSize().h, }, ok_cancel_buttons } } } self[1] = WidgetContainer:new{ align = "center", dimen = Geom:new{ x = 0, y = 0, w = self.screen_width, h = self.screen_height, }, FrameContainer:new{ bordersize = 0, self.time_frame, } } UIManager:setDirty(self, function() return "ui", self.time_frame.dimen end) end function TimeWidget:onCloseWidget() UIManager:setDirty(nil, function() return "partial", self.time_frame.dimen end) return true end function TimeWidget:onShow() UIManager:setDirty(self, function() return "ui", self.time_frame.dimen end) return true end function TimeWidget:onAnyKeyPressed() UIManager:close(self) return true end function TimeWidget:onTapClose(arg, ges_ev) if ges_ev.pos:notIntersectWith(self.time_frame.dimen) then self:onClose() end return true end function TimeWidget:onClose() UIManager:close(self) return true end return TimeWidget
local Blitbuffer = require("ffi/blitbuffer") local ButtonTable = require("ui/widget/buttontable") local CenterContainer = require("ui/widget/container/centercontainer") local CloseButton = require("ui/widget/closebutton") local Device = require("device") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local Font = require("ui/font") local HorizontalGroup = require("ui/widget/horizontalgroup") local InputContainer = require("ui/widget/container/inputcontainer") local LineWidget = require("ui/widget/linewidget") local OverlapGroup = require("ui/widget/overlapgroup") local NumberPickerWidget = require("ui/widget/numberpickerwidget") local Size = require("ui/size") local TextBoxWidget = require("ui/widget/textboxwidget") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local WidgetContainer = require("ui/widget/container/widgetcontainer") local _ = require("gettext") local Screen = Device.screen local TimeWidget = InputContainer:new{ title_face = Font:getFace("x_smalltfont"), width = nil, height = nil, hour = 0, hour_max = 23, min = 0, ok_text = _("OK"), cancel_text = _("Cancel"), } function TimeWidget:init() self.medium_font_face = Font:getFace("ffont") self.light_bar = {} self.screen_width = Screen:getWidth() self.screen_height = Screen:getHeight() self.width = self.screen_width * 0.95 if Device:hasKeys() then self.key_events = { Close = { {"Back"}, doc = "close time widget" } } end if Device:isTouchDevice() then self.ges_events = { TapClose = { GestureRange:new{ ges = "tap", range = Geom:new{ w = self.screen_width, h = self.screen_height, } }, }, } end self:update() end function TimeWidget:update() local hour_widget = NumberPickerWidget:new{ show_parent = self, width = self.screen_width * 0.2, value = self.hour, value_min = 0, value_max = self.hour_max, value_step = 1, value_hold_step = 4, } local min_widget = NumberPickerWidget:new{ show_parent = self, width = self.screen_width * 0.2, value = self.min, value_min = 0, value_max = 59, value_step = 1, value_hold_step = 10, } local colon_space = TextBoxWidget:new{ text = ":", alignment = "center", face = self.title_face, bold = true, width = self.screen_width * 0.2, } local time_group = HorizontalGroup:new{ align = "center", hour_widget, colon_space, min_widget, } local closebutton = CloseButton:new{ window = self, padding_top = Size.margin.title, } local time_title = FrameContainer:new{ padding = Size.padding.default, margin = Size.margin.title, bordersize = 0, TextWidget:new{ text = self.title_text, face = self.title_face, bold = true, max_width = self.screen_width * 0.95 - closebutton:getSize().w, }, } local time_line = LineWidget:new{ dimen = Geom:new{ w = self.width, h = Size.line.thick, } } local time_bar = OverlapGroup:new{ dimen = { w = self.width, h = time_title:getSize().h }, time_title, closebutton, } local buttons = { { { text = self.cancel_text, callback = function() self:onClose() end, }, { text = self.ok_text, callback = function() if self.callback then self.hour = hour_widget:getValue() self.min = min_widget:getValue() self:callback(self) end self:onClose() end, }, } } local ok_cancel_buttons = ButtonTable:new{ width = self.width - 2*Size.padding.default, buttons = buttons, zero_sep = true, show_parent = self, } self.time_frame = FrameContainer:new{ radius = Size.radius.window, padding = 0, margin = 0, background = Blitbuffer.COLOR_WHITE, VerticalGroup:new{ align = "left", time_bar, time_line, CenterContainer:new{ dimen = Geom:new{ w = self.screen_width * 0.95, h = time_group:getSize().h * 1.2, }, time_group }, CenterContainer:new{ dimen = Geom:new{ w = self.width, h = ok_cancel_buttons:getSize().h, }, ok_cancel_buttons } } } self[1] = WidgetContainer:new{ align = "center", dimen = Geom:new{ x = 0, y = 0, w = self.screen_width, h = self.screen_height, }, FrameContainer:new{ bordersize = 0, self.time_frame, } } UIManager:setDirty(self, function() return "ui", self.time_frame.dimen end) end function TimeWidget:onCloseWidget() UIManager:setDirty(nil, function() return "partial", self.time_frame.dimen end) return true end function TimeWidget:onShow() UIManager:setDirty(self, function() return "ui", self.time_frame.dimen end) return true end function TimeWidget:onAnyKeyPressed() UIManager:close(self) return true end function TimeWidget:onTapClose(arg, ges_ev) if ges_ev.pos:notIntersectWith(self.time_frame.dimen) then self:onClose() end return true end function TimeWidget:onClose() UIManager:close(self) return true end return TimeWidget
[fix] Handle max_width in time widget (#5540)
[fix] Handle max_width in time widget (#5540) Set max_width like in #5503
Lua
agpl-3.0
Markismus/koreader,poire-z/koreader,poire-z/koreader,Frenzie/koreader,koreader/koreader,NiLuJe/koreader,Hzj-jie/koreader,mihailim/koreader,NiLuJe/koreader,Frenzie/koreader,pazos/koreader,mwoz123/koreader,koreader/koreader
9a7579c3cecfe653184b7ba55bbedc084c67ae50
tests/actions/codelite/codelite_files.lua
tests/actions/codelite/codelite_files.lua
-- -- tests/actions/codelite/codelite_files.lua -- Validate generation of files block in CodeLite C/C++ projects. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.codelite_files = { } local suite = T.codelite_files local codelite = premake.codelite -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() io.indent = " " premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) codelite.files(prj) end -- -- Test grouping and nesting -- function suite.SimpleSourceFile() files { "hello.c" } prepare() test.capture [[ <File Name="hello.c"/> ]] end function suite.SingleFolderLevel() files { "src/hello.c" } prepare() test.capture [[ <VirtualDirectory Name="src"> <File Name="src/hello.c"/> </VirtualDirectory> ]] end function suite.MultipleFolderLevels() files { "src/greetings/hello.c" } prepare() test.capture [[ <VirtualDirectory Name="src"> <VirtualDirectory Name="greetings"> <File Name="src/greetings/hello.c"/> </VirtualDirectory> </VirtualDirectory> ]] end
-- -- tests/actions/codelite/codelite_files.lua -- Validate generation of files block in CodeLite C/C++ projects. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.codelite_files = { } local suite = T.codelite_files local codelite = premake.codelite -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() io.indent = " " premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) codelite.files(prj) end -- -- Test grouping and nesting -- function suite.SimpleSourceFile() files { "hello.c" } prepare() test.capture [[ <VirtualDirectory Name="MyProject"> <File Name="hello.c"/> </VirtualDirectory> ]] end function suite.SingleFolderLevel() files { "src/hello.c" } prepare() test.capture [[ <VirtualDirectory Name="MyProject"> <VirtualDirectory Name="src"> <File Name="src/hello.c"/> </VirtualDirectory> </VirtualDirectory> ]] end function suite.MultipleFolderLevels() files { "src/greetings/hello.c" } prepare() test.capture [[ <VirtualDirectory Name="MyProject"> <VirtualDirectory Name="src"> <VirtualDirectory Name="greetings"> <File Name="src/greetings/hello.c"/> </VirtualDirectory> </VirtualDirectory> </VirtualDirectory> ]] end
Fix CodeLite file tests
Fix CodeLite file tests
Lua
bsd-3-clause
ryanjmulder/premake-4.x,lizh06/premake-4.x,premake/premake-4.x,soundsrc/premake-stable,soundsrc/premake-stable,soundsrc/premake-stable,lizh06/premake-4.x,ryanjmulder/premake-4.x,lizh06/premake-4.x,premake/premake-4.x,ryanjmulder/premake-4.x,premake/premake-4.x,soundsrc/premake-stable,ryanjmulder/premake-4.x,premake/premake-4.x,lizh06/premake-4.x
a490d64b387d876c15f45caeee41b2ffbf00cdea
orange/utils/extractor.lua
orange/utils/extractor.lua
local type = type local ipairs = ipairs local pairs = pairs local string_find = string.find local string_lower = string.lower local table_insert = table.insert local ngx_re_find = ngx.re.find local ngx_re_match = ngx.re.match local function extract_variable(extraction) if not extraction or not extraction.type then return "" end local etype = extraction.type local result = "" if etype == "URI" then -- 为简化逻辑,URI模式每次只允许提取一个变量 local uri = ngx.var.uri local m, err = ngx_re_match(uri, extraction.name) if not err and m and m[1] then result = m[1] -- 提取第一个匹配的子模式 end elseif etype == "Query" then local query = ngx.req.get_uri_args() result = query[extraction.name] elseif etype == "Header" then local headers = ngx.req.get_headers() result = headers[extraction.name] elseif etype == "PostParams" then local headers = ngx.req.get_headers() local header = headers['Content-Type'] if header then local is_multipart = string_find(header, "multipart") if is_multipart and is_multipart > 0 then return false end end ngx.req.read_body() local post_params, err = ngx.req.get_post_args() if not post_params or err then ngx.log(ngx.ERR, "[Extract Variable]failed to get post args: ", err) return false end result = post_params[extraction.name] elseif etype == "Host" then result = ngx.var.host elseif etype == "IP" then result = ngx.var.remote_addr elseif etype == "Method" then local method = ngx.req.get_method() result = string_lower(method) end return result end local function extract_variable_for_template(extractions) if not extractions then return {} end local result = {} local ngx_var = ngx.var for i, extraction in ipairs(extractions) do local etype = extraction.type if etype == "URI" then -- URI模式通过正则可以提取出N个值 local uri = ngx_var.uri local m, err = ngx_re_match(uri, extraction.name) if not err and m and m[1] then if not result["uri"] then result["uri"] = {} end for j, v in ipairs(m) do if j >= 1 then result["uri"]["v" .. j] = v end end end elseif etype == "Query" then local query = ngx.req.get_uri_args() if not result["query"] then result["query"] = {} end result["query"][extraction.name] = query[extraction.name] or extraction.default elseif etype == "Header" then local headers = ngx.req.get_headers() if not result["header"] then result["header"] = {} end result["header"][extraction.name] = headers[extraction.name] or extraction.default elseif etype == "PostParams" then local headers = ngx.req.get_headers() local header = headers['Content-Type'] local ok = true if header then local is_multipart = string_find(header, "multipart") if is_multipart and is_multipart > 0 then ok = false end end ngx.req.read_body() local post_params, err = ngx.req.get_post_args() if not post_params or err then ngx.log(ngx.ERR, "[Extract Variable]failed to get post args: ", err) ok = false end if ok then if not result["body"] then result["body"] = {} end result["body"][extraction.name] = post_params[extraction.name] or extraction.default end elseif etype == "Host" then result["host"] = ngx_var.host or extraction.default elseif etype == "IP" then result["ip"] = ngx_var.remote_addr or extraction.default elseif etype == "Method" then local method = ngx.req.get_method() result["method"] = string_lower(method) end end return result end local _M = {} function _M.extract(extractor_type, extractions) if not extractions or type(extractions) ~= "table" or #extractions < 1 then return {} end if not extractor_type then extractor_type = 1 end local result = {} if extractor_type == 1 then -- simple variables extractor for i, extraction in ipairs(extractions) do local variable = extract_variable(extraction) or extraction.default or "" table_insert(result, variable) end elseif extractor_type == 2 then -- tempalte variables extractor result = extract_variable_for_template(extractions) end -- for i, v in pairs(result) do -- if type(v) == "table" then -- for j, m in pairs(v) do -- ngx.log(ngx.ERR, i, ":", j, ":", m) -- end -- else -- ngx.log(ngx.ERR, i, ":", v) -- end -- end return result end return _M
local type = type local ipairs = ipairs local pairs = pairs local string_find = string.find local string_lower = string.lower local table_insert = table.insert local ngx_re_find = ngx.re.find local ngx_re_match = ngx.re.match local function extract_variable(extraction) if not extraction or not extraction.type then return "" end local etype = extraction.type local result = "" if etype == "URI" then -- 为简化逻辑,URI模式每次只允许提取一个变量 local uri = ngx.var.uri local m, err = ngx_re_match(uri, extraction.name) if not err and m and m[1] then result = m[1] -- 提取第一个匹配的子模式 end elseif etype == "Query" then local query = ngx.req.get_uri_args() result = query[extraction.name] elseif etype == "Header" then local headers = ngx.req.get_headers() result = headers[extraction.name] elseif etype == "PostParams" then local headers = ngx.req.get_headers() local header = headers['Content-Type'] if header then local is_multipart = string_find(header, "multipart") if is_multipart and is_multipart > 0 then return false end end ngx.req.read_body() local post_params, err = ngx.req.get_post_args() if not post_params or err then ngx.log(ngx.ERR, "[Extract Variable]failed to get post args: ", err) return false end result = post_params[extraction.name] elseif etype == "Host" then result = ngx.var.host elseif etype == "IP" then result = ngx.var.remote_addr elseif etype == "Method" then local method = ngx.req.get_method() result = string_lower(method) end return result end local function extract_variable_for_template(extractions) if not extractions then return {} end local result = {} local ngx_var = ngx.var for i, extraction in ipairs(extractions) do local etype = extraction.type if etype == "URI" then -- URI模式通过正则可以提取出N个值 result["uri"] = {} -- fixbug: nil `uri` variable for tempalte parse local uri = ngx_var.uri local m, err = ngx_re_match(uri, extraction.name) if not err and m and m[1] then if not result["uri"] then result["uri"] = {} end for j, v in ipairs(m) do if j >= 1 then result["uri"]["v" .. j] = v end end end elseif etype == "Query" then local query = ngx.req.get_uri_args() if not result["query"] then result["query"] = {} end result["query"][extraction.name] = query[extraction.name] or extraction.default elseif etype == "Header" then local headers = ngx.req.get_headers() if not result["header"] then result["header"] = {} end result["header"][extraction.name] = headers[extraction.name] or extraction.default elseif etype == "PostParams" then local headers = ngx.req.get_headers() local header = headers['Content-Type'] local ok = true if header then local is_multipart = string_find(header, "multipart") if is_multipart and is_multipart > 0 then ok = false end end ngx.req.read_body() local post_params, err = ngx.req.get_post_args() if not post_params or err then ngx.log(ngx.ERR, "[Extract Variable]failed to get post args: ", err) ok = false end if ok then if not result["body"] then result["body"] = {} end result["body"][extraction.name] = post_params[extraction.name] or extraction.default end elseif etype == "Host" then result["host"] = ngx_var.host or extraction.default elseif etype == "IP" then result["ip"] = ngx_var.remote_addr or extraction.default elseif etype == "Method" then local method = ngx.req.get_method() result["method"] = string_lower(method) end end return result end local _M = {} function _M.extract(extractor_type, extractions) if not extractions or type(extractions) ~= "table" or #extractions < 1 then return {} end if not extractor_type then extractor_type = 1 end local result = {} if extractor_type == 1 then -- simple variables extractor for i, extraction in ipairs(extractions) do local variable = extract_variable(extraction) or extraction.default or "" table_insert(result, variable) end elseif extractor_type == 2 then -- tempalte variables extractor result = extract_variable_for_template(extractions) end -- for i, v in pairs(result) do -- if type(v) == "table" then -- for j, m in pairs(v) do -- ngx.log(ngx.ERR, i, ":", j, ":", m) -- end -- else -- ngx.log(ngx.ERR, i, ":", v) -- end -- end return result end return _M
fixbug: nil uri when parsing uri/url template
fixbug: nil uri when parsing uri/url template
Lua
mit
jxskiss/orange,jxskiss/orange,sumory/orange,thisverygoodhhhh/orange,sumory/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange,wuhuatianbao007/orange,wuhuatianbao007/orange,jxskiss/orange,sumory/orange,wuhuatianbao007/orange
af60fb015e5ba915e93733e5154b326cbcc9ca36
OvaleQueue.lua
OvaleQueue.lua
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2013 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]-------------------------------------------------------------------- -- Double-ended queue. local _, Ovale = ... local OvaleQueue = {} Ovale.OvaleQueue = OvaleQueue --<private-static-properties> local setmetatable = setmetatable --</private-static-properties> --<public-static-properties> OvaleQueue.name = "OvaleQueue" OvaleQueue.first = 0 OvaleQueue.last = -1 OvaleQueue.__index = OvaleQueue --</public-static-properties> --<private-static-methods> local function BackToFrontIterator(invariant, control) control = control - 1 local element = invariant[control] if element then return control, element end end local function FrontToBackIterator(invariant, control) control = control + 1 local element = invariant[control] if element then return control, element end end --</private-static-methods> --<public-static-methods> function OvaleQueue:NewDeque(name) return setmetatable({ name = name, first = 0, last = -1 }, OvaleQueue) end function OvaleQueue:InsertFront(element) local first = self.first - 1 self.first = first self[first] = element end function OvaleQueue:InsertBack(element) local last = self.last + 1 self.last = last self[last] = element end function OvaleQueue:RemoveFront() local first = self.first local element = self[first] if element then self[first] = nil self.first = first + 1 end return element end function OvaleQueue:RemoveBack() local last = self.last local element = self[last] if element then self[last] = nil self.last = last - 1 end return element end function OvaleQueue:Front() return self[self.first] end function OvaleQueue:Back() return self[self.last] end function OvaleQueue:BackToFrontIterator() return BackToFrontIterator, self, self.last + 1 end function OvaleQueue:FrontToBackIterator() return FrontToBackIterator, self, self.first - 1 end function OvaleQueue:Reset() for i in self:BackToFrontIterator() do self[i] = nil end self.first = 0 self.last = -1 end function OvaleQueue:Size() return self.last - self.first + 1 end function OvaleQueue:Debug() Ovale:FormatPrint("Queue %s has %d item(s), first=%d, last=%d.", self.name, self:Size(), self.first, self.last) end --</public-static-methods> --<public-static-properties> -- Queue (LIFO) methods OvaleQueue.NewQueue = OvaleQueue.NewDeque OvaleQueue.Insert = OvaleQueue.InsertBack OvaleQueue.Remove = OvaleQueue.RemoveFront OvaleQueue.Iterator = OvaleQueue.FrontToBackIterator -- Stack (FIFO) methods OvaleQueue.NewStack = OvaleQueue.NewDeque OvaleQueue.Push = OvaleQueue.InsertFront OvaleQueue.Pop = OvaleQueue.RemoveFront OvaleQueue.Top = OvaleQueue.Front --</public-static-properties>
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2013 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]-------------------------------------------------------------------- -- Double-ended queue. local _, Ovale = ... local OvaleQueue = {} Ovale.OvaleQueue = OvaleQueue --<private-static-properties> local setmetatable = setmetatable --</private-static-properties> --<public-static-properties> OvaleQueue.name = "OvaleQueue" OvaleQueue.first = 1 OvaleQueue.last = 0 OvaleQueue.__index = OvaleQueue --</public-static-properties> --<private-static-methods> local function BackToFrontIterator(invariant, control) control = control - 1 local element = invariant[control] if element then return control, element end end local function FrontToBackIterator(invariant, control) control = control + 1 local element = invariant[control] if element then return control, element end end --</private-static-methods> --<public-static-methods> function OvaleQueue:NewDeque(name) return setmetatable({ name = name, first = 0, last = -1 }, OvaleQueue) end function OvaleQueue:InsertFront(element) local first = self.first - 1 self.first = first self[first] = element end function OvaleQueue:InsertBack(element) local last = self.last + 1 self.last = last self[last] = element end function OvaleQueue:RemoveFront() local first = self.first local element = self[first] if element then self[first] = nil self.first = first + 1 end return element end function OvaleQueue:RemoveBack() local last = self.last local element = self[last] if element then self[last] = nil self.last = last - 1 end return element end function OvaleQueue:At(index) if index > self:Size() then return end return self[self.first + index - 1] end function OvaleQueue:Front() return self[self.first] end function OvaleQueue:Back() return self[self.last] end function OvaleQueue:BackToFrontIterator() return BackToFrontIterator, self, self.last + 1 end function OvaleQueue:FrontToBackIterator() return FrontToBackIterator, self, self.first - 1 end function OvaleQueue:Reset() for i in self:BackToFrontIterator() do self[i] = nil end self.first = 0 self.last = -1 end function OvaleQueue:Size() return self.last - self.first + 1 end function OvaleQueue:Debug() Ovale:FormatPrint("Queue %s has %d item(s), first=%d, last=%d.", self.name, self:Size(), self.first, self.last) end --</public-static-methods> --<public-static-properties> -- Queue (FIFO) methods OvaleQueue.NewQueue = OvaleQueue.NewDeque OvaleQueue.Insert = OvaleQueue.InsertBack OvaleQueue.Remove = OvaleQueue.RemoveFront OvaleQueue.Iterator = OvaleQueue.FrontToBackIterator -- Stack (LIFO) methods OvaleQueue.NewStack = OvaleQueue.NewDeque OvaleQueue.Push = OvaleQueue.InsertBack OvaleQueue.Pop = OvaleQueue.RemoveBack OvaleQueue.Top = OvaleQueue.Back --</public-static-properties>
Add new queue method :At() to return the queue element at the given index.
Add new queue method :At() to return the queue element at the given index. Also, tweak the internal indices so that in the best case usage, the queue simply uses array table size for the queued elements. Lastly, fix the documentation since queue = FIFO and stack = LIFO. git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1538 d5049fe3-3747-40f7-a4b5-f36d6801af5f
Lua
mit
eXhausted/Ovale,eXhausted/Ovale,Xeltor/ovale,ultijlam/ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale
6a1cdca34518fac1ca4ee2f77dad6ff60062bda5
modules/luci-mod-rpc/luasrc/controller/rpc.lua
modules/luci-mod-rpc/luasrc/controller/rpc.lua
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local require = require local pairs = pairs local print = print local pcall = pcall local table = table local type = type local tonumber = tonumber module "luci.controller.rpc" local function session_retrieve(sid, allowed_users) local util = require "luci.util" local sdat = util.ubus("session", "get", { ubus_rpc_session = sid }) if type(sdat) == "table" and type(sdat.values) == "table" and type(sdat.values.token) == "string" and type(sdat.values.secret) == "string" and type(sdat.values.username) == "string" and util.contains(allowed_users, sdat.values.username) then return sid, sdat.values end return nil end local function authenticator(validator, accs) local auth = luci.http.formvalue("auth", true) or luci.http.getcookie("sysauth") if auth then -- if authentication token was given local sid, sdat = session_retrieve(auth, accs) if sdat then -- if given token is valid return sdat.username, sid end luci.http.status(403, "Forbidden") end end function index() local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local server = {} server.challenge = function(user, pass) local config = require "luci.config" local login = util.ubus("session", "login", { username = user, password = pass, timeout = tonumber(config.sauth.sessiontime) }) if type(login) == "table" and type(login.ubus_rpc_session) == "string" then util.ubus("session", "set", { ubus_rpc_session = login.ubus_rpc_session, values = { token = sys.uniqueid(16), secret = sys.uniqueid(16) } }) local sid, sdat = session_retrieve(login.ubus_rpc_session, { user }) if sdat then return { sid = sid, token = sdat.token, secret = sdat.secret } end end return nil end server.login = function(...) local challenge = server.challenge(...) if challenge then http.header("Set-Cookie", 'sysauth=%s; path=%s' %{ challenge.sid, http.getenv("SCRIPT_NAME") }) return challenge.sid end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.rpc", package.seeall) function index() local function session_retrieve(sid, allowed_users) local util = require "luci.util" local sdat = util.ubus("session", "get", { ubus_rpc_session = sid }) if type(sdat) == "table" and type(sdat.values) == "table" and type(sdat.values.token) == "string" and type(sdat.values.secret) == "string" and type(sdat.values.username) == "string" and util.contains(allowed_users, sdat.values.username) then return sid, sdat.values end return nil end local function authenticator(validator, accs) local http = require "luci.http" local auth = http.formvalue("auth", true) or http.getcookie("sysauth") if auth then -- if authentication token was given local sid, sdat = session_retrieve(auth, accs) if sdat then -- if given token is valid return sdat.username, sid end http.status(403, "Forbidden") end end local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local server = {} server.challenge = function(user, pass) local config = require "luci.config" local login = util.ubus("session", "login", { username = user, password = pass, timeout = tonumber(config.sauth.sessiontime) }) if type(login) == "table" and type(login.ubus_rpc_session) == "string" then util.ubus("session", "set", { ubus_rpc_session = login.ubus_rpc_session, values = { token = sys.uniqueid(16), secret = sys.uniqueid(16) } }) local sid, sdat = session_retrieve(login.ubus_rpc_session, { user }) if sdat then return { sid = sid, token = sdat.token, secret = sdat.secret } end end return nil end server.login = function(...) local challenge = server.challenge(...) if challenge then http.header("Set-Cookie", 'sysauth=%s; path=%s' %{ challenge.sid, http.getenv("SCRIPT_NAME") }) return challenge.sid end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end
luci-mod-rpc: fix authentication via query string parameter
luci-mod-rpc: fix authentication via query string parameter Localize the `authenticatior()` and `session_retrieve()` functions into the `index()` function scope so that they're retained when extracting the function into the dispatcher bytecode cache. Also allow access to the global scope since upvalues do not work reliably due to the out-of-context byte code caching of index functions. Fixes https://github.com/openwrt/luci/issues/1300#issuecomment-381352765 Fixes feefc600e ("luci-mod-rpc: rework authentication and session handling") Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
Lua
apache-2.0
tobiaswaldvogel/luci,artynet/luci,kuoruan/lede-luci,remakeelectric/luci,rogerpueyo/luci,Noltari/luci,hnyman/luci,wongsyrone/luci-1,nmav/luci,rogerpueyo/luci,rogerpueyo/luci,artynet/luci,kuoruan/lede-luci,hnyman/luci,hnyman/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,nmav/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,remakeelectric/luci,kuoruan/luci,remakeelectric/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci,rogerpueyo/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,tobiaswaldvogel/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,artynet/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,chris5560/openwrt-luci,remakeelectric/luci,Noltari/luci,openwrt-es/openwrt-luci,kuoruan/luci,kuoruan/luci,artynet/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,nmav/luci,hnyman/luci,openwrt/luci,wongsyrone/luci-1,openwrt/luci,openwrt/luci,remakeelectric/luci,tobiaswaldvogel/luci,remakeelectric/luci,wongsyrone/luci-1,rogerpueyo/luci,wongsyrone/luci-1,Noltari/luci,wongsyrone/luci-1,kuoruan/lede-luci,remakeelectric/luci,tobiaswaldvogel/luci,artynet/luci,Noltari/luci,Noltari/luci,hnyman/luci,remakeelectric/luci,lbthomsen/openwrt-luci,nmav/luci,chris5560/openwrt-luci,openwrt/luci,kuoruan/luci,Noltari/luci,nmav/luci,chris5560/openwrt-luci,nmav/luci,hnyman/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,nmav/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,artynet/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,Noltari/luci,chris5560/openwrt-luci,kuoruan/luci,kuoruan/lede-luci,kuoruan/luci,openwrt/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,artynet/luci,Noltari/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,kuoruan/luci,nmav/luci,nmav/luci,kuoruan/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,wongsyrone/luci-1,artynet/luci,hnyman/luci,Noltari/luci,openwrt/luci,artynet/luci
24fd3c7b3b3003d44bee3c237604fa0fb3735912
libs/uci/luasrc/model/uci/bind.lua
libs/uci/luasrc/model/uci/bind.lua
--[[ LuCI - UCI utilities for model classes Copyright 2009 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 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 assert, pairs, type = assert, pairs, type local utl = require "luci.util" module "luci.model.uci.bind" bind = utl.class() function bind.__init__(self, config, cursor) assert(config, "call to bind() without config file") self.cfg = config self.uci = cursor end function bind.init(self, cursor) assert(cursor, "call to init() without uci cursor") self.uci = cursor end function bind.section(self, stype) local x = utl.class(bsection) x.__init__ = function(inst, sid) assert(self.uci:get(self.cfg, sid) == stype, "attempt to instantiate bsection(%q) of wrong type, expected %q" % { sid, stype }) inst.bind = self inst.stype = stype inst.sid = sid end return x end function bind.usection(self, stype) local x = utl.class(bsection) x.__init__ = function(inst) inst.bind = self inst.stype = stype inst.sid = true end return x() end function bind.list(self, list, add, rem) local lookup = { } if type(list) == "string" then local item for item in list:gmatch("%S+") do lookup[item] = true end elseif type(list) == "table" then local item for _, item in pairs(list) do lookup[item] = true end end if add then lookup[add] = true end if rem then lookup[rem] = nil end return utl.keys(lookup) end function bind.bool(self, v) return ( v == "1" or v == "true" or v == "yes" or v == "on" ) end bsection = utl.class() function bsection.uciop(self, op, ...) assert(self.bind and self.bind.uci, "attempt to use unitialized binding: " .. type(self.sid)) return op and self.bind.uci[op](self.bind.uci, self.bind.cfg, ...) or self.bind.uci end function bsection.get(self, k, c) local v self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end elseif type(c) == "string" and s['.name'] ~= c then return true end if k ~= nil then v = s[k] else v = s end return false end) return v end function bsection.set(self, k, v, c) local stat self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end elseif type(c) == "string" and s['.name'] ~= c then return true end stat = self:uciop("set", c, k, v) return false end) return stat or false end function bsection.property(self, k, n) self[n or k] = function(c, val) if val == nil then return c:get(k, c.sid) else return c:set(k, val, c.sid) end end end function bsection.property_bool(self, k, n) self[n or k] = function(c, val) if val == nil then return self.bind:bool(c:get(k, c.sid)) else return c:set(k, self.bind:bool(val) and "1" or "0", c.sid) end end end
--[[ LuCI - UCI utilities for model classes Copyright 2009 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 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 assert, pairs, type = assert, pairs, type local utl = require "luci.util" module "luci.model.uci.bind" bind = utl.class() function bind.__init__(self, config, cursor) assert(config, "call to bind() without config file") self.cfg = config self.uci = cursor end function bind.init(self, cursor) assert(cursor, "call to init() without uci cursor") self.uci = cursor end function bind.section(self, stype) local x = utl.class(bsection) x.__init__ = function(inst, sid) assert(self.uci:get(self.cfg, sid) == stype, "attempt to instantiate bsection(%q) of wrong type, expected %q" % { sid, stype }) inst.bind = self inst.stype = stype inst.sid = sid end return x end function bind.usection(self, stype) local x = utl.class(bsection) x.__init__ = function(inst) inst.bind = self inst.stype = stype inst.sid = true end return x() end function bind.list(self, list, add, rem) local lookup = { } if type(list) == "string" then local item for item in list:gmatch("%S+") do lookup[item] = true end elseif type(list) == "table" then local item for _, item in pairs(list) do lookup[item] = true end end if add then lookup[add] = true end if rem then lookup[rem] = nil end return utl.keys(lookup) end function bind.bool(self, v) return ( v == "1" or v == "true" or v == "yes" or v == "on" ) end bsection = utl.class() function bsection.uciop(self, op, ...) assert(self.bind and self.bind.uci, "attempt to use unitialized binding") if op then return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...) else return self.bind.uci end end function bsection.get(self, k, c) local v if type(c) == "string" then v = self:uciop("get", c, k) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end if k ~= nil then v = s[k] else v = s end return false end) end return v end function bsection.set(self, k, v, c) local stat if type(c) == "string" then stat = self:uciop("set", c, k, v) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end stat = self:uciop("set", c, k, v) return false end) end return stat or false end function bsection.property(self, k, n) self[n or k] = function(c, val) if val == nil then return c:get(k, c.sid) else return c:set(k, val, c.sid) end end end function bsection.property_bool(self, k, n) self[n or k] = function(c, val) if val == nil then return self.bind:bool(c:get(k, c.sid)) else return c:set(k, self.bind:bool(val) and "1" or "0", c.sid) end end end
libs/uci: optimize get & set performance in luci.model.uci.bind, fix ambiguous case in uciop()
libs/uci: optimize get & set performance in luci.model.uci.bind, fix ambiguous case in uciop() git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5378 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,stephank/luci,8devices/carambola2-luci,stephank/luci,vhpham80/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,vhpham80/luci,ch3n2k/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,gwlim/luci,ch3n2k/luci,saraedum/luci-packages-old,gwlim/luci,Flexibity/luci,gwlim/luci,freifunk-gluon/luci,vhpham80/luci,phi-psi/luci,ch3n2k/luci,8devices/carambola2-luci,ch3n2k/luci,ch3n2k/luci,eugenesan/openwrt-luci,jschmidlapp/luci,saraedum/luci-packages-old,freifunk-gluon/luci,vhpham80/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,projectbismark/luci-bismark,freifunk-gluon/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,phi-psi/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,freifunk-gluon/luci,stephank/luci,stephank/luci,Canaan-Creative/luci,8devices/carambola2-luci,phi-psi/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,Flexibity/luci,phi-psi/luci,phi-psi/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,vhpham80/luci,Canaan-Creative/luci,yeewang/openwrt-luci,gwlim/luci,Canaan-Creative/luci,yeewang/openwrt-luci,Flexibity/luci,yeewang/openwrt-luci,Flexibity/luci,gwlim/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,stephank/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,Flexibity/luci,vhpham80/luci,Flexibity/luci,stephank/luci,Canaan-Creative/luci,jschmidlapp/luci,jschmidlapp/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,projectbismark/luci-bismark,freifunk-gluon/luci,gwlim/luci,jschmidlapp/luci,Flexibity/luci,jschmidlapp/luci,gwlim/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,Canaan-Creative/luci
3144e77d013c344471e26cf58d3c7262b951a11a
kong/core/globalpatches.lua
kong/core/globalpatches.lua
local meta = require "kong.meta" local randomseed = math.randomseed _G._KONG = { _NAME = meta._NAME, _VERSION = meta._VERSION } local seed --- Seeds the random generator, use with care. -- The uuid.seed() method will create a unique seed per worker -- process, using a combination of both time and the worker's pid. -- We only allow it to be called once to prevent third-party modules -- from overriding our correct seed (many modules make a wrong usage -- of `math.randomseed()` by calling it multiple times or do not use -- unique seed for Nginx workers). -- luacheck: globals math _G.math.randomseed = function() if ngx.get_phase() ~= "init_worker" then ngx.log(ngx.ERR, "math.randomseed() must be called in init_worker") elseif not seed then seed = ngx.time() + ngx.worker.pid() ngx.log(ngx.DEBUG, "random seed: ", seed, " for worker n", ngx.worker.id(), " (pid: ", ngx.worker.pid(), ")") randomseed(seed) else ngx.log(ngx.DEBUG, "attempt to seed random number generator, but ", "already seeded") end return seed end
local meta = require "kong.meta" local randomseed = math.randomseed _G._KONG = { _NAME = meta._NAME, _VERSION = meta._VERSION } local seed --- Seeds the random generator, use with care. -- The uuid.seed() method will create a unique seed per worker -- process, using a combination of both time and the worker's pid. -- We only allow it to be called once to prevent third-party modules -- from overriding our correct seed (many modules make a wrong usage -- of `math.randomseed()` by calling it multiple times or do not use -- unique seed for Nginx workers). -- luacheck: globals math _G.math.randomseed = function() if not seed then if ngx.get_phase() ~= "init_worker" then error("math.randomseed() must be called in init_worker", 2) end seed = ngx.time() + ngx.worker.pid() ngx.log(ngx.DEBUG, "random seed: ", seed, " for worker n", ngx.worker.id(), " (pid: ", ngx.worker.pid(), ")") randomseed(seed) else ngx.log(ngx.DEBUG, "attempt to seed random number generator, but ", "already seeded with ", seed) end return seed end
fix(globalpatches) randomseed throws error when seeded in wrong context
fix(globalpatches) randomseed throws error when seeded in wrong context
Lua
apache-2.0
akh00/kong,li-wl/kong,salazar/kong,Kong/kong,ccyphers/kong,Kong/kong,jebenexer/kong,icyxp/kong,beauli/kong,shiprabehera/kong,jerizm/kong,Kong/kong,Vermeille/kong,Mashape/kong
2d290a3f376997dad424b06e394ffc5d0a7b5d49
scripts/ovale_demonhunter_spells.lua
scripts/ovale_demonhunter_spells.lua
local OVALE, Ovale = ... local OvaleScripts = Ovale.OvaleScripts do local name = "ovale_demonhunter_spells" local desc = "[7.0] Ovale: DemonHunter spells" local code = [[ Define(annihilation 201427) SpellInfo(annihilation fury=40) Define(blade_dance 188499) SpellInfo(blade_dance replace death_sweep=buff,metamorphosis_havoc_buff) SpellInfo(blade_dance fury=35) Define(bloodlet_talent 9) Define(blur 198589) SpellInfo(blur cd=60) Define(chaos_blades 211048) SpellInfo(chaos_blades cd=120) Define(chaos_blades_buff 211048) SpellInfo(chaos_blades_buff duration=12) Define(chaos_cleave_talent 2) Define(chaos_strike 162794) SpellInfo(chaos_strike replace annihilation=buff,metamorphosis_havoc_buff) SpellInfo(chaos_strike fury=40) Define(consume_magic 183752) SpellInfo(consume_magic cd=15 gcd=0 interrupt=1 offgcd=1) Define(death_sweep 210152) SpellInfo(death_sweep fury=35) Define(demonic_talent 21) Define(demon_spikes 203720) SpellInfo(demon_spikes pain=20 cd_haste=melee haste=melee specialization=vengeance cd=15 gcd=0 offgcd=1) SpellAddBuff(demon_spikes demon_spikes_buff=1) Define(demon_spikes_buff 203819) SpellInfo(demon_spikes_buff duration=6) Define(demons_bite 162243) Define(empower_wards 218256) SpellInfo(empower_wards cd=20 gcd=0 offgcd=1) SpellAddBuff(empower_wards empower_wards_buff=1) Define(empower_wards_buff 218256) SpellInfo(empower_wards_buff duration=6) Define(eye_beam 198013) SpellInfo(eye_beam fury=50) Define(felblade 213241) SpellInfo(felblade cd=15) SpellInfo(felblade cd_haste=melee haste=melee specialization=vengeance) Define(fel_barrage 211053) SpellInfo(fel_barrage cd=30) Define(fel_devastation 212084) SpellInfo(fel_devastation cd=60) SpellInfo(fel_devastation pain=30) Define(fel_eruption 211881) SpellInfo(fel_eruption cd=35) SpellInfo(fel_eruption fury=20) SpellInfo(fel_eruption pain=10) Define(fel_eruption_talent 14) Define(fel_mastery_talent 1) Define(fel_rush 195072) Define(fiery_brand 204021) SpellInfo(fiery_brand cd=60 gcd=0 offgcd=1) SpellAddTargetDebuff(fiery_brand fiery_brand_debuff=1) Define(fiery_brand_debuff 207744) SpellInfo(fiery_brand_debuff duration=8) Define(first_blood_talent 8) Define(fracture 209795) SpellInfo(fracture pain=40) Define(frailty_debuff 224509) SpellInfo(frailty_debuff duration=15) Define(fury_of_the_ilidari 201467) SpellInfo(fury_of_the_ilidari cd=60) Define(immolation_aura 178740) SpellAddBuff(immolation_aura immolation_aura_buff=1) Define(immolation_aura_buff 201122) SpellInfo(immolation_aura_buff duration=6) Define(imprison 217832) Define(infernal_strike 189110) SpellInfo(infernal_strike cd=20) Define(infernal_strike_debuff 189110) Define(metamorphosis_havoc 191427) SpellInfo(metamorphosis_havoc cd=300) SpellAddBuff(metamorphosis_havoc metamorphosis_havoc_buff=1) Define(metamorphosis_havoc_buff 162264) SpellInfo(metamorphosis_havoc_buff duration=30) Define(metamorphosis_veng 187827) SpellInfo(metamorphosis_veng cd=180 gcd=0 offgcd=1) SpellAddBuff(metamorphosis_veng metamorphosis_veng_buff=1) Define(metamorphosis_veng_buff 187827) SpellInfo(metamorphosis_veng_buff duration=15) Define(momentum_buff 208628) Define(nemesis 206491) SpellInfo(nemesis cd=120) SpellAddTargetDebuff(nemesis nemesis_debuff=1) Define(nemesis_debuff 206491) Define(pick_up_fragment 210788) Define(prepared_buff 203650) Define(shear 203782) Define(sigil_of_flame 204596) SpellInfo(sigil_of_flame cd=30) Define(sigil_of_flame_debuff 204598) Define(sigil_of_silence 202137) Define(sigil_of_misery 207684) Define(soul_cleave 228477) SpellInfo(soul_cleave pain=30 extra_pain=30) SpellAddBuff(soul_cleave soul_fragments=0) Define(soul_carver 214743) SpellInfo(soul_carver cd=40) Define(soul_fragments 203981) SpellInfo(soul_fragments duration=20) Define(soul_barrier 227225) SpellInfo(soul_barrier cd=20) SpellInfo(soul_barrier pain=30) Define(spirit_bomb 218679) Define(throw_glaive 185123) Define(vengeful_retreat 198793) SpellAddTargetDebuff(vengeful_retreat vengeful_retreat_debuff=1) Define(vengeful_retreat_debuff 198813) SpellInfo(vengeful_retreat_debuff duration=3) # Artifact traits Define(anguish_of_the_deceiver 201473) Define(demon_speed 201469) Define(fiery_demise 212817) Define(fury_of_the_illidari 201467) SpellInfo(fury_of_the_ilidari cd=60) # Talents Define(abyssal_strike_talent 1) Define(chaos_blades_talent 19) Define(demon_blades_talent 5) Define(demonic_appetite_talent 6) Define(felblade_talent 4) Define(master_of_the_glaive_talent 16) Define(momentum_talent 13) Define(nemesis_talent 15) Define(prepared_talent 4) Define(quickened_sigils_talent 15) SpellInfo(fel_rush tag=shortcd) ]] OvaleScripts:RegisterScript("DEMONHUNTER", nil, name, desc, code, "include") end
local OVALE, Ovale = ... local OvaleScripts = Ovale.OvaleScripts do local name = "ovale_demonhunter_spells" local desc = "[7.0] Ovale: DemonHunter spells" local code = [[ Define(annihilation 201427) SpellInfo(annihilation fury=40) Define(blade_dance 188499) SpellInfo(blade_dance replace death_sweep=buff,metamorphosis_havoc_buff) SpellInfo(blade_dance fury=35) Define(bloodlet_talent 9) Define(blur 198589) SpellInfo(blur cd=60) Define(chaos_blades 211048) SpellInfo(chaos_blades cd=120) Define(chaos_blades_buff 211048) SpellInfo(chaos_blades_buff duration=12) Define(chaos_cleave_talent 2) Define(chaos_strike 162794) SpellInfo(chaos_strike replace annihilation=buff,metamorphosis_havoc_buff) SpellInfo(chaos_strike fury=40) Define(consume_magic 183752) SpellInfo(consume_magic cd=15 gcd=0 interrupt=1 offgcd=1) Define(death_sweep 210152) SpellInfo(death_sweep fury=35) Define(demonic_talent 21) Define(demon_spikes 203720) SpellInfo(demon_spikes pain=20 cd_haste=melee haste=melee specialization=vengeance cd=15 gcd=0 offgcd=1) SpellAddBuff(demon_spikes demon_spikes_buff=1) Define(demon_spikes_buff 203819) SpellInfo(demon_spikes_buff duration=6) Define(demons_bite 162243) Define(empower_wards 218256) SpellInfo(empower_wards cd=20 gcd=0 offgcd=1) SpellAddBuff(empower_wards empower_wards_buff=1) Define(empower_wards_buff 218256) SpellInfo(empower_wards_buff duration=6) Define(eye_beam 198013) SpellInfo(eye_beam fury=50) Define(felblade 213241) SpellInfo(felblade cd=15) SpellInfo(felblade cd_haste=melee haste=melee specialization=vengeance) Define(fel_barrage 211053) SpellInfo(fel_barrage cd=30) Define(fel_devastation 212084) SpellInfo(fel_devastation cd=60) SpellInfo(fel_devastation pain=30) Define(fel_eruption 211881) SpellInfo(fel_eruption cd=35) SpellInfo(fel_eruption fury=20) SpellInfo(fel_eruption pain=10) Define(fel_eruption_talent 14) Define(fel_mastery_talent 1) Define(fel_rush 195072) Define(fiery_brand 204021) SpellInfo(fiery_brand cd=60 gcd=0 offgcd=1) SpellAddTargetDebuff(fiery_brand fiery_brand_debuff=1) Define(fiery_brand_debuff 207744) SpellInfo(fiery_brand_debuff duration=8) Define(first_blood_talent 8) Define(fracture 209795) SpellInfo(fracture pain=40) Define(frailty_debuff 224509) SpellInfo(frailty_debuff duration=15) Define(fury_of_the_ilidari 201467) SpellInfo(fury_of_the_ilidari cd=60) Define(immolation_aura 178740) SpellAddBuff(immolation_aura immolation_aura_buff=1) Define(immolation_aura_buff 201122) SpellInfo(immolation_aura_buff duration=6) Define(imprison 217832) Define(infernal_strike 189110) SpellInfo(infernal_strike cd=20 charges=2) Define(infernal_strike_debuff 189110) Define(metamorphosis_havoc 191427) SpellInfo(metamorphosis_havoc cd=300) SpellAddBuff(metamorphosis_havoc metamorphosis_havoc_buff=1) Define(metamorphosis_havoc_buff 162264) SpellInfo(metamorphosis_havoc_buff duration=30) Define(metamorphosis_veng 187827) SpellInfo(metamorphosis_veng cd=180 gcd=0 offgcd=1) SpellAddBuff(metamorphosis_veng metamorphosis_veng_buff=1) Define(metamorphosis_veng_buff 187827) SpellInfo(metamorphosis_veng_buff duration=15) Define(momentum_buff 208628) Define(nemesis 206491) SpellInfo(nemesis cd=120) SpellAddTargetDebuff(nemesis nemesis_debuff=1) Define(nemesis_debuff 206491) Define(pick_up_fragment 210788) Define(prepared_buff 203650) Define(shear 203782) Define(sigil_of_chains 202138) Define(sigil_of_flame 204596) SpellInfo(sigil_of_flame cd=30) Define(sigil_of_flame_debuff 204598) Define(sigil_of_silence 202137) Define(sigil_of_misery 207684) Define(soul_cleave 228477) SpellInfo(soul_cleave pain=30 extra_pain=30) SpellAddBuff(soul_cleave soul_fragments=0) Define(soul_carver 214743) SpellInfo(soul_carver cd=40) Define(soul_fragments 203981) SpellInfo(soul_fragments duration=20) Define(soul_barrier 227225) SpellInfo(soul_barrier cd=20 pain=30) Define(spirit_bomb 218679) Define(throw_glaive 185123) Define(vengeful_retreat 198793) SpellAddTargetDebuff(vengeful_retreat vengeful_retreat_debuff=1) Define(vengeful_retreat_debuff 198813) SpellInfo(vengeful_retreat_debuff duration=3) # Artifact traits Define(anguish_of_the_deceiver 201473) Define(demon_speed 201469) Define(fiery_demise 212817) Define(fury_of_the_illidari 201467) SpellInfo(fury_of_the_ilidari cd=60) # Talents Define(abyssal_strike_talent 1) Define(chaos_blades_talent 19) Define(demon_blades_talent 5) Define(demonic_appetite_talent 6) Define(felblade_talent 4) Define(flame_crash_talent 8) Define(master_of_the_glaive_talent 16) Define(momentum_talent 13) Define(nemesis_talent 15) Define(prepared_talent 4) Define(quickened_sigils_talent 15) SpellInfo(fel_rush tag=shortcd) ]] OvaleScripts:RegisterScript("DEMONHUNTER", nil, name, desc, code, "include") end
various fixes in definitions
various fixes in definitions
Lua
mit
ultijlam/ovale,ultijlam/ovale,Xeltor/ovale,ultijlam/ovale
9c82238a96947173e9a147d3d1aaf80e275f9d83
kong/cmd/utils/serf_signals.lua
kong/cmd/utils/serf_signals.lua
-- Enhanced implementation of previous "services.serf.lua" module, -- no change in actual logic, only decoupled from the events features -- which now live in kong.serf local pl_stringx = require "pl.stringx" local pl_utils = require "pl.utils" local pl_file = require "pl.file" local Serf = require "kong.serf" local kill = require "kong.cmd.utils.kill" local log = require "kong.cmd.utils.log" local meta = require "kong.meta" local version = require "version" local fmt = string.format local serf_event_name = "kong" local serf_version_pattern = "^Serf v([%d%.]+)" local serf_compatible = version.set(unpack(meta._DEPENDENCIES.serf)) local start_timeout = 5 local serf_search_paths = { "serf", "/usr/local/bin/serf" } local function check_version(path) local cmd = fmt("%s version", path) local ok, _, stdout = pl_utils.executeex(cmd) log.debug("%s: '%s'", cmd, pl_stringx.splitlines(stdout)[1]) if ok and stdout then local version_match = stdout:match(serf_version_pattern) if not version_match or not serf_compatible:matches(version_match) then return nil, fmt("incompatible serf found at '%s'. Kong requires version '%s', got '%s'", path, tostring(serf_compatible), version_match) end return true end end local function check_serf_bin(kong_config) log.debug("searching for 'serf' executable") if kong_config.serf_path then serf_search_paths = { kong_config.serf_path } end local found for _, path in ipairs(serf_search_paths) do if check_version(path) then found = path log.debug("found 'serf' executable at %s", found) break end end if not found then return nil, "could not find 'serf' executable (is 'serf_path' correctly set?)" end return found end local _M = {} function _M.start(kong_config, dao) -- is Serf already running in this prefix? if kill.is_running(kong_config.serf_pid) then log.verbose("serf agent already running at %s", kong_config.serf_pid) return true else log.verbose("serf agent not running, deleting %s", kong_config.serf_pid) pl_file.delete(kong_config.serf_pid) end -- make sure Serf is in PATH local ok, err = check_serf_bin(kong_config) if not ok then return nil, err end local serf = Serf.new(kong_config, dao) local args = setmetatable({ ["-bind"] = kong_config.cluster_listen, ["-rpc-addr"] = kong_config.cluster_listen_rpc, ["-advertise"] = kong_config.cluster_advertise, ["-encrypt"] = kong_config.cluster_encrypt_key, ["-keyring-file"] = kong_config.cluster_keyring_file, ["-log-level"] = "err", ["-profile"] = kong_config.cluster_profile, ["-node"] = serf.node_name, ["-event-handler"] = "member-join,member-leave,member-failed," .."member-update,member-reap,user:" ..serf_event_name.."="..kong_config.serf_event }, Serf.args_mt) local cmd = string.format("nohup %s agent %s > %s 2>&1 & echo $! > %s", kong_config.serf_path, tostring(args), kong_config.serf_log, kong_config.serf_pid) log.debug("starting serf agent: %s", cmd) -- start Serf agent local ok = pl_utils.execute(cmd) if not ok then return nil end log.verbose("waiting for serf agent to be running") -- ensure started (just an improved version of previous Serf service) local tstart = ngx.time() local texp, started = tstart + start_timeout repeat ngx.sleep(0.2) started = kill.is_running(kong_config.serf_pid) until started or ngx.time() >= texp if not started then -- time to get latest error log from serf.log local logs = pl_file.read(kong_config.serf_log) local tlogs = pl_stringx.split(logs, "\n") local err = string.gsub(tlogs[#tlogs-1], "==> ", "") err = pl_stringx.strip(err) return nil, "could not start serf: "..err end log.verbose("serf agent started") -- cleanup current node from cluster to prevent inconsistency of data local ok, err = serf:cleanup() if not ok then return nil, err end log.verbose("auto-joining serf cluster") local ok, err = serf:autojoin() if not ok then return nil, err end log.verbose("registering serf node in datastore") local ok, err = serf:add_node() if not ok then return nil, err end log.verbose("cluster joined and node registered in datastore") return true end function _M.stop(kong_config, dao) log.verbose("leaving serf cluster") local serf = Serf.new(kong_config, dao) local ok, err = serf:leave() if not ok then return nil, err end log.verbose("left serf cluster") log.verbose("stopping serf agent at %s", kong_config.serf_pid) local code = kill.kill(kong_config.serf_pid, "-15") --SIGTERM if code == 256 then -- If no error is returned pl_file.delete(kong_config.serf_pid) end log.verbose("serf agent stopped") return true end return _M
-- Enhanced implementation of previous "services.serf.lua" module, -- no change in actual logic, only decoupled from the events features -- which now live in kong.serf local pl_stringx = require "pl.stringx" local pl_utils = require "pl.utils" local pl_file = require "pl.file" local Serf = require "kong.serf" local kill = require "kong.cmd.utils.kill" local log = require "kong.cmd.utils.log" local meta = require "kong.meta" local version = require "version" local fmt = string.format local serf_event_name = "kong" local serf_version_pattern = "^Serf v([%d%.]+)" local serf_compatible = version.set(unpack(meta._DEPENDENCIES.serf)) local start_timeout = 5 local serf_search_paths = { "serf", "/usr/local/bin/serf" } local function check_version(path) local cmd = fmt("%s version", path) local ok, _, stdout = pl_utils.executeex(cmd) log.debug("%s: '%s'", cmd, pl_stringx.splitlines(stdout)[1]) if ok and stdout then local version_match = stdout:match(serf_version_pattern) if not version_match or not serf_compatible:matches(version_match) then log.verbose(fmt("incompatible serf found at '%s'. Kong requires version '%s', got '%s'", path, tostring(serf_compatible), version_match)) return nil end return true end log.debug("Serf executable not found at %s", path) end local function check_serf_bin(kong_config) log.debug("searching for 'serf' executable") if kong_config.serf_path then serf_search_paths = { kong_config.serf_path } end local found for _, path in ipairs(serf_search_paths) do if check_version(path) then found = path log.debug("found 'serf' executable at %s", found) break end end if not found then return nil, "could not find 'serf' executable. Kong requires version " .. serf_compatible .. " (you can tweak 'serf_path' to your needs)" end return found end local _M = {} function _M.start(kong_config, dao) -- is Serf already running in this prefix? if kill.is_running(kong_config.serf_pid) then log.verbose("serf agent already running at %s", kong_config.serf_pid) return true else log.verbose("serf agent not running, deleting %s", kong_config.serf_pid) pl_file.delete(kong_config.serf_pid) end -- make sure Serf is in PATH local ok, err = check_serf_bin(kong_config) if not ok then return nil, err end local serf = Serf.new(kong_config, dao) local args = setmetatable({ ["-bind"] = kong_config.cluster_listen, ["-rpc-addr"] = kong_config.cluster_listen_rpc, ["-advertise"] = kong_config.cluster_advertise, ["-encrypt"] = kong_config.cluster_encrypt_key, ["-keyring-file"] = kong_config.cluster_keyring_file, ["-log-level"] = "err", ["-profile"] = kong_config.cluster_profile, ["-node"] = serf.node_name, ["-event-handler"] = "member-join,member-leave,member-failed," .."member-update,member-reap,user:" ..serf_event_name.."="..kong_config.serf_event }, Serf.args_mt) local cmd = string.format("nohup %s agent %s > %s 2>&1 & echo $! > %s", kong_config.serf_path, tostring(args), kong_config.serf_log, kong_config.serf_pid) log.debug("starting serf agent: %s", cmd) -- start Serf agent local ok = pl_utils.execute(cmd) if not ok then return nil end log.verbose("waiting for serf agent to be running") -- ensure started (just an improved version of previous Serf service) local tstart = ngx.time() local texp, started = tstart + start_timeout repeat ngx.sleep(0.2) started = kill.is_running(kong_config.serf_pid) until started or ngx.time() >= texp if not started then -- time to get latest error log from serf.log local logs = pl_file.read(kong_config.serf_log) local tlogs = pl_stringx.split(logs, "\n") local err = string.gsub(tlogs[#tlogs-1], "==> ", "") err = pl_stringx.strip(err) return nil, "could not start serf: "..err end log.verbose("serf agent started") -- cleanup current node from cluster to prevent inconsistency of data local ok, err = serf:cleanup() if not ok then return nil, err end log.verbose("auto-joining serf cluster") local ok, err = serf:autojoin() if not ok then return nil, err end log.verbose("registering serf node in datastore") local ok, err = serf:add_node() if not ok then return nil, err end log.verbose("cluster joined and node registered in datastore") return true end function _M.stop(kong_config, dao) log.verbose("leaving serf cluster") local serf = Serf.new(kong_config, dao) local ok, err = serf:leave() if not ok then return nil, err end log.verbose("left serf cluster") log.verbose("stopping serf agent at %s", kong_config.serf_pid) local code = kill.kill(kong_config.serf_pid, "-15") --SIGTERM if code == 256 then -- If no error is returned pl_file.delete(kong_config.serf_pid) end log.verbose("serf agent stopped") return true end return _M
fix(cli) consistent logging output in serf path search
fix(cli) consistent logging output in serf path search
Lua
apache-2.0
Kong/kong,ccyphers/kong,shiprabehera/kong,Kong/kong,li-wl/kong,akh00/kong,Kong/kong,jebenexer/kong,salazar/kong,icyxp/kong,Mashape/kong
6c5a095967ca0dd1b937cd0f5743d65800e79cd9
premake.lua
premake.lua
-- TODO: Because there is plenty ... -- 1. What about other IDE's that Premake supports? e.g. codeblocks, xcode -- 2. x86/x64 switching -- 3. get macosx library for zlib -- 4. actually test linux/mac build configurations -- 5. clean this file up because I'm sure it could be organized better -- -- NOTE: I am intentionally leaving out a "windows+gmake" configuration -- as trying to compile against the FBX SDK using MinGW results in -- compile errors. Some quick googling seems to indicate MinGW is -- not supported by the FBX SDK? -- If you try to use this script to build with MinGW you will end -- up with a Makefile that has god knows what in it FBX_SDK_ROOT = os.getenv("FBX_SDK_ROOT") if not FBX_SDK_ROOT then printf("ERROR: Environment variable FBX_SDK_ROOT is not set.") printf("Set it to something like: C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2013.3") os.exit() end BUILD_DIR = "build" if _ACTION == "clean" then os.rmdir(BUILD_DIR) end solution "fbx-conv" configurations { "Debug", "Release" } location (BUILD_DIR .. "/" .. _ACTION) project "fbx-conv" --- GENERAL STUFF FOR ALL PLATFORMS -------------------------------- kind "ConsoleApp" language "C++" location (BUILD_DIR .. "/" .. _ACTION) files { "./src/**.c*", "./src/**.h", } includedirs { (FBX_SDK_ROOT .. "/include"), "./libs/libpng/include", "./libs/zlib/include", } defines { "FBXSDK_NEW_API", } debugdir "." configuration "Debug" defines { "DEBUG", } flags { "Symbols" } configuration "Release" defines { "NDEBUG", } flags { "Optimize" } --- VISUAL STUDIO -------------------------------------------------- configuration "vs*" flags { "NoPCH", "NoMinimalRebuild" } buildoptions { "/MP" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86"), "./libs/libpng/lib/windows/x86", "./libs/zlib/lib/windows/x86", } links { "libpng14", "zlib", } configuration { "vs*", "Debug" } links { "fbxsdk-2013.3-mdd", } configuration { "vs*", "Release" } links { "fbxsdk-2013.3-md", } --- LINUX (GCC+MAKE) ----------------------------------------------- configuration { "linux" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x86"), "./libs/libpng/lib/linux/x86", "./libs/zlib/lib/linux/x86", } links { "libpng", "libz", } configuration { "linux", "Debug" } links { "fbxsdk-2013-staticd", } configuration { "linux", "Release" } links { "fbxsdk-2013-static", } --- MAC (GCC+MAKE) ------------------------------------------------- configuration { "macosx" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub"), "./libs/libpng/lib/macosx/x86", "./libs/zlib/lib/macosx/x86", } links { "libpng", "libz", } configuration { "macosx", "Debug" } links { "fbxsdk-2013-staticd", } configuration { "macosx", "Release" } links { "fbxsdk-2013-static", }
-- TODO: Because there is plenty ... -- 1. What about other IDE's that Premake supports? e.g. codeblocks, xcode -- 2. x86/x64 switching -- 3. get macosx library for zlib -- 4. actually test linux/mac build configurations -- 5. clean this file up because I'm sure it could be organized better -- -- NOTE: I am intentionally leaving out a "windows+gmake" configuration -- as trying to compile against the FBX SDK using MinGW results in -- compile errors. Some quick googling seems to indicate MinGW is -- not supported by the FBX SDK? -- If you try to use this script to build with MinGW you will end -- up with a Makefile that has god knows what in it FBX_SDK_ROOT = os.getenv("FBX_SDK_ROOT") if not FBX_SDK_ROOT then printf("ERROR: Environment variable FBX_SDK_ROOT is not set.") printf("Set it to something like: C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2013.3") os.exit() end BUILD_DIR = "build" if _ACTION == "clean" then os.rmdir(BUILD_DIR) end solution "fbx-conv" configurations { "Debug", "Release" } location (BUILD_DIR .. "/" .. _ACTION) project "fbx-conv" --- GENERAL STUFF FOR ALL PLATFORMS -------------------------------- kind "ConsoleApp" language "C++" location (BUILD_DIR .. "/" .. _ACTION) files { "./src/**.c*", "./src/**.h", } includedirs { (FBX_SDK_ROOT .. "/include"), "./libs/libpng/include", "./libs/zlib/include", } defines { "FBXSDK_NEW_API", } debugdir "." configuration "Debug" defines { "DEBUG", } flags { "Symbols" } configuration "Release" defines { "NDEBUG", } flags { "Optimize" } --- VISUAL STUDIO -------------------------------------------------- configuration "vs*" flags { "NoPCH", "NoMinimalRebuild" } buildoptions { "/MP" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86"), "./libs/libpng/lib/windows/x86", "./libs/zlib/lib/windows/x86", } links { "libpng14", "zlib", } configuration { "vs*", "Debug" } links { "fbxsdk-2013.3-mdd", } configuration { "vs*", "Release" } links { "fbxsdk-2013.3-md", } --- LINUX (GCC+MAKE) ----------------------------------------------- configuration { "linux" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x86"), "./libs/libpng/lib/linux/x86", "./libs/zlib/lib/linux/x86", } links { "libpng", "libz", } configuration { "linux", "Debug" } links { "fbxsdk-2013-staticd", } configuration { "linux", "Release" } links { "fbxsdk-2013-static", } --- MAC (GCC+MAKE) ------------------------------------------------- configuration { "macosx" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub"), "./libs/libpng/lib/macosx", "./libs/zlib/lib/macosx", } links { "png", "z", "CoreFoundation.framework", } configuration { "macosx", "Debug" } links { "fbxsdk-2013.3-staticd", } configuration { "macosx", "Release" } links { "fbxsdk-2013.3-static", }
fix a bunch of incorrect things I wrote in the premake script for Mac builds
fix a bunch of incorrect things I wrote in the premake script for Mac builds
Lua
apache-2.0
iichenbf/fbx-conv,reduz/fbx-conv,iichenbf/fbx-conv,lvlonggame/fbx-conv,davidedmonds/fbx-conv,reduz/fbx-conv,arisecbf/fbx-conv,arisecbf/fbx-conv,xoppa/fbx-conv,lvlonggame/fbx-conv,xoppa/fbx-conv,iichenbf/fbx-conv,xoppa/fbx-conv,cocos2d-x/fbx-conv,lvlonggame/fbx-conv,andyvand/fbx-conv,davidedmonds/fbx-conv,reduz/fbx-conv,andyvand/fbx-conv,super626/fbx-conv,cocos2d-x/fbx-conv,super626/fbx-conv,Maxwolf/Multimap.FBXConv,cocos2d-x/fbx-conv,davidedmonds/fbx-conv,super626/fbx-conv,arisecbf/fbx-conv,Maxwolf/Multimap.FBXConv,andyvand/fbx-conv
82d18183116b43699e978c081206163105d73737
share/lua/website/soundcloud.lua
share/lua/website/soundcloud.lua
-- libquvi-scripts -- Copyright (C) 2011 Bastien Nocera <hadess@hadess.net> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local Soundcloud = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "soundcloud%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/.+/.+$", "/player.swf"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "soundcloud" Soundcloud.normalize(self) local page = quvi.fetch(self.page_url) local _,_,s = page:find("window%.SC%.bufferTracks%.push(%(.-%);)") local metadata = s or error("no match: metadata") local _,_,s = metadata:find('"uid":"(%w-)"') self.id = s or error("no match: media id") local _,_,s = metadata:find('"title":"(.-)"') local title = s or error("no match: media title") -- Unescape the Unicode strings if any -- the HTML will be unescaped by quvi itself self.title = string.gsub(title, "\\u(%d+)", function (h) return string.char(tonumber(h, 16)) end) local _,_,s = page:find('content="([:/%w%?%.-]-)" property="og:image"') self.thumbnail_url = s or "" local _,_,s = metadata:find('"duration":(%d-),') self.duration = tonumber(s) or 0 local _,_,s = metadata:find('"streamUrl":"(.-)"') self.url = { s } or error("no match: stream URL") return self end -- -- Utility functions -- function Soundcloud.normalize(self) -- "Normalize" an embedded URL local url = self.page_url:match('swf%?url=(.-)$') if not url then return end local U = require 'quvi/util' local oe_url = string.format( 'http://soundcloud.com/oembed?url=%s&format=json', U.unescape(url)) local s = quvi.fetch(oe_url):match('href=\\"(.-)\\"') self.page_url = s or error('no match: page url') end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2011 Bastien Nocera <hadess@hadess.net> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- For Soundcloud.toUtf8(): -- Copyright 2004 by Rici Lake. Permission is granted to use this code under -- the same terms and conditions as found in the Lua copyright notice at -- http://www.lua.org/license.html. local Soundcloud = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "soundcloud%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/.+/.+$", "/player.swf"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "soundcloud" Soundcloud.normalize(self) local page = quvi.fetch(self.page_url) local _,_,s = page:find("window%.SC%.bufferTracks%.push(%(.-%);)") local metadata = s or error("no match: metadata") local _,_,s = metadata:find('"uid":"(%w-)"') self.id = s or error("no match: media id") local _,_,s = metadata:find('"title":"(.-)"') local title = s or error("no match: media title") -- Unescape the Unicode strings if any -- the HTML will be unescaped by quvi itself self.title = string.gsub(title, "\\u(%x+)", function (h) return Soundcloud.toUtf8(tonumber(h, 16)) end) local _,_,s = page:find('content="([:/%w%?%.-]-)" property="og:image"') self.thumbnail_url = s or "" local _,_,s = metadata:find('"duration":(%d-),') self.duration = tonumber(s) or 0 local _,_,s = metadata:find('"streamUrl":"(.-)"') self.url = { s } or error("no match: stream URL") return self end -- -- Utility functions -- function Soundcloud.normalize(self) -- "Normalize" an embedded URL local url = self.page_url:match('swf%?url=(.-)$') if not url then return end local U = require 'quvi/util' local oe_url = string.format( 'http://soundcloud.com/oembed?url=%s&format=json', U.unescape(url)) local s = quvi.fetch(oe_url):match('href=\\"(.-)\\"') self.page_url = s or error('no match: page url') end -- Adapted from http://luaparse.luaforge.net/libquery.lua.html -- -- Convert an integer to a UTF-8 sequence, without checking for -- invalid codes. -- This originally had calls to floor scattered about but it is -- not necessary: string.char does a "C" conversion from float to int, -- which is a truncate towards zero operation; i must be non-negative, -- so that is the same as floor. function Soundcloud.toUtf8(i) if i <= 127 then return string.char(i) elseif i <= tonumber("7FF", 16) then return string.char(i / 64 + 192, math.mod(i, 64) + 128) elseif i <= tonumber("FFFF", 16) then return string.char(i / 4096 + 224, math.mod(i / 64, 64) + 128, math.mod(i, 64) + 128) else return string.char(i / 262144 + 240, math.mod(i / 4096, 64) + 128, math.mod(i / 64, 64) + 128, math.mod(i, 64) + 128) end end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: soundcloud.lua: Multi-byte char handling
FIX: soundcloud.lua: Multi-byte char handling The previous code only worked for unicode escaped characters that didn't contain any characters on the range a-f as we matched with %d. Furthermore, we didn't handle values >= 256 when unescaping them. This is now fixed using the helper code from: http://luaparse.luaforge.net/libquery.lua.html
Lua
lgpl-2.1
hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts
b7c182165fa8d2805d24e32105519190e1836cfb
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/df.lua
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/df.lua
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.df", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { title = "%H: Disk space usage on %di", vlabel = "Bytes", per_instance = true, number_format = "%5.1lf%sB", data = { sources = { df = { "free", "used" } }, options = { df__free = { color = "00ff00", overlay = false, title = "free" }, df__used = { color = "ff0000", overlay = false, title = "used" } } } } end
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.df", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { title = "%H: Disk space usage on %di", vlabel = "Bytes", per_instance = true, number_format = "%5.1lf%sB", data = { instances = { df_complex = { "free", "used", "reserved" } }, options = { df_complex_free = { color = "00ff00", overlay = false, title = "free" }, df_complex_used = { color = "ff0000", overlay = false, title = "used" }, df_complex_reserved = { color = "0000ff", overlay = false, title = "reserved" } } } } end
luci-app-statistics: Fix disk usage graphing
luci-app-statistics: Fix disk usage graphing Disk usage graphing was broken. This fixes it. Signed-off-by: Daniel Dickinson <9b934cf284d9b196f48b43876d3e01912797242c@daniel.thecshore.com> (cherry picked from commit 6d2163eb622a6f4da43b6ecc8379a1fc891b5b0b)
Lua
apache-2.0
Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,RuiChen1113/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,RuiChen1113/luci
989723b2c1d8854e279898f25d83d783c3534b73
share/lua/sd/appletrailers.lua
share/lua/sd/appletrailers.lua
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Ilkka Ollakka <ileoo at videolan dot org > This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] function descriptor() return { title="Apple Trailers" } end function find( haystack, needle ) local _,_,r = string.find( haystack, needle ) return r end function main() fd = vlc.stream( "http://trailers.apple.com/trailers/iphone/home/feeds/just_added.json" ) if not fd then return nil end options = {":http-user-agent='iPhone'"} while true do line = fd:readline() if not line then break end if string.match( line, "title" ) and string.match( line, "hd\":true")then title = vlc.strings.resolve_xml_special_chars( find( line, "title\":\"(.-)\"")) art = find( line, "poster\":\"(.-)\"") url = find( line, "url\":\"(.-)\"") url = string.gsub( url, "trailers/","trailers/iphone/") url = "http://trailers.apple.com"..url.."trailer/" vlc.sd.add_item( { path = url, name=title, title=title, options=options, arturl=art}) end end end
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Ilkka Ollakka <ileoo at videolan dot org > This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] function descriptor() return { title="Apple Trailers" } end function find( haystack, needle ) local _,_,r = string.find( haystack, needle ) return r end function main() fd = vlc.stream( "http://trailers.apple.com/trailers/iphone/home/feeds/just_added.json" ) if not fd then return nil end options = {":http-user-agent='iPhone'"} while true do line = fd:readline() if not line then break end if string.match( line, "title" ) and string.match( line, "hd\":true")then title = vlc.strings.resolve_xml_special_chars( find( line, "title\":\"(.-)\"")) art = find( line, "poster\":\"(.-)\"") url = find( line, "location\":\"(.-)\"") trailertype = "" trailertype = find( line, "type\":\"(.-)\"") vlc.msg.err(trailertype) if trailertype then trailertype = string.gsub( trailertype, " ", "") trailertype = string.lower( trailertype ) else trailertype = "trailer" end url = "http://trailers.apple.com"..url..trailertype.."/" vlc.sd.add_item( { path = url, name=title, title=title, options=options, arturl=art}) end end end
appletrailers sd: fix parsing
appletrailers sd: fix parsing Fix parsing to get trailertype. Should help to view all the trailers now.
Lua
lgpl-2.1
krichter722/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1
f492d291ebacbd043e1f520974e9137df77c594b
modules/game_cooldown/cooldown.lua
modules/game_cooldown/cooldown.lua
cooldownWindow = nil cooldownButton = nil contentsPanel = nil spellCooldownPanel = nil function init() connect(g_game, { onGameStart = online, onGameEnd = offline, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton = modules.client_topmenu.addRightGameToggleButton('cooldownButton', tr('Cooldowns'), '/images/topbuttons/cooldowns', toggle) cooldownButton:setOn(true) cooldownButton:hide() cooldownWindow = g_ui.loadUI('cooldown', modules.game_interface.getRightPanel()) cooldownWindow:disableResize() cooldownWindow:setup() contentsPanel = cooldownWindow:getChildById('contentsPanel') spellCooldownPanel = contentsPanel:getChildById('spellCooldownPanel') if g_game.isOnline() then online() end end function terminate() disconnect(g_game, { onGameStart = online, onGameEnd = offline, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton:destroy() cooldownWindow:destroy() end function onMiniWindowClose() cooldownButton:setOn(false) end function toggle() if cooldownButton:isOn() then cooldownWindow:close() cooldownButton:setOn(false) else cooldownWindow:open() cooldownButton:setOn(true) end end function online() if g_game.getFeature(GameSpellList) then cooldownButton:show() else cooldownButton:hide() cooldownWindow:close() end end function offline() end function updateProgressRect(progressRect, interval, init) if init then progressRect:setPercent(0) else progressRect:setPercent(progressRect:getPercent() + 5) end if progressRect:getPercent() < 100 then removeEvent(progressRect.event) progressRect.event = scheduleEvent(function() updateProgressRect(progressRect, interval) end, interval) end end function onSpellCooldown(iconId, duration) local spell, profile, spellName = Spells.getSpellByIcon(iconId) if not spellName then return end local ping = g_game.getPing() if ping > 0 then duration = duration - (ping/2) end clientIconId = Spells.getClientId(spellName) if not clientIconId then return end local icon = spellCooldownPanel:getChildById(spellName) if not icon then icon = g_ui.createWidget('SpellIcon', spellCooldownPanel) icon:setId(spellName) icon:setImageSource('/images/game/spells/' .. SpelllistSettings[profile].iconFile) icon:setImageClip(Spells.getImageClip(clientIconId, profile)) icon.event = scheduleEvent(function() icon:destroy() icon = nil end, duration) local progressRect = g_ui.createWidget('SpellProgressRect', icon) progressRect:fill('parent') progressRect:setTooltip(spellName) updateProgressRect(progressRect, duration/25, true) end end function onSpellGroupCooldown(groupId, duration) if not SpellGroups[groupId] then return end local ping = g_game.getPing() if ping > 0 then duration = duration - (ping/2) end local icon = contentsPanel:getChildById('groupIcon' .. SpellGroups[groupId]) local progressRect = contentsPanel:getChildById('progressRect' .. SpellGroups[groupId]) if icon then icon:setOn(true) removeEvent(icon.event) icon.event = scheduleEvent(function() icon:setOn(false) end, duration) end if progressRect then removeEvent(progressRect.event) updateProgressRect(progressRect, duration/25, true) end end
local ProgressCallback = { update = 1, finish = 2 } cooldownWindow = nil cooldownButton = nil contentsPanel = nil spellCooldownPanel = nil function init() connect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton = modules.client_topmenu.addRightGameToggleButton('cooldownButton', tr('Cooldowns'), '/images/topbuttons/cooldowns', toggle) cooldownButton:setOn(true) cooldownButton:hide() cooldownWindow = g_ui.loadUI('cooldown', modules.game_interface.getRightPanel()) cooldownWindow:disableResize() cooldownWindow:setup() contentsPanel = cooldownWindow:getChildById('contentsPanel') spellCooldownPanel = contentsPanel:getChildById('spellCooldownPanel') if g_game.isOnline() then online() end end function terminate() disconnect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton:destroy() cooldownWindow:destroy() end function onMiniWindowClose() cooldownButton:setOn(false) end function toggle() if cooldownButton:isOn() then cooldownWindow:close() cooldownButton:setOn(false) else cooldownWindow:open() cooldownButton:setOn(true) end end function online() if g_game.getFeature(GameSpellList) then cooldownButton:show() else cooldownButton:hide() cooldownWindow:close() end end function removeCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:destroy() progressRect.icon = nil end progressRect = nil end function turnOffCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:setOn(false) progressRect.icon = nil end progressRect = nil end function initCooldown(progressRect, updateCallback, finishCallback) progressRect:setPercent(0) progressRect.callback = {} progressRect.callback[ProgressCallback.update] = updateCallback progressRect.callback[ProgressCallback.finish] = finishCallback updateCallback() end function updateCooldown(progressRect, interval) progressRect:setPercent(progressRect:getPercent() + 5) if progressRect:getPercent() < 100 then removeEvent(progressRect.event) progressRect.event = scheduleEvent(function() progressRect.callback[ProgressCallback.update]() end, interval) else progressRect.callback[ProgressCallback.finish]() end end function onSpellCooldown(iconId, duration) local spell, profile, spellName = Spells.getSpellByIcon(iconId) if not spellName then return end --local ping = g_game.getPing() --if ping > 0 then duration = duration + ping end clientIconId = Spells.getClientId(spellName) if not clientIconId then return end local icon = spellCooldownPanel:getChildById(spellName) if not icon then icon = g_ui.createWidget('SpellIcon', spellCooldownPanel) icon:setId(spellName) icon:setImageSource('/images/game/spells/' .. SpelllistSettings[profile].iconFile) icon:setImageClip(Spells.getImageClip(clientIconId, profile)) local progressRect = g_ui.createWidget('SpellProgressRect', icon) progressRect.icon = icon progressRect:fill('parent') progressRect:setTooltip(spellName) local updateFunc = function() updateCooldown(progressRect, duration/25) end local finishFunc = function() removeCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end end function onSpellGroupCooldown(groupId, duration) if not SpellGroups[groupId] then return end --local ping = g_game.getPing() --if ping > 0 then duration = duration + ping end local icon = contentsPanel:getChildById('groupIcon' .. SpellGroups[groupId]) local progressRect = contentsPanel:getChildById('progressRect' .. SpellGroups[groupId]) if icon then icon:setOn(true) removeEvent(icon.event) end progressRect.icon = icon if progressRect then removeEvent(progressRect.event) local updateFunc = function() updateCooldown(progressRect, duration/25) end local finishFunc = function() turnOffCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end end
More fixes to spell cooldown module: * Fixed duration issues. * Fixed referencing after destroyed issue. * Using callbacks for progress rect now.
More fixes to spell cooldown module: * Fixed duration issues. * Fixed referencing after destroyed issue. * Using callbacks for progress rect now.
Lua
mit
dreamsxin/otclient,Radseq/otclient,Cavitt/otclient_mapgen,gpedro/otclient,Radseq/otclient,Cavitt/otclient_mapgen,EvilHero90/otclient,gpedro/otclient,kwketh/otclient,EvilHero90/otclient,kwketh/otclient,dreamsxin/otclient,gpedro/otclient,dreamsxin/otclient
1b210126778c4c92b1026657e6b69508dac7f5cf
spec/integration/proxy/realip_spec.lua
spec/integration/proxy/realip_spec.lua
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local stringy = require "stringy" local cjson = require "cjson" local yaml = require "yaml" local uuid = require "uuid" local IO = require "kong.tools.io" -- This is important to seed the UUID generator uuid.seed() local FILE_LOG_PATH = "/tmp/file_log_spec_output.log" describe("Real IP", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { { name = "tests realip", public_dns = "realip.com", target_url = "http://mockbin.com" } }, plugin_configuration = { { name = "filelog", value = { path = FILE_LOG_PATH }, __api = 1 } } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) it("should parse the correct IP", function() os.remove(FILE_LOG_PATH) local uuid = string.gsub(uuid(), "-", "") -- Making the request local _, status = http_client.get(spec_helper.STUB_GET_URL, nil, { host = "realip.com", ["X-Forwarded-For"] = "4.4.4.4, 1.1.1.1, 5.5.5.5", file_log_uuid = uuid } ) assert.are.equal(200, status) while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do -- Wait for the file to be created, and for the log to be appended end local file_log = IO.read_file(FILE_LOG_PATH) local log_message = cjson.decode(stringy.strip(file_log)) assert.are.same("4.4.4.4", log_message.client_ip) assert.are.same(uuid, log_message.request.headers.file_log_uuid) end) end)
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local stringy = require "stringy" local cjson = require "cjson" local yaml = require "yaml" local uuid = require "uuid" local IO = require "kong.tools.io" -- This is important to seed the UUID generator uuid.seed() local FILE_LOG_PATH = spec_helper.get_env().configuration.nginx_working_dir.."/file_log_spec_output.log" describe("Real IP", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { { name = "tests realip", public_dns = "realip.com", target_url = "http://mockbin.com" } }, plugin_configuration = { { name = "filelog", value = { path = FILE_LOG_PATH }, __api = 1 } } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) it("should parse the correct IP", function() os.remove(FILE_LOG_PATH) local uuid = string.gsub(uuid(), "-", "") -- Making the request local _, status = http_client.get(spec_helper.STUB_GET_URL, nil, { host = "realip.com", ["X-Forwarded-For"] = "4.4.4.4, 1.1.1.1, 5.5.5.5", file_log_uuid = uuid } ) assert.are.equal(200, status) while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do -- Wait for the file to be created, and for the log to be appended end local file_log = IO.read_file(FILE_LOG_PATH) local log_message = cjson.decode(stringy.strip(file_log)) assert.are.same("4.4.4.4", log_message.client_ip) assert.are.same(uuid, log_message.request.headers.file_log_uuid) end) end)
fix(tests) using the local nginx_tmp directory
fix(tests) using the local nginx_tmp directory
Lua
apache-2.0
peterayeni/kong,chourobin/kong,wakermahmud/kong,skynet/kong,vmercierfr/kong,puug/kong,Skyscanner/kong,sbuettner/kong,ChristopherBiscardi/kong,bbalu/kong,AnsonSmith/kong,paritoshmmmec/kong
4437c46825b34ced12a5e6babd4d681067c79db1
lua_modules/ds3231/ds3231.lua
lua_modules/ds3231/ds3231.lua
-------------------------------------------------------------------------------- -- DS3231 I2C module for NODEMCU -- NODEMCU TEAM -- LICENCE: http://opensource.org/licenses/MIT -- Tobie Booth <tbooth@hindbra.in> -------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M -- Default value for i2c communication local id = 0 --device address local dev_addr = 0x68 local function decToBcd(val) return((val/10*16) + (val%10)) end local function bcdToDec(val) return((val/16*10) + (val%16)) end -- initialize i2c --parameters: --d: sda --l: scl function M.init(d, l) if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then sda = d scl = l else print("iic config failed!") return nil end print("init done") i2c.setup(id, sda, scl, i2c.SLOW) end --get time from DS3231 function M.getTime() i2c.start(id) i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.write(id, 0x00) i2c.stop(id) i2c.start(id) i2c.address(id, dev_addr, i2c.RECEIVER) local c=i2c.read(id, 7) i2c.stop(id) return bcdToDec(tonumber(string.byte(c, 1))), bcdToDec(tonumber(string.byte(c, 2))), bcdToDec(tonumber(string.byte(c, 3))), bcdToDec(tonumber(string.byte(c, 4))), bcdToDec(tonumber(string.byte(c, 5))), bcdToDec(tonumber(string.byte(c, 6))), bcdToDec(tonumber(string.byte(c, 7))) end --set time for DS3231 function M.setTime(second, minute, hour, day, date, month, year) i2c.start(id) i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.write(id, 0x00) i2c.write(id, decToBcd(second)) i2c.write(id, decToBcd(minute)) i2c.write(id, decToBcd(hour)) i2c.write(id, decToBcd(day)) i2c.write(id, decToBcd(date)) i2c.write(id, decToBcd(month)) i2c.write(id, decToBcd(year)) i2c.stop(id) end return M
-------------------------------------------------------------------------------- -- DS3231 I2C module for NODEMCU -- NODEMCU TEAM -- LICENCE: http://opensource.org/licenses/MIT -- Tobie Booth <tbooth@hindbra.in> -------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M -- Default value for i2c communication local id = 0 --device address local dev_addr = 0x68 local function decToBcd(val) return((((val/10) - ((val/10)%1)) *16) + (val%10)) end local function bcdToDec(val) return((((val/16) - ((val/16)%1)) *10) + (val%16)) end -- initialize i2c --parameters: --d: sda --l: scl function M.init(d, l) if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then sda = d scl = l else print("iic config failed!") return nil end print("init done") i2c.setup(id, sda, scl, i2c.SLOW) end --get time from DS3231 function M.getTime() i2c.start(id) i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.write(id, 0x00) i2c.stop(id) i2c.start(id) i2c.address(id, dev_addr, i2c.RECEIVER) local c=i2c.read(id, 7) i2c.stop(id) return bcdToDec(tonumber(string.byte(c, 1))), bcdToDec(tonumber(string.byte(c, 2))), bcdToDec(tonumber(string.byte(c, 3))), bcdToDec(tonumber(string.byte(c, 4))), bcdToDec(tonumber(string.byte(c, 5))), bcdToDec(tonumber(string.byte(c, 6))), bcdToDec(tonumber(string.byte(c, 7))) end --set time for DS3231 function M.setTime(second, minute, hour, day, date, month, year) i2c.start(id) i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.write(id, 0x00) i2c.write(id, decToBcd(second)) i2c.write(id, decToBcd(minute)) i2c.write(id, decToBcd(hour)) i2c.write(id, decToBcd(day)) i2c.write(id, decToBcd(date)) i2c.write(id, decToBcd(month)) i2c.write(id, decToBcd(year)) i2c.stop(id) end return M
fixed floating point problem in bcd conversions
fixed floating point problem in bcd conversions
Lua
mit
marcelstoer/nodemcu-firmware,TerryE/nodemcu-firmware,anusornc/nodemcu-firmware,funshine/nodemcu-firmware,ruisebastiao/nodemcu-firmware,cs8425/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,FrankX0/nodemcu-firmware,FelixPe/nodemcu-firmware,ojahan/node-mcu-firmware,mikeller/nodemcu-firmware,Alkorin/nodemcu-firmware,karrots/nodemcu-firmware,iotcafe/nodemcu-firmware,Kisaua/nodemcu-firmware,TerryE/nodemcu-firmware,petrkr/nodemcu-firmware,marcelstoer/nodemcu-firmware,oyooyo/nodemcu-firmware,marktsai0316/nodemcu-firmware,orlando3d/nodemcu-firmware,ojahan/node-mcu-firmware,borromeotlhs/nodemcu-firmware,nwf/nodemcu-firmware,creationix/nodemcu-firmware,raburton/nodemcu-firmware,xatanais/nodemcu-firmware,HEYAHONG/nodemcu-firmware,ruisebastiao/nodemcu-firmware,dscoolx6/MyESP8266,oyooyo/nodemcu-firmware,mikeller/nodemcu-firmware,kbeckmann/nodemcu-firmware,vowstar/nodemcu-firmware,Alkorin/nodemcu-firmware,devsaurus/nodemcu-firmware,christakahashi/nodemcu-firmware,bhrt/nodeMCU,nwf/nodemcu-firmware,SmartArduino/nodemcu-firmware,fetchbot/nodemcu-firmware,luizfeliperj/nodemcu-firmware,funshine/nodemcu-firmware,karrots/nodemcu-firmware,xatanais/nodemcu-firmware,robertfoss/nodemcu-firmware,benwolfe/nodemcu-firmware,marcelstoer/nodemcu-firmware,eku/nodemcu-firmware,shangwudong/MyNodeMcu,SmartArduino/nodemcu-firmware,zerog2k/nodemcu-firmware,ciufciuf57/nodemcu-firmware,FelixPe/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,raburton/nodemcu-firmware,robertfoss/nodemcu-firmware,dnc40085/nodemcu-firmware,HEYAHONG/nodemcu-firmware,devsaurus/nodemcu-firmware,nodemcu/nodemcu-firmware,ktosiu/nodemcu-firmware,xatanais/nodemcu-firmware,marktsai0316/nodemcu-firmware,yurenyong123/nodemcu-firmware,Kisaua/nodemcu-firmware,bogvak/nodemcu-firmware,klukonin/nodemcu-firmware,nodemcu/nodemcu-firmware,noahchense/nodemcu-firmware,FelixPe/nodemcu-firmware,sowbug/nodemcu-firmware,eku/nodemcu-firmware,funshine/nodemcu-firmware,radiojam11/nodemcu-firmware,makefu/nodemcu-firmware,borromeotlhs/nodemcu-firmware,jmattsson/nodemcu-firmware,bhrt/nodeMCU,remspoor/nodemcu-firmware,danronco/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,christakahashi/nodemcu-firmware,raburton/nodemcu-firmware,natetrue/nodemcu-firmware,robertfoss/nodemcu-firmware,fetchbot/nodemcu-firmware,vsky279/nodemcu-firmware,dnc40085/nodemcu-firmware,abgoyal/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,christakahashi/nodemcu-firmware,mikeller/nodemcu-firmware,jmattsson/nodemcu-firmware,marcelstoer/nodemcu-firmware,funshine/nodemcu-firmware,nodemcu/nodemcu-firmware,natetrue/nodemcu-firmware,sowbug/nodemcu-firmware,karrots/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,TerryE/nodemcu-firmware,radiojam11/nodemcu-firmware,luizfeliperj/nodemcu-firmware,makefu/nodemcu-firmware,dnc40085/nodemcu-firmware,rowellx68/nodemcu-firmware-custom,sowbug/nodemcu-firmware,TerryE/nodemcu-firmware,oyooyo/nodemcu-firmware,digitalloggers/nodemcu-firmware,FrankX0/nodemcu-firmware,remspoor/nodemcu-firmware,anusornc/nodemcu-firmware,flexiti/nodemcu-firmware,zerog2k/nodemcu-firmware,cs8425/nodemcu-firmware,iotcafe/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,digitalloggers/nodemcu-firmware,noahchense/nodemcu-firmware,petrkr/nodemcu-firmware,bogvak/nodemcu-firmware,rowellx68/nodemcu-firmware-custom,nwf/nodemcu-firmware,kbeckmann/nodemcu-firmware,nwf/nodemcu-firmware,nodemcu/nodemcu-firmware,filug/nodemcu-firmware,ruisebastiao/nodemcu-firmware,karrots/nodemcu-firmware,orlando3d/nodemcu-firmware,FrankX0/nodemcu-firmware,weera00/nodemcu-firmware,flexiti/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,vowstar/nodemcu-firmware,Alkorin/nodemcu-firmware,jmattsson/nodemcu-firmware,FelixPe/nodemcu-firmware,filug/nodemcu-firmware,vsky279/nodemcu-firmware,funshine/nodemcu-firmware,FrankX0/nodemcu-firmware,djphoenix/nodemcu-firmware,karrots/nodemcu-firmware,marcelstoer/nodemcu-firmware,filug/nodemcu-firmware,zerog2k/nodemcu-firmware,dscoolx6/MyESP8266,Andrew-Collins/nodemcu-firmware,nodemcu/nodemcu-firmware,flexiti/nodemcu-firmware,makefu/nodemcu-firmware,remspoor/nodemcu-firmware,borromeotlhs/nodemcu-firmware,FrankX0/nodemcu-firmware,christakahashi/nodemcu-firmware,radiojam11/nodemcu-firmware,kbeckmann/nodemcu-firmware,jmattsson/nodemcu-firmware,kbeckmann/nodemcu-firmware,klukonin/nodemcu-firmware,FelixPe/nodemcu-firmware,HEYAHONG/nodemcu-firmware,Alkorin/nodemcu-firmware,creationix/nodemcu-firmware,djphoenix/nodemcu-firmware,ciufciuf57/nodemcu-firmware,romanchyla/nodemcu-firmware,ktosiu/nodemcu-firmware,daned33/nodemcu-firmware,abgoyal/nodemcu-firmware,remspoor/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,vsky279/nodemcu-firmware,benwolfe/nodemcu-firmware,yurenyong123/nodemcu-firmware,oyooyo/nodemcu-firmware,devsaurus/nodemcu-firmware,Kisaua/nodemcu-firmware,luizfeliperj/nodemcu-firmware,noahchense/nodemcu-firmware,creationix/nodemcu-firmware,nwf/nodemcu-firmware,shangwudong/MyNodeMcu,ktosiu/nodemcu-firmware,danronco/nodemcu-firmware,christakahashi/nodemcu-firmware,orlando3d/nodemcu-firmware,digitalloggers/nodemcu-firmware,daned33/nodemcu-firmware,natetrue/nodemcu-firmware,romanchyla/nodemcu-firmware,abgoyal/nodemcu-firmware,shangwudong/MyNodeMcu,daned33/nodemcu-firmware,petrkr/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,weera00/nodemcu-firmware,romanchyla/nodemcu-firmware,devsaurus/nodemcu-firmware,shangwudong/MyNodeMcu,ojahan/node-mcu-firmware,SmartArduino/nodemcu-firmware,bhrt/nodeMCU,petrkr/nodemcu-firmware,cs8425/nodemcu-firmware,zhujunsan/nodemcu-firmware,bhrt/nodeMCU,HEYAHONG/nodemcu-firmware,devsaurus/nodemcu-firmware,jmattsson/nodemcu-firmware,klukonin/nodemcu-firmware,bhrt/nodeMCU,petrkr/nodemcu-firmware,danronco/nodemcu-firmware,Alkorin/nodemcu-firmware,marktsai0316/nodemcu-firmware,vsky279/nodemcu-firmware,rowellx68/nodemcu-firmware-custom,kbeckmann/nodemcu-firmware,dscoolx6/MyESP8266,luizfeliperj/nodemcu-firmware,yurenyong123/nodemcu-firmware,TerryE/nodemcu-firmware,dnc40085/nodemcu-firmware,benwolfe/nodemcu-firmware,eku/nodemcu-firmware,djphoenix/nodemcu-firmware,vowstar/nodemcu-firmware,remspoor/nodemcu-firmware,weera00/nodemcu-firmware,zhujunsan/nodemcu-firmware,fetchbot/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,eku/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,vsky279/nodemcu-firmware,bogvak/nodemcu-firmware,anusornc/nodemcu-firmware,ciufciuf57/nodemcu-firmware,dnc40085/nodemcu-firmware,djphoenix/nodemcu-firmware,zhujunsan/nodemcu-firmware,HEYAHONG/nodemcu-firmware,shangwudong/MyNodeMcu,fetchbot/nodemcu-firmware,iotcafe/nodemcu-firmware
6b45a4ea06279313b52a3ea11ddb39107a3b5c8a
frontend/cache.lua
frontend/cache.lua
--[[ A global LRU cache ]]-- local md5 = require("MD5") local lfs = require("libs/libkoreader-lfs") local DEBUG = require("dbg") local function calcFreeMem() local meminfo = io.open("/proc/meminfo", "r") local freemem = 0 if meminfo then for line in meminfo:lines() do local free, buffer, cached, n free, n = line:gsub("^MemFree:%s-(%d+) kB", "%1") if n ~= 0 then freemem = freemem + tonumber(free)*1024 end buffer, n = line:gsub("^Buffers:%s-(%d+) kB", "%1") if n ~= 0 then freemem = freemem + tonumber(buffer)*1024 end cached, n = line:gsub("^Cached:%s-(%d+) kB", "%1") if n ~= 0 then freemem = freemem + tonumber(cached)*1024 end end meminfo:close() end return freemem end local function calcCacheMemSize() local min = DGLOBAL_CACHE_SIZE_MINIMUM local max = DGLOBAL_CACHE_SIZE_MAXIMUM local calc = calcFreeMem()*(DGLOBAL_CACHE_FREE_PROPORTION or 0) return math.min(max, math.max(min, calc)) end local cache_path = lfs.currentdir().."/cache/" --[[ -- return a snapshot of disk cached items for subsequent check --]] local function getDiskCache() local cached = {} for key_md5 in lfs.dir(cache_path) do local file = cache_path..key_md5 if lfs.attributes(file, "mode") == "file" then cached[key_md5] = file end end return cached end local Cache = { -- cache configuration: max_memsize = calcCacheMemSize(), -- cache state: current_memsize = 0, -- associative cache cache = {}, -- this will hold the LRU order of the cache cache_order = {}, -- disk Cache snapshot cached = getDiskCache(), } function Cache:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function Cache:insert(key, object) -- guarantee that we have enough memory in cache if(object.size > self.max_memsize) then DEBUG("too much memory claimed for", key) return end -- delete objects that least recently used -- (they are at the end of the cache_order array) while self.current_memsize + object.size > self.max_memsize do local removed_key = table.remove(self.cache_order) self.current_memsize = self.current_memsize - self.cache[removed_key].size self.cache[removed_key]:onFree() self.cache[removed_key] = nil end -- insert new object in front of the LRU order table.insert(self.cache_order, 1, key) self.cache[key] = object self.current_memsize = self.current_memsize + object.size end --[[ -- check for cache item for key -- if ItemClass is given, disk cache is also checked. --]] function Cache:check(key, ItemClass) if self.cache[key] then if self.cache_order[1] ~= key then -- put key in front of the LRU list for k, v in ipairs(self.cache_order) do if v == key then table.remove(self.cache_order, k) end end table.insert(self.cache_order, 1, key) end return self.cache[key] elseif ItemClass then local cached = self.cached[md5(key)] if cached then local item = ItemClass:new{} local ok, msg = pcall(item.load, item, cached) if ok then self:insert(key, item) return item else DEBUG("discard cache", msg) end end end end function Cache:willAccept(size) -- we only allow single objects to fill 75% of the cache if size*4 < self.max_memsize*3 then return true end end function Cache:serialize() -- calculate disk cache size local cached_size = 0 local sorted_caches = {} for _,file in pairs(self.cached) do table.insert(sorted_caches, {file=file, time=lfs.attributes(file, "access")}) cached_size = cached_size + (lfs.attributes(file, "size") or 0) end table.sort(sorted_caches, function(v1,v2) return v1.time > v2.time end) -- serialize the most recently used cache local cache_size = 0 for _, key in ipairs(self.cache_order) do local cache_item = self.cache[key] -- only dump cache item that requests serialization explicitly if cache_item.persistent and cache_item.dump then DEBUG("dump cache item", key) cache_size = cache_item:dump(cache_path..md5(key)) or 0 if cache_size > 0 then break end end end -- set disk cache the same limit as memory cache while cached_size + cache_size - self.max_memsize > 0 do -- discard the least recently used cache local discarded = table.remove(sorted_caches) cached_size = cached_size - lfs.attributes(discarded.file, "size") os.remove(discarded.file) end -- disk cache may have changes so need to refresh disk cache snapshot self.cached = getDiskCache() end -- blank the cache function Cache:clear() for k, _ in pairs(self.cache) do self.cache[k]:onFree() end self.cache = {} self.cache_order = {} self.current_memsize = 0 end return Cache
--[[ A global LRU cache ]]-- local md5 = require("MD5") local lfs = require("libs/libkoreader-lfs") local DEBUG = require("dbg") local function calcFreeMem() local meminfo = io.open("/proc/meminfo", "r") local freemem = 0 if meminfo then for line in meminfo:lines() do local free, buffer, cached, n free, n = line:gsub("^MemFree:%s-(%d+) kB", "%1") if n ~= 0 then freemem = freemem + tonumber(free)*1024 end buffer, n = line:gsub("^Buffers:%s-(%d+) kB", "%1") if n ~= 0 then freemem = freemem + tonumber(buffer)*1024 end cached, n = line:gsub("^Cached:%s-(%d+) kB", "%1") if n ~= 0 then freemem = freemem + tonumber(cached)*1024 end end meminfo:close() end return freemem end local function calcCacheMemSize() local min = DGLOBAL_CACHE_SIZE_MINIMUM local max = DGLOBAL_CACHE_SIZE_MAXIMUM local calc = calcFreeMem()*(DGLOBAL_CACHE_FREE_PROPORTION or 0) return math.min(max, math.max(min, calc)) end local cache_path = lfs.currentdir().."/cache/" --[[ -- return a snapshot of disk cached items for subsequent check --]] local function getDiskCache() local cached = {} for key_md5 in lfs.dir(cache_path) do local file = cache_path..key_md5 if lfs.attributes(file, "mode") == "file" then cached[key_md5] = file end end return cached end local Cache = { -- cache configuration: max_memsize = calcCacheMemSize(), -- cache state: current_memsize = 0, -- associative cache cache = {}, -- this will hold the LRU order of the cache cache_order = {}, -- disk Cache snapshot cached = getDiskCache(), } function Cache:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end -- internal: remove reference in cache_order list function Cache:_unref(key) for i = #self.cache_order, 1, -1 do if self.cache_order[i] == key then table.remove(self.cache_order, i) end end end -- internal: free cache item function Cache:_free(key) if not self.cache[key] then return end self.current_memsize = self.current_memsize - self.cache[key].size self.cache[key]:onFree() self.cache[key] = nil end -- drop an item named via key from the cache function Cache:drop(key) self:_unref(key) self:_free(key) end function Cache:insert(key, object) -- make sure that one key only exists once: delete existing self:drop(key) -- guarantee that we have enough memory in cache if(object.size > self.max_memsize) then DEBUG("too much memory claimed for", key) return end -- delete objects that least recently used -- (they are at the end of the cache_order array) while self.current_memsize + object.size > self.max_memsize do local removed_key = table.remove(self.cache_order) self:_free(removed_key) end -- insert new object in front of the LRU order table.insert(self.cache_order, 1, key) self.cache[key] = object self.current_memsize = self.current_memsize + object.size end --[[ -- check for cache item for key -- if ItemClass is given, disk cache is also checked. --]] function Cache:check(key, ItemClass) if self.cache[key] then if self.cache_order[1] ~= key then -- put key in front of the LRU list self:_unref(key) table.insert(self.cache_order, 1, key) end return self.cache[key] elseif ItemClass then local cached = self.cached[md5(key)] if cached then local item = ItemClass:new{} local ok, msg = pcall(item.load, item, cached) if ok then self:insert(key, item) return item else DEBUG("discard cache", msg) end end end end function Cache:willAccept(size) -- we only allow single objects to fill 75% of the cache if size*4 < self.max_memsize*3 then return true end end function Cache:serialize() -- calculate disk cache size local cached_size = 0 local sorted_caches = {} for _,file in pairs(self.cached) do table.insert(sorted_caches, {file=file, time=lfs.attributes(file, "access")}) cached_size = cached_size + (lfs.attributes(file, "size") or 0) end table.sort(sorted_caches, function(v1,v2) return v1.time > v2.time end) -- serialize the most recently used cache local cache_size = 0 for _, key in ipairs(self.cache_order) do local cache_item = self.cache[key] -- only dump cache item that requests serialization explicitly if cache_item.persistent and cache_item.dump then DEBUG("dump cache item", key) cache_size = cache_item:dump(cache_path..md5(key)) or 0 if cache_size > 0 then break end end end -- set disk cache the same limit as memory cache while cached_size + cache_size - self.max_memsize > 0 do -- discard the least recently used cache local discarded = table.remove(sorted_caches) cached_size = cached_size - lfs.attributes(discarded.file, "size") os.remove(discarded.file) end -- disk cache may have changes so need to refresh disk cache snapshot self.cached = getDiskCache() end -- blank the cache function Cache:clear() for k, _ in pairs(self.cache) do self.cache[k]:onFree() end self.cache = {} self.cache_order = {} self.current_memsize = 0 end return Cache
fix cache implementation
fix cache implementation the cache would behave badly when the same item was insert()ed twice: it would add the size twice to memory consumption, but would never substract it twice when purging the (actually single) object from cache. So the cache would seem to fill up while in fact it wasn't.
Lua
agpl-3.0
NickSavage/koreader,noname007/koreader,frankyifei/koreader,houqp/koreader,NiLuJe/koreader,ashang/koreader,chihyang/koreader,Frenzie/koreader,Hzj-jie/koreader,lgeek/koreader,Frenzie/koreader,mwoz123/koreader,koreader/koreader,apletnev/koreader,robert00s/koreader,koreader/koreader,NiLuJe/koreader,ashhher3/koreader,pazos/koreader,Markismus/koreader,poire-z/koreader,poire-z/koreader,chrox/koreader,mihailim/koreader
aae809ba4838ddaebfff1d3f3564ba00c86d4901
frontend/ui/widget/buttontable.lua
frontend/ui/widget/buttontable.lua
local HorizontalGroup = require("ui/widget/horizontalgroup") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") local FocusManager = require("ui/widget/focusmanager") local LineWidget = require("ui/widget/linewidget") local Blitbuffer = require("ffi/blitbuffer") local Button = require("ui/widget/button") local Geom = require("ui/geometry") local Device = require("device") local Screen = Device.screen local ButtonTable = FocusManager:new{ width = Screen:getWidth(), buttons = { { {text="OK", enabled=true, callback=nil}, {text="Cancel", enabled=false, callback=nil}, }, }, sep_width = Screen:scaleBySize(1), padding = Screen:scaleBySize(2), zero_sep = false, button_font_face = "cfont", button_font_size = 20, } function ButtonTable:init() self.buttons_layout = {} self.container = VerticalGroup:new{ width = self.width } table.insert(self, self.container) if self.zero_sep then self:addHorizontalSep() end local row_cnt = #self.buttons for i = 1, row_cnt do self.buttons_layout[i] = {} local horizontal_group = HorizontalGroup:new{} local row = self.buttons[i] local column_cnt = #row local sizer_space = self.sep_width * (column_cnt - 1) + 2 for j = 1, column_cnt do local btn_entry = row[j] local button = Button:new{ text = btn_entry.text, enabled = btn_entry.enabled, callback = btn_entry.callback, width = (self.width - sizer_space)/column_cnt, bordersize = 0, margin = 0, padding = 0, text_font_face = self.button_font_face, text_font_size = self.button_font_size, show_parent = self.show_parent, } local button_dim = button:getSize() local vertical_sep = LineWidget:new{ background = Blitbuffer.COLOR_GREY, dimen = Geom:new{ w = self.sep_width, h = button_dim.h, } } self.buttons_layout[i][j] = button table.insert(horizontal_group, button) if j < column_cnt then table.insert(horizontal_group, vertical_sep) end end -- end for each button table.insert(self.container, horizontal_group) if i < row_cnt then self:addHorizontalSep() end end -- end for each button line if Device:hasDPad() or Device:hasKeyboard() then self.layout = self.buttons_layout self.layout[1][1]:onFocus() self.key_events.SelectByKeyPress = { {{"Press", "Enter"}} } else self.key_events = {} -- deregister all key press event listeners end end function ButtonTable:addHorizontalSep() table.insert(self.container, VerticalSpan:new{ width = Screen:scaleBySize(2) }) table.insert(self.container, LineWidget:new{ background = Blitbuffer.COLOR_GREY, dimen = Geom:new{ w = self.width, h = self.sep_width, } }) table.insert(self.container, VerticalSpan:new{ width = Screen:scaleBySize(2) }) end function ButtonTable:onSelectByKeyPress() self:getFocusItem().callback() end return ButtonTable
local Blitbuffer = require("ffi/blitbuffer") local Button = require("ui/widget/button") local Device = require("device") local FocusManager = require("ui/widget/focusmanager") local HorizontalGroup = require("ui/widget/horizontalgroup") local LineWidget = require("ui/widget/linewidget") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") local Geom = require("ui/geometry") local Screen = Device.screen local ButtonTable = FocusManager:new{ width = Screen:getWidth(), buttons = { { {text="OK", enabled=true, callback=nil}, {text="Cancel", enabled=false, callback=nil}, }, }, sep_width = Screen:scaleBySize(1), padding = Screen:scaleBySize(2), zero_sep = false, button_font_face = "cfont", button_font_size = 20, } function ButtonTable:init() self.buttons_layout = {} self.container = VerticalGroup:new{ width = self.width } table.insert(self, self.container) if self.zero_sep then self:addHorizontalSep() end local row_cnt = #self.buttons for i = 1, row_cnt do self.buttons_layout[i] = {} local horizontal_group = HorizontalGroup:new{} local row = self.buttons[i] local column_cnt = #row local sizer_space = self.sep_width * (column_cnt - 1) + 2 for j = 1, column_cnt do local btn_entry = row[j] local button = Button:new{ text = btn_entry.text, enabled = btn_entry.enabled, callback = btn_entry.callback, width = (self.width - sizer_space)/column_cnt, max_width = (self.width - sizer_space)/column_cnt - 2*self.sep_width - 2*self.padding, bordersize = 0, margin = 0, padding = 0, text_font_face = self.button_font_face, text_font_size = self.button_font_size, show_parent = self.show_parent, } local button_dim = button:getSize() local vertical_sep = LineWidget:new{ background = Blitbuffer.COLOR_GREY, dimen = Geom:new{ w = self.sep_width, h = button_dim.h, } } self.buttons_layout[i][j] = button table.insert(horizontal_group, button) if j < column_cnt then table.insert(horizontal_group, vertical_sep) end end -- end for each button table.insert(self.container, horizontal_group) if i < row_cnt then self:addHorizontalSep() end end -- end for each button line if Device:hasDPad() or Device:hasKeyboard() then self.layout = self.buttons_layout self.layout[1][1]:onFocus() self.key_events.SelectByKeyPress = { {{"Press", "Enter"}} } else self.key_events = {} -- deregister all key press event listeners end end function ButtonTable:addHorizontalSep() table.insert(self.container, VerticalSpan:new{ width = Screen:scaleBySize(2) }) table.insert(self.container, LineWidget:new{ background = Blitbuffer.COLOR_GREY, dimen = Geom:new{ w = self.width, h = self.sep_width, } }) table.insert(self.container, VerticalSpan:new{ width = Screen:scaleBySize(2) }) end function ButtonTable:onSelectByKeyPress() self:getFocusItem().callback() end return ButtonTable
max_width in buttontable - prevent overlong text (#3145)
max_width in buttontable - prevent overlong text (#3145) * max_width in buttontable - prevent overlong text * fix max_width
Lua
agpl-3.0
koreader/koreader,houqp/koreader,poire-z/koreader,mwoz123/koreader,lgeek/koreader,poire-z/koreader,Frenzie/koreader,Hzj-jie/koreader,mihailim/koreader,Markismus/koreader,NiLuJe/koreader,koreader/koreader,NiLuJe/koreader,Frenzie/koreader,apletnev/koreader,pazos/koreader
5a6455caf36899728b0c7fd1fc0e8c6a66af0c42
libs/uci/luasrc/model/uci/bind.lua
libs/uci/luasrc/model/uci/bind.lua
--[[ LuCI - UCI utilities for model classes Copyright 2009 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 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 assert, pairs, type = assert, pairs, type local utl = require "luci.util" module "luci.model.uci.bind" bind = utl.class() function bind.__init__(self, config, cursor) assert(config, "call to bind() without config file") self.cfg = config self.uci = cursor end function bind.init(self, cursor) assert(cursor, "call to init() without uci cursor") self.uci = cursor end function bind.section(self, stype) local x = utl.class(bsection) x.__init__ = function(inst, sid) assert(self.uci:get(self.cfg, sid) == stype, "attempt to instantiate bsection(%q) of wrong type, expected %q" % { sid, stype }) inst.bind = self inst.stype = stype inst.sid = sid end return x end function bind.usection(self, stype) local x = utl.class(bsection) x.__init__ = function(inst) inst.bind = self inst.stype = stype inst.sid = true end return x() end function bind.list(self, list, add, rem) local lookup = { } if type(list) == "string" then local item for item in list:gmatch("%S+") do lookup[item] = true end elseif type(list) == "table" then local item for _, item in pairs(list) do lookup[item] = true end end if add then lookup[add] = true end if rem then lookup[rem] = nil end return utl.keys(lookup) end function bind.bool(self, v) return ( v == "1" or v == "true" or v == "yes" or v == "on" ) end bsection = utl.class() function bsection.uciop(self, op, ...) assert(self.bind and self.bind.uci, "attempt to use unitialized binding") if op then return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...) else return self.bind.uci end end function bsection.get(self, k, c) local v if type(c) == "string" then v = self:uciop("get", c, k) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end if k ~= nil then v = s[k] else v = s end return false end) end return v end function bsection.set(self, k, v, c) local stat if type(c) == "string" then stat = self:uciop("set", c, k, v) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end stat = self:uciop("set", c, k, v) return false end) end return stat or false end function bsection.property(self, k, n) self[n or k] = function(c, val) if val == nil then return c:get(k, c.sid) else return c:set(k, val, c.sid) end end end function bsection.property_bool(self, k, n) self[n or k] = function(c, val) if val == nil then return self.bind:bool(c:get(k, c.sid)) else return c:set(k, self.bind:bool(val) and "1" or "0", c.sid) end end end
--[[ LuCI - UCI utilities for model classes Copyright 2009 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 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 assert, pairs, type = assert, pairs, type local utl = require "luci.util" module "luci.model.uci.bind" bind = utl.class() function bind.__init__(self, config, cursor) assert(config, "call to bind() without config file") self.cfg = config self.uci = cursor end function bind.init(self, cursor) assert(cursor, "call to init() without uci cursor") self.uci = cursor end function bind.section(self, stype) local x = utl.class(bsection) x.__init__ = function(inst, sid) assert(self.uci:get(self.cfg, sid) == stype, "attempt to instantiate bsection(%q) of wrong type, expected %q" % { sid, stype }) inst.bind = self inst.stype = stype inst.sid = sid end return x end function bind.usection(self, stype) local x = utl.class(bsection) x.__init__ = function(inst) inst.bind = self inst.stype = stype inst.sid = true end return x() end function bind.list(self, list, add, rem) local lookup = { } if type(list) == "string" then local item for item in list:gmatch("%S+") do lookup[item] = true end elseif type(list) == "table" then local item for _, item in pairs(list) do lookup[item] = true end end if add then lookup[add] = true end if rem then lookup[rem] = nil end return utl.keys(lookup) end function bind.bool(self, v) return ( v == "1" or v == "true" or v == "yes" or v == "on" ) end bsection = utl.class() function bsection.uciop(self, op, ...) assert(self.bind and self.bind.uci, "attempt to use unitialized binding") if op then return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...) else return self.bind.uci end end function bsection.get(self, k, c) local v if type(c) == "string" then v = self:uciop("get", c, k) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end if k ~= nil then v = s[k] else v = s end return false end) end return v end function bsection.set(self, k, v, c) local stat if type(c) == "string" then if type(v) == "table" and #v == 0 then stat = self:uciop("delete", c, k) else stat = self:uciop("set", c, k, v) end else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end stat = self:uciop("set", c, k, v) return false end) end return stat or false end function bsection.property(self, k, n) self[n or k] = function(c, val) if val == nil then return c:get(k, c.sid) else return c:set(k, val, c.sid) end end end function bsection.property_bool(self, k, n) self[n or k] = function(c, val) if val == nil then return self.bind:bool(c:get(k, c.sid)) else return c:set(k, self.bind:bool(val) and "1" or "0", c.sid) end end end
libs/uci: fix attempt to assign empty tables in uci bind class
libs/uci: fix attempt to assign empty tables in uci bind class git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5403 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
ch3n2k/luci,Canaan-Creative/luci,yeewang/openwrt-luci,vhpham80/luci,projectbismark/luci-bismark,8devices/carambola2-luci,eugenesan/openwrt-luci,jschmidlapp/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,jschmidlapp/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,zwhfly/openwrt-luci,stephank/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,Canaan-Creative/luci,saraedum/luci-packages-old,ch3n2k/luci,vhpham80/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,Flexibity/luci,yeewang/openwrt-luci,vhpham80/luci,jschmidlapp/luci,Flexibity/luci,gwlim/luci,projectbismark/luci-bismark,vhpham80/luci,eugenesan/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,gwlim/luci,vhpham80/luci,phi-psi/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,saraedum/luci-packages-old,freifunk-gluon/luci,eugenesan/openwrt-luci,Flexibity/luci,jschmidlapp/luci,stephank/luci,eugenesan/openwrt-luci,ch3n2k/luci,stephank/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,freifunk-gluon/luci,vhpham80/luci,phi-psi/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,stephank/luci,jschmidlapp/luci,jschmidlapp/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,phi-psi/luci,ch3n2k/luci,saraedum/luci-packages-old,gwlim/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,Flexibity/luci,gwlim/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,stephank/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,freifunk-gluon/luci,freifunk-gluon/luci,freifunk-gluon/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,ch3n2k/luci,gwlim/luci,ch3n2k/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Flexibity/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,stephank/luci,gwlim/luci
21e9264e6e7cd80b2baaab86aadde55f7dd7c50f
build/scripts/LLVM.lua
build/scripts/LLVM.lua
require "Build" require "Utils" require "../Helpers" local llvm = basedir .. "/../deps/llvm" -- If we are inside vagrant then clone and build LLVM outside the shared folder, -- otherwise file I/O performance will be terrible. if is_vagrant() then llvm = "~/llvm" end local llvm_build = llvm .. "/" .. os.get() function get_llvm_rev() return cat(basedir .. "/LLVM-commit") end function get_clang_rev() return cat(basedir .. "/Clang-commit") end function clone_llvm() local llvm_release = get_llvm_rev() print("LLVM release: " .. llvm_release) local clang_release = get_clang_rev() print("Clang release: " .. clang_release) if os.isdir(llvm) and not os.isdir(llvm .. "/.git") then error("LLVM directory is not a git repository.") end if not os.isdir(llvm) then git.clone(llvm, "http://llvm.org/git/llvm.git") else git.reset_hard(llvm, "HEAD") git.pull_rebase(llvm) end local clang = llvm .. "/tools/clang" if not os.isdir(clang) then git.clone(clang, "http://llvm.org/git/clang.git") else git.reset_hard(clang, "HEAD") git.pull_rebase(clang) end git.reset_hard(llvm, llvm_release) git.reset_hard(clang, clang_release) end function get_llvm_package_name(rev, conf) if not rev then rev = get_llvm_rev() end if not conf then conf = get_llvm_configuration_name() end rev = string.sub(rev, 0, 6) return table.concat({"llvm", rev, os.get(), conf}, "-") end function get_llvm_configuration_name() return os.is("windows") and "RelWithDebInfo" or "Release" end function extract_7z(archive, dest_dir) return execute(string.format("7z x %s -o%s -y", archive, dest_dir), true) end function download_llvm() local base = "https://dl.dropboxusercontent.com/u/194502/CppSharp/llvm/" local pkg_name = get_llvm_package_name() local archive = pkg_name .. ".7z" -- check if we already have the file downloaded if not os.isfile(archive) then download(base .. archive, archive) end -- extract the package if not os.isdir(pkg_name) then extract_7z(archive, pkg_name) end end function cmake(gen, conf, options) local cwd = os.getcwd() os.chdir(llvm_build) local cmd = "cmake -G " .. '"' .. gen .. '"' .. ' -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false' .. ' -DCLANG_ENABLE_ARCMT=false -DCLANG_ENABLE_REWRITER=false -DCLANG_ENABLE_STATIC_ANALYZER=false' .. ' -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false' .. ' -DLLVM_TARGETS_TO_BUILD="X86"' .. ' -DCMAKE_BUILD_TYPE=' .. conf .. ' ..' .. ' ' .. options execute(cmd) os.chdir(cwd) end function clean_llvm(llvm_build) if os.isdir(llvm_build) then os.rmdir(llvm_build) end os.mkdir(llvm_build) end function build_llvm(llvm_build) local conf = get_llvm_configuration_name() local use_msbuild = false if os.is("windows") and use_msbuild then cmake("Visual Studio 12 2013", conf) local llvm_sln = path.join(llvm_build, "LLVM.sln") msbuild(llvm_sln, conf) else local options = os.is("macosx") and "-DLLVM_ENABLE_LIBCXX=true -DLLVM_BUILD_32_BITS=true" or "" cmake("Ninja", conf, options) ninja(llvm_build) ninja(llvm_build, "clang-headers") end end function package_llvm(conf, llvm, llvm_build) local rev = git.rev_parse(llvm, "HEAD") if string.is_empty(rev) then rev = get_llvm_rev() end local out = get_llvm_package_name(rev, conf) if os.isdir(out) then os.rmdir(out) end os.mkdir(out) os.copydir(llvm .. "/include", out .. "/include") os.copydir(llvm_build .. "/include", out .. "/build/include") local llvm_msbuild_libdir = "/" .. conf .. "/lib" local lib_dir = os.is("windows") and os.isdir(llvm_msbuild_libdir) and llvm_msbuild_libdir or "/lib" local llvm_build_libdir = llvm_build .. lib_dir if os.is("windows") and os.isdir(llvm_build_libdir) then os.copydir(llvm_build_libdir, out .. "/build" .. lib_dir, "*.lib") else os.copydir(llvm_build_libdir, out .. "/build/lib", "*.a") end os.copydir(llvm .. "/tools/clang/include", out .. "/tools/clang/include") os.copydir(llvm_build .. "/tools/clang/include", out .. "/build/tools/clang/include") os.copydir(llvm .. "/tools/clang/lib/CodeGen", out .. "/tools/clang/lib/CodeGen", "*.h") os.copydir(llvm .. "/tools/clang/lib/Driver", out .. "/tools/clang/lib/Driver", "*.h") local out_lib_dir = out .. "/build" .. lib_dir if os.is("windows") then os.rmfiles(out_lib_dir, "LLVM*ObjCARCOpts*.lib") os.rmfiles(out_lib_dir, "clang*ARC*.lib") os.rmfiles(out_lib_dir, "clang*Matchers*.lib") os.rmfiles(out_lib_dir, "clang*Rewrite*.lib") os.rmfiles(out_lib_dir, "clang*StaticAnalyzer*.lib") os.rmfiles(out_lib_dir, "clang*Tooling*.lib") else os.rmfiles(out_lib_dir, "libllvm*ObjCARCOpts*.a") os.rmfiles(out_lib_dir, "libclang*ARC*.a") os.rmfiles(out_lib_dir, "libclang*Matchers*.a") os.rmfiles(out_lib_dir, "libclang*Rewrite*.a") os.rmfiles(out_lib_dir, "libclang*StaticAnalyzer*.a") os.rmfiles(out_lib_dir, "libclang*Tooling*.a") end return out end function archive_llvm(dir) execute("7z a " .. dir .. ".7z " .. "./" .. dir .. "/*") end if _ACTION == "clone_llvm" then clone_llvm() os.exit() end if _ACTION == "build_llvm" then clean_llvm(llvm_build) build_llvm(llvm_build) os.exit() end if _ACTION == "package_llvm" then local conf = get_llvm_configuration_name() local pkg = package_llvm(conf, llvm, llvm_build) archive_llvm(pkg) os.exit() end if _ACTION == "download_llvm" then download_llvm() os.exit() end
require "Build" require "Utils" require "../Helpers" local llvm = basedir .. "/../deps/llvm" -- If we are inside vagrant then clone and build LLVM outside the shared folder, -- otherwise file I/O performance will be terrible. if is_vagrant() then llvm = "~/llvm" end local llvm_build = llvm .. "/" .. os.get() function get_llvm_rev() return cat(basedir .. "/LLVM-commit") end function get_clang_rev() return cat(basedir .. "/Clang-commit") end function clone_llvm() local llvm_release = get_llvm_rev() print("LLVM release: " .. llvm_release) local clang_release = get_clang_rev() print("Clang release: " .. clang_release) if os.isdir(llvm) and not os.isdir(llvm .. "/.git") then error("LLVM directory is not a git repository.") end if not os.isdir(llvm) then git.clone(llvm, "http://llvm.org/git/llvm.git") else git.reset_hard(llvm, "HEAD") git.pull_rebase(llvm) end local clang = llvm .. "/tools/clang" if not os.isdir(clang) then git.clone(clang, "http://llvm.org/git/clang.git") else git.reset_hard(clang, "HEAD") git.pull_rebase(clang) end git.reset_hard(llvm, llvm_release) git.reset_hard(clang, clang_release) end function get_llvm_package_name(rev, conf) if not rev then rev = get_llvm_rev() end if not conf then conf = get_llvm_configuration_name() end rev = string.sub(rev, 0, 6) return table.concat({"llvm", rev, os.get(), conf}, "-") end function get_llvm_configuration_name() return os.is("windows") and "RelWithDebInfo" or "Release" end function extract_7z(archive, dest_dir) return execute(string.format("7z x %s -o%s -y", archive, dest_dir), true) end function download_llvm() local base = "https://dl.dropboxusercontent.com/u/194502/CppSharp/llvm/" local pkg_name = get_llvm_package_name() local archive = pkg_name .. ".7z" -- check if we already have the file downloaded if not os.isfile(archive) then download(base .. archive, archive) end -- extract the package if not os.isdir(pkg_name) then extract_7z(archive, pkg_name) end end function cmake(gen, conf, options) local cwd = os.getcwd() os.chdir(llvm_build) local cmd = "cmake -G " .. '"' .. gen .. '"' .. ' -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false' .. ' -DCLANG_ENABLE_ARCMT=false -DCLANG_ENABLE_REWRITER=false -DCLANG_ENABLE_STATIC_ANALYZER=false' .. ' -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false' .. ' -DLLVM_TARGETS_TO_BUILD="X86"' .. ' -DCMAKE_BUILD_TYPE=' .. conf .. ' ..' .. ' ' .. options execute(cmd) os.chdir(cwd) end function clean_llvm(llvm_build) if os.isdir(llvm_build) then os.rmdir(llvm_build) end os.mkdir(llvm_build) end function build_llvm(llvm_build) local conf = get_llvm_configuration_name() local use_msbuild = false if os.is("windows") and use_msbuild then cmake("Visual Studio 12 2013", conf) local llvm_sln = path.join(llvm_build, "LLVM.sln") msbuild(llvm_sln, conf) else local options = os.is("macosx") and "-DLLVM_ENABLE_LIBCXX=true -DLLVM_BUILD_32_BITS=true" or "" cmake("Ninja", conf, options) ninja(llvm_build) ninja(llvm_build, "clang-headers") end end function package_llvm(conf, llvm, llvm_build) local rev = git.rev_parse(llvm, "HEAD") if string.is_empty(rev) then rev = get_llvm_rev() end local out = get_llvm_package_name(rev, conf) if os.isdir(out) then os.rmdir(out) end os.mkdir(out) os.copydir(llvm .. "/include", out .. "/include") os.copydir(llvm_build .. "/include", out .. "/build/include") local llvm_msbuild_libdir = "/" .. conf .. "/lib" local lib_dir = os.is("windows") and os.isdir(llvm_msbuild_libdir) and llvm_msbuild_libdir or "/lib" local llvm_build_libdir = llvm_build .. lib_dir if os.is("windows") and os.isdir(llvm_build_libdir) then os.copydir(llvm_build_libdir, out .. "/build" .. lib_dir, "*.lib") else os.copydir(llvm_build_libdir, out .. "/build/lib", "*.a") end os.copydir(llvm .. "/tools/clang/include", out .. "/tools/clang/include") os.copydir(llvm_build .. "/tools/clang/include", out .. "/build/tools/clang/include") os.copydir(llvm .. "/tools/clang/lib/CodeGen", out .. "/tools/clang/lib/CodeGen", "*.h") os.copydir(llvm .. "/tools/clang/lib/Driver", out .. "/tools/clang/lib/Driver", "*.h") local out_lib_dir = out .. "/build" .. lib_dir if os.is("windows") then os.rmfiles(out_lib_dir, "LLVM*ObjCARCOpts*.lib") os.rmfiles(out_lib_dir, "clang*ARC*.lib") os.rmfiles(out_lib_dir, "clang*Matchers*.lib") os.rmfiles(out_lib_dir, "clang*Rewrite*.lib") os.rmfiles(out_lib_dir, "clang*StaticAnalyzer*.lib") os.rmfiles(out_lib_dir, "clang*Tooling*.lib") else os.rmfiles(out_lib_dir, "libllvm*ObjCARCOpts*.a") os.rmfiles(out_lib_dir, "libclang*ARC*.a") os.rmfiles(out_lib_dir, "libclang*Matchers*.a") os.rmfiles(out_lib_dir, "libclang*Rewrite*.a") os.rmfiles(out_lib_dir, "libclang*StaticAnalyzer*.a") os.rmfiles(out_lib_dir, "libclang*Tooling*.a") end return out end function archive_llvm(dir) local archive = dir .. ".7z" if os.isfile(archive) then os.remove(archive) end local cwd = os.getcwd() os.chdir(dir) execute("7z a " .. path.join("..", archive) .. " *") os.chdir(cwd) end if _ACTION == "clone_llvm" then clone_llvm() os.exit() end if _ACTION == "build_llvm" then clean_llvm(llvm_build) build_llvm(llvm_build) os.exit() end if _ACTION == "package_llvm" then local conf = get_llvm_configuration_name() local pkg = package_llvm(conf, llvm, llvm_build) archive_llvm(pkg) os.exit() end if _ACTION == "download_llvm" then download_llvm() os.exit() end
Fixed LLVM archive packaging scripts.
Fixed LLVM archive packaging scripts.
Lua
mit
inordertotest/CppSharp,u255436/CppSharp,u255436/CppSharp,genuinelucifer/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,mono/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,mono/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,mono/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,mono/CppSharp,mono/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp
99668c7e1a701eef6f420e4086ff7e6116fc6cc8
IOHandler.lua
IOHandler.lua
--[[ * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * ]]-- require 'torch' require 'env' local zmq = require 'lzmq' local zloop = require 'lzmq.loop' local zassert = zmq.assert local json=require 'cjson' local uuid = require 'uuid' local ffi = require'ffi' local util = require 'itorch.util' local context = zmq.context() local tablex = require 'pl.tablex' local kvstore = {} -- this stores exclusive key-values passed in by main.lua ------------------------------------------ -- load and decode json config local ipyfile = assert(io.open(arg[1], "rb"), "Could not open iPython config") local ipyjson = ipyfile:read("*all") ipyfile:close() local ipycfg = json.decode(ipyjson) -------------------------------------------------------------- --- The libc functions used by this process (for non-blocking IO) ffi.cdef[[ int open(const char* pathname, int flags); int close(int fd); int read(int fd, void* buf, size_t count); ]] local O_NONBLOCK = 0x0004 local chunk_size = 4096 local buffer = ffi.new('uint8_t[?]',chunk_size) local io_stdo = ffi.C.open(arg[2], O_NONBLOCK) local ip = ipycfg.transport .. '://' .. ipycfg.ip .. ':' local heartbeat, err = context:socket{zmq.REP, bind = ip .. ipycfg.hb_port} zassert(heartbeat, err) local iopub, err = context:socket{zmq.PUB, bind = ip .. ipycfg.iopub_port} zassert(iopub, err) ------------------------------------------------------------------------------ local rawpub_port=0 do -- wait till the main process writes the port, and the use it while rawpub_port == 0 do local portnum_f = torch.DiskFile(arg[3],'r') portnum_f:quiet() rawpub_port = portnum_f:readInt() if portnum_f:hasError() then rawpub_port = 0 end portnum_f:close() end end local rawpub, err = context:socket{zmq.PAIR, connect = ip .. rawpub_port} zassert(rawpub, err) ------------------------------------------------------------------------------ local function handleHeartbeat(sock) local m = zassert(sock:recv_all()); zassert(sock:send_all(m)) end function handleSTDO(ev) local nbytes = ffi.C.read(io_stdo,buffer,chunk_size) if nbytes > 0 then local output = ffi.string(buffer, nbytes) if kvstore.current_msg then local o = {} o.uuid = kvstore.current_msg.uuid o.parent_header = kvstore.current_msg.header o.header = tablex.deepcopy(kvstore.current_msg.header) o.header.msg_id = uuid.new() o.header.msg_type = 'pyout' o.header.version = "4.0" o.content = { data = {}, metadata = {}, execution_count = kvstore.exec_count } o.content.data['text/plain'] = output util.ipyEncodeAndSend(iopub, o) else print(output) end end ev:set_interval(1) end function handleRawPub(sock) local m = zassert(sock:recv_all()) -- if this message is a key-value from main.lua if m[1] == 'private_msg' then if m[2] == 'current_msg' then kvstore[m[2]] = json.decode(m[3]) elseif m[2] == 'exec_count' then kvstore[m[2]] = tonumber(m[3]) elseif m[2] == 'shutdown' then sock:send('ACK') loop:stop() iopub:close() rawpub:close() heartbeat:close() ffi.C.close(io_stdo) os.execute('rm -f ' .. arg[2]) -- cleanup files os.execute('rm -f ' .. arg[3]) print('Shutting down iTorch') os.exit() end sock:send('ACK') return end -- else, just pass it over to iopub zassert(iopub:send_all(m)) end local function handleIOPub(sock) print('Error: IOPub is a Publisher, it cant have incoming requests') end loop = zloop.new(1, context) loop:add_socket(heartbeat, handleHeartbeat) loop:add_socket(rawpub, handleRawPub) loop:add_socket(iopub, handleIOPub) loop:add_interval(1, handleSTDO) loop:start()
--[[ * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * ]]-- require 'torch' require 'env' local zmq = require 'lzmq' local zloop = require 'lzmq.loop' local zassert = zmq.assert local json=require 'cjson' local uuid = require 'uuid' local ffi = require'ffi' local util = require 'itorch.util' local context = zmq.context() local tablex = require 'pl.tablex' local kvstore = {} -- this stores exclusive key-values passed in by main.lua ------------------------------------------ -- load and decode json config local ipyfile = assert(io.open(arg[1], "rb"), "Could not open iPython config") local ipyjson = ipyfile:read("*all") ipyfile:close() local ipycfg = json.decode(ipyjson) -------------------------------------------------------------- --- The libc functions used by this process (for non-blocking IO) ffi.cdef[[ int open(const char* pathname, int flags); int close(int fd); int read(int fd, void* buf, size_t count); ]] local O_NONBLOCK = 0x0004 local chunk_size = 4096 local buffer = ffi.new('uint8_t[?]',chunk_size) local io_stdo = ffi.C.open(arg[2], O_NONBLOCK) local ip = ipycfg.transport .. '://' .. ipycfg.ip .. ':' local heartbeat, err = context:socket{zmq.REP, bind = ip .. ipycfg.hb_port} zassert(heartbeat, err) local iopub, err = context:socket{zmq.PUB, bind = ip .. ipycfg.iopub_port} zassert(iopub, err) ------------------------------------------------------------------------------ local rawpub_port=0 do -- wait till the main process writes the port, and the use it while rawpub_port == 0 do local portnum_f = torch.DiskFile(arg[3],'r') portnum_f:quiet() rawpub_port = portnum_f:readInt() if portnum_f:hasError() then rawpub_port = 0 end portnum_f:close() end end local rawpub, err = context:socket{zmq.PAIR, connect = ip .. rawpub_port} zassert(rawpub, err) ------------------------------------------------------------------------------ local function handleHeartbeat(sock) local m = zassert(sock:recv_all()); zassert(sock:send_all(m)) end function handleSTDO(ev) local nbytes = ffi.C.read(io_stdo,buffer,chunk_size) if nbytes > 0 then local output = ffi.string(buffer, nbytes) if kvstore.current_msg then local o = util.msg('pyout', kvstore.current_msg) o.content = { data = {}, metadata = {}, execution_count = kvstore.exec_count } o.content.data['text/plain'] = output util.ipyEncodeAndSend(iopub, o) else print(output) end end ev:set_interval(1) end function handleRawPub(sock) local m = zassert(sock:recv_all()) -- if this message is a key-value from main.lua if m[1] == 'private_msg' then if m[2] == 'current_msg' then kvstore[m[2]] = json.decode(m[3]) elseif m[2] == 'exec_count' then kvstore[m[2]] = tonumber(m[3]) elseif m[2] == 'shutdown' then sock:send('ACK') loop:stop() iopub:close() rawpub:close() heartbeat:close() ffi.C.close(io_stdo) os.execute('rm -f ' .. arg[2]) -- cleanup files os.execute('rm -f ' .. arg[3]) print('Shutting down iTorch') os.exit() end sock:send('ACK') return end -- else, just pass it over to iopub zassert(iopub:send_all(m)) end local function handleIOPub(sock) print('Error: IOPub is a Publisher, it cant have incoming requests') end loop = zloop.new(1, context) loop:add_socket(heartbeat, handleHeartbeat) loop:add_socket(rawpub, handleRawPub) loop:add_socket(iopub, handleIOPub) loop:add_interval(1, handleSTDO) loop:start()
Refactor to use util.msg per @minrk comment
Refactor to use util.msg per @minrk comment Fix indentation
Lua
bsd-3-clause
facebook/iTorch,michaf/iTorch,facebook/iTorch,michaf/iTorch,Laeeth/dbokeh_torch,Laeeth/dbokeh_torch
a197f31da7577ce215f46f036d61c7137cf7499f
reader.lua
reader.lua
#!./luajit require "defaults" pcall(dofile, "defaults.persistent.lua") package.path = "?.lua;common/?.lua;frontend/?.lua" package.cpath = "?.so;common/?.so;common/?.dll;/usr/lib/lua/?.so" local ffi = require("ffi") if ffi.os == "Windows" then ffi.cdef[[ int _putenv(const char *envvar); ]] ffi.C._putenv("PATH=libs;common;") --ffi.C._putenv("EMULATE_READER_W=480") --ffi.C._putenv("EMULATE_READER_H=600") end local DocSettings = require("docsettings") local _ = require("gettext") local util = require("ffi/util") -- read settings and check for language override -- has to be done before requiring other files because -- they might call gettext on load G_reader_settings = DocSettings:open(".reader") local lang_locale = G_reader_settings:readSetting("language") if lang_locale then _.changeLang(lang_locale) end local lfs = require("libs/libkoreader-lfs") local UIManager = require("ui/uimanager") local Device = require("ui/device") local Screen = require("ui/screen") local input = require("ffi/input") local DEBUG = require("dbg") local Profiler = nil local function exitReader() local KindlePowerD = require("ui/device/kindlepowerd") local ReaderActivityIndicator = require("apps/reader/modules/readeractivityindicator") G_reader_settings:close() -- Close lipc handles KindlePowerD:coda() ReaderActivityIndicator:coda() if not util.isEmulated() then if Device:isKindle3() or (Device:getModel() == "KindleDXG") then -- send double menu key press events to trigger screen refresh os.execute("echo 'send 139' > /proc/keypad;echo 'send 139' > /proc/keypad") end if Device:isTouchDevice() and Device.survive_screen_saver then -- If needed, hack the swipe to unlock screen if Device:isSpecialOffers() then local dev = Device:getTouchInputDev() if dev then local width, height = Screen:getWidth(), Screen:getHeight() input.fakeTapInput(dev, math.min(width, height)/2, math.max(width, height)-30 ) end end end end input.closeAll() Screen:close() if Profiler then Profiler.stop() end os.exit(0) end -- option parsing: local longopts = { debug = "d", profile = "p", help = "h", } local function showusage() print("usage: ./reader.lua [OPTION] ... path") print("Read all the books on your E-Ink reader") print("") print("-d start in debug mode") print("-p enable Lua code profiling") print("-h show this usage help") print("") print("If you give the name of a directory instead of a file path, a file") print("chooser will show up and let you select a file") print("") print("If you don't pass any path, the last viewed document will be opened") print("") print("This software is licensed under the AGPLv3.") print("See http://github.com/koreader/koreader for more info.") return end local ARGV = arg local argidx = 1 while argidx <= #ARGV do local arg = ARGV[argidx] argidx = argidx + 1 if arg == "--" then break end -- parse longopts if arg:sub(1,2) == "--" then local opt = longopts[arg:sub(3)] if opt ~= nil then arg = "-"..opt end end -- code for each option if arg == "-h" then return showusage() elseif arg == "-d" then DEBUG:turnOn() elseif arg == "-p" then Profiler = require("jit.p") Profiler.start("la") else -- not a recognized option, should be a filename argidx = argidx - 1 break end end -- read some global reader setting here: -- font local fontmap = G_reader_settings:readSetting("fontmap") if fontmap ~= nil then Font.fontmap = fontmap end -- last file local last_file = G_reader_settings:readSetting("lastfile") -- load last opened file local open_last = G_reader_settings:readSetting("open_last") -- night mode if G_reader_settings:readSetting("night_mode") then Screen.bb:invert() end -- restore kobo frontlight settings if Device:isKobo() then local powerd = Device:getPowerDevice() if powerd and powerd.restore_settings then local intensity = G_reader_settings:readSetting("frontlight_intensity") intensity = intensity or powerd.flIntensity powerd:setIntensityWithoutHW(intensity) -- powerd:setIntensity(intensity) end end if ARGV[argidx] and ARGV[argidx] ~= "" then local file = nil if lfs.attributes(ARGV[argidx], "mode") == "file" then file = ARGV[argidx] elseif open_last and last_file then file = last_file end -- if file is given in command line argument or open last document is set true -- the given file or the last file is opened in the reader if file then local ReaderUI = require("apps/reader/readerui") ReaderUI:showReader(file) -- we assume a directory is given in command line argument -- the filemanger will show the files in that path else local FileManager = require("apps/filemanager/filemanager") FileManager:showFiles(ARGV[argidx]) end UIManager:run() elseif last_file then local ReaderUI = require("apps/reader/readerui") ReaderUI:showReader(last_file) UIManager:run() else return showusage() end exitReader()
#!./luajit require "defaults" pcall(dofile, "defaults.persistent.lua") package.path = "?.lua;common/?.lua;frontend/?.lua" package.cpath = "?.so;common/?.so;common/?.dll;/usr/lib/lua/?.so" local ffi = require("ffi") if ffi.os == "Windows" then ffi.cdef[[ int _putenv(const char *envvar); ]] ffi.C._putenv("PATH=libs;common;") --ffi.C._putenv("EMULATE_READER_W=480") --ffi.C._putenv("EMULATE_READER_H=600") end local DocSettings = require("docsettings") local _ = require("gettext") local util = require("ffi/util") -- read settings and check for language override -- has to be done before requiring other files because -- they might call gettext on load G_reader_settings = DocSettings:open(".reader") local lang_locale = G_reader_settings:readSetting("language") if lang_locale then _.changeLang(lang_locale) end local lfs = require("libs/libkoreader-lfs") local UIManager = require("ui/uimanager") local Device = require("ui/device") local Screen = require("ui/screen") local input = require("ffi/input") local DEBUG = require("dbg") local Profiler = nil local function exitReader() local KindlePowerD = require("ui/device/kindlepowerd") local ReaderActivityIndicator = require("apps/reader/modules/readeractivityindicator") G_reader_settings:close() -- Close lipc handles KindlePowerD:coda() ReaderActivityIndicator:coda() if not util.isEmulated() then if Device:isKindle3() or (Device:getModel() == "KindleDXG") then -- send double menu key press events to trigger screen refresh os.execute("echo 'send 139' > /proc/keypad;echo 'send 139' > /proc/keypad") end if Device:isTouchDevice() and Device.survive_screen_saver then -- If needed, hack the swipe to unlock screen if Device:isSpecialOffers() then local dev = Device:getTouchInputDev() if dev then local width, height = Screen:getWidth(), Screen:getHeight() input.fakeTapInput(dev, math.min(width, height)/2, math.max(width, height)-30 ) end end end end input.closeAll() Screen:close() if Profiler then Profiler.stop() end os.exit(0) end -- option parsing: local longopts = { debug = "d", profile = "p", help = "h", } local function showusage() print("usage: ./reader.lua [OPTION] ... path") print("Read all the books on your E-Ink reader") print("") print("-d start in debug mode") print("-p enable Lua code profiling") print("-h show this usage help") print("") print("If you give the name of a directory instead of a file path, a file") print("chooser will show up and let you select a file") print("") print("If you don't pass any path, the last viewed document will be opened") print("") print("This software is licensed under the AGPLv3.") print("See http://github.com/koreader/koreader for more info.") return end local ARGV = arg local argidx = 1 while argidx <= #ARGV do local arg = ARGV[argidx] argidx = argidx + 1 if arg == "--" then break end -- parse longopts if arg:sub(1,2) == "--" then local opt = longopts[arg:sub(3)] if opt ~= nil then arg = "-"..opt end end -- code for each option if arg == "-h" then return showusage() elseif arg == "-d" then DEBUG:turnOn() elseif arg == "-p" then Profiler = require("jit.p") Profiler.start("la") else -- not a recognized option, should be a filename argidx = argidx - 1 break end end -- read some global reader setting here: -- font local fontmap = G_reader_settings:readSetting("fontmap") if fontmap ~= nil then Font.fontmap = fontmap end -- last file local last_file = G_reader_settings:readSetting("lastfile") if last_file and lfs.attributes(last_file, "mode") ~= "file" then last_file = nil end -- load last opened file local open_last = G_reader_settings:readSetting("open_last") -- night mode if G_reader_settings:readSetting("night_mode") then Screen.bb:invert() end -- restore kobo frontlight settings if Device:isKobo() then local powerd = Device:getPowerDevice() if powerd and powerd.restore_settings then local intensity = G_reader_settings:readSetting("frontlight_intensity") intensity = intensity or powerd.flIntensity powerd:setIntensityWithoutHW(intensity) -- powerd:setIntensity(intensity) end end if ARGV[argidx] and ARGV[argidx] ~= "" then local file = nil if lfs.attributes(ARGV[argidx], "mode") == "file" then file = ARGV[argidx] elseif open_last and last_file then file = last_file end -- if file is given in command line argument or open last document is set true -- the given file or the last file is opened in the reader if file then local ReaderUI = require("apps/reader/readerui") ReaderUI:showReader(file) -- we assume a directory is given in command line argument -- the filemanger will show the files in that path else local FileManager = require("apps/filemanager/filemanager") FileManager:showFiles(ARGV[argidx]) end UIManager:run() elseif last_file then local ReaderUI = require("apps/reader/readerui") ReaderUI:showReader(last_file) UIManager:run() else return showusage() end exitReader()
check if last opened file exists before opening it This should fix #916.
check if last opened file exists before opening it This should fix #916.
Lua
agpl-3.0
chihyang/koreader,ashhher3/koreader,Markismus/koreader,NickSavage/koreader,Frenzie/koreader,chrox/koreader,ashang/koreader,frankyifei/koreader,noname007/koreader,mihailim/koreader,koreader/koreader,poire-z/koreader,NiLuJe/koreader,robert00s/koreader,mwoz123/koreader,houqp/koreader,Frenzie/koreader,pazos/koreader,poire-z/koreader,apletnev/koreader,koreader/koreader,NiLuJe/koreader,Hzj-jie/koreader,lgeek/koreader
b6ca66894fe497d9fa6a5ec5bc44e5a519ef0897
src/luacheck/utils.lua
src/luacheck/utils.lua
local utils = {} utils.dir_sep = package.config:sub(1,1) utils.is_windows = utils.dir_sep == "\\" local bom = "\239\187\191" -- Returns all contents of file (path or file handler) or nil. function utils.read_file(file) local handler if type(file) == "string" then handler = io.open(file, "rb") if not handler then return nil end else handler = file end local res = handler:read("*a") handler:close() if res and res:sub(1, #bom) == bom then res = res:sub(#bom + 1) end return res end -- luacheck: push -- luacheck: compat if _VERSION:find "5.1" then -- Loads Lua source string in an environment, returns function or nil, error. function utils.load(src, env, chunkname) local func, err = loadstring(src, chunkname) if func then if env then setfenv(func, env) end return func else return nil, err end end else -- Loads Lua source string in an environment, returns function or nil, error. function utils.load(src, env, chunkname) return load(src, chunkname, "t", env or _ENV) end end -- luacheck: pop -- Loads config containing assignments to global variables from path. -- Returns config table and return value of config or nil and error message -- ("I/O" or "syntax" or "runtime"). function utils.load_config(path, env) env = env or {} local src = utils.read_file(path) if not src then return nil, "I/O" end local func = utils.load(src, env) if not func then return nil, "syntax" end local ok, res = pcall(func) if not ok then return nil, "runtime" end return env, res end function utils.array_to_set(array) local set = {} for index, value in ipairs(array) do set[value] = index end return set end function utils.concat_arrays(array) local res = {} for _, subarray in ipairs(array) do for _, item in ipairs(subarray) do table.insert(res, item) end end return res end function utils.update(t1, t2) for k, v in pairs(t2) do t1[k] = v end return t1 end local class_metatable = {} function class_metatable.__call(class, ...) local obj = setmetatable({}, class) if class.__init then class.__init(obj, ...) end return obj end function utils.class() local class = setmetatable({}, class_metatable) class.__index = class return class end utils.Stack = utils.class() function utils.Stack:__init() self.size = 0 end function utils.Stack:push(value) self.size = self.size + 1 self[self.size] = value self.top = value end function utils.Stack:pop() local value = self[self.size] self[self.size] = nil self.size = self.size - 1 self.top = self[self.size] return value end local function error_handler(err) return { err = err, traceback = debug.traceback() } end -- Calls f with arg, returns what it does. -- If f throws a table, returns nil, the table. -- If f throws not a table, rethrows. function utils.pcall(f, arg) local function task() return f(arg) end local ok, res = xpcall(task, error_handler) if ok then return res elseif type(res.err) == "table" then return nil, res.err else error(tostring(res.err) .. "\n" .. res.traceback, 0) end end local function ripairs_iterator(array, i) if i == 1 then return nil else i = i - 1 return i, array[i] end end function utils.ripairs(array) return ripairs_iterator, array, #array + 1 end function utils.after(str, pattern) local _, last_matched_index = str:find(pattern) if last_matched_index then return str:sub(last_matched_index + 1) end end function utils.strip(str) local _, last_start_space = str:find("^%s*") local first_end_space = str:find("%s*$") return str:sub(last_start_space + 1, first_end_space - 1) end -- `sep` must be nil or a single character. Behaves like python's `str.split`. function utils.split(str, sep) local parts = {} local pattern if sep then pattern = sep .. "([^" .. sep .. "]*)" str = sep .. str else pattern = "%S+" end for part in str:gmatch(pattern) do table.insert(parts, part) end return parts end -- Maps func over array. function utils.map(func, array) local res = {} for i, item in ipairs(array) do res[i] = func(item) end return res end -- Returns predicate checking type. function utils.has_type(type_) return function(x) return type(x) == type_ end end -- Returns predicate checking that value is an array with -- elements of type. function utils.array_of(type_) return function(x) if type(x) ~= "table" then return false end for _, item in ipairs(x) do if type(item) ~= type_ then return false end end return true end end -- Returns predicate chacking if value satisfies on of predicates. function utils.either(pred1, pred2) return function(x) return pred1(x) or pred2(x) end end return utils
local utils = {} utils.dir_sep = package.config:sub(1,1) utils.is_windows = utils.dir_sep == "\\" local bom = "\239\187\191" -- Returns all contents of file (path or file handler) or nil. function utils.read_file(file) local handler if type(file) == "string" then handler = io.open(file, "rb") if not handler then return nil end else handler = file end local res = handler:read("*a") handler:close() -- Use :len() instead of # operator because in some environments -- string library is patched to handle UTF. if res and res:sub(1, bom:len()) == bom then res = res:sub(bom:len() + 1) end return res end -- luacheck: push -- luacheck: compat if _VERSION:find "5.1" then -- Loads Lua source string in an environment, returns function or nil, error. function utils.load(src, env, chunkname) local func, err = loadstring(src, chunkname) if func then if env then setfenv(func, env) end return func else return nil, err end end else -- Loads Lua source string in an environment, returns function or nil, error. function utils.load(src, env, chunkname) return load(src, chunkname, "t", env or _ENV) end end -- luacheck: pop -- Loads config containing assignments to global variables from path. -- Returns config table and return value of config or nil and error message -- ("I/O" or "syntax" or "runtime"). function utils.load_config(path, env) env = env or {} local src = utils.read_file(path) if not src then return nil, "I/O" end local func = utils.load(src, env) if not func then return nil, "syntax" end local ok, res = pcall(func) if not ok then return nil, "runtime" end return env, res end function utils.array_to_set(array) local set = {} for index, value in ipairs(array) do set[value] = index end return set end function utils.concat_arrays(array) local res = {} for _, subarray in ipairs(array) do for _, item in ipairs(subarray) do table.insert(res, item) end end return res end function utils.update(t1, t2) for k, v in pairs(t2) do t1[k] = v end return t1 end local class_metatable = {} function class_metatable.__call(class, ...) local obj = setmetatable({}, class) if class.__init then class.__init(obj, ...) end return obj end function utils.class() local class = setmetatable({}, class_metatable) class.__index = class return class end utils.Stack = utils.class() function utils.Stack:__init() self.size = 0 end function utils.Stack:push(value) self.size = self.size + 1 self[self.size] = value self.top = value end function utils.Stack:pop() local value = self[self.size] self[self.size] = nil self.size = self.size - 1 self.top = self[self.size] return value end local function error_handler(err) return { err = err, traceback = debug.traceback() } end -- Calls f with arg, returns what it does. -- If f throws a table, returns nil, the table. -- If f throws not a table, rethrows. function utils.pcall(f, arg) local function task() return f(arg) end local ok, res = xpcall(task, error_handler) if ok then return res elseif type(res.err) == "table" then return nil, res.err else error(tostring(res.err) .. "\n" .. res.traceback, 0) end end local function ripairs_iterator(array, i) if i == 1 then return nil else i = i - 1 return i, array[i] end end function utils.ripairs(array) return ripairs_iterator, array, #array + 1 end function utils.after(str, pattern) local _, last_matched_index = str:find(pattern) if last_matched_index then return str:sub(last_matched_index + 1) end end function utils.strip(str) local _, last_start_space = str:find("^%s*") local first_end_space = str:find("%s*$") return str:sub(last_start_space + 1, first_end_space - 1) end -- `sep` must be nil or a single character. Behaves like python's `str.split`. function utils.split(str, sep) local parts = {} local pattern if sep then pattern = sep .. "([^" .. sep .. "]*)" str = sep .. str else pattern = "%S+" end for part in str:gmatch(pattern) do table.insert(parts, part) end return parts end -- Maps func over array. function utils.map(func, array) local res = {} for i, item in ipairs(array) do res[i] = func(item) end return res end -- Returns predicate checking type. function utils.has_type(type_) return function(x) return type(x) == type_ end end -- Returns predicate checking that value is an array with -- elements of type. function utils.array_of(type_) return function(x) if type(x) ~= "table" then return false end for _, item in ipairs(x) do if type(item) ~= type_ then return false end end return true end end -- Returns predicate chacking if value satisfies on of predicates. function utils.either(pred1, pred2) return function(x) return pred1(x) or pred2(x) end end return utils
Fix BOM stripping in UTF-aware environments
Fix BOM stripping in UTF-aware environments
Lua
mit
linuxmaniac/luacheck,mpeterv/luacheck,adan830/luacheck,xpol/luacheck,kidaa/luacheck,xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,tst2005/luacheck,kidaa/luacheck,linuxmaniac/luacheck,adan830/luacheck,tst2005/luacheck,xpol/luacheck
989e319af90f07e9094e9e625e6c2df76e236748
frontend/device/pocketbook/device.lua
frontend/device/pocketbook/device.lua
local Generic = require("device/generic/device") -- <= look at this file! local logger = require("logger") local ffi = require("ffi") local inkview = ffi.load("inkview") -- luacheck: push -- luacheck: ignore local EVT_INIT = 21 local EVT_EXIT = 22 local EVT_SHOW = 23 local EVT_REPAINT = 23 local EVT_HIDE = 24 local EVT_KEYDOWN = 25 local EVT_KEYPRESS = 25 local EVT_KEYUP = 26 local EVT_KEYRELEASE = 26 local EVT_KEYREPEAT = 28 local EVT_FOREGROUND = 151 local EVT_BACKGROUND = 152 local KEY_POWER = 0x01 local KEY_DELETE = 0x08 local KEY_OK = 0x0a local KEY_UP = 0x11 local KEY_DOWN = 0x12 local KEY_LEFT = 0x13 local KEY_RIGHT = 0x14 local KEY_MINUS = 0x15 local KEY_PLUS = 0x16 local KEY_MENU = 0x17 local KEY_PREV = 0x18 local KEY_NEXT = 0x19 local KEY_HOME = 0x1a local KEY_BACK = 0x1b local KEY_PREV2 = 0x1c local KEY_NEXT2 = 0x1d local KEY_COVEROPEN = 0x02 local KEY_COVERCLOSE = 0x03 -- luacheck: pop ffi.cdef[[ char *GetSoftwareVersion(void); char *GetDeviceModel(void); ]] local function yes() return true end local function no() return false end local function pocketbookEnableWifi(toggle) os.execute("/ebrmain/bin/netagent " .. (toggle == 1 and "connect" or "disconnect")) end local PocketBook = Generic:new{ model = "PocketBook", isPocketBook = yes, isInBackGround = false, } function PocketBook:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg} self.powerd = require("device/pocketbook/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = { [KEY_MENU] = "Menu", [KEY_PREV] = "LPgBack", [KEY_NEXT] = "LPgFwd", }, handleMiscEv = function(this, ev) if ev.code == EVT_BACKGROUND then self.isInBackGround = true return "Suspend" elseif ev.code == EVT_FOREGROUND then if self.isInBackGround then self.isInBackGround = false return "Resume" end end end, } -- in contrast to kobo/kindle, pocketbook-devices do not use linux/input -- events directly. To be able to use input.lua nevertheless, we make -- inkview-events look like linux/input events or handle them directly -- here. -- Unhandled events will leave Input:waitEvent() as "GenericInput" self.input:registerEventAdjustHook(function(_input, ev) if ev.type == EVT_KEYDOWN or ev.type == EVT_KEYUP then ev.value = ev.type == EVT_KEYDOWN and 1 or 0 ev.type = 1 -- linux/input.h Key-Event end -- handle EVT_BACKGROUND and EVT_FOREGROUND as MiscEvent as this makes -- it easy to return a string directly which can be used in -- uimanager.lua as event_handler index. if ev.type == EVT_BACKGROUND or ev.type == EVT_FOREGROUND then ev.code = ev.type ev.type = 4 -- handle as MiscEvent, see above end -- auto shutdown event from inkview framework, gracefully close -- everything and let the framework shutdown the device if ev.type == EVT_EXIT then require("ui/uimanager"):broadcastEvent( require("ui/event"):new("Close")) end end) os.remove(self.emu_events_dev) os.execute("mkfifo " .. self.emu_events_dev) self.input.open(self.emu_events_dev, 1) Generic.init(self) end function PocketBook:supportsScreensaver() return true end function PocketBook:setDateTime(year, month, day, hour, min, sec) if hour == nil or min == nil then return true end local command if year and month and day then command = string.format("date -s '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec) else command = string.format("date -s '%d:%d'",hour, min) end if os.execute(command) == 0 then os.execute('hwclock -u -w') return true else return false end end function PocketBook:initNetworkManager(NetworkMgr) NetworkMgr.turnOnWifi = function() pocketbookEnableWifi(1) end NetworkMgr.turnOffWifi = function() pocketbookEnableWifi(0) end end function PocketBook:getSoftwareVersion() return ffi.string(inkview.GetSoftwareVersion()) end function PocketBook:getDeviceModel() return ffi.string(inkview.GetDeviceModel()) end -- PocketBook InkPad local PocketBook840 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, display_dpi = 250, emu_events_dev = "/var/dev/shm/emu_events", } -- PocketBook HD Touch local PocketBook631 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, display_dpi = 300, emu_events_dev = "/dev/shm/emu_events", } -- PocketBook Lux 3 local PocketBook626 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, display_dpi = 212, emu_events_dev = "/var/dev/shm/emu_events", } -- PocketBook Basic Touch local PocketBook624 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = no, display_dpi = 166, emu_events_dev = "/var/dev/shm/emu_events", } -- PocketBook Touch Lux local PocketBook623 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, display_dpi = 212, emu_events_dev = "/var/dev/shm/emu_events", } logger.info('SoftwareVersion: ', PocketBook:getSoftwareVersion()) local codename = PocketBook:getDeviceModel() if codename == "PocketBook 840" then return PocketBook840 elseif codename == "PB631" then return PocketBook631 elseif codename == "PocketBook 626" then return PocketBook626 elseif codename == "PocketBook 624" then return PocketBook624 elseif codename == "PocketBook 623" then return PocketBook623 else error("unrecognized PocketBook model " .. codename) end
local Generic = require("device/generic/device") -- <= look at this file! local logger = require("logger") local ffi = require("ffi") local inkview = ffi.load("inkview") -- luacheck: push -- luacheck: ignore local EVT_INIT = 21 local EVT_EXIT = 22 local EVT_SHOW = 23 local EVT_REPAINT = 23 local EVT_HIDE = 24 local EVT_KEYDOWN = 25 local EVT_KEYPRESS = 25 local EVT_KEYUP = 26 local EVT_KEYRELEASE = 26 local EVT_KEYREPEAT = 28 local EVT_FOREGROUND = 151 local EVT_BACKGROUND = 152 local KEY_POWER = 0x01 local KEY_DELETE = 0x08 local KEY_OK = 0x0a local KEY_UP = 0x11 local KEY_DOWN = 0x12 local KEY_LEFT = 0x13 local KEY_RIGHT = 0x14 local KEY_MINUS = 0x15 local KEY_PLUS = 0x16 local KEY_MENU = 0x17 local KEY_PREV = 0x18 local KEY_NEXT = 0x19 local KEY_HOME = 0x1a local KEY_BACK = 0x1b local KEY_PREV2 = 0x1c local KEY_NEXT2 = 0x1d local KEY_COVEROPEN = 0x02 local KEY_COVERCLOSE = 0x03 -- luacheck: pop ffi.cdef[[ char *GetSoftwareVersion(void); char *GetDeviceModel(void); ]] local function yes() return true end local function no() return false end local function pocketbookEnableWifi(toggle) os.execute("/ebrmain/bin/netagent " .. (toggle == 1 and "connect" or "disconnect")) end local PocketBook = Generic:new{ model = "PocketBook", isPocketBook = yes, isInBackGround = false, } function PocketBook:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg} self.powerd = require("device/pocketbook/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = { [KEY_MENU] = "Menu", [KEY_PREV] = "LPgBack", [KEY_NEXT] = "LPgFwd", }, handleMiscEv = function(this, ev) if ev.code == EVT_BACKGROUND then self.isInBackGround = true return "Suspend" elseif ev.code == EVT_FOREGROUND then if self.isInBackGround then self.isInBackGround = false return "Resume" end end end, } -- in contrast to kobo/kindle, pocketbook-devices do not use linux/input -- events directly. To be able to use input.lua nevertheless, we make -- inkview-events look like linux/input events or handle them directly -- here. -- Unhandled events will leave Input:waitEvent() as "GenericInput" self.input:registerEventAdjustHook(function(_input, ev) if ev.type == EVT_KEYDOWN or ev.type == EVT_KEYUP then ev.value = ev.type == EVT_KEYDOWN and 1 or 0 ev.type = 1 -- linux/input.h Key-Event end -- handle EVT_BACKGROUND and EVT_FOREGROUND as MiscEvent as this makes -- it easy to return a string directly which can be used in -- uimanager.lua as event_handler index. if ev.type == EVT_BACKGROUND or ev.type == EVT_FOREGROUND then ev.code = ev.type ev.type = 4 -- handle as MiscEvent, see above end -- auto shutdown event from inkview framework, gracefully close -- everything and let the framework shutdown the device if ev.type == EVT_EXIT then require("ui/uimanager"):broadcastEvent( require("ui/event"):new("Close")) end end) os.remove(self.emu_events_dev) os.execute("mkfifo " .. self.emu_events_dev) self.input.open(self.emu_events_dev, 1) Generic.init(self) end function PocketBook:supportsScreensaver() return true end function PocketBook:setDateTime(year, month, day, hour, min, sec) if hour == nil or min == nil then return true end local command if year and month and day then command = string.format("date -s '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec) else command = string.format("date -s '%d:%d'",hour, min) end if os.execute(command) == 0 then os.execute('hwclock -u -w') return true else return false end end function PocketBook:initNetworkManager(NetworkMgr) NetworkMgr.turnOnWifi = function() pocketbookEnableWifi(1) end NetworkMgr.turnOffWifi = function() pocketbookEnableWifi(0) end end function PocketBook:getSoftwareVersion() return ffi.string(inkview.GetSoftwareVersion()) end function PocketBook:getDeviceModel() return ffi.string(inkview.GetDeviceModel()) end -- PocketBook InkPad local PocketBook840 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, display_dpi = 250, emu_events_dev = "/var/dev/shm/emu_events", } -- PocketBook HD Touch local PocketBook631 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, display_dpi = 300, emu_events_dev = "/dev/shm/emu_events", } -- PocketBook Lux 3 local PocketBook626 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, display_dpi = 212, emu_events_dev = "/var/dev/shm/emu_events", } -- PocketBook Basic Touch local PocketBook624 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = no, display_dpi = 166, emu_events_dev = "/var/dev/shm/emu_events", } -- PocketBook Touch Lux local PocketBook623 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, display_dpi = 212, emu_events_dev = "/var/dev/shm/emu_events", } -- PocketBook InkPad 3 local PocketBook740 = PocketBook:new{ isTouchDevice = yes, hasKeys = yes, hasFrontlight = yes, isAlwaysPortrait = yes, display_dpi = 300, emu_events_dev = "/var/dev/shm/emu_events", } logger.info('SoftwareVersion: ', PocketBook:getSoftwareVersion()) local codename = PocketBook:getDeviceModel() if codename == "PocketBook 840" then return PocketBook840 elseif codename == "PB631" then return PocketBook631 elseif codename == "PocketBook 626" then return PocketBook626 elseif codename == "PocketBook 624" then return PocketBook624 elseif codename == "PocketBook 623" then return PocketBook623 elseif codename == "PB740" then return PocketBook740 else error("unrecognized PocketBook model " .. codename) end
[PocketBook] Add Inkpad 3 (PB740) definition (#3830)
[PocketBook] Add Inkpad 3 (PB740) definition (#3830) Fixes #3687 Thanks to @Maradar for testing, see https://github.com/koreader/koreader/issues/3687#issuecomment-378652074
Lua
agpl-3.0
pazos/koreader,mwoz123/koreader,NiLuJe/koreader,koreader/koreader,poire-z/koreader,NiLuJe/koreader,houqp/koreader,mihailim/koreader,poire-z/koreader,koreader/koreader,Frenzie/koreader,Hzj-jie/koreader,lgeek/koreader,Frenzie/koreader,Markismus/koreader
2532debe30c5d952516f474f4ffdc918552bd45a
kong/tools/ngx_stub.lua
kong/tools/ngx_stub.lua
-- Stub _G.ngx for unit testing. -- Creates a stub for `ngx` for use by Kong's modules such as the DAO. It allows to use them -- outside of the nginx context such as when using the CLI, or unit testing. -- -- Monkeypatches the global `ngx` table. local reg = require "rex_pcre" local utils = require "kong.tools.utils" -- DICT Proxy -- https://github.com/bsm/fakengx/blob/master/fakengx.lua local SharedDict = {} local function set(data, key, value) data[key] = { value = value, info = {expired = false} } end function SharedDict:new() return setmetatable({data = {}}, {__index = self}) end function SharedDict:get(key) return self.data[key] and self.data[key].value, nil end function SharedDict:set(key, value) set(self.data, key, value) return true, nil, false end SharedDict.safe_set = SharedDict.set function SharedDict:add(key, value) if self.data[key] ~= nil then return false, "exists", false end set(self.data, key, value) return true, nil, false end function SharedDict:replace(key, value) if self.data[key] == nil then return false, "not found", false end set(self.data, key, value) return true, nil, false end function SharedDict:delete(key) self.data[key] = nil end function SharedDict:incr(key, value) if not self.data[key] then return nil, "not found" elseif type(self.data[key].value) ~= "number" then return nil, "not a number" end self.data[key].value = self.data[key].value + value return self.data[key].value, nil end function SharedDict:flush_all() for _, item in pairs(self.data) do item.info.expired = true end end function SharedDict:flush_expired(n) local data = self.data local flushed = 0 for key, item in pairs(self.data) do if item.info.expired then data[key] = nil flushed = flushed + 1 if n and flushed == n then break end end end self.data = data return flushed end local shared = {} local shared_mt = { __index = function(self, key) if shared[key] == nil then shared[key] = SharedDict:new() end return shared[key] end } _G.ngx = { stub = true, req = { get_headers = function() return {} end }, ctx = {}, header = {}, get_phase = function() return "init" end, socket = {}, exit = function() end, say = function() end, log = function() end, --socket = { tcp = {} }, now = function() return os.time() end, time = function() return os.time() end, timer = { at = function() end }, shared = setmetatable({}, shared_mt), re = { match = reg.match, gsub = function(str, pattern, sub) local res_str, _, sub_made = reg.gsub(str, pattern, sub) return res_str, sub_made end }, encode_base64 = function(str) return string.format("base64_%s", str) end, encode_args = utils.encode_args }
-- Stub _G.ngx for unit testing. -- Creates a stub for `ngx` for use by Kong's modules such as the DAO. It allows to use them -- outside of the nginx context such as when using the CLI, or unit testing. -- -- Monkeypatches the global `ngx` table. local reg = require "rex_pcre" local utils = require "kong.tools.utils" -- DICT Proxy -- https://github.com/bsm/fakengx/blob/master/fakengx.lua local SharedDict = {} local function set(data, key, value) data[key] = { value = value, info = {expired = false} } end function SharedDict:new() return setmetatable({data = {}}, {__index = self}) end function SharedDict:get(key) return self.data[key] and self.data[key].value, nil end function SharedDict:set(key, value) set(self.data, key, value) return true, nil, false end SharedDict.safe_set = SharedDict.set function SharedDict:add(key, value) if self.data[key] ~= nil then return false, "exists", false end set(self.data, key, value) return true, nil, false end function SharedDict:replace(key, value) if self.data[key] == nil then return false, "not found", false end set(self.data, key, value) return true, nil, false end function SharedDict:delete(key) self.data[key] = nil end function SharedDict:incr(key, value) if not self.data[key] then return nil, "not found" elseif type(self.data[key].value) ~= "number" then return nil, "not a number" end self.data[key].value = self.data[key].value + value return self.data[key].value, nil end function SharedDict:flush_all() for _, item in pairs(self.data) do item.info.expired = true end end function SharedDict:flush_expired(n) local data = self.data local flushed = 0 for key, item in pairs(self.data) do if item.info.expired then data[key] = nil flushed = flushed + 1 if n and flushed == n then break end end end self.data = data return flushed end local shared = {} local shared_mt = { __index = function(self, key) if shared[key] == nil then shared[key] = SharedDict:new() end return shared[key] end } _G.ngx = { stub = true, req = { get_headers = function() return {} end, set_header = function() return {} end }, ctx = {}, header = {}, get_phase = function() return "init" end, socket = {}, exit = function() end, say = function() end, log = function() end, --socket = { tcp = {} }, now = function() return os.time() end, time = function() return os.time() end, timer = { at = function() end }, shared = setmetatable({}, shared_mt), re = { match = reg.match, gsub = function(str, pattern, sub) local res_str, _, sub_made = reg.gsub(str, pattern, sub) return res_str, sub_made end }, encode_base64 = function(str) return string.format("base64_%s", str) end, encode_args = utils.encode_args }
fix/test-ngx-stub
fix/test-ngx-stub
Lua
apache-2.0
Mashape/kong,Kong/kong,Kong/kong,li-wl/kong,smanolache/kong,jerizm/kong,jebenexer/kong,ccyphers/kong,icyxp/kong,beauli/kong,salazar/kong,Vermeille/kong,Kong/kong,shiprabehera/kong,akh00/kong
6eca26f610fcecef8636574cf9e69680554936d8
frontend/ui/screensaver.lua
frontend/ui/screensaver.lua
local DocumentRegistry = require("document/documentregistry") local UIManager = require("ui/uimanager") local Screen = require("device").screen local DocSettings = require("docsettings") local DEBUG = require("dbg") local _ = require("gettext") local Screensaver = { } function Screensaver:getCoverImage(file) local ImageWidget = require("ui/widget/imagewidget") local CenterContainer = require("ui/widget/container/centercontainer") local FrameContainer = require("ui/widget/container/framecontainer") local AlphaContainer = require("ui/widget/container/alphacontainer") local image_height local image_width local screen_height = Screen:getHeight() local screen_width = Screen:getWidth() local doc = DocumentRegistry:openDocument(file) if doc then local image = doc:getCoverPageImage() doc:close() local lastfile = G_reader_settings:readSetting("lastfile") local data = DocSettings:open(lastfile) local proportional_cover = data:readSetting("proportional_screensaver") if image then if proportional_cover then image_height = image:getHeight() image_width = image:getWidth() local image_ratio = image_width / image_height local screen_ratio = screen_width / screen_height if image_ratio < 1 then image_height = screen_height image_width = image_height * image_ratio else image_width = screen_width image_height = image_width / image_ratio end else image_height = screen_height image_width = screen_width end local image_widget = ImageWidget:new{ image = image, width = image_width, height = image_height, } return AlphaContainer:new{ alpha = 1, height = screen_height, width = screen_width, CenterContainer:new{ dimen = Screen:getSize(), FrameContainer:new{ bordersize = 0, padding = 0, height = screen_height, width = screen_width, image_widget } } } end end end function Screensaver:getRandomImage(dir) local ImageWidget = require("ui/widget/imagewidget") local pics = {} local i = 0 math.randomseed(os.time()) for entry in lfs.dir(dir) do if lfs.attributes(dir .. entry, "mode") == "file" then local extension = string.lower(string.match(entry, ".+%.([^.]+)") or "") if extension == "jpg" or extension == "jpeg" or extension == "png" then i = i + 1 pics[i] = entry end end end local image = pics[math.random(i)] if image then image = dir .. image if lfs.attributes(image, "mode") == "file" then return ImageWidget:new{ file = image, width = Screen:getWidth(), height = Screen:getHeight(), } end end end function Screensaver:show() DEBUG("show screensaver") local InfoMessage = require("ui/widget/infomessage") -- first check book cover image if KOBO_SCREEN_SAVER_LAST_BOOK then local lastfile = G_reader_settings:readSetting("lastfile") local data = DocSettings:open(lastfile) local exclude = data:readSetting("exclude_screensaver") if not exclude then self.suspend_msg = self:getCoverImage(lastfile) end end -- then screensaver directory or file image if not self.suspend_msg then if type(KOBO_SCREEN_SAVER) == "string" then local file = KOBO_SCREEN_SAVER if lfs.attributes(file, "mode") == "directory" then if string.sub(file,string.len(file)) ~= "/" then file = file .. "/" end self.suspend_msg = self:getRandomImage(file) elseif lfs.attributes(file, "mode") == "file" then local ImageWidget = require("ui/widget/imagewidget") self.suspend_msg = ImageWidget:new{ file = file, width = Screen:getWidth(), height = Screen:getHeight(), } end end end -- fallback to suspended message if not self.suspend_msg then self.suspend_msg = InfoMessage:new{ text = _("Suspended") } end UIManager:show(self.suspend_msg) end function Screensaver:close() DEBUG("close screensaver") if self.suspend_msg then UIManager:close(self.suspend_msg) self.suspend_msg = nil end end return Screensaver
local DocumentRegistry = require("document/documentregistry") local UIManager = require("ui/uimanager") local Screen = require("device").screen local DocSettings = require("docsettings") local DEBUG = require("dbg") local _ = require("gettext") local Screensaver = { } function Screensaver:getCoverImage(file) local ImageWidget = require("ui/widget/imagewidget") local CenterContainer = require("ui/widget/container/centercontainer") local FrameContainer = require("ui/widget/container/framecontainer") local AlphaContainer = require("ui/widget/container/alphacontainer") local image_height local image_width local screen_height = Screen:getHeight() local screen_width = Screen:getWidth() local doc = DocumentRegistry:openDocument(file) if doc then local image = doc:getCoverPageImage() doc:close() local lastfile = G_reader_settings:readSetting("lastfile") local data = DocSettings:open(lastfile) local proportional_cover = data:readSetting("proportional_screensaver") if image then if proportional_cover then image_height = image:getHeight() image_width = image:getWidth() local image_ratio = image_width / image_height local screen_ratio = screen_width / screen_height if image_ratio < 1 then image_height = screen_height image_width = image_height * image_ratio else image_width = screen_width image_height = image_width / image_ratio end else image_height = screen_height image_width = screen_width end local image_widget = ImageWidget:new{ image = image, width = image_width, height = image_height, } return AlphaContainer:new{ alpha = 1, height = screen_height, width = screen_width, CenterContainer:new{ dimen = Screen:getSize(), FrameContainer:new{ bordersize = 0, padding = 0, height = screen_height, width = screen_width, image_widget } } } end end end function Screensaver:getRandomImage(dir) local ImageWidget = require("ui/widget/imagewidget") local pics = {} local i = 0 math.randomseed(os.time()) for entry in lfs.dir(dir) do if lfs.attributes(dir .. entry, "mode") == "file" then local extension = string.lower(string.match(entry, ".+%.([^.]+)") or "") if extension == "jpg" or extension == "jpeg" or extension == "png" then i = i + 1 pics[i] = entry end end end local image = pics[math.random(i)] if image then image = dir .. image if lfs.attributes(image, "mode") == "file" then return ImageWidget:new{ file = image, width = Screen:getWidth(), height = Screen:getHeight(), } end end end function Screensaver:show() DEBUG("show screensaver") local InfoMessage = require("ui/widget/infomessage") -- first check book cover image if KOBO_SCREEN_SAVER_LAST_BOOK then local lastfile = G_reader_settings:readSetting("lastfile") if lastfile then local data = DocSettings:open(lastfile) local exclude = data:readSetting("exclude_screensaver") if not exclude then self.suspend_msg = self:getCoverImage(lastfile) end end end -- then screensaver directory or file image if not self.suspend_msg then if type(KOBO_SCREEN_SAVER) == "string" then local file = KOBO_SCREEN_SAVER if lfs.attributes(file, "mode") == "directory" then if string.sub(file,string.len(file)) ~= "/" then file = file .. "/" end self.suspend_msg = self:getRandomImage(file) elseif lfs.attributes(file, "mode") == "file" then local ImageWidget = require("ui/widget/imagewidget") self.suspend_msg = ImageWidget:new{ file = file, width = Screen:getWidth(), height = Screen:getHeight(), } end end end -- fallback to suspended message if not self.suspend_msg then self.suspend_msg = InfoMessage:new{ text = _("Suspended") } end UIManager:show(self.suspend_msg) end function Screensaver:close() DEBUG("close screensaver") if self.suspend_msg then UIManager:close(self.suspend_msg) self.suspend_msg = nil end end return Screensaver
fix(screensaver): lastfile will be nil for fresh installation
fix(screensaver): lastfile will be nil for fresh installation
Lua
agpl-3.0
ashhher3/koreader,chrox/koreader,frankyifei/koreader,noname007/koreader,NiLuJe/koreader,chihyang/koreader,koreader/koreader,houqp/koreader,Frenzie/koreader,Markismus/koreader,Hzj-jie/koreader,NiLuJe/koreader,pazos/koreader,ashang/koreader,koreader/koreader,apletnev/koreader,mwoz123/koreader,Frenzie/koreader,poire-z/koreader,mihailim/koreader,robert00s/koreader,poire-z/koreader,lgeek/koreader,NickSavage/koreader
6d39c71c4c896e164dcfd509b229c165b47e3655
premake.lua
premake.lua
project.name = "Premake4" -- Project options addoption("no-tests", "Build without automated tests") -- Output directories project.config["Debug"].bindir = "bin/debug" project.config["Release"].bindir = "bin/release" -- Packages dopackage("src") -- Cleanup code function doclean(cmd, arg) docommand(cmd, arg) os.rmdir("bin") os.rmdir("doc") end -- Release code REPOS = "https://premake.svn.sourceforge.net/svnroot/premake" TRUNK = "/trunk" BRANCHES = "/branches/4.0-alpha/" function dorelease(cmd, arg) if (not arg) then error "You must specify a version" end ------------------------------------------------------------------- -- Make sure everything is good before I start ------------------------------------------------------------------- print("") print("PRE-FLIGHT CHECKLIST") print(" * is README up-to-date?") print(" * is CHANGELOG up-to-date?") print(" * did you test build with GCC?") print(" * did you test build with Doxygen?") print(" * are 'svn' (all) and '7z' (Windows) available?") print("") print("Press [Enter] to continue or [^C] to quit.") io.stdin:read("*l") ------------------------------------------------------------------- -- Set up environment ------------------------------------------------------------------- local version = arg os.mkdir("releases") local folder = "premake-"..version local trunk = REPOS..TRUNK local branch = REPOS..BRANCHES..version ------------------------------------------------------------------- -- Build and run all automated tests ------------------------------------------------------------------- print("Building tests on working copy...") os.execute("premake --target gnu > ../releases/release.log") result = os.execute("make CONFIG=Release >../releases/release.log") if (result ~= 0) then error("Test build failed; see release.log for details") end ------------------------------------------------------------------- -- Look for a release branch in SVN, and create one from trunk if necessary ------------------------------------------------------------------- print("Checking for release branch...") os.chdir("releases") result = os.execute(string.format("svn ls %s >release.log 2>&1", branch)) if (result ~= 0) then print("Creating release branch...") result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version)) if (result ~= 0) then error("Failed to create release branch at "..branch) end end ------------------------------------------------------------------- -- Checkout a local copy of the release branch ------------------------------------------------------------------- print("Getting source code from release branch...") os.execute(string.format("svn co %s %s >release.log", branch, folder)) if (not os.fileexists(folder.."/README.txt")) then error("Unable to checkout from repository at "..branch) end ------------------------------------------------------------------- -- Embed version numbers into the files ------------------------------------------------------------------- print("TODO - set version number in premake") ------------------------------------------------------------------- -- Build the release binary for this platform ------------------------------------------------------------------- print("Building release version...") os.execute("premake --clean --no-tests --target gnu >../release.log") os.execute("make CONFIG=Release >../release.log") if (windows) then result = os.execute(string.format("7z a -tzip ..\\premake-win32-%s.zip bin\\release\\premake4.exe >../release.log", version)) elseif (macosx) then error("OSX binary not implemented yet") else error("Linux binary not implemented yet") end if (result ~= 0) then error("Failed to build binary package; see release.log for details") end ------------------------------------------------------------------- -- Clean up ------------------------------------------------------------------- print("Cleaning up...") os.chdir("..") os.rmdir(folder) os.remove("release.log") end
project.name = "Premake4" -- Project options addoption("no-tests", "Build without automated tests") -- Output directories project.config["Debug"].bindir = "bin/debug" project.config["Release"].bindir = "bin/release" -- Packages dopackage("src") -- Cleanup code function doclean(cmd, arg) docommand(cmd, arg) os.rmdir("bin") os.rmdir("doc") end -- Release code REPOS = "https://premake.svn.sourceforge.net/svnroot/premake" TRUNK = "/trunk" BRANCHES = "/branches/4.0-alpha/" function dorelease(cmd, arg) if (not arg) then error "You must specify a version" end ------------------------------------------------------------------- -- Make sure everything is good before I start ------------------------------------------------------------------- print("") print("PRE-FLIGHT CHECKLIST") print(" * is README up-to-date?") print(" * is CHANGELOG up-to-date?") print(" * did you test build with GCC?") print(" * did you test build with Doxygen?") print(" * are 'svn' (all) and '7z' (Windows) available?") print("") print("Press [Enter] to continue or [^C] to quit.") io.stdin:read("*l") ------------------------------------------------------------------- -- Set up environment ------------------------------------------------------------------- local version = arg os.mkdir("releases") local folder = "premake-"..version local trunk = REPOS..TRUNK local branch = REPOS..BRANCHES..version ------------------------------------------------------------------- -- Build and run all automated tests on working copy ------------------------------------------------------------------- print("Building tests on working copy...") os.execute("premake --target gnu >releases/release.log") result = os.execute("make CONFIG=Release >releases/release.log") if (result ~= 0) then error("Test build failed; see release.log for details") end ------------------------------------------------------------------- -- Look for a release branch in SVN, and create one from trunk if necessary ------------------------------------------------------------------- print("Checking for release branch...") os.chdir("releases") result = os.execute(string.format("svn ls %s >release.log 2>&1", branch)) if (result ~= 0) then print("Creating release branch...") result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version)) if (result ~= 0) then error("Failed to create release branch at "..branch) end end ------------------------------------------------------------------- -- Checkout a local copy of the release branch ------------------------------------------------------------------- print("Getting source code from release branch...") os.execute(string.format("svn co %s %s >release.log", branch, folder)) if (not os.fileexists(folder.."/README.txt")) then error("Unable to checkout from repository at "..branch) end ------------------------------------------------------------------- -- Embed version numbers into the files ------------------------------------------------------------------- print("TODO - set version number in premake") ------------------------------------------------------------------- -- Build the release binary for this platform ------------------------------------------------------------------- print("Building release version...") os.chdir(folder) os.execute("premake --clean --no-tests --target gnu >../release.log") os.execute("make CONFIG=Release >../release.log") if (windows) then result = os.execute(string.format("7z a -tzip ..\\premake-win32-%s.zip bin\\release\\premake4.exe >../release.log", version)) elseif (macosx) then error("OSX binary not implemented yet") else error("Linux binary not implemented yet") end if (result ~= 0) then error("Failed to build binary package; see release.log for details") end ------------------------------------------------------------------- -- Clean up ------------------------------------------------------------------- print("Cleaning up...") os.chdir("..") os.rmdir(folder) os.remove("release.log") end
Minor fixes to release script
Minor fixes to release script
Lua
bsd-3-clause
dimitarcl/premake-dev,Amorph/premake-dev,Amorph/premake-dev,Amorph/premake-dev,Amorph/premake-stable,Amorph/premake-stable,dimitarcl/premake-dev,dimitarcl/premake-dev,Amorph/premake-stable
8196ae771e305596eea403f7d83e6e23309211ff
CCLib/src/cc/native/Turtle.lua
CCLib/src/cc/native/Turtle.lua
natives["cc.turtle.Turtle"] = natives["cc.turtle.Turtle"] or {} function booleanToInt(b) if b then return 1 else return 0 end end natives["cc.turtle.Turtle"]["forward()Z"] = function() local success = turtle.forward() return booleanToInt(success) end natives["cc.turtle.Turtle"]["back()Z"] = function() local success = turtle.back() return booleanToInt(success) end natives["cc.turtle.Turtle"]["up()Z"] = function() local success = turtle.up() return booleanToInt(success) end natives["cc.turtle.Turtle"]["down()Z"] = function() local success = turtle.down() return booleanToInt(success) end natives["cc.turtle.Turtle"]["turnLeft()Z"] = function() local success = turtle.turnLeft() return booleanToInt(success) end natives["cc.turtle.Turtle"]["turnRight()Z"] = function() local success = turtle.turnRight() return booleanToInt(success) end natives["cc.turtle.Turtle"]["select(I)Z"] = function(slot) local success = turtle.select(slot) return booleanToInt(success) end natives["cc.turtle.Turtle"]["getSelectedSlot()I"] = function() local slot = turtle.getSelectedSlot() return slot; end natives["cc.turtle.Turtle"]["getItemCount(I)I"] = function(slot) local count = turtle.getItemCount(slot); return count; end natives["cc.turtle.Turtle"]["getItemSpace(I)I"] = function(slot) local space = turtle.getItemSpace(slot); return space; end natives["cc.turtle.Turtle"]["getItemDetail(I)Lcc/turtle/ItemStack;"] = function(slot) local data = turtle.getItemDetail(slot); if data == nil then return null end local class = classByName("cc.turtle.ItemStack") local itemstack = newInstance(class) findMethod(class, "<init>()V")[1](itemstack) setObjectField(itemstack, "name", toJString(data.name)) setObjectField(itemstack, "damage", data.damage) setObjectField(itemstack, "count", data.count) return itemstack; end natives["cc.turtle.Turtle"]["equipLeft()Z"] = function() local success = turtle.equipLeft() return success end natives["cc.turtle.Turtle"]["equipRight()Z"] = function() local success = turtle.equipRight() return success end natives["cc.turtle.Turtle"]["place(Ljava/lang/String;)Z"] = function(text) local success = turtle.place(toLString(text)) return booleanToInt(success) end natives["cc.turtle.Turtle"]["placeUp()Z"] = function() local success = turtle.placeUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["placeDown()Z"] = function() local success = turtle.placeDown() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detect()Z"] = function() local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detectUp()Z"] = function() local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detectDown()Z"] = function() local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["inspect()Lcc/turtle/InspectionReport;"] = function() local success, data = turtle.inspect() return createInspectionReport(success, data) end natives["cc.turtle.Turtle"]["inspectUp()Lcc/turtle/InspectionReport;"] = function() local success, data = turtle.inspectUp() return createInspectionReport(success, data) end natives["cc.turtle.Turtle"]["inspectDown()Lcc/turtle/InspectionReport;"] = function() local success, data = turtle.inspectDown() return createInspectionReport(success, data) end function createInspectionReport(success, data) local class = classByName("cc.turtle.InspectionReport") local report = newInstance(class) findMethod(class, "<init>()V")[1](report) if success then setObjectField(report, "success", 1) setObjectField(report, "blockName", toJString(data.name)) setObjectField(report, "blockMetadata", data.metadata) else setObjectField(report, "success", 0) setObjectField(report, "errorMessage", toJString(data)) end return report end natives["cc.turtle.Turtle"]["compare()Z"] = function() local success = turtle.compare() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareUp()Z"] = function() local success = turtle.compareUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareDown()Z"] = function() local success = turtle.compareDown() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareTo(I)Z"] = function(slot) local success = turtle.compareTo(slot) return booleanToInt(success) end natives["cc.turtle.Turtle"]["drop(I)Z"] = function(count) local success = turtle.drop(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["dropUp(I)Z"] = function(count) local success = turtle.dropUp(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["dropDown(I)Z"] = function(count) local success = turtle.dropDown(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suck(I)Z"] = function(count) local success = turtle.suck(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suckUp(I)Z"] = function(count) local success = turtle.suckUp(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suckDown(I)Z"] = function(count) local success = turtle.suckDown(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["refuel(I)Z"] = function(quantity) local success = turtle.refuel(quantity) return booleanToInt(success) end natives["cc.turtle.Turtle"]["getFuelLevel()I"] = function() local level = turtle.getFuelLevel() return level end natives["cc.turtle.Turtle"]["getFuelLimit()I"] = function() local level = turtle.getFuelLimit() return level end natives["cc.turtle.Turtle"]["transferTo(II)Z"] = function(slot, quantity) local success = turtle.transferTo(slot, quantity) return booleanToInt(success) end -- crafty turtles only natives["cc.turtle.Turtle"]["craft(I)Z"] = function(quantity) local success = turtle.craft(quantity) return booleanToInt(success) end -- digging, felling, mining, farming turtles natives["cc.turtle.Turtle"]["dig()Z"] = function() local success = turtle.dig() return booleanToInt(success) end natives["cc.turtle.Turtle"]["digUp()Z"] = function() local success = turtle.digUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["digDown()Z"] = function() local success = turtle.digDown() return booleanToInt(success) end -- all tools only natives["cc.turtle.Turtle"]["attack()Z"] = function() local success = turtle.attack() return booleanToInt(success) end natives["cc.turtle.Turtle"]["attackUp()Z"] = function() local success = turtle.attackUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["attackDown()Z"] = function() local success = turtle.attackDown() return booleanToInt(success) end
natives["cc.turtle.Turtle"] = natives["cc.turtle.Turtle"] or {} function booleanToInt(b) if b then return 1 else return 0 end end natives["cc.turtle.Turtle"]["forward()Z"] = function(this) local success = turtle.forward() return booleanToInt(success) end natives["cc.turtle.Turtle"]["back()Z"] = function(this) local success = turtle.back() return booleanToInt(success) end natives["cc.turtle.Turtle"]["up()Z"] = function(this) local success = turtle.up() return booleanToInt(success) end natives["cc.turtle.Turtle"]["down()Z"] = function(this) local success = turtle.down() return booleanToInt(success) end natives["cc.turtle.Turtle"]["turnLeft()Z"] = function(this) local success = turtle.turnLeft() return booleanToInt(success) end natives["cc.turtle.Turtle"]["turnRight()Z"] = function(this) local success = turtle.turnRight() return booleanToInt(success) end natives["cc.turtle.Turtle"]["select(I)Z"] = function(this, slot) local success = turtle.select(slot) return booleanToInt(success) end natives["cc.turtle.Turtle"]["getSelectedSlot()I"] = function(this) local slot = turtle.getSelectedSlot() return slot; end natives["cc.turtle.Turtle"]["getItemCount(I)I"] = function(this, slot) local count = turtle.getItemCount(slot); return count; end natives["cc.turtle.Turtle"]["getItemSpace(I)I"] = function(this, slot) local space = turtle.getItemSpace(slot); return space; end natives["cc.turtle.Turtle"]["getItemDetail(I)Lcc/turtle/ItemStack;"] = function(this, slot) local data = turtle.getItemDetail(slot); if data == nil then return null end local class = classByName("cc.turtle.ItemStack") local itemstack = newInstance(class) findMethod(class, "<init>()V")[1](itemstack) setObjectField(itemstack, "name", toJString(data.name)) setObjectField(itemstack, "damage", data.damage) setObjectField(itemstack, "count", data.count) return itemstack; end natives["cc.turtle.Turtle"]["equipLeft()Z"] = function(this) local success = turtle.equipLeft() return success end natives["cc.turtle.Turtle"]["equipRight()Z"] = function(this) local success = turtle.equipRight() return success end natives["cc.turtle.Turtle"]["place(Ljava/lang/String;)Z"] = function(this, text) local success = turtle.place(toLString(text)) return booleanToInt(success) end natives["cc.turtle.Turtle"]["placeUp()Z"] = function(this) local success = turtle.placeUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["placeDown()Z"] = function(this) local success = turtle.placeDown() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detect()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detectUp()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detectDown()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["inspect()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspect() return createInspectionReport(success, data) end natives["cc.turtle.Turtle"]["inspectUp()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspectUp() return createInspectionReport(success, data) end natives["cc.turtle.Turtle"]["inspectDown()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspectDown() return createInspectionReport(success, data) end function createInspectionReport(success, data) local class = classByName("cc.turtle.InspectionReport") local report = newInstance(class) findMethod(class, "<init>()V")[1](report) if success then setObjectField(report, "success", 1) setObjectField(report, "blockName", toJString(data.name)) setObjectField(report, "blockMetadata", data.metadata) else setObjectField(report, "success", 0) setObjectField(report, "errorMessage", toJString(data)) end return report end natives["cc.turtle.Turtle"]["compare()Z"] = function(this) local success = turtle.compare() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareUp()Z"] = function(this) local success = turtle.compareUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareDown()Z"] = function(this) local success = turtle.compareDown() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareTo(I)Z"] = function(this, slot) local success = turtle.compareTo(slot) return booleanToInt(success) end natives["cc.turtle.Turtle"]["drop(I)Z"] = function(this, count) local success = turtle.drop(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["dropUp(I)Z"] = function(this, count) local success = turtle.dropUp(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["dropDown(I)Z"] = function(this, count) local success = turtle.dropDown(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suck(I)Z"] = function(this, count) local success = turtle.suck(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suckUp(I)Z"] = function(this, count) local success = turtle.suckUp(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suckDown(I)Z"] = function(count) local success = turtle.suckDown(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["refuel(I)Z"] = function(quantity) local success = turtle.refuel(quantity) return booleanToInt(success) end natives["cc.turtle.Turtle"]["getFuelLevel()I"] = function() local level = turtle.getFuelLevel() return level end natives["cc.turtle.Turtle"]["getFuelLimit()I"] = function() local level = turtle.getFuelLimit() return level end natives["cc.turtle.Turtle"]["transferTo(II)Z"] = function(slot, quantity) local success = turtle.transferTo(slot, quantity) return booleanToInt(success) end -- crafty turtles only natives["cc.turtle.Turtle"]["craft(I)Z"] = function(quantity) local success = turtle.craft(quantity) return booleanToInt(success) end -- digging, felling, mining, farming turtles natives["cc.turtle.Turtle"]["dig()Z"] = function() local success = turtle.dig() return booleanToInt(success) end natives["cc.turtle.Turtle"]["digUp()Z"] = function() local success = turtle.digUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["digDown()Z"] = function() local success = turtle.digDown() return booleanToInt(success) end -- all tools only natives["cc.turtle.Turtle"]["attack()Z"] = function() local success = turtle.attack() return booleanToInt(success) end natives["cc.turtle.Turtle"]["attackUp()Z"] = function() local success = turtle.attackUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["attackDown()Z"] = function() local success = turtle.attackDown() return booleanToInt(success) end
Fixed methods interpreting the this paramter wrong (the most of them)
Fixed methods interpreting the this paramter wrong (the most of them)
Lua
mit
Team-CC-Corp/JVML-JIT,apemanzilla/JVML-JIT
eb941f277f4ac65f68dd0724a16e7e1875c05f76
lua/include/dpdk.lua
lua/include/dpdk.lua
--- high-level dpdk wrapper local mod = {} local ffi = require "ffi" local dpdkc = require "dpdkc" local serpent = require "Serpent" -- DPDK constants (lib/librte_mbuf/rte_mbuf.h) -- TODO: import more constants here mod.PKT_RX_IEEE1588_TMST = 0x0400 mod.PKT_TX_IPV4_CSUM = 0x1000 mod.PKT_TX_TCP_CKSUM = 0x2000 mod.PKT_TX_UDP_CKSUM = 0x6000 mod.PKT_TX_NO_CRC_CSUM = 0x0001 mod.PKT_TX_IEEE1588_TMST = 0x8000 local function fileExists(f) local file = io.open(f, "r") if file then file:close() end return not not file end local cores --- Inits DPDK. Called by MoonGen on startup. function mod.init() -- register drivers dpdkc.register_pmd_drivers() -- TODO: support arbitrary dpdk configurations by allowing configuration in the form ["cmdLine"] = "foo" local cfgFileLocations = { "./dpdk-conf.lua", "./lua/dpdk-conf.lua", "../lua/dpdk-conf.lua", "/etc/moongen/dpdk-conf.lua" } local cfg for _, f in ipairs(cfgFileLocations) do if fileExists(f) then cfgScript = loadfile(f) setfenv(cfgScript, setmetatable({ DPDKConfig = function(arg) cfg = arg end }, { __index = _G })) local ok, err = pcall(cfgScript) if not ok then print("could not load DPDK config: " .. err) return false end if not cfg then print("config file does not contain DPDKConfig statement") return false end cfg.name = f break end end if not cfg then print("no DPDK config found, using defaults") cfg = {} end local coreMask if not cfg.cores then -- default: use all the cores local cpus = io.open("/proc/cpuinfo", "r") cfg.cores = {} for cpu in cpus:read("*a"):gmatch("processor : (%d+)") do cfg.cores[#cfg.cores + 1] = tonumber(cpu) end cpus:close() end if type(cfg.cores) == "number" then coreMask = cfg.cores cores = {} -- TODO: support more than 32 cores but bit operations on 64 bit types are currently not supported in luajit for i = 0, 31 do if bit.band(coreMask, bit.lshift(1, i)) ~= 0 then cores[#cores + 1] = i end end if cfg.cores >= 2^32 then print("Warning: more than 32 cores are currently not supported in bitmask format, sorry") print("Use a table as a work-around") return end elseif type(cfg.cores) == "table" then cores = cfg.cores coreMask = 0 for i, v in ipairs(cores) do coreMask = coreMask + 2^v end end local argv = { "MoonGen" } if cfg.noHugeTlbFs then argv[#argv + 1] = "--no-huge" end argv[#argv + 1] = ("-c0x%X"):format(coreMask) argv[#argv + 1] = "-n" .. (cfg.memoryChannels or 4) -- todo: auto-detect local argc = #argv dpdkc.rte_eal_init(argc, ffi.new("const char*[?]", argc, argv)) return true end ffi.cdef[[ void launch_lua_core(int core, uint64_t task_id, char* args); void free(void* ptr); uint64_t generate_task_id(); void store_result(uint64_t task_id, char* result); char* get_result(uint64_t task_id); ]] local function checkCore() if MOONGEN_TASK_NAME ~= "master" then error("[ERROR] This function is only available on the master task.", 2) end end local task = {} task.__index = task local tasks = {} function task:new(core) checkCore() local obj = setmetatable({ -- double instead of uint64_t is easier here and okay (unless you want to start more than 2^53 tasks) id = tonumber(ffi.C.generate_task_id()), core = core }, task) tasks[core] = obj return obj end --- Wait for a task and return any arguments returned by the task function task:wait() checkCore() while true do if dpdkc.rte_eal_get_lcore_state(self.core) ~= dpdkc.RUNNING then -- task is finished local result = dpdkc.get_result(self.id) if result == nil then -- thread crashed :( return end local resultString = ffi.string(result) dpdkc.free(result) return unpackAll(loadstring(resultString)()) end ffi.C.usleep(100) end end function task:isRunning() checkCore() if not tasks[self.core] or task[self.core].id ~= self.id then -- something else or nothing is running on this core return false end -- this task is still on this cora, but is it still running? return dpdkc.rte_eal_get_lcore_state(core) == dpdkc.RUNNING end --- Launch a LuaJIT VM on a core with the given arguments. --- TODO: use proper serialization and only pass strings function mod.launchLuaOnCore(core, ...) checkCore() local args = serpent.dump({ mod.userScript, ... }) local task = task:new(core) local buf = ffi.new("char[?]", #args + 1) ffi.copy(buf, args) dpdkc.launch_lua_core(core, task.id, buf) return task end --- launches the lua file on the first free core function mod.launchLua(...) checkCore() for i = 2, #cores do -- skip master local core = cores[i] local status = dpdkc.rte_eal_get_lcore_state(core) if status == dpdkc.FINISHED then dpdkc.rte_eal_wait_lcore(core) -- should be guaranteed to be in WAIT state now according to DPDK documentation status = dpdkc.rte_eal_get_lcore_state(core) end if status == dpdkc.WAIT then -- core is in WAIT state return mod.launchLuaOnCore(core, ...) end end error("not enough cores to start this lua task") end ffi.cdef [[ int usleep(unsigned int usecs); ]] --- waits until all slave cores have finished their jobs function mod.waitForSlaves() while true do local allCoresFinished = true for i = 2, #cores do -- skip master local core = cores[i] if dpdkc.rte_eal_get_lcore_state(core) == dpdkc.RUNNING then allCoresFinished = false break end end if allCoresFinished then return end ffi.C.usleep(100) end end function mod.getCores() return cores end --- get the CPU's TSC function mod.getCycles() return dpdkc.rte_rdtsc() end --- get the TSC frequency function mod.getCyclesFrequency() return tonumber(dpdkc.rte_get_tsc_hz()) end --- gets the time in seconds function mod.getTime() return tonumber(mod.getCycles()) / tonumber(mod.getCyclesFrequency()) end --- set total run time of the test (to be called from master core on startup, shared between all cores) function mod.setRuntime(time) dpdkc.set_runtime(time * 1000) end --- returns false once the app receives SIGTERM or SIGINT, the time set via setRuntime expires, or when a thread calls dpdk.stop() function mod.running(extraTime) return dpdkc.is_running(extraTime or 0) == 1 -- luajit-2.0.3 does not like bool return types (TRACE NYI: unsupported C function type) end --- request all tasks to exit function mod.stop() dpdkc.set_runtime(0) end --- Delay by t milliseconds. Note that this does not sleep the actual thread; --- the time is spent in a busy wait loop by DPDK. function mod.sleepMillis(t) dpdkc.rte_delay_ms_export(t) end --- Delay by t microseconds. Note that this does not sleep the actual thread; --- the time is spent in a busy wait loop by DPDK. This means that this sleep --- is somewhat more accurate than relying on the OS. function mod.sleepMicros(t) dpdkc.rte_delay_us_export(t) end --- Get the core and socket id for the current thread function mod.getCore() return dpdkc.get_current_core(), dpdkc.get_current_socket() end return mod
--- high-level dpdk wrapper local mod = {} local ffi = require "ffi" local dpdkc = require "dpdkc" local serpent = require "Serpent" -- DPDK constants (lib/librte_mbuf/rte_mbuf.h) -- TODO: import more constants here mod.PKT_RX_IEEE1588_TMST = 0x0400 mod.PKT_TX_IPV4_CSUM = 0x1000 mod.PKT_TX_TCP_CKSUM = 0x2000 mod.PKT_TX_UDP_CKSUM = 0x6000 mod.PKT_TX_NO_CRC_CSUM = 0x0001 mod.PKT_TX_IEEE1588_TMST = 0x8000 local function fileExists(f) local file = io.open(f, "r") if file then file:close() end return not not file end local cores --- Inits DPDK. Called by MoonGen on startup. function mod.init() -- register drivers dpdkc.register_pmd_drivers() -- TODO: support arbitrary dpdk configurations by allowing configuration in the form ["cmdLine"] = "foo" local cfgFileLocations = { "./dpdk-conf.lua", "./lua/dpdk-conf.lua", "../lua/dpdk-conf.lua", "/etc/moongen/dpdk-conf.lua" } local cfg for _, f in ipairs(cfgFileLocations) do if fileExists(f) then cfgScript = loadfile(f) setfenv(cfgScript, setmetatable({ DPDKConfig = function(arg) cfg = arg end }, { __index = _G })) local ok, err = pcall(cfgScript) if not ok then print("could not load DPDK config: " .. err) return false end if not cfg then print("config file does not contain DPDKConfig statement") return false end cfg.name = f break end end if not cfg then print("no DPDK config found, using defaults") cfg = {} end local coreMask if not cfg.cores then -- default: use all the cores local cpus = io.open("/proc/cpuinfo", "r") cfg.cores = {} for cpu in cpus:read("*a"):gmatch("processor : (%d+)") do cfg.cores[#cfg.cores + 1] = tonumber(cpu) end cpus:close() end if type(cfg.cores) == "number" then coreMask = cfg.cores cores = {} -- TODO: support more than 32 cores but bit operations on 64 bit types are currently not supported in luajit for i = 0, 31 do if bit.band(coreMask, bit.lshift(1, i)) ~= 0 then cores[#cores + 1] = i end end if cfg.cores >= 2^32 then print("Warning: more than 32 cores are currently not supported in bitmask format, sorry") print("Use a table as a work-around") return end elseif type(cfg.cores) == "table" then cores = cfg.cores coreMask = 0 for i, v in ipairs(cores) do coreMask = coreMask + 2^v end end local argv = { "MoonGen" } if cfg.noHugeTlbFs then argv[#argv + 1] = "--no-huge" end argv[#argv + 1] = ("-c0x%X"):format(coreMask) argv[#argv + 1] = "-n" .. (cfg.memoryChannels or 4) -- todo: auto-detect local argc = #argv dpdkc.rte_eal_init(argc, ffi.new("const char*[?]", argc, argv)) return true end ffi.cdef[[ void launch_lua_core(int core, uint64_t task_id, char* args); void free(void* ptr); uint64_t generate_task_id(); void store_result(uint64_t task_id, char* result); char* get_result(uint64_t task_id); ]] local function checkCore() if MOONGEN_TASK_NAME ~= "master" then error("[ERROR] This function is only available on the master task.", 2) end end local task = {} task.__index = task local tasks = {} function task:new(core) checkCore() local obj = setmetatable({ -- double instead of uint64_t is easier here and okay (unless you want to start more than 2^53 tasks) id = tonumber(ffi.C.generate_task_id()), core = core }, task) tasks[core] = obj return obj end --- Wait for a task and return any arguments returned by the task function task:wait() checkCore() while true do if dpdkc.rte_eal_get_lcore_state(self.core) ~= dpdkc.RUNNING then -- task is finished local result = dpdkc.get_result(self.id) if result == nil then -- thread crashed :( return end local resultString = ffi.string(result) dpdkc.free(result) return unpackAll(loadstring(resultString)()) end ffi.C.usleep(100) end end function task:isRunning() checkCore() if not tasks[self.core] or task[self.core].id ~= self.id then -- something else or nothing is running on this core return false end -- this task is still on this cora, but is it still running? return dpdkc.rte_eal_get_lcore_state(core) == dpdkc.RUNNING end --- Launch a LuaJIT VM on a core with the given arguments. --- TODO: use proper serialization and only pass strings function mod.launchLuaOnCore(core, ...) checkCore() local args = serpent.dump({ mod.userScript, ... }) local task = task:new(core) local buf = ffi.new("char[?]", #args + 1) ffi.copy(buf, args) dpdkc.launch_lua_core(core, task.id, buf) return task end --- launches the lua file on the first free core function mod.launchLua(...) checkCore() for i = 2, #cores do -- skip master local core = cores[i] local status = dpdkc.rte_eal_get_lcore_state(core) if status == dpdkc.FINISHED then dpdkc.rte_eal_wait_lcore(core) -- should be guaranteed to be in WAIT state now according to DPDK documentation status = dpdkc.rte_eal_get_lcore_state(core) end if status == dpdkc.WAIT then -- core is in WAIT state return mod.launchLuaOnCore(core, ...) end end error("not enough cores to start this lua task") end ffi.cdef [[ int usleep(unsigned int usecs); ]] --- waits until all slave cores have finished their jobs function mod.waitForSlaves() while true do local allCoresFinished = true for i = 2, #cores do -- skip master local core = cores[i] if dpdkc.rte_eal_get_lcore_state(core) == dpdkc.RUNNING then allCoresFinished = false break end end if allCoresFinished then return end ffi.C.usleep(100) end end function mod.getCores() return cores end --- get the CPU's TSC function mod.getCycles() return dpdkc.rte_rdtsc() end --- get the TSC frequency function mod.getCyclesFrequency() return tonumber(dpdkc.rte_get_tsc_hz()) end --- gets the time in seconds function mod.getTime() return tonumber(mod.getCycles()) / tonumber(mod.getCyclesFrequency()) end --- set total run time of the test (to be called from master core on startup, shared between all cores) function mod.setRuntime(time) dpdkc.set_runtime(time * 1000) end --- Returns false once the app receives SIGTERM or SIGINT, the time set via setRuntime expires, or when a thread calls dpdk.stop(). -- @param extraTime additional time in milliseconds before false will be returned function mod.running(extraTime) return dpdkc.is_running(extraTime or 0) == 1 -- luajit-2.0.3 does not like bool return types (TRACE NYI: unsupported C function type) end --- request all tasks to exit function mod.stop() dpdkc.set_runtime(0) end --- Delay by t milliseconds. Note that this does not sleep the actual thread; --- the time is spent in a busy wait loop by DPDK. function mod.sleepMillis(t) dpdkc.rte_delay_ms_export(t) end --- Delay by t microseconds. Note that this does not sleep the actual thread; --- the time is spent in a busy wait loop by DPDK. This means that this sleep --- is somewhat more accurate than relying on the OS. function mod.sleepMicros(t) dpdkc.rte_delay_us_export(t) end --- Get the core and socket id for the current thread function mod.getCore() return dpdkc.get_current_core(), dpdkc.get_current_socket() end return mod
fix LuaDoc for dpdk.running()
fix LuaDoc for dpdk.running()
Lua
mit
emmericp/MoonGen,schoenb/MoonGen,slyon/MoonGen,duk3luk3/MoonGen,wenhuizhang/MoonGen,dschoeffm/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,scholzd/MoonGen,pavel-odintsov/MoonGen,slyon/MoonGen,scholzd/MoonGen,pavel-odintsov/MoonGen,emmericp/MoonGen,slyon/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,werpat/MoonGen,bmichalo/MoonGen,pavel-odintsov/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,schoenb/MoonGen,bmichalo/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,werpat/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,scholzd/MoonGen,werpat/MoonGen,wenhuizhang/MoonGen,atheurer/MoonGen,NetronomeMoongen/MoonGen,slyon/MoonGen,atheurer/MoonGen,schoenb/MoonGen,duk3luk3/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen
3bbc9976fbdb8163776b4a0ad68d020eb59262be
SFLib.lua
SFLib.lua
--[[---------------------------------------] [ Starfall Library ] [ By Colonel Thirty Two ] [---------------------------------------]] local SFLib = SFLib or {} function SFLib.limitString(text, length) if #text <= length then return text else return string.sub(text, 1, length) .. "..." end end -- Operators SFLib.optree_inv = { add = "+", sub = "-", mul = "*", div = "/", mod = "%", exp = "^", ass = "=", aadd = "+=", asub = "-=", amul = "*=", adiv = "/=", inc = "++", dec = "--", eq = "==", neq = "!=", lth = "<", geq = ">=", leq = "<=", gth = ">", ["not"] = "not", ["and"] = "and", ["or"] = "or", qsm = "?", col = ":", def = "?:", com = ",", lpa = "(", rpa = ")", rcb = "{", lcb = "}", lsb = "[", rsb = "]", trg = "~", imp = "->", } SFLib.optree = {} for token,op in pairs(SFLib.optree_inv) do local current = SFLib.optree for i = 1,#op do local c = op:sub(i,i) local nxt = current[c] if not nxt then nxt = {} current[c] = nxt end if i == #op then nxt[1] = token else if not nxt[2] then nxt[2] = {} end current = nxt[2] end end end -- Types SFLib.types = {} function SFLib:AddType(name, tbl) if types[name] == nil then self.types[name] = tbl else error("Starfall: Type "..name.." defined more than once") end end SFLib.functions = {} function SFLib:FuncToStr(name, base, args) -- Returns a string representation of a function. -- Note: the function doesn't have to be defined. local out = "" if base then out = base..":" end out = out .. name for _,arg in ipairs(args) do out = out .. arg .. "," end return out:sub(1,out:len()-1) end function SFLib:FuncTypToStr(base, args) -- Returns the string type of a function -- [base]:arg1,arg2,arg3 -- There is a ":" even if no base type is available local imploded = string.Implode(args,",") return (base or "") .. ":" .. imploded end local function get_or_add(tbl, key) if tbl[key] then return tbl[key] end else tbl[key] = {} return tbl[key] end end function SFLib:AddFunction(name, base, args, rt, func) local node = get_or_add(self.functions, name) local key = (base or "")..":"..string.Implode(args,",") if node[key] then error("Starfall: Function " .. self:FuncToStr(name, base, args) .. " defined more than once") end node[key] = func node["rt:"..key] = rt end function SFLib:GetFunction(name, base, args) local node = SFLib.functions[name] if not node then return nil end local imploded = string.Implode(",",args) if node[imploded] then -- Exact match return node[imploded], node["rt:"..imploded] end -- No match, look for ellipsis for i=#args,0,-1 do local str = "" for j=1,i do str = str .. args[j] .. "," end str = str .. "..." if node[str] then return node[str], node["rt:"..str] end end -- No match return nil end -- ---------------------------------------- -- -- Per-Player Ops Counters -- -- ---------------------------------------- -- SFLib.ops = {} hook.Add("PlayerInitialSpawn", "sf_perplayer_ops", function(ply) ops[ply] = 0 end) hook.Add("PlayerDisconnected", "sf_perplayer_ops_dc",function(ply) ops[ply] = nil end)
--[[---------------------------------------] [ Starfall Library ] [ By Colonel Thirty Two ] [---------------------------------------]] AddCSLuaFile("SFLib.lua") SFLib = SFLib or {} function SFLib.limitString(text, length) if #text <= length then return text else return string.sub(text, 1, length) .. "..." end end -- Operators SFLib.optree_inv = { add = "+", sub = "-", mul = "*", div = "/", mod = "%", exp = "^", ass = "=", aadd = "+=", asub = "-=", amul = "*=", adiv = "/=", inc = "++", dec = "--", eq = "==", neq = "!=", lth = "<", geq = ">=", leq = "<=", gth = ">", ["not"] = "not", ["and"] = "and", ["or"] = "or", qsm = "?", col = ":", def = "?:", com = ",", lpa = "(", rpa = ")", rcb = "{", lcb = "}", lsb = "[", rsb = "]", trg = "~", imp = "->", } SFLib.optree = {} for token,op in pairs(SFLib.optree_inv) do local current = SFLib.optree for i = 1,#op do local c = op:sub(i,i) local nxt = current[c] if not nxt then nxt = {} current[c] = nxt end if i == #op then nxt[1] = token else if not nxt[2] then nxt[2] = {} end current = nxt[2] end end end -- Types SFLib.types = {} function SFLib:AddType(name, tbl) if types[name] == nil then self.types[name] = tbl else error("Starfall: Type "..name.." defined more than once") end end SFLib.functions = {} function SFLib:FuncToStr(name, base, args) -- Returns a string representation of a function. -- Note: the function doesn't have to be defined. local out = "" if base then out = base..":" end out = out .. name for _,arg in ipairs(args) do out = out .. arg .. "," end return out:sub(1,out:len()-1) end function SFLib:FuncTypToStr(base, args) -- Returns the string type of a function -- [base]:arg1,arg2,arg3 -- There is a ":" even if no base type is available local imploded = string.Implode(args,",") return (base or "") .. ":" .. imploded end local function get_or_add(tbl, key) if tbl[key] then return tbl[key] else tbl[key] = {} return tbl[key] end end function SFLib:AddFunction(name, base, args, rt, func) local node = get_or_add(self.functions, name) local key = (base or "")..":"..string.Implode(args,",") if node[key] then error("Starfall: Function " .. self:FuncToStr(name, base, args) .. " defined more than once") end node[key] = func node["rt:"..key] = rt end function SFLib:GetFunction(name, base, args) local node = SFLib.functions[name] if not node then return nil end local imploded = string.Implode(",",args) if node[imploded] then -- Exact match return node[imploded], node["rt:"..imploded] end -- No match, look for ellipsis for i=#args,0,-1 do local str = "" for j=1,i do str = str .. args[j] .. "," end str = str .. "..." if node[str] then return node[str], node["rt:"..str] end end -- No match return nil end -- ---------------------------------------- -- -- Per-Player Ops Counters -- -- ---------------------------------------- -- SFLib.ops = {} hook.Add("PlayerInitialSpawn", "sf_perplayer_ops", function(ply) SFLib.ops[ply] = 0 end) hook.Add("PlayerDisconnected", "sf_perplayer_ops_dc",function(ply) SFLib.ops[ply] = nil end)
[starfall/SFLib.lua] Fixed some syntax errors
[starfall/SFLib.lua] Fixed some syntax errors
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall
d058a92d5ae177e54280c35738b8711b0174149e
mod_adhoc_cmd_modules/mod_adhoc_cmd_modules.lua
mod_adhoc_cmd_modules/mod_adhoc_cmd_modules.lua
-- Copyright (C) 2009-2010 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local prosody = _G.prosody; local hosts = prosody.hosts; require "util.iterators"; local dataforms_new = require "util.dataforms".new; local array = require "util.array"; local modulemanager = require "modulemanager"; local adhoc_new = module:require "adhoc".new; function list_modules_handler(self, data, state) local result = dataforms_new { title = "List of loaded modules"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#list" }; { name = "modules", type = "text-multi", label = "The following modules are loaded:" }; }; local modules = array.collect(keys(hosts[data.to].modules)):sort():concat("\n"); return { status = "completed", result = { layout = result; data = { modules = modules } } }; end function load_module_handler(self, data, state) local layout = dataforms_new { title = "Load module"; instructions = "Specify the module to be loaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#load" }; { name = "module", type = "text-single", required = true, label = "Module to be loaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end if modulemanager.is_loaded(data.to, fields.module) then return { status = "completed", info = "Module already loaded" }; end local ok, err = modulemanager.load(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully loaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to load module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err or "<unspecified>")..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = layout }, "executing"; end end -- TODO: Allow reloading multiple modules (depends on list-multi) function reload_modules_handler(self, data, state) local layout = dataforms_new { title = "Reload module"; instructions = "Select the module to be reloaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#reload" }; { name = "module", type = "list-single", required = true, label = "Module to be reloaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end local ok, err = modulemanager.reload(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully reloaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to reload module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err)..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing"; end end -- TODO: Allow unloading multiple modules (depends on list-multi) function unload_modules_handler(self, data, state) local layout = dataforms_new { title = "Unload module"; instructions = "Select the module to be unloaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#unload" }; { name = "module", type = "list-single", required = true, label = "Module to be unloaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end local ok, err = modulemanager.unload(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully unloaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to unload module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err)..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing"; end end local list_modules_desc = adhoc_new("List loaded modules", "http://prosody.im/protocol/modules#list", list_modules_handler, "admin"); local load_module_desc = adhoc_new("Load module", "http://prosody.im/protocol/modules#load", load_module_handler, "admin"); local reload_modules_desc = adhoc_new("Reload module", "http://prosody.im/protocol/modules#reload", reload_modules_handler, "admin"); local unload_modules_desc = adhoc_new("Unload module", "http://prosody.im/protocol/modules#unload", unload_modules_handler, "admin"); module:add_item("adhoc", list_modules_desc); module:add_item("adhoc", load_module_desc); module:add_item("adhoc", reload_modules_desc); module:add_item("adhoc", unload_modules_desc);
-- Copyright (C) 2009-2010 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local prosody = _G.prosody; local hosts = prosody.hosts; require "util.iterators"; local dataforms_new = require "util.dataforms".new; local array = require "util.array"; local modulemanager = require "modulemanager"; local adhoc_new = module:require "adhoc".new; function list_modules_handler(self, data, state) local result = dataforms_new { title = "List of loaded modules"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#list" }; { name = "modules", type = "text-multi", label = "The following modules are loaded:" }; }; local modules = array.collect(keys(hosts[data.to].modules)):sort():concat("\n"); return { status = "completed", result = { layout = result; data = { modules = modules } } }; end function load_module_handler(self, data, state) local layout = dataforms_new { title = "Load module"; instructions = "Specify the module to be loaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#load" }; { name = "module", type = "text-single", required = true, label = "Module to be loaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module." } }; end if modulemanager.is_loaded(data.to, fields.module) then return { status = "completed", info = "Module already loaded" }; end local ok, err = modulemanager.load(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully loaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to load module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err or "<unspecified>")..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = layout }, "executing"; end end -- TODO: Allow reloading multiple modules (depends on list-multi) function reload_modules_handler(self, data, state) local layout = dataforms_new { title = "Reload module"; instructions = "Select the module to be reloaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#reload" }; { name = "module", type = "list-single", required = true, label = "Module to be reloaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end local ok, err = modulemanager.reload(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully reloaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to reload module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err)..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing"; end end -- TODO: Allow unloading multiple modules (depends on list-multi) function unload_modules_handler(self, data, state) local layout = dataforms_new { title = "Unload module"; instructions = "Select the module to be unloaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#unload" }; { name = "module", type = "list-single", required = true, label = "Module to be unloaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end local ok, err = modulemanager.unload(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully unloaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to unload module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err)..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing"; end end local list_modules_desc = adhoc_new("List loaded modules", "http://prosody.im/protocol/modules#list", list_modules_handler, "admin"); local load_module_desc = adhoc_new("Load module", "http://prosody.im/protocol/modules#load", load_module_handler, "admin"); local reload_modules_desc = adhoc_new("Reload module", "http://prosody.im/protocol/modules#reload", reload_modules_handler, "admin"); local unload_modules_desc = adhoc_new("Unload module", "http://prosody.im/protocol/modules#unload", unload_modules_handler, "admin"); module:add_item("adhoc", list_modules_desc); module:add_item("adhoc", load_module_desc); module:add_item("adhoc", reload_modules_desc); module:add_item("adhoc", unload_modules_desc);
mod_adhoc_cmd_modules: Fix error message
mod_adhoc_cmd_modules: Fix error message
Lua
mit
olax/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,1st8/prosody-modules,brahmi2/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,prosody-modules/import,jkprg/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,either1/prosody-modules,apung/prosody-modules,either1/prosody-modules,softer/prosody-modules,Craige/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,NSAKEY/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,heysion/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,obelisk21/prosody-modules,joewalker/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,drdownload/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,apung/prosody-modules,heysion/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,crunchuser/prosody-modules,heysion/prosody-modules,LanceJenkinZA/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,olax/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,mmusial/prosody-modules,mardraze/prosody-modules,jkprg/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules
04d461bceab027028f6df19e8032e0df517f071c
share/lua/playlist/mpora.lua
share/lua/playlist/mpora.lua
--[[ $Id$ Copyright © 2009 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "video.mpora.com/watch/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.*)\" />" ) end if string.match( line, "image_src" ) then _,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" ) end if string.match( line, "filmID" ) then _,_,video = string.find( line, "var filmID = \'(.*)\';") end end if not name or not arturl or not video then return nil end -- Try and get URL for SD video. sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/") if not sd then return nil end page = sd:read( 65653 ) sdurl = string.match( page, "url=\"(.*)\" />") page = nil table.insert( p, { path = sdurl; name = name; arturl = arturl; } ) -- Try and check if HD video is available. checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" ) if not checkhd then return nil end page = checkhd:read( 65653 ) hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) ) page = nil if hashd then hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/") page = hd:read( 65653 ) hdurl = string.match( page, "url=\"(.*)\" />") table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl } ) end return p end
--[[ $Id$ Copyright © 2009 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "video.mpora.com/watch/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.*)\" />" ) end if string.match( line, "image_src" ) then _,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" ) end if string.match( line, "video_src" ) then _,_,video = string.find( line, "href=\"http://video\.mpora\.com/ep/(.*).swf\" />" ) end end if not name or not arturl or not video then return nil end -- Try and get URL for SD video. sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/") if not sd then return nil end page = sd:read( 65653 ) sdurl = string.match( page, "url=\"(.*)\" />") page = nil table.insert( p, { path = sdurl; name = name; arturl = arturl; } ) -- Try and check if HD video is available. checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" ) if not checkhd then return nil end page = checkhd:read( 65653 ) hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) ) page = nil if hashd then hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/") page = hd:read( 65653 ) hdurl = string.match( page, "url=\"(.*)\" />") table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl; } ) end return p end
LUA: Fix MPORA playlist parser.
LUA: Fix MPORA playlist parser.
Lua
lgpl-2.1
vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.1
212242c4341d2d150bfae7dd67456e908754803f
openresty/app.lua
openresty/app.lua
local _M = {} local cjson = require "cjson" local mysql = require "resty.mysql" local math = require "math" local encode = cjson.encode local random = math.random local insert = table.insert local mysqlconn = { host = "DBHOSTNAME", port = 3306, database = "hello_world", user = "benchmarkdbuser", password = "benchmarkdbpass" } function _M.handler(ngx) ngx.header.content_type = 'application/json' if ngx.var.uri == '/json' then local resp = {message = "Hello, World!"} ngx.print( encode(resp) ) elseif ngx.var.uri == '/db' then local db, err = mysql:new() local ok, err = db:connect(mysqlconn) local num_queries = tonumber(ngx.var.arg_queries) or 1 local worlds = {} for i=1, num_queries do local wid = random(1, 10000) insert(worlds, db:query('SELECT * FROM World WHERE id = '..wid)[1]) end ngx.print( encode(worlds) ) local ok, err = db:set_keepalive(0, 256) end end return _M
local _M = {} local cjson = require "cjson" local mysql = require "resty.mysql" local math = require "math" local encode = cjson.encode local random = math.random local insert = table.insert local mysqlconn = { host = "DBHOSTNAME", port = 3306, database = "hello_world", user = "benchmarkdbuser", password = "benchmarkdbpass" } function _M.handler(ngx) ngx.header.content_type = 'application/json' if ngx.var.uri == '/json' then local resp = {message = "Hello, World!"} ngx.print( encode(resp) ) elseif ngx.var.uri == '/db' then local db, err = mysql:new() local ok, err = db:connect(mysqlconn) local num_queries = tonumber(ngx.var.arg_queries) or 1 local worlds = {} for i=1, num_queries do local wid = random(1, 10000) insert(worlds, db:query('SELECT * FROM World WHERE id = '..wid)[1]) end ngx.print( encode(worlds) ) local ok, err = db:set_keepalive(0, 256) end end return _M
fix formatting
fix formatting
Lua
bsd-3-clause
Eyepea/FrameworkBenchmarks,grob/FrameworkBenchmarks,jamming/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,dmacd/FB-try1,julienschmidt/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,herloct/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,testn/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,methane/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,joshk/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,denkab/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,testn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,khellang/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,valyala/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,jamming/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,methane/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,grob/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,torhve/FrameworkBenchmarks,herloct/FrameworkBenchmarks,methane/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,joshk/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,leafo/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,grob/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,testn/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,methane/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,testn/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zapov/FrameworkBenchmarks,jamming/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zapov/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,zloster/FrameworkBenchmarks,joshk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,grob/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Verber/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,khellang/FrameworkBenchmarks,valyala/FrameworkBenchmarks,dmacd/FB-try1,Jesterovskiy/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zloster/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Verber/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,khellang/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,methane/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jamming/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,torhve/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,doom369/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,denkab/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sxend/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jamming/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sxend/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zloster/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Verber/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,actframework/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,khellang/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,dmacd/FB-try1,jeevatkm/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,leafo/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,methane/FrameworkBenchmarks,methane/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,dmacd/FB-try1,Rayne/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Verber/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zapov/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,doom369/FrameworkBenchmarks,testn/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,denkab/FrameworkBenchmarks,leafo/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,valyala/FrameworkBenchmarks,joshk/FrameworkBenchmarks,zloster/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zapov/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,torhve/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,actframework/FrameworkBenchmarks,actframework/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,doom369/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,herloct/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,grob/FrameworkBenchmarks,Verber/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,khellang/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,herloct/FrameworkBenchmarks,herloct/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,methane/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,actframework/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sxend/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,dmacd/FB-try1,victorbriz/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,torhve/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zloster/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jamming/FrameworkBenchmarks,doom369/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,torhve/FrameworkBenchmarks,grob/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,denkab/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,dmacd/FB-try1,greenlaw110/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zloster/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,actframework/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,herloct/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,dmacd/FB-try1,denkab/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,herloct/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,testn/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,actframework/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sgml/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,denkab/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,dmacd/FB-try1,xitrum-framework/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,torhve/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,leafo/FrameworkBenchmarks,leafo/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sxend/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,dmacd/FB-try1,zhuochenKIDD/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,jamming/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,actframework/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,grob/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,grob/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jamming/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,methane/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sxend/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,valyala/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sgml/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,torhve/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sgml/FrameworkBenchmarks,actframework/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zapov/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,khellang/FrameworkBenchmarks,valyala/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,torhve/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,grob/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,jamming/FrameworkBenchmarks,torhve/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,leafo/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,grob/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Verber/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,testn/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sxend/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jamming/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,actframework/FrameworkBenchmarks,valyala/FrameworkBenchmarks,torhve/FrameworkBenchmarks,doom369/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,denkab/FrameworkBenchmarks,sxend/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,valyala/FrameworkBenchmarks,valyala/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,doom369/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,methane/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,denkab/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,valyala/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sgml/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,valyala/FrameworkBenchmarks,khellang/FrameworkBenchmarks,herloct/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sgml/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,torhve/FrameworkBenchmarks,zloster/FrameworkBenchmarks,joshk/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,grob/FrameworkBenchmarks,zapov/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,joshk/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,khellang/FrameworkBenchmarks,doom369/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,herloct/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,leafo/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,testn/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,dmacd/FB-try1,steveklabnik/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,testn/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Verber/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sgml/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jamming/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,sgml/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,sgml/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zloster/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,herloct/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,joshk/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zapov/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,leafo/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,leafo/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,methane/FrameworkBenchmarks,zapov/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,herloct/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Verber/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zloster/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,grob/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,valyala/FrameworkBenchmarks,sxend/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,dmacd/FB-try1,dmacd/FB-try1,sanjoydesk/FrameworkBenchmarks,khellang/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,leafo/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,actframework/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,testn/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,grob/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,testn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sxend/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,valyala/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Verber/FrameworkBenchmarks,joshk/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,khellang/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,valyala/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zloster/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,doom369/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,jamming/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sgml/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,khellang/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,methane/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,joshk/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,testn/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,methane/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Verber/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,joshk/FrameworkBenchmarks,denkab/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Verber/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,sgml/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,leafo/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,khellang/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,testn/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zapov/FrameworkBenchmarks,grob/FrameworkBenchmarks,actframework/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,doom369/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sxend/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Verber/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,testn/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zloster/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Verber/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jamming/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jamming/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,sgml/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,methane/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,herloct/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,leafo/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,valyala/FrameworkBenchmarks,kbrock/FrameworkBenchmarks
19d100b5de7e3f6248611e8fa86d6754acd04e72
mod_smacks/mod_smacks.lua
mod_smacks/mod_smacks.lua
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.sends2s or session.send; local function new_send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.clone(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end if session.sends2s then session.sends2s = new_send; else session.send = new_send; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> (origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = st.reply(queue[i]); if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, reply); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end end return _destroy_session(session, err); end
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local timer = require "util.timer"; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local resume_timeout = 300; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.sends2s or session.send; local function new_send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.clone(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end if session.sends2s then session.sends2s = new_send; else session.send = new_send; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> (origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = st.reply(queue[i]); if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, reply); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then if not session.resumption_token then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end else session.hibernating = true; timer.add_task(resume_timeout, function () if session.hibernating then session.resumption_token = nil; sessionmanager.destroy_session(session); -- Re-destroy end end); return; -- Postpone destruction for now end end return _destroy_session(session, err); end
mod_smacks: Fixes for monkey-patched sessionmanager.destroy to handle stream resumption, and to fall back to stock destroy() if the session is not smacks-enabled.
mod_smacks: Fixes for monkey-patched sessionmanager.destroy to handle stream resumption, and to fall back to stock destroy() if the session is not smacks-enabled.
Lua
mit
either1/prosody-modules,crunchuser/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,crunchuser/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,prosody-modules/import,drdownload/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,olax/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,dhotson/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,apung/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,LanceJenkinZA/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,prosody-modules/import,1st8/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,mmusial/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,1st8/prosody-modules,prosody-modules/import,joewalker/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,prosody-modules/import,guilhem/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,drdownload/prosody-modules
5412893954dd557c17d38971e010baf1f7528ce4
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <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") m = Map("network", translate("a_n_routes"), translate("a_n_routes1")) local routes6 = luci.sys.net.routes6() if not arg or not arg[1] then local routes = luci.sys.net.routes() v = m:section(Table, routes, translate("a_n_routes_kernel4")) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end if routes6 then v = m:section(Table, routes6, translate("a_n_routes_kernel6")) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes6[section].device) or routes6[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v:option(DummyValue, "gateway", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return string.format( "%08X", routes6[section].metric ) end end end s = m:section(TypedSection, "route", translate("a_n_routes_static4")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("interface")) luci.tools.webadmin.cbi_add_networks(iface) if not arg or not arg[1] then net.titleref = iface.titleref end s:option(Value, "target", translate("target"), translate("a_n_r_target1")) s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true s:option(Value, "gateway", translate("gateway")) if routes6 then s = m:section(TypedSection, "route6", translate("a_n_routes_static6")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("interface")) luci.tools.webadmin.cbi_add_networks(iface) if not arg or not arg[1] then net.titleref = iface.titleref end s:option(Value, "target", translate("target"), translate("a_n_r_target6")) s:option(Value, "gateway", translate("gateway6")).rmempty = true end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <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") m = Map("network", translate("a_n_routes"), translate("a_n_routes1")) local routes6 = luci.sys.net.routes6() local bit = require "bit" if not arg or not arg[1] then local routes = luci.sys.net.routes() v = m:section(Table, routes, translate("a_n_routes_kernel4")) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end if routes6 then v = m:section(Table, routes6, translate("a_n_routes_kernel6")) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes6[section].device) or routes6[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v:option(DummyValue, "gateway", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) local metr = routes6[section].metric local lower = bit.band(metr, 0xffff) local higher = bit.rshift(bit.band(metr, 0xffff0000), 16) return "%04X%04X" % {higher, lower} end end end s = m:section(TypedSection, "route", translate("a_n_routes_static4")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("interface")) luci.tools.webadmin.cbi_add_networks(iface) if not arg or not arg[1] then net.titleref = iface.titleref end s:option(Value, "target", translate("target"), translate("a_n_r_target1")) s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true s:option(Value, "gateway", translate("gateway")) if routes6 then s = m:section(TypedSection, "route6", translate("a_n_routes_static6")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("interface")) luci.tools.webadmin.cbi_add_networks(iface) if not arg or not arg[1] then net.titleref = iface.titleref end s:option(Value, "target", translate("target"), translate("a_n_r_target6")) s:option(Value, "gateway", translate("gateway6")).rmempty = true end return m
Fixed an overflow error with IPv6 route metric
Fixed an overflow error with IPv6 route metric
Lua
apache-2.0
ReclaimYourPrivacy/cloak-luci,dismantl/luci-0.12,thesabbir/luci,RuiChen1113/luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,chris5560/openwrt-luci,oneru/luci,Kyklas/luci-proto-hso,ollie27/openwrt_luci,981213/luci-1,Hostle/luci,tcatm/luci,tobiaswaldvogel/luci,Noltari/luci,kuoruan/luci,ff94315/luci-1,cshore/luci,RuiChen1113/luci,kuoruan/luci,db260179/openwrt-bpi-r1-luci,oyido/luci,shangjiyu/luci-with-extra,aa65535/luci,nmav/luci,keyidadi/luci,Noltari/luci,oyido/luci,harveyhu2012/luci,male-puppies/luci,remakeelectric/luci,keyidadi/luci,kuoruan/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,lbthomsen/openwrt-luci,bittorf/luci,lbthomsen/openwrt-luci,slayerrensky/luci,tobiaswaldvogel/luci,schidler/ionic-luci,tcatm/luci,oyido/luci,RuiChen1113/luci,zhaoxx063/luci,thess/OpenWrt-luci,slayerrensky/luci,lcf258/openwrtcn,aa65535/luci,dwmw2/luci,nwf/openwrt-luci,obsy/luci,male-puppies/luci,dwmw2/luci,slayerrensky/luci,rogerpueyo/luci,artynet/luci,Noltari/luci,fkooman/luci,cshore/luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,shangjiyu/luci-with-extra,Hostle/luci,dwmw2/luci,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,forward619/luci,Wedmer/luci,981213/luci-1,rogerpueyo/luci,Wedmer/luci,forward619/luci,jlopenwrtluci/luci,david-xiao/luci,kuoruan/lede-luci,ff94315/luci-1,aa65535/luci,remakeelectric/luci,cshore/luci,kuoruan/lede-luci,lcf258/openwrtcn,dismantl/luci-0.12,keyidadi/luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,Noltari/luci,cshore/luci,nmav/luci,MinFu/luci,openwrt/luci,male-puppies/luci,NeoRaider/luci,schidler/ionic-luci,david-xiao/luci,shangjiyu/luci-with-extra,zhaoxx063/luci,Wedmer/luci,LuttyYang/luci,mumuqz/luci,taiha/luci,ff94315/luci-1,Hostle/openwrt-luci-multi-user,Sakura-Winkey/LuCI,florian-shellfire/luci,fkooman/luci,cappiewu/luci,dismantl/luci-0.12,rogerpueyo/luci,kuoruan/luci,maxrio/luci981213,Wedmer/luci,kuoruan/luci,urueedi/luci,RuiChen1113/luci,wongsyrone/luci-1,openwrt/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,sujeet14108/luci,tobiaswaldvogel/luci,ollie27/openwrt_luci,rogerpueyo/luci,Wedmer/luci,zhaoxx063/luci,Kyklas/luci-proto-hso,urueedi/luci,lbthomsen/openwrt-luci,981213/luci-1,tcatm/luci,palmettos/cnLuCI,981213/luci-1,palmettos/test,jchuang1977/luci-1,lcf258/openwrtcn,jchuang1977/luci-1,bright-things/ionic-luci,NeoRaider/luci,palmettos/test,kuoruan/lede-luci,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,teslamint/luci,joaofvieira/luci,palmettos/test,dwmw2/luci,jlopenwrtluci/luci,NeoRaider/luci,Hostle/luci,NeoRaider/luci,Kyklas/luci-proto-hso,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,deepak78/new-luci,tcatm/luci,obsy/luci,ff94315/luci-1,florian-shellfire/luci,NeoRaider/luci,keyidadi/luci,daofeng2015/luci,bittorf/luci,LuttyYang/luci,harveyhu2012/luci,fkooman/luci,fkooman/luci,maxrio/luci981213,tobiaswaldvogel/luci,fkooman/luci,Sakura-Winkey/LuCI,kuoruan/luci,florian-shellfire/luci,deepak78/new-luci,joaofvieira/luci,ff94315/luci-1,schidler/ionic-luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,shangjiyu/luci-with-extra,oyido/luci,opentechinstitute/luci,joaofvieira/luci,Wedmer/luci,forward619/luci,marcel-sch/luci,oneru/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,Noltari/luci,joaofvieira/luci,marcel-sch/luci,male-puppies/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,daofeng2015/luci,obsy/luci,wongsyrone/luci-1,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,forward619/luci,forward619/luci,forward619/luci,opentechinstitute/luci,Sakura-Winkey/LuCI,tcatm/luci,mumuqz/luci,obsy/luci,MinFu/luci,Kyklas/luci-proto-hso,jorgifumi/luci,chris5560/openwrt-luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,marcel-sch/luci,urueedi/luci,kuoruan/lede-luci,lcf258/openwrtcn,harveyhu2012/luci,maxrio/luci981213,bright-things/ionic-luci,ollie27/openwrt_luci,zhaoxx063/luci,artynet/luci,Noltari/luci,Sakura-Winkey/LuCI,maxrio/luci981213,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,bittorf/luci,dwmw2/luci,marcel-sch/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,thesabbir/luci,nmav/luci,artynet/luci,forward619/luci,david-xiao/luci,nmav/luci,lcf258/openwrtcn,zhaoxx063/luci,MinFu/luci,nwf/openwrt-luci,jorgifumi/luci,cshore-firmware/openwrt-luci,Wedmer/luci,thesabbir/luci,Hostle/luci,shangjiyu/luci-with-extra,joaofvieira/luci,Hostle/openwrt-luci-multi-user,david-xiao/luci,oyido/luci,tobiaswaldvogel/luci,cappiewu/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,kuoruan/lede-luci,chris5560/openwrt-luci,openwrt/luci,981213/luci-1,jchuang1977/luci-1,MinFu/luci,opentechinstitute/luci,jlopenwrtluci/luci,kuoruan/lede-luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,thesabbir/luci,ff94315/luci-1,nwf/openwrt-luci,rogerpueyo/luci,oyido/luci,openwrt-es/openwrt-luci,palmettos/cnLuCI,kuoruan/lede-luci,obsy/luci,florian-shellfire/luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,RuiChen1113/luci,openwrt/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,jorgifumi/luci,urueedi/luci,nwf/openwrt-luci,keyidadi/luci,oneru/luci,schidler/ionic-luci,Hostle/openwrt-luci-multi-user,jchuang1977/luci-1,NeoRaider/luci,aa65535/luci,wongsyrone/luci-1,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,artynet/luci,fkooman/luci,dismantl/luci-0.12,deepak78/new-luci,deepak78/new-luci,lbthomsen/openwrt-luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,maxrio/luci981213,jorgifumi/luci,teslamint/luci,daofeng2015/luci,981213/luci-1,male-puppies/luci,sujeet14108/luci,mumuqz/luci,teslamint/luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,tcatm/luci,ollie27/openwrt_luci,daofeng2015/luci,remakeelectric/luci,nmav/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,ollie27/openwrt_luci,schidler/ionic-luci,dismantl/luci-0.12,david-xiao/luci,palmettos/test,LuttyYang/luci,Noltari/luci,palmettos/cnLuCI,harveyhu2012/luci,thesabbir/luci,tobiaswaldvogel/luci,MinFu/luci,maxrio/luci981213,wongsyrone/luci-1,dismantl/luci-0.12,slayerrensky/luci,Hostle/luci,cappiewu/luci,chris5560/openwrt-luci,dismantl/luci-0.12,lbthomsen/openwrt-luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,joaofvieira/luci,taiha/luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,palmettos/test,artynet/luci,Sakura-Winkey/LuCI,florian-shellfire/luci,Noltari/luci,fkooman/luci,bright-things/ionic-luci,hnyman/luci,daofeng2015/luci,cappiewu/luci,teslamint/luci,thesabbir/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,taiha/luci,LazyZhu/openwrt-luci-trunk-mod,jorgifumi/luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,palmettos/test,ff94315/luci-1,palmettos/test,teslamint/luci,Noltari/luci,dwmw2/luci,palmettos/cnLuCI,bright-things/ionic-luci,deepak78/new-luci,slayerrensky/luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,obsy/luci,tcatm/luci,marcel-sch/luci,lbthomsen/openwrt-luci,marcel-sch/luci,urueedi/luci,palmettos/test,chris5560/openwrt-luci,artynet/luci,lbthomsen/openwrt-luci,RuiChen1113/luci,hnyman/luci,obsy/luci,nmav/luci,tcatm/luci,shangjiyu/luci-with-extra,thesabbir/luci,sujeet14108/luci,cappiewu/luci,harveyhu2012/luci,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,thess/OpenWrt-luci,nwf/openwrt-luci,thess/OpenWrt-luci,NeoRaider/luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,oyido/luci,taiha/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,Wedmer/luci,cshore/luci,bittorf/luci,NeoRaider/luci,lcf258/openwrtcn,bittorf/luci,MinFu/luci,marcel-sch/luci,harveyhu2012/luci,lcf258/openwrtcn,hnyman/luci,wongsyrone/luci-1,oneru/luci,openwrt-es/openwrt-luci,Hostle/luci,male-puppies/luci,cshore-firmware/openwrt-luci,david-xiao/luci,deepak78/new-luci,ollie27/openwrt_luci,jorgifumi/luci,mumuqz/luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,remakeelectric/luci,bright-things/ionic-luci,rogerpueyo/luci,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,opentechinstitute/luci,mumuqz/luci,lcf258/openwrtcn,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,cshore/luci,remakeelectric/luci,lcf258/openwrtcn,aa65535/luci,david-xiao/luci,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,fkooman/luci,remakeelectric/luci,cshore/luci,aa65535/luci,oyido/luci,marcel-sch/luci,ff94315/luci-1,Hostle/luci,LuttyYang/luci,jlopenwrtluci/luci,joaofvieira/luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,maxrio/luci981213,thess/OpenWrt-luci,LuttyYang/luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,slayerrensky/luci,jlopenwrtluci/luci,slayerrensky/luci,opentechinstitute/luci,hnyman/luci,forward619/luci,nmav/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,nmav/luci,Hostle/luci,male-puppies/luci,mumuqz/luci,wongsyrone/luci-1,remakeelectric/luci,zhaoxx063/luci,teslamint/luci,rogerpueyo/luci,daofeng2015/luci,MinFu/luci,shangjiyu/luci-with-extra,openwrt/luci,artynet/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,bittorf/luci,sujeet14108/luci,artynet/luci,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,981213/luci-1,cshore-firmware/openwrt-luci,dwmw2/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,sujeet14108/luci,thess/OpenWrt-luci,joaofvieira/luci,dwmw2/luci,zhaoxx063/luci,chris5560/openwrt-luci,aa65535/luci,jchuang1977/luci-1,sujeet14108/luci,male-puppies/luci,teslamint/luci,kuoruan/luci,oneru/luci,thess/OpenWrt-luci,LazyZhu/openwrt-luci-trunk-mod,bright-things/ionic-luci,teslamint/luci,keyidadi/luci,aa65535/luci,opentechinstitute/luci,remakeelectric/luci,bittorf/luci,Kyklas/luci-proto-hso,deepak78/new-luci,kuoruan/luci,bittorf/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,oneru/luci,hnyman/luci,artynet/luci,taiha/luci,bright-things/ionic-luci,thesabbir/luci,florian-shellfire/luci,oneru/luci,maxrio/luci981213,jchuang1977/luci-1,jorgifumi/luci,oneru/luci,zhaoxx063/luci,palmettos/cnLuCI,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,taiha/luci,schidler/ionic-luci,thess/OpenWrt-luci,openwrt/luci,Kyklas/luci-proto-hso,florian-shellfire/luci,deepak78/new-luci,nwf/openwrt-luci,openwrt/luci,urueedi/luci,nmav/luci,cappiewu/luci,hnyman/luci
88f6405b1bba3317d572586df17c7ac18dc2f5e2
modules/admin-full/luasrc/model/cbi/admin_index/luci.lua
modules/admin-full/luasrc/model/cbi/admin_index/luci.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 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.config") m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>.")) local fs = require "nixio.fs" -- force reload of global luci config namespace to reflect the changes function m.commit_handler(self) package.loaded["luci.config"] = nil require("luci.config") end c = m:section(NamedSection, "main", "core", translate("General")) l = c:option(ListValue, "lang", translate("Language")) l: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 fs.access(file .. ".lmo") then l:value(k, v) end end t = c:option(ListValue, "mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then t:value(v, k) end end u = m:section(NamedSection, "uci_oncommit", "event", translate("Post-commit actions"), translate("These commands will be executed automatically when a given <abbr title=\"Unified Configuration Interface\">UCI</abbr> configuration is committed allowing changes to be applied instantly.")) u.dynamic = true f = m: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) return nixio.fs.writefile("/etc/sysupgrade.conf", value) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 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.config") m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>.")) local fs = require "nixio.fs" -- force reload of global luci config namespace to reflect the changes function m.commit_handler(self) package.loaded["luci.config"] = nil require("luci.config") end c = m:section(NamedSection, "main", "core", translate("General")) l = c:option(ListValue, "lang", translate("Language")) l: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 fs.access(file .. ".lmo") then l:value(k, v) end end t = c:option(ListValue, "mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then t:value(v, k) end end u = m:section(NamedSection, "uci_oncommit", "event", translate("Post-commit actions"), translate("These commands will be executed automatically when a given <abbr title=\"Unified Configuration Interface\">UCI</abbr> configuration is committed allowing changes to be applied instantly.")) u.dynamic = true f = m: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
modules/admin-full: fixup newlines when storing sysupgrade.conf
modules/admin-full: fixup newlines when storing sysupgrade.conf git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6698 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
gwlim/luci,stephank/luci,vhpham80/luci,jschmidlapp/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,freifunk-gluon/luci,Flexibity/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,phi-psi/luci,yeewang/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,stephank/luci,ch3n2k/luci,vhpham80/luci,projectbismark/luci-bismark,stephank/luci,dtaht/cerowrt-luci-3.3,stephank/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,yeewang/openwrt-luci,jschmidlapp/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,ch3n2k/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,eugenesan/openwrt-luci,ch3n2k/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,freifunk-gluon/luci,gwlim/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,Flexibity/luci,Flexibity/luci,Canaan-Creative/luci,freifunk-gluon/luci,projectbismark/luci-bismark,stephank/luci,zwhfly/openwrt-luci,vhpham80/luci,saraedum/luci-packages-old,Canaan-Creative/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,ch3n2k/luci,gwlim/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,jschmidlapp/luci,phi-psi/luci,freifunk-gluon/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,gwlim/luci,Flexibity/luci,saraedum/luci-packages-old,Canaan-Creative/luci,phi-psi/luci,jschmidlapp/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,ch3n2k/luci,8devices/carambola2-luci,projectbismark/luci-bismark,jschmidlapp/luci,eugenesan/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,gwlim/luci,jschmidlapp/luci,Flexibity/luci,8devices/carambola2-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,Flexibity/luci,Canaan-Creative/luci,Canaan-Creative/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,8devices/carambola2-luci,stephank/luci,Canaan-Creative/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,gwlim/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,phi-psi/luci,phi-psi/luci,jschmidlapp/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,zwhfly/openwrt-luci
738e22e1be5e2f940a7e831a2d4d5f102b8d9d4e
kong/serf.lua
kong/serf.lua
-- from the previous services.serf module, simply decoupled from -- the Serf agent supervision logic. local pl_stringx = require "pl.stringx" local pl_utils = require "pl.utils" local pl_file = require "pl.file" local cjson = require "cjson.safe" local log = require "kong.cmd.utils.log" local Serf = {} Serf.__index = Serf Serf.args_mt = { __tostring = function(t) local buf = {} for k, v in pairs(t) do buf[#buf+1] = k.." '"..v.."'" end return table.concat(buf, " ") end } function Serf.new(kong_config, dao) return setmetatable({ node_name = pl_file.read(kong_config.serf_node_id), config = kong_config, dao = dao }, Serf) end -- WARN: BAD, this is **blocking** IO. Legacy code from previous Serf -- implementation that needs to be upgraded. function Serf:invoke_signal(signal, args, no_rpc) args = args or {} if type(args) == "table" then setmetatable(args, Serf.args_mt) end local rpc = no_rpc and "" or "-rpc-addr="..self.config.cluster_listen_rpc local cmd = string.format("serf %s %s %s", signal, rpc, tostring(args)) local ok, code, stdout = pl_utils.executeex(cmd) if not ok or code ~= 0 then return nil, pl_stringx.splitlines(stdout)[1] end -- always print the first error line of serf return stdout end function Serf:join_node(address) return select(2, self:invoke_signal("join", address)) == nil end function Serf:leave() local res, err = self:invoke_signal("leave") if not res then return nil, err end local _, err = self.dao.nodes:delete {name = self.node_name} if err then return nil, err end return true end function Serf:force_leave(node_name) local res, err = self:invoke_signal("force-leave", node_name) if not res then return nil, err end return true end function Serf:members() local res, err = self:invoke_signal("members", {["-format"] = "json"}) if not res then return nil, err end local json, err = cjson.decode(res) if not json then return nil, err end return json.members end function Serf:keygen() return self:invoke_signal("keygen", nil, true) end function Serf:reachability() return self:invoke_signal("reachability") end function Serf:cleanup() -- Delete current node just in case it was there -- (due to an inconsistency caused by a crash) local ok, err = self.dao.nodes:delete {name = self.node_name } return ok, tostring(err) end function Serf:autojoin() local nodes, err = self.dao.nodes:find_all() if err then return nil, tostring(err) elseif #nodes == 0 then log.info("No other Kong nodes were found in the cluster") else -- Sort by newest to oldest (although by TTL would be a better sort) table.sort(nodes, function(a, b) return a.created_at > b.created_at end) local joined for _, v in ipairs(nodes) do if self:join_node(v.cluster_listening_address) then log("Successfully auto-joined %s", v.cluster_listening_address) joined = true break else log.warn("could not join %s, if the node does not exist anymore it will be automatically purged", v.cluster_listening_address) end end if not joined then log.warn("could not join the existing cluster") end end return true end function Serf:add_node() local members, err = self:members() if not members then return nil, err end local addr for _, member in ipairs(members) do if member.name == self.node_name then addr = member.addr break end end if not addr then return nil, "can't find current member address" end local _, err = self.dao.nodes:insert({ name = self.node_name, cluster_listening_address = pl_stringx.strip(addr) }, {ttl = self.config.cluster_ttl_on_failure}) if err then return nil, tostring(err) end return true end function Serf:event(t_payload) local payload, err = cjson.encode(t_payload) if not payload then return nil, err end if #payload > 512 then -- Serf can't send a payload greater than 512 bytes return nil, "Encoded payload is "..#payload.." and exceeds the limit of 512 bytes!" end return self:invoke_signal("event -coalesce=false", " kong '"..payload.."'") end return Serf
-- from the previous services.serf module, simply decoupled from -- the Serf agent supervision logic. local pl_stringx = require "pl.stringx" local pl_utils = require "pl.utils" local pl_file = require "pl.file" local cjson = require "cjson.safe" local log = require "kong.cmd.utils.log" local Serf = {} Serf.__index = Serf Serf.args_mt = { __tostring = function(t) local buf = {} for k, v in pairs(t) do buf[#buf+1] = k.." '"..v.."'" end return table.concat(buf, " ") end } function Serf.new(kong_config, dao) return setmetatable({ node_name = pl_file.read(kong_config.serf_node_id), config = kong_config, dao = dao }, Serf) end -- WARN: BAD, this is **blocking** IO. Legacy code from previous Serf -- implementation that needs to be upgraded. function Serf:invoke_signal(signal, args, no_rpc) args = args or {} if type(args) == "table" then setmetatable(args, Serf.args_mt) end local rpc = no_rpc and "" or "-rpc-addr="..self.config.cluster_listen_rpc local cmd = string.format("serf %s %s %s", signal, rpc, tostring(args)) local ok, code, stdout = pl_utils.executeex(cmd) if not ok or code ~= 0 then return nil, pl_stringx.splitlines(stdout)[1] end -- always print the first error line of serf return stdout end function Serf:join_node(address) return select(2, self:invoke_signal("join", address)) == nil end function Serf:leave() local res, err = self:invoke_signal("leave") if not res then return nil, err end local _, err = self.dao.nodes:delete {name = self.node_name} if err then return nil, err end return true end function Serf:force_leave(node_name) local res, err = self:invoke_signal("force-leave", node_name) if not res then return nil, err end return true end function Serf:members() local res, err = self:invoke_signal("members", {["-format"] = "json"}) if not res then return nil, err end local json, err = cjson.decode(res) if not json then return nil, err end return json.members end function Serf:keygen() return self:invoke_signal("keygen", nil, true) end function Serf:reachability() return self:invoke_signal("reachability") end function Serf:cleanup() -- Delete current node just in case it was there -- (due to an inconsistency caused by a crash) local _, err = self.dao.nodes:delete {name = self.node_name } if err then return nil, tostring(err) end return true end function Serf:autojoin() local nodes, err = self.dao.nodes:find_all() if err then return nil, tostring(err) elseif #nodes == 0 then log.info("No other Kong nodes were found in the cluster") else -- Sort by newest to oldest (although by TTL would be a better sort) table.sort(nodes, function(a, b) return a.created_at > b.created_at end) local joined for _, v in ipairs(nodes) do if self:join_node(v.cluster_listening_address) then log("Successfully auto-joined %s", v.cluster_listening_address) joined = true break else log.warn("could not join %s, if the node does not exist anymore it will be automatically purged", v.cluster_listening_address) end end if not joined then log.warn("could not join the existing cluster") end end return true end function Serf:add_node() local members, err = self:members() if not members then return nil, err end local addr for _, member in ipairs(members) do if member.name == self.node_name then addr = member.addr break end end if not addr then return nil, "can't find current member address" end local _, err = self.dao.nodes:insert({ name = self.node_name, cluster_listening_address = pl_stringx.strip(addr) }, {ttl = self.config.cluster_ttl_on_failure}) if err then return nil, tostring(err) end return true end function Serf:event(t_payload) local payload, err = cjson.encode(t_payload) if not payload then return nil, err end if #payload > 512 then -- Serf can't send a payload greater than 512 bytes return nil, "Encoded payload is "..#payload.." and exceeds the limit of 512 bytes!" end return self:invoke_signal("event -coalesce=false", " kong '"..payload.."'") end return Serf
fix(cluster) error check
fix(cluster) error check
Lua
apache-2.0
akh00/kong,beauli/kong,li-wl/kong,salazar/kong,Kong/kong,Kong/kong,jebenexer/kong,Kong/kong,icyxp/kong,shiprabehera/kong,Vermeille/kong,Mashape/kong,jerizm/kong,ccyphers/kong
4735455ec8e486ee445288d9ada16fe54f479261
share/lua/website/metacafe.lua
share/lua/website/metacafe.lua
-- libquvi-scripts -- Copyright (C) 2011 Lionel Elie Mamane <lionel@mamane.lu> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local Metacafe = {} -- Utility functions unique to this script. -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "metacafe%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/watch/%d+/", "/watch/yt-[^/]+/"}) return r end -- Query available formats. function query_formats(self) if not Metacafe.redirectp(self) then self.formats = 'default' end return self end -- Parse media URL. function parse(self) self.host_id = "metacafe" if Metacafe.redirectp(self) then return self end local U = require 'quvi/util' local p = Metacafe.fetch_page(self, U) self.title = p:match('"title":"(.-)"') or error("no match: media title") self.title = U.unescape(self.title) self.id = p:match('"itemID":"(.-)"') or error('no match: media id') self.thumbnail_url = p:match('rel="image_src" href="(.-)"') or '' local d = p:match('"mediaData":"(.-)"') or error('no match: media data') d = U.unescape(d) local u = d:match('"mediaURL":"(.-)"') or error('no match: media url') u = U.slash_unescape(u) local k = d:match('"key":"(.-)"') or error('no match: gda key') self.url = {string.format("%s?__gda__=%s", u, k)} return self end -- -- Utility functions -- function Metacafe.redirectp(self) local s = self.page_url:match('/watch/yt%-([^/]+)/') if s then -- Hand over to youtube.lua self.redirect_url = 'http://youtube.com/watch?v=' .. s return true end return false end function Metacafe.fetch_page(self, U) self.page_url = Metacafe.normalize(self.page_url) return quvi.fetch(self.page_url) end function Metacafe.normalize(page_url) -- "Normalize" embedded URLs return page_url end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2013 Toni Gundogdu <legatvs@gmail.com> -- Copyright (C) 2011 Lionel Elie Mamane <lionel@mamane.lu> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local Metacafe = {} -- Utility functions unique to this script. -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "metacafe%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/watch/%d+/", "/watch/yt-[^/]+/"}) return r end -- Query available formats. function query_formats(self) if not Metacafe.redirectp(self) then self.formats = 'default' end return self end -- Parse media URL. function parse(self) self.host_id = "metacafe" if Metacafe.redirectp(self) then return self end local U = require 'quvi/util' local p = Metacafe.fetch_page(self, U) local v = p:match('name="flashvars" value="(.-)"') or error('no match: flashvars') v = U.slash_unescape(U.unescape(v)) self.thumbnail_url = p:match('rel="image_src" href="(.-)"') or '' self.title = v:match('title=(.-)&') or error('no match: media title') self.id = v:match('itemID=(%d+)') or error('no match: media ID') local u = v:match('"mediaURL":"(.-)"') or error('no match: media stream URL') local k = v:match('"key":"__gda__","value":"(.-)"') or error('no match: key') self.url = {string.format("%s?__gda__=%s", u, k)} return self end -- -- Utility functions -- function Metacafe.redirectp(self) local s = self.page_url:match('/watch/yt%-([^/]+)/') if s then -- Hand over to youtube.lua self.redirect_url = 'http://youtube.com/watch?v=' .. s return true end return false end function Metacafe.fetch_page(self, U) self.page_url = Metacafe.normalize(self.page_url) return quvi.fetch(self.page_url) end function Metacafe.normalize(page_url) -- "Normalize" embedded URLs return page_url end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: metacafe.lua: Key parsing
FIX: metacafe.lua: Key parsing Some of the patterns were outdated due to the changes made to the website. Have the script extract the 'flashvars' value, unescape it and then extract each individual value from this unescaped value. Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
Lua
agpl-3.0
alech/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
e593cef109ec847a1f20bfd6f4d4bb25a93bc165
MCServer/Plugins/MagicCarpet/plugin.lua
MCServer/Plugins/MagicCarpet/plugin.lua
local Carpets = {} function Initialize( Plugin ) Plugin:SetName( "MagicCarpet" ) Plugin:SetVersion( 2 ) cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_MOVING, OnPlayerMoving) cPluginManager.AddHook(cPluginManager.HOOK_DISCONNECT, OnDisconnect) local PluginManager = cPluginManager:Get() PluginManager:BindCommand("/mc", "magiccarpet", HandleCarpetCommand, " - Spawns a magical carpet"); LOG( "Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion() ) return true end function OnDisable() LOG( PLUGIN:GetName() .. " v." .. PLUGIN:GetVersion() .. " is shutting down..." ) for i, Carpet in pairs( Carpets ) do Carpet:remove() end end function HandleCarpetCommand( Split, Player ) Carpet = Carpets[ Player ] if( Carpet == nil ) then Carpets[ Player ] = cCarpet:new() SendMessageSuccess(Player, "You're on a magic carpet!") SendMessage(Player, "Look straight down to descend. Jump to ascend.") else Carpet:remove() Carpets[ Player ] = nil SendMessageSuccess(Player, "The carpet vanished!") end return true end function OnDisconnect( Reason, Player ) local Carpet = Carpets[ Player ] if( Carpet ~= nil ) then Carpet:remove() end Carpets[ Player ] = nil end function OnPlayerMoving(Player) local Carpet = Carpets[ Player ] if( Carpet == nil ) then return end if( Player:GetPitch() == 90 ) then Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY() - 1, Player:GetPosZ() ) ) else if( Player:GetPosY() < Carpet:getY() ) then Player:TeleportToCoords(Player:GetPosX(), Carpet:getY() + 0.2, Player:GetPosZ()) end Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY(), Player:GetPosZ() ) ) end end
local Carpets = {} local PLUGIN function Initialize( Plugin ) Plugin:SetName( "MagicCarpet" ) Plugin:SetVersion( 2 ) cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_MOVING, OnPlayerMoving) cPluginManager.AddHook(cPluginManager.HOOK_DISCONNECT, OnDisconnect) local PluginManager = cPluginManager:Get() PluginManager:BindCommand("/mc", "magiccarpet", HandleCarpetCommand, " - Spawns a magical carpet"); PLUGIN = Plugin LOG( "Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion() ) return true end function OnDisable() LOG( PLUGIN:GetName() .. " v." .. PLUGIN:GetVersion() .. " is shutting down..." ) for i, Carpet in pairs( Carpets ) do Carpet:remove() end end function HandleCarpetCommand( Split, Player ) Carpet = Carpets[ Player ] if( Carpet == nil ) then Carpets[ Player ] = cCarpet:new() SendMessageSuccess(Player, "You're on a magic carpet!") SendMessage(Player, "Look straight down to descend. Jump to ascend.") else Carpet:remove() Carpets[ Player ] = nil SendMessageSuccess(Player, "The carpet vanished!") end return true end function OnDisconnect( Reason, Player ) local Carpet = Carpets[ Player ] if( Carpet ~= nil ) then Carpet:remove() end Carpets[ Player ] = nil end function OnPlayerMoving(Player) local Carpet = Carpets[ Player ] if( Carpet == nil ) then return end if( Player:GetPitch() == 90 ) then Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY() - 1, Player:GetPosZ() ) ) else if( Player:GetPosY() < Carpet:getY() ) then Player:TeleportToCoords(Player:GetPosX(), Carpet:getY() + 0.2, Player:GetPosZ()) end Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY(), Player:GetPosZ() ) ) end end
Store plugin in a local variable to fix error on disable
Store plugin in a local variable to fix error on disable
Lua
apache-2.0
birkett/cuberite,Haxi52/cuberite,guijun/MCServer,guijun/MCServer,kevinr/cuberite,mc-server/MCServer,mc-server/MCServer,mc-server/MCServer,Schwertspize/cuberite,nevercast/cuberite,birkett/MCServer,nicodinh/cuberite,MuhammadWang/MCServer,HelenaKitty/EbooMC,linnemannr/MCServer,bendl/cuberite,tonibm19/cuberite,linnemannr/MCServer,linnemannr/MCServer,ionux/MCServer,mmdk95/cuberite,johnsoch/cuberite,SamOatesPlugins/cuberite,bendl/cuberite,johnsoch/cuberite,nichwall/cuberite,SamOatesPlugins/cuberite,Haxi52/cuberite,nevercast/cuberite,guijun/MCServer,nounoursheureux/MCServer,Haxi52/cuberite,nicodinh/cuberite,Frownigami1/cuberite,jammet/MCServer,MuhammadWang/MCServer,Schwertspize/cuberite,guijun/MCServer,marvinkopf/cuberite,QUSpilPrgm/cuberite,bendl/cuberite,thetaeo/cuberite,HelenaKitty/EbooMC,MuhammadWang/MCServer,Tri125/MCServer,birkett/cuberite,tonibm19/cuberite,jammet/MCServer,SamOatesPlugins/cuberite,SamOatesPlugins/cuberite,zackp30/cuberite,marvinkopf/cuberite,zackp30/cuberite,birkett/MCServer,guijun/MCServer,tonibm19/cuberite,johnsoch/cuberite,ionux/MCServer,linnemannr/MCServer,birkett/MCServer,Fighter19/cuberite,kevinr/cuberite,mmdk95/cuberite,mmdk95/cuberite,nounoursheureux/MCServer,mmdk95/cuberite,Frownigami1/cuberite,thetaeo/cuberite,ionux/MCServer,electromatter/cuberite,nichwall/cuberite,zackp30/cuberite,birkett/cuberite,Frownigami1/cuberite,linnemannr/MCServer,birkett/cuberite,Howaner/MCServer,zackp30/cuberite,linnemannr/MCServer,Frownigami1/cuberite,Howaner/MCServer,Altenius/cuberite,birkett/cuberite,jammet/MCServer,QUSpilPrgm/cuberite,guijun/MCServer,Fighter19/cuberite,birkett/cuberite,Tri125/MCServer,bendl/cuberite,kevinr/cuberite,birkett/MCServer,nichwall/cuberite,ionux/MCServer,mc-server/MCServer,birkett/MCServer,Haxi52/cuberite,nevercast/cuberite,marvinkopf/cuberite,jammet/MCServer,thetaeo/cuberite,mjssw/cuberite,kevinr/cuberite,Fighter19/cuberite,Tri125/MCServer,electromatter/cuberite,mjssw/cuberite,electromatter/cuberite,Howaner/MCServer,QUSpilPrgm/cuberite,nichwall/cuberite,Tri125/MCServer,Schwertspize/cuberite,nicodinh/cuberite,electromatter/cuberite,nicodinh/cuberite,mc-server/MCServer,Frownigami1/cuberite,marvinkopf/cuberite,MuhammadWang/MCServer,mjssw/cuberite,Howaner/MCServer,electromatter/cuberite,marvinkopf/cuberite,nounoursheureux/MCServer,QUSpilPrgm/cuberite,Fighter19/cuberite,SamOatesPlugins/cuberite,nevercast/cuberite,Haxi52/cuberite,johnsoch/cuberite,Howaner/MCServer,Altenius/cuberite,QUSpilPrgm/cuberite,jammet/MCServer,electromatter/cuberite,thetaeo/cuberite,Haxi52/cuberite,mjssw/cuberite,marvinkopf/cuberite,Howaner/MCServer,zackp30/cuberite,nicodinh/cuberite,nevercast/cuberite,nounoursheureux/MCServer,ionux/MCServer,nounoursheureux/MCServer,Tri125/MCServer,HelenaKitty/EbooMC,thetaeo/cuberite,nichwall/cuberite,bendl/cuberite,mjssw/cuberite,ionux/MCServer,nevercast/cuberite,Altenius/cuberite,mmdk95/cuberite,nicodinh/cuberite,zackp30/cuberite,HelenaKitty/EbooMC,tonibm19/cuberite,HelenaKitty/EbooMC,Altenius/cuberite,Fighter19/cuberite,mjssw/cuberite,nichwall/cuberite,QUSpilPrgm/cuberite,Tri125/MCServer,Fighter19/cuberite,nounoursheureux/MCServer,Schwertspize/cuberite,mmdk95/cuberite,thetaeo/cuberite,kevinr/cuberite,tonibm19/cuberite,Schwertspize/cuberite,MuhammadWang/MCServer,mc-server/MCServer,johnsoch/cuberite,kevinr/cuberite,jammet/MCServer,Altenius/cuberite,tonibm19/cuberite,birkett/MCServer
011062967ab28b8c1cd9903570d67e04f67e4a45
rootfs/etc/nginx/lua/lua_ingress.lua
rootfs/etc/nginx/lua/lua_ingress.lua
local _M = {} local seeds = {} local original_randomseed = math.randomseed math.randomseed = function(seed) local pid = ngx.worker.pid() if seeds[pid] then ngx.log(ngx.WARN, string.format("ignoring math.randomseed(%d) since PRNG is already seeded for worker %d", seed, pid)) return end original_randomseed(seed) seeds[pid] = seed end local function randomseed() math.randomseed(ngx.time() + ngx.worker.pid()) end function _M.init_worker() randomseed() end return _M
local _M = {} local seeds = {} local original_randomseed = math.randomseed local function get_seed_from_urandom() local seed local frandom = io.open("/dev/urandom", "rb") if frandom then local str = frandom:read(4) frandom:close() seed = 0 for i = 1, 4 do seed = 256 * seed + str:byte(i) end end return seed end math.randomseed = function() local pid = ngx.worker.pid() local seed = seeds[pid] if seed then ngx.log(ngx.WARN, string.format("ignoring math.randomseed(%d) since PRNG is already seeded for worker %d", seed, pid)) return end seed = get_seed_from_urandom() if not seed then seed = ngx.now() * 1000 + pid end original_randomseed(seed) seeds[pid] = seed end function _M.init_worker() math.randomseed() end return _M
bugfix: fixed duplicated seeds.
bugfix: fixed duplicated seeds. ngx.time() + ngx.worker.pid() maybe get duplicated seeds. get from /dev/urandom first.
Lua
apache-2.0
aledbf/ingress-nginx,caicloud/ingress,caicloud/ingress,kubernetes/ingress-nginx,canhnt/ingress,caicloud/ingress,canhnt/ingress,aledbf/ingress-nginx,kubernetes/ingress-nginx,kubernetes/ingress-nginx,aledbf/ingress-nginx,aledbf/ingress-nginx,canhnt/ingress,caicloud/ingress,kubernetes/ingress-nginx,kubernetes/ingress-nginx,canhnt/ingress
4a1dbe2d57e98e5a388edd9f7c63a973fe9ac819
OvaleBanditsGuile.lua
OvaleBanditsGuile.lua
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2013, 2014 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]------------------------------------------------------------------- --[[ This addon tracks the hidden stacking damage buff from Bandit's Guile on a combat rogue. Bandit's Guile description from wowhead.com: Your training allows you to recognize and take advantage of the natural ebb and flow of combat. Your Sinister Strike and Revealing Strike abilities increase your damage dealt by up to 30%. After reaching this maximum, the effect will fade after 15 sec and the cycle will begin anew. Mechanically, there is a hidden buff that stacks up to 12. At 4 stacks, the rogue gains Shallow Insight (10% increased damage). At 8 stacks, the rogue gains Moderate Insight (20% increased damage). At 12 stacks, the rogue gains Deep Insight (30% increased damage). This addon manages the hidden aura in OvaleAura using events triggered by either attacking with Sinister/Revealing Strike or by changes to the Insight auras on the player. The aura ID of the hidden aura is set to 84654, the spell ID of Bandit's Guile, and can be checked like any other aura using OvaleAura's public or state methods. --]] local _, Ovale = ... local OvaleBanditsGuile = Ovale:NewModule("OvaleBanditsGuile", "AceEvent-3.0") Ovale.OvaleBanditsGuile = OvaleBanditsGuile --<private-static-properties> -- Forward declarations for module dependencies. local OvaleAura = nil local API_GetTime = GetTime local API_UnitClass = UnitClass local API_UnitGUID = UnitGUID -- Player's class. local _, self_class = API_UnitClass("player") -- Player's GUID. local self_guid = nil -- Aura IDs for visible buff from Bandit's Guile. local SHALLOW_INSIGHT = 84745 local MODERATE_INSIGHT = 84746 local DEEP_INSIGHT = 84747 -- Spell IDs for abilities that proc Bandit's Guile. local REVEALING_STRIKE = 84617 local SINISTER_STRIKE = 1752 --</private-static-properties> --<public-static-properties> OvaleBanditsGuile.name = "Bandit's Guile" -- Bandit's Guile spell ID from spellbook; re-used as the aura ID of the hidden, stacking buff. OvaleBanditsGuile.spellId = 84654 OvaleBanditsGuile.start = 0 OvaleBanditsGuile.ending = math.huge OvaleBanditsGuile.duration = 15 OvaleBanditsGuile.stacks = 0 --</public-static-properties> --<public-static-methods> function OvaleBanditsGuile:OnInitialize() -- Resolve module dependencies. OvaleAura = Ovale.OvaleAura end function OvaleBanditsGuile:OnEnable() if self_class == "ROGUE" then self_guid = API_UnitGUID("player") self:RegisterMessage("Ovale_SpecializationChanged") end end function OvaleBanditsGuile:OnDisable() if self_class == "ROGUE" then self:UnregisterMessage("Ovale_SpecializationChanged") end end function OvaleBanditsGuile:Ovale_SpecializationChanged(event, specialization, previousSpecialization) if specialization == "combat" then self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterMessage("Ovale_AuraAdded") self:RegisterMessage("Ovale_AuraChanged") self:RegisterMessage("Ovale_AuraRemoved") else self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:UnregisterMessage("Ovale_AuraAdded") self:UnregisterMessage("Ovale_AuraChanged") self:UnregisterMessage("Ovale_AuraRemoved") end end function OvaleBanditsGuile:COMBAT_LOG_EVENT_UNFILTERED(event, timestamp, cleuEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...) local arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23 = ... if sourceGUID == self_guid and cleuEvent == "SPELL_DAMAGE" and self.stacks < 4 then local spellId = arg12 if spellId == REVEALING_STRIKE or spellID == SINISTER_STRIKE then local now = API_GetTime() self.start = now self.ending = now + INSIGHT_DURATION self.stacks = self.stacks + 1 self:GainedAura(now) end end end function OvaleBanditsGuile:Ovale_AuraAdded(event, timestamp, target, auraId, caster) if target == self_guid then if auraId == SHALLOW_INSIGHT or auraId == MODERATE_INSIGHT or auraId == DEEP_INSIGHT then -- Unregister for CLEU since we can now track stacks using refreshes on Insight buffs. self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") -- Set stacks to count implied by seeing the given aura added to the player. if auraId == SHALLOW_INSIGHT then self.stacks = 4 elseif auraId == MODERATE_INSIGHT then self.stacks = 8 elseif auraId == DEEP_INSIGHT then self.stacks = 12 end self.start, self.ending = OvaleAura:GetAura("player", auraId, "HELPFUL", true) self:GainedAura(timestamp) end end end function OvaleBanditsGuile:Ovale_AuraChanged(event, timestamp, target, auraId, caster) if target == self_guid then if auraId == SHALLOW_INSIGHT or auraId == MODERATE_INSIGHT or auraId == DEEP_INSIGHT then -- A changed Insight buff also means that the Bandit's Guile hidden buff gained a stack. self.stacks = self.stacks + 1 self.start, self.ending = OvaleAura:GetAura("player", auraId, "HELPFUL", true) self:GainedAura(timestamp) end end end function OvaleBanditsGuile:Ovale_AuraRemoved(event, timestamp, target, auraId, caster) if target == self_guid then if (auraId == SHALLOW_INSIGHT and self.stacks < 8) or (auraId == MODERATE_INSIGHT and self.stacks < 12) or auraId == DEEP_INSIGHT then self.start = 0 self.ending = math.huge self.stacks = 0 self:LostAura(timestamp) -- Register for CLEU again to track the aura before reaching Shallow Insight. self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") end end end function OvaleBanditsGuile:GainedAura(atTime) atTime = atTime or API_GetTime() OvaleAura:GainedAuraOnGUID(self_guid, atTime, self.spellId, self_guid, "HELPFUL", nil, nil, self.stacks, nil, INSIGHT_DURATION, self.ending, nil, self.name, nil, nil, nil) end function OvaleBanditsGuile:LostAura(atTime) atTime = atTime or API_GetTime() OvaleAura:LostAuraOnGUID(self_guid, atTime, self.spellId, self_guid) end function OvaleBanditsGuile:Debug() local aura = OvaleAura:GetAuraByGUID(self_guid, self.spellId, "HELPFUL", true) Ovale:FormatPrint("Player has Bandit's Guile aura with start=%s, end=%s, stacks=%d.", aura.start, aura.ending, aura.stacks) end --</public-static-methods>
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2013, 2014 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]------------------------------------------------------------------- --[[ This addon tracks the hidden stacking damage buff from Bandit's Guile on a combat rogue. Bandit's Guile description from wowhead.com: Your training allows you to recognize and take advantage of the natural ebb and flow of combat. Your Sinister Strike and Revealing Strike abilities increase your damage dealt by up to 30%. After reaching this maximum, the effect will fade after 15 sec and the cycle will begin anew. Mechanically, there is a hidden buff that stacks up to 12. At 4 stacks, the rogue gains Shallow Insight (10% increased damage). At 8 stacks, the rogue gains Moderate Insight (20% increased damage). At 12 stacks, the rogue gains Deep Insight (30% increased damage). This addon manages the hidden aura in OvaleAura using events triggered by either attacking with Sinister/Revealing Strike or by changes to the Insight auras on the player. The aura ID of the hidden aura is set to 84654, the spell ID of Bandit's Guile, and can be checked like any other aura using OvaleAura's public or state methods. --]] local _, Ovale = ... local OvaleBanditsGuile = Ovale:NewModule("OvaleBanditsGuile", "AceEvent-3.0") Ovale.OvaleBanditsGuile = OvaleBanditsGuile --<private-static-properties> -- Forward declarations for module dependencies. local OvaleAura = nil local API_GetTime = GetTime local API_UnitClass = UnitClass local API_UnitGUID = UnitGUID -- Player's class. local _, self_class = API_UnitClass("player") -- Player's GUID. local self_guid = nil -- Aura IDs for visible buff from Bandit's Guile. local SHALLOW_INSIGHT = 84745 local MODERATE_INSIGHT = 84746 local DEEP_INSIGHT = 84747 -- Spell IDs for abilities that proc Bandit's Guile. local BANDITS_GUILE_ATTACK = { [ 1752] = "Sinister Strike", [84617] = "Revealing Strike", } --</private-static-properties> --<public-static-properties> OvaleBanditsGuile.name = "Bandit's Guile" -- Bandit's Guile spell ID from spellbook; re-used as the aura ID of the hidden, stacking buff. OvaleBanditsGuile.spellId = 84654 OvaleBanditsGuile.start = 0 OvaleBanditsGuile.ending = math.huge OvaleBanditsGuile.duration = 15 OvaleBanditsGuile.stacks = 0 --</public-static-properties> --<public-static-methods> function OvaleBanditsGuile:OnInitialize() -- Resolve module dependencies. OvaleAura = Ovale.OvaleAura end function OvaleBanditsGuile:OnEnable() if self_class == "ROGUE" then self_guid = API_UnitGUID("player") self:RegisterMessage("Ovale_SpecializationChanged") end end function OvaleBanditsGuile:OnDisable() if self_class == "ROGUE" then self:UnregisterMessage("Ovale_SpecializationChanged") end end function OvaleBanditsGuile:Ovale_SpecializationChanged(event, specialization, previousSpecialization) if specialization == "combat" then self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterMessage("Ovale_AuraAdded") self:RegisterMessage("Ovale_AuraChanged") self:RegisterMessage("Ovale_AuraRemoved") else self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:UnregisterMessage("Ovale_AuraAdded") self:UnregisterMessage("Ovale_AuraChanged") self:UnregisterMessage("Ovale_AuraRemoved") end end -- This event handler uses CLEU to track Bandit's Guile before it has procced any level of the -- Insight buff. function OvaleBanditsGuile:COMBAT_LOG_EVENT_UNFILTERED(event, timestamp, cleuEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...) local arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23 = ... if sourceGUID == self_guid and cleuEvent == "SPELL_DAMAGE" and self.stacks < 3 then local spellId = arg12 if BANDITS_GUILE_ATTACK[spellId] then local now = API_GetTime() self.start = now self.ending = self.start + self.duration self.stacks = self.stacks + 1 self:GainedAura(now) end end end -- This event handler uses Ovale_AuraAdded to track the Insight buff being applied for the first -- time and sets the implied stacks of Bandit's Guile. function OvaleBanditsGuile:Ovale_AuraAdded(event, timestamp, target, auraId, caster) if target == self_guid then if auraId == SHALLOW_INSIGHT or auraId == MODERATE_INSIGHT or auraId == DEEP_INSIGHT then local aura = OvaleAura:GetAura("player", auraId, "HELPFUL", true) self.start, self.ending = aura.start, aura.ending -- Set stacks to count implied by seeing the given aura added to the player. if auraId == SHALLOW_INSIGHT then self.stacks = 4 elseif auraId == MODERATE_INSIGHT then self.stacks = 8 elseif auraId == DEEP_INSIGHT then self.stacks = 12 end self:GainedAura(timestamp) end end end -- This event handler uses Ovale_AuraChanged to track refreshes of the Insight buff, which indicates -- that it the hidden Bandit's Guile buff has gained extra stacks. function OvaleBanditsGuile:Ovale_AuraChanged(event, timestamp, target, auraId, caster) if target == self_guid then if auraId == SHALLOW_INSIGHT or auraId == MODERATE_INSIGHT or auraId == DEEP_INSIGHT then local aura = OvaleAura:GetAura("player", auraId, "HELPFUL", true) self.start, self.ending = aura.start, aura.ending -- A changed Insight buff also means that the Bandit's Guile hidden buff gained a stack. self.stacks = self.stacks + 1 self:GainedAura(timestamp) end end end function OvaleBanditsGuile:Ovale_AuraRemoved(event, timestamp, target, auraId, caster) if target == self_guid then if (auraId == SHALLOW_INSIGHT and self.stacks < 8) or (auraId == MODERATE_INSIGHT and self.stacks < 12) or auraId == DEEP_INSIGHT then self.ending = timestamp self.stacks = 0 OvaleAura:LostAuraOnGUID(self_guid, timestamp, self.spellId, self_guid) end end end function OvaleBanditsGuile:GainedAura(atTime) OvaleAura:GainedAuraOnGUID(self_guid, atTime, self.spellId, self_guid, "HELPFUL", nil, nil, self.stacks, nil, self.duration, self.ending, nil, self.name, nil, nil, nil) end function OvaleBanditsGuile:Debug() local aura = OvaleAura:GetAuraByGUID(self_guid, self.spellId, "HELPFUL", true) if aura then Ovale:FormatPrint("Player has Bandit's Guile aura with start=%s, end=%s, stacks=%d.", aura.start, aura.ending, aura.stacks) end end --</public-static-methods>
Fix tracking of Bandit's Guile stacks before Insight buff appears.
Fix tracking of Bandit's Guile stacks before Insight buff appears. git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1358 d5049fe3-3747-40f7-a4b5-f36d6801af5f
Lua
mit
ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale
4e28f32956fd6b98ac47b4c104d8153abec68b04
examples/bbs/engine.lua
examples/bbs/engine.lua
local print = print local pcall = pcall local coroutine = coroutine local ui = require 'ui' module 'engine' local STATE = {} function run(conn, engine) while true do -- Get a message from the Mongrel2 server local good, request = pcall(conn.recv_json, conn) if good then local msg_type = request.data.type if msg_type == 'disconnect' then -- The client has disconnected print("disconnect", request.conn_id) STATE[request.conn_id] = nil elseif msg_type == 'msg' then -- The client has sent data local eng = STATE[request.conn_id] -- If the client hasn't sent data before, create a new engine. if not eng then eng = coroutine.create(engine) STATE[request.conn_id] = eng -- Initialize the engine with the client's connection coroutine.resume(eng, conn) end -- Pass the data on to the engine local good, error = coroutine.resume(eng, request) print("status", coroutine.status(eng)) if not good then -- There was an error print("ERROR", error) ui.exit(conn, request, 'error') elseif coroutine.status(eng) == "dead" then -- The engine has finished STATE[request.conn_id] = nil end else print("invalid message.") end print("eng", STATE[request.conn_id]) end end end
local print = print local pcall = pcall local coroutine = coroutine local ui = require 'ui' module 'engine' local STATE = {} function run(conn, engine) while true do -- Get a message from the Mongrel2 server local good, request = pcall(conn.recv_json, conn) if good then local msg_type = request.data.type if msg_type == 'disconnect' then -- The client has disconnected print("disconnect", request.conn_id) STATE[request.conn_id] = nil elseif msg_type == 'msg' then -- The client has sent data local eng = STATE[request.conn_id] -- If the client hasn't sent data before, create a new engine. if not eng then eng = coroutine.create(engine) STATE[request.conn_id] = eng -- Initialize the engine with the client's connection coroutine.resume(eng, conn) end -- Pass the data on to the engine local good, error = coroutine.resume(eng, request) print("status", coroutine.status(eng)) -- If the engine is done, stop tracking the client if coroutine.status(eng) == "dead" then STATE[request.conn_id] = nil if not good then -- There was an error print("ERROR", error) ui.exit(conn, request, 'error') end end else print("invalid message.") end print("eng", STATE[request.conn_id]) end end end
Fixed bug where the STATE entry for a connection wouldn't be cleared if an error occured.
Fixed bug where the STATE entry for a connection wouldn't be cleared if an error occured.
Lua
bsd-3-clause
musl/mongrel2,steamraven/mongrel2,musl/mongrel2,markokr/mongrel2,mongrel2/mongrel2,krakensden/mongrel2,aidenkeating/mongrel2,AlexVPopov/mongrel2,winks/mongrel2,bashi-bazouk/mongrel2,jubarajborgohain/mongrel2,nickdesaulniers/mongrel2,chickenkiller/mongrel2,niedbalski/mongrel2,xrl/mongrel2,winks/mongrel2,AlexVPopov/mongrel2,wayneeseguin/mongrel2,AlexVPopov/mongrel2,wayneeseguin/mongrel2,wayneeseguin/mongrel2,ralphbean/mongrel2,apjanke/mongrel2,AustinWise/mongrel2,issuu/mongrel2,jdesgats/mongrel2,msteinert/mongrel2,griffordson/mongrel2,markokr/mongrel2,jiffyjeff/mongrel2,aidenkeating/mongrel2,apjanke/mongrel2,cpick/mongrel2,duaneg/mongrel2,steamraven/mongrel2,dermoth/mongrel2,musl/mongrel2,jablkopp/mongrel2,mongrel2/mongrel2,AustinWise/mongrel2,mongrel2/mongrel2,nmandery/mongrel2,markokr/mongrel2,yoink00/mongrel2,krakensden/mongrel2,moai/mongrel2,rpeterson/mongrel2,yoink00/mongrel2,mongrel2/mongrel2,duaneg/mongrel2,winks/mongrel2,nmandery/mongrel2,ralphbean/mongrel2,AustinWise/mongrel2,rpeterson/mongrel2,mbj/mongrel2,bashi-bazouk/mongrel2,niedbalski/mongrel2,jagguli/mongrel2,steamraven/mongrel2,aidenkeating/mongrel2,chickenkiller/mongrel2,jasom/mongrel2,reshefm/mongrel2,pjkundert/mongrel2,metadave/mongrel2,minrk/mongrel2,moai/mongrel2,chickenkiller/mongrel2,nickdesaulniers/mongrel2,mongrel2/mongrel2,bashi-bazouk/mongrel2,xrl/mongrel2,aidenkeating/mongrel2,cpick/mongrel2,steamraven/mongrel2,xrl/mongrel2,yoink00/mongrel2,jiffyjeff/mongrel2,minrk/mongrel2,jdesgats/mongrel2,aidenkeating/mongrel2,cpick/mongrel2,Gibheer/mongrel2,issuu/mongrel2,dermoth/mongrel2,chickenkiller/mongrel2,jiffyjeff/mongrel2,xrl/mongrel2,ralphbean/mongrel2,jubarajborgohain/mongrel2,nickdesaulniers/mongrel2,pjkundert/mongrel2,reshefm/mongrel2,moai/mongrel2,AvdN/mongrel2,nmandery/mongrel2,AvdN/mongrel2,pjkundert/mongrel2,jdesgats/mongrel2,griffordson/mongrel2,minrk/mongrel2,jablkopp/mongrel2,sshirokov/mongrel2,AlexVPopov/mongrel2,elo80ka/mongrel2,niedbalski/mongrel2,fanout/mongrel2,elo80ka/mongrel2,elo80ka/mongrel2,cpick/mongrel2,apjanke/mongrel2,AvdN/mongrel2,niedbalski/mongrel2,metadave/mongrel2,reshefm/mongrel2,fanout/mongrel2,metadave/mongrel2,msteinert/mongrel2,chickenkiller/mongrel2,fanout/mongrel2,jubarajborgohain/mongrel2,Gibheer/mongrel2,cpick/mongrel2,winks/mongrel2,jdesgats/mongrel2,musl/mongrel2,rpeterson/mongrel2,Gibheer/mongrel2,jagguli/mongrel2,xrl/mongrel2,mongrel2/mongrel2,AustinWise/mongrel2,aidenkeating/mongrel2,xrl/mongrel2,minrk/mongrel2,wayneeseguin/mongrel2,ameuret/mongrel2,duaneg/mongrel2,jasom/mongrel2,msteinert/mongrel2,yoink00/mongrel2,fanout/mongrel2,jagguli/mongrel2,krakensden/mongrel2,griffordson/mongrel2,yoink00/mongrel2,moai/mongrel2,musl/mongrel2,AvdN/mongrel2,elo80ka/mongrel2,fanout/mongrel2,jablkopp/mongrel2,mbj/mongrel2,sshirokov/mongrel2,nickdesaulniers/mongrel2,pjkundert/mongrel2,cpick/mongrel2,duaneg/mongrel2,bashi-bazouk/mongrel2,krakensden/mongrel2,ralphbean/mongrel2,dermoth/mongrel2,ameuret/mongrel2,mbj/mongrel2,apjanke/mongrel2,jubarajborgohain/mongrel2,jiffyjeff/mongrel2,jagguli/mongrel2,mbj/mongrel2,krakensden/mongrel2,steamraven/mongrel2,elo80ka/mongrel2,moai/mongrel2,reshefm/mongrel2,jagguli/mongrel2,bashi-bazouk/mongrel2,markokr/mongrel2,Gibheer/mongrel2,nickdesaulniers/mongrel2,msteinert/mongrel2,issuu/mongrel2,AlexVPopov/mongrel2,jasom/mongrel2,ameuret/mongrel2,ameuret/mongrel2,jiffyjeff/mongrel2,issuu/mongrel2,jablkopp/mongrel2,sshirokov/mongrel2,minrk/mongrel2,ameuret/mongrel2,apjanke/mongrel2,nmandery/mongrel2,jasom/mongrel2,dermoth/mongrel2,jdesgats/mongrel2,jasom/mongrel2,issuu/mongrel2,pjkundert/mongrel2,metadave/mongrel2,sshirokov/mongrel2,markokr/mongrel2,griffordson/mongrel2,ameuret/mongrel2,rpeterson/mongrel2,jablkopp/mongrel2,chickenkiller/mongrel2,yoink00/mongrel2
6818e93787cbcaa716370ed050e080b5d9da8c30
applications/luci-minidlna/luasrc/controller/minidlna.lua
applications/luci-minidlna/luasrc/controller/minidlna.lua
--[[ LuCI - Lua Configuration Interface - miniDLNA support Copyright 2012 Gabor Juhos <juhosg@openwrt.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$ ]]-- module("luci.controller.minidlna", package.seeall) function index() if not nixio.fs.access("/etc/config/minidlna") then return end local page page = entry({"admin", "services", "minidlna"}, cbi("minidlna"), _("miniDLNA")) page.i18n = "minidlna" page.dependent = true entry({"admin", "services", "minidlna_status"}, call("minidlna_status")) end function minidlna_status() local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local port = tonumber(uci:get_first("minidlna", "minidlna", "port")) local status = { running = (sys.call("pidof minidlna >/dev/null") == 0), audio = 0, video = 0, image = 0 } if status.running then local fd = sys.httpget("http://127.0.0.1:%d/" % (port or 8200), true) if fd then local ln repeat ln = fd:read("*l") if ln and ln:match("files:") then local ftype, fcount = ln:match("(.+) files: (%d+)") status[ftype:lower()] = tonumber(fcount) or 0 end until not ln fd:close() end end luci.http.prepare_content("application/json") luci.http.write_json(status) end
--[[ LuCI - Lua Configuration Interface - miniDLNA support Copyright 2012 Gabor Juhos <juhosg@openwrt.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$ ]]-- module("luci.controller.minidlna", package.seeall) function index() if not nixio.fs.access("/etc/config/minidlna") then return end local page page = entry({"admin", "services", "minidlna"}, cbi("minidlna"), _("miniDLNA")) page.i18n = "minidlna" page.dependent = true entry({"admin", "services", "minidlna_status"}, call("minidlna_status")) end function minidlna_status() local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local port = tonumber(uci:get_first("minidlna", "minidlna", "port")) local status = { running = (sys.call("pidof minidlna >/dev/null") == 0), audio = 0, video = 0, image = 0 } if status.running then local fd = sys.httpget("http://127.0.0.1:%d/" % (port or 8200), true) if fd then local html = fd:read("*a") if html then status.audio = (tonumber(html:match("Audio files: (%d+)")) or 0) status.video = (tonumber(html:match("Video files: (%d+)")) or 0) status.image = (tonumber(html:match("Image files: (%d+)")) or 0) end fd:close() end end luci.http.prepare_content("application/json") luci.http.write_json(status) end
applications/luci-minidlna: fix status parsing
applications/luci-minidlna: fix status parsing git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8658 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,jschmidlapp/luci,eugenesan/openwrt-luci,stephank/luci,ThingMesh/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,stephank/luci,eugenesan/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,jschmidlapp/luci,stephank/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,jschmidlapp/luci,gwlim/luci,freifunk-gluon/luci,gwlim/luci,stephank/luci,vhpham80/luci,Flexibity/luci,gwlim/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,8devices/carambola2-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,stephank/luci,jschmidlapp/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,vhpham80/luci,zwhfly/openwrt-luci,vhpham80/luci,phi-psi/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,ch3n2k/luci,ch3n2k/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,stephank/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,phi-psi/luci,jschmidlapp/luci,saraedum/luci-packages-old,saraedum/luci-packages-old,yeewang/openwrt-luci,freifunk-gluon/luci,gwlim/luci,Flexibity/luci,freifunk-gluon/luci,8devices/carambola2-luci,Flexibity/luci,8devices/carambola2-luci,phi-psi/luci,saraedum/luci-packages-old,saraedum/luci-packages-old,Flexibity/luci,8devices/carambola2-luci,ch3n2k/luci,gwlim/luci,zwhfly/openwrt-luci,gwlim/luci,Flexibity/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,jschmidlapp/luci,vhpham80/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,Flexibity/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,phi-psi/luci,phi-psi/luci,Canaan-Creative/luci,vhpham80/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci
6dff532b37805fcc17d30d7bb1a05b332eff2eed
core/units.lua
core/units.lua
local units = { pt = { relative = false, value = 1 } } setmetatable(units, { __newindex = function (self, unit, spec) local def = SU.required(spec, "definition", "registering unit " .. unit) local relative = SU.boolean(spec.relative, false) if type(def) == "string" then local parsed = SILE.parserBits.measurement:match(def) if not parsed then SU.error("Could not parse unit definition '"..def.."'") end if not self[parsed.unit] then SU.error("Unit " .. unit .. " defined in terms of unknown unit " .. parsed.unit) elseif self[parsed.unit].relative then rawset(self, unit, { relative = true, converter = function (value) return value * self[parsed.unit].converter(parsed.amount) end }) else rawset(self, unit, { relative = false, value = parsed.amount * self[parsed.unit].value }) end elseif type(def) == "function" then rawset(self, unit, { relative = relative, converter = def }) end end }) SILE.registerUnit = function (unit, spec) -- SU.warn("Use of SILE.registerUnit() is deprecated, add via metamethod SILE.units["unit"] = (spec)" units[unit] = spec end units["mm"] = { definition = "2.8346457pt" } units["cm"] = { definition = "10mm" } units["m"] = { definition = "100cm" } units["in"] = { definition = "72pt" } units["ft"] = { definition = "12in" } local checkPaperDefined = function () if not SILE.documentState or not SILE.documentState.orgPaperSize then SU.error("A measurement tried to measure the paper size before the paper was defined", true) end end local checkFrameDefined = function () if not SILE.typesetter.frame then SU.error("A measurement tried to measure the frame before the frame was defined", true) end end units["%pw"] = { relative = true, definition = function (value) checkPaperDefined() return value / 100 * SILE.documentState.orgPaperSize[1] end } units["%ph"] = { relative = true, definition = function (value) checkPaperDefined() return value / 100 * SILE.documentState.orgPaperSize[2] end } units["%pmin"] = { relative = true, definition = function (value) checkPaperDefined() return value / 100 * SU.min(SILE.documentState.orgPaperSize[1], SILE.documentState.orgPaperSize[2]) end } units["%pmax"] = { relative = true, definition = function (value) checkPaperDefined() return value / 100 * SU.max(SILE.documentState.orgPaperSize[1], SILE.documentState.orgPaperSize[2]) end } units["%fw"] = { relative = true, definition = function (value) checkFrameDefined() return value / 100 * SILE.typesetter.frame:width() end } units["%fh"] = { relative = true, definition = function (value) checkFrameDefined() return value / 100 * SILE.typesetter.frame:height() end } units["%fmin"] = { relative = true, definition = function (value) checkFrameDefined() return value / 100 * SU.min(SILE.typesetter.frame:width(), SILE.typesetter.frame:height()) end } units["%fmax"] = { relative = true, definition = function (value) checkFrameDefined() return value / 100 * SU.max(SILE.typesetter.frame:width(), SILE.typesetter.frame:height()) end } units["%lw"] = { relative = true, definition = function (value) local lskip = SILE.settings.get("document.lskip") or SILE.length(0) local rskip = SILE.settings.get("document.rskip") or SILE.length(0) local left = lskip.width and lskip.width:absolute() or lskip:absolute() local right = rskip.width and rskip.width:absolute() or rskip:absolute() checkFrameDefined() local lw = SILE.typesetter.frame:getLineWidth() - left - right return lw * value / 100 end } units["ps"] = { relative = true, definition = function (value) local ps = SILE.settings.get("document.parskip") or SILE.length() ps = ps.height and ps.height:absolute() or ps:absolute() return value * ps.length end } units["bs"] = { relative = true, definition = function (value) local bs = SILE.settings.get("document.baselineskip") or SILE.length() bs = bs.height and bs.height:absolute() or bs:absolute() return value * bs.length end } units["em"] = { relative = true, definition = function (value) return value * SILE.settings.get("font.size") end } units["ex"] = { relative = true, definition = function (value) return value * SILE.shaper:measureChar("x").height end } units["spc"] = { relative = true, definition = function (value) return value * SILE.shaper:measureChar(" ").width end } units["en"] = { relative = true, definition = "0.5em" } return units
local units = { pt = { relative = false, value = 1 } } setmetatable(units, { __newindex = function (self, unit, spec) local def = SU.required(spec, "definition", "registering unit " .. unit) local relative = SU.boolean(spec.relative, false) if type(def) == "string" then local parsed = SILE.parserBits.measurement:match(def) if not parsed then SU.error("Could not parse unit definition '"..def.."'") end if not self[parsed.unit] then SU.error("Unit " .. unit .. " defined in terms of unknown unit " .. parsed.unit) elseif self[parsed.unit].relative then rawset(self, unit, { relative = true, converter = function (value) return value * self[parsed.unit].converter(parsed.amount) end }) else rawset(self, unit, { relative = false, value = parsed.amount * self[parsed.unit].value }) end elseif type(def) == "function" then rawset(self, unit, { relative = relative, converter = def }) end end }) SILE.registerUnit = function (unit, spec) -- SU.warn("Use of SILE.registerUnit() is deprecated, add via metamethod SILE.units["unit"] = (spec)" units[unit] = spec end units["mm"] = { definition = "2.8346457pt" } units["cm"] = { definition = "10mm" } units["m"] = { definition = "100cm" } units["in"] = { definition = "72pt" } units["ft"] = { definition = "12in" } local checkPaperDefined = function () if not SILE.documentState or not SILE.documentState.orgPaperSize then SU.error("A measurement tried to measure the paper size before the paper was defined", true) end end local checkFrameDefined = function () if not SILE.typesetter.frame then SU.error("A measurement tried to measure the frame before the frame was defined", true) end end units["%pw"] = { relative = true, definition = function (value) checkPaperDefined() return value / 100 * SILE.documentState.orgPaperSize[1] end } units["%ph"] = { relative = true, definition = function (value) checkPaperDefined() return value / 100 * SILE.documentState.orgPaperSize[2] end } units["%pmin"] = { relative = true, definition = function (value) checkPaperDefined() return value / 100 * SU.min(SILE.documentState.orgPaperSize[1], SILE.documentState.orgPaperSize[2]) end } units["%pmax"] = { relative = true, definition = function (value) checkPaperDefined() return value / 100 * SU.max(SILE.documentState.orgPaperSize[1], SILE.documentState.orgPaperSize[2]) end } units["%fw"] = { relative = true, definition = function (value) checkFrameDefined() return value / 100 * SILE.typesetter.frame:width():tonumber() end } units["%fh"] = { relative = true, definition = function (value) checkFrameDefined() return value / 100 * SILE.typesetter.frame:height():tonumber() end } units["%fmin"] = { relative = true, definition = function (value) checkFrameDefined() return value / 100 * SU.min(SILE.typesetter.frame:width():tonumber(), SILE.typesetter.frame:height():tonumber()) end } units["%fmax"] = { relative = true, definition = function (value) checkFrameDefined() return value / 100 * SU.max(SILE.typesetter.frame:width():tonumber(), SILE.typesetter.frame:height():tonumber()) end } units["%lw"] = { relative = true, definition = function (value) local lskip = SILE.settings.get("document.lskip") local rskip = SILE.settings.get("document.rskip") local left = lskip and lskip.width:tonumber() or 0 local right = rskip and rskip.width:tonumber() or 0 checkFrameDefined() return value / 100 * SILE.typesetter.frame:getLineWidth():tonumber() - left - right end } units["ps"] = { relative = true, definition = function (value) local ps = SILE.settings.get("document.parskip") ps = ps.height:tonumber() or 0 return value * ps end } units["bs"] = { relative = true, definition = function (value) local bs = SILE.settings.get("document.baselineskip") bs = bs.height:tonumber() or 0 return value * bs end } units["em"] = { relative = true, definition = function (value) return value * SILE.settings.get("font.size") end } units["ex"] = { relative = true, definition = function (value) return value * SILE.shaper:measureChar("x").height end } units["spc"] = { relative = true, definition = function (value) return value * SILE.shaper:measureChar(" ").width end } units["en"] = { relative = true, definition = "0.5em" } return units
fix(core): Don't let units deal in length objects more than necessary
fix(core): Don't let units deal in length objects more than necessary Some of the :absolute() calls were causing side effects and/or race conditions
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
ba253c4d60d466b49dbd918e4ea11961ed822f75
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local prosody = _G.prosody; local hosts = prosody.hosts; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local adhoc_new = module:require "adhoc".new; local sessions = {}; local add_user_layout = dataforms_new{ title = "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; local get_online_users_layout = dataforms_new{ title = "Getting List of Online Users"; instructions = "How many users should be returned at most?"; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "max_items", type = "list-single", label = "Maximum number of users", value = { "25", "50", "75", "100", "150", "200", "all" } }; }; function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :add_child(item:cmdtag("canceled") :tag("note", {type="error"}):text("You don't have permission to add a user"))); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Account already exists"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):add_child(item:cmdtag("completed", stanza.tags[1].attr.sessionid) :tag("note", {type="info"}):text("Account successfully created"))); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Failed to write data to disk"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPassword mismatch, or empty username"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Invalid data.\nPassword mismatch, or empty username"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):add_child(item:cmdtag("executing", sessionid):add_child(add_user_layout:form()))); end return true; end function get_online_users_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to request a list of online users"):up() :add_child(item:cmdtag("canceled") :tag("note", {type="error"}):text("You don't have permission to request a list of online users"))); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local max_items = nil if fields.max_items ~= "all" then max_items = tonumber(fields.max_items); end local count = 0; local field = st.stanza("field", {label="The list of all online users", var="onlineuserjids", type="text-multi"}); for username, user in pairs(hosts[stanza.attr.to].sessions or {}) do if (max_items ~= nil) and (count >= max_items) then break; end field:tag("value"):text(username.."@"..stanza.attr.to):up(); count = count + 1; end origin.send(st.reply(stanza):add_child(item:cmdtag("completed", stanza.tags[1].attr.sessionid) :tag("x", {xmlns="jabber:x:data", type="result"}) :tag("field", {type="hidden", var="FORM_TYPE"}) :tag("value"):text("http://jabber.org/protocol/admin"):up():up() :add_child(field))); else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):add_child(item:cmdtag("executing", sessionid):add_child(get_online_users_layout:form()))); end return true; end local add_user_desc = adhoc_new("Add User", "http://jabber.org/protocol/admin#add-user", add_user_command_handler, "admin"); local get_online_users_desc = adhoc_new("Get List of Online Users", "http://jabber.org/protocol/admin#get-online-users", get_online_users_command_handler, "admin"); function module.unload() module:remove_item("adhoc", add_user_desc); module:remove_item("adhoc", get_online_users_desc); end module:add_item("adhoc", add_user_desc); module:add_item("adhoc", get_online_users_desc);
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local prosody = _G.prosody; local hosts = prosody.hosts; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local adhoc_new = module:require "adhoc".new; local sessions = {}; local add_user_layout = dataforms_new{ title = "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; local get_online_users_layout = dataforms_new{ title = "Getting List of Online Users"; instructions = "How many users should be returned at most?"; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "max_items", type = "list-single", label = "Maximum number of users", value = { "25", "50", "75", "100", "150", "200", "all" } }; }; function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :add_child(item:cmdtag("canceled") :tag("note", {type="error"}):text("You don't have permission to add a user"))); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Account already exists"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):add_child(item:cmdtag("completed", stanza.tags[1].attr.sessionid) :tag("note", {type="info"}):text("Account successfully created"))); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Failed to write data to disk"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPassword mismatch, or empty username"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Invalid data.\nPassword mismatch, or empty username"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):add_child(item:cmdtag("executing", sessionid):add_child(add_user_layout:form()))); end return true; end function get_online_users_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to request a list of online users"):up() :add_child(item:cmdtag("canceled") :tag("note", {type="error"}):text("You don't have permission to request a list of online users"))); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local max_items = nil if fields.max_items ~= "all" then max_items = tonumber(fields.max_items); end local count = 0; local field = st.stanza("field", {label="The list of all online users", var="onlineuserjids", type="text-multi"}); for username, user in pairs(hosts[stanza.attr.to].sessions or {}) do if (max_items ~= nil) and (count >= max_items) then break; end field:tag("value"):text(username.."@"..stanza.attr.to):up(); count = count + 1; end origin.send(st.reply(stanza):add_child(item:cmdtag("completed", stanza.tags[1].attr.sessionid) :tag("x", {xmlns="jabber:x:data", type="result"}) :tag("field", {type="hidden", var="FORM_TYPE"}) :tag("value"):text("http://jabber.org/protocol/admin"):up():up() :add_child(field))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):add_child(item:cmdtag("executing", sessionid):add_child(get_online_users_layout:form()))); end return true; end local add_user_desc = adhoc_new("Add User", "http://jabber.org/protocol/admin#add-user", add_user_command_handler, "admin"); local get_online_users_desc = adhoc_new("Get List of Online Users", "http://jabber.org/protocol/admin#get-online-users", get_online_users_command_handler, "admin"); function module.unload() module:remove_item("adhoc", add_user_desc); module:remove_item("adhoc", get_online_users_desc); end module:add_item("adhoc", add_user_desc); module:add_item("adhoc", get_online_users_desc);
mod_adhoc_cmd_admin: Fix session leak
mod_adhoc_cmd_admin: Fix session leak
Lua
mit
brahmi2/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,apung/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,mardraze/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,olax/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,asdofindia/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,softer/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,apung/prosody-modules,brahmi2/prosody-modules,prosody-modules/import,mmusial/prosody-modules,mmusial/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,1st8/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,syntafin/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,joewalker/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules
54c69cd97e1690d2a3aefb81fd4d5017814883f0
lua/entities/starfall_hologram/init.lua
lua/entities/starfall_hologram/init.lua
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include( "shared.lua" ) util.AddNetworkString "starfall_hologram_scale" util.AddNetworkString "starfall_hologram_clip" function ENT:Initialize() self.BaseClass.Initialize() self:SetSolid(SOLID_NONE) self:SetMoveType(MOVETYPE_NOCLIP) -- TODO: custom movetype hook? self:DrawShadow( false ) end function ENT:SetScale(scale) net.Start("starfall_hologram_scale") net.WriteEntity(self) net.WriteDouble(scale.x) net.WriteDouble(scale.y) net.WriteDouble(scale.z) net.Broadcast() end function ENT:UpdateClip(index, enabled, origin, normal, islocal) net.Start("starfall_hologram_clip") net.WriteEntity(self) net.WriteUInt(index,16) net.WriteBit(enabled) net.WriteDouble(origin.x) net.WriteDouble(origin.y) net.WriteDouble(origin.z) net.WriteDouble(normal.x) net.WriteDouble(normal.y) net.WriteDouble(normal.z) net.WriteBit(islocal) net.Broadcast() end
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include( "shared.lua" ) util.AddNetworkString "starfall_hologram_scale" util.AddNetworkString "starfall_hologram_clip" function ENT:Initialize() self.BaseClass.Initialize() self:SetSolid(SOLID_NONE) self:SetMoveType(MOVETYPE_NOCLIP) -- TODO: custom movetype hook? self:DrawShadow( false ) end function ENT:SetScale ( scale ) net.Start( "starfall_hologram_scale" ) net.WriteUInt( self:EntIndex(), 32 ) net.WriteDouble( scale.x ) net.WriteDouble( scale.y ) net.WriteDouble( scale.z ) net.Broadcast() end function ENT:UpdateClip(index, enabled, origin, normal, islocal) net.Start("starfall_hologram_clip") net.WriteEntity(self) net.WriteUInt(index,16) net.WriteBit(enabled) net.WriteDouble(origin.x) net.WriteDouble(origin.y) net.WriteDouble(origin.z) net.WriteDouble(normal.x) net.WriteDouble(normal.y) net.WriteDouble(normal.z) net.WriteBit(islocal) net.Broadcast() end
Fix hologram scaling
Fix hologram scaling net.WriteEntity used to send a 32 bit unsigned integer, which is expected on the client side. Garry seems to have changed that. Sending the entIndex as 32-bit unsigned integer should work properly.
Lua
bsd-3-clause
INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall
a71faab2e8680a3a3ea0a1c8efe88e6d4fa5a4de
mod_auto_accept_subscriptions/mod_auto_accept_subscriptions.lua
mod_auto_accept_subscriptions/mod_auto_accept_subscriptions.lua
local rostermanager = require "core.rostermanager"; local jid = require "util.jid"; local st = require "util.stanza"; local core_post_stanza = prosody.core_post_stanza; local function handle_inbound_subscription_request(origin, stanza) local to_bare, from_bare = jid.bare(stanza.attr.to), jid.bare(stanza.attr.from); local node, host = jid.split(to_bare); stanza.attr.from, stanza.attr.to = from_bare, to_bare; module:log("info", "Auto-accepting inbound subscription request from %s to %s", from_bare, to_bare); if not rostermanager.is_contact_subscribed(node, host, from_bare) then core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"}), true); -- acknowledging receipt module:log("debug", "receipt acknowledged"); if rostermanager.set_contact_pending_in(node, host, from_bare) then module:log("debug", "set pending in"); if rostermanager.subscribed(node, host, from_bare) then module:log("debug", "set subscribed"); rostermanager.roster_push(node, host, to_bare); module:log("debug", "pushed roster item"); local subscribed_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribed"; core_post_stanza(hosts[host], subscribed_stanza); module:log("debug", "sent subscribed"); hosts[host].modules.presence.send_presence_of_available_resources(node, host, to_bare, origin); module:log("debug", "sent available presence of all resources"); -- Add return subscription from user to contact local subscribe_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribe"; if rostermanager.set_contact_pending_out(node, host, from_bare) then rostermanager.roster_push(node, host, from_bare); end core_post_stanza(hosts[host], subscribe_stanza); return true; end end end module:log("warn", "Failed to auto-accept subscription request from %s to %s", from_bare, to_bare); end module:hook("presence/bare", function (event) local stanza = event.stanza; if stanza.attr.type == "subscribe" then handle_inbound_subscription_request(event.origin, stanza); return true; end end, 0.1);
local rostermanager = require "core.rostermanager"; local jid = require "util.jid"; local st = require "util.stanza"; local core_post_stanza = prosody.core_post_stanza; local function handle_inbound_subscription_request(origin, stanza) local to_bare, from_bare = jid.bare(stanza.attr.to), jid.bare(stanza.attr.from); local node, host = jid.split(to_bare); stanza.attr.from, stanza.attr.to = from_bare, to_bare; module:log("info", "Auto-accepting inbound subscription request from %s to %s", tostring(from_bare), tostring(to_bare)); if not rostermanager.is_contact_subscribed(node, host, from_bare) then core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"}), true); -- acknowledging receipt module:log("debug", "receipt acknowledged"); if rostermanager.set_contact_pending_in(node, host, from_bare) then module:log("debug", "set pending in"); if rostermanager.subscribed(node, host, from_bare) then module:log("debug", "set subscribed"); rostermanager.roster_push(node, host, to_bare); module:log("debug", "pushed roster item"); local subscribed_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribed"; core_post_stanza(hosts[host], subscribed_stanza); module:log("debug", "sent subscribed"); hosts[host].modules.presence.send_presence_of_available_resources(node, host, to_bare, origin); module:log("debug", "sent available presence of all resources"); -- Add return subscription from user to contact local subscribe_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribe"; if rostermanager.set_contact_pending_out(node, host, from_bare) then rostermanager.roster_push(node, host, from_bare); end core_post_stanza(hosts[host], subscribe_stanza); return true; end end end module:log("warn", "Failed to auto-accept subscription request from %s to %s", tostring(from_bare), tostring(to_bare)); end module:hook("presence/bare", function (event) local stanza = event.stanza; if stanza.attr.type == "subscribe" then handle_inbound_subscription_request(event.origin, stanza); return true; end end, 0.1);
mod_auto_accept_subscriptions: Fix passing nil in log message
mod_auto_accept_subscriptions: Fix passing nil in log message
Lua
mit
prosody-modules/import,syntafin/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,1st8/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,1st8/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,1st8/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,amenophis1er/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules
91856a9242125388336d88140c840938704e9053
modules/admin-full/luasrc/controller/admin/network.lua
modules/admin-full/luasrc/controller/admin/network.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$ ]]-- module("luci.controller.admin.network", package.seeall) function index() require("luci.i18n") local uci = require("luci.model.uci").cursor() local i18n = luci.i18n.translate local page = node("admin", "network") page.target = alias("admin", "network", "network") page.title = i18n("network") page.order = 50 page.index = true local page = node("admin", "network", "vlan") page.target = cbi("admin_network/vlan") page.title = i18n("a_n_switch") page.order = 20 local page = entry({"admin", "network", "wireless"}, arcombine(template("admin_network/wifi_overview"), cbi("admin_network/wifi")), i18n("wifi"), 15) page.i18n = "wifi" page.leaf = true page.subindex = true uci:foreach("wireless", "wifi-device", function (section) local ifc = section[".name"] entry({"admin", "network", "wireless", ifc}, true, ifc:upper()).i18n = "wifi" end ) local page = entry({"admin", "network", "wireless_join"}, call("wifi_join"), nil, 16) page.i18n = "wifi" page.leaf = true local page = entry({"admin", "network", "network"}, arcombine(cbi("admin_network/network"), cbi("admin_network/ifaces")), i18n("interfaces", "Schnittstellen"), 10) page.leaf = true page.subindex = true local page = entry({"admin", "network", "add"}, cbi("admin_network/iface_add"), nil) page.leaf = true uci:foreach("network", "interface", function (section) local ifc = section[".name"] if ifc ~= "loopback" then entry({"admin", "network", "network", ifc}, true, ifc:upper()) end end ) local page = node("admin", "network", "dhcp") page.target = cbi("admin_network/dhcp") page.title = "DHCP" page.order = 30 page.subindex = true entry( {"admin", "network", "dhcp", "leases"}, cbi("admin_network/dhcpleases"), i18n("dhcp_leases") ) local page = node("admin", "network", "hosts") page.target = cbi("admin_network/hosts") page.title = i18n("hostnames", "Hostnames") page.order = 40 local page = node("admin", "network", "routes") page.target = cbi("admin_network/routes") page.title = i18n("a_n_routes_static") page.order = 50 end function wifi_join() local function param(x) return luci.http.formvalue(x) end local function ptable(x) x = param(x) return x and (type(x) ~= "table" and { x } or x) or {} end local dev = param("device") local ssid = param("join") if dev and ssid then local wep = (tonumber(param("wep")) == 1) local wpa = tonumber(param("wpa_version")) or 0 local channel = tonumber(param("channel")) local mode = param("mode") local bssid = param("bssid") local confirm = (param("confirm") == "1") local cancel = param("cancel") and true or false if confirm and not cancel then local fixed_bssid = (param("fixed_bssid") == "1") local replace_net = (param("replace_net") == "1") local autoconnect = (param("autoconnect") == "1") local attach_intf = param("attach_intf") local uci = require "luci.model.uci".cursor() if replace_net then uci:delete_all("wireless", "wifi-iface") end local wificonf = { device = dev, mode = (mode == "Ad-Hoc" and "adhoc" or "sta"), ssid = ssid } if attach_intf and uci:get("network", attach_intf, "ifname") then -- target network already has a interface, make it a bridge uci:set("network", attach_intf, "type", "bridge") uci:save("network") uci:commit("network") if autoconnect then require "luci.sys".call("/sbin/ifup " .. attach_intf) end end if fixed_bssid then wificonf.bssid = bssid end if wep then wificonf.encryption = "wep" wificonf.key = param("key") elseif wpa > 0 then wificonf.encryption = param("wpa_suite") wificonf.key = param("key") end uci:section("wireless", "wifi-iface", nil, wificonf) uci:delete("wireless", dev, "disabled") uci:set("wireless", dev, "channel", channel) uci:save("wireless") uci:commit("wireless") if autoconnect then require "luci.sys".call("/sbin/wifi") end luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless", dev)) elseif cancel then luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless_join?device=" .. dev)) else luci.template.render("admin_network/wifi_join_settings") end else luci.template.render("admin_network/wifi_join") end end
--[[ 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$ ]]-- module("luci.controller.admin.network", package.seeall) function index() require("luci.i18n") local uci = require("luci.model.uci").cursor() local i18n = luci.i18n.translate local page = node("admin", "network") page.target = alias("admin", "network", "network") page.title = i18n("network") page.order = 50 page.index = true local page = node("admin", "network", "vlan") page.target = cbi("admin_network/vlan") page.title = i18n("a_n_switch") page.order = 20 local page = entry({"admin", "network", "wireless"}, arcombine(template("admin_network/wifi_overview"), cbi("admin_network/wifi")), i18n("wifi"), 15) page.i18n = "wifi" page.leaf = true page.subindex = true uci:foreach("wireless", "wifi-device", function (section) local ifc = section[".name"] entry({"admin", "network", "wireless", ifc}, true, ifc:upper()).i18n = "wifi" end ) local page = entry({"admin", "network", "wireless_join"}, call("wifi_join"), nil, 16) page.i18n = "wifi" page.leaf = true local page = entry({"admin", "network", "wireless_delete"}, call("wifi_delete"), nil, 16) page.i18n = "wifi" page.leaf = true local page = entry({"admin", "network", "network"}, arcombine(cbi("admin_network/network"), cbi("admin_network/ifaces")), i18n("interfaces", "Schnittstellen"), 10) page.leaf = true page.subindex = true local page = entry({"admin", "network", "add"}, cbi("admin_network/iface_add"), nil) page.leaf = true uci:foreach("network", "interface", function (section) local ifc = section[".name"] if ifc ~= "loopback" then entry({"admin", "network", "network", ifc}, true, ifc:upper()) end end ) local page = node("admin", "network", "dhcp") page.target = cbi("admin_network/dhcp") page.title = "DHCP" page.order = 30 page.subindex = true entry( {"admin", "network", "dhcp", "leases"}, cbi("admin_network/dhcpleases"), i18n("dhcp_leases") ) local page = node("admin", "network", "hosts") page.target = cbi("admin_network/hosts") page.title = i18n("hostnames", "Hostnames") page.order = 40 local page = node("admin", "network", "routes") page.target = cbi("admin_network/routes") page.title = i18n("a_n_routes_static") page.order = 50 end function wifi_join() local function param(x) return luci.http.formvalue(x) end local function ptable(x) x = param(x) return x and (type(x) ~= "table" and { x } or x) or {} end local dev = param("device") local ssid = param("join") if dev and ssid then local wep = (tonumber(param("wep")) == 1) local wpa = tonumber(param("wpa_version")) or 0 local channel = tonumber(param("channel")) local mode = param("mode") local bssid = param("bssid") local confirm = (param("confirm") == "1") local cancel = param("cancel") and true or false if confirm and not cancel then local fixed_bssid = (param("fixed_bssid") == "1") local replace_net = (param("replace_net") == "1") local autoconnect = (param("autoconnect") == "1") local attach_intf = param("attach_intf") local uci = require "luci.model.uci".cursor() if replace_net then uci:delete_all("wireless", "wifi-iface") end local wificonf = { device = dev, mode = (mode == "Ad-Hoc" and "adhoc" or "sta"), ssid = ssid } if attach_intf and uci:get("network", attach_intf) == "interface" then -- target network already has a interface, make it a bridge uci:set("network", attach_intf, "type", "bridge") uci:save("network") uci:commit("network") wificonf.network = attach_intf if autoconnect then require "luci.sys".call("/sbin/ifup " .. attach_intf) end end if fixed_bssid then wificonf.bssid = bssid end if wep then wificonf.encryption = "wep" wificonf.key = param("key") elseif wpa > 0 then wificonf.encryption = param("wpa_suite") wificonf.key = param("key") end local s = uci:section("wireless", "wifi-iface", nil, wificonf) uci:delete("wireless", dev, "disabled") uci:set("wireless", dev, "channel", channel) uci:save("wireless") uci:commit("wireless") if autoconnect then require "luci.sys".call("/sbin/wifi") end luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless")) elseif cancel then luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless_join?device=" .. dev)) else luci.template.render("admin_network/wifi_join_settings") end else luci.template.render("admin_network/wifi_join") end end function wifi_delete(network) local uci = require "luci.model.uci".cursor() local wlm = require "luci.model.wireless" wlm.init(uci) wlm:del_network(network) uci:save("wireless") luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless")) end
modules/admin-full: support deleting wireless networks and fix wireless join
modules/admin-full: support deleting wireless networks and fix wireless join
Lua
apache-2.0
teslamint/luci,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,981213/luci-1,jlopenwrtluci/luci,teslamint/luci,obsy/luci,jlopenwrtluci/luci,NeoRaider/luci,maxrio/luci981213,taiha/luci,schidler/ionic-luci,remakeelectric/luci,lcf258/openwrtcn,hnyman/luci,openwrt-es/openwrt-luci,RuiChen1113/luci,dismantl/luci-0.12,chris5560/openwrt-luci,palmettos/cnLuCI,ff94315/luci-1,lcf258/openwrtcn,RuiChen1113/luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,joaofvieira/luci,palmettos/test,florian-shellfire/luci,lcf258/openwrtcn,slayerrensky/luci,remakeelectric/luci,mumuqz/luci,wongsyrone/luci-1,fkooman/luci,marcel-sch/luci,lbthomsen/openwrt-luci,aa65535/luci,tcatm/luci,cshore/luci,schidler/ionic-luci,harveyhu2012/luci,wongsyrone/luci-1,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,teslamint/luci,ff94315/luci-1,zhaoxx063/luci,cshore-firmware/openwrt-luci,slayerrensky/luci,ollie27/openwrt_luci,openwrt/luci,maxrio/luci981213,nwf/openwrt-luci,harveyhu2012/luci,david-xiao/luci,nmav/luci,bright-things/ionic-luci,rogerpueyo/luci,dwmw2/luci,joaofvieira/luci,981213/luci-1,mumuqz/luci,thess/OpenWrt-luci,taiha/luci,oyido/luci,forward619/luci,dwmw2/luci,lbthomsen/openwrt-luci,Hostle/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,kuoruan/luci,florian-shellfire/luci,joaofvieira/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,Wedmer/luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,thesabbir/luci,kuoruan/luci,NeoRaider/luci,cappiewu/luci,MinFu/luci,wongsyrone/luci-1,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,obsy/luci,openwrt-es/openwrt-luci,fkooman/luci,cappiewu/luci,nmav/luci,taiha/luci,forward619/luci,ollie27/openwrt_luci,Noltari/luci,male-puppies/luci,Noltari/luci,NeoRaider/luci,RedSnake64/openwrt-luci-packages,tcatm/luci,daofeng2015/luci,mumuqz/luci,LuttyYang/luci,hnyman/luci,remakeelectric/luci,kuoruan/lede-luci,bittorf/luci,urueedi/luci,tcatm/luci,aa65535/luci,slayerrensky/luci,aircross/OpenWrt-Firefly-LuCI,Noltari/luci,jlopenwrtluci/luci,oneru/luci,nmav/luci,ReclaimYourPrivacy/cloak-luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,dwmw2/luci,taiha/luci,cshore/luci,LuttyYang/luci,tcatm/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,981213/luci-1,sujeet14108/luci,rogerpueyo/luci,Sakura-Winkey/LuCI,daofeng2015/luci,chris5560/openwrt-luci,nwf/openwrt-luci,Noltari/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,artynet/luci,david-xiao/luci,nmav/luci,wongsyrone/luci-1,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,hnyman/luci,nwf/openwrt-luci,kuoruan/lede-luci,aa65535/luci,bittorf/luci,fkooman/luci,tcatm/luci,ff94315/luci-1,dismantl/luci-0.12,Sakura-Winkey/LuCI,ff94315/luci-1,slayerrensky/luci,NeoRaider/luci,openwrt/luci,shangjiyu/luci-with-extra,teslamint/luci,daofeng2015/luci,artynet/luci,shangjiyu/luci-with-extra,cshore/luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,chris5560/openwrt-luci,thesabbir/luci,florian-shellfire/luci,oyido/luci,dwmw2/luci,palmettos/cnLuCI,teslamint/luci,ollie27/openwrt_luci,oyido/luci,forward619/luci,opentechinstitute/luci,keyidadi/luci,oyido/luci,male-puppies/luci,RedSnake64/openwrt-luci-packages,sujeet14108/luci,lbthomsen/openwrt-luci,opentechinstitute/luci,keyidadi/luci,deepak78/new-luci,tobiaswaldvogel/luci,taiha/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,MinFu/luci,artynet/luci,oyido/luci,tobiaswaldvogel/luci,LuttyYang/luci,jchuang1977/luci-1,daofeng2015/luci,deepak78/new-luci,kuoruan/lede-luci,lcf258/openwrtcn,aa65535/luci,Hostle/luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,tobiaswaldvogel/luci,taiha/luci,opentechinstitute/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,sujeet14108/luci,openwrt/luci,marcel-sch/luci,lcf258/openwrtcn,NeoRaider/luci,lcf258/openwrtcn,RuiChen1113/luci,oyido/luci,cappiewu/luci,bittorf/luci,oneru/luci,marcel-sch/luci,thess/OpenWrt-luci,bittorf/luci,taiha/luci,forward619/luci,cappiewu/luci,palmettos/test,Wedmer/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,shangjiyu/luci-with-extra,thess/OpenWrt-luci,tobiaswaldvogel/luci,aa65535/luci,jorgifumi/luci,cappiewu/luci,fkooman/luci,Hostle/luci,bright-things/ionic-luci,LuttyYang/luci,jchuang1977/luci-1,marcel-sch/luci,bright-things/ionic-luci,rogerpueyo/luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,artynet/luci,Noltari/luci,deepak78/new-luci,jlopenwrtluci/luci,RuiChen1113/luci,shangjiyu/luci-with-extra,tcatm/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,aa65535/luci,jorgifumi/luci,tobiaswaldvogel/luci,urueedi/luci,deepak78/new-luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,wongsyrone/luci-1,LuttyYang/luci,bright-things/ionic-luci,cshore/luci,sujeet14108/luci,jlopenwrtluci/luci,LuttyYang/luci,kuoruan/lede-luci,jorgifumi/luci,forward619/luci,Sakura-Winkey/LuCI,mumuqz/luci,db260179/openwrt-bpi-r1-luci,kuoruan/luci,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,keyidadi/luci,daofeng2015/luci,florian-shellfire/luci,david-xiao/luci,joaofvieira/luci,openwrt/luci,remakeelectric/luci,LuttyYang/luci,oyido/luci,opentechinstitute/luci,ff94315/luci-1,tobiaswaldvogel/luci,hnyman/luci,Noltari/luci,Hostle/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,LuttyYang/luci,bittorf/luci,obsy/luci,remakeelectric/luci,marcel-sch/luci,nmav/luci,remakeelectric/luci,jorgifumi/luci,RuiChen1113/luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,urueedi/luci,mumuqz/luci,bright-things/ionic-luci,cappiewu/luci,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,zhaoxx063/luci,florian-shellfire/luci,palmettos/test,jchuang1977/luci-1,nmav/luci,Noltari/luci,oneru/luci,openwrt-es/openwrt-luci,hnyman/luci,harveyhu2012/luci,MinFu/luci,oneru/luci,zhaoxx063/luci,bittorf/luci,deepak78/new-luci,rogerpueyo/luci,deepak78/new-luci,jorgifumi/luci,ff94315/luci-1,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,urueedi/luci,schidler/ionic-luci,marcel-sch/luci,kuoruan/lede-luci,obsy/luci,slayerrensky/luci,kuoruan/luci,obsy/luci,jchuang1977/luci-1,male-puppies/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,nwf/openwrt-luci,nwf/openwrt-luci,wongsyrone/luci-1,teslamint/luci,Sakura-Winkey/LuCI,keyidadi/luci,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,oneru/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,kuoruan/lede-luci,remakeelectric/luci,obsy/luci,oneru/luci,cshore-firmware/openwrt-luci,male-puppies/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,MinFu/luci,Wedmer/luci,ollie27/openwrt_luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,openwrt/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,MinFu/luci,jlopenwrtluci/luci,chris5560/openwrt-luci,openwrt/luci,tobiaswaldvogel/luci,cappiewu/luci,sujeet14108/luci,openwrt/luci,palmettos/test,opentechinstitute/luci,forward619/luci,maxrio/luci981213,palmettos/cnLuCI,Wedmer/luci,male-puppies/luci,thess/OpenWrt-luci,schidler/ionic-luci,thesabbir/luci,jchuang1977/luci-1,RuiChen1113/luci,MinFu/luci,shangjiyu/luci-with-extra,thesabbir/luci,artynet/luci,artynet/luci,urueedi/luci,oyido/luci,fkooman/luci,schidler/ionic-luci,harveyhu2012/luci,david-xiao/luci,LazyZhu/openwrt-luci-trunk-mod,cshore-firmware/openwrt-luci,chris5560/openwrt-luci,urueedi/luci,hnyman/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,RuiChen1113/luci,urueedi/luci,zhaoxx063/luci,dwmw2/luci,MinFu/luci,kuoruan/luci,wongsyrone/luci-1,nmav/luci,zhaoxx063/luci,deepak78/new-luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,shangjiyu/luci-with-extra,keyidadi/luci,aa65535/luci,forward619/luci,Sakura-Winkey/LuCI,male-puppies/luci,david-xiao/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,marcel-sch/luci,dwmw2/luci,rogerpueyo/luci,fkooman/luci,981213/luci-1,nmav/luci,openwrt/luci,RuiChen1113/luci,bittorf/luci,cshore/luci,db260179/openwrt-bpi-r1-luci,bright-things/ionic-luci,artynet/luci,jorgifumi/luci,981213/luci-1,daofeng2015/luci,palmettos/cnLuCI,cshore/luci,ReclaimYourPrivacy/cloak-luci,Kyklas/luci-proto-hso,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,aa65535/luci,mumuqz/luci,maxrio/luci981213,chris5560/openwrt-luci,palmettos/cnLuCI,cshore-firmware/openwrt-luci,harveyhu2012/luci,Kyklas/luci-proto-hso,MinFu/luci,lcf258/openwrtcn,slayerrensky/luci,cshore/luci,cappiewu/luci,artynet/luci,florian-shellfire/luci,david-xiao/luci,maxrio/luci981213,tcatm/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,dismantl/luci-0.12,981213/luci-1,taiha/luci,zhaoxx063/luci,bright-things/ionic-luci,dwmw2/luci,david-xiao/luci,kuoruan/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,thess/OpenWrt-luci,thesabbir/luci,NeoRaider/luci,Hostle/luci,cshore-firmware/openwrt-luci,teslamint/luci,Hostle/luci,openwrt-es/openwrt-luci,urueedi/luci,florian-shellfire/luci,jchuang1977/luci-1,NeoRaider/luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,mumuqz/luci,daofeng2015/luci,Noltari/luci,lcf258/openwrtcn,slayerrensky/luci,daofeng2015/luci,remakeelectric/luci,marcel-sch/luci,teslamint/luci,Hostle/luci,schidler/ionic-luci,hnyman/luci,thesabbir/luci,nwf/openwrt-luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,Kyklas/luci-proto-hso,male-puppies/luci,keyidadi/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,wongsyrone/luci-1,mumuqz/luci,lbthomsen/openwrt-luci,nwf/openwrt-luci,cshore-firmware/openwrt-luci,forward619/luci,zhaoxx063/luci,obsy/luci,schidler/ionic-luci,jorgifumi/luci,florian-shellfire/luci,tcatm/luci,RedSnake64/openwrt-luci-packages,RedSnake64/openwrt-luci-packages,palmettos/test,harveyhu2012/luci,male-puppies/luci,Wedmer/luci,joaofvieira/luci,schidler/ionic-luci,cshore/luci,Noltari/luci,joaofvieira/luci,thesabbir/luci,joaofvieira/luci,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,981213/luci-1,sujeet14108/luci,opentechinstitute/luci,palmettos/cnLuCI,bright-things/ionic-luci,Wedmer/luci,palmettos/test,ollie27/openwrt_luci,hnyman/luci,Kyklas/luci-proto-hso,Hostle/openwrt-luci-multi-user,palmettos/test,chris5560/openwrt-luci,david-xiao/luci,nwf/openwrt-luci,palmettos/cnLuCI,obsy/luci,fkooman/luci,slayerrensky/luci,rogerpueyo/luci,bittorf/luci,maxrio/luci981213
196a95f4c021dd0520a63f22496910c00ca5669d
modules/client_options/options.lua
modules/client_options/options.lua
Options = {} local optionsWindow local optionsButton function Options.init() optionsWindow = displayUI('options.otui') optionsWindow:setVisible(false) optionsButton = TopMenu.addButton('settingsButton', 'Options (Ctrl+O)', '/core_styles/icons/settings.png', Options.toggle) Hotkeys.bind('Ctrl+O', Options.toggle) -- load settings local booleanOptions = { vsync = true, showfps = true, fullscreen = false, classicControl = false } for k,v in pairs(booleanOptions) do Settings.setDefault(k, v) Options.changeOption(k, Settings.getBoolean(k)) end end function Options.terminate() Hotkeys.unbind('Ctrl+O') optionsWindow:destroy() optionsWindow = nil optionsButton:destroy() optionsButton = nil end function Options.toggle() if optionsWindow:isVisible() then Options.hide() else Options.show() end end function Options.show() optionsWindow:show() optionsWindow:lock() end function Options.hide() optionsWindow:unlock() optionsWindow:hide() end function Options.openWebpage() displayErrorBox("Error", "Not implemented yet") end -- private functions function Options.changeOption(key, status) if key == 'vsync' then g_window.setVerticalSync(status) elseif key == 'showfps' then addEvent(function() local frameCounter = rootWidget:recursiveGetChildById('frameCounter') if frameCounter then frameCounter:setVisible(status) end end) elseif key == 'fullscreen' then addEvent(function() g_window.setFullscreen(status) end) end Settings.set(key, status) Options[key] = status end
Options = {} local optionsWindow local optionsButton function Options.init() -- load settings local booleanOptions = { vsync = true, showfps = true, fullscreen = false, classicControl = false } for k,v in pairs(booleanOptions) do Settings.setDefault(k, v) Options.changeOption(k, Settings.getBoolean(k)) end optionsWindow = displayUI('options.otui') optionsWindow:setVisible(false) optionsButton = TopMenu.addButton('settingsButton', 'Options (Ctrl+O)', '/core_styles/icons/settings.png', Options.toggle) Hotkeys.bind('Ctrl+O', Options.toggle) end function Options.terminate() Hotkeys.unbind('Ctrl+O') optionsWindow:destroy() optionsWindow = nil optionsButton:destroy() optionsButton = nil end function Options.toggle() if optionsWindow:isVisible() then Options.hide() else Options.show() end end function Options.show() optionsWindow:show() optionsWindow:lock() end function Options.hide() optionsWindow:unlock() optionsWindow:hide() end function Options.openWebpage() displayErrorBox("Error", "Not implemented yet") end -- private functions function Options.changeOption(key, status) if key == 'vsync' then g_window.setVerticalSync(status) elseif key == 'showfps' then addEvent(function() local frameCounter = rootWidget:recursiveGetChildById('frameCounter') if frameCounter then frameCounter:setVisible(status) end end) elseif key == 'fullscreen' then addEvent(function() g_window.setFullscreen(status) end) end Settings.set(key, status) Options[key] = status end
fix options
fix options
Lua
mit
gpedro/otclient,gpedro/otclient,Radseq/otclient,EvilHero90/otclient,dreamsxin/otclient,EvilHero90/otclient,Cavitt/otclient_mapgen,Radseq/otclient,dreamsxin/otclient,kwketh/otclient,kwketh/otclient,gpedro/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen
859cb31f5dea9a1134595d2d019556ee7c368db6
modules/game_cooldown/cooldown.lua
modules/game_cooldown/cooldown.lua
local ProgressCallback = { update = 1, finish = 2 } cooldownWindow = nil cooldownButton = nil contentsPanel = nil spellCooldownPanel = nil function init() connect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton = modules.client_topmenu.addRightGameToggleButton('cooldownButton', tr('Cooldowns'), '/images/topbuttons/cooldowns', toggle) cooldownButton:setOn(true) cooldownButton:hide() cooldownWindow = g_ui.loadUI('cooldown', modules.game_interface.getRightPanel()) cooldownWindow:disableResize() cooldownWindow:setup() contentsPanel = cooldownWindow:getChildById('contentsPanel') spellCooldownPanel = contentsPanel:getChildById('spellCooldownPanel') if g_game.isOnline() then online() end end function terminate() disconnect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton:destroy() cooldownWindow:destroy() end function onMiniWindowClose() cooldownButton:setOn(false) end function toggle() if cooldownButton:isOn() then cooldownWindow:close() cooldownButton:setOn(false) else cooldownWindow:open() cooldownButton:setOn(true) end end function online() if g_game.getFeature(GameSpellList) then cooldownButton:show() else cooldownButton:hide() cooldownWindow:close() end end function removeCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:destroy() progressRect.icon = nil end progressRect = nil end function turnOffCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:setOn(false) progressRect.icon = nil end -- create particles --[[local particle = g_ui.createWidget('GroupCooldownParticles', progressRect) particle:fill('parent') scheduleEvent(function() particle:destroy() end, 1000) -- hack until onEffectEnd]] progressRect = nil end function initCooldown(progressRect, updateCallback, finishCallback) progressRect:setPercent(0) progressRect.callback = {} progressRect.callback[ProgressCallback.update] = updateCallback progressRect.callback[ProgressCallback.finish] = finishCallback updateCallback() end function updateCooldown(progressRect, interval) progressRect:setPercent(progressRect:getPercent() + 5) if progressRect:getPercent() < 100 then removeEvent(progressRect.event) progressRect.event = scheduleEvent(function() progressRect.callback[ProgressCallback.update]() end, interval) else progressRect.callback[ProgressCallback.finish]() end end function onSpellCooldown(iconId, duration) local spell, profile, spellName = Spells.getSpellByIcon(iconId) if not spellName then return end clientIconId = Spells.getClientId(spellName) if not clientIconId then return end local icon = spellCooldownPanel:getChildById(spellName) if not icon then icon = g_ui.createWidget('SpellIcon', spellCooldownPanel) icon:setId(spellName) end icon:setImageSource('/images/game/spells/' .. SpelllistSettings[profile].iconFile) icon:setImageClip(Spells.getImageClip(clientIconId, profile)) local progressRect = icon:getChildById(spellName) if not progressRect then progressRect = g_ui.createWidget('SpellProgressRect', icon) progressRect:setId(spellName) progressRect.icon = icon progressRect:fill('parent') else progressRect:setPercent(0) end progressRect:setTooltip(spellName) local updateFunc = function() updateCooldown(progressRect, duration/19) end local finishFunc = function() removeCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end function onSpellGroupCooldown(groupId, duration) if not SpellGroups[groupId] then return end local icon = contentsPanel:getChildById('groupIcon' .. SpellGroups[groupId]) local progressRect = contentsPanel:getChildById('progressRect' .. SpellGroups[groupId]) if icon then icon:setOn(true) removeEvent(icon.event) end progressRect.icon = icon if progressRect then removeEvent(progressRect.event) local updateFunc = function() updateCooldown(progressRect, duration/19) end local finishFunc = function() turnOffCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end end
local ProgressCallback = { update = 1, finish = 2 } cooldownWindow = nil cooldownButton = nil contentsPanel = nil spellCooldownPanel = nil lastPlayer = nil function init() connect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton = modules.client_topmenu.addRightGameToggleButton('cooldownButton', tr('Cooldowns'), '/images/topbuttons/cooldowns', toggle) cooldownButton:setOn(true) cooldownButton:hide() cooldownWindow = g_ui.loadUI('cooldown', modules.game_interface.getRightPanel()) cooldownWindow:disableResize() cooldownWindow:setup() contentsPanel = cooldownWindow:getChildById('contentsPanel') spellCooldownPanel = contentsPanel:getChildById('spellCooldownPanel') if g_game.isOnline() then online() end end function terminate() disconnect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton:destroy() cooldownWindow:destroy() end function onMiniWindowClose() cooldownButton:setOn(false) end function toggle() if cooldownButton:isOn() then cooldownWindow:close() cooldownButton:setOn(false) else cooldownWindow:open() cooldownButton:setOn(true) end end function online() if g_game.getFeature(GameSpellList) then cooldownButton:show() else cooldownButton:hide() cooldownWindow:close() end if lastPlayer ~= g_game.getCharacterName() then refresh() lastPlayer = g_game.getCharacterName() end end function refresh() spellCooldownPanel:destroyChildren() end function removeCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:destroy() progressRect.icon = nil end progressRect = nil end function turnOffCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:setOn(false) progressRect.icon = nil end -- create particles --[[local particle = g_ui.createWidget('GroupCooldownParticles', progressRect) particle:fill('parent') scheduleEvent(function() particle:destroy() end, 1000) -- hack until onEffectEnd]] progressRect = nil end function initCooldown(progressRect, updateCallback, finishCallback) progressRect:setPercent(0) progressRect.callback = {} progressRect.callback[ProgressCallback.update] = updateCallback progressRect.callback[ProgressCallback.finish] = finishCallback updateCallback() end function updateCooldown(progressRect, interval) progressRect:setPercent(progressRect:getPercent() + 5) if progressRect:getPercent() < 100 then removeEvent(progressRect.event) progressRect.event = scheduleEvent(function() progressRect.callback[ProgressCallback.update]() end, interval) else progressRect.callback[ProgressCallback.finish]() end end function onSpellCooldown(iconId, duration) local spell, profile, spellName = Spells.getSpellByIcon(iconId) if not spellName then return end clientIconId = Spells.getClientId(spellName) if not clientIconId then return end local icon = spellCooldownPanel:getChildById(spellName) if not icon then icon = g_ui.createWidget('SpellIcon', spellCooldownPanel) icon:setId(spellName) end icon:setImageSource('/images/game/spells/' .. SpelllistSettings[profile].iconFile) icon:setImageClip(Spells.getImageClip(clientIconId, profile)) local progressRect = icon:getChildById(spellName) if not progressRect then progressRect = g_ui.createWidget('SpellProgressRect', icon) progressRect:setId(spellName) progressRect.icon = icon progressRect:fill('parent') else progressRect:setPercent(0) end progressRect:setTooltip(spellName) local updateFunc = function() updateCooldown(progressRect, duration/19) end local finishFunc = function() removeCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end function onSpellGroupCooldown(groupId, duration) if not SpellGroups[groupId] then return end local icon = contentsPanel:getChildById('groupIcon' .. SpellGroups[groupId]) local progressRect = contentsPanel:getChildById('progressRect' .. SpellGroups[groupId]) if icon then icon:setOn(true) removeEvent(icon.event) end progressRect.icon = icon if progressRect then removeEvent(progressRect.event) local updateFunc = function() updateCooldown(progressRect, duration/19) end local finishFunc = function() turnOffCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end end
Fix #257
Fix #257
Lua
mit
gpedro/otclient,Radseq/otclient,kwketh/otclient,dreamsxin/otclient,gpedro/otclient,EvilHero90/otclient,Cavitt/otclient_mapgen,kwketh/otclient,Radseq/otclient,EvilHero90/otclient,dreamsxin/otclient,dreamsxin/otclient,gpedro/otclient,Cavitt/otclient_mapgen
c4a6e71f2128899ba8f7969acb73ddfeff022a2b
company.lua
company.lua
local defaultVars = {cash=0,employees=0,workSpeed=1,emplSpeed=1,loyalty=65,currentProject={},completedProjects=0,lastNick="",} local defaultPVars = {name="Project0",work=0,needed=60,reward=150,time=70,timespent=0} local function loadUsers() return table.load("compData.txt") or {} end compData = compData or loadUsers() local function metafy(t) setmetatable(t,{__index=function(t,k) if defaultVars[k] then t[k]=defaultVars[k] return defaultVars[k] end end--[[can add new vars to old tables, need default here]]}) setmetatable(t.currentProject,{__index=function(t,k) if defaultPVars[k] then t[k]=defaultPVars[k] return defaultPVars[k] end end}) end setmetatable(compData,{__index=function(t,k) t[k]={} metafy(t[k]) return t[k] end}) for k,v in pairs(compData) do if type(v)=="table" then metafy(v) end end local activeProjects = {} local function timedSave() table.save(compData,"compData.txt") end remUpdate("compSave") addUpdate(timedSave,60,"cracker64","compSave") local function nextProject(comp) --30-90 second for a project local time= math.random(30,90) --calculate possible work/s local ws = comp.employees+1 for i=1,9000 do if ((comp.employees)*50+100)*i + (i-1)*50 + (comp.employees+i)*time > comp.cash-((comp.employees)*50+100)*i + (i-1)*50 then break end ws = ws+1 end --adjust work/s ws = ws*(math.random(90,110)/100) local reward= math.floor(ws*time*math.random(90,110)/100) local t = {name="Project"..comp.completedProjects,lostEmpl=0,work=0,needed=math.floor(ws*time),reward=reward,time=time,timespent=0} setmetatable(t,{__index=function(t,k) if defaultPVars[k] then t[k]=defaultVars[k] return defaultVars[k] end end}) return t end local firstUpdate=false local function updateComps() if not firstUpdate then firstUpdate=true for k,v in pairs(compData) do if v.currentProject.work>0 then table.insert(activeProjects,v) end end end for k,v in pairs(activeProjects) do proj = v.currentProject proj.timespent = proj.timespent+1 proj.work = proj.work + v.workSpeed if v.employees>0 and v.cash>0 then v.cash = math.max(v.cash-v.employees,0) proj.work = proj.work + v.employees*v.emplSpeed end if proj.work >= proj.needed then activeProjects[k]=nil v.completedProjects = v.completedProjects+1 local adjust = math.max(1-(math.abs(proj.timespent-proj.time)/proj.time),0.3)*2 local reward = math.floor(proj.reward*adjust) local vreward = math.floor((3*adjust)-3.7) v.cash = v.cash + reward v.loyalty = v.loyalty + vreward local rstring = proj.name.." finished! You gained $"..reward if vreward ~= 0 then rstring = rstring .. " ,Loyalty:"..vreward end rstring = rstring.." "..(math.abs(proj.timespent-proj.time)/proj.time).."% away from goal" local lost=0 for i=1,v.employees do if math.random(0,v.loyalty/4)==0 then lost=lost+1 end end if lost>0 then v.employees=v.employees-lost rstring = rstring .. " You lost "..lost.." employees after the project." end ircSendChatQ(v.lastNick,rstring) ircSendRawQ("NOTICE "..v.lastNick.." :"..rstring) v.currentProject = nextProject(v) end end end remUpdate("company") addUpdate(updateComps,1,"jacob1","company") local function calcWork(comp) return comp.workSpeed + comp.employees*comp.emplSpeed end local function compSave(usr,chan,msg,args) timedSave() return "Saved!" end add_cmd(compSave,"compsave",101,"Saves all company data",false) local function compHelp(usr,chan,msg,args) local comp = compData[usr.host] local rstring = "Your Comp. Cash:"..comp.cash.." CurrentWorkSpeed:"..calcWork(comp).." Project("..math.floor(comp.currentProject.work/comp.currentProject.needed*100).."%):"..comp.currentProject.name.." Employees:"..comp.employees.." Loyalty:"..comp.loyalty.." Info:" if comp.loyalty<30 then rstring=rstring .. "People don't trust your company" elseif comp.loyalty<50 then rstring=rstring .. "People are wary of your company" elseif comp.loyalty<70 then rstring=rstring .. "People don't mind your company" elseif comp.loyalty<90 then rstring=rstring .. "People like your company" else rstring=rstring .. "People are in love with you" end return rstring end add_cmd(compHelp,"comp",0,"Basic information of your company",true) local function projHelp(usr,chan,msg,args) local proj = compData[usr.host].currentProject if args[1]=="start" and not proj.started then proj.started=true table.insert(activeProjects,compData[usr.host]) compData[usr.host].lastNick = usr.nick return "Started "..proj.name end local rstring = "Current ProjectName:"..proj.name.." Progress:"..proj.work.."/"..proj.needed.."("..math.floor(proj.work/proj.needed*100).."%) Reward: "..proj.reward.." TimeGoal: "..proj.time return rstring end add_cmd(projHelp,"proj",0,"Current company project information, '/proj [start]' to intiate it.",true) local function hireEmp(usr,chan,msg,args) local comp = compData[usr.host] if not msg then return "Hiring Firm Sells: Employee(1w/s, $1/s)($"..((comp.employees)*50+100)..") Manager(+.5 w/s to 10 employees, $2/s) (unavailble right now) '/hire <amt>'" end local amt= tonumber(args[1]) if amt>0 then local cost = ((comp.employees)*50+100)*amt + (amt-1)*50 --(amt*100)+(amt+comp.employees-1)*50 if comp.cash>=cost then comp.employees = comp.employees + amt comp.cash = comp.cash - cost return "You hired "..amt.." employee(s)!" else return "Not enough money for "..amt.." employee(s)!" end else return "Bad amount" end end add_cmd(hireEmp,"hire",0,"Hire workers to work on projects faster '/hire [amt]' Note: Employees may leave your company at any time during a project",true)
local defaultVars = {cash=0,employees=0,workSpeed=1,emplSpeed=1,loyalty=65,currentProject={},completedProjects=0,lastNick="",} local defaultPVars = {name="Project0",work=0,needed=60,reward=150,time=70,timespent=0} local function loadUsers() return table.load("compData.txt") or {} end compData = compData or loadUsers() local function metafy(t) setmetatable(t,{__index=function(t,k) if defaultVars[k] then t[k]=defaultVars[k] return defaultVars[k] end end--[[can add new vars to old tables, need default here]]}) setmetatable(t.currentProject,{__index=function(t,k) if defaultPVars[k] then t[k]=defaultPVars[k] return defaultPVars[k] end end}) end setmetatable(compData,{__index=function(t,k) t[k]={} metafy(t[k]) return t[k] end}) for k,v in pairs(compData) do if type(v)=="table" then metafy(v) end end local activeProjects = {} local function timedSave() table.save(compData,"compData.txt") end remUpdate("compSave") addUpdate(timedSave,60,"cracker64","compSave") local function nextProject(comp) --30-90 second for a project local time= math.random(30,90) --calculate possible work/s local ws = comp.employees+1 for i=1,9000 do if ((comp.employees)*50+100)*i + (i-1)*50 + (comp.employees+i)*time > comp.cash-((comp.employees)*50+100)*i + (i-1)*50 then break end ws = ws+1 end --adjust work/s ws = ws*(math.random(90,110)/100) local reward= math.floor(ws*time*math.random(90,110)/100) local t = {name="Project"..comp.completedProjects,lostEmpl=0,work=0,needed=math.floor(ws*time),reward=reward,time=time,timespent=0} setmetatable(t,{__index=function(t,k) if defaultPVars[k] then t[k]=defaultVars[k] return defaultVars[k] end end}) return t end local firstUpdate=false local function updateComps() if not firstUpdate then firstUpdate=true for k,v in pairs(compData) do if v.currentProject.work>0 then table.insert(activeProjects,v) end end end for k,v in pairs(activeProjects) do proj = v.currentProject proj.timespent = proj.timespent+1 proj.work = proj.work + v.workSpeed if v.employees>0 and v.cash>0 then v.cash = math.max(v.cash-v.employees,0) proj.work = proj.work + v.employees*v.emplSpeed end if proj.work >= proj.needed then activeProjects[k]=nil v.completedProjects = v.completedProjects+1 local adjust = math.max(1-(math.abs(proj.timespent-proj.time)/proj.time),0.3)*2 local reward = math.floor(proj.reward*adjust) local vreward = math.floor((3*adjust)-3.7) v.cash = v.cash + reward v.loyalty = v.loyalty + vreward local rstring = proj.name.." finished! You gained $"..reward if vreward ~= 0 then rstring = rstring .. " ,Loyalty:"..vreward end rstring = rstring.." "..(math.abs(proj.timespent-proj.time)/proj.time).."% away from goal" local lost=0 for i=1,v.employees do if math.random(0,v.loyalty/4)==0 then lost=lost+1 end end if lost>0 then v.employees=v.employees-lost rstring = rstring .. " You lost "..lost.." employees after the project." end ircSendChatQ(v.lastNick,rstring) ircSendRawQ("NOTICE "..v.lastNick.." :"..rstring) v.currentProject = nextProject(v) end end end remUpdate("company") addUpdate(updateComps,1,"jacob1","company") local function calcWork(comp) return comp.workSpeed + comp.employees*comp.emplSpeed end local function compSave(usr,chan,msg,args) timedSave() return "Saved!" end add_cmd(compSave,"compsave",101,"Saves all company data",false) local function compHelp(usr,chan,msg,args) local comp = compData[usr.host] local rstring = "Your Comp. Cash:"..comp.cash.." CurrentWorkSpeed:"..calcWork(comp).." Project("..math.floor(comp.currentProject.work/comp.currentProject.needed*100).."%):"..comp.currentProject.name.." Employees:"..comp.employees.." Loyalty:"..comp.loyalty.." Info:" if comp.loyalty<30 then rstring=rstring .. "People don't trust your company" elseif comp.loyalty<50 then rstring=rstring .. "People are wary of your company" elseif comp.loyalty<70 then rstring=rstring .. "People don't mind your company" elseif comp.loyalty<90 then rstring=rstring .. "People like your company" else rstring=rstring .. "People are in love with you" end return rstring end add_cmd(compHelp,"comp",0,"Basic information of your company",true) local function projHelp(usr,chan,msg,args) local proj = compData[usr.host].currentProject if args[1]=="start" and not proj.started then proj.started=true table.insert(activeProjects,compData[usr.host]) compData[usr.host].lastNick = usr.nick return "Started "..proj.name end local rstring = "Current ProjectName:"..proj.name.." Progress:"..proj.work.."/"..proj.needed.."("..math.floor(proj.work/proj.needed*100).."%) Reward: "..proj.reward.." TimeGoal: "..proj.time return rstring end add_cmd(projHelp,"proj",0,"Current company project information, '/proj [start]' to intiate it.",true) local function hireEmp(usr,chan,msg,args) local comp = compData[usr.host] if not msg then return "Hiring Firm Sells: Employee(1w/s, $1/s)($"..((comp.employees)*50+100)..") Manager(+.5 w/s to 10 employees, $2/s) (unavailble right now) '/hire <amt>'" end local amt= tonumber(args[1]) if amt and amt > 0 and amt == math.floor(amt) then local cost = ((comp.employees)*50+100)*amt + (amt-1)*50 --(amt*100)+(amt+comp.employees-1)*50 if comp.cash>=cost then comp.employees = comp.employees + amt comp.cash = comp.cash - cost return "You hired "..amt.." employee(s)!" else return "Not enough money for "..amt.." employee(s)!" end else return "Bad amount" end end add_cmd(hireEmp,"hire",0,"Hire workers to work on projects faster '/hire [amt]' Note: Employees may leave your company at any time during a project",true)
fix very minor ./hire issues like ./hire .5 or ./hire moo
fix very minor ./hire issues like ./hire .5 or ./hire moo
Lua
mit
GLolol/Crackbot,cracker64/Crackbot,wolfy1339/WolfyBot,Brilliant-Minds/BMNBot-2,wolfy1339/WolfyBot,GLolol/Crackbot,Brilliant-Minds/BMNBot-2,wolfy1339/WolfyBot,cracker64/Crackbot
48c847020947d7a748f35ac3e0c2581807cbbffc
frontend/ui/network/wpa_supplicant.lua
frontend/ui/network/wpa_supplicant.lua
local UIManager = require("ui/uimanager") local WpaClient = require('lj-wpaclient/wpaclient') local InfoMessage = require("ui/widget/infomessage") local sleep = require("ffi/util").sleep local T = require("ffi/util").template local _ = require("gettext") local CLIENT_INIT_ERR_MSG = _("Failed to initialize network control client: %1.") local WpaSupplicant = {} function WpaSupplicant:getNetworkList() local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end local list = wcli:scanThenGetResults() wcli:close() local saved_networks = self:getAllSavedNetworks() local curr_network = self:getCurrentNetwork() for _,network in ipairs(list) do network.signal_quality = network:getSignalQuality() local saved_nw = saved_networks:readSetting(network.ssid) if saved_nw and saved_nw.flags == network.flags then network.password = saved_nw.password end -- TODO: also verify bssid if it is not set to any if curr_network and curr_network.ssid == network.ssid then network.connected = true network.wpa_supplicant_id = curr_network.id end end return list end function WpaSupplicant:authenticateNetwork(network) -- TODO: support passwordless network local err, wcli, nw_id wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if not wcli then return false, T(CLIENT_INIT_ERR_MSG, err) end nw_id, err = wcli:addNetwork() if err then return false, err end wcli:setNetwork(nw_id, "ssid", network.ssid) wcli:setNetwork(nw_id, "psk", network.password) wcli:enableNetworkByID(nw_id) wcli:attach() local cnt = 0 local failure_cnt = 0 local max_retry = 30 local info = InfoMessage:new{text = _("Authenticating…")} local re, msg UIManager:show(info) UIManager:forceRePaint() while cnt < max_retry do local ev = wcli:readEvent() if ev ~= nil then if not ev:isScanEvent() then UIManager:close(info) info = InfoMessage:new{text = ev.msg} UIManager:show(info) UIManager:forceRePaint() end if ev:isAuthSuccessful() then network.wpa_supplicant_id = nw_id re = true break elseif ev:isAuthFailed() then failure_cnt = failure_cnt + 1 if failure_cnt > 3 then re, msg = false, _('Failed to authenticate') break end end else sleep(1) cnt = cnt + 1 end end if re ~= true then wcli:removeNetwork(nw_id) end wcli:close() UIManager:close(info) UIManager:forceRePaint() if cnt >= max_retry then re, msg = false, _('Timed out') end return re, msg end function WpaSupplicant:disconnectNetwork(network) if not network.wpa_supplicant_id then return end local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end wcli:removeNetwork(network.wpa_supplicant_id) wcli:close() end function WpaSupplicant:getCurrentNetwork() local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end local nw = wcli:getCurrentNetwork() wcli:close() return nw end function WpaSupplicant.init(network_mgr, options) network_mgr.wpa_supplicant = {ctrl_interface = options.ctrl_interface} network_mgr.getNetworkList = WpaSupplicant.getNetworkList network_mgr.getCurrentNetwork = WpaSupplicant.getCurrentNetwork network_mgr.authenticateNetwork = WpaSupplicant.authenticateNetwork network_mgr.disconnectNetwork = WpaSupplicant.disconnectNetwork end return WpaSupplicant
local UIManager = require("ui/uimanager") local WpaClient = require('lj-wpaclient/wpaclient') local InfoMessage = require("ui/widget/infomessage") local sleep = require("ffi/util").sleep local T = require("ffi/util").template local _ = require("gettext") local CLIENT_INIT_ERR_MSG = _("Failed to initialize network control client: %1.") local WpaSupplicant = {} function WpaSupplicant:getNetworkList() local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end local list = wcli:scanThenGetResults() wcli:close() local saved_networks = self:getAllSavedNetworks() local curr_network = self:getCurrentNetwork() for _,network in ipairs(list) do network.signal_quality = network:getSignalQuality() local saved_nw = saved_networks:readSetting(network.ssid) if saved_nw then -- TODO: verify saved_nw.flags == network.flags? This will break if user changed the -- network setting from [WPA-PSK-TKIP+CCMP][WPS][ESS] to [WPA-PSK-TKIP+CCMP][ESS] network.password = saved_nw.password end -- TODO: also verify bssid if it is not set to any if curr_network and curr_network.ssid == network.ssid then network.connected = true network.wpa_supplicant_id = curr_network.id end end return list end function WpaSupplicant:authenticateNetwork(network) -- TODO: support passwordless network local err, wcli, nw_id wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if not wcli then return false, T(CLIENT_INIT_ERR_MSG, err) end nw_id, err = wcli:addNetwork() if err then return false, err end wcli:setNetwork(nw_id, "ssid", network.ssid) wcli:setNetwork(nw_id, "psk", network.password) wcli:enableNetworkByID(nw_id) wcli:attach() local cnt = 0 local failure_cnt = 0 local max_retry = 30 local info = InfoMessage:new{text = _("Authenticating…")} local re, msg UIManager:show(info) UIManager:forceRePaint() while cnt < max_retry do local ev = wcli:readEvent() if ev ~= nil then if not ev:isScanEvent() then UIManager:close(info) info = InfoMessage:new{text = ev.msg} UIManager:show(info) UIManager:forceRePaint() end if ev:isAuthSuccessful() then network.wpa_supplicant_id = nw_id re = true break elseif ev:isAuthFailed() then failure_cnt = failure_cnt + 1 if failure_cnt > 3 then re, msg = false, _('Failed to authenticate') break end end else sleep(1) cnt = cnt + 1 end end if re ~= true then wcli:removeNetwork(nw_id) end wcli:close() UIManager:close(info) UIManager:forceRePaint() if cnt >= max_retry then re, msg = false, _('Timed out') end return re, msg end function WpaSupplicant:disconnectNetwork(network) if not network.wpa_supplicant_id then return end local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end wcli:removeNetwork(network.wpa_supplicant_id) wcli:close() end function WpaSupplicant:getCurrentNetwork() local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end local nw = wcli:getCurrentNetwork() wcli:close() return nw end function WpaSupplicant.init(network_mgr, options) network_mgr.wpa_supplicant = {ctrl_interface = options.ctrl_interface} network_mgr.getNetworkList = WpaSupplicant.getNetworkList network_mgr.getCurrentNetwork = WpaSupplicant.getCurrentNetwork network_mgr.authenticateNetwork = WpaSupplicant.authenticateNetwork network_mgr.disconnectNetwork = WpaSupplicant.disconnectNetwork end return WpaSupplicant
wpa_supplicant(fix): restore password bassed on SSID
wpa_supplicant(fix): restore password bassed on SSID
Lua
agpl-3.0
poire-z/koreader,mihailim/koreader,Hzj-jie/koreader,NiLuJe/koreader,NiLuJe/koreader,poire-z/koreader,robert00s/koreader,NickSavage/koreader,houqp/koreader,apletnev/koreader,pazos/koreader,Markismus/koreader,Frenzie/koreader,koreader/koreader,mwoz123/koreader,lgeek/koreader,koreader/koreader,Frenzie/koreader
4c0235ccfe92047390b445ee1c3b2a9353aa258c
src_trunk/resources/chat-system/c_chat_icon.lua
src_trunk/resources/chat-system/c_chat_icon.lua
function checkForChat() local chatting = getElementData(getLocalPlayer(), "chatting") if (isChatBoxInputActive() and chatting==0) then setElementData(getLocalPlayer(), "chatting", true, 1) elseif (not isChatBoxInputActive() and chatting==1) then setElementData(getLocalPlayer(), "chatting", true, 0) end end setTimer(checkForChat, 50, 0) setElementData(getLocalPlayer(), "chatting", true, 0) function render() local x, y, z = getElementPosition(getLocalPlayer()) for key, value in ipairs(getElementsByType("player")) do if (value==getLocalPlayer()) then local chatting = getElementData(value, "chatting") if (chatting==1) then --local px, py, pz = getElementPosition(value) local px, py, pz = getPedBonePosition(value, 6) local dist = getDistanceBetweenPoints3D(x, y, z, px, py, pz) if (dist < 300) then local reconning = getElementData(value, "reconx") if (isLineOfSightClear(x, y, z, px, py, pz, true, false, false, false ) and isElementOnScreen(value)) and not (reconning) then local screenX, screenY = getScreenFromWorldPosition(px, py, pz+0.5) if (screenX and screenY) then local draw = dxDrawImage(screenX, screenY, 70, 70, "chat.png") end end end end end end end addEventHandler("onClientRender", getRootElement(), render) chaticon = true function toggleChatIcon() if (chaticon) then outputChatBox("Chat icons are now disabled.", 255, 0, 0) chaticon = false removeEventHandler("onClientRender", getRootElement(), render) else outputChatBox("Chat icons are now enabled.", 0, 255, 0) chaticon = true addEventHandler("onClientRender", getRootElement(), render) end end addCommandHandler("togglechaticons", toggleChatIcon, false) addCommandHandler("togchaticons", toggleChatIcon, false)
function checkForChat() local chatting = getElementData(getLocalPlayer(), "chatting") if (isChatBoxInputActive() and chatting==0) then setElementData(getLocalPlayer(), "chatting", true, 1) elseif (not isChatBoxInputActive() and chatting==1) then setElementData(getLocalPlayer(), "chatting", true, 0) end end setTimer(checkForChat, 50, 0) setElementData(getLocalPlayer(), "chatting", true, 0) function render() local x, y, z = getElementPosition(getLocalPlayer()) for key, value in ipairs(getElementsByType("player")) do if (value~=getLocalPlayer()) then local chatting = getElementData(value, "chatting") if (chatting==1) then local px, py, pz = getPedBonePosition(value, 6) local dist = getDistanceBetweenPoints3D(x, y, z, px, py, pz) if (dist < 300) then local reconning = getElementData(value, "reconx") if (isLineOfSightClear(x, y, z, px, py, pz, true, false, false, false ) and isElementOnScreen(value)) and not (reconning) then local screenX, screenY = getScreenFromWorldPosition(px, py, pz+0.5) if (screenX and screenY) then local draw = dxDrawImage(screenX, screenY, 70, 70, "chat.png") end end end end end end end addEventHandler("onClientRender", getRootElement(), render) chaticon = true function toggleChatIcon() if (chaticon) then outputChatBox("Chat icons are now disabled.", 255, 0, 0) chaticon = false removeEventHandler("onClientRender", getRootElement(), render) else outputChatBox("Chat icons are now enabled.", 0, 255, 0) chaticon = true addEventHandler("onClientRender", getRootElement(), render) end end addCommandHandler("togglechaticons", toggleChatIcon, false) addCommandHandler("togchaticons", toggleChatIcon, false)
Bug fix for chat icons
Bug fix for chat icons git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@402 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
ad0d90def03eba64e749fde9717f00a28edc7f06
kong/templates/nginx_kong.lua
kong/templates/nginx_kong.lua
return [[ charset UTF-8; error_log logs/error.log ${{LOG_LEVEL}}; > if anonymous_reports then ${{SYSLOG_REPORTS}} > end > if nginx_optimizations then >-- send_timeout 60s; # default value >-- keepalive_timeout 75s; # default value >-- client_body_timeout 60s; # default value >-- client_header_timeout 60s; # default value >-- tcp_nopush on; # disabled until benchmarked >-- proxy_buffer_size 128k; # disabled until benchmarked >-- proxy_buffers 4 256k; # disabled until benchmarked >-- proxy_busy_buffers_size 256k; # disabled until benchmarked >-- reset_timedout_connection on; # disabled until benchmarked > end client_max_body_size 0; proxy_ssl_server_name on; underscores_in_headers on; real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; lua_package_path '${{LUA_PACKAGE_PATH}};;'; lua_package_cpath '${{LUA_PACKAGE_CPATH}};;'; lua_code_cache ${{LUA_CODE_CACHE}}; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict kong 4m; lua_shared_dict cache ${{MEM_CACHE_SIZE}}; lua_shared_dict cache_locks 100k; lua_shared_dict process_events 1m; lua_shared_dict cassandra 5m; lua_socket_log_errors off; > if lua_ssl_trusted_certificate then lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}'; lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}}; > end init_by_lua_block { require 'resty.core' kong = require 'kong' kong.init() } init_worker_by_lua_block { kong.init_worker() } proxy_next_upstream_tries 999; upstream kong_upstream { server 0.0.0.1; balancer_by_lua_block { kong.balancer() } keepalive ${{UPSTREAM_KEEPALIVE}}; } map $http_upgrade $upstream_connection { default keep-alive; websocket upgrade; } map $http_upgrade $upstream_upgrade { default ''; websocket websocket; } server { server_name kong; listen ${{PROXY_LISTEN}}; error_page 404 408 411 412 413 414 417 /kong_error_handler; error_page 500 502 503 504 /kong_error_handler; access_log logs/access.log; > if ssl then listen ${{PROXY_LISTEN_SSL}} ssl; ssl_certificate ${{SSL_CERT}}; ssl_certificate_key ${{SSL_CERT_KEY}}; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_certificate_by_lua_block { kong.ssl_certificate() } > end location / { set $upstream_host nil; set $upstream_scheme nil; set $upstream_connection nil; access_by_lua_block { kong.access() } proxy_http_version 1.1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $upstream_host; proxy_set_header Upgrade $upstream_upgrade; proxy_set_header Connection $upstream_connection; proxy_pass_header Server; proxy_pass $upstream_scheme://kong_upstream; header_filter_by_lua_block { kong.header_filter() } body_filter_by_lua_block { kong.body_filter() } log_by_lua_block { kong.log() } } location = /kong_error_handler { internal; content_by_lua_block { require('kong.core.error_handlers')(ngx) } } } server { server_name kong_admin; listen ${{ADMIN_LISTEN}}; access_log logs/admin_access.log; client_max_body_size 10m; client_body_buffer_size 10m; > if admin_ssl then listen ${{ADMIN_LISTEN_SSL}} ssl; ssl_certificate ${{ADMIN_SSL_CERT}}; ssl_certificate_key ${{ADMIN_SSL_CERT_KEY}}; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; > end location / { default_type application/json; content_by_lua_block { ngx.header['Access-Control-Allow-Origin'] = '*' if ngx.req.get_method() == 'OPTIONS' then ngx.header['Access-Control-Allow-Methods'] = 'GET,HEAD,PUT,PATCH,POST,DELETE' ngx.header['Access-Control-Allow-Headers'] = 'Content-Type' ngx.exit(204) end require('lapis').serve('kong.api') } } location /nginx_status { internal; access_log off; stub_status; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } } ]]
return [[ charset UTF-8; error_log logs/error.log ${{LOG_LEVEL}}; > if anonymous_reports then ${{SYSLOG_REPORTS}} > end > if nginx_optimizations then >-- send_timeout 60s; # default value >-- keepalive_timeout 75s; # default value >-- client_body_timeout 60s; # default value >-- client_header_timeout 60s; # default value >-- tcp_nopush on; # disabled until benchmarked >-- proxy_buffer_size 128k; # disabled until benchmarked >-- proxy_buffers 4 256k; # disabled until benchmarked >-- proxy_busy_buffers_size 256k; # disabled until benchmarked >-- reset_timedout_connection on; # disabled until benchmarked > end client_max_body_size 0; proxy_ssl_server_name on; underscores_in_headers on; real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; lua_package_path '${{LUA_PACKAGE_PATH}};;'; lua_package_cpath '${{LUA_PACKAGE_CPATH}};;'; lua_code_cache ${{LUA_CODE_CACHE}}; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict kong 4m; lua_shared_dict cache ${{MEM_CACHE_SIZE}}; lua_shared_dict cache_locks 100k; lua_shared_dict process_events 1m; lua_shared_dict cassandra 5m; lua_socket_log_errors off; > if lua_ssl_trusted_certificate then lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}'; lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}}; > end init_by_lua_block { require 'resty.core' kong = require 'kong' kong.init() } init_worker_by_lua_block { kong.init_worker() } proxy_next_upstream_tries 999; upstream kong_upstream { server 0.0.0.1; balancer_by_lua_block { kong.balancer() } keepalive ${{UPSTREAM_KEEPALIVE}}; } map $http_upgrade $upstream_connection { default keep-alive; websocket upgrade; } map $http_upgrade $upstream_upgrade { default ''; websocket websocket; } server { server_name kong; listen ${{PROXY_LISTEN}}; error_page 404 408 411 412 413 414 417 /kong_error_handler; error_page 500 502 503 504 /kong_error_handler; access_log logs/access.log; > if ssl then listen ${{PROXY_LISTEN_SSL}} ssl; ssl_certificate ${{SSL_CERT}}; ssl_certificate_key ${{SSL_CERT_KEY}}; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_certificate_by_lua_block { kong.ssl_certificate() } > end location / { set $upstream_host nil; set $upstream_scheme nil; access_by_lua_block { kong.access() } proxy_http_version 1.1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $upstream_host; proxy_set_header Upgrade $upstream_upgrade; proxy_set_header Connection $upstream_connection; proxy_pass_header Server; proxy_pass $upstream_scheme://kong_upstream; header_filter_by_lua_block { kong.header_filter() } body_filter_by_lua_block { kong.body_filter() } log_by_lua_block { kong.log() } } location = /kong_error_handler { internal; content_by_lua_block { require('kong.core.error_handlers')(ngx) } } } server { server_name kong_admin; listen ${{ADMIN_LISTEN}}; access_log logs/admin_access.log; client_max_body_size 10m; client_body_buffer_size 10m; > if admin_ssl then listen ${{ADMIN_LISTEN_SSL}} ssl; ssl_certificate ${{ADMIN_SSL_CERT}}; ssl_certificate_key ${{ADMIN_SSL_CERT_KEY}}; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; > end location / { default_type application/json; content_by_lua_block { ngx.header['Access-Control-Allow-Origin'] = '*' if ngx.req.get_method() == 'OPTIONS' then ngx.header['Access-Control-Allow-Methods'] = 'GET,HEAD,PUT,PATCH,POST,DELETE' ngx.header['Access-Control-Allow-Headers'] = 'Content-Type' ngx.exit(204) end require('lapis').serve('kong.api') } } location /nginx_status { internal; access_log off; stub_status; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } } ]]
fix(ws) do not override upstream_connection header
fix(ws) do not override upstream_connection header
Lua
apache-2.0
akh00/kong,Kong/kong,salazar/kong,Mashape/kong,ccyphers/kong,jebenexer/kong,icyxp/kong,Kong/kong,li-wl/kong,Kong/kong,shiprabehera/kong
dfad516e8402de33a3bb9d0750cc8736b83d6a85
applications/luci-app-dnscrypt-proxy/luasrc/model/cbi/dnscrypt-proxy/overview_tab.lua
applications/luci-app-dnscrypt-proxy/luasrc/model/cbi/dnscrypt-proxy/overview_tab.lua
-- Copyright 2017 Dirk Brenken (dev@brenken.org) -- This is free software, licensed under the Apache License, Version 2.0 local fs = require("nixio.fs") local uci = require("luci.model.uci").cursor() local util = require("luci.util") local date = require("luci.http.protocol.date") local res_input = "/usr/share/dnscrypt-proxy/dnscrypt-resolvers.csv" local dump = util.ubus("network.interface", "dump", {}) local plug_cnt = tonumber(luci.sys.exec("env -i /usr/sbin/dnscrypt-proxy --version | grep 'Support for plugins: present' | wc -l")) local res_list = {} local url = "https://download.dnscrypt.org/dnscrypt-proxy/dnscrypt-resolvers.csv" if not fs.access("/lib/libustream-ssl.so") then m = SimpleForm("error", nil, translate("SSL support not available, please install an libustream-ssl variant to use this package.")) m.submit = false m.reset = false return m end if not fs.access(res_input) then luci.sys.call("env -i /bin/uclient-fetch --no-check-certificate -O " .. res_input .. " " .. url .. " >/dev/null 2>&1") end for line in io.lines(res_input) do local name = line:match("^[%w_.-]*") res_list[#res_list + 1] = { name = name } end m = Map("dnscrypt-proxy", translate("DNSCrypt-Proxy"), translate("Configuration of the DNSCrypt-Proxy package. ") .. translate("Keep in mind to configure Dnsmasq as well. ") .. translatef("For further information " .. "<a href=\"%s\" target=\"_blank\">" .. "see the wiki online</a>", "https://wiki.openwrt.org/inbox/dnscrypt")) function m.on_after_commit(self) luci.sys.call("env -i /etc/init.d/dnsmasq restart >/dev/null 2>&1") luci.sys.call("env -i /etc/init.d/dnscrypt-proxy restart >/dev/null 2>&1") end -- Trigger selection s = m:section(TypedSection, "global", translate("General options")) s.anonymous = true -- Main dnscrypt-proxy resource list o1 = s:option(DummyValue, "", translate("Default Resolver List")) o1.template = "dnscrypt-proxy/res_options" o1.value = res_input o2 = s:option(DummyValue, "", translate("File Date")) o2.template = "dnscrypt-proxy/res_options" o2.value = date.to_http(nixio.fs.stat(res_input).mtime) o3 = s:option(DummyValue, "", translate("File Checksum")) o3.template = "dnscrypt-proxy/res_options" o3.value = luci.sys.exec("sha256sum " .. res_input .. " | awk '{print $1}'") btn = s:option(Button, "", translate("Refresh Resolver List")) btn.inputtitle = translate("Refresh List") btn.inputstyle = "apply" btn.disabled = false function btn.write(self, section, value) luci.sys.call("env -i /bin/uclient-fetch --no-check-certificate -O " .. res_input .. " " .. url .. " >/dev/null 2>&1") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "dnscrypt-proxy")) end -- Trigger settings t = s:option(DynamicList, "procd_trigger", translate("Startup Trigger"), translate("By default the DNSCrypt-Proxy startup will be triggered by ifup events of multiple network interfaces. ") .. translate("To restrict the trigger, add only the relevant network interface(s). ") .. translate("Usually the 'wan' interface should work for most users.")) if dump then local i, v for i, v in ipairs(dump.interface) do if v.interface ~= "loopback" then t:value(v.interface) end end end t.rmempty = true -- Mandatory options per instance s = m:section(TypedSection, "dnscrypt-proxy", translate("Instance options")) s.anonymous = true s.addremove = true o1 = s:option(Value, "address", translate("IP Address"), translate("The local IP address.")) o1.datatype = "ip4addr" o1.default = address or "127.0.0.1" o1.rmempty = false o2 = s:option(Value, "port", translate("Port"), translate("The listening port for DNS queries.")) o2.datatype = "port" o2.default = port o2.rmempty = false o3 = s:option(ListValue, "resolver", translate("Resolver"), translate("Name of the remote DNS service for resolving queries.")) o3.datatype = "hostname" o3.widget = "select" local i, v for i, v in ipairs(res_list) do if v.name ~= "Name" then o3:value(v.name) end end o3.default = resolver o3.rmempty = false -- Extra options per instance e1 = s:option(Value, "resolvers_list", translate("Alternate Resolver List"), translate("Specify a non-default Resolver List.")) e1.datatype = "file" e1.optional = true e2 = s:option(Value, "ephemeral_keys", translate("Ephemeral Keys"), translate("Improve privacy by using an ephemeral public key for each query. ") .. translate("This option requires extra CPU cycles and is useless with most DNSCrypt server.")) e2.datatype = "bool" e2.value = 1 e2.optional = true if plug_cnt > 0 then e3 = s:option(DynamicList, "blacklist", translate("Blacklist"), translate("Local blacklists allow you to block abuse sites by domains or ip addresses. ") .. translate("The value for this property is the blocklist type and path to the file, e.g.'domains:/path/to/dbl.txt' or 'ips:/path/to/ipbl.txt'.")) e3.optional = true e4 = s:option(Value, "block_ipv6", translate("Block IPv6"), translate("Disable IPv6 to speed up DNSCrypt-Proxy.")) e4.datatype = "bool" e4.value = 1 e4.optional = true e5 = s:option(Value, "local_cache", translate("Local Cache"), translate("Enable Caching to speed up DNSCcrypt-Proxy.")) e5.datatype = "bool" e5.value = 1 e5.optional = true e6 = s:option(Value, "query_log_file", translate("DNS Query Logfile"), translate("Log the received DNS queries to a file, so you can watch in real-time what is happening on the network.")) e6.optional = true end return m
-- Copyright 2017 Dirk Brenken (dev@brenken.org) -- This is free software, licensed under the Apache License, Version 2.0 local fs = require("nixio.fs") local uci = require("luci.model.uci").cursor() local util = require("luci.util") local date = require("luci.http.protocol.date") local res_input = "/usr/share/dnscrypt-proxy/dnscrypt-resolvers.csv" local dump = util.ubus("network.interface", "dump", {}) local plug_cnt = tonumber(luci.sys.exec("env -i /usr/sbin/dnscrypt-proxy --version | grep 'Support for plugins: present' | wc -l")) local res_list = {} local url = "https://download.dnscrypt.org/dnscrypt-proxy/dnscrypt-resolvers.csv" if not fs.access("/lib/libustream-ssl.so") then m = SimpleForm("error", nil, translate("SSL support not available, please install an libustream-ssl variant to use this package.")) m.submit = false m.reset = false return m end if not fs.access(res_input) then luci.sys.call("env -i /bin/uclient-fetch --no-check-certificate -O " .. res_input .. " " .. url .. " >/dev/null 2>&1") end if not uci:get_first("dnscrypt-proxy", "global") then uci:add("dnscrypt-proxy", "global") uci:save("dnscrypt-proxy") uci:commit("dnscrypt-proxy") end for line in io.lines(res_input) do local name = line:match("^[%w_.-]*") res_list[#res_list + 1] = { name = name } end m = Map("dnscrypt-proxy", translate("DNSCrypt-Proxy"), translate("Configuration of the DNSCrypt-Proxy package. ") .. translate("Keep in mind to configure Dnsmasq as well. ") .. translatef("For further information " .. "<a href=\"%s\" target=\"_blank\">" .. "see the wiki online</a>", "https://wiki.openwrt.org/inbox/dnscrypt")) function m.on_after_commit(self) luci.sys.call("env -i /etc/init.d/dnsmasq restart >/dev/null 2>&1") luci.sys.call("env -i /etc/init.d/dnscrypt-proxy restart >/dev/null 2>&1") end s = m:section(TypedSection, "global", translate("General options")) s.anonymous = true -- Main dnscrypt-proxy resource list o1 = s:option(DummyValue, "", translate("Default Resolver List")) o1.template = "dnscrypt-proxy/res_options" o1.value = res_input o2 = s:option(DummyValue, "", translate("File Date")) o2.template = "dnscrypt-proxy/res_options" o2.value = date.to_http(nixio.fs.stat(res_input).mtime) o3 = s:option(DummyValue, "", translate("File Checksum")) o3.template = "dnscrypt-proxy/res_options" o3.value = luci.sys.exec("sha256sum " .. res_input .. " | awk '{print $1}'") btn = s:option(Button, "", translate("Refresh Resolver List")) btn.inputtitle = translate("Refresh List") btn.inputstyle = "apply" btn.disabled = false function btn.write(self, section, value) luci.sys.call("env -i /bin/uclient-fetch --no-check-certificate -O " .. res_input .. " " .. url .. " >/dev/null 2>&1") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "dnscrypt-proxy")) end -- Trigger settings t = s:option(DynamicList, "procd_trigger", translate("Startup Trigger"), translate("By default the DNSCrypt-Proxy startup will be triggered by ifup events of multiple network interfaces. ") .. translate("To restrict the trigger, add only the relevant network interface(s). ") .. translate("Usually the 'wan' interface should work for most users.")) if dump then local i, v for i, v in ipairs(dump.interface) do if v.interface ~= "loopback" then t:value(v.interface) end end end t.rmempty = true -- Extra options ds = s:option(DummyValue, "_dummy", translate("Extra options"), translate("Options for further tweaking in case the defaults are not suitable for you.")) ds.template = "cbi/nullsection" btn = s:option(Button, "", translate("Create custom config file"), translate("Create '/etc/resolv-crypt.conf' with 'options timeout:1' to reduce DNS upstream timeouts with multiple DNSCrypt instances. ") .. translatef("For further information " .. "<a href=\"%s\" target=\"_blank\">" .. "see the wiki online</a>", "https://wiki.openwrt.org/inbox/dnscrypt")) btn.inputtitle = translate("Create Config File") btn.inputstyle = "apply" btn.disabled = false function btn.write(self, section, value) if not fs.access("/etc/resolv-crypt.conf") then luci.sys.call("env -i echo 'options timeout:1' > '/etc/resolv-crypt.conf'") end end -- Mandatory options per instance s = m:section(TypedSection, "dnscrypt-proxy", translate("Instance options")) s.anonymous = true s.addremove = true o1 = s:option(Value, "address", translate("IP Address"), translate("The local IPv4 or IPv6 address. The latter one should be specified within brackets, e.g. '[::1]'.")) o1.default = address or "127.0.0.1" o1.rmempty = false o2 = s:option(Value, "port", translate("Port"), translate("The listening port for DNS queries.")) o2.datatype = "port" o2.default = port o2.rmempty = false o3 = s:option(ListValue, "resolver", translate("Resolver"), translate("Name of the remote DNS service for resolving queries.")) o3.datatype = "hostname" o3.widget = "select" local i, v for i, v in ipairs(res_list) do if v.name ~= "Name" then o3:value(v.name) end end o3.default = resolver o3.rmempty = false -- Extra options per instance e1 = s:option(Value, "resolvers_list", translate("Alternate Resolver List"), translate("Specify a non-default Resolver List.")) e1.datatype = "file" e1.optional = true e2 = s:option(Value, "ephemeral_keys", translate("Ephemeral Keys"), translate("Improve privacy by using an ephemeral public key for each query. ") .. translate("This option requires extra CPU cycles and is useless with most DNSCrypt server.")) e2.datatype = "bool" e2.value = 1 e2.optional = true if plug_cnt > 0 then e3 = s:option(DynamicList, "blacklist", translate("Blacklist"), translate("Local blacklists allow you to block abuse sites by domains or ip addresses. ") .. translate("The value for this property is the blocklist type and path to the file, e.g.'domains:/path/to/dbl.txt' or 'ips:/path/to/ipbl.txt'.")) e3.optional = true e4 = s:option(Value, "block_ipv6", translate("Block IPv6"), translate("Disable IPv6 to speed up DNSCrypt-Proxy.")) e4.datatype = "bool" e4.value = 1 e4.optional = true e5 = s:option(Value, "local_cache", translate("Local Cache"), translate("Enable Caching to speed up DNSCcrypt-Proxy.")) e5.datatype = "bool" e5.value = 1 e5.optional = true e6 = s:option(Value, "query_log_file", translate("DNS Query Logfile"), translate("Log the received DNS queries to a file, so you can watch in real-time what is happening on the network.")) e6.optional = true end return m
luci-app-dnscrypt-proxy: small fixes & additions
luci-app-dnscrypt-proxy: small fixes & additions * check/add for 'global' section to fix a possible issue with old (non-default) dnscrypt-proxy config files * a custom 'resolv-crypt.conf' can now be added in the new "Extra options" section * accept IPv4 and IPv6 address as local dnscrypt ip address Signed-off-by: Dirk Brenken <34c6fceca75e456f25e7e99531e2425c6c1de443@brenken.org>
Lua
apache-2.0
artynet/luci,openwrt-es/openwrt-luci,kuoruan/luci,remakeelectric/luci,Noltari/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,Wedmer/luci,Wedmer/luci,rogerpueyo/luci,nmav/luci,hnyman/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,Wedmer/luci,981213/luci-1,981213/luci-1,Noltari/luci,Noltari/luci,artynet/luci,remakeelectric/luci,nmav/luci,Noltari/luci,openwrt/luci,lbthomsen/openwrt-luci,981213/luci-1,tobiaswaldvogel/luci,Noltari/luci,Wedmer/luci,tobiaswaldvogel/luci,rogerpueyo/luci,nmav/luci,oneru/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,artynet/luci,kuoruan/luci,981213/luci-1,kuoruan/luci,kuoruan/lede-luci,artynet/luci,lbthomsen/openwrt-luci,981213/luci-1,nmav/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,oneru/luci,oneru/luci,openwrt/luci,kuoruan/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,nmav/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,rogerpueyo/luci,kuoruan/luci,981213/luci-1,hnyman/luci,remakeelectric/luci,lbthomsen/openwrt-luci,remakeelectric/luci,chris5560/openwrt-luci,kuoruan/luci,oneru/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,oneru/luci,wongsyrone/luci-1,hnyman/luci,oneru/luci,Wedmer/luci,openwrt/luci,openwrt-es/openwrt-luci,Noltari/luci,chris5560/openwrt-luci,remakeelectric/luci,kuoruan/lede-luci,Noltari/luci,hnyman/luci,rogerpueyo/luci,nmav/luci,chris5560/openwrt-luci,rogerpueyo/luci,chris5560/openwrt-luci,oneru/luci,rogerpueyo/luci,nmav/luci,wongsyrone/luci-1,chris5560/openwrt-luci,hnyman/luci,openwrt-es/openwrt-luci,artynet/luci,kuoruan/luci,nmav/luci,nmav/luci,kuoruan/luci,Wedmer/luci,oneru/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,Noltari/luci,openwrt/luci,wongsyrone/luci-1,hnyman/luci,openwrt/luci,remakeelectric/luci,kuoruan/lede-luci,Wedmer/luci,Wedmer/luci,Noltari/luci,artynet/luci,remakeelectric/luci,openwrt/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,artynet/luci,artynet/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,wongsyrone/luci-1,tobiaswaldvogel/luci,openwrt/luci,openwrt/luci,kuoruan/lede-luci,hnyman/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,rogerpueyo/luci,rogerpueyo/luci,artynet/luci,wongsyrone/luci-1,981213/luci-1,wongsyrone/luci-1,remakeelectric/luci
d19d4f24431fcb2b3e87ab4ec13c14e628ea9e98
lualib/sharedata/corelib.lua
lualib/sharedata/corelib.lua
local core = require "sharedata.core" local type = type local next = next local rawget = rawget local conf = {} conf.host = { new = core.new, delete = core.delete, getref = core.getref, markdirty = core.markdirty, incref = core.incref, decref = core.decref, } local meta = {} local isdirty = core.isdirty local index = core.index local needupdate = core.needupdate local len = core.len local function findroot(self) while self.__parent do self = self.__parent end return self end local function update(root, cobj, gcobj) root.__obj = cobj root.__gcobj = gcobj -- don't use pairs for k,v in next, root do if type(v)=="table" and k~="__parent" then local pointer = index(cobj, k) if type(pointer) == "userdata" then update(v, pointer, gcobj) else root[k] = nil end end end end local function genkey(self) local key = tostring(self.__key) while self.__parent do self = self.__parent key = self.__key .. "." .. key end return key end local function getcobj(self) local obj = self.__obj if isdirty(obj) then local newobj, newtbl = needupdate(self.__gcobj) if newobj then local newgcobj = newtbl.__gcobj local root = findroot(self) update(root, newobj, newgcobj) if obj == self.__obj then error ("The key [" .. genkey(self) .. "] doesn't exist after update") end obj = self.__obj end end return obj end function meta:__index(key) local obj = getcobj(self) local v = index(obj, key) if type(v) == "userdata" then local r = setmetatable({ __obj = v, __gcobj = self.__gcobj, __parent = self, __key = key, }, meta) self[key] = r return r else return v end end function meta:__len() return len(getcobj(self)) end function meta:__pairs() return conf.next, self, nil end function conf.next(obj, key) local cobj = getcobj(obj) local nextkey = core.nextkey(cobj, key) if nextkey then return nextkey, obj[nextkey] end end function conf.box(obj) local gcobj = core.box(obj) return setmetatable({ __parent = false, __obj = obj, __gcobj = gcobj, __key = "", } , meta) end function conf.update(self, pointer) local cobj = self.__obj assert(isdirty(cobj), "Only dirty object can be update") core.update(self.__gcobj, pointer, { __gcobj = core.box(pointer) }) end return conf
local core = require "sharedata.core" local type = type local next = next local rawget = rawget local conf = {} conf.host = { new = core.new, delete = core.delete, getref = core.getref, markdirty = core.markdirty, incref = core.incref, decref = core.decref, } local meta = {} local isdirty = core.isdirty local index = core.index local needupdate = core.needupdate local len = core.len local function findroot(self) while self.__parent do self = self.__parent end return self end local function update(root, cobj, gcobj) root.__obj = cobj root.__gcobj = gcobj local children = root.__cache if children then for k,v in pairs(children) do local pointer = index(cobj, k) if type(pointer) == "userdata" then update(v, pointer, gcobj) else children[k] = nil end end end end local function genkey(self) local key = tostring(self.__key) while self.__parent do self = self.__parent key = self.__key .. "." .. key end return key end local function getcobj(self) local obj = self.__obj if isdirty(obj) then local newobj, newtbl = needupdate(self.__gcobj) if newobj then local newgcobj = newtbl.__gcobj local root = findroot(self) update(root, newobj, newgcobj) if obj == self.__obj then error ("The key [" .. genkey(self) .. "] doesn't exist after update") end obj = self.__obj end end return obj end function meta:__index(key) local obj = getcobj(self) local v = index(obj, key) if type(v) == "userdata" then local children = self.__cache if children == nil then children = {} self.__cache = children end local r = children[key] if r then return r end r = setmetatable({ __obj = v, __gcobj = self.__gcobj, __parent = self, __key = key, }, meta) children[key] = r return r else return v end end function meta:__len() return len(getcobj(self)) end function meta:__pairs() return conf.next, self, nil end function conf.next(obj, key) local cobj = getcobj(obj) local nextkey = core.nextkey(cobj, key) if nextkey then return nextkey, obj[nextkey] end end function conf.box(obj) local gcobj = core.box(obj) return setmetatable({ __parent = false, __obj = obj, __gcobj = gcobj, __key = "", } , meta) end function conf.update(self, pointer) local cobj = self.__obj assert(isdirty(cobj), "Only dirty object can be update") core.update(self.__gcobj, pointer, { __gcobj = core.box(pointer) }) end return conf
bugfix: clear cached sub node
bugfix: clear cached sub node
Lua
mit
LiangMa/skynet,microcai/skynet,xcjmine/skynet,felixdae/skynet,zhaijialong/skynet,helling34/skynet,samael65535/skynet,puXiaoyi/skynet,rainfiel/skynet,dymx101/skynet,cuit-zhaxin/skynet,bingo235/skynet,harryzeng/skynet,MoZhonghua/skynet,MRunFoss/skynet,enulex/skynet,firedtoad/skynet,fhaoquan/skynet,zhangshiqian1214/skynet,sanikoyes/skynet,great90/skynet,ludi1991/skynet,lynx-seu/skynet,pigparadise/skynet,MRunFoss/skynet,LuffyPan/skynet,ypengju/skynet_comment,zhouxiaoxiaoxujian/skynet,fztcjjl/skynet,helling34/skynet,ruleless/skynet,MoZhonghua/skynet,lawnight/skynet,iskygame/skynet,longmian/skynet,Zirpon/skynet,rainfiel/skynet,xinjuncoding/skynet,pichina/skynet,matinJ/skynet,pigparadise/skynet,javachengwc/skynet,kebo/skynet,zhouxiaoxiaoxujian/skynet,zhaijialong/skynet,wangjunwei01/skynet,catinred2/skynet,wangyi0226/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,ludi1991/skynet,fhaoquan/skynet,kyle-wang/skynet,dymx101/skynet,chfg007/skynet,korialuo/skynet,codingabc/skynet,cpascal/skynet,jxlczjp77/skynet,zhaijialong/skynet,lc412/skynet,fztcjjl/skynet,kyle-wang/skynet,firedtoad/skynet,icetoggle/skynet,wangyi0226/skynet,KittyCookie/skynet,togolwb/skynet,MetSystem/skynet,chenjiansnail/skynet,felixdae/skynet,ypengju/skynet_comment,sanikoyes/skynet,wangjunwei01/skynet,liuxuezhan/skynet,matinJ/skynet,plsytj/skynet,letmefly/skynet,lawnight/skynet,MRunFoss/skynet,enulex/skynet,kyle-wang/skynet,Ding8222/skynet,nightcj/mmo,bigrpg/skynet,zhangshiqian1214/skynet,codingabc/skynet,LiangMa/skynet,pichina/skynet,helling34/skynet,sundream/skynet,hongling0/skynet,lc412/skynet,ilylia/skynet,icetoggle/skynet,ag6ag/skynet,your-gatsby/skynet,harryzeng/skynet,gitfancode/skynet,u20024804/skynet,ruleless/skynet,sundream/skynet,xjdrew/skynet,sanikoyes/skynet,iskygame/skynet,korialuo/skynet,dymx101/skynet,catinred2/skynet,xcjmine/skynet,xcjmine/skynet,longmian/skynet,cmingjian/skynet,chfg007/skynet,zzh442856860/skynet-Note,ilylia/skynet,pigparadise/skynet,KAndQ/skynet,bingo235/skynet,winglsh/skynet,microcai/skynet,zhoukk/skynet,lc412/skynet,plsytj/skynet,MetSystem/skynet,czlc/skynet,cdd990/skynet,czlc/skynet,lawnight/skynet,jxlczjp77/skynet,ag6ag/skynet,zhoukk/skynet,longmian/skynet,samael65535/skynet,xjdrew/skynet,ilylia/skynet,jiuaiwo1314/skynet,matinJ/skynet,LiangMa/skynet,zzh442856860/skynet,togolwb/skynet,puXiaoyi/skynet,boyuegame/skynet,bigrpg/skynet,winglsh/skynet,bttscut/skynet,yunGit/skynet,Zirpon/skynet,vizewang/skynet,cuit-zhaxin/skynet,catinred2/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,liuxuezhan/skynet,Ding8222/skynet,sdgdsffdsfff/skynet,zhouxiaoxiaoxujian/skynet,boyuegame/skynet,pichina/skynet,iskygame/skynet,chenjiansnail/skynet,lynx-seu/skynet,vizewang/skynet,cloudwu/skynet,ag6ag/skynet,cpascal/skynet,Markal128/skynet,liuxuezhan/skynet,hongling0/skynet,Markal128/skynet,KittyCookie/skynet,your-gatsby/skynet,yinjun322/skynet,KAndQ/skynet,bttscut/skynet,vizewang/skynet,MetSystem/skynet,lynx-seu/skynet,QuiQiJingFeng/skynet,kebo/skynet,zzh442856860/skynet-Note,chuenlungwang/skynet,icetoggle/skynet,yinjun322/skynet,asanosoyokaze/skynet,korialuo/skynet,chuenlungwang/skynet,cdd990/skynet,plsytj/skynet,LuffyPan/skynet,bingo235/skynet,puXiaoyi/skynet,your-gatsby/skynet,asanosoyokaze/skynet,yinjun322/skynet,winglsh/skynet,gitfancode/skynet,jiuaiwo1314/skynet,JiessieDawn/skynet,Ding8222/skynet,Markal128/skynet,cpascal/skynet,gitfancode/skynet,firedtoad/skynet,letmefly/skynet,bttscut/skynet,boyuegame/skynet,Zirpon/skynet,xjdrew/skynet,u20024804/skynet,cdd990/skynet,xinjuncoding/skynet,wangyi0226/skynet,great90/skynet,chuenlungwang/skynet,cloudwu/skynet,zzh442856860/skynet-Note,KAndQ/skynet,cmingjian/skynet,MoZhonghua/skynet,fhaoquan/skynet,microcai/skynet,JiessieDawn/skynet,liuxuezhan/skynet,nightcj/mmo,harryzeng/skynet,zzh442856860/skynet,bigrpg/skynet,zzh442856860/skynet-Note,fztcjjl/skynet,leezhongshan/skynet,togolwb/skynet,ypengju/skynet_comment,cloudwu/skynet,yunGit/skynet,javachengwc/skynet,javachengwc/skynet,ludi1991/skynet,felixdae/skynet,leezhongshan/skynet,LuffyPan/skynet,zhangshiqian1214/skynet,yunGit/skynet,sundream/skynet,great90/skynet,QuiQiJingFeng/skynet,chfg007/skynet,cuit-zhaxin/skynet,QuiQiJingFeng/skynet,zzh442856860/skynet,u20024804/skynet,czlc/skynet,kebo/skynet,wangjunwei01/skynet,codingabc/skynet,enulex/skynet,rainfiel/skynet,letmefly/skynet,cmingjian/skynet,sdgdsffdsfff/skynet,JiessieDawn/skynet,xinjuncoding/skynet,ruleless/skynet,jiuaiwo1314/skynet,nightcj/mmo,KittyCookie/skynet,leezhongshan/skynet,samael65535/skynet,asanosoyokaze/skynet,chenjiansnail/skynet,sdgdsffdsfff/skynet,letmefly/skynet,ludi1991/skynet,zhoukk/skynet,lawnight/skynet,hongling0/skynet
d11ccc9b820adbe654a037667751b1e3d794a72c
examples/icmp-arp-responder.lua
examples/icmp-arp-responder.lua
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" local dpdkc = require "dpdkc" local utils = require "utils" local headers = require "headers" local packet = require "packet" local arp = require "proto.arp" local icmp = require "proto.icmp" local ffi = require "ffi" function master(funny, port, ...) if funny and funny ~= "--do-funny-things" then return master(nil, funny, port, ...) end port = tonumber(port) if not port or select("#", ...) == 0 then printf("usage: [--do-funny-things] port ip [ip...]") return end local dev = device.config(port, 2, 2) device.waitForLinks() dpdk.launchLua(arp.arpTask, dev:getRxQueue(1), dev:getTxQueue(1), { ... }) pingResponder(dev, funny) end local DIGITS = { 1, 8 } local states = { " ", " X ", " XXX ", " XXXXX ", " XXXXXXX ", "XXXXXXXXX", "XXXX XXXX", "XXX XXX", "XX XX", "X X", } for i, v in ipairs(states) do states[i] = tonumber((v:gsub(" ", DIGITS[1]):gsub("X", DIGITS[2]))) end local function getSymbol(step) return states[step % #states + 1] end function pingResponder(dev, funny) if funny then print("Note: most ping 'clients' do not support the --do-funny-things option and ignore our responses :(") print("One notable exception is Linux ping from the iputils package") end local devMac = dev:getMac() local rxQueue = dev:getRxQueue(0) local txQueue = dev:getTxQueue(0) local rxMem = memory.createMemPool() local rxBufs = rxMem:bufArray(1) while dpdk.running() do rx = rxQueue:recv(rxBufs) if rx > 0 then local buf = rxBufs[1] local pkt = buf:getIcmpPacket() if pkt.ip4:getProtocol() == ip4.PROTO_ICMP then local tmp = pkt.ip4.src:get() pkt.eth.dst:set(pkt.eth.src) pkt.eth.src:set(devMac) pkt.ip4.src:set(pkt.ip4.dst:get()) pkt.ip4.dst:set(tmp) pkt.icmp:setType(icmp.ECHO_REPLY.type) if funny then local ts = pkt.icmp.body.uint32[1] local seq = bswap16(pkt.icmp.body.uint16[1]) local symbol = getSymbol(seq) ts = ts - symbol seq = seq + 10000 pkt.ip4.ttl = math.min(63 - pkt.ip4.ttl + 100, 200) pkt.icmp.body.uint32[1] = ts pkt.icmp.body.uint16[1] = bswap16(seq) end pkt.ip4:setChecksum(0) pkt.icmp:calculateChecksum(pkt.ip4:getLength() - pkt.ip4:getHeaderLength() * 4) rxBufs:offloadIPChecksums() txQueue:send(rxBufs) else rxBufs:freeAll() end end end end
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" local dpdkc = require "dpdkc" local utils = require "utils" local headers = require "headers" local packet = require "packet" local arp = require "proto.arp" local ip = require "proto.ip4" local icmp = require "proto.icmp" local ffi = require "ffi" function master(funny, port, ...) if funny and funny ~= "--do-funny-things" then return master(nil, funny, port, ...) end port = tonumber(port) if not port or select("#", ...) == 0 then printf("usage: [--do-funny-things] port ip [ip...]") return end local dev = device.config(port, 2, 2) device.waitForLinks() dpdk.launchLua(arp.arpTask, { { rxQueue = dev:getRxQueue(1), txQueue = dev:getTxQueue(1), ips = { ... } } }) pingResponder(dev, funny) end local DIGITS = { 1, 8 } local states = { " ", " X ", " XXX ", " XXXXX ", " XXXXXXX ", "XXXXXXXXX", "XXXX XXXX", "XXX XXX", "XX XX", "X X", } for i, v in ipairs(states) do states[i] = tonumber((v:gsub(" ", DIGITS[1]):gsub("X", DIGITS[2]))) end local function getSymbol(step) return states[step % #states + 1] end function pingResponder(dev, funny) if funny then print("Note: most ping 'clients' do not support the --do-funny-things option and ignore our responses :(") print("One notable exception is Linux ping from the iputils package") end local devMac = dev:getMac() local rxQueue = dev:getRxQueue(0) local txQueue = dev:getTxQueue(0) local rxMem = memory.createMemPool() local rxBufs = rxMem:bufArray(1) while dpdk.running() do rx = rxQueue:recv(rxBufs) if rx > 0 then local buf = rxBufs[1] local pkt = buf:getIcmpPacket() if pkt.ip4:getProtocol() == ip.PROTO_ICMP then local tmp = pkt.ip4.src:get() pkt.eth.dst:set(pkt.eth.src) pkt.eth.src:set(devMac) pkt.ip4.src:set(pkt.ip4.dst:get()) pkt.ip4.dst:set(tmp) pkt.icmp:setType(icmp.ECHO_REPLY.type) if funny then local ts = pkt.icmp.body.uint32[1] local seq = bswap16(pkt.icmp.body.uint16[1]) local symbol = getSymbol(seq) ts = ts - symbol seq = seq + 10000 pkt.ip4.ttl = math.min(63 - pkt.ip4.ttl + 100, 200) pkt.icmp.body.uint32[1] = ts pkt.icmp.body.uint16[1] = bswap16(seq) end pkt.ip4:setChecksum(0) pkt.icmp:calculateChecksum(pkt.ip4:getLength() - pkt.ip4:getHeaderLength() * 4) rxBufs:offloadIPChecksums() txQueue:send(rxBufs) else rxBufs:freeAll() end end end end
fix ping/arp responder example
fix ping/arp responder example
Lua
mit
slyon/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,wenhuizhang/MoonGen,kidaa/MoonGen,emmericp/MoonGen,atheurer/MoonGen,slyon/MoonGen,schoenb/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,atheurer/MoonGen,duk3luk3/MoonGen,schoenb/MoonGen,dschoeffm/MoonGen,dschoeffm/MoonGen,wenhuizhang/MoonGen,scholzd/MoonGen,slyon/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,slyon/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,scholzd/MoonGen,schoenb/MoonGen,werpat/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,atheurer/MoonGen,werpat/MoonGen,werpat/MoonGen,emmericp/MoonGen
1a3bfe360f0f3e4a3119b45588682b2b88ad45fa
build/LLVM.lua
build/LLVM.lua
-- Setup the LLVM dependency directories LLVMRootDir = "../../deps/llvm/" LLVMBuildDir = "../../deps/llvm/build/" -- TODO: Search for available system dependencies function SetupLLVMIncludes() local c = configuration() includedirs { path.join(LLVMRootDir, "include"), path.join(LLVMRootDir, "tools/clang/include"), path.join(LLVMRootDir, "tools/clang/lib"), path.join(LLVMBuildDir, "include"), path.join(LLVMBuildDir, "tools/clang/include"), } configuration(c) end function SetupLLVMLibs() local c = configuration() libdirs { path.join(LLVMBuildDir, "lib") } configuration { "Debug", "vs*" } libdirs { path.join(LLVMBuildDir, "Debug/lib") } configuration { "Release", "vs*" } libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") } configuration "not vs*" defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" } configuration "macosx" links { "c++", "curses", "pthread", "z" } configuration "*" links { "LLVMAnalysis", "LLVMAsmParser", "LLVMBitReader", "LLVMBitWriter", "LLVMCodeGen", "LLVMCore", "LLVMipa", "LLVMipo", "LLVMInstCombine", "LLVMInstrumentation", "LLVMIRReader", "LLVMLinker", "LLVMMC", "LLVMMCParser", "LLVMObjCARCOpts", "LLVMObject", "LLVMOption", "LLVMProfileData", "LLVMScalarOpts", "LLVMSupport", "LLVMTarget", "LLVMTransformUtils", "LLVMVectorize", "LLVMX86AsmParser", "LLVMX86AsmPrinter", "LLVMX86Desc", "LLVMX86Info", "LLVMX86Utils", "clangAnalysis", "clangAST", "clangBasic", "clangCodeGen", "clangDriver", "clangEdit", "clangFrontend", "clangLex", "clangParse", "clangSema", "clangSerialization", "clangIndex", } configuration(c) end
-- Setup the LLVM dependency directories LLVMRootDir = "../../deps/llvm/" LLVMBuildDir = "../../deps/llvm/build/" -- TODO: Search for available system dependencies function SetupLLVMIncludes() local c = configuration() includedirs { path.join(LLVMRootDir, "include"), path.join(LLVMRootDir, "tools/clang/include"), path.join(LLVMRootDir, "tools/clang/lib"), path.join(LLVMBuildDir, "include"), path.join(LLVMBuildDir, "tools/clang/include"), } configuration(c) end function SetupLLVMLibs() local c = configuration() libdirs { path.join(LLVMBuildDir, "lib") } configuration { "Debug", "vs*" } libdirs { path.join(LLVMBuildDir, "Debug/lib") } configuration { "Release", "vs*" } libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") } configuration "not vs*" defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" } configuration "macosx" links { "c++", "curses", "pthread", "z" } configuration "*" links { "LLVMAnalysis", "LLVMAsmParser", "LLVMBitReader", "LLVMBitWriter", "LLVMCodeGen", "LLVMCore", "LLVMipa", "LLVMipo", "LLVMInstCombine", "LLVMInstrumentation", "LLVMIRReader", "LLVMLinker", "LLVMMC", "LLVMMCParser", "LLVMObjCARCOpts", "LLVMObject", "LLVMOption", "LLVMProfileData", "LLVMScalarOpts", "LLVMSupport", "LLVMTarget", "LLVMTransformUtils", "LLVMVectorize", "LLVMX86AsmParser", "LLVMX86AsmPrinter", "LLVMX86Desc", "LLVMX86Info", "LLVMX86Utils", "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic", "clangIndex", } configuration(c) end
build: fix clang linking
build: fix clang linking At least on linux with gcc the linking order of the libraries is important. Fix linking clang libraries by changing the link order. Signed-off-by: Tomi Valkeinen <e1ca4dbb8be1acaf20734fecd2da10ed1d46a9bb@iki.fi>
Lua
mit
KonajuGames/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,xistoso/CppSharp,xistoso/CppSharp,txdv/CppSharp,nalkaro/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,SonyaSa/CppSharp,KonajuGames/CppSharp,KonajuGames/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,mono/CppSharp,mono/CppSharp,ddobrev/CppSharp,mono/CppSharp,txdv/CppSharp,ktopouzi/CppSharp,Samana/CppSharp,nalkaro/CppSharp,mydogisbox/CppSharp,genuinelucifer/CppSharp,Samana/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,KonajuGames/CppSharp,mohtamohit/CppSharp,imazen/CppSharp,mohtamohit/CppSharp,mono/CppSharp,mono/CppSharp,Samana/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,xistoso/CppSharp,mydogisbox/CppSharp,xistoso/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,Samana/CppSharp,u255436/CppSharp,ddobrev/CppSharp,SonyaSa/CppSharp,mohtamohit/CppSharp,imazen/CppSharp,imazen/CppSharp,nalkaro/CppSharp,inordertotest/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,Samana/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,mydogisbox/CppSharp,SonyaSa/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,KonajuGames/CppSharp,u255436/CppSharp,imazen/CppSharp,txdv/CppSharp,zillemarco/CppSharp,imazen/CppSharp,nalkaro/CppSharp
5e2dd31cc1688dca05bbdd8857d42d254dcdec93
spec/unit/statics_spec.lua
spec/unit/statics_spec.lua
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should parse a correct configuration", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog # Nginx prefix path directory nginx_working_dir: /usr/local/kong/ # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # Sends anonymous error reports send_anonymous_reports: true # Cache configuration cache: expiration: 5 # in seconds nginx: | worker_processes auto; error_log logs/error.log info; daemon on; # Set "worker_rlimit_nofile" to a high value # worker_rlimit_nofile 65536; env KONG_CONF; events { # Set "worker_connections" to a high value worker_connections 1024; } http { # Generic Settings resolver 8.8.8.8; charset UTF-8; # Logs access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen 8000; location / { # Assigns the default MIME-type to be used for files where the # standard MIME map doesn't specify anything. default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen 8001; location / { default_type application/json; content_by_lua ' require("lapis").serve("kong.web.app") '; } location /static/ { alias static/; } location /admin/ { alias admin/; } location /favicon.ico { alias static/favicon.ico; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } } } ]], configuration) end) end) end)
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should parse a correct configuration", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog # Nginx prefix path directory nginx_working_dir: /usr/local/kong/ # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # Sends anonymous error reports send_anonymous_reports: true # Nginx Plus Status nginx_plus_status: false # Cache configuration cache: expiration: 5 # in seconds nginx: | worker_processes auto; error_log logs/error.log info; daemon on; # Set "worker_rlimit_nofile" to a high value # worker_rlimit_nofile 65536; env KONG_CONF; events { # Set "worker_connections" to a high value worker_connections 1024; } http { # Generic Settings resolver 8.8.8.8; charset UTF-8; # Logs access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen 8000; location / { # Assigns the default MIME-type to be used for files where the # standard MIME map doesn't specify anything. default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen 8001; location / { default_type application/json; content_by_lua ' require("lapis").serve("kong.web.app") '; } location /static/ { alias static/; } location /admin/ { alias admin/; } location /favicon.ico { alias static/favicon.ico; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } # Do not remove the following comment # plugin_configuration_placeholder } } ]], configuration) end) end) end)
fixing test
fixing test
Lua
apache-2.0
AnsonSmith/kong,puug/kong,chourobin/kong,vmercierfr/kong,sbuettner/kong,paritoshmmmec/kong,ChristopherBiscardi/kong,Skyscanner/kong,bbalu/kong,wakermahmud/kong,skynet/kong,peterayeni/kong,ropik/kong
7cbd56fcdd5f93555a7be72af46badc3c840dd06
frontend/apps/reader/modules/readerstatus.lua
frontend/apps/reader/modules/readerstatus.lua
local BookStatusWidget = require("ui/widget/bookstatuswidget") local ButtonDialogTitle = require("ui/widget/buttondialogtitle") local InfoMessage = require("ui/widget/infomessage") local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderStatus = InputContainer:new { document = nil, summary = { rating = 0, note = nil, status = "", modified = "", }, enabled = true, total_pages = 0 } function ReaderStatus:init() if self.ui.document.is_pic then self.enabled = false return else self.total_pages = self.document:getPageCount() self.ui.menu:registerToMainMenu(self) end end function ReaderStatus:addToMainMenu(menu_items) menu_items.book_status = { text = _("Book status"), callback = function() self:onShowBookStatus() end, } end function ReaderStatus:onEndOfBook() local settings = G_reader_settings:readSetting("end_document_action") local choose_action local collate = true local QuickStart = require("ui/quickstart") local last_file = G_reader_settings:readSetting("lastfile") if last_file and last_file == QuickStart.quickstart_filename then self:openFileBrowser() return end if G_reader_settings:readSetting("collate") == "access" then collate = false end if settings == "pop-up" or settings == nil then local buttons = { { { text = _("Cancel"), callback = function() UIManager:close(choose_action) end, }, { text = _("Book status"), callback = function() self:onShowBookStatus() UIManager:close(choose_action) end, }, }, { { text = _("Open next file"), enabled = collate, callback = function() self:openNextFile(self.document.file) UIManager:close(choose_action) end, }, { text = _("File browser"), callback = function() self:openFileBrowser() UIManager:close(choose_action) end, }, }, } choose_action = ButtonDialogTitle:new{ title = _("You've reached the end of the document.\nWhat would you like to do?"), title_align = "center", buttons = buttons, } UIManager:show(choose_action) elseif settings == "book_status" then self:onShowBookStatus() elseif settings == "next_file" then if G_reader_settings:readSetting("collate") ~= "access" then local info = InfoMessage:new{ text = _("Searching next file…"), } UIManager:show(info) UIManager:forceRePaint() self:openNextFile(self.document.file) UIManager:close(info) else UIManager:show(InfoMessage:new{ text = _("Could not open next file. Sort by last read date does not support this feature."), }) end elseif settings == "file_browser" then self:openFileBrowser() elseif settings == "book_status_file_browser" then local before_show_callback = function() self:openFileBrowser() end self:onShowBookStatus(before_show_callback) end end function ReaderStatus:openFileBrowser() local FileManager = require("apps/filemanager/filemanager") if not FileManager.instance then self.ui:showFileManager() end self.ui:onClose() self.document = nil end function ReaderStatus:openNextFile(next_file) local FileManager = require("apps/filemanager/filemanager") if not FileManager.instance then self.ui:showFileManager() end next_file = FileManager.instance.file_chooser:getNextFile(next_file) FileManager.instance:onClose() if next_file then self.ui:switchDocument(next_file) else UIManager:show(InfoMessage:new{ text = _("This is the last file in the current folder. No next file to open."), }) end end function ReaderStatus:onShowBookStatus(before_show_callback) local status_page = BookStatusWidget:new { thumbnail = self.document:getCoverPageImage(), props = self.document:getProps(), document = self.document, settings = self.settings, view = self.view, } if before_show_callback then before_show_callback() end status_page.dithered = true UIManager:show(status_page, "full") return true end function ReaderStatus:onReadSettings(config) self.settings = config end return ReaderStatus
local BookStatusWidget = require("ui/widget/bookstatuswidget") local ButtonDialogTitle = require("ui/widget/buttondialogtitle") local InfoMessage = require("ui/widget/infomessage") local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderStatus = InputContainer:new { document = nil, summary = { rating = 0, note = nil, status = "", modified = "", }, enabled = true, total_pages = 0 } function ReaderStatus:init() if self.ui.document.is_pic then self.enabled = false return else self.total_pages = self.document:getPageCount() self.ui.menu:registerToMainMenu(self) end end function ReaderStatus:addToMainMenu(menu_items) menu_items.book_status = { text = _("Book status"), callback = function() self:onShowBookStatus() end, } end function ReaderStatus:onEndOfBook() local settings = G_reader_settings:readSetting("end_document_action") local choose_action local collate = true local QuickStart = require("ui/quickstart") local last_file = G_reader_settings:readSetting("lastfile") if last_file and last_file == QuickStart.quickstart_filename then self:openFileBrowser() return end if G_reader_settings:readSetting("collate") == "access" then collate = false end if settings == "pop-up" or settings == nil then local buttons = { { { text = _("Cancel"), callback = function() UIManager:close(choose_action) end, }, { text = _("Book status"), callback = function() self:onShowBookStatus() UIManager:close(choose_action) end, }, }, { { text = _("Open next file"), enabled = collate, callback = function() self:openNextFile(self.document.file) UIManager:close(choose_action) end, }, { text = _("File browser"), callback = function() self:openFileBrowser() UIManager:close(choose_action) end, }, }, } choose_action = ButtonDialogTitle:new{ title = _("You've reached the end of the document.\nWhat would you like to do?"), title_align = "center", buttons = buttons, } UIManager:show(choose_action) elseif settings == "book_status" then self:onShowBookStatus() elseif settings == "next_file" then if G_reader_settings:readSetting("collate") ~= "access" then local info = InfoMessage:new{ text = _("Searching next file…"), } UIManager:show(info) UIManager:forceRePaint() self:openNextFile(self.document.file) UIManager:close(info) else UIManager:show(InfoMessage:new{ text = _("Could not open next file. Sort by last read date does not support this feature."), }) end elseif settings == "file_browser" then self:openFileBrowser() elseif settings == "book_status_file_browser" then local before_show_callback = function() self:openFileBrowser() end self:onShowBookStatus(before_show_callback) end end function ReaderStatus:openFileBrowser() local FileManager = require("apps/filemanager/filemanager") self.ui:onClose() if not FileManager.instance then self.ui:showFileManager() end self.document = nil end function ReaderStatus:openNextFile(next_file) local FileManager = require("apps/filemanager/filemanager") if not FileManager.instance then self.ui:showFileManager() end next_file = FileManager.instance.file_chooser:getNextFile(next_file) FileManager.instance:onClose() if next_file then self.ui:switchDocument(next_file) else UIManager:show(InfoMessage:new{ text = _("This is the last file in the current folder. No next file to open."), }) end end function ReaderStatus:onShowBookStatus(before_show_callback) local status_page = BookStatusWidget:new { thumbnail = self.document:getCoverPageImage(), props = self.document:getProps(), document = self.document, settings = self.settings, view = self.view, } if before_show_callback then before_show_callback() end status_page.dithered = true UIManager:show(status_page, "full") return true end function ReaderStatus:onReadSettings(config) self.settings = config end return ReaderStatus
[fix] End of document - go to file browser: swap openFileBrowser() close/open order (#5062)
[fix] End of document - go to file browser: swap openFileBrowser() close/open order (#5062) Fixes #5060. Cf. https://github.com/koreader/koreader/blob/89e002f2367079cefd445e1719c1715dccedd65b/frontend/apps/reader/modules/readermenu.lua#L42-L50 and https://github.com/koreader/koreader/blob/89e002f2367079cefd445e1719c1715dccedd65b/frontend/apps/reader/readerui.lua#L711-L718
Lua
agpl-3.0
koreader/koreader,Frenzie/koreader,NiLuJe/koreader,Frenzie/koreader,mihailim/koreader,pazos/koreader,NiLuJe/koreader,Markismus/koreader,poire-z/koreader,mwoz123/koreader,poire-z/koreader,Hzj-jie/koreader,koreader/koreader
31d22dfc1771ec731e47c5a6b490ac2a141565c2
frontend/apps/reader/modules/readerkobolight.lua
frontend/apps/reader/modules/readerkobolight.lua
local InputContainer = require("ui/widget/container/inputcontainer") local LeftContainer = require("ui/widget/container/leftcontainer") local GestureRange = require("ui/gesturerange") local Device = require("device") local Geom = require("ui/geometry") local Screen = Device.screen local DEBUG = require("dbg") local UIManager = require("ui/uimanager") local Notification = require("ui/widget/notification") local T = require("ffi/util").template local _ = require("gettext") local DTAP_ZONE_KOBOLIGHTTOGGLE = {x = 0, y = 0.9375, w = 0.1, h = 0.0625 } local DTAP_ZONE_KOBOLIGHTSWIPE = {x = 0, y = 0.125, w = 0.1, h = 0.875 } local ReaderKoboLight = InputContainer:new{ steps = {0,1,1,1,1,2,2,2,3,4,5,6,7,8,9,10}, gestureScale = Screen:getHeight() * DTAP_ZONE_KOBOLIGHTSWIPE.h * 0.8, } function ReaderKoboLight:init() self[1] = LeftContainer:new{ dimen = Geom:new{w = Screen:getWidth(), h = Screen:getHeight()}, } self:resetLayout() end function ReaderKoboLight:resetLayout() local new_screen_width = Screen:getWidth() if new_screen_width == self[1].dimen.w then return end local new_screen_height = Screen:getHeight() self[1].dimen.w = new_screen_width self[1].dimen.h = new_screen_height self.gestureScale = new_screen_height * DTAP_ZONE_KOBOLIGHTSWIPE.h * 0.8 if Device:isTouchDevice() then self.ges_events = { Tap = { GestureRange:new{ ges = "tap", range = Geom:new{ x = new_screen_width*DTAP_ZONE_KOBOLIGHTTOGGLE.x, y = new_screen_height*DTAP_ZONE_KOBOLIGHTTOGGLE.y, w = new_screen_width*DTAP_ZONE_KOBOLIGHTTOGGLE.w, h = new_screen_height*DTAP_ZONE_KOBOLIGHTTOGGLE.h } } }, Swipe = { GestureRange:new{ ges = "swipe", range = Geom:new{ x = new_screen_width*DTAP_ZONE_KOBOLIGHTSWIPE.x, y = new_screen_height*DTAP_ZONE_KOBOLIGHTSWIPE.y, w = new_screen_width*DTAP_ZONE_KOBOLIGHTSWIPE.w, h = new_screen_height*DTAP_ZONE_KOBOLIGHTSWIPE.h } } } } end end function ReaderKoboLight:onShowIntensity() local powerd = Device:getPowerDevice() if powerd.fl_intensity ~= nil then UIManager:show(Notification:new{ text = T(_("Frontlight intensity is set to %1."), powerd.fl_intensity), timeout = 1.0, }) end return true end function ReaderKoboLight:onShowOnOff() local powerd = Device:getPowerDevice() local new_text if powerd.is_fl_on then new_text = _("Frontlight is on.") else new_text = _("Frontlight is off.") end UIManager:show(Notification:new{ text = new_text, timeout = 1.0, }) return true end function ReaderKoboLight:onTap() Device:getPowerDevice():toggleFrontlight() self:onShowOnOff() return true end function ReaderKoboLight:onSwipe(arg, ges) local powerd = Device:getPowerDevice() if powerd.fl_intensity == nil then return true end DEBUG("frontlight intensity", powerd.fl_intensity) local step = math.ceil(#self.steps * ges.distance / self.gestureScale) DEBUG("step = ", step) local delta_int = self.steps[step] or self.steps[#self.steps] DEBUG("delta_int = ", delta_int) local new_intensity if ges.direction == "north" then new_intensity = powerd.fl_intensity + delta_int elseif ges.direction == "south" then new_intensity = powerd.fl_intensity - delta_int end if new_intensity ~= nil then -- when new_intensity <=0, toggle light off if new_intensity <=0 then if powerd.is_fl_on then powerd:toggleFrontlight() end self:onShowOnOff() else -- general case powerd:setIntensity(new_intensity) self:onShowIntensity() end end return true end return ReaderKoboLight
local InputContainer = require("ui/widget/container/inputcontainer") local LeftContainer = require("ui/widget/container/leftcontainer") local GestureRange = require("ui/gesturerange") local Device = require("device") local Geom = require("ui/geometry") local Screen = Device.screen local DEBUG = require("dbg") local UIManager = require("ui/uimanager") local Notification = require("ui/widget/notification") local T = require("ffi/util").template local _ = require("gettext") local DTAP_ZONE_KOBOLIGHTTOGGLE = {x = 0, y = 0.9375, w = 0.1, h = 0.0625 } local DTAP_ZONE_KOBOLIGHTSWIPE = {x = 0, y = 0.125, w = 0.1, h = 0.875 } local ReaderKoboLight = InputContainer:new{ steps = {0,1,1,1,1,2,2,2,3,4,5,6,7,8,9,10}, gestureScale = Screen:getHeight() * DTAP_ZONE_KOBOLIGHTSWIPE.h * 0.8, } function ReaderKoboLight:init() self[1] = LeftContainer:new{ dimen = Geom:new{w = nil, h = nil}, } self:resetLayout() end function ReaderKoboLight:resetLayout() local new_screen_width = Screen:getWidth() if new_screen_width == self[1].dimen.w then return end local new_screen_height = Screen:getHeight() self[1].dimen.w = new_screen_width self[1].dimen.h = new_screen_height self.gestureScale = new_screen_height * DTAP_ZONE_KOBOLIGHTSWIPE.h * 0.8 if Device:isTouchDevice() then self.ges_events = { Tap = { GestureRange:new{ ges = "tap", range = Geom:new{ x = new_screen_width*DTAP_ZONE_KOBOLIGHTTOGGLE.x, y = new_screen_height*DTAP_ZONE_KOBOLIGHTTOGGLE.y, w = new_screen_width*DTAP_ZONE_KOBOLIGHTTOGGLE.w, h = new_screen_height*DTAP_ZONE_KOBOLIGHTTOGGLE.h } } }, Swipe = { GestureRange:new{ ges = "swipe", range = Geom:new{ x = new_screen_width*DTAP_ZONE_KOBOLIGHTSWIPE.x, y = new_screen_height*DTAP_ZONE_KOBOLIGHTSWIPE.y, w = new_screen_width*DTAP_ZONE_KOBOLIGHTSWIPE.w, h = new_screen_height*DTAP_ZONE_KOBOLIGHTSWIPE.h } } } } end end function ReaderKoboLight:onShowIntensity() local powerd = Device:getPowerDevice() if powerd.fl_intensity ~= nil then UIManager:show(Notification:new{ text = T(_("Frontlight intensity is set to %1."), powerd.fl_intensity), timeout = 1.0, }) end return true end function ReaderKoboLight:onShowOnOff() local powerd = Device:getPowerDevice() local new_text if powerd.is_fl_on then new_text = _("Frontlight is on.") else new_text = _("Frontlight is off.") end UIManager:show(Notification:new{ text = new_text, timeout = 1.0, }) return true end function ReaderKoboLight:onTap() Device:getPowerDevice():toggleFrontlight() self:onShowOnOff() return true end function ReaderKoboLight:onSwipe(arg, ges) local powerd = Device:getPowerDevice() if powerd.fl_intensity == nil then return true end DEBUG("frontlight intensity", powerd.fl_intensity) local step = math.ceil(#self.steps * ges.distance / self.gestureScale) DEBUG("step = ", step) local delta_int = self.steps[step] or self.steps[#self.steps] DEBUG("delta_int = ", delta_int) local new_intensity if ges.direction == "north" then new_intensity = powerd.fl_intensity + delta_int elseif ges.direction == "south" then new_intensity = powerd.fl_intensity - delta_int end if new_intensity ~= nil then -- when new_intensity <=0, toggle light off if new_intensity <=0 then if powerd.is_fl_on then powerd:toggleFrontlight() end self:onShowOnOff() else -- general case powerd:setIntensity(new_intensity) self:onShowIntensity() end end return true end return ReaderKoboLight
fix(kobofrontligh): initialize dimen with nil value
fix(kobofrontligh): initialize dimen with nil value
Lua
agpl-3.0
robert00s/koreader,apletnev/koreader,mwoz123/koreader,Markismus/koreader,Hzj-jie/koreader,mihailim/koreader,koreader/koreader,NiLuJe/koreader,lgeek/koreader,poire-z/koreader,pazos/koreader,houqp/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,NickSavage/koreader,NiLuJe/koreader,Frenzie/koreader
e08051ad3df985e0882b22ede32eae4e14a0e8a8
modules/protocol/http/http.lua
modules/protocol/http/http.lua
local str = string.char local function getchar(stream) local char while true do char = stream:getchar() if char == -1 then coroutine.yield() else break end end return char end local function read_line(stream) local line = "" local char, c local read = 0 while true do c = getchar(stream) read = read+1 char = str(c) if c == 0xd then c = getchar(stream) read = read+1 if c == 0xa then return line, read else line = line .. char char = str(c) end elseif c == 0xa then return line, read end line = line .. char end end -- The comparison is broken in Lua 5.1, so we need to reimplement the -- string comparison local function string_compare(a, b) if type(a) == "string" and type(b) == "string" then local i = 1 local sa = #a local sb = #b while true do if i > sa then return false elseif i > sb then return true end if a:byte(i) < b:byte(i) then return true elseif a:byte(i) > b:byte(i) then return false end i = i+1 end return false else return a < b end end local function sorted_pairs(t) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, string_compare) local i = 0 return function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end end local function dump(t, indent) if not indent then indent = "" end for n, v in sorted_pairs(t) do if type(v) == "table" then print(indent, n) dump(v, indent .. " ") elseif type(v) ~= "thread" and type(v) ~= "userdata" and type(v) ~= "function" then print(indent, n, "=", v) end end end local function parse_header(stream, http) local total_len = 0 http.headers = {} http._headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("([^%s]+):%s*(.+)") if not name then http._invalid = string.format("invalid header '%s'", line) return end http.headers[name] = value table.insert(http._headers_order, name) line, len = read_line(stream) total_len = total_len + len end return total_len end local function parse_request(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.method, http.uri, http.version = line:match("([^%s]+) ([^%s]+) (.+)") if not http.method then http._invalid = string.format("invalid request '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = dump return true end local function parse_response(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.version, http.status, http.reason = line:match("([^%s]+) ([^%s]+) (.+)") if not http.version then http._invalid = string.format("invalid response '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = dump return true end local function build_headers(stream, headers, headers_order) for _, name in pairs(headers_order) do local value = headers[name] if value then headers[name] = nil stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end for name, value in pairs(headers) do if value then stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end end local function forge(http) local tcp = http._tcp_stream if tcp then if http._state == 2 and tcp.direction then http._state = 3 if haka.packet.mode() ~= haka.packet.PASSTHROUGH then tcp.stream:seek(http.request._mark, true) http.request._mark = nil tcp.stream:erase(http.request._length) tcp.stream:insert(http.request.method) tcp.stream:insert(" ") tcp.stream:insert(http.request.uri) tcp.stream:insert(" ") tcp.stream:insert(http.request.version) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.request.headers, http.request._headers_order) tcp.stream:insert("\r\n") end elseif http._state == 5 and not tcp.direction then http._state = 0 if haka.packet.mode() ~= haka.packet.PASSTHROUGH then tcp.stream:seek(http.response._mark, true) http.response._mark = nil tcp.stream:erase(http.response._length) tcp.stream:insert(http.response.version) tcp.stream:insert(" ") tcp.stream:insert(http.response.status) tcp.stream:insert(" ") tcp.stream:insert(http.response.reason) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.response.headers, http.response._headers_order) tcp.stream:insert("\r\n") end end http._tcp_stream = nil end return tcp end local function parse(http, context, f, name, next_state) if not context._co then if haka.packet.mode() ~= haka.packet.PASSTHROUGH then context._mark = http._tcp_stream.stream:mark() end context._co = coroutine.create(function () f(http._tcp_stream.stream, context) end) end coroutine.resume(context._co) if coroutine.status(context._co) == "dead" then if not context._invalid then http._state = next_state if not haka.rule_hook("http-".. name, http) then return nil end context.next_dissector = http.next_dissector else haka.log.error("http", context._invalid) http._tcp_stream:drop() return nil end end end haka.dissector { name = "http", hooks = { "http-request", "http-response" }, dissect = function (stream) if not stream.connection.data._http then local http = {} http.dissector = "http" http.next_dissector = nil http.valid = function (self) return self._tcp_stream:valid() end http.drop = function (self) return self._tcp_stream:drop() end http.reset = function (self) return self._tcp_stream:reset() end http.forge = forge http._state = 0 stream.connection.data._http = http end local http = stream.connection.data._http http._tcp_stream = stream if stream.direction then if http._state == 0 or http._state == 1 then if stream.stream:available() > 0 then if http._state == 0 then http.request = {} http.response = nil http._state = 1 end parse(http, http.request, parse_request, "request", 2) end elseif http.request then http.next_dissector = http.request.next_dissector end else if http._state == 3 or http._state == 4 then if stream.stream:available() > 0 then if http._state == 3 then http.response = {} http._state = 4 end parse(http, http.response, parse_response, "response", 5) end elseif http.response then http.next_dissector = http.response.next_dissector end end return http end }
local module = {} local str = string.char local function getchar(stream) local char while true do char = stream:getchar() if char == -1 then coroutine.yield() else break end end return char end local function read_line(stream) local line = "" local char, c local read = 0 while true do c = getchar(stream) read = read+1 char = str(c) if c == 0xd then c = getchar(stream) read = read+1 if c == 0xa then return line, read else line = line .. char char = str(c) end elseif c == 0xa then return line, read end line = line .. char end end -- The comparison is broken in Lua 5.1, so we need to reimplement the -- string comparison local function string_compare(a, b) if type(a) == "string" and type(b) == "string" then local i = 1 local sa = #a local sb = #b while true do if i > sa then return false elseif i > sb then return true end if a:byte(i) < b:byte(i) then return true elseif a:byte(i) > b:byte(i) then return false end i = i+1 end return false else return a < b end end local function sorted_pairs(t) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, string_compare) local i = 0 return function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end end local function dump(t, indent) if not indent then indent = "" end for n, v in sorted_pairs(t) do if type(v) == "table" then print(indent, n) dump(v, indent .. " ") elseif type(v) ~= "thread" and type(v) ~= "userdata" and type(v) ~= "function" then print(indent, n, "=", v) end end end local function parse_header(stream, http) local total_len = 0 http.headers = {} http._headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("([^%s]+):%s*(.+)") if not name then http._invalid = string.format("invalid header '%s'", line) return end http.headers[name] = value table.insert(http._headers_order, name) line, len = read_line(stream) total_len = total_len + len end return total_len end local function parse_request(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.method, http.uri, http.version = line:match("([^%s]+) ([^%s]+) (.+)") if not http.method then http._invalid = string.format("invalid request '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = dump return true end local function parse_response(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.version, http.status, http.reason = line:match("([^%s]+) ([^%s]+) (.+)") if not http.version then http._invalid = string.format("invalid response '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = dump return true end local function build_headers(stream, headers, headers_order) for _, name in pairs(headers_order) do local value = headers[name] if value then headers[name] = nil stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end for name, value in pairs(headers) do if value then stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end end local function forge(http) local tcp = http._tcp_stream if tcp then if http._state == 2 and tcp.direction then http._state = 3 if haka.packet.mode() ~= haka.packet.PASSTHROUGH then tcp.stream:seek(http.request._mark, true) http.request._mark = nil tcp.stream:erase(http.request._length) tcp.stream:insert(http.request.method) tcp.stream:insert(" ") tcp.stream:insert(http.request.uri) tcp.stream:insert(" ") tcp.stream:insert(http.request.version) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.request.headers, http.request._headers_order) tcp.stream:insert("\r\n") end elseif http._state == 5 and not tcp.direction then http._state = 0 if haka.packet.mode() ~= haka.packet.PASSTHROUGH then tcp.stream:seek(http.response._mark, true) http.response._mark = nil tcp.stream:erase(http.response._length) tcp.stream:insert(http.response.version) tcp.stream:insert(" ") tcp.stream:insert(http.response.status) tcp.stream:insert(" ") tcp.stream:insert(http.response.reason) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.response.headers, http.response._headers_order) tcp.stream:insert("\r\n") end end http._tcp_stream = nil end return tcp end local function parse(http, context, f, name, next_state) if not context._co then if haka.packet.mode() ~= haka.packet.PASSTHROUGH then context._mark = http._tcp_stream.stream:mark() end context._co = coroutine.create(function () f(http._tcp_stream.stream, context) end) end coroutine.resume(context._co) if coroutine.status(context._co) == "dead" then if not context._invalid then http._state = next_state if not haka.rule_hook("http-".. name, http) then return nil end context.next_dissector = http.next_dissector else haka.log.error("http", context._invalid) http._tcp_stream:drop() return nil end end end haka.dissector { name = "http", hooks = { "http-request", "http-response" }, dissect = function (stream) if not stream.connection.data._http then local http = {} http.dissector = "http" http.next_dissector = nil http.valid = function (self) return self._tcp_stream:valid() end http.drop = function (self) return self._tcp_stream:drop() end http.reset = function (self) return self._tcp_stream:reset() end http.forge = forge http._state = 0 stream.connection.data._http = http end local http = stream.connection.data._http http._tcp_stream = stream if stream.direction then if http._state == 0 or http._state == 1 then if stream.stream:available() > 0 then if http._state == 0 then http.request = {} http.response = nil http._state = 1 end parse(http, http.request, parse_request, "request", 2) end elseif http.request then http.next_dissector = http.request.next_dissector end else if http._state == 3 or http._state == 4 then if stream.stream:available() > 0 then if http._state == 3 then http.response = {} http._state = 4 end parse(http, http.response, parse_response, "response", 5) end elseif http.response then http.next_dissector = http.response.next_dissector end end return http end } return module
Fix http module
Fix http module The module should return a table.
Lua
mpl-2.0
Wingless-Archangel/haka,LubyRuffy/haka,LubyRuffy/haka,nabilbendafi/haka,nabilbendafi/haka,nabilbendafi/haka,haka-security/haka,lcheylus/haka,haka-security/haka,Wingless-Archangel/haka,haka-security/haka,lcheylus/haka,lcheylus/haka
0122c086f277654bb64d80a3bf10197ba69108c8
frontend/device/kobo/powerd.lua
frontend/device/kobo/powerd.lua
local BasePowerD = require("device/generic/powerd") local NickelConf = require("device/kobo/nickel_conf") local batt_state_folder = "/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/" -- Here, we only deal with the real hw intensity. -- Dealing with toggling and remembering/restoring -- previous intensity when toggling/untoggling is done -- by BasePowerD. local KoboPowerD = BasePowerD:new{ fl_min = 0, fl_max = 100, fl = nil, batt_capacity_file = batt_state_folder .. "capacity", is_charging_file = batt_state_folder .. "status", } -- TODO: Remove KOBO_LIGHT_ON_START function KoboPowerD:_syncKoboLightOnStart() local new_intensity = nil local is_frontlight_on = nil local kobo_light_on_start = tonumber(KOBO_LIGHT_ON_START) if kobo_light_on_start then if kobo_light_on_start > 0 then new_intensity = math.min(kobo_light_on_start, 100) is_frontlight_on = true elseif kobo_light_on_start == 0 then new_intensity = 0 is_frontlight_on = false elseif kobo_light_on_start == -2 then -- get values from NickelConf new_intensity = NickelConf.frontLightLevel.get() is_frontlight_on = NickelConf.frontLightState:get() if is_frontlight_on == nil then -- this device does not support frontlight toggle, -- we set the value based on frontlight intensity. if new_intensity > 0 then is_frontlight_on = true else is_frontlight_on = false end end if is_frontlight_on == false and new_intensity == 0 then -- frontlight was toggled off in nickel, and we have no -- level-before-toggle-off (firmware without "FrontLightState"): -- use the one from koreader settings new_intensity = G_reader_settings:readSetting("frontlight_intensity") end else -- if kobo_light_on_start == -1 or other unexpected value then -- As we can't read value from the OS or hardware, use last values -- stored in koreader settings new_intensity = G_reader_settings:readSetting("frontlight_intensity") is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on") end end if new_intensity ~= nil then self.hw_intensity = new_intensity end if is_frontlight_on ~= nil then -- will only be used to give initial state to BasePowerD:_decideFrontlightState() self.initial_is_fl_on = is_frontlight_on end -- In any case frontlight is off, ensure intensity is non-zero so untoggle works if self.initial_is_fl_on == false and self.hw_intensity == 0 then self.hw_intensity = 1 end end function KoboPowerD:init() -- Default values in case self:_syncKoboLightOnStart() does not find -- any previously saved setting (and for unit tests where it will -- not be called) self.hw_intensity = 20 self.initial_is_fl_on = true if self.device.hasFrontlight() then local kobolight = require("ffi/kobolight") local ok, light = pcall(kobolight.open) if ok then self.fl = light self:_syncKoboLightOnStart() end end end function KoboPowerD:saveSettings() -- Store BasePowerD values into settings (and not our hw_intensity, so -- that if frontlight was toggled off, we save and restore the previous -- untoggled intensity and toggle state at next startup) local cur_intensity = self.fl_intensity local cur_is_fl_on = self.is_fl_on -- Save intensity to koreader settings G_reader_settings:saveSetting("frontlight_intensity", cur_intensity) G_reader_settings:saveSetting("is_frontlight_on", cur_is_fl_on) -- And to "Kobo eReader.conf" if needed if KOBO_SYNC_BRIGHTNESS_WITH_NICKEL then if NickelConf.frontLightState.get() ~= nil then if NickelConf.frontLightState.get() ~= cur_is_fl_on then NickelConf.frontLightState.set(cur_is_fl_on) end else -- no support for frontlight state if not cur_is_fl_on then -- if toggled off, save intensity as 0 cur_intensity = self.fl_min end end if NickelConf.frontLightLevel.get() ~= cur_intensity then NickelConf.frontLightLevel.set(cur_intensity) end end end function KoboPowerD:frontlightIntensityHW() return self.hw_intensity end function KoboPowerD:isFrontlightOnHW() if self.initial_is_fl_on ~= nil then -- happens only once after init() -- give initial state to BasePowerD, which will -- reset our self.hw_intensity to 0 if self.initial_is_fl_on is false local ret = self.initial_is_fl_on self.initial_is_fl_on = nil return ret end return self.hw_intensity > 0 end function KoboPowerD:turnOffFrontlightHW() self:_setIntensity(0) -- will call setIntensityHW(0) end function KoboPowerD:setIntensityHW(intensity) if self.fl == nil then return end self.fl:setBrightness(intensity) self.hw_intensity = intensity -- Now that we have set intensity, we need to let BasePowerD -- know about possibly changed frontlight state (if we came -- from light toggled off to some intensity > 0). self:_decideFrontlightState() end function KoboPowerD:getCapacityHW() return self:read_int_file(self.batt_capacity_file) end function KoboPowerD:isChargingHW() return self:read_str_file(self.is_charging_file) == "Charging\n" end -- Turn off front light before suspend. function KoboPowerD:beforeSuspend() if self.fl == nil then return end -- just turn off frontlight without remembering its state self.fl:setBrightness(0) end -- Restore front light state after resume. function KoboPowerD:afterResume() if self.fl == nil then return end -- just re-set it to self.hw_intensity that we haven't change on Suspend self.fl:setBrightness(self.hw_intensity) end return KoboPowerD
local BasePowerD = require("device/generic/powerd") local NickelConf = require("device/kobo/nickel_conf") local batt_state_folder = "/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/" -- Here, we only deal with the real hw intensity. -- Dealing with toggling and remembering/restoring -- previous intensity when toggling/untoggling is done -- by BasePowerD. local KoboPowerD = BasePowerD:new{ fl_min = 0, fl_max = 100, fl = nil, batt_capacity_file = batt_state_folder .. "capacity", is_charging_file = batt_state_folder .. "status", } -- TODO: Remove KOBO_LIGHT_ON_START function KoboPowerD:_syncKoboLightOnStart() local new_intensity = nil local is_frontlight_on = nil local kobo_light_on_start = tonumber(KOBO_LIGHT_ON_START) if kobo_light_on_start then if kobo_light_on_start > 0 then new_intensity = math.min(kobo_light_on_start, 100) is_frontlight_on = true elseif kobo_light_on_start == 0 then new_intensity = 0 is_frontlight_on = false elseif kobo_light_on_start == -2 then -- get values from NickelConf new_intensity = NickelConf.frontLightLevel.get() is_frontlight_on = NickelConf.frontLightState:get() if is_frontlight_on == nil then -- this device does not support frontlight toggle, -- we set the value based on frontlight intensity. if new_intensity > 0 then is_frontlight_on = true else is_frontlight_on = false end end if is_frontlight_on == false and new_intensity == 0 then -- frontlight was toggled off in nickel, and we have no -- level-before-toggle-off (firmware without "FrontLightState"): -- use the one from koreader settings new_intensity = G_reader_settings:readSetting("frontlight_intensity") end else -- if kobo_light_on_start == -1 or other unexpected value then -- As we can't read value from the OS or hardware, use last values -- stored in koreader settings new_intensity = G_reader_settings:readSetting("frontlight_intensity") is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on") end end if new_intensity ~= nil then self.hw_intensity = new_intensity end if is_frontlight_on ~= nil then -- will only be used to give initial state to BasePowerD:_decideFrontlightState() self.initial_is_fl_on = is_frontlight_on end -- In any case frontlight is off, ensure intensity is non-zero so untoggle works if self.initial_is_fl_on == false and self.hw_intensity == 0 then self.hw_intensity = 1 end end function KoboPowerD:init() -- Default values in case self:_syncKoboLightOnStart() does not find -- any previously saved setting (and for unit tests where it will -- not be called) self.hw_intensity = 20 self.initial_is_fl_on = true if self.device.hasFrontlight() then local kobolight = require("ffi/kobolight") local ok, light = pcall(kobolight.open) if ok then self.fl = light self:_syncKoboLightOnStart() end end end function KoboPowerD:saveSettings() if self.device.hasFrontlight() then -- Store BasePowerD values into settings (and not our hw_intensity, so -- that if frontlight was toggled off, we save and restore the previous -- untoggled intensity and toggle state at next startup) local cur_intensity = self.fl_intensity local cur_is_fl_on = self.is_fl_on -- Save intensity to koreader settings G_reader_settings:saveSetting("frontlight_intensity", cur_intensity) G_reader_settings:saveSetting("is_frontlight_on", cur_is_fl_on) -- And to "Kobo eReader.conf" if needed if KOBO_SYNC_BRIGHTNESS_WITH_NICKEL then if NickelConf.frontLightState.get() ~= nil then if NickelConf.frontLightState.get() ~= cur_is_fl_on then NickelConf.frontLightState.set(cur_is_fl_on) end else -- no support for frontlight state if not cur_is_fl_on then -- if toggled off, save intensity as 0 cur_intensity = self.fl_min end end if NickelConf.frontLightLevel.get() ~= cur_intensity then NickelConf.frontLightLevel.set(cur_intensity) end end end end function KoboPowerD:frontlightIntensityHW() return self.hw_intensity end function KoboPowerD:isFrontlightOnHW() if self.initial_is_fl_on ~= nil then -- happens only once after init() -- give initial state to BasePowerD, which will -- reset our self.hw_intensity to 0 if self.initial_is_fl_on is false local ret = self.initial_is_fl_on self.initial_is_fl_on = nil return ret end return self.hw_intensity > 0 end function KoboPowerD:turnOffFrontlightHW() self:_setIntensity(0) -- will call setIntensityHW(0) end function KoboPowerD:setIntensityHW(intensity) if self.fl == nil then return end self.fl:setBrightness(intensity) self.hw_intensity = intensity -- Now that we have set intensity, we need to let BasePowerD -- know about possibly changed frontlight state (if we came -- from light toggled off to some intensity > 0). self:_decideFrontlightState() end function KoboPowerD:getCapacityHW() return self:read_int_file(self.batt_capacity_file) end function KoboPowerD:isChargingHW() return self:read_str_file(self.is_charging_file) == "Charging\n" end -- Turn off front light before suspend. function KoboPowerD:beforeSuspend() if self.fl == nil then return end -- just turn off frontlight without remembering its state self.fl:setBrightness(0) end -- Restore front light state after resume. function KoboPowerD:afterResume() if self.fl == nil then return end -- just re-set it to self.hw_intensity that we haven't change on Suspend self.fl:setBrightness(self.hw_intensity) end return KoboPowerD
Fix crash on exit on Kobo devices with no frontlight (#3221)
Fix crash on exit on Kobo devices with no frontlight (#3221)
Lua
agpl-3.0
mwoz123/koreader,NiLuJe/koreader,houqp/koreader,Hzj-jie/koreader,NiLuJe/koreader,mihailim/koreader,poire-z/koreader,koreader/koreader,pazos/koreader,Markismus/koreader,Frenzie/koreader,Frenzie/koreader,apletnev/koreader,koreader/koreader,lgeek/koreader,poire-z/koreader
f486854b5fb48490a8ea3b9d321a71d929f46d6d
libs/uvl/luasrc/uvl/errors.lua
libs/uvl/luasrc/uvl/errors.lua
--[[ UCI Validation Layer - Error handling (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> (c) 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$ ]]-- local uci = require "luci.model.uci" local uvl = require "luci.uvl" local util = require "luci.util" local string = require "string" local ipairs, error, type = ipairs, error, type local tonumber, unpack = tonumber, unpack local luci = luci module "luci.uvl.errors" ERRCODES = { UCILOAD = 'Unable to load config "%p": %1', SCHEME = 'Error in scheme "%p":\n%c', CONFIG = 'Error in config "%p":\n%c', SECTION = 'Error in section "%i" (%I):\n%c', OPTION = 'Error in option "%i" (%I):\n%c', REFERENCE = 'Option "%i" has invalid reference specification %1:\n%c', DEPENDENCY = 'In dependency check for %t "%i":\n%c', SME_FIND = 'Can not find scheme "%p" in "%1"', SME_READ = 'Can not access file "%1"', SME_REQFLD = 'Missing required scheme field "%1" in "%i"', SME_INVREF = 'Illegal reference "%1" to an anonymous section', SME_BADREF = 'Malformed reference in "%1"', SME_BADDEP = 'Malformed dependency specification "%1" in "%i"', SME_BADVAL = 'Malformed validator specification "%1" in "%i"', SME_ERRVAL = 'External validator "%1" failed: %2', SME_VBADPACK = 'Variable "%o" in scheme "%p" references unknown package "%1"', SME_VBADSECT = 'Variable "%o" in scheme "%p" references unknown section "%1"', SME_EBADPACK = 'Enum "%v" in scheme "%p" references unknown package "%1"', SME_EBADSECT = 'Enum "%v" in scheme "%p" references unknown section "%1"', SME_EBADOPT = 'Enum "%v" in scheme "%p" references unknown option "%1"', SME_EBADTYPE = 'Enum "%v" in scheme "%p" references non-enum option "%I"', SME_EBADDEF = 'Enum "%v" in scheme "%p" redeclares the default value of "%I"', SECT_UNKNOWN = 'Section "%i" (%I) not found in scheme', SECT_REQUIRED = 'Required section "%p.%S" not found in config', SECT_UNIQUE = 'Unique section "%p.%S" occurs multiple times in config', SECT_NAMED = 'The section of type "%p.%S" is stored anonymously in config but must be named', SECT_NOTFOUND = 'Section "%p.%s" not found in config', OPT_UNKNOWN = 'Option "%i" (%I) not found in scheme', OPT_REQUIRED = 'Required option "%i" has no value', OPT_BADVALUE = 'Value "%1" of option "%i" is not defined in enum %2', OPT_INVVALUE = 'Value "%1" of option "%i" does not validate as datatype "%2"', OPT_NOTLIST = 'Option "%i" is defined as list but stored as plain value', OPT_DATATYPE = 'Option "%i" has unknown datatype "%1"', OPT_NOTFOUND = 'Option "%p.%s.%o" not found in config', OPT_RANGE = 'Option "%p.%s.%o" is not within the specified range', DEP_NOTEQUAL = 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"', DEP_NOVALUE = 'Dependency (%1) failed:\nOption "%i" has no value', DEP_NOTVALID = 'Dependency (%1) failed:\n%c', DEP_RECURSIVE = 'Recursive dependency for option "%i" detected', DEP_BADENUM = 'In dependency check for enum value "%i":\n%c' } function i18n(key) if luci.i18n then return luci.i18n.translate(key) else return key end end error = util.class() function error.__init__(self, code, pso, args) self.code = code self.args = ( type(args) == "table" and args or { args } ) if util.instanceof( pso, uvl.uvlitem ) then self.stype = pso.sref[2] self.package, self.section, self.option, self.value = unpack(pso.cref) self.object = pso self.value = self.value or ( pso.value and pso:value() ) else pso = ( type(pso) == "table" and pso or { pso } ) if pso[2] then local uci = uci.cursor() self.stype = uci:get(pso[1], pso[2]) or pso[2] end self.package, self.section, self.option, self.value = unpack(pso) end end function error.child(self, err) if not self.childs then self.childs = { err } else self.childs[#self.childs+1] = err end return self end function error.string(self,pad) pad = pad or " " local str = i18n(ERRCODES[self.code] or self.code]) :gsub("\n", "\n"..pad) :gsub("%%i", self:cid()) :gsub("%%I", self:sid()) :gsub("%%p", self.package or '(nil)') :gsub("%%s", self.section or '(nil)') :gsub("%%S", self.stype or '(nil)') :gsub("%%o", self.option or '(nil)') :gsub("%%v", self.value or '(nil)') :gsub("%%t", self.object and self.object:type() or '(nil)' ) :gsub("%%T", self.object and self.object:title() or '(nil)' ) :gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end) :gsub("%%c", function() local s = "" for _, err in ipairs(self.childs or {}) do s = s .. err:string(pad.." ") .. "\n" .. pad end return s end ) return (str:gsub("%s+$","")) end function error.cid(self) return self.object and self.object:cid() or self.package .. ( self.section and '.' .. self.section or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.sid(self) return self.object and self.object:sid() or self.package .. ( self.stype and '.' .. self.stype or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.is(self, code) if self.code == code then return true elseif self.childs then for _, c in ipairs(self.childs) do if c:is(code) then return true end end end return false end function error.is_all(self, ...) local codes = { ... } if util.contains(codes, self.code) then return true else local equal = false for _, c in ipairs(self.childs) do if c.childs then equal = c:is_all(...) else equal = util.contains(codes, c.code) end end return equal end end
--[[ UCI Validation Layer - Error handling (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> (c) 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$ ]]-- local uci = require "luci.model.uci" local uvl = require "luci.uvl" local util = require "luci.util" local string = require "string" local ipairs, error, type = ipairs, error, type local tonumber, unpack = tonumber, unpack local luci = luci module "luci.uvl.errors" ERRCODES = { UCILOAD = 'Unable to load config "%p": %1', SCHEME = 'Error in scheme "%p":\n%c', CONFIG = 'Error in config "%p":\n%c', SECTION = 'Error in section "%i" (%I):\n%c', OPTION = 'Error in option "%i" (%I):\n%c', REFERENCE = 'Option "%i" has invalid reference specification %1:\n%c', DEPENDENCY = 'In dependency check for %t "%i":\n%c', SME_FIND = 'Can not find scheme "%p" in "%1"', SME_READ = 'Can not access file "%1"', SME_REQFLD = 'Missing required scheme field "%1" in "%i"', SME_INVREF = 'Illegal reference "%1" to an anonymous section', SME_BADREF = 'Malformed reference in "%1"', SME_BADDEP = 'Malformed dependency specification "%1" in "%i"', SME_BADVAL = 'Malformed validator specification "%1" in "%i"', SME_ERRVAL = 'External validator "%1" failed: %2', SME_VBADPACK = 'Variable "%o" in scheme "%p" references unknown package "%1"', SME_VBADSECT = 'Variable "%o" in scheme "%p" references unknown section "%1"', SME_EBADPACK = 'Enum "%v" in scheme "%p" references unknown package "%1"', SME_EBADSECT = 'Enum "%v" in scheme "%p" references unknown section "%1"', SME_EBADOPT = 'Enum "%v" in scheme "%p" references unknown option "%1"', SME_EBADTYPE = 'Enum "%v" in scheme "%p" references non-enum option "%I"', SME_EBADDEF = 'Enum "%v" in scheme "%p" redeclares the default value of "%I"', SECT_UNKNOWN = 'Section "%i" (%I) not found in scheme', SECT_REQUIRED = 'Required section "%p.%S" not found in config', SECT_UNIQUE = 'Unique section "%p.%S" occurs multiple times in config', SECT_NAMED = 'The section of type "%p.%S" is stored anonymously in config but must be named', SECT_NOTFOUND = 'Section "%p.%s" not found in config', OPT_UNKNOWN = 'Option "%i" (%I) not found in scheme', OPT_REQUIRED = 'Required option "%i" has no value', OPT_BADVALUE = 'Value "%1" of option "%i" is not defined in enum %2', OPT_INVVALUE = 'Value "%1" of option "%i" does not validate as datatype "%2"', OPT_NOTLIST = 'Option "%i" is defined as list but stored as plain value', OPT_DATATYPE = 'Option "%i" has unknown datatype "%1"', OPT_NOTFOUND = 'Option "%p.%s.%o" not found in config', OPT_RANGE = 'Option "%p.%s.%o" is not within the specified range', DEP_NOTEQUAL = 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"', DEP_NOVALUE = 'Dependency (%1) failed:\nOption "%i" has no value', DEP_NOTVALID = 'Dependency (%1) failed:\n%c', DEP_RECURSIVE = 'Recursive dependency for option "%i" detected', DEP_BADENUM = 'In dependency check for enum value "%i":\n%c' } function i18n(key) if luci.i18n then return luci.i18n.translate(key) else return key end end error = util.class() function error.__init__(self, code, pso, args) self.code = code self.args = ( type(args) == "table" and args or { args } ) if util.instanceof( pso, uvl.uvlitem ) then self.stype = pso.sref[2] self.package, self.section, self.option, self.value = unpack(pso.cref) self.object = pso self.value = self.value or ( pso.value and pso:value() ) else pso = ( type(pso) == "table" and pso or { pso } ) if pso[2] then local uci = uci.cursor() self.stype = uci:get(pso[1], pso[2]) or pso[2] end self.package, self.section, self.option, self.value = unpack(pso) end end function error.child(self, err) if not self.childs then self.childs = { err } else self.childs[#self.childs+1] = err end return self end function error.string(self,pad) pad = pad or " " local str = i18n(ERRCODES[self.code] or self.code) :gsub("\n", "\n"..pad) :gsub("%%i", self:cid()) :gsub("%%I", self:sid()) :gsub("%%p", self.package or '(nil)') :gsub("%%s", self.section or '(nil)') :gsub("%%S", self.stype or '(nil)') :gsub("%%o", self.option or '(nil)') :gsub("%%v", self.value or '(nil)') :gsub("%%t", self.object and self.object:type() or '(nil)' ) :gsub("%%T", self.object and self.object:title() or '(nil)' ) :gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end) :gsub("%%c", function() local s = "" for _, err in ipairs(self.childs or {}) do s = s .. err:string(pad.." ") .. "\n" .. pad end return s end ) return (str:gsub("%s+$","")) end function error.cid(self) return self.object and self.object:cid() or self.package .. ( self.section and '.' .. self.section or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.sid(self) return self.object and self.object:sid() or self.package .. ( self.stype and '.' .. self.stype or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.is(self, code) if self.code == code then return true elseif self.childs then for _, c in ipairs(self.childs) do if c:is(code) then return true end end end return false end function error.is_all(self, ...) local codes = { ... } if util.contains(codes, self.code) then return true else local equal = false for _, c in ipairs(self.childs) do if c.childs then equal = c:is_all(...) else equal = util.contains(codes, c.code) end end return equal end end
libs/uvl: fix syntax error introduced with r5861
libs/uvl: fix syntax error introduced with r5861 git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5863 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
stephank/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,vhpham80/luci,phi-psi/luci,8devices/carambola2-luci,saraedum/luci-packages-old,projectbismark/luci-bismark,ThingMesh/openwrt-luci,yeewang/openwrt-luci,Canaan-Creative/luci,gwlim/luci,ch3n2k/luci,8devices/carambola2-luci,Flexibity/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,gwlim/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,gwlim/luci,Flexibity/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,Canaan-Creative/luci,phi-psi/luci,phi-psi/luci,stephank/luci,zwhfly/openwrt-luci,stephank/luci,phi-psi/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,ch3n2k/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,ch3n2k/luci,freifunk-gluon/luci,8devices/carambola2-luci,gwlim/luci,stephank/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,Flexibity/luci,freifunk-gluon/luci,phi-psi/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,Flexibity/luci,saraedum/luci-packages-old,Flexibity/luci,zwhfly/openwrt-luci,Flexibity/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,gwlim/luci,saraedum/luci-packages-old,stephank/luci,vhpham80/luci,yeewang/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,vhpham80/luci,projectbismark/luci-bismark,ch3n2k/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,saraedum/luci-packages-old,Canaan-Creative/luci,ch3n2k/luci,Flexibity/luci,jschmidlapp/luci,gwlim/luci,eugenesan/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,jschmidlapp/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,saraedum/luci-packages-old,8devices/carambola2-luci,stephank/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,ch3n2k/luci,Canaan-Creative/luci,yeewang/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,8devices/carambola2-luci,vhpham80/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,jschmidlapp/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci
11d0129f9661155dd2bd44cce5866726acd53433
modules/luci-base/luasrc/http.lua
modules/luci-base/luasrc/http.lua
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local ltn12 = require "luci.ltn12" local protocol = require "luci.http.protocol" local util = require "luci.util" local string = require "string" local coroutine = require "coroutine" local table = require "table" local ipairs, pairs, next, type, tostring, error = ipairs, pairs, next, type, tostring, error module "luci.http" context = util.threadlocal() Request = util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler nil by default to let .content() work self.filehandler = nil -- HTTP-Message table self.message = { env = env, headers = {}, params = protocol.urldecode_params(env.QUERY_STRING or ""), } self.parsed_input = false end function Request.formvalue(self, name, noparse) if not noparse and not self.parsed_input then self:_parse_input() end if name then return self.message.params[name] else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." if not self.parsed_input then self:_parse_input() end local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.content(self) if not self.parsed_input then self:_parse_input() end return self.message.content, self.message.content_length end function Request.getcookie(self, name) local c = string.gsub(";" .. (self:getenv("HTTP_COOKIE") or "") .. ";", "%s*;%s*", ";") local p = ";" .. name .. "=(.-);" local i, j, value = c:find(p) return value and urldecode(value) end function Request.getenv(self, name) if name then return self.message.env[name] else return self.message.env end end function Request.setfilehandler(self, callback) self.filehandler = callback -- If input has already been parsed then any files are either in temporary files -- or are in self.message.params[key] if self.parsed_input then for param, value in pairs(self.message.params) do repeat -- We're only interested in files if (not value["file"]) then break end -- If we were able to write to temporary file if (value["fd"]) then fd = value["fd"] local eof = false repeat filedata = fd:read(1024) if (filedata:len() < 1024) then eof = true end callback({ name=value["name"], file=value["file"] }, filedata, eof) until (eof) fd:close() value["fd"] = nil -- We had to read into memory else -- There should only be one numbered value in table - the data for k, v in ipairs(value) do callback({ name=value["name"], file=value["file"] }, v, true) end end until true end end end function Request._parse_input(self) protocol.parse_message_body( self.input, self.message, self.filehandler ) self.parsed_input = true end function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end function content() return context.request:content() end function formvalue(name, noparse) return context.request:formvalue(name, noparse) end function formvaluetable(prefix) return context.request:formvaluetable(prefix) end function getcookie(name) return context.request:getcookie(name) end -- or the environment table itself. function getenv(name) return context.request:getenv(name) end function setfilehandler(callback) return context.request:setfilehandler(callback) end function header(key, value) if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end function prepare_content(mime) if not context.headers or not context.headers["content-type"] then if mime == "application/xhtml+xml" then if not getenv("HTTP_ACCEPT") or not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then mime = "text/html; charset=UTF-8" end header("Vary", "Accept") end header("Content-Type", mime) end end function source() return context.request.input end function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end -- This function is as a valid LTN12 sink. -- If the content chunk is nil this function will automatically invoke close. function write(content, src_err) if not content then if src_err then error(src_err) else close() end return true elseif #content == 0 then return true else if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end if not context.headers["cache-control"] then header("Cache-Control", "no-cache") header("Expires", "0") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) return true end end function splice(fd, size) coroutine.yield(6, fd, size) end function redirect(url) if url == "" then url = "/" end status(302, "Found") header("Location", url) close() end function build_querystring(q) local s = { "?" } for k, v in pairs(q) do if #s > 1 then s[#s+1] = "&" end s[#s+1] = urldecode(k) s[#s+1] = "=" s[#s+1] = urldecode(v) end return table.concat(s, "") end urldecode = protocol.urldecode urlencode = protocol.urlencode function write_json(x) util.serialize_json(x, write) end
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local ltn12 = require "luci.ltn12" local protocol = require "luci.http.protocol" local util = require "luci.util" local string = require "string" local coroutine = require "coroutine" local table = require "table" local ipairs, pairs, next, type, tostring, error = ipairs, pairs, next, type, tostring, error module "luci.http" context = util.threadlocal() Request = util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler nil by default to let .content() work self.filehandler = nil -- HTTP-Message table self.message = { env = env, headers = {}, params = protocol.urldecode_params(env.QUERY_STRING or ""), } self.parsed_input = false end function Request.formvalue(self, name, noparse) if not noparse and not self.parsed_input then self:_parse_input() end if name then return self.message.params[name] else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." if not self.parsed_input then self:_parse_input() end local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.content(self) if not self.parsed_input then self:_parse_input() end return self.message.content, self.message.content_length end function Request.getcookie(self, name) local c = string.gsub(";" .. (self:getenv("HTTP_COOKIE") or "") .. ";", "%s*;%s*", ";") local p = ";" .. name .. "=(.-);" local i, j, value = c:find(p) return value and urldecode(value) end function Request.getenv(self, name) if name then return self.message.env[name] else return self.message.env end end function Request.setfilehandler(self, callback) self.filehandler = callback -- If input has already been parsed then any files are either in temporary files -- or are in self.message.params[key] if self.parsed_input then for param, value in pairs(self.message.params) do repeat -- We're only interested in files if (not value["file"]) then break end -- If we were able to write to temporary file if (value["fd"]) then fd = value["fd"] local eof = false repeat filedata = fd:read(1024) if (filedata:len() < 1024) then eof = true end callback({ name=value["name"], file=value["file"] }, filedata, eof) until (eof) fd:close() value["fd"] = nil -- We had to read into memory else -- There should only be one numbered value in table - the data for k, v in ipairs(value) do callback({ name=value["name"], file=value["file"] }, v, true) end end until true end end end function Request._parse_input(self) protocol.parse_message_body( self.input, self.message, self.filehandler ) self.parsed_input = true end function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end function content() return context.request:content() end function formvalue(name, noparse) return context.request:formvalue(name, noparse) end function formvaluetable(prefix) return context.request:formvaluetable(prefix) end function getcookie(name) return context.request:getcookie(name) end -- or the environment table itself. function getenv(name) return context.request:getenv(name) end function setfilehandler(callback) return context.request:setfilehandler(callback) end function header(key, value) if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end function prepare_content(mime) if not context.headers or not context.headers["content-type"] then if mime == "application/xhtml+xml" then if not getenv("HTTP_ACCEPT") or not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then mime = "text/html; charset=UTF-8" end header("Vary", "Accept") end header("Content-Type", mime) end end function source() return context.request.input end function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end -- This function is as a valid LTN12 sink. -- If the content chunk is nil this function will automatically invoke close. function write(content, src_err) if not content then if src_err then error(src_err) else close() end return true elseif #content == 0 then return true else if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end if not context.headers["cache-control"] then header("Cache-Control", "no-cache") header("Expires", "0") end if not context.headers["x-frame-options"] then header("X-Frame-Options", "SAMEORIGIN") end if not context.headers["x-xss-protection"] then header("X-XSS-Protection", "1; mode=block") end if not context.headers["x-content-type-options"] then header("X-Content-Type-Options", "nosniff") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) return true end end function splice(fd, size) coroutine.yield(6, fd, size) end function redirect(url) if url == "" then url = "/" end status(302, "Found") header("Location", url) close() end function build_querystring(q) local s = { "?" } for k, v in pairs(q) do if #s > 1 then s[#s+1] = "&" end s[#s+1] = urldecode(k) s[#s+1] = "=" s[#s+1] = urldecode(v) end return table.concat(s, "") end urldecode = protocol.urldecode urlencode = protocol.urlencode function write_json(x) util.serialize_json(x, write) end
http: add random security headers
http: add random security headers Fixes #1343. Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
Lua
apache-2.0
981213/luci-1,981213/luci-1,remakeelectric/luci,nmav/luci,kuoruan/lede-luci,chris5560/openwrt-luci,chris5560/openwrt-luci,kuoruan/luci,kuoruan/lede-luci,remakeelectric/luci,Noltari/luci,artynet/luci,hnyman/luci,openwrt/luci,openwrt-es/openwrt-luci,Wedmer/luci,rogerpueyo/luci,openwrt/luci,wongsyrone/luci-1,kuoruan/luci,Wedmer/luci,hnyman/luci,lbthomsen/openwrt-luci,nmav/luci,openwrt/luci,rogerpueyo/luci,Wedmer/luci,wongsyrone/luci-1,openwrt/luci,remakeelectric/luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,nmav/luci,wongsyrone/luci-1,openwrt/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,kuoruan/luci,hnyman/luci,nmav/luci,Noltari/luci,artynet/luci,kuoruan/lede-luci,kuoruan/luci,tobiaswaldvogel/luci,Wedmer/luci,chris5560/openwrt-luci,artynet/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,rogerpueyo/luci,artynet/luci,Noltari/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,remakeelectric/luci,oneru/luci,kuoruan/luci,Wedmer/luci,lbthomsen/openwrt-luci,remakeelectric/luci,chris5560/openwrt-luci,kuoruan/luci,kuoruan/lede-luci,hnyman/luci,oneru/luci,kuoruan/luci,rogerpueyo/luci,981213/luci-1,oneru/luci,openwrt-es/openwrt-luci,Noltari/luci,wongsyrone/luci-1,981213/luci-1,lbthomsen/openwrt-luci,openwrt/luci,wongsyrone/luci-1,oneru/luci,hnyman/luci,lbthomsen/openwrt-luci,Noltari/luci,openwrt-es/openwrt-luci,openwrt/luci,981213/luci-1,Wedmer/luci,nmav/luci,tobiaswaldvogel/luci,981213/luci-1,kuoruan/lede-luci,wongsyrone/luci-1,artynet/luci,Wedmer/luci,wongsyrone/luci-1,oneru/luci,openwrt/luci,tobiaswaldvogel/luci,remakeelectric/luci,remakeelectric/luci,Wedmer/luci,nmav/luci,oneru/luci,Noltari/luci,nmav/luci,artynet/luci,oneru/luci,artynet/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,Noltari/luci,chris5560/openwrt-luci,rogerpueyo/luci,remakeelectric/luci,nmav/luci,tobiaswaldvogel/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,oneru/luci,981213/luci-1,Noltari/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,Noltari/luci,nmav/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,kuoruan/luci,artynet/luci,tobiaswaldvogel/luci,artynet/luci,hnyman/luci,tobiaswaldvogel/luci
e71d2a336a2c30516d89b6932ecc3078314ff5f3
tests/actions/make/test_make_pch.lua
tests/actions/make/test_make_pch.lua
-- -- tests/actions/make/test_make_pch.lua -- Validate the setup for precompiled headers in makefiles. -- Copyright (c) 2010 Jason Perkins and the Premake project -- T.make_pch = { } local suite = T.make_pch local _ = premake.make.cpp -- -- Setup and teardown -- local sln, prj, cfg function suite.setup() sln, prj = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.getconfig(prj) cfg = premake.getconfig(prj, "Debug") end -- -- Configuration block tests -- function suite.NoConfig_OnNoHeaderSet() prepare() _.pchconfig(cfg) test.capture [[]] end function suite.NoConfig_OnHeaderAndNoPCHFlag() pchheader "include/myproject.h" flags { NoPCH } prepare() _.pchconfig(cfg) test.capture [[]] end function suite.ConfigBlock_OnPchEnabled() pchheader "include/myproject.h" prepare() _.pchconfig(cfg) test.capture [[ PCH = include/myproject.h GCH = $(OBJDIR)/$(notdir $(PCH)).gch ]] end -- -- Build rule tests -- function suite.BuildRules_OnCpp() pchheader "include/myproject.h" prepare() _.pchrules(prj) test.capture [[ ifneq (,$(PCH)) $(GCH): $(PCH) @echo $(notdir $<) $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" ]] end function suite.BuildRules_OnC() language "C" pchheader "include/myproject.h" prepare() _.pchrules(prj) test.capture [[ ifneq (,$(PCH)) $(GCH): $(PCH) @echo $(notdir $<) $(SILENT) $(CC) -x c-header $(ALL_CFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" ]] end -- -- Ensure that PCH is included on all files that use it. -- function suite.includesPCH_onUse() pchheader "include/myproject.h" files { "main.cpp" } prepare() _.fileRules(prj) test.capture [[ $(OBJDIR)/main.o: main.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF $(@:%.o=%.d) -c "$<" ]] end -- -- If the header is located on one of the include file -- search directories, it should get found automatically. -- function suite.findsPCH_onIncludeDirs() location "MyProject" pchheader "premake.h" includedirs { "../src/host" } prepare() _.pchconfig(cfg) test.capture [[ PCH = ../../src/host/premake.h ]] end
-- -- tests/actions/make/test_make_pch.lua -- Validate the setup for precompiled headers in makefiles. -- Copyright (c) 2010 Jason Perkins and the Premake project -- T.make_pch = { } local suite = T.make_pch local _ = premake.make.cpp -- -- Setup and teardown -- local sln, prj, cfg function suite.setup() sln, prj = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.getconfig(prj) cfg = premake.getconfig(prj, "Debug") end -- -- Configuration block tests -- function suite.NoConfig_OnNoHeaderSet() prepare() _.pchconfig(cfg) test.capture [[]] end function suite.NoConfig_OnHeaderAndNoPCHFlag() pchheader "include/myproject.h" flags { NoPCH } prepare() _.pchconfig(cfg) test.capture [[]] end function suite.ConfigBlock_OnPchEnabled() pchheader "include/myproject.h" prepare() _.pchconfig(cfg) test.capture [[ PCH = include/myproject.h GCH = $(OBJDIR)/$(notdir $(PCH)).gch ]] end -- -- Build rule tests -- function suite.BuildRules_OnCpp() pchheader "include/myproject.h" prepare() _.pchrules(prj) test.capture [[ ifneq (,$(PCH)) .NOTPARALLEL: $(GCH) $(PCH) $(GCH): $(PCH) @echo $(notdir $<) $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" ]] end function suite.BuildRules_OnC() language "C" pchheader "include/myproject.h" prepare() _.pchrules(prj) test.capture [[ ifneq (,$(PCH)) .NOTPARALLEL: $(GCH) $(PCH) $(GCH): $(PCH) @echo $(notdir $<) $(SILENT) $(CC) -x c-header $(ALL_CFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" ]] end -- -- Ensure that PCH is included on all files that use it. -- function suite.includesPCH_onUse() pchheader "include/myproject.h" files { "main.cpp" } prepare() _.fileRules(prj) test.capture [[ $(OBJDIR)/main.o: main.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF $(@:%.o=%.d) -c "$<" ]] end -- -- If the header is located on one of the include file -- search directories, it should get found automatically. -- function suite.findsPCH_onIncludeDirs() location "MyProject" pchheader "premake.h" includedirs { "../src/host" } prepare() _.pchconfig(cfg) test.capture [[ PCH = ../../src/host/premake.h ]] end
Issue #236: Fix failing PCH unit tests
Issue #236: Fix failing PCH unit tests
Lua
bsd-3-clause
lizh06/premake-4.x,ryanjmulder/premake-4.x,premake/premake-4.x,ryanjmulder/premake-4.x,ryanjmulder/premake-4.x,lizh06/premake-4.x,lizh06/premake-4.x,lizh06/premake-4.x,premake/premake-4.x,premake/premake-4.x,ryanjmulder/premake-4.x,premake/premake-4.x
fb859e602b1254c5d199d7f641f6b6717edd01cf
applications/luci-app-nlbwmon/luasrc/controller/nlbw.lua
applications/luci-app-nlbwmon/luasrc/controller/nlbw.lua
-- Copyright 2017 Jo-Philipp Wich <jo@mein.io> -- Licensed to the public under the Apache License 2.0. module("luci.controller.nlbw", package.seeall) function index() entry({"admin", "nlbw"}, firstchild(), _("Bandwidth Monitor"), 80) entry({"admin", "nlbw", "display"}, template("nlbw/display"), _("Display"), 1) entry({"admin", "nlbw", "config"}, cbi("nlbw/config"), _("Configuration"), 2) entry({"admin", "nlbw", "backup"}, template("nlbw/backup"), _("Backup"), 3) entry({"admin", "nlbw", "data"}, call("action_data"), nil, 4) entry({"admin", "nlbw", "list"}, call("action_list"), nil, 5) entry({"admin", "nlbw", "ptr"}, call("action_ptr"), nil, 6).leaf = true entry({"admin", "nlbw", "download"}, call("action_download"), nil, 7) entry({"admin", "nlbw", "restore"}, post("action_restore"), nil, 8) entry({"admin", "nlbw", "commit"}, call("action_commit"), nil, 9) end local function exec(cmd, args, writer) local os = require "os" local nixio = require "nixio" local fdi, fdo = nixio.pipe() local pid = nixio.fork() if pid > 0 then fdo:close() while true do local buffer = fdi:read(2048) if not buffer or #buffer == 0 then break end if writer then writer(buffer) end end nixio.waitpid(pid) elseif pid == 0 then nixio.dup(fdo, nixio.stdout) fdi:close() fdo:close() nixio.exece(cmd, args, nil) nixio.stdout:close() os.exit(1) end end function action_data() local http = require "luci.http" local types = { csv = "text/csv", json = "application/json" } local filename = "data." .. mtype local args = { } local mtype = http.formvalue("type") or "json" local delim = http.formvalue("delim") or "," local period = http.formvalue("period") local group_by = http.formvalue("group_by") local order_by = http.formvalue("order_by") if types[mtype] then args[#args+1] = "-c" args[#args+1] = mtype else http.status(400, "Unsupported type") return end if delim and #delim > 0 then args[#args+1] = "-s%s" % delim end if period and #period > 0 then args[#args+1] = "-t" args[#args+1] = period end if group_by and #group_by > 0 then args[#args+1] = "-g" args[#args+1] = group_by end if order_by and #order_by > 0 then args[#args+1] = "-o" args[#args+1] = order_by end http.prepare_content(types[mtype]) http.header("Content-Disposition", "attachment; filename=\"%s\"" % filename) exec("/usr/sbin/nlbw", args, http.write) end function action_list() local http = require "luci.http" local fd = io.popen("/usr/sbin/nlbw -c list") local periods = { } if fd then while true do local period = fd:read("*l") if not period then break end periods[#periods+1] = period end fd:close() end http.prepare_content("application/json") http.write_json(periods) end function action_ptr(...) local http = require "luci.http" local util = require "luci.util" http.prepare_content("application/json") http.write_json(util.ubus("network.rrdns", "lookup", { addrs = {...}, timeout = 3000 })) end function action_download() local nixio = require "nixio" local http = require "luci.http" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local dir = uci:get_first("nlbwmon", "nlbwmon", "database_directory") or "/var/lib/nlbwmon" if dir and nixio.fs.stat(dir, "type") == "dir" then local n = "nlbwmon-backup-%s-%s.tar.gz" %{ sys.hostname(), os.date("%Y-%m-%d") } http.prepare_content("application/octet-stream") http.header("Content-Disposition", "attachment; filename=\"%s\"" % n) exec("/bin/tar", { "-C", dir, "-c", "-z", ".", "-f", "-" }, http.write) else http.status(500, "Unable to find database directory") end end function action_restore() local nixio = require "nixio" local http = require "luci.http" local i18n = require "luci.i18n" local tpl = require "luci.template" local uci = require "luci.model.uci".cursor() local tmp = "/tmp/nlbw-restore.tar.gz" local dir = uci:get_first("nlbwmon", "nlbwmon", "database_directory") or "/var/lib/nlbwmon" local fp http.setfilehandler( function(meta, chunk, eof) if not fp and meta and meta.name == "archive" then fp = io.open(tmp, "w") end if fp and chunk then fp:write(chunk) end if fp and eof then fp:close() end end) local files = { } local tar = io.popen("/bin/tar -tzf %s" % tmp, "r") if tar then while true do local file = tar:read("*l") if not file then break elseif file:match("^%d%d%d%d%d%d%d%d%.db%.gz$") or file:match("^%./%d%d%d%d%d%d%d%d%.db%.gz$") then files[#files+1] = file end end tar:close() end if #files == 0 then http.status(500, "Internal Server Error") tpl.render("nlbw/backup", { message = i18n.translate("Invalid or empty backup archive") }) return end local output = { } exec("/etc/init.d/nlbwmon", { "stop" }) exec("/bin/mkdir", { "-p", dir }) exec("/bin/tar", { "-C", dir, "-vxzf", tmp, unpack(files) }, function(chunk) output[#output+1] = chunk:match("%S+") end) exec("/bin/rm", { "-f", tmp }) exec("/etc/init.d/nlbwmon", { "start" }) tpl.render("nlbw/backup", { message = i18n.translatef( "The following database files have been restored: %s", table.concat(output, ", ")) }) end function action_commit() local http = require "luci.http" local disp = require "luci.dispatcher" http.redirect(disp.build_url("admin/nlbw/display")) exec("/usr/sbin/nlbw", { "-c", "commit" }) end
-- Copyright 2017 Jo-Philipp Wich <jo@mein.io> -- Licensed to the public under the Apache License 2.0. module("luci.controller.nlbw", package.seeall) function index() entry({"admin", "nlbw"}, firstchild(), _("Bandwidth Monitor"), 80) entry({"admin", "nlbw", "display"}, template("nlbw/display"), _("Display"), 1) entry({"admin", "nlbw", "config"}, cbi("nlbw/config"), _("Configuration"), 2) entry({"admin", "nlbw", "backup"}, template("nlbw/backup"), _("Backup"), 3) entry({"admin", "nlbw", "data"}, call("action_data"), nil, 4) entry({"admin", "nlbw", "list"}, call("action_list"), nil, 5) entry({"admin", "nlbw", "ptr"}, call("action_ptr"), nil, 6).leaf = true entry({"admin", "nlbw", "download"}, call("action_download"), nil, 7) entry({"admin", "nlbw", "restore"}, post("action_restore"), nil, 8) entry({"admin", "nlbw", "commit"}, call("action_commit"), nil, 9) end local function exec(cmd, args, writer) local os = require "os" local nixio = require "nixio" local fdi, fdo = nixio.pipe() local pid = nixio.fork() if pid > 0 then fdo:close() while true do local buffer = fdi:read(2048) if not buffer or #buffer == 0 then break end if writer then writer(buffer) end end nixio.waitpid(pid) elseif pid == 0 then nixio.dup(fdo, nixio.stdout) fdi:close() fdo:close() nixio.exece(cmd, args, nil) nixio.stdout:close() os.exit(1) end end function action_data() local http = require "luci.http" local types = { csv = "text/csv", json = "application/json" } local args = { } local mtype = http.formvalue("type") or "json" local delim = http.formvalue("delim") or "," local period = http.formvalue("period") local group_by = http.formvalue("group_by") local order_by = http.formvalue("order_by") if types[mtype] then args[#args+1] = "-c" args[#args+1] = mtype else http.status(400, "Unsupported type") return end if delim and #delim > 0 then args[#args+1] = "-s%s" % delim end if period and #period > 0 then args[#args+1] = "-t" args[#args+1] = period end if group_by and #group_by > 0 then args[#args+1] = "-g" args[#args+1] = group_by end if order_by and #order_by > 0 then args[#args+1] = "-o" args[#args+1] = order_by end http.prepare_content(types[mtype]) http.header("Content-Disposition", "attachment; filename=\"data.%s\"" % mtype) exec("/usr/sbin/nlbw", args, http.write) end function action_list() local http = require "luci.http" local fd = io.popen("/usr/sbin/nlbw -c list") local periods = { } if fd then while true do local period = fd:read("*l") if not period then break end periods[#periods+1] = period end fd:close() end http.prepare_content("application/json") http.write_json(periods) end function action_ptr(...) local http = require "luci.http" local util = require "luci.util" http.prepare_content("application/json") http.write_json(util.ubus("network.rrdns", "lookup", { addrs = {...}, timeout = 3000 })) end function action_download() local nixio = require "nixio" local http = require "luci.http" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local dir = uci:get_first("nlbwmon", "nlbwmon", "database_directory") or "/var/lib/nlbwmon" if dir and nixio.fs.stat(dir, "type") == "dir" then local n = "nlbwmon-backup-%s-%s.tar.gz" %{ sys.hostname(), os.date("%Y-%m-%d") } http.prepare_content("application/octet-stream") http.header("Content-Disposition", "attachment; filename=\"%s\"" % n) exec("/bin/tar", { "-C", dir, "-c", "-z", ".", "-f", "-" }, http.write) else http.status(500, "Unable to find database directory") end end function action_restore() local nixio = require "nixio" local http = require "luci.http" local i18n = require "luci.i18n" local tpl = require "luci.template" local uci = require "luci.model.uci".cursor() local tmp = "/tmp/nlbw-restore.tar.gz" local dir = uci:get_first("nlbwmon", "nlbwmon", "database_directory") or "/var/lib/nlbwmon" local fp http.setfilehandler( function(meta, chunk, eof) if not fp and meta and meta.name == "archive" then fp = io.open(tmp, "w") end if fp and chunk then fp:write(chunk) end if fp and eof then fp:close() end end) local files = { } local tar = io.popen("/bin/tar -tzf %s" % tmp, "r") if tar then while true do local file = tar:read("*l") if not file then break elseif file:match("^%d%d%d%d%d%d%d%d%.db%.gz$") or file:match("^%./%d%d%d%d%d%d%d%d%.db%.gz$") then files[#files+1] = file end end tar:close() end if #files == 0 then http.status(500, "Internal Server Error") tpl.render("nlbw/backup", { message = i18n.translate("Invalid or empty backup archive") }) return end local output = { } exec("/etc/init.d/nlbwmon", { "stop" }) exec("/bin/mkdir", { "-p", dir }) exec("/bin/tar", { "-C", dir, "-vxzf", tmp, unpack(files) }, function(chunk) output[#output+1] = chunk:match("%S+") end) exec("/bin/rm", { "-f", tmp }) exec("/etc/init.d/nlbwmon", { "start" }) tpl.render("nlbw/backup", { message = i18n.translatef( "The following database files have been restored: %s", table.concat(output, ", ")) }) end function action_commit() local http = require "luci.http" local disp = require "luci.dispatcher" http.redirect(disp.build_url("admin/nlbw/display")) exec("/usr/sbin/nlbw", { "-c", "commit" }) end
luci-app-nlbwmon: fix nil value concat
luci-app-nlbwmon: fix nil value concat Do not concatenate the yet undefined mtime variable to avoid a controller error with backtrace. Fixes: b3642f476 ("luci-app-nlbwmon: add proper file names for json and csv exports.") Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
Lua
apache-2.0
lbthomsen/openwrt-luci,rogerpueyo/luci,Noltari/luci,hnyman/luci,openwrt/luci,tobiaswaldvogel/luci,nmav/luci,openwrt/luci,Noltari/luci,nmav/luci,openwrt/luci,openwrt/luci,lbthomsen/openwrt-luci,Noltari/luci,openwrt/luci,Noltari/luci,nmav/luci,artynet/luci,tobiaswaldvogel/luci,openwrt/luci,tobiaswaldvogel/luci,hnyman/luci,lbthomsen/openwrt-luci,Noltari/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,nmav/luci,rogerpueyo/luci,Noltari/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,hnyman/luci,Noltari/luci,rogerpueyo/luci,artynet/luci,rogerpueyo/luci,artynet/luci,hnyman/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,artynet/luci,openwrt/luci,openwrt/luci,nmav/luci,nmav/luci,nmav/luci,tobiaswaldvogel/luci,nmav/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,lbthomsen/openwrt-luci,hnyman/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,nmav/luci,Noltari/luci,hnyman/luci,rogerpueyo/luci,tobiaswaldvogel/luci,artynet/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,tobiaswaldvogel/luci,artynet/luci,Noltari/luci,artynet/luci,openwrt-es/openwrt-luci,artynet/luci
5158fe6ebbc326f2b5b9b7429423911182f4a79f
world/Plugins/Docker/container.lua
world/Plugins/Docker/container.lua
-- Container object is the representation of a Docker -- container in the Minecraft world -- constant variables CONTAINER_CREATED = 0 CONTAINER_RUNNING = 1 CONTAINER_STOPPED = 2 -- NewContainer returns a Container object, -- representation of a Docker container in -- the Minecraft world function NewContainer() c = Container return c end Container = {displayed = false, x = 0, z = 0, name="",id="",imageRepo="",imageTag="",running=false} -- Container:init sets Container's position function Container:init(x,z) self.x = x self.z = z self.displayed = false end -- Container:setInfos sets Container's id, name, imageRepo, -- image tag and running state function Container:setInfos(id,name,imageRepo,imageTag,running) self.id = id self.name = name self.imageRepo = imageRepo self.imageTag = imageTag self.running = running end -- Container:destroy removes all blocks of the -- container, it won't be visible on the map anymore function Container:destroy(running) for py = GROUND_LEVEL+1, GROUND_LEVEL+4 do for px=self.x-1, self.x+4 do for pz=self.z-1, self.z+5 do digBlock(UpdateQueue,px,py,pz) end end end end -- Container:display displays all Container's blocks -- Blocks will be blue if the container is running, -- orange otherwise. function Container:display(running) metaPrimaryColor = E_META_WOOL_LIGHTBLUE metaSecondaryColor = E_META_WOOL_BLUE if running == false then metaPrimaryColor = E_META_WOOL_ORANGE metaSecondaryColor = E_META_WOOL_RED end self.displayed = true for px=self.x, self.x+3 do for pz=self.z, self.z+4 do setBlock(UpdateQueue,px,GROUND_LEVEL + 1,pz,E_BLOCK_WOOL,metaPrimaryColor) end end for py = GROUND_LEVEL+2, GROUND_LEVEL+3 do setBlock(UpdateQueue,self.x+1,py,self.z,E_BLOCK_WOOL,metaPrimaryColor) -- leave empty space for the door -- setBlock(UpdateQueue,self.x+2,py,self.z,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x,py,self.z,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+3,py,self.z,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x,py,self.z+1,E_BLOCK_WOOL,metaSecondaryColor) setBlock(UpdateQueue,self.x+3,py,self.z+1,E_BLOCK_WOOL,metaSecondaryColor) setBlock(UpdateQueue,self.x,py,self.z+2,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+3,py,self.z+2,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x,py,self.z+3,E_BLOCK_WOOL,metaSecondaryColor) setBlock(UpdateQueue,self.x+3,py,self.z+3,E_BLOCK_WOOL,metaSecondaryColor) setBlock(UpdateQueue,self.x,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+3,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+1,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+2,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor) end -- torch setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+3,E_BLOCK_TORCH,E_META_TORCH_ZP) -- start / stop lever setBlock(UpdateQueue,self.x+1,GROUND_LEVEL + 3,self.z + 2,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_XP) updateSign(UpdateQueue,self.x+1,GROUND_LEVEL + 3,self.z + 2,"","START/STOP","---->","",2) if running then setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1,E_BLOCK_LEVER,1) else setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1,E_BLOCK_LEVER,9) end -- remove button setBlock(UpdateQueue,self.x+2,GROUND_LEVEL + 3,self.z + 2,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_XM) updateSign(UpdateQueue,self.x+2,GROUND_LEVEL + 3,self.z + 2,"","REMOVE","---->","",2) setBlock(UpdateQueue,self.x+2,GROUND_LEVEL+3,self.z+3,E_BLOCK_STONE_BUTTON,E_BLOCK_BUTTON_XM) -- door -- Cuberite bug with Minecraft 1.8 apparently, doors are not displayed correctly -- setBlock(UpdateQueue,self.x+2,GROUND_LEVEL+2,self.z,E_BLOCK_WOODEN_DOOR,E_META_CHEST_FACING_ZM) for px=self.x, self.x+3 do for pz=self.z, self.z+4 do setBlock(UpdateQueue,px,GROUND_LEVEL + 4,pz,E_BLOCK_WOOL,metaPrimaryColor) end end setBlock(UpdateQueue,self.x+3,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM) updateSign(UpdateQueue,self.x+3,GROUND_LEVEL + 2,self.z - 1,string.sub(self.id,1,8),self.name,self.imageRepo,self.imageTag,2) -- Mem sign setBlock(UpdateQueue,self.x,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM) -- CPU sign setBlock(UpdateQueue,self.x+1,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM) end -- Container:updateMemSign updates the mem usage -- value displayed on Container's sign function Container:updateMemSign(s) updateSign(UpdateQueue,self.x,GROUND_LEVEL + 2,self.z - 1,"Mem usage","",s,"") end -- Container:updateCPUSign updates the mem usage -- value displayed on Container's sign function Container:updateCPUSign(s) updateSign(UpdateQueue,self.x+1,GROUND_LEVEL + 2,self.z - 1,"CPU usage","",s,"") end -- Container:addGround creates ground blocks -- necessary to display the container function Container:addGround() if GROUND_MIN_X > self.x - 2 then OLD_GROUND_MIN_X = GROUND_MIN_X GROUND_MIN_X = self.x - 2 for x= GROUND_MIN_X, OLD_GROUND_MIN_X do for z=GROUND_MIN_Z,GROUND_MAX_Z do setBlock(UpdateQueue,x,y,z,E_BLOCK_WOOL,E_META_WOOL_WHITE) end end end end
-- Container object is the representation of a Docker -- container in the Minecraft world -- constant variables CONTAINER_CREATED = 0 CONTAINER_RUNNING = 1 CONTAINER_STOPPED = 2 -- NewContainer returns a Container object, -- representation of a Docker container in -- the Minecraft world function NewContainer() c = { displayed = false, x = 0, z = 0, name="", id="", imageRepo="", imageTag="", running=false, init=Container.init, setInfos=Container.setInfos, destroy=Container.destroy, display=Container.display, updateMemSign=Container.updateMemSign, updateCPUSign=Container.updateCPUSign, addGround=Container.addGround } return c end Container = {displayed = false, x = 0, z = 0, name="",id="",imageRepo="",imageTag="",running=false} -- Container:init sets Container's position function Container:init(x,z) self.x = x self.z = z self.displayed = false end -- Container:setInfos sets Container's id, name, imageRepo, -- image tag and running state function Container:setInfos(id,name,imageRepo,imageTag,running) self.id = id self.name = name self.imageRepo = imageRepo self.imageTag = imageTag self.running = running end -- Container:destroy removes all blocks of the -- container, it won't be visible on the map anymore function Container:destroy(running) for py = GROUND_LEVEL+1, GROUND_LEVEL+4 do for px=self.x-1, self.x+4 do for pz=self.z-1, self.z+5 do digBlock(UpdateQueue,px,py,pz) end end end end -- Container:display displays all Container's blocks -- Blocks will be blue if the container is running, -- orange otherwise. function Container:display(running) metaPrimaryColor = E_META_WOOL_LIGHTBLUE metaSecondaryColor = E_META_WOOL_BLUE if running == false then metaPrimaryColor = E_META_WOOL_ORANGE metaSecondaryColor = E_META_WOOL_RED end self.displayed = true for px=self.x, self.x+3 do for pz=self.z, self.z+4 do setBlock(UpdateQueue,px,GROUND_LEVEL + 1,pz,E_BLOCK_WOOL,metaPrimaryColor) end end for py = GROUND_LEVEL+2, GROUND_LEVEL+3 do setBlock(UpdateQueue,self.x+1,py,self.z,E_BLOCK_WOOL,metaPrimaryColor) -- leave empty space for the door -- setBlock(UpdateQueue,self.x+2,py,self.z,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x,py,self.z,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+3,py,self.z,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x,py,self.z+1,E_BLOCK_WOOL,metaSecondaryColor) setBlock(UpdateQueue,self.x+3,py,self.z+1,E_BLOCK_WOOL,metaSecondaryColor) setBlock(UpdateQueue,self.x,py,self.z+2,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+3,py,self.z+2,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x,py,self.z+3,E_BLOCK_WOOL,metaSecondaryColor) setBlock(UpdateQueue,self.x+3,py,self.z+3,E_BLOCK_WOOL,metaSecondaryColor) setBlock(UpdateQueue,self.x,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+3,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+1,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor) setBlock(UpdateQueue,self.x+2,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor) end -- torch setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+3,E_BLOCK_TORCH,E_META_TORCH_ZP) -- start / stop lever setBlock(UpdateQueue,self.x+1,GROUND_LEVEL + 3,self.z + 2,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_XP) updateSign(UpdateQueue,self.x+1,GROUND_LEVEL + 3,self.z + 2,"","START/STOP","---->","",2) if running then setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1,E_BLOCK_LEVER,1) else setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1,E_BLOCK_LEVER,9) end -- remove button setBlock(UpdateQueue,self.x+2,GROUND_LEVEL + 3,self.z + 2,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_XM) updateSign(UpdateQueue,self.x+2,GROUND_LEVEL + 3,self.z + 2,"","REMOVE","---->","",2) setBlock(UpdateQueue,self.x+2,GROUND_LEVEL+3,self.z+3,E_BLOCK_STONE_BUTTON,E_BLOCK_BUTTON_XM) -- door -- Cuberite bug with Minecraft 1.8 apparently, doors are not displayed correctly -- setBlock(UpdateQueue,self.x+2,GROUND_LEVEL+2,self.z,E_BLOCK_WOODEN_DOOR,E_META_CHEST_FACING_ZM) for px=self.x, self.x+3 do for pz=self.z, self.z+4 do setBlock(UpdateQueue,px,GROUND_LEVEL + 4,pz,E_BLOCK_WOOL,metaPrimaryColor) end end setBlock(UpdateQueue,self.x+3,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM) updateSign(UpdateQueue,self.x+3,GROUND_LEVEL + 2,self.z - 1,string.sub(self.id,1,8),self.name,self.imageRepo,self.imageTag,2) -- Mem sign setBlock(UpdateQueue,self.x,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM) -- CPU sign setBlock(UpdateQueue,self.x+1,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM) end -- Container:updateMemSign updates the mem usage -- value displayed on Container's sign function Container:updateMemSign(s) updateSign(UpdateQueue,self.x,GROUND_LEVEL + 2,self.z - 1,"Mem usage","",s,"") end -- Container:updateCPUSign updates the mem usage -- value displayed on Container's sign function Container:updateCPUSign(s) updateSign(UpdateQueue,self.x+1,GROUND_LEVEL + 2,self.z - 1,"CPU usage","",s,"") end -- Container:addGround creates ground blocks -- necessary to display the container function Container:addGround() if GROUND_MIN_X > self.x - 2 then OLD_GROUND_MIN_X = GROUND_MIN_X GROUND_MIN_X = self.x - 2 for x= GROUND_MIN_X, OLD_GROUND_MIN_X do for z=GROUND_MIN_Z,GROUND_MAX_Z do setBlock(UpdateQueue,x,y,z,E_BLOCK_WOOL,E_META_WOOL_WHITE) end end end end
fix NewContainer so it creates multiple instances
fix NewContainer so it creates multiple instances
Lua
apache-2.0
docker/dockercraft,nyasukun/openstackcraft,stevesloka/kubecraft,gdevillele/dockercraft,stevesloka/kubecraft,nyasukun/openstackcraft,stevesloka/kubecraft,johnmccabe/dockercraft,gdevillele/dockercraft,nyasukun/openstackcraft,johnmccabe/dockercraft,gdevillele/dockercraft,docker/dockercraft,johnmccabe/dockercraft
3983b0e66dad160b315fb6ad33397bdd798d72c9
access.lua
access.lua
-- import requirements -- allow either ccjsonjson, or th-LuaJSON local has_cjson, jsonmod = pcall(require, "cjson") if not has_cjson then jsonmod = require "json" end -- Ubuntu broke the install. Puts the source in /usr/share/lua/5.1/https.lua, -- but since the source defines itself as the module "ssl.https", after we -- load the source, we need to grab the actual thing. Building from source -- wasn't practical. -- TODO: make this more generic but still work with Ubuntu require "https" -- local https = require "ssl.https" -- /usr/share/lua/5.1/https.lua local ltn12 = require("ltn12") -- setup some app-level vars local client_id = ngx.var.ngo_client_id local client_secret = ngx.var.ngo_client_secret local domain = ngx.var.ngo_domain local cb_scheme = ngx.var.ngo_callback_scheme or ngx.var.scheme local cb_server_name = ngx.var.ngo_callback_host or ngx.var.server_name local cb_uri = ngx.var.ngo_callback_uri or "/_oauth" local cb_url = cb_scheme.."://"..cb_server_name..cb_uri local signout_uri = ngx.var.ngo_signout_uri or "/_signout" local debug = ngx.var.ngo_debug local whitelist = ngx.var.ngo_whitelist local blacklist = ngx.var.ngo_blacklist local secure_cookies = ngx.var.ngo_secure_cookies local uri_args = ngx.req.get_uri_args() -- See https://developers.google.com/accounts/docs/OAuth2WebServer if ngx.var.uri == signout_uri then ngx.header["Set-Cookie"] = "AccessToken=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT" return ngx.redirect(ngx.var.scheme.."://"..ngx.var.server_name) end if not ngx.var.cookie_AccessToken then -- If no access token and this isn't the callback URI, redirect to oauth if ngx.var.uri ~= cb_uri then -- Redirect to the /oauth endpoint, request access to ALL scopes return ngx.redirect("https://accounts.google.com/o/oauth2/auth?client_id="..client_id.."&scope=email&response_type=code&redirect_uri="..ngx.escape_uri(cb_url).."&state="..ngx.escape_uri(ngx.var.uri).."&login_hint="..ngx.escape_uri(domain)) end -- Fetch teh authorization code from the parameters local auth_code = uri_args["code"] local auth_error = uri_args["error"] if auth_error then ngx.log(ngx.ERR, "received "..auth_error.." from https://accounts.google.com/o/oauth2/auth") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end if debug then ngx.log(ngx.ERR, "DEBUG: fetching token for auth code "..auth_code) end -- TODO: Switch to NBIO sockets -- If I get around to working luasec, this says how to pass a function which -- can generate a socket, needed for NBIO using nginx cosocket -- http://lua-users.org/lists/lua-l/2009-02/msg00251.html local res, code, headers, status = https.request( "https://accounts.google.com/o/oauth2/token", "code="..ngx.escape_uri(auth_code).."&client_id="..client_id.."&client_secret="..client_secret.."&redirect_uri="..ngx.escape_uri(cb_url).."&grant_type=authorization_code" ) if debug then ngx.log(ngx.ERR, "DEBUG: token response "..res..code..status) end if code~=200 then ngx.log(ngx.ERR, "received "..code.." from https://accounts.google.com/o/oauth2/token") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end -- use version 1 cookies so we don't have to encode. MSIE-old beware local json = jsonmod.decode( res ) local access_token = json["access_token"] local cookie_tail = ";version=1;path=/;Max-Age="..json["expires_in"] if secure_cookies then cookie_tail = cookie_tail..";secure" end local send_headers = { Authorization = "Bearer "..access_token, } local result_table = {} local res2, code2, headers2, status2 = https.request({ url = "https://www.googleapis.com/oauth2/v2/userinfo", method = "GET", headers = send_headers, sink = ltn12.sink.table(result_table), }) if code2~=200 then ngx.log(ngx.ERR, "received "..code2.." from https://www.googleapis.com/oauth2/v2/userinfo") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end if debug then ngx.log(ngx.ERR, "DEBUG: userinfo response "..res2..code2..status2..table.concat(result_table)) end json = jsonmod.decode( table.concat(result_table) ) local name = json["name"] local email = json["email"] local picture = json["picture"] -- If no whitelist or blacklist, match on domain if not whitelist and not blacklist then if not string.find(email, "@"..domain) then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." not in "..domain) end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end if whitelist then if not string.find(whitelist, email) then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." not in whitelist") end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end if blacklist then if string.find(blacklist, email) then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." in blacklist") end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end ngx.header["Set-Cookie"] = { "AccessToken="..access_token..cookie_tail, "Name="..ngx.escape_uri(name)..cookie_tail, "Email="..ngx.escape_uri(email)..cookie_tail, "Picture="..ngx.escape_uri(picture)..cookie_tail } -- Redirect if debug then ngx.log(ngx.ERR, "DEBUG: authorized "..json["email"]..", redirecting to "..uri_args["state"]) end return ngx.redirect(uri_args["state"]) end
-- import requirements -- allow either ccjsonjson, or th-LuaJSON local has_cjson, jsonmod = pcall(require, "cjson") if not has_cjson then jsonmod = require "json" end -- Ubuntu broke the install. Puts the source in /usr/share/lua/5.1/https.lua, -- but since the source defines itself as the module "ssl.https", after we -- load the source, we need to grab the actual thing. pcall(require,"https") local https = require "ssl.https" -- /usr/share/lua/5.1/https.lua local ltn12 = require("ltn12") -- setup some app-level vars local client_id = ngx.var.ngo_client_id local client_secret = ngx.var.ngo_client_secret local domain = ngx.var.ngo_domain local cb_scheme = ngx.var.ngo_callback_scheme or ngx.var.scheme local cb_server_name = ngx.var.ngo_callback_host or ngx.var.server_name local cb_uri = ngx.var.ngo_callback_uri or "/_oauth" local cb_url = cb_scheme.."://"..cb_server_name..cb_uri local signout_uri = ngx.var.ngo_signout_uri or "/_signout" local debug = ngx.var.ngo_debug local whitelist = ngx.var.ngo_whitelist local blacklist = ngx.var.ngo_blacklist local secure_cookies = ngx.var.ngo_secure_cookies local uri_args = ngx.req.get_uri_args() -- See https://developers.google.com/accounts/docs/OAuth2WebServer if ngx.var.uri == signout_uri then ngx.header["Set-Cookie"] = "AccessToken=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT" return ngx.redirect(ngx.var.scheme.."://"..ngx.var.server_name) end if not ngx.var.cookie_AccessToken then -- If no access token and this isn't the callback URI, redirect to oauth if ngx.var.uri ~= cb_uri then -- Redirect to the /oauth endpoint, request access to ALL scopes return ngx.redirect("https://accounts.google.com/o/oauth2/auth?client_id="..client_id.."&scope=email&response_type=code&redirect_uri="..ngx.escape_uri(cb_url).."&state="..ngx.escape_uri(ngx.var.uri).."&login_hint="..ngx.escape_uri(domain)) end -- Fetch teh authorization code from the parameters local auth_code = uri_args["code"] local auth_error = uri_args["error"] if auth_error then ngx.log(ngx.ERR, "received "..auth_error.." from https://accounts.google.com/o/oauth2/auth") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end if debug then ngx.log(ngx.ERR, "DEBUG: fetching token for auth code "..auth_code) end -- TODO: Switch to NBIO sockets -- If I get around to working luasec, this says how to pass a function which -- can generate a socket, needed for NBIO using nginx cosocket -- http://lua-users.org/lists/lua-l/2009-02/msg00251.html local res, code, headers, status = https.request( "https://accounts.google.com/o/oauth2/token", "code="..ngx.escape_uri(auth_code).."&client_id="..client_id.."&client_secret="..client_secret.."&redirect_uri="..ngx.escape_uri(cb_url).."&grant_type=authorization_code" ) if debug then ngx.log(ngx.ERR, "DEBUG: token response "..res..code..status) end if code~=200 then ngx.log(ngx.ERR, "received "..code.." from https://accounts.google.com/o/oauth2/token") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end -- use version 1 cookies so we don't have to encode. MSIE-old beware local json = jsonmod.decode( res ) local access_token = json["access_token"] local cookie_tail = ";version=1;path=/;Max-Age="..json["expires_in"] if secure_cookies then cookie_tail = cookie_tail..";secure" end local send_headers = { Authorization = "Bearer "..access_token, } local result_table = {} local res2, code2, headers2, status2 = https.request({ url = "https://www.googleapis.com/oauth2/v2/userinfo", method = "GET", headers = send_headers, sink = ltn12.sink.table(result_table), }) if code2~=200 then ngx.log(ngx.ERR, "received "..code2.." from https://www.googleapis.com/oauth2/v2/userinfo") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end if debug then ngx.log(ngx.ERR, "DEBUG: userinfo response "..res2..code2..status2..table.concat(result_table)) end json = jsonmod.decode( table.concat(result_table) ) local name = json["name"] local email = json["email"] local picture = json["picture"] -- If no whitelist or blacklist, match on domain if not whitelist and not blacklist then if not string.find(email, "@"..domain) then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." not in "..domain) end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end if whitelist then if not string.find(whitelist, email) then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." not in whitelist") end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end if blacklist then if string.find(blacklist, email) then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." in blacklist") end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end ngx.header["Set-Cookie"] = { "AccessToken="..access_token..cookie_tail, "Name="..ngx.escape_uri(name)..cookie_tail, "Email="..ngx.escape_uri(email)..cookie_tail, "Picture="..ngx.escape_uri(picture)..cookie_tail } -- Redirect if debug then ngx.log(ngx.ERR, "DEBUG: authorized "..json["email"]..", redirecting to "..uri_args["state"]) end return ngx.redirect(uri_args["state"]) end
Fixed https module abiguity in Ubuntu
Fixed https module abiguity in Ubuntu
Lua
mit
milliwayslabs/nginx-google-oauth,ivan1986/nginx-google-oauth,milliwayslabs/nginx-google-oauth,agoragames/nginx-google-oauth,agoragames/nginx-google-oauth,ivan1986/nginx-google-oauth
57a6025da9ad3b0478bbf9d4a9fad34eed5381a0
mod_mam/rsm.lib.lua
mod_mam/rsm.lib.lua
local stanza = require"util.stanza".stanza; local tostring, tonumber = tostring, tonumber; local type = type; local pairs = pairs; local xmlns_rsm = 'http://jabber.org/protocol/rsm'; local element_parsers; do local function xs_int(st) return tonumber((st:get_text())); end local function xs_string(st) return st:get_text(); end element_parsers = { after = xs_string; before = function(st) return st:get_text() or true; end; max = xs_int; index = xs_int; first = function(st) return { index = tonumber(st.attr.index); st:get_text() }; end; last = xs_string; count = xs_int; } end local element_generators = setmetatable({ first = function(st, data) if type(data) == "table" then st:tag("first", { index = data.index }):text(data[1]):up(); else st:tag("first"):text(tostring(data)):up(); end end; }, { __index = function(_, name) return function(st, data) st:tag(name):text(tostring(data)):up(); end end; }); local function parse(stanza) local rs = {}; for tag in stanza:childtags() do local name = tag.name; local parser = name and element_parsers[name]; if parser then rs[name] = parser(tag); end end return rs; end local function generate(t) local st = stanza("set", { xmlns = xmlns_rsm }); for k,v in pairs(t) do if element_parsers[k] then element_generators[k](st, v); end end return st; end local function get(st) local set = st:get_child("set", xmlns_rsm); if set and #set.tags > 0 then return parse(set); end end return { parse = parse, generate = generate, get = get };
local stanza = require"util.stanza".stanza; local tostring, tonumber = tostring, tonumber; local type = type; local pairs = pairs; local xmlns_rsm = 'http://jabber.org/protocol/rsm'; local element_parsers; do local function xs_int(st) return tonumber((st:get_text())); end local function xs_string(st) return st:get_text(); end element_parsers = { after = xs_string; before = function(st) return st:get_text() or true; end; max = xs_int; index = xs_int; first = function(st) return { index = tonumber(st.attr.index); st:get_text() }; end; last = xs_string; count = xs_int; } end local element_generators = setmetatable({ first = function(st, data) if type(data) == "table" then st:tag("first", { index = data.index }):text(data[1]):up(); else st:tag("first"):text(tostring(data)):up(); end end; before = function(st, data) if data == true then st:tag("before"):up(); else st:tag("before"):text(tostring(data)):up(); end end }, { __index = function(_, name) return function(st, data) st:tag(name):text(tostring(data)):up(); end end; }); local function parse(stanza) local rs = {}; for tag in stanza:childtags() do local name = tag.name; local parser = name and element_parsers[name]; if parser then rs[name] = parser(tag); end end return rs; end local function generate(t) local st = stanza("set", { xmlns = xmlns_rsm }); for k,v in pairs(t) do if element_parsers[k] then element_generators[k](st, v); end end return st; end local function get(st) local set = st:get_child("set", xmlns_rsm); if set and #set.tags > 0 then return parse(set); end end return { parse = parse, generate = generate, get = get };
mod_mam/rsm.lib: Fix serialization of before = true
mod_mam/rsm.lib: Fix serialization of before = true
Lua
mit
vfedoroff/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,crunchuser/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,mmusial/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,prosody-modules/import,either1/prosody-modules,Craige/prosody-modules,softer/prosody-modules,prosody-modules/import,either1/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,Craige/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,Craige/prosody-modules,heysion/prosody-modules,cryptotoad/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,olax/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,softer/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,heysion/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,joewalker/prosody-modules,vince06fr/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,amenophis1er/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,BurmistrovJ/prosody-modules
a037d9438357a30e443b5b6ee84abe936d5255f1
libs/core/luasrc/model/network.lua
libs/core/luasrc/model/network.lua
--[[ LuCI - Network model Copyright 2009 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 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 type, pairs, ipairs, table = type, pairs, ipairs, table local lmo = require "lmo" local nxo = require "nixio" local iwi = require "iwinfo" local ipc = require "luci.ip" local utl = require "luci.util" local uct = require "luci.model.uci.bind" module "luci.model.network" local ub = uct.bind("network") local ifs, brs function init(cursor) if cursor then cursor:unload("network") cursor:load("network") ub:init(cursor) ifs = { } brs = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") if not _M:ignore_interface(name) then ifs[name] = ifs[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if i.family == "packet" then ifs[name].flags = i.flags ifs[name].stats = i.data ifs[name].macaddr = i.addr elseif i.family == "inet" then ifs[name].ipaddrs[#ifs[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then ifs[name].ip6addrs[#ifs[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { ifs[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end brs[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = ifs[r[2]] b.ifnames[#b.ifnames].bridge = b end end end end end function add_network(self, n, options) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not self:get_network(n) then if ub.uci:section("network", "interface", n, options) then return network(n) end end end function get_network(self, n) if n and ub.uci:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } ub.uci:foreach("network", "interface", function(s) nets[#nets+1] = network(s['.name']) end) return nets end function del_network(self, n) local r = ub.uci:delete("network", n) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = ub.uci:section("network", "interface", new, ub.uci:get_all("network", old)) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) end end return r or false end function get_interface(self, i) return ifs[i] and interface(i) end function get_interfaces(self) local ifaces = { } local iface for iface, _ in pairs(ifs) do ifaces[#ifaces+1] = interface(iface) end return ifaces end function ignore_interface(self, x) return (x:match("^wmaster%d") or x:match("^wifi%d") or x:match("^hwsim%d") or x:match("^imq%d") or x == "lo") end network = ub:section("interface") network:property("device") network:property("ifname") network:property("proto") network:property("type") function network.name(self) return self.sid end function network.is_bridge(self) return (self:type() == "bridge") end function network.add_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:ifname() end if ifs[ifname] then self:ifname(ub:list((self:ifname() or ''), ifname)) end end function network.del_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:ifname() end self:ifname(ub:list((self:ifname() or ''), nil, ifname)) end function network.get_interfaces(self) local ifaces = { } local iface for _, iface in ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) do iface = iface:match("[^:]+") if ifs[iface] then ifaces[#ifaces+1] = interface(iface) end end return ifaces end function contains_interface(self, iface) local i local ifaces = ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) if type(iface) ~= "string" then iface = iface:ifname() end for _, i in ipairs(ifaces) do if i == iface then return true end end return false end interface = utl.class() function interface.__init__(self, ifname) if ifs[ifname] then self.ifname = ifname self.dev = ifs[ifname] self.br = brs[ifname] end end function interface.name(self) return self.ifname end function interface.type(self) if iwi.type(self.ifname) and iwi.type(self.ifname) ~= "dummy" then return "wifi" elseif brs[self.ifname] then return "bridge" elseif self.ifname:match("%.") then return "switch" else return "ethernet" end end function interface.ports(self) if self.br then local iface local ifaces = { } for _, iface in ipairs(self.br.ifnames) do ifaces[#ifaces+1] = interface(iface) end return ifaces end end function interface.is_up(self) return self.dev.flags and self.dev.flags.up end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.get_network(self) local net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) then return net end end end
--[[ LuCI - Network model Copyright 2009 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 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 type, pairs, ipairs, table, i18n = type, pairs, ipairs, table, luci.i18n local lmo = require "lmo" local nxo = require "nixio" local iwi = require "iwinfo" local ipc = require "luci.ip" local utl = require "luci.util" local uct = require "luci.model.uci.bind" module "luci.model.network" local ub = uct.bind("network") local ifs, brs function init(cursor) if cursor then cursor:unload("network") cursor:load("network") ub:init(cursor) ifs = { } brs = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") if not _M:ignore_interface(name) then ifs[name] = ifs[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if i.family == "packet" then ifs[name].flags = i.flags ifs[name].stats = i.data ifs[name].macaddr = i.addr elseif i.family == "inet" then ifs[name].ipaddrs[#ifs[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then ifs[name].ip6addrs[#ifs[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { ifs[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end brs[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = ifs[r[2]] b.ifnames[#b.ifnames].bridge = b end end end end end function add_network(self, n, options) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not self:get_network(n) then if ub.uci:section("network", "interface", n, options) then return network(n) end end end function get_network(self, n) if n and ub.uci:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } ub.uci:foreach("network", "interface", function(s) nets[#nets+1] = network(s['.name']) end) return nets end function del_network(self, n) local r = ub.uci:delete("network", n) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = ub.uci:section("network", "interface", new, ub.uci:get_all("network", old)) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) end end return r or false end function get_interface(self, i) return ifs[i] and interface(i) end function get_interfaces(self) local ifaces = { } local iface for iface, _ in pairs(ifs) do ifaces[#ifaces+1] = interface(iface) end return ifaces end function ignore_interface(self, x) return (x:match("^wmaster%d") or x:match("^wifi%d") or x:match("^hwsim%d") or x:match("^imq%d") or x == "lo") end network = ub:section("interface") network:property("device") network:property("ifname") network:property("proto") network:property("type") function network.name(self) return self.sid end function network.is_bridge(self) return (self:type() == "bridge") end function network.add_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:name() end if ifs[ifname] then self:ifname(ub:list((self:ifname() or ''), ifname)) end end function network.del_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:name() end self:ifname(ub:list((self:ifname() or ''), nil, ifname)) end function network.get_interfaces(self) local ifaces = { } local iface for _, iface in ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) do iface = iface:match("[^:]+") if ifs[iface] then ifaces[#ifaces+1] = interface(iface) end end return ifaces end function network.contains_interface(self, iface) local i local ifaces = ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) if type(iface) ~= "string" then iface = iface:name() end for _, i in ipairs(ifaces) do if i == iface then return true end end return false end interface = utl.class() function interface.__init__(self, ifname) if ifs[ifname] then self.ifname = ifname self.dev = ifs[ifname] self.br = brs[ifname] end end function interface.name(self) return self.ifname end function interface.type(self) if iwi.type(self.ifname) and iwi.type(self.ifname) ~= "dummy" then return "wifi" elseif brs[self.ifname] then return "bridge" elseif self.ifname:match("%.") then return "switch" else return "ethernet" end end function interface.get_type_i18n(self) local x = self:type() if x == "wifi" then return i18n.translate("a_s_if_wifidev", "Wireless Adapter") elseif x == "bridge" then return i18n.translate("a_s_if_bridge", "Bridge") elseif x == "switch" then return i18n.translate("a_s_if_ethswitch", "Ethernet Switch") else return i18n.translate("a_s_if_ethdev", "Ethernet Adapter") end end function interface.ports(self) if self.br then local iface local ifaces = { } for _, iface in ipairs(self.br.ifnames) do ifaces[#ifaces+1] = interface(iface) end return ifaces end end function interface.is_up(self) return self.dev.flags and self.dev.flags.up end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.get_network(self) local net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) then return net end end end
libs/core: luci.model.network: implement contains_inteface(), fix bugs
libs/core: luci.model.network: implement contains_inteface(), fix bugs
Lua
apache-2.0
zhaoxx063/luci,tobiaswaldvogel/luci,nmav/luci,slayerrensky/luci,chris5560/openwrt-luci,dwmw2/luci,lcf258/openwrtcn,jorgifumi/luci,ff94315/luci-1,opentechinstitute/luci,florian-shellfire/luci,harveyhu2012/luci,cshore/luci,mumuqz/luci,daofeng2015/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,oneru/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,openwrt/luci,LuttyYang/luci,lbthomsen/openwrt-luci,nwf/openwrt-luci,forward619/luci,harveyhu2012/luci,ff94315/luci-1,bittorf/luci,david-xiao/luci,urueedi/luci,sujeet14108/luci,schidler/ionic-luci,thesabbir/luci,ollie27/openwrt_luci,981213/luci-1,urueedi/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,jorgifumi/luci,MinFu/luci,ollie27/openwrt_luci,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,jorgifumi/luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,nwf/openwrt-luci,palmettos/test,teslamint/luci,bright-things/ionic-luci,openwrt/luci,harveyhu2012/luci,artynet/luci,jorgifumi/luci,dwmw2/luci,opentechinstitute/luci,schidler/ionic-luci,oneru/luci,shangjiyu/luci-with-extra,taiha/luci,kuoruan/lede-luci,RuiChen1113/luci,cshore/luci,oyido/luci,daofeng2015/luci,keyidadi/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,Kyklas/luci-proto-hso,tcatm/luci,jchuang1977/luci-1,fkooman/luci,jchuang1977/luci-1,dwmw2/luci,teslamint/luci,palmettos/test,palmettos/test,forward619/luci,opentechinstitute/luci,jorgifumi/luci,MinFu/luci,thess/OpenWrt-luci,mumuqz/luci,lcf258/openwrtcn,obsy/luci,thesabbir/luci,forward619/luci,obsy/luci,Hostle/luci,deepak78/new-luci,david-xiao/luci,bright-things/ionic-luci,Noltari/luci,dwmw2/luci,NeoRaider/luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,male-puppies/luci,wongsyrone/luci-1,teslamint/luci,kuoruan/luci,RedSnake64/openwrt-luci-packages,tobiaswaldvogel/luci,bright-things/ionic-luci,nwf/openwrt-luci,Wedmer/luci,oyido/luci,cshore-firmware/openwrt-luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,teslamint/luci,kuoruan/luci,Noltari/luci,RedSnake64/openwrt-luci-packages,artynet/luci,dwmw2/luci,palmettos/test,schidler/ionic-luci,taiha/luci,LuttyYang/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,RuiChen1113/luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,fkooman/luci,bittorf/luci,wongsyrone/luci-1,sujeet14108/luci,aircross/OpenWrt-Firefly-LuCI,aa65535/luci,cshore-firmware/openwrt-luci,Noltari/luci,RedSnake64/openwrt-luci-packages,Hostle/luci,NeoRaider/luci,bright-things/ionic-luci,maxrio/luci981213,wongsyrone/luci-1,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,ReclaimYourPrivacy/cloak-luci,artynet/luci,RuiChen1113/luci,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,MinFu/luci,david-xiao/luci,nwf/openwrt-luci,nmav/luci,obsy/luci,mumuqz/luci,openwrt/luci,joaofvieira/luci,Noltari/luci,oyido/luci,kuoruan/lede-luci,obsy/luci,oneru/luci,kuoruan/luci,Sakura-Winkey/LuCI,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,Kyklas/luci-proto-hso,urueedi/luci,Kyklas/luci-proto-hso,jlopenwrtluci/luci,Wedmer/luci,urueedi/luci,wongsyrone/luci-1,deepak78/new-luci,artynet/luci,ollie27/openwrt_luci,jlopenwrtluci/luci,Hostle/luci,lbthomsen/openwrt-luci,mumuqz/luci,Noltari/luci,joaofvieira/luci,openwrt/luci,bittorf/luci,daofeng2015/luci,981213/luci-1,florian-shellfire/luci,aa65535/luci,RuiChen1113/luci,slayerrensky/luci,openwrt/luci,jorgifumi/luci,jlopenwrtluci/luci,Wedmer/luci,schidler/ionic-luci,LuttyYang/luci,shangjiyu/luci-with-extra,taiha/luci,tcatm/luci,maxrio/luci981213,daofeng2015/luci,mumuqz/luci,ff94315/luci-1,kuoruan/lede-luci,Sakura-Winkey/LuCI,urueedi/luci,Kyklas/luci-proto-hso,Noltari/luci,ReclaimYourPrivacy/cloak-luci,bright-things/ionic-luci,NeoRaider/luci,RuiChen1113/luci,sujeet14108/luci,RuiChen1113/luci,ollie27/openwrt_luci,joaofvieira/luci,florian-shellfire/luci,fkooman/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,taiha/luci,daofeng2015/luci,981213/luci-1,marcel-sch/luci,daofeng2015/luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,aa65535/luci,jchuang1977/luci-1,palmettos/cnLuCI,forward619/luci,tobiaswaldvogel/luci,teslamint/luci,ReclaimYourPrivacy/cloak-luci,cshore/luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,taiha/luci,zhaoxx063/luci,oneru/luci,hnyman/luci,Hostle/openwrt-luci-multi-user,tcatm/luci,teslamint/luci,artynet/luci,rogerpueyo/luci,obsy/luci,MinFu/luci,fkooman/luci,cappiewu/luci,ff94315/luci-1,981213/luci-1,wongsyrone/luci-1,Noltari/luci,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,nmav/luci,tcatm/luci,florian-shellfire/luci,cshore/luci,Hostle/luci,nwf/openwrt-luci,keyidadi/luci,kuoruan/luci,hnyman/luci,oyido/luci,LuttyYang/luci,florian-shellfire/luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,jchuang1977/luci-1,Kyklas/luci-proto-hso,palmettos/cnLuCI,jchuang1977/luci-1,cshore-firmware/openwrt-luci,cappiewu/luci,openwrt-es/openwrt-luci,remakeelectric/luci,david-xiao/luci,florian-shellfire/luci,cappiewu/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,mumuqz/luci,fkooman/luci,marcel-sch/luci,openwrt-es/openwrt-luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,oyido/luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,bittorf/luci,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,nmav/luci,dismantl/luci-0.12,MinFu/luci,wongsyrone/luci-1,ollie27/openwrt_luci,cappiewu/luci,slayerrensky/luci,male-puppies/luci,cappiewu/luci,Hostle/luci,aa65535/luci,NeoRaider/luci,keyidadi/luci,kuoruan/lede-luci,forward619/luci,hnyman/luci,nmav/luci,obsy/luci,teslamint/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,nmav/luci,maxrio/luci981213,obsy/luci,wongsyrone/luci-1,slayerrensky/luci,tcatm/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,palmettos/cnLuCI,palmettos/cnLuCI,LuttyYang/luci,remakeelectric/luci,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,ollie27/openwrt_luci,slayerrensky/luci,openwrt-es/openwrt-luci,opentechinstitute/luci,shangjiyu/luci-with-extra,oneru/luci,cappiewu/luci,Hostle/luci,cshore-firmware/openwrt-luci,harveyhu2012/luci,aa65535/luci,nwf/openwrt-luci,chris5560/openwrt-luci,Sakura-Winkey/LuCI,ollie27/openwrt_luci,schidler/ionic-luci,marcel-sch/luci,obsy/luci,chris5560/openwrt-luci,florian-shellfire/luci,oneru/luci,cappiewu/luci,zhaoxx063/luci,lcf258/openwrtcn,artynet/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,jorgifumi/luci,hnyman/luci,david-xiao/luci,oneru/luci,981213/luci-1,keyidadi/luci,wongsyrone/luci-1,dismantl/luci-0.12,shangjiyu/luci-with-extra,oyido/luci,david-xiao/luci,daofeng2015/luci,keyidadi/luci,dismantl/luci-0.12,Kyklas/luci-proto-hso,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,zhaoxx063/luci,sujeet14108/luci,openwrt-es/openwrt-luci,remakeelectric/luci,jlopenwrtluci/luci,schidler/ionic-luci,aa65535/luci,lcf258/openwrtcn,rogerpueyo/luci,maxrio/luci981213,kuoruan/lede-luci,jchuang1977/luci-1,forward619/luci,remakeelectric/luci,RuiChen1113/luci,slayerrensky/luci,cshore/luci,981213/luci-1,palmettos/cnLuCI,urueedi/luci,thess/OpenWrt-luci,slayerrensky/luci,remakeelectric/luci,harveyhu2012/luci,male-puppies/luci,nmav/luci,kuoruan/luci,zhaoxx063/luci,sujeet14108/luci,zhaoxx063/luci,slayerrensky/luci,marcel-sch/luci,marcel-sch/luci,thesabbir/luci,joaofvieira/luci,rogerpueyo/luci,joaofvieira/luci,remakeelectric/luci,taiha/luci,deepak78/new-luci,palmettos/test,Wedmer/luci,bright-things/ionic-luci,marcel-sch/luci,artynet/luci,NeoRaider/luci,lcf258/openwrtcn,harveyhu2012/luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,palmettos/cnLuCI,taiha/luci,joaofvieira/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/luci,LuttyYang/luci,schidler/ionic-luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,maxrio/luci981213,dismantl/luci-0.12,fkooman/luci,LuttyYang/luci,opentechinstitute/luci,forward619/luci,jlopenwrtluci/luci,bittorf/luci,opentechinstitute/luci,ff94315/luci-1,male-puppies/luci,mumuqz/luci,dwmw2/luci,Noltari/luci,taiha/luci,ff94315/luci-1,Hostle/openwrt-luci-multi-user,aa65535/luci,NeoRaider/luci,dwmw2/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,urueedi/luci,joaofvieira/luci,oyido/luci,RuiChen1113/luci,david-xiao/luci,deepak78/new-luci,Wedmer/luci,Wedmer/luci,dwmw2/luci,MinFu/luci,Hostle/luci,kuoruan/lede-luci,fkooman/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,hnyman/luci,lcf258/openwrtcn,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,maxrio/luci981213,artynet/luci,thess/OpenWrt-luci,thesabbir/luci,ff94315/luci-1,joaofvieira/luci,rogerpueyo/luci,mumuqz/luci,Sakura-Winkey/LuCI,deepak78/new-luci,jlopenwrtluci/luci,jchuang1977/luci-1,bittorf/luci,chris5560/openwrt-luci,kuoruan/luci,sujeet14108/luci,nmav/luci,NeoRaider/luci,male-puppies/luci,keyidadi/luci,cshore-firmware/openwrt-luci,openwrt/luci,cshore/luci,bright-things/ionic-luci,remakeelectric/luci,palmettos/cnLuCI,Hostle/luci,aa65535/luci,openwrt/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,male-puppies/luci,thess/OpenWrt-luci,nmav/luci,981213/luci-1,palmettos/cnLuCI,thesabbir/luci,rogerpueyo/luci,bittorf/luci,florian-shellfire/luci,tobiaswaldvogel/luci,MinFu/luci,thesabbir/luci,fkooman/luci,marcel-sch/luci,opentechinstitute/luci,forward619/luci,Wedmer/luci,dismantl/luci-0.12,male-puppies/luci,schidler/ionic-luci,maxrio/luci981213,male-puppies/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,nwf/openwrt-luci,jorgifumi/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,marcel-sch/luci,Sakura-Winkey/LuCI,openwrt/luci,oneru/luci,david-xiao/luci,remakeelectric/luci,Sakura-Winkey/LuCI,chris5560/openwrt-luci,oyido/luci,thesabbir/luci,sujeet14108/luci,urueedi/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,artynet/luci,lbthomsen/openwrt-luci,ff94315/luci-1,Hostle/openwrt-luci-multi-user,MinFu/luci,ReclaimYourPrivacy/cloak-luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,daofeng2015/luci,hnyman/luci,maxrio/luci981213
4eda42fddf30ab947dcf91a478bfe03a843ab666
tests/test_gmake_cpp.lua
tests/test_gmake_cpp.lua
-- -- tests/test_gmake_cpp.lua -- Automated test suite for GNU Make C/C++ project generation. -- Copyright (c) 2009 Jason Perkins and the Premake project -- T.gmake_cpp = { } -- -- Configure a solution for testing -- local sln, prj function T.gmake_cpp.setup() _ACTION = "gmake" _OPTIONS.os = "linux" sln = solution "MySolution" configurations { "Debug", "Release" } platforms { "native" } prj = project "MyProject" language "C++" kind "ConsoleApp" end local function prepare() io.capture() premake.buildconfigs() end -- -- Test the header -- function T.gmake_cpp.BasicHeader() prepare() premake.gmake_cpp_header(prj, premake.gcc, sln.platforms) test.capture [[ # GNU Make project makefile autogenerated by Premake ifndef config config=debug endif ifndef verbose SILENT = @ endif ifndef CC CC = gcc endif ifndef CXX CXX = g++ endif ifndef AR AR = ar endif ]] end -- -- Test configuration blocks -- function T.gmake_cpp.BasicCfgBlock() prepare() local cfg = premake.getconfig(prj, "Debug") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debug) OBJDIR = obj/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) CXXFLAGS += $(CFLAGS) LDFLAGS += -s LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.BasicCfgBlockWithPlatformCc() platforms { "ps3" } prepare() local cfg = premake.getconfig(prj, "Debug", "PS3") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debugps3) CC = ppu-lv2-g++ CXX = ppu-lv2-g++ AR = ppu-lv2-ar OBJDIR = obj/PS3/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject.elf DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) CXXFLAGS += $(CFLAGS) LDFLAGS += -s LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.PlatformSpecificBlock() platforms { "x64" } prepare() local cfg = premake.getconfig(prj, "Debug", "x64") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debug64) OBJDIR = obj/x64/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) -m64 CXXFLAGS += $(CFLAGS) LDFLAGS += -s -m64 -L/usr/lib64 LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.UniversalStaticLibBlock() kind "StaticLib" platforms { "universal32" } prepare() local cfg = premake.getconfig(prj, "Debug", "Universal32") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debuguniv32) OBJDIR = obj/Universal32/Debug TARGETDIR = . TARGET = $(TARGETDIR)/libMyProject.a DEFINES += INCLUDES += CPPFLAGS += $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) -arch i386 -arch ppc CXXFLAGS += $(CFLAGS) LDFLAGS += -s -arch i386 -arch ppc LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = libtool -o $(TARGET) $(OBJECTS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end
-- -- tests/test_gmake_cpp.lua -- Automated test suite for GNU Make C/C++ project generation. -- Copyright (c) 2009 Jason Perkins and the Premake project -- T.gmake_cpp = { } -- -- Configure a solution for testing -- local sln, prj function T.gmake_cpp.setup() _ACTION = "gmake" _OPTIONS.os = "linux" sln = solution "MySolution" configurations { "Debug", "Release" } platforms { "native" } prj = project "MyProject" language "C++" kind "ConsoleApp" end local function prepare() io.capture() premake.buildconfigs() end -- -- Test the header -- function T.gmake_cpp.BasicHeader() prepare() premake.gmake_cpp_header(prj, premake.gcc, sln.platforms) test.capture [[ # GNU Make project makefile autogenerated by Premake ifndef config config=debug endif ifndef verbose SILENT = @ endif ifndef CC CC = gcc endif ifndef CXX CXX = g++ endif ifndef AR AR = ar endif ]] end -- -- Test configuration blocks -- function T.gmake_cpp.BasicCfgBlock() prepare() local cfg = premake.getconfig(prj, "Debug") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debug) OBJDIR = obj/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) CXXFLAGS += $(CFLAGS) LDFLAGS += -s LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.BasicCfgBlockWithPlatformCc() platforms { "ps3" } prepare() local cfg = premake.getconfig(prj, "Debug", "PS3") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debugps3) CC = ppu-lv2-g++ CXX = ppu-lv2-g++ AR = ppu-lv2-ar OBJDIR = obj/PS3/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject.elf DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) CXXFLAGS += $(CFLAGS) LDFLAGS += -s LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.PlatformSpecificBlock() platforms { "x64" } prepare() local cfg = premake.getconfig(prj, "Debug", "x64") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debug64) OBJDIR = obj/x64/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) -m64 CXXFLAGS += $(CFLAGS) LDFLAGS += -s -m64 -L/usr/lib64 LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.UniversalStaticLibBlock() kind "StaticLib" platforms { "universal32" } prepare() local cfg = premake.getconfig(prj, "Debug", "Universal32") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debuguniv32) OBJDIR = obj/Universal32/Debug TARGETDIR = . TARGET = $(TARGETDIR)/libMyProject.a DEFINES += INCLUDES += CPPFLAGS += $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) -arch i386 -arch ppc CXXFLAGS += $(CFLAGS) LDFLAGS += -s -arch i386 -arch ppc LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = libtool -o $(TARGET) $(OBJECTS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end
Fixed failing GMake C++ tests
Fixed failing GMake C++ tests
Lua
bsd-3-clause
Amorph/premake-dev,dimitarcl/premake-dev,Amorph/premake-dev,Amorph/premake-stable,dimitarcl/premake-dev,Amorph/premake-dev,dimitarcl/premake-dev,Amorph/premake-stable,Amorph/premake-stable
45d9fe0b165467b808bf2fa56edb9e9ebaa89c7b
applications/luci-statistics/luasrc/statistics/i18n.lua
applications/luci-statistics/luasrc/statistics/i18n.lua
--[[ Luci statistics - diagram i18n helper (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.statistics.i18n", package.seeall) require("luci.util") require("luci.i18n") Instance = luci.util.class() function Instance.__init__( self, graph ) self.i18n = luci.i18n self.graph = graph self.i18n.loadc("rrdtool") self.i18n.loadc("statistics") end function Instance._subst( self, str, val ) str = str:gsub( "%%H", self.graph.opts.host or "" ) str = str:gsub( "%%pn", val.plugin or "" ) str = str:gsub( "%%pi", val.pinst or "" ) str = str:gsub( "%%dt", val.dtype or "" ) str = str:gsub( "%%di", val.dinst or "" ) str = str:gsub( "%%ds", val.dsrc or "" ) return str end function Instance.title( self, plugin, pinst, dtype, dinst ) local title = self.i18n.translate( string.format( "stat_dg_title_%s_%s_%s", plugin, pinst, dtype ), self.i18n.translate( string.format( "stat_dg_title_%s_%s", plugin, pinst ), self.i18n.translate( string.format( "stat_dg_title_%s__%s", plugin, dtype ), self.i18n.translate( string.format( "stat_dg_title_%s", plugin ), self.graph:_mkpath( plugin, pinst, dtype ) ) ) ) ) return self:_subst( title, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.label( self, plugin, pinst, dtype, dinst ) local label = self.i18n.translate( string.format( "stat_dg_label_%s_%s_%s", plugin, pinst, dtype ), self.i18n.translate( string.format( "stat_dg_label_%s_%s", plugin, pinst ), self.i18n.translate( string.format( "stat_dg_label_%s__%s", plugin, dtype ), self.i18n.translate( string.format( "stat_dg_label_%s", plugin ), self.graph:_mkpath( plugin, pinst, dtype ) ) ) ) ) return self:_subst( label, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.ds( self, source ) local label = self.i18n.translate( string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ), self.i18n.translate( string.format( "stat_ds_%s_%s", source.type, source.instance ), self.i18n.translate( string.format( "stat_ds_label_%s__%s", source.type, source.ds ), self.i18n.translate( string.format( "stat_ds_%s", source.type ), source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds ) ) ) ) return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ) end
--[[ Luci statistics - diagram i18n helper (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.statistics.i18n", package.seeall) require("luci.util") require("luci.i18n") Instance = luci.util.class() function Instance.__init__( self, graph ) self.i18n = luci.i18n self.graph = graph self.i18n.loadc("rrdtool") self.i18n.loadc("statistics") end function Instance._subst( self, str, val ) str = str:gsub( "%%H", self.graph.opts.host or "" ) str = str:gsub( "%%pn", val.plugin or "" ) str = str:gsub( "%%pi", val.pinst or "" ) str = str:gsub( "%%dt", val.dtype or "" ) str = str:gsub( "%%di", val.dinst or "" ) str = str:gsub( "%%ds", val.dsrc or "" ) return str end function Instance.title( self, plugin, pinst, dtype, dinst ) local title = self.i18n.string( string.format( "stat_dg_title_%s_%s_%s", plugin, pinst, dtype ), self.i18n.string( string.format( "stat_dg_title_%s_%s", plugin, pinst ), self.i18n.string( string.format( "stat_dg_title_%s__%s", plugin, dtype ), self.i18n.string( string.format( "stat_dg_title_%s", plugin ), self.graph:_mkpath( plugin, pinst, dtype ) ) ) ) ) return self:_subst( title, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.label( self, plugin, pinst, dtype, dinst ) local label = self.i18n.string( string.format( "stat_dg_label_%s_%s_%s", plugin, pinst, dtype ), self.i18n.string( string.format( "stat_dg_label_%s_%s", plugin, pinst ), self.i18n.string( string.format( "stat_dg_label_%s__%s", plugin, dtype ), self.i18n.string( string.format( "stat_dg_label_%s", plugin ), self.graph:_mkpath( plugin, pinst, dtype ) ) ) ) ) return self:_subst( label, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.ds( self, source ) local label = self.i18n.string( string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ), self.i18n.string( string.format( "stat_ds_%s_%s", source.type, source.instance ), self.i18n.string( string.format( "stat_ds_label_%s__%s", source.type, source.ds ), self.i18n.string( string.format( "stat_ds_%s", source.type ), source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds ) ) ) ) return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ) end
application/luci-statistics: fix i18n binding, use string() instead of translate
application/luci-statistics: fix i18n binding, use string() instead of translate
Lua
apache-2.0
jorgifumi/luci,opentechinstitute/luci,palmettos/cnLuCI,keyidadi/luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,joaofvieira/luci,oyido/luci,nmav/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,thesabbir/luci,palmettos/cnLuCI,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,lbthomsen/openwrt-luci,fkooman/luci,nmav/luci,cshore/luci,deepak78/new-luci,thess/OpenWrt-luci,cshore/luci,oyido/luci,dismantl/luci-0.12,daofeng2015/luci,tcatm/luci,kuoruan/luci,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,openwrt/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,hnyman/luci,openwrt/luci,florian-shellfire/luci,bittorf/luci,bittorf/luci,sujeet14108/luci,zhaoxx063/luci,florian-shellfire/luci,slayerrensky/luci,oneru/luci,jorgifumi/luci,dwmw2/luci,hnyman/luci,daofeng2015/luci,Hostle/luci,cappiewu/luci,Kyklas/luci-proto-hso,maxrio/luci981213,david-xiao/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,tcatm/luci,Wedmer/luci,cshore/luci,hnyman/luci,oneru/luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,taiha/luci,bright-things/ionic-luci,wongsyrone/luci-1,oyido/luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,ff94315/luci-1,obsy/luci,fkooman/luci,zhaoxx063/luci,palmettos/test,teslamint/luci,dismantl/luci-0.12,opentechinstitute/luci,male-puppies/luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,nmav/luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,deepak78/new-luci,981213/luci-1,taiha/luci,daofeng2015/luci,Hostle/luci,nmav/luci,Sakura-Winkey/LuCI,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,oyido/luci,wongsyrone/luci-1,zhaoxx063/luci,Kyklas/luci-proto-hso,NeoRaider/luci,teslamint/luci,taiha/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,urueedi/luci,opentechinstitute/luci,bright-things/ionic-luci,jlopenwrtluci/luci,ollie27/openwrt_luci,rogerpueyo/luci,oneru/luci,male-puppies/luci,Sakura-Winkey/LuCI,schidler/ionic-luci,male-puppies/luci,urueedi/luci,RuiChen1113/luci,Noltari/luci,chris5560/openwrt-luci,palmettos/cnLuCI,oyido/luci,forward619/luci,thesabbir/luci,artynet/luci,marcel-sch/luci,kuoruan/luci,remakeelectric/luci,Kyklas/luci-proto-hso,jchuang1977/luci-1,chris5560/openwrt-luci,openwrt/luci,palmettos/test,NeoRaider/luci,cshore-firmware/openwrt-luci,dwmw2/luci,marcel-sch/luci,LuttyYang/luci,nwf/openwrt-luci,teslamint/luci,opentechinstitute/luci,tcatm/luci,Sakura-Winkey/LuCI,joaofvieira/luci,RedSnake64/openwrt-luci-packages,aa65535/luci,thess/OpenWrt-luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,marcel-sch/luci,deepak78/new-luci,thesabbir/luci,nwf/openwrt-luci,fkooman/luci,kuoruan/luci,sujeet14108/luci,urueedi/luci,aa65535/luci,schidler/ionic-luci,forward619/luci,maxrio/luci981213,ff94315/luci-1,lbthomsen/openwrt-luci,chris5560/openwrt-luci,jchuang1977/luci-1,MinFu/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,teslamint/luci,NeoRaider/luci,tobiaswaldvogel/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,joaofvieira/luci,deepak78/new-luci,taiha/luci,Hostle/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,cappiewu/luci,palmettos/test,teslamint/luci,981213/luci-1,chris5560/openwrt-luci,sujeet14108/luci,lcf258/openwrtcn,keyidadi/luci,daofeng2015/luci,jorgifumi/luci,RedSnake64/openwrt-luci-packages,marcel-sch/luci,cshore-firmware/openwrt-luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,lcf258/openwrtcn,rogerpueyo/luci,kuoruan/luci,981213/luci-1,fkooman/luci,openwrt/luci,harveyhu2012/luci,Wedmer/luci,opentechinstitute/luci,taiha/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,RuiChen1113/luci,florian-shellfire/luci,obsy/luci,forward619/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,dismantl/luci-0.12,chris5560/openwrt-luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,urueedi/luci,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,marcel-sch/luci,Hostle/luci,cappiewu/luci,RuiChen1113/luci,maxrio/luci981213,harveyhu2012/luci,Wedmer/luci,forward619/luci,Kyklas/luci-proto-hso,ollie27/openwrt_luci,zhaoxx063/luci,kuoruan/lede-luci,maxrio/luci981213,obsy/luci,RuiChen1113/luci,jorgifumi/luci,aa65535/luci,male-puppies/luci,david-xiao/luci,mumuqz/luci,cshore/luci,sujeet14108/luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,NeoRaider/luci,shangjiyu/luci-with-extra,taiha/luci,cshore-firmware/openwrt-luci,nwf/openwrt-luci,dwmw2/luci,MinFu/luci,rogerpueyo/luci,ff94315/luci-1,thess/OpenWrt-luci,wongsyrone/luci-1,keyidadi/luci,tobiaswaldvogel/luci,ff94315/luci-1,harveyhu2012/luci,nmav/luci,male-puppies/luci,db260179/openwrt-bpi-r1-luci,MinFu/luci,rogerpueyo/luci,remakeelectric/luci,mumuqz/luci,shangjiyu/luci-with-extra,Kyklas/luci-proto-hso,nwf/openwrt-luci,teslamint/luci,kuoruan/lede-luci,tcatm/luci,nmav/luci,mumuqz/luci,daofeng2015/luci,ollie27/openwrt_luci,joaofvieira/luci,deepak78/new-luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,harveyhu2012/luci,MinFu/luci,openwrt-es/openwrt-luci,taiha/luci,lbthomsen/openwrt-luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,bright-things/ionic-luci,tcatm/luci,dismantl/luci-0.12,artynet/luci,NeoRaider/luci,cappiewu/luci,taiha/luci,aa65535/luci,thesabbir/luci,male-puppies/luci,dwmw2/luci,artynet/luci,obsy/luci,palmettos/cnLuCI,dwmw2/luci,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,keyidadi/luci,kuoruan/luci,nwf/openwrt-luci,palmettos/test,joaofvieira/luci,jchuang1977/luci-1,florian-shellfire/luci,wongsyrone/luci-1,kuoruan/lede-luci,joaofvieira/luci,slayerrensky/luci,artynet/luci,jorgifumi/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,openwrt/luci,thess/OpenWrt-luci,remakeelectric/luci,NeoRaider/luci,bittorf/luci,schidler/ionic-luci,palmettos/cnLuCI,bright-things/ionic-luci,Hostle/openwrt-luci-multi-user,nmav/luci,rogerpueyo/luci,teslamint/luci,Noltari/luci,artynet/luci,db260179/openwrt-bpi-r1-luci,urueedi/luci,mumuqz/luci,thess/OpenWrt-luci,obsy/luci,ff94315/luci-1,MinFu/luci,openwrt/luci,cshore/luci,shangjiyu/luci-with-extra,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,openwrt-es/openwrt-luci,zhaoxx063/luci,Sakura-Winkey/LuCI,kuoruan/lede-luci,keyidadi/luci,palmettos/test,forward619/luci,ff94315/luci-1,daofeng2015/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,nmav/luci,forward619/luci,david-xiao/luci,openwrt-es/openwrt-luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,tobiaswaldvogel/luci,male-puppies/luci,artynet/luci,aa65535/luci,fkooman/luci,slayerrensky/luci,maxrio/luci981213,florian-shellfire/luci,dismantl/luci-0.12,NeoRaider/luci,nwf/openwrt-luci,nwf/openwrt-luci,joaofvieira/luci,Noltari/luci,Wedmer/luci,chris5560/openwrt-luci,tcatm/luci,MinFu/luci,cshore/luci,dwmw2/luci,mumuqz/luci,florian-shellfire/luci,wongsyrone/luci-1,florian-shellfire/luci,obsy/luci,palmettos/cnLuCI,lbthomsen/openwrt-luci,maxrio/luci981213,ff94315/luci-1,RuiChen1113/luci,chris5560/openwrt-luci,remakeelectric/luci,ReclaimYourPrivacy/cloak-luci,dismantl/luci-0.12,schidler/ionic-luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,tcatm/luci,oneru/luci,deepak78/new-luci,RedSnake64/openwrt-luci-packages,oneru/luci,remakeelectric/luci,Kyklas/luci-proto-hso,artynet/luci,keyidadi/luci,981213/luci-1,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,remakeelectric/luci,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,Noltari/luci,dismantl/luci-0.12,david-xiao/luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,thess/OpenWrt-luci,hnyman/luci,schidler/ionic-luci,lcf258/openwrtcn,jlopenwrtluci/luci,urueedi/luci,oyido/luci,jchuang1977/luci-1,Hostle/luci,Noltari/luci,cshore/luci,lbthomsen/openwrt-luci,marcel-sch/luci,aa65535/luci,obsy/luci,david-xiao/luci,kuoruan/luci,deepak78/new-luci,harveyhu2012/luci,urueedi/luci,bright-things/ionic-luci,harveyhu2012/luci,Noltari/luci,Wedmer/luci,rogerpueyo/luci,openwrt/luci,fkooman/luci,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,tcatm/luci,thess/OpenWrt-luci,Hostle/luci,cshore/luci,kuoruan/lede-luci,oneru/luci,jorgifumi/luci,palmettos/test,thesabbir/luci,LuttyYang/luci,bittorf/luci,fkooman/luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,Hostle/luci,dwmw2/luci,mumuqz/luci,openwrt/luci,palmettos/test,jchuang1977/luci-1,mumuqz/luci,dwmw2/luci,palmettos/cnLuCI,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,thesabbir/luci,tobiaswaldvogel/luci,daofeng2015/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,Hostle/luci,maxrio/luci981213,jorgifumi/luci,obsy/luci,marcel-sch/luci,slayerrensky/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,kuoruan/lede-luci,kuoruan/lede-luci,urueedi/luci,RuiChen1113/luci,thesabbir/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,wongsyrone/luci-1,remakeelectric/luci,kuoruan/luci,zhaoxx063/luci,jlopenwrtluci/luci,rogerpueyo/luci,sujeet14108/luci,Noltari/luci,Noltari/luci,oyido/luci,oyido/luci,openwrt-es/openwrt-luci,MinFu/luci,remakeelectric/luci,slayerrensky/luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,Wedmer/luci,lcf258/openwrtcn,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,hnyman/luci,artynet/luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,Hostle/openwrt-luci-multi-user,LuttyYang/luci,MinFu/luci,981213/luci-1,rogerpueyo/luci,LuttyYang/luci,ollie27/openwrt_luci,male-puppies/luci,cappiewu/luci,bittorf/luci,marcel-sch/luci,sujeet14108/luci,cappiewu/luci,Wedmer/luci,LuttyYang/luci,aa65535/luci,kuoruan/lede-luci,bittorf/luci,opentechinstitute/luci,981213/luci-1,sujeet14108/luci,jlopenwrtluci/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,zhaoxx063/luci,daofeng2015/luci,thess/OpenWrt-luci,fkooman/luci,981213/luci-1,lcf258/openwrtcn,cappiewu/luci,harveyhu2012/luci,LuttyYang/luci,kuoruan/luci,wongsyrone/luci-1,Noltari/luci,jchuang1977/luci-1,slayerrensky/luci,lcf258/openwrtcn,nwf/openwrt-luci,keyidadi/luci,david-xiao/luci,Kyklas/luci-proto-hso,jchuang1977/luci-1,jlopenwrtluci/luci,mumuqz/luci,oneru/luci,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,NeoRaider/luci,tobiaswaldvogel/luci,keyidadi/luci,bittorf/luci
bba1ff0cfa40fcc52a56bb8a3ee294a2838629e0
alias.lua
alias.lua
--Contains data needed to create command aliasList = table.load("AliasList.txt") or {} local macroCMDs = { ["%*"] = function(nusr,nchan,nmsg,nargs,usedArgs) local add = "" for k,v in pairs(nargs) do if not usedArgs[k] then add = add .. v .. (k<#nargs and " " or "") end end return add end, ["me"] = function(nusr,nchan,nmsg,nargs,usedArgs) return nusr.nick end, ["chan"] = function(nusr,nchan,nmsg,nargs,usedArgs) return nchan end, ["host([^m])"] = function(nusr,nchan,nmsg,nargs,usedArgs,left) return nusr.host..left end, ["hostmask"] = function(nusr,nchan,nmsg,nargs,usedArgs) return nusr.fullhost end, ["cash"] = function(nusr,nchan,nmsg,nargs,usedArgs) return gameUsers[nusr.host].cash end, } --Return a helper function to insert new args correctly local aliasDepth = 0 local function mkAliasFunc(t,aArgs) return function(nusr,nchan,nmsg,nargs) --TODO: FIX DEPTH CHECK if aliasDepth>10 then aliasDepth=0 error("Alias depth limit reached!") end if not commands[t.cmd] then aliasDepth=0 error("Alias destination for "..t.name.." doesn't exist!") end --A few blacklists if t.cmd == "use" or t.cmd == "timer" or t.cmd == "bug" then error("You can't alias to that") end --Replace for numbered macros first local usedArgs = {} nmsg = t.aMsg:gsub("%$(%d)",function(repl) local repN = tonumber(repl) if repN and repN~=0 then usedArgs[repN] = true return nargs[repN] or "" end end) --Replace custom macros now for k,v in pairs(macroCMDs) do nmsg = nmsg:gsub("%$"..k,v[nusr][nchan][nmsg][nargs][usedArgs]) end aliasDepth = aliasDepth+1 --TODO: Fix coroutine to actually make nested alias loops not block coroutine.yield(false,0) local f = makeCMD(t.cmd,nusr,nchan,nmsg,getArgs(nmsg)) if not f then return "" end local ret = {f()} aliasDepth = 0 return unpack(ret) end end --Insert alias commands on reload for k,v in pairs(aliasList) do local aArgs = getArgs(v.aMsg) if not commands[v.name] then add_cmd( mkAliasFunc(v,aArgs) ,v.name,v.level,"Alias for "..v.cmd.." "..v.aMsg,false) else --name already exists, hide alias aliasList[k]=nil end end --ALIAS, add an alias for a command local function alias(usr,chan,msg,args) if not msg or not args[1] then return "Usage: '/alias add/rem/list <name> <cmd> [<args>]'" end if args[1]=="add" then if not args[2] then return "Usage: '/alias add <name> <cmd> [<args>]'" end if not args[3] then return "No cmd specified! '/alias add <name> <cmd> [<args>]'" end local name,cmd,aArgs = args[2],args[3],{} if not commands[cmd] then return cmd.." doesn't exist!" end if cmd == "timer" or cmd == "use" or cmd == "bug" then return "Error: You can't alias to that" end if allCommands[name] then return name.." already exists!" end if getPerms(usr.host) < commands[cmd].level then return "You can't alias that!" end if name:find("[%*:][%c]?%d?%d?,?%d?%d?$") then return "Bad alias name!" end if name:find("[\128-\255]") then return "Ascii aliases only" end if #args > 50 then return "Alias too complex!" end for i=4,#args do table.insert(aArgs,args[i]) end local aMsg = table.concat(aArgs," ") if #aMsg > 500 then return "Alias too complex!" end local alis = {name=name,cmd=cmd,aMsg=aMsg,level=commands[cmd].level} add_cmd( mkAliasFunc(alis,aArgs) ,name,alis.level,"Alias for "..cmd.." "..aMsg,false) table.insert(aliasList,alis) table.save(aliasList,"AliasList.txt") if config.logchannel then ircSendChatQ(config.logchannel, usr.nick.."!"..usr.username.."@"..usr.host.." added alias "..name.." to "..cmd.." "..aMsg) end return "Added alias" elseif args[1]=="rem" or args[1]=="remove" then if not args[2] then return "Usage: '/alias rem <name>'" end local name = args[2] for k,v in pairs(aliasList) do if name==v.name then if v.lock then return "Alias is locked!" end aliasList[k]=nil commands[name]=nil allCommands[name]=nil table.save(aliasList,"AliasList.txt") return "Removed alias" end end return "Alias not found" elseif args[1]=="list" then local t={} for k,v in pairs(aliasList) do table.insert(t,v.name.."\15"..(v.lock or "")) end return "Aliases: "..table.concat(t,", ") elseif args[1]=="lock" then --Lock an alias so other users can't remove it if not args[2] then return "'/alias lock <name>'" end if getPerms(usr.host) < 101 then return "No permission to lock!" end local name = args[2] for k,v in pairs(aliasList) do if name==v.name then v.lock = "*" --bool doesn't save right now table.save(aliasList,"AliasList.txt") return "Locked alias" end end return "Alias not found" elseif args[1]=="unlock" then if not args[2] then return "'/alias unlock <name>'" end if getPerms(usr.host) < 101 then return "No permission to unlock!" end local name = args[2] for k,v in pairs(aliasList) do if name==v.name then v.lock = nil table.save(aliasList,"AliasList.txt") return "Unlocked alias" end end return "Alias not found" end end add_cmd(alias,"alias",0,"Add another name to execute a command, '/alias add/rem/list <newName> <cmd> [<args>]'.",true)
--Contains data needed to create command aliasList = table.load("AliasList.txt") or {} local macroCMDs = { ["me"] = function(nusr,nchan,nmsg,nargs,usedArgs) return nusr.nick end, ["chan"] = function(nusr,nchan,nmsg,nargs,usedArgs) return nchan end, ["host(m?a?s?k?)"] = function(nusr,nchan,nmsg,nargs,usedArgs,right) if right then if right=="mask" then return nusr.fullhost end end return nusr.host..right end, ["cash"] = function(nusr,nchan,nmsg,nargs,usedArgs) return gameUsers[nusr.host].cash end, } --Return a helper function to insert new args correctly local aliasDepth = 0 local function mkAliasFunc(t,aArgs) return function(nusr,nchan,nmsg,nargs) --TODO: FIX DEPTH CHECK if aliasDepth>10 then aliasDepth=0 error("Alias depth limit reached!") end if not commands[t.cmd] then aliasDepth=0 error("Alias destination for "..t.name.." doesn't exist!") end --A few blacklists if t.cmd == "use" or t.cmd == "timer" or t.cmd == "bug" then error("You can't alias to that") end --Replace for numbered macros first local usedArgs = {} nmsg = t.aMsg:gsub("%$(%d)",function(repl) local repN = tonumber(repl) if repN and repN~=0 then usedArgs[repN] = true return nargs[repN] or "" end end) --Replace $* here because nmsg = nmsg:gsub("%$%*",function() local t = {} for k,v in pairs(nargs) do if not usedArgs[k] then table.insert(t,v) end end return table.concat(t," ") end,1) --Replace custom macros now for k,v in pairs(macroCMDs) do nmsg = nmsg:gsub("%$"..k,v[nusr][nchan][nmsg][nargs][usedArgs]) end aliasDepth = aliasDepth+1 --TODO: Fix coroutine to actually make nested alias loops not block coroutine.yield(false,0) local f = makeCMD(t.cmd,nusr,nchan,nmsg,getArgs(nmsg)) if not f then return "" end local ret = {f()} aliasDepth = 0 return unpack(ret) end end --Insert alias commands on reload for k,v in pairs(aliasList) do local aArgs = getArgs(v.aMsg) if not commands[v.name] then add_cmd( mkAliasFunc(v,aArgs) ,v.name,v.level,"Alias for "..v.cmd.." "..v.aMsg,false) else --name already exists, hide alias aliasList[k]=nil end end --ALIAS, add an alias for a command local function alias(usr,chan,msg,args) if not msg or not args[1] then return "Usage: '/alias add/rem/list <name> <cmd> [<args>]'" end if args[1]=="add" then if not args[2] then return "Usage: '/alias add <name> <cmd> [<args>]'" end if not args[3] then return "No cmd specified! '/alias add <name> <cmd> [<args>]'" end local name,cmd,aArgs = args[2],args[3],{} if not commands[cmd] then return cmd.." doesn't exist!" end if cmd == "timer" or cmd == "use" or cmd == "bug" then return "Error: You can't alias to that" end if allCommands[name] then return name.." already exists!" end if getPerms(usr.host) < commands[cmd].level then return "You can't alias that!" end if name:find("[%*:][%c]?%d?%d?,?%d?%d?$") then return "Bad alias name!" end if name:find("[\128-\255]") then return "Ascii aliases only" end if #args > 50 then return "Alias too complex!" end for i=4,#args do table.insert(aArgs,args[i]) end local aMsg = table.concat(aArgs," ") if #aMsg > 500 then return "Alias too complex!" end local alis = {name=name,cmd=cmd,aMsg=aMsg,level=commands[cmd].level} add_cmd( mkAliasFunc(alis,aArgs) ,name,alis.level,"Alias for "..cmd.." "..aMsg,false) table.insert(aliasList,alis) table.save(aliasList,"AliasList.txt") if config.logchannel then ircSendChatQ(config.logchannel, usr.nick.."!"..usr.username.."@"..usr.host.." added alias "..name.." to "..cmd.." "..aMsg) end return "Added alias" elseif args[1]=="rem" or args[1]=="remove" then if not args[2] then return "Usage: '/alias rem <name>'" end local name = args[2] for k,v in pairs(aliasList) do if name==v.name then if v.lock then return "Alias is locked!" end aliasList[k]=nil commands[name]=nil allCommands[name]=nil table.save(aliasList,"AliasList.txt") return "Removed alias" end end return "Alias not found" elseif args[1]=="list" then local t={} for k,v in pairs(aliasList) do table.insert(t,v.name.."\15"..(v.lock or "")) end return "Aliases: "..table.concat(t,", ") elseif args[1]=="lock" then --Lock an alias so other users can't remove it if not args[2] then return "'/alias lock <name>'" end if getPerms(usr.host) < 101 then return "No permission to lock!" end local name = args[2] for k,v in pairs(aliasList) do if name==v.name then v.lock = "*" --bool doesn't save right now table.save(aliasList,"AliasList.txt") return "Locked alias" end end return "Alias not found" elseif args[1]=="unlock" then if not args[2] then return "'/alias unlock <name>'" end if getPerms(usr.host) < 101 then return "No permission to unlock!" end local name = args[2] for k,v in pairs(aliasList) do if name==v.name then v.lock = nil table.save(aliasList,"AliasList.txt") return "Unlocked alias" end end return "Alias not found" end end add_cmd(alias,"alias",0,"Add another name to execute a command, '/alias add/rem/list <newName> <cmd> [<args>]'.",true)
$* is correctly only used once.
$* is correctly only used once. Fix $host/hostmask
Lua
mit
wolfy1339/WolfyBot,GLolol/Crackbot,cracker64/Crackbot,Brilliant-Minds/BMNBot-2,wolfy1339/WolfyBot,GLolol/Crackbot,Brilliant-Minds/BMNBot-2,cracker64/Crackbot,wolfy1339/WolfyBot
3b95ecd9b22d736dbb65009c4a0d764f4e163aaf
lualib/skynet/queue.lua
lualib/skynet/queue.lua
local skynet = require "skynet" local coroutine = coroutine local pcall = pcall local table = table function skynet.queue() local current_thread local ref = 0 local thread_queue = {} return function(f, ...) local thread = coroutine.running() if ref == 0 then current_thread = thread elseif current_thread ~= thread then table.insert(thread_queue, thread) skynet.wait() assert(ref == 0) end ref = ref + 1 local ok, err = pcall(f, ...) ref = ref - 1 if ref == 0 then current_thread = nil local co = table.remove(thread_queue,1) if co then skynet.wakeup(co) end end assert(ok,err) end end return skynet.queue
local skynet = require "skynet" local coroutine = coroutine local pcall = pcall local table = table function skynet.queue() local current_thread local ref = 0 local thread_queue = {} return function(f, ...) local thread = coroutine.running() if current_thread and current_thread ~= thread then table.insert(thread_queue, thread) skynet.wait() assert(ref == 0) -- current_thread == thread end current_thread = thread ref = ref + 1 local ok, err = pcall(f, ...) ref = ref - 1 if ref == 0 then current_thread = table.remove(thread_queue,1) if current_thread then skynet.wakeup(current_thread) end end assert(ok,err) end end return skynet.queue
bugfix: skynet.queue
bugfix: skynet.queue
Lua
mit
JiessieDawn/skynet,bttscut/skynet,vizewang/skynet,bingo235/skynet,LiangMa/skynet,samael65535/skynet,letmefly/skynet,lc412/skynet,kebo/skynet,microcai/skynet,cuit-zhaxin/skynet,ag6ag/skynet,korialuo/skynet,KittyCookie/skynet,KittyCookie/skynet,xjdrew/skynet,lynx-seu/skynet,zhaijialong/skynet,xubigshu/skynet,firedtoad/skynet,catinred2/skynet,bttscut/skynet,matinJ/skynet,ludi1991/skynet,ag6ag/skynet,lawnight/skynet,cdd990/skynet,xjdrew/skynet,lawnight/skynet,hongling0/skynet,rainfiel/skynet,sundream/skynet,pigparadise/skynet,jiuaiwo1314/skynet,javachengwc/skynet,boyuegame/skynet,enulex/skynet,sdgdsffdsfff/skynet,Ding8222/skynet,icetoggle/skynet,zhaijialong/skynet,winglsh/skynet,MoZhonghua/skynet,cdd990/skynet,longmian/skynet,chenjiansnail/skynet,czlc/skynet,cuit-zhaxin/skynet,chenjiansnail/skynet,xinmingyao/skynet,Zirpon/skynet,zhangshiqian1214/skynet,javachengwc/skynet,longmian/skynet,jxlczjp77/skynet,xubigshu/skynet,codingabc/skynet,chfg007/skynet,matinJ/skynet,zhoukk/skynet,pichina/skynet,MRunFoss/skynet,zzh442856860/skynet,ilylia/skynet,QuiQiJingFeng/skynet,LuffyPan/skynet,fhaoquan/skynet,hongling0/skynet,icetoggle/skynet,yinjun322/skynet,your-gatsby/skynet,lawnight/skynet,LuffyPan/skynet,bigrpg/skynet,puXiaoyi/skynet,ruleless/skynet,sdgdsffdsfff/skynet,LuffyPan/skynet,leezhongshan/skynet,zhangshiqian1214/skynet,chenjiansnail/skynet,xinjuncoding/skynet,lynx-seu/skynet,Zirpon/skynet,xinmingyao/skynet,sundream/skynet,MetSystem/skynet,cloudwu/skynet,codingabc/skynet,chfg007/skynet,lawnight/skynet,ilylia/skynet,matinJ/skynet,zhangshiqian1214/skynet,cpascal/skynet,longmian/skynet,ag6ag/skynet,kebo/skynet,kyle-wang/skynet,felixdae/skynet,hongling0/skynet,pigparadise/skynet,great90/skynet,togolwb/skynet,bingo235/skynet,zhouxiaoxiaoxujian/skynet,wangyi0226/skynet,samael65535/skynet,helling34/skynet,leezhongshan/skynet,zzh442856860/skynet-Note,boyuegame/skynet,liuxuezhan/skynet,microcai/skynet,yinjun322/skynet,xcjmine/skynet,rainfiel/skynet,zhaijialong/skynet,ilylia/skynet,ruleless/skynet,chuenlungwang/skynet,winglsh/skynet,plsytj/skynet,togolwb/skynet,dymx101/skynet,QuiQiJingFeng/skynet,cdd990/skynet,helling34/skynet,iskygame/skynet,KAndQ/skynet,chuenlungwang/skynet,czlc/skynet,yunGit/skynet,catinred2/skynet,zhoukk/skynet,liuxuezhan/skynet,chfg007/skynet,nightcj/mmo,ypengju/skynet_comment,zzh442856860/skynet-Note,vizewang/skynet,ludi1991/skynet,czlc/skynet,sundream/skynet,zzh442856860/skynet,xinjuncoding/skynet,javachengwc/skynet,cuit-zhaxin/skynet,MoZhonghua/skynet,dymx101/skynet,JiessieDawn/skynet,MetSystem/skynet,wangjunwei01/skynet,zzh442856860/skynet-Note,icetoggle/skynet,cmingjian/skynet,Ding8222/skynet,harryzeng/skynet,nightcj/mmo,your-gatsby/skynet,MetSystem/skynet,pigparadise/skynet,LiangMa/skynet,letmefly/skynet,felixdae/skynet,great90/skynet,samael65535/skynet,cmingjian/skynet,ypengju/skynet_comment,zhangshiqian1214/skynet,jiuaiwo1314/skynet,korialuo/skynet,liuxuezhan/skynet,zhangshiqian1214/skynet,helling34/skynet,codingabc/skynet,Zirpon/skynet,yunGit/skynet,yinjun322/skynet,KAndQ/skynet,u20024804/skynet,sanikoyes/skynet,jxlczjp77/skynet,MoZhonghua/skynet,cpascal/skynet,enulex/skynet,KittyCookie/skynet,zhangshiqian1214/skynet,u20024804/skynet,fhaoquan/skynet,leezhongshan/skynet,u20024804/skynet,KAndQ/skynet,firedtoad/skynet,lc412/skynet,iskygame/skynet,sanikoyes/skynet,gitfancode/skynet,dymx101/skynet,LiangMa/skynet,enulex/skynet,MRunFoss/skynet,MRunFoss/skynet,harryzeng/skynet,cpascal/skynet,lc412/skynet,bingo235/skynet,bttscut/skynet,zzh442856860/skynet-Note,winglsh/skynet,firedtoad/skynet,wangjunwei01/skynet,kyle-wang/skynet,zhouxiaoxiaoxujian/skynet,Markal128/skynet,fztcjjl/skynet,bigrpg/skynet,boyuegame/skynet,zhoukk/skynet,harryzeng/skynet,chuenlungwang/skynet,cloudwu/skynet,cloudwu/skynet,microcai/skynet,felixdae/skynet,sanikoyes/skynet,yunGit/skynet,sdgdsffdsfff/skynet,vizewang/skynet,asanosoyokaze/skynet,puXiaoyi/skynet,nightcj/mmo,catinred2/skynet,wangyi0226/skynet,asanosoyokaze/skynet,great90/skynet,kyle-wang/skynet,xinjuncoding/skynet,zhouxiaoxiaoxujian/skynet,xjdrew/skynet,bigrpg/skynet,jiuaiwo1314/skynet,plsytj/skynet,kebo/skynet,letmefly/skynet,Markal128/skynet,xcjmine/skynet,gitfancode/skynet,letmefly/skynet,Markal128/skynet,asanosoyokaze/skynet,zzh442856860/skynet,ruleless/skynet,Ding8222/skynet,puXiaoyi/skynet,gitfancode/skynet,lynx-seu/skynet,togolwb/skynet,iskygame/skynet,pichina/skynet,fhaoquan/skynet,liuxuezhan/skynet,ludi1991/skynet,your-gatsby/skynet,rainfiel/skynet,plsytj/skynet,wangjunwei01/skynet,JiessieDawn/skynet,pichina/skynet,jxlczjp77/skynet,fztcjjl/skynet,fztcjjl/skynet,korialuo/skynet,QuiQiJingFeng/skynet,xcjmine/skynet,ypengju/skynet_comment,ludi1991/skynet,cmingjian/skynet,wangyi0226/skynet
027ee54ab0de2faa17de8efc01330315796689e8
tests/sample/security-rules.lua
tests/sample/security-rules.lua
------------------------------------ -- Loading disscetors ------------------------------------ require("ipv4") require("tcp") require("http") ------------------------------------ -- Function definition ------------------------------------ function getpayload(data) payload = '' for i = 1, #data do payload = payload .. string.format("%c", data[i]) end return payload end function contains(table, elem) return table[elem] ~= nil end ------------------------------------ -- IP compliance ------------------------------------ haka.rule { hooks = { "ipv4-up" }, eval = function (self, pkt) -- bad IP checksum if not pkt:verify_checksum() then haka.log("filter", "\tBad IP checksum") pkt:drop() end end } ------------------------------------ -- IP attacks ------------------------------------ haka.rule { hooks = { "ipv4-up" }, eval = function (self, pkt) if pkt.src == pkt.dst then haka.log("filter", "Land attack detected") pkt:drop() end end } ------------------------------------ -- TCP attacks ------------------------------------ haka.rule { hooks = { "tcp-up" }, eval = function (self, pkt) --Xmas scan, as made by nmap -sX <IP> if pkt.flags.psh and pkt.flags.fin and pkt.flags.urg then haka.log("filter", "Xmas attack detected !!!") pkt:drop() end end } haka.rule { hooks = { "tcp-up" }, eval = function (self, pkt) local bindshell = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" .. "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" .. "\x80\xe8\xdc\xff\xff\xff/bin/sh" if #pkt.payload > 0 then -- reconstruct payload payload = getpayload(pkt.payload) -- test if shellcode is present in data if string.find(payload, bindshell) then haka.log("filter", "/bin/sh shellcode detected !!!") pkt:drop() end end end } ------------------------------------ -- HTTP compliance ------------------------------------ -- check http method value haka.rule { hooks = {"http-request"}, eval = function (self, http) local http_methods = { 'get', 'post', 'head', 'put', 'trace', 'delete', 'options' } local method = http.request.method if contains(http_methods, method:lower()) == nil then haka.log("filter", "non authorized http method") http:drop() end end } -- check http version value haka.rule { hooks = {"http-request"}, eval = function (self, http) local http_versions = { '0.9', '1.0', '1.1' } local protocol = http.request.version:sub(1,4) local version = http.request.version:sub(6) if not protocol == "HTTP" or contains(http_versions, version) == nil then haka.log("filter", "unsupported http version") http:drop() end end } -- check content length value haka.rule { hooks = {"http-request"}, eval = function (self, http) local content_length = http.request.headers["Content-Length"] if content_length then if tonumber(content_length) or content_length < 0 then haka.log("filter", "corrupted content-length header value") http:drop() end end end } ------------------------------------ -- HTTP Policy ------------------------------------ -- add custom user-agent haka.rule { hooks = {"http-response"}, eval = function (self, http) http.response.headers["User-Agent"] = "Haka User-Agent" end } -- allow only get and post methods haka.rule { hooks = {"http-request"}, eval = function (self, http) local method = http.request.method:lower() print(method) if not method == 'get' and not method == 'post' then haka.log("filter", "not allowed http method") end end } ------------------------------------ -- HTTP Attacks ------------------------------------ -- detect malicious web scanners haka.rule { hooks = {"http-request"}, eval = function (self, http) --user-agent patterns of known web scanners local http_useragent = { nikto = '.+%(Nikto%/.+%)%s%(Evasions:.+%)%s%(Test:.+%)', nessus = '^Nessus.*', w3af = '*.%s;w3af.sf.net%)', sqlmap = '^sqlmap%/%.*%s(http:%/%/sqlmap%.sourceforge%.net)', fimap = '^fimap%.googlecode%.%com.*', grabber = '^Grabber.*' } if (http.request.headers['User-Agent']) then local user_agent = http.request.headers['User-Agent'] print('[' .. user_agent .. ']') for scanner, pattern in pairs(http_useragent) do if user_agent:match(pattern) then haka.log("filter", "Nikto scan detected !!!") http:drop() end end end end } ------------------------------------ -- Firewall rules ------------------------------------ akpf = haka.rule_group { name = "akpf", init = function (self, pkt) haka.log("filter", "entering packet filetring rules : %d --> %d", pkt.tcp.srcport, pkt.tcp.dstport) end, fini = function (self, pkt) haka.log("filter", "packet dropped : drop by default") pkt:drop() end, continue = function (self, ret) print ("ret:" .. tostring(ret)) return not ret end } akpf:rule { hooks = {"tcp-connection-new"}, eval = function (self, pkt) local netsrc = ipv4.network("10.2.96.0/22") local netdst = ipv4.network("10.2.104.0/22") -- if netsrc:contains(pkt.ip.src) and -- netdst:contains(pkt.ip.dst) and -- pkt.dstport == 80 then if pkt.tcp.dstport == 8888 or pkt.tcp.dstport == 8008 then haka.log("filter", "authorizing http traffic") pkt.next_dissector = "http" return true end end } akpf:rule { hooks = {"tcp-connection-new"}, eval = function (self, pkt) local netsrc = ipv4.network("10.2.96.0/22") local netdst = ipv4.network("10.2.104.0/22") local tcp = pkt.tcp if netsrc:contains(tcp.ip.src) and netdst:contains(tcp.ip.dst) and tcp.dstport == 22 then haka.log("filter", "authorizing ssh traffic") haka.log.warning("filter", "no available dissector for ssh") return true end end }
------------------------------------ -- Loading disscetors ------------------------------------ require("ipv4") require("tcp") require("http") ------------------------------------ -- Function definition ------------------------------------ local function getpayload(data) payload = '' for i = 1, #data do payload = payload .. string.char(data[i]) end return payload end local function contains(table, elem) return table[elem] ~= nil end local function dict(table) local ret = {} for _, v in pairs(table) do ret[v] = true end return ret end ------------------------------------ -- IP compliance ------------------------------------ haka.rule { hooks = { "ipv4-up" }, eval = function (self, pkt) -- bad IP checksum if not pkt:verify_checksum() then haka.log.error("filter", "Bad IP checksum") pkt:drop() end end } ------------------------------------ -- IP attacks ------------------------------------ haka.rule { hooks = { "ipv4-up" }, eval = function (self, pkt) if pkt.src == pkt.dst then haka.log.error("filter", "Land attack detected") pkt:drop() end end } ------------------------------------ -- TCP attacks ------------------------------------ haka.rule { hooks = { "tcp-up" }, eval = function (self, pkt) --Xmas scan, as made by nmap -sX <IP> if pkt.flags.psh and pkt.flags.fin and pkt.flags.urg then haka.log.error("filter", "Xmas attack detected !!!") pkt:drop() end end } haka.rule { hooks = { "tcp-up" }, eval = function (self, pkt) local bindshell = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" .. "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" .. "\x80\xe8\xdc\xff\xff\xff/bin/sh" if #pkt.payload > 0 then -- reconstruct payload payload = getpayload(pkt.payload) -- test if shellcode is present in data if string.find(payload, bindshell) then haka.log.error("filter", "/bin/sh shellcode detected !!!") pkt:drop() end end end } ------------------------------------ -- HTTP compliance ------------------------------------ -- check http method value haka.rule { hooks = {"http-request"}, eval = function (self, http) local http_methods = dict({ 'get', 'post', 'head', 'put', 'trace', 'delete', 'options' }) local method = http.request.method:lower() if not contains(http_methods, method) then haka.log.error("filter", "non authorized http method '%s'", method) http:drop() end end } -- check http version value haka.rule { hooks = {"http-request"}, eval = function (self, http) local http_versions = dict({ '0.9', '1.0', '1.1' }) local protocol = http.request.version:sub(1,4) local version = http.request.version:sub(6) if not protocol == "HTTP" or not contains(http_versions, version) then haka.log.error("filter", "unsupported http version '%s/%s'", protocol, version) http:drop() end end } -- check content length value haka.rule { hooks = {"http-request"}, eval = function (self, http) local content_length = http.request.headers["Content-Length"] if content_length then content_length = tonumber(content_length) if content_length == nil or content_length < 0 then haka.log.error("filter", "corrupted content-length header value") http:drop() end end end } ------------------------------------ -- HTTP Policy ------------------------------------ -- add custom user-agent haka.rule { hooks = {"http-request"}, eval = function (self, http) http.request.headers["User-Agent"] = "Haka User-Agent" end } -- allow only get and post methods haka.rule { hooks = {"http-request"}, eval = function (self, http) local method = http.request.method:lower() if method ~= 'get' and method ~= 'post' then haka.log.warning("filter", "forbidden http method '%s'", method) end end } ------------------------------------ -- HTTP Attacks ------------------------------------ -- detect malicious web scanners haka.rule { hooks = {"http-request"}, eval = function (self, http) --user-agent patterns of known web scanners local http_useragent = { nikto = '.+%(Nikto%/.+%)%s%(Evasions:.+%)%s%(Test:.+%)', nessus = '^Nessus.*', w3af = '*.%s;w3af.sf.net%)', sqlmap = '^sqlmap%/.*%s%(http:%/%/sqlmap.*%)', fimap = '^fimap%.googlecode%.%com.*', grabber = '^Grabber.*' } if (http.request.headers['User-Agent']) then local user_agent = http.request.headers['User-Agent'] for scanner, pattern in pairs(http_useragent) do if user_agent:match(pattern) then haka.log.error("filter", "'%s' scan detected !!!", scanner) http:drop() end end end end } ------------------------------------ -- Firewall rules ------------------------------------ akpf = haka.rule_group { name = "akpf", init = function (self, pkt) haka.log.debug("filter", "entering packet filetring rules : %d --> %d", pkt.tcp.srcport, pkt.tcp.dstport) end, fini = function (self, pkt) haka.log.error("filter", "packet dropped : drop by default") pkt:drop() end, continue = function (self, ret) return not ret end } akpf:rule { hooks = {"tcp-connection-new"}, eval = function (self, pkt) local netsrc = ipv4.network("10.2.96.0/22") local netdst = ipv4.network("10.2.104.0/22") local tcp = pkt.tcp if netsrc:contains(tcp.ip.src) and netdst:contains(tcp.ip.dst) and tcp.dstport == 80 then haka.log.warning("filter", "authorizing http traffic") pkt.next_dissector = "http" return true end end } akpf:rule { hooks = {"tcp-connection-new"}, eval = function (self, pkt) local netsrc = ipv4.network("10.2.96.0/22") local netdst = ipv4.network("10.2.104.0/22") local tcp = pkt.tcp if netsrc:contains(tcp.ip.src) and netdst:contains(tcp.ip.dst) and tcp.dstport == 22 then haka.log.warning("filter", "authorizing ssh traffic") haka.log.warning("filter", "no available dissector for ssh") return true end end }
Fix security rule configuration sample
Fix security rule configuration sample
Lua
mpl-2.0
haka-security/haka,Wingless-Archangel/haka,nabilbendafi/haka,LubyRuffy/haka,nabilbendafi/haka,lcheylus/haka,lcheylus/haka,lcheylus/haka,haka-security/haka,nabilbendafi/haka,haka-security/haka,Wingless-Archangel/haka,LubyRuffy/haka
96498131c0571a329419efe2e61a5a88ed4dd1b8
test/sophia/transaction.test.lua
test/sophia/transaction.test.lua
-- basic transaction tests space = box.schema.space.create('test', { engine = 'sophia' }) index = space:create_index('primary', { type = 'tree', parts = {1, 'num'} }) -- begin/rollback box.begin() for key = 1, 10 do space:insert({key}) end t = {} for key = 1, 10 do table.insert(t, space:select({key})[1]) end t box.rollback() t = {} for key = 1, 10 do assert(#space:select({key}) == 0) end t -- begin/commit insert box.begin() t = {} for key = 1, 10 do space:insert({key}) end t = {} box.commit() t = {} for key = 1, 10 do table.insert(t, space:select({key})[1]) end t -- begin/commit delete box.begin() for key = 1, 10 do space:delete({key}) end box.commit() t = {} for key = 1, 10 do assert(#space:select({key}) == 0) end t space:drop() -- multi-space transactions a = box.schema.space.create('test', { engine = 'sophia' }) index = a:create_index('primary', { type = 'tree', parts = {1, 'num'} }) b = box.schema.space.create('test_tmp', { engine = 'sophia' }) index = b:create_index('primary', { type = 'tree', parts = {1, 'num'} }) -- begin/rollback box.begin() for key = 1, 10 do a:insert({key}) end t = {} for key = 1, 10 do table.insert(t, a:select({key})[1]) end t for key = 1, 10 do b:insert({key}) end t = {} for key = 1, 10 do table.insert(t, b:select({key})[1]) end t box.rollback() t = {} for key = 1, 10 do assert(#a:select({key}) == 0) end t for key = 1, 10 do assert(#b:select({key}) == 0) end t -- begin/commit insert box.begin() t = {} for key = 1, 10 do a:insert({key}) end t = {} for key = 1, 10 do b:insert({key}) end t = {} box.commit() t = {} for key = 1, 10 do table.insert(t, a:select({key})[1]) end t t = {} for key = 1, 10 do table.insert(t, b:select({key})[1]) end t -- begin/commit delete box.begin() for key = 1, 10 do a:delete({key}) end for key = 1, 10 do b:delete({key}) end box.commit() t = {} for key = 1, 10 do assert(#a:select({key}) == 0) end t for key = 1, 10 do assert(#b:select({key}) == 0) end t a:drop() b:drop()
-- basic transaction tests space = box.schema.space.create('test', { engine = 'sophia' }) index = space:create_index('primary', { type = 'tree', parts = {1, 'num'} }) -- begin/rollback box.begin() for key = 1, 10 do space:insert({key}) end t = {} for key = 1, 10 do table.insert(t, space:select({key})[1]) end t box.rollback() t = {} for key = 1, 10 do assert(#space:select({key}) == 0) end t -- begin/commit insert box.begin() t = {} for key = 1, 10 do space:insert({key}) end t = {} box.commit() t = {} for key = 1, 10 do table.insert(t, space:select({key})[1]) end t -- begin/commit delete box.begin() for key = 1, 10 do space:delete({key}) end box.commit() t = {} for key = 1, 10 do assert(#space:select({key}) == 0) end t space:drop() -- multi-space transactions a = box.schema.space.create('test', { engine = 'sophia' }) index = a:create_index('primary', { type = 'tree', parts = {1, 'num'} }) b = box.schema.space.create('test_tmp', { engine = 'sophia' }) index = b:create_index('primary', { type = 'tree', parts = {1, 'num'} }) -- begin/rollback box.begin() for key = 1, 10 do a:insert({key}) end t = {} for key = 1, 10 do table.insert(t, a:select({key})[1]) end t for key = 1, 10 do b:insert({key}) end t = {} for key = 1, 10 do table.insert(t, b:select({key})[1]) end t box.rollback() t = {} for key = 1, 10 do assert(#a:select({key}) == 0) end t for key = 1, 10 do assert(#b:select({key}) == 0) end t -- begin/commit insert box.begin() t = {} for key = 1, 10 do a:insert({key}) end t = {} for key = 1, 10 do b:insert({key}) end t = {} box.commit() t = {} for key = 1, 10 do table.insert(t, a:select({key})[1]) end t t = {} for key = 1, 10 do table.insert(t, b:select({key})[1]) end t -- begin/commit delete box.begin() for key = 1, 10 do a:delete({key}) end for key = 1, 10 do b:delete({key}) end box.commit() t = {} for key = 1, 10 do assert(#a:select({key}) == 0) end t for key = 1, 10 do assert(#b:select({key}) == 0) end t a:drop() b:drop() -- ensure findByKey works in empty transaction context space = box.schema.space.create('test', { engine = 'sophia' }) index = space:create_index('primary', { type = 'tree', parts = {1, 'num'} }) box.begin() space:get({0}) box.rollback() space:drop()
sophia: fix case for first read in a transaction context
sophia: fix case for first read in a transaction context
Lua
bsd-2-clause
ocelot-inc/tarantool,rtsisyk/tarantool,ocelot-inc/tarantool,mejedi/tarantool,mejedi/tarantool,ocelot-inc/tarantool,mejedi/tarantool,rtsisyk/tarantool,ocelot-inc/tarantool,rtsisyk/tarantool,mejedi/tarantool,rtsisyk/tarantool
78186f738fe4c35de1ed8c205dd3606bf537f54b
generate.lua
generate.lua
do dofile("WoWAPI.lua") Ovale = {} LoadAddonFile("OvaleLexer.lua") LoadAddonFile("OvaleSimulationCraft.lua") local OvaleSimulationCraft = Ovale.OvaleSimulationCraft local profilesDirectory = "..\\SimulationCraft\\profiles\\Tier16H" local outputDirectory = "scripts" local saveInput = io.input() local saveOutput = io.output() local dir = io.popen("dir /b " .. profilesDirectory) os.execute("mkdir " .. outputDirectory) for filename in dir:lines() do if string.match(filename, "^[A-Z]") then local inputName = string.gsub(profilesDirectory, "\\", "/") .. "/" .. filename io.input(inputName) local simcStr = io.read("*all") if not string.find(simcStr, "optimal_raid=") then local simc = OvaleSimulationCraft(simcStr) simc.simcComments = true local outputFileName = "simulationcraft_" .. string.lower(string.gsub(filename, ".simc", ".lua")) outputFileName = string.gsub(outputFileName, "death_knight", "deathknight") print("Generating " .. outputFileName) local outputName = outputDirectory .. "/" .. outputFileName io.output(outputName) io.write(table.concat(simc:GenerateScript(), "\n")) end end end io.input(saveInput) io.output(saveOutput) end
--[[------------------------------ Load fake WoW environment. --]]------------------------------ local root = "../" do local state = { class = "DRUID", } dofile("WoWAPI.lua") WoWAPI:Initialize("Ovale", state) WoWAPI:ExportSymbols() end do -- Load all of the addon files. WoWAPI:LoadAddonFile("Ovale.toc") -- Pretend to fire ADDON_LOADED event. local AceAddon = LibStub("AceAddon-3.0") AceAddon:ADDON_LOADED() end local OvaleSimulationCraft = Ovale.OvaleSimulationCraft local profilesDirectory = "..\\SimulationCraft\\profiles\\Tier16H" local outputDirectory = "scripts" local saveInput = io.input() local saveOutput = io.output() local dir = io.popen("dir /b " .. profilesDirectory) os.execute("mkdir " .. outputDirectory) for filename in dir:lines() do if string.match(filename, "^[A-Z]") then local inputName = string.gsub(profilesDirectory, "\\", "/") .. "/" .. filename io.input(inputName) local simcStr = io.read("*all") if not string.find(simcStr, "optimal_raid=") then local simc = OvaleSimulationCraft(simcStr) simc.simcComments = true local outputFileName = "simulationcraft_" .. string.lower(string.gsub(filename, ".simc", ".lua")) outputFileName = string.gsub(outputFileName, "death_knight", "deathknight") print("Generating " .. outputFileName) local outputName = outputDirectory .. "/" .. outputFileName io.output(outputName) io.write(table.concat(simc:GenerateScript(), "\n")) end end end io.input(saveInput) io.output(saveOutput)
Fix generate.lua to work after WoWAPI module changes.
Fix generate.lua to work after WoWAPI module changes. git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1534 d5049fe3-3747-40f7-a4b5-f36d6801af5f
Lua
mit
ultijlam/ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale
8b326962c7d429024a80b6665fbdec0278902bf1
CCLib/src/java/lang/native/HashMap.lua
CCLib/src/java/lang/native/HashMap.lua
natives["java.util.HashMap"] = natives["java.util.HashMap"] or {} local tables = {} natives["java.util.HashMap"]["putHash(Ljava/lang/Object;ILjava/lang/Object;)Ljava/lang/Object;"] = function(this, key, hash, value) tables[this] = tables[this] or {} local bucket = tables[this][hash] local previous = nil if not bucket then bucket = {{key, value}} elseif #bucket == 1 then local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1] local ret, exception = jKeyEquals(key, bucket[1][1]) if exception then return nil, exception end if ret == 1 then bucket[1][2] = value else table.insert(bucket, {key, value}) end else local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1] local found = false for _, j in pairs(bucket) do local ret, exception = jKeyEquals(key, j[1]) if exception then return nil, exception end if ret == 1 then found = true previous = j[2] j[2] = value end end if not found then table.insert(bucket, {key, value}) end end tables[this][hash] = bucket end natives["java.util.HashMap"]["getHash(Ljava/lang/Object;I)Ljava/lang/Object;"] = function(this, key, hash) if tables[this] == nil then return nil end local bucket = tables[this][hash] if not bucket then return nil elseif #bucket == 1 then return bucket[1][2] else local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1] for _, i in pairs(bucket) do local ret, exc = jKeyEquals(key, i[1]) if exc then return nil, exc end if ret == 1 then return i[2] end end end end
natives["java.util.HashMap"] = natives["java.util.HashMap"] or {} local tables = setmetatable({}, {__mode = "k"}) natives["java.util.HashMap"]["putHash(Ljava/lang/Object;ILjava/lang/Object;)Ljava/lang/Object;"] = function(this, key, hash, value) tables[this] = tables[this] or {} local bucket = tables[this][hash] local previous = nil if not bucket then bucket = {{key, value}} elseif #bucket == 1 then local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1] local ret, exception = jKeyEquals(key, bucket[1][1]) if exception then return nil, exception end if ret == 1 then bucket[1][2] = value else table.insert(bucket, {key, value}) end else local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1] local found = false for _, j in pairs(bucket) do local ret, exception = jKeyEquals(key, j[1]) if exception then return nil, exception end if ret == 1 then found = true previous = j[2] j[2] = value end end if not found then table.insert(bucket, {key, value}) end end tables[this][hash] = bucket end natives["java.util.HashMap"]["getHash(Ljava/lang/Object;I)Ljava/lang/Object;"] = function(this, key, hash) if tables[this] == nil then return nil end local bucket = tables[this][hash] if not bucket then return nil elseif #bucket == 1 then return bucket[1][2] else local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1] for _, i in pairs(bucket) do local ret, exc = jKeyEquals(key, i[1]) if exc then return nil, exc end if ret == 1 then return i[2] end end end end
Fixed memory leak
Fixed memory leak
Lua
mit
apemanzilla/JVML-JIT,Team-CC-Corp/JVML-JIT
8f224a1685203bb71e12a0128a10b42fe353d675
lua/entities/base_starfall_entity/init.lua
lua/entities/base_starfall_entity/init.lua
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include( "shared.lua" ) function ENT:Initialize () baseclass.Get( "base_gmodentity" ).Initialize( self ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.instance = nil self.tableCopy = function ( t, lookup_table ) if ( t == nil ) then return nil end local copy = {} setmetatable( copy, debug.getmetatable( t ) ) for i, v in pairs( t ) do if ( not istable( v ) ) then copy[ i ] = v else lookup_table = lookup_table or {} lookup_table[ t ] = copy if lookup_table[ v ] then copy[ i ] = lookup_table[ v ] -- we already copied this table. reuse the copy. else copy[ i ] = table.Copy( v, lookup_table ) -- not yet copied. copy it. end end end return copy end end function ENT:OnRemove () if not self.instance then return end self.instance:deinitialize() self.instance = nil end function ENT:onRestore () end function ENT:BuildDupeInfo () -- Remove table.Copy fix when Garrysmod updates with @Xandaros patch. table.Copy = self.tableCopy return {} end function ENT:ApplyDupeInfo () return {} end function ENT:PreEntityCopy () local i = self:BuildDupeInfo() if i then duplicator.StoreEntityModifier( self, "SFDupeInfo", i ) end end function ENT:PostEntityPaste ( ply, ent ) if ent.EntityMods and ent.EntityMods.SFDupeInfo then ent:ApplyDupeInfo( ply, ent, ent.EntityMods.SFDupeInfo ) end end
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include( "shared.lua" ) function ENT:Initialize () baseclass.Get( "base_gmodentity" ).Initialize( self ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.instance = nil end function ENT:OnRemove () if not self.instance then return end self.instance:deinitialize() self.instance = nil end function ENT:onRestore () end function ENT:BuildDupeInfo () return {} end function ENT:ApplyDupeInfo () return {} end function ENT:PreEntityCopy () local i = self:BuildDupeInfo() if i then duplicator.StoreEntityModifier( self, "SFDupeInfo", i ) end end function ENT:PostEntityPaste ( ply, ent ) if ent.EntityMods and ent.EntityMods.SFDupeInfo then ent:ApplyDupeInfo( ply, ent, ent.EntityMods.SFDupeInfo ) end end
Remove table.Copy hack
Remove table.Copy hack This used to be necessary because the table.Copy function had a bug, which has since been fixed upstream. Fix #185
Lua
bsd-3-clause
Jazzelhawk/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall
503eca675eb8ae72362d4a1227d2d3f1ba87267d
src/plugins/finalcutpro/browser/selectlibrary.lua
src/plugins/finalcutpro/browser/selectlibrary.lua
--- === plugins.finalcutpro.browser.selectlibrary === --- --- Actions for selecting libraries local require = require local fcp = require "cp.apple.finalcutpro" local i18n = require "cp.i18n" local plugin = { id = "finalcutpro.browser.selectlibrary", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) local fcpxCmds = deps.fcpxCmds -------------------------------------------------------------------------------- -- Select Topmost Library in Browser: -------------------------------------------------------------------------------- fcpxCmds :add("selectTopmostLibraryInBrowser") :whenActivated(function() local libraries = fcp:libraries() local browser = fcp:browser() local sidebar = libraries:sidebar() browser:show() if not libraries:sidebar():isShowing() then browser:showLibraries():press() end libraries:sidebar():selectRowAt(1) libraries:sidebar():showRowAt(1) end) :titled(i18n("selectTopmostLibraryInBrowser")) -------------------------------------------------------------------------------- -- Select Active Library in Browser: -------------------------------------------------------------------------------- fcpxCmds :add("selectActiveLibraryInBrowser") :whenActivated(function() local libraries = fcp:libraries() local browser = fcp:browser() local sidebar = libraries:sidebar() browser:show() if not libraries:sidebar():isShowing() then browser:showLibraries():press() end local scrollArea = libraries:sidebar():UI() local outline = scrollArea and scrollArea[1] if outline and outline:attributeValue("AXRole") == "AXOutline" then local children = outline:attributeValue("AXChildren") if children then local foundSelected = false for i=#children, 1, -1 do local child = children[i] if child and child:attributeValue("AXSelected") then foundSelected = true end if foundSelected then if child and child:attributeValue("AXDisclosureLevel") == 0 then outline:setAttributeValue("AXSelectedRows", {child}) break end end end end end end) :titled(i18n("selectActiveLibraryInBrowser")) end return plugin
--- === plugins.finalcutpro.browser.selectlibrary === --- --- Actions for selecting libraries local require = require local fcp = require "cp.apple.finalcutpro" local i18n = require "cp.i18n" local plugin = { id = "finalcutpro.browser.selectlibrary", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) local fcpxCmds = deps.fcpxCmds -------------------------------------------------------------------------------- -- Select Topmost Library in Browser: -------------------------------------------------------------------------------- fcpxCmds :add("selectTopmostLibraryInBrowser") :whenActivated(function() local libraries = fcp:libraries() local browser = fcp:browser() local sidebar = libraries:sidebar() browser:show() if not sidebar:isShowing() then browser:showLibraries():press() end sidebar:selectRowAt(1) sidebar:showRowAt(1) end) :titled(i18n("selectTopmostLibraryInBrowser")) -------------------------------------------------------------------------------- -- Select Active Library in Browser: -------------------------------------------------------------------------------- fcpxCmds :add("selectActiveLibraryInBrowser") :whenActivated(function() local libraries = fcp:libraries() local browser = fcp:browser() local sidebar = libraries:sidebar() browser:show() if not sidebar:isShowing() then browser:showLibraries():press() end local scrollArea = sidebar:UI() local outline = scrollArea and scrollArea[1] if outline and outline:attributeValue("AXRole") == "AXOutline" then local children = outline:attributeValue("AXChildren") if children then local foundSelected = false for i=#children, 1, -1 do local child = children[i] if child and child:attributeValue("AXSelected") then foundSelected = true end if foundSelected then if child and child:attributeValue("AXDisclosureLevel") == 0 then outline:setAttributeValue("AXSelectedRows", {child}) break end end end end end end) :titled(i18n("selectActiveLibraryInBrowser")) end return plugin
Fixed @stickler-ci errors
Fixed @stickler-ci errors
Lua
mit
CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks
b69589fba337ac9c362e02d58c354b2e218900c7
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins.lua
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins.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.fs") require("luci.ip") mp = Map("olsrd", "OLSR - Plugins") p = mp:section(TypedSection, "LoadPlugin") p.addremove = true p.dynamic = true p.anonymous = true ign = p:option(Flag, "ignore") ign.enabled = "1" ign.disabled = "0" ign.optional = true lib = p:option(ListValue, "library", translate("library")) lib:value("") for k, v in pairs(luci.fs.dir("/usr/lib")) do if v:sub(1, 6) == "olsrd_" then lib:value(v) end end local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = luci.ip.IPv4(val[i]) or luci.ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s+])%s+([^%s+])")() local cidr if ip and mask and ip:match(":") then cidr = luci.ip.IPv6(ip, mask) elseif ip and mask then cidr = luci.ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf.so.1.5.3"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "eth1" } }, ["olsrd_dyn_gw.so.0.4"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo.so.0.1"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_nameservice.so.0.2"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" } }, ["olsrd_quagga.so.0.2.2"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure.so.0.5"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo.so.0.1"] = { { Value, "accept", "10.247.200.4" } } } -- build plugin options with dependencies for plugin, options in pairs(knownPlParams) do for _, option in ipairs(options) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end if otype == DynamicList then field:value( default ) end field.default = default field:depends({ library = plugin }) end end end return mp
--[[ 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.fs") require("luci.ip") mp = Map("olsrd", "OLSR - Plugins") p = mp:section(TypedSection, "LoadPlugin") p.addremove = true p.dynamic = true p.anonymous = true ign = p:option(Flag, "ignore") ign.enabled = "1" ign.disabled = "0" ign.optional = true lib = p:option(ListValue, "library", translate("library")) lib:value("") for k, v in pairs(luci.fs.dir("/usr/lib")) do if v:sub(1, 6) == "olsrd_" then lib:value(v) end end local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = luci.ip.IPv4(val[i]) or luci.ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s+])%s+([^%s+])")() local cidr if ip and mask and ip:match(":") then cidr = luci.ip.IPv6(ip, mask) elseif ip and mask then cidr = luci.ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf.so.1.5.3"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "eth1" } }, ["olsrd_dyn_gw.so.0.4"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo.so.0.1"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_nameservice.so.0.3"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" } }, ["olsrd_quagga.so.0.2.2"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure.so.0.5"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo.so.0.1"] = { { Value, "accept", "10.247.200.4" } } } -- build plugin options with dependencies for plugin, options in pairs(knownPlParams) do for _, option in ipairs(options) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.optional = true bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end if otype == DynamicList then field:value( default ) end field.optional = true field.default = default field:depends({ library = plugin }) end end end return mp
* luci/app-olsr: further fixes in olsr plugins config
* luci/app-olsr: further fixes in olsr plugins config
Lua
apache-2.0
kuoruan/luci,palmettos/cnLuCI,nwf/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,aa65535/luci,remakeelectric/luci,chris5560/openwrt-luci,bittorf/luci,remakeelectric/luci,artynet/luci,obsy/luci,zhaoxx063/luci,keyidadi/luci,florian-shellfire/luci,palmettos/cnLuCI,maxrio/luci981213,thesabbir/luci,slayerrensky/luci,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,remakeelectric/luci,Kyklas/luci-proto-hso,zhaoxx063/luci,schidler/ionic-luci,jorgifumi/luci,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,cappiewu/luci,schidler/ionic-luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,Hostle/luci,jorgifumi/luci,981213/luci-1,kuoruan/lede-luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,artynet/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,teslamint/luci,keyidadi/luci,ff94315/luci-1,lcf258/openwrtcn,cshore-firmware/openwrt-luci,palmettos/cnLuCI,tobiaswaldvogel/luci,artynet/luci,Sakura-Winkey/LuCI,keyidadi/luci,daofeng2015/luci,Noltari/luci,cshore/luci,harveyhu2012/luci,oyido/luci,Noltari/luci,Kyklas/luci-proto-hso,opentechinstitute/luci,RuiChen1113/luci,teslamint/luci,aa65535/luci,thess/OpenWrt-luci,shangjiyu/luci-with-extra,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,dismantl/luci-0.12,NeoRaider/luci,openwrt/luci,daofeng2015/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,wongsyrone/luci-1,palmettos/cnLuCI,lcf258/openwrtcn,Kyklas/luci-proto-hso,rogerpueyo/luci,jorgifumi/luci,deepak78/new-luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,taiha/luci,mumuqz/luci,LuttyYang/luci,nmav/luci,lcf258/openwrtcn,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,lcf258/openwrtcn,schidler/ionic-luci,deepak78/new-luci,rogerpueyo/luci,urueedi/luci,teslamint/luci,aa65535/luci,palmettos/cnLuCI,sujeet14108/luci,oneru/luci,thesabbir/luci,shangjiyu/luci-with-extra,aa65535/luci,hnyman/luci,deepak78/new-luci,RuiChen1113/luci,oyido/luci,lbthomsen/openwrt-luci,maxrio/luci981213,nwf/openwrt-luci,chris5560/openwrt-luci,male-puppies/luci,hnyman/luci,harveyhu2012/luci,oneru/luci,maxrio/luci981213,chris5560/openwrt-luci,mumuqz/luci,wongsyrone/luci-1,taiha/luci,openwrt-es/openwrt-luci,joaofvieira/luci,nmav/luci,oneru/luci,opentechinstitute/luci,slayerrensky/luci,jlopenwrtluci/luci,oyido/luci,kuoruan/lede-luci,cappiewu/luci,bittorf/luci,obsy/luci,male-puppies/luci,maxrio/luci981213,981213/luci-1,florian-shellfire/luci,fkooman/luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,ff94315/luci-1,zhaoxx063/luci,mumuqz/luci,jchuang1977/luci-1,mumuqz/luci,shangjiyu/luci-with-extra,forward619/luci,lbthomsen/openwrt-luci,nmav/luci,jorgifumi/luci,zhaoxx063/luci,slayerrensky/luci,nwf/openwrt-luci,openwrt-es/openwrt-luci,teslamint/luci,david-xiao/luci,cappiewu/luci,RuiChen1113/luci,kuoruan/lede-luci,mumuqz/luci,teslamint/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,palmettos/test,forward619/luci,bright-things/ionic-luci,MinFu/luci,kuoruan/lede-luci,NeoRaider/luci,nmav/luci,fkooman/luci,joaofvieira/luci,slayerrensky/luci,MinFu/luci,shangjiyu/luci-with-extra,palmettos/cnLuCI,Hostle/luci,Noltari/luci,dwmw2/luci,Sakura-Winkey/LuCI,remakeelectric/luci,keyidadi/luci,oyido/luci,Hostle/luci,obsy/luci,RuiChen1113/luci,thess/OpenWrt-luci,Wedmer/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,wongsyrone/luci-1,marcel-sch/luci,oyido/luci,kuoruan/luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,daofeng2015/luci,981213/luci-1,ollie27/openwrt_luci,ollie27/openwrt_luci,Noltari/luci,jlopenwrtluci/luci,thesabbir/luci,marcel-sch/luci,cshore/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,dwmw2/luci,slayerrensky/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,sujeet14108/luci,cshore/luci,cappiewu/luci,teslamint/luci,lbthomsen/openwrt-luci,palmettos/test,bright-things/ionic-luci,thess/OpenWrt-luci,fkooman/luci,wongsyrone/luci-1,remakeelectric/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,maxrio/luci981213,LuttyYang/luci,tobiaswaldvogel/luci,palmettos/test,artynet/luci,jlopenwrtluci/luci,cshore/luci,cshore-firmware/openwrt-luci,Noltari/luci,981213/luci-1,teslamint/luci,Hostle/luci,ollie27/openwrt_luci,oneru/luci,NeoRaider/luci,Noltari/luci,thesabbir/luci,kuoruan/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,obsy/luci,florian-shellfire/luci,cappiewu/luci,david-xiao/luci,bright-things/ionic-luci,tcatm/luci,nmav/luci,cappiewu/luci,thesabbir/luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,fkooman/luci,MinFu/luci,Wedmer/luci,NeoRaider/luci,obsy/luci,zhaoxx063/luci,tcatm/luci,urueedi/luci,mumuqz/luci,artynet/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,forward619/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,cshore-firmware/openwrt-luci,daofeng2015/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,jorgifumi/luci,hnyman/luci,zhaoxx063/luci,Wedmer/luci,LuttyYang/luci,ff94315/luci-1,schidler/ionic-luci,kuoruan/luci,urueedi/luci,slayerrensky/luci,kuoruan/lede-luci,joaofvieira/luci,david-xiao/luci,jorgifumi/luci,dismantl/luci-0.12,wongsyrone/luci-1,chris5560/openwrt-luci,rogerpueyo/luci,dwmw2/luci,marcel-sch/luci,obsy/luci,MinFu/luci,oyido/luci,keyidadi/luci,kuoruan/luci,bright-things/ionic-luci,obsy/luci,slayerrensky/luci,oneru/luci,cshore/luci,dwmw2/luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,marcel-sch/luci,dwmw2/luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,artynet/luci,florian-shellfire/luci,openwrt/luci,kuoruan/luci,maxrio/luci981213,obsy/luci,MinFu/luci,schidler/ionic-luci,jlopenwrtluci/luci,bittorf/luci,dismantl/luci-0.12,Noltari/luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,shangjiyu/luci-with-extra,Kyklas/luci-proto-hso,kuoruan/luci,cshore/luci,sujeet14108/luci,Sakura-Winkey/LuCI,nmav/luci,florian-shellfire/luci,fkooman/luci,kuoruan/lede-luci,ff94315/luci-1,urueedi/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,nmav/luci,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,kuoruan/luci,LuttyYang/luci,jlopenwrtluci/luci,fkooman/luci,openwrt/luci,male-puppies/luci,marcel-sch/luci,nmav/luci,LuttyYang/luci,david-xiao/luci,chris5560/openwrt-luci,sujeet14108/luci,artynet/luci,hnyman/luci,daofeng2015/luci,nwf/openwrt-luci,MinFu/luci,lbthomsen/openwrt-luci,nwf/openwrt-luci,RuiChen1113/luci,jchuang1977/luci-1,NeoRaider/luci,MinFu/luci,tcatm/luci,ff94315/luci-1,ff94315/luci-1,joaofvieira/luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,joaofvieira/luci,Hostle/luci,taiha/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,hnyman/luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,lcf258/openwrtcn,mumuqz/luci,palmettos/test,wongsyrone/luci-1,tcatm/luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,taiha/luci,jchuang1977/luci-1,deepak78/new-luci,MinFu/luci,nwf/openwrt-luci,dwmw2/luci,nmav/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,LuttyYang/luci,tcatm/luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,thess/OpenWrt-luci,rogerpueyo/luci,forward619/luci,artynet/luci,ff94315/luci-1,joaofvieira/luci,male-puppies/luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,taiha/luci,slayerrensky/luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,Sakura-Winkey/LuCI,schidler/ionic-luci,Wedmer/luci,bright-things/ionic-luci,dismantl/luci-0.12,hnyman/luci,tobiaswaldvogel/luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,Wedmer/luci,Wedmer/luci,oyido/luci,opentechinstitute/luci,david-xiao/luci,deepak78/new-luci,sujeet14108/luci,wongsyrone/luci-1,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,urueedi/luci,bittorf/luci,thesabbir/luci,urueedi/luci,RuiChen1113/luci,harveyhu2012/luci,bittorf/luci,Sakura-Winkey/LuCI,ollie27/openwrt_luci,urueedi/luci,teslamint/luci,981213/luci-1,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,mumuqz/luci,remakeelectric/luci,harveyhu2012/luci,fkooman/luci,male-puppies/luci,remakeelectric/luci,oyido/luci,Noltari/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,david-xiao/luci,aa65535/luci,openwrt/luci,bright-things/ionic-luci,981213/luci-1,openwrt-es/openwrt-luci,palmettos/test,openwrt/luci,cshore/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,forward619/luci,remakeelectric/luci,bittorf/luci,dwmw2/luci,Wedmer/luci,david-xiao/luci,thesabbir/luci,openwrt/luci,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,chris5560/openwrt-luci,male-puppies/luci,oneru/luci,harveyhu2012/luci,male-puppies/luci,jlopenwrtluci/luci,dismantl/luci-0.12,Wedmer/luci,hnyman/luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,tobiaswaldvogel/luci,thess/OpenWrt-luci,taiha/luci,joaofvieira/luci,openwrt/luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,bright-things/ionic-luci,sujeet14108/luci,schidler/ionic-luci,opentechinstitute/luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,openwrt/luci,male-puppies/luci,cshore/luci,opentechinstitute/luci,palmettos/test,keyidadi/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,Kyklas/luci-proto-hso,dwmw2/luci,NeoRaider/luci,urueedi/luci,rogerpueyo/luci,nwf/openwrt-luci,openwrt-es/openwrt-luci,opentechinstitute/luci,cappiewu/luci,Hostle/luci,fkooman/luci,lcf258/openwrtcn,daofeng2015/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,bittorf/luci,981213/luci-1,keyidadi/luci,tcatm/luci,thesabbir/luci,sujeet14108/luci,cshore-firmware/openwrt-luci,forward619/luci,taiha/luci,thess/OpenWrt-luci,palmettos/cnLuCI,lcf258/openwrtcn,marcel-sch/luci,chris5560/openwrt-luci,harveyhu2012/luci,florian-shellfire/luci,florian-shellfire/luci,bittorf/luci,tcatm/luci,daofeng2015/luci,RuiChen1113/luci,cappiewu/luci,aa65535/luci,marcel-sch/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,daofeng2015/luci,aircross/OpenWrt-Firefly-LuCI,deepak78/new-luci,aa65535/luci,forward619/luci,david-xiao/luci,taiha/luci,NeoRaider/luci,Kyklas/luci-proto-hso,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso
b182505d46c54573706c9d2f78a1d021f8c2949f
share/lua/website/audioboo.lua
share/lua/website/audioboo.lua
-- libquvi-scripts -- Copyright (C) 2011 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident (self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "audioboo%.fm" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/boos/%d+%-"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse (self) self.host_id = "audioboo" local oe_url = "http://audioboo.fm/publishing/oembed.json?url=" .. self.page_url local oe = quvi.fetch(oe_url, {fetch_type='config'}) self.title = oe:match('"title":"(.-)"') or error('no match: media title') self.thumbnail_url = oe:match('"thumbnail_url":"(.-)"') or '' self.id = oe:match('id=."boo_embed_(.-)."') or error('no match: media id') self.url = {oe:match('a href=."(.-)."') or error('no match: media url')} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2011-2012 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident (self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "audioboo%.fm" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/boos/%d+%-"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse (self) self.host_id = "audioboo" self.id = self.page_url:match('/boos/(%d+)%-') or error('no match: media ID') local p = quvi.fetch(self.page_url) self.title = p:match('.+content=[\'"](.-)[\'"]%s+property=[\'"]og:title[\'"]') or error('no match: media title') self.thumbnail_url = p:match('.+content=[\'"](.-)[\'"]%s+property=[\'"]og:image[\'"]') or '' self.url = { p:match('.+content=[\'"](.-)[\'"]%s+property=[\'"]og:audio[\'"]') or error('no match: media stream URL') } return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: audioboo.lua: multiple patterns
FIX: audioboo.lua: multiple patterns Fix {title,id,thumbnail,stream} patterns. Parse from the contents of the media URL instead of oembed which no longer appears to provide the media stream URL. Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
Lua
agpl-3.0
alech/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts
f2d38336c17832137962356313a1cefe674ca400
frontend/apps/reader/modules/readerwikipedia.lua
frontend/apps/reader/modules/readerwikipedia.lua
local ReaderDictionary = require("apps/reader/modules/readerdictionary") local EventListener = require("ui/widget/eventlistener") local NetworkMgr = require("ui/networkmgr") local Translator = require("ui/translator") local Wikipedia = require("ui/wikipedia") local UIManager = require("ui/uimanager") local Geom = require("ui/geometry") local Screen = require("device").screen local DEBUG = require("dbg") local _ = require("gettext") -- Wikipedia as a special dictionary local ReaderWikipedia = ReaderDictionary:extend{ -- identify itself wiki = true, no_page = _("No wiki page found."), } -- the super "class" ReaderDictionary has already registers a menu entry -- we should override the init function in ReaderWikipedia function ReaderWikipedia:init() end function ReaderWikipedia:onLookupWikipedia(word, box) -- detect language of the text local ok, lang = pcall(Translator.detect, Translator, word) -- prompt users to turn on Wifi if network is unreachable if not ok and lang and lang:find("Network is unreachable") then NetworkMgr:promptWifiOn() return end -- convert "zh-CN" and "zh-TW" to "zh" lang = lang:match("(.*)-") or lang -- strip punctuation characters around selected word word = string.gsub(word, "^%p+", '') word = string.gsub(word, "%p+$", '') -- seems lower case phrase has higher hit rate word = string.lower(word) local results = {} local ok, pages = pcall(Wikipedia.wikintro, Wikipedia, word, lang) if ok and pages then for pageid, page in pairs(pages) do local result = { dict = _("Wikipedia"), word = page.title, definition = page.extract or self.no_page, } table.insert(results, result) end DEBUG("lookup result:", word, results) self:showDict(word, results, box) else DEBUG("error:", pages) -- dummy results results = { { dict = _("Wikipedia"), word = word, definition = self.no_page, } } DEBUG("dummy result table:", word, results) self:showDict(word, results, box) end end -- override onSaveSettings in ReaderDictionary function ReaderWikipedia:onSaveSettings() end return ReaderWikipedia
local ReaderDictionary = require("apps/reader/modules/readerdictionary") local EventListener = require("ui/widget/eventlistener") local NetworkMgr = require("ui/networkmgr") local Translator = require("ui/translator") local Wikipedia = require("ui/wikipedia") local UIManager = require("ui/uimanager") local Geom = require("ui/geometry") local Screen = require("device").screen local DEBUG = require("dbg") local _ = require("gettext") -- Wikipedia as a special dictionary local ReaderWikipedia = ReaderDictionary:extend{ -- identify itself wiki = true, no_page = _("No wiki page found."), } -- the super "class" ReaderDictionary has already registers a menu entry -- we should override the init function in ReaderWikipedia function ReaderWikipedia:init() end function ReaderWikipedia:onLookupWikipedia(word, box) -- detect language of the text local ok, lang = pcall(Translator.detect, Translator, word) if not ok then return end -- convert "zh-CN" and "zh-TW" to "zh" lang = lang:match("(.*)-") or lang -- strip punctuation characters around selected word word = string.gsub(word, "^%p+", '') word = string.gsub(word, "%p+$", '') -- seems lower case phrase has higher hit rate word = string.lower(word) local results = {} local ok, pages = pcall(Wikipedia.wikintro, Wikipedia, word, lang) if ok and pages then for pageid, page in pairs(pages) do local result = { dict = _("Wikipedia"), word = page.title, definition = page.extract or self.no_page, } table.insert(results, result) end DEBUG("lookup result:", word, results) self:showDict(word, results, box) else DEBUG("error:", pages) -- dummy results results = { { dict = _("Wikipedia"), word = word, definition = self.no_page, } } DEBUG("dummy result table:", word, results) self:showDict(word, results, box) end end -- override onSaveSettings in ReaderDictionary function ReaderWikipedia:onSaveSettings() end return ReaderWikipedia
fix #1642 GFW block in China may also cause Network unavailable error
fix #1642 GFW block in China may also cause Network unavailable error
Lua
agpl-3.0
koreader/koreader,Frenzie/koreader,koreader/koreader,NiLuJe/koreader,Frenzie/koreader,apletnev/koreader,poire-z/koreader,lgeek/koreader,Markismus/koreader,houqp/koreader,chihyang/koreader,poire-z/koreader,robert00s/koreader,mwoz123/koreader,mihailim/koreader,frankyifei/koreader,Hzj-jie/koreader,NickSavage/koreader,pazos/koreader,NiLuJe/koreader
02db33e9b3330e194c39bc6d3090609299579f15
src/haka/lua/utils.lua
src/haka/lua/utils.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/. function sorted_pairs(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end function safe_string(str) local len = #str local sstr = {} for i=1,len do local b = str:byte(i) if b >= 0x20 and b <= 0x7e then sstr[i] = string.char(b) else sstr[i] = string.format('\\x%x', b) end end return table.concat(sstr) 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/. function sorted_pairs(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end function safe_string(str) local len = #str local sstr = {} for i=1,len do local b = str:byte(i) if b >= 0x20 and b <= 0x7e then sstr[i] = string.char(b) else sstr[i] = string.format('\\x%x', b) end end return table.concat(sstr) end
Fix code formating
Fix code formating
Lua
mpl-2.0
nabilbendafi/haka,haka-security/haka,nabilbendafi/haka,LubyRuffy/haka,LubyRuffy/haka,Wingless-Archangel/haka,haka-security/haka,haka-security/haka,lcheylus/haka,lcheylus/haka,Wingless-Archangel/haka,nabilbendafi/haka,lcheylus/haka
c855494ba03d2b29c15473d43e367715ed1650a7
reader.lua
reader.lua
#!./luajit io.stdout:write([[ --------------------------------------------- launching... _ _____ ____ _ | |/ / _ \| _ \ ___ __ _ __| | ___ _ __ | ' / | | | |_) / _ \/ _` |/ _` |/ _ \ '__| | . \ |_| | _ < __/ (_| | (_| | __/ | |_|\_\___/|_| \_\___|\__,_|\__,_|\___|_| [*] Current time: ]], os.date("%x-%X"), "\n\n") io.stdout:flush() -- load default settings require("defaults") local DataStorage = require("datastorage") pcall(dofile, DataStorage:getDataDir() .. "/defaults.persistent.lua") require("setupkoenv") -- read settings and check for language override -- has to be done before requiring other files because -- they might call gettext on load G_reader_settings = require("luasettings"):open( DataStorage:getDataDir().."/settings.reader.lua") local lang_locale = G_reader_settings:readSetting("language") local _ = require("gettext") if lang_locale then _.changeLang(lang_locale) end -- option parsing: local longopts = { debug = "d", profile = "p", help = "h", } local function showusage() print("usage: ./reader.lua [OPTION] ... path") print("Read all the books on your E-Ink reader") print("") print("-d start in debug mode") print("-v debug in verbose mode") print("-p enable Lua code profiling") print("-h show this usage help") print("") print("If you give the name of a directory instead of a file path, a file") print("chooser will show up and let you select a file") print("") print("If you don't pass any path, the last viewed document will be opened") print("") print("This software is licensed under the AGPLv3.") print("See http://github.com/koreader/koreader for more info.") end -- should check DEBUG option in arg and turn on DEBUG before loading other -- modules, otherwise DEBUG in some modules may not be printed. local dbg = require("dbg") if G_reader_settings:readSetting("debug") then dbg:turnOn() end local Profiler = nil local ARGV = arg local argidx = 1 while argidx <= #ARGV do local arg = ARGV[argidx] argidx = argidx + 1 if arg == "--" then break end -- parse longopts if arg:sub(1,2) == "--" then local opt = longopts[arg:sub(3)] if opt ~= nil then arg = "-"..opt end end -- code for each option if arg == "-h" then return showusage() elseif arg == "-d" then dbg:turnOn() elseif arg == "-v" then dbg:setVerbose(true) elseif arg == "-p" then Profiler = require("jit.p") Profiler.start("la") else -- not a recognized option, should be a filename argidx = argidx - 1 break end end local lfs = require("libs/libkoreader-lfs") local UIManager = require("ui/uimanager") local Device = require("device") local Font = require("ui/font") -- read some global reader setting here: -- font local fontmap = G_reader_settings:readSetting("fontmap") if fontmap ~= nil then for k, v in pairs(fontmap) do Font.fontmap[k] = v end end -- last file local last_file = G_reader_settings:readSetting("lastfile") if last_file and lfs.attributes(last_file, "mode") ~= "file" then last_file = nil end -- load last opened file local open_last = G_reader_settings:readSetting("open_last") -- night mode if G_reader_settings:readSetting("night_mode") then Device.screen:toggleNightMode() end -- restore kobo frontlight settings and probe kobo touch coordinates if Device:isKobo() then if Device:hasFrontlight() then local powerd = Device:getPowerDevice() if powerd and powerd.restore_settings then -- UIManager:init() should have sanely set up the frontlight_stuff by this point local intensity = G_reader_settings:readSetting("frontlight_intensity") powerd.fl_intensity = intensity or powerd.fl_intensity local is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on") if is_frontlight_on then -- default powerd.is_fl_on is false, turn it on powerd:toggleFrontlight() else -- the light can still be turned on manually outside of KOReader -- or Nickel. so we always set the intensity to 0 here to keep it -- in sync with powerd.is_fl_on (false by default) -- NOTE: we cant use setIntensity method here because for Kobo the -- min intensity is 1 :( powerd.fl:setBrightness(0) end end end end if Device:needsTouchScreenProbe() then Device:touchScreenProbe() end if ARGV[argidx] and ARGV[argidx] ~= "" then local file = nil if lfs.attributes(ARGV[argidx], "mode") == "file" then file = ARGV[argidx] elseif open_last and last_file then file = last_file end -- if file is given in command line argument or open last document is set -- true, the given file or the last file is opened in the reader if file then local ReaderUI = require("apps/reader/readerui") UIManager:nextTick(function() ReaderUI:showReader(file) end) -- we assume a directory is given in command line argument -- the filemanger will show the files in that path else local FileManager = require("apps/filemanager/filemanager") local home_dir = G_reader_settings:readSetting("home_dir") or ARGV[argidx] UIManager:nextTick(function() FileManager:showFiles(home_dir) end) end UIManager:run() elseif last_file then local ReaderUI = require("apps/reader/readerui") UIManager:nextTick(function() ReaderUI:showReader(last_file) end) UIManager:run() else return showusage() end local function exitReader() local ReaderActivityIndicator = require("apps/reader/modules/readeractivityindicator") G_reader_settings:close() -- Close lipc handles ReaderActivityIndicator:coda() -- shutdown hardware abstraction Device:exit() require("ui/network/manager"):turnOffWifi() if Profiler then Profiler.stop() end os.exit(0) end exitReader()
#!./luajit io.stdout:write([[ --------------------------------------------- launching... _ _____ ____ _ | |/ / _ \| _ \ ___ __ _ __| | ___ _ __ | ' / | | | |_) / _ \/ _` |/ _` |/ _ \ '__| | . \ |_| | _ < __/ (_| | (_| | __/ | |_|\_\___/|_| \_\___|\__,_|\__,_|\___|_| [*] Current time: ]], os.date("%x-%X"), "\n\n") io.stdout:flush() -- load default settings require("defaults") local DataStorage = require("datastorage") pcall(dofile, DataStorage:getDataDir() .. "/defaults.persistent.lua") require("setupkoenv") -- read settings and check for language override -- has to be done before requiring other files because -- they might call gettext on load G_reader_settings = require("luasettings"):open( DataStorage:getDataDir().."/settings.reader.lua") local lang_locale = G_reader_settings:readSetting("language") local _ = require("gettext") if lang_locale then _.changeLang(lang_locale) end -- option parsing: local longopts = { debug = "d", profile = "p", help = "h", } local function showusage() print("usage: ./reader.lua [OPTION] ... path") print("Read all the books on your E-Ink reader") print("") print("-d start in debug mode") print("-v debug in verbose mode") print("-p enable Lua code profiling") print("-h show this usage help") print("") print("If you give the name of a directory instead of a file path, a file") print("chooser will show up and let you select a file") print("") print("If you don't pass any path, the last viewed document will be opened") print("") print("This software is licensed under the AGPLv3.") print("See http://github.com/koreader/koreader for more info.") end -- should check DEBUG option in arg and turn on DEBUG before loading other -- modules, otherwise DEBUG in some modules may not be printed. local dbg = require("dbg") if G_reader_settings:readSetting("debug") then dbg:turnOn() end local Profiler = nil local ARGV = arg local argidx = 1 while argidx <= #ARGV do local arg = ARGV[argidx] argidx = argidx + 1 if arg == "--" then break end -- parse longopts if arg:sub(1,2) == "--" then local opt = longopts[arg:sub(3)] if opt ~= nil then arg = "-"..opt end end -- code for each option if arg == "-h" then return showusage() elseif arg == "-d" then dbg:turnOn() elseif arg == "-v" then dbg:setVerbose(true) elseif arg == "-p" then Profiler = require("jit.p") Profiler.start("la") else -- not a recognized option, should be a filename argidx = argidx - 1 break end end local lfs = require("libs/libkoreader-lfs") local UIManager = require("ui/uimanager") local Device = require("device") local Font = require("ui/font") -- read some global reader setting here: -- font local fontmap = G_reader_settings:readSetting("fontmap") if fontmap ~= nil then for k, v in pairs(fontmap) do Font.fontmap[k] = v end end -- last file local last_file = G_reader_settings:readSetting("lastfile") if last_file and lfs.attributes(last_file, "mode") ~= "file" then last_file = nil end -- load last opened file local open_last = G_reader_settings:readSetting("open_last") -- night mode if G_reader_settings:readSetting("night_mode") then Device.screen:toggleNightMode() end -- restore kobo frontlight settings and probe kobo touch coordinates if Device:isKobo() then if Device:hasFrontlight() then local powerd = Device:getPowerDevice() if powerd and powerd.restore_settings then -- UIManager:init() should have sanely set up the frontlight_stuff by this point local intensity = G_reader_settings:readSetting("frontlight_intensity") powerd.fl_intensity = intensity or powerd.fl_intensity local is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on") if is_frontlight_on then -- default powerd.is_fl_on is false, turn it on powerd:toggleFrontlight() else -- the light can still be turned on manually outside of KOReader -- or Nickel. so we always set the intensity to 0 here to keep it -- in sync with powerd.is_fl_on (false by default) -- NOTE: we cant use setIntensity method here because for Kobo the -- min intensity is 1 :( powerd.fl:setBrightness(0) end end end end if Device:needsTouchScreenProbe() then Device:touchScreenProbe() end if ARGV[argidx] and ARGV[argidx] ~= "" then local file = nil if lfs.attributes(ARGV[argidx], "mode") == "file" then file = ARGV[argidx] elseif open_last and last_file then file = last_file end -- if file is given in command line argument or open last document is set -- true, the given file or the last file is opened in the reader if file then local ReaderUI = require("apps/reader/readerui") UIManager:nextTick(function() ReaderUI:showReader(file) end) -- we assume a directory is given in command line argument -- the filemanger will show the files in that path else local FileManager = require("apps/filemanager/filemanager") local home_dir = G_reader_settings:readSetting("home_dir") or ARGV[argidx] UIManager:nextTick(function() FileManager:showFiles(home_dir) end) end UIManager:run() elseif last_file then local ReaderUI = require("apps/reader/readerui") UIManager:nextTick(function() ReaderUI:showReader(last_file) end) UIManager:run() else return showusage() end local function exitReader() local ReaderActivityIndicator = require("apps/reader/modules/readeractivityindicator") G_reader_settings:close() -- Close lipc handles ReaderActivityIndicator:coda() -- shutdown hardware abstraction Device:exit() if Profiler then Profiler.stop() end os.exit(0) end exitReader()
Minor: don't turn off wifi on exit
Minor: don't turn off wifi on exit This fixes #2379 and #2511.
Lua
agpl-3.0
houqp/koreader,NiLuJe/koreader,koreader/koreader,poire-z/koreader,apletnev/koreader,Frenzie/koreader,NiLuJe/koreader,mwoz123/koreader,pazos/koreader,poire-z/koreader,Hzj-jie/koreader,lgeek/koreader,koreader/koreader,robert00s/koreader,Markismus/koreader,mihailim/koreader,Frenzie/koreader