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
d78e86c1bc9dbbff45973be3c12d3d7ef52940c2
test_scripts/RC/Capabilities/005_Resend_only_supported_parameters.lua
test_scripts/RC/Capabilities/005_Resend_only_supported_parameters.lua
--------------------------------------------------------------------------------------------------- -- User story: https://github.com/smartdevicelink/sdl_requirements/issues/1 -- Use case: https://github.com/smartdevicelink/sdl_requirements/blob/master/detailed_docs/detailed_info_GetSystemCapability.md -- Item: Use Case 1:Exception 3.3 -- -- Requirement summary: -- [SDL_RC] Set available control module settings SetInteriorVehicleData -- -- Description: -- In case: -- 1) SDL receive several supported Radio parameters in GetCapabilites response -- SDL must: -- 1) Transfer to HMI remote control RPCs only with supported parameters and -- 2) Reject any request for RADIO with unsupported parameters with UNSUPPORTED_RESOURCE result code, success: false --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') local common_functions = require('user_modules/shared_testcases/commonTestCases') --[[ Local Variables ]] local radio_capabilities = {{moduleName = "Radio", radioFrequencyAvailable = true, radioBandAvailable = true}} local rc_capabilities = commonRC.buildHmiRcCapabilities(commonRC.DEFAULT, radio_capabilities, commonRC.DEFAULT) local available_params = { moduleType = "RADIO", radioControlData = {frequencyInteger = 1, frequencyFraction = 2, band = "AM"} } local absent_params = {moduleType = "RADIO", radioControlData = {frequencyInteger = 1, frequencyFraction = 2}} --[[ Local Functions ]] local function setVehicleData(params, self) local cid = self.mobileSession1:SendRPC("SetInteriorVehicleData", {moduleData = params}) if params.radioControlData.frequencyInteger then EXPECT_HMICALL("RC.SetInteriorVehicleData", { appID = commonRC.getHMIAppId(1), moduleData = params}) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { moduleData = params}) end) self.mobileSession1:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) else EXPECT_HMICALL("RC.SetInteriorVehicleData"):Times(0) self.mobileSession1:ExpectResponse(cid, { success = false, resultCode = "UNSUPPORTED_RESOURCE" }) common_functions.DelayedExp(commonRC.timeout) end end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start, {rc_capabilities}) runner.Step("RAI, PTU", commonRC.rai_ptu) runner.Step("Activate_App", commonRC.activate_app) runner.Title("Test") for _, module_name in pairs({"CLIMATE", "RADIO"}) do runner.Step("GetInteriorVehicleData for " .. module_name, commonRC.subscribeToModule, {module_name, 1}) runner.Step("ButtonPress for " .. module_name, commonRC.rpcAllowed, {module_name, 1, "ButtonPress"}) end runner.Step("SetInteriorVehicleData processed for several supported params", setVehicleData, { available_params }) runner.Step("SetInteriorVehicleData rejected with unsupported parameter", setVehicleData, { absent_params }) runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
--------------------------------------------------------------------------------------------------- -- User story: https://github.com/smartdevicelink/sdl_requirements/issues/1 -- Use case: https://github.com/smartdevicelink/sdl_requirements/blob/master/detailed_docs/detailed_info_GetSystemCapability.md -- Item: Use Case 1:Exception 3.3 -- -- Requirement summary: -- [SDL_RC] Set available control module settings SetInteriorVehicleData -- -- Description: -- In case: -- 1) SDL receive several supported Radio parameters in GetCapabilites response -- SDL must: -- 1) Transfer to HMI remote control RPCs only with supported parameters and -- 2) Reject any request for RADIO with unsupported parameters with UNSUPPORTED_RESOURCE result code, success: false --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') local common_functions = require('user_modules/shared_testcases/commonTestCases') --[[ Local Variables ]] local radio_capabilities = {{moduleName = "Radio", radioFrequencyAvailable = true}} local rc_capabilities = commonRC.buildHmiRcCapabilities(commonRC.DEFAULT, radio_capabilities, commonRC.DEFAULT) local available_params = { moduleType = "RADIO", radioControlData = {frequencyInteger = 1, frequencyFraction = 2} } local absent_params = {moduleType = "RADIO", radioControlData = {band = "AM"}} --[[ Local Functions ]] local function setVehicleData(params, self) local cid = self.mobileSession1:SendRPC("SetInteriorVehicleData", {moduleData = params}) if params.radioControlData.frequencyInteger then EXPECT_HMICALL("RC.SetInteriorVehicleData", { appID = commonRC.getHMIAppId(1), moduleData = params}) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { moduleData = params}) end) self.mobileSession1:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) else EXPECT_HMICALL("RC.SetInteriorVehicleData"):Times(0) self.mobileSession1:ExpectResponse(cid, { success = false, resultCode = "UNSUPPORTED_RESOURCE" }) common_functions:DelayedExp(commonRC.timeout) end end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start, {rc_capabilities}) runner.Step("RAI, PTU", commonRC.rai_ptu) runner.Step("Activate_App", commonRC.activate_app) runner.Title("Test") for _, module_name in pairs({"CLIMATE", "RADIO"}) do runner.Step("GetInteriorVehicleData for " .. module_name, commonRC.subscribeToModule, {module_name, 1}) runner.Step("ButtonPress for " .. module_name, commonRC.rpcAllowed, {module_name, 1, "ButtonPress"}) end runner.Step("SetInteriorVehicleData processed for several supported params", setVehicleData, { available_params }) runner.Step("SetInteriorVehicleData rejected with unsupported parameter", setVehicleData, { absent_params }) runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
Remove Band from supported params. Fix common_functions typo.
Remove Band from supported params. Fix common_functions typo. Remove Band from supported params. Fix common_functions typo.
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
6d83b0e5748348962b8b4a248b4a1de202d723b1
bin/process/PoolTestData.lua
bin/process/PoolTestData.lua
-- -- User: pat -- Date: 2/10/16 -- require 'nn' local cmd = torch.CmdLine() cmd:option('-inFile', '', 'input file') cmd:option('-keyFile', '', 'file that maps entity pairs to relations') cmd:option('-outFile', '', 'out file') local params = cmd:parse(arg) -- load key file int map print('Loading ep-rel map from ' .. params.keyFile) local key = torch.load(params.keyFile) local ep_rel_map = {} for a, dat in pairs(key) do if dat and torch.type(dat) == 'table' and dat.ep then for i = 1, dat.ep:size(1) do ep_rel_map[dat.ep[i]] = dat.seq:narrow(1,i,1) end end end print('Converting data from ' .. params.inFile .. ' and exporting to ' .. params.outFile) local data = torch.load(params.inFile)[1] local mapped_data = {} local missing = 0 for i = 1, data.ep:size(1) do local ep = data.ep[i][1] local rels = ep_rel_map[ep] if rels then local seq = rels:size(2) local label = data.label[i] local kb_rel = data.rel[i] if not mapped_data[seq] then mapped_data[seq] = {col_seq={}, label ={}, row_seq ={}} end -- table.insert(mapped_data[seq].ep, ep) table.insert(mapped_data[seq].col_seq, rels) table.insert(mapped_data[seq].label, label) table.insert(mapped_data[seq].row_seq, kb_rel) else missing = missing + 1 end end print('couldnt map ' .. missing .. ' entity pairs') for len, data in pairs(mapped_data) do mapped_data[len].label = nn.JoinTable(1)(data.label):view(-1, 1) mapped_data[len].col_seq = nn.JoinTable(1)(data.col_seq) mapped_data[len].row_seq = nn.JoinTable(1)(data.row_seq):view(-1, 1) mapped_data[len].row = mapped_data[len].row_seq mapped_data[len].col = torch.Tensor(mapped_data[len].col_seq:size(1)) end -- SAVE FILE torch.save(params.outFile, mapped_data) print('Done')
-- -- User: pat -- Date: 2/10/16 -- require 'nn' local cmd = torch.CmdLine() cmd:option('-inFile', '', 'input file') cmd:option('-keyFile', '', 'file that maps entity pairs to relations') cmd:option('-outFile', '', 'out file') local params = cmd:parse(arg) -- load key file int map print('Loading ep-rel map from ' .. params.keyFile) local key = torch.load(params.keyFile) local ep_rel_map = {} local ep_seq_map = {} for a, dat in pairs(key) do if dat and torch.type(dat) == 'table' and dat.ep then for i = 1, dat.ep:size(1) do ep_rel_map[dat.ep[i]] = dat.rel:narrow(1,i,1) ep_seq_map[dat.ep[i]] = dat.seq:narrow(1,i,1) end end end print('Converting data from ' .. params.inFile .. ' and exporting to ' .. params.outFile) local data = torch.load(params.inFile) local mapped_data = {} local missing = 0 for _, sub_data in pairs(data) do if torch.type(sub_data) == 'table' then for i = 1, sub_data.row:size(1) do local ep = sub_data.row[i][1] local rels = ep_rel_map[ep] local seq = ep_seq_map[ep] if rels then local k = rels:size(2) local label = sub_data.label[i] local kb_rel = sub_data.col[i] local kb_rel_seq = sub_data.col_seq[i] if not mapped_data[k] then mapped_data[k] = {row={}, row_seq ={}, col={}, col_seq={}, label ={}} end table.insert(mapped_data[k].col, rels) table.insert(mapped_data[k].col_seq, seq) table.insert(mapped_data[k].label, label) table.insert(mapped_data[k].row, kb_rel) table.insert(mapped_data[k].row_seq, kb_rel_seq) else missing = missing + 1 end end end end print('couldnt map ' .. missing .. ' entity pairs') for len, sub_data in pairs(mapped_data) do mapped_data[len].label = nn.JoinTable(1)(sub_data.label) mapped_data[len].col = nn.JoinTable(1)(sub_data.col) mapped_data[len].col_seq = nn.JoinTable(1)(sub_data.col_seq) mapped_data[len].row = nn.JoinTable(1)(sub_data.row) -- todo, something seems wrong with row_seq mapped_data[len].row_seq = nn.JoinTable(1)(sub_data.row_seq) mapped_data[len].count = sub_data.label:size(1) end -- SAVE FILE torch.save(params.outFile, mapped_data) print('Done')
fix pool test data scropt
fix pool test data scropt
Lua
mit
patverga/torch-relation-extraction,patverga/torch-relation-extraction,patverga/torch-relation-extraction
bdda7f71f4cdf5bdc0cf9bf59737664469a22199
queuebot.lua
queuebot.lua
require "luarocks.loader" require "irc" local config = require "config".irc local inspect = require "inspect" local lanes = require "lanes".configure() local linda = lanes.linda() local re = require "re" local sleep = require "socket".sleep local id = 0 local queued_requests = {} local send_request = lanes.gen("*", function(command, account, item, id) local http = require "socket.http" local ltn12 = require "ltn12" local tab = {} <<<<<<< HEAD local req = item local _, status if command == "push" then _, status = http.request{ url = "http://queue.octayn.net/webservice.lua/" .. account, method = "POST", headers = { ["Content-Length"] = #req, ["Content-Type"] = "application/json" }, source = ltn12.source.string(req), sink = ltn12.sink.table(tab) } end if status ~= 200 then linda:set(id, false) print("http req failed: " .. tostring(status) .. tostring(table.concat(tab))) else linda:set(id, true) ======= if command == "push" then local _, status = http.request{ url = config.api_url .. account, method = "POST", source = ltn12.source.string(item), sink = ltn12.sink.table(tab) } if status ~= 200 then linda:set(id, false) print("http req failed: " .. tostring(status) .. tostring(table.concat(tab))) else linda:set(id, true) end elseif command == "pop" then local _, status = http.request{ url = config.api_url .. account, method = "GET", sink = ltn12.sink.table(tab) } if status ~= 200 then linda:set(id, false) print("http req failed: " .. tostring(status) .. tostring(table.concat(tab))) else linda:set(id, cjson.decode(table.concat(tab)[0].content)) local _, status = http.request{ url = config.api_url .. account, method = "DELETE", source = ltn12.source.string(cjson.decode(table.concat(tab))[0].id), sink = ltn12.sink.table(tab) } linda:set(id, true) print("deleting item failed!") end >>>>>>> 1ca00d7a0b7ea239d455d58bc58e21334cde57bb end end) local pat = ("'%s: ' {[^ ]*} ' ' {[^:]*} ' ' {.*}"):format(config.irc.nick) function target(message) local command, nick, item = re.match(message, pat) if nick == nil or command == nil or item == nil then return nil end return nick, command, item end commands = { push = true, pop = true } local qb = irc.new { nick = config.nick } qb:hook("OnChat", function(user, channel, message) local nick, command, item if message ~= "pop" then nick, command, item = target(message) if nick == nil then return end else nick, command = user, "pop" end if commands[command] then local id_ = tostring(id) id = id + 1 send_request(command, nick, item, id_) queued_requests[id_] = channel qb:sendChat(channel, ("done [%s]"):format(id_)) end end) qb:connect(config.network) for _, channel in ipairs(config.channels) do qb:join(channel) end while true do qb:think() for k,v in pairs(queued_requests) do local val = linda:get(k) if val == false then queued_requests[k] = nil qb:sendChat(v, ("%s failed!"):format(k)) end end sleep(0.3) end
require "luarocks.loader" require "irc" local config = require "config".irc local inspect = require "inspect" local lanes = require "lanes".configure() local linda = lanes.linda() local re = require "re" local sleep = require "socket".sleep local id = 0 local queued_requests = {} local send_request = lanes.gen("*", function(command, account, item, id) local http = require "socket.http" local ltn12 = require "ltn12" local tab = {} if command == "push" then local _, status = http.request{ url = config.api_url .. account, method = "POST", source = ltn12.source.string(item), sink = ltn12.sink.table(tab) } if status ~= 200 then linda:set(id, false) print("http req failed: " .. tostring(status) .. tostring(table.concat(tab))) else linda:set(id, true) end elseif command == "pop" then local _, status = http.request{ url = config.api_url .. account, method = "GET", sink = ltn12.sink.table(tab) } if status ~= 200 then linda:set(id, false) print("http req failed: " .. tostring(status) .. tostring(table.concat(tab))) else linda:set(id, cjson.decode(table.concat(tab)[0].content)) local _, status = http.request{ url = config.api_url .. account, method = "DELETE", source = ltn12.source.string(cjson.decode(table.concat(tab))[0].id), sink = ltn12.sink.table(tab) } linda:set(id, true) print("deleting item failed!") end end end) local pat = ("'%s: ' {[^ ]*} ' ' {[^:]*} ' ' {.*}"):format(config.irc.nick) function target(message) local command, nick, item = re.match(message, pat) if nick == nil or command == nil or item == nil then return nil end return nick, command, item end commands = { push = true, pop = true } local qb = irc.new { nick = config.nick } qb:hook("OnChat", function(user, channel, message) local nick, command, item if message ~= "pop" then nick, command, item = target(message) if nick == nil then return end else nick, command = user, "pop" end if commands[command] then local id_ = tostring(id) id = id + 1 send_request(command, nick, item, id_) queued_requests[id_] = channel qb:sendChat(channel, ("done [%s]"):format(id_)) end end) qb:connect(config.network) for _, channel in ipairs(config.channels) do qb:join(channel) end while true do qb:think() for k,v in pairs(queued_requests) do local val = linda:get(k) if val == false then queued_requests[k] = nil qb:sendChat(v, ("%s failed!"):format(k)) end end sleep(0.3) end
fix merge conflict
fix merge conflict
Lua
bsd-2-clause
cmr/queue
43a72918db4ed34126a2929f38d593f353fe04aa
applications/luci-radvd/luasrc/model/cbi/radvd.lua
applications/luci-radvd/luasrc/model/cbi/radvd.lua
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("radvd", translate("Radvd"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) local nm = require "luci.model.network".init(m.uci) -- -- Interfaces -- s = m:section(TypedSection, "interface", translate("Interfaces")) s.template = "cbi/tblsection" s.extedit = luci.dispatcher.build_url("admin/network/radvd/interface/%s") s.anonymous = true s.addremove = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s.extedit % id) end function s.remove(self, section) local iface = m.uci:get("radvd", section, "interface") if iface then m.uci:delete_all("radvd", "prefix", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "route", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "rdnss", function(s) return s.interface == iface end) end return TypedSection.remove(self, section) end o = s:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s:option(DummyValue, "UnicastOnly", translate("Multicast")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("no") or translate("yes") end o = s:option(DummyValue, "AdvSendAdvert", translate("Advertising")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "MaxRtrAdvInterval", translate("Max. interval")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "600" return v .. "s" end o = s:option(DummyValue, "AdvHomeAgentFlag", translate("Mobile IPv6")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "AdvDefaultPreference", translate("Preference")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "medium" return translate(v) end -- -- Prefixes -- s2 = m:section(TypedSection, "prefix", translate("Prefixes")) s2.template = "cbi/tblsection" s2.extedit = luci.dispatcher.build_url("admin/network/radvd/prefix/%s") s2.addremove = true s2.anonymous = true function s2.create(...) local id = TypedSection.create(...) luci.http.redirect(s2.extedit % id) end o = s2:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s2:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:string() break end end end end else v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s2:option(DummyValue, "AdvAutonomous", translate("Autonomous")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvOnLink", translate("On-link")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvValidLifetime", translate("Validity time")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "86400" return translate(v) end -- -- Routes -- s3 = m:section(TypedSection, "route", translate("Routes")) s3.template = "cbi/tblsection" s3.extedit = luci.dispatcher.build_url("admin/network/radvd/route/%s") s3.addremove = true s3.anonymous = true function s3.create(...) local id = TypedSection.create(...) luci.http.redirect(s3.extedit % id) end o = s3:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s3:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if v then v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s3:option(DummyValue, "AdvRouteLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1800" return translate(v) end o = s3:option(DummyValue, "AdvRoutePreference", translate("Preference")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "medium" return translate(v) end -- -- RDNSS -- s4 = m:section(TypedSection, "rdnss", translate("RDNSS")) s4.template = "cbi/tblsection" s4.extedit = luci.dispatcher.build_url("admin/network/radvd/rdnss/%s") s4.addremove = true s4.anonymous = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s4.extedit % id) end o = s4:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s4:option(DummyValue, "addr", translate("Address")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:network(128):string() break end end end end else v = luci.ip.IPv6(v) v = v and v:network(128):string() end return v or "?" end o = s4:option(DummyValue, "AdvRDNSSOpen", translate("Open")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v == "1" and translate("yes") or translate("no") end o = s4:option(DummyValue, "AdvRDNSSLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1200" return translate(v) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("radvd", translate("Radvd"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) local nm = require "luci.model.network".init(m.uci) -- -- Interfaces -- s = m:section(TypedSection, "interface", translate("Interfaces")) s.template = "cbi/tblsection" s.extedit = luci.dispatcher.build_url("admin/network/radvd/interface/%s") s.anonymous = true s.addremove = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s.extedit % id) end function s.remove(self, section) if m.uci:get("radvd", section) == "interface" then local iface = m.uci:get("radvd", section, "interface") if iface then m.uci:delete_all("radvd", "prefix", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "route", function(s) return s.interface == iface end) m.uci:delete_all("radvd", "rdnss", function(s) return s.interface == iface end) end end return TypedSection.remove(self, section) end o = s:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s:option(DummyValue, "UnicastOnly", translate("Multicast")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("no") or translate("yes") end o = s:option(DummyValue, "AdvSendAdvert", translate("Advertising")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "MaxRtrAdvInterval", translate("Max. interval")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "600" return v .. "s" end o = s:option(DummyValue, "AdvHomeAgentFlag", translate("Mobile IPv6")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s:option(DummyValue, "AdvDefaultPreference", translate("Preference")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "medium" return translate(v) end -- -- Prefixes -- s2 = m:section(TypedSection, "prefix", translate("Prefixes")) s2.template = "cbi/tblsection" s2.extedit = luci.dispatcher.build_url("admin/network/radvd/prefix/%s") s2.addremove = true s2.anonymous = true function s2.create(...) local id = TypedSection.create(...) luci.http.redirect(s2.extedit % id) end o = s2:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s2:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:string() break end end end end else v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s2:option(DummyValue, "AdvAutonomous", translate("Autonomous")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvOnLink", translate("On-link")) function o.cfgvalue(...) local v = Value.cfgvalue(...) return v == "1" and translate("yes") or translate("no") end o = s2:option(DummyValue, "AdvValidLifetime", translate("Validity time")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or "86400" return translate(v) end -- -- Routes -- s3 = m:section(TypedSection, "route", translate("Routes")) s3.template = "cbi/tblsection" s3.extedit = luci.dispatcher.build_url("admin/network/radvd/route/%s") s3.addremove = true s3.anonymous = true function s3.create(...) local id = TypedSection.create(...) luci.http.redirect(s3.extedit % id) end o = s3:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s3:option(DummyValue, "prefix", translate("Prefix")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if v then v = luci.ip.IPv6(v) v = v and v:string() end return v or "?" end o = s3:option(DummyValue, "AdvRouteLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1800" return translate(v) end o = s3:option(DummyValue, "AdvRoutePreference", translate("Preference")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "medium" return translate(v) end -- -- RDNSS -- s4 = m:section(TypedSection, "rdnss", translate("RDNSS")) s4.template = "cbi/tblsection" s4.extedit = luci.dispatcher.build_url("admin/network/radvd/rdnss/%s") s4.addremove = true s4.anonymous = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s4.extedit % id) end o = s4:option(DummyValue, "interface", translate("Interface")) o.template = "cbi/network_netinfo" o = s4:option(DummyValue, "addr", translate("Address")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) if not v then local net = nm:get_network(m.uci:get("radvd", section, "interface")) if net then local ifc = nm:get_interface(net:ifname()) if ifc then local adr local lla = luci.ip.IPv6("fe80::/10") for _, adr in ipairs(ifc:ip6addrs()) do if not lla:contains(adr) then v = adr:network(128):string() break end end end end else v = luci.ip.IPv6(v) v = v and v:network(128):string() end return v or "?" end o = s4:option(DummyValue, "AdvRDNSSOpen", translate("Open")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v == "1" and translate("yes") or translate("no") end o = s4:option(DummyValue, "AdvRDNSSLifetime", translate("Lifetime")) function o.cfgvalue(self, section) local v = Value.cfgvalue(self, section) or "1200" return translate(v) end return m
applications/luci-radvd: fix removal of section in overview page
applications/luci-radvd: fix removal of section in overview page
Lua
apache-2.0
palmettos/test,cappiewu/luci,taiha/luci,slayerrensky/luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,fkooman/luci,taiha/luci,Kyklas/luci-proto-hso,MinFu/luci,artynet/luci,teslamint/luci,hnyman/luci,RedSnake64/openwrt-luci-packages,dismantl/luci-0.12,ollie27/openwrt_luci,rogerpueyo/luci,fkooman/luci,keyidadi/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,forward619/luci,db260179/openwrt-bpi-r1-luci,981213/luci-1,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,jlopenwrtluci/luci,palmettos/cnLuCI,hnyman/luci,RuiChen1113/luci,joaofvieira/luci,aircross/OpenWrt-Firefly-LuCI,urueedi/luci,Noltari/luci,obsy/luci,MinFu/luci,tobiaswaldvogel/luci,tcatm/luci,palmettos/cnLuCI,slayerrensky/luci,wongsyrone/luci-1,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,remakeelectric/luci,Kyklas/luci-proto-hso,thesabbir/luci,db260179/openwrt-bpi-r1-luci,dwmw2/luci,mumuqz/luci,jchuang1977/luci-1,openwrt/luci,cshore-firmware/openwrt-luci,NeoRaider/luci,NeoRaider/luci,david-xiao/luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,artynet/luci,oneru/luci,aa65535/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,teslamint/luci,rogerpueyo/luci,palmettos/test,zhaoxx063/luci,teslamint/luci,Wedmer/luci,aa65535/luci,harveyhu2012/luci,db260179/openwrt-bpi-r1-luci,palmettos/test,urueedi/luci,rogerpueyo/luci,joaofvieira/luci,slayerrensky/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,tcatm/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,taiha/luci,openwrt-es/openwrt-luci,schidler/ionic-luci,Noltari/luci,ollie27/openwrt_luci,remakeelectric/luci,openwrt-es/openwrt-luci,schidler/ionic-luci,daofeng2015/luci,oyido/luci,david-xiao/luci,ff94315/luci-1,thesabbir/luci,marcel-sch/luci,jchuang1977/luci-1,Noltari/luci,sujeet14108/luci,artynet/luci,kuoruan/luci,nmav/luci,bittorf/luci,oneru/luci,LuttyYang/luci,cshore/luci,nwf/openwrt-luci,florian-shellfire/luci,obsy/luci,daofeng2015/luci,MinFu/luci,Kyklas/luci-proto-hso,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,lcf258/openwrtcn,taiha/luci,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,sujeet14108/luci,bittorf/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,forward619/luci,marcel-sch/luci,thess/OpenWrt-luci,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,palmettos/cnLuCI,oyido/luci,bright-things/ionic-luci,teslamint/luci,981213/luci-1,urueedi/luci,tcatm/luci,remakeelectric/luci,cshore-firmware/openwrt-luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,981213/luci-1,opentechinstitute/luci,wongsyrone/luci-1,Hostle/luci,jlopenwrtluci/luci,fkooman/luci,male-puppies/luci,dismantl/luci-0.12,ff94315/luci-1,forward619/luci,zhaoxx063/luci,Sakura-Winkey/LuCI,opentechinstitute/luci,lcf258/openwrtcn,dwmw2/luci,Hostle/luci,deepak78/new-luci,LuttyYang/luci,ollie27/openwrt_luci,harveyhu2012/luci,cappiewu/luci,thess/OpenWrt-luci,joaofvieira/luci,MinFu/luci,teslamint/luci,male-puppies/luci,opentechinstitute/luci,cappiewu/luci,zhaoxx063/luci,openwrt-es/openwrt-luci,urueedi/luci,sujeet14108/luci,forward619/luci,slayerrensky/luci,cshore/luci,schidler/ionic-luci,chris5560/openwrt-luci,lcf258/openwrtcn,Hostle/luci,keyidadi/luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,harveyhu2012/luci,LuttyYang/luci,obsy/luci,ollie27/openwrt_luci,RuiChen1113/luci,chris5560/openwrt-luci,oyido/luci,kuoruan/lede-luci,kuoruan/luci,daofeng2015/luci,thess/OpenWrt-luci,wongsyrone/luci-1,zhaoxx063/luci,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,obsy/luci,male-puppies/luci,kuoruan/luci,Noltari/luci,david-xiao/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,urueedi/luci,zhaoxx063/luci,hnyman/luci,jorgifumi/luci,tcatm/luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,wongsyrone/luci-1,ff94315/luci-1,maxrio/luci981213,male-puppies/luci,cappiewu/luci,nmav/luci,Hostle/luci,david-xiao/luci,nmav/luci,zhaoxx063/luci,urueedi/luci,Wedmer/luci,openwrt/luci,tobiaswaldvogel/luci,cappiewu/luci,bittorf/luci,981213/luci-1,kuoruan/luci,chris5560/openwrt-luci,taiha/luci,wongsyrone/luci-1,remakeelectric/luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,forward619/luci,jlopenwrtluci/luci,maxrio/luci981213,oneru/luci,kuoruan/lede-luci,dismantl/luci-0.12,Hostle/luci,tcatm/luci,chris5560/openwrt-luci,forward619/luci,oyido/luci,Kyklas/luci-proto-hso,jorgifumi/luci,Noltari/luci,obsy/luci,palmettos/test,fkooman/luci,mumuqz/luci,oyido/luci,sujeet14108/luci,mumuqz/luci,david-xiao/luci,aa65535/luci,nmav/luci,florian-shellfire/luci,nwf/openwrt-luci,cshore/luci,thess/OpenWrt-luci,jchuang1977/luci-1,openwrt/luci,slayerrensky/luci,mumuqz/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,NeoRaider/luci,fkooman/luci,nwf/openwrt-luci,palmettos/cnLuCI,keyidadi/luci,tobiaswaldvogel/luci,bittorf/luci,bright-things/ionic-luci,oyido/luci,lcf258/openwrtcn,jchuang1977/luci-1,981213/luci-1,schidler/ionic-luci,openwrt/luci,shangjiyu/luci-with-extra,tcatm/luci,palmettos/cnLuCI,LuttyYang/luci,maxrio/luci981213,jorgifumi/luci,daofeng2015/luci,lbthomsen/openwrt-luci,deepak78/new-luci,openwrt-es/openwrt-luci,cappiewu/luci,thess/OpenWrt-luci,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,palmettos/cnLuCI,remakeelectric/luci,Noltari/luci,jorgifumi/luci,wongsyrone/luci-1,oneru/luci,cshore-firmware/openwrt-luci,cshore-firmware/openwrt-luci,ff94315/luci-1,schidler/ionic-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,dwmw2/luci,remakeelectric/luci,daofeng2015/luci,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,schidler/ionic-luci,palmettos/cnLuCI,marcel-sch/luci,male-puppies/luci,ff94315/luci-1,fkooman/luci,Kyklas/luci-proto-hso,cshore/luci,keyidadi/luci,Hostle/luci,nmav/luci,slayerrensky/luci,sujeet14108/luci,oneru/luci,oneru/luci,mumuqz/luci,nmav/luci,Noltari/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,bright-things/ionic-luci,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,chris5560/openwrt-luci,keyidadi/luci,ollie27/openwrt_luci,aa65535/luci,dwmw2/luci,joaofvieira/luci,jorgifumi/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,sujeet14108/luci,jorgifumi/luci,tcatm/luci,kuoruan/lede-luci,MinFu/luci,nwf/openwrt-luci,artynet/luci,marcel-sch/luci,kuoruan/lede-luci,forward619/luci,Kyklas/luci-proto-hso,taiha/luci,LuttyYang/luci,hnyman/luci,lcf258/openwrtcn,sujeet14108/luci,dismantl/luci-0.12,florian-shellfire/luci,maxrio/luci981213,florian-shellfire/luci,dismantl/luci-0.12,deepak78/new-luci,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,oneru/luci,tobiaswaldvogel/luci,rogerpueyo/luci,schidler/ionic-luci,bittorf/luci,lcf258/openwrtcn,lbthomsen/openwrt-luci,joaofvieira/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,harveyhu2012/luci,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,jlopenwrtluci/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,slayerrensky/luci,thesabbir/luci,rogerpueyo/luci,aa65535/luci,marcel-sch/luci,marcel-sch/luci,NeoRaider/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,RuiChen1113/luci,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,tcatm/luci,nmav/luci,dwmw2/luci,opentechinstitute/luci,taiha/luci,teslamint/luci,hnyman/luci,MinFu/luci,Wedmer/luci,palmettos/test,florian-shellfire/luci,jorgifumi/luci,rogerpueyo/luci,dwmw2/luci,981213/luci-1,artynet/luci,ollie27/openwrt_luci,daofeng2015/luci,oyido/luci,lcf258/openwrtcn,ollie27/openwrt_luci,dwmw2/luci,RuiChen1113/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,male-puppies/luci,openwrt/luci,thesabbir/luci,artynet/luci,nmav/luci,bittorf/luci,lcf258/openwrtcn,urueedi/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,harveyhu2012/luci,Sakura-Winkey/LuCI,Wedmer/luci,maxrio/luci981213,ff94315/luci-1,nwf/openwrt-luci,chris5560/openwrt-luci,ReclaimYourPrivacy/cloak-luci,LuttyYang/luci,nwf/openwrt-luci,tobiaswaldvogel/luci,jchuang1977/luci-1,artynet/luci,kuoruan/lede-luci,jlopenwrtluci/luci,david-xiao/luci,ff94315/luci-1,artynet/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,fkooman/luci,nwf/openwrt-luci,oneru/luci,openwrt/luci,joaofvieira/luci,MinFu/luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,sujeet14108/luci,lbthomsen/openwrt-luci,joaofvieira/luci,obsy/luci,fkooman/luci,mumuqz/luci,Kyklas/luci-proto-hso,keyidadi/luci,ff94315/luci-1,Hostle/openwrt-luci-multi-user,openwrt/luci,wongsyrone/luci-1,cshore/luci,remakeelectric/luci,dismantl/luci-0.12,thess/OpenWrt-luci,forward619/luci,marcel-sch/luci,bittorf/luci,Wedmer/luci,cshore/luci,rogerpueyo/luci,shangjiyu/luci-with-extra,taiha/luci,jchuang1977/luci-1,LuttyYang/luci,opentechinstitute/luci,cshore/luci,lbthomsen/openwrt-luci,hnyman/luci,florian-shellfire/luci,artynet/luci,lbthomsen/openwrt-luci,bittorf/luci,jchuang1977/luci-1,obsy/luci,Wedmer/luci,thesabbir/luci,cshore-firmware/openwrt-luci,david-xiao/luci,kuoruan/luci,deepak78/new-luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,male-puppies/luci,mumuqz/luci,chris5560/openwrt-luci,LuttyYang/luci,zhaoxx063/luci,Noltari/luci,nwf/openwrt-luci,oyido/luci,marcel-sch/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,NeoRaider/luci,urueedi/luci,bright-things/ionic-luci,palmettos/test,male-puppies/luci,kuoruan/luci,Sakura-Winkey/LuCI,obsy/luci,aa65535/luci,kuoruan/lede-luci,dismantl/luci-0.12,mumuqz/luci,NeoRaider/luci,aa65535/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,harveyhu2012/luci,aa65535/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,kuoruan/lede-luci,lcf258/openwrtcn,MinFu/luci,rogerpueyo/luci,NeoRaider/luci,teslamint/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,palmettos/test,maxrio/luci981213,deepak78/new-luci,palmettos/cnLuCI,kuoruan/luci,remakeelectric/luci,opentechinstitute/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,maxrio/luci981213,nmav/luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,bright-things/ionic-luci,kuoruan/luci,cappiewu/luci
68ab33b6eed3ef40bef5434d67342208be1ba56d
Dusk/dusk_core/load/tilesets.lua
Dusk/dusk_core/load/tilesets.lua
-------------------------------------------------------------------------------- --[[ Dusk Engine Component: Tilesets Loads tilesets from data. --]] -------------------------------------------------------------------------------- local lib_tilesets = {} -------------------------------------------------------------------------------- -- Localize -------------------------------------------------------------------------------- local lib_settings = require("Dusk.dusk_core.misc.settings") local lib_functions = require("Dusk.dusk_core.misc.functions") local graphics_newImageSheet = graphics.newImageSheet local math_floor = math.floor local math_ceil = math.ceil local table_insert = table.insert local table_concat = table.concat local tostring = tostring local string_len = string.len local getProperties = lib_functions.getProperties local getDirectory = lib_functions.getDirectory -------------------------------------------------------------------------------- -- Get Tilesets from Data -------------------------------------------------------------------------------- function lib_tilesets.get(data, dirTree) local data = data local dirTree = dirTree or {} local tilesetOptions = {} local imageSheets = {} -- The tileset image sheets themselves local imageSheetConfig = {} -- The image sheet configurations local tileProperties = {} -- Tile properties for each tileset local tileIndex = {} -- Tile GID table - each number in the data corresponds to a tile local c = 0 -- Total number of tiles from all tilesets local tileIDs = {} -- Tile ID list ------------------------------------------------------------------------------ -- Iterate Through Tilesets ------------------------------------------------------------------------------ for i = 1, #data.tilesets do local gid = 0 -- The GID for this tileset local tilesetProperties = {} -- Element to add to the tileProperties table for this tileset local options -- Data table for this tileset -- Make sure the tileset has properties (if it has no properties, Tiled saves it without even a blank table as the properties table) data.tilesets[i].tileproperties = data.tilesets[i].tileproperties or {} local directoryPath, filename = getDirectory(dirTree, data.tilesets[i].image) options = { config = { frames = {}, sheetContentWidth = data.tilesets[i].imagewidth, sheetContentHeight = data.tilesets[i].imageheight, width = data.tilesets[i].tilewidth, height = data.tilesets[i].tileheight, start = 1, count = 0 }, image = directoryPath .. "/" .. filename, margin = data.tilesets[i].margin, spacing = data.tilesets[i].spacing, tilewidth = data.tilesets[i].tilewidth, tileheight = data.tilesets[i].tileheight, tilesetWidth = 0, tilesetHeight = 0 } -- Remove opening slash, if existent if options.image:sub(1,1) == "/" or options.image:sub(1,1) == "\\" then options.image = options.image:sub(2) end -- Tileset width/height in tiles options.tilesetWidth = math_ceil(((options.config.sheetContentWidth - options.margin * 2) - options.spacing) / (options.tilewidth + options.spacing)) options.tilesetHeight = math_ceil(((options.config.sheetContentHeight - options.margin * 2) - options.spacing) / (options.tileheight + options.spacing)) -- Iterate throught the tileset for y = 1, options.tilesetHeight do for x = 1, options.tilesetWidth do local element = { -- X and Y of the tile on the sheet x = (x - 1) * (options.tilewidth + options.spacing) + options.margin, y = (y - 1) * (options.tileheight + options.spacing) + options.margin, -- Width of tile width = options.tilewidth, height = options.tileheight } gid = gid + 1 c = c + 1 table_insert(options.config.frames, gid, element) -- Add to the frames of the sheet tileIndex[c] = {tilesetIndex = i, gid = gid} local strGID = tostring(gid - 1) -- Tile properties start at 0, so we must subtract 1. Because of the sparse table that tileset properties usually are, they're encoded into JSON with string keys, thus we must tostring() the GID first if data.tilesets[i].tileproperties[strGID] then tilesetProperties[gid] = getProperties(data.tilesets[i].tileproperties[strGID], "tile", false) if tilesetProperties[gid].object["!tileID!"] then tileIDs[tilesetProperties[gid].object["!tileID!"] ] = gid end end end end -------------------------------------------------------------------------------- -- Store Values -------------------------------------------------------------------------------- imageSheets[i] = graphics_newImageSheet(options.image, options.config) options.config.count = gid if not imageSheets[i] then error("Tileset image (\"" .. options.image .. "\") not found.") end imageSheetConfig[i] = options.config tileProperties[i] = tilesetProperties tilesetOptions[#tilesetOptions + 1] = options end data.highestGID = c return tilesetOptions, imageSheets, imageSheetConfig, tileProperties, tileIndex, tileIDs end return lib_tilesets
-------------------------------------------------------------------------------- --[[ Dusk Engine Component: Tilesets Loads tilesets from data. --]] -------------------------------------------------------------------------------- local lib_tilesets = {} -------------------------------------------------------------------------------- -- Localize -------------------------------------------------------------------------------- local lib_settings = require("Dusk.dusk_core.misc.settings") local lib_functions = require("Dusk.dusk_core.misc.functions") local graphics_newImageSheet = graphics.newImageSheet local math_floor = math.floor local math_ceil = math.ceil local table_insert = table.insert local table_concat = table.concat local tostring = tostring local string_len = string.len local getProperties = lib_functions.getProperties local getDirectory = lib_functions.getDirectory -------------------------------------------------------------------------------- -- Get Tilesets from Data -------------------------------------------------------------------------------- function lib_tilesets.get(data, dirTree) local data = data local dirTree = dirTree or {} local tilesetOptions = {} local imageSheets = {} -- The tileset image sheets themselves local imageSheetConfig = {} -- The image sheet configurations local tileProperties = {} -- Tile properties for each tileset local tileIndex = {} -- Tile GID table - each number in the data corresponds to a tile local c = 0 -- Total number of tiles from all tilesets local tileIDs = {} -- Tile ID list ------------------------------------------------------------------------------ -- Iterate Through Tilesets ------------------------------------------------------------------------------ for i = 1, #data.tilesets do local gid = 0 -- The GID for this tileset local tilesetProperties = {} -- Element to add to the tileProperties table for this tileset local options -- Data table for this tileset -- Make sure the tileset has properties (if it has no properties, Tiled saves it without even a blank table as the properties table) data.tilesets[i].tileproperties = data.tilesets[i].tileproperties or {} local directoryPath, filename = getDirectory(dirTree, data.tilesets[i].image) options = { config = { frames = {}, sheetContentWidth = data.tilesets[i].imagewidth, sheetContentHeight = data.tilesets[i].imageheight, width = data.tilesets[i].tilewidth, height = data.tilesets[i].tileheight, start = 1, count = 0 }, image = directoryPath .. "/" .. filename, margin = data.tilesets[i].margin, spacing = data.tilesets[i].spacing, tilewidth = data.tilesets[i].tilewidth, tileheight = data.tilesets[i].tileheight, tilesetWidth = 0, tilesetHeight = 0 } -- Remove opening slash, if existent if options.image:sub(1,1) == "/" or options.image:sub(1,1) == "\\" then options.image = options.image:sub(2) end data.tilesets[i].columns = data.tilesets[i].columns or math.floor((data.tilesets[i].imagewidth - data.tilesets[i].margin * 2 + data.tilesets[i].spacing) / (data.tilesets[i].tilewidth + data.tilesets[i].spacing)) -- Tileset width/height in tiles options.tilesetWidth = data.tilesets[i].columns options.tilesetHeight = data.tilesets[i].tilecount / data.tilesets[i].columns -- Iterate throught the tileset for y = 1, options.tilesetHeight do for x = 1, options.tilesetWidth do local element = { -- X and Y of the tile on the sheet x = (x - 1) * (options.tilewidth + options.spacing) + options.margin, y = (y - 1) * (options.tileheight + options.spacing) + options.margin, -- Width of tile width = options.tilewidth, height = options.tileheight } gid = gid + 1 c = c + 1 table_insert(options.config.frames, gid, element) -- Add to the frames of the sheet tileIndex[c] = {tilesetIndex = i, gid = gid} local strGID = tostring(gid - 1) -- Tile properties start at 0, so we must subtract 1. Because of the sparse table that tileset properties usually are, they're encoded into JSON with string keys, thus we must tostring() the GID first if data.tilesets[i].tileproperties[strGID] then tilesetProperties[gid] = getProperties(data.tilesets[i].tileproperties[strGID], "tile", false) if tilesetProperties[gid].object["!tileID!"] then tileIDs[tilesetProperties[gid].object["!tileID!"] ] = gid end end end end -------------------------------------------------------------------------------- -- Store Values -------------------------------------------------------------------------------- imageSheets[i] = graphics_newImageSheet(options.image, options.config) options.config.count = gid if not imageSheets[i] then error("Tileset image (\"" .. options.image .. "\") not found.") end imageSheetConfig[i] = options.config tileProperties[i] = tilesetProperties tilesetOptions[#tilesetOptions + 1] = options end data.highestGID = c return tilesetOptions, imageSheets, imageSheetConfig, tileProperties, tileIndex, tileIDs end return lib_tilesets
Fix incorrect tiles displaying with margin and spacing
Fix incorrect tiles displaying with margin and spacing
Lua
mit
GymbylCoding/Dusk-Engine
ee6bb5a2d21f9942658fc037da666451f80381d0
sorted_array.lua
sorted_array.lua
local bit = require("bit") local table = require("table") local string = require("string") local floor = require("math").floor local function s_to_a(data) local a = {} local bytes = {string.byte(data, i, #data)} for i = 1, #data / 8 do a[i] = 0 for c = 0, 7 do a[i] = bit.lshift(a[i], 8) a[i] = a[i] + bytes[i * 8 - c] end end return a end local function a_to_s(a) local bytes = {} for i = 1, #a do for c = 0, 7 do table.insert(bytes, bit.band(a[i], 0xff)) a[i] = bit.rshift(a[i], 8) end end return string.char(unpack(bytes)) end local limit = 500 local function amerge(a, b) local r = {} local n = limit while #a > 0 and #b > 0 and n > 0 do if a[1] > b[1] then table.insert(r, table.remove(a, 1)) else table.insert(r, table.remove(b, 1)) end n = n - 1 end while #a > 0 and n > 0 do table.insert(r, table.remove(a, 1)) n = n - 1 end while #b > 0 and n > 0 do table.insert(r, table.remove(b, 1)) n = n - 1 end return r end local function afind_ge(a, x) if #a == 0 then return 1 end local min, max = 1, #a repeat mid = floor((min + max) / 2) if x < a[mid] then min = mid + 1 else max = mid - 1 end until a[mid] == b or min > max return mid end local function ains(a, key) key = tonumber(key) local i = afind_ge(a, key) if a[i] and a[i] >= key then table.insert(a, i + 1, key) -- next to equal or greater else table.insert(a, i, key) end while #a > limit do table.remove(a) end end local function adel(a, key) key = tonumber(key) local i = afind_ge(a, key) if a[i] == key then table.remove(a, i) end end local function get(space, key) local tuple = box.select(space, 0, key) if tuple then return s_to_a(tuple[1]) else return {} end end local function store(space, key, a) return box.replace(space, key, a_to_s(a)) end function box.sa_insert(space, key, value) local a = get(space, key) ains(a, value) print(unpack(a)) return store(space, key, a) end function box.sa_delete(space, key, ...) local a = get(space, key) for i, d in pairs({...}) do adel(a, d) end return store(space, key, a) end function box.sa_select(space, key, from, limit) if from ~= '' then from = afind_ge(a, tonumber(from)) else from = 1 end if limit ~= '' then limit = tonumber(limit) else limit = 0 end local a = get(space, key) local r = {} for i = from, #a - from + 1 do if a[i] == nil then break end table.insert(r, a[i]) limit = limit - 1 if limit == 0 then break end end return key, a_to_s(r) end function box.sa_merge(space, key_a, key_b) local a = get(space, key_a) local b = get(space, key_b) local r = amerge(a, b) return a_to_s(r) end
local bit = require("bit") local table = require("table") local string = require("string") local floor = require("math").floor local function s_to_a(data) local a = {} local bytes = {string.byte(data, i, #data)} for i = 1, #data / 8 do a[i] = 0 for c = 0, 7 do a[i] = bit.lshift(a[i], 8) a[i] = a[i] + bytes[i * 8 - c] end end return a end local function a_to_s(a) local bytes = {} for i = 1, #a do for c = 0, 7 do table.insert(bytes, bit.band(a[i], 0xff)) a[i] = bit.rshift(a[i], 8) end end return string.char(unpack(bytes)) end local limit = 500 local function amerge(a, b) local r = {} local n = limit while #a > 0 and #b > 0 and n > 0 do if a[1] > b[1] then table.insert(r, table.remove(a, 1)) else table.insert(r, table.remove(b, 1)) end n = n - 1 end while #a > 0 and n > 0 do table.insert(r, table.remove(a, 1)) n = n - 1 end while #b > 0 and n > 0 do table.insert(r, table.remove(b, 1)) n = n - 1 end return r end local function afind_ge(a, x) if #a == 0 then return 1 end local first, last = 1, #a local mid repeat mid = floor(first + (last - first) / 2) if x > a[mid] then last = mid else first = mid + 1 end until first >= last if a[mid] >= x then mid = mid + 1 end return mid end local function ains(a, key) key = tonumber(key) local i = afind_ge(a, key) if a[i] and a[i] >= key then table.insert(a, i + 1, key) -- next to equal or greater else table.insert(a, i, key) end while #a > limit do table.remove(a) end end local function adel(a, key) key = tonumber(key) local i = afind_ge(a, key) if a[i] == key then table.remove(a, i) end end local function get(space, key) local tuple = box.select(space, 0, key) if tuple then return s_to_a(tuple[1]) else return {} end end local function store(space, key, a) return box.replace(space, key, a_to_s(a)) end function box.sa_insert(space, key, value) local a = get(space, key) ains(a, value) print(unpack(a)) return store(space, key, a) end function box.sa_delete(space, key, ...) local a = get(space, key) for i, d in pairs({...}) do adel(a, d) end return store(space, key, a) end function box.sa_select(space, key, from, limit) local a = get(space, key) if from ~= nil then from = afind_ge(a, tonumber(from)) else from = 1 end if limit ~= nil then limit = tonumber(limit) else limit = 0 end local r = {} for i = from, #a do if a[i] == nil then break end table.insert(r, a[i]) limit = limit - 1 if limit == 0 then break end end return key, a_to_s(r) end function box.sa_merge(space, key_a, key_b) local a = get(space, key_a) local b = get(space, key_b) local r = amerge(a, b) return a_to_s(r) end
sorted_array procedures was fixed.
sorted_array procedures was fixed.
Lua
bsd-2-clause
BHYCHIK/tntlua,grechkin-pogrebnyakov/tntlua,spectrec/tntlua,mailru/tntlua,derElektrobesen/tntlua
a3487077ca3908252b5af0a700d52ca26659adbe
game_view.lua
game_view.lua
-- imports grid_state = require 'grid_state' glitch_gen = require 'glitchGen' directions = require 'directions' glider = require 'glider' background_color = {240, 240, 240} grid_normal_color = {180, 230, 255} grid_block_color = {100, 200, 250} grid_line_width = 0.5 grid_unit_size = 32 grid_big_border = 5 -- mouse variables mouse_x = 0; mouse_y = 0; mouseClicked = false; lastFrameMouseClicked = false; -- glider variables rectanglesToDraw = {} numberOfGliders = 0 gliderPlaced = false -- grid state -- visual glitch state glitchUpdateTimer = 0.5 function draw_line(grid_num, x1, y1, x2, y2) local is_main = grid_num % grid_big_border == 0 local color = is_main and grid_block_color or grid_normal_color local width = grid_line_width love.graphics.setLineWidth(width) love.graphics.setColor(color[1], color[2], color[3]) love.graphics.line(x1, y1, x2, y2) end function processGoButtonClicked(grid_state) grid_state:update_objects() gliderPlaced = false; end function exports() local instance = {} local block_size = grid_unit_size * grid_big_border local xoffsets = 1280 % block_size if xoffsets == 0 then xoffsets = block_size end local xoffset = xoffsets / 2 local xcount = (1280 - xoffsets) / grid_unit_size local yoffsets = 720 % block_size local yoffset = yoffsets / 2 local ycount = (720 - yoffsets) / grid_unit_size instance.grid_state = grid_state(xcount, ycount) instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" ) local goButtonX = (xcount - 2) * grid_unit_size + xoffset local goButtonY = (ycount + 1.4) * grid_unit_size local goButtonWidth = 64 local goButtonHeight = 32 function instance:draw() love.graphics.setColor(background_color[1], background_color[2], background_color[3]) love.graphics.rectangle('fill', 0, 0, 1280, 720) -- Draw Grid local current_x = xoffset local grid_num = 0 -- glider local drawGliderX = -1 local drawGliderY = -1 while grid_num <= xcount do draw_line(grid_num, current_x, yoffset, current_x, 720 - yoffset) if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then drawGliderX = grid_num end current_x = current_x + grid_unit_size grid_num = grid_num + 1 end local current_y = yoffset grid_num = 0 while grid_num <= ycount do draw_line(grid_num, xoffset, current_y, 1280 - xoffset, current_y) if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then drawGliderY = grid_num end current_y = current_y + grid_unit_size grid_num = grid_num + 1 end if mouseClicked and drawGliderX >= 0 and drawGliderY >= 0 and drawGliderX < xcount and drawGliderY < ycount and not self.grid_state:get_space_at(drawGliderX+1, drawGliderY+1) and not gliderPlaced then self.grid_state:add_object(glider(drawGliderX + 1, drawGliderY + 1, directions.DOWN)) gliderPlaced = true end if glitchUpdateTimer > 0.2 then glitchUpdate = true glitchUpdateTimer = glitchUpdateTimer - 0.2 end for i,rect in ipairs(rectanglesToDraw) do glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate) end self.grid_state:draw_objects(xoffset, yoffset) for x = 1, xcount, 1 do for y = 1, ycount, 1 do if self.grid_state:get_space_at(x, y) then --love.graphics.setColor(255,0,0) --love.graphics.rectangle('fill', (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, grid_unit_size, grid_unit_size) glitch_gen.drawGlich( (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, xcount, glitchUpdate) end end end glitchUpdate = false self.grid_state:update_objects() -- Button Go to Evolution mode love.graphics.draw(self.goButtonImage, goButtonX, goButtonY) end function instance:update() mouse_x, mouse_y = love.mouse.getPosition() lastFrameMouseClicked = mouseClicked mouseClicked = love.mouse.isDown("l") if mouseClicked and mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight and not lastFrameMouseClicked then processGoButtonClicked(self.grid_state) end glitchUpdateTimer = glitchUpdateTimer + 1/60 end return instance end return exports
-- imports grid_state = require 'grid_state' glitch_gen = require 'glitchGen' directions = require 'directions' glider = require 'glider' background_color = {240, 240, 240} grid_normal_color = {180, 230, 255} grid_block_color = {100, 200, 250} grid_line_width = 0.5 grid_unit_size = 32 grid_big_border = 5 -- mouse variables mouse_x = 0; mouse_y = 0; mouseClicked = false; lastFrameMouseClicked = false; -- glider variables rectanglesToDraw = {} numberOfGliders = 0 gliderPlaced = false -- grid state -- visual glitch state glitchUpdateTimer = 0.5 function draw_line(grid_num, x1, y1, x2, y2) local is_main = grid_num % grid_big_border == 0 local color = is_main and grid_block_color or grid_normal_color local width = grid_line_width love.graphics.setLineWidth(width) love.graphics.setColor(color[1], color[2], color[3]) love.graphics.line(x1, y1, x2, y2) end function processGoButtonClicked(grid_state) grid_state:update_objects() gliderPlaced = false; end function exports() local instance = {} local block_size = grid_unit_size * grid_big_border local xoffsets = 1280 % block_size if xoffsets == 0 then xoffsets = block_size end local xoffset = xoffsets / 2 local xcount = (1280 - xoffsets) / grid_unit_size local yoffsets = 720 % block_size local yoffset = yoffsets / 2 local ycount = (720 - yoffsets) / grid_unit_size instance.grid_state = grid_state(xcount, ycount) instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" ) local goButtonX = (xcount - 2) * grid_unit_size + xoffset local goButtonY = (ycount + 1.4) * grid_unit_size local goButtonWidth = 64 local goButtonHeight = 32 function instance:draw() love.graphics.setColor(background_color[1], background_color[2], background_color[3]) love.graphics.rectangle('fill', 0, 0, 1280, 720) -- Draw Grid local current_x = xoffset local grid_num = 0 -- glider local drawGliderX = -1 local drawGliderY = -1 while grid_num <= xcount do draw_line(grid_num, current_x, yoffset, current_x, 720 - yoffset) if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then drawGliderX = grid_num end current_x = current_x + grid_unit_size grid_num = grid_num + 1 end local current_y = yoffset grid_num = 0 while grid_num <= ycount do draw_line(grid_num, xoffset, current_y, 1280 - xoffset, current_y) if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then drawGliderY = grid_num end current_y = current_y + grid_unit_size grid_num = grid_num + 1 end if mouseClicked and drawGliderX >= 0 and drawGliderY >= 0 and drawGliderX < xcount and drawGliderY < ycount and not self.grid_state:get_space_at(drawGliderX+1, drawGliderY+1) and not gliderPlaced then self.grid_state:add_object(glider(drawGliderX + 1, drawGliderY + 1, directions.DOWN)) gliderPlaced = true end if glitchUpdateTimer > 0.2 then glitchUpdate = true glitchUpdateTimer = glitchUpdateTimer - 0.2 end for i,rect in ipairs(rectanglesToDraw) do glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate) end self.grid_state:draw_objects(xoffset, yoffset) for x = 1, xcount, 1 do for y = 1, ycount, 1 do if self.grid_state:get_space_at(x, y) then glitch_gen.drawGlich( (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, xcount, glitchUpdate) end end end glitchUpdate = false -- Button Go to Evolution mode love.graphics.draw(self.goButtonImage, (xcount - 2) * grid_unit_size + xoffset, (ycount+1.4) * grid_unit_size) love.graphics.draw(self.goButtonImage, goButtonX, goButtonY) end function instance:update() mouse_x, mouse_y = love.mouse.getPosition() lastFrameMouseClicked = mouseClicked mouseClicked = love.mouse.isDown("l") if mouseClicked and mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight and not lastFrameMouseClicked then processGoButtonClicked(self.grid_state) end glitchUpdateTimer = glitchUpdateTimer + 1/60 end return instance end return exports
Fix last merge.
Fix last merge.
Lua
mit
NamefulTeam/PortoGameJam2015
f908ab6b6442a63fd5932221346789939f52c24f
main.lua
main.lua
require 'util' require 'Object' require 'settings' require 'game' require 'ui' require 'dredmor' if not love then require 'tty' require 'lovecompat' else error 'running under love2d is not yet supported' love.readkey = function() end end flags.register "help" { help = "This text."; } flags.register "load" { help = "Load this game immediately on game startup."; type = flags.string; } flags.register "seed" { help = "Random seed to use. Default: current time."; type = flags.number; default = os.time(); } local function turn() while true do game.get('player'):turn() end end function love.load(argv) flags.parse(unpack(argv)) if flags.parsed.help then print(flags.help()) return end math.randomseed(flags.parsed.seed) os.execute("mkdir -p '%s'" % flags.parsed.config_dir) settings.load() dredmor.loadAll() if flags.parsed.load then game.load(flags.parsed.load) else game.new('test') end ui.init() turn = coroutine.create(turn) end function love.draw() ui.draw() end local state = 0 local keybuffer = {} function love.keypressed(key) table.insert(keybuffer, key) end function love.update(t) local _ if state == 'key' then -- get a key from the keybuffer, and pass it to the main thread -- if the keybuffer is empty, just sleep briefly and return love.readkey(keybuffer) if #keybuffer > 0 then _,state = assert(coroutine.resume(turn, table.remove(keybuffer, 1))) else log.debug('sleeping') love.timer.sleep(0.033) end else -- state is a delay; decrement it and then resume state = state - t if state <= 0 then _,state = assert(coroutine.resume(turn)) end end end function love.errhand(...) tty.deinit() log.error('Fatal error: %s', debug.traceback(..., 2)) io.stderr:write(debug.traceback(..., 2)) os.exit(1) -- die without saving settings end function love.quit() tty.deinit() settings.save() end if love.main then -- We're running in compatibility mode, not inside actual love2d -- Call the main function provided by lovecompat return love.main(...) end -- Otherwise we just return and love2d handles setting up the mainloop.
require 'util' require 'Object' require 'settings' require 'game' require 'ui' require 'dredmor' if not love then require 'tty' require 'lovecompat' else error 'running under love2d is not yet supported' love.readkey = function() end end flags.register "help" { help = "This text."; } flags.register "load" { help = "Load this game immediately on game startup."; type = flags.string; } flags.register "seed" { help = "Random seed to use. Default: current time."; type = flags.number; default = os.time(); } local function turn() while true do local player = game.get 'player' xpcall(player.turn, love.errhand, player) end end function love.load(argv) flags.parse(unpack(argv)) if flags.parsed.help then print(flags.help()) return end math.randomseed(flags.parsed.seed) os.execute("mkdir -p '%s'" % flags.parsed.config_dir) settings.load() dredmor.loadAll() if flags.parsed.load then game.load(flags.parsed.load) else game.new('test') end ui.init() turn = coroutine.wrap(turn) end function love.draw() ui.draw() end local state = 0 local keybuffer = {} function love.keypressed(key) table.insert(keybuffer, key) end function love.update(t) local _ if state == 'key' then -- get a key from the keybuffer, and pass it to the main thread -- if the keybuffer is empty, just sleep briefly and return love.readkey(keybuffer) if #keybuffer > 0 then state = turn(table.remove(keybuffer, 1)) else log.debug('sleeping') love.timer.sleep(0.033) end else -- state is a delay; decrement it and then resume state = state - t if state <= 0 then state = turn() end end end function love.errhand(...) tty.deinit() log.error('Fatal error: %s', debug.traceback(..., 2)) os.exit(1) -- die without saving settings end function love.quit() tty.deinit() settings.save() end if love.main then -- We're running in compatibility mode, not inside actual love2d -- Call the main function provided by lovecompat return love.main(...) end -- Otherwise we just return and love2d handles setting up the mainloop.
Fix error reporting in new coroutine-based mainloop
Fix error reporting in new coroutine-based mainloop
Lua
mit
ToxicFrog/ttymor
41837e61932f23679a1613d550f2c71163f3aa46
mods/beds/functions.lua
mods/beds/functions.lua
local player_in_bed = 0 local is_sp = minetest.is_singleplayer() local enable_respawn = minetest.setting_getbool("enable_bed_respawn") or true -- helper functions local function get_look_yaw(pos) local n = minetest.get_node(pos) if n.param2 == 1 then return 7.9, n.param2 elseif n.param2 == 3 then return 4.75, n.param2 elseif n.param2 == 0 then return 3.15, n.param2 else return 6.28, n.param2 end end local function check_in_beds(players) local in_bed = beds.player if not players then players = minetest.get_connected_players() end for n, player in ipairs(players) do local name = player:get_player_name() if not in_bed[name] then return false end end return true end local function lay_down(player, pos, bed_pos, state, skip) local name = player:get_player_name() local hud_flags = player:hud_get_flags() if not player or not name then return end -- stand up if state ~= nil and not state then local p = beds.pos[name] or nil if beds.player[name] ~= nil then beds.player[name] = nil player_in_bed = player_in_bed - 1 end -- skip here to prevent sending player specific changes (used for leaving players) if skip then return end if p then player:setpos(p) end -- physics, eye_offset, etc player:set_eye_offset({x=0,y=0,z=0}, {x=0,y=0,z=0}) player:set_look_yaw(math.random(1, 180)/100) default.player_attached[name] = false player:set_physics_override(1, 1, 1) hud_flags.wielditem = true default.player_set_animation(player, "stand" , 30) -- lay down else beds.player[name] = 1 beds.pos[name] = pos player_in_bed = player_in_bed + 1 -- physics, eye_offset, etc player:set_eye_offset({x=0,y=-13,z=0}, {x=0,y=0,z=0}) local yaw, param2 = get_look_yaw(bed_pos) player:set_look_yaw(yaw) local dir = minetest.facedir_to_dir(param2) local p = {x=bed_pos.x+dir.x/2,y=bed_pos.y,z=bed_pos.z+dir.z/2} player:set_physics_override(0, 0, 0) player:setpos(p) default.player_attached[name] = true hud_flags.wielditem = false default.player_set_animation(player, "lay" , 0) end player:hud_set_flags(hud_flags) end local function update_formspecs(finished) local ges = #minetest.get_connected_players() local form_n = "" local is_majority = (ges/2) < player_in_bed if finished then form_n = beds.formspec .. "label[2.7,11; Good morning.]" else form_n = beds.formspec .. "label[2.2,11;"..tostring(player_in_bed).." of "..tostring(ges).." players are in bed]" if is_majority then form_n = form_n .. "button_exit[2,8;4,0.75;force;Force night skip]" end end for name,_ in pairs(beds.player) do minetest.show_formspec(name, "beds_form", form_n) end end -- public functions function beds.kick_players() for name,_ in pairs(beds.player) do local player = minetest.get_player_by_name(name) lay_down(player, nil, nil, false) end end function beds.skip_night() minetest.set_timeofday(0.23) beds.set_spawns() end function beds.on_rightclick(pos, player) local name = player:get_player_name() local ppos = player:getpos() local tod = minetest.get_timeofday() if tod > 0.2 and tod < 0.805 then if beds.player[name] then lay_down(player, nil, nil, false) end minetest.chat_send_player(name, "You can only sleep at night.") return end -- move to bed if not beds.player[name] then lay_down(player, ppos, pos) else lay_down(player, nil, nil, false) end if not is_sp then update_formspecs(false) end -- skip the night and let all players stand up if check_in_beds() then minetest.after(2, function() beds.skip_night() if not is_sp then update_formspecs(true) end beds.kick_players() end) end end -- callbacks minetest.register_on_joinplayer(function(player) beds.read_spawns() end) -- respawn player at bed if enabled and valid position is found minetest.register_on_respawnplayer(function(player) if not enable_respawn then return false end local name = player:get_player_name() local pos = beds.spawn[name] or nil if pos then player:setpos(pos) return true end end) minetest.register_on_leaveplayer(function(player) local name = player:get_player_name() lay_down(player, nil, nil, false, true) beds.player[name] = nil if check_in_beds() then minetest.after(2, function() beds.skip_night() update_formspecs(true) beds.kick_players() end) end end) minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "beds_form" then return end if fields.quit or fields.leave then lay_down(player, nil, nil, false) update_formspecs(false) end if fields.force then beds.skip_night() update_formspecs(true) beds.kick_players() end end)
local player_in_bed = 0 local is_sp = minetest.is_singleplayer() local enable_respawn = minetest.setting_getbool("enable_bed_respawn") if enable_respawn == nil then enable_respawn = true end -- helper functions local function get_look_yaw(pos) local n = minetest.get_node(pos) if n.param2 == 1 then return 7.9, n.param2 elseif n.param2 == 3 then return 4.75, n.param2 elseif n.param2 == 0 then return 3.15, n.param2 else return 6.28, n.param2 end end local function check_in_beds(players) local in_bed = beds.player if not players then players = minetest.get_connected_players() end for n, player in ipairs(players) do local name = player:get_player_name() if not in_bed[name] then return false end end return true end local function lay_down(player, pos, bed_pos, state, skip) local name = player:get_player_name() local hud_flags = player:hud_get_flags() if not player or not name then return end -- stand up if state ~= nil and not state then local p = beds.pos[name] or nil if beds.player[name] ~= nil then beds.player[name] = nil player_in_bed = player_in_bed - 1 end -- skip here to prevent sending player specific changes (used for leaving players) if skip then return end if p then player:setpos(p) end -- physics, eye_offset, etc player:set_eye_offset({x=0,y=0,z=0}, {x=0,y=0,z=0}) player:set_look_yaw(math.random(1, 180)/100) default.player_attached[name] = false player:set_physics_override(1, 1, 1) hud_flags.wielditem = true default.player_set_animation(player, "stand" , 30) -- lay down else beds.player[name] = 1 beds.pos[name] = pos player_in_bed = player_in_bed + 1 -- physics, eye_offset, etc player:set_eye_offset({x=0,y=-13,z=0}, {x=0,y=0,z=0}) local yaw, param2 = get_look_yaw(bed_pos) player:set_look_yaw(yaw) local dir = minetest.facedir_to_dir(param2) local p = {x=bed_pos.x+dir.x/2,y=bed_pos.y,z=bed_pos.z+dir.z/2} player:set_physics_override(0, 0, 0) player:setpos(p) default.player_attached[name] = true hud_flags.wielditem = false default.player_set_animation(player, "lay" , 0) end player:hud_set_flags(hud_flags) end local function update_formspecs(finished) local ges = #minetest.get_connected_players() local form_n = "" local is_majority = (ges/2) < player_in_bed if finished then form_n = beds.formspec .. "label[2.7,11; Good morning.]" else form_n = beds.formspec .. "label[2.2,11;"..tostring(player_in_bed).." of "..tostring(ges).." players are in bed]" if is_majority then form_n = form_n .. "button_exit[2,8;4,0.75;force;Force night skip]" end end for name,_ in pairs(beds.player) do minetest.show_formspec(name, "beds_form", form_n) end end -- public functions function beds.kick_players() for name,_ in pairs(beds.player) do local player = minetest.get_player_by_name(name) lay_down(player, nil, nil, false) end end function beds.skip_night() minetest.set_timeofday(0.23) beds.set_spawns() end function beds.on_rightclick(pos, player) local name = player:get_player_name() local ppos = player:getpos() local tod = minetest.get_timeofday() if tod > 0.2 and tod < 0.805 then if beds.player[name] then lay_down(player, nil, nil, false) end minetest.chat_send_player(name, "You can only sleep at night.") return end -- move to bed if not beds.player[name] then lay_down(player, ppos, pos) else lay_down(player, nil, nil, false) end if not is_sp then update_formspecs(false) end -- skip the night and let all players stand up if check_in_beds() then minetest.after(2, function() beds.skip_night() if not is_sp then update_formspecs(true) end beds.kick_players() end) end end -- callbacks minetest.register_on_joinplayer(function(player) beds.read_spawns() end) -- respawn player at bed if enabled and valid position is found minetest.register_on_respawnplayer(function(player) if not enable_respawn then return false end local name = player:get_player_name() local pos = beds.spawn[name] or nil if pos then player:setpos(pos) return true end end) minetest.register_on_leaveplayer(function(player) local name = player:get_player_name() lay_down(player, nil, nil, false, true) beds.player[name] = nil if check_in_beds() then minetest.after(2, function() beds.skip_night() update_formspecs(true) beds.kick_players() end) end end) minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "beds_form" then return end if fields.quit or fields.leave then lay_down(player, nil, nil, false) update_formspecs(false) end if fields.force then beds.skip_night() update_formspecs(true) beds.kick_players() end end)
Fix beds respawn settings check
Fix beds respawn settings check
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
5ecf31705836a7c27adc811fc963ad6c79eabe9a
l2l/list.lua
l2l/list.lua
--[[ A very fast Lua linked list implementation that has a program lifetime. The maximum number of cons cells created is the maximum integer that can be held accurately in a lua number. Likely to have unsolved memory leaks. Garbage Collection not thought through. ]]-- local utils = require("leftry").utils local vector = require("l2l.vector") local data = setmetatable({n=0, free=0}, {}) local list = utils.prototype("list", function(list, ...) if select("#", ...) == 0 then return vector() end local self = setmetatable({position = data.n + 1}, list) local count = select("#", ...) local index = self.position for i=1, count do local datum = (select(i, ...)) data.n = data.n + 1 data[data.n] = datum data.n = data.n + 1 if i < count then data[data.n] = index + i * 2 end end return self end) -- function list:__gc() -- -- Free this cell. -- data[self.position] = nil -- data[self.position + 1] = nil -- data.free = data.free + 1 -- if data.free == data.n then -- -- Take the opportunity to reset `data`. -- data = setmetatable({n=0, free=0}, {}) -- end -- end function list:__tostring() local text = {} local cdr = self local i = 0 while cdr do i = i + 1 local car = cdr:car() if type(car) == "string" then car = utils.escape(car) end text[i] = tostring(car) cdr = cdr:cdr() end return "list("..table.concat(text, ", ")..")" end function list:__ipairs() local cdr = self local i = 0 return function(invariant, state) if not cdr then return end i = i + 1 local car = cdr:car() cdr = cdr:cdr() return i, car end end function list:__len() if not self then return 0 end local cdr = self:cdr() local count = 1 while cdr do count = count + 1 cdr = cdr:cdr() end return count end function list:car() return data[self.position] end function list:cdr() local position = data[self.position + 1] if position then return setmetatable({position = position}, list) end end function list:unpack() if not self then return end local car, cdr = self:car(), self:cdr() if cdr then return car, cdr:unpack() end return car end function list.sub(t, from, to) to = to or #t from = from or 1 return list.cast(t, function(i) return i >= from and i <= to end) end function list.cast(t, f) -- Cast an ipairs-enumerable object into a list. if not t or #t == 0 then return nil end local self = setmetatable({position = data.n + 1}, list) local n = data.n data.n = data.n + #t * 2 for i, v in ipairs(t) do n = n + 1 if f then data[n] = f(v, i) else data[n] = v end n = n + 1 if i < #t then data[n] = n + 1 end end return self end function list:cons(car) -- Prepend car to the list and return a new head. data.n = data.n + 1 local position = data.n data[data.n] = car data.n = data.n + 1 if self then data[data.n] = self.position end return setmetatable({position = position}, list) end return list
-- A very fast Lua linked list implementation that can only add a number of -- items equal to the maximum integer that can be held in a lua number. local utils = require("leftry").utils local vector = require("l2l.vector") local data = setmetatable({n=0, free=0}, {}) local retains = {} local function retain(n) retains[n] = (retains[n] or 0) + 1 local rest = data[n+1] if rest then return retain(rest) end end local function release(n) retains[n] = retains[n] - 1 if retains[n] == 0 then retains[n] = nil data[n] = nil data[n+1] = nil data.free = data.free + 1 end if data.free == data.n then -- Take the opportunity to reset `data`. data = setmetatable({n=0, free=0}, {}) end local rest = data[n+1] if rest then return release(rest) end end local list = utils.prototype("list", function(list, ...) if select("#", ...) == 0 then return vector() end local self = setmetatable({position = data.n + 1}, list) local count = select("#", ...) local index = self.position for i=1, count do local datum = (select(i, ...)) data.n = data.n + 1 data[data.n] = datum data.n = data.n + 1 if i < count then data[data.n] = index + i * 2 end end retain(self.position) return self end) function list:__gc() release(self.position) end function list:__tostring() local text = {} local cdr = self local i = 0 while cdr do i = i + 1 local car = cdr:car() if type(car) == "string" then car = utils.escape(car) end text[i] = tostring(car) cdr = cdr:cdr() end return "list("..table.concat(text, ", ")..")" end function list:__ipairs() local cdr = self local i = 0 return function(invariant, state) if not cdr then return end i = i + 1 local car = cdr:car() cdr = cdr:cdr() return i, car end end function list:__len() if not self then return 0 end local cdr = self:cdr() local count = 1 while cdr do count = count + 1 cdr = cdr:cdr() end return count end function list:car() return data[self.position] end function list:cdr() local position = data[self.position + 1] if position then retain(position) return setmetatable({position = position}, list) end end function list:unpack() if not self then return end local car, cdr = self:car(), self:cdr() if cdr then return car, cdr:unpack() end return car end function list.sub(t, from, to) to = to or #t from = from or 1 return list.cast(t, function(i) return i >= from and i <= to end) end function list.cast(t, f) -- Cast an ipairs-enumerable object into a list. if not t or #t == 0 then return nil end local self = setmetatable({position = data.n + 1}, list) local n = data.n data.n = data.n + #t * 2 for i, v in ipairs(t) do n = n + 1 if f then data[n] = f(v, i) else data[n] = v end n = n + 1 if i < #t then data[n] = n + 1 end end retain(self.position) return self end function list:cons(car) -- Prepend car to the list and return a new head. data.n = data.n + 1 local position = data.n data[data.n] = car data.n = data.n + 1 if self then data[data.n] = self.position end retain(position) return setmetatable({position = position}, list) end return list
Added reference counting to l2l.list. Fixes #39
Added reference counting to l2l.list. Fixes #39
Lua
bsd-2-clause
meric/l2l,carloscm/l2l
99c8b21386c2e94e57dfbcc6cc43ed785ba660c7
src/gluttony.lua
src/gluttony.lua
local sentinel = {} local end_program = {} local function exit (operands) print ('result', unpack (operands)) print ('exit') end local function quote (operands) return operands end local function operator_prototype (operators, execute) local delimit_counter = 1 local delimiter = sentinel local operands = {} local handle_operands = function (_) table.insert (operands, _) end local handle_quoted_operators = function (_) delimit_counter = delimit_counter + 1 handle_operands (_) end local handle_operators = function (_) table.insert (operators, operator_prototype (operators, _)) end local check_sequence = function (_) return not (_ == nil or _ == delimiter) end local check_sequence_quoted = function (_) return _ ~= nil and delimit_counter > 0 end if execute == quote then -- suspend execution of quoted check_sequence = check_sequence_quoted handle_operators = handle_quoted_operators elseif -- a special end_program delimiter is required to exit the program execute == exit then delimiter = end_program end return function (...) local args = {...} local _ while (function () _ = table.remove (args, 1) if _ == delimiter then delimit_counter = delimit_counter - 1 end return check_sequence (_) end) () do if type (_) == 'function' then handle_operators (_) else handle_operands (_) end end -- debug -- print (delimit_counter) -- debug if delimit_counter <= 0 then table.remove (operators) local output = { execute (operands, operators) } for i, v in ipairs (args) do table.insert (output, v) end return output end end end function eval (operands, operators) for i, v in ipairs (operands) do local _ = operators[#operators] (v) while not (_ == nil or #operators == 0) do _ = operators[#operators] (unpack (_)) end end end function processor_prototype () local operators = {} table.insert (operators, operator_prototype (operators, exit)) return function (...) eval ({...}, operators) end end function eval_quotes (operands, operators) for i, v in ipairs (operands) do eval (v, operators) end end local function combinator_prototype (op) return function (operands) local _ = table.remove (operands, 1) for i, v in ipairs (operands) do if type(v) == 'table' then print ('table', unpack (v)) end _ = op (_, v) end return _ end end local add = combinator_prototype (function (x, y) return x + y end) local sub = combinator_prototype (function (x, y) return x - y end) local mul = combinator_prototype (function (x, y) return x * y end) local div = combinator_prototype (function (x, y) return x / y end) local loop loop = function (operands, operators) local idx = operands[1] local limit = operands[2] local step = operands[3] print('loop', unpack (operands)) if idx < limit then table.insert (operators, operator_prototype (operators, loop)) return idx + step, limit, step, sentinel end end local app = processor_prototype () app (add, eval_quotes, quote, div, 1, 2, 3, add, 4, 5, 6, sentinel, sentinel, sentinel, quote, div, 1, 2, 3, add, 4, 5, 6, sentinel, sentinel, sentinel, sentinel, sentinel, end_program)
table.unpack = unpack -- polyfill local sentinel = {} local quote_sentinel = {} local function exit (operands) print ('result', table.unpack (operands)) print ('exit') end local function quote (operands) return operands end local operator_prototype_base local operator_prototype operator_prototype_base = function (operators, execute) local base base = { delimiter = sentinel, delimit_counter = 1, operands = {}, handle_operators = function (_) table.insert (operators, operator_prototype (operators, _)) end, handle_operands = function (_) table.insert (base.operands, _) end, run = function (...) local args = {...} local _ while (function () _ = table.remove (args, 1) if _ == base.delimiter then base.delimit_counter = base.delimit_counter - 1 end return _ ~= nil and base.delimit_counter > 0 end) () do if type (_) == 'function' then base.handle_operators (_) else base.handle_operands (_) end end -- debug print (base.delimit_counter) -- debug if base.delimit_counter <= 0 then for i = #operators, 1, -1 do -- remove self if operators[i] == base.run then table.remove (operators, i) break end end local output = { execute (base.operands, operators) } for i, v in ipairs (args) do table.insert (output, v) end return output end end } return base end operator_prototype = function (operators, execute) local base = operator_prototype_base (operators, execute) -- polymorphic dispatch if execute == quote then -- suspend execution of quoted base.delimiter = quote_sentinel base.handle_operators = function (_) if _ == quote_sentinel then base.delimit_counter = base.delimit_counter + 1 else base.handle_operands (_) end end elseif execute == exit then base.delimiter = exit end return base.run end function eval (operands, operators) for i, v in ipairs (operands) do local _ = operators[#operators] (v) while not (_ == nil or #operators == 0) do _ = operators[#operators] (table.unpack (_)) end end end function processor_prototype () local operators = {} table.insert (operators, operator_prototype (operators, exit)) return function (...) if #operators > 0 then eval ({...}, operators) else print ('the program had ended its execution, any further invocations are futile') end end end function eval_quotes (operands, operators) for i, v in ipairs (operands) do eval (v, operators) end end local function combinator_prototype (op) return function (operands) local _ = table.remove (operands, 1) for i, v in ipairs (operands) do if type(v) == 'table' then print ('table', table.unpack (v)) end _ = op (_, v) end return _ end end local add = combinator_prototype (function (x, y) return x + y end) local sub = combinator_prototype (function (x, y) return x - y end) local mul = combinator_prototype (function (x, y) return x * y end) local div = combinator_prototype (function (x, y) return x / y end) local loop loop = function (operands, operators) local idx = operands[1] local limit = operands[2] local step = operands[3] print('loop', table.unpack (operands)) if idx < limit then table.insert (operators, operator_prototype (operators, loop)) return idx + step, limit, step, sentinel end end local fork = function (operands, operators) table.insert (operators, operator_prototype (operators, eval_quotes)) local left = operands[1] local right = operands[2] local predicate = operands[3] local evaluated if predicate then evaluated = left else evaluated = right end return evaluated, sentinel end local app = processor_prototype () app (add, eval_quotes, quote, div, 1, 2, 3, add, 4, 5, 6, sentinel, sentinel, quote_sentinel, quote, div, 1, 2, 3, add, 4, 5, 6, sentinel, sentinel, quote_sentinel, sentinel, sentinel, exit) app () app2 = processor_prototype () app2 (fork, quote, add, 1, 2, 3, sentinel, quote_sentinel, quote, sub, 1, 2, 3, sentinel, quote_sentinel, false, sentinel, exit)
Refactored, added a polyfill to fix different Lua versions and implemented a fork primitive.
Refactored, added a polyfill to fix different Lua versions and implemented a fork primitive.
Lua
mit
alisa-dolinsky/Thirst,alisa-dolinsky/Gluttony,Alisaxy/Thirst
b78d0f98165ea999469b281008fa3c5edc2d6676
whisper.lua
whisper.lua
local mod = EPGP:NewModule("whisper", "AceEvent-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local senderMap = {} function mod:CHAT_MSG_WHISPER(event_name, msg, sender) if not UnitInRaid("player") then return end if msg:sub(1, 12):lower() ~= 'epgp standby' then return end local member = msg:sub(13):match("([^ ]+)") if member then -- http://lua-users.org/wiki/LuaUnicode local firstChar, offset = member:match("([%z\1-\127\194-\244][\128-\191]*)()") member = firstChar:upper()..member:sub(offset):lower() else member = sender end senderMap[member] = sender if not EPGP:GetEPGP(member) then SendChatMessage(L["%s is not eligible for EP awards"]:format(member), "WHISPER", nil, sender) elseif EPGP:IsMemberInAwardList(member) then SendChatMessage(L["%s is already in the award list"]:format(member), "WHISPER", nil, sender) else EPGP:SelectMember(member) SendChatMessage(L["%s is added to the award list"]:format(member), "WHISPER", nil, sender) end end local function SendNotifiesAndClearExtras( event_name, names, reason, amount, extras_awarded, extras_reason, extras_amount) EPGP:GetModule("announce"):AnnounceTo( "GUILD", L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"]) if extras_awarded then for member,_ in pairs(extras_awarded) do local sender = senderMap[member] if sender then SendChatMessage(L["%+d EP (%s) to %s"]:format( extras_amount, extras_reason, member), "WHISPER", nil, sender) SendChatMessage( L["%s is now removed from the award list"]:format(member), "WHISPER", nil, sender) end senderMap[member] = nil end end end mod.dbDefaults = { profile = { enable = false, } } mod.optionsName = L["Whisper"] mod.optionsDesc = L["Standby whispers in raid"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."], }, } function mod:OnEnable() self:RegisterEvent("CHAT_MSG_WHISPER") EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras) EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras) end function mod:OnDisable() EPGP.UnregisterAllCallbacks(self) end
local mod = EPGP:NewModule("whisper", "AceEvent-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local senderMap = {} function mod:CHAT_MSG_WHISPER(event_name, msg, sender) if not UnitInRaid("player") then return end if msg:sub(1, 12):lower() ~= 'epgp standby' then return end local member = msg:sub(13):match("([^ ]+)") if member then -- http://lua-users.org/wiki/LuaUnicode local firstChar, offset = member:match("([%z\1-\127\194-\244][\128-\191]*)()") member = firstChar:upper()..member:sub(offset):lower() else member = sender end senderMap[member] = sender if not EPGP:GetEPGP(member) then SendChatMessage(L["%s is not eligible for EP awards"]:format(member), "WHISPER", nil, sender) elseif EPGP:IsMemberInAwardList(member) then SendChatMessage(L["%s is already in the award list"]:format(member), "WHISPER", nil, sender) else EPGP:SelectMember(member) SendChatMessage(L["%s is added to the award list"]:format(member), "WHISPER", nil, sender) end end local function SendNotifiesAndClearExtras( event_name, names, reason, amount, extras_awarded, extras_reason, extras_amount) EPGP:GetModule("announce"):AnnounceTo( "GUILD", L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"]) if extras_awarded then for member,_ in pairs(extras_awarded) do local sender = senderMap[member] if sender then SendChatMessage(L["%+d EP (%s) to %s"]:format( extras_amount, extras_reason, member), "WHISPER", nil, sender) EPGP:DeSelectMember(member) SendChatMessage( L["%s is now removed from the award list"]:format(member), "WHISPER", nil, sender) end senderMap[member] = nil end end end mod.dbDefaults = { profile = { enable = false, } } mod.optionsName = L["Whisper"] mod.optionsDesc = L["Standby whispers in raid"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."], }, } function mod:OnEnable() self:RegisterEvent("CHAT_MSG_WHISPER") EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras) EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras) end function mod:OnDisable() EPGP.UnregisterAllCallbacks(self) end
Remove members from standby list after a mass EP award.
Remove members from standby list after a mass EP award. This fixes issue 476.
Lua
bsd-3-clause
ceason/epgp-tfatf,sheldon/epgp,sheldon/epgp,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded
aca879d9eb9b6d973bb26e8d5a7eb5ba0e5bd43a
libs/util.lua
libs/util.lua
-- ivar2 IRC utilities and more -- vim: set noexpandtab: local reset = function(s) return '\015' end local bold = function(s) return string.format("\002%s\002", s) end local underline = function(s) return string.format("\031%s\031", s) end local italic = function(s) return string.format("\029%s\029", s) end local reverse = function(s) return string.format("\018%s\018", s) end local rot13 = function(s) local byte_a, byte_A = string.byte('a'), string.byte('A') return (string.gsub((s or ''), "[%a]", function (char) local offset = (char < 'a') and byte_A or byte_a local b = string.byte(char) - offset -- 0 to 25 b = ((b + 13) % 26) + offset -- Rotate return string.char(b) end )) end local color = function(s, color) return string.format("\03%02d%s%s", color, s, reset()) end local urlEncode = function(str) return str:gsub( '([^%w ])', function (c) return string.format ("%%%02X", string.byte(c)) end ):gsub(' ', '+') end local trim = function(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local split = function(str, delim) if str == "" or str == nil then return { } end str = str .. delim local _accum_0 = { } local _len_0 = 1 for m in str:gmatch("(.-)" .. delim) do _accum_0[_len_0] = m _len_0 = _len_0 + 1 end return _accum_0 end local translateWords = function(str, callback, fixCase, nickpat) -- Usage: etc.translateWords(s ,callback) the callback can return new word, false to skip, or nil to keep the same word. local str = assert(str) local callback = assert(callback, "Callback expected") local fixCase = fixCase == nil or fixCase == true local nickpat = nickpat local prev = 1 local result = "" local pat = "()([%w'%-]+)()" if nickpat then pat = "()([%w_'%-%{%}%[%]`%^]+)()" end for wpos, w, wposEnd in str:gmatch(pat) do local wnew = callback(w) if wnew ~= false then result = result .. str:sub(prev, wpos - 1) if wnew then if fixCase then if w == w:lower() then elseif w == w:upper() then wnew = wnew:upper() elseif w:sub(1, 1) == w:sub(1, 1):upper() then wnew = wnew:sub(1, 1):upper() .. wnew:sub(2) end end result = result .. wnew else result = result .. w end if not wnew then wnew = w end end prev = wposEnd end result = result .. str:sub(prev) return result end local nonickalert = function(nicklist, str) -- U+200B, ZERO WIDTH SPACE: "\226\128\139" local s = str or '' local nl = nicklist -- nicklist local zwsp = "\226\128\142" -- LTR nl = nl or {} local nlkeys = {} for nick, t in pairs(nicklist) do nlkeys[nick:lower()] = true end return translateWords(s, function(x) if nlkeys[x:lower()] then return x:sub(1, 1) .. zwsp .. x:sub(2) end end, nil, true) end return { bold=bold, underline=underline, italic=italic, reverse=reverse, color=color, reset=reset, urlEncode=urlEncode, trim=trim, split=split, rot13=rot13, json = require'cjson', simplehttp = require'simplehttp', white=function(s) return color(s, 0) end, black=function(s) return color(s, 1) end, blue=function(s) return color(s, 2) end, green=function(s) return color(s, 3) end, red=function(s) return color(s, 4) end, maroon=function(s) return color(s, 5) end, purple=function(s) return color(s, 6) end, orange=function(s) return color(s, 7) end, yellow=function(s) return color(s, 8) end, lightgreen=function(s) return color(s, 9) end, teal=function(s) return color(s, 10) end, cyan=function(s) return color(s, 11) end, lightblue=function(s) return color(s, 12) end, fuchsia=function(s) return color(s, 13) end, gray=function(s) return color(s, 14) end, lightgray=function(s) return color(s, 15) end, nonickalert=nonickalert, translateWords=translateWords, }
-- ivar2 IRC utilities and more -- vim: set noexpandtab: local reset = function(s) return '\015' end local bold = function(s) return string.format("\002%s\002", s) end local underline = function(s) return string.format("\031%s\031", s) end local italic = function(s) return string.format("\029%s\029", s) end local reverse = function(s) return string.format("\018%s\018", s) end local rot13 = function(s) local byte_a, byte_A = string.byte('a'), string.byte('A') return (string.gsub((s or ''), "[%a]", function (char) local offset = (char < 'a') and byte_A or byte_a local b = string.byte(char) - offset -- 0 to 25 b = ((b + 13) % 26) + offset -- Rotate return string.char(b) end )) end local color = function(s, color) return string.format("\03%02d%s%s", color, s, reset()) end local urlEncode = function(str) return str:gsub( '([^%w ])', function (c) return string.format ("%%%02X", string.byte(c)) end ):gsub(' ', '+') end local trim = function(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local split = function(str, delim) if str == "" or str == nil then return { } end str = str .. delim local _accum_0 = { } local _len_0 = 1 for m in str:gmatch("(.-)" .. delim) do _accum_0[_len_0] = m _len_0 = _len_0 + 1 end return _accum_0 end local translateWords = function(str, callback, fixCase, nickpat) -- Usage: etc.translateWords(s ,callback) the callback can return new word, false to skip, or nil to keep the same word. local str = assert(str) local callback = assert(callback, "Callback expected") local fixCase = fixCase == nil or fixCase == true local nickpat = nickpat local prev = 1 local result = "" local pat = "()([%w'%-]+)()" if nickpat then pat = "()([%w_'%-%{%}%[%]`%^]+)()" end for wpos, w, wposEnd in str:gmatch(pat) do local wnew = callback(w) if wnew ~= false then result = result .. str:sub(prev, wpos - 1) if wnew then if fixCase then if w == w:lower() then elseif w == w:upper() then wnew = wnew:upper() elseif w:sub(1, 1) == w:sub(1, 1):upper() then wnew = wnew:sub(1, 1):upper() .. wnew:sub(2) end end result = result .. wnew else result = result .. w end if not wnew then wnew = w end end prev = wposEnd end result = result .. str:sub(prev) return result end local nonickalert = function(nicklist, str) -- U+200B, ZERO WIDTH SPACE: "\226\128\139" local s = str or '' local nl = nicklist -- nicklist local zwsp = "\226\128\142" -- LTR nl = nl or {} local nlkeys = {} for nick, t in pairs(nicklist) do nlkeys[nick:lower()] = true end return translateWords(s, function(x) if nlkeys[x:lower()] then return x:sub(1, 1) .. zwsp .. x:sub(2) end end, nil, true) end return { bold=bold, underline=underline, italic=italic, reverse=reverse, color=color, reset=reset, urlEncode=urlEncode, trim=trim, split=split, rot13=rot13, json = require'cjson', simplehttp = require'simplehttp', white=function(s) return color(s, 0) end, black=function(s) return color(s, 1) end, blue=function(s) return color(s, 2) end, green=function(s) return color(s, 3) end, red=function(s) return color(s, 4) end, maroon=function(s) return color(s, 5) end, purple=function(s) return color(s, 6) end, orange=function(s) return color(s, 7) end, yellow=function(s) return color(s, 8) end, lightgreen=function(s) return color(s, 9) end, teal=function(s) return color(s, 10) end, cyan=function(s) return color(s, 11) end, lightblue=function(s) return color(s, 12) end, fuchsia=function(s) return color(s, 13) end, gray=function(s) return color(s, 14) end, lightgray=function(s) return color(s, 15) end, nonickalert=nonickalert, translateWords=translateWords, }
util: Fix mixed indent.
util: Fix mixed indent. Former-commit-id: 4c96d23efba2fa19658c4ec998e5e91d1c9f7a4b [formerly 7e1ef7bd21eee0dc60a3acaac377387c7f963d72] Former-commit-id: b490e65dd3c5f846720dd82c68085aaa48c69732
Lua
mit
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
f43dbe092e487cbc376b946d511479c261a3cce8
extensions/mouse/init.lua
extensions/mouse/init.lua
--- === hs.mouse === --- --- Inspect/manipulate the position of the mouse pointer --- --- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/). local module = require("hs.mouse.internal") local fnutils = require("hs.fnutils") local geometry = require("hs.geometry") local screen = require("hs.screen") -- private variables and methods ----------------------------------------- local deprecation_warnings = {} -- Public interface ------------------------------------------------------ function module.get(...) local state = debug.getinfo(2) local tag = state.short_src..":"..state.currentline if not deprecation_warnings[tag] then print(tag..": hs.mouse.get is deprecated. Please update your code to use hs.mouse.getAbsolutePosition or hs.mouse.getRelativePosition") deprecation_warnings[tag] = true end return module.getAbsolutePosition(...) end function module.set(...) local state = debug.getinfo(2) local tag = state.short_src..":"..state.currentline if not deprecation_warnings[tag] then print(tag..": hs.mouse.set is deprecated. Please update your code to use hs.mouse.setAbsolutePosition or hs.mouse.setRelativePosition") deprecation_warnings[tag] = true end return module.setAbsolutePosition(...) end --- hs.mouse.getRelativePosition() -> point or nil --- Function --- Gets the co-ordinates of the mouse pointer, relative to the screen it is on --- --- Parameters: --- * None --- --- Returns: --- * A point-table containing the relative x and y co-ordinates of the mouse pointer, or nil if an error occured --- --- Notes: --- * The co-ordinates returned by this function are relative to the top left pixel of the screen the mouse is on (see `hs.mouse.getAbsolutePosition` if you need the location in the full desktop space) function module.getRelativePosition() local screen = module.getCurrentScreen() if screen == nil then return nil end local frame = screen:fullFrame() local point = module.getAbsolutePosition() local rel = {} rel["x"] = point["x"] - frame["x"] rel["y"] = point["y"] - frame["y"] return rel end --- hs.mouse.setRelativePosition(point[, screen]) --- Function --- Sets the co-ordinates of the mouse pointer, relative to a screen --- --- Parameters: --- * point - A point-table containing the relative x and y co-ordinates to move the mouse pointer to --- * screen - An optional `hs.screen` object. Defaults to the screen the mouse pointer is currently on --- --- Returns: --- * None function module.setRelativePosition(point, screen) if screen == nil then screen = module.getCurrentScreen() if screen == nil then print("ERROR: Unable to find the current screen") return nil end end local frame = screen:fullFrame() local abs = {} abs["x"] = frame["x"] + point["x"] abs["y"] = frame["y"] + point["y"] return module.setAbsolutePosition(abs) end --- hs.mouse.getCurrentScreen() -> screen or nil --- Function --- Gets the screen the mouse pointer is on --- --- Parameters: --- * None --- --- Returns: --- * An `hs.screen` object that the mouse pointer is on, or nil if an error occurred function module.getCurrentScreen() local point = module.getAbsolutePosition() return fnutils.find(screen.allScreens(), function(aScreen) return geometry.isPointInRect(point, aScreen:fullFrame()) end) end --- hs.mouse.getButtons() -> table --- Function --- Returns a table containing the current mouse buttons being pressed *at this instant*. --- --- Parameters: --- None --- --- Returns: --- * Returns an array containing indicies starting from 1 up to the highest numbered button currently being pressed where the index is `true` if the button is currently pressed or `false` if it is not. --- * Special hash tag synonyms for `left` (button 1), `right` (button 2), and `middle` (button 3) are also set to true if these buttons are currently being pressed. --- --- Notes: --- * This function is a wrapper to `hs.eventtap.checkMouseButtons` --- * This is an instantaneous poll of the current mouse buttons, not a callback. function module.getButtons(...) return require("hs.eventtap").checkMouseButtons(...) end -- Return Module Object -------------------------------------------------- return module
--- === hs.mouse === --- --- Inspect/manipulate the position of the mouse pointer --- --- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/). local module = require("hs.mouse.internal") local fnutils = require("hs.fnutils") local geometry = require("hs.geometry") local screen = require("hs.screen") -- private variables and methods ----------------------------------------- local deprecation_warnings = {} -- Public interface ------------------------------------------------------ function module.get(...) local state = debug.getinfo(2) local tag = state.short_src..":"..state.currentline if not deprecation_warnings[tag] then print(tag..": hs.mouse.get is deprecated. Please update your code to use hs.mouse.getAbsolutePosition or hs.mouse.getRelativePosition") deprecation_warnings[tag] = true end return module.getAbsolutePosition(...) end function module.set(...) local state = debug.getinfo(2) local tag = state.short_src..":"..state.currentline if not deprecation_warnings[tag] then print(tag..": hs.mouse.set is deprecated. Please update your code to use hs.mouse.setAbsolutePosition or hs.mouse.setRelativePosition") deprecation_warnings[tag] = true end return module.setAbsolutePosition(...) end --- hs.mouse.getRelativePosition() -> point or nil --- Function --- Gets the co-ordinates of the mouse pointer, relative to the screen it is on --- --- Parameters: --- * None --- --- Returns: --- * A point-table containing the relative x and y co-ordinates of the mouse pointer, or nil if an error occured --- --- Notes: --- * The co-ordinates returned by this function are relative to the top left pixel of the screen the mouse is on (see `hs.mouse.getAbsolutePosition` if you need the location in the full desktop space) function module.getRelativePosition() local currentScreen = module.getCurrentScreen() if currentScreen == nil then return nil end local frame = currentScreen:fullFrame() local point = module.getAbsolutePosition() local rel = {} rel["x"] = point["x"] - frame["x"] rel["y"] = point["y"] - frame["y"] return rel end --- hs.mouse.setRelativePosition(point[, screen]) --- Function --- Sets the co-ordinates of the mouse pointer, relative to a screen --- --- Parameters: --- * point - A point-table containing the relative x and y co-ordinates to move the mouse pointer to --- * screen - An optional `hs.screen` object. Defaults to the screen the mouse pointer is currently on --- --- Returns: --- * None function module.setRelativePosition(point, currentScreen) if currentScreen == nil then currentScreen = module.getCurrentScreen() if currentScreen == nil then print("ERROR: Unable to find the current screen") return nil end end local frame = currentScreen:fullFrame() local abs = {} abs["x"] = frame["x"] + point["x"] abs["y"] = frame["y"] + point["y"] return module.setAbsolutePosition(abs) end --- hs.mouse.getCurrentScreen() -> screen or nil --- Function --- Gets the screen the mouse pointer is on --- --- Parameters: --- * None --- --- Returns: --- * An `hs.screen` object that the mouse pointer is on, or nil if an error occurred function module.getCurrentScreen() local point = module.getAbsolutePosition() return fnutils.find(screen.allScreens(), function(aScreen) return geometry.isPointInRect(point, aScreen:fullFrame()) end) end --- hs.mouse.getButtons() -> table --- Function --- Returns a table containing the current mouse buttons being pressed *at this instant*. --- --- Parameters: --- None --- --- Returns: --- * Returns an array containing indicies starting from 1 up to the highest numbered button currently being pressed where the index is `true` if the button is currently pressed or `false` if it is not. --- * Special hash tag synonyms for `left` (button 1), `right` (button 2), and `middle` (button 3) are also set to true if these buttons are currently being pressed. --- --- Notes: --- * This function is a wrapper to `hs.eventtap.checkMouseButtons` --- * This is an instantaneous poll of the current mouse buttons, not a callback. function module.getButtons(...) return require("hs.eventtap").checkMouseButtons(...) end -- Return Module Object -------------------------------------------------- return module
Cleanup hs.mouse
Cleanup hs.mouse - Fixed @stickler-ci bugs
Lua
mit
cmsj/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon
2c9ced17fcb49b7f70015e84d31f01878e93fc5f
src/ui/Timeline.lua
src/ui/Timeline.lua
--================================================================================================== -- Copyright (C) 2014 - 2015 by Robert Machmer = -- = -- Permission is hereby granted, free of charge, to any person obtaining a copy = -- of this software and associated documentation files (the "Software"), to deal = -- in the Software without restriction, including without limitation the rights = -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell = -- copies of the Software, and to permit persons to whom the Software is = -- furnished to do so, subject to the following conditions: = -- = -- The above copyright notice and this permission notice shall be included in = -- all copies or substantial portions of the Software. = -- = -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR = -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, = -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE = -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER = -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, = -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN = -- THE SOFTWARE. = --================================================================================================== local TEXT_FONT = love.graphics.newFont('res/fonts/SourceCodePro-Medium.otf', 15); local DEFAULT_FONT = love.graphics.newFont(12); local MARGIN_LEFT = 10; local MARGIN_RIGHT = 10; local HEIGHT = 30; local TOTAL_STEPS = 128; -- ------------------------------------------------ -- Module -- ------------------------------------------------ local Timeline = {}; -- ------------------------------------------------ -- Constructor -- ------------------------------------------------ function Timeline.new(v, totalCommits, date) local self = {}; local stepWidth = (love.graphics.getWidth() - MARGIN_LEFT - MARGIN_RIGHT) / TOTAL_STEPS; local currentStep = 0; local highlighted = -1; local visible = v; local w, h = 2, -5; --- -- Calculates which timestep the user has clicked on and returns the -- index of the commit which has been mapped to that location. -- @param x - The clicked x-position -- local function calculateCommitIndex(x) return math.floor(totalCommits / (TOTAL_STEPS / math.floor((x / stepWidth)))); end --- -- Maps a certain commit to a timestep. -- local function calculateTimelineIndex(cindex) return math.floor((cindex / totalCommits) * (TOTAL_STEPS - 1) + 1); end function self:draw() if not visible then return end for i = 1, TOTAL_STEPS do if i == highlighted then love.graphics.setColor(200, 0, 0); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w * 2, h * 2.1); elseif i == currentStep then love.graphics.setColor(80, 80, 80); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w * 2, h * 2); else love.graphics.setColor(50, 50, 50); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w, h); end love.graphics.setColor(100, 100, 100); love.graphics.setFont(TEXT_FONT); love.graphics.print(date, love.graphics.getWidth() * 0.5 - TEXT_FONT:getWidth(date) * 0.5, love.graphics.getHeight() - 25); love.graphics.setFont(DEFAULT_FONT) love.graphics.setColor(255, 255, 255); end end function self:update(dt) if love.mouse.getY() > love.graphics.getHeight() - HEIGHT then highlighted = math.floor(love.mouse.getX() / stepWidth); else highlighted = -1; end end function self:setCurrentCommit(commit) currentStep = calculateTimelineIndex(commit); end function self:setCurrentDate(ndate) date = ndate; end function self:toggle() visible = not visible; end function self:getCommitAt(x, y) if y > love.graphics.getHeight() - HEIGHT then return calculateCommitIndex(x); end end function self:resize(nx, ny) stepWidth = (nx - MARGIN_LEFT - MARGIN_RIGHT) / TOTAL_STEPS; end return self; end return Timeline;
--================================================================================================== -- Copyright (C) 2014 - 2015 by Robert Machmer = -- = -- Permission is hereby granted, free of charge, to any person obtaining a copy = -- of this software and associated documentation files (the "Software"), to deal = -- in the Software without restriction, including without limitation the rights = -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell = -- copies of the Software, and to permit persons to whom the Software is = -- furnished to do so, subject to the following conditions: = -- = -- The above copyright notice and this permission notice shall be included in = -- all copies or substantial portions of the Software. = -- = -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR = -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, = -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE = -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER = -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, = -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN = -- THE SOFTWARE. = --================================================================================================== local TEXT_FONT = love.graphics.newFont('res/fonts/SourceCodePro-Medium.otf', 15); local DEFAULT_FONT = love.graphics.newFont(12); local MARGIN_LEFT = 10; local MARGIN_RIGHT = 10; local HEIGHT = 30; local TOTAL_STEPS = 128; -- ------------------------------------------------ -- Module -- ------------------------------------------------ local Timeline = {}; -- ------------------------------------------------ -- Constructor -- ------------------------------------------------ function Timeline.new(v, totalCommits, date) local self = {}; local steps = totalCommits < TOTAL_STEPS and totalCommits or TOTAL_STEPS; local stepWidth = (love.graphics.getWidth() - MARGIN_LEFT - MARGIN_RIGHT) / steps; local currentStep = 0; local highlighted = -1; local visible = v; local w, h = 2, -5; --- -- Calculates which timestep the user has clicked on and returns the -- index of the commit which has been mapped to that location. -- @param x - The clicked x-position -- local function calculateCommitIndex(x) return math.floor(totalCommits / (steps / math.floor((x / stepWidth)))); end --- -- Maps a certain commit to a timestep. -- local function calculateTimelineIndex(cindex) return math.floor((cindex / totalCommits) * (steps - 1) + 1); end function self:draw() if not visible then return end for i = 1, steps do if i == highlighted then love.graphics.setColor(200, 0, 0); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w * 2, h * 2.1); elseif i == currentStep then love.graphics.setColor(80, 80, 80); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w * 2, h * 2); else love.graphics.setColor(50, 50, 50); love.graphics.rectangle('fill', MARGIN_LEFT + (i - 1) * stepWidth, love.graphics.getHeight(), w, h); end love.graphics.setColor(100, 100, 100); love.graphics.setFont(TEXT_FONT); love.graphics.print(date, love.graphics.getWidth() * 0.5 - TEXT_FONT:getWidth(date) * 0.5, love.graphics.getHeight() - 25); love.graphics.setFont(DEFAULT_FONT) love.graphics.setColor(255, 255, 255); end end function self:update(dt) if love.mouse.getY() > love.graphics.getHeight() - HEIGHT then highlighted = math.floor(love.mouse.getX() / stepWidth); else highlighted = -1; end end function self:setCurrentCommit(commit) currentStep = calculateTimelineIndex(commit); end function self:setCurrentDate(ndate) date = ndate; end function self:toggle() visible = not visible; end function self:getCommitAt(x, y) if y > love.graphics.getHeight() - HEIGHT then return calculateCommitIndex(x); end end function self:resize(nx, ny) stepWidth = (nx - MARGIN_LEFT - MARGIN_RIGHT) / steps; end return self; end return Timeline;
Fix #16 - Adjust timeline for repos with less than 128 commits
Fix #16 - Adjust timeline for repos with less than 128 commits The timeline will use the number of commits if it is lower than the TOTAL_STEPS value.
Lua
mit
rm-code/logivi
0e73d944c6e301765e235f201457971236a68ff0
src/lib/cltable.lua
src/lib/cltable.lua
module(..., package.seeall) local ffi = require("ffi") local ctable = require("lib.ctable") function build(keys, values) return setmetatable({ keys = keys, values = values }, {__index=get, __newindex=set}) end function new(params) local ctable_params = {} for k,v in _G.pairs(params) do ctable_params[k] = v end assert(not ctable_params.value_type) ctable_params.value_type = ffi.typeof('uint32_t') return build(ctable.new(ctable_params), {}) end function get(cltable, key) local entry = cltable.keys:lookup_ptr(key) if not entry then return nil end return cltable.values[entry.value] end function set(cltable, key, value) local entry = cltable.keys:lookup_ptr(key) if entry then cltable.values[entry.value] = value if value == nil then cltable.keys:remove_ptr(entry) end elseif value ~= nil then table.insert(cltable.values, value) cltable.keys:add(key, #cltable.values) end end function pairs(cltable) local ctable_next, ctable_max, ctable_entry = cltable.keys:iterate() return function() ctable_entry = ctable_next(ctable_max, ctable_entry) if not ctable_entry then return end return ctable_entry.key, cltable.values[ctable_entry.value] end end function selftest() print("selftest: cltable") local ipv4 = require('lib.protocol.ipv4') local params = { key_type = ffi.typeof('uint8_t[4]') } local cltab = new(params) for i=0,255 do local addr = ipv4:pton('1.2.3.'..i) cltab[addr] = 'hello, '..i end for i=0,255 do local addr = ipv4:pton('1.2.3.'..i) assert(cltab[addr] == 'hello, '..i) end for i=0,255 do -- Remove value that is present. cltab[ipv4:pton('1.2.3.'..i)] = nil -- Remove value that is not present. cltab[ipv4:pton('2.3.4.'..i)] = nil end for k,v in pairs(cltab) do error('not reachable') end print("selftest: ok") end
module(..., package.seeall) local ffi = require("ffi") local ctable = require("lib.ctable") function build(keys, values) return setmetatable({ keys = keys, values = values }, {__index=get, __newindex=set}) end function new(params) local ctable_params = {} for k,v in _G.pairs(params) do ctable_params[k] = v end assert(not ctable_params.value_type) ctable_params.value_type = ffi.typeof('uint32_t') return build(ctable.new(ctable_params), {}) end function get(cltable, key) local entry = cltable.keys:lookup_ptr(key) if not entry then return nil end return cltable.values[entry.value] end function set(cltable, key, value) local entry = cltable.keys:lookup_ptr(key) if entry then cltable.values[entry.value] = value if value == nil then cltable.keys:remove_ptr(entry) end elseif value ~= nil then local idx = #cltable.values + 1 cltable.values[idx] = value cltable.keys:add(key, idx) end end function pairs(cltable) local ctable_next, ctable_max, ctable_entry = cltable.keys:iterate() return function() ctable_entry = ctable_next(ctable_max, ctable_entry) if not ctable_entry then return end return ctable_entry.key, cltable.values[ctable_entry.value] end end function selftest() print("selftest: cltable") local ipv4 = require('lib.protocol.ipv4') local params = { key_type = ffi.typeof('uint8_t[4]') } local cltab = new(params) for i=0,255 do local addr = ipv4:pton('1.2.3.'..i) cltab[addr] = 'hello, '..i end for i=0,255 do local addr = ipv4:pton('1.2.3.'..i) assert(cltab[addr] == 'hello, '..i) end for i=0,255 do -- Remove value that is present. cltab[ipv4:pton('1.2.3.'..i)] = nil -- Remove value that is not present. cltab[ipv4:pton('2.3.4.'..i)] = nil end for k,v in pairs(cltab) do error('not reachable') end print("selftest: ok") end
Fix insertion into sparse cltables
Fix insertion into sparse cltables Previously we would do a table.insert, then assume the index was inserted at #values. However the # operator just returns a filled index for which the next index is nil, and thus table.insert could insert into the middle of a table but we don't know afterwards where that insertion was! So, instead use # to find an insertion point, and don't use table.insert.
Lua
apache-2.0
dpino/snabbswitch,eugeneia/snabb,eugeneia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,dpino/snabb,eugeneia/snabb,dpino/snabbswitch,Igalia/snabb,eugeneia/snabb,Igalia/snabb,dpino/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,eugeneia/snabb,snabbco/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,eugeneia/snabbswitch,dpino/snabb,dpino/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,dpino/snabb,Igalia/snabb,dpino/snabb,eugeneia/snabb,Igalia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,snabbco/snabb,Igalia/snabb,snabbco/snabb,dpino/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabb,snabbco/snabb,snabbco/snabb,dpino/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabb
40bed7373c15e13536cfeb115a87b818fb1af262
Connectors/Quik/Lua/StockSharp.Quik.lua
Connectors/Quik/Lua/StockSharp.Quik.lua
------------------------------------------------------------------------- -- StockSharp QUIK Lua Fix Server (c) 2015 http://stocksharp.com -- ------------------------------------------------------------------------- ------------------------------------------------------------------------- -- ------------------------------------------------------------------------- -- . -- 1 - Debug -- 2 - Info -- 3 - Warning -- 4 - Error LogLevel=2 -- ( ), -- -. -- LogFile="StockSharp.QuikLua" -- . , . -- , . -- IncrementalDepthUpdates=false ------------------------------------------------------------------------- ------------------------------------------------------------------------- -- QUIK Lua Fix ------------------------------------------------------------------------- -- . -- , FIX . -- , 5001. -- ServerPort=5001 -- , FIX . -- , -- ( ). -- ServerLogin="quik" -- , FIX . -- ServerPassword="quik" ------------------------------------------------------------------------- ------------------------------------------------------------------------- -- Lua ( ) ------------------------------------------------------------------------- package.path = "" package.cpath = getScriptPath() .. "\\StockSharp.QuikLua.dll" require("StockSharp") -------------------------------------------------------------------------
------------------------------------------------------------------------- -- StockSharp QUIK Lua Fix Server (c) 2015 http://stocksharp.com -- ------------------------------------------------------------------------- -- . ------------------------------------------------------------------------- -- ------------------------------------------------------------------------- -- . -- 1 - Debug -- 2 - Info -- 3 - Warning -- 4 - Error LogLevel=2 -- ( ), -- -. -- LogFile="StockSharp.QuikLua" ------------------------------------------------------------------------- ------------------------------------------------------------------------- -- QUIK Lua Fix ------------------------------------------------------------------------- -- , FIX . -- , 5001. -- ServerPort=5001 -- , FIX . -- , -- ( ). -- ServerLogin="quik" -- , FIX . -- ServerPassword="quik" ------------------------------------------------------------------------- ------------------------------------------------------------------------- -- - ------------------------------------------------------------------------- -- . , -- . -- , . -- IncrementalDepthUpdates=false ------------------------------------------------------------------------- ------------------------------------------------------------------------- -- Lua ( ) ------------------------------------------------------------------------- package.path = "" package.cpath = getScriptPath() .. "\\StockSharp.QuikLua.dll" require("StockSharp") -------------------------------------------------------------------------
Quik.lua Fix formatting
Quik.lua Fix formatting
Lua
apache-2.0
risty/StockSharp,Shadance/StockSharp,Sergey-Dvortsov/StockSharp,dmDen/StockSharp,StockSharp/StockSharp
6b25769bbed48480407923e75044d8b0dc1f294e
src/logging/sql.lua
src/logging/sql.lua
------------------------------------------------------------------------------- -- Saves the logging information in a table using luasql -- -- @author Thiago Costa Ponte ([email protected]) -- -- @copyright 2004-2007 Kepler Project -- -- @release $Id: sql.lua,v 1.4 2007-09-05 12:15:31 tomas Exp $ ------------------------------------------------------------------------------- require"logging" function logging.sql(params) params = params or {} params.tablename = params.tablename or "LogTable" params.logdatefield = params.logdatefield or "LogDate" params.loglevelfield = params.loglevelfield or "LogLevel" params.logmessagefield = params.logmessagefield or "LogMessage" if params.connectionfactory == nil or type(params.connectionfactory) ~= "function" then return nil, "No specified connection factory function" end local con, err if params.keepalive then con, err = params.connectionfactory() end return logging.new( function(self, level, message) if (not params.keepalive) or (con == nil) then con, err = params.connectionfactory() if not con then return nil, err end end local logDate = os.date("%Y-%m-%d %H:%M:%S") local insert = string.format("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')", params.tablename, params.logdatefield, params.loglevelfield, params.logmessagefield, logDate, level, message) local ret, err = pcall(con.execute, con, insert) if not ret then con, err = params.connectionfactory() if not con then return nil, err end ret, err = con:execute(insert) if not ret then return nil, err end end if not params.keepalive then con:close() end return true end ) end
------------------------------------------------------------------------------- -- Saves the logging information in a table using luasql -- -- @author Thiago Costa Ponte ([email protected]) -- -- @copyright 2004-2007 Kepler Project -- -- @release $Id: sql.lua,v 1.5 2008-01-17 16:25:46 carregal Exp $ ------------------------------------------------------------------------------- require"logging" function logging.sql(params) params = params or {} params.tablename = params.tablename or "LogTable" params.logdatefield = params.logdatefield or "LogDate" params.loglevelfield = params.loglevelfield or "LogLevel" params.logmessagefield = params.logmessagefield or "LogMessage" if params.connectionfactory == nil or type(params.connectionfactory) ~= "function" then return nil, "No specified connection factory function" end local con, err if params.keepalive then con, err = params.connectionfactory() end return logging.new( function(self, level, message) if (not params.keepalive) or (con == nil) then con, err = params.connectionfactory() if not con then return nil, err end end local logDate = os.date("%Y-%m-%d %H:%M:%S") local insert = string.format("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')", params.tablename, params.logdatefield, params.loglevelfield, params.logmessagefield, logDate, level, string.gsub(message, "'", "''")) local ret, err = pcall(con.execute, con, insert) if not ret then con, err = params.connectionfactory() if not con then return nil, err end ret, err = con:execute(insert) if not ret then return nil, err end end if not params.keepalive then con:close() end return true end ) end
Escaping the message before inserting it into the SQL database. Fix by Christopher Smith
Escaping the message before inserting it into the SQL database. Fix by Christopher Smith
Lua
mit
mwchase/log4l,Neopallium/lualogging,StoneDot/lualogging
c7250a0a3d796aaa15eb0076af6ea2379fb253e8
cmus-widget/cmus.lua
cmus-widget/cmus.lua
------------------------------------------------- -- Cmus Widget for Awesome Window Manager -- Show what's playing, play/pause, etc -- @author Augusto Gunsch -- @copyright 2022 Augusto Gunsch ------------------------------------------------- local awful = require("awful") local wibox = require("wibox") local watch = require("awful.widget.watch") local spawn = require("awful.spawn") local naughty = require("naughty") local cmus_widget = {} local function show_warning(message) naughty.notify{ preset = naughty.config.presets.critical, title = "Cmus Widget", text = message} end local function worker(user_args) local args = user_args or {} local font = args.font or "Play 9" local path_to_icons = args.path_to_icons or "/usr/share/icons/Arc/actions/symbolic/" local timeout = args.timeout or 10 local space = args.space or 3 cmus_widget.widget = wibox.widget { { { id = "playback_icon", resize = false, widget = wibox.widget.imagebox, }, layout = wibox.container.place }, { id = "text", font = font, widget = wibox.widget.textbox }, spacing = space, layout = wibox.layout.fixed.horizontal, update_icon = function(self, name) self:get_children_by_id("playback_icon")[1]:set_image(path_to_icons .. name) end, set_title = function(self, title) self:get_children_by_id("text")[1]:set_text(title) end } function update_widget(widget, stdout, _, _, code) if code == 0 then local cmus_info = {} for s in stdout:gmatch("[^\r\n]+") do local key, val = string.match(s, "^tag (%a+) (.+)$") if key and val then cmus_info[key] = val else local key, val = string.match(s, "^set (%a+) (.+)$") if key and val then cmus_info[key] = val else local key, val = string.match(s, "^(%a+) (.+)$") if key and val then cmus_info[key] = val end end end end local title = cmus_info.title if not title and cmus_info.file then title = cmus_info.file:gsub("%..-$", "") title = title:gsub("^.+/", "") end if title then if cmus_info["status"] == "playing" then widget:update_icon("media-playback-start-symbolic.svg") elseif cmus_info["status"] == "paused" then widget:update_icon("media-playback-pause-symbolic.svg") else widget:update_icon("media-playback-stop-symbolic.svg") end widget:set_title(title) widget.visible = true else widget.visible = false widget.width = 0 end else widget.visible = false end end function cmus_widget:play_pause() spawn("cmus-remote -u") spawn.easy_async("cmus-remote -Q", function(stdout, _, _, code) update_widget(cmus_widget.widget, stdout, _, _, code) end) end cmus_widget.widget:buttons( awful.util.table.join( awful.button({}, 1, function() cmus_widget:play_pause() end) ) ) watch("cmus-remote -Q", timeout, update_widget, cmus_widget.widget) return cmus_widget.widget end return setmetatable(cmus_widget, { __call = function(_, ...) return worker(...) end })
------------------------------------------------- -- Cmus Widget for Awesome Window Manager -- Show what's playing, play/pause, etc -- @author Augusto Gunsch -- @copyright 2022 Augusto Gunsch ------------------------------------------------- local awful = require("awful") local wibox = require("wibox") local watch = require("awful.widget.watch") local spawn = require("awful.spawn") local naughty = require("naughty") local cmus_widget = {} local function worker(user_args) local args = user_args or {} local font = args.font or "Play 9" local path_to_icons = args.path_to_icons or "/usr/share/icons/Arc/actions/symbolic/" local timeout = args.timeout or 10 local space = args.space or 3 cmus_widget.widget = wibox.widget { { { id = "playback_icon", resize = false, widget = wibox.widget.imagebox, }, layout = wibox.container.place }, { id = "text", font = font, widget = wibox.widget.textbox }, spacing = space, layout = wibox.layout.fixed.horizontal, update_icon = function(self, name) self:get_children_by_id("playback_icon")[1]:set_image(path_to_icons .. name) end, set_title = function(self, title) self:get_children_by_id("text")[1]:set_text(title) end } local function update_widget(widget, stdout, _, _, code) if code == 0 then local cmus_info = {} for s in stdout:gmatch("[^\r\n]+") do local key, val = string.match(s, "^tag (%a+) (.+)$") if key and val then cmus_info[key] = val else key, val = string.match(s, "^set (%a+) (.+)$") if key and val then cmus_info[key] = val else key, val = string.match(s, "^(%a+) (.+)$") if key and val then cmus_info[key] = val end end end end local title = cmus_info.title if not title and cmus_info.file then title = cmus_info.file:gsub("%..-$", "") title = title:gsub("^.+/", "") end if title then if cmus_info["status"] == "playing" then widget:update_icon("media-playback-start-symbolic.svg") elseif cmus_info["status"] == "paused" then widget:update_icon("media-playback-pause-symbolic.svg") else widget:update_icon("media-playback-stop-symbolic.svg") end widget:set_title(title) widget.visible = true else widget.visible = false widget.width = 0 end else widget.visible = false end end function cmus_widget:play_pause() spawn("cmus-remote -u") spawn.easy_async("cmus-remote -Q", function(stdout, _, _, code) update_widget(cmus_widget.widget, stdout, _, _, code) end) end cmus_widget.widget:buttons( awful.util.table.join( awful.button({}, 1, function() cmus_widget:play_pause() end) ) ) watch("cmus-remote -Q", timeout, update_widget, cmus_widget.widget) return cmus_widget.widget end return setmetatable(cmus_widget, { __call = function(_, ...) return worker(...) end })
Fix warnings
Fix warnings
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
7729b7b6c51a90c549f65b9b177f26d670724e96
vendor/lua/exec.lua
vendor/lua/exec.lua
local ffi = require "ffi" local C = ffi.C local exec = {} ffi.cdef([[ static const int EINTR = 4; /* Interrupted system call */ static const int EAGAIN = 11; /* Try again */ typedef int32_t pid_t; pid_t fork(void); pid_t waitpid(pid_t pid, int *status, int options); char *strerror(int errnum); int open(const char *pathname, int flags, int mode); int close(int fd); int dup2(int oldfd, int newfd); int setenv(const char*, const char*, int); int execvp(const char *file, char *const argv[]); int chdir(const char *); ]]) local ffi_error = function(s) s = s or "error" return string.format("%s: %s\n", s, ffi.string(C.strerror(ffi.errno()))) end local octal = function(n) return tonumber(n, 8) end local STDOUT = 1 local STDERR = 2 local ERETRY = function(fn) return function(...) local r, e repeat r = fn(...) e = ffi.errno() if r ~= -1 then break end until((e ~= C.EINTR) and (e ~= C.EAGAIN)) return r, e end end -- dest should be either 0 or 1 (STDOUT or STDERR) local redirect = function(io_or_filename, dest_fd) if io_or_filename == nil then return true end local O_WRONLY = octal('0001') local O_CREAT = octal('0100') local S_IRUSR = octal('00400') -- user has read permission local S_IWUSR = octal('00200') -- user has write permission -- first check for regular if (io_or_filename == io.stdout or io_or_filename == STDOUT) and dest_fd ~= STDOUT then C.dup2(STDERR, STDOUT) elseif (io_or_filename == io.stderr or io_or_filename == STDERR) and dest_fd ~= STDERR then C.dup2(STDOUT, STDERR) -- otherwise handle file-based redirection else local fd = C.open(io_or_filename, bit.bor(O_WRONLY, O_CREAT), bit.bor(S_IRUSR, S_IWUSR)) if fd < 0 then return nil, ffi_error(string.format("failure opening file '%s'", fname)) end C.dup2(fd, dest_fd) C.close(fd) end end exec.spawn = function (exe, args, env, cwd, stdout_redirect, stderr_redirect) args = args or {} local pid = C.fork() if pid < 0 then return nil, ffi_error("fork(2) failed") elseif pid == 0 then -- child process redirect(stdout_redirect, STDOUT) redirect(stderr_redirect, STDERR) local string_array_t = ffi.typeof('const char *[?]') -- local char_p_k_p_t = ffi.typeof('char *const*') -- args is 1-based Lua table, argv is 0-based C array -- automatically NULL terminated local argv = string_array_t(#args + 1 + 1) for i = 1, #args do argv[i] = tostring(args[i]) end do local function setenv(name, value) local overwrite_flag = 1 if C.setenv(name, value, overwrite_flag) == -1 then return nil, ffi_error("setenv(3) failed") else return value end end for name, value in pairs(env or {}) do local x, e = setenv(name, tostring(value)) if x == nil then return nil, e end end end if cwd then if C.chdir(tostring(cwd)) == -1 then return nil, ffi_error("chdir(2) failed") end end argv[0] = exe argv[#args + 1] = nil if C.execvp(exe, ffi.cast("char *const*", argv)) == -1 then return nil, ffi_error("execvp(3) failed") end assert(nil, "assertion failed: exec.spawn (should be unreachable!)") else if ERETRY(C.waitpid)(pid, nil, 0) == -1 then return nil, ffi_error("waitpid(2) failed") end end end exec.context = function(exe) local args = {} return setmetatable(args, {__call = function(_, ...) local n = select("#", ...) if n == 1 then for k in string.gmatch(..., "%S+") do args[#args+1] = k end elseif n > 1 then for _, k in ipairs({...}) do args[#args+1] = k end end return exec.spawn(exe, args, args.env, args.cwd, args.stdout, args.stderr) end}) end exec.ctx = exec.context exec.cmd = setmetatable({}, {__index = function (_, exe) return function(...) local args if not (...) then args = {} elseif type(...) == "table" then args = ... else args = {...} end return exec.spawn(exe, args, args.env, args.cwd, args.stdout, args.stderr) end end }) return exec
local ffi = require "ffi" local C = ffi.C local exec = {} ffi.cdef([[ static const int EINTR = 4; /* Interrupted system call */ static const int EAGAIN = 11; /* Try again */ typedef int32_t pid_t; pid_t fork(void); pid_t waitpid(pid_t pid, int *status, int options); char *strerror(int errnum); int open(const char *pathname, int flags, int mode); int close(int fd); int dup2(int oldfd, int newfd); int setenv(const char*, const char*, int); int execvp(const char *file, char *const argv[]); int chdir(const char *); ]]) local ffi_error = function(s) s = s or "error" return string.format("%s: %s\n", s, ffi.string(C.strerror(ffi.errno()))) end local octal = function(n) return tonumber(n, 8) end local STDOUT = 1 local STDERR = 2 local ERETRY = function(fn) return function(...) local r, e repeat r = fn(...) e = ffi.errno() if r ~= -1 then break end until((e ~= C.EINTR) and (e ~= C.EAGAIN)) return r, e end end -- dest should be either 0 or 1 (STDOUT or STDERR) local redirect = function(io_or_filename, dest_fd) if io_or_filename == nil then return true end local O_WRONLY = octal('0001') local O_CREAT = octal('0100') local S_IRUSR = octal('00400') -- user has read permission local S_IWUSR = octal('00200') -- user has write permission -- first check for regular if (io_or_filename == io.stdout or io_or_filename == STDOUT) and dest_fd ~= STDOUT then C.dup2(STDERR, STDOUT) elseif (io_or_filename == io.stderr or io_or_filename == STDERR) and dest_fd ~= STDERR then C.dup2(STDOUT, STDERR) -- otherwise handle file-based redirection else local fd = C.open(io_or_filename, bit.bor(O_WRONLY, O_CREAT), bit.bor(S_IRUSR, S_IWUSR)) if fd < 0 then return nil, ffi_error(string.format("failure opening file '%s'", fname)) end C.dup2(fd, dest_fd) C.close(fd) end end exec.spawn = function (exe, args, env, cwd, stdout_redirect, stderr_redirect) args = args or {} local pid = C.fork() if pid < 0 then return nil, ffi_error("fork(2) failed") elseif pid == 0 then -- child process redirect(stdout_redirect, STDOUT) redirect(stderr_redirect, STDERR) local string_array_t = ffi.typeof('const char *[?]') -- local char_p_k_p_t = ffi.typeof('char *const*') -- args is 1-based Lua table, argv is 0-based C array -- automatically NULL terminated local argv = string_array_t(#args + 1 + 1) for i = 1, #args do argv[i] = tostring(args[i]) end do local function setenv(name, value) local overwrite_flag = 1 if C.setenv(name, value, overwrite_flag) == -1 then return nil, ffi_error("setenv(3) failed") else return value end end for name, value in pairs(env or {}) do local x, e = setenv(name, tostring(value)) if x == nil then return nil, e end end end if cwd then if C.chdir(tostring(cwd)) == -1 then return nil, ffi_error("chdir(2) failed") end end argv[0] = exe argv[#args + 1] = nil if C.execvp(exe, ffi.cast("char *const*", argv)) == -1 then return nil, ffi_error("execvp(3) failed") end assert(nil, "assertion failed: exec.spawn (should be unreachable!)") else if ERETRY(C.waitpid)(pid, nil, 0) == -1 then return nil, ffi_error("waitpid(2) failed") end end end exec.context = function(exe) local args = {} return setmetatable(args, {__call = function(_, ...) local n = select("#", ...) if n == 1 then for k in string.gmatch(..., "%S+") do args[#args+1] = k end elseif n > 1 then for _, k in ipairs({...}) do args[#args+1] = k end end return exec.spawn(exe, args, args.env, args.cwd, args.stdout, args.stderr) end}) end exec.ctx = exec.context exec.cmd = setmetatable({}, {__index = function (_, exe) return function(...) local args if not (...) then args = {} elseif type(...) == "table" then args = ... else args = {...} end return exec.spawn(exe, args, args.env, args.cwd, args.stdout, args.stderr) end end }) return exec
exec: Fix indention.;
exec: Fix indention.;
Lua
mit
Configi/configi,Configi/configi,Configi/configi,Configi/configi,Configi/configi
f5efd4200d3440f09f32da46cc60433e189ab741
.mjolnir/init.lua
.mjolnir/init.lua
local griderr, grid = pcall(function() return require "mjolnir.bg.grid" end) local windowerr, window = pcall(function() return require "mjolnir.window" end) local hotkeyerr, hotkey = pcall(function() return require "mjolnir.hotkey" end) local alerterr, alert = pcall(function() return require "mjolnir.alert" end) local fnutilserr, fnutils = pcall(function() return require "mjolnir.fnutils" end) function print_if_not_table(var) if not(type(var) == "table") then print(var) end end if not griderr or not windowerr or not hotkeyerr or not alerterr then mjolnir.showerror("Some packages appear to be missing.") print("At least one package was missing. Have you installed the packages? See README.md.") print_if_not_table(grid) print_if_not_table(window) print_if_not_table(hotkey) print_if_not_table(alert) print_if_not_table(fnutils) end mash = {"cmd", "alt", "ctrl"} MARGIN = 2 GRIDWIDTH = 12 GRIDHEIGHT = 9 grid.MARGINX = MARGIN grid.MARGINY = MARGIN -- ternary if function tif(cond, a, b) if cond then return a else return b end end function reset_granularity() grid.GRIDWIDTH = GRIDWIDTH grid.GRIDHEIGHT = GRIDHEIGHT end reset_granularity() function change_granularity(iswidth, del) if iswidth then grid.GRIDWIDTH = grid.GRIDWIDTH + del else grid.GRIDHEIGHT = grid.GRIDHEIGHT + del end alert.show(tif(iswidth, grid.GRIDWIDTH, grid.GRIDHEIGHT)) end function centerpoint() w = grid.GRIDWIDTH - 2 h = grid.GRIDHEIGHT - 2 return { x = 1, y = 1, w = w, h = h } end function fullheightatcolumn(column) return { x = column - 1, y = 0, w = 1, h = grid.GRIDHEIGHT } end local grid_shortcuts = { R = mjolnir.reload, [";"] = function() grid.snap(window.focusedwindow()) end, up = grid.pushwindow_up, left = grid.pushwindow_left, right = grid.pushwindow_right, down = grid.pushwindow_down, A = grid.resizewindow_thinner, D = grid.resizewindow_wider, W = grid.resizewindow_shorter, S = grid.resizewindow_taller, space = grid.maximize_window, F = grid.pushwindow_nextscreen, C = function() grid.set(window.focusedwindow(), centerpoint(), window.focusedwindow():screen()) end, H = function() change_granularity(true, 1) end, J = function() change_granularity(false, 1) end, K = function() change_granularity(false, -1) end, L = function() change_granularity(true, -1) end, ["1"] = function() grid.set(window.focusedwindow(), fullheightatcolumn(1), window.focusedwindow():screen()) end, ["2"] = function() grid.set(window.focusedwindow(), fullheightatcolumn(2), window.focusedwindow():screen()) end, ["3"] = function() grid.set(window.focusedwindow(), fullheightatcolumn(3), window.focusedwindow():screen()) end, ["4"] = function() grid.set(window.focusedwindow(), fullheightatcolumn(4), window.focusedwindow():screen()) end, ["0"] = function() reset_granularity() alert.show(GRIDWIDTH..", "..GRIDHEIGHT) end } for key, func in pairs(grid_shortcuts) do hotkey.bind(mash, key, func) end alert.show(" 🎩\n 💀")
local griderr, grid = pcall(function() return require "mjolnir.bg.grid" end) local windowerr, window = pcall(function() return require "mjolnir.window" end) local hotkeyerr, hotkey = pcall(function() return require "mjolnir.hotkey" end) local alerterr, alert = pcall(function() return require "mjolnir.alert" end) local fnutilserr, fnutils = pcall(function() return require "mjolnir.fnutils" end) function print_if_not_table(var) if not(type(var) == "table") then print(var) end end if not griderr or not windowerr or not hotkeyerr or not alerterr then mjolnir.showerror("Some packages appear to be missing.") print("At least one package was missing. Have you installed the packages? See README.md.") print_if_not_table(grid) print_if_not_table(window) print_if_not_table(hotkey) print_if_not_table(alert) print_if_not_table(fnutils) end mash = {"cmd", "alt", "ctrl"} MARGIN = 2 GRIDWIDTH = 12 GRIDHEIGHT = 9 grid.MARGINX = MARGIN grid.MARGINY = MARGIN -- ternary if function tif(cond, a, b) if cond then return a else return b end end function reset_granularity() grid.GRIDWIDTH = GRIDWIDTH grid.GRIDHEIGHT = GRIDHEIGHT end reset_granularity() function change_granularity(iswidth, del) if iswidth then grid.GRIDWIDTH = grid.GRIDWIDTH + del else grid.GRIDHEIGHT = grid.GRIDHEIGHT + del end alert.show(tif(iswidth, grid.GRIDWIDTH, grid.GRIDHEIGHT)) end function centerpoint() w = grid.GRIDWIDTH - 2 h = grid.GRIDHEIGHT - 2 return { x = 1, y = 1, w = w, h = h } end function fullheightatcolumn(column) return { x = column - 1, y = 0, w = 1, h = grid.GRIDHEIGHT } end function ifwin(fn) return function() local win = window.focusedwindow() if win then fn(win) end end end local grid_shortcuts = { R = mjolnir.reload, [";"] = ifwin(grid.snap), up = ifwin(grid.pushwindow_up), left = ifwin(grid.pushwindow_left), right = ifwin(grid.pushwindow_right), down = ifwin(grid.pushwindow_down), A = ifwin(grid.resizewindow_thinner), D = ifwin(grid.resizewindow_wider), W = ifwin(grid.resizewindow_shorter), S = ifwin(grid.resizewindow_taller), space = ifwin(grid.maximize_window), F = ifwin(grid.pushwindow_nextscreen), C = ifwin(function(win) grid.set(win, centerpoint(), win:screen()) end), H = function() change_granularity(true, 1) end, J = function() change_granularity(false, 1) end, K = function() change_granularity(false, -1) end, L = function() change_granularity(true, -1) end, ["1"] = ifwin(function(win) grid.set(win, fullheightatcolumn(1), win:screen()) end), ["2"] = ifwin(function(win) grid.set(win, fullheightatcolumn(2), win:screen()) end), ["3"] = ifwin(function(win) grid.set(win, fullheightatcolumn(3), win:screen()) end), ["4"] = ifwin(function(win) grid.set(win, fullheightatcolumn(4), win:screen()) end), ["0"] = function() reset_granularity() alert.show(GRIDWIDTH..", "..GRIDHEIGHT) end } for key, func in pairs(grid_shortcuts) do hotkey.bind(mash, key, func) end alert.show(" 🎩\n 💀")
Fix attempt to index local 'win' (a nil value) in mjolnir when there's no focused window
Fix attempt to index local 'win' (a nil value) in mjolnir when there's no focused window
Lua
mit
rileyjshaw/.supermac
67e7219314589f1cfbf1347cfdc9496dae3dd97d
deps/coro-channel.lua
deps/coro-channel.lua
--[[lit-meta name = "creationix/coro-channel" version = "3.0.0" homepage = "https://github.com/luvit/lit/blob/master/deps/coro-channel.lua" description = "An adapter for wrapping uv streams as coro-streams." tags = {"coro", "adapter"} license = "MIT" author = { name = "Tim Caswell" } ]] -- local p = require('pretty-print').prettyPrint local function makeCloser(socket) local closer = { read = false, written = false, errored = false, } local closed = false local function close() if closed then return end closed = true if not closer.readClosed then closer.readClosed = true if closer.onClose() then closer.onClose() end end if not socket:is_closing() then socket:close() end end closer.close = close function closer.check() if closer.errored or (closer.read and closer.written) then return close() end end return closer end local function makeRead(socket, closer) local paused = true local queue = {} local tindex = 0 local dindex = 0 local function dispatch(data) -- p("<-", data[1]) if tindex > dindex then local thread = queue[dindex] queue[dindex] = nil dindex = dindex + 1 assert(coroutine.resume(thread, unpack(data))) else queue[dindex] = data dindex = dindex + 1 if not paused then paused = true assert(socket:read_stop()) end end end closer.onClose = function () if not closer.read then closer.read = true return dispatch {nil, closer.errored} end end local function onRead(err, chunk) if err then closer.errored = err return closer.check() end if not chunk then if closer.read then return end closer.read = true dispatch {} return closer.check() end return dispatch {chunk} end local function read() if dindex > tindex then local data = queue[tindex] queue[tindex] = nil tindex = tindex + 1 return unpack(data) end if paused then paused = false assert(socket:read_start(onRead)) end queue[tindex] = coroutine.running() tindex = tindex + 1 return coroutine.yield() end -- Auto use wrapper library for backwards compat return read end local function makeWrite(socket, closer) local function wait() local thread = coroutine.running() return function (err) assert(coroutine.resume(thread, err)) end end local function write(chunk) if closer.written then return nil, "already shutdown" end -- p("->", chunk) if chunk == nil then closer.written = true closer.check() if socket:shutdown(wait()) then return coroutine.yield() else return nil end end local success, err = socket:write(chunk, wait()) if not success then closer.errored = err closer.check() return nil, err end err = coroutine.yield() return not err, err end return write end local function wrapRead(socket) local closer = makeCloser(socket) closer.written = true return makeRead(socket, closer), closer.close end local function wrapWrite(socket) local closer = makeCloser(socket) closer.read = true return makeWrite(socket, closer), closer.close end local function wrapStream(socket) assert(socket and socket.write and socket.shutdown and socket.read_start and socket.read_stop and socket.is_closing and socket.close, "socket does not appear to be a socket/uv_stream_t") local closer = makeCloser(socket) return makeRead(socket, closer), makeWrite(socket, closer), closer.close end return { wrapRead = wrapRead, wrapWrite = wrapWrite, wrapStream = wrapStream, }
--[[lit-meta name = "creationix/coro-channel" version = "3.0.0" homepage = "https://github.com/luvit/lit/blob/master/deps/coro-channel.lua" description = "An adapter for wrapping uv streams as coro-streams." tags = {"coro", "adapter"} license = "MIT" author = { name = "Tim Caswell" } ]] -- local p = require('pretty-print').prettyPrint local function makeCloser(socket) local closer = { read = false, written = false, errored = false, } local closed = false local function close() if closed then return end closed = true if not closer.readClosed then closer.readClosed = true if closer.onClose() then closer.onClose() end end if not socket:is_closing() then socket:close() end end closer.close = close function closer.check() if closer.errored or (closer.read and closer.written) then return close() end end return closer end local function makeRead(socket, closer) local paused = true local queue = {} local tindex = 0 local dindex = 0 local function dispatch(data) -- p("<-", data[1]) if tindex > dindex then local thread = queue[dindex] queue[dindex] = nil dindex = dindex + 1 assert(coroutine.resume(thread, unpack(data))) else queue[dindex] = data dindex = dindex + 1 if not paused then paused = true assert(socket:read_stop()) end end end closer.onClose = function () if not closer.read then closer.read = true return dispatch {nil, closer.errored} end end local function onRead(err, chunk) if err then closer.errored = err return closer.check() end if not chunk then if closer.read then return end closer.read = true dispatch {} return closer.check() end return dispatch {chunk} end local function read() if dindex > tindex then local data = queue[tindex] queue[tindex] = nil tindex = tindex + 1 return unpack(data) end if paused then paused = false assert(socket:read_start(onRead)) end queue[tindex] = coroutine.running() tindex = tindex + 1 return coroutine.yield() end -- Auto use wrapper library for backwards compat return read end local function makeWrite(socket, closer) local function wait() local thread = coroutine.running() return function (err) assert(coroutine.resume(thread, err)) end end local function write(chunk) if closer.written then return nil, "already shutdown" end -- p("->", chunk) if chunk == nil then closer.written = true closer.check() local success, err = socket:shutdown(wait()) if not success then return nil, err end err = coroutine.yield() return not err, err end local success, err = socket:write(chunk, wait()) if not success then closer.errored = err closer.check() return nil, err end err = coroutine.yield() return not err, err end return write end local function wrapRead(socket) local closer = makeCloser(socket) closer.written = true return makeRead(socket, closer), closer.close end local function wrapWrite(socket) local closer = makeCloser(socket) closer.read = true return makeWrite(socket, closer), closer.close end local function wrapStream(socket) assert(socket and socket.write and socket.shutdown and socket.read_start and socket.read_stop and socket.is_closing and socket.close, "socket does not appear to be a socket/uv_stream_t") local closer = makeCloser(socket) return makeRead(socket, closer), makeWrite(socket, closer), closer.close end return { wrapRead = wrapRead, wrapWrite = wrapWrite, wrapStream = wrapStream, }
Fixes coro-channel shutdown consistency
Fixes coro-channel shutdown consistency
Lua
apache-2.0
luvit/lit,zhaozg/lit
43a2f6e698b672ac7997ed1ccb64303158594d1c
particles.lua
particles.lua
Particle = {} function Particle.ballImpactWithPlayer() local tex = love.graphics.newImage("assets/textures/smoke.png") local emitter = love.graphics.newParticleSystem(tex,10) emitter:setDirection(0) emitter:setAreaSpread("uniform",8,16) emitter:setEmissionRate(10) emitter:setEmitterLifetime(-1) emitter:setLinearAcceleration(0,0,0,0) emitter:setParticleLifetime(1,1) emitter:setRadialAcceleration(0,0) emitter:setRotation(0,0) emitter:setTangentialAcceleration(0,0) emitter:setSpeed(0,0) emitter:setSpin(0,0) emitter:setSpinVariation(0) emitter:setLinearDamping(0,0) emitter:setSpread(0) emitter:setRelativeRotation(false) emitter:setOffset(0,0) emitter:setSizes(1) emitter:setSizeVariation(0) emitter:setColors(255,255,255,255 ) return emitter; end function Particle.ballImpactWithAnything() local tex = love.graphics.newImage("assets/textures/spark.png") local emitter = love.graphics.newParticleSystem(tex,50) emitter:setDirection(6.9388939039072e-16) emitter:setAreaSpread("none",0,0) emitter:setEmissionRate(357) emitter:setEmitterLifetime(0.10000000149012) emitter:setLinearAcceleration(0,0,0,0) emitter:setParticleLifetime(0,0.5) emitter:setRadialAcceleration(0,0) emitter:setRotation(0,0) emitter:setTangentialAcceleration(0,0) emitter:setSpeed(88,90) emitter:setSpin(0,0) emitter:setSpinVariation(2.7755575615629e-17) emitter:setLinearDamping(0,2) emitter:setSpread(6.1999998092651) emitter:setRelativeRotation(false) emitter:setOffset(2.5,2.5) emitter:setSizes(1,1,1,1,1,1,1,1) emitter:setSizeVariation(1) emitter:setColors(255,255,255,255 ) return emitter; end
Particle = {} function Particle.ballImpactWithPlayer() local tex = love.graphics.newImage("assets/textures/smoke.png") local emitter = love.graphics.newParticleSystem(tex,10) emitter:setDirection(6.9388939039072e-16) emitter:setAreaSpread("none",0,0) emitter:setEmissionRate(357) emitter:setEmitterLifetime(0.10000000149012) emitter:setLinearAcceleration(0,0,0,0) emitter:setParticleLifetime(0,0.5) emitter:setRadialAcceleration(0,0) emitter:setRotation(0,0) emitter:setTangentialAcceleration(0,0) emitter:setSpeed(88,90) emitter:setSpin(0,0) emitter:setSpinVariation(2.7755575615629e-17) emitter:setLinearDamping(0,2) emitter:setSpread(6.1999998092651) emitter:setRelativeRotation(false) emitter:setOffset(2.5,2.5) emitter:setSizes(1,1,1,1,1,1,1,1) emitter:setSizeVariation(1) emitter:setColors(255,255,255,255 ) return emitter; end function Particle.ballImpactWithAnything() local tex = love.graphics.newImage("assets/textures/spark.png") local emitter = love.graphics.newParticleSystem(tex,50) emitter:setDirection(6.9388939039072e-16) emitter:setAreaSpread("none",0,0) emitter:setEmissionRate(357) emitter:setEmitterLifetime(0.10000000149012) emitter:setLinearAcceleration(0,0,0,0) emitter:setParticleLifetime(0,0.5) emitter:setRadialAcceleration(0,0) emitter:setRotation(0,0) emitter:setTangentialAcceleration(0,0) emitter:setSpeed(88,90) emitter:setSpin(0,0) emitter:setSpinVariation(2.7755575615629e-17) emitter:setLinearDamping(0,2) emitter:setSpread(6.1999998092651) emitter:setRelativeRotation(false) emitter:setOffset(2.5,2.5) emitter:setSizes(1,1,1,1,1,1,1,1) emitter:setSizeVariation(1) emitter:setColors(255,255,255,255 ) return emitter; end function Particle.ballMovement() local tex = love.graphics.newImage("assets/textures/spark.png") local emitter = love.graphics.newParticleSystem(tex,50) emitter:setDirection(0) emitter:setAreaSpread("uniform",8,16) emitter:setEmissionRate(10) emitter:setEmitterLifetime(-1) emitter:setLinearAcceleration(0,0,0,0) emitter:setParticleLifetime(1,1) emitter:setRadialAcceleration(0,0) emitter:setRotation(0,0) emitter:setTangentialAcceleration(0,0) emitter:setSpeed(0,0) emitter:setSpin(0,0) emitter:setSpinVariation(0) emitter:setLinearDamping(0,0) emitter:setSpread(0) emitter:setRelativeRotation(false) emitter:setOffset(0,0) emitter:setSizes(1) emitter:setSizeVariation(0) emitter:setColors(255,255,255,255 ) emitter:setColors(255,255,255,255 ) return emitter; end
Fixed farts and added particles for ball movement
Fixed farts and added particles for ball movement
Lua
mit
GuiSim/pixel
50c81219a127fdb40c048de9f341ef2386d0b667
RandomPokémon.lua
RandomPokémon.lua
--[[ Questo modulo sceglie un Pokémon randomicamente e ne fa usi diversi in base alla funzione --]] local p = {} local form = require('Wikilib-forms') local tab = require('Wikilib-tables') local txt = require('Wikilib-strings') local ot = require('Wikilib-others') local data = require("Wikilib-data") local pokedata = require("Poké-data") local alt = require("AltForms-data") local useless = require("UselessForms-data") -- Ritorna un ndex randomico local randomNdex = function() math.randomseed(os.time()) return math.random(data.pokeNum) -- return ot.random(data.pokeNum) end --[[ Ritorna le forme alternative nella nomenclatura degli artwork. Si aspetta la sigla della forma e il nome del Pokémon --]] local getArtworkForm = function(abbr, name) -- Forma base if abbr == 'base' then return '' end local formName = (alt[name] or useless[name]).names[abbr] -- Mega e archeo evoluzioni if form.hasMega(name) then return table.concat{'-', abbr:find('M') and 'Mega' or 'Archeo', formName:match(' [XY]') or ''} end --[[ Altre forme alternative: è necessario rimuovere un'eventuale prima parola, es 'Forma' o 'Manto' --]] return '-' .. (formName:match('%S*%s(.+)') or formName) end -- Ritorna l'artwork di un Pokèmon random p.artwork = function(frame) local dimensione = string.trim(frame.args[1] or '100') local num = tonumber(frame.args[2]) or randomNdex() local nome = pokedata[num].name local forme = nil if alt[num] then forme = alt[num].gamesOrder elseif useless[num] then forme = useless[num].gamesOrder end num = string.three_figures(num) if forme then num = num .. getArtworkForm(forme[math.random(table.getn(forme))], nome:lower()) end return string.interp("[[File:Artwork${num}.png|center|${dimensione}x${dimensione}px|link=${nome}]]", {num = num, nome = nome, dimensione = dimensione}) end print(p[table.remove(arg, 1)]{args=arg}) -- return p
--[[ Questo modulo sceglie un Pokémon randomicamente e ne fa usi diversi in base alla funzione --]] local p = {} local form = require('Wikilib-forms') local tab = require('Wikilib-tables') local txt = require('Wikilib-strings') local ot = require('Wikilib-others') local data = require("Wikilib-data") local pokedata = require("Poké-data") local alt = require("AltForms-data") local useless = require("UselessForms-data") -- Ritorna un ndex randomico local randomNdex = function() math.randomseed(os.time()) return math.random(data.pokeNum) -- return ot.random(data.pokeNum) end --[[ Ritorna le forme alternative nella nomenclatura degli artwork. Si aspetta la sigla della forma e il nome del Pokémon --]] local getArtworkForm = function(abbr, name) -- Forma base if abbr == 'base' then return '' end local formName = (alt[name] or useless[name]).names[abbr] -- Mega e archeo evoluzioni if form.hasMega(name) then return table.concat{'-', abbr:find('M') and 'Mega' or 'Archeo', formName:match(' [XY]') or ''} end -- Forme di Alola if form.hasAlola(name) then return '-Alola' end --[[ Altre forme alternative: è necessario rimuovere un'eventuale prima parola, es 'Forma' o 'Manto' --]] return '-' .. (formName:match('%S*%s(.+)') or formName) end -- Ritorna l'artwork di un Pokèmon random p.artwork = function(frame) local dimensione = string.trim(frame.args[1] or '100') local num = tonumber(frame.args[2]) or randomNdex() local nome = pokedata[num].name local forme = nil if alt[num] then forme = alt[num].gamesOrder elseif useless[num] then forme = useless[num].gamesOrder end num = string.three_figures(num) if forme then num = num .. getArtworkForm(forme[math.random(table.getn(forme))], nome:lower()) end return string.interp("[[File:Artwork${num}.png|center|${dimensione}x${dimensione}px|link=${nome}]]", {num = num, nome = nome, dimensione = dimensione}) end print(p[table.remove(arg, 1)]{args=arg}) -- return p
Fixed Alolan forms artwork name
Fixed Alolan forms artwork name
Lua
cc0-1.0
pokemoncentral/wiki-lua-modules
19edbcb109c73dcc88240c1c654440447c6f0e93
deps/Mono/premake4.lua
deps/Mono/premake4.lua
project "Mono" local version = "2.12" local repo = "git|git://github.com/mono/mono.git" local license = "LGPL" kind "StaticLib" defines { "__default_codegen__", "HAVE_CONFIG_H", } -- sgen defines defines { "HAVE_SGEN_GC", "HAVE_MOVING_COLLECTOR", "HAVE_WRITE_BARRIERS" } includedirs { "./", "mono/", "eglib/src/" } files { "eglib/src/*.c", "mono/metadata/*.c", "mono/mini/*.c", "mono/utils/*.c", } excludes { "mono/metadata/boehm-gc.c", "mono/metadata/console-unix.c", "mono/metadata/console-win32.c", --"mono/metadata/coree.c", "mono/metadata/monodiet.c", "mono/metadata/monosn.c", "mono/metadata/null-gc.c", "mono/metadata/pedump.c", "mono/metadata/tpool-*.c", "mono/metadata/sgen-fin-weak-hash.c", "mono/mini/fsacheck.c", "mono/mini/genmdesc.c", "mono/mini/main.c", "mono/mini/mini-darwin.c", "mono/mini/mini-alpha.c", "mono/mini/exceptions-alpha.c", "mono/mini/tramp-alpha.c", "mono/mini/mini-arm.c", "mono/mini/exceptions-arm.c", "mono/mini/tramp-arm.c", "mono/mini/mini-hppa.c", "mono/mini/exceptions-hppa.c", "mono/mini/tramp-hppa.c", "mono/mini/mini-ia64.c", "mono/mini/exceptions-ia64.c", "mono/mini/tramp-ia64.c", "mono/mini/mini-mips.c", "mono/mini/exceptions-mips.c", "mono/mini/tramp-mips.c", "mono/mini/mini-ppc.c", "mono/mini/exceptions-ppc.c", "mono/mini/tramp-ppc.c", "mono/mini/mini-s390*.c", "mono/mini/exceptions-s390*.c", "mono/mini/tramp-s390*.c", "mono/mini/mini-sparc.c", "mono/mini/exceptions-sparc.c", "mono/mini/tramp-sparc.c", "mono/mini/mini-llvm.c", "mono/mini/mini-posix.c", "mono/utils/mono-embed.c", } configuration "not windows" excludes { "eglib/src/*-win32.c" } files { "eglib/src/*-unix.c" } configuration "not x32" excludes { --"mono/mini/mini-x86.c", --"mono/mini/exceptions-x86.c", --"mono/mini/tramp-x86.c", } files { --"mono/mini/mini-amd64.c", --"mono/mini/exceptions-amd64.c", --"mono/mini/tramp-amd64.c", } configuration "not x64" excludes { "mono/mini/mini-amd64.c", "mono/mini/exceptions-amd64.c", "mono/mini/tramp-amd64.c", } files { "mono/mini/mini-x86.c", "mono/mini/exceptions-x86.c", "mono/mini/tramp-x86.c", } configuration "windows" files { "mono/mini/mini-windows.c" } excludes { "eglib/src/*-unix.c" } defines { "WIN32_THREADS", "WINVER=0x0500", "_WIN32_WINNT=0x0500", "_WIN32_IE=0x0501", "_UNICODE", "UNICODE", "FD_SETSIZE=1024" } links { "Mswsock", "ws2_32", "psapi", "version", "winmm" } configuration "linux" files { "mono/metadata/tpool-epoll.c" } configuration "macosx or freebsd" files { "mono/metadata/tpool-kqueue.c" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } buildoptions { "/wd4018", -- signed/unsigned mismatch "/wd4244", -- conversion from 'x' to 'y', possible loss of data "/wd4133", -- incompatible types - from 'x *' to 'y *' "/wd4715", -- not all control paths return a value "/wd4047", -- 'x' differs in levels of indirection from 'y' } configuration ""
local version = "2.12" local repo = "git|git://github.com/mono/mono.git" local license = "LGPL" project "Mono" kind "SharedLib" defines { "HAVE_CONFIG_H", } -- sgen defines defines { "HAVE_SGEN_GC", "HAVE_MOVING_COLLECTOR", "HAVE_WRITE_BARRIERS" } includedirs { "./", "mono/", "eglib/src/" } files { "eglib/src/*.c", "mono/metadata/*.c", "mono/utils/*.c", } excludes { "mono/metadata/boehm-gc.c", "mono/metadata/console-unix.c", "mono/metadata/console-win32.c", --"mono/metadata/coree.c", "mono/metadata/monodiet.c", "mono/metadata/monosn.c", "mono/metadata/null-gc.c", "mono/metadata/pedump.c", "mono/metadata/tpool-*.c", "mono/metadata/sgen-fin-weak-hash.c", "mono/utils/mono-embed.c", } configuration "windows" files { "eglib/src/*-win32.c" } excludes { "eglib/src/*-unix.c" } defines { "WIN32_THREADS", "WINVER=0x0500", "_WIN32_WINNT=0x0500", "_WIN32_IE=0x0501", "_UNICODE", "UNICODE", "FD_SETSIZE=1024" } links { "MonoMini", "Mswsock", "ws2_32", "psapi", "version", "winmm", } configuration "linux" files { "mono/metadata/tpool-epoll.c" } configuration "macosx or freebsd" files { "mono/metadata/tpool-kqueue.c" } --configuration "not windows" -- files { "eglib/src/*-unix.c" } -- excludes { "eglib/src/*-win32.c" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } buildoptions { "/wd4018", -- signed/unsigned mismatch "/wd4244", -- conversion from 'x' to 'y', possible loss of data "/wd4133", -- incompatible types - from 'x *' to 'y *' "/wd4715", -- not all control paths return a value "/wd4047", -- 'x' differs in levels of indirection from 'y' } configuration "" project "MonoMini" kind "StaticLib" defines { "__default_codegen__", "HAVE_CONFIG_H", } includedirs { "./", "mono/", "eglib/src/" } files { "mono/mini/*.c", } excludes { "mono/mini/fsacheck.c", "mono/mini/genmdesc.c", "mono/mini/main.c", "mono/mini/mini-darwin.c", "mono/mini/mini-alpha.c", "mono/mini/exceptions-alpha.c", "mono/mini/tramp-alpha.c", "mono/mini/mini-arm.c", "mono/mini/exceptions-arm.c", "mono/mini/tramp-arm.c", "mono/mini/mini-hppa.c", "mono/mini/exceptions-hppa.c", "mono/mini/tramp-hppa.c", "mono/mini/mini-ia64.c", "mono/mini/exceptions-ia64.c", "mono/mini/tramp-ia64.c", "mono/mini/mini-mips.c", "mono/mini/exceptions-mips.c", "mono/mini/tramp-mips.c", "mono/mini/mini-ppc.c", "mono/mini/exceptions-ppc.c", "mono/mini/tramp-ppc.c", "mono/mini/mini-s390*.c", "mono/mini/exceptions-s390*.c", "mono/mini/tramp-s390*.c", "mono/mini/mini-sparc.c", "mono/mini/exceptions-sparc.c", "mono/mini/tramp-sparc.c", "mono/mini/mini-llvm.c", "mono/mini/mini-posix.c", } configuration "x32" files { "mono/mini/mini-x86.c", "mono/mini/exceptions-x86.c", "mono/mini/tramp-x86.c", } excludes { "mono/mini/mini-amd64.c", "mono/mini/exceptions-amd64.c", "mono/mini/tramp-amd64.c", } configuration "x64" files { "mono/mini/mini-amd64.c", "mono/mini/exceptions-amd64.c", "mono/mini/tramp-amd64.c", } excludes { "mono/mini/mini-x86.c", "mono/mini/exceptions-x86.c", "mono/mini/tramp-x86.c", } configuration "windows" files { "mono/mini/mini-windows.c" } defines { "WIN32_THREADS", "WINVER=0x0500", "_WIN32_WINNT=0x0500", "_WIN32_IE=0x0501", "_UNICODE", "UNICODE", "FD_SETSIZE=1024" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } buildoptions { "/wd4018", -- signed/unsigned mismatch "/wd4244", -- conversion from 'x' to 'y', possible loss of data "/wd4133", -- incompatible types - from 'x *' to 'y *' "/wd4715", -- not all control paths return a value "/wd4047", -- 'x' differs in levels of indirection from 'y' } configuration ""
Fixed the Mono build scripts to work with latest trunk.
Fixed the Mono build scripts to work with latest trunk.
Lua
bsd-2-clause
FloodProject/flood,FloodProject/flood,FloodProject/flood
470b00f1bbcf4b8d4ef671b703b8e6fa3209344a
OnlineTrainer.lua
OnlineTrainer.lua
local OnlineTrainer, parent = torch.class('nn.OnlineTrainer','nn.Trainer') function OnlineTrainer:__init(...) parent.__init(self) -- unpack args xlua.unpack_class(self, {...}, 'OnlineTrainer', 'A general-purpose online trainer class.\n' .. 'Provides 4 user hooks to perform extra work after each sample, or each epoch:\n' .. '> trainer = nn.OnlineTrainer(...) \n' .. '> trainer.hookTrainSample = function(trainer, sample) ... end \n' .. '> trainer.hookTrainEpoch = function(trainer) ... end \n' .. '> trainer.hookTestSample = function(trainer, sample) ... end \n' .. '> trainer.hookTestEpoch = function(trainer) ... end \n' .. '> ', {arg='module', type='nn.Module', help='a module to train', req=true}, {arg='criterion', type='nn.Criterion', help='a criterion to estimate the error'}, {arg='preprocessor', type='nn.Module', help='a preprocessor to prime the data before the module'}, {arg='optimizer', type='nn.Optimization', help='an optimization method'}, {arg='batchSize', type='number', help='[mini] batch size', default=1}, {arg='maxEpoch', type='number', help='maximum number of epochs', default=50}, {arg='dispProgress', type='boolean', help='display a progress bar during training/testing', default=true}, {arg='save', type='string', help='path to save networks and log training'}, {arg='timestamp', type='boolean', help='if true, appends a timestamp to each network saved', default=false} ) -- private params self.trainOffset = 0 self.testOffset = 0 end function OnlineTrainer:log() -- save network local filename = self.save os.execute('mkdir -p ' .. sys.dirname(filename)) if self.timestamp then -- use a timestamp to store all networks uniquely filename = filename .. '-' .. os.date("%Y_%m_%d_%X") else -- if no timestamp, just store the previous one if sys.filep(filename) then os.execute('mv ' .. filename .. ' ' .. filename .. '.old') end end print('<trainer> saving network to '..filename) local file = torch.DiskFile(filename,'w') self.module:write(file) file:close() end function OnlineTrainer:train(dataset) self.epoch = self.epoch or 1 local module = self.module local criterion = self.criterion self.trainset = dataset local shuffledIndices = {} if not self.shuffleIndices then for t = 1,dataset:size() do shuffledIndices[t] = t end else shuffledIndices = lab.randperm(dataset:size()) end while true do print('<trainer> on training set:') print("<trainer> online epoch # " .. self.epoch .. ' [batchSize = ' .. self.batchSize .. ']') self.time = sys.clock() self.currentError = 0 for t = 1,dataset:size(),self.batchSize do -- disp progress if self.dispProgress then xlua.progress(t, dataset:size()) end -- create mini batch local inputs = {} local targets = {} for i = t,math.min(t+self.batchSize-1,dataset:size()) do -- load new sample local sample = dataset[self.trainOffset + shuffledIndices[i]] local input = sample[1] local target = sample[2] -- optional preprocess (no learning is done for that guy) if self.preprocessor then input = self.preprocessor:forward(input) end -- store input/target table.insert(inputs, input) table.insert(targets, target) end -- optimize the model given current input/target set local error = self.optimizer:forward(inputs, targets) -- accumulate error self.currentError = self.currentError + error -- call user hook, if any if self.hookTrainSample then self.hookTrainSample(self, {inputs[#inputs], targets[#targets]}) end end self.currentError = self.currentError / dataset:size() print("<trainer> current error = " .. self.currentError) self.time = sys.clock() - self.time self.time = self.time / dataset:size() print("<trainer> time to learn 1 sample = " .. (self.time*1000) .. 'ms') if self.hookTrainEpoch then self.hookTrainEpoch(self) end if self.save then self:log() end self.epoch = self.epoch + 1 if dataset.infiniteSet then self.trainOffset = self.trainOffset + dataset:size() end if self.maxEpoch > 0 and self.epoch > self.maxEpoch then print("<trainer> you have reached the maximum number of epochs") break end end end function OnlineTrainer:test(dataset) print('<trainer> on testing Set:') local module = self.module local shuffledIndices = {} local criterion = self.criterion self.currentError = 0 self.testset = dataset local shuffledIndices = {} if not self.shuffleIndices then for t = 1,dataset:size() do shuffledIndices[t] = t end else shuffledIndices = lab.randperm(dataset:size()) end self.time = sys.clock() for t = 1,dataset:size() do -- disp progress if self.dispProgress then xlua.progress(t, dataset:size()) end -- get new sample local sample = dataset[self.testOffset + shuffledIndices[t]] local input = sample[1] local target = sample[2] -- test sample through current model if self.preprocessor then input = self.preprocessor:forward(input) end if criterion then self.currentError = self.currentError + criterion:forward(module:forward(input), target) else local _,error = module:forward(input, target) self.currentError = self.currentError + error end -- user hook if self.hookTestSample then self.hookTestSample(self, sample) end end self.currentError = self.currentError / dataset:size() print("<trainer> test current error = " .. self.currentError) self.time = sys.clock() - self.time self.time = self.time / dataset:size() print("<trainer> time to test 1 sample = " .. (self.time*1000) .. 'ms') if self.hookTestEpoch then self.hookTestEpoch(self) end if dataset.infiniteSet then self.testOffset = self.testOffset + dataset:size() end return self.currentError end function OnlineTrainer:write(file) parent.write(self,file) file:writeObject(self.module) file:writeObject(self.criterion) end function OnlineTrainer:read(file) parent.read(self,file) self.module = file:readObject() self.criterion = file:readObject() end
local OnlineTrainer, parent = torch.class('nn.OnlineTrainer','nn.Trainer') function OnlineTrainer:__init(...) parent.__init(self) -- unpack args xlua.unpack_class(self, {...}, 'OnlineTrainer', 'A general-purpose online trainer class.\n' .. 'Provides 4 user hooks to perform extra work after each sample, or each epoch:\n' .. '> trainer = nn.OnlineTrainer(...) \n' .. '> trainer.hookTrainSample = function(trainer, sample) ... end \n' .. '> trainer.hookTrainEpoch = function(trainer) ... end \n' .. '> trainer.hookTestSample = function(trainer, sample) ... end \n' .. '> trainer.hookTestEpoch = function(trainer) ... end \n' .. '> ', {arg='module', type='nn.Module', help='a module to train', req=true}, {arg='criterion', type='nn.Criterion', help='a criterion to estimate the error'}, {arg='preprocessor', type='nn.Module', help='a preprocessor to prime the data before the module'}, {arg='optimizer', type='nn.Optimization', help='an optimization method'}, {arg='batchSize', type='number', help='[mini] batch size', default=1}, {arg='maxEpoch', type='number', help='maximum number of epochs', default=50}, {arg='dispProgress', type='boolean', help='display a progress bar during training/testing', default=true}, {arg='save', type='string', help='path to save networks and log training'}, {arg='timestamp', type='boolean', help='if true, appends a timestamp to each network saved', default=false} ) -- private params self.trainOffset = 0 self.testOffset = 0 end function OnlineTrainer:log() -- save network local filename = self.save os.execute('mkdir -p ' .. sys.dirname(filename)) if self.timestamp then -- use a timestamp to store all networks uniquely filename = filename .. '-' .. os.date("%Y_%m_%d_%X") else -- if no timestamp, just store the previous one if sys.filep(filename) then os.execute('mv ' .. filename .. ' ' .. filename .. '.old') end end print('<trainer> saving network to '..filename) local file = torch.DiskFile(filename,'w') self.module:write(file) file:close() end function OnlineTrainer:train(dataset) self.epoch = self.epoch or 1 local module = self.module local criterion = self.criterion self.trainset = dataset local shuffledIndices = {} if not self.shuffleIndices then for t = 1,dataset:size() do shuffledIndices[t] = t end else shuffledIndices = lab.randperm(dataset:size()) end while true do print('<trainer> on training set:') print("<trainer> online epoch # " .. self.epoch .. ' [batchSize = ' .. self.batchSize .. ']') self.time = sys.clock() self.currentError = 0 for t = 1,dataset:size(),self.batchSize do -- disp progress if self.dispProgress then xlua.progress(t, dataset:size()) end -- create mini batch local inputs = {} local targets = {} for i = t,math.min(t+self.batchSize-1,dataset:size()) do -- load new sample local sample = dataset[shuffledIndices[self.trainOffset + i]] local input = sample[1] local target = sample[2] -- optional preprocess (no learning is done for that guy) if self.preprocessor then input = self.preprocessor:forward(input) end -- store input/target table.insert(inputs, input) table.insert(targets, target) end -- optimize the model given current input/target set local error = self.optimizer:forward(inputs, targets) -- accumulate error self.currentError = self.currentError + error -- call user hook, if any if self.hookTrainSample then self.hookTrainSample(self, {inputs[#inputs], targets[#targets]}) end end self.currentError = self.currentError / dataset:size() print("<trainer> current error = " .. self.currentError) self.time = sys.clock() - self.time self.time = self.time / dataset:size() print("<trainer> time to learn 1 sample = " .. (self.time*1000) .. 'ms') if self.hookTrainEpoch then self.hookTrainEpoch(self) end if self.save then self:log() end self.epoch = self.epoch + 1 if dataset.infiniteSet then self.trainOffset = self.trainOffset + dataset:size() end if self.maxEpoch > 0 and self.epoch > self.maxEpoch then print("<trainer> you have reached the maximum number of epochs") break end end end function OnlineTrainer:test(dataset) print('<trainer> on testing Set:') local module = self.module local shuffledIndices = {} local criterion = self.criterion self.currentError = 0 self.testset = dataset local shuffledIndices = {} if not self.shuffleIndices then for t = 1,dataset:size() do shuffledIndices[t] = t end else shuffledIndices = lab.randperm(dataset:size()) end self.time = sys.clock() for t = 1,dataset:size() do -- disp progress if self.dispProgress then xlua.progress(t, dataset:size()) end -- get new sample local sample = dataset[shuffledIndices[self.testOffset + t]] local input = sample[1] local target = sample[2] -- test sample through current model if self.preprocessor then input = self.preprocessor:forward(input) end if criterion then self.currentError = self.currentError + criterion:forward(module:forward(input), target) else local _,error = module:forward(input, target) self.currentError = self.currentError + error end -- user hook if self.hookTestSample then self.hookTestSample(self, sample) end end self.currentError = self.currentError / dataset:size() print("<trainer> test current error = " .. self.currentError) self.time = sys.clock() - self.time self.time = self.time / dataset:size() print("<trainer> time to test 1 sample = " .. (self.time*1000) .. 'ms') if self.hookTestEpoch then self.hookTestEpoch(self) end if dataset.infiniteSet then self.testOffset = self.testOffset + dataset:size() end return self.currentError end function OnlineTrainer:write(file) parent.write(self,file) file:writeObject(self.module) file:writeObject(self.criterion) end function OnlineTrainer:read(file) parent.read(self,file) self.module = file:readObject() self.criterion = file:readObject() end
fixed bug when using shuffled indices
fixed bug when using shuffled indices
Lua
mit
clementfarabet/lua---nnx
3607a2e74038d124f20c74713128fefe7cf38881
framework/reeme/request/post.lua
framework/reeme/request/post.lua
--from reqargs local upload = require "resty.upload" local tmpname = os.tmpname local concat = table.concat local type = type local find = string.find local open = io.open local sub = string.sub local ngx = ngx local req = ngx.req local var = ngx.var local body = req.read_body local data = req.get_body_data local pargs = req.get_post_args local fd = require('reeme.fd')() local function rightmost(s, sep) local p = 1 local i = find(s, sep, 1, true) while i do p = i + 1 i = find(s, sep, p, true) end if p > 1 then s = sub(s, p) end return s end local function basename(s) return rightmost(rightmost(s, "\\"), "/") end local function kv(r, s) if s == "formdata" then return end local e = find(s, "=", 1, true) if e then r[sub(s, 2, e - 1)] = sub(s, e + 2, #s - 1) else r[#r+1] = s end end local function parse(s) if not s then return nil end local r = {} local i = 1 local b = find(s, ";", 1, true) while b do local p = sub(s, i, b - 1) kv(r, p) i = b + 1 b = find(s, ";", i, true) end local p = sub(s, i) if p ~= "" then kv(r, p) end return r end local tempFolder = ngx.var.TEMPFOLDER if type(tempFolder) ~= 'string' or #tempFolder == 0 then tempFolder = nil end local function getTempFileName() local ffi = require("ffi") local tname = tempFolder and tempFolder .. os.tmpname() or os.tmpname() local fpos = string.rfindchar(tname, '/') if not fpos then fpos = string.rfindchar(tname, '\\') if not fpos then fpos = #tname end end if fd.pathIsDir(string.sub(tname, 1, fpos)) then return tname end if ffi.abi('win') then ffi.cdef[[ unsigned long GetTempPathA(unsigned long nBufferLength, char* lpBuffer); ]] local tempPathLengh = 256 local tempPathBuffer = ffi.new("char[?]", tempPathLengh) ffi.C.GetTempPathA(tempPathLengh, tempPathBuffer) return ffi.string(tempPathBuffer) or "d:/" end assert(0, 'cannot get temp-filename') return '' end local function getPostArgsAndFiles(options) local post = { } local files = { } local bodydata = nil local request_method = ngx.req.get_method() local ct = var.content_type if not options then options = { } end if ct == nil then return post, files end function _move(self, dstFilename) if fd.pathIsFile(dstFilename) and not fd.deleteFile(dstFilename) then return false end return os.rename(self.temp, dstFilename) end function _append(self, dstFilename) local dstFile = io.open(dstFilename, "ab+") local srcFile = io.open(self.temp, "rb") dstFile:write(srcFile:read("*all")) dstFile:close() srcFile:close() end function _del(self) fd.deleteFile(self.temp) end function _full(self) local t = nil local f, err = io.open(self.temp, 'rb') if f then t = f:read("*all") f:close() end return t end if sub(ct, 1, 19) == "multipart/form-data" then local chunk = options.chunk_size or 8192 local form, e = upload:new(chunk) if not form then return nil, e end local h, p, f, o form:set_timeout(options.timeout or 1000) while true do local t, r, e = form:read() if not t then return nil, e end if t == "header" then if not h then h = {} end if type(r) == "table" then local k, v = r[1], parse(r[2]) if v then h[k] = v end end elseif t == "body" then if h then local d = h["Content-Disposition"] if d then if d.filename then f = { name = d.name, type = h["Content-Type"] and h["Content-Type"][1], file = basename(d.filename), temp = getTempFileName(), moveFile = _move, appendFile = _append, delFile = _del, fullFile = _full, } o, e = open(f.temp, "wb") if not o then return nil, e end o:setvbuf("full", chunk) else p = { name = d.name, data = { n = 1 } } end end h = nil end if o then local ok, e = o:write(r) if not ok then return nil, e end elseif p then local n = p.data.n p.data[n] = r p.data.n = n + 1 end elseif t == "part_end" then if o then f.size = o:seek() o:close() o = nil end local c, d if f then c, d, f = files, f, nil elseif p then c, d, p = post, p, nil end if c then local n = d.name local s = d.data and concat(d.data) or d if n then local z = c[n] if z then if z.n then z.n = z.n + 1 z[z.n] = s else z = { z, s } z.n = 2 end c[n] = z else c[n] = s end else c.n = c.n + 1 c[c.n] = s end end elseif t == "eof" then break end end local t, r, e = form:read() if not t then return nil, e end elseif sub(ct, 1, 16) == "application/json" then body() post = string.json(data()) or {} else body() post, err = pargs() if err then --can also set client_body_buffer_size 128k; in http part local data = ngx.req.get_body_data() or '' local file = ngx.req.get_body_file() if file then local f, e = io.open(file, "rb") if f then local req = f:read('*a') f:close() post = ngx.decode_args(data .. req) end end end if request_method == 'POST' then bodydata = data() end end return post, files, bodydata end return function(reeme) local postArgs, files, body = getPostArgsAndFiles() local post = { __R = reeme, __post = postArgs, files = files or { }, body = body } return setmetatable(post, { __index = postArgs or { }, }) end
--from reqargs local upload = require "resty.upload" local tmpname = os.tmpname local concat = table.concat local type = type local find = string.find local open = io.open local sub = string.sub local ngx = ngx local req = ngx.req local var = ngx.var local body = req.read_body local data = req.get_body_data local pargs = req.get_post_args local fd = require('reeme.fd')() local function rightmost(s, sep) local p = 1 local i = find(s, sep, 1, true) while i do p = i + 1 i = find(s, sep, p, true) end if p > 1 then s = sub(s, p) end return s end local function basename(s) return rightmost(rightmost(s, "\\"), "/") end local function kv(r, s) if s == "formdata" then return end local e = find(s, "=", 1, true) if e then r[sub(s, 2, e - 1)] = sub(s, e + 2, #s - 1) else r[#r+1] = s end end local function parse(s) if not s then return nil end local r = {} local i = 1 local b = find(s, ";", 1, true) while b do local p = sub(s, i, b - 1) kv(r, p) i = b + 1 b = find(s, ";", i, true) end local p = sub(s, i) if p ~= "" then kv(r, p) end return r end local tempFolder = ngx.var.TEMPFOLDER if type(tempFolder) ~= 'string' or #tempFolder == 0 then tempFolder = nil end local function getTempFileName() local ffi = require("ffi") local tname = tempFolder and tempFolder .. os.tmpname() or os.tmpname() local fpos = string.rfindchar(tname, '/') if not fpos then fpos = string.rfindchar(tname, '\\') if not fpos then fpos = #tname end end if fd.pathIsDir(string.sub(tname, 1, fpos)) then return tname end if ffi.abi('win') then ffi.cdef[[ unsigned long GetTempPathA(unsigned long nBufferLength, char* lpBuffer); ]] local tempPathLengh = 256 local tempPathBuffer = ffi.new("char[?]", tempPathLengh) ffi.C.GetTempPathA(tempPathLengh, tempPathBuffer) return ffi.string(tempPathBuffer) or "d:/" end assert(0, 'cannot get temp-filename') return '' end local function getPostArgsAndFiles(options) local post = { } local files = { } local bodydata = nil local request_method = ngx.req.get_method() local ct = var.content_type if not options then options = { } end if ct == nil then return post, files end function _move(self, dstFilename) if fd.pathIsFile(dstFilename) and not fd.deleteFile(dstFilename) then return false end return os.rename(self.temp, dstFilename) end function _append(self, dstFilename) local dstFile = io.open(dstFilename, "ab+") local srcFile = io.open(self.temp, "rb") dstFile:write(srcFile:read("*all")) dstFile:close() srcFile:close() end function _del(self) fd.deleteFile(self.temp) end function _full(self) local t = nil local f, err = io.open(self.temp, 'rb') if f then t = f:read("*all") f:close() end return t end if sub(ct, 1, 19) == "multipart/form-data" then local chunk = options.chunk_size or 8192 local form, e = upload:new(chunk) if not form then return nil, e end local h, p, f, o form:set_timeout(options.timeout or 1000) while true do local t, r, e = form:read() if not t then return nil, e end if t == "header" then if not h then h = {} end if type(r) == "table" then local k, v = r[1], parse(r[2]) if v then h[k] = v end end elseif t == "body" then if h then local d = h["Content-Disposition"] if d then if d.filename then f = { name = d.name, type = h["Content-Type"] and h["Content-Type"][1], file = basename(d.filename), temp = getTempFileName(), moveFile = _move, appendFile = _append, delFile = _del, fullFile = _full, } o, e = open(f.temp, "wb") if not o then return nil, e end o:setvbuf("full", chunk) else p = { name = d.name, data = { n = 1 } } end end h = nil end if o then local ok, e = o:write(r) if not ok then return nil, e end elseif p then local n = p.data.n p.data[n] = r p.data.n = n + 1 end elseif t == "part_end" then if o then f.size = o:seek() o:close() o = nil end local c, d if f then c, d, f = files, f, nil elseif p then c, d, p = post, p, nil end if c then local n = d.name local s = d.data and concat(d.data) or d if n then local z = c[n] if z then if z.n then z.n = z.n + 1 z[z.n] = s else z = { z, s } z.n = 2 end c[n] = z else c[n] = s end else c.n = c.n + 1 c[c.n] = s end end elseif t == "eof" then break end end local t, r, e = form:read() if not t then return nil, e end elseif sub(ct, 1, 16) == "application/json" then body() post = string.json(data()) or {} else if request_method == 'POST' then body() local data = ngx.req.get_body_data() post, err = pargs() if err then --can also set client_body_buffer_size 128k; in http part local file = ngx.req.get_body_file() if file then local f, e = io.open(file, "rb") if f then local req = f:read('*a') f:close() if not data then data = '' end data = data .. req post = ngx.decode_args(data) end end end bodydata = data end end return post, files, bodydata end return function(reeme) local postArgs, files, body = getPostArgsAndFiles() local post = { __R = reeme, __post = postArgs, files = files or { }, body = body } return setmetatable(post, { __index = postArgs or { }, }) end
fix post body bug
fix post body bug
Lua
apache-2.0
mobilesolution2016/reeme,mobilesolution2016/reeme,mobilesolution2016/reeme
a655ca196c9312a10e0dacea3eb4c72be48e8aba
mod_archive_muc/mod_archive_muc.lua
mod_archive_muc/mod_archive_muc.lua
-- Prosody IM -- Copyright (C) 2010 Dai Zhiwei -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local dm = require "util.datamanager"; local jid = require "util.jid"; local datetime = require "util.datetime"; local PREFS_DIR = "archive_muc_prefs"; local ARCHIVE_DIR = "archive_muc"; local HOST = 'localhost'; local AUTO_ARCHIVING_ENABLED = true; module:add_feature("urn:xmpp:archive#preferences"); module:add_feature("urn:xmpp:archive#management"); ------------------------------------------------------------ -- Utils ------------------------------------------------------------ local function load_prefs(node, host) return st.deserialize(dm.load(node, host, PREFS_DIR)); end local function store_prefs(data, node, host) dm.store(node, host, PREFS_DIR, st.preserialize(data)); end local function date_time(localtime) return datetime.datetime(localtime); end local function match_jid(rule, id) return not rule or jid.compare(id, rule); end local function is_earlier(start, coll_start) return not start or start <= coll_start; end local function is_later(endtime, coll_start) return not endtime or endtime >= coll_start; end ------------------------------------------------------------ -- Preferences ------------------------------------------------------------ local function preferences_handler(event) local origin, stanza = event.origin, event.stanza; module:log("debug", "-- Enter muc preferences_handler()"); module:log("debug", "-- muc pref:\n%s", tostring(stanza)); if stanza.attr.type == "get" then local data = load_prefs(origin.username, origin.host); if data then origin.send(st.reply(stanza):add_child(data)); else origin.send(st.reply(stanza)); end elseif stanza.attr.type == "set" then local node, host = origin.username, origin.host; if stanza.tags[1] and stanza.tags[1].name == 'prefs' then store_prefs(stanza.tags[1], node, host); origin.send(st.reply(stanza)); local user = bare_sessions[node.."@"..host]; local push = st.iq({type="set"}); push:add_child(stanza.tags[1]); for _, res in pairs(user and user.sessions or NULL) do -- broadcast to all resources if res.presence then -- to resource push.attr.to = res.full_jid; res.send(push); end end end end return true; end ------------------------------------------------------------ -- Archive Management ------------------------------------------------------------ local function management_handler(event) module:log("debug", "-- Enter muc management_handler()"); local origin, stanza = event.origin, event.stanza; local node, host = origin.username, origin.host; local data = dm.list_load(node, host, ARCHIVE_DIR); local elem = stanza.tags[1]; local resset = {} if data then for i = #data, 1, -1 do local forwarded = st.deserialize(data[i]); local res = (match_jid(elem.attr["with"], forwarded.tags[2].attr.from) or match_jid(elem.attr["with"], forwarded.tags[2].attr.to)) and is_earlier(elem.attr["start"], forwarded.tags[1].attr["stamp"]) and is_later(elem.attr["end"], forwarded.tags[1].attr["stamp"]); if res then table.insert(resset, forwarded); end end for i = #resset, 1, -1 do local res = st.message({to = stanza.attr.from, id=st.new_id()}); res:add_child(resset[i]); origin.send(res); end end origin.send(st.reply(stanza)); return true; end ------------------------------------------------------------ -- Message Handler ------------------------------------------------------------ local function is_in(list, jid) for _,v in ipairs(list) do if match_jid(v:get_text(), jid) then -- JID Matching return true; end end return false; end local function is_in_roster(node, host, jid) -- TODO return true; end local function apply_pref(node, host, jid) local pref = load_prefs(node, host); if not pref then return AUTO_ARCHIVING_ENABLED; end local always = pref:child_with_name('always'); if always and is_in(always, jid) then return true; end local never = pref:child_with_name('never'); if never and is_in(never, jid) then return false; end local default = pref.attr['default']; if default == 'roster' then return is_in_roster(node, host, jid); elseif default == 'always' then return true; elseif default == 'never' then return false; end return AUTO_ARCHIVING_ENABLED; end local function store_msg(msg, node, host) local forwarded = st.stanza('forwarded', {xmlns='urn:xmpp:forward:tmp'}); forwarded:tag('delay', {xmlns='urn:xmpp:delay',stamp=date_time()}):up(); forwarded:add_child(msg); dm.list_append(node, host, ARCHIVE_DIR, st.preserialize(forwarded)); end local function msg_handler(data) module:log("debug", "-- Enter muc msg_handler()"); local origin, stanza = data.origin, data.stanza; local body = stanza:child_with_name("body"); if body then local from_node, from_host = jid.split(stanza.attr.from); local to_node, to_host = jid.split(stanza.attr.to); -- FIXME only archive messages of users on this host if from_host == HOST and apply_pref(from_node, from_host, stanza.attr.to) then store_msg(stanza, from_node, from_host); end if to_host == HOST and apply_pref(to_node, to_host, stanza.attr.from) then store_msg(stanza, to_node, to_host); end end return nil; end -- Preferences module:hook("iq/self/urn:xmpp:archive#preferences:prefs", preferences_handler); -- Archive management module:hook("iq/self/urn:xmpp:archive#management:query", management_handler); module:hook("message/full", msg_handler, 20); module:hook("message/bare", msg_handler, 20); -- TODO prefs: [1] = "\n ";
-- Prosody IM -- Copyright (C) 2010 Dai Zhiwei -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local dm = require "util.datamanager"; local jid = require "util.jid"; local datetime = require "util.datetime"; local um = require "core.usermanager"; local rom = require "core.rostermanager"; local PREFS_DIR = "archive_muc_prefs"; local ARCHIVE_DIR = "archive_muc"; local AUTO_ARCHIVING_ENABLED = true; module:add_feature("urn:xmpp:archive#preferences"); module:add_feature("urn:xmpp:archive#management"); ------------------------------------------------------------ -- Utils ------------------------------------------------------------ local function load_prefs(node, host) return st.deserialize(dm.load(node, host, PREFS_DIR)); end local function store_prefs(data, node, host) dm.store(node, host, PREFS_DIR, st.preserialize(data)); end local date_time = datetime.datetime; local function match_jid(rule, id) return not rule or jid.compare(id, rule); end local function is_earlier(start, coll_start) return not start or start <= coll_start; end local function is_later(endtime, coll_start) return not endtime or endtime >= coll_start; end ------------------------------------------------------------ -- Preferences ------------------------------------------------------------ local function preferences_handler(event) local origin, stanza = event.origin, event.stanza; module:log("debug", "-- Enter muc preferences_handler()"); module:log("debug", "-- muc pref:\n%s", tostring(stanza)); if stanza.attr.type == "get" then local data = load_prefs(origin.username, origin.host); if data then origin.send(st.reply(stanza):add_child(data)); else origin.send(st.reply(stanza)); end elseif stanza.attr.type == "set" then local node, host = origin.username, origin.host; if stanza.tags[1] and stanza.tags[1].name == 'prefs' then store_prefs(stanza.tags[1], node, host); origin.send(st.reply(stanza)); local user = bare_sessions[node.."@"..host]; local push = st.iq({type="set"}); push:add_child(stanza.tags[1]); for _, res in pairs(user and user.sessions or NULL) do -- broadcast to all resources if res.presence then -- to resource push.attr.to = res.full_jid; res.send(push); end end end end return true; end ------------------------------------------------------------ -- Archive Management ------------------------------------------------------------ local function management_handler(event) module:log("debug", "-- Enter muc management_handler()"); local origin, stanza = event.origin, event.stanza; local node, host = origin.username, origin.host; local data = dm.list_load(node, host, ARCHIVE_DIR); local elem = stanza.tags[1]; local resset = {} if data then for i = #data, 1, -1 do local forwarded = st.deserialize(data[i]); local res = (match_jid(elem.attr["with"], forwarded.tags[2].attr.from) or match_jid(elem.attr["with"], forwarded.tags[2].attr.to)) and is_earlier(elem.attr["start"], forwarded.tags[1].attr["stamp"]) and is_later(elem.attr["end"], forwarded.tags[1].attr["stamp"]); if res then table.insert(resset, forwarded); end end for i = #resset, 1, -1 do local res = st.message({to = stanza.attr.from, id=st.new_id()}); res:add_child(resset[i]); origin.send(res); end end origin.send(st.reply(stanza)); return true; end ------------------------------------------------------------ -- Message Handler ------------------------------------------------------------ local function is_in(list, jid) for _,v in ipairs(list) do if match_jid(v:get_text(), jid) then -- JID Matching return true; end end return false; end local function is_in_roster(node, host, id) return rom.is_contact_subscribed(node, host, jid.bare(id)); end local function apply_pref(node, host, jid) local pref = load_prefs(node, host); if not pref then return AUTO_ARCHIVING_ENABLED; end local always = pref:child_with_name('always'); if always and is_in(always, jid) then return true; end local never = pref:child_with_name('never'); if never and is_in(never, jid) then return false; end local default = pref.attr['default']; if default == 'roster' then return is_in_roster(node, host, jid); elseif default == 'always' then return true; elseif default == 'never' then return false; end return AUTO_ARCHIVING_ENABLED; end local function store_msg(msg, node, host) local forwarded = st.stanza('forwarded', {xmlns='urn:xmpp:forward:tmp'}); forwarded:tag('delay', {xmlns='urn:xmpp:delay',stamp=date_time()}):up(); forwarded:add_child(msg); dm.list_append(node, host, ARCHIVE_DIR, st.preserialize(forwarded)); end local function msg_handler(data) module:log("debug", "-- Enter muc msg_handler()"); local origin, stanza = data.origin, data.stanza; local body = stanza:child_with_name("body"); if body then local from_node, from_host = jid.split(stanza.attr.from); local to_node, to_host = jid.split(stanza.attr.to); if um.user_exists(from_node, from_host) and apply_pref(from_node, from_host, stanza.attr.to) then store_msg(stanza, from_node, from_host); end if um.user_exists(to_node, to_host) and apply_pref(to_node, to_host, stanza.attr.from) then store_msg(stanza, to_node, to_host); end end return nil; end -- Preferences module:hook("iq/self/urn:xmpp:archive#preferences:prefs", preferences_handler); -- Archive management module:hook("iq/self/urn:xmpp:archive#management:query", management_handler); module:hook("message/bare", msg_handler, 20); -- TODO prefs: [1] = "\n ";
mod_archive_muc: use usermanager to check if some user exists; use rostermanager to check if someone is in the roster; minor fixes.
mod_archive_muc: use usermanager to check if some user exists; use rostermanager to check if someone is in the roster; minor fixes.
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
2b38b16d2795a228b1a541fbc2e09bd093119aad
ffi/input_android.lua
ffi/input_android.lua
local ffi = require("ffi") local bit = require("bit") local android = require("android") local dummy = require("ffi/linux_input_h") -- to trigger refreshes for certain Android framework events: local fb = require("ffi/framebuffer_android").open() local input = {} function input.open() end local inputQueue = {} local ev_time = ffi.new("struct timeval") local function genEmuEvent(evtype, code, value) ffi.C.gettimeofday(ev_time, nil) local ev = { type = tonumber(evtype), code = tonumber(code), value = tonumber(value), time = { sec = tonumber(ev_time.tv_sec), usec = tonumber(ev_time.tv_usec) } } table.insert(inputQueue, ev) end local function genTouchDownEvent(event, id) local x = ffi.C.AMotionEvent_getX(event, id) local y = ffi.C.AMotionEvent_getY(event, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_TRACKING_ID, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y) genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0) end local function genTouchUpEvent(event, id) local x = ffi.C.AMotionEvent_getX(event, id) local y = ffi.C.AMotionEvent_getY(event, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_TRACKING_ID, -1) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y) genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0) end local function genTouchMoveEvent(event, id) local x = ffi.C.AMotionEvent_getX(event, id) local y = ffi.C.AMotionEvent_getY(event, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y) genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0) end local is_in_touch = false local function motionEventHandler(motion_event) local action = ffi.C.AMotionEvent_getAction(motion_event) local pointer_count = ffi.C.AMotionEvent_getPointerCount(motion_event) local pointer_index = bit.rshift( bit.band(action, ffi.C.AMOTION_EVENT_ACTION_POINTER_INDEX_MASK), ffi.C.AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT) local id = ffi.C.AMotionEvent_getPointerId(motion_event, pointer_index) local flags = bit.band(action, ffi.C.AMOTION_EVENT_ACTION_MASK) if flags == ffi.C.AMOTION_EVENT_ACTION_DOWN then is_in_touch = true genTouchDownEvent(motion_event, id) elseif flags == ffi.C.AMOTION_EVENT_ACTION_POINTER_DOWN then is_in_touch = true genTouchDownEvent(motion_event, id) elseif flags == ffi.C.AMOTION_EVENT_ACTION_UP then is_in_touch = false genTouchUpEvent(motion_event, id) elseif flags == ffi.C.AMOTION_EVENT_ACTION_POINTER_UP then is_in_touch = false genTouchUpEvent(motion_event, id) elseif flags == ffi.C.AMOTION_EVENT_ACTION_MOVE then if is_in_touch then genTouchMoveEvent(motion_event, id) end end end function input.waitForEvent(usecs) local timeout = math.ceil(usecs and usecs/1000 or -1) while true do -- check for queued events if #inputQueue > 0 then -- return oldest FIFO element return table.remove(inputQueue, 1) end local events = ffi.new("int[1]") local source = ffi.new("struct android_poll_source*[1]") local poll_state = ffi.C.ALooper_pollAll(timeout, nil, events, ffi.cast("void**", source)) if poll_state >= 0 then if source[0] ~= nil then --source[0].process(android.app, source[0]) if source[0].id == ffi.C.LOOPER_ID_MAIN then local cmd = ffi.C.android_app_read_cmd(android.app) ffi.C.android_app_pre_exec_cmd(android.app, cmd) android.LOGI("got command: " .. tonumber(cmd)) if cmd == ffi.C.APP_CMD_INIT_WINDOW then fb:refresh() elseif cmd == ffi.C.APP_CMD_TERM_WINDOW then -- do nothing for now elseif cmd == ffi.C.APP_CMD_LOST_FOCUS then -- do we need this here? fb:refresh() end ffi.C.android_app_post_exec_cmd(android.app, cmd) elseif source[0].id == ffi.C.LOOPER_ID_INPUT then local event = ffi.new("AInputEvent*[1]") while ffi.C.AInputQueue_getEvent(android.app.inputQueue, event) >= 0 do if ffi.C.AInputQueue_preDispatchEvent(android.app.inputQueue, event[0]) == 0 then if ffi.C.AInputEvent_getType(event[0]) == ffi.C.AINPUT_EVENT_TYPE_MOTION then motionEventHandler(event[0]) end ffi.C.AInputQueue_finishEvent(android.app.inputQueue, event[0], 1) end end end end if android.app.destroyRequested ~= 0 then android.LOGI("Engine thread destroy requested!") error("application forced to quit") return end elseif poll_state == ffi.C.ALOOPER_POLL_TIMEOUT then error("Waiting for input failed: timeout\n") end end end function input.fakeTapInput() end function input.closeAll() end return input
local ffi = require("ffi") local bit = require("bit") local android = require("android") local dummy = require("ffi/linux_input_h") -- to trigger refreshes for certain Android framework events: local fb = require("ffi/framebuffer_android").open() local input = {} function input.open() end local inputQueue = {} local ev_time = ffi.new("struct timeval") local function genEmuEvent(evtype, code, value) ffi.C.gettimeofday(ev_time, nil) local ev = { type = tonumber(evtype), code = tonumber(code), value = tonumber(value), time = { sec = tonumber(ev_time.tv_sec), usec = tonumber(ev_time.tv_usec) } } table.insert(inputQueue, ev) end local function genTouchDownEvent(event, id) local x = ffi.C.AMotionEvent_getX(event, id) local y = ffi.C.AMotionEvent_getY(event, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_TRACKING_ID, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y) genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0) end local function genTouchUpEvent(event, id) local x = ffi.C.AMotionEvent_getX(event, id) local y = ffi.C.AMotionEvent_getY(event, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_TRACKING_ID, -1) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y) genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0) end local function genTouchMoveEvent(event, id, index) local x = ffi.C.AMotionEvent_getX(event, index) local y = ffi.C.AMotionEvent_getY(event, index) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x) genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y) genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0) end local is_in_touch = false local function motionEventHandler(motion_event) local action = ffi.C.AMotionEvent_getAction(motion_event) local pointer_count = ffi.C.AMotionEvent_getPointerCount(motion_event) local pointer_index = bit.rshift( bit.band(action, ffi.C.AMOTION_EVENT_ACTION_POINTER_INDEX_MASK), ffi.C.AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT) local id = ffi.C.AMotionEvent_getPointerId(motion_event, pointer_index) local flags = bit.band(action, ffi.C.AMOTION_EVENT_ACTION_MASK) if flags == ffi.C.AMOTION_EVENT_ACTION_DOWN then is_in_touch = true genTouchDownEvent(motion_event, id) elseif flags == ffi.C.AMOTION_EVENT_ACTION_POINTER_DOWN then is_in_touch = true genTouchDownEvent(motion_event, id) elseif flags == ffi.C.AMOTION_EVENT_ACTION_UP then is_in_touch = false genTouchUpEvent(motion_event, id) elseif flags == ffi.C.AMOTION_EVENT_ACTION_POINTER_UP then is_in_touch = false genTouchUpEvent(motion_event, id) elseif flags == ffi.C.AMOTION_EVENT_ACTION_MOVE then if is_in_touch then for index = 0, pointer_count - 1 do id = ffi.C.AMotionEvent_getPointerId(motion_event, index) genTouchMoveEvent(motion_event, id, index) end end end end function input.waitForEvent(usecs) local timeout = math.ceil(usecs and usecs/1000 or -1) while true do -- check for queued events if #inputQueue > 0 then -- return oldest FIFO element return table.remove(inputQueue, 1) end local events = ffi.new("int[1]") local source = ffi.new("struct android_poll_source*[1]") local poll_state = ffi.C.ALooper_pollAll(timeout, nil, events, ffi.cast("void**", source)) if poll_state >= 0 then if source[0] ~= nil then --source[0].process(android.app, source[0]) if source[0].id == ffi.C.LOOPER_ID_MAIN then local cmd = ffi.C.android_app_read_cmd(android.app) ffi.C.android_app_pre_exec_cmd(android.app, cmd) android.LOGI("got command: " .. tonumber(cmd)) if cmd == ffi.C.APP_CMD_INIT_WINDOW then fb:refresh() elseif cmd == ffi.C.APP_CMD_TERM_WINDOW then -- do nothing for now elseif cmd == ffi.C.APP_CMD_LOST_FOCUS then -- do we need this here? fb:refresh() end ffi.C.android_app_post_exec_cmd(android.app, cmd) elseif source[0].id == ffi.C.LOOPER_ID_INPUT then local event = ffi.new("AInputEvent*[1]") while ffi.C.AInputQueue_getEvent(android.app.inputQueue, event) >= 0 do if ffi.C.AInputQueue_preDispatchEvent(android.app.inputQueue, event[0]) == 0 then if ffi.C.AInputEvent_getType(event[0]) == ffi.C.AINPUT_EVENT_TYPE_MOTION then motionEventHandler(event[0]) end ffi.C.AInputQueue_finishEvent(android.app.inputQueue, event[0], 1) end end end end if android.app.destroyRequested ~= 0 then android.LOGI("Engine thread destroy requested!") error("application forced to quit") return end elseif poll_state == ffi.C.ALOOPER_POLL_TIMEOUT then error("Waiting for input failed: timeout\n") end end end function input.fakeTapInput() end function input.closeAll() end return input
fix multi-touch in Android
fix multi-touch in Android
Lua
agpl-3.0
houqp/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,koreader/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,koreader/koreader-base,koreader/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,houqp/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base
e95c1ffbc5cf8e265b8d427384525f770be8f892
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") require("luci.model.uci") require("luci.util") m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "") s.addremove = true s.anonymous = true iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) local uci = luci.model.uci.cursor() uci:foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface.default = iface.default or section[".name"] s:depends("interface", section[".name"]) end end) uci:foreach("network", "alias", function (section) iface:value(section[".name"]) s:depends("interface", section[".name"]) end) s:option(Value, "start", translate("Start")).rmempty = true s:option(Value, "limit", translate("Limit")).rmempty = true s:option(Value, "leasetime").rmempty = true local dd = s:option(Flag, "dynamicdhcp") dd.rmempty = false function dd.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "1" end s:option(Value, "name", translate("Name")).optional = true ignore = s:option(Flag, "ignore") ignore.optional = true s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true s:option(Flag, "force").optional = true s:option(DynamicList, "dhcp_option").optional = true for i, n in ipairs(s.children) do if n ~= iface and n ~= ignore then n:depends("ignore", "") end end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") require("luci.model.uci") require("luci.util") m = Map("dhcp", translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"), translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " .. "members can automatically receive their network settings (<abbr title=" .. "\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " .. "System\">DNS</abbr>-server, ...).")) s = m:section(TypedSection, "dhcp", "") s.addremove = true s.anonymous = true iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) local uci = luci.model.uci.cursor() uci:foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface.default = iface.default or section[".name"] s:depends("interface", section[".name"]) end end) uci:foreach("network", "alias", function (section) iface:value(section[".name"]) s:depends("interface", section[".name"]) end) s:option(Value, "start", translate("Start")).rmempty = true s:option(Value, "limit", translate("Limit")).rmempty = true s:option(Value, "leasetime", translate("Leasetime")).rmempty = true local dd = s:option(Flag, "dynamicdhcp", translate("dynamic")) dd.rmempty = false function dd.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "1" end s:option(Value, "name", translate("Name")).optional = true ignore = s:option(Flag, "ignore", translate("Ignore interface"), translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " .. "this interface")) ignore.optional = true s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true s:option(Flag, "force", translate("Force")).optional = true s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true for i, n in ipairs(s.children) do if n ~= iface and n ~= ignore then n:depends("ignore", "") end end return m
modules/admin-full: fix dhcp page
modules/admin-full: fix dhcp page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5465 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
588d8775048259b158c8ce750624ed0729f8ab91
util/datamanager.lua
util/datamanager.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local format = string.format; local setmetatable, type = setmetatable, type; local pairs, ipairs = pairs, ipairs; local char = string.char; local loadfile, setfenv, pcall = loadfile, setfenv, pcall; local log = require "util.logger".init("datamanager"); local io_open = io.open; local os_remove = os.remove; local io_popen = io.popen; local tostring, tonumber = tostring, tonumber; local error = error; local next = next; local t_insert = table.insert; local append = require "util.serialization".append; local path_separator = "/"; if os.getenv("WINDIR") then path_separator = "\\" end module "datamanager" ---- utils ----- local encode, decode; do local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); decode = function (s) return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes)); end encode = function (s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end end local _mkdir = {}; local function mkdir(path) path = path:gsub("/", path_separator); -- TODO as an optimization, do this during path creation rather than here if not _mkdir[path] then local x = io_popen("mkdir \""..path.."\" 2>&1"):read("*a"); _mkdir[path] = true; end return path; end local data_path = "data"; local callbacks = {}; ------- API ------------- function set_data_path(path) log("debug", "Setting data path to: %s", path); data_path = path; end local function callback(username, host, datastore, data) for _, f in ipairs(callbacks) do username, host, datastore, data = f(username, host, datastore, data); if username == false then break; end end return username, host, datastore, data; end function add_callback(func) if not callbacks[func] then -- Would you really want to set the same callback more than once? callbacks[func] = true; callbacks[#callbacks+1] = func; return true; end end function remove_callback(func) if callbacks[func] then for i, f in ipairs(callbacks) do if f == func then callbacks[i] = nil; callbacks[f] = nil; return true; end end end end function getpath(username, host, datastore, ext, create) ext = ext or "dat"; host = host and encode(host); username = username and encode(username); if username then if create then mkdir(mkdir(mkdir(data_path).."/"..host).."/"..datastore); end return format("%s/%s/%s/%s.%s", data_path, host, datastore, username, ext); elseif host then if create then mkdir(mkdir(data_path).."/"..host); end return format("%s/%s/%s.%s", data_path, host, datastore, ext); else if create then mkdir(data_path); end return format("%s/%s.%s", data_path, datastore, ext); end end function load(username, host, datastore) local data, ret = loadfile(getpath(username, host, datastore)); if not data then log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil")); return nil; end setfenv(data, {}); local success, ret = pcall(data); if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil")); return nil; end return ret; end function store(username, host, datastore, data) if not data then data = {}; end username, host, datastore, data = callback(username, host, datastore, data); if username == false then return true; -- Don't save this data at all end -- save the datastore local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+"); if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil")); return; end f:write("return "); append(f, data); f:close(); if next(data) == nil then -- try to delete empty datastore log("debug", "Removing empty %s datastore for user %s@%s", datastore, username, host); os_remove(getpath(username, host, datastore)); end -- we write data even when we are deleting because lua doesn't have a -- platform independent way of checking for non-exisitng files return true; end function list_append(username, host, datastore, data) if not data then return; end if callback(username, host, datastore) == false then return true; end -- save the datastore local f, msg = io_open(getpath(username, host, datastore, "list", true), "a+"); if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil")); return; end f:write("item("); append(f, data); f:write(");\n"); f:close(); return true; end function list_store(username, host, datastore, data) if not data then data = {}; end if callback(username, host, datastore) == false then return true; end -- save the datastore local f, msg = io_open(getpath(username, host, datastore, "list", true), "w+"); if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil")); return; end for _, d in ipairs(data) do f:write("item("); append(f, d); f:write(");\n"); end f:close(); if next(data) == nil then -- try to delete empty datastore log("debug", "Removing empty %s datastore for user %s@%s", datastore, username, host); os_remove(getpath(username, host, datastore, "list")); end -- we write data even when we are deleting because lua doesn't have a -- platform independent way of checking for non-exisitng files return true; end function list_load(username, host, datastore) local data, ret = loadfile(getpath(username, host, datastore, "list")); if not data then log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil")); return nil; end local items = {}; setfenv(data, {item = function(i) t_insert(items, i); end}); local success, ret = pcall(data); if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil")); return nil; end return items; end return _M;
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local format = string.format; local setmetatable, type = setmetatable, type; local pairs, ipairs = pairs, ipairs; local char = string.char; local loadfile, setfenv, pcall = loadfile, setfenv, pcall; local log = require "util.logger".init("datamanager"); local io_open = io.open; local os_remove = os.remove; local io_popen = io.popen; local tostring, tonumber = tostring, tonumber; local error = error; local next = next; local t_insert = table.insert; local append = require "util.serialization".append; local path_separator = "/"; if os.getenv("WINDIR") then path_separator = "\\" end module "datamanager" ---- utils ----- local encode, decode; do local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); decode = function (s) return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes)); end encode = function (s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end end local _mkdir = {}; local function mkdir(path) path = path:gsub("/", path_separator); -- TODO as an optimization, do this during path creation rather than here if not _mkdir[path] then local x = io_popen("mkdir \""..path.."\" 2>&1"):read("*a"); _mkdir[path] = true; end return path; end local data_path = "data"; local callbacks = {}; ------- API ------------- function set_data_path(path) log("debug", "Setting data path to: %s", path); data_path = path; end local function callback(username, host, datastore, data) for _, f in ipairs(callbacks) do username, host, datastore, data = f(username, host, datastore, data); if username == false then break; end end return username, host, datastore, data; end function add_callback(func) if not callbacks[func] then -- Would you really want to set the same callback more than once? callbacks[func] = true; callbacks[#callbacks+1] = func; return true; end end function remove_callback(func) if callbacks[func] then for i, f in ipairs(callbacks) do if f == func then callbacks[i] = nil; callbacks[f] = nil; return true; end end end end function getpath(username, host, datastore, ext, create) ext = ext or "dat"; host = host and encode(host); username = username and encode(username); if username then if create then mkdir(mkdir(mkdir(data_path).."/"..host).."/"..datastore); end return format("%s/%s/%s/%s.%s", data_path, host, datastore, username, ext); elseif host then if create then mkdir(mkdir(data_path).."/"..host); end return format("%s/%s/%s.%s", data_path, host, datastore, ext); else if create then mkdir(data_path); end return format("%s/%s.%s", data_path, datastore, ext); end end function load(username, host, datastore) local data, ret = loadfile(getpath(username, host, datastore)); if not data then log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil")); return nil; end setfenv(data, {}); local success, ret = pcall(data); if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil")); return nil; end return ret; end function store(username, host, datastore, data) if not data then data = {}; end username, host, datastore, data = callback(username, host, datastore, data); if username == false then return true; -- Don't save this data at all end -- save the datastore local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+"); if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil")); return; end f:write("return "); append(f, data); f:close(); if next(data) == nil then -- try to delete empty datastore log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil"); os_remove(getpath(username, host, datastore)); end -- we write data even when we are deleting because lua doesn't have a -- platform independent way of checking for non-exisitng files return true; end function list_append(username, host, datastore, data) if not data then return; end if callback(username, host, datastore) == false then return true; end -- save the datastore local f, msg = io_open(getpath(username, host, datastore, "list", true), "a+"); if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil")); return; end f:write("item("); append(f, data); f:write(");\n"); f:close(); return true; end function list_store(username, host, datastore, data) if not data then data = {}; end if callback(username, host, datastore) == false then return true; end -- save the datastore local f, msg = io_open(getpath(username, host, datastore, "list", true), "w+"); if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil")); return; end for _, d in ipairs(data) do f:write("item("); append(f, d); f:write(");\n"); end f:close(); if next(data) == nil then -- try to delete empty datastore log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil"); os_remove(getpath(username, host, datastore, "list")); end -- we write data even when we are deleting because lua doesn't have a -- platform independent way of checking for non-exisitng files return true; end function list_load(username, host, datastore) local data, ret = loadfile(getpath(username, host, datastore, "list")); if not data then log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil")); return nil; end local items = {}; setfenv(data, {item = function(i) t_insert(items, i); end}); local success, ret = pcall(data); if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil")); return nil; end return items; end return _M;
datamanager: Fixed logging errors on deletion of datastores not owned by a user@host
datamanager: Fixed logging errors on deletion of datastores not owned by a user@host
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
826be07f72de4420f2121c0e78371bab68fee271
src/make.lua
src/make.lua
local file_dir local test_dir local function git_fresh(fname) local f = io.open((test_dir / fname):string(), 'rb') local test_file = f:read('*a') f:close() local map_file f = io.open((file_dir / fname):string(), 'rb') if f then map_file = f:read('*a') f:close() end if test_file ~= map_file then f = io.open((file_dir / fname):string(), 'wb') f:write(test_file) f:close() print('[ɹ]: ' .. fname) end end local function main() -- arg[1]Ϊͼ, arg[2]Ϊ· local flag_newmap if (not arg) or (#arg < 2) then print('[]: 뽫ͼ϶bat') do return end flag_newmap = true end local input_map = flag_newmap and (arg[1] .. 'src\\map.w3x') or arg[1] local root_dir = flag_newmap and arg[1] or arg[2] --requireѰ· package.path = package.path .. ';' .. root_dir .. 'src\\?.lua' package.cpath = package.cpath .. ';' .. root_dir .. 'build\\?.dll' require 'luabind' require 'filesystem' require 'utility' --· git_path = root_dir local input_map = fs.path(input_map) local root_dir = fs.path(root_dir) file_dir = root_dir / 'map' fs.create_directories(root_dir / 'test') test_dir = root_dir / 'test' local output_map = test_dir / input_map:filename():string() --һݵͼ pcall(fs.copy_file, input_map, output_map, true) --򿪵ͼ local inmap = mpq_open(output_map) if inmap then print('[ɹ]: ' .. input_map:string()) else print('[ʧ]: ' .. input_map:string()) return end local fname if not flag_newmap then --listfile fname = '(listfile)' if inmap:extract(fname, test_dir / fname) then print('[ɹ]: ' .. fname) else print('[ʧ]: ' .. fname) return end --listfile for line in io.lines((test_dir / fname):string()) do --listfileоٵÿһļ local dir = fs.path(test_dir:string() .. '\\' .. line) local map_dir = fs.path(file_dir:string() .. '\\' .. line) local dir_par = dir:parent_path() local map_dir_par = map_dir:parent_path() fs.create_directories(dir_par) fs.create_directories(map_dir_par) if inmap:extract(line, dir) then --print('[ɹ]: ' .. line) git_fresh(line) else print('[ʧ]: ' .. line) return end end end --[[ --dirµļ,ͼ local files = {} local function dir_scan(dir) for full_path in dir:list_directory() do if fs.is_directory(full_path) then -- ݹ鴦 dir_scan(full_path) else local name = full_path:string():gsub(file_dir:string() .. '\\', '') --ļfiles table.insert(files, name) end end end dir_scan(file_dir) --µlistfile fname = '(listfile)' local listfile_path = test_dir / fname local listfile = io.open(listfile_path:string(), 'w') listfile:write(table.concat(files, '\n') .. "\n") listfile:close() git_fresh(fname) local map_dir = root_dir / 'src' / 'map.w3x' local new_dir = root_dir / 'test' / input_map:filename():string() if not flag_newmap then --Ƶͼģ嵽test,֮ǰĵͼ inmap:close() if pcall(fs.copy_file, map_dir, new_dir, true) then print('[ɹ]: ' .. new_dir:string()) else print('[ʧ]: ' .. new_dir:string()) end inmap = mpq_open(new_dir) if inmap then print('[ɹ]: ' .. new_dir:string()) else print('[ʧ]: ' .. new_dir:string()) return end end --ļȫȥ table.insert(files, '(listfile)') for _, name in ipairs(files) do if name ~= '(listfile)' then if inmap:import(name, file_dir / name) then print('[ɹ]: ' .. name) else print('[ʧ]: ' .. name) end end end if not flag_newmap then local dir = input_map:parent_path() / ('new_' .. input_map:filename():string()) if pcall(fs.copy_file, new_dir, dir, true) then print('[ɹ]: ' .. dir:string()) else print('[ʧ]: ' .. dir:string()) end end --]] inmap:close() print('[]: ʱ ' .. os.clock() .. ' ') end main()
local file_dir local test_dir local function git_fresh(fname) local r, w = 'rb', 'wb' if fname:sub(-2) == '.j' or fname:sub(-4) == '.lua' then r, w = 'r', 'w' end local f = io.open((test_dir / fname):string(), r) local test_file = f:read('*a') f:close() local map_file f = io.open((file_dir / fname):string(), r) if f then map_file = f:read('*a') f:close() end if test_file ~= map_file then f = io.open((file_dir / fname):string(), w) f:write(test_file) f:close() print('[ɹ]: ' .. fname) end end local function main() -- arg[1]Ϊͼ, arg[2]Ϊ· local flag_newmap if (not arg) or (#arg < 2) then print('[]: 뽫ͼ϶bat') do return end flag_newmap = true end local input_map = flag_newmap and (arg[1] .. 'src\\map.w3x') or arg[1] local root_dir = flag_newmap and arg[1] or arg[2] --requireѰ· package.path = package.path .. ';' .. root_dir .. 'src\\?.lua' package.cpath = package.cpath .. ';' .. root_dir .. 'build\\?.dll' require 'luabind' require 'filesystem' require 'utility' --· git_path = root_dir local input_map = fs.path(input_map) local root_dir = fs.path(root_dir) file_dir = root_dir / 'map' fs.create_directories(root_dir / 'test') test_dir = root_dir / 'test' local output_map = test_dir / input_map:filename():string() --һݵͼ pcall(fs.copy_file, input_map, output_map, true) --򿪵ͼ local inmap = mpq_open(output_map) if inmap then print('[ɹ]: ' .. input_map:string()) else print('[ʧ]: ' .. input_map:string()) return end local fname if not flag_newmap then --listfile fname = '(listfile)' if inmap:extract(fname, test_dir / fname) then print('[ɹ]: ' .. fname) else print('[ʧ]: ' .. fname) return end --listfile for line in io.lines((test_dir / fname):string()) do --listfileоٵÿһļ local dir = fs.path(test_dir:string() .. '\\' .. line) local map_dir = fs.path(file_dir:string() .. '\\' .. line) local dir_par = dir:parent_path() local map_dir_par = map_dir:parent_path() fs.create_directories(dir_par) fs.create_directories(map_dir_par) if inmap:extract(line, dir) then --print('[ɹ]: ' .. line) git_fresh(line) else print('[ʧ]: ' .. line) return end end end --[[ --dirµļ,ͼ local files = {} local function dir_scan(dir) for full_path in dir:list_directory() do if fs.is_directory(full_path) then -- ݹ鴦 dir_scan(full_path) else local name = full_path:string():gsub(file_dir:string() .. '\\', '') --ļfiles table.insert(files, name) end end end dir_scan(file_dir) --µlistfile fname = '(listfile)' local listfile_path = test_dir / fname local listfile = io.open(listfile_path:string(), 'w') listfile:write(table.concat(files, '\n') .. "\n") listfile:close() git_fresh(fname) local map_dir = root_dir / 'src' / 'map.w3x' local new_dir = root_dir / 'test' / input_map:filename():string() if not flag_newmap then --Ƶͼģ嵽test,֮ǰĵͼ inmap:close() if pcall(fs.copy_file, map_dir, new_dir, true) then print('[ɹ]: ' .. new_dir:string()) else print('[ʧ]: ' .. new_dir:string()) end inmap = mpq_open(new_dir) if inmap then print('[ɹ]: ' .. new_dir:string()) else print('[ʧ]: ' .. new_dir:string()) return end end --ļȫȥ table.insert(files, '(listfile)') for _, name in ipairs(files) do if name ~= '(listfile)' then if inmap:import(name, file_dir / name) then print('[ɹ]: ' .. name) else print('[ʧ]: ' .. name) end end end if not flag_newmap then local dir = input_map:parent_path() / ('new_' .. input_map:filename():string()) if pcall(fs.copy_file, new_dir, dir, true) then print('[ɹ]: ' .. dir:string()) else print('[ʧ]: ' .. dir:string()) end end --]] inmap:close() print('[]: ʱ ' .. os.clock() .. ' ') end main()
修正会错误判断.lua文件更新状态的BUG
修正会错误判断.lua文件更新状态的BUG
Lua
apache-2.0
syj2010syj/All-star-Battle
ea575a814b3d74a3184fd880c90497d00df50fb8
src_trunk/resources/job-system/fishing/s_fishing_job.lua
src_trunk/resources/job-system/fishing/s_fishing_job.lua
local totalCatch = 0 local fishSize = 0 -- /fish to start fishing. function startFishing(thePlayer) if not (thePlayer) then thePlayer = source end local element = getPedContactElement(thePlayer) if not (isElement(element)) then outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0) else if not (getElementType(element)=="vehicle") then outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0) else if not (getVehicleType(element)=="Boat") then outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0) else local x, y, z = getElementPosition(thePlayer) if (x < 3000) or (y > 4000) then -- the further out to sea you go the bigger the fish you will catch. outputChatBox("You must be out at sea to fish.", thePlayer, 255, 0, 0) else if not(exports.global:doesPlayerHaveItem(thePlayer, 49)) then -- does the player have the fishing rod item? outputChatBox("You need a fishing rod to fish.", thePlayer, 255, 0, 0) else if (catchTimer) then -- Are they already fishing? outputChatBox("You have already cast your line. Wait for a fish to bite.", thePlayer, 255, 0, 0) else if (totalCatch >= 2000) then outputChatBox("#FF9933The boat can't hold any more fish. #FF66CCSell#FF9933 the fish you have caught before continuing.", thePlayer, 255, 104, 91, true) else local biteTimer = math.random(60000,300000) --catchTimer = setTimer( theyHaveABite, biteTimer, 1, thePlayer) -- A fish will bite within 1 and 5 minutes. catchTimer = setTimer( theyHaveABite, 10000, 1, thePlayer) exports.global:sendLocalMeAction(thePlayer,"casts a fishing line.") if not (colsphere) then -- If the /sellfish marker isnt already being shown... blip = createBlip( 2243.7339, 578.905, 6.78, 0, 2, 255, 0, 255, 255 ) marker = createMarker( 2243.7339, 578.905, 6.78, "cylinder", 2, 255, 0, 255, 150 ) colsphere = createColSphere (2243.7339, 578.905, 6.78, 3) exports.pool:allocateElement(blip) exports.pool:allocateElement(marker) exports.pool:allocateElement(colsphere) setElementVisibleTo(blip, getRootElement(), false) setElementVisibleTo(blip, thePlayer, true) setElementVisibleTo(marker, getRootElement(), false) setElementVisibleTo(marker, thePlayer, true) outputChatBox("#FF9933When you are done fishing you can sell your catch at the fish market ((#FF66CCblip#FF9933 added to radar)).", thePlayer, 255, 104, 91, true) outputChatBox("#FF9933((/totalcatch to see how much you have caught. To sell your catch enter /sellfish in the #FF66CCmarker#FF9933.))", thePlayer, 255, 104, 91, true) end end end end end end end end end addCommandHandler("fish", startFishing, false, false) addEvent("fish") addEventHandler("fish", getRootElement(), startFishing) ------ triggers the mini game. function theyHaveABite(source) killTimer(catchTimer) catchTimer=nil triggerClientEvent("createReel", source) exports.global:sendLocalMeAction(source,"has a bite!") end ----- Snapped line. function lineSnap() exports.global:takePlayerItem(source, 49, 1) -- fishing rod exports.global:sendLocalMeAction(source,"snaps their fishing line.") outputChatBox("The monster of a fish has broken your line. You need to buy a new fishing rod to continue fishing.", source, 255, 0, 0) end addEvent("lineSnap",true) addEventHandler("lineSnap", getRootElement(), lineSnap) ----- Successfully reeled in the fish. function catchFish(fishSize) exports.global:sendLocalMeAction(source,"catches a fish weighing ".. fishSize .."lbs.") totalCatch = math.floor(totalCatch + fishSize) outputChatBox("You have caught "..totalCatch.."lbs of fish so far.", source, 255, 194, 14) if (fishSize >= 100) then exports.global:givePlayerAchievement(source, 35) end end addEvent("catchFish", true) addEventHandler("catchFish", getRootElement(), catchFish) ------ /totalcatch command function currentCatch(thePlayer) outputChatBox("You have "..totalCatch.."lbs of fish caught so far.", thePlayer, 255, 194, 14) end addCommandHandler("totalcatch", currentCatch, false, false) ------ /sellfish function unloadCatch(thePlayer) if (isElementWithinColShape(thePlayer, colsphere)) then if (totalCatch == 0) then outputChatBox("You need to catch some fish to sell first." ,thePlayer, 255, 0, 0) else local profit = math.floor(totalCatch/2) exports.global:sendLocalMeAction(thePlayer,"sells " .. totalCatch .."lbs of fish.") exports.global:givePlayerSafeMoney(thePlayer, profit) outputChatBox("You made $".. profit .." from the fish you caught." ,thePlayer, 255, 104, 91) totalCatch = 0 destroyElement(blip) destroyElement(marker) destroyElement(colsphere) blip=nil marker=nil colsphere=nil end else outputChatBox("You need to be at the fish market to sell your catch.", thePlayer, 255, 0, 0) end end addCommandHandler("sellFish", unloadCatch, false, false)
local totalCatch = 0 local fishSize = 0 -- /fish to start fishing. function startFishing(thePlayer) if not (thePlayer) then thePlayer = source end local element = getPedContactElement(thePlayer) local totalCatch = getElementData(thePlayer, "totalcatch") if not (totalCatch) then totalCatch = 0 end if not (isElement(element)) then outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0) else if not (getElementType(element)=="vehicle") then outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0) else if not (getVehicleType(element)=="Boat") then outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0) else local x, y, z = getElementPosition(thePlayer) if (x < 3000) or (y > 4000) then -- the further out to sea you go the bigger the fish you will catch. outputChatBox("You must be out at sea to fish.", thePlayer, 255, 0, 0) else if not(exports.global:doesPlayerHaveItem(thePlayer, 49)) then -- does the player have the fishing rod item? outputChatBox("You need a fishing rod to fish.", thePlayer, 255, 0, 0) else if (catchTimer) then -- Are they already fishing? outputChatBox("You have already cast your line. Wait for a fish to bite.", thePlayer, 255, 0, 0) else if (totalCatch >= 2000) then outputChatBox("#FF9933The boat can't hold any more fish. #FF66CCSell#FF9933 the fish you have caught before continuing.", thePlayer, 255, 104, 91, true) else local biteTimer = math.random(60000,300000) --catchTimer = setTimer( theyHaveABite, biteTimer, 1, thePlayer) -- A fish will bite within 1 and 5 minutes. catchTimer = setTimer( theyHaveABite, 10000, 1, thePlayer) exports.global:sendLocalMeAction(thePlayer,"casts a fishing line.") if not (colsphere) then -- If the /sellfish marker isnt already being shown... blip = createBlip( 2243.7339, 578.905, 6.78, 0, 2, 255, 0, 255, 255 ) marker = createMarker( 2243.7339, 578.905, 6.78, "cylinder", 2, 255, 0, 255, 150 ) colsphere = createColSphere (2243.7339, 578.905, 6.78, 3) exports.pool:allocateElement(blip) exports.pool:allocateElement(marker) exports.pool:allocateElement(colsphere) setElementVisibleTo(blip, getRootElement(), false) setElementVisibleTo(blip, thePlayer, true) setElementVisibleTo(marker, getRootElement(), false) setElementVisibleTo(marker, thePlayer, true) outputChatBox("#FF9933When you are done fishing you can sell your catch at the fish market ((#FF66CCblip#FF9933 added to radar)).", thePlayer, 255, 104, 91, true) outputChatBox("#FF9933((/totalcatch to see how much you have caught. To sell your catch enter /sellfish in the #FF66CCmarker#FF9933.))", thePlayer, 255, 104, 91, true) end end end end end end end end end addCommandHandler("fish", startFishing, false, false) addEvent("fish") addEventHandler("fish", getRootElement(), startFishing) ------ triggers the mini game. function theyHaveABite(source) killTimer(catchTimer) catchTimer=nil triggerClientEvent("createReel", source) exports.global:sendLocalMeAction(source,"has a bite!") end ----- Snapped line. function lineSnap() exports.global:takePlayerItem(source, 49, 1) -- fishing rod exports.global:sendLocalMeAction(source,"snaps their fishing line.") outputChatBox("The monster of a fish has broken your line. You need to buy a new fishing rod to continue fishing.", source, 255, 0, 0) end addEvent("lineSnap",true) addEventHandler("lineSnap", getRootElement(), lineSnap) ----- Successfully reeled in the fish. function catchFish(fishSize) exports.global:sendLocalMeAction(source,"catches a fish weighing ".. fishSize .."lbs.") local totalCatch = getElementData(thePlayer, "totalcatch") totalCatch = math.floor(totalCatch + fishSize) outputChatBox("You have caught "..totalCatch.."lbs of fish so far.", source, 255, 194, 14) if (fishSize >= 100) then exports.global:givePlayerAchievement(source, 35) end end addEvent("catchFish", true) addEventHandler("catchFish", getRootElement(), catchFish) ------ /totalcatch command function currentCatch(thePlayer) local totalCatch = getElementData(thePlayer, "totalcatch") outputChatBox("You have "..totalCatch.."lbs of fish caught so far.", thePlayer, 255, 194, 14) end addCommandHandler("totalcatch", currentCatch, false, false) ------ /sellfish function unloadCatch(thePlayer) if (isElementWithinColShape(thePlayer, colsphere)) then local totalCatch = getElementData(thePlayer, "totalcatch") if (totalCatch == 0) then outputChatBox("You need to catch some fish to sell first." ,thePlayer, 255, 0, 0) else local profit = math.floor(totalCatch/2) exports.global:sendLocalMeAction(thePlayer,"sells " .. totalCatch .."lbs of fish.") exports.global:givePlayerSafeMoney(thePlayer, profit) outputChatBox("You made $".. profit .." from the fish you caught." ,thePlayer, 255, 104, 91) totalCatch = 0 destroyElement(blip) destroyElement(marker) destroyElement(colsphere) blip=nil marker=nil colsphere=nil end else outputChatBox("You need to be at the fish market to sell your catch.", thePlayer, 255, 0, 0) end end addCommandHandler("sellFish", unloadCatch, false, false)
Fix for total catch being global
Fix for total catch being global git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@510 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
8436d90adcb24be51aa5bd1e1f07d289a9aca857
src/hs/finalcutpro/main/PrimaryWindow.lua
src/hs/finalcutpro/main/PrimaryWindow.lua
local log = require("hs.logger").new("PrefsDlg") local inspect = require("hs.inspect") local axutils = require("hs.finalcutpro.axutils") local just = require("hs.just") local Button = require("hs.finalcutpro.ui.Button") local Inspector = require("hs.finalcutpro.main.Inspector") local ColorBoard = require("hs.finalcutpro.main.ColorBoard") local PrimaryWindow = {} function PrimaryWindow.matches(w) return w and w:attributeValue("AXSubrole") == "AXStandardWindow" end function PrimaryWindow:new(app) o = { _app = app } setmetatable(o, self) self.__index = self return o end function PrimaryWindow:app() return self._app end function PrimaryWindow:isShowing() return self:UI() ~= nil end function PrimaryWindow:show() -- Currently a null-op. Determin if there are any scenarios where we need to force this. return true end function PrimaryWindow:UI() return axutils.cache(self, "_ui", function() local ui = self:app():UI() if ui then if PrimaryWindow.matches(ui:mainWindow()) then return ui:mainWindow() else local windowsUI = self:app():windowsUI() return windowsUI and self:_findWindowUI(windowsUI) end end return nil end, PrimaryWindow.matches) end function PrimaryWindow:_findWindowUI(windows) for i,w in ipairs(windows) do if PrimaryWindow.matches(w) then return w end end return nil end function PrimaryWindow:isFullScreen() local ui = self:UI() return ui and ui:fullScreen() end function PrimaryWindow:setFullScreen(isFullScreen) local ui = self:UI() if ui then ui:setFullScreen(isFullScreen) end return self end function PrimaryWindow:toggleFullScreen() local ui = self:UI() if ui then ui:setFullScreen(not self:isFullScreen()) end return self end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- UI STRUCTURE ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- The top AXSplitGroup contains the function PrimaryWindow:rootGroupUI() return axutils.cache(self, "_rootGroup", function() local ui = self:UI() return ui and axutils.childWith(ui, "AXRole", "AXSplitGroup") end) end function PrimaryWindow:leftGroupUI() local root = self:rootGroupUI() if root then for i,child in ipairs(root) do -- the left group has only one child if #child == 1 then return child[1] end end end return nil end function PrimaryWindow:rightGroupUI() local root = self:rootGroupUI() if root and #root == 2 then if #(root[1]) >= 3 then return root[1] else return root[2] end end return nil end function PrimaryWindow:topGroupUI() local left = self:leftGroupUI() if left and #left >= 3 then for i,child in ipairs(left) do if #child == 1 and #(child[1]) > 1 then return child[1] end end end return nil end function PrimaryWindow:bottomGroupUI() local left = self:leftGroupUI() if left and #left >= 3 then for i,child in ipairs(left) do if #child == 1 and #(child[1]) == 1 then return child[1] end end end return nil end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- INSPECTOR ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:inspector() if not self._inspector then self._inspector = Inspector:new(self) end return self._inspector end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- INSPECTOR ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:colorBoard() if not self._colorBoard then self._colorBoard = ColorBoard:new(self) end return self._colorBoard end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- VIEWER ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:viewerGroupUI() return self:topGroupUI() end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- TIMELINE GROUP UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:timelineGroupUI() return self:bottomGroupUI() end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- BROWSER ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:browserGroupUI() return self:topGroupUI() end return PrimaryWindow
local log = require("hs.logger").new("PrefsDlg") local inspect = require("hs.inspect") local axutils = require("hs.finalcutpro.axutils") local just = require("hs.just") local Button = require("hs.finalcutpro.ui.Button") local Inspector = require("hs.finalcutpro.main.Inspector") local ColorBoard = require("hs.finalcutpro.main.ColorBoard") local PrimaryWindow = {} function PrimaryWindow.matches(w) return w and w:attributeValue("AXSubrole") == "AXStandardWindow" end function PrimaryWindow:new(app) o = { _app = app } setmetatable(o, self) self.__index = self return o end function PrimaryWindow:app() return self._app end function PrimaryWindow:isShowing() return self:UI() ~= nil end function PrimaryWindow:show() -- Currently a null-op. Determin if there are any scenarios where we need to force this. return true end function PrimaryWindow:UI() return axutils.cache(self, "_ui", function() local ui = self:app():UI() if ui then if PrimaryWindow.matches(ui:mainWindow()) then return ui:mainWindow() else local windowsUI = self:app():windowsUI() return windowsUI and self:_findWindowUI(windowsUI) end end return nil end, PrimaryWindow.matches) end function PrimaryWindow:_findWindowUI(windows) for i,w in ipairs(windows) do if PrimaryWindow.matches(w) then return w end end return nil end function PrimaryWindow:isFullScreen() local ui = self:UI() return ui and ui:fullScreen() end function PrimaryWindow:setFullScreen(isFullScreen) local ui = self:UI() if ui then ui:setFullScreen(isFullScreen) end return self end function PrimaryWindow:toggleFullScreen() local ui = self:UI() if ui then ui:setFullScreen(not self:isFullScreen()) end return self end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- UI STRUCTURE ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- The top AXSplitGroup contains the function PrimaryWindow:rootGroupUI() return axutils.cache(self, "_rootGroup", function() local ui = self:UI() return ui and axutils.childWith(ui, "AXRole", "AXSplitGroup") end) end function PrimaryWindow:leftGroupUI() local root = self:rootGroupUI() if root then for i,child in ipairs(root) do -- the left group has only one child if #child == 1 then return child[1] end end end return nil end function PrimaryWindow:rightGroupUI() local root = self:rootGroupUI() if root and #root == 2 then if #(root[1]) >= 3 then return root[1] else return root[2] end end return nil end function PrimaryWindow:topGroupUI() local left = self:leftGroupUI() if left then if #left < 3 then -- Either top or bottom is visible. -- It's impossible to determine which it at this level, so just return the non-empty one for _,child in ipairs(left) do if #child > 0 then return child[1] end end elseif #left >= 3 then -- Both top and bottom are visible. Grab the highest AXGroup local top = nil for _,child in ipairs(left) do if child:attributeValue("AXRole") == "AXGroup" then if top == nil or top:frame().y > child:frame().y then top = child end end end if top then return top[1] end end end return nil end function PrimaryWindow:bottomGroupUI() local left = self:leftGroupUI() if left then if #left < 3 then -- Either top or bottom is visible. -- It's impossible to determine which it at this level, so just return the non-empty one for _,child in ipairs(left) do if #child > 0 then return child[1] end end elseif #left >= 3 then -- Both top and bottom are visible. Grab the lowest AXGroup local top = nil for _,child in ipairs(left) do if child:attributeValue("AXRole") == "AXGroup" then if top == nil or top:frame().y < child:frame().y then top = child end end end if top then return top[1] end end end return nil end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- INSPECTOR ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:inspector() if not self._inspector then self._inspector = Inspector:new(self) end return self._inspector end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- INSPECTOR ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:colorBoard() if not self._colorBoard then self._colorBoard = ColorBoard:new(self) end return self._colorBoard end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- VIEWER ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:viewerGroupUI() return self:topGroupUI() end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- TIMELINE GROUP UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:timelineGroupUI() return self:bottomGroupUI() end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- BROWSER ----------------------------------------------------------------------- ----------------------------------------------------------------------- function PrimaryWindow:browserGroupUI() return self:topGroupUI() end return PrimaryWindow
#197 * Fixed discovery of browser/timeline/etc when few UI elements are visible in the Primary Window.
#197 * Fixed discovery of browser/timeline/etc when few UI elements are visible in the Primary Window.
Lua
mit
cailyoung/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,cailyoung/CommandPost,fcpxhacks/fcpxhacks,cailyoung/CommandPost,CommandPost/CommandPost
8b8f850e01dc33ce05047521a5d4b680a6e3e12c
agents/monitoring/tests/net/init.lua
agents/monitoring/tests/net/init.lua
local table = require('table') local async = require('async') local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream local misc = require('monitoring/default/util/misc') local helper = require('../helper') local timer = require('timer') local fixtures = require('../fixtures') local constants = require('constants') local consts = require('../../default/util/constants') local Endpoint = require('../../default/endpoint').Endpoint local path = require('path') local exports = {} local child exports['test_reconnects'] = function(test, asserts) local options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } local client = ConnectionStream:new('id', 'token', 'guid', options) local clientEnd = 0 local reconnect = 0 client:on('client_end', function(err) clientEnd = clientEnd + 1 end) client:on('reconnect', function(err) reconnect = reconnect + 1 end) async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = get_endpoints() client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', counterTrigger(3, callback)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', counterTrigger(3, callback)) end) end, }, function() helper.stop_server(child) asserts.ok(clientEnd > 0) asserts.ok(reconnect > 0) test.done() end) end exports['test_upgrades'] = function(test, asserts) local options, client, endpoints -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } endpoints = get_endpoints() async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client = ConnectionStream:new('id', 'token', 'guid', options) client:on('handshake_success', misc.nCallbacks(callback, 3)) client:createConnections(endpoints, function() end) end, function(callback) callback = misc.nCallbacks(callback, 4) client:on('binary_upgrade.found', callback) client:on('bundle_upgrade.found', callback) client:on('bundle_upgrade.error', callback) client:on('binary_upgrade.error', callback) client:getUpgrade():forceUpgradeCheck() end }, function() helper.stop_server(child) client:done() test.done() end) end return exports
local table = require('table') local async = require('async') local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream local misc = require('monitoring/default/util/misc') local helper = require('../helper') local timer = require('timer') local fixtures = require('../fixtures') local constants = require('constants') local consts = require('../../default/util/constants') local Endpoint = require('../../default/endpoint').Endpoint local path = require('path') local exports = {} local child exports['test_reconnects'] = function(test, asserts) local options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } local client = ConnectionStream:new('id', 'token', 'guid', options) local clientEnd = 0 local reconnect = 0 client:on('client_end', function(err) clientEnd = clientEnd + 1 end) client:on('reconnect', function(err) reconnect = reconnect + 1 end) async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', counterTrigger(3, callback)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', counterTrigger(3, callback)) end) end, }, function() helper.stop_server(child) asserts.ok(clientEnd > 0) asserts.ok(reconnect > 0) test.done() end) end exports['test_upgrades'] = function(test, asserts) local options, client, endpoints -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } endpoints = get_endpoints() async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client = ConnectionStream:new('id', 'token', 'guid', options) client:on('handshake_success', misc.nCallbacks(callback, 3)) client:createConnections(endpoints, function() end) end, function(callback) callback = misc.nCallbacks(callback, 4) client:on('binary_upgrade.found', callback) client:on('bundle_upgrade.found', callback) client:on('bundle_upgrade.error', callback) client:on('binary_upgrade.error', callback) client:getUpgrade():forceUpgradeCheck() end }, function() helper.stop_server(child) client:done() test.done() end) end return exports
fix merge
fix merge
Lua
apache-2.0
virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
b05983e73f911176b8b34137f770709a43708de2
src/formatters/init.lua
src/formatters/init.lua
-- module will not return anything, only register formatters with the main assert engine local assert = require('luassert.assert') local ok, term = pcall(require, 'term') local colors = setmetatable({ none = function(c) return c end },{ __index = function(self, key) local isatty = io.type(io.stdout) == 'file' and term.isatty(io.stdout) if not ok or not isatty or not term.colors then return function(c) return c end end return function(c) for token in key:gmatch("[^%.]+") do c = term.colors[token](c) end return c end end }) local function fmt_string(arg) if type(arg) == "string" then return string.format("(string) '%s'", arg) end end -- A version of tostring which formats numbers more precisely. local function tostr(arg) if type(arg) ~= "number" then return tostring(arg) end if arg ~= arg then return "NaN" elseif arg == 1/0 then return "Inf" elseif arg == -1/0 then return "-Inf" end local str = string.format("%.20g", arg) if math.type and math.type(arg) == "float" and not str:find("[%.,]") then -- Number is a float but looks like an integer. -- Insert ".0" after first run of digits. str = str:gsub("%d+", "%0.0", 1) end return str end local function fmt_number(arg) if type(arg) == "number" then return string.format("(number) %s", tostr(arg)) end end local function fmt_boolean(arg) if type(arg) == "boolean" then return string.format("(boolean) %s", tostring(arg)) end end local function fmt_nil(arg) if type(arg) == "nil" then return "(nil)" end end local type_priorities = { number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7 } local function is_in_array_part(key, length) return type(key) == "number" and 1 <= key and key <= length and math.floor(key) == key end local function get_sorted_keys(t) local keys = {} local nkeys = 0 for key in pairs(t) do nkeys = nkeys + 1 keys[nkeys] = key end local length = #t local function key_comparator(key1, key2) local type1, type2 = type(key1), type(key2) local priority1 = is_in_array_part(key1, length) and 0 or type_priorities[type1] or 8 local priority2 = is_in_array_part(key2, length) and 0 or type_priorities[type2] or 8 if priority1 == priority2 then if type1 == "string" or type1 == "number" then return key1 < key2 elseif type1 == "boolean" then return key1 -- put true before false end else return priority1 < priority2 end end table.sort(keys, key_comparator) return keys, nkeys end local function fmt_table(arg, fmtargs) if type(arg) ~= "table" then return end local tmax = assert:get_parameter("TableFormatLevel") local showrec = assert:get_parameter("TableFormatShowRecursion") local errchar = assert:get_parameter("TableErrorHighlightCharacter") or "" local errcolor = assert:get_parameter("TableErrorHighlightColor") or "none" local crumbs = fmtargs and fmtargs.crumbs or {} local cache = {} local function ft(t, l, with_crumbs) if showrec and cache[t] and cache[t] > 0 then return "{ ... recursive }" end if next(t) == nil then return "{ }" end if l > tmax and tmax >= 0 then return "{ ... more }" end local result = "{" local keys, nkeys = get_sorted_keys(t) cache[t] = (cache[t] or 0) + 1 local crumb = crumbs[#crumbs - l + 1] for i = 1, nkeys do local k = keys[i] local v = t[k] local use_crumbs = with_crumbs and k == crumb if type(v) == "table" then v = ft(v, l + 1, use_crumbs) elseif type(v) == "string" then v = "'"..v.."'" end local ch = use_crumbs and errchar or "" local indent = string.rep(" ",l * 2 - ch:len()) local mark = (ch:len() == 0 and "" or colors[errcolor](ch)) result = result .. string.format("\n%s%s[%s] = %s", indent, mark, tostr(k), tostr(v)) end cache[t] = cache[t] - 1 return result .. " }" end return "(table) " .. ft(arg, 1, true) end local function fmt_function(arg) if type(arg) == "function" then local debug_info = debug.getinfo(arg) return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source)) end end local function fmt_userdata(arg) if type(arg) == "userdata" then return string.format("(userdata) '%s'", tostring(arg)) end end local function fmt_thread(arg) if type(arg) == "thread" then return string.format("(thread) '%s'", tostring(arg)) end end assert:add_formatter(fmt_string) assert:add_formatter(fmt_number) assert:add_formatter(fmt_boolean) assert:add_formatter(fmt_nil) assert:add_formatter(fmt_table) assert:add_formatter(fmt_function) assert:add_formatter(fmt_userdata) assert:add_formatter(fmt_thread) -- Set default table display depth for table formatter assert:set_parameter("TableFormatLevel", 3) assert:set_parameter("TableFormatShowRecursion", false) assert:set_parameter("TableErrorHighlightCharacter", "*") assert:set_parameter("TableErrorHighlightColor", "none")
-- module will not return anything, only register formatters with the main assert engine local assert = require('luassert.assert') local colors = setmetatable({ none = function(c) return c end },{ __index = function(self, key) local ok, term = pcall(require, 'term') local isatty = io.type(io.stdout) == 'file' and ok and term.isatty(io.stdout) if not ok or not isatty or not term.colors then return function(c) return c end end return function(c) for token in key:gmatch("[^%.]+") do c = term.colors[token](c) end return c end end }) local function fmt_string(arg) if type(arg) == "string" then return string.format("(string) '%s'", arg) end end -- A version of tostring which formats numbers more precisely. local function tostr(arg) if type(arg) ~= "number" then return tostring(arg) end if arg ~= arg then return "NaN" elseif arg == 1/0 then return "Inf" elseif arg == -1/0 then return "-Inf" end local str = string.format("%.20g", arg) if math.type and math.type(arg) == "float" and not str:find("[%.,]") then -- Number is a float but looks like an integer. -- Insert ".0" after first run of digits. str = str:gsub("%d+", "%0.0", 1) end return str end local function fmt_number(arg) if type(arg) == "number" then return string.format("(number) %s", tostr(arg)) end end local function fmt_boolean(arg) if type(arg) == "boolean" then return string.format("(boolean) %s", tostring(arg)) end end local function fmt_nil(arg) if type(arg) == "nil" then return "(nil)" end end local type_priorities = { number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7 } local function is_in_array_part(key, length) return type(key) == "number" and 1 <= key and key <= length and math.floor(key) == key end local function get_sorted_keys(t) local keys = {} local nkeys = 0 for key in pairs(t) do nkeys = nkeys + 1 keys[nkeys] = key end local length = #t local function key_comparator(key1, key2) local type1, type2 = type(key1), type(key2) local priority1 = is_in_array_part(key1, length) and 0 or type_priorities[type1] or 8 local priority2 = is_in_array_part(key2, length) and 0 or type_priorities[type2] or 8 if priority1 == priority2 then if type1 == "string" or type1 == "number" then return key1 < key2 elseif type1 == "boolean" then return key1 -- put true before false end else return priority1 < priority2 end end table.sort(keys, key_comparator) return keys, nkeys end local function fmt_table(arg, fmtargs) if type(arg) ~= "table" then return end local tmax = assert:get_parameter("TableFormatLevel") local showrec = assert:get_parameter("TableFormatShowRecursion") local errchar = assert:get_parameter("TableErrorHighlightCharacter") or "" local errcolor = assert:get_parameter("TableErrorHighlightColor") or "none" local crumbs = fmtargs and fmtargs.crumbs or {} local cache = {} local function ft(t, l, with_crumbs) if showrec and cache[t] and cache[t] > 0 then return "{ ... recursive }" end if next(t) == nil then return "{ }" end if l > tmax and tmax >= 0 then return "{ ... more }" end local result = "{" local keys, nkeys = get_sorted_keys(t) cache[t] = (cache[t] or 0) + 1 local crumb = crumbs[#crumbs - l + 1] for i = 1, nkeys do local k = keys[i] local v = t[k] local use_crumbs = with_crumbs and k == crumb if type(v) == "table" then v = ft(v, l + 1, use_crumbs) elseif type(v) == "string" then v = "'"..v.."'" end local ch = use_crumbs and errchar or "" local indent = string.rep(" ",l * 2 - ch:len()) local mark = (ch:len() == 0 and "" or colors[errcolor](ch)) result = result .. string.format("\n%s%s[%s] = %s", indent, mark, tostr(k), tostr(v)) end cache[t] = cache[t] - 1 return result .. " }" end return "(table) " .. ft(arg, 1, true) end local function fmt_function(arg) if type(arg) == "function" then local debug_info = debug.getinfo(arg) return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source)) end end local function fmt_userdata(arg) if type(arg) == "userdata" then return string.format("(userdata) '%s'", tostring(arg)) end end local function fmt_thread(arg) if type(arg) == "thread" then return string.format("(thread) '%s'", tostring(arg)) end end assert:add_formatter(fmt_string) assert:add_formatter(fmt_number) assert:add_formatter(fmt_boolean) assert:add_formatter(fmt_nil) assert:add_formatter(fmt_table) assert:add_formatter(fmt_function) assert:add_formatter(fmt_userdata) assert:add_formatter(fmt_thread) -- Set default table display depth for table formatter assert:set_parameter("TableFormatLevel", 3) assert:set_parameter("TableFormatShowRecursion", false) assert:set_parameter("TableErrorHighlightCharacter", "*") assert:set_parameter("TableErrorHighlightColor", "none")
Fix TTY detection
Fix TTY detection This fixes an error in the way `term.isatty` is called. If the `term` module is not present, then `term.isatty` will trigger an error. So we have to make sure that the call to `require 'term'` succeeded before using `term`.
Lua
mit
o-lim/luassert
7f2a1d25bb257999efb03c3ef248ad5e0e2d11d9
src/lib/numa.lua
src/lib/numa.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Call bind_to_cpu(1) to bind the current Snabb process to CPU 1 (for -- example), to bind its memory to the corresponding NUMA node, to -- migrate mapped pages to that NUMA node, and to arrange to warn if -- you use a PCI device from a remote NUMA node. See README.numa.md -- for full API documentation. local S = require("syscall") local pci = require("lib.hardware.pci") local lib = require("core.lib") local bound_cpu local bound_numa_node local node_path = '/sys/devices/system/node/node' local MAX_CPU = 1023 function cpu_get_numa_node (cpu) local node = 0 while true do local node_dir = S.open(node_path..node, 'rdonly, directory') if not node_dir then return 0 end -- default NUMA node local found = S.readlinkat(node_dir, 'cpu'..cpu) node_dir:close() if found then return node end node = node + 1 end end local function supports_numa () local node0 = S.open(node_path..tostring(0), 'rdonly, directory') if not node0 then return false end node0:close() return true end function has_numa () local node1 = S.open(node_path..tostring(1), 'rdonly, directory') if not node1 then return false end node1:close() return true end function pci_get_numa_node (addr) addr = pci.qualified(addr) local file = assert(io.open('/sys/bus/pci/devices/'..addr..'/numa_node')) local node = assert(tonumber(file:read())) -- node can be -1. return math.max(0, node) end function choose_numa_node_for_pci_addresses (addrs, require_affinity) local chosen_node, chosen_because_of_addr for _, addr in ipairs(addrs) do local node = pci_get_numa_node(addr) if not node or node == chosen_node then -- Keep trucking. elseif not chosen_node then chosen_node = node chosen_because_of_addr = addr else local msg = string.format( "PCI devices %s and %s have different NUMA node affinities", chosen_because_of_addr, addr) if require_affinity then error(msg) else print('Warning: '..msg) end end end return chosen_node end function check_affinity_for_pci_addresses (addrs) local policy = S.get_mempolicy() if policy.mode == S.c.MPOL_MODE['default'] then if has_numa() then print('Warning: No NUMA memory affinity.') print('Pass --cpu to bind to a CPU and its NUMA node.') end elseif policy.mode ~= S.c.MPOL_MODE['bind'] then print("Warning: NUMA memory policy already in effect, but it's not --membind.") else local node = S.getcpu().node local node_for_pci = choose_numa_node_for_pci_addresses(addrs) if node_for_pci and node ~= node_for_pci then print("Warning: Bound NUMA node does not have affinity with PCI devices.") end end end function unbind_cpu () local cpu_set = S.sched_getaffinity() cpu_set:zero() for i = 0, MAX_CPU do cpu_set:set(i) end assert(S.sched_setaffinity(0, cpu_set)) bound_cpu = nil end function bind_to_cpu (cpu) local function contains (t, e) for k,v in ipairs(t) do if tonumber(v) == tonumber(e) then return true end end return false end if not cpu then return unbind_cpu() end if cpu == bound_cpu then return end assert(not bound_cpu, "already bound") if type(cpu) ~= 'table' then cpu = {cpu} end assert(S.sched_setaffinity(0, cpu), ("Couldn't set affinity for cpuset %s"):format(table.concat(cpu, ','))) local cpu_and_node = S.getcpu() assert(contains(cpu, cpu_and_node.cpu)) bound_cpu = cpu_and_node.cpu bind_to_numa_node (cpu_and_node.node) end function unbind_numa_node () if supports_numa() then assert(S.set_mempolicy('default')) end bound_numa_node = nil end function bind_to_numa_node (node, policy) if node == bound_numa_node then return end if not node then return unbind_numa_node() end assert(not bound_numa_node, "already bound") if supports_numa() then assert(S.set_mempolicy(policy or 'preferred', node)) -- Migrate any pages that might have the wrong affinity. local from_mask = assert(S.get_mempolicy(nil, nil, nil, 'mems_allowed')).mask local ok, err = S.migrate_pages(0, from_mask, node) if not ok then io.stderr:write( string.format("Warning: Failed to migrate pages to NUMA node %d: %s\n", node, tostring(err))) end end bound_numa_node = node end function prevent_preemption(priority) assert(S.sched_setscheduler(0, "fifo", priority or 1), 'Failed to enable real-time scheduling. Try running as root.') end function selftest () function test_cpu(cpu) local node = cpu_get_numa_node(cpu) bind_to_cpu(cpu) assert(bound_cpu == cpu) assert(bound_numa_node == node) assert(S.getcpu().cpu == cpu) assert(S.getcpu().node == node) bind_to_cpu(nil) assert(bound_cpu == nil) assert(bound_numa_node == node) assert(S.getcpu().node == node) bind_to_numa_node(nil) assert(bound_cpu == nil) assert(bound_numa_node == nil) end function test_pci_affinity (pciaddr) check_affinity_for_pci_addresses({pciaddr}) local node = choose_numa_node_for_pci_addresses({pciaddr}, true) bind_to_numa_node(node) assert(bound_numa_node == node) check_affinity_for_pci_addresses({pciaddr}) bind_to_numa_node(nil) assert(bound_numa_node == nil) end print('selftest: numa') local cpu_set = S.sched_getaffinity() for cpuid = 0, MAX_CPU do if cpu_set:get(cpuid) then test_cpu(cpuid) end end local pciaddr = os.getenv("SNABB_PCI0") if pciaddr then test_pci_affinity(pciaddr) end print('selftest: numa: ok') end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Call bind_to_cpu(1) to bind the current Snabb process to CPU 1 (for -- example), to bind its memory to the corresponding NUMA node, to -- migrate mapped pages to that NUMA node, and to arrange to warn if -- you use a PCI device from a remote NUMA node. See README.numa.md -- for full API documentation. local S = require("syscall") local pci = require("lib.hardware.pci") local lib = require("core.lib") local bound_cpu local bound_numa_node local node_path = '/sys/devices/system/node/node' local MAX_CPU = 1023 function cpu_get_numa_node (cpu) local node = 0 while true do local node_dir = S.open(node_path..node, 'rdonly, directory') if not node_dir then return 0 end -- default NUMA node local found = S.readlinkat(node_dir, 'cpu'..cpu) node_dir:close() if found then return node end node = node + 1 end end local function supports_numa () local node0 = S.open(node_path..tostring(0), 'rdonly, directory') if not node0 then return false end node0:close() return true end function has_numa () local node1 = S.open(node_path..tostring(1), 'rdonly, directory') if not node1 then return false end node1:close() return true end function pci_get_numa_node (addr) addr = pci.qualified(addr) local file = assert(io.open('/sys/bus/pci/devices/'..addr..'/numa_node')) local node = assert(tonumber(file:read())) -- node can be -1. return math.max(0, node) end function choose_numa_node_for_pci_addresses (addrs, require_affinity) local chosen_node, chosen_because_of_addr for _, addr in ipairs(addrs) do local node = pci_get_numa_node(addr) if not node or node == chosen_node then -- Keep trucking. elseif not chosen_node then chosen_node = node chosen_because_of_addr = addr else local msg = string.format( "PCI devices %s and %s have different NUMA node affinities", chosen_because_of_addr, addr) if require_affinity then error(msg) else print('Warning: '..msg) end end end return chosen_node end function check_affinity_for_pci_addresses (addrs) local policy = S.get_mempolicy() if policy.mode == S.c.MPOL_MODE['default'] then if has_numa() then print('Warning: No NUMA memory affinity.') print('Pass --cpu to bind to a CPU and its NUMA node.') end elseif (policy.mode ~= S.c.MPOL_MODE['bind'] and policy.mode ~= S.c.MPOL_MODE['preferred']) then print("Warning: NUMA memory policy already in effect, but it's not --membind or --preferred.") else local node = S.getcpu().node local node_for_pci = choose_numa_node_for_pci_addresses(addrs) if node_for_pci and node ~= node_for_pci then print("Warning: Bound NUMA node does not have affinity with PCI devices.") end end end function unbind_cpu () local cpu_set = S.sched_getaffinity() cpu_set:zero() for i = 0, MAX_CPU do cpu_set:set(i) end assert(S.sched_setaffinity(0, cpu_set)) bound_cpu = nil end function bind_to_cpu (cpu) local function contains (t, e) for k,v in ipairs(t) do if tonumber(v) == tonumber(e) then return true end end return false end if not cpu then return unbind_cpu() end if cpu == bound_cpu then return end assert(not bound_cpu, "already bound") if type(cpu) ~= 'table' then cpu = {cpu} end assert(S.sched_setaffinity(0, cpu), ("Couldn't set affinity for cpuset %s"):format(table.concat(cpu, ','))) local cpu_and_node = S.getcpu() assert(contains(cpu, cpu_and_node.cpu)) bound_cpu = cpu_and_node.cpu bind_to_numa_node (cpu_and_node.node) end function unbind_numa_node () if supports_numa() then assert(S.set_mempolicy('default')) end bound_numa_node = nil end function bind_to_numa_node (node, policy) if node == bound_numa_node then return end if not node then return unbind_numa_node() end assert(not bound_numa_node, "already bound") if supports_numa() then assert(S.set_mempolicy(policy or 'preferred', node)) -- Migrate any pages that might have the wrong affinity. local from_mask = assert(S.get_mempolicy(nil, nil, nil, 'mems_allowed')).mask local ok, err = S.migrate_pages(0, from_mask, node) if not ok then io.stderr:write( string.format("Warning: Failed to migrate pages to NUMA node %d: %s\n", node, tostring(err))) end end bound_numa_node = node end function prevent_preemption(priority) assert(S.sched_setscheduler(0, "fifo", priority or 1), 'Failed to enable real-time scheduling. Try running as root.') end function selftest () function test_cpu(cpu) local node = cpu_get_numa_node(cpu) bind_to_cpu(cpu) assert(bound_cpu == cpu) assert(bound_numa_node == node) assert(S.getcpu().cpu == cpu) assert(S.getcpu().node == node) bind_to_cpu(nil) assert(bound_cpu == nil) assert(bound_numa_node == node) assert(S.getcpu().node == node) bind_to_numa_node(nil) assert(bound_cpu == nil) assert(bound_numa_node == nil) end function test_pci_affinity (pciaddr) check_affinity_for_pci_addresses({pciaddr}) local node = choose_numa_node_for_pci_addresses({pciaddr}, true) bind_to_numa_node(node) assert(bound_numa_node == node) check_affinity_for_pci_addresses({pciaddr}) bind_to_numa_node(nil) assert(bound_numa_node == nil) end print('selftest: numa') local cpu_set = S.sched_getaffinity() for cpuid = 0, MAX_CPU do if cpu_set:get(cpuid) then test_cpu(cpuid) end end local pciaddr = os.getenv("SNABB_PCI0") if pciaddr then test_pci_affinity(pciaddr) end print('selftest: numa: ok') end
Fix PCI affinity check for --preferred NUMA binding
Fix PCI affinity check for --preferred NUMA binding
Lua
apache-2.0
eugeneia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,snabbco/snabb,Igalia/snabb,Igalia/snabbswitch,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabb,snabbco/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,snabbco/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,SnabbCo/snabbswitch
5554375409ebdb65f9f2fda008bf69ebed5f93be
hammerspoon/init.lua
hammerspoon/init.lua
--- reload config hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() hs.reload() end) hs.alert.show("Config loaded") local v60hyper = {} local globalHyper = {"ctrl", "alt"} local primaryScreen = hs.screen.primaryScreen() local primaryScreenMenuBarOffset = primaryScreen:frame().y hs.loadSpoon("MiroWindowsManager") -- the notation here is confusing -- the numerator and denominator are revered. -- also be sure the grid size is divisible by the grid size _for height and width_. spoon.MiroWindowsManager.sizes = {12/7, 2, 12/5} hs.grid.MARGINX = 12 hs.grid.MARGINY = 12 -- setting animationDuration to not-zero makes iTerm/Terminal windows move all herky-jerky hs.window.animationDuration = 0.0 -- bindings for my custom-programmed keyboard spoon.MiroWindowsManager:bindHotkeys({ -- these keys are all mapped under layer 2 -- f14 is w/up-arrow up = {v60hyper, "f14"}, --pad+ is s/down-arrow down = {v60hyper, "pad+"}, -- pad- is a/left-arrow left = {v60hyper, "pad-"}, -- padenter is d/right-arrow right = {v60hyper, "padenter"}, -- pad1 is f fullscreen = {v60hyper,"pad1"} }) -- bindings for an Apple keyboard, like the built-in one on a laptop spoon.MiroWindowsManager:bindHotkeys({ up = {globalHyper, "up"}, down = {globalHyper, "down"}, left = {globalHyper, "left"}, right = {globalHyper, "right"}, fullscreen = {globalHyper, "f"} }) function stackWindows(win) -- find all windows in the app of the frontmost window -- make all the windows in the app the same size local f = win:frame() local app = win:application() local windows = app:allWindows() for i, window in ipairs(windows) do window:setFrame(f) end end hs.hotkey.bind(v60hyper, "f17", function() local win = hs.window.focusedWindow() stackWindows(win) end) maxFrame = { x = 0, y = primaryScreenMenuBarOffset, h = primaryScreen:frame().h, w = primaryScreen:frame().w, } -- on a 24x24 grid, these are {x, y, w, h} lowerRight = { 14.0, 10.0, 10.0, 14.0 } upperRight = { 14.0, 0.0, 10.0, 10.0 } halfLeft = { 0.0, 0.0, 14.0, 24.0 } local appPositions = { Atom = halfLeft, ['Google Chrome'] = halfLeft, ['IntelliJ IDEA'] = halfLeft, iTerm2 = upperRight, -- Messages = lowerRight, PyCharm = halfLeft, Slack = lowerRight, } hs.hotkey.bind(globalHyper, "k", function() -- print("setting up default window positions") -- print(appPositions.PyCharm.x) for appName, position in pairs(appPositions) do -- print("for ", appName) thisApp = hs.application.get(appName) if thisApp == nil then print("skipping nil app: ", appName) else for title, appWindow in pairs(thisApp:allWindows()) do print("the position for ", title, " is h/w/x/y", position.h, position.w, position.x, position.y) hs.grid.set(appWindow, position) end end end end) -- the 'pad=' key is under 'n' on layer 2 hs.hotkey.bind(v60hyper, "pad=", function() local win = hs.window.focusedWindow() local scr = win:screen() local nextScreen = scr:next() win:moveToScreen(scr:next()) if nextScreen:fullFrame().h * nextScreen:fullFrame().w < scr:fullFrame().h * scr:fullFrame().w then print(string.format("next screen area: %s", nextScreen:fullFrame().h * nextScreen:fullFrame().w)) print(string.format("this screen area: %s", scr:fullFrame().h * scr:fullFrame().w)) -- next screen is smaller; make it MiroWindowsManager's idea of full screen. spoon.MiroWindowsManager:_nextFullScreenStep() end end)
--- reload config hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() hs.reload() end) hs.alert.show("Config loaded") local v60hyper = {} local globalHyper = {"ctrl", "alt"} local primaryScreen = hs.screen.primaryScreen() local primaryScreenMenuBarOffset = primaryScreen:frame().y hs.loadSpoon("MiroWindowsManager") -- Since there is no way to pass arguments to a spoon, we have to (re-) set -- hs.grid and MiroWindowsManager.GRID to 12x12. The default grid of 24x24 _works_ -- but it looks like a remainder bug makes windows, particularly on small (laprop) screens, -- decrease in height every time they are re-sized; using a 12x12 grid avoids that bug. hs.grid.setGrid('12x12') spoon.MiroWindowsManager.GRID = {w = 12, h = 12} -- the notation here is confusing -- the numerator and denominator are reversed; -- also be sure the grid size is divisible by the grid size _for height and width_. spoon.MiroWindowsManager.sizes = {12/7, 2, 12/5} -- a margin of 8 seems to be small enough to avoid the aforementioned bug hs.grid.setMargins(hs.geometry.size({w=8, h=8})) -- setting animationDuration to not-zero makes iTerm/Terminal windows move all herky-jerky hs.window.animationDuration = 0.0 -- bindings for my custom-programmed keyboard spoon.MiroWindowsManager:bindHotkeys({ -- these keys are all mapped under layer 2 -- f14 is w/up-arrow up = {v60hyper, "f14"}, --pad+ is s/down-arrow down = {v60hyper, "pad+"}, -- pad- is a/left-arrow left = {v60hyper, "pad-"}, -- padenter is d/right-arrow right = {v60hyper, "padenter"}, -- pad1 is f fullscreen = {v60hyper,"pad1"} }) -- bindings for an Apple keyboard, like the built-in one on a laptop spoon.MiroWindowsManager:bindHotkeys({ up = {globalHyper, "up"}, down = {globalHyper, "down"}, left = {globalHyper, "left"}, right = {globalHyper, "right"}, fullscreen = {globalHyper, "f"} }) function stackWindows(win) -- find all windows in the app of the frontmost window -- make all the windows in the app the same size local f = win:frame() local app = win:application() local windows = app:allWindows() for i, window in ipairs(windows) do window:setFrame(f) end end hs.hotkey.bind(v60hyper, "f17", function() local win = hs.window.focusedWindow() stackWindows(win) end) maxFrame = { x = 0, y = primaryScreenMenuBarOffset, h = primaryScreen:frame().h, w = primaryScreen:frame().w, } -- on a 24x24 grid, these are {x, y, w, h} lowerRight = { 14.0, 10.0, 10.0, 14.0 } upperRight = { 14.0, 0.0, 10.0, 10.0 } halfLeft = { 0.0, 0.0, 14.0, 24.0 } local appPositions = { Atom = halfLeft, ['Google Chrome'] = halfLeft, ['IntelliJ IDEA'] = halfLeft, iTerm2 = upperRight, -- Messages = lowerRight, PyCharm = halfLeft, Slack = lowerRight, } hs.hotkey.bind(globalHyper, "k", function() -- print("setting up default window positions") -- print(appPositions.PyCharm.x) for appName, position in pairs(appPositions) do -- print("for ", appName) thisApp = hs.application.get(appName) if thisApp == nil then print("skipping nil app: ", appName) else for title, appWindow in pairs(thisApp:allWindows()) do print("the position for ", title, " is h/w/x/y", position.h, position.w, position.x, position.y) hs.grid.set(appWindow, position) end end end end) -- the 'pad=' key is under 'n' on layer 2 hs.hotkey.bind(v60hyper, "pad=", function() local win = hs.window.focusedWindow() local scr = win:screen() local nextScreen = scr:next() win:moveToScreen(scr:next()) if nextScreen:fullFrame().h * nextScreen:fullFrame().w < scr:fullFrame().h * scr:fullFrame().w then print(string.format("next screen area: %s", nextScreen:fullFrame().h * nextScreen:fullFrame().w)) print(string.format("this screen area: %s", scr:fullFrame().h * scr:fullFrame().w)) -- next screen is smaller; make it MiroWindowsManager's idea of full screen. spoon.MiroWindowsManager:_nextFullScreenStep() end end)
try to fix small screen/large margin bug
try to fix small screen/large margin bug
Lua
mit
paul-krohn/configs
95236ec1030e8946c1c36b0e8e2f1d67f04b6299
game/scripts/vscripts/items/item_book_of_the_guardian.lua
game/scripts/vscripts/items/item_book_of_the_guardian.lua
LinkLuaModifier("modifier_item_book_of_the_guardian", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_item_book_of_the_guardian_effect", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_item_book_of_the_guardian_blast", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE) item_book_of_the_guardian_baseclass = { GetIntrinsicModifierName = function() return "modifier_item_book_of_the_guardian" end } if IsServer() then function item_book_of_the_guardian_baseclass:OnSpellStart() local caster = self:GetCaster() local blast_radius = self:GetAbilitySpecial("blast_radius") local blast_speed = self:GetAbilitySpecial("blast_speed") local blast_damage_int_mult = self:GetSpecialValueFor("blast_damage_int_mult") local blast_debuff_duration = self:GetSpecialValueFor("blast_debuff_duration") local blast_vision_duration = self:GetSpecialValueFor("blast_vision_duration") local startTime = GameRules:GetGameTime() local affectedUnits = {} local pfx = ParticleManager:CreateParticle("particles/econ/events/ti7/shivas_guard_active_ti7.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster) ParticleManager:SetParticleControl(pfx, 1, Vector(blast_radius, blast_radius / blast_speed * 1.5, blast_speed)) caster:EmitSound("DOTA_Item.ShivasGuard.Activate") Timers:CreateTimer(function() local now = GameRules:GetGameTime() local elapsed = now - startTime local abs = caster:GetAbsOrigin() self:CreateVisibilityNode(abs, blast_radius, blast_vision_duration) for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), abs, nil, elapsed * blast_speed, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do if not affectedUnits[v] then affectedUnits[v] = true ApplyDamage({ attacker = caster, victim = v, damage = caster:GetIntellect() * blast_damage_int_mult, damage_type = self:GetAbilityDamageType(), damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION, ability = self }) local impact_pfx = ParticleManager:CreateParticle("particles/econ/events/ti7/shivas_guard_impact_ti7.vpcf", PATTACH_ABSORIGIN_FOLLOW, v) ParticleManager:SetParticleControlEnt(impact_pfx, 1, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), true) v:AddNewModifier(caster, self, "modifier_item_book_of_the_guardian_blast", {duration = blast_debuff_duration}) end end if elapsed * blast_speed < blast_radius then return 0.1 end end) end end item_book_of_the_guardian = class(item_book_of_the_guardian_baseclass) modifier_item_book_of_the_guardian = class({ IsHidden = function() return true end, IsAura = function() return true end, GetAttributes = function() return MODIFIER_ATTRIBUTE_MULTIPLE end, IsPurgable = function() return false end, }) function modifier_item_book_of_the_guardian:DeclareFunctions() return { MODIFIER_PROPERTY_STATS_INTELLECT_BONUS, MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT, MODIFIER_PROPERTY_MANA_REGEN_PERCENTAGE, MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE, MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE, } end function modifier_item_book_of_the_guardian:GetModifierBonusStats_Intellect() return self:GetAbility():GetSpecialValueFor("bonus_intellect") end function modifier_item_book_of_the_guardian:GetModifierConstantHealthRegen() return self:GetAbility():GetSpecialValueFor("bonus_health_regen") end function modifier_item_book_of_the_guardian:GetModifierPercentageManaRegen() return self:GetAbility():GetSpecialValueFor("bonus_mana_regen") end function modifier_item_book_of_the_guardian:GetModifierPreAttack_BonusDamage() return self:GetAbility():GetSpecialValueFor("bonus_damage") end function modifier_item_book_of_the_guardian:GetModifierSpellAmplify_Percentage() return self:GetAbility():GetSpecialValueFor("spell_amp_pct") end function modifier_item_book_of_the_guardian:GetModifierAura() return "modifier_item_book_of_the_guardian_aura" end function modifier_item_book_of_the_guardian:GetAuraRadius() return self:GetAbility():GetSpecialValueFor("aura_radius") end function modifier_item_book_of_the_guardian:GetAuraDuration() return 0.5 end function modifier_item_book_of_the_guardian:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_ENEMY end function modifier_item_book_of_the_guardian:GetAuraSearchType() return DOTA_UNIT_TARGET_HERO end modifier_item_book_of_the_guardian_aura = class({ IsPurgable = function() return false end, }) function modifier_item_book_of_the_guardian_aura:DeclareFunctions() return {MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT} end function modifier_item_book_of_the_guardian_aura:GetModifierAttackSpeedBonus_Constant() return self:GetAbility():GetSpecialValueFor("aura_attack_speed") end modifier_item_book_of_the_guardian_blast = class({ GetEffectName = function() return "particles/econ/events/ti7/shivas_guard_slow.vpcf" end, GetEffectAttachType = function() return PATTACH_ABSORIGIN_FOLLOW end, }) function modifier_item_book_of_the_guardian_blast:DeclareFunctions() return {MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE} end function modifier_item_book_of_the_guardian_blast:GetModifierMoveSpeedBonus_Percentage() return self:GetAbility():GetSpecialValueFor("blast_movement_speed_pct") end
LinkLuaModifier("modifier_item_book_of_the_guardian", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_item_book_of_the_guardian_effect", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_item_book_of_the_guardian_blast", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE) item_book_of_the_guardian_baseclass = { GetIntrinsicModifierName = function() return "modifier_item_book_of_the_guardian" end } if IsServer() then function item_book_of_the_guardian_baseclass:OnSpellStart() local caster = self:GetCaster() local blast_radius = self:GetAbilitySpecial("blast_radius") local blast_speed = self:GetAbilitySpecial("blast_speed") local blast_damage_int_mult = self:GetSpecialValueFor("blast_damage_int_mult") local blast_debuff_duration = self:GetSpecialValueFor("blast_debuff_duration") local blast_vision_duration = self:GetSpecialValueFor("blast_vision_duration") local startTime = GameRules:GetGameTime() local affectedUnits = {} local pfx = ParticleManager:CreateParticle("particles/econ/events/ti7/shivas_guard_active_ti7.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster) ParticleManager:SetParticleControl(pfx, 1, Vector(blast_radius, blast_radius / blast_speed * 1.5, blast_speed)) caster:EmitSound("DOTA_Item.ShivasGuard.Activate") Timers:CreateTimer(function() local now = GameRules:GetGameTime() local elapsed = now - startTime local abs = caster:GetAbsOrigin() self:CreateVisibilityNode(abs, blast_radius, blast_vision_duration) for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), abs, nil, elapsed * blast_speed, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do if not affectedUnits[v] then affectedUnits[v] = true ApplyDamage({ attacker = caster, victim = v, damage = caster:GetIntellect() * blast_damage_int_mult, damage_type = self:GetAbilityDamageType(), damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION, ability = self }) local impact_pfx = ParticleManager:CreateParticle("particles/econ/events/ti7/shivas_guard_impact_ti7.vpcf", PATTACH_ABSORIGIN_FOLLOW, v) ParticleManager:SetParticleControlEnt(impact_pfx, 1, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), true) v:AddNewModifier(caster, self, "modifier_item_book_of_the_guardian_blast", {duration = blast_debuff_duration}) end end if elapsed * blast_speed < blast_radius then return 0.1 end end) end end item_book_of_the_guardian = class(item_book_of_the_guardian_baseclass) modifier_item_book_of_the_guardian = class({ IsHidden = function() return true end, IsAura = function() return true end, GetAttributes = function() return MODIFIER_ATTRIBUTE_MULTIPLE end, IsPurgable = function() return false end, }) function modifier_item_book_of_the_guardian:DeclareFunctions() return { MODIFIER_PROPERTY_STATS_INTELLECT_BONUS, MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT, MODIFIER_PROPERTY_MANA_REGEN_PERCENTAGE, MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE, MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS, MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE, } end function modifier_item_book_of_the_guardian:GetModifierBonusStats_Intellect() return self:GetAbility():GetSpecialValueFor("bonus_intellect") end function modifier_item_book_of_the_guardian:GetModifierConstantHealthRegen() return self:GetAbility():GetSpecialValueFor("bonus_health_regen") end function modifier_item_book_of_the_guardian:GetModifierPercentageManaRegen() return self:GetAbility():GetSpecialValueFor("bonus_mana_regen") end function modifier_item_book_of_the_guardian:GetModifierPreAttack_BonusDamage() return self:GetAbility():GetSpecialValueFor("bonus_damage") end function modifier_item_book_of_the_guardian:GetModifierPhysicalArmorBonus() return self:GetAbility():GetSpecialValueFor("bonus_armor") end function modifier_item_book_of_the_guardian:GetModifierSpellAmplify_Percentage() return self:GetAbility():GetSpecialValueFor("spell_amp_pct") end function modifier_item_book_of_the_guardian:GetModifierAura() return "modifier_item_book_of_the_guardian_aura" end function modifier_item_book_of_the_guardian:GetAuraRadius() return self:GetAbility():GetSpecialValueFor("aura_radius") end function modifier_item_book_of_the_guardian:GetAuraDuration() return 0.5 end function modifier_item_book_of_the_guardian:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_ENEMY end function modifier_item_book_of_the_guardian:GetAuraSearchType() return DOTA_UNIT_TARGET_HERO end modifier_item_book_of_the_guardian_aura = class({ IsPurgable = function() return false end, }) function modifier_item_book_of_the_guardian_aura:DeclareFunctions() return {MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT} end function modifier_item_book_of_the_guardian_aura:GetModifierAttackSpeedBonus_Constant() return self:GetAbility():GetSpecialValueFor("aura_attack_speed") end modifier_item_book_of_the_guardian_blast = class({ GetEffectName = function() return "particles/econ/events/ti7/shivas_guard_slow.vpcf" end, GetEffectAttachType = function() return PATTACH_ABSORIGIN_FOLLOW end, }) function modifier_item_book_of_the_guardian_blast:DeclareFunctions() return {MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE} end function modifier_item_book_of_the_guardian_blast:GetModifierMoveSpeedBonus_Percentage() return self:GetAbility():GetSpecialValueFor("blast_movement_speed_pct") end
Fixed Book of the Guardian didn't increased attack damage
Fixed Book of the Guardian didn't increased attack damage
Lua
mit
ark120202/aabs
6d4985118ffdf78ea20f8bbb6174ea7c9c157ceb
src/romdisk/system/lib/boot.lua
src/romdisk/system/lib/boot.lua
package.path = "/romdisk/system/lib/?.lua;/romdisk/system/lib/?/init.lua;" .. package.path package.cpath = "/romdisk/system/lib/?.so;/romdisk/system/lib/loadall.so;" .. package.cpath print = require("org.xboot.buildin.logger").print local function loader() require("main") end local function handler(msg, layer) print((debug.traceback("ERROR: " .. tostring(msg), 1 + (layer or 1)):gsub("\n[^\n]+$", ""))) end return function() local res, ret = xpcall(loader, handler) if not res then return -1 end return tonumber(ret) or -1 end
package.path = "/romdisk/system/lib/?.lua;/romdisk/system/lib/?/init.lua;./?.lua" package.cpath = "/romdisk/system/lib/?.so;/romdisk/system/lib/loadall.so;./?.so" print = require("org.xboot.buildin.logger").print local function loader() require("main") end local function handler(msg, layer) print((debug.traceback("ERROR: " .. tostring(msg), 1 + (layer or 1)):gsub("\n[^\n]+$", ""))) end return function() local res, ret = xpcall(loader, handler) if not res then return -1 end return tonumber(ret) or -1 end
fix boot.lua
fix boot.lua
Lua
mit
xboot/xboot,xboot/xboot
47984efec93841c3979c4847ace1e592250ce1a4
aspects/nvim/files/.config/nvim/plugin/mappings/normal.lua
aspects/nvim/files/.config/nvim/plugin/mappings/normal.lua
-- -- Normal mode mappings. -- local nnoremap = wincent.vim.nnoremap local noremap = wincent.vim.noremap -- Toggle fold at current position. nnoremap('<Tab>', 'za') -- Relying on Karabiner-Elements (macOS) or Interception Tools (Linux) to avoid -- collision between <Tab> and <C-i> (have it send F6 instead for <C-i>). nnoremap('<F6>', '<C-i>') -- Avoid unintentional switches to Ex mode. nnoremap('Q', '<Nop>') -- Note this one is multi-mode mappings (Normal, Visual, Operating-pending modes). noremap('Y', 'y$') nnoremap('<C-h>', '<C-w>h') nnoremap('<C-j>', '<C-w>j') nnoremap('<C-k>', '<C-w>k') nnoremap('<C-l>', '<C-w>l') -- Repurpose cursor keys (accessible near homerow via "SpaceFN" layout) for one -- of my most oft-use key sequences. nnoremap('<Up>', ':cprevious<CR>', {silent = true}) nnoremap('<Down>', ':cnext<CR>', {silent = true}) nnoremap('<Left>', ':cpfile<CR>', {silent = true}) nnoremap('<Right>', ':cnfile<CR>', {silent = true}) nnoremap('<S-Up>', ':lprevious<CR>', {silent = true}) nnoremap('<S-Down>', ':lnext<CR>', {silent = true}) nnoremap('<S-Left>', ':lpfile<CR>', {silent = true}) nnoremap('<S-Right>', ':lnfile<CR>', {silent = true}) -- Store relative line number jumps in the jumplist if they exceed a threshold. nnoremap('k', function () return (vim.v.count > 5 and "m'" .. vim.v.count or '') .. 'k' end, {expr = true}) nnoremap('j', function () return (vim.v.count > 5 and "m'" .. vim.v.count or '') .. 'j' end, {expr = true})
-- -- Normal mode mappings. -- local nnoremap = wincent.vim.nnoremap local noremap = wincent.vim.noremap -- Wrap all mappings related to folding so that indent-blankline.nvim can -- update when folds are changed. See: -- https://github.com/lukas-reineke/indent-blankline.nvim/issues/118 local fold = function(mapping) if vim.g.loaded_indent_blankline == 1 then return mapping .. ':IndentBlanklineRefresh<CR>' else return mapping end end -- Toggle fold at current position. nnoremap('<Tab>', fold('za'), {silent = true}) -- Other fold-related remaps for compatibility with indent-blankline.nvim: nnoremap('zA', fold('zA'), {silent = true}) nnoremap('zC', fold('zC'), {silent = true}) nnoremap('zM', fold('zM'), {silent = true}) nnoremap('zO', fold('zO'), {silent = true}) nnoremap('zR', fold('zR'), {silent = true}) nnoremap('zX', fold('zX'), {silent = true}) nnoremap('za', fold('za'), {silent = true}) nnoremap('zc', fold('zc'), {silent = true}) nnoremap('zm', fold('zm'), {silent = true}) nnoremap('zo', fold('zo'), {silent = true}) nnoremap('zr', fold('zr'), {silent = true}) nnoremap('zv', fold('zv'), {silent = true}) nnoremap('zx', fold('zx'), {silent = true}) -- Relying on Karabiner-Elements (macOS) or Interception Tools (Linux) to avoid -- collision between <Tab> and <C-i> (have it send F6 instead for <C-i>). nnoremap('<F6>', '<C-i>') -- Avoid unintentional switches to Ex mode. nnoremap('Q', '<Nop>') -- Note this one is multi-mode mappings (Normal, Visual, Operating-pending modes). noremap('Y', 'y$') nnoremap('<C-h>', '<C-w>h') nnoremap('<C-j>', '<C-w>j') nnoremap('<C-k>', '<C-w>k') nnoremap('<C-l>', '<C-w>l') -- Repurpose cursor keys (accessible near homerow via "SpaceFN" layout) for one -- of my most oft-use key sequences. nnoremap('<Up>', ':cprevious<CR>', {silent = true}) nnoremap('<Down>', ':cnext<CR>', {silent = true}) nnoremap('<Left>', ':cpfile<CR>', {silent = true}) nnoremap('<Right>', ':cnfile<CR>', {silent = true}) nnoremap('<S-Up>', ':lprevious<CR>', {silent = true}) nnoremap('<S-Down>', ':lnext<CR>', {silent = true}) nnoremap('<S-Left>', ':lpfile<CR>', {silent = true}) nnoremap('<S-Right>', ':lnfile<CR>', {silent = true}) -- Store relative line number jumps in the jumplist if they exceed a threshold. nnoremap('k', function () return (vim.v.count > 5 and "m'" .. vim.v.count or '') .. 'k' end, {expr = true}) nnoremap('j', function () return (vim.v.count > 5 and "m'" .. vim.v.count or '') .. 'j' end, {expr = true})
fix(nvim): make indent-blankline.nvim play nicely with fold markers
fix(nvim): make indent-blankline.nvim play nicely with fold markers Otherwise, it ends up overwriting the left side of the marker. I did think about indenting the markers (from my `foldtext` function), but I think this is going to look better.
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
37d7737297d31b6c85877e73b0d343be12997ce2
SVUI_!Core/libs/LibReputationData-1.0/LibReputationData-1.0.lua
SVUI_!Core/libs/LibReputationData-1.0/LibReputationData-1.0.lua
local MAJOR, MINOR = "LibReputationData-1.0", 1 assert(_G.LibStub, MAJOR .. " requires LibStub") local lib = _G.LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end lib.callbacks = lib.callbacks or _G.LibStub("CallbackHandler-1.0"):New(lib) -- local store local reputationChanges = {} local allFactions = {} local watchedFaction = 0 -- blizzard api local GetFactionInfo = _G.GetFactionInfo local GetFriendshipReputation = _G.GetFriendshipReputation local IsFactionInactive = _G.IsFactionInactive local SetWatchedFactionIndex = _G.SetWatchedFactionIndex local TimerAfter = _G.C_Timer.After -- lua api local select = _G.select local strmatch = _G.string.match local tonumber = _G.tonumber local private = {} -- private space for the event handlers lib.frame = lib.frame or _G.CreateFrame("Frame") local frame = lib.frame frame:UnregisterAllEvents() -- deactivate old versions frame:SetScript("OnEvent", function(_, event, ...) private[event](event, ...) end) frame:RegisterEvent("PLAYER_ENTERING_WORLD") local function CopyTable(tbl) if not tbl then return {} end local copy = {}; for k, v in pairs(tbl) do if ( type(v) == "table" ) then copy[k] = CopyTable(v); else copy[k] = v; end end return copy; end local function GetFLocalFactionInfo(factionIndex) return allFactions[factionIndex] end local function GetFactionIndex(factionName) for i = 1, #allFactions do local name, _, _, _, _, _, _, _, _, _, _, _, _ = GetFLocalFactionInfo(i); if name == factionName then return i end end end local function GetFactionData(factionIndex) local name, _, standingID, bottomValue, topValue, earnedValue, _, _, isHeader, isCollapsed, hasRep, isWatched, isChild, factionID = GetFactionInfo(factionIndex) if not name then return nil end if isWatched then watchedFaction = factionIndex end local standingText = _G['FACTION_STANDING_LABEL'..standingID] local friendID, friendRep, friendMaxRep, _, _, _, friendTextLevel, friendThresh = GetFriendshipReputation(factionID) if friendID ~= nil then bottomValue = friendThresh if nextThresh then topValue = friendThresh + min( friendMaxRep - friendThresh, 8400 ) -- Magic number! Yay! end earnedValue = friendRep standingText = friendTextLevel end local faction = { factionIndex = factionIndex, name = name, standingID = standingID, standing = standingText, min = bottomValue, max = topValue, value = earnedValue, isHeader = isHeader, isChild = isChild, hasRep = hasRep, isActive = not IsFactionInactive(factionIndex), factionID = factionID, friendID = friendID } return faction end -- Refresh the list of known factions local function RefreshAllFactions() local i = 1 local lastName local factions = {} repeat local name, description, standingId, bottomValue, topValue, earnedValue, atWarWith, canToggleAtWar, isHeader, isCollapsed, hasRep, isWatched, isChild, factionID = GetFactionInfo(i) if not name or name == lastName and name ~= GUILD then break end lastName = name local faction = GetFactionData(i) if faction then tinsert(factions, faction) end if isCollapsed then ExpandFactionHeader(i) end i = i + 1 until i > 200 allFactions = factions lib.callbacks:Fire("FACTIONS_LOADED") end local function UpdateFaction(factionIndex) allFactions[factionIndex] = GetFactionData(factionIndex) end ------------------------------------------------------------------------------ -- Ensure factions and guild info are loaded ------------------------------------------------------------------------------ local function EnsureFactionsLoaded() -- Sometimes it takes a while for faction and guild info -- to load when the game boots up so we need to periodically -- check whether its loaded before we can display it if GetFactionInfo(1) == nil or (IsInGuild() and GetGuildInfo("player") == nil) then TimerAfter(0.5, EnsureFactionsLoaded) else -- Refresh all factions and notify subscribers RefreshAllFactions() end end ------------------------------------------------------------------------------ -- Update reputation ------------------------------------------------------------------------------ local function UpdateReputationChanges() RefreshAllFactions() -- Build sorted change table local changes = {} for name, amount in pairs(reputationChanges) do local factionIndex= GetFactionIndex(name) if factionIndex then UpdateFaction(factionIndex) tinsert(changes, { name = name, amount = amount, factionIndex = factionIndex }) end end if #changes > 1 then table.sort(changes, function(a, b) return a.amount > b.amount end) end if #changes > 0 then -- Notify subscribers InformReputationsChanged(changes) end reputationChanges = {} end local function InformReputationsChanged(changes) for _,_,factionIndex in changes do lib.callbacks:Fire("REPUTATION_CHANGED", factionIndex) end end ------------------------------------------------------------------------------ -- Events ------------------------------------------------------------------------------ function private.PLAYER_ENTERING_WORLD(event) TimerAfter(3, function() frame:RegisterEvent("COMBAT_TEXT_UPDATE") frame:RegisterEvent("UPDATE_FACTION") EnsureFactionsLoaded() end) end function private.COMBAT_TEXT_UPDATE(event, type, name, amount) if (type == "FACTION") then if IsInGuild() then -- Check name for guild reputation if name == GUILD then name = (GetGuildInfo("player")) if not name or name == "" then return end end end if not reputationChanges[name] then reputationChanges[name] = amount else reputationChanges[name] = reputationChanges[name] + amount end TimerAfter(0.5,UpdateReputationChanges) end end function private.UPDATE_FACTION(event) RefreshAllFactions() end ------------------------------------------------------------------------------ -- API ------------------------------------------------------------------------------ function lib:SetWatchedFaction(factionIndex) SetWatchedFactionIndex(factionIndex) watchedFaction = factionIndex lib.callbacks:Fire("REPUTATION_CHANGED", factionIndex) end function lib:GetWatchedFactionIndex() return watchedFaction end function lib:GetReputationInfo(_, factionIndex) factionIndex = factionIndex or watchedFaction if allFactions[factionIndex] then return factionIndex, CopyTable(allFactions[factionIndex]) else return nil,nil end end function lib:GetAllFactionsInfo() return CopyTable(allFactions) end function lib:GetAllActiveFactionsInfo() local activeFactions = {} for i=1,#allFactions do if allFactions[i].isActive then tinsert(activeFactions,allFactions[i]) end end if #activeFactions > 0 then return CopyTable(activeFactions) else return nil end end function lib:GetNumObtainedReputations() return #allFactions end function lib:ForceUpdate() EnsureFactionsLoaded() end
local MAJOR, MINOR = "LibReputationData-1.0", 1 assert(_G.LibStub, MAJOR .. " requires LibStub") local lib = _G.LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end lib.callbacks = lib.callbacks or _G.LibStub("CallbackHandler-1.0"):New(lib) -- local store local reputationChanges = {} local allFactions = {} local watchedFaction = 0 -- blizzard api local GetFactionInfo = _G.GetFactionInfo local GetFriendshipReputation = _G.GetFriendshipReputation local IsFactionInactive = _G.IsFactionInactive local SetWatchedFactionIndex = _G.SetWatchedFactionIndex local TimerAfter = _G.C_Timer.After -- lua api local select = _G.select local strmatch = _G.string.match local tonumber = _G.tonumber local private = {} -- private space for the event handlers lib.frame = lib.frame or _G.CreateFrame("Frame") local frame = lib.frame frame:UnregisterAllEvents() -- deactivate old versions frame:SetScript("OnEvent", function(_, event, ...) private[event](event, ...) end) frame:RegisterEvent("PLAYER_ENTERING_WORLD") local function CopyTable(tbl) if not tbl then return {} end local copy = {}; for k, v in pairs(tbl) do if ( type(v) == "table" ) then copy[k] = CopyTable(v); else copy[k] = v; end end return copy; end local function GetFLocalFactionInfo(factionIndex) return allFactions[factionIndex] end local function GetFactionIndex(factionName) for i = 1, #allFactions do local name, _, _, _, _, _, _, _, _, _, _, _, _ = GetFLocalFactionInfo(i); if name == factionName then return i end end end local function GetFactionData(factionIndex) local name, _, standingID, bottomValue, topValue, earnedValue, _, _, isHeader, isCollapsed, hasRep, isWatched, isChild, factionID = GetFactionInfo(factionIndex) if not name then return nil end if isWatched then watchedFaction = factionIndex end local standingText = _G['FACTION_STANDING_LABEL'..standingID] local friendID, friendRep, friendMaxRep, _, _, _, friendTextLevel, friendThresh = GetFriendshipReputation(factionID) if friendID ~= nil then bottomValue = friendThresh if nextThresh then topValue = friendThresh + min( friendMaxRep - friendThresh, 8400 ) -- Magic number! Yay! end earnedValue = friendRep standingText = friendTextLevel end local faction = { factionIndex = factionIndex, name = name, standingID = standingID, standing = standingText, min = bottomValue, max = topValue, value = earnedValue, isHeader = isHeader, isChild = isChild, hasRep = hasRep, isActive = not IsFactionInactive(factionIndex), factionID = factionID, friendID = friendID } return faction end -- Refresh the list of known factions local function RefreshAllFactions() local i = 1 local lastName local factions = {} repeat local name, description, standingId, bottomValue, topValue, earnedValue, atWarWith, canToggleAtWar, isHeader, isCollapsed, hasRep, isWatched, isChild, factionID = GetFactionInfo(i) if not name or name == lastName and name ~= GUILD then break end lastName = name local faction = GetFactionData(i) if faction then tinsert(factions, faction) end if isCollapsed then ExpandFactionHeader(i) end i = i + 1 until i > 200 allFactions = factions lib.callbacks:Fire("FACTIONS_LOADED") end local function UpdateFaction(factionIndex) allFactions[factionIndex] = GetFactionData(factionIndex) end ------------------------------------------------------------------------------ -- Ensure factions and guild info are loaded ------------------------------------------------------------------------------ local function EnsureFactionsLoaded() -- Sometimes it takes a while for faction and guild info -- to load when the game boots up so we need to periodically -- check whether its loaded before we can display it if GetFactionInfo(1) == nil or (IsInGuild() and GetGuildInfo("player") == nil) then TimerAfter(0.5, EnsureFactionsLoaded) else -- Refresh all factions and notify subscribers RefreshAllFactions() end end ------------------------------------------------------------------------------ -- Update reputation ------------------------------------------------------------------------------ local function UpdateReputationChanges() RefreshAllFactions() -- Build sorted change table local changes = {} for name, amount in pairs(reputationChanges) do local factionIndex= GetFactionIndex(name) if factionIndex then UpdateFaction(factionIndex) tinsert(changes, { name = name, amount = amount, factionIndex = factionIndex }) end end if #changes > 1 then table.sort(changes, function(a, b) return a.amount > b.amount end) end if #changes > 0 then -- Notify subscribers InformReputationsChanged(changes) end reputationChanges = {} end local function InformReputationsChanged(changes) for _,_,factionIndex in changes do lib.callbacks:Fire("REPUTATION_CHANGED", factionIndex) end end ------------------------------------------------------------------------------ -- Events ------------------------------------------------------------------------------ function private.PLAYER_ENTERING_WORLD(event) TimerAfter(3, function() frame:RegisterEvent("COMBAT_TEXT_UPDATE") EnsureFactionsLoaded() end) end function private.COMBAT_TEXT_UPDATE(event, type, name, amount) if (type == "FACTION") then if IsInGuild() then -- Check name for guild reputation if name == GUILD then name = (GetGuildInfo("player")) if not name or name == "" then return end end end if not reputationChanges[name] then reputationChanges[name] = amount else reputationChanges[name] = reputationChanges[name] + amount end TimerAfter(0.5,UpdateReputationChanges) end end function private.UPDATE_FACTION(event) RefreshAllFactions() end ------------------------------------------------------------------------------ -- API ------------------------------------------------------------------------------ function lib:SetWatchedFaction(factionIndex) SetWatchedFactionIndex(factionIndex) watchedFaction = factionIndex lib.callbacks:Fire("REPUTATION_CHANGED", factionIndex) end function lib:GetWatchedFactionIndex() return watchedFaction end function lib:GetReputationInfo(_, factionIndex) factionIndex = factionIndex or watchedFaction if allFactions[factionIndex] then return factionIndex, CopyTable(allFactions[factionIndex]) else return nil,nil end end function lib:GetAllFactionsInfo() return CopyTable(allFactions) end function lib:GetAllActiveFactionsInfo() local activeFactions = {} for i=1,#allFactions do if allFactions[i].isActive then tinsert(activeFactions,allFactions[i]) end end if #activeFactions > 0 then return CopyTable(activeFactions) else return nil end end function lib:GetNumObtainedReputations() return #allFactions end function lib:ForceUpdate() EnsureFactionsLoaded() end
Updated LibReputationData to fix #10
Updated LibReputationData to fix #10 Fix for #10 where Rep panel faction groupings couldn't be collapsed.
Lua
mit
finalsliver/supervillain-ui,FailcoderAddons/supervillain-ui
a14cdd5c75c13b2b09d80356e08c91734513942d
feedback/perplexity.lua
feedback/perplexity.lua
------------------------------------------------------------------------ --[[ Perplexity ]]-- -- Feedback -- Computes perplexity for language models -- For now, only works with SoftmaxTree ------------------------------------------------------------------------ local Perplexity, parent = torch.class("dp.Perplexity", "dp.Feedback") Perplexity.isPerplexity = true function Perplexity:__init(config) config = config or {} assert(torch.type(config) == 'table' and not config[1], "Constructor requires key-value arguments") local args, name = xlua.unpack( {config}, 'Perplexity', 'Computes perplexity for language models', {arg='name', type='string', default='perplexity', help='name identifying Feedback in reports'} ) config.name = name parent.__init(self, config) self._nll = 0 end function Perplexity:setup(config) parent.setup(self, config) self._mediator:subscribe("doneEpoch", self, "doneEpoch") end function Perplexity:perplexity() -- exponential of the mean NLL return math.exp(self._nll / self._n_sample) end function Perplexity:doneEpoch(report) if self._n_sample > 0 and self._verbose then print(self._id:toString().." perplexity = "..self:perplexity()) end end function Perplexity:add(batch, output, report) assert(torch.isTypeOf(batch, 'dp.Batch'), "First argument should be dp.Batch") -- table outputs are expected of recurrent neural networks if torch.type(output) == 'table' then -- targets aren't a table local targets = batch:targets():forward('bt') self._n_sample = self._n_sample + (batch:nSample()*targets:size(1)) assert(batch:nSample() == targets:size(1)) local sum = 0 for i=1,#output do local target = targets:select(2,i) local act = output[i] if torch.type(act) ~= torch.FloatTensor() then self._act = self._act or torch.FloatTensor() self._act:resize(act:size()):copy(act) act = self._act end if act:dim() == 2 then -- assume output originates from LogSoftMax for i=1,target:size(1) do sum = sum + act[i][target[i]] end else -- assume output originates from SoftMaxTree sum = sum + act:view(-1):sum() end end -- divide by number of elements in sequence self._nll = self._nll - sum else self._n_sample = self._n_sample + batch:nSample() local act = output if torch.type(act) ~= torch.FloatTensor() then self._act = self._act or torch.FloatTensor() self._act:resize(act:size()):copy(act) act = self._act end if output:dim() == 2 then -- assume output originates from LogSoftMax local targets = batch:targets():forward('b') local sum = 0 for i=1,targets:size(1) do sum = sum + act[i][targets[i]] end self._nll = self._nll - sum else -- assume output originates from SoftMaxTree -- accumulate the sum of negative log likelihoods self._nll = self._nll - act:view(-1):sum() end end end function Perplexity:_reset() self._nll = 0 end function Perplexity:report() return { [self:name()] = { perplexity = self._n_sample > 0 and self:perplexity() or 0 }, n_sample = self._n_sample } end
------------------------------------------------------------------------ --[[ Perplexity ]]-- -- Feedback -- Computes perplexity for language models -- For now, only works with SoftmaxTree ------------------------------------------------------------------------ local Perplexity, parent = torch.class("dp.Perplexity", "dp.Feedback") Perplexity.isPerplexity = true function Perplexity:__init(config) config = config or {} assert(torch.type(config) == 'table' and not config[1], "Constructor requires key-value arguments") local args, name = xlua.unpack( {config}, 'Perplexity', 'Computes perplexity for language models', {arg='name', type='string', default='perplexity', help='name identifying Feedback in reports'} ) config.name = name parent.__init(self, config) self._nll = 0 end function Perplexity:setup(config) parent.setup(self, config) self._mediator:subscribe("doneEpoch", self, "doneEpoch") end function Perplexity:perplexity() -- exponential of the mean NLL return math.exp(self._nll / self._n_sample) end function Perplexity:doneEpoch(report) if self._n_sample > 0 and self._verbose then print(self._id:toString().." perplexity = "..self:perplexity()) end end function Perplexity:add(batch, output, report) assert(torch.isTypeOf(batch, 'dp.Batch'), "First argument should be dp.Batch") -- table outputs are expected of recurrent neural networks if torch.type(output) == 'table' then -- targets aren't a table local targets = batch:targets():forward('bt') self._n_sample = self._n_sample + targets:nElement() local sum = 0 for i=1,#output do local target = targets:select(2,i) local act = output[i] if torch.type(act) ~= torch.FloatTensor() then self._act = self._act or torch.FloatTensor() self._act:resize(act:size()):copy(act) act = self._act end if act:dim() == 2 then -- assume output originates from LogSoftMax for i=1,target:size(1) do sum = sum + act[i][target[i]] end else -- assume output originates from SoftMaxTree sum = sum + act:view(-1):sum() end end -- divide by number of elements in sequence self._nll = self._nll - sum else self._n_sample = self._n_sample + batch:nSample() local act = output if torch.type(act) ~= torch.FloatTensor() then self._act = self._act or torch.FloatTensor() self._act:resize(act:size()):copy(act) act = self._act end if output:dim() == 2 then -- assume output originates from LogSoftMax local targets = batch:targets():forward('b') local sum = 0 for i=1,targets:size(1) do sum = sum + act[i][targets[i]] end self._nll = self._nll - sum else -- assume output originates from SoftMaxTree -- accumulate the sum of negative log likelihoods self._nll = self._nll - act:view(-1):sum() end end end function Perplexity:_reset() self._nll = 0 end function Perplexity:report() return { [self:name()] = { perplexity = self._n_sample > 0 and self:perplexity() or 0 }, n_sample = self._n_sample } end
fix Perplexity for recurrent nets
fix Perplexity for recurrent nets
Lua
bsd-3-clause
nicholas-leonard/dp,sagarwaghmare69/dp,kracwarlock/dp,jnhwkim/dp,eulerreich/dp
68ec350388b2b52edb74cca13e0715bb35211343
rootfs/etc/nginx/lua/monitor.lua
rootfs/etc/nginx/lua/monitor.lua
local ngx = ngx local tonumber = tonumber local assert = assert local string = string local tostring = tostring local socket = ngx.socket.tcp local cjson = require("cjson.safe") local new_tab = require "table.new" local clear_tab = require "table.clear" local clone_tab = require "table.clone" -- if an Nginx worker processes more than (MAX_BATCH_SIZE/FLUSH_INTERVAL) RPS -- then it will start dropping metrics local MAX_BATCH_SIZE = 10000 local FLUSH_INTERVAL = 1 -- second local metrics_batch = new_tab(MAX_BATCH_SIZE, 0) local metrics_count = 0 local _M = {} local function send(payload) local s = assert(socket()) assert(s:connect("unix:/tmp/prometheus-nginx.socket")) assert(s:send(payload)) assert(s:close()) end local function metrics() return { host = ngx.var.host or "-", namespace = ngx.var.namespace or "-", ingress = ngx.var.ingress_name or "-", service = ngx.var.service_name or "-", path = ngx.var.location_path or "-", method = ngx.var.request_method or "-", status = ngx.var.status or "-", requestLength = tonumber(ngx.var.request_length) or -1, requestTime = tonumber(ngx.var.request_time) or -1, responseLength = tonumber(ngx.var.bytes_sent) or -1, upstreamLatency = tonumber(ngx.var.upstream_connect_time) or -1, upstreamResponseTime = tonumber(ngx.var.upstream_response_time) or -1, upstreamResponseLength = tonumber(ngx.var.upstream_response_length) or -1, --upstreamStatus = ngx.var.upstream_status or "-", } end local function flush(premature) if premature then return end if metrics_count == 0 then return end local current_metrics_batch = clone_tab(metrics_batch) clear_tab(metrics_batch) metrics_count = 0 local payload, err = cjson.encode(current_metrics_batch) if not payload then ngx.log(ngx.ERR, "error while encoding metrics: ", err) return end send(payload) end local function set_metrics_max_batch_size(max_batch_size) if max_batch_size > 10000 then MAX_BATCH_SIZE = max_batch_size end end function _M.init_worker(max_batch_size) set_metrics_max_batch_size(max_batch_size) local _, err = ngx.timer.every(FLUSH_INTERVAL, flush) if err then ngx.log(ngx.ERR, string.format("error when setting up timer.every: %s", tostring(err))) end end function _M.call() if metrics_count >= MAX_BATCH_SIZE then ngx.log(ngx.WARN, "omitting metrics for the request, current batch is full") return end metrics_count = metrics_count + 1 metrics_batch[metrics_count] = metrics() end setmetatable(_M, {__index = { flush = flush, set_metrics_max_batch_size = set_metrics_max_batch_size, get_metrics_batch = function() return metrics_batch end, }}) return _M
local ngx = ngx local tonumber = tonumber local assert = assert local string = string local tostring = tostring local socket = ngx.socket.tcp local cjson = require("cjson.safe") local new_tab = require "table.new" local clear_tab = require "table.clear" local table = table local pairs = pairs -- if an Nginx worker processes more than (MAX_BATCH_SIZE/FLUSH_INTERVAL) RPS -- then it will start dropping metrics local MAX_BATCH_SIZE = 10000 local FLUSH_INTERVAL = 1 -- second local metrics_batch = new_tab(MAX_BATCH_SIZE, 0) local metrics_count = 0 -- for save json raw metrics table local metrics_raw_batch = new_tab(MAX_BATCH_SIZE, 0) local _M = {} local function send(payload) local s = assert(socket()) assert(s:connect("unix:/tmp/prometheus-nginx.socket")) assert(s:send(payload)) assert(s:close()) end local function metrics() return { host = ngx.var.host or "-", namespace = ngx.var.namespace or "-", ingress = ngx.var.ingress_name or "-", service = ngx.var.service_name or "-", path = ngx.var.location_path or "-", method = ngx.var.request_method or "-", status = ngx.var.status or "-", requestLength = tonumber(ngx.var.request_length) or -1, requestTime = tonumber(ngx.var.request_time) or -1, responseLength = tonumber(ngx.var.bytes_sent) or -1, upstreamLatency = tonumber(ngx.var.upstream_connect_time) or -1, upstreamResponseTime = tonumber(ngx.var.upstream_response_time) or -1, upstreamResponseLength = tonumber(ngx.var.upstream_response_length) or -1, --upstreamStatus = ngx.var.upstream_status or "-", } end local function flush(premature) if premature then return end if metrics_count == 0 then return end metrics_count = 0 clear_tab(metrics_batch) local request_metrics = {} table.insert(request_metrics, "[") for i in pairs(metrics_raw_batch) do local item = metrics_raw_batch[i] .."," if i == table.getn(metrics_raw_batch) then item = metrics_raw_batch[i] end table.insert(request_metrics, item) end table.insert(request_metrics, "]") local payload = table.concat(request_metrics) clear_tab(metrics_raw_batch) send(payload) end local function set_metrics_max_batch_size(max_batch_size) if max_batch_size > 10000 then MAX_BATCH_SIZE = max_batch_size end end function _M.init_worker(max_batch_size) set_metrics_max_batch_size(max_batch_size) local _, err = ngx.timer.every(FLUSH_INTERVAL, flush) if err then ngx.log(ngx.ERR, string.format("error when setting up timer.every: %s", tostring(err))) end end function _M.call() if metrics_count >= MAX_BATCH_SIZE then ngx.log(ngx.WARN, "omitting metrics for the request, current batch is full") return end local metrics_obj = metrics() local payload, err = cjson.encode(metrics_obj) if err then ngx.log(ngx.ERR, string.format("error when encoding metrics: %s", tostring(err))) return end metrics_count = metrics_count + 1 metrics_batch[metrics_count] = metrics_obj metrics_raw_batch[metrics_count] = payload end setmetatable(_M, {__index = { flush = flush, set_metrics_max_batch_size = set_metrics_max_batch_size, get_metrics_batch = function() return metrics_batch end, }}) return _M
perf: json encoding share to eatch request (#6955)
perf: json encoding share to eatch request (#6955) * perf: json encoding share to eatch request * fix: fix lint lua
Lua
apache-2.0
kubernetes/ingress-nginx,canhnt/ingress,kubernetes/ingress-nginx,kubernetes/ingress-nginx,kubernetes/ingress-nginx,canhnt/ingress,canhnt/ingress,canhnt/ingress,kubernetes/ingress-nginx
7c8d2a5565afb8c00940e5e4d6c48d502213cb1f
.hammerspoon/init.lua
.hammerspoon/init.lua
local mash = {"cmd", "alt", "ctrl"} -- Application shortcuts hs.hotkey.bind({"cmd", "shift"}, "{", function() current_app():selectMenuItem({"Window", "Select Previous Tab"}) end) hs.hotkey.bind({"cmd", "shift"}, "}", function() current_app():selectMenuItem({"Window", "Select Previous Tab"}) end) -- Window management hs.hotkey.bind(mash, "h", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) hs.hotkey.bind(mash, "l", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) function current_app() return hs.window.application() end function reload_config(files) hs.reload() end hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reload_config):start() hs.alert.show("Config loaded")
local mash = {"cmd", "alt", "ctrl"} local mash = {"cmd", "alt", "ctrl", "shift"} -- Application shortcuts hs.hotkey.bind({"cmd", "shift"}, "[", function() current_app():selectMenuItem({"Window", "Select Previous Tab"}) end) hs.hotkey.bind({"cmd", "shift"}, "]", function() current_app():selectMenuItem({"Window", "Select Next Tab"}) end) -- Window management hs.hotkey.bind(mash, "h", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) hs.hotkey.bind(mash, "l", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) function current_app() return hs.application.frontmostApplication() end function reload_config(files) hs.reload() end hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reload_config):start() hs.alert.show("Config loaded")
[hammerspoon] Fix hotkey binding
[hammerspoon] Fix hotkey binding
Lua
mit
kejadlen/dotfiles,kejadlen/dotfiles
7a463dd06818589c4f009174ac9f7766e05f360b
kong/db/migrations/core/012_213_to_220.lua
kong/db/migrations/core/012_213_to_220.lua
local fmt = string.format local function pg_clean_repeated_targets(connector, upstream_id) local targets_query = fmt("SELECT id, created_at, target FROM targets WHERE upstream_id = '%s'", upstream_id) for target, err in connector:iterate(targets_query) do local rep_tgt_query = fmt("SELECT id, created_at, target FROM targets WHERE upstream_id = '%s' AND target = '%s' AND id <> '%s'", upstream_id, target.target, target.id) for rep_tgt, err in connector:iterate(rep_tgt_query) do local tgt_to_clean if target.created_at >= rep_tgt.created_at then tgt_to_clean = rep_tgt else tgt_to_clean = target end local del_tgt_query = fmt("DELETE FROM targets WHERE id = '%s';", tgt_to_clean.id) local _, err = connector:query(del_tgt_query) if err then return nil, err end end end end -- remove repeated targets, the older ones are not useful anymore. targets with -- weight 0 will be kept, as we cannot tell which were deleted and which were -- explicitly set as 0. local function pg_remove_unused_targets(connector) assert(connector:connect_migrations()) for upstream, err in connector:iterate("SELECT id FROM upstreams") do local upstream_id = upstream and upstream.id if not upstream_id then return nil, err end local _, err = pg_clean_repeated_targets(connector, upstream_id) if err then return nil, err end end return true end local function c_clean_repeated_targets(connector, upstream_id) local cassandra = require 'cassandra' local rows, err = connector:query( "SELECT id, created_at, target FROM targets WHERE upstream_id = ?", { cassandra.uuid(upstream_id), } ) if err then return nil, err end for i = 1, #rows do local target = rows[i] local rep_tgt_rows, err = connector:query( "SELECT id, created_at, target FROM targets ".. "WHERE upstream_id = ? AND target = ? ALLOW FILTERING", { cassandra.uuid(upstream_id), cassandra.text(target.target), } ) if err then return nil, err end for j = i, #rep_tgt_rows do local rep_tgt = rep_tgt_rows[j] if rep_tgt.id ~= target.id then local tgt_to_clean if target.created_at >= rep_tgt.created_at then tgt_to_clean = rep_tgt else tgt_to_clean = target end local _, err = connector:query( "DELETE FROM targets WHERE id = ?", { cassandra.uuid(tgt_to_clean.id) } ) if err then return nil, err end end end end end -- remove repeated targets, the older ones are not useful anymore. targets with -- weight 0 will be kept, as we cannot tell which were deleted and which were -- explicitly set as 0. local function c_remove_unused_targets(connector) local coordinator = assert(connector:connect_migrations()) for rows, err in coordinator:iterate("SELECT id FROM upstreams") do for i = 1, #rows do local upstream_id = rows[i] and rows[i].id if not upstream_id then return nil, err end local _, err = c_clean_repeated_targets(connector, upstream_id) if err then return nil, err end end end return true end return { postgres = { up = [[ CREATE TABLE IF NOT EXISTS "clustering_data_planes" ( id UUID PRIMARY KEY, hostname TEXT NOT NULL, ip TEXT NOT NULL, last_seen TIMESTAMP WITH TIME ZONE DEFAULT (CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'), config_hash TEXT NOT NULL, ttl TIMESTAMP WITH TIME ZONE ); CREATE INDEX IF NOT EXISTS clustering_data_planes_ttl_idx ON clustering_data_planes (ttl); DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "routes" ADD "request_buffering" BOOLEAN; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "routes" ADD "response_buffering" BOOLEAN; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; ]], teardown = function(connector) local _, err = pg_remove_unused_targets(connector) if err then return nil, err end return true end }, cassandra = { up = [[ CREATE TABLE IF NOT EXISTS clustering_data_planes( id uuid, hostname text, ip text, last_seen timestamp, config_hash text, PRIMARY KEY (id) ) WITH default_time_to_live = 1209600; ALTER TABLE routes ADD request_buffering boolean; ALTER TABLE routes ADD response_buffering boolean; ]], teardown = function(connector) local _, err = c_remove_unused_targets(connector) if err then return nil, err end return true end } }
local fmt = string.format local function pg_clean_repeated_targets(connector, upstream_id) local targets_query = fmt("SELECT id, created_at, target FROM targets WHERE upstream_id = '%s'", upstream_id) for target, err in connector:iterate(targets_query) do if err then return nil, err end local rep_tgt_query = fmt("SELECT id, created_at, target FROM targets WHERE upstream_id = '%s' AND target = '%s' AND id <> '%s'", upstream_id, target.target, target.id) for rep_tgt, err in connector:iterate(rep_tgt_query) do if err then return nil, err end local tgt_to_clean if target.created_at >= rep_tgt.created_at then tgt_to_clean = rep_tgt else tgt_to_clean = target end local del_tgt_query = fmt("DELETE FROM targets WHERE id = '%s';", tgt_to_clean.id) local _, err = connector:query(del_tgt_query) if err then return nil, err end end end return true end -- remove repeated targets, the older ones are not useful anymore. targets with -- weight 0 will be kept, as we cannot tell which were deleted and which were -- explicitly set as 0. local function pg_remove_unused_targets(connector) for upstream, err in connector:iterate("SELECT id FROM upstreams") do if err then return nil, err end local upstream_id = upstream and upstream.id if not upstream_id then return nil, err end local _, err = pg_clean_repeated_targets(connector, upstream_id) if err then return nil, err end end return true end local function c_clean_repeated_targets(coordinator, upstream_id) local cassandra = require 'cassandra' local rows, err = coordinator:execute( "SELECT id, created_at, target FROM targets WHERE upstream_id = ?", { cassandra.uuid(upstream_id), } ) if err then return nil, err end for i = 1, #rows do local target = rows[i] local rep_tgt_rows, err = coordinator:execute( "SELECT id, created_at, target FROM targets ".. "WHERE upstream_id = ? AND target = ? ALLOW FILTERING", { cassandra.uuid(upstream_id), cassandra.text(target.target), } ) if err then return nil, err end for j = i, #rep_tgt_rows do local rep_tgt = rep_tgt_rows[j] if rep_tgt.id ~= target.id then local tgt_to_clean if target.created_at >= rep_tgt.created_at then tgt_to_clean = rep_tgt else tgt_to_clean = target end local _, err = coordinator:execute( "DELETE FROM targets WHERE id = ?", { cassandra.uuid(tgt_to_clean.id) } ) if err then return nil, err end end end end return true end -- remove repeated targets, the older ones are not useful anymore. targets with -- weight 0 will be kept, as we cannot tell which were deleted and which were -- explicitly set as 0. local function c_remove_unused_targets(coordinator) for rows, err in coordinator:iterate("SELECT id FROM upstreams") do if err then return nil, err end for i = 1, #rows do local upstream_id = rows[i] and rows[i].id if not upstream_id then return nil, err end local _, err = c_clean_repeated_targets(coordinator, upstream_id) if err then return nil, err end end end return true end return { postgres = { up = [[ CREATE TABLE IF NOT EXISTS "clustering_data_planes" ( id UUID PRIMARY KEY, hostname TEXT NOT NULL, ip TEXT NOT NULL, last_seen TIMESTAMP WITH TIME ZONE DEFAULT (CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'), config_hash TEXT NOT NULL, ttl TIMESTAMP WITH TIME ZONE ); CREATE INDEX IF NOT EXISTS clustering_data_planes_ttl_idx ON clustering_data_planes (ttl); DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "routes" ADD "request_buffering" BOOLEAN; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "routes" ADD "response_buffering" BOOLEAN; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; ]], teardown = function(connector) local _, err = pg_remove_unused_targets(connector) if err then return nil, err end return true end }, cassandra = { up = [[ CREATE TABLE IF NOT EXISTS clustering_data_planes( id uuid, hostname text, ip text, last_seen timestamp, config_hash text, PRIMARY KEY (id) ) WITH default_time_to_live = 1209600; ALTER TABLE routes ADD request_buffering boolean; ALTER TABLE routes ADD response_buffering boolean; ]], teardown = function(connector) local coordinator = assert(connector:get_stored_connection()) local _, err = c_remove_unused_targets(coordinator) if err then return nil, err end return true end } }
fix(migrations) add proper error handling to 2.1.3 to 2.2.0 migrations (#6440)
fix(migrations) add proper error handling to 2.1.3 to 2.2.0 migrations (#6440) ### Summary Adds proper error handling to 2.1.3 to 2.2.0 migrations. Also removes the non-needed `connect_migrations` call from Postgres. The Cassandra uses `coordinator:execute` on all the migrations. Rest of the fixes should be merged from master when this PR is merged: #6439.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
dc92a417fa7b6ca61bc7fdd6887d54f7fffeba52
core/portmanager.lua
core/portmanager.lua
local config = require "core.configmanager"; local server = require "net.server"; local log = require "util.logger".init("portmanager"); local multitable = require "util.multitable"; local set = require "util.set"; local prosody = prosody; local fire_event = prosody.events.fire_event; module "portmanager"; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end module("portmanager", package.seeall); prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 }); local mode = listener.default_mode or "*a"; local ssl; if service_info.encryption == "ssl" then ssl = prosody.global_ssl_ctx; if not ssl then return nil, "global-ssl-context-required"; end end for interface in bind_interfaces do for port in bind_ports do if #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do close(interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, server = get_service_at(interface, port); if not service then return false, "port-not-open"; end server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end function get_registered_services() return services; end return _M;
local config = require "core.configmanager"; local server = require "net.server"; local log = require "util.logger".init("portmanager"); local multitable = require "util.multitable"; local set = require "util.set"; local table, package = table, package; local setmetatable, rawset, rawget = setmetatable, rawset, rawget; local type = type; local prosody = prosody; local fire_event = prosody.events.fire_event; module "portmanager"; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 }); local mode = listener.default_mode or "*a"; local ssl; if service_info.encryption == "ssl" then ssl = prosody.global_ssl_ctx; if not ssl then return nil, "global-ssl-context-required"; end end for interface in bind_interfaces do for port in bind_ports do if #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do close(interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, server = get_service_at(interface, port); if not service then return false, "port-not-open"; end server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end function get_registered_services() return services; end return _M;
portmanager: Fix breakage (import ALL the functions)
portmanager: Fix breakage (import ALL the functions)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
2d8becef0f546ead3134cb76b62132ac4d165be9
share/lua/playlist/appletrailers.lua
share/lua/playlist/appletrailers.lua
--[[ Translate trailers.apple.com video webpages URLs to the corresponding movie URL $Id$ Copyright © 2007-2010 the VideoLAN team 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, "trailers.apple.com" ) end function find( haystack, needle ) local _,_,r = string.find( haystack, needle ) return r end function sort(a, b) if(a == nil) then return false end if(b == nil) then return false end local str_a local str_b if(string.find(a.name, '%(') == 1) then str_a = tonumber(string.sub(a.name, 2, string.find(a.name, 'p') - 1)) str_b = tonumber(string.sub(b.name, 2, string.find(b.name, 'p') - 1)) else str_a = string.sub(a.name, 1, string.find(a.name, '%(') - 2) str_b = string.sub(b.name, 1, string.find(b.name, '%(') - 2) if(str_a == str_b) then str_a = tonumber(string.sub(a.name, string.len(str_a) + 3, string.find(a.name, 'p', string.len(str_a) + 3) - 1)) str_b = tonumber(string.sub(b.name, string.len(str_b) + 3, string.find(b.name, 'p', string.len(str_b) + 3) - 1)) end end if(str_a > str_b) then return false else return true end end -- Parse function. function parse() local playlist = {} local description = '' local art_url = '' while true do line = vlc.readline() if not line then break end if string.match( line, "class=\".-first" ) then description = find( line, "h%d.->(.-)</h%d") .. ' ' end if string.match( line, 'img src=') then for img in string.gmatch(line, '<img src="(http://.*%.jpg)" ') do art_url = img end for i,value in pairs(playlist) do if value.arturl == '' then playlist[i].arturl = art_url else break end end end if string.match( line, 'class="hd".-%.mov') then for urlline,resolution in string.gmatch(line, 'class="hd".-href="(.-%.mov)".-(%d+.-p)') do urlline = string.gsub( urlline, "_"..resolution, "_h"..resolution ) table.insert( playlist, { path = urlline, name = description .. '(' .. resolution .. ')', arturl = art_url, options = {":http-user-agent=QuickTime/7.5", ":play-and-pause"} } ) end end end table.sort(playlist, sort) return playlist end
--[[ Translate trailers.apple.com video webpages URLs to the corresponding movie URL $Id$ Copyright © 2007-2010 the VideoLAN team 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, "trailers.apple.com" ) and string.match( vlc.path, "web.inc" ) end function find( haystack, needle ) local _,_,r = string.find( haystack, needle ) return r end function sort(a, b) if(a == nil) then return false end if(b == nil) then return false end local str_a local str_b if(string.find(a.name, '%(') == 1) then str_a = tonumber(string.sub(a.name, 2, string.find(a.name, 'p') - 1)) str_b = tonumber(string.sub(b.name, 2, string.find(b.name, 'p') - 1)) else str_a = string.sub(a.name, 1, string.find(a.name, '%(') - 2) str_b = string.sub(b.name, 1, string.find(b.name, '%(') - 2) if(str_a == str_b) then str_a = tonumber(string.sub(a.name, string.len(str_a) + 3, string.find(a.name, 'p', string.len(str_a) + 3) - 1)) str_b = tonumber(string.sub(b.name, string.len(str_b) + 3, string.find(b.name, 'p', string.len(str_b) + 3) - 1)) end end if(str_a > str_b) then return false else return true end end -- Parse function. function parse() local playlist = {} local description = '' local art_url = '' while true do line = vlc.readline() if not line then break end if string.match( line, "h%d>.-</h%d" ) then description = find( line, "h%d>(.+)</h%d") vlc.msg.dbg(description) end if string.match( line, 'img src=') then for img in string.gmatch(line, '<img src="(http://.*%.jpg)" ') do art_url = img end for i,value in pairs(playlist) do if value.arturl == '' then playlist[i].arturl = art_url end end end if string.match( line, 'class="hd".-%.mov') then for urlline,resolution in string.gmatch(line, 'class="hd".-href="(.-%.mov)".->(%d+.-p)') do urlline = string.gsub( urlline, "_"..resolution, "_h"..resolution ) table.insert( playlist, { path = urlline, name = description.." "..resolution, arturl = art_url, options = {":http-user-agent=QuickTime/7.5", ":play-and-pause", ":demux=avformat"} } ) end end end return playlist end
fix appletrailers playlist parser
fix appletrailers playlist parser
Lua
lgpl-2.1
krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,xkfz007/vlc,xkfz007/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,shyamalschandra/vlc
3fc7d3f5de08a6d750cc8ccbe124f23f29bad732
libs/httpd/luasrc/httpd/handler/luci.lua
libs/httpd/luasrc/httpd/handler/luci.lua
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.httpd.handler.luci", package.seeall) require("luci.dispatcher") require("luci.http") require("luci.http.protocol.date") require("ltn12") Luci = luci.util.class(luci.httpd.module.Handler) Response = luci.httpd.module.Response function Luci.__init__(self) luci.httpd.module.Handler.__init__(self) end function Luci.handle_head(self, ...) local response, sourceout = self:handle_get(...) return response end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) local r = luci.http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local x = coroutine.create(luci.dispatcher.httpdispatch) while not id or id < 3 do coroutine.yield() res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end <<<<<<< HEAD:libs/httpd/luasrc/httpd/handler/luci.lua ======= >>>>>>> * libs/httpd: Added Cache-Control header to LuCI:libs/httpd/luasrc/httpd/handler/luci.lua local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id then return true elseif id == 5 then return nil else return data end end headers["Expires"] = luci.http.protocol.date.to_http( os.time() ) headers["Date"] = headers["Expires"] headers["Cache-Control"] = "no-cache" return Response(status, headers), iter end
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.httpd.handler.luci", package.seeall) require("luci.dispatcher") require("luci.http") require("luci.http.protocol.date") require("ltn12") Luci = luci.util.class(luci.httpd.module.Handler) Response = luci.httpd.module.Response function Luci.__init__(self) luci.httpd.module.Handler.__init__(self) end function Luci.handle_head(self, ...) local response, sourceout = self:handle_get(...) return response end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) local r = luci.http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local x = coroutine.create(luci.dispatcher.httpdispatch) while not id or id < 3 do coroutine.yield() res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id then return true elseif id == 5 then return nil else return data end end headers["Expires"] = luci.http.protocol.date.to_http( os.time() ) headers["Date"] = headers["Expires"] headers["Cache-Control"] = "no-cache" return Response(status, headers), iter end
* Fixed last commit
* Fixed last commit
Lua
apache-2.0
cshore-firmware/openwrt-luci,RuiChen1113/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,maxrio/luci981213,kuoruan/lede-luci,florian-shellfire/luci,david-xiao/luci,cshore/luci,palmettos/cnLuCI,wongsyrone/luci-1,palmettos/cnLuCI,cshore/luci,sujeet14108/luci,Sakura-Winkey/LuCI,openwrt/luci,ReclaimYourPrivacy/cloak-luci,tobiaswaldvogel/luci,Wedmer/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,deepak78/new-luci,taiha/luci,obsy/luci,rogerpueyo/luci,chris5560/openwrt-luci,MinFu/luci,Hostle/luci,slayerrensky/luci,ff94315/luci-1,981213/luci-1,zhaoxx063/luci,jorgifumi/luci,male-puppies/luci,tcatm/luci,deepak78/new-luci,hnyman/luci,lcf258/openwrtcn,nwf/openwrt-luci,obsy/luci,maxrio/luci981213,openwrt-es/openwrt-luci,daofeng2015/luci,fkooman/luci,cshore/luci,bright-things/ionic-luci,fkooman/luci,palmettos/test,palmettos/test,joaofvieira/luci,daofeng2015/luci,nwf/openwrt-luci,keyidadi/luci,tobiaswaldvogel/luci,RuiChen1113/luci,david-xiao/luci,keyidadi/luci,cshore/luci,remakeelectric/luci,deepak78/new-luci,dwmw2/luci,openwrt/luci,Kyklas/luci-proto-hso,lcf258/openwrtcn,taiha/luci,jchuang1977/luci-1,taiha/luci,dwmw2/luci,david-xiao/luci,opentechinstitute/luci,schidler/ionic-luci,Noltari/luci,florian-shellfire/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,Hostle/luci,aa65535/luci,opentechinstitute/luci,dwmw2/luci,bittorf/luci,tcatm/luci,daofeng2015/luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,Kyklas/luci-proto-hso,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,RuiChen1113/luci,florian-shellfire/luci,keyidadi/luci,jorgifumi/luci,dismantl/luci-0.12,palmettos/cnLuCI,ReclaimYourPrivacy/cloak-luci,artynet/luci,teslamint/luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,nwf/openwrt-luci,bright-things/ionic-luci,obsy/luci,keyidadi/luci,keyidadi/luci,cappiewu/luci,aa65535/luci,LuttyYang/luci,Sakura-Winkey/LuCI,ff94315/luci-1,zhaoxx063/luci,nmav/luci,RedSnake64/openwrt-luci-packages,NeoRaider/luci,oyido/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,harveyhu2012/luci,zhaoxx063/luci,cshore-firmware/openwrt-luci,Hostle/luci,thesabbir/luci,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,cshore-firmware/openwrt-luci,dismantl/luci-0.12,zhaoxx063/luci,fkooman/luci,bright-things/ionic-luci,MinFu/luci,marcel-sch/luci,oyido/luci,aa65535/luci,LuttyYang/luci,slayerrensky/luci,Kyklas/luci-proto-hso,slayerrensky/luci,bright-things/ionic-luci,maxrio/luci981213,jlopenwrtluci/luci,nwf/openwrt-luci,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,urueedi/luci,NeoRaider/luci,openwrt/luci,Hostle/openwrt-luci-multi-user,taiha/luci,aa65535/luci,Wedmer/luci,thess/OpenWrt-luci,dwmw2/luci,oneru/luci,Noltari/luci,MinFu/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,artynet/luci,cappiewu/luci,sujeet14108/luci,schidler/ionic-luci,sujeet14108/luci,nwf/openwrt-luci,981213/luci-1,maxrio/luci981213,lbthomsen/openwrt-luci,NeoRaider/luci,male-puppies/luci,oneru/luci,mumuqz/luci,lbthomsen/openwrt-luci,ollie27/openwrt_luci,harveyhu2012/luci,cshore/luci,remakeelectric/luci,mumuqz/luci,wongsyrone/luci-1,oyido/luci,Wedmer/luci,hnyman/luci,male-puppies/luci,david-xiao/luci,opentechinstitute/luci,cappiewu/luci,Noltari/luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,nmav/luci,sujeet14108/luci,Sakura-Winkey/LuCI,palmettos/cnLuCI,bright-things/ionic-luci,marcel-sch/luci,fkooman/luci,lcf258/openwrtcn,florian-shellfire/luci,nmav/luci,tobiaswaldvogel/luci,obsy/luci,thesabbir/luci,palmettos/cnLuCI,remakeelectric/luci,maxrio/luci981213,oyido/luci,oneru/luci,forward619/luci,fkooman/luci,fkooman/luci,forward619/luci,cappiewu/luci,daofeng2015/luci,thesabbir/luci,jlopenwrtluci/luci,MinFu/luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,teslamint/luci,palmettos/test,jorgifumi/luci,nwf/openwrt-luci,thesabbir/luci,zhaoxx063/luci,hnyman/luci,cshore-firmware/openwrt-luci,remakeelectric/luci,ff94315/luci-1,teslamint/luci,NeoRaider/luci,remakeelectric/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,forward619/luci,oyido/luci,mumuqz/luci,opentechinstitute/luci,Noltari/luci,NeoRaider/luci,kuoruan/lede-luci,urueedi/luci,tobiaswaldvogel/luci,artynet/luci,bittorf/luci,db260179/openwrt-bpi-r1-luci,kuoruan/luci,kuoruan/luci,RuiChen1113/luci,RuiChen1113/luci,Hostle/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,kuoruan/luci,zhaoxx063/luci,NeoRaider/luci,florian-shellfire/luci,male-puppies/luci,remakeelectric/luci,dismantl/luci-0.12,palmettos/cnLuCI,zhaoxx063/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,david-xiao/luci,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,cshore/luci,dwmw2/luci,taiha/luci,oyido/luci,marcel-sch/luci,jlopenwrtluci/luci,kuoruan/luci,kuoruan/luci,forward619/luci,MinFu/luci,Wedmer/luci,jchuang1977/luci-1,david-xiao/luci,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,Noltari/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,artynet/luci,RuiChen1113/luci,hnyman/luci,urueedi/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,kuoruan/luci,bright-things/ionic-luci,jorgifumi/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,palmettos/test,cshore-firmware/openwrt-luci,deepak78/new-luci,obsy/luci,tcatm/luci,mumuqz/luci,hnyman/luci,981213/luci-1,marcel-sch/luci,ollie27/openwrt_luci,thesabbir/luci,kuoruan/luci,Noltari/luci,kuoruan/lede-luci,slayerrensky/luci,tobiaswaldvogel/luci,harveyhu2012/luci,dwmw2/luci,Kyklas/luci-proto-hso,wongsyrone/luci-1,lbthomsen/openwrt-luci,mumuqz/luci,palmettos/test,urueedi/luci,artynet/luci,cshore/luci,bittorf/luci,chris5560/openwrt-luci,forward619/luci,RedSnake64/openwrt-luci-packages,RuiChen1113/luci,taiha/luci,openwrt/luci,tobiaswaldvogel/luci,harveyhu2012/luci,cappiewu/luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,nwf/openwrt-luci,oyido/luci,hnyman/luci,bittorf/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,tcatm/luci,nmav/luci,maxrio/luci981213,urueedi/luci,wongsyrone/luci-1,Hostle/luci,oneru/luci,rogerpueyo/luci,daofeng2015/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,fkooman/luci,Hostle/luci,openwrt-es/openwrt-luci,deepak78/new-luci,thess/OpenWrt-luci,NeoRaider/luci,RedSnake64/openwrt-luci-packages,nmav/luci,jchuang1977/luci-1,daofeng2015/luci,joaofvieira/luci,Kyklas/luci-proto-hso,bittorf/luci,RedSnake64/openwrt-luci-packages,wongsyrone/luci-1,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,marcel-sch/luci,dismantl/luci-0.12,cappiewu/luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,nmav/luci,male-puppies/luci,Hostle/openwrt-luci-multi-user,sujeet14108/luci,palmettos/test,openwrt-es/openwrt-luci,daofeng2015/luci,LuttyYang/luci,oneru/luci,male-puppies/luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,slayerrensky/luci,palmettos/test,lcf258/openwrtcn,thesabbir/luci,nmav/luci,openwrt-es/openwrt-luci,981213/luci-1,jchuang1977/luci-1,lbthomsen/openwrt-luci,Wedmer/luci,nmav/luci,oyido/luci,ollie27/openwrt_luci,remakeelectric/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,florian-shellfire/luci,obsy/luci,kuoruan/lede-luci,harveyhu2012/luci,lcf258/openwrtcn,joaofvieira/luci,lcf258/openwrtcn,teslamint/luci,jlopenwrtluci/luci,tcatm/luci,tobiaswaldvogel/luci,jorgifumi/luci,harveyhu2012/luci,joaofvieira/luci,rogerpueyo/luci,981213/luci-1,LuttyYang/luci,openwrt/luci,schidler/ionic-luci,opentechinstitute/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/openwrt-luci-multi-user,Wedmer/luci,openwrt/luci,cshore/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,LuttyYang/luci,tcatm/luci,taiha/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,ff94315/luci-1,sujeet14108/luci,chris5560/openwrt-luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,slayerrensky/luci,lbthomsen/openwrt-luci,cappiewu/luci,bittorf/luci,lbthomsen/openwrt-luci,forward619/luci,dwmw2/luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,MinFu/luci,kuoruan/lede-luci,thess/OpenWrt-luci,rogerpueyo/luci,RuiChen1113/luci,thesabbir/luci,slayerrensky/luci,maxrio/luci981213,ollie27/openwrt_luci,urueedi/luci,oneru/luci,Hostle/openwrt-luci-multi-user,forward619/luci,slayerrensky/luci,obsy/luci,deepak78/new-luci,981213/luci-1,ff94315/luci-1,Noltari/luci,deepak78/new-luci,kuoruan/lede-luci,dismantl/luci-0.12,MinFu/luci,Wedmer/luci,teslamint/luci,chris5560/openwrt-luci,aa65535/luci,schidler/ionic-luci,palmettos/test,openwrt-es/openwrt-luci,sujeet14108/luci,jchuang1977/luci-1,openwrt/luci,Noltari/luci,schidler/ionic-luci,jlopenwrtluci/luci,taiha/luci,RedSnake64/openwrt-luci-packages,aa65535/luci,nwf/openwrt-luci,urueedi/luci,marcel-sch/luci,Hostle/luci,artynet/luci,Kyklas/luci-proto-hso,artynet/luci,ff94315/luci-1,LuttyYang/luci,artynet/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,thess/OpenWrt-luci,openwrt/luci,rogerpueyo/luci,Hostle/luci,palmettos/cnLuCI,joaofvieira/luci,cappiewu/luci,florian-shellfire/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,jlopenwrtluci/luci,mumuqz/luci,remakeelectric/luci,teslamint/luci,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,marcel-sch/luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,jorgifumi/luci,oneru/luci,thess/OpenWrt-luci,wongsyrone/luci-1,jchuang1977/luci-1,ff94315/luci-1,jchuang1977/luci-1,joaofvieira/luci,zhaoxx063/luci,kuoruan/luci,MinFu/luci,rogerpueyo/luci,sujeet14108/luci,thess/OpenWrt-luci,kuoruan/lede-luci,wongsyrone/luci-1,chris5560/openwrt-luci,jorgifumi/luci,male-puppies/luci,ollie27/openwrt_luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,981213/luci-1,LuttyYang/luci,keyidadi/luci,ollie27/openwrt_luci,oneru/luci,harveyhu2012/luci,kuoruan/lede-luci,fkooman/luci,bright-things/ionic-luci,Noltari/luci,hnyman/luci,david-xiao/luci,nmav/luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,bittorf/luci,forward619/luci,opentechinstitute/luci,shangjiyu/luci-with-extra,obsy/luci,cshore-firmware/openwrt-luci,teslamint/luci,chris5560/openwrt-luci,marcel-sch/luci,tcatm/luci,joaofvieira/luci,NeoRaider/luci,joaofvieira/luci,teslamint/luci,daofeng2015/luci
29512dd3ec06f234b839e13dd399601f4b24c258
lib/grid.lua
lib/grid.lua
local Grid = class('Grid') function Grid:initialize(width, height) assert(type(width) == "number" and width > 0) assert(type(height) == "number" and height > 0) for i = 1, width do self[i] = {} end self.width = width self.height = height self.orientation = 0 end -- TODO I don't actually trust this iterator, double check it all function Grid:each(x, y, width, height) x = x or 1 y = y or 1 width = width or self.width height = height or self.height width, height = width - 1, height - 1 -- don't try to iterate outside of the grid bounds local x_diff, y_diff = 0, 0 if x < 1 then x_diff = 1 - x x = 1 end if y < 1 then y_diff = 1 - y y = 1 end -- if you bump up x or y, bump down the width or height the same amount width, height = width - x_diff, height - y_diff if x + width > self.width then width = self.width - x end if y + height > self.height then height = self.height - y end local function iterator(state) while state.childIndex <= x + width do local child = self[state.childIndex] state.grandChildIndex = state.grandChildIndex + 1 if state.grandChildIndex > y + height then state.childIndex = state.childIndex + 1 state.grandChildIndex = y - 1 else return state.childIndex, state.grandChildIndex, child[state.grandChildIndex] end end end return iterator, {childIndex = x, grandChildIndex = y - 1} end function Grid:rotate(angle) return self:rotate_to(self.orientation + angle) end function Grid:rotate_to(angle) self.orientation = angle return self.orientation end function Grid:out_of_bounds(x, y) return x < 1 or y < 1 or x > self.width or y > self.height end function Grid:get(x, y, orientation) if self:out_of_bounds(x, y) then -- out of bounds return nil end orientation = orientation or self.orientation local angle_quad = orientation / 90 % 4 if angle_quad == 0 then return self[x][y] elseif angle_quad == 1 then return self[y][#self - x + 1] elseif angle_quad == 2 then return self[#self - x + 1][#self - y + 1] elseif angle_quad == 3 then return self[#self - y + 1][x] end end Grid.g = Grid.get function Grid:set(x, y, value, orientation) if self:out_of_bounds(x, y) then -- out of bounds return end orientation = orientation or self.orientation local angle_quad = orientation / 90 % 4 if angle_quad == 0 then self[x][y] = value elseif angle_quad == 1 then self[y][#self - x + 1] = value elseif angle_quad == 2 then self[#self - x + 1][#self - y + 1] = value elseif angle_quad == 3 then self[#self - y + 1][x] = value end end Grid.s = Grid.set function Grid:__tostring() local strings, result = {}, " " for i,row in ipairs(self) do for j,cell in ipairs(row) do if strings[j] == nil then strings[j] = {} end strings[j][i] = self:get(i, j) end end for i = 1, self.width do result = result .. i .. ", " end result = result .. "\n" for i = 1, self.width do if i >= 10 then result = result .. i .. ": " .. table.concat(strings[i], ", ") .. "\n" else result = result .. i .. ": " .. table.concat(strings[i], ", ") .. "\n" end end return result end return Grid
local Grid = class('Grid') function Grid:initialize(width, height) assert(type(width) == "number" and width > 0) assert(type(height) == "number" and height > 0) for i = 1, width do self[i] = {} end self.width = width self.height = height self.orientation = 0 end -- TODO I don't actually trust this iterator, double check it all function Grid:each(x, y, width, height) x = x or 1 y = y or 1 width = width or self.width height = height or self.height width, height = width - 1, height - 1 -- don't try to iterate outside of the grid bounds local x_diff, y_diff = 0, 0 if x < 1 then x_diff = 1 - x x = 1 end if y < 1 then y_diff = 1 - y y = 1 end -- if you bump up x or y, bump down the width or height the same amount width, height = width - x_diff, height - y_diff if x + width > self.width then width = self.width - x end if y + height > self.height then height = self.height - y end local function iterator(state) while state.childIndex <= x + width do state.grandChildIndex = state.grandChildIndex + 1 if state.grandChildIndex > y + height then state.childIndex = state.childIndex + 1 state.grandChildIndex = y - 1 else return state.childIndex, state.grandChildIndex, self:get(state.childIndex, state.grandChildIndex) end end end return iterator, {childIndex = x, grandChildIndex = y - 1} end function Grid:rotate(angle) return self:rotate_to(self.orientation + angle) end function Grid:rotate_to(angle) self.orientation = angle return self.orientation end function Grid:out_of_bounds(x, y) return x < 1 or y < 1 or x > self.width or y > self.height end function Grid:get(x, y, orientation) if self:out_of_bounds(x, y) then -- out of bounds return nil end orientation = orientation or self.orientation local angle_quad = orientation / 90 % 4 if angle_quad == 0 then return self[x][y] elseif angle_quad == 1 then return self[y][#self - x + 1] elseif angle_quad == 2 then return self[#self - x + 1][#self - y + 1] elseif angle_quad == 3 then return self[#self - y + 1][x] end end Grid.g = Grid.get function Grid:set(x, y, value, orientation) if self:out_of_bounds(x, y) then -- out of bounds return end orientation = orientation or self.orientation local angle_quad = orientation / 90 % 4 if angle_quad == 0 then self[x][y] = value elseif angle_quad == 1 then self[y][#self - x + 1] = value elseif angle_quad == 2 then self[#self - x + 1][#self - y + 1] = value elseif angle_quad == 3 then self[#self - y + 1][x] = value end end Grid.s = Grid.set function Grid:__tostring() local strings, result = {}, " " for i,row in ipairs(self) do for j,cell in ipairs(row) do if strings[j] == nil then strings[j] = {} end strings[j][i] = self:get(i, j) end end for i = 1, self.width do result = result .. i .. ", " end result = result .. "\n" for i = 1, self.width do if i >= 10 then result = result .. i .. ": " .. table.concat(strings[i], ", ") .. "\n" else result = result .. i .. ": " .. table.concat(strings[i], ", ") .. "\n" end end return result end return Grid
fix grid iterator not respecting the grid orientation
fix grid iterator not respecting the grid orientation
Lua
mit
TannerRogalsky/GGJ2017
1e5cd18025b99129bd9d81e1cfad6018817c6ae3
aspects/nvim/files/.config/nvim/lua/wincent/cmp/handles.lua
aspects/nvim/files/.config/nvim/lua/wincent/cmp/handles.lua
-- Custom nvim-cmp source for GitHub handles. local handles = {} local registered = false handles.setup = function() if registered then return end registered = true local has_cmp, cmp = pcall(require, 'cmp') if not has_cmp then return end local config = vim.fn.expand('~/.github-handles.json') if vim.fn.filereadable(config) == 0 then return end local addresses = vim.fn.json_decode(vim.fn.readfile(config)) local source = {} source.new = function() return setmetatable({}, {__index = source}) end source.get_trigger_characters = function() return { '@' } end source.complete = function(self, request, callback) local input = string.sub(request.context.cursor_before_line, request.offset - 1) local prefix = string.sub(request.context.cursor_before_line, 1, request.offset - 1) if vim.startswith(input, '@') and (prefix == '@' or vim.endswith(prefix, ' @')) then local items = {} for handle, address in pairs(addresses) do table.insert(items, { label = address, textEdit = { newText = address, range = { start = { line = request.context.cursor.row - 1, character = request.context.cursor.col - 1 - #input, }, ['end'] = { line = request.context.cursor.row - 1, character = request.context.cursor.col - 1, }, }, }, } ) end callback { items = items, isIncomplete = true, } else callback({isIncomplete = true}) end end cmp.register_source('handles', source.new()) cmp.setup.filetype('gitcommit', { sources = cmp.config.sources({ { name = 'luasnip' }, { name = 'buffer' }, { name = 'calc' }, { name = 'emoji' }, { name = 'path' }, -- My custom sources. { name = 'handles' }, -- GitHub handles; eg. @wincent → Greg Hurrell <[email protected]> }), }) end return handles
-- Custom nvim-cmp source for GitHub handles. local handles = {} local registered = false handles.setup = function() if registered then return end registered = true local has_cmp, cmp = pcall(require, 'cmp') if not has_cmp then return end local config = vim.fn.expand('~/.github-handles.json') if vim.fn.filereadable(config) == 0 then return end local addresses = vim.fn.json_decode(vim.fn.readfile(config)) local source = {} source.new = function() return setmetatable({}, {__index = source}) end source.get_trigger_characters = function() return { '@' } end source.complete = function(self, request, callback) local input = string.sub(request.context.cursor_before_line, request.offset - 1) local prefix = string.sub(request.context.cursor_before_line, 1, request.offset - 1) if vim.startswith(input, '@') and (prefix == '@' or vim.endswith(prefix, ' @')) then local items = {} for handle, address in pairs(addresses) do table.insert(items, { filterText = handle .. ' ' .. address, label = address, textEdit = { newText = address, range = { start = { line = request.context.cursor.row - 1, character = request.context.cursor.col - 1 - #input, }, ['end'] = { line = request.context.cursor.row - 1, character = request.context.cursor.col - 1, }, }, }, } ) end callback { items = items, isIncomplete = true, } else callback({isIncomplete = true}) end end cmp.register_source('handles', source.new()) cmp.setup.filetype('gitcommit', { sources = cmp.config.sources({ { name = 'luasnip' }, { name = 'buffer' }, { name = 'calc' }, { name = 'emoji' }, { name = 'path' }, -- My custom sources. { name = 'handles' }, -- GitHub handles; eg. @wincent → Greg Hurrell <[email protected]> }), }) end return handles
fix(nvim): include handle text in handle completion autocomplete
fix(nvim): include handle text in handle completion autocomplete Hadn't spotted this bug because at GitHub your handle always matches your email address: @wincent Greg Hurrell <[email protected]> ^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ Handle Name Email address As such, I could type "@wincent" and it would always match the suggested `newText`, because "wincent" is in the email address part. However, when the handles don't match, it would not work; ie. in the following scenario "@wincent" wouldn't work: @wincent Greg Hurrell <[email protected]> ^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ Handle Name Email address This is slightly weird because I can type something like "@winHurrgreghurr" and it will match, but it generally yields the expected result. (Note that including a dot in the input breaks the autocompletion because it is not considered a keyword character; I may have to override the keyword detection to fix that.)
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
0a6ce204234c9485549e290230e51484b1fceb64
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/processes.lua
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/processes.lua
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.processes", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { { title = "%H: Processes", vlabel = "Processes/s", data = { instances = { ps_state = { "sleeping", "running", "paging", "blocked", "stopped", "zombies" } }, options = { ps_state_sleeping = { color = "0000ff", title = "Sleeping" }, ps_state_running = { color = "008000", title = "Running" }, ps_state_paging = { color = "ffff00", title = "Paging" }, ps_state_blocked = { color = "ff5000", title = "Blocked" }, ps_state_stopped = { color = "555555", title = "Stopped" }, ps_state_zombies = { color = "ff0000", title = "Zombies" } } } }, { title = "%H: CPU time used by %pi", vlabel = "Jiffies", data = { sources = { ps_cputime = { "syst", "user" } }, options = { ps_cputime__user = { color = "0000ff", title = "User", overlay = true }, ps_cputime__syst = { color = "ff0000", title = "System", overlay = true } } } }, { title = "%H: Threads and processes belonging to %pi", vlabel = "Count", detail = true, data = { sources = { ps_count = { "threads", "processes" } }, options = { ps_count__threads = { color = "00ff00", title = "Threads" }, ps_count__processes = { color = "0000bb", title = "Processes" } } } }, { title = "%H: Page faults in %pi", vlabel = "Page faults", detail = true, data = { sources = { ps_pagefaults = { "minflt", "majflt" } }, options = { ps_pagefaults__minflt = { color = "0000ff", title = "Minor" }, ps_pagefaults__majflt = { color = "ff0000", title = "Major" } } } }, { title = "%H: Resident segment size (RSS) of %pi", vlabel = "Bytes", detail = true, number_format = "%5.1lf%sB", data = { types = { "ps_rss" }, options = { ps_rss = { color = "0000ff", title = "Resident segment" } } } }, { title = "%H: Virtual memory size (VSZ) of %pi", vlabel = "Bytes", detail = true, number_format = "%5.1lf%sB", data = { types = { "ps_vm" }, options = { ps_vm = { color = "0000ff", title = "Virtual memory" } } } } } end
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.processes", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) if plugin_instance == "" then return { title = "%H: Processes", vlabel = "Processes/s", data = { instances = { ps_state = { "sleeping", "running", "paging", "blocked", "stopped", "zombies" } }, options = { ps_state_sleeping = { color = "0000ff", title = "Sleeping" }, ps_state_running = { color = "008000", title = "Running" }, ps_state_paging = { color = "ffff00", title = "Paging" }, ps_state_blocked = { color = "ff5000", title = "Blocked" }, ps_state_stopped = { color = "555555", title = "Stopped" }, ps_state_zombies = { color = "ff0000", title = "Zombies" } } } } else return { { title = "%H: CPU time used by %pi", vlabel = "Jiffies", data = { sources = { ps_cputime = { "syst", "user" } }, options = { ps_cputime__user = { color = "0000ff", title = "User", overlay = true }, ps_cputime__syst = { color = "ff0000", title = "System", overlay = true } } } }, { title = "%H: Threads and processes belonging to %pi", vlabel = "Count", detail = true, data = { sources = { ps_count = { "threads", "processes" } }, options = { ps_count__threads = { color = "00ff00", title = "Threads" }, ps_count__processes = { color = "0000bb", title = "Processes" } } } }, { title = "%H: Page faults in %pi", vlabel = "Page faults", detail = true, data = { sources = { ps_pagefaults = { "minflt", "majflt" } }, options = { ps_pagefaults__minflt = { color = "0000ff", title = "Minor" }, ps_pagefaults__majflt = { color = "ff0000", title = "Major" } } } }, { title = "%H: Resident segment size (RSS) of %pi", vlabel = "Bytes", detail = true, number_format = "%5.1lf%sB", data = { types = { "ps_rss" }, options = { ps_rss = { color = "0000ff", title = "Resident segment" } } } }, { title = "%H: Virtual memory size (VSZ) of %pi", vlabel = "Bytes", detail = true, number_format = "%5.1lf%sB", data = { types = { "ps_vm" }, options = { ps_vm = { color = "0000ff", title = "Virtual memory" } } } } } end end
luci-app-statistics: processes: fix graph visibility
luci-app-statistics: processes: fix graph visibility Fix graph visibility on processes page based on plugin instance. The overview instance is empty, while monitored processes have their own instances. Original version of the patch created by @koblack and discussed in #1021 Signed-off-by: Hannu Nyman <[email protected]>
Lua
apache-2.0
hnyman/luci,wongsyrone/luci-1,artynet/luci,artynet/luci,taiha/luci,rogerpueyo/luci,chris5560/openwrt-luci,oneru/luci,tobiaswaldvogel/luci,981213/luci-1,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,kuoruan/lede-luci,remakeelectric/luci,rogerpueyo/luci,hnyman/luci,wongsyrone/luci-1,remakeelectric/luci,hnyman/luci,chris5560/openwrt-luci,rogerpueyo/luci,aa65535/luci,remakeelectric/luci,kuoruan/lede-luci,taiha/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,nmav/luci,981213/luci-1,kuoruan/lede-luci,taiha/luci,openwrt-es/openwrt-luci,981213/luci-1,Noltari/luci,tobiaswaldvogel/luci,Noltari/luci,wongsyrone/luci-1,artynet/luci,981213/luci-1,chris5560/openwrt-luci,openwrt/luci,aa65535/luci,oneru/luci,hnyman/luci,aa65535/luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,nmav/luci,openwrt/luci,rogerpueyo/luci,oneru/luci,oneru/luci,Noltari/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,remakeelectric/luci,openwrt/luci,taiha/luci,taiha/luci,nmav/luci,Wedmer/luci,aa65535/luci,wongsyrone/luci-1,nmav/luci,lbthomsen/openwrt-luci,Noltari/luci,remakeelectric/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,kuoruan/luci,openwrt-es/openwrt-luci,kuoruan/luci,Wedmer/luci,chris5560/openwrt-luci,nmav/luci,nmav/luci,taiha/luci,remakeelectric/luci,openwrt-es/openwrt-luci,oneru/luci,wongsyrone/luci-1,Wedmer/luci,openwrt-es/openwrt-luci,remakeelectric/luci,Noltari/luci,taiha/luci,Noltari/luci,chris5560/openwrt-luci,nmav/luci,lbthomsen/openwrt-luci,hnyman/luci,kuoruan/luci,rogerpueyo/luci,Wedmer/luci,kuoruan/lede-luci,artynet/luci,tobiaswaldvogel/luci,oneru/luci,kuoruan/luci,Wedmer/luci,aa65535/luci,Noltari/luci,rogerpueyo/luci,taiha/luci,artynet/luci,nmav/luci,openwrt/luci,remakeelectric/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,openwrt/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,Noltari/luci,rogerpueyo/luci,981213/luci-1,nmav/luci,tobiaswaldvogel/luci,artynet/luci,rogerpueyo/luci,981213/luci-1,aa65535/luci,wongsyrone/luci-1,wongsyrone/luci-1,artynet/luci,openwrt/luci,Noltari/luci,kuoruan/luci,Wedmer/luci,hnyman/luci,oneru/luci,openwrt/luci,oneru/luci,kuoruan/lede-luci,kuoruan/luci,lbthomsen/openwrt-luci,Wedmer/luci,openwrt-es/openwrt-luci,981213/luci-1,kuoruan/luci,kuoruan/luci,aa65535/luci,openwrt/luci,artynet/luci,chris5560/openwrt-luci,aa65535/luci,Wedmer/luci,artynet/luci
26e1fdbfc18fd52665579c9e1e58ba41e37c62c5
UCDmafiaWars/LV_c.lua
UCDmafiaWars/LV_c.lua
local t addEventHandler("onClientColShapeHit", LV, function (ele, matchingDimension) if (ele.type == "player" and ele == localPlayer and matchingDimension) then exports.UCDdx:add("Welcome to Las Venturas", 255, 255, 0) t = Timer(function () exports.UCDdx:del("Welcome to Las Venturas") end, 2500, 1) end end ) addEventHandler("onClientColShapeLeave", LV, function (ele, matchingDimension) if (ele.type == "player" and ele == localPlayer and matchingDimension) then exports.UCDdx:del("Welcome to Las Venturas") if (t and isTimer(t)) then t:kill() t = nil end end end )
local t addEventHandler("onClientColShapeHit", LV, function (ele, matchingDimension) if (ele.type == "player" and ele == localPlayer and matchingDimension) then exports.UCDdx:add("welcometolv", "Welcome to Las Venturas", 255, 255, 0) t = Timer(function () exports.UCDdx:del("welcometolv") end, 5000, 1) end end ) addEventHandler("onClientColShapeLeave", LV, function (ele, matchingDimension) if (ele.type == "player" and ele == localPlayer and matchingDimension) then exports.UCDdx:del("welcometolv") if (t and isTimer(t)) then t:destroy() t = nil end end end )
UCDmafiaWars
UCDmafiaWars - Fixed debug from LV switching with timer. - Fixed to work with new dx side bar.
Lua
mit
nokizorque/ucd,nokizorque/ucd
638467f8791ba7752eb3f201a853c7f8d7345e09
build/scripts/actions/codeblocks/codeblocks_project.lua
build/scripts/actions/codeblocks/codeblocks_project.lua
-- -- codeblocks_cbp.lua -- Generate a Code::Blocks C/C++ project. -- Copyright (c) 2009, 2011 Jason Perkins and the Premake project -- local p = premake local project = p.project local config = p.config local tree = p.tree local codeblocks = p.modules.codeblocks codeblocks.project = {} local m = codeblocks.project m.elements = {} m.ctools = { gcc = "gcc", msc = "Visual C++", } function m.getcompilername(cfg) local tool = _OPTIONS.cc or cfg.toolset or p.GCC local toolset = p.tools[tool] if not toolset then error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") end return m.ctools[tool] end function m.getcompiler(cfg) local toolset = p.tools[_OPTIONS.cc or cfg.toolset or p.GCC] if not toolset then error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") end return toolset end function m.header(prj) _p('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>') _p('<CodeBlocks_project_file>') _p(1,'<FileVersion major="1" minor="6" />') -- write project block header _p(1,'<Project>') _p(2,'<Option title="%s" />', prj.name) _p(2,'<Option pch_mode="2" />') end function m.footer(prj) -- write project block footer _p(1,'</Project>') _p('</CodeBlocks_project_file>') end m.elements.project = function(prj) return { m.header, m.configurations, m.files, m.extensions, m.footer } end -- -- Project: Generate the CodeBlocks project file. -- function m.generate(prj) p.utf8() p.callArray(m.elements.project, prj) end function m.configurations(prj) -- write configuration blocks _p(2,'<Build>') local platforms = {} for cfg in project.eachconfig(prj) do local found = false for k,v in pairs(platforms) do if (v.platform == cfg.platform) then table.insert(v.configs, cfg) found = true break end end if (not found) then table.insert(platforms, {platform = cfg.platform, configs = {cfg}}) end end for k,platform in pairs(platforms) do for k,cfg in pairs(platform.configs) do local compiler = m.getcompiler(cfg) _p(3,'<Target title="%s">', cfg.longname) _p(4,'<Option output="%s" prefix_auto="0" extension_auto="0" />', p.esc(cfg.buildtarget.relpath)) if cfg.debugdir then _p(4,'<Option working_dir="%s" />', p.esc(cfg.debugdir)) end _p(4,'<Option object_output="%s" />', p.esc(cfg.objectsdir)) -- identify the type of binary local types = { WindowedApp = 0, ConsoleApp = 1, StaticLib = 2, SharedLib = 3 } _p(4,'<Option type="%d" />', types[cfg.kind]) _p(4,'<Option compiler="%s" />', m.getcompilername(cfg)) if (cfg.kind == "SharedLib") then _p(4,'<Option createDefFile="0" />') _p(4,'<Option createStaticLib="%s" />', iif(cfg.flags.NoImportLib, 0, 1)) end -- begin compiler block -- _p(4,'<Compiler>') for _,flag in ipairs(table.join(compiler.getcflags(cfg), compiler.getcxxflags(cfg), compiler.getdefines(cfg.defines), cfg.buildoptions)) do _p(5,'<Add option="%s" />', p.esc(flag)) end if not cfg.flags.NoPCH and cfg.pchheader then _p(5,'<Add option="-Winvalid-pch" />') _p(5,'<Add option="-include &quot;%s&quot;" />', p.esc(cfg.pchheader)) end for _,v in ipairs(cfg.includedirs) do _p(5,'<Add directory="%s" />', p.esc(path.getrelative(prj.location, v))) end _p(4,'</Compiler>') -- end compiler block -- -- begin linker block -- _p(4,'<Linker>') for _,flag in ipairs(table.join(compiler.getldflags(cfg), cfg.linkoptions)) do _p(5,'<Add option="%s" />', p.esc(flag)) end for _,v in ipairs(config.getlinks(cfg, "all", "directory")) do _p(5,'<Add directory="%s" />', p.esc(v)) end for _,v in ipairs(config.getlinks(cfg, "all", "basename")) do _p(5,'<Add library="%s" />', p.esc(v)) end _p(4,'</Linker>') -- end linker block -- -- begin resource compiler block -- if config.findfile(cfg, ".rc") then _p(4,'<ResourceCompiler>') for _,v in ipairs(cfg.includedirs) do _p(5,'<Add directory="%s" />', p.esc(v)) end for _,v in ipairs(cfg.resincludedirs) do _p(5,'<Add directory="%s" />', p.esc(v)) end _p(4,'</ResourceCompiler>') end -- end resource compiler block -- -- begin build steps -- if #cfg.prebuildcommands > 0 or #cfg.postbuildcommands > 0 then _p(4,'<ExtraCommands>') for _,v in ipairs(cfg.prebuildcommands) do _p(5,'<Add before="%s" />', p.esc(v)) end for _,v in ipairs(cfg.postbuildcommands) do _p(5,'<Add after="%s" />', p.esc(v)) end _p(4,'</ExtraCommands>') end -- end build steps -- _p(3,'</Target>') end end _p(2,'</Build>') end -- -- Write out a list of the source code files in the project. -- function m.files(prj) local pchheader if (prj.pchheader) then pchheader = path.getrelative(prj.location, prj.pchheader) end local tr = project.getsourcetree(prj) tree.traverse(tr, { -- source files are handled at the leaves onleaf = function(node, depth) if node.relpath == node.vpath then _p(2,'<Unit filename="%s">', node.relpath) else _p(2,'<Unit filename="%s">', node.name) _p(3,'<Option virtualFolder="%s" />', path.getdirectory(node.vpath)) end if path.isresourcefile(node.name) then _p(3,'<Option compilerVar="WINDRES" />') elseif path.iscfile(node.name) and prj.language == "C++" then _p(3,'<Option compilerVar="CC" />') end if not prj.flags.NoPCH and node.name == pchheader then _p(3,'<Option compilerVar="%s" />', iif(prj.language == "C", "CC", "CPP")) _p(3,'<Option compile="1" />') _p(3,'<Option weight="0" />') _p(3,'<Add option="-x c++-header" />') end _p(2,'</Unit>') end, }, false, 1) end function m.extensions(prj) for cfg in project.eachconfig(prj) do if cfg.debugenvs and #cfg.debugenvs > 0 then --Assumption: if gcc is being used then so is gdb although this section will be ignored by --other debuggers. If using gcc and not gdb it will silently not pass the --environment arguments to the debugger if m.getcompilername(cfg) == "gcc" then _p(3,'<debugger>') _p(4,'<remote_debugging target="%s">', p.esc(cfg.longname)) local args = '' local sz = #cfg.debugenvs for idx, v in ipairs(cfg.debugenvs) do args = args .. 'set env ' .. v if sz ~= idx then args = args .. '&#x0A;' end end _p(5,'<options additional_cmds_before="%s" />',args) _p(4,'</remote_debugging>') _p(3,'</debugger>') else error('Sorry at this moment there is no support for debug environment variables with this debugger and codeblocks') end end end end
-- -- codeblocks_cbp.lua -- Generate a Code::Blocks C/C++ project. -- Copyright (c) 2009, 2011 Jason Perkins and the Premake project -- local p = premake local project = p.project local config = p.config local tree = p.tree local codeblocks = p.modules.codeblocks codeblocks.project = {} local m = codeblocks.project m.elements = {} m.ctools = { gcc = "gcc", msc = "Visual C++", } function m.getcompilername(cfg) local tool = _OPTIONS.cc or cfg.toolset or p.GCC local toolset = p.tools[tool] if not toolset then error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") end return m.ctools[tool] end function m.getcompiler(cfg) local toolset = p.tools[_OPTIONS.cc or cfg.toolset or p.GCC] if not toolset then error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") end return toolset end function m.header(prj) _p('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>') _p('<CodeBlocks_project_file>') _p(1,'<FileVersion major="1" minor="6" />') -- write project block header _p(1,'<Project>') _p(2,'<Option title="%s" />', prj.name) _p(2,'<Option pch_mode="2" />') end function m.footer(prj) -- write project block footer _p(1,'</Project>') _p('</CodeBlocks_project_file>') end m.elements.project = function(prj) return { m.header, m.configurations, m.files, m.extensions, m.footer } end -- -- Project: Generate the CodeBlocks project file. -- function m.generate(prj) p.utf8() p.callArray(m.elements.project, prj) end function m.configurations(prj) -- write configuration blocks _p(2,'<Build>') local platforms = {} for cfg in project.eachconfig(prj) do local found = false for k,v in pairs(platforms) do if (v.platform == cfg.platform) then table.insert(v.configs, cfg) found = true break end end if (not found) then table.insert(platforms, {platform = cfg.platform, configs = {cfg}}) end end for k,platform in pairs(platforms) do for k,cfg in pairs(platform.configs) do local compiler = m.getcompiler(cfg) _p(3,'<Target title="%s">', cfg.longname) _p(4,'<Option output="%s" prefix_auto="0" extension_auto="0" />', p.esc(cfg.buildtarget.relpath)) if cfg.debugdir then _p(4,'<Option working_dir="%s" />', p.esc(path.getrelative(prj.location, cfg.debugdir))) end _p(4,'<Option object_output="%s" />', p.esc(path.getrelative(prj.location, cfg.objdir))) -- identify the type of binary local types = { WindowedApp = 0, ConsoleApp = 1, StaticLib = 2, SharedLib = 3 } _p(4,'<Option type="%d" />', types[cfg.kind]) _p(4,'<Option compiler="%s" />', m.getcompilername(cfg)) if (cfg.kind == "SharedLib") then _p(4,'<Option createDefFile="0" />') _p(4,'<Option createStaticLib="%s" />', iif(cfg.flags.NoImportLib, 0, 1)) end -- begin compiler block -- _p(4,'<Compiler>') for _,flag in ipairs(table.join(compiler.getcflags(cfg), compiler.getcxxflags(cfg), compiler.getdefines(cfg.defines), cfg.buildoptions)) do _p(5,'<Add option="%s" />', p.esc(flag)) end if not cfg.flags.NoPCH and cfg.pchheader then _p(5,'<Add option="-Winvalid-pch" />') _p(5,'<Add option="-include &quot;%s&quot;" />', p.esc(cfg.pchheader)) end for _,v in ipairs(cfg.includedirs) do _p(5,'<Add directory="%s" />', p.esc(path.getrelative(prj.location, v))) end _p(4,'</Compiler>') -- end compiler block -- -- begin linker block -- _p(4,'<Linker>') for _,flag in ipairs(table.join(compiler.getldflags(cfg), cfg.linkoptions)) do _p(5,'<Add option="%s" />', p.esc(flag)) end for _,v in ipairs(config.getlinks(cfg, "all", "directory")) do _p(5,'<Add directory="%s" />', p.esc(v)) end for _,v in ipairs(config.getlinks(cfg, "all", "basename")) do _p(5,'<Add library="%s" />', p.esc(v)) end _p(4,'</Linker>') -- end linker block -- -- begin resource compiler block -- if config.findfile(cfg, ".rc") then _p(4,'<ResourceCompiler>') for _,v in ipairs(cfg.includedirs) do _p(5,'<Add directory="%s" />', p.esc(v)) end for _,v in ipairs(cfg.resincludedirs) do _p(5,'<Add directory="%s" />', p.esc(v)) end _p(4,'</ResourceCompiler>') end -- end resource compiler block -- -- begin build steps -- if #cfg.prebuildcommands > 0 or #cfg.postbuildcommands > 0 then _p(4,'<ExtraCommands>') for _,v in ipairs(cfg.prebuildcommands) do _p(5,'<Add before="%s" />', p.esc(v)) end for _,v in ipairs(cfg.postbuildcommands) do _p(5,'<Add after="%s" />', p.esc(v)) end _p(4,'</ExtraCommands>') end -- end build steps -- _p(3,'</Target>') end end _p(2,'</Build>') end -- -- Write out a list of the source code files in the project. -- function m.files(prj) local pchheader if (prj.pchheader) then pchheader = path.getrelative(prj.location, prj.pchheader) end local tr = project.getsourcetree(prj) tree.traverse(tr, { -- source files are handled at the leaves onleaf = function(node, depth) if node.relpath == node.vpath then _p(2,'<Unit filename="%s">', node.relpath) else _p(2,'<Unit filename="%s">', node.name) _p(3,'<Option virtualFolder="%s" />', path.getdirectory(node.vpath)) end if path.isresourcefile(node.name) then _p(3,'<Option compilerVar="WINDRES" />') elseif path.iscfile(node.name) and prj.language == "C++" then _p(3,'<Option compilerVar="CC" />') end if not prj.flags.NoPCH and node.name == pchheader then _p(3,'<Option compilerVar="%s" />', iif(prj.language == "C", "CC", "CPP")) _p(3,'<Option compile="1" />') _p(3,'<Option weight="0" />') _p(3,'<Add option="-x c++-header" />') end _p(2,'</Unit>') end, }, false, 1) end function m.extensions(prj) for cfg in project.eachconfig(prj) do if cfg.debugenvs and #cfg.debugenvs > 0 then --Assumption: if gcc is being used then so is gdb although this section will be ignored by --other debuggers. If using gcc and not gdb it will silently not pass the --environment arguments to the debugger if m.getcompilername(cfg) == "gcc" then _p(3,'<debugger>') _p(4,'<remote_debugging target="%s">', p.esc(cfg.longname)) local args = '' local sz = #cfg.debugenvs for idx, v in ipairs(cfg.debugenvs) do args = args .. 'set env ' .. v if sz ~= idx then args = args .. '&#x0A;' end end _p(5,'<options additional_cmds_before="%s" />',args) _p(4,'</remote_debugging>') _p(3,'</debugger>') else error('Sorry at this moment there is no support for debug environment variables with this debugger and codeblocks') end end end end
Build: Fix codeblocks debug and object directory
Build: Fix codeblocks debug and object directory
Lua
mit
DigitalPulseSoftware/NazaraEngine
665eebb6117daa69189e84277168b7d2f13d7ec0
lua_modules/luvit-rackspace-monitoring-client/lib/client.lua
lua_modules/luvit-rackspace-monitoring-client/lib/client.lua
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local JSON = require('json') local Object = require('core').Object local string = require('string') local fmt = require('string').format local https = require('https') local url = require('url') local table = require('table') local Error = require('core').Error local async = require('async') local misc = require('./misc') local errors = require('./errors') local KeystoneClient = require('keystone').Client local MAAS_CLIENT_KEYSTONE_URL = 'https://identity.api.rackspacecloud.com/v2.0' local MAAS_CLIENT_DEFAULT_HOST = 'monitoring.api.rackspacecloud.com' local MAAS_CLIENT_DEFAULT_VERSION = 'v1.0' --[[ ClientBase ]]-- local ClientBase = Object:extend() function ClientBase:initialize(host, port, version, apiType, options) local headers = {} self.host = host self.port = port self.version = version self.apiType = apiType self.tenantId = nil if self.apiType == 'public' then headers['User-Agent'] = 'agent/virgo' end self.headers = headers self.options = misc.merge({}, options) self.headers['Accept'] = 'application/json' self.headers['Content-Type'] = 'application/json' end function ClientBase:setToken(token, expiry) self.token = token self.headers['X-Auth-Token'] = token self._tokenExpiry = expiry end function ClientBase:setTenantId(tenantId) self.tenantId = tenantId end function ClientBase:_parseResponse(data, callback) local parsed = JSON.parse(data) callback(nil, parsed) end function ClientBase:_parseData(data) local res = { xpcall(function() return JSON.parse(data) end, function(e) return e end) } if res[1] == false then return res[2] else return JSON.parse(res[2]) end end function ClientBase:request(method, path, payload, expectedStatusCode, callback) local options local headers local extraHeaders = {} -- setup payload if payload then if type(payload) == 'table' and self.headers['Content-Type'] == 'application/json' then payload = JSON.stringify(payload) end extraHeaders['Content-Length'] = #payload else extraHeaders['Content-Length'] = 0 end -- setup path if self.tenantId then path = fmt('/%s/%s%s', self.version, self.tenantId, path) else path = fmt('/%s%s', self.version, path) end headers = misc.merge(self.headers, extraHeaders) options = { host = self.host, port = self.port, path = path, headers = headers, method = method } local req = https.request(options, function(res) local data = '' res:on('data', function(chunk) data = data .. chunk end) res:on('end', function() self._lastRes = res if res.statusCode ~= expectedStatusCode then data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) else if res.statusCode == 200 then self:_parseResponse(data, callback) elseif res.statusCode == 201 or res.statusCode == 204 then callback(nil, res.headers['location']) else data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) end end end) end) if payload then req:write(payload) end req:done() end --[[ Client ]]-- local Client = ClientBase:extend() function Client:initialize(userId, key, options) options = options or {} self.userId = userId self.key = key self.authUrl = options.authUrl self.entities = {} self.agent_tokens = {} self:_init() ClientBase.initialize(self, MAAS_CLIENT_DEFAULT_HOST, 443, MAAS_CLIENT_DEFAULT_VERSION, 'public', options) end function Client:_init() self.entities.get = function(callback) self:request('GET', '/entities', nil, 200, callback) end self.agent_tokens.get = function(callback) self:request('GET', '/agent_tokens', nil, 200, callback) end self.agent_tokens.create = function(options, callback) local body = {} body['label'] = options.label self:request('POST', '/agent_tokens', body, 201, function(err, tokenUrl) if err then callback(err) return end callback(nil, string.match(tokenUrl, 'agent_tokens/(.*)')) end) end end function Client:auth(authUrl, username, keyOrPassword, callback) local apiKeyClient = KeystoneClient:new(authUrl, { username = self.userId, apikey = keyOrPassword }) local passwordClient = KeystoneClient:new(authUrl, { username = self.userId, password = keyOrPassword }) local errors = {} local responses = {} function iterator(client, callback) client:tenantIdAndToken(function(err, obj) if err then table.insert(errors, err) callback() else table.insert(responses, obj) callback() end end) end async.forEach({ apiKeyClient, passwordClient }, iterator, function() if #responses > 0 then callback(nil, responses[1]) else callback(errors) end end) end --[[ The request. callback.function(err, results) ]]-- function Client:request(method, path, payload, expectedStatusCode, callback) local authUrl = self.authUrl or MAAS_CLIENT_KEYSTONE_URL local authPayload local results async.waterfall({ function(callback) if self:tokenValid() then callback() return end self:auth(authUrl, self.userId, self.key, function(err, obj) if err then callback(err) return end self:setToken(obj.token, obj.expires) self:setTenantId(obj.tenantId) callback() end) end, function(callback) ClientBase.request(self, method, path, payload, expectedStatusCode, function(err, obj) if not err then results = obj end callback(err) end) end }, function(err) callback(err, results) end) end function Client:tokenValid() if self.token then return true end -- TODO add support for expiry return nil end local exports = {} exports.Client = Client return exports
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local JSON = require('json') local Object = require('core').Object local string = require('string') local fmt = require('string').format local https = require('https') local url = require('url') local table = require('table') local Error = require('core').Error local async = require('async') local misc = require('./misc') local errors = require('./errors') local KeystoneClient = require('keystone').Client local MAAS_CLIENT_KEYSTONE_URL = 'https://identity.api.rackspacecloud.com/v2.0' local MAAS_CLIENT_DEFAULT_HOST = 'monitoring.api.rackspacecloud.com' local MAAS_CLIENT_DEFAULT_VERSION = 'v1.0' --[[ ClientBase ]]-- local ClientBase = Object:extend() function ClientBase:initialize(host, port, version, apiType, options) local headers = {} self.host = host self.port = port self.version = version self.apiType = apiType self.tenantId = nil if self.apiType == 'public' then headers['User-Agent'] = 'agent/virgo' end self.headers = headers self.options = misc.merge({}, options) self.headers['Accept'] = 'application/json' self.headers['Content-Type'] = 'application/json' end function ClientBase:setToken(token, expiry) self.token = token self.headers['X-Auth-Token'] = token self._tokenExpiry = expiry end function ClientBase:setTenantId(tenantId) self.tenantId = tenantId end function ClientBase:_parseResponse(data, callback) local parsed = JSON.parse(data) callback(nil, parsed) end function ClientBase:_parseData(data) local res = { xpcall(function() return JSON.parse(data) end, function(e) return e end) } if res[1] == false then return res[2] else return JSON.parse(res[2]) end end function ClientBase:request(method, path, payload, expectedStatusCode, callback) local options local headers local extraHeaders = {} -- setup payload if payload then if type(payload) == 'table' and self.headers['Content-Type'] == 'application/json' then payload = JSON.stringify(payload) end extraHeaders['Content-Length'] = #payload else extraHeaders['Content-Length'] = 0 end -- setup path if self.tenantId then path = fmt('/%s/%s%s', self.version, self.tenantId, path) else path = fmt('/%s%s', self.version, path) end headers = misc.merge(self.headers, extraHeaders) options = { host = self.host, port = self.port, path = path, headers = headers, method = method } local req = https.request(options, function(res) local data = '' res:on('data', function(chunk) data = data .. chunk end) res:on('end', function() self._lastRes = res if res.statusCode ~= expectedStatusCode then callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) else if res.statusCode == 200 then self:_parseResponse(data, callback) elseif res.statusCode == 201 or res.statusCode == 204 then callback(nil, res.headers['location']) else data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) end end end) end) if payload then req:write(payload) end req:done() end --[[ Client ]]-- local Client = ClientBase:extend() function Client:initialize(userId, key, options) options = options or {} self.userId = userId self.key = key self.authUrl = options.authUrl self.entities = {} self.agent_tokens = {} self:_init() ClientBase.initialize(self, MAAS_CLIENT_DEFAULT_HOST, 443, MAAS_CLIENT_DEFAULT_VERSION, 'public', options) end function Client:_init() self.entities.get = function(callback) self:request('GET', '/entities', nil, 200, callback) end self.agent_tokens.get = function(callback) self:request('GET', '/agent_tokens', nil, 200, callback) end self.agent_tokens.create = function(options, callback) local body = {} body['label'] = options.label self:request('POST', '/agent_tokens', body, 201, function(err, tokenUrl) if err then callback(err) return end callback(nil, string.match(tokenUrl, 'agent_tokens/(.*)')) end) end end function Client:auth(authUrl, username, keyOrPassword, callback) local apiKeyClient = KeystoneClient:new(authUrl, { username = self.userId, apikey = keyOrPassword }) local passwordClient = KeystoneClient:new(authUrl, { username = self.userId, password = keyOrPassword }) local errors = {} local responses = {} function iterator(client, callback) client:tenantIdAndToken(function(err, obj) if err then table.insert(errors, err) callback() else table.insert(responses, obj) callback() end end) end async.forEach({ apiKeyClient, passwordClient }, iterator, function() if #responses > 0 then callback(nil, responses[1]) else callback(errors) end end) end --[[ The request. callback.function(err, results) ]]-- function Client:request(method, path, payload, expectedStatusCode, callback) local authUrl = self.authUrl or MAAS_CLIENT_KEYSTONE_URL local authPayload local results async.waterfall({ function(callback) if self:tokenValid() then callback() return end self:auth(authUrl, self.userId, self.key, function(err, obj) if err then callback(err) return end self:setToken(obj.token, obj.expires) self:setTenantId(obj.tenantId) callback() end) end, function(callback) ClientBase.request(self, method, path, payload, expectedStatusCode, function(err, obj) if not err then results = obj end callback(err) end) end }, function(err) callback(err, results) end) end function Client:tokenValid() if self.token then return true end -- TODO add support for expiry return nil end local exports = {} exports.Client = Client return exports
rackspace-monitoring-client: bump client for parse fix
rackspace-monitoring-client: bump client for parse fix
Lua
apache-2.0
kans/birgo,kans/birgo,kans/birgo,kans/birgo,kans/birgo
94380a19d41c327bd27b24f568ddaa0934320f20
timeseries/insert.lua
timeseries/insert.lua
pathtest = string.match(test, "(.*/)") or "" dofile(pathtest .. "common.lua") function thread_init(thread_id) set_vars() init_ts = os.time() end function event(thread_id) db_bulk_insert_init("INSERT INTO sensordata(ts, sensor_id, data1,data2,data3,data4,data5,cnt) VALUES") for j = sensors_per_thread*thread_id, sensors_per_thread*(thread_id+1)-1 do db_bulk_insert_next("("..init_ts.."," .. j .. ",".. sb_rand_uniform(1,10000).."/"..sb_rand_uniform(1,10000).. ",".. sb_rand_uniform(1,10000).."/"..sb_rand_uniform(1,10000)..",".. sb_rand_uniform(1,10000).."/"..sb_rand_uniform(1,10000)..",".. sb_rand_uniform(1,10000).."/"..sb_rand_uniform(1,10000)..",".. sb_rand_uniform(1,10000)/sb_rand_uniform(1,10000)..","..sb_rand_uniform(30,90)..")") end init_ts = init_ts + 1 db_bulk_insert_done() end
pathtest = string.match(test, "(.*/)") or "" dofile(pathtest .. "common.lua") function thread_init(thread_id) set_vars() init_ts = os.time() end function event(thread_id) db_bulk_insert_init("INSERT INTO sensordata(ts, sensor_id, data1,data2,data3,data4,data5,cnt) VALUES") for j = sensors_per_thread*thread_id, sensors_per_thread*(thread_id+1)-1 do db_bulk_insert_next("("..init_ts.."," .. j .. ",".. sb_rand(1,1000).."/10,".. sb_rand(1,1000).."/10,".. sb_rand(1,1000).."/10,".. sb_rand(1,1000).."/10,".. sb_rand(1,1000).."/10,"..sb_rand(40,60)..")") end init_ts = init_ts + 1 db_bulk_insert_done() end
Fix insert workload
Fix insert workload
Lua
bsd-2-clause
percona/sysbench-scripts
c8e83565addad6ca85d9a6c0386dae52409791cc
xmake/scripts/base/os.lua
xmake/scripts/base/os.lua
--!The Automatic Cross-platform Build Tool -- -- XMake 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. -- -- XMake 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 XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2009 - 2015, ruki All rights reserved. -- -- @author ruki -- @file os.lua -- -- define module: os local os = os or {} -- load modules local path = require("base/path") local utils = require("base/utils") local string = require("base/string") -- match files or directories -- -- @param pattern the search pattern -- uses "*" to match any part of a file or directory name, -- uses "**" to recurse into subdirectories. -- -- @param findir true: find directory, false: find file -- @return the result array and count -- -- @code -- local dirs, count = os.match("./src/*", true) -- local files, count = os.match("./src/**.c") -- local file = os.match("./src/test.c") -- @endcode -- function os.match(pattern, findir) -- get the excludes local excludes = pattern:match("|.*$") if excludes then excludes = excludes:split("|") end -- translate excludes if excludes then local _excludes = {} for _, exclude in ipairs(excludes) do exclude = path.translate(exclude) exclude = exclude:gsub("([%+%.%-%^%$%(%)%%])", "%%%1") exclude = exclude:gsub("%*%*", "\001") exclude = exclude:gsub("%*", "\002") exclude = exclude:gsub("\001", ".*") exclude = exclude:gsub("\002", "[^/]*") table.insert(_excludes, exclude) end excludes = _excludes end -- translate path and remove some repeat separators pattern = path.translate(pattern:gsub("|.*$", "")) -- get the root directory local rootdir = pattern local starpos = pattern:find("%*") if starpos then rootdir = rootdir:sub(1, starpos - 1) end rootdir = path.directory(rootdir) -- is recurse? local recurse = pattern:find("**", nil, true) -- convert pattern to a lua pattern pattern = pattern:gsub("([%+%.%-%^%$%(%)%%])", "%%%1") pattern = pattern:gsub("%*%*", "\001") pattern = pattern:gsub("%*", "\002") pattern = pattern:gsub("\001", ".*") pattern = pattern:gsub("\002", "[^/]*") -- find it return os.find(rootdir, pattern, recurse, findir, excludes) end -- copy file or directory function os.cp(src, dst) -- check assert(src and dst) -- is file? if os.isfile(src) then -- the destination is directory? append the filename if os.isdir(dst) then dst = string.format("%s/%s", dst, path.filename(src)) end -- copy file if not os.cpfile(src, dst) then return false, string.format("cannot copy file %s to %s %s", src, dst, os.strerror()) end -- is directory? elseif os.isdir(src) then -- copy directory if not os.cpdir(src, dst) then return false, string.format("cannot copy directory %s to %s %s", src, dst, os.strerror()) end -- cp dir/*? elseif src:find("%*") then -- get the root directory local starpos = src:find("%*") -- match all files local files = os.match((src:gsub("%*+", "**"))) if files then for _, file in ipairs(files) do local dstfile = string.format("%s/%s", dst, file:sub(starpos)) if not os.cpfile(file, dstfile) then return false, string.format("cannot copy file %s to %s %s", file, dstfile, os.strerror()) end end end -- not exists? else return false, string.format("cannot copy file %s, not found this file %s", src, os.strerror()) end -- ok return true end -- move file or directory function os.mv(src, dst) -- check assert(src and dst) -- exists file or directory? if os.exists(src) then -- move file or directory if not os.rename(src, dst) then return false, string.format("cannot move %s to %s %s", src, dst, os.strerror()) end -- not exists? else return false, string.format("cannot move %s to %s, not found this file %s", src, dst, os.strerror()) end -- ok return true end -- remove file or directory function os.rm(path) -- check assert(path) -- is file? if os.isfile(path) then -- remove file if not os.rmfile(path) then return false, string.format("cannot remove file %s %s", path, os.strerror()) end -- is directory? elseif os.isdir(path) then -- remove directory if not os.rmdir(path) then return false, string.format("cannot remove directory %s %s", path, os.strerror()) end -- not exists? else return false, string.format("cannot remove file %s, not found this file %s", path, os.strerror()) end -- ok return true end -- change to directory function os.cd(path) -- check assert(path) -- change to the previous directory? if path == "-" then -- exists the previous directory? if os._PREDIR then path = os._PREDIR os._PREDIR = nil else -- error return false, string.format("not found the previous directory %s", os.strerror()) end end -- is directory? if os.isdir(path) then -- get the current directory local current = os.curdir() -- change to directory if not os.chdir(path) then return false, string.format("cannot change directory %s %s", path, os.strerror()) end -- save the previous directory os._PREDIR = current -- not exists? else return false, string.format("cannot change directory %s, not found this directory %s", path, os.strerror()) end -- ok return true end -- return module: os return os
--!The Automatic Cross-platform Build Tool -- -- XMake 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. -- -- XMake 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 XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2009 - 2015, ruki All rights reserved. -- -- @author ruki -- @file os.lua -- -- define module: os local os = os or {} -- load modules local path = require("base/path") local utils = require("base/utils") local string = require("base/string") -- match files or directories -- -- @param pattern the search pattern -- uses "*" to match any part of a file or directory name, -- uses "**" to recurse into subdirectories. -- -- @param findir true: find directory, false: find file -- @return the result array and count -- -- @code -- local dirs, count = os.match("./src/*", true) -- local files, count = os.match("./src/**.c") -- local file = os.match("./src/test.c") -- @endcode -- function os.match(pattern, findir) -- get the excludes local excludes = pattern:match("|.*$") if excludes then excludes = excludes:split("|") end -- translate excludes if excludes then local _excludes = {} for _, exclude in ipairs(excludes) do exclude = path.translate(exclude) exclude = exclude:gsub("([%+%.%-%^%$%(%)%%])", "%%%1") exclude = exclude:gsub("%*%*", "\001") exclude = exclude:gsub("%*", "\002") exclude = exclude:gsub("\001", ".*") exclude = exclude:gsub("\002", "[^/]*") table.insert(_excludes, exclude) end excludes = _excludes end -- translate path and remove some repeat separators pattern = path.translate(pattern:gsub("|.*$", "")) -- get the root directory local rootdir = pattern local starpos = pattern:find("%*") if starpos then rootdir = rootdir:sub(1, starpos - 1) end rootdir = path.directory(rootdir) -- is recurse? local recurse = pattern:find("**", nil, true) -- convert pattern to a lua pattern pattern = pattern:gsub("([%+%.%-%^%$%(%)%%])", "%%%1") pattern = pattern:gsub("%*%*", "\001") pattern = pattern:gsub("%*", "\002") pattern = pattern:gsub("\001", ".*") pattern = pattern:gsub("\002", "[^/]*") -- patch "./" for matching ok if root directory is '.' if rootdir == '.' then pattern = "./" .. pattern end -- find it return os.find(rootdir, pattern, recurse, findir, excludes) end -- copy file or directory function os.cp(src, dst) -- check assert(src and dst) -- is file? if os.isfile(src) then -- the destination is directory? append the filename if os.isdir(dst) then dst = string.format("%s/%s", dst, path.filename(src)) end -- copy file if not os.cpfile(src, dst) then return false, string.format("cannot copy file %s to %s %s", src, dst, os.strerror()) end -- is directory? elseif os.isdir(src) then -- copy directory if not os.cpdir(src, dst) then return false, string.format("cannot copy directory %s to %s %s", src, dst, os.strerror()) end -- cp dir/*? elseif src:find("%*") then -- get the root directory local starpos = src:find("%*") -- match all files local files = os.match((src:gsub("%*+", "**"))) if files then for _, file in ipairs(files) do local dstfile = string.format("%s/%s", dst, file:sub(starpos)) if not os.cpfile(file, dstfile) then return false, string.format("cannot copy file %s to %s %s", file, dstfile, os.strerror()) end end end -- not exists? else return false, string.format("cannot copy file %s, not found this file %s", src, os.strerror()) end -- ok return true end -- move file or directory function os.mv(src, dst) -- check assert(src and dst) -- exists file or directory? if os.exists(src) then -- move file or directory if not os.rename(src, dst) then return false, string.format("cannot move %s to %s %s", src, dst, os.strerror()) end -- not exists? else return false, string.format("cannot move %s to %s, not found this file %s", src, dst, os.strerror()) end -- ok return true end -- remove file or directory function os.rm(path) -- check assert(path) -- is file? if os.isfile(path) then -- remove file if not os.rmfile(path) then return false, string.format("cannot remove file %s %s", path, os.strerror()) end -- is directory? elseif os.isdir(path) then -- remove directory if not os.rmdir(path) then return false, string.format("cannot remove directory %s %s", path, os.strerror()) end -- not exists? else return false, string.format("cannot remove file %s, not found this file %s", path, os.strerror()) end -- ok return true end -- change to directory function os.cd(path) -- check assert(path) -- change to the previous directory? if path == "-" then -- exists the previous directory? if os._PREDIR then path = os._PREDIR os._PREDIR = nil else -- error return false, string.format("not found the previous directory %s", os.strerror()) end end -- is directory? if os.isdir(path) then -- get the current directory local current = os.curdir() -- change to directory if not os.chdir(path) then return false, string.format("cannot change directory %s %s", path, os.strerror()) end -- save the previous directory os._PREDIR = current -- not exists? else return false, string.format("cannot change directory %s, not found this directory %s", path, os.strerror()) end -- ok return true end -- return module: os return os
fix os.match bug
fix os.match bug
Lua
apache-2.0
tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake
223dc19ec7960e70d68d9135415b447f63cd3ea5
CIFAR10/cifar10_L2.lua
CIFAR10/cifar10_L2.lua
--[[ Multiple meta-iterations for DrMAD on CIFAR10 ]] require 'torch' require 'sys' require 'image' local root = '../' local grad = require 'autograd' local utils = require(root .. 'models/utils.lua') local optim = require 'optim' local dl = require 'dataload' local xlua = require 'xlua' local c = require 'trepl.colorize' --local debugger = require 'fb.debugger' opt = lapp[[ -s,--save (default "logs") subdirectory to save logs -b,--batchSize (default 64) batch size -r,--learningRate (default 0.0001) learning rate --learningRateDecay (default 1e-7) learning rate decay --weightDecay (default 0.0005) weightDecay -m,--momentum (default 0.9) momentum --epoch_step (default 25) epoch step --model (default vgg) model name --max_epoch (default 300) maximum number of iterations --backend (default nn) backend --mode (default L2) L2/L1/learningrate --type (default cuda) cuda/float/cl --numMeta (default 3) #episode --hLR (default 0.0001) learningrate of hyperparameter --initHyper (default 0.001) initial value for hyperparameter ]] print(c.blue "==> " .. "parameter:") print(opt) grad.optimize(true) -- Load in MNIST print(c.blue '==>' ..' loading data') local trainset, validset, testset = dl.loadCIFAR10() local classes = testset.classes local confusionMatrix = optim.ConfusionMatrix(classes) print(c.blue ' completed!') local predict, model, modelf, dfTrain, params, initParams, params_l2 local hyper_params = {} local function cast(t) if opt.type == 'cuda' then require 'cunn' return t:cuda() elseif opt.type == 'float' then return t:float() elseif opt.type == 'cl' then require 'clnn' return t:cl() else error('Unknown type '..opt.type) end end local function L2_norm_create(params, initHyper) local hyper_L2 = {} for i = 1, #params do -- dimension = 1 is bias, do not need L2_reg if (params[i]:nDimension() > 1) then hyper_L2[i] = params[i]:clone():fill(initHyper) end end return hyper_L2 end local function L2_norm(params) -- print(params_l2, params[1]) local penalty = torch.sum(torch.cmul(params[1], params_l2[1])) -- local penalty = torch.sum(params[1]) -- local penalty = 0 -- for i = 1, #params do -- -- dimension = 1 is bias, do not need L2_reg -- if (params[i]:nDimension() > 1) then -- print(i) -- penalty = penalty + torch.sum(params[i]) * params_l2[i] -- end -- end return penalty end local function init(iter) ---- --- build VGG net. ---- if iter == 1 then -- load model print(c.blue '==>' ..' configuring model') model = cast(dofile(root .. 'models/'..opt.model..'.lua')) -- cast a model using functionalize modelf, params = grad.functionalize(model) params_l2 = L2_norm_create(params, opt.initHyper) local Lossf = grad.nn.MSECriterion() local function fTrain(params, x, y) -- print(params) local prediction = modelf(params.p2, x) local penalty = L2_norm(params.p2) return Lossf(prediction, y) + penalty end dfTrain = grad(fTrain) -- a simple unit test local X = cast(torch.Tensor(64, 3, 32, 32):fill(0.5)) local Y = cast(torch.Tensor(64, 10):fill(0)) local p = { p1 = params_l2, p2 = params } local dparams, l = dfTrain(p, X, Y) if (l) then print(c.green ' Auto Diff works!') end print(c.blue ' completed!') end print(c.blue '==>' ..' initializing model') utils.MSRinit(model) print(c.blue ' completed!') -- copy initial weights for later computation initParams = utils.deepcopy(params) end local function train_meta(iter) --[[ One meta-iteration to get directives w.r.t. hyperparameters ]] ----------------------------------- -- [[Meta training]] ----------------------------------- -- Train a neural network to get final parameters for epoch = 1, opt.max_epoch do print(c.blue '==>' ..' Meta episode #' .. iter .. ', Training epoch #' .. epoch) for i, inputs, targets in trainset:subiter(opt.batchSize) do local function makesample(inputs, targets) local t_ = torch.FloatTensor(targets:size(1), 10):zero() for j = 1, targets:size(1) do t_[targets[j]] = 1 end return inputs:cuda(), t_:cuda() end local grads, loss = dfTrain(params, makesample(inputs, targets)) for i = 1, #grads do params[i] = params[i] + opt.learningRate * grads[i] end print(c.red 'loss: ', loss) end end -- copy final parameters after convergence local finalParams = utils.deepcopy(params) finalParams = nn.utils.recursiveCopy(finalParams, params) ----------------------- -- [[Reverse mode hyper-parameter training: -- to get gradient w.r.t. hyper-parameters]] ----------------------- end ----------------------------- -- entry point ----------------------------- local time = sys.clock() for i = 1, opt.numMeta do init(i) -- print("wtf", model) train_meta(i) end time = sys.clock() - time print(time)
--[[ Multiple meta-iterations for DrMAD on CIFAR10 ]] require 'torch' require 'sys' require 'image' local root = '../' local grad = require 'autograd' local utils = require(root .. 'models/utils.lua') local optim = require 'optim' local dl = require 'dataload' local xlua = require 'xlua' local c = require 'trepl.colorize' --local debugger = require 'fb.debugger' opt = lapp[[ -s,--save (default "logs") subdirectory to save logs -b,--batchSize (default 64) batch size -r,--learningRate (default 0.0001) learning rate --learningRateDecay (default 1e-7) learning rate decay --weightDecay (default 0.0005) weightDecay -m,--momentum (default 0.9) momentum --epoch_step (default 25) epoch step --model (default vgg) model name --max_epoch (default 300) maximum number of iterations --backend (default nn) backend --mode (default L2) L2/L1/learningrate --type (default cuda) cuda/float/cl --numMeta (default 3) #episode --hLR (default 0.0001) learningrate of hyperparameter --initHyper (default 0.001) initial value for hyperparameter ]] print(c.blue "==> " .. "parameter:") print(opt) grad.optimize(true) -- Load in MNIST print(c.blue '==>' ..' loading data') local trainset, validset, testset = dl.loadCIFAR10() local classes = testset.classes local confusionMatrix = optim.ConfusionMatrix(classes) print(c.blue ' completed!') local predict, model, modelf, dfTrain, params, initParams, params_l2 local hyper_params = {} local function cast(t) if opt.type == 'cuda' then require 'cunn' return t:cuda() elseif opt.type == 'float' then return t:float() elseif opt.type == 'cl' then require 'clnn' return t:cl() else error('Unknown type '..opt.type) end end local function L2_norm_create(params, initHyper) local hyper_L2 = {} for i = 1, #params do -- dimension = 1 is bias, do not need L2_reg if (params[i]:nDimension() > 1) then hyper_L2[i] = params[i]:clone():fill(initHyper) end end return hyper_L2 end local function L2_norm(params, params_l2) -- print(params_l2, params[1]) local penalty = torch.sum(torch.cmul(params[1], params_l2[1])) -- local penalty = torch.sum(params[1]) -- local penalty = 0 -- for i = 1, #params do -- -- dimension = 1 is bias, do not need L2_reg -- if (params[i]:nDimension() > 1) then -- print(i) -- penalty = penalty + torch.sum(params[i]) * params_l2[i] -- end -- end return penalty end local function init(iter) ---- --- build VGG net. ---- if iter == 1 then -- load model print(c.blue '==>' ..' configuring model') model = cast(dofile(root .. 'models/'..opt.model..'.lua')) -- cast a model using functionalize modelf, params = grad.functionalize(model) params_l2 = L2_norm_create(params, opt.initHyper) local Lossf = grad.nn.MSECriterion() local function fTrain(params, x, y) print(params.p1) print(params.p2) local prediction = modelf(params.p2, x) local penalty = L2_norm(params.p2, params.p1) return Lossf(prediction, y) + penalty end dfTrain = grad(fTrain) -- a simple unit test local X = cast(torch.Tensor(64, 3, 32, 32):fill(0.5)) local Y = cast(torch.Tensor(64, 10):fill(0)) local p = { p1 = params_l2, p2 = params } local dparams, l = dfTrain(p, X, Y) if (l) then print(c.green ' Auto Diff works!') end print(c.blue ' completed!') end print(c.blue '==>' ..' initializing model') utils.MSRinit(model) print(c.blue ' completed!') -- copy initial weights for later computation initParams = utils.deepcopy(params) end local function train_meta(iter) --[[ One meta-iteration to get directives w.r.t. hyperparameters ]] ----------------------------------- -- [[Meta training]] ----------------------------------- -- Train a neural network to get final parameters for epoch = 1, opt.max_epoch do print(c.blue '==>' ..' Meta episode #' .. iter .. ', Training epoch #' .. epoch) for i, inputs, targets in trainset:subiter(opt.batchSize) do local function makesample(inputs, targets) local t_ = torch.FloatTensor(targets:size(1), 10):zero() for j = 1, targets:size(1) do t_[targets[j]] = 1 end return inputs:cuda(), t_:cuda() end local p = { p1 = params_l2, p2 = params } local grads, loss = dfTrain(p, makesample(inputs, targets)) for i = 1, #grads do params[i] = params[i] + opt.learningRate * grads[i] end print(c.red 'loss: ', loss) end end -- copy final parameters after convergence local finalParams = utils.deepcopy(params) finalParams = nn.utils.recursiveCopy(finalParams, params) ----------------------- -- [[Reverse mode hyper-parameter training: -- to get gradient w.r.t. hyper-parameters]] ----------------------- end ----------------------------- -- entry point ----------------------------- local time = sys.clock() for i = 1, opt.numMeta do init(i) -- print("wtf", model) train_meta(i) end time = sys.clock() - time print(time)
Fix bug: all variables should be passed to the function.
Fix bug: all variables should be passed to the function.
Lua
mit
bigaidream-projects/drmad
01cd04fc7813b515be6772cc1f59939b30d7ff07
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 <[email protected]> Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- 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 <[email protected]> Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- 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
Lua
apache-2.0
LazyZhu/openwrt-luci-trunk-mod,cappiewu/luci,sujeet14108/luci,NeoRaider/luci,maxrio/luci981213,nwf/openwrt-luci,nwf/openwrt-luci,hnyman/luci,thess/OpenWrt-luci,openwrt/luci,oyido/luci,obsy/luci,cshore/luci,oneru/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,zhaoxx063/luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,LuttyYang/luci,nmav/luci,oyido/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,keyidadi/luci,bittorf/luci,urueedi/luci,artynet/luci,joaofvieira/luci,schidler/ionic-luci,rogerpueyo/luci,deepak78/new-luci,remakeelectric/luci,MinFu/luci,tobiaswaldvogel/luci,openwrt/luci,Kyklas/luci-proto-hso,981213/luci-1,male-puppies/luci,urueedi/luci,maxrio/luci981213,Hostle/luci,taiha/luci,kuoruan/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,cappiewu/luci,MinFu/luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,bright-things/ionic-luci,openwrt/luci,keyidadi/luci,Hostle/luci,harveyhu2012/luci,fkooman/luci,MinFu/luci,bright-things/ionic-luci,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,ff94315/luci-1,thesabbir/luci,fkooman/luci,rogerpueyo/luci,remakeelectric/luci,bittorf/luci,shangjiyu/luci-with-extra,keyidadi/luci,florian-shellfire/luci,marcel-sch/luci,cshore/luci,Wedmer/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,oyido/luci,palmettos/test,nwf/openwrt-luci,lcf258/openwrtcn,Noltari/luci,urueedi/luci,NeoRaider/luci,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,slayerrensky/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,hnyman/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,zhaoxx063/luci,Hostle/luci,keyidadi/luci,ollie27/openwrt_luci,jorgifumi/luci,aa65535/luci,wongsyrone/luci-1,david-xiao/luci,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,florian-shellfire/luci,nmav/luci,Wedmer/luci,opentechinstitute/luci,nmav/luci,opentechinstitute/luci,schidler/ionic-luci,maxrio/luci981213,jchuang1977/luci-1,sujeet14108/luci,bittorf/luci,obsy/luci,male-puppies/luci,david-xiao/luci,wongsyrone/luci-1,obsy/luci,dwmw2/luci,kuoruan/lede-luci,MinFu/luci,schidler/ionic-luci,zhaoxx063/luci,lcf258/openwrtcn,artynet/luci,nmav/luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,bittorf/luci,Kyklas/luci-proto-hso,dwmw2/luci,forward619/luci,marcel-sch/luci,lbthomsen/openwrt-luci,NeoRaider/luci,marcel-sch/luci,zhaoxx063/luci,lcf258/openwrtcn,palmettos/test,aa65535/luci,deepak78/new-luci,dwmw2/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,daofeng2015/luci,NeoRaider/luci,cappiewu/luci,chris5560/openwrt-luci,dismantl/luci-0.12,daofeng2015/luci,tcatm/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,thess/OpenWrt-luci,david-xiao/luci,lcf258/openwrtcn,dismantl/luci-0.12,teslamint/luci,oneru/luci,nmav/luci,urueedi/luci,Sakura-Winkey/LuCI,male-puppies/luci,daofeng2015/luci,oyido/luci,jlopenwrtluci/luci,Noltari/luci,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,Wedmer/luci,dwmw2/luci,david-xiao/luci,RedSnake64/openwrt-luci-packages,palmettos/test,db260179/openwrt-bpi-r1-luci,maxrio/luci981213,oyido/luci,slayerrensky/luci,nwf/openwrt-luci,maxrio/luci981213,thesabbir/luci,lbthomsen/openwrt-luci,ff94315/luci-1,joaofvieira/luci,bittorf/luci,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,cshore/luci,thess/OpenWrt-luci,jorgifumi/luci,ollie27/openwrt_luci,sujeet14108/luci,remakeelectric/luci,Wedmer/luci,daofeng2015/luci,LuttyYang/luci,maxrio/luci981213,keyidadi/luci,dismantl/luci-0.12,teslamint/luci,deepak78/new-luci,daofeng2015/luci,palmettos/test,slayerrensky/luci,jchuang1977/luci-1,LuttyYang/luci,openwrt/luci,ollie27/openwrt_luci,taiha/luci,opentechinstitute/luci,forward619/luci,cappiewu/luci,harveyhu2012/luci,joaofvieira/luci,joaofvieira/luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,bittorf/luci,Noltari/luci,forward619/luci,kuoruan/luci,openwrt-es/openwrt-luci,Wedmer/luci,joaofvieira/luci,Wedmer/luci,forward619/luci,aa65535/luci,RuiChen1113/luci,hnyman/luci,cappiewu/luci,taiha/luci,thess/OpenWrt-luci,jchuang1977/luci-1,RuiChen1113/luci,openwrt/luci,jchuang1977/luci-1,florian-shellfire/luci,cshore/luci,sujeet14108/luci,artynet/luci,cappiewu/luci,Kyklas/luci-proto-hso,kuoruan/lede-luci,tcatm/luci,wongsyrone/luci-1,tcatm/luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,palmettos/test,remakeelectric/luci,mumuqz/luci,urueedi/luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,joaofvieira/luci,deepak78/new-luci,schidler/ionic-luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,ff94315/luci-1,marcel-sch/luci,marcel-sch/luci,teslamint/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,aa65535/luci,keyidadi/luci,bright-things/ionic-luci,kuoruan/luci,Noltari/luci,palmettos/test,jchuang1977/luci-1,chris5560/openwrt-luci,jlopenwrtluci/luci,LuttyYang/luci,marcel-sch/luci,urueedi/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,harveyhu2012/luci,cshore-firmware/openwrt-luci,slayerrensky/luci,teslamint/luci,RuiChen1113/luci,thess/OpenWrt-luci,Hostle/luci,jorgifumi/luci,zhaoxx063/luci,florian-shellfire/luci,Hostle/luci,david-xiao/luci,forward619/luci,MinFu/luci,slayerrensky/luci,kuoruan/luci,artynet/luci,obsy/luci,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,oneru/luci,981213/luci-1,nwf/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,thess/OpenWrt-luci,jchuang1977/luci-1,teslamint/luci,jorgifumi/luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,dismantl/luci-0.12,oneru/luci,nmav/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,keyidadi/luci,cappiewu/luci,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,male-puppies/luci,db260179/openwrt-bpi-r1-luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,981213/luci-1,RuiChen1113/luci,schidler/ionic-luci,Hostle/openwrt-luci-multi-user,david-xiao/luci,fkooman/luci,hnyman/luci,ff94315/luci-1,Noltari/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,lcf258/openwrtcn,male-puppies/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,fkooman/luci,remakeelectric/luci,tobiaswaldvogel/luci,RuiChen1113/luci,maxrio/luci981213,mumuqz/luci,daofeng2015/luci,tcatm/luci,palmettos/cnLuCI,teslamint/luci,maxrio/luci981213,jchuang1977/luci-1,slayerrensky/luci,LuttyYang/luci,thess/OpenWrt-luci,mumuqz/luci,MinFu/luci,981213/luci-1,palmettos/test,ollie27/openwrt_luci,hnyman/luci,male-puppies/luci,opentechinstitute/luci,Kyklas/luci-proto-hso,cshore-firmware/openwrt-luci,mumuqz/luci,cappiewu/luci,taiha/luci,thesabbir/luci,slayerrensky/luci,urueedi/luci,dismantl/luci-0.12,981213/luci-1,harveyhu2012/luci,981213/luci-1,RuiChen1113/luci,dwmw2/luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,lcf258/openwrtcn,urueedi/luci,fkooman/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,RuiChen1113/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,sujeet14108/luci,Noltari/luci,hnyman/luci,jchuang1977/luci-1,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,oneru/luci,openwrt/luci,sujeet14108/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,kuoruan/lede-luci,chris5560/openwrt-luci,981213/luci-1,teslamint/luci,florian-shellfire/luci,jlopenwrtluci/luci,sujeet14108/luci,florian-shellfire/luci,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,nwf/openwrt-luci,zhaoxx063/luci,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,LuttyYang/luci,harveyhu2012/luci,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,Hostle/luci,oyido/luci,harveyhu2012/luci,ff94315/luci-1,Sakura-Winkey/LuCI,Hostle/openwrt-luci-multi-user,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,obsy/luci,nmav/luci,kuoruan/luci,schidler/ionic-luci,jlopenwrtluci/luci,wongsyrone/luci-1,deepak78/new-luci,cshore-firmware/openwrt-luci,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,dismantl/luci-0.12,palmettos/cnLuCI,Noltari/luci,fkooman/luci,rogerpueyo/luci,tcatm/luci,ollie27/openwrt_luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,jlopenwrtluci/luci,joaofvieira/luci,cshore/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,ff94315/luci-1,lcf258/openwrtcn,nmav/luci,opentechinstitute/luci,deepak78/new-luci,jlopenwrtluci/luci,Hostle/luci,artynet/luci,Hostle/luci,aa65535/luci,mumuqz/luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,fkooman/luci,dwmw2/luci,tcatm/luci,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,obsy/luci,palmettos/cnLuCI,thesabbir/luci,daofeng2015/luci,NeoRaider/luci,obsy/luci,rogerpueyo/luci,jorgifumi/luci,MinFu/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,thesabbir/luci,oyido/luci,male-puppies/luci,RuiChen1113/luci,thess/OpenWrt-luci,ff94315/luci-1,oyido/luci,aa65535/luci,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,oneru/luci,marcel-sch/luci,tcatm/luci,wongsyrone/luci-1,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,jorgifumi/luci,forward619/luci,Wedmer/luci,schidler/ionic-luci,palmettos/cnLuCI,aa65535/luci,RedSnake64/openwrt-luci-packages,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,kuoruan/luci,schidler/ionic-luci,taiha/luci,remakeelectric/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,taiha/luci,nmav/luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,kuoruan/lede-luci,deepak78/new-luci,florian-shellfire/luci,dwmw2/luci,bright-things/ionic-luci,slayerrensky/luci,kuoruan/luci,palmettos/cnLuCI,palmettos/test,ReclaimYourPrivacy/cloak-luci,oneru/luci,tobiaswaldvogel/luci,cshore/luci,jorgifumi/luci,opentechinstitute/luci,thesabbir/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,remakeelectric/luci,sujeet14108/luci,bittorf/luci,jorgifumi/luci,marcel-sch/luci,LuttyYang/luci,bright-things/ionic-luci,male-puppies/luci,NeoRaider/luci,mumuqz/luci,openwrt/luci,artynet/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,artynet/luci,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,fkooman/luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,remakeelectric/luci,ollie27/openwrt_luci,obsy/luci,kuoruan/luci,Noltari/luci,florian-shellfire/luci,ff94315/luci-1,palmettos/cnLuCI,cshore/luci,wongsyrone/luci-1,david-xiao/luci,lbthomsen/openwrt-luci,taiha/luci,NeoRaider/luci,lcf258/openwrtcn,artynet/luci,lcf258/openwrtcn,opentechinstitute/luci,aa65535/luci,hnyman/luci,rogerpueyo/luci,Sakura-Winkey/LuCI,taiha/luci,dwmw2/luci,Wedmer/luci,openwrt-es/openwrt-luci,oneru/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,openwrt/luci
a6e607407f38304e68aeb48ce58fde7d19793c2f
examples/timeout.lua
examples/timeout.lua
-- -- display time in all its joy -- -- setup() and draw() are start and main functions -- grid is drawn, time is kept on the grid -- screen_width = WIDTH screen_height = HEIGHT screen_w_center = screen_width / 2 screen_h_center = screen_height / 2 cell_size = HEIGHT / 4 colors = {} colors = { {r=255, g=0, b=255, a=1}, {r=0, g=0, b=255, a=1}, {r=255, g=0, b=0, a=1}, {r=80, g=500, b=200, a=1}, {r=87, g=133, b=160, a =1} } NUM_EVENTS = 20 SLICE_MODULO = 1 -- present-time countdown ptc = NUM_EVENTS -- current frame values only tick = 0 time_str = "time: " pixlen = 0 -- from now until NUM_EVENTS event_ticks = {} event_joyheights = {} -- dunno where we should get this from .. math.?? function map(x, in_min, in_max, out_min, out_max) return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; end function setup() background(255, 0, 0, 0) tick = tick + 1 end function draw_centered_grid() fill(100,0,0,1) rect(screen_w_center, screen_h_center, 4, 4) fill (100,50,0,1) --fill (153,150,50) line(0, screen_h_center, screen_width, screen_h_center) line(screen_w_center, 0, screen_w_center, screen_height) for z = screen_w_center, screen_width, 10 do if (((z - screen_w_center) % 50) == 0) then fill (25,102,0,1) ellipse(z, screen_h_center, 6, 6) text(z - 8, screen_h_center + 16 ,tostring(z - screen_w_center)) -- padding end end for z = screen_w_center, 0, -10 do if (((z - screen_w_center) % 50) == 0) then fill (25,102,0,1) ellipse(z, screen_h_center, 6, 6) text(z - 8, screen_h_center + 16, tostring(z - screen_w_center)) -- padding end end for z = screen_h_center, screen_height, 10 do if (((z - screen_h_center) % 50) == 0) then ellipse(screen_w_center, z, 6, 6) text(screen_w_center - 8, z + 16, tostring(z - screen_h_center)) -- padding end end for z = screen_h_center, 0, -10 do if (((z - screen_h_center) % 50) == 0) then ellipse(screen_w_center, z, 6, 6) text(screen_w_center - 8, z + 16, tostring(z - screen_h_center)) -- padding end end end function draw_colors_grids() for x = 1, screen_width / cell_size do for y = 1, screen_height / cell_size do for i = #colors, 1, -1 do fill (colors[i].r, colors[i].g, colors[i].b, colors[i].a) --print(" colors: " .. colors[i].r .. " " .. colors[i].g .. " " .. colors[i].b .. " " .. colors[i].a) --rect (x * (cell_size / 16), y * (cell_size / 16), 15, 15) rect (x * 16, y * 16, i * 15, i * 15) end end end end function draw_event_labels(i) fill(colors[2].r, colors[2].g, colors[2].b, colors[2].a) <<<<<<< HEAD local cn = math.modf(map (joystick[1].x, -32768, 32768, 1, #colors)) -- print(cn) fill (colors[cn].r, colors[cn].g, colors[cn].b, colors[cn].a) ======= if joystick.count ~= 0 then local cn = math.modf(map (joystick[1].x, -32768, 32768, 1, #colors)) print(cn) fill (colors[cn].r, colors[cn].g, colors[cn].b, colors[cn].a) end >>>>>>> 081392d010235579d0adfd44c2e093ffd1920218 rect( (i * 48) - 38, screen_h_center, (i * 48) - 34, map(event_joyheights[i], -32768, 32768, cell_size * 2, -cell_size * 2)) fill (87,133,160,1) text((i * 48) - 38, screen_h_center, event_ticks[i] .. " ") end function draw() if joystick.count == 0 then fill (240,0,0,1) text(250, 10, string.format("Joystick not found, but one is required!")) else -- we keep our own count of event_ticks since start tick = tick + 1 -- keep a list of NUM_EVENTS records and therefore need a present counter if ptc <= 1 then ptc = NUM_EVENTS end -- decrement ptc = ptc - 1 -- time slice if ((ptc % SLICE_MODULO) == 0) then background(0,0,0,1) text(10, 10, string.format("timeout, by torpor")) --draw_percentile_grid() draw_centered_grid() --draw_XY_grid() -- remember our current ptc data table.insert(event_ticks, tick) if joystick.count ~= 0 then table.insert(event_joyheights, joystick[1].y) end for i = #event_ticks,1,-1 do draw_event_labels(i) end draw_colors_grids() -- prune our little stack if #event_ticks > NUM_EVENTS then table.remove(event_ticks, 1) table.remove(event_joyheights, 1) end end end end
-- -- display time in all its joy -- -- setup() and draw() are start and main functions -- grid is drawn, time is kept on the grid -- screen_width = WIDTH screen_height = HEIGHT screen_w_center = screen_width / 2 screen_h_center = screen_height / 2 cell_size = HEIGHT / 4 colors = {} colors = { {r=255, g=0, b=255, a=1}, {r=0, g=0, b=255, a=1}, {r=255, g=0, b=0, a=1}, {r=80, g=500, b=200, a=1}, {r=87, g=133, b=160, a =1} } NUM_EVENTS = 20 SLICE_MODULO = 1 -- present-time countdown ptc = NUM_EVENTS -- current frame values only tick = 0 time_str = "time: " pixlen = 0 -- from now until NUM_EVENTS event_ticks = {} event_joyheights = {} -- dunno where we should get this from .. math.?? function map(x, in_min, in_max, out_min, out_max) return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; end function setup() background(255, 0, 0, 0) tick = tick + 1 end function draw_centered_grid() fill(100,0,0,1) rect(screen_w_center, screen_h_center, 4, 4) fill (100,50,0,1) --fill (153,150,50) line(0, screen_h_center, screen_width, screen_h_center) line(screen_w_center, 0, screen_w_center, screen_height) for z = screen_w_center, screen_width, 10 do if (((z - screen_w_center) % 50) == 0) then fill (25,102,0,1) ellipse(z, screen_h_center, 6, 6) text(z - 8, screen_h_center + 16 ,tostring(z - screen_w_center)) -- padding end end for z = screen_w_center, 0, -10 do if (((z - screen_w_center) % 50) == 0) then fill (25,102,0,1) ellipse(z, screen_h_center, 6, 6) text(z - 8, screen_h_center + 16, tostring(z - screen_w_center)) -- padding end end for z = screen_h_center, screen_height, 10 do if (((z - screen_h_center) % 50) == 0) then ellipse(screen_w_center, z, 6, 6) text(screen_w_center - 8, z + 16, tostring(z - screen_h_center)) -- padding end end for z = screen_h_center, 0, -10 do if (((z - screen_h_center) % 50) == 0) then ellipse(screen_w_center, z, 6, 6) text(screen_w_center - 8, z + 16, tostring(z - screen_h_center)) -- padding end end end function draw_colors_grids() for x = 1, screen_width / cell_size do for y = 1, screen_height / cell_size do for i = #colors, 1, -1 do fill (colors[i].r, colors[i].g, colors[i].b, colors[i].a) --print(" colors: " .. colors[i].r .. " " .. colors[i].g .. " " .. colors[i].b .. " " .. colors[i].a) --rect (x * (cell_size / 16), y * (cell_size / 16), 15, 15) rect (x * 16, y * 16, i * 15, i * 15) end end end end function draw_event_labels(i) fill(colors[2].r, colors[2].g, colors[2].b, colors[2].a) -- print(cn) fill (colors[cn].r, colors[cn].g, colors[cn].b, colors[cn].a) if joystick.count ~= 0 then local cn = math.modf(map (joystick[1].x, -32768, 32768, 1, #colors)) print(cn) fill (colors[cn].r, colors[cn].g, colors[cn].b, colors[cn].a) end rect( (i * 48) - 38, screen_h_center, (i * 48) - 34, map(event_joyheights[i], -32768, 32768, cell_size * 2, -cell_size * 2)) fill (87,133,160,1) text((i * 48) - 38, screen_h_center, event_ticks[i] .. " ") end function draw() if joystick.count == 0 then fill (240,0,0,1) text(250, 10, string.format("Joystick not found, but one is required!")) else -- we keep our own count of event_ticks since start tick = tick + 1 -- keep a list of NUM_EVENTS records and therefore need a present counter if ptc <= 1 then ptc = NUM_EVENTS end -- decrement ptc = ptc - 1 -- time slice if ((ptc % SLICE_MODULO) == 0) then background(0,0,0,1) text(10, 10, string.format("timeout, by torpor")) --draw_percentile_grid() draw_centered_grid() --draw_XY_grid() -- remember our current ptc data table.insert(event_ticks, tick) if joystick.count ~= 0 then table.insert(event_joyheights, joystick[1].y) end for i = #event_ticks,1,-1 do draw_event_labels(i) end draw_colors_grids() -- prune our little stack if #event_ticks > NUM_EVENTS then table.remove(event_ticks, 1) table.remove(event_joyheights, 1) end end end end
fix of merge hiccup
fix of merge hiccup
Lua
bsd-2-clause
seclorum/load81,seclorum/load81,seclorum/load81,seclorum/load81,seclorum/load81
c6bfe29e3ee7a2741e6652c974d87dfb20b49ee4
groupped-list.lua
groupped-list.lua
-- cached id list key local idListKey = KEYS[1]; -- meta key local metadataKey = KEYS[2]; -- stringified [key]: [aggregateMethod] pairs local aggregates = ARGV[1]; -- local cache local rcall = redis.call; local tinsert = table.insert; local jsonAggregates = cjson.decode(aggregates); local aggregateKeys = {}; local result = {}; local function aggregateSum(value1, value2) value1 = value1 or 0; value2 = value2 or 0; return value1 + value2; end local aggregateType = { sum = aggregateSum }; for key, method in pairs(jsonAggregates) do tinsert(aggregateKeys, key); result[key] = 0; if type(aggregateType[method]) ~= "function" then return error("not supported op: " .. method); end end local valuesToGroup = rcall("LRANGE", idListKey, 0, -1); -- group for _, id in ipairs(valuesToGroup) do -- metadata is stored here local metaKey = metadataKey:gsub("*", id, 1); -- pull information about required aggregate keys -- only 1 operation is supported now - sum -- but we can calculate multiple values local values = rcall("HMGET", metaKey, unpack(aggregateKeys)); for i, aggregateKey in ipairs(aggregateKeys) do local aggregateMethod = aggregateType[jsonAggregates[aggregateKey]]; local value = tonumber(values[i] or 0); result[aggregateKey] = aggregateMethod(result[aggregateKey], value); end end return cjson.encode(result);
-- cached id list key local idListKey = KEYS[1]; -- meta key local metadataKey = KEYS[2]; -- stringified [key]: [aggregateMethod] pairs local aggregates = ARGV[1]; -- local cache local rcall = redis.call; local tinsert = table.insert; local jsonAggregates = cjson.decode(aggregates); local aggregateKeys = {}; local result = {}; local function anynumber(a) return try { function() local num = tonumber(a); return num ~= nil and num or tonumber(cjson.decode(a)); end, catch { function() return nil; end } } end local function aggregateSum(value1, value2) local num1 = anynumber(value1) or 0; local num2 = anynumber(value2) or 0; return value1 + value2; end local aggregateType = { sum = aggregateSum }; for key, method in pairs(jsonAggregates) do tinsert(aggregateKeys, key); result[key] = 0; if type(aggregateType[method]) ~= "function" then return error("not supported op: " .. method); end end local valuesToGroup = rcall("LRANGE", idListKey, 0, -1); -- group for _, id in ipairs(valuesToGroup) do -- metadata is stored here local metaKey = metadataKey:gsub("*", id, 1); -- pull information about required aggregate keys -- only 1 operation is supported now - sum -- but we can calculate multiple values local values = rcall("HMGET", metaKey, unpack(aggregateKeys)); for i, aggregateKey in ipairs(aggregateKeys) do local aggregateMethod = aggregateType[jsonAggregates[aggregateKey]]; local value = tonumber(values[i] or 0); result[aggregateKey] = aggregateMethod(result[aggregateKey], value); end end return cjson.encode(result);
fix: be able to parse json-encoded numbers
fix: be able to parse json-encoded numbers
Lua
mit
makeomatic/redis-filtered-sort,makeomatic/redis-filtered-sort
e0729a483d6b5b86c76af14b167f2527f84e89a3
lualib/skynet/cluster.lua
lualib/skynet/cluster.lua
local skynet = require "skynet" local clusterd local cluster = {} local sender = {} local inquery_name = {} local function get_sender(t, node) local waitco = inquery_name[node] if waitco then local co=coroutine.running() table.insert(waitco, co) skynet.wait(co) return rawget(t, node) else waitco = {} inquery_name[node] = waitco local c = skynet.call(clusterd, "lua", "sender", node) inquery_name[node] = nil t[node] = c for _, co in ipairs(waitco) do skynet.wakeup(co) end return c end end setmetatable(sender, { __index = get_sender } ) function cluster.call(node, address, ...) -- skynet.pack(...) will free by cluster.core.packrequest return skynet.call(sender[node], "lua", "req", address, skynet.pack(...)) end function cluster.send(node, address, ...) -- push is the same with req, but no response skynet.send(sender[node], "lua", "push", address, skynet.pack(...)) end function cluster.open(port) if type(port) == "string" then skynet.call(clusterd, "lua", "listen", port) else skynet.call(clusterd, "lua", "listen", "0.0.0.0", port) end end function cluster.reload(config) skynet.call(clusterd, "lua", "reload", config) end function cluster.proxy(node, name) return skynet.call(clusterd, "lua", "proxy", node, name) end function cluster.snax(node, name, address) local snax = require "skynet.snax" if not address then address = cluster.call(node, ".service", "QUERY", "snaxd" , name) end local handle = skynet.call(clusterd, "lua", "proxy", node, address) return snax.bind(handle, name) end function cluster.register(name, addr) assert(type(name) == "string") assert(addr == nil or type(addr) == "number") return skynet.call(clusterd, "lua", "register", name, addr) end function cluster.query(node, name) return skynet.call(sender[node], "lua", "req", 0, skynet.pack(name)) end skynet.init(function() clusterd = skynet.uniqueservice("clusterd") end) return cluster
local skynet = require "skynet" local clusterd local cluster = {} local sender = {} local function get_sender(t, node) local c = skynet.call(clusterd, "lua", "sender", node) t[node] = c return c end setmetatable(sender, { __index = get_sender } ) function cluster.call(node, address, ...) -- skynet.pack(...) will free by cluster.core.packrequest return skynet.call(sender[node], "lua", "req", address, skynet.pack(...)) end function cluster.send(node, address, ...) -- push is the same with req, but no response skynet.send(sender[node], "lua", "push", address, skynet.pack(...)) end function cluster.open(port) if type(port) == "string" then skynet.call(clusterd, "lua", "listen", port) else skynet.call(clusterd, "lua", "listen", "0.0.0.0", port) end end function cluster.reload(config) skynet.call(clusterd, "lua", "reload", config) end function cluster.proxy(node, name) return skynet.call(clusterd, "lua", "proxy", node, name) end function cluster.snax(node, name, address) local snax = require "skynet.snax" if not address then address = cluster.call(node, ".service", "QUERY", "snaxd" , name) end local handle = skynet.call(clusterd, "lua", "proxy", node, address) return snax.bind(handle, name) end function cluster.register(name, addr) assert(type(name) == "string") assert(addr == nil or type(addr) == "number") return skynet.call(clusterd, "lua", "register", name, addr) end function cluster.query(node, name) return skynet.call(sender[node], "lua", "req", 0, skynet.pack(name)) end skynet.init(function() clusterd = skynet.uniqueservice("clusterd") end) return cluster
Revert "bugfix:cluster初始化节点的时候有可能导致消息乱序"
Revert "bugfix:cluster初始化节点的时候有可能导致消息乱序" This reverts commit 9ba0860c701850a04154b4f9799f391f9d388fa3.
Lua
mit
hongling0/skynet,bigrpg/skynet,cloudwu/skynet,korialuo/skynet,ag6ag/skynet,wangyi0226/skynet,ag6ag/skynet,pigparadise/skynet,cloudwu/skynet,hongling0/skynet,sanikoyes/skynet,jxlczjp77/skynet,icetoggle/skynet,wangyi0226/skynet,xjdrew/skynet,bigrpg/skynet,xcjmine/skynet,sanikoyes/skynet,wangyi0226/skynet,xjdrew/skynet,korialuo/skynet,jxlczjp77/skynet,jxlczjp77/skynet,pigparadise/skynet,xcjmine/skynet,JiessieDawn/skynet,cloudwu/skynet,hongling0/skynet,sanikoyes/skynet,ag6ag/skynet,pigparadise/skynet,xcjmine/skynet,icetoggle/skynet,icetoggle/skynet,korialuo/skynet,bigrpg/skynet,xjdrew/skynet,JiessieDawn/skynet,JiessieDawn/skynet
bc06611c4ca1ef79760db8d08ce64a29a2cb2837
Quadtastic/Tooltip.lua
Quadtastic/Tooltip.lua
local Text = require("Text") local imgui = require("imgui") local Renderutils = require("Renderutils") local Tooltip = {} unpack = unpack or table.unpack local border_quads = Renderutils.border_quads(0, 48, 5, 5, 128, 128, 2) local tip_quad_down = love.graphics.newQuad(6, 48, 5, 3, 128, 128) local tip_quad_up = love.graphics.newQuad(6, 50, 5, 3, 128, 128) local find_tooltip_position = function(gui_state, x, y, w, h, label, options) local textlength = Text.min_width(gui_state, label or "Someone forgot to set the tooltip text...") return x + w / 2 - (textlength + 2*2)/2, y + h + 3, textlength + 2*2, 16 end local show_tooltip = function(gui_state, x, y, w, h, label, options) gui_state.overlay_canvas:renderTo(function() -- Remember and remove the current scissor local old_scissor = {love.graphics.getScissor()} love.graphics.setScissor() -- Use the small font for the tooltip label imgui.push_style(gui_state, "font", gui_state.style.small_font) local ttx, tty, ttw, tth = find_tooltip_position(gui_state, x, y, w, h, label, options) love.graphics.setColor(255, 255, 255, 255) -- Draw tooltip border Renderutils.draw_border(gui_state.style.stylesheet, border_quads, ttx, tty, ttw, tth, 2) -- Draw tooltip tip love.graphics.draw(gui_state.style.stylesheet, tip_quad_up, x + w/2, y+h) if not options then options = {} end if not options.font_color then options.font_color = {202, 222, 227} end Text.draw(gui_state, ttx + 2, tty, ttw, tth, label, options) imgui.pop_style(gui_state, "font") -- Restore the old scissor love.graphics.setScissor(unpack(old_scissor)) end) end -- A tooltip ignores the current layout's bounds but uses the current layout -- hints to determine where it should be drawn. It will be drawn at the bottom -- or the top of the previously drawn component Tooltip.draw = function(gui_state, label, x, y, w, h, options) -- The dimensions of the item next to which the tooltip will be displayed x = x or gui_state.layout.next_x y = y or gui_state.layout.next_y w = w or gui_state.layout.adv_x h = h or gui_state.layout.adv_y -- love.graphics.rectangle("line", x, y, w, h) local old_mouse_x = gui_state.mouse.old_x local old_mouse_y = gui_state.mouse.old_y if not old_mouse_x or not old_mouse_y then return end -- Check if the mouse was in that area in the previous frame local was_in_frame = imgui.is_mouse_in_rect(gui_state, x, y, w, h, old_mouse_x, old_mouse_y) -- Now check the current mouse position local is_in_frame = imgui.is_mouse_in_rect(gui_state, x, y, w, h) if was_in_frame and is_in_frame then gui_state.tooltip_time = gui_state.tooltip_time + gui_state.dt elseif is_in_frame then -- the mouse has just been moved into the frame -- This is not super-accurate but will probably suffice gui_state.tooltip_time = gui_state.dt else -- the mouse is not in the frame. return end print("tooltip time: ", gui_state.tooltip_time) -- The threshold after which the tooltip should be displayed. Default is 1s local threshold = options and options.tooltip_threshold or 1 if gui_state.tooltip_time > threshold then -- display the tooltip show_tooltip(gui_state, x, y, w, h, label, options) end end return Tooltip
local Text = require("Text") local imgui = require("imgui") local Renderutils = require("Renderutils") local Tooltip = {} unpack = unpack or table.unpack local border_quads = Renderutils.border_quads(0, 48, 5, 5, 128, 128, 2) local tip_quad_down = love.graphics.newQuad(6, 48, 5, 3, 128, 128) local tip_quad_up = love.graphics.newQuad(6, 50, 5, 3, 128, 128) local find_tooltip_position = function(gui_state, x, y, w, h, label, options) local textlength = Text.min_width(gui_state, label or "Someone forgot to set the tooltip text...") return x + w / 2 - (textlength + 2*2)/2, y + h + 3, textlength + 2*2, 16 end local show_tooltip = function(gui_state, x, y, w, h, label, options) gui_state.overlay_canvas:renderTo(function() -- Remember and remove the current scissor local old_scissor = {love.graphics.getScissor()} love.graphics.setScissor() -- Use the small font for the tooltip label imgui.push_style(gui_state, "font", gui_state.style.small_font) local ttx, tty, ttw, tth = find_tooltip_position(gui_state, x, y, w, h, label, options) love.graphics.setColor(255, 255, 255, 255) -- Draw tooltip border Renderutils.draw_border(gui_state.style.stylesheet, border_quads, ttx, tty, ttw, tth, 2) -- Draw tooltip tip love.graphics.draw(gui_state.style.stylesheet, tip_quad_up, x + w/2, y+h) if not options then options = {} end if not options.font_color then options.font_color = {202, 222, 227} end Text.draw(gui_state, ttx + 2, tty, ttw, tth, label, options) imgui.pop_style(gui_state, "font") -- Restore the old scissor love.graphics.setScissor(unpack(old_scissor)) end) end -- A tooltip ignores the current layout's bounds but uses the current layout -- hints to determine where it should be drawn. It will be drawn at the bottom -- or the top of the previously drawn component Tooltip.draw = function(gui_state, label, x, y, w, h, options) -- The dimensions of the item next to which the tooltip will be displayed x = x or gui_state.layout.next_x y = y or gui_state.layout.next_y w = w or gui_state.layout.adv_x h = h or gui_state.layout.adv_y -- love.graphics.rectangle("line", x, y, w, h) local old_mouse_x = gui_state.mouse.old_x local old_mouse_y = gui_state.mouse.old_y if not old_mouse_x or not old_mouse_y then return end -- Check if the mouse was in that area in the previous frame local was_in_frame = imgui.is_mouse_in_rect(gui_state, x, y, w, h, old_mouse_x, old_mouse_y) -- Now check the current mouse position local is_in_frame = imgui.is_mouse_in_rect(gui_state, x, y, w, h) if was_in_frame and is_in_frame then gui_state.tooltip_time = gui_state.tooltip_time + gui_state.dt elseif is_in_frame then -- the mouse has just been moved into the frame -- This is not super-accurate but will probably suffice gui_state.tooltip_time = gui_state.dt else -- the mouse is not in the frame. return end print("tooltip time: ", gui_state.tooltip_time) -- The threshold after which the tooltip should be displayed. Default is 1s local threshold = options and options.tooltip_threshold or 1 if gui_state.tooltip_time > threshold then -- display the tooltip show_tooltip(gui_state, x, y, w, h, label, options) end end return Tooltip
[Whitespace] Fix whitespace inconsistency
[Whitespace] Fix whitespace inconsistency
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
e42d0bf91e634b7253c53e12417a1449a55e2236
core/cairo-output.lua
core/cairo-output.lua
local lgi = require("lgi"); local cairo = lgi.cairo local pango = lgi.Pango if (not SILE.outputters) then SILE.outputters = {} end local cr SILE.outputters.cairo = { init = function() local surface = cairo.PdfSurface.create(SILE.outputFilename, SILE.documentState.paperSize[1], SILE.documentState.paperSize[2]) cr = cairo.Context.create(surface) end, newPage = function() cr:show_page(); end, finish = function() end, showGlyphString = function(f,pgs) cr:show_glyph_string(f,pgs) end, moveTo = function (x,y) cr:move_to(x,y) end, debugFrame = function (f) cr:rectangle(f.left(), f.top(), f.width(), f.height()); cr:moveTo(f.left(), f.top()); cr:showText(f.id); end, debugHbox = function(typesetter, hbox, scaledWidth) cr:setSourceRGB(0.9,0.9,0.9); cr:rectangle(typesetter.state.cursorX, typesetter.state.cursorY-(hbox.height), scaledWidth, hbox.height+hbox.depth); if (hbox.depth) then cr:rectangle(typesetter.state.cursorX, typesetter.state.cursorY-(hbox.height), scaledWidth, hbox.height); end cr:setSourceRGB(0,0,0); end } SILE.outputter = SILE.outputters.cairo
local lgi = require("lgi"); local cairo = lgi.cairo local pango = lgi.Pango if (not SILE.outputters) then SILE.outputters = {} end local cr SILE.outputters.cairo = { init = function() local surface = cairo.PdfSurface.create(SILE.outputFilename, SILE.documentState.paperSize[1], SILE.documentState.paperSize[2]) cr = cairo.Context.create(surface) end, newPage = function() cr:show_page(); end, finish = function() end, showGlyphString = function(f,pgs) cr:show_glyph_string(f,pgs) end, moveTo = function (x,y) cr:move_to(x,y) end, debugFrame = function (self,f) cr:set_line_width(0.5); cr:rectangle(f:left(), f:top(), f:width(), f:height()); cr:stroke(); cr:move_to(f:left(), f:top()); cr:show_text(f.id); end, debugHbox = function(typesetter, hbox, scaledWidth) cr:setSourceRGB(0.9,0.9,0.9); cr:rectangle(typesetter.state.cursorX, typesetter.state.cursorY-(hbox.height), scaledWidth, hbox.height+hbox.depth); if (hbox.depth) then cr:rectangle(typesetter.state.cursorX, typesetter.state.cursorY-(hbox.height), scaledWidth, hbox.height); end cr:setSourceRGB(0,0,0); end } SILE.outputter = SILE.outputters.cairo
Fix this method.
Fix this method.
Lua
mit
alerque/sile,neofob/sile,shirat74/sile,anthrotype/sile,simoncozens/sile,Nathan22Miles/sile,neofob/sile,anthrotype/sile,WAKAMAZU/sile_fe,shirat74/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,simoncozens/sile,WAKAMAZU/sile_fe,anthrotype/sile,alerque/sile,shirat74/sile,simoncozens/sile,Nathan22Miles/sile,alerque/sile,simoncozens/sile,anthrotype/sile,alerque/sile,Nathan22Miles/sile,neofob/sile,shirat74/sile,neofob/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile
e1ff894595450e2f5c220b0666ed056274524e85
src_trunk/resources/realism-system/c_weapons_back.lua
src_trunk/resources/realism-system/c_weapons_back.lua
local objectmade = false local crouched = nil local weapon = nil function weaponSwitched() -- SLOT 5 if (getPedWeaponSlot(getLocalPlayer())~=5 and getPedWeapon(getLocalPlayer(), 5)~=0) then local weap = getPedWeapon(getLocalPlayer(), 5) if (weap==30 or weap==31) then if not (objectmade) or (isPedDucked(getLocalPlayer())~=crouched) or (weap~=weapon) then -- no object, so lets create it local bx, by, bz = getPedBonePosition(getLocalPlayer(), 3) local x, y, z = getElementPosition(getLocalPlayer()) local r = getPedRotation(getLocalPlayer()) weapon = weap crouched = isPedDucked(getLocalPlayer()) local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25 if (crouched) then oz = -0.025 end triggerServerEvent("createWeaponBackModel", getLocalPlayer(), ox, oy, oz, weapon) objectmade = true end end else if (objectmade) then objectmade = false triggerServerEvent("destroyWeaponBackModel", getLocalPlayer()) end end end addEventHandler("onClientRender", getRootElement(), weaponSwitched)
local objectmade = false local crouched = nil local weapon = nil function weaponSwitched() -- SLOT 5 if (getPedWeaponSlot(getLocalPlayer())~=5 and getPedWeapon(getLocalPlayer(), 5)~=0) and not (isPedInVehicle(getLocalPlayer())) then local weap = getPedWeapon(getLocalPlayer(), 5) if (weap==30 or weap==31) then if not (objectmade) or (isPedDucked(getLocalPlayer())~=crouched) or (weap~=weapon) then -- no object, so lets create it local bx, by, bz = getPedBonePosition(getLocalPlayer(), 3) local x, y, z = getElementPosition(getLocalPlayer()) local r = getPedRotation(getLocalPlayer()) weapon = weap crouched = isPedDucked(getLocalPlayer()) local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25 if (crouched) then oz = -0.025 end triggerServerEvent("createWeaponBackModel", getLocalPlayer(), ox, oy, oz, weapon) objectmade = true end end else if (objectmade) then objectmade = false triggerServerEvent("destroyWeaponBackModel", getLocalPlayer()) end end end addEventHandler("onClientRender", getRootElement(), weaponSwitched)
Fixed 245
Fixed 245 git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@74 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
de8d8e4f13e530edc3c14a6524e8c2b9ed66c5d0
modules/exchange.lua
modules/exchange.lua
local simplehttp = require'simplehttp' local html2unicode = require'html' local cc = { ["AED"] = "United Arab Emirates Dirham (AED)", ["ANG"] = "Netherlands Antillean Guilder (ANG)", ["ARS"] = "Argentine Peso (ARS)", ["AUD"] = "Australian Dollar (AUD)", ["BDT"] = "Bangladeshi Taka (BDT)", ["BGN"] = "Bulgarian Lev (BGN)", ["BHD"] = "Bahraini Dinar (BHD)", ["BND"] = "Brunei Dollar (BND)", ["BOB"] = "Bolivian Boliviano (BOB)", ["BRL"] = "Brazilian Real (BRL)", ["BWP"] = "Botswanan Pula (BWP)", ["CAD"] = "Canadian Dollar (CAD)", ["CHF"] = "Swiss Franc (CHF)", ["CLP"] = "Chilean Peso (CLP)", ["CNY"] = "Chinese Yuan (CNY)", ["COP"] = "Colombian Peso (COP)", ["CRC"] = "Costa Rican Colón (CRC)", ["CZK"] = "Czech Republic Koruna (CZK)", ["DKK"] = "Danish Krone (DKK)", ["DOP"] = "Dominican Peso (DOP)", ["DZD"] = "Algerian Dinar (DZD)", ["EEK"] = "Estonian Kroon (EEK)", ["EGP"] = "Egyptian Pound (EGP)", ["EUR"] = "Euro (EUR)", ["FJD"] = "Fijian Dollar (FJD)", ["GBP"] = "British Pound Sterling (GBP)", ["HKD"] = "Hong Kong Dollar (HKD)", ["HNL"] = "Honduran Lempira (HNL)", ["HRK"] = "Croatian Kuna (HRK)", ["HUF"] = "Hungarian Forint (HUF)", ["IDR"] = "Indonesian Rupiah (IDR)", ["ILS"] = "Israeli New Sheqel (ILS)", ["INR"] = "Indian Rupee (INR)", ["JMD"] = "Jamaican Dollar (JMD)", ["JOD"] = "Jordanian Dinar (JOD)", ["JPY"] = "Japanese Yen (JPY)", ["KES"] = "Kenyan Shilling (KES)", ["KRW"] = "South Korean Won (KRW)", ["KWD"] = "Kuwaiti Dinar (KWD)", ["KYD"] = "Cayman Islands Dollar (KYD)", ["KZT"] = "Kazakhstani Tenge (KZT)", ["LBP"] = "Lebanese Pound (LBP)", ["LKR"] = "Sri Lankan Rupee (LKR)", ["LTL"] = "Lithuanian Litas (LTL)", ["LVL"] = "Latvian Lats (LVL)", ["MAD"] = "Moroccan Dirham (MAD)", ["MDL"] = "Moldovan Leu (MDL)", ["MKD"] = "Macedonian Denar (MKD)", ["MUR"] = "Mauritian Rupee (MUR)", ["MVR"] = "Maldivian Rufiyaa (MVR)", ["MXN"] = "Mexican Peso (MXN)", ["MYR"] = "Malaysian Ringgit (MYR)", ["NAD"] = "Namibian Dollar (NAD)", ["NGN"] = "Nigerian Naira (NGN)", ["NIO"] = "Nicaraguan Córdoba (NIO)", ["NOK"] = "Norwegian Krone (NOK)", ["NPR"] = "Nepalese Rupee (NPR)", ["NZD"] = "New Zealand Dollar (NZD)", ["OMR"] = "Omani Rial (OMR)", ["PEN"] = "Peruvian Nuevo Sol (PEN)", ["PGK"] = "Papua New Guinean Kina (PGK)", ["PHP"] = "Philippine Peso (PHP)", ["PKR"] = "Pakistani Rupee (PKR)", ["PLN"] = "Polish Zloty (PLN)", ["PYG"] = "Paraguayan Guarani (PYG)", ["QAR"] = "Qatari Rial (QAR)", ["RON"] = "Romanian Leu (RON)", ["RSD"] = "Serbian Dinar (RSD)", ["RUB"] = "Russian Ruble (RUB)", ["SAR"] = "Saudi Riyal (SAR)", ["SCR"] = "Seychellois Rupee (SCR)", ["SEK"] = "Swedish Krona (SEK)", ["SGD"] = "Singapore Dollar (SGD)", ["SKK"] = "Slovak Koruna (SKK)", ["SLL"] = "Sierra Leonean Leone (SLL)", ["SVC"] = "Salvadoran Colón (SVC)", ["THB"] = "Thai Baht (THB)", ["TND"] = "Tunisian Dinar (TND)", ["TRY"] = "Turkish Lira (TRY)", ["TTD"] = "Trinidad and Tobago Dollar (TTD)", ["TWD"] = "New Taiwan Dollar (TWD)", ["TZS"] = "Tanzanian Shilling (TZS)", ["UAH"] = "Ukrainian Hryvnia (UAH)", ["UGX"] = "Ugandan Shilling (UGX)", ["USD"] = "US Dollar (USD)", ["UYU"] = "Uruguayan Peso (UYU)", ["UZS"] = "Uzbekistan Som (UZS)", ["VEF"] = "Venezuelan Bolívar (VEF)", ["VND"] = "Vietnamese Dong (VND)", ["XOF"] = "CFA Franc BCEAO (XOF)", ["YER"] = "Yemeni Rial (YER)", ["ZAR"] = "South African Rand (ZAR)", ["ZMK"] = "Zambian Kwacha (ZMK)", } local conv = { ['euro'] = 'eur', } -- make environment local _X = setmetatable({ math = math, print = function(val) if(val and tonumber(val)) then return tonumber(val) end end }, {__index = math}) -- run code under environment local function run(untrusted_code) local untrusted_function, message = loadstring(untrusted_code) if not untrusted_function then return nil, message end setfenv(untrusted_function, _X) return pcall(untrusted_function) end local parseData = function(data) local data = data:match'<div id=currency_converter_result>(.-)</span>' return html2unicode(data:gsub('<.->', '')):gsub(' ', ' ') end local checkInput = function(value, from, to) if(not (cc[from] and cc[to])) then return nil, string.format('Invalid currency: %s.', (not cc[from] and from) or (not cc[to] and to)) end -- Control the input. value = value:gsub(',', '.') local success, value, err = run('return ' .. value) if(err) then return nil, string.format('Parsing of input failed: %s', err) end -- Number validation, serious business! if(type(value) ~= 'number' or value <= 0 or value == math.huge or value ~= value) then return nil, string.format('Invalid number provided: %s', tonumber(value)) end return true, value end local handleExchange = function(self, source, destination, value, from, to) -- Strip away to/in and spaces. to = to:lower():gsub('[toin ]+ ', '') from = from:lower() -- Default to NOK. if(to == '') then to = 'NOK' end from = (conv[from] or from):upper() to = (conv[to] or to):upper() if(from == to) then return self:Msg('privmsg', destination, source, 'wat ar u dewn... %s! STAHP!', source.nick) end local success, value = checkInput(value, from, to) if(not success) then self:Msg('privmsg', destination, source, '%s: %s', source.nick, value) else simplehttp( ('http://www.google.com/finance/converter?a=%s&from=%s&to=%s'):format(value, from, to), function(data) local message = parseData(data) if(message) then self:Msg('privmsg', destination, source, '%s: %s', source.nick, message) end end ) end end return { PRIVMSG = { ['^!xe (%S+) (%S+) ?(.*)$'] = handleExchange, ['^!cur (%S+) (%S+) ?(.*)$'] = handleExchange, }, }
local simplehttp = require'simplehttp' local html2unicode = require'html' local cc = { ["AED"] = "United Arab Emirates Dirham (AED)", ["ANG"] = "Netherlands Antillean Guilder (ANG)", ["ARS"] = "Argentine Peso (ARS)", ["AUD"] = "Australian Dollar (AUD)", ["BDT"] = "Bangladeshi Taka (BDT)", ["BGN"] = "Bulgarian Lev (BGN)", ["BHD"] = "Bahraini Dinar (BHD)", ["BND"] = "Brunei Dollar (BND)", ["BOB"] = "Bolivian Boliviano (BOB)", ["BRL"] = "Brazilian Real (BRL)", ["BWP"] = "Botswanan Pula (BWP)", ["CAD"] = "Canadian Dollar (CAD)", ["CHF"] = "Swiss Franc (CHF)", ["CLP"] = "Chilean Peso (CLP)", ["CNY"] = "Chinese Yuan (CNY)", ["COP"] = "Colombian Peso (COP)", ["CRC"] = "Costa Rican Colón (CRC)", ["CZK"] = "Czech Republic Koruna (CZK)", ["DKK"] = "Danish Krone (DKK)", ["DOP"] = "Dominican Peso (DOP)", ["DZD"] = "Algerian Dinar (DZD)", ["EEK"] = "Estonian Kroon (EEK)", ["EGP"] = "Egyptian Pound (EGP)", ["EUR"] = "Euro (EUR)", ["FJD"] = "Fijian Dollar (FJD)", ["GBP"] = "British Pound Sterling (GBP)", ["HKD"] = "Hong Kong Dollar (HKD)", ["HNL"] = "Honduran Lempira (HNL)", ["HRK"] = "Croatian Kuna (HRK)", ["HUF"] = "Hungarian Forint (HUF)", ["IDR"] = "Indonesian Rupiah (IDR)", ["ILS"] = "Israeli New Sheqel (ILS)", ["INR"] = "Indian Rupee (INR)", ["JMD"] = "Jamaican Dollar (JMD)", ["JOD"] = "Jordanian Dinar (JOD)", ["JPY"] = "Japanese Yen (JPY)", ["KES"] = "Kenyan Shilling (KES)", ["KRW"] = "South Korean Won (KRW)", ["KWD"] = "Kuwaiti Dinar (KWD)", ["KYD"] = "Cayman Islands Dollar (KYD)", ["KZT"] = "Kazakhstani Tenge (KZT)", ["LBP"] = "Lebanese Pound (LBP)", ["LKR"] = "Sri Lankan Rupee (LKR)", ["LTL"] = "Lithuanian Litas (LTL)", ["LVL"] = "Latvian Lats (LVL)", ["MAD"] = "Moroccan Dirham (MAD)", ["MDL"] = "Moldovan Leu (MDL)", ["MKD"] = "Macedonian Denar (MKD)", ["MUR"] = "Mauritian Rupee (MUR)", ["MVR"] = "Maldivian Rufiyaa (MVR)", ["MXN"] = "Mexican Peso (MXN)", ["MYR"] = "Malaysian Ringgit (MYR)", ["NAD"] = "Namibian Dollar (NAD)", ["NGN"] = "Nigerian Naira (NGN)", ["NIO"] = "Nicaraguan Córdoba (NIO)", ["NOK"] = "Norwegian Krone (NOK)", ["NPR"] = "Nepalese Rupee (NPR)", ["NZD"] = "New Zealand Dollar (NZD)", ["OMR"] = "Omani Rial (OMR)", ["PEN"] = "Peruvian Nuevo Sol (PEN)", ["PGK"] = "Papua New Guinean Kina (PGK)", ["PHP"] = "Philippine Peso (PHP)", ["PKR"] = "Pakistani Rupee (PKR)", ["PLN"] = "Polish Zloty (PLN)", ["PYG"] = "Paraguayan Guarani (PYG)", ["QAR"] = "Qatari Rial (QAR)", ["RON"] = "Romanian Leu (RON)", ["RSD"] = "Serbian Dinar (RSD)", ["RUB"] = "Russian Ruble (RUB)", ["SAR"] = "Saudi Riyal (SAR)", ["SCR"] = "Seychellois Rupee (SCR)", ["SEK"] = "Swedish Krona (SEK)", ["SGD"] = "Singapore Dollar (SGD)", ["SKK"] = "Slovak Koruna (SKK)", ["SLL"] = "Sierra Leonean Leone (SLL)", ["SVC"] = "Salvadoran Colón (SVC)", ["THB"] = "Thai Baht (THB)", ["TND"] = "Tunisian Dinar (TND)", ["TRY"] = "Turkish Lira (TRY)", ["TTD"] = "Trinidad and Tobago Dollar (TTD)", ["TWD"] = "New Taiwan Dollar (TWD)", ["TZS"] = "Tanzanian Shilling (TZS)", ["UAH"] = "Ukrainian Hryvnia (UAH)", ["UGX"] = "Ugandan Shilling (UGX)", ["USD"] = "US Dollar (USD)", ["UYU"] = "Uruguayan Peso (UYU)", ["UZS"] = "Uzbekistan Som (UZS)", ["VEF"] = "Venezuelan Bolívar (VEF)", ["VND"] = "Vietnamese Dong (VND)", ["XOF"] = "CFA Franc BCEAO (XOF)", ["YER"] = "Yemeni Rial (YER)", ["ZAR"] = "South African Rand (ZAR)", ["ZMK"] = "Zambian Kwacha (ZMK)", } local conv = { ['euro'] = 'eur', } -- make environment local _X = setmetatable({ math = math, print = function(val) if(val and tonumber(val)) then return tonumber(val) end end }, {__index = math}) -- run code under environment local function run(untrusted_code) local untrusted_function, message = loadstring(untrusted_code) if not untrusted_function then return nil, message end setfenv(untrusted_function, _X) return pcall(untrusted_function) end local parseData = function(data) local data = data:match'<div id=currency_converter_result>(.-)</span>' if(not data) then return 'Some currency died? No exchange rates returned.' end return html2unicode(data:gsub('<.->', '')):gsub(' ', ' ') end local checkInput = function(value, from, to) if(not (cc[from] and cc[to])) then return nil, string.format('Invalid currency: %s.', (not cc[from] and from) or (not cc[to] and to)) end -- Control the input. value = value:gsub(',', '.') local success, value, err = run('return ' .. value) if(err) then return nil, string.format('Parsing of input failed: %s', err) end -- Number validation, serious business! if(type(value) ~= 'number' or value <= 0 or value == math.huge or value ~= value) then return nil, string.format('Invalid number provided: %s', tonumber(value)) end return true, value end local handleExchange = function(self, source, destination, value, from, to) -- Strip away to/in and spaces. to = to:lower():gsub('[toin ]+ ', '') from = from:lower() -- Default to NOK. if(to == '') then to = 'NOK' end from = (conv[from] or from):upper() to = (conv[to] or to):upper() if(from == to) then return self:Msg('privmsg', destination, source, 'wat ar u dewn... %s! STAHP!', source.nick) end local success, value = checkInput(value, from, to) if(not success) then self:Msg('privmsg', destination, source, '%s: %s', source.nick, value) else simplehttp( ('http://www.google.com/finance/converter?a=%s&from=%s&to=%s'):format(value, from, to), function(data) local message = parseData(data) if(message) then self:Msg('privmsg', destination, source, '%s: %s', source.nick, message) end end ) end end return { PRIVMSG = { ['^!xe (%S+) (%S+) ?(.*)$'] = handleExchange, ['^!cur (%S+) (%S+) ?(.*)$'] = handleExchange, }, }
exchange: Workaround empty data returns.
exchange: Workaround empty data returns. Fixes #42.
Lua
mit
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
efad7a3437f6b166d63be6d775b6d520c1ab4277
MMOCoreORB/bin/scripts/screenplays/tasks/naboo/huff_zinga.lua
MMOCoreORB/bin/scripts/screenplays/tasks/naboo/huff_zinga.lua
huff_zinga_missions = { { missionType = "assassinate", primarySpawns = { { npcTemplate = "huff_blistmok", planetName = "naboo", npcName = "Adult blistmok" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 100 }, } }, { missionType = "assassinate", primarySpawns = { { npcTemplate = "bocatt", planetName = "naboo", npcName = "Bocatt" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 100 }, } }, { missionType = "assassinate", primarySpawns = { { npcTemplate = "sharptooth_langlatch", planetName = "naboo", npcName = "Langlatch" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 200 }, } }, { missionType = "assassinate", primarySpawns = { { npcTemplate = "grassland_slice_hound", planetName = "naboo", npcName = "Corellian Slice Hound" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 10 }, } }, } npcMapHuffZinga = { { spawnData = { planetName = "naboo", npcTemplate = "huff_zinga", x = 5155, z = -192, y = 6636, direction = 47, cellID = 0, position = STAND }, worldPosition = { x = 5155, y = 6636 }, npcNumber = 1, stfFile = "@static_npc/naboo/huff_zinga", hasWaypointNames = "no", missions = huff_zinga_missions } } HuffZinga = ThemeParkLogic:new { numberOfActs = 1, npcMap = npcMapHuffZinga, className = "HuffZinga", screenPlayState = "huff_zinga_quest", missionCompletionMessageStf = "@theme_park/messages:static_completion_message", distance = 600 } registerScreenPlay("HuffZinga", true) huff_zinga_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = HuffZinga } huff_zinga_mission_target_conv_handler = mission_target_conv_handler:new { themePark = HuffZinga }
huff_zinga_missions = { { missionType = "assassinate", silentTarget = "yes", primarySpawns = { { npcTemplate = "huff_blistmok", planetName = "naboo", npcName = "Adult blistmok" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 100 }, } }, { missionType = "assassinate", silentTarget = "yes", primarySpawns = { { npcTemplate = "bocatt", planetName = "naboo", npcName = "Bocatt" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 100 }, } }, { missionType = "assassinate", silentTarget = "yes", primarySpawns = { { npcTemplate = "sharptooth_langlatch", planetName = "naboo", npcName = "Langlatch" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 200 }, } }, { missionType = "assassinate", silentTarget = "yes", primarySpawns = { { npcTemplate = "grassland_slice_hound", planetName = "naboo", npcName = "Corellian Slice Hound" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 200 }, } }, } npcMapHuffZinga = { { spawnData = { planetName = "naboo", npcTemplate = "huff_zinga", x = 5155, z = -192, y = 6636, direction = 47, cellID = 0, position = STAND }, worldPosition = { x = 5155, y = 6636 }, npcNumber = 1, stfFile = "@static_npc/naboo/huff_zinga", hasWaypointNames = "no", missions = huff_zinga_missions } } HuffZinga = ThemeParkLogic:new { numberOfActs = 1, npcMap = npcMapHuffZinga, className = "HuffZinga", screenPlayState = "huff_zinga_quest", missionCompletionMessageStf = "@theme_park/messages:static_completion_message", distance = 600 } registerScreenPlay("HuffZinga", true) huff_zinga_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = HuffZinga } huff_zinga_mission_target_conv_handler = mission_target_conv_handler:new { themePark = HuffZinga }
[fixed] Huff Zinga quest targets set to silent and final reward adjusted
[fixed] Huff Zinga quest targets set to silent and final reward adjusted Change-Id: I8bf87d4283894cbf47585117ab9d88ff268960ce
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
631ba21c182389dd5a68241a36d1eb4fb13c895b
packages/leaders.lua
packages/leaders.lua
-- -- Leaders package -- local widthToFrameEdge = function (frame) local w if frame:writingDirection() == "LTR" then w = frame:right() - frame.state.cursorX elseif frame:writingDirection() == "RTL" then w = frame.state.cursorX - frame:left() elseif frame:writingDirection() == "TTB" then w = frame:bottom() - frame.state.cursorY elseif frame:writingDirection() == "BTT" then w = frame.state.cursorY - frame:top() else SU.error("Unknown writing direction") end return w end local leader = pl.class(SILE.nodefactory.glue) function leader:outputYourself (typesetter, line) local outputWidth = SU.rationWidth(self.width, self.width, line.ratio):tonumber() local leaderWidth = self.value.width:tonumber() local ox = typesetter.frame.state.cursorX local oy = typesetter.frame.state.cursorY -- Implementation note: -- We want leaders on different lines to be aligned vertically in the frame, -- from its end edge (e.g. the right edge in LTR writing direction). -- Compute how many leaders we can fit from the current initial position. local fitWidth = widthToFrameEdge(typesetter.frame):tonumber() local maxRepetitions = math.floor(fitWidth / leaderWidth) -- round down! -- Compute how many leaders we have to skip after our final position. typesetter.frame:advanceWritingDirection(outputWidth) local skipWidth = widthToFrameEdge(typesetter.frame):tonumber() skipWidth = math.floor(skipWidth * 1e6) / 1e6 -- accept some rounding imprecision local skipRepetitions = math.ceil(skipWidth / leaderWidth) -- round up! local repetitions = maxRepetitions - skipRepetitions local remainder = fitWidth - maxRepetitions * leaderWidth SU.debug("leaders", "Leader repetitions: "..repetitions ..", skipped: "..skipRepetitions..", remainder: "..remainder.."pt") -- Return back to our start position typesetter.frame:advanceWritingDirection(-outputWidth) -- Handle the leader element repetitions if repetitions > 0 then typesetter.frame:advanceWritingDirection(remainder) for _ = 1, repetitions do if SU.debugging("leaders") then -- Draw some visible lines around leader repetitions. -- N.B. This might be wrong for other directions than LTR-TTB, but heh it's debug stuff. SILE.outputter:drawRule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-leaderWidth, leaderWidth-0.3, 0.3) SILE.outputter:drawRule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-leaderWidth, 0.3, leaderWidth-0.3) end self.value:outputYourself(typesetter, line) end if SU.debugging("leaders") then -- Draw some visible lines around skipped leader repetitions. -- N.B. This might be wrong for other directions than LTR-TTB, but it's debug stuff again. for _ = 0, skipRepetitions-1 do SILE.outputter:drawRule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY, leaderWidth, 0.3) SILE.outputter:drawRule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-leaderWidth, 0.3, leaderWidth) typesetter.frame:advanceWritingDirection(leaderWidth) end end end -- Return to our start (saved) position and move to the full leaders width. -- (So we are sure to safely get the correct width, whathever we did above -- with the remainder space and the leader repetitions). typesetter.frame.state.cursorX = ox typesetter.frame.state.cursorY = oy typesetter.frame:advanceWritingDirection(outputWidth) end local function registerCommands (_) SILE.registerCommand("leaders", function(options, content) local width = options.width and SU.cast("glue", options.width) or SILE.nodefactory.hfillglue() SILE.call("hbox", {}, content) local hbox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil local l = leader({ width = width, value = hbox }) table.insert(SILE.typesetter.state.nodes, l) end) SILE.registerCommand("dotfill", function(_, _) -- Implementation note: -- The "usual" space between dots in "modern days" is 0.5em (cf. "points -- conducteurs" in Frey & Bouchez, 1857), evenly distributed around the dot, -- though in older times it was sometimes up to 1em and could be distributed -- differently. Anyhow, it is also the approach taken by LaTeX, with a -- \@dotsep space of 4.5mu (where 18mu = 1em, so indeed leading to 0.25em). SILE.call("leaders", { width = SILE.nodefactory.hfillglue() }, function() SILE.call("kern", { width = SILE.length("0.25em") }) SILE.typesetter:typeset(".") SILE.call("kern", {width = SILE.length("0.25em") }) end) end) end return { registerCommands = registerCommands, documentation = [[ \begin{document} The \autodoc:package{leaders} package allows you to create repeating patterns which fill a given space. It provides the \autodoc:command{\dotfill} command, which does this: \begin{verbatim} \line A\\dotfill\{\}B \line \end{verbatim} \begin{examplefont} A\dotfill{}B\par \end{examplefont} It also provides the \autodoc:command{\leaders[width=<dimension>]{<content>}} command which allow you to define your own leaders. For example: \begin{verbatim} \line A\\leaders[width=40pt]\{/\\\\\}B \line \end{verbatim} \begin{examplefont} A\leaders[width=40pt]{/\\}B\par \end{examplefont} If the width is omitted, the leaders extend as much as possible (as a \autodoc:command{\dotfill} or \autodoc:command{\hfill}). Leader patterns are always vertically aligned, respectively to the end edge of the frame they appear in, for a given font. It implies that the number of repeated patterns and their positions do not only depend on the available space, but also on the alignment constraint and the active font. \end{document} ]] }
-- -- Leaders package -- local widthToFrameEdge = function (frame) local w if frame:writingDirection() == "LTR" then w = frame:right() - frame.state.cursorX elseif frame:writingDirection() == "RTL" then w = frame.state.cursorX - frame:left() elseif frame:writingDirection() == "TTB" then w = frame:bottom() - frame.state.cursorY elseif frame:writingDirection() == "BTT" then w = frame.state.cursorY - frame:top() else SU.error("Unknown writing direction") end return w end local leader = pl.class(SILE.nodefactory.glue) function leader:outputYourself (typesetter, line) local outputWidth = SU.rationWidth(self.width, self.width, line.ratio):tonumber() local leaderWidth = self.value.width:tonumber() local ox = typesetter.frame.state.cursorX local oy = typesetter.frame.state.cursorY -- Implementation note: -- We want leaders on different lines to be aligned vertically in the frame, -- from its end edge (e.g. the right edge in LTR writing direction). -- Compute how many leaders we can fit from the current initial position. local fitWidth = widthToFrameEdge(typesetter.frame):tonumber() local maxRepetitions = math.floor(fitWidth / leaderWidth) -- round down! -- Compute how many leaders we have to skip after our final position. typesetter.frame:advanceWritingDirection(outputWidth) local skipWidth = widthToFrameEdge(typesetter.frame):tonumber() skipWidth = math.floor(skipWidth * 1e6) / 1e6 -- accept some rounding imprecision local skipRepetitions = math.ceil(skipWidth / leaderWidth) -- round up! local repetitions = maxRepetitions - skipRepetitions local remainder = fitWidth - maxRepetitions * leaderWidth SU.debug("leaders", "Leader repetitions: "..repetitions ..", skipped: "..skipRepetitions..", remainder: "..remainder.."pt") -- Return back to our start position typesetter.frame:advanceWritingDirection(-outputWidth) -- Handle the leader element repetitions if repetitions > 0 then typesetter.frame:advanceWritingDirection(remainder) for _ = 1, repetitions do if SU.debugging("leaders") then -- Draw some visible lines around leader repetitions. -- N.B. This might be wrong for other directions than LTR-TTB, but heh it's debug stuff. SILE.outputter:drawRule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-leaderWidth, leaderWidth-0.3, 0.3) SILE.outputter:drawRule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-leaderWidth, 0.3, leaderWidth-0.3) end self.value:outputYourself(typesetter, line) end if SU.debugging("leaders") then -- Draw some visible lines around skipped leader repetitions. -- N.B. This might be wrong for other directions than LTR-TTB, but it's debug stuff again. for _ = 0, skipRepetitions-1 do SILE.outputter:drawRule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY, leaderWidth, 0.3) SILE.outputter:drawRule(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-leaderWidth, 0.3, leaderWidth) typesetter.frame:advanceWritingDirection(leaderWidth) end end end -- Return to our start (saved) position and move to the full leaders width. -- (So we are sure to safely get the correct width, whathever we did above -- with the remainder space and the leader repetitions). typesetter.frame.state.cursorX = ox typesetter.frame.state.cursorY = oy typesetter.frame:advanceWritingDirection(outputWidth) end local function registerCommands (_) SILE.registerCommand("leaders", function(options, content) local width = options.width and SU.cast("glue", options.width) or SILE.nodefactory.hfillglue() SILE.call("hbox", {}, content) local hbox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil local l = leader({ width = width, value = hbox }) SILE.typesetter:pushExplicitGlue(l) end) SILE.registerCommand("dotfill", function(_, _) -- Implementation note: -- The "usual" space between dots in "modern days" is 0.5em (cf. "points -- conducteurs" in Frey & Bouchez, 1857), evenly distributed around the dot, -- though in older times it was sometimes up to 1em and could be distributed -- differently. Anyhow, it is also the approach taken by LaTeX, with a -- \@dotsep space of 4.5mu (where 18mu = 1em, so indeed leading to 0.25em). SILE.call("leaders", { width = SILE.nodefactory.hfillglue() }, function() SILE.call("kern", { width = SILE.length("0.25em") }) SILE.typesetter:typeset(".") SILE.call("kern", {width = SILE.length("0.25em") }) end) end) end return { registerCommands = registerCommands, documentation = [[ \begin{document} The \autodoc:package{leaders} package allows you to create repeating patterns which fill a given space. It provides the \autodoc:command{\dotfill} command, which does this: \begin{verbatim} \line A\\dotfill\{\}B \line \end{verbatim} \begin{examplefont} A\dotfill{}B\par \end{examplefont} It also provides the \autodoc:command{\leaders[width=<dimension>]{<content>}} command which allow you to define your own leaders. For example: \begin{verbatim} \line A\\leaders[width=40pt]\{/\\\\\}B \line \end{verbatim} \begin{examplefont} A\leaders[width=40pt]{/\\}B\par \end{examplefont} If the width is omitted, the leaders extend as much as possible (as a \autodoc:command{\dotfill} or \autodoc:command{\hfill}). Leader patterns are always vertically aligned, respectively to the end edge of the frame they appear in, for a given font. It implies that the number of repeated patterns and their positions do not only depend on the available space, but also on the alignment constraint and the active font. \end{document} ]] }
fix(packages): Leaders shall be an explicit (non-discardable) glue
fix(packages): Leaders shall be an explicit (non-discardable) glue
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
cd57ca19294b0cebebf60839f7886c9f6f9ecd14
OS/DiskOS/Programs/run.lua
OS/DiskOS/Programs/run.lua
--This file loads a lk12 disk and execute it --First we will start by obtaining the disk data --We will run the current code in the editor print("") local eapi = require("C://Editors") local sprid = "spritesheet" local codeid = "luacode" local diskdata = eapi:export() diskdata = loadstring(diskdata)() --Load the spritesheet local SpriteMap, FlagsData if diskdata[sprid] then local sheetData = diskdata[sprid] local w,h,imgdata = string.match(sheetData,"LK12;GPUIMG;(%d+)x(%d+);(.+)") local sheetW, sheetH = w/8, h/8 FlagsData = imgdata:sub(w*h+1,-1) if FlagsData:len() < sheetW*sheetH then local missing = sheetW*sheetH local zerochar = string.char(0) for i=1,missing do FlagsData = FlagsData..zerochar end end imgdata = imgdata:sub(0,w*h) imgdata = "LK12;GPUIMG;"..w.."x"..h..";"..imgdata SpriteMap = SpriteSheet(imagedata(imgdata):image(),sheetW,sheetH) end --Load the code local luacode = diskdata[codeid]:sub(2,-1) --Remove the first empty line local diskchunk, err = loadstring(luacode) if not diskchunk then local err = tostring(err) local pos = string.find(err,":") err = err:sub(pos+1,-1) color(9) print("Compile ERR: "..err ) return end --Create the sandboxed global variables local glob = _FreshGlobals() glob._G = glob --Magic ;) glob.loadstring = function(...) local chunk, err = loadstring(...) if not chunk then return nil, err end setfenv(chunk,glob) return chunk end glob.coroutine.create = function(chunk) --if type(chunk) == "function" then setfenv(chunk,glob) end local ok,co = pcall(coroutine.create,chunk) if not ok then return error(co) end return co end --Add peripherals api local blocklist = { HDD = true } local _,perlist = coroutine.yield("BIOS:listPeripherals") for k, v in pairs(blocklist) do perlist[v] = nil end for peripheral,funcs in pairs(perlist) do for _,func in ipairs(funcs) do local command = peripheral..":"..func glob[func] = function(...) local args = {coroutine.yield(command,...)} if not args[1] then return error(args[2]) end local nargs = {} for k,v in ipairs(args) do if k >1 then table.insert(nargs,k-1,v) end end return unpack(nargs) end end end local apiloader = loadstring(fs.read("C://api.lua")) setfenv(apiloader,glob) apiloader() --Add special disk api glob.SpriteMap = SpriteMap glob.SheetFlagsData = FlagsData local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua")) if not helpersloader then error(err) end setfenv(helpersloader,glob) helpersloader() --Apply the sandbox setfenv(diskchunk,glob) --Create the coroutine local co = coroutine.create(diskchunk) --Too Long Without Yielding local checkclock = true local eventclock = os.clock() local lastclock = os.clock() coroutine.sethook(co,function() if os.clock() > lastclock + 3.5 and checkclock then error("Too Long Without Yielding",2) end end,"",10000) --Run the thing ! local function extractArgs(args,factor) local nargs = {} for k,v in ipairs(args) do if k > factor then table.insert(nargs,v) end end return nargs end local lastArgs = {} while true do if coroutine.status(co) == "dead" then break end --[[local name, key = rawPullEvent() if name == "keypressed" and key == "escape" then break end]] if os.clock() > eventclock + 3.5 then color(9) print("Too Long Without Pulling Event / Flipping") break end local args = {coroutine.resume(co,unpack(lastArgs))} checkclock = false if not args[1] then local err = tostring(args[2]) local pos = string.find(err,":") err = err:sub(pos+1,-1); color(9) print("ERR: "..err ); break end if args[2] then lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))} if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then eventclock = os.clock() if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then local name, key = rawPullEvent() if name == "keypressed" and key == "escape" then break end else if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then break end end end lastclock = os.clock() checkclock = true --lastclock = os.clock() end end coroutine.sethook(co) clearEStack() print("")
--This file loads a lk12 disk and execute it --First we will start by obtaining the disk data --We will run the current code in the editor print("") local eapi = require("C://Editors") local sprid = "spritesheet" local codeid = "luacode" local diskdata = eapi:export() diskdata = loadstring(diskdata)() --Load the spritesheet local SpriteMap, FlagsData if diskdata[sprid] then local sheetData = diskdata[sprid] local w,h,imgdata = string.match(sheetData,"LK12;GPUIMG;(%d+)x(%d+);(.+)") local sheetW, sheetH = w/8, h/8 FlagsData = imgdata:sub(w*h+1,-1) if FlagsData:len() < sheetW*sheetH then local missing = sheetW*sheetH local zerochar = string.char(0) for i=1,missing do FlagsData = FlagsData..zerochar end end imgdata = imgdata:sub(0,w*h) imgdata = "LK12;GPUIMG;"..w.."x"..h..";"..imgdata SpriteMap = SpriteSheet(imagedata(imgdata):image(),sheetW,sheetH) end --Load the code local luacode = diskdata[codeid]:sub(2,-1) --Remove the first empty line local diskchunk, err = loadstring(luacode) if not diskchunk then local err = tostring(err) local pos = string.find(err,":") err = err:sub(pos+1,-1) color(9) print("Compile ERR: "..err ) return end --Create the sandboxed global variables local glob = _FreshGlobals() glob._G = glob --Magic ;) glob.loadstring = function(...) local chunk, err = loadstring(...) if not chunk then return nil, err end setfenv(chunk,glob) return chunk end glob.coroutine.create = function(chunk) --if type(chunk) == "function" then setfenv(chunk,glob) end local ok,co = pcall(coroutine.create,chunk) if not ok then return error(co) end return co end --Add peripherals api local blocklist = { HDD = true } local perglob = {GPU = true, CPU = true, Keyboard = true} --The perihperals to make global not in a table. local _,perlist = coroutine.yield("BIOS:listPeripherals") for k, v in pairs(blocklist) do perlist[k] = nil end for peripheral,funcs in pairs(perlist) do local holder = glob; if not perglob[peripheral] then glob[peripheral] = {}; holder = glob[peripheral] end for _,func in ipairs(funcs) do local command = peripheral..":"..func holder[func] = function(...) local args = {coroutine.yield(command,...)} if not args[1] then return error(args[2]) end local nargs = {} for k,v in ipairs(args) do if k >1 then table.insert(nargs,k-1,v) end end return unpack(nargs) end end end local apiloader = loadstring(fs.read("C://api.lua")) setfenv(apiloader,glob) apiloader() --Add special disk api glob.SpriteMap = SpriteMap glob.SheetFlagsData = FlagsData local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua")) if not helpersloader then error(err) end setfenv(helpersloader,glob) helpersloader() --Apply the sandbox setfenv(diskchunk,glob) --Create the coroutine local co = coroutine.create(diskchunk) --Too Long Without Yielding local checkclock = true local eventclock = os.clock() local lastclock = os.clock() coroutine.sethook(co,function() if os.clock() > lastclock + 3.5 and checkclock then error("Too Long Without Yielding",2) end end,"",10000) --Run the thing ! local function extractArgs(args,factor) local nargs = {} for k,v in ipairs(args) do if k > factor then table.insert(nargs,v) end end return nargs end local lastArgs = {} while true do if coroutine.status(co) == "dead" then break end --[[local name, key = rawPullEvent() if name == "keypressed" and key == "escape" then break end]] if os.clock() > eventclock + 3.5 then color(9) print("Too Long Without Pulling Event / Flipping") break end local args = {coroutine.resume(co,unpack(lastArgs))} checkclock = false if not args[1] then local err = tostring(args[2]) local pos = string.find(err,":") err = err:sub(pos+1,-1); color(9) print("ERR: "..err ); break end if args[2] then lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))} if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then eventclock = os.clock() if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then local name, key = rawPullEvent() if name == "keypressed" and key == "escape" then break end else if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then break end end end lastclock = os.clock() checkclock = true --lastclock = os.clock() end end coroutine.sethook(co) clearEStack() print("")
Bugfix for the sandbox
Bugfix for the sandbox
Lua
mit
RamiLego4Game/LIKO-12
e70dd603a49bf01ea8044b04aa2ba11c37d2ac75
lib/resty/consul.lua
lib/resty/consul.lua
local pcall = pcall local cjson = require('cjson') local json_decode = cjson.decode local json_encode = cjson.encode local tbl_concat = table.concat local ngx = ngx local ngx_socket_tcp = ngx.socket.tcp local ngx_log = ngx.log local ngx_ERR = ngx.ERR local ngx_DEBUG = ngx.DEBUG local http = require('resty.http') local _M = { _VERSION = '0.01', } local API_VERSION = "v1" local DEFAULT_HOST = "127.0.0.1" local DEFAULT_PORT = 8500 local DEFAULT_TIMEOUT = 60*1000 -- 60s efault timeout local mt = { __index = _M } local function safe_json_decode(json_str) local ok, json = pcall(json_decode, json_str) if ok then return json else ngx_log(ngx_ERR, json) end end local function build_uri(key, opts) local uri = "/"..API_VERSION..key if opts then local params = {} for k,v in pairs(opts) do tbl_insert(params, k.."="..v) end uri = uri.."?"..tbl_concat(opts, "&") end return uri end function _M.new(_, opts) local self = { host = opts.host or DEFAULT_HOST, port = opts.port or DEFAULT_PORT, connect_timeout = opts.connect_timeout or DEFAULT_TIMEOUT, read_timeout = opts.read_timeout or DEFAULT_TIMEOUT } return setmetatable(self, mt) end function _M.get_client_body_reader(self, ...) return http:get_client_body_reader(...) end local function connect(self) local httpc = http.new() local connect_timeout = self.connect_timeout if connect_timeout then httpc:set_timeout(connect_timeout) end local ok, err = httpc:connect(self.host, self.port) if not ok then return nil, err end return httpc end local function _get(httpc, key, opts) local uri = build_uri(key, opts) local res, err = httpc:request({path = uri}) if not res then return nil, err end local status = res.status if not status then return nil, "No status from consul" elseif status ~= 200 then if status == 404 then return nil, "Key not found" else return nil, "Consul returned: HTTP "..status end end local body, err = res:read_body() if not body then return nil, err end local response = safe_json_decode(body) local headers = res.headers return response, headers["X-Consul-Lastcontact"], headers["X-Consul-Knownleader"] end function _M.get(self, key, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if opts and (opts.wait or opts.index) then -- Blocking request, increase timeout local timeout = 10 * 60 -- Default timeout is 10m if opts.wait then timeout = opts.wait * 1000 end local ok,err = httpc:set_timeout(timeout) if not ok then return ok, err end else httpc:set_timeout(self.read_timeout) end local res, lastcontact_or_err, knownleader = _get(httpc, key, opts) httpc:set_keepalive() if not res then return nil, lastcontact_or_err end return res, {lastcontact_or_err, knownleader} end function _M.get_decoded(self, key, opts) local res, err = self:get(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do if type(entry.Value) == "string" then local decoded = ngx.decode_base64(entry.Value) if decoded ~= nil then entry.Value = decoded end end end return res, err end function _M.get_json_decoded(self, key, opts) local res, err = self:get_decoded(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do local decoded = safe_json_decode(entry.Value) if decoded ~= nil then entry.Value = decoded end end return res, err end function _M.put(self, key, value, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end local uri = build_uri(key, opts) local res, err = httpc:request({ method = "PUT", path = uri, body = value }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() return (body == "true\n") end function _M.delete(self, key, recurse) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if recurse then recurse = {recurse = true} end local uri = build_uri(key, recurse) local res, err = httpc:request({ method = "DELETE", path = uri, }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() if res.status == 200 then return true end -- DELETE seems to return 200 regardless, but just in case return {status = res.status, body = body, headers = res.headers}, err end return _M
local pcall = pcall local cjson = require('cjson') local json_decode = cjson.decode local json_encode = cjson.encode local tbl_concat = table.concat local tbl_insert = table.insert local ngx = ngx local ngx_log = ngx.log local ngx_ERR = ngx.ERR local ngx_DEBUG = ngx.DEBUG local http = require('resty.http') local _M = { _VERSION = '0.01', } local API_VERSION = "v1" local DEFAULT_HOST = "127.0.0.1" local DEFAULT_PORT = 8500 local DEFAULT_TIMEOUT = 60*1000 -- 60s efault timeout local mt = { __index = _M } function _M.new(_, opts) local self = { host = opts.host or DEFAULT_HOST, port = opts.port or DEFAULT_PORT, connect_timeout = opts.connect_timeout or DEFAULT_TIMEOUT, read_timeout = opts.read_timeout or DEFAULT_TIMEOUT } return setmetatable(self, mt) end function _M.get_client_body_reader(self, ...) return http:get_client_body_reader(...) end local function safe_json_decode(json_str) local ok, json = pcall(json_decode, json_str) if ok then return json else ngx_log(ngx_ERR, json) end end local function build_uri(key, opts) local uri = "/"..API_VERSION..key if opts then local params = {} for k,v in pairs(opts) do tbl_insert(params, k.."="..v) end uri = uri.."?"..tbl_concat(params, "&") end return uri end local function connect(self) local httpc = http.new() local connect_timeout = self.connect_timeout if connect_timeout then httpc:set_timeout(connect_timeout) end local ok, err = httpc:connect(self.host, self.port) if not ok then return nil, err end return httpc end local function _get(httpc, key, opts) local uri = build_uri(key, opts) local res, err = httpc:request({path = uri}) if not res then return nil, err end local status = res.status if not status then return nil, "No status from consul" elseif status ~= 200 then if status == 404 then return nil, "Key not found" else return nil, "Consul returned: HTTP "..status end end local body, err = res:read_body() if not body then return nil, err end local response = safe_json_decode(body) local headers = res.headers return response, headers["X-Consul-Lastcontact"], headers["X-Consul-Knownleader"] end function _M.get(self, key, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if opts and (opts.wait or opts.index) then -- Blocking request, increase timeout local timeout = 10 * 60 * 1000 -- Default timeout is 10m if opts.wait then timeout = opts.wait * 1000 end httpc:set_timeout(timeout) else httpc:set_timeout(self.read_timeout) end local res, lastcontact_or_err, knownleader = _get(httpc, key, opts) httpc:set_keepalive() if not res then return nil, lastcontact_or_err end return res, {lastcontact_or_err, knownleader} end function _M.get_decoded(self, key, opts) local res, err = self:get(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do if type(entry.Value) == "string" then local decoded = ngx.decode_base64(entry.Value) if decoded ~= nil then entry.Value = decoded end end end return res, err end function _M.get_json_decoded(self, key, opts) local res, err = self:get_decoded(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do local decoded = safe_json_decode(entry.Value) if decoded ~= nil then entry.Value = decoded end end return res, err end function _M.put(self, key, value, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end local uri = build_uri(key, opts) local res, err = httpc:request({ method = "PUT", path = uri, body = value }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() return (body == "true\n") end function _M.delete(self, key, recurse) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if recurse then recurse = {recurse = true} end local uri = build_uri(key, recurse) local res, err = httpc:request({ method = "DELETE", path = uri, }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() if res.status == 200 then return true end -- DELETE seems to return 200 regardless, but just in case return {status = res.status, body = body, headers = res.headers}, err end return _M
Fix blocking get
Fix blocking get
Lua
mit
hamishforbes/lua-resty-consul
af58264598eca406fcbd907c1193b74a030c37c3
lib/resty/github.lua
lib/resty/github.lua
-- Copyright (C) James Marlowe (jamesmarlowe), Lumate LLC. local cjson = require "cjson" local github_proxy_url = "/github/v3/" local issue_url = "/repos/${owner}/${repo}/issues/${issue}" -- obtain a copy of enc() here: http://lua-users.org/wiki/BaseSixtyFour function enc(data) -- character table string local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' return ((data:gsub('.', function(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return b:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- a string replacement function function macro_replace(s,tab) return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end)) end local ok, new_tab = pcall(require, "table.new") if not ok then new_tab = function (narr, nrec) return {} end end local _M = new_tab(0, 155) _M._VERSION = '0.01' local mt = { __index = _M } function _M.new(self, access_token ) local access_token = access_token if not access_token then return nil, "must provide access_token " end return setmetatable({ access_token = access_token }, mt) end function _M.get_issues(self, owner, repo, state, issue) local access_token = self.access_token if not access_token then return nil, "not initialized" end if not owner then return nil, "no owner" end if not repo then return nil, "no repo" end local parameter_specification = { state = state, issue = issue } local repo_specification = { owner = owner, repo = repo, issue = "" } resp = ngx.location.capture( github_proxy_url, { method = ngx.HTTP_GET, body = cjson.encode(parameter_specification), args = {api_method = macro_replace(issue_url,repo_specification), authentication = enc(access_token..":x-oauth-basic")}} ) if resp.status ~= 200 then return nil, resp.status.." : "..resp.body end return resp.body end function _M.new_issue(self, owner, repo, title, body) local access_token = self.access_token if not access_token then return nil, "not initialized" end if not title then return nil, "no title specified" end if not body then return nil, "no body specified" end local parameter_specification = { title = title, body = body } local repo_specification = { owner = owner, repo = repo, issue = "" } resp = ngx.location.capture( github_proxy_url, { method = ngx.HTTP_POST, body = cjson.encode(parameter_specification), args = {api_method = macro_replace(issue_url,repo_specification), authentication = enc(access_token..":x-oauth-basic")}} ) if resp.status ~= 200 then return nil, resp.status.." : "..resp.body end return resp.body end return _M
-- Copyright (C) James Marlowe (jamesmarlowe), Lumate LLC. local cjson = require "cjson" local github_proxy_url = "/github/v3/" local issue_url = "/repos/${owner}/${repo}/issues${issue}" -- obtain a copy of enc() here: http://lua-users.org/wiki/BaseSixtyFour function enc(data) -- character table string local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' return ((data:gsub('.', function(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return b:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- a string replacement function function macro_replace(s,tab) return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end)) end local ok, new_tab = pcall(require, "table.new") if not ok then new_tab = function (narr, nrec) return {} end end local _M = new_tab(0, 155) _M._VERSION = '0.01' local valid_state_values = { open = "open", closed = "closed", all = "all" } local mt = { __index = _M } function _M.new(self, access_token ) local access_token = access_token if not access_token then return nil, "must provide access_token " end return setmetatable({ access_token = access_token }, mt) end function _M.get_issues(self, owner, repo, state, issue) local access_token = self.access_token if not access_token then return nil, "not initialized" end if not owner then return nil, "no owner" end if not repo then return nil, "no repo" end local state = state and valid_state_values[state] or "open" local parameter_specification = { state = state } local repo_specification = { owner = owner, repo = repo, issue = issue and "/"..issue or "" } resp = ngx.location.capture( github_proxy_url, { method = ngx.HTTP_GET, body = cjson.encode(parameter_specification), args = {api_method = macro_replace(issue_url,repo_specification), authentication = enc(access_token..":x-oauth-basic")}} ) if resp.status ~= 200 then return nil, resp.status.." : "..resp.body end return resp.body end function _M.new_issue(self, owner, repo, title, body) local access_token = self.access_token if not access_token then return nil, "not initialized" end if not title then return nil, "no title specified" end if not body then return nil, "no body specified" end local parameter_specification = { title = title, body = body } local repo_specification = { owner = owner, repo = repo, issue = "" } resp = ngx.location.capture( github_proxy_url, { method = ngx.HTTP_POST, body = cjson.encode(parameter_specification), args = {api_method = macro_replace(issue_url,repo_specification), authentication = enc(access_token..":x-oauth-basic")}} ) if resp.status ~= 200 then return nil, resp.status.." : "..resp.body end return resp.body end return _M
minor fixes
minor fixes
Lua
bsd-2-clause
jamesmarlowe/lua-resty-github
2802d9b14318a514da5fa56bfb60f67b698db51b
packages/rebox.lua
packages/rebox.lua
SILE.registerCommand("rebox", function (options, content) local box = SILE.call("hbox", {}, content) if options.width then box.width = SILE.length(options.width) end if options.height then box.height = SILE.length(options.height) end if options.depth then box.depth = SILE.length(options.depth) end if options.phantom then box.outputYourself = function (self, typesetter, line) typesetter.frame:advanceWritingDirection(self:scaledWidth(line)) end end table.insert(SILE.typesetter.state.nodes, box) end, "Place the output within a box of specified width, height, depth and visibility") return { documentation = [[ \begin{document} This package provides the \code{\\rebox} command, which allows you to lie to SILE about the size of content. You can change the \code{width}, \code{height}, or \code{depth} of your content with the respective parameters, or make it invisible by using the \code{phantom} parameter. For example: \begin{verbatim} \line Hello \\rebox[width=0pt]\{world\}overprint. Look I’m not \\rebox[phantom=true]\{here\}! \line \end{verbatim} \begin{examplefont} Hello \rebox[width=0pt]{world}overprint. Look I’m not \rebox[phantom=true]{here}! \end{examplefont} \end{document} ]] }
SILE.registerCommand("rebox", function (options, content) local box = SILE.call("hbox", {}, content) table.remove(SILE.typesetter.state.nodes) -- steal it back if options.width then box.width = SILE.length(options.width) end if options.height then box.height = SILE.length(options.height) end if options.depth then box.depth = SILE.length(options.depth) end if options.phantom then box.outputYourself = function (self, typesetter, line) typesetter.frame:advanceWritingDirection(self:scaledWidth(line)) end end table.insert(SILE.typesetter.state.nodes, box) end, "Place the output within a box of specified width, height, depth and visibility") return { documentation = [[ \begin{document} This package provides the \code{\\rebox} command, which allows you to lie to SILE about the size of content. You can change the \code{width}, \code{height}, or \code{depth} of your content with the respective parameters, or make it invisible by using the \code{phantom} parameter. For example: \begin{verbatim} \line Hello \\rebox[width=0pt]\{world\}overprint. Look I’m not \\rebox[phantom=true]\{here\}! \line \end{verbatim} \begin{examplefont} Hello \rebox[width=0pt]{world}overprint. Look I’m not \rebox[phantom=true]{here}! \end{examplefont} \end{document} ]] }
fix(packages): Correct rebox to not output duplicate content
fix(packages): Correct rebox to not output duplicate content
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
1819e1898e1cc0e932089bfc43e343755debc7f2
.config/nvim/lua/config/neo-tree.lua
.config/nvim/lua/config/neo-tree.lua
local status_ok, p = pcall(require, "neo-tree") if not status_ok then return end p.setup({ popup_border_style = "rounded", default_component_configs = { git_status = { symbols = { -- Change type added = "", -- or "✚", but this is redundant info if you use git_status_colors on the name modified = "", -- or "", but this is redundant info if you use git_status_colors on the name deleted = "✖", -- this can only be used in the git_status source renamed = "➜", -- this can only be used in the git_status source -- Status type untracked = "", ignored = "◌", unstaged = "", staged = "", conflict = "", }, }, }, window = { mappings = { ["u"] = "navigate_up", ["l"] = "open", ["<BS>"] = "close_node", ["h"] = "close_node", ["s"] = "open_split", ["-"] = "open_split", ["v"] = "open_vsplit", ["|"] = "open_vsplit", ["t"] = "open_tabnew", ["w"] = "open_with_window_picker", ["<C-c>"] = "close_window", ["f"] = "filter_as_you_type", ["/"] = "filter_on_submit", ["<C-]>"] = "set_root", ["i"] = { "add", config = { show_path = "relative", }, }, ["y"] = function(state) local node = state.tree:get_node() local name = node.name vim.fn.setreg("+", name) vim.fn.setreg('"', name) print("Copied: " .. name) end, ["Y"] = function(state) local node = state.tree:get_node() local path = vim.fn.fnamemodify(node.path, ":.") vim.fn.setreg("+", path) vim.fn.setreg('"', path) print("Copied: " .. path) end, ["gy"] = function(state) local node = state.tree:get_node() local path = node.path vim.fn.setreg("+", path) vim.fn.setreg('"', path) print("Copied: " .. path) end, }, }, filesystem = { filtered_items = { hide_dotfiles = false, hide_hidden = false, hide_gitignored = false, }, -- hijack_netrw_behavior = "disabled", follow_current_file = true, }, }) local opts = { noremap = true, silent = true } local keymap = vim.api.nvim_set_keymap keymap("n", "-", "<Cmd>Neotree float reveal_force_cwd<CR>", opts) keymap("n", "<Leader>e", "<Cmd>NeoTreeFocusToggle<CR>", opts)
local status_ok, p = pcall(require, "neo-tree") if not status_ok then return end p.setup({ use_default_mappings = false, popup_border_style = "rounded", default_component_configs = { git_status = { symbols = { -- Change type added = "", -- or "✚", but this is redundant info if you use git_status_colors on the name modified = "", -- or "", but this is redundant info if you use git_status_colors on the name deleted = "✖", -- this can only be used in the git_status source renamed = "➜", -- this can only be used in the git_status source -- Status type untracked = "", ignored = "◌", unstaged = "", staged = "", conflict = "", }, }, }, window = { mappings = { ["u"] = "navigate_up", ["l"] = "open", ["<CR>"] = "open", ["<BS>"] = "close_node", ["h"] = "close_node", ["H"] = "toggle_hidden", ["s"] = "open_split", ["-"] = "open_split", ["v"] = "open_vsplit", ["|"] = "open_vsplit", ["t"] = "open_tabnew", ["f"] = "filter_on_submit", ["<C-]>"] = "set_root", ["<C-c><C-c>"] = "clear_filter", ["i"] = { "add", config = { show_path = "relative", }, }, ["o"] = "add_directory", ["d"] = "delete", ["r"] = "rename", ["c"] = "copy", ["m"] = "move", -- takes text input for destination, also accepts the optional config.show_path option like "add". ["q"] = "close_window", ["R"] = "refresh", ["?"] = "show_help", ["[g"] = "prev_git_modified", ["]g"] = "next_git_modified", ["C"] = "close_all_nodes", ["y"] = function(state) local node = state.tree:get_node() local name = node.name vim.fn.setreg("+", name) vim.fn.setreg('"', name) print("Copied: " .. name) end, ["Y"] = function(state) local node = state.tree:get_node() local path = vim.fn.fnamemodify(node.path, ":.") vim.fn.setreg("+", path) vim.fn.setreg('"', path) print("Copied: " .. path) end, ["gy"] = function(state) local node = state.tree:get_node() local path = node.path vim.fn.setreg("+", path) vim.fn.setreg('"', path) print("Copied: " .. path) end, }, }, filesystem = { filtered_items = { hide_dotfiles = false, hide_hidden = false, hide_gitignored = false, }, hijack_netrw_behavior = "open_current", follow_current_file = true, never_show = { ".DS_Store", "thumbs.db", }, }, }) local opts = { noremap = true, silent = true } local keymap = vim.api.nvim_set_keymap keymap("n", "-", "<Cmd>Neotree float reveal_force_cwd<CR>", opts) keymap("n", "<Leader>e", "<Cmd>NeoTreeFocusToggle<CR>", opts)
[nvim] Fix neo-tree config
[nvim] Fix neo-tree config
Lua
mit
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
819b0e7193f84d36f0d689efdc19fef2415f386b
plugins/mod_http.lua
plugins/mod_http.lua
-- Prosody IM -- Copyright (C) 2008-2012 Matthew Wild -- Copyright (C) 2008-2012 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- module:set_global(); module:depends("http_errors"); local moduleapi = require "core.moduleapi"; local url_parse = require "socket.url".parse; local server = require "net.http.server"; server.set_default_host(module:get_option_string("http_default_host")); local function normalize_path(path) if path:sub(1,1) ~= "/" then path = "/"..path; end if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end return path; end local function get_http_event(host, app_path, key) local method, path = key:match("^(%S+)%s+(.+)$"); if not method then -- No path specified, default to "" (base path) method, path = key, ""; end if method:sub(1,1) == "/" then return nil; end return method:upper().." "..host..app_path..path; end local function get_base_path(host_module, app_name, default_app_path) return normalize_path(host_module:get_option("http_paths", {})[app_name] -- Host or module:get_option("http_paths", {})[app_name] -- Global or default_app_path); -- Default end -- Helper to deduce a module's external URL function moduleapi.http_url(module, app_name, default_path) app_name = app_name or (module.name:gsub("^http_", "")); local ext = url_parse(module:get_option_string("http_external_url")) or {}; local services = portmanager.get_active_services(); local http_services = services:get("https") or services:get("http"); for interface, ports in pairs(http_services) do for port, services in pairs(ports) do local path = get_base_path(module, app_name, default_path or "/"..app_name); port = tonumber(ext.port) or port or 80; if port == 80 then port = ""; else port = ":"..port; end return (ext.scheme or services[1].service.name).."://" ..(ext.host or module.host)..port ..normalize_path(ext.path or "/")..(path:sub(2)); end end end function module.add_host(module) local host = module.host; local apps = {}; module.environment.apps = apps; local function http_app_added(event) local app_name = event.item.name; local default_app_path = event.item.default_path or "/"..app_name; local app_path = get_base_path(module, app_name, default_app_path); if not app_name then -- TODO: Link to docs module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)"); return; end apps[app_name] = apps[app_name] or {}; local app_handlers = apps[app_name]; for key, handler in pairs(event.item.route or {}) do local event_name = get_http_event(host, app_path, key); if event_name then if type(handler) ~= "function" then local data = handler; handler = function () return data; end elseif event_name:sub(-2, -1) == "/*" then local base_path = event_name:match("/(.+)/*$"); local _handler = handler; handler = function (event) local path = event.request.path:sub(#base_path+1); return _handler(event, path); end; end if not app_handlers[event_name] then app_handlers[event_name] = handler; module:hook_object_event(server, event_name, handler); else module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name); end else module:log("error", "Invalid route in %s, %q. See http://prosody.im/doc/developers/http#routes", app_name, key); end end end local function http_app_removed(event) local app_handlers = apps[event.item.name]; apps[event.item.name] = nil; for event, handler in pairs(app_handlers) do module:unhook_object_event(server, event, handler); end end module:handle_items("http-provider", http_app_added, http_app_removed); server.add_host(host); function module.unload() server.remove_host(host); end end module:add_item("net-provider", { name = "http"; listener = server.listener; default_port = 5280; multiplex = { pattern = "^[A-Z]"; }; }); module:add_item("net-provider", { name = "https"; listener = server.listener; default_port = 5281; encryption = "ssl"; multiplex = { pattern = "^[A-Z]"; }; });
-- Prosody IM -- Copyright (C) 2008-2012 Matthew Wild -- Copyright (C) 2008-2012 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- module:set_global(); module:depends("http_errors"); local moduleapi = require "core.moduleapi"; local url_parse = require "socket.url".parse; local server = require "net.http.server"; server.set_default_host(module:get_option_string("http_default_host")); local function normalize_path(path) if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end if path:sub(1,1) ~= "/" then path = "/"..path; end return path; end local function get_http_event(host, app_path, key) local method, path = key:match("^(%S+)%s+(.+)$"); if not method then -- No path specified, default to "" (base path) method, path = key, ""; end if method:sub(1,1) == "/" then return nil; end return method:upper().." "..host..app_path..path; end local function get_base_path(host_module, app_name, default_app_path) return normalize_path(host_module:get_option("http_paths", {})[app_name] -- Host or module:get_option("http_paths", {})[app_name] -- Global or default_app_path); -- Default end -- Helper to deduce a module's external URL function moduleapi.http_url(module, app_name, default_path) app_name = app_name or (module.name:gsub("^http_", "")); local ext = url_parse(module:get_option_string("http_external_url")) or {}; local services = portmanager.get_active_services(); local http_services = services:get("https") or services:get("http"); for interface, ports in pairs(http_services) do for port, services in pairs(ports) do local path = get_base_path(module, app_name, default_path or "/"..app_name); port = tonumber(ext.port) or port or 80; if port == 80 then port = ""; else port = ":"..port; end return (ext.scheme or services[1].service.name).."://" ..(ext.host or module.host)..port ..normalize_path(ext.path or "/")..(path:sub(2)); end end end function module.add_host(module) local host = module.host; local apps = {}; module.environment.apps = apps; local function http_app_added(event) local app_name = event.item.name; local default_app_path = event.item.default_path or "/"..app_name; local app_path = get_base_path(module, app_name, default_app_path); if not app_name then -- TODO: Link to docs module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)"); return; end apps[app_name] = apps[app_name] or {}; local app_handlers = apps[app_name]; for key, handler in pairs(event.item.route or {}) do local event_name = get_http_event(host, app_path, key); if event_name then if type(handler) ~= "function" then local data = handler; handler = function () return data; end elseif event_name:sub(-2, -1) == "/*" then local base_path = event_name:match("/(.+)/*$"); local _handler = handler; handler = function (event) local path = event.request.path:sub(#base_path+1); return _handler(event, path); end; end if not app_handlers[event_name] then app_handlers[event_name] = handler; module:hook_object_event(server, event_name, handler); else module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name); end else module:log("error", "Invalid route in %s, %q. See http://prosody.im/doc/developers/http#routes", app_name, key); end end end local function http_app_removed(event) local app_handlers = apps[event.item.name]; apps[event.item.name] = nil; for event, handler in pairs(app_handlers) do module:unhook_object_event(server, event, handler); end end module:handle_items("http-provider", http_app_added, http_app_removed); server.add_host(host); function module.unload() server.remove_host(host); end end module:add_item("net-provider", { name = "http"; listener = server.listener; default_port = 5280; multiplex = { pattern = "^[A-Z]"; }; }); module:add_item("net-provider", { name = "https"; listener = server.listener; default_port = 5281; encryption = "ssl"; multiplex = { pattern = "^[A-Z]"; }; });
mod_http: Fix normalize_path('/') to not return an empty string, fixes module:http_url()
mod_http: Fix normalize_path('/') to not return an empty string, fixes module:http_url()
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
c4779c03609b3bca76ab5c242a4542e385d7b7c3
mock/core/signal.lua
mock/core/signal.lua
--[[ * MOCK framework for Moai * Copyright (C) 2012 Tommo Zhou([email protected]). All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -------------------------------------------------------------------- local insert = table.insert local setmetatable = setmetatable local staticHolder = {} local signalProto = {} local signalMT = { __index = signalProto } local weakMT = { __mode = 'v', } local function newSignal() local signal = setmetatable( { slots = setmetatable( {}, weakMT ) }, signalMT ) return signal end local function signalConnect( sig, obj, func ) sig.slots[ obj ] = func return obj, func end local function signalConnectFunc( sig, func ) sig.slots[ func ] = staticHolder return func end local function signalDisconnect( sig, obj ) sig.slots[ obj ] = nil end local function signalDisconnectAll( sig ) sig.slots = {} end local function signalEmit( sig, ... ) local slots = sig.slots for obj, func in pairs( slots ) do if func == staticHolder then obj( ... ) else func( obj, ... ) end end end signalMT.__call = signalEmit function signalProto:connect( a, b ) if (not b) and ( type( a ) == 'function' ) then --function connection return signalConnectFunc( self, a ) elseif type( b ) == 'string' then func = a[ b ] return signalConnect( self, a, func ) else return signalConnect( self, a, b ) end end function signalProto:disconnect( a ) return signalDisconnect( self, a ) end function signalProto:disconnectAll() return signalDisconnectAll( self ) end -------------------------------------------------------------------- --GLOBAL SIGALS -------------------------------------------------------------------- local globalSignalTable = {} local weakmt = {__mode='v'} local function registerGlobalSignal( sigName ) --TODO: add module info for unregistration assert( type(sigName) == 'string', 'signal name should be string' ) local sig = globalSignalTable[sigName] if sig then _warn('duplicated signal name:'..sigName) end -- sig=setmetatable({},weakmt) sig = newSignal() globalSignalTable[sigName] = sig return sig end local function registerGlobalSignals( sigTable ) for i,k in ipairs( sigTable ) do registerGlobalSignal( k ) --TODO: add module info for unregistration end end local function getGlobalSignal( sigName ) local sig = globalSignalTable[ sigName ] if not sig then return error( 'signal not found:'..sigName ) end return sig end local function connectGlobalSignalFunc( sigName, func ) local sig = getGlobalSignal( sigName ) signalConnectFunc( sig, func ) return s end local function connectGlobalSignalMethod( sigName, obj, methodname ) local sig = getGlobalSignal(sigName) local method = assert( obj[ methodname ], 'method not found' ) signalConnect( sig, obj, method ) return sig end local function disconnectGlobalSignal( sigName, obj ) local sig = getGlobalSignal(sigName) signalDisconnect( sig, obj ) end local function emitGlobalSignal( sigName, ... ) local sig = getGlobalSignal( sigName ) return signalEmit( sig, ... ) end -------------------------------------------------------------------- --EXPORT -------------------------------------------------------------------- _G.newSignal = newSignal _G.signalConnect = signalConnect _G.signalConnectFunc = signalConnectFunc _G.signalEmit = signalEmit _G.signalDisconnect = signalDisconnect -------------------------------------------------------------------- _G.connectSignal = connectSignalFunc _G.registerSignal = registerGlobalSignal _G.registerGlobalSignal = registerGlobalSignal _G.registerSignals = registerGlobalSignals _G.registerGlobalSignals = registerGlobalSignals _G.getSignal = getGlobalSignal _G.connectSignalFunc = connectGlobalSignalFunc _G.connectSignalMethod = connectGlobalSignalMethod _G.disconnectSignal = disconnectGlobalSignal _G.emitSignal = emitGlobalSignal
--[[ * MOCK framework for Moai * Copyright (C) 2012 Tommo Zhou([email protected]). All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -------------------------------------------------------------------- local insert = table.insert local setmetatable = setmetatable local staticHolder = {} local signalProto = {} local signalMT = { __index = signalProto } local weakMT = { __mode = 'v', } local function newSignal() local signal = setmetatable( { slots = setmetatable( {}, weakMT ) }, signalMT ) return signal end local function signalConnect( sig, obj, func ) sig.slots[ obj ] = func return obj, func end local function signalConnectFunc( sig, func ) sig.slots[ func ] = staticHolder return func end local function signalDisconnect( sig, obj ) sig.slots[ obj ] = nil end local function signalDisconnectAll( sig ) sig.slots = {} end local function signalEmit( sig, ... ) local slots = sig.slots for obj, func in pairs( slots ) do if func == staticHolder then obj( ... ) else func( obj, ... ) end end end signalMT.__call = signalEmit function signalProto:connect( a, b ) if (not b) and ( type( a ) == 'function' ) then --function connection return signalConnectFunc( self, a ) elseif type( b ) == 'string' then func = a[ b ] return signalConnect( self, a, func ) else return signalConnect( self, a, b ) end end function signalProto:disconnect( a ) return signalDisconnect( self, a ) end function signalProto:disconnectAll() return signalDisconnectAll( self ) end -------------------------------------------------------------------- --GLOBAL SIGALS -------------------------------------------------------------------- local globalSignalTable = {} local weakmt = {__mode='v'} local function registerGlobalSignal( sigName ) --TODO: add module info for unregistration assert( type(sigName) == 'string', 'signal name should be string' ) local sig = globalSignalTable[sigName] if sig then _warn('duplicated signal name:'..sigName) end -- sig=setmetatable({},weakmt) sig = newSignal() globalSignalTable[sigName] = sig return sig end local function registerGlobalSignals( sigTable ) for i,k in ipairs( sigTable ) do registerGlobalSignal( k ) --TODO: add module info for unregistration end end local function getGlobalSignal( sigName ) local sig = globalSignalTable[ sigName ] if not sig then return error( 'signal not found:'..sigName ) end return sig end local function connectGlobalSignalFunc( sigName, func ) local sig = getGlobalSignal( sigName ) signalConnectFunc( sig, func ) return s end local function connectGlobalSignalMethod( sigName, obj, methodname ) local sig = getGlobalSignal(sigName) local method = assert( obj[ methodname ], 'method not found' ) signalConnect( sig, obj, method ) return sig end local function disconnectGlobalSignal( sigName, obj ) local sig = getGlobalSignal(sigName) signalDisconnect( sig, obj ) end local function emitGlobalSignal( sigName, ... ) local sig = getGlobalSignal( sigName ) return signalEmit( sig, ... ) end -------------------------------------------------------------------- --EXPORT -------------------------------------------------------------------- _G.newSignal = newSignal _G.signalConnect = signalConnect _G.signalConnectFunc = signalConnectFunc _G.signalEmit = signalEmit _G.signalDisconnect = signalDisconnect -------------------------------------------------------------------- _G.connectSignal = connectSignalFunc _G.registerSignal = registerGlobalSignal _G.registerGlobalSignal = registerGlobalSignal _G.registerSignals = registerGlobalSignals _G.registerGlobalSignals = registerGlobalSignals _G.getSignal = getGlobalSignal _G.connectSignalFunc = connectGlobalSignalFunc _G.connectSignalMethod = connectGlobalSignalMethod _G.disconnectSignal = disconnectGlobalSignal _G.emitSignal = emitGlobalSignal _G.getGlobalSignal = getGlobalSignal _G.connectGlobalSignalFunc = connectGlobalSignalFunc _G.connectGlobalSignalMethod = connectGlobalSignalMethod _G.disconnectGlobalSignal = disconnectGlobalSignal _G.emitGlobalSignal = emitGlobalSignal
add 'global' prefix to global signal functions
add 'global' prefix to global signal functions
Lua
mit
tommo/mock
8c977451a8d6336a28bf07bc4a3762bd62500720
mods/stairs/init.lua
mods/stairs/init.lua
-- Minetest 0.4 mod: stairs -- See README.txt for licensing and other information. stairs = {} -- Node will be called stairs:stair_<subname> function stairs.register_stair(subname, recipeitem, groups, images, description, sounds) minetest.register_node("stairs:stair_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end local p0 = pointed_thing.under local p1 = pointed_thing.above if p0.y-1 == p1.y then local fakestack = ItemStack("stairs:stair_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_node("stairs:stair_" .. subname.."upside_down", { drop = "stairs:stair_" .. subname, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = { {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, {-0.5, -0.5, 0, 0.5, 0, 0.5}, }, }, }) minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 4', recipe = { {recipeitem, "", ""}, {recipeitem, recipeitem, ""}, {recipeitem, recipeitem, recipeitem}, }, }) -- Flipped recipe for the silly minecrafters minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 4', recipe = { {"", "", recipeitem}, {"", recipeitem, recipeitem}, {recipeitem, recipeitem, recipeitem}, }, }) end -- Node will be called stairs:slab_<subname> function stairs.register_slab(subname, recipeitem, groups, images, description, sounds) minetest.register_node("stairs:slab_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end -- If it's being placed on an another similar one, replace it with -- a full block local slabpos = nil local slabnode = nil local p0 = pointed_thing.under local p1 = pointed_thing.above local n0 = minetest.env:get_node(p0) if n0.name == "stairs:slab_" .. subname and p0.y+1 == p1.y then slabpos = p0 slabnode = n0 end if slabpos then -- Remove the slab at slabpos minetest.env:remove_node(slabpos) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = slabpos fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(slabpos, slabnode) end return itemstack end -- Upside down slabs if p0.y-1 == p1.y then -- Turn into full block if pointing at a existing slab if n0.name == "stairs:slab_" .. subname.."upside_down" then -- Remove the slab at the position of the slab minetest.env:remove_node(p0) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = p0 fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(p0, n0) end return itemstack end -- Place upside down slab local fakestack = ItemStack("stairs:slab_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- If pointing at the side of a upside down slab if n0.name == "stairs:slab_" .. subname.."upside_down" and p0.y+1 ~= p1.y then -- Place upside down slab local fakestack = ItemStack("stairs:slab_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_node("stairs:slab_" .. subname.."upside_down", { drop = "stairs:slab_"..subname, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, }, }) minetest.register_craft({ output = 'stairs:slab_' .. subname .. ' 3', recipe = { {recipeitem, recipeitem, recipeitem}, }, }) end -- Nodes will be called stairs:{stair,slab}_<subname> function stairs.register_stair_and_slab(subname, recipeitem, groups, images, desc_stair, desc_slab, sounds) stairs.register_stair(subname, recipeitem, groups, images, desc_stair, sounds) stairs.register_slab(subname, recipeitem, groups, images, desc_slab, sounds) end stairs.register_stair_and_slab("wood", "default:wood", {snappy=2,choppy=2,oddly_breakable_by_hand=2}, {"default_wood.png"}, "Wooden stair", "Wooden slab", default.node_sound_wood_defaults()) stairs.register_stair_and_slab("stone", "default:stone", {cracky=3}, {"default_stone.png"}, "Stone stair", "Stone slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("cobble", "default:cobble", {cracky=3}, {"default_cobble.png"}, "Cobble stair", "Cobble slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("brick", "default:brick", {cracky=3}, {"default_brick.png"}, "Brick stair", "Brick slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("sandstone", "default:sandstone", {crumbly=2,cracky=2}, {"default_sandstone.png"}, "Sandstone stair", "Sandstone slab", default.node_sound_stone_defaults())
-- Minetest 0.4 mod: stairs -- See README.txt for licensing and other information. stairs = {} -- Node will be called modname:stair_<subname> function stairs.register_stair(subname, recipeitem, groups, images, description, sounds) local modname = minetest.get_current_modname() minetest.register_node(modname..":stair_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end local p0 = pointed_thing.under local p1 = pointed_thing.above if p0.y-1 == p1.y then local fakestack = ItemStack(modname..":stair_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_node(modname..":stair_" .. subname.."upside_down", { drop = modname..":stair_" .. subname, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = { {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, {-0.5, -0.5, 0, 0.5, 0, 0.5}, }, }, }) minetest.register_craft({ output = modname..':stair_' .. subname .. ' 4', recipe = { {recipeitem, "", ""}, {recipeitem, recipeitem, ""}, {recipeitem, recipeitem, recipeitem}, }, }) -- Flipped recipe for the silly minecrafters minetest.register_craft({ output = modname..':stair_' .. subname .. ' 4', recipe = { {"", "", recipeitem}, {"", recipeitem, recipeitem}, {recipeitem, recipeitem, recipeitem}, }, }) end -- Node will be called modname:slab_<subname> function stairs.register_slab(subname, recipeitem, groups, images, description, sounds) local modname = minetest.get_current_modname() minetest.register_node(modname..":slab_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end -- If it's being placed on an another similar one, replace it with -- a full block local slabpos = nil local slabnode = nil local p0 = pointed_thing.under local p1 = pointed_thing.above local n0 = minetest.env:get_node(p0) if n0.name == modname..":slab_" .. subname and p0.y+1 == p1.y then slabpos = p0 slabnode = n0 end if slabpos then -- Remove the slab at slabpos minetest.env:remove_node(slabpos) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = slabpos fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(slabpos, slabnode) end return itemstack end -- Upside down slabs if p0.y-1 == p1.y then -- Turn into full block if pointing at a existing slab if n0.name == modname..":slab_" .. subname.."upside_down" then -- Remove the slab at the position of the slab minetest.env:remove_node(p0) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = p0 fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(p0, n0) end return itemstack end -- Place upside down slab local fakestack = ItemStack(modname..":slab_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- If pointing at the side of a upside down slab if n0.name == modname..":slab_" .. subname.."upside_down" and p0.y+1 ~= p1.y then -- Place upside down slab local fakestack = ItemStack(modname..":slab_" .. subname.."upside_down") local ret = minetest.item_place(fakestack, placer, pointed_thing) if ret:is_empty() then itemstack:take_item() return itemstack end end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_node(modname..":slab_" .. subname.."upside_down", { drop = modname..":slab_"..subname, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5}, }, }) minetest.register_craft({ output = modname..':slab_' .. subname .. ' 3', recipe = { {recipeitem, recipeitem, recipeitem}, }, }) end -- Nodes will be called modname:{stair,slab}_<subname> function stairs.register_stair_and_slab(subname, recipeitem, groups, images, desc_stair, desc_slab, sounds) stairs.register_stair(subname, recipeitem, groups, images, desc_stair, sounds) stairs.register_slab(subname, recipeitem, groups, images, desc_slab, sounds) end stairs.register_stair_and_slab("wood", "default:wood", {snappy=2,choppy=2,oddly_breakable_by_hand=2}, {"default_wood.png"}, "Wooden stair", "Wooden slab", default.node_sound_wood_defaults()) stairs.register_stair_and_slab("stone", "default:stone", {cracky=3}, {"default_stone.png"}, "Stone stair", "Stone slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("cobble", "default:cobble", {cracky=3}, {"default_cobble.png"}, "Cobble stair", "Cobble slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("brick", "default:brick", {cracky=3}, {"default_brick.png"}, "Brick stair", "Brick slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("sandstone", "default:sandstone", {crumbly=2,cracky=2}, {"default_sandstone.png"}, "Sandstone stair", "Sandstone slab", default.node_sound_stone_defaults())
Fix modname prefix in stairs and slab functions
Fix modname prefix in stairs and slab functions
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
e0e5cad0caf3c9dcdbb429c9d0cbc58457b66f33
pud/ui/Tooltip.lua
pud/ui/Tooltip.lua
local Class = require 'lib.hump.class' local Frame = getClass 'pud.ui.Frame' local Text = getClass 'pud.ui.Text' local Bar = getClass 'pud.ui.Bar' -- Tooltip -- local Tooltip = Class{name='Tooltip', inherits=Frame, function(self, ...) Frame.construct(self, ...) self._margin = 0 end } -- destructor function Tooltip:destroy() self:clear() self._margin = nil Frame.destroy(self) end -- clear the tooltip function Tooltip:clear() if self._header1 then self._header1:destroy() self._header1 = nil end if self._header2 then self._header2:destroy() self._header2 = nil end if self._icon then self._icon:destroy() self._icon = nil end if self._lines then local numLines = #self._lines for i=1,numLines do self._lines[i]:destroy() self._lines[i] = nil end self._lines = nil end end -- XXX -- subclass for entities -- query entity for icon, name, family, kind, and loop through a list of properties -- then build tooltip based on these -- so this class need methods for building the tooltip --[[ all tooltips have this basic structure: ------------------------------- | ICON TEXT (usually Name) | } | TEXT or BLANK SPACE | }- This whole header area is optional | BLANK SPACE | } | TEXT or BAR | | TEXT or BAR or BLANK SPACE | | TEXT or BAR or BLANK SPACE | | TEXT or BAR or BLANK SPACE | | ... | | TEXT or BAR | ------------------------------- ]]-- -- set icon function Tooltip:setIcon(icon) verifyClass('pud.ui.Frame', icon) if self._icon then self._icon:destroy() end self._icon = icon self:_adjustLayout() self:_drawFB() end -- set header line 1 function Tooltip:setHeader1(text) verifyClass('pud.ui.Text', text) if self._header1 then self._header1:destroy() end self._header1 = text self:_adjustLayout() self:_drawFB() end -- set header line 2 function Tooltip:setHeader2(text) verifyClass('pud.ui.Text', text) if self._header2 then self._header2:destroy() end self._header2 = text self:_adjustLayout() self:_drawFB() end -- add a Text function Tooltip:addText(text) verifyClass('pud.ui.Text', text) self._addLine(text) end -- add a Bar function Tooltip:addBar(bar) verifyClass('pud.ui.Bar', bar) self._addLine(bar) end -- add a blank space function Tooltip:addSpace() local spacing = self:getSpacing() if spacing then local space = Frame(0, 0, 0, spacing) self:_addLine(space) end end -- add a line to the tooltip function Tooltip:_addLine(frame) verifyClass('pud.ui.Frame', frame) self._lines = self._lines or {} self._lines[#self._lines + 1] = frame self:_adjustLayout() self:_drawFB() end -- set the margin between the frame edge and the contents function Tooltip:setMargin(margin) verify('number', margin) self._margin = margin self:_adjustLayout() self:_drawFB() end function Tooltip:_adjustLayout() local numLines = self._lines and #self._lines or 0 if self._icon or self._header1 or self._header2 or numLines > 0 then local x, y = self._margin, self._margin local width, height = 0, 0 local spacing = self:getSpacing() if spacing then if self._icon then self._icon:setPosition(x, y) width = self._icon:getWidth() x = width + spacing end local headerWidth = 0 if self._header1 then self._header1:setPosition(x, y) headerWidth = self._header1:getWidth() y = y + spacing end if self._header2 then self._header2:setPosition(x, y) local h2width = self._header2:getWidth() headerWidth = headerWidth > h2width and headerWidth or h2width y = y + spacing end width = width + headerWidth if numLines > 0 then -- set some blank space if any headers exist if self._icon or self._header1 or self._header2 then y = y + spacing end x = self._margin for i=1,numLines do local line = self._lines[i] line:setPosition(x, y) local lineWidth = line:getWidth() width = width > lineWidth and width or lineWidth y = y + spacing end -- for i=1,num end -- if self._lines width = width + self._margin*2 height = height + self._margin*2 -- XXX: might have an extra spacing self:setSize(width, height) end -- if spacing end -- if self._icon or self._header1 or ... end function Tooltip:_getSpacing() local spacing local normalStyle = self:getNormalStyle() if normalStyle then local font = normalStyle:getFont() if font then spacing = font:getHeight() end end if nil == spacing then warning('Please set Tooltip normal font style.') end return spacing end -- draw in the foreground layer -- draws over any foreground set in the Style. Usually, you just don't want to -- set a foreground in the Style. function Tooltip:_drawForeground() Frame._drawForeground(self) if self._icon then self._icon:draw() end if self._header1 then self._header1:draw() end if self._header2 then self._header2:draw() end local numLines = self._lines and #self._lines or 0 if numLines > 0 then for i=1,numLines do local line = self._lines[i] line:draw() end end end -- the class return Tooltip
local Class = require 'lib.hump.class' local Frame = getClass 'pud.ui.Frame' local Text = getClass 'pud.ui.Text' local Bar = getClass 'pud.ui.Bar' -- Tooltip -- local Tooltip = Class{name='Tooltip', inherits=Frame, function(self, ...) Frame.construct(self, ...) self._margin = 0 end } -- destructor function Tooltip:destroy() self:clear() self._margin = nil Frame.destroy(self) end -- clear the tooltip function Tooltip:clear() if self._header1 then self._header1:destroy() self._header1 = nil end if self._header2 then self._header2:destroy() self._header2 = nil end if self._icon then self._icon:destroy() self._icon = nil end if self._lines then local numLines = #self._lines for i=1,numLines do self._lines[i]:destroy() self._lines[i] = nil end self._lines = nil end end -- XXX -- subclass for entities -- query entity for icon, name, family, kind, and loop through a list of properties -- then build tooltip based on these -- so this class need methods for building the tooltip --[[ all tooltips have this basic structure: ------------------------------- | ICON TEXT (usually Name) | } | TEXT or BLANK SPACE | }- This whole header area is optional | BLANK SPACE | } | TEXT or BAR | | TEXT or BAR or BLANK SPACE | | TEXT or BAR or BLANK SPACE | | TEXT or BAR or BLANK SPACE | | ... | | TEXT or BAR | ------------------------------- ]]-- -- set icon function Tooltip:setIcon(icon) verifyClass('pud.ui.Frame', icon) if self._icon then self._icon:destroy() end self._icon = icon self:_adjustLayout() self:_drawFB() end -- set header line 1 function Tooltip:setHeader1(text) verifyClass('pud.ui.Text', text) if self._header1 then self._header1:destroy() end self._header1 = text self:_adjustLayout() self:_drawFB() end -- set header line 2 function Tooltip:setHeader2(text) verifyClass('pud.ui.Text', text) if self._header2 then self._header2:destroy() end self._header2 = text self:_adjustLayout() self:_drawFB() end -- add a Text function Tooltip:addText(text) verifyClass('pud.ui.Text', text) self._addLine(text) end -- add a Bar function Tooltip:addBar(bar) verifyClass('pud.ui.Bar', bar) self._addLine(bar) end -- add a blank space function Tooltip:addSpace() local spacing = self:getSpacing() if spacing then local space = Frame(0, 0, 0, spacing) self:_addLine(space) end end -- add a line to the tooltip function Tooltip:_addLine(frame) verifyClass('pud.ui.Frame', frame) self._lines = self._lines or {} self._lines[#self._lines + 1] = frame self:_adjustLayout() self:_drawFB() end -- set the margin between the frame edge and the contents function Tooltip:setMargin(margin) verify('number', margin) self._margin = margin self:_adjustLayout() self:_drawFB() end function Tooltip:_adjustLayout() local numLines = self._lines and #self._lines or 0 if self._icon or self._header1 or self._header2 or numLines > 0 then local width, height = self._margin, self._margin local x, y = self._x + width, self._y + height local spacing = self:getSpacing() if spacing then if self._icon then self._icon:setPosition(x, y) width = width + self._icon:getWidth() x = self._x + width + spacing end local headerWidth = 0 if self._header1 then self._header1:setPosition(x, y) headerWidth = self._header1:getWidth() y = y + spacing end if self._header2 then self._header2:setPosition(x, y) local h2width = self._header2:getWidth() headerWidth = headerWidth > h2width and headerWidth or h2width y = y + spacing end width = width + headerWidth if numLines > 0 then -- set some blank space if any headers exist if self._icon or self._header1 or self._header2 then y = y + spacing end x = self._x + self._margin for i=1,numLines do local line = self._lines[i] line:setPosition(x, y) local lineWidth = line:getWidth() width = width > lineWidth and width or lineWidth y = y + spacing end -- for i=1,num end -- if self._lines width = width + self._margin height = height + self._margin -- XXX: might have an extra spacing self:setSize(width, height) end -- if spacing end -- if self._icon or self._header1 or ... end function Tooltip:_getSpacing() local spacing local normalStyle = self:getNormalStyle() if normalStyle then local font = normalStyle:getFont() if font then spacing = font:getHeight() end end if nil == spacing then warning('Please set Tooltip normal font style.') end return spacing end -- draw in the foreground layer -- draws over any foreground set in the Style. Usually, you just don't want to -- set a foreground in the Style. function Tooltip:_drawForeground() Frame._drawForeground(self) if self._icon then self._icon:draw() end if self._header1 then self._header1:draw() end if self._header2 then self._header2:draw() end local numLines = self._lines and #self._lines or 0 if numLines > 0 then for i=1,numLines do local line = self._lines[i] line:draw() end end end -- the class return Tooltip
fix tooltip drawing relative to position
fix tooltip drawing relative to position
Lua
mit
scottcs/wyx
0b12b901357a270e0d7d131561735ed61306685e
XLifeBar/HP.class.lua
XLifeBar/HP.class.lua
-- -- ƽѪUI -- ֻUI κ߼ж -- XLifeBar = XLifeBar or {} XLifeBar.HP = class() local HP = XLifeBar.HP function HP:ctor(dwID, frame, handle) -- KGobject self.dwID = dwID self.frame = frame self.handle = handle return self end -- function HP:Create() -- Create handle local frame = self.frame if not frame:Lookup("",tostring(self.dwID)) then local Total = frame:Lookup("","") Total:AppendItemFromString(FormatHandle( string.format("name=\"%s\"",self.dwID) )) end local handle = frame:Lookup("",tostring(self.dwID)) if not handle:Lookup(string.format("hp_bg_%s",self.dwID)) then handle:AppendItemFromString( string.format("<shadow>name=\"hp_bg_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"hp_bg2_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"hp_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"ot_bg_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"ot_bg2_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"ot_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"lines_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"hp_title_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"ot_title_%s\"</shadow>",self.dwID) ) end self.handle = handle return self end -- ɾ function HP:Remove() local frame = self.frame if frame:Lookup("",tostring(self.dwID)) then local Total = frame:Lookup("","") Total:RemoveItem(frame:Lookup("",tostring(self.dwID))) end return self end -- //ƺ ȵ -- rgbaf: ,,,͸, -- tWordlines: {[,߶ƫ],...} function HP:DrawWordlines(tWordlines, rgbaf) if not self.handle then return end local r,g,b,a,f = unpack(rgbaf) local sha = self.handle:Lookup(string.format("lines_%s",self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TEXT) sha:ClearTriangleFanPoint() for _, aWordline in ipairs(tWordlines) do sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,0,- aWordline[2]},f,aWordline[1],1,1) end return self end -- Ѫٷֱ֣ػԺWordlines룩 function HP:DrawLifePercentage(aWordline, rgbaf) if not self.handle then return end local r,g,b,a,f = unpack(rgbaf) local sha = self.handle:Lookup(string.format("hp_title_%s",self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TEXT) sha:ClearTriangleFanPoint() sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,0,- aWordline[2]},f,aWordline[1],1,1) end -- ƶƣػԺWordlines룩 function HP:DrawOTTitle(aWordline, rgbaf) if not self.handle then return end local r,g,b,a,f = unpack(rgbaf) local sha = self.handle:Lookup(string.format("ot_title_%s",self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TEXT) sha:ClearTriangleFanPoint() sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,0,- aWordline[2]},f,aWordline[1],1,1) return self end -- ߿ Ĭ200nAlpha function HP:DrawBorder(nWidth, nHeight, nOffsetY, nAlpha, szShadowName, szShadowName2) if not self.handle then return end nAlpha = nAlpha or 200 local handle = self.handle -- ߿ local sha = handle:Lookup(string.format(szShadowName,self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TRIANGLE) sha:SetD3DPT(D3DPT.TRIANGLEFAN) sha:ClearTriangleFanPoint() local bcX,bcY = - nWidth / 2 ,(- nHeight) - nOffsetY sha:AppendCharacterID(self.dwID,true,180,180,180,nAlpha,{0,0,0,bcX,bcY}) sha:AppendCharacterID(self.dwID,true,180,180,180,nAlpha,{0,0,0,bcX+nWidth,bcY}) sha:AppendCharacterID(self.dwID,true,180,180,180,nAlpha,{0,0,0,bcX+nWidth,bcY+nHeight}) sha:AppendCharacterID(self.dwID,true,180,180,180,nAlpha,{0,0,0,bcX,bcY+nHeight}) -- ڱ߿ local sha = handle:Lookup(string.format(szShadowName2,self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TRIANGLE) sha:SetD3DPT(D3DPT.TRIANGLEFAN) sha:ClearTriangleFanPoint() local bcX,bcY = - (nWidth / 2 - 1),(- (nHeight - 1)) - nOffsetY sha:AppendCharacterID(self.dwID,true,30,30,30,nAlpha,{0,0,0,bcX,bcY}) sha:AppendCharacterID(self.dwID,true,30,30,30,nAlpha,{0,0,0,bcX+(nWidth - 2),bcY}) sha:AppendCharacterID(self.dwID,true,30,30,30,nAlpha,{0,0,0,bcX+(nWidth - 2),bcY+(nHeight - 2)}) sha:AppendCharacterID(self.dwID,true,30,30,30,nAlpha,{0,0,0,bcX,bcY+(nHeight - 2)}) return self end -- Ѫ߿ Ĭ200nAlpha function HP:DrawLifeBorder(nWidth, nHeight, nOffsetY, nAlpha) return self:DrawBorder(nWidth, nHeight, nOffsetY, nAlpha, "hp_bg_%s", "hp_bg2_%s") end -- ߿ Ĭ200nAlpha function HP:DrawOTBarBorder(nWidth, nHeight, nOffsetY, nAlpha) return self:DrawBorder(nWidth, nHeight, nOffsetY, nAlpha, "ot_bg_%s", "ot_bg2_%s") end -- Σ/Ѫ -- rgbap: ,,,͸, function HP:DrawRect(nWidth, nHeight, nOffsetY, rgbap, szShadowName) if not self.handle then return end local r,g,b,a,p = unpack(rgbap) if p > 1 then p = 1 elseif p < 0 then p = 0 end -- fix local sha = self.handle:Lookup(string.format(szShadowName,self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TRIANGLE) sha:SetD3DPT(D3DPT.TRIANGLEFAN) sha:ClearTriangleFanPoint() local bcX,bcY = - (nWidth / 2 - 2),(- (nHeight - 2)) - nOffsetY nWidth = (nWidth - 4) * p -- ʵʻƿ sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,bcX,bcY}) sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,bcX+nWidth,bcY}) sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,bcX+nWidth,bcY+(nHeight - 4)}) sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,bcX,bcY+(nHeight - 4)}) return self end -- Ѫ function HP:DrawLifebar(nWidth, nHeight, nOffsetY, rgbap) return self:DrawRect(nWidth, nHeight, nOffsetY, rgbap, "hp_%s") end -- function HP:DrawOTBar(nWidth, nHeight, nOffsetY, rgbap) return self:DrawRect(nWidth, nHeight, nOffsetY, rgbap, "ot_%s") end
-- -- ƽѪUI -- ֻUI κ߼ж -- XLifeBar = XLifeBar or {} XLifeBar.HP = class() local HP = XLifeBar.HP function HP:ctor(dwID, frame, handle) -- KGobject self.dwID = dwID self.frame = frame self.handle = handle return self end -- function HP:Create() -- Create handle local frame = self.frame if not frame:Lookup("",tostring(self.dwID)) then local Total = frame:Lookup("","") Total:AppendItemFromString(FormatHandle( string.format("name=\"%s\"",self.dwID) )) end local handle = frame:Lookup("",tostring(self.dwID)) if not handle:Lookup(string.format("hp_bg_%s",self.dwID)) then handle:AppendItemFromString( string.format("<shadow>name=\"hp_bg_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"hp_bg2_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"hp_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"ot_bg_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"ot_bg2_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"ot_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"lines_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"hp_title_%s\"</shadow>",self.dwID) ) handle:AppendItemFromString( string.format("<shadow>name=\"ot_title_%s\"</shadow>",self.dwID) ) end self.handle = handle return self end -- ɾ function HP:Remove() local frame = self.frame if frame:Lookup("",tostring(self.dwID)) then local Total = frame:Lookup("","") Total:RemoveItem(frame:Lookup("",tostring(self.dwID))) end return self end -- //ƺ ȵ -- rgbaf: ,,,͸, -- tWordlines: {[,߶ƫ],...} function HP:DrawWordlines(tWordlines, rgbaf) if not self.handle then return end local r,g,b,a,f = unpack(rgbaf) local sha = self.handle:Lookup(string.format("lines_%s",self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TEXT) sha:ClearTriangleFanPoint() for _, aWordline in ipairs(tWordlines) do sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,0,- aWordline[2]},f,aWordline[1],1,1) end return self end -- Ѫٷֱ֣ػԺWordlines룩 function HP:DrawLifePercentage(aWordline, rgbaf) if not self.handle then return end local r,g,b,a,f = unpack(rgbaf) local sha = self.handle:Lookup(string.format("hp_title_%s",self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TEXT) sha:ClearTriangleFanPoint() sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,0,- aWordline[2]},f,aWordline[1],1,1) end -- ƶƣػԺWordlines룩 function HP:DrawOTTitle(aWordline, rgbaf) if not self.handle then return end local r,g,b,a,f = unpack(rgbaf) local sha = self.handle:Lookup(string.format("ot_title_%s",self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TEXT) sha:ClearTriangleFanPoint() sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,0,- aWordline[2]},f,aWordline[1],1,1) return self end -- ߿ Ĭ200nAlpha function HP:DrawBorder(nWidth, nHeight, nOffsetY, nAlpha, szShadowName, szShadowName2) if not self.handle then return end nAlpha = nAlpha or 200 local handle = self.handle -- ߿ local sha = handle:Lookup(string.format(szShadowName,self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TRIANGLE) sha:SetD3DPT(D3DPT.TRIANGLEFAN) sha:ClearTriangleFanPoint() local bcX,bcY = - nWidth / 2 ,(- nHeight) - nOffsetY sha:AppendCharacterID(self.dwID,true,180,180,180,nAlpha,{0,0,0,bcX,bcY}) sha:AppendCharacterID(self.dwID,true,180,180,180,nAlpha,{0,0,0,bcX+nWidth,bcY}) sha:AppendCharacterID(self.dwID,true,180,180,180,nAlpha,{0,0,0,bcX+nWidth,bcY+nHeight}) sha:AppendCharacterID(self.dwID,true,180,180,180,nAlpha,{0,0,0,bcX,bcY+nHeight}) -- ڱ߿ local sha = handle:Lookup(string.format(szShadowName2,self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TRIANGLE) sha:SetD3DPT(D3DPT.TRIANGLEFAN) sha:ClearTriangleFanPoint() local bcX,bcY = - (nWidth / 2 - 1),(- (nHeight - 1)) - nOffsetY sha:AppendCharacterID(self.dwID,true,30,30,30,nAlpha,{0,0,0,bcX,bcY}) sha:AppendCharacterID(self.dwID,true,30,30,30,nAlpha,{0,0,0,bcX+(nWidth - 2),bcY}) sha:AppendCharacterID(self.dwID,true,30,30,30,nAlpha,{0,0,0,bcX+(nWidth - 2),bcY+(nHeight - 2)}) sha:AppendCharacterID(self.dwID,true,30,30,30,nAlpha,{0,0,0,bcX,bcY+(nHeight - 2)}) return self end -- Ѫ߿ Ĭ200nAlpha function HP:DrawLifeBorder(nWidth, nHeight, nOffsetY, nAlpha) return self:DrawBorder(nWidth, nHeight, nOffsetY, nAlpha, "hp_bg_%s", "hp_bg2_%s") end -- ߿ Ĭ200nAlpha function HP:DrawOTBarBorder(nWidth, nHeight, nOffsetY, nAlpha) return self:DrawBorder(nWidth, nHeight, nOffsetY, nAlpha, "ot_bg_%s", "ot_bg2_%s") end -- Σ/Ѫ -- rgbap: ,,,͸, function HP:DrawRect(nWidth, nHeight, nOffsetY, rgbap, szShadowName) if not self.handle then return end local r,g,b,a,p = unpack(rgbap) if not p or p > 1 then p = 1 elseif p < 0 then p = 0 end -- fix local sha = self.handle:Lookup(string.format(szShadowName,self.dwID)) sha:SetTriangleFan(GEOMETRY_TYPE.TRIANGLE) sha:SetD3DPT(D3DPT.TRIANGLEFAN) sha:ClearTriangleFanPoint() local bcX,bcY = - (nWidth / 2 - 2),(- (nHeight - 2)) - nOffsetY nWidth = (nWidth - 4) * p -- ʵʻƿ sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,bcX,bcY}) sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,bcX+nWidth,bcY}) sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,bcX+nWidth,bcY+(nHeight - 4)}) sha:AppendCharacterID(self.dwID,true,r,g,b,a,{0,0,0,bcX,bcY+(nHeight - 4)}) return self end -- Ѫ function HP:DrawLifebar(nWidth, nHeight, nOffsetY, rgbap) return self:DrawRect(nWidth, nHeight, nOffsetY, rgbap, "hp_%s") end -- function HP:DrawOTBar(nWidth, nHeight, nOffsetY, rgbap) return self:DrawRect(nWidth, nHeight, nOffsetY, rgbap, "ot_%s") end
扁平血条:库一处可能BUG的地方
扁平血条:库一处可能BUG的地方
Lua
bsd-3-clause
tinymins/MY
8c7805f1d931f3a200041b25137a056daeeb528d
himan-scripts/precipitation-type.lua
himan-scripts/precipitation-type.lua
local function CheckedFetch(parm_name, lvl, time) local p = luatool:FetchWithType(time, lvl, param(parm_name), current_forecast_type) if not p then msg = string.format("Failed to find parameter '%s'", parm_name) logger:Error(msg) error("luatool:Fetch failed") else return p end end local MISS = missing local currentProducer = configuration:GetSourceProducer(1) local currentProducerName = currentProducer.GetName(currentProducer) msg = string.format("Calculating potential precipitation type for producer: %s", currentProducerName) logger:Info(msg) local rh925 = nil local rh850 = nil local rh700 = nil if currentProducerName == "MEPS" or currentProducerName == "MEPSMTA" then rh925 = CheckedFetch("RH-0TO1", level(HPLevelType.kPressure, 925), current_time) rh850 = CheckedFetch("RH-0TO1", level(HPLevelType.kPressure, 850), current_time) rh700 = CheckedFetch("RH-0TO1", level(HPLevelType.kPressure, 700), current_time) else rh925 = CheckedFetch("RH-PRCNT", level(HPLevelType.kPressure, 925), current_time) rh850 = CheckedFetch("RH-PRCNT", level(HPLevelType.kPressure, 850), current_time) rh700 = CheckedFetch("RH-PRCNT", level(HPLevelType.kPressure, 700), current_time) end local pref = CheckedFetch("POTPRECF-N", level(HPLevelType.kHeight, 0), current_time) local rrr = CheckedFetch("RRR-KGM2", level(HPLevelType.kHeight, 0), current_time) -- Limit for relative humidity -- HARMONIE and HIRLAM seem to have PRCNT in the range [0,1] but EC -- seems to have it in [0,100] local Limit if currentProducerName == "ECG" or currentProducerName == "ECGMTA" then Limit = 80 elseif currentProducerName == "AROME" or currentProducerName == "AROMTA" or currentProducerName == "HL2" or currentProducerName == "HL2MTA" or currentProducerName == "MEPS" or currentProducerName == "MEPSMTA" then Limit = 0.8 end local pret = {} local potpret = {} for i=1, #rh700 do local _rh925 = rh925[i] local _rh850 = rh850[i] local _rh700 = rh700[i] local _pref = pref[i] local _rrr = rrr[i] potpret[i] = 2 -- initially 2 pret[i] = MISS if _rh700 > Limit and _rh850 > Limit and _rh925 > Limit then potpret[i] = 1 end if _pref == 0 or _pref == 4 or _pref == 5 then potpret[i] = 1 end if _rrr > 0 then pret[i] = potpret[i] end end result:SetParam(param("PRECTYPE-N")) result:SetValues(pret) result:SetParam(param("POTPRECT-N")) result:SetValues(potpret) logger:Info("Writing source data to file") luatool:WriteToFile(result)
local function CheckedFetch(parm_name, lvl, time) local p = luatool:FetchWithType(time, lvl, param(parm_name), current_forecast_type) if not p then msg = string.format("Failed to find parameter '%s'", parm_name) logger:Error(msg) error("luatool:Fetch failed") else return p end end local MISS = missing local currentProducer = configuration:GetSourceProducer(1) local currentProducerName = currentProducer.GetName(currentProducer) msg = string.format("Calculating potential precipitation type for producer: %s", currentProducerName) logger:Info(msg) local rh925 = nil local rh850 = nil local rh700 = nil if currentProducerName == "MEPS" or currentProducerName == "MEPSMTA" then rh925 = CheckedFetch("RH-0TO1", level(HPLevelType.kPressure, 925), current_time) rh850 = CheckedFetch("RH-0TO1", level(HPLevelType.kPressure, 850), current_time) rh700 = CheckedFetch("RH-0TO1", level(HPLevelType.kPressure, 700), current_time) else rh925 = CheckedFetch("RH-PRCNT", level(HPLevelType.kPressure, 925), current_time) rh850 = CheckedFetch("RH-PRCNT", level(HPLevelType.kPressure, 850), current_time) rh700 = CheckedFetch("RH-PRCNT", level(HPLevelType.kPressure, 700), current_time) end local pref = CheckedFetch("POTPRECF-N", level(HPLevelType.kHeight, 0), current_time) local rrr = CheckedFetch("RRR-KGM2", level(HPLevelType.kHeight, 0), current_time) -- Limit for relative humidity -- HARMONIE and HIRLAM seem to have PRCNT in the range [0,1] but EC -- seems to have it in [0,100] local Limit if currentProducerName == "ECG" or currentProducerName == "ECGMTA" or currentProducerName == "GFSMTA" then Limit = 80 elseif currentProducerName == "AROME" or currentProducerName == "AROMTA" or currentProducerName == "HL2" or currentProducerName == "HL2MTA" or currentProducerName == "MEPS" or currentProducerName == "MEPSMTA" then Limit = 0.8 end local pret = {} local potpret = {} for i=1, #rh700 do local _rh925 = rh925[i] local _rh850 = rh850[i] local _rh700 = rh700[i] local _pref = pref[i] local _rrr = rrr[i] potpret[i] = 2 -- initially 2 pret[i] = MISS if _rh700 > Limit and _rh850 > Limit and _rh925 > Limit then potpret[i] = 1 end if _pref == 0 or _pref == 4 or _pref == 5 then potpret[i] = 1 end if _rrr > 0 then pret[i] = potpret[i] end end result:SetParam(param("PRECTYPE-N")) result:SetValues(pret) luatool:WriteToFile(result) result:SetParam(param("POTPRECT-N")) result:SetValues(potpret) luatool:WriteToFile(result)
Minor fixes
Minor fixes
Lua
mit
fmidev/himan,fmidev/himan,fmidev/himan
aa3ee1ec9c1b10ae9aab6e3331ebd73a95b82822
script/c80600066.lua
script/c80600066.lua
--旗鼓堂々 function c80600066.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCategory(CATEGORY_EQUIP) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c80600066.eqtg) e1:SetOperation(c80600066.eqop) c:RegisterEffect(e1) end function c80600066.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetFlagEffect(tp,80600066)==0 end Duel.RegisterFlagEffect(tp,80600066,RESET_PHASE+PHASE_END,EFFECT_FLAG_OATH,1) end function c80600066.filter(c) return c:IsType(TYPE_EQUIP) and Duel.IsExistingMatchingCard(c80600066.filter2,tp,LOCATION_MZONE,0,1,nil,c) end function c80600066.filter2(c,ec) return ec:CheckEquipTarget(c) and c:IsFaceup() end function c80600066.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c80600066.filter(chkc,e:GetHandler()) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(c80600066.filter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local tc=Duel.SelectTarget(tp,c80600066.filter,tp,LOCATION_GRAVE,0,1,1,nil) local tc2=Duel.SelectTarget(tp,c80600066.filter2,tp,LOCATION_MZONE,0,1,1,nil,tc:GetFirst()) Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0) end function c80600066.eqop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local tc2=g:GetFirst() local tc=g:GetNext() if tc:IsRelateToEffect(e) and tc2:IsFaceup() and tc2:IsRelateToEffect(e) then Duel.Equip(tp,tc,tc2) end end
--旗鼓堂々 function c80600066.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCategory(CATEGORY_EQUIP) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCost(c80600066.cost) e1:SetTarget(c80600066.eqtg) e1:SetOperation(c80600066.eqop) c:RegisterEffect(e1) end function c80600066.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not Duel.CheckSpecialSummonActivity(tp) and Duel.GetFlagEffect(tp,80600066)==0 end --oath effects local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetTargetRange(1,0) Duel.RegisterEffect(e1,tp) Duel.RegisterFlagEffect(tp,80600066,RESET_PHASE+PHASE_END,EFFECT_FLAG_OATH,1) end function c80600066.filter(c) return c:IsType(TYPE_EQUIP) and Duel.IsExistingMatchingCard(c80600066.filter2,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil,c) end function c80600066.filter2(c,ec) return ec:CheckEquipTarget(c) and c:IsFaceup() end function c80600066.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c80600066.filter(chkc,e:GetHandler()) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(c80600066.filter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local tc=Duel.SelectTarget(tp,c80600066.filter,tp,LOCATION_GRAVE,0,1,1,nil) local tc2=Duel.SelectTarget(tp,c80600066.filter2,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil,tc:GetFirst()) Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0) end function c80600066.eqop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local tc2=g:GetFirst() local tc=g:GetNext() if tc:IsRelateToEffect(e) and tc2:IsFaceup() and tc2:IsRelateToEffect(e) then Duel.Equip(tp,tc,tc2) tc:RegisterFlagEffect(80600066,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetLabelObject(tc) e1:SetOperation(c80600066.desop) Duel.RegisterEffect(e1,tp) end end function c80600066.desop(e,tp,eg,ep,ev,re,r,rp) local tc=e:GetLabelObject() if tc:GetFlagEffect(80600066)>0 then Duel.Destroy(tc,REASON_EFFECT) end end
fix
fix fix due to changed text
Lua
mit
Tic-Tac-Toc/DevProLauncher,sidschingis/DevProLauncher,SuperAndroid17/DevProLauncher
3da60abce8b56e0d89a35509e0998c03806f6acd
modules/sortModes/core.lua
modules/sortModes/core.lua
--- Bench (i.e., move to group 8) all guild members below a certain rank. local A, L = unpack(select(2, ...)) local P = A.sortModes local M = P:NewModule("core", "AceEvent-3.0") P.core = M local R = { core = {}, nonCore = {}, } M.private = R local PADDING_PLAYER = {isDummy=true} local format, gsub, ipairs, min, select, sort, strfind, strlower, tinsert, wipe = format, gsub, ipairs, min, select, sort, strfind, strlower, tinsert, wipe local GuildControlGetNumRanks, GuildControlGetRankName, GetGuildInfo, GetRealmName, UnitIsInMyGuild = GuildControlGetNumRanks, GuildControlGetRankName, GetGuildInfo, GetRealmName, UnitIsInMyGuild local function getGuildFullName() local guildName, _, _, realm = GetGuildInfo("player") if not guildName then return end return format("%s-%s", guildName, gsub(realm or GetRealmName(), "[ %-]", "")) end function M:GetCoreRank() return A.options.coreRaiderRank[getGuildFullName()] end function M:SetCoreRank(rank) A.options.coreRaiderRank[getGuildFullName()] = rank end function M:GetGuildRanks() if not A.db.global.guildRanks then A.db.global.guildRanks = {} end local guildName = getGuildFullName() if not guildName then return end if not A.db.global.guildRanks[guildName] then A.db.global.guildRanks[guildName] = {} end return A.db.global.guildRanks[guildName] end function M:UpdateGuildRanks() local ranks = M:GetGuildRanks() if not ranks then return end wipe(ranks) for i = 1, GuildControlGetNumRanks() do tinsert(ranks, GuildControlGetRankName(i)) end local rank = M:GetCoreRank() if not rank or rank < 1 or rank > #ranks then -- Guess which rank is for core raiders. rank = nil local name -- First pass: first rank containing "core". for i = #ranks, 1, -1 do name = strlower(ranks[i]) if not rank and strfind(name, "core") then rank = i end end if not rank then -- Second pass: last rank containing "raid" but not a keyword indicating -- the player is a fresh recruit or a non-raider. for i = 1, #ranks do name = strlower(ranks[i]) if not rank and strfind(name, "raid") and not strfind(name, "no[nt]") and not strfind(name, "trial") and not strfind(name, "new") and not strfind(name, "recruit") and not strfind(name, "backup") and not strfind(name, "ex") and not strfind(name, "retire") and not strfind(name, "former") and not strfind(name, "casual") and not strfind(name, "alt") then rank = i end end end if not rank then -- Otherwise just guess 4, on the theory that many guilds' ranks are -- similar to: -- GM > Officer > Veteran > Core > Recruit > Alt > Casual > Muted. rank = min(#ranks, 4) end M:SetCoreRank(rank) end end function M:OnEnable() A.sortModes:Register({ key = "core", name = L["sorter.mode.core"], desc = function(t) t:AddLine(format("%s: |n%s.", L["tooltip.right.fixGroups"], L["sorter.mode.core"]), 1,1,0) t:AddLine(" ") local guildName = GetGuildInfo("player") if guildName then M:UpdateGuildRanks() local rank = M:GetCoreRank() t:AddLine(format(L["gui.fixGroups.help.note.core.1"], A.util:HighlightGuild(guildName), A.util:HighlightGuild(M:GetGuildRanks()[rank]), rank), 1,1,1, true) t:AddLine(" ") t:AddLine(L["gui.fixGroups.help.note.core.2"], 1,1,1, true) else t:AddLine(format(L["sorter.print.notInGuild"], "core"), 1,1,1, true) end end, isIncludingSitting = true, onBeforeStart = M.verifyInGuild, onStart = M.UpdateGuildRanks, onBeforeSort = M.verifyInGuild, onSort = M.onSort, }) end function M.verifyInGuild() if not GetGuildInfo("player") then A.console:Printf(L["sorter.print.notInGuild"], "core") return true end end function M.onSort(keys, players) -- Perform an initial sort. sort(keys, P:BaseGetCompareFunc(players)) -- Split keys into core/nonCore. local maxRank = M:GetCoreRank() local core, nonCore = wipe(R.core), wipe(R.nonCore) local unitID for _, k in ipairs(keys) do unitID = players[k].unitID if unitID and UnitIsInMyGuild(unitID) and select(3, GetGuildInfo(unitID)) > maxRank then tinsert(nonCore, k) else -- Note that non-guildmates will be considered core. -- This is a good thing: if you have to PUG to fill in a key role, -- you definitely want them in the raid. tinsert(core, k) end end -- Recombine into keys, inserting padding to force nonCore to group 8. wipe(keys) for _, k in ipairs(core) do tinsert(keys, k) end local k for i = 1, (40 - #core - #nonCore) do k = format("_pad%02d", i) tinsert(keys, k) players[k] = PADDING_PLAYER end for _, k in ipairs(nonCore) do tinsert(keys, k) end end
--- Bench (i.e., move to group 8) all guild members below a certain rank. local A, L = unpack(select(2, ...)) local P = A.sortModes local M = P:NewModule("core", "AceEvent-3.0") P.core = M local R = { core = {}, nonCore = {}, } M.private = R local PADDING_PLAYER = {isDummy=true} local format, gsub, ipairs, min, select, sort, strfind, strlower, tinsert, wipe = format, gsub, ipairs, min, select, sort, strfind, strlower, tinsert, wipe local GuildControlGetNumRanks, GuildControlGetRankName, GetGuildInfo, GetRealmName, UnitIsInMyGuild = GuildControlGetNumRanks, GuildControlGetRankName, GetGuildInfo, GetRealmName, UnitIsInMyGuild local function getGuildFullName() local guildName, _, _, realm = GetGuildInfo("player") if not guildName then return end return format("%s-%s", guildName, gsub(realm or GetRealmName(), "[ %-]", "")) end function M:GetCoreRank() return A.options.coreRaiderRank[getGuildFullName()] end function M:SetCoreRank(rank) A.options.coreRaiderRank[getGuildFullName()] = rank end function M:GetGuildRanks() if not A.db.global.guildRanks then A.db.global.guildRanks = {} end local guildName = getGuildFullName() if not guildName then return end if not A.db.global.guildRanks[guildName] then A.db.global.guildRanks[guildName] = {} end return A.db.global.guildRanks[guildName] end function M:UpdateGuildRanks() local ranks = M:GetGuildRanks() if not ranks then return end wipe(ranks) for i = 1, GuildControlGetNumRanks() do tinsert(ranks, GuildControlGetRankName(i)) end local rank = M:GetCoreRank() if not rank or rank < 1 or rank > #ranks then -- Guess which rank is for core raiders. rank = nil local name -- First pass: first rank containing "core". for i = #ranks, 1, -1 do name = strlower(ranks[i]) if not rank and strfind(name, "core") then rank = i end end if not rank then -- Second pass: last rank containing "raid" but not a keyword indicating -- the player is a fresh recruit or a non-raider. for i = 1, #ranks do name = strlower(ranks[i]) if not rank and strfind(name, "raid") and not strfind(name, "no[nt]") and not strfind(name, "trial") and not strfind(name, "new") and not strfind(name, "recruit") and not strfind(name, "backup") and not strfind(name, "ex") and not strfind(name, "retire") and not strfind(name, "former") and not strfind(name, "casual") and not strfind(name, "alt") then rank = i end end end if not rank then -- Otherwise just guess 4, on the theory that many guilds' ranks are -- similar to: -- GM > Officer > Veteran > Core > Recruit > Alt > Casual > Muted. rank = min(#ranks, 4) end M:SetCoreRank(rank) end end function M:OnEnable() A.sortModes:Register({ key = "core", name = L["sorter.mode.core"], desc = function(t) t:AddLine(format("%s: |n%s.", L["tooltip.right.fixGroups"], L["sorter.mode.core"]), 1,1,0) t:AddLine(" ") local guildName = GetGuildInfo("player") if guildName then M:UpdateGuildRanks() local rank = M:GetCoreRank() t:AddLine(format(L["gui.fixGroups.help.note.core.1"], A.util:HighlightGuild(guildName), A.util:HighlightGuild(M:GetGuildRanks()[rank]), rank), 1,1,1, true) t:AddLine(" ") t:AddLine(L["gui.fixGroups.help.note.core.2"], 1,1,1, true) else t:AddLine(format(L["sorter.print.notInGuild"], "core"), 1,1,1, true) end end, isIncludingSitting = true, onBeforeStart = M.verifyInGuild, onStart = M.UpdateGuildRanks, onBeforeSort = M.verifyInGuild, onSort = M.onSort, }) end function M.verifyInGuild() if not GetGuildInfo("player") then A.console:Printf(L["sorter.print.notInGuild"], "core") return true end end function M.onSort(keys, players) -- Perform an initial sort. sort(keys, P:BaseGetCompareFunc(players)) -- Split keys into core/nonCore. -- Subtract 1 because GetGuildInfo is 0-based, but -- GuildControlGetRankName is 1-based. local maxRank = M:GetCoreRank() - 1 local core, nonCore = wipe(R.core), wipe(R.nonCore) local unitID for _, k in ipairs(keys) do unitID = players[k].unitID if unitID and UnitIsInMyGuild(unitID) and select(3, GetGuildInfo(unitID)) > maxRank then tinsert(nonCore, k) else -- Note that non-guildmates will be considered core. -- This is a good thing: if you have to PUG to fill in a key role, -- you definitely want them in the raid. tinsert(core, k) end end -- Recombine into keys, inserting padding to force nonCore into group 8. wipe(keys) for _, k in ipairs(core) do tinsert(keys, k) end local k for i = 1, (40 - #core - #nonCore) do k = format("_pad%02d", i) tinsert(keys, k) players[k] = PADDING_PLAYER end for _, k in ipairs(nonCore) do tinsert(keys, k) end end
Fix off-by-one error
Fix off-by-one error
Lua
mit
bencvt/FixGroups
5f09c2969c746e0545648e6d706574ec1521c988
testserver/item/books.lua
testserver/item/books.lua
require("base.common"); module("item.books", package.seeall) -- UPDATE common SET com_script='item.books' WHERE com_itemid = 2622; function InitBook() --[[ -- needs a check if (Init == nil) then bookTitleDE = {}; -- The german title of the book. bookTitleEN = {}; -- The english title of the book. bookLanguage = {}; -- The ingame language skill name in which the book is written. bookminimumLanguage = {}; -- The minimum language skill needed to read that book. -- Book of the priests of Eldan (1) bookTitleDE[1] = "Das Buch der Priester Eldans"; bookTitleEN[1] = "Book of the priests of Eldan"; bookLanguage[1] = Character.commonLanguage; bookMinimumLanguage[1] = 0; Init = true; end]] end function UseItem(User, SourceItem, TargetItem, Counter, Param) InitBook(); -- alchemy book; just to make it accessable for testers if SourceItem:getData("alchemyBook")=="true" then User:sendBook(101) end -- alchemy end -- old data! --[[ if (User:getSkill(bookLanguage[SourceItem.data]) >= bookMinimumLanguage) then User:sendBook(SourceItem.data); else base.common.InformNLS(User, Item, "Das Buch ist in einer Sprache geschrieben, von der du zu wenig Kenntnisse hast.", "The book is written in a language in what your knowledge is not advanced enough."); end]] end function getLookAt(player,item) if player:getPlayerLanguage() == 0 then bookName = "Allgemeine Einfhrng in die Grundlagen der gewhnlichen Alchemie" else bookName = "General introduction to the basics of common alchemy" end lookAt.name = bookName return lookAt end function LookAtItem(player, item) if item:getData("alchemyBook")=="true" then world:itemInform(player, item, getLookAt(player,item)) else world:itemInform(player, item, base.lookat.GenerateLookAt(player, item, 0)) end end
require("base.common"); module("item.books", package.seeall) -- UPDATE common SET com_script='item.books' WHERE com_itemid = 2622; function InitBook() --[[ -- needs a check if (Init == nil) then bookTitleDE = {}; -- The german title of the book. bookTitleEN = {}; -- The english title of the book. bookLanguage = {}; -- The ingame language skill name in which the book is written. bookminimumLanguage = {}; -- The minimum language skill needed to read that book. -- Book of the priests of Eldan (1) bookTitleDE[1] = "Das Buch der Priester Eldans"; bookTitleEN[1] = "Book of the priests of Eldan"; bookLanguage[1] = Character.commonLanguage; bookMinimumLanguage[1] = 0; Init = true; end]] end function UseItem(User, SourceItem, TargetItem, Counter, Param) InitBook(); -- alchemy book; just to make it accessable for testers if SourceItem:getData("alchemyBook")=="true" then User:sendBook(101) end -- alchemy end -- old data! --[[ if (User:getSkill(bookLanguage[SourceItem.data]) >= bookMinimumLanguage) then User:sendBook(SourceItem.data); else base.common.InformNLS(User, Item, "Das Buch ist in einer Sprache geschrieben, von der du zu wenig Kenntnisse hast.", "The book is written in a language in what your knowledge is not advanced enough."); end]] end function LookAtItem(player, item) if item:getData("alchemyBook")=="true" then base.lookat.SetSpecialName(item, "Allgemeine Einfhrng in die Grundlagen der gewhnlichen Alchemie", "General introduction to the basics of common alchemy"); end world:itemInform(player, item, base.lookat.GenerateLookAt(player, item, base.lookat.NONE)); end
alchemy book lookat fix
alchemy book lookat fix
Lua
agpl-3.0
Illarion-eV/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content
9ec432ba638332ea8c2a0b44d2edf17ee5795852
src/cosy/i18n/en.lua
src/cosy/i18n/en.lua
return { ["server:listening"] = "server is listening on %{host}:%{port}", ["tos"] = [[ Cas n°1: Utilisation du logiciel Cosyverif par téléchargement If you download the Cosyverif software, you acknowledge that this software is distributed under the MIT license and that you accept its terms. If you decline the terms of this license you must not download this software. Cas n°2: Utilisation du logiciel Cosyverif directement sur le site If you use the Cosyverif software, you acknowledge that this software is distributed under the MIT license and you accept its terms. If you decline the terms of this license you must not use this software. CAS 3: - Pour le cas que quelqu'un souhaite contribuer avec des modules, c'est moins facile. est-ce que celui qui propose le module vous donne une licence ? et si oui, avec quels droits ? Cas 3a: A l'intention du contributeur qui veut ajouter une contribution au logiciel Cosyverif If you want that your contribution be integrated into the Cosyverif software be sure to read and accept the following provisions: By integrating your contribution into the Cosyverif software, you warrant that you are the author of the contribution and that the latter does not infringe the intellectual property rights of a third party. You assign your patrimonial rights to X for the duration of the patrimonial rights, for all territories throughout the world in order to distribute your contribution as a module of the Cosyverif software. It is specified that the rights assigned to X are as follows: - the right to reproduce the contribution in a whole,........ - the right to represent your contribution in a whole,..... - the right to distribute your contribution under the MIT License - the right to integrate your contribution into the Cosyverif software This assignment of rights is granted for free. Cas 3b: A l'intention des utilisateurs quand la contribution est intégrée au logiciel Cosyverif sans avoir été préalablement accepté par les administrateurs réseaux Be aware the Cosyverif software contains several modules provided "as is", we do not warrant that the modules do not infringe the intellectual property rigths of a third party. ]], ["locale:available"] = "i18n locale '%{loaded}' has been loaded", ["locale:missing"] = "i18n locale '%{loaded}' has not been loaded", ["bcrypt:rounds"] = { one = "using one round in bcrypt for at least %{time} milliseconds of computation", other = "using %{count} rounds in bcrypt for at least %{time} milliseconds of computation", }, ["token:no-secret"] = "token secret is not defined in configuration", ["smtp:not-available"] = "no SMTP server discovered, sending of emails will not work", ["smtp:available"] = "SMTP on %{host}:%{port} uses %{method} (encrypted with %{protocol})", ["smtp:discover"] = "discovering SMTP on %{host}:%{port} using %{method} (encrypted with %{protocol})", ["configuration:using"] = "using configuration in directory %{path}", ["configuration:skipping"] = "skipping configuration in directory %{path}, because %{reason}", ["check:error"] = "some parameters are invalid or missing", ["check:no-check"] = "request argument %{key} has not been checked", ["check:missing"] = "parameter %{key} is missing", ["check:is-string"] = "a %{key} must be a string", ["check:min-size"] = { one = "a %{key} must contain at least one character", other = "a %{key} must be at least %{count} characters long", }, ["check:max-size"] = { one = "a %{key} must contain at most one character", other = "a %{key} must be at most %{count} characters long", }, ["check:username:alphanumeric"] = "a username must contain only alphanumeric characters", ["check:email:pattern"] = "an email address must comply to the standard", ["check:locale:pattern"] = "a locale must comply to the standard", ["check:tos_digest:pattern"] = "a terms of service digest must be a MD5 digest, and thus a sequence of alphanumeric characters", ["check:tos_digest:incorrect"] = "terms of service digest is does not correspond to the terms of service", ["check:token:invalid"] = "token is invalid", ["create-user:email-exists"] = "email address %{email} is already bound to an account", ["create-user:username-exists"] = "username %{username} is already a user account", ["authenticate:failure"] = "authentication failed", ["reset-user:retry"] = "reset failed, please try again later", ["email:reset_account:from"] = '"%{name}" <%{email}>', ["email:reset_account:to"] = '"%{name}" <%{email}>', ["email:reset_account:subject"] = "[%{servername}] Welcome, %{username}!", ["email:reset_account:body"] = "%{username}, your validation token is <%{validation}>.", ["token:not-validation"] = "token is not a validation one", ["token:not-authentication"] = "token is not an authentication one", ["forbidden"] = "action is forbidden", ["redis:unavailable"] = "redis server is unavailable", ["rpc:invalid"] = "rpc message is invalid", ["rpc:no-operation"] = "unknown operation '%{reason}'", ["client:timeout"] = "connection timed out", ["suspend:not-user"] = "account %{username} is not a user", ["suspend:self"] = "are you mad?", ["suspend:not-enough"] = "suspending a user requires %{required} reputation, but only %{owned} is owned", }
return { ["server:listening"] = "server is listening on %{host}:%{port}", ["tos"] = [[ Cas n°1: Utilisation du logiciel Cosyverif par téléchargement If you download the Cosyverif software, you acknowledge that this software is distributed under the MIT license and that you accept its terms. If you decline the terms of this license you must not download this software. Cas n°2: Utilisation du logiciel Cosyverif directement sur le site If you use the Cosyverif software, you acknowledge that this software is distributed under the MIT license and you accept its terms. If you decline the terms of this license you must not use this software. CAS 3: - Pour le cas que quelqu'un souhaite contribuer avec des modules, c'est moins facile. est-ce que celui qui propose le module vous donne une licence ? et si oui, avec quels droits ? Cas 3a: A l'intention du contributeur qui veut ajouter une contribution au logiciel Cosyverif If you want that your contribution be integrated into the Cosyverif software be sure to read and accept the following provisions: By integrating your contribution into the Cosyverif software, you warrant that you are the author of the contribution and that the latter does not infringe the intellectual property rights of a third party. You assign your patrimonial rights to X for the duration of the patrimonial rights, for all territories throughout the world in order to distribute your contribution as a module of the Cosyverif software. It is specified that the rights assigned to X are as follows: - the right to reproduce the contribution in a whole,........ - the right to represent your contribution in a whole,..... - the right to distribute your contribution under the MIT License - the right to integrate your contribution into the Cosyverif software This assignment of rights is granted for free. Cas 3b: A l'intention des utilisateurs quand la contribution est intégrée au logiciel Cosyverif sans avoir été préalablement accepté par les administrateurs réseaux Be aware the Cosyverif software contains several modules provided "as is", we do not warrant that the modules do not infringe the intellectual property rigths of a third party. ]], ["locale:available"] = "i18n locale '%{loaded}' has been loaded", ["locale:missing"] = "i18n locale '%{loaded}' has not been loaded", ["directory:not-directory"] = "a %{mode} already exists at %{directory}", ["directory:created"] = "directory %{directory} has been successfully created", ["directory:not-created"] = "directory %{directory} has not been created because %{reason}", ["dependency:success"] = "dependency %{source} has been downloaded and installed as %{target}", ["dependency:failure"] = "dependency %{source} is unavailable and cannot be installed as %{target}", ["bcrypt:rounds"] = { one = "using one round in bcrypt for at least %{time} milliseconds of computation", other = "using %{count} rounds in bcrypt for at least %{time} milliseconds of computation", }, ["token:no-secret"] = "token secret is not defined in configuration", ["smtp:not-available"] = "no SMTP server discovered, sending of emails will not work", ["smtp:available"] = "SMTP on %{host}:%{port} uses %{method} (encrypted with %{protocol})", ["smtp:discover"] = "discovering SMTP on %{host}:%{port} using %{method} (encrypted with %{protocol})", ["configuration:using"] = "using configuration in directory %{path}", ["configuration:skipping"] = "skipping configuration in directory %{path}, because %{reason}", ["check:error"] = "some parameters are invalid or missing", ["check:no-check"] = "request argument %{key} has not been checked", ["check:missing"] = "parameter %{key} is missing", ["check:is-string"] = "a %{key} must be a string", ["check:min-size"] = { one = "a %{key} must contain at least one character", other = "a %{key} must be at least %{count} characters long", }, ["check:max-size"] = { one = "a %{key} must contain at most one character", other = "a %{key} must be at most %{count} characters long", }, ["check:username:alphanumeric"] = "a username must contain only alphanumeric characters", ["check:email:pattern"] = "an email address must comply to the standard", ["check:locale:pattern"] = "a locale must comply to the standard", ["check:tos_digest:pattern"] = "a terms of service digest must be a MD5 digest, and thus a sequence of alphanumeric characters", ["check:tos_digest:incorrect"] = "terms of service digest is does not correspond to the terms of service", ["check:token:invalid"] = "token is invalid", ["create-user:email-exists"] = "email address %{email} is already bound to an account", ["create-user:username-exists"] = "username %{username} is already a user account", ["authenticate:failure"] = "authentication failed", ["reset-user:retry"] = "reset failed, please try again later", ["email:reset_account:from"] = '"%{name}" <%{email}>', ["email:reset_account:to"] = '"%{name}" <%{email}>', ["email:reset_account:subject"] = "[%{servername}] Welcome, %{username}!", ["email:reset_account:body"] = "%{username}, your validation token is <%{validation}>.", ["token:not-validation"] = "token is not a validation one", ["token:not-authentication"] = "token is not an authentication one", ["forbidden"] = "action is forbidden", ["redis:unavailable"] = "redis server is unavailable", ["rpc:invalid"] = "rpc message is invalid", ["rpc:no-operation"] = "unknown operation '%{reason}'", ["client:timeout"] = "connection timed out", ["suspend:not-user"] = "account %{username} is not a user", ["suspend:self"] = "are you mad?", ["suspend:not-enough"] = "suspending a user requires %{required} reputation, but only %{owned} is owned", }
Fix the call to make_default.
Fix the call to make_default.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
fdc0783b887b7c9289c3fc9063a538bacf66001c
modules/luci-base/luasrc/tools/status.lua
modules/luci-base/luasrc/tools/status.lua
-- Copyright 2011 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.tools.status", package.seeall) local uci = require "luci.model.uci".cursor() local function dhcp_leases_common(family) local rv = { } local nfs = require "nixio.fs" local leasefile = "/var/dhcp.leases" uci:foreach("dhcp", "dnsmasq", function(s) if s.leasefile and nfs.access(s.leasefile) then leasefile = s.leasefile return false end end) local fd = io.open(leasefile, "r") if fd then while true do local ln = fd:read("*l") if not ln then break else local ts, mac, ip, name, duid = ln:match("^(%d+) (%S+) (%S+) (%S+) (%S+)") if ts and mac and ip and name and duid then if family == 4 and not ip:match(":") then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), macaddr = mac, ipaddr = ip, hostname = (name ~= "*") and name } elseif family == 6 and ip:match(":") then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), ip6addr = ip, duid = (duid ~= "*") and duid, hostname = (name ~= "*") and name } end end end end fd:close() end local fd = io.open("/tmp/hosts/odhcpd", "r") if fd then while true do local ln = fd:read("*l") if not ln then break else local iface, duid, iaid, name, ts, id, length, ip = ln:match("^# (%S+) (%S+) (%S+) (%S+) (%d+) (%S+) (%S+) (.*)") if ip and iaid ~= "ipv4" and family == 6 then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), duid = duid, ip6addr = ip, hostname = (name ~= "-") and name } elseif ip and iaid == "ipv4" and family == 4 then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), macaddr = duid, ipaddr = ip, hostname = (name ~= "-") and name } end end end fd:close() end return rv end function dhcp_leases() return dhcp_leases_common(4) end function dhcp6_leases() return dhcp_leases_common(6) end function wifi_networks() local rv = { } local ntm = require "luci.model.network".init() local dev for _, dev in ipairs(ntm:get_wifidevs()) do local rd = { up = dev:is_up(), device = dev:name(), name = dev:get_i18n(), networks = { } } local net for _, net in ipairs(dev:get_wifinets()) do rd.networks[#rd.networks+1] = { name = net:shortname(), link = net:adminlink(), up = net:is_up(), mode = net:active_mode(), ssid = net:active_ssid(), bssid = net:active_bssid(), encryption = net:active_encryption(), frequency = net:frequency(), channel = net:channel(), signal = net:signal(), quality = net:signal_percent(), noise = net:noise(), bitrate = net:bitrate(), ifname = net:ifname(), assoclist = net:assoclist(), country = net:country(), txpower = net:txpower(), txpoweroff = net:txpower_offset(), disabled = (dev:get("disabled") == "1" or net:get("disabled") == "1") } end rv[#rv+1] = rd end return rv end function wifi_network(id) local ntm = require "luci.model.network".init() local net = ntm:get_wifinet(id) if net then local dev = net:get_device() if dev then return { id = id, name = net:shortname(), link = net:adminlink(), up = net:is_up(), mode = net:active_mode(), ssid = net:active_ssid(), bssid = net:active_bssid(), encryption = net:active_encryption(), frequency = net:frequency(), channel = net:channel(), signal = net:signal(), quality = net:signal_percent(), noise = net:noise(), bitrate = net:bitrate(), ifname = net:ifname(), assoclist = net:assoclist(), country = net:country(), txpower = net:txpower(), txpoweroff = net:txpower_offset(), disabled = (dev:get("disabled") == "1" or net:get("disabled") == "1"), device = { up = dev:is_up(), device = dev:name(), name = dev:get_i18n() } } end end return { } end function switch_status(devs) local dev local switches = { } for dev in devs:gmatch("[^%s,]+") do local ports = { } local swc = io.popen("swconfig dev %q show" % dev, "r") if swc then local l repeat l = swc:read("*l") if l then local port, up = l:match("port:(%d+) link:(%w+)") if port then local speed = l:match(" speed:(%d+)") local duplex = l:match(" (%w+)-duplex") local txflow = l:match(" (txflow)") local rxflow = l:match(" (rxflow)") local auto = l:match(" (auto)") ports[#ports+1] = { port = tonumber(port) or 0, speed = tonumber(speed) or 0, link = (up == "up"), duplex = (duplex == "full"), rxflow = (not not rxflow), txflow = (not not txflow), auto = (not not auto) } end end until not l swc:close() end switches[dev] = ports end return switches end
-- Copyright 2011 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.tools.status", package.seeall) local uci = require "luci.model.uci".cursor() local function dhcp_leases_common(family) local rv = { } local nfs = require "nixio.fs" local leasefile = "/var/dhcp.leases" uci:foreach("dhcp", "dnsmasq", function(s) if s.leasefile and nfs.access(s.leasefile) then leasefile = s.leasefile return false end end) local fd = io.open(leasefile, "r") if fd then while true do local ln = fd:read("*l") if not ln then break else local ts, mac, ip, name, duid = ln:match("^(%d+) (%S+) (%S+) (%S+) (%S+)") if ts and mac and ip and name and duid then if family == 4 and not ip:match(":") then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), macaddr = mac, ipaddr = ip, hostname = (name ~= "*") and name } elseif family == 6 and ip:match(":") then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), ip6addr = ip, duid = (duid ~= "*") and duid, hostname = (name ~= "*") and name } end end end end fd:close() end local lease6file = "/tmp/hosts/odhcpd" uci:foreach("dhcp", "odhcpd", function(t) if t.leasefile and nfs.access(t.leasefile) then lease6file = t.leasefile return false end end) local fd = io.open(lease6file, "r") if fd then while true do local ln = fd:read("*l") if not ln then break else local iface, duid, iaid, name, ts, id, length, ip = ln:match("^# (%S+) (%S+) (%S+) (%S+) (%d+) (%S+) (%S+) (.*)") if ip and iaid ~= "ipv4" and family == 6 then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), duid = duid, ip6addr = ip, hostname = (name ~= "-") and name } elseif ip and iaid == "ipv4" and family == 4 then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), macaddr = duid, ipaddr = ip, hostname = (name ~= "-") and name } end end end fd:close() end return rv end function dhcp_leases() return dhcp_leases_common(4) end function dhcp6_leases() return dhcp_leases_common(6) end function wifi_networks() local rv = { } local ntm = require "luci.model.network".init() local dev for _, dev in ipairs(ntm:get_wifidevs()) do local rd = { up = dev:is_up(), device = dev:name(), name = dev:get_i18n(), networks = { } } local net for _, net in ipairs(dev:get_wifinets()) do rd.networks[#rd.networks+1] = { name = net:shortname(), link = net:adminlink(), up = net:is_up(), mode = net:active_mode(), ssid = net:active_ssid(), bssid = net:active_bssid(), encryption = net:active_encryption(), frequency = net:frequency(), channel = net:channel(), signal = net:signal(), quality = net:signal_percent(), noise = net:noise(), bitrate = net:bitrate(), ifname = net:ifname(), assoclist = net:assoclist(), country = net:country(), txpower = net:txpower(), txpoweroff = net:txpower_offset(), disabled = (dev:get("disabled") == "1" or net:get("disabled") == "1") } end rv[#rv+1] = rd end return rv end function wifi_network(id) local ntm = require "luci.model.network".init() local net = ntm:get_wifinet(id) if net then local dev = net:get_device() if dev then return { id = id, name = net:shortname(), link = net:adminlink(), up = net:is_up(), mode = net:active_mode(), ssid = net:active_ssid(), bssid = net:active_bssid(), encryption = net:active_encryption(), frequency = net:frequency(), channel = net:channel(), signal = net:signal(), quality = net:signal_percent(), noise = net:noise(), bitrate = net:bitrate(), ifname = net:ifname(), assoclist = net:assoclist(), country = net:country(), txpower = net:txpower(), txpoweroff = net:txpower_offset(), disabled = (dev:get("disabled") == "1" or net:get("disabled") == "1"), device = { up = dev:is_up(), device = dev:name(), name = dev:get_i18n() } } end end return { } end function switch_status(devs) local dev local switches = { } for dev in devs:gmatch("[^%s,]+") do local ports = { } local swc = io.popen("swconfig dev %q show" % dev, "r") if swc then local l repeat l = swc:read("*l") if l then local port, up = l:match("port:(%d+) link:(%w+)") if port then local speed = l:match(" speed:(%d+)") local duplex = l:match(" (%w+)-duplex") local txflow = l:match(" (txflow)") local rxflow = l:match(" (rxflow)") local auto = l:match(" (auto)") ports[#ports+1] = { port = tonumber(port) or 0, speed = tonumber(speed) or 0, link = (up == "up"), duplex = (duplex == "full"), rxflow = (not not rxflow), txflow = (not not txflow), auto = (not not auto) } end end until not l swc:close() end switches[dev] = ports end return switches end
luci-base: read odhcpd leasefile location via uci
luci-base: read odhcpd leasefile location via uci Check the location of the odhcpd leasefile from /etc/config/dhcp via uci. Fallback to the default location. This fixes #702 Signed-off-by: Hannu Nyman <[email protected]> (cherry picked from commit 51a7f96877d8c5bf70217073ed8aa7ab6a196d20)
Lua
apache-2.0
Sakura-Winkey/LuCI,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,RuiChen1113/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,RuiChen1113/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,RuiChen1113/luci
ad5436e1ee8060aa6dc6df172ee710e02bdd63f8
libs/sys/luasrc/sys/mtdow.lua
libs/sys/luasrc/sys/mtdow.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local io = require "io" local os = require "os" local fs = require "luci.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local posix = require "posix" local type, assert, error = type, assert, error module "luci.sys.mtdow" WRITE_IMAGE = 0 WRITE_COMBINED = 1 WRITE_EMULATED = 2 ERROR_INTERNAL = 1 ERROR_NOTFOUND = 2 ERROR_RESOURCE = 3 ERROR_NODETECT = 4 ERROR_NOTAVAIL = 5 ERROR_NOSTREAM = 6 ERROR_INVMAGIC = 7 Writer = util.class() -- x86 EmulatedWriter = util.class(Writer) EmulatedWriter.blocks = { image = { magic = "eb48", device = "/dev/hda", write = WRITE_SEPARATELY } } function EmulatedWriter.write_block(self, name, imagestream, appendpattern) if appendpattern then os.execute("grep rootfs /proc/mtd >/dev/null || " .. "{ echo /dev/hda2,65536,rootfs > " .. "/sys/module/block2mtd/parameters/block2mtd }") end return Writer.write_block(self, name, imagestream, appendpattern) end -- Broadcom CFEWriter = util.class(Writer) CFEWriter.blocks = { image = { magic = {"4844", "5735"}, device = "linux", write = WRITE_COMBINED } } -- Magicbox CommonWriter = util.class(Writer) CommonWriter.blocks = { image = { device = "linux", write = WRITE_COMBINED } } -- Atheros RedWriter = util.class(Writer) RedWriter.blocks = { kernel = { device = "vmlinux.bin.l7", write = WRITE_IMAGE }, rootfs = { device = "rootfs", write = WRITE_COMBINED } } -- Auto Detect function native_writer() local w = Writer() -- Detect amd64 / x86 local x86 = {"x86_64", "i386", "i486", "i586", "i686"} if util.contains(x86, posix.uname("%m")) then return EmulatedWriter() end -- Detect CFE if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then return CFEWriter() end -- Detect Redboot if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then return RedWriter() end -- Detect MagicBox if fs.readfile("/proc/cpuinfo"):find("MagicBox") then return CommonWriter() end end Writer.MTD = "/sbin/mtd" Writer.SAFEMTD = "/tmp/mtd" Writer.IMAGEFIFO = "/tmp/mtdimage.fifo" function Writer.write_block(self, name, imagestream, appendfile) assert(self.blocks[name], ERROR_NOTFOUND) local block = self.blocks[name] local device = block.device device = fs.stat(device) and device or self:_find_mtdblock(device) assert(device, ERROR_NODETECT) if block.magic then imagestream = self:_check_magic(imagestream, block.magic) end assert(imagestream, ERROR_INVMAGIC) if appendfile then if block.write == WRITE_COMBINED then return (self:_write_combined(device, imagestream, appendfile) == 0) elseif block.write == WRITE_EMULATED then return (self:_write_emulated(device, imagestream, appendfile) == 0) else error(ERROR_NOTAVAIL) end else return (self:_write_memory(device, imagestream) == 0) end end function Writer._check_magic(self, imagestream, magic) magic = type(magic) == "table" and magic or {magic} local block = imagestream() assert(block, ERROR_NOSTREAM) local cm = "%x%x" % {block:byte(1), block:byte(2)} if util.contains(magic, cm) then return ltn12.source.cat(ltn12.source.string(block), imagestream) end end function Writer._find_mtdblock(self, mtdname) local k local prefix = "/dev/mtdblock" prefix = prefix .. (fs.stat(prefix) and "/" or "") for l in io.lines("/proc/mtd") do local k = l:match('([%w-_]+):.*-"%s"' % mtdname) if k then return prefix..k end end end function Write._write_emulated(self, devicename, imagestream, appendfile) local stat = (self:_write_memory(device, imagestream) == 0) stat = stat and (self:_refresh_block("rootfs") == 0) local squash = self:_find_mtdblock("rootfs_data") if squash then stat = stat and (self:_append("rootfs_data", imagestream, true) == 0) else stat = stat and (self:_append("rootfs", imagestream) == 0) end return stat end function Writer._write_memory(self, devicename, imagestream) local devicestream = ltn12.sink.file(io.open(devicename, "w")) local stat, err = ltn12.pump.all(imagestream, devicestream) if stat then return os.execute("sync") end end function Writer._write_combined(self, devicename, imagestream, appendfile) assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s -j '%s' write '%s' '%s'" % { self.SAFEMTD, appendfile, devicename, self.IMAGEFIFO } ) end function Writer._refresh_block(self, devicename) assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL) return os.execute("%s refresh '%s'" % {self.SAFEMTD, devicename}) end function Writer._append(self, devicename, appendfile, erase) assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL) erase = erase and ("-e '%s' " % devicename) or '' return os.execute( "%s %s jffs2write '%s' '%s'" % { self.SAFEMTD, erase, appendfile, devicename } ) end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local io = require "io" local os = require "os" local fs = require "luci.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local posix = require "posix" local type, assert, error = type, assert, error module "luci.sys.mtdow" WRITE_IMAGE = 0 WRITE_COMBINED = 1 WRITE_EMULATED = 2 ERROR_INTERNAL = 1 ERROR_NOTFOUND = 2 ERROR_RESOURCE = 3 ERROR_NODETECT = 4 ERROR_NOTAVAIL = 5 ERROR_NOSTREAM = 6 ERROR_INVMAGIC = 7 Writer = util.class() -- x86 EmulatedWriter = util.class(Writer) EmulatedWriter.blocks = { image = { magic = "eb48", device = "/dev/hda", write = WRITE_SEPARATELY } } function EmulatedWriter.write_block(self, name, imagestream, appendpattern) if appendpattern then os.execute("grep rootfs /proc/mtd >/dev/null || " .. "{ echo /dev/hda2,65536,rootfs > " .. "/sys/module/block2mtd/parameters/block2mtd }") end return Writer.write_block(self, name, imagestream, appendpattern) end -- Broadcom CFEWriter = util.class(Writer) CFEWriter.blocks = { image = { magic = {"4844", "5735"}, device = "linux", write = WRITE_COMBINED } } -- Magicbox CommonWriter = util.class(Writer) CommonWriter.blocks = { image = { device = "linux", write = WRITE_COMBINED } } -- Atheros RedWriter = util.class(Writer) RedWriter.blocks = { kernel = { device = "vmlinux.bin.l7", write = WRITE_IMAGE }, rootfs = { device = "rootfs", write = WRITE_COMBINED } } -- Auto Detect function native_writer() local w = Writer() -- Detect amd64 / x86 local x86 = {"x86_64", "i386", "i486", "i586", "i686"} if util.contains(x86, posix.uname("%m")) then return EmulatedWriter() end -- Detect CFE if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then return CFEWriter() end -- Detect Redboot if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then return RedWriter() end -- Detect MagicBox if fs.readfile("/proc/cpuinfo"):find("MagicBox") then return CommonWriter() end end Writer.MTD = "/sbin/mtd" Writer.SAFEMTD = "/tmp/mtd" Writer.IMAGEFIFO = "/tmp/mtdimage.fifo" function Writer.write_block(self, name, imagestream, appendfile) assert(self.blocks[name], ERROR_NOTFOUND) local block = self.blocks[name] local device = block.device device = fs.stat(device) and device or self:_find_mtdblock(device) assert(device, ERROR_NODETECT) if block.magic then imagestream = self:_check_magic(imagestream, block.magic) end assert(imagestream, ERROR_INVMAGIC) if appendfile then if block.write == WRITE_COMBINED then return (self:_write_combined(device, imagestream, appendfile) == 0) elseif block.write == WRITE_EMULATED then return (self:_write_emulated(device, imagestream, appendfile) == 0) else error(ERROR_NOTAVAIL) end else return (self:_write_memory(device, imagestream) == 0) end end function Writer._check_magic(self, imagestream, magic) magic = type(magic) == "table" and magic or {magic} local block = imagestream() assert(block, ERROR_NOSTREAM) local cm = "%x%x" % {block:byte(1), block:byte(2)} if util.contains(magic, cm) then return ltn12.source.cat(ltn12.source.string(block), imagestream) end end function Writer._find_mtdblock(self, mtdname) local k local prefix = "/dev/mtd" prefix = prefix .. (fs.stat(prefix) and "/" or "") for l in io.lines("/proc/mtd") do local k = l:match('mtd([%%w-_]+):.*"%s"' % mtdname) if k then return prefix..k end end end function Writer._write_emulated(self, devicename, imagestream, appendfile) local stat = (self:_write_memory(device, imagestream) == 0) stat = stat and (self:_refresh_block("rootfs") == 0) local squash = self:_find_mtdblock("rootfs_data") if squash then stat = stat and (self:_append("rootfs_data", imagestream, true) == 0) else stat = stat and (self:_append("rootfs", imagestream) == 0) end return stat end function Writer._write_memory(self, devicename, imagestream) local devicestream = ltn12.sink.file(io.open(devicename, "w")) local stat, err = ltn12.pump.all(imagestream, devicestream) if stat then return os.execute("sync") end end function Writer._write_combined(self, devicename, imagestream, appendfile) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then fs.unlink(self.IMAGEFIFO) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s -j '%s' write '%s' '%s'" % { self.MTD, appendfile, self.IMAGEFIFO, devicename } ) end function Writer._refresh_block(self, devicename) return os.execute("%s refresh '%s'" % {self.MTD, devicename}) end function Writer._append(self, devicename, appendfile, erase) erase = erase and ("-e '%s' " % devicename) or '' return os.execute( "%s %s jffs2write '%s' '%s'" % { self.MTD, erase, appendfile, devicename } ) end
mtdow fixes level 1
mtdow fixes level 1
Lua
apache-2.0
8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
16246abef87351eaf106d235dbcee591196ba0e2
modules/rpc/luasrc/controller/rpc.lua
modules/rpc/luasrc/controller/rpc.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local require = require local pairs = pairs local print = print local pcall = pcall local table = table module "luci.controller.rpc" function index() local function authenticator(validator, accs) local auth = luci.http.formvalue("auth", true) if auth then local user = luci.sauth.read(auth) if user and luci.util.contains(accs, user) then return user, auth end end luci.http.status(403, "Forbidden") end if pcall(require, "luci.model.uci") then uci = entry({"rpc", "uci"}, call("rpc_uci")) uci.sysauth = "root" uci.sysauth_authenticator = authenticator end fs = entry({"rpc", "fs"}, call("rpc_fs")) fs.sysauth = "root" fs.sysauth_authenticator = authenticator sys = entry({"rpc", "sys"}, call("rpc_sys")) sys.sysauth = "root" sys.sysauth_authenticator = authenticator if pcall(require, "luci.model.ipkg") then fs = entry({"rpc", "ipkg"}, call("rpc_ipkg")) fs.sysauth = "root" fs.sysauth_authenticator = authenticator end uci = entry({"rpc", "auth"}, call("rpc_auth")) end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local sauth = require "luci.sauth" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" http.setfilehandler() local loginstat local server = {} server.login = function(user, pass) local sid if sys.user.checkpasswd(user, pass) then sid = sys.uniqueid(16) http.header("Set-Cookie", "sysauth=" .. sid.."; path=/") sauth.write(sid, user) end return sid end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() local uci = require "luci.controller.rpc.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 "luci.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() 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 - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local require = require local pairs = pairs local print = print local pcall = pcall local table = table module "luci.controller.rpc" function index() local function authenticator(validator, accs) local auth = luci.http.formvalue("auth", true) if auth then local user = luci.sauth.read(auth) if user and luci.util.contains(accs, user) then return user, auth end end luci.http.status(403, "Forbidden") end uci = entry({"rpc", "uci"}, call("rpc_uci")) uci.sysauth = "root" uci.sysauth_authenticator = authenticator fs = entry({"rpc", "fs"}, call("rpc_fs")) fs.sysauth = "root" fs.sysauth_authenticator = authenticator sys = entry({"rpc", "sys"}, call("rpc_sys")) sys.sysauth = "root" sys.sysauth_authenticator = authenticator ipkg = entry({"rpc", "ipkg"}, call("rpc_ipkg")) ipkg.sysauth = "root" ipkg.sysauth_authenticator = authenticator uci = entry({"rpc", "auth"}, call("rpc_auth")) end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local sauth = require "luci.sauth" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" http.setfilehandler() local loginstat local server = {} server.login = function(user, pass) local sid if sys.user.checkpasswd(user, pass) then sid = sys.uniqueid(16) http.header("Set-Cookie", "sysauth=" .. sid.."; path=/") sauth.write(sid, user) end return sid 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.controller.rpc.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 "luci.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
Fixed RPC-API
Fixed RPC-API git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3005 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
ThingMesh/openwrt-luci,Canaan-Creative/luci,vhpham80/luci,gwlim/luci,jschmidlapp/luci,freifunk-gluon/luci,freifunk-gluon/luci,jschmidlapp/luci,freifunk-gluon/luci,Flexibity/luci,Flexibity/luci,ch3n2k/luci,yeewang/openwrt-luci,vhpham80/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,8devices/carambola2-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,Canaan-Creative/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,alxhh/piratenluci,jschmidlapp/luci,gwlim/luci,vhpham80/luci,eugenesan/openwrt-luci,Flexibity/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,freifunk-gluon/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,yeewang/openwrt-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,ch3n2k/luci,stephank/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,8devices/carambola2-luci,8devices/carambola2-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,saraedum/luci-packages-old,Flexibity/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,eugenesan/openwrt-luci,Flexibity/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,8devices/carambola2-luci,stephank/luci,Flexibity/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,alxhh/piratenluci,zwhfly/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,phi-psi/luci,zwhfly/openwrt-luci,vhpham80/luci,saraedum/luci-packages-old,gwlim/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,phi-psi/luci,ch3n2k/luci,projectbismark/luci-bismark,freifunk-gluon/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ch3n2k/luci,vhpham80/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,Canaan-Creative/luci,projectbismark/luci-bismark,jschmidlapp/luci,stephank/luci,Canaan-Creative/luci,saraedum/luci-packages-old,Flexibity/luci,gwlim/luci,Canaan-Creative/luci,jschmidlapp/luci,gwlim/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,stephank/luci,alxhh/piratenluci,zwhfly/openwrt-luci,Canaan-Creative/luci,jschmidlapp/luci,Flexibity/luci,jschmidlapp/luci,phi-psi/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,ThingMesh/openwrt-luci,stephank/luci,yeewang/openwrt-luci,phi-psi/luci
7cb337035ee80c059c583cecd84962b1e05efa21
vim/.config/nvim/lua/plugins/lsp.lua
vim/.config/nvim/lua/plugins/lsp.lua
local lspconfig, ok = prequire"lspconfig" if not ok then return end local cmp_lsp = require"cmp_nvim_lsp" local path = require("lspconfig/util").path local on_attach = function(client, bufnr) local bufopts = {noremap=true, silent=true, buffer=bufnr} vim.keymap.set("n", "gD", vim.lsp.buf.declaration, bufopts) vim.keymap.set("n", "gd", vim.lsp.buf.definition, bufopts) vim.keymap.set("n", "K", vim.lsp.buf.hover, bufopts) vim.keymap.set("n", "gi", vim.lsp.buf.implementation, bufopts) vim.keymap.set("n", "<C-k>", vim.lsp.buf.signature_help, bufopts) vim.keymap.set("n", "<space>rn", vim.lsp.buf.rename, bufopts) vim.keymap.set("n", "<space>ca", vim.lsp.buf.code_action, bufopts) vim.keymap.set("n", "gr", vim.lsp.buf.references, bufopts) vim.keymap.set("n", "mf", function() vim.lsp.buf.format { async = false, timeout_ms = 2500 } end, bufopts) vim.keymap.set("n", "<space>e", vim.diagnostic.open_float, bufopts) vim.keymap.set("n", "[d", vim.diagnostic.goto_prev, bufopts) vim.keymap.set("n", "]d", vim.diagnostic.goto_next, bufopts) vim.keymap.set("n", "<space>q", vim.diagnostic.setloclist, bufopts) end function before_init(initialize_params, config) if initialize_params.clientInfo.name == "pyright" then local python_bin if vim.env.VIRTUAL_ENV then python_bin = path.join(vim.env.VIRTUAL_ENV, "bin", "python") else python_bin = exepath("python") or "python" end config.settings.python.pythonPath = python_bin end end local capabilities = cmp_lsp.default_capabilities() local servers = {"pyright"} for _, lsp in ipairs(servers) do lspconfig[lsp].setup { capabilities = capabilities, on_attach = on_attach, before_init = before_init, } end
local lspconfig, ok = prequire"lspconfig" if not ok then return end local cmp_lsp = require"cmp_nvim_lsp" local path = require("lspconfig/util").path local on_attach = function(client, bufnr) local bufopts = {noremap=true, silent=true, buffer=bufnr} vim.keymap.set("n", "gD", vim.lsp.buf.declaration, bufopts) vim.keymap.set("n", "gd", vim.lsp.buf.definition, bufopts) vim.keymap.set("n", "K", vim.lsp.buf.hover, bufopts) vim.keymap.set("n", "gi", vim.lsp.buf.implementation, bufopts) vim.keymap.set("n", "<C-k>", vim.lsp.buf.signature_help, bufopts) vim.keymap.set("n", "<space>rn", vim.lsp.buf.rename, bufopts) vim.keymap.set("n", "<space>ca", vim.lsp.buf.code_action, bufopts) vim.keymap.set("n", "gr", vim.lsp.buf.references, bufopts) vim.keymap.set("n", "mf", function() vim.lsp.buf.format { async = false, timeout_ms = 2500 } end, bufopts) vim.keymap.set("n", "<space>e", vim.diagnostic.open_float, bufopts) vim.keymap.set("n", "[d", vim.diagnostic.goto_prev, bufopts) vim.keymap.set("n", "]d", vim.diagnostic.goto_next, bufopts) vim.keymap.set("n", "<space>q", vim.diagnostic.setloclist, bufopts) end function before_init(_, config) if config.settings.python ~= nil then local python_bin if vim.env.VIRTUAL_ENV then python_bin = path.join(vim.env.VIRTUAL_ENV, "bin", "python") else python_bin = exepath("python") or "python" end config.settings.python.pythonPath = python_bin end end local capabilities = cmp_lsp.default_capabilities() local servers = {"pyright"} for _, lsp in ipairs(servers) do lspconfig[lsp].setup { capabilities = capabilities, on_attach = on_attach, before_init = before_init, } end
vim: fix pyright lsp initialization
vim: fix pyright lsp initialization Signed-off-by: Niklas Koep <[email protected]>
Lua
apache-2.0
nkoep/dotfiles,nkoep/dotfiles,nkoep/dotfiles
2780fb5910feeef2cca14b3a98c9788b1c0d1eaf
state/settings_video_display.lua
state/settings_video_display.lua
local o = {} local startx = W.getWidth() * 0.5 - 191 * 0.5 local starty = 80 o.imgBackground = love.graphics.newImage("resources/sprites/ui/menu_background.png") o.imgMiddleground = love.graphics.newImage("resources/sprites/ui/menu_middleground.png") o.imgScreen = love.graphics.newImage("gfx/screen00.png") o.fontMenu = G.newFont(32) o.fontOption = G.newFont(24) o.effectTimer = 0 o.chromaticEffect = 0 o.guiMenu = love.gui.newGui() o.chkFullscreen = o.guiMenu.newCheckbox(startx, starty + 64 * 0, 191, 32, true, "Fullscreen") o.chkLarge = o.guiMenu.newCheckbox(startx, starty + 64 * 1, 191, 32, false, "Large") o.btnBack = o.guiMenu.newButton(startx + 8, starty + 64 * 5 + 8, 176, 32, "Back") o.optionBloom = true o.optionScanlines = true o.optionShadow = true o.optionGlow = true o.reset = function() o.guiMenu.flushMouse() end o.update = function(dt) o.effectTimer = o.effectTimer + dt o.chromaticEffect = o.chromaticEffect + dt o.guiMenu.update(dt) if o.chkFullscreen.isHit() then love.sounds.playSound("sounds/button_pressed.wav") --o.optionBloom = o.chkBloom.isChecked() end if o.chkLarge.isHit() then love.sounds.playSound("sounds/button_pressed.wav") --o.optionScanlines = o.chkScanlines.isChecked() end if o.btnBack.isHit() or love.keyboard.isDown("escape") then love.sounds.playSound("sounds/button_pressed.wav") love.setgamestate(7) o.guiMenu.flushMouse() end end o.draw = function() G.setFont(o.fontMenu) G.setBlendMode("alpha") G.setColor(255, 255, 255) G.draw(o.imgScreen) G.setColor(255, 255, 255, 223) G.draw(o.imgBackground) G.setColor(95 + math.sin(o.effectTimer * 0.1) * 63, 191 + math.cos(o.effectTimer) * 31, 223 + math.sin(o.effectTimer) * 31, 255) G.setBlendMode("additive") G.draw(o.imgMiddleground,(W.getWidth()-o.imgMiddleground:getWidth())*0.5,0) G.setBlendMode("alpha") G.setColor(0, 0, 0, 95) G.printf("Settings", 4, 24 + 4, W.getWidth(), "center") G.setColor(255, 127, 0) G.setBlendMode("additive") G.printf("Settings", 0, 24, W.getWidth(), "center") G.setFont(o.fontOption) o.guiMenu.draw() if math.random(0, love.timer.getFPS() * 5) == 0 then o.chromaticEffect = math.random(0, 5) * 0.1 end if o.chromaticEffect < 1.0 then local colorAberration1 = math.sin(love.timer.getTime() * 10.0) * (1.0 - o.chromaticEffect) * 2.0 local colorAberration2 = math.cos(love.timer.getTime() * 10.0) * (1.0 - o.chromaticEffect) * 2.0 love.postshader.addEffect("chromatic", colorAberration1, colorAberration2, colorAberration2, -colorAberration1, colorAberration1, -colorAberration2) end end return o
local o = {} local startx = W.getWidth() * 0.5 - 191 * 0.5 local starty = 80 o.imgBackground = love.graphics.newImage("resources/sprites/ui/menu_background.png") o.imgMiddleground = love.graphics.newImage("resources/sprites/ui/menu_middleground.png") o.imgScreen = love.graphics.newImage("gfx/screen00.png") o.fontMenu = G.newFont(32) o.fontOption = G.newFont(24) o.effectTimer = 0 o.chromaticEffect = 0 o.guiMenu = love.gui.newGui() o.chkFullscreen = o.guiMenu.newCheckbox(startx, starty + 64 * 0, 191, 32, true, "Fullscreen") o.chkLarge = o.guiMenu.newCheckbox(startx, starty + 64 * 1, 191, 32, false, "Large") o.btnBack = o.guiMenu.newButton(startx + 8, starty + 64 * 5 + 8, 176, 32, "Back") o.optionLarge = small o.reset = function() o.guiMenu.flushMouse() end o.update = function(dt) o.effectTimer = o.effectTimer + dt o.chromaticEffect = o.chromaticEffect + dt o.guiMenu.update(dt) if o.chkFullscreen.isHit() then love.sounds.playSound("sounds/button_pressed.wav") --o.optionBloom = o.chkBloom.isChecked() end if o.chkLarge.isHit() then love.sounds.playSound("sounds/button_pressed.wav") local success o.optionLarge = o.chkLarge.isChecked() if o.optionLarge then success = love.window.setMode( 1280, 720) else success = love.window.setMode( 800, 600 ) end if not success then --do something end end if o.btnBack.isHit() or love.keyboard.isDown("escape") then love.sounds.playSound("sounds/button_pressed.wav") love.setgamestate(7) o.guiMenu.flushMouse() end end o.draw = function() G.setFont(o.fontMenu) G.setBlendMode("alpha") G.setColor(255, 255, 255) G.draw(o.imgScreen) G.setColor(255, 255, 255, 223) G.draw(o.imgBackground) G.setColor(95 + math.sin(o.effectTimer * 0.1) * 63, 191 + math.cos(o.effectTimer) * 31, 223 + math.sin(o.effectTimer) * 31, 255) G.setBlendMode("additive") G.draw(o.imgMiddleground,(W.getWidth()-o.imgMiddleground:getWidth())*0.5,0) G.setBlendMode("alpha") G.setColor(0, 0, 0, 95) G.printf("Settings", 4, 24 + 4, W.getWidth(), "center") G.setColor(255, 127, 0) G.setBlendMode("additive") G.printf("Settings", 0, 24, W.getWidth(), "center") G.setFont(o.fontOption) o.guiMenu.draw() if math.random(0, love.timer.getFPS() * 5) == 0 then o.chromaticEffect = math.random(0, 5) * 0.1 end if o.chromaticEffect < 1.0 then local colorAberration1 = math.sin(love.timer.getTime() * 10.0) * (1.0 - o.chromaticEffect) * 2.0 local colorAberration2 = math.cos(love.timer.getTime() * 10.0) * (1.0 - o.chromaticEffect) * 2.0 love.postshader.addEffect("chromatic", colorAberration1, colorAberration2, colorAberration2, -colorAberration1, colorAberration1, -colorAberration2) end end return o
switch between small (800x600) and [moderately] large [1280x720) resolutions. this partially fixes issue #54. I will get the fullscreen option setting working too, but actually choosing resolutions from a will be done in a separate issue, because it involves a whole new widget type.
switch between small (800x600) and [moderately] large [1280x720) resolutions. this partially fixes issue #54. I will get the fullscreen option setting working too, but actually choosing resolutions from a will be done in a separate issue, because it involves a whole new widget type.
Lua
mit
sam1i/Turres-Monacorum,sam1i/Turres-Monacorum
d0229ce52dd664d7e7abd07f2c35b7cea719d850
regex_find.lua
regex_find.lua
-- Copyright (C) 2014 Chris Emerson <[email protected]> -- See LICENSE for details (MIT license). local M = {} local ta_regex = require 'ta-regex.regex' -- Replace textadept's events.FIND handler with one implementing better regex. function M.install() events.connect(events.FIND, M.find, 1) end -- Find expression forwards from the current point. function M.find(regex, forward) local pat = ta_regex.compile(regex) -- Search a subset of the buffer, and adjust the match to set the -- start/end pointers correctly. local function search(startpos, endpos) local m = pat:match(buffer:text_range(startpos, endpos)) if m then -- Adjust result to take account of startpos m._start = m._start + startpos - 1 m._end = m._end + startpos end return m end -- As search(), but search backwards. -- This isn't as efficient, as it searches forward and waits for the -- last match. local function search_rev(startpos, endpos) local res = nil while true do local m = search(startpos, endpos) if m then -- a later match than we'd previously had res = m -- Start searching from this point (non-overlapping) startpos = m._end else -- no other matches - return the last we got. break end end return res end local m = nil if forward then local startpos = buffer.current_pos + 1 local endpos = buffer.length m = search(startpos, endpos) or search(0, endpos) else local startpos = 0 local endpos = buffer.current_pos m = search_rev(startpos, endpos) or search_rev(0, buffer.length) end if m then local s, e = m._start, m._end buffer:set_sel(e, s) else ui.statusbar_text = "Not found" end return false end return M
-- Copyright (C) 2014 Chris Emerson <[email protected]> -- See LICENSE for details (MIT license). local M = {} local ta_regex = require 'ta-regex.regex' -- Replace textadept's events.FIND handler with one implementing better regex. function M.install() events.connect(events.FIND, M.find, 1) end -- Find expression forwards from the current point. function M.find(regex, forward) local pat = ta_regex.compile(regex) -- Search a subset of the buffer, and adjust the match to set the -- start/end pointers correctly. local function search(startpos, endpos) local m = pat:match(buffer:text_range(startpos, endpos)) if m then -- Adjust result to take account of startpos m._start = m._start + startpos - 1 m._end = m._end + startpos end return m end -- As search(), but search backwards. -- This isn't as efficient, as it searches forward and waits for the -- last match. local function search_rev(startpos, endpos) local res = nil while true do local m = search(startpos, endpos) if m then -- a later match than we'd previously had res = m -- Start searching from this point (non-overlapping) startpos = m._end else -- no other matches - return the last we got. break end end return res end local m = nil if forward then local startpos = buffer.current_pos + 1 local endpos = buffer.length -- If we're at the end of the buffer, then start from -- the beginning. if startpos >= endpos then startpos = 0 end m = search(startpos, endpos) or search(0, endpos) else local startpos = 0 local endpos = buffer.current_pos m = search_rev(startpos, endpos) or search_rev(0, buffer.length) end if m then local s, e = m._start, m._end buffer:set_sel(e, s) else ui.statusbar_text = "Not found" end return false end return M
Hopefully fix issue #4: fix a case where startpos > end of buffer (when starting a search at the end of the buffer).
Hopefully fix issue #4: fix a case where startpos > end of buffer (when starting a search at the end of the buffer).
Lua
mit
jugglerchris/textadept-vi,jugglerchris/textadept-vi
a836734bfc02b695aa102b257b22c0f0f13e4a34
test/test_multi_callback.lua
test/test_multi_callback.lua
local curl = require "lcurl" local called, active_coroutine = 0 function on_timer() called = called + 1 -- use `os.exit` because now Lua-cURL did not propogate error from callback if coroutine.running() ~= active_coroutine then os.exit(-1) end end local function test_1() io.write('Test #1 - ') called, active_coroutine = 0 local e = curl.easy() local m = curl.multi{ timerfunction = on_timer } active_coroutine = coroutine.create(function() m:add_handle(e) end) coroutine.resume(active_coroutine) assert(called == 1) active_coroutine = nil m:remove_handle(e) assert(called == 2) io.write('pass!\n') end local function test_2() io.write('Test #2 - ') called, active_coroutine = 0 local e = curl.easy() local m = curl.multi{ timerfunction = on_timer } active_coroutine = coroutine.create(function() m:add_handle(e) end) coroutine.resume(active_coroutine) assert(called == 1) active_coroutine = coroutine.create(function() m:remove_handle(e) end) coroutine.resume(active_coroutine) assert(called == 2) io.write('pass!\n') end local function test_3() io.write('Test #3 - ') called, active_coroutine = 0 local e = curl.easy() local m = curl.multi{ timerfunction = on_timer } active_coroutine = coroutine.create(function() m:add_handle(e) end) coroutine.resume(active_coroutine) assert(called == 1) active_coroutine = nil e:close() assert(called == 2) io.write('pass!\n') end local function test_4() io.write('Test #4 - ') called, active_coroutine = 0 local e = curl.easy() local m = curl.multi{ timerfunction = on_timer } active_coroutine = coroutine.create(function() m:add_handle(e) end) coroutine.resume(active_coroutine) assert(called == 1) active_coroutine = coroutine.create(function() e:close() end) coroutine.resume(active_coroutine) assert(called == 2) io.write('pass!\n') end test_1() test_2() test_3() test_4()
local curl = require "lcurl" local called, active_coroutine = 0 -- for Lua 5.1 compat local function co_running() local co, main = coroutine.running() if main == true then return nil end return co end function on_timer() called = called + 1 -- use `os.exit` because now Lua-cURL did not propogate error from callback if co_running() ~= active_coroutine then os.exit(-1) end end local function test_1() io.write('Test #1 - ') called, active_coroutine = 0 local e = curl.easy() local m = curl.multi{ timerfunction = on_timer } active_coroutine = coroutine.create(function() m:add_handle(e) end) coroutine.resume(active_coroutine) assert(called == 1) active_coroutine = nil m:remove_handle(e) assert(called == 2) io.write('pass!\n') end local function test_2() io.write('Test #2 - ') called, active_coroutine = 0 local e = curl.easy() local m = curl.multi{ timerfunction = on_timer } active_coroutine = coroutine.create(function() m:add_handle(e) end) coroutine.resume(active_coroutine) assert(called == 1) active_coroutine = coroutine.create(function() m:remove_handle(e) end) coroutine.resume(active_coroutine) assert(called == 2) io.write('pass!\n') end local function test_3() io.write('Test #3 - ') called, active_coroutine = 0 local e = curl.easy() local m = curl.multi{ timerfunction = on_timer } active_coroutine = coroutine.create(function() m:add_handle(e) end) coroutine.resume(active_coroutine) assert(called == 1) active_coroutine = nil e:close() assert(called == 2) io.write('pass!\n') end local function test_4() io.write('Test #4 - ') called, active_coroutine = 0 local e = curl.easy() local m = curl.multi{ timerfunction = on_timer } active_coroutine = coroutine.create(function() m:add_handle(e) end) coroutine.resume(active_coroutine) assert(called == 1) active_coroutine = coroutine.create(function() e:close() end) coroutine.resume(active_coroutine) assert(called == 2) io.write('pass!\n') end test_1() test_2() test_3() test_4()
Fix. Test for Lua > 5.1
Fix. Test for Lua > 5.1
Lua
mit
Lua-cURL/Lua-cURLv3,Lua-cURL/Lua-cURLv3,moteus/lua-lcurl,Lua-cURL/Lua-cURLv3,moteus/lua-lcurl
a57a6187a7976f84d6f752bde31258d33daa5a6d
npc/base/condition/magictype.lua
npc/base/condition/magictype.lua
require("base.class") require("npc.base.condition.condition") module("npc.base.condition.magictype", package.seeall) magictype = base.class.class(npc.base.condition.condition.condition, function(self, value) npc.base.condition.condition.condition:init(self); if (value == "nomagic") then self["check"] = _magictype_helper_none; elseif (value == "mage") then self["check"] = _magictype_helper_mage; elseif (value == "priest") then self["check"] = _magictype_helper_priest; elseif (value == "bard") then self["check"] = _magictype_helper_bard; elseif (value == "druid") then self["check"] = _magictype_helper_druid; end; end); function _magictype_helper_none(self, npcChar, player) return (player:getMagicFlags(player:getMagicType()) == 0) end; function _magictype_helper_mage(self, npcChar, player) local magicType = player:getMagicType(); if (magicType == 0) then return true; end; if (player:getMagicFlags(magicType) == 0) then return true; end; return false; end; function _magictype_helper_priest(self, npcChar, player) local magicType = player:getMagicType(); if (magicType == 1) then return true; end; if (player:getMagicFlags(magicType) == 0) then return true; end; return false; end; function _magictype_helper_bard(self, npcChar, player) local magicType = player:getMagicType(); if (magicType == 2) then return true; end; if (player:getMagicFlags(magicType) == 0) then return true; end; return false; end; function _magictype_helper_druid(self, npcChar, player) local magicType = player:getMagicType(); if (magicType == 3) then return true; end; if (player:getMagicFlags(magicType) == 0) then return true; end; return false; end;
require("base.class") require("npc.base.condition.condition") module("npc.base.condition.magictype", package.seeall) magictype = base.class.class(npc.base.condition.condition.condition, function(self, value) npc.base.condition.condition.condition:init(self); if (value == "nomagic") then self["check"] = _magictype_helper_none; elseif (value == "mage") then self["check"] = _magictype_helper_mage; elseif (value == "priest") then self["check"] = _magictype_helper_priest; elseif (value == "bard") then self["check"] = _magictype_helper_bard; elseif (value == "druid") then self["check"] = _magictype_helper_druid; end; end); function _magictype_helper_none(self, npcChar, player) return (player:getMagicFlags(player:getMagicType()) == 0) end; function _magictype_helper_mage(self, npcChar, player) return _test_magictype(player, 0) end; function _magictype_helper_priest(self, npcChar, player) return _test_magictype(player, 1) end; function _magictype_helper_bard(self, npcChar, player) return _test_magictype(player, 2) end; function _magictype_helper_druid(self, npcChar, player) return _test_magictype(player, 3) end; function _test_magictype(player, magicType) local playerMagicType = player:getMagicType(); if (playerMagicType ~= magicType) then return false; end; return player:getMagicFlags(magicType) >= 0; end;
Fixed magic type NPC condition
Fixed magic type NPC condition The magic type condition did not return the correct values.
Lua
agpl-3.0
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content
765e30772e8711945e87d38bffac243732a83887
plugins/mod_disco.lua
plugins/mod_disco.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local get_children = require "core.hostmanager".get_children; local is_contact_subscribed = require "core.rostermanager".is_contact_subscribed; local jid_split = require "util.jid".split; local jid_bare = require "util.jid".bare; local st = require "util.stanza" local calculate_hash = require "util.caps".calculate_hash; local disco_items = module:get_option("disco_items") or {}; do -- validate disco_items for _, item in ipairs(disco_items) do local err; if type(item) ~= "table" then err = "item is not a table"; elseif type(item[1]) ~= "string" then err = "item jid is not a string"; elseif item[2] and type(item[2]) ~= "string" then err = "item name is not a string"; end if err then module:log("error", "option disco_items is malformed: %s", err); disco_items = {}; -- TODO clean up data instead of removing it? break; end end end module:add_identity("server", "im", "Prosody"); -- FIXME should be in the non-existing mod_router module:add_feature("http://jabber.org/protocol/disco#info"); module:add_feature("http://jabber.org/protocol/disco#items"); -- Generate and cache disco result and caps hash local _cached_server_disco_info, _cached_server_caps_feature, _cached_server_caps_hash; local function build_server_disco_info() local query = st.stanza("query", { xmlns = "http://jabber.org/protocol/disco#info" }); local done = {}; for _,identity in ipairs(module:get_host_items("identity")) do local identity_s = identity.category.."\0"..identity.type; if not done[identity_s] then query:tag("identity", identity):up(); done[identity_s] = true; end end for _,feature in ipairs(module:get_host_items("feature")) do if not done[feature] then query:tag("feature", {var=feature}):up(); done[feature] = true; end end _cached_server_disco_info = query; _cached_server_caps_hash = calculate_hash(query); _cached_server_caps_feature = st.stanza("c", { xmlns = "http://jabber.org/protocol/caps"; hash = "sha-1"; node = "http://prosody.im"; ver = _cached_server_caps_hash; }); end local function clear_disco_cache() _cached_server_disco_info, _cached_server_caps_feature, _cached_server_caps_hash = nil, nil, nil; end local function get_server_disco_info() if not _cached_server_disco_info then build_server_disco_info(); end return _cached_server_disco_info; end local function get_server_caps_feature() if not _cached_server_caps_feature then build_server_disco_info(); end return _cached_server_caps_feature; end local function get_server_caps_hash() if not _cached_server_caps_hash then build_server_disco_info(); end return _cached_server_caps_hash; end module:hook("item-added/identity", clear_disco_cache); module:hook("item-added/feature", clear_disco_cache); module:hook("item-removed/identity", clear_disco_cache); module:hook("item-removed/feature", clear_disco_cache); -- Handle disco requests to the server module:hook("iq/host/http://jabber.org/protocol/disco#info:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" and node ~= "http://prosody.im#"..get_server_caps_hash() then return; end -- TODO fire event? local reply_query = get_server_disco_info(); reply_query.node = node; local reply = st.reply(stanza):add_child(reply_query); origin.send(reply); return true; end); module:hook("iq/host/http://jabber.org/protocol/disco#items:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items"); for jid in pairs(get_children(module.host)) do reply:tag("item", {jid = jid}):up(); end for _, item in ipairs(disco_items) do reply:tag("item", {jid=item[1], name=item[2]}):up(); end origin.send(reply); return true; end); -- Handle caps stream feature module:hook("stream-features", function (event) if event.origin.type == "c2s" then event.features:add_child(get_server_caps_feature()); end end); -- Handle disco requests to user accounts module:hook("iq/bare/http://jabber.org/protocol/disco#info:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local username = jid_split(stanza.attr.to) or origin.username; if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then local reply = st.reply(stanza):tag('query', {xmlns='http://jabber.org/protocol/disco#info'}); if not reply.attr.from then reply.attr.from = origin.username.."@"..origin.host; end -- COMPAT To satisfy Psi when querying own account module:fire_event("account-disco-info", { origin = origin, stanza = reply }); origin.send(reply); return true; end end); module:hook("iq/bare/http://jabber.org/protocol/disco#items:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local username = jid_split(stanza.attr.to) or origin.username; if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then local reply = st.reply(stanza):tag('query', {xmlns='http://jabber.org/protocol/disco#items'}); if not reply.attr.from then reply.attr.from = origin.username.."@"..origin.host; end -- COMPAT To satisfy Psi when querying own account module:fire_event("account-disco-items", { origin = origin, stanza = reply }); origin.send(reply); return true; end end);
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local get_children = require "core.hostmanager".get_children; local is_contact_subscribed = require "core.rostermanager".is_contact_subscribed; local jid_split = require "util.jid".split; local jid_bare = require "util.jid".bare; local st = require "util.stanza" local calculate_hash = require "util.caps".calculate_hash; local disco_items = module:get_option("disco_items") or {}; do -- validate disco_items for _, item in ipairs(disco_items) do local err; if type(item) ~= "table" then err = "item is not a table"; elseif type(item[1]) ~= "string" then err = "item jid is not a string"; elseif item[2] and type(item[2]) ~= "string" then err = "item name is not a string"; end if err then module:log("error", "option disco_items is malformed: %s", err); disco_items = {}; -- TODO clean up data instead of removing it? break; end end end module:add_identity("server", "im", "Prosody"); -- FIXME should be in the non-existing mod_router module:add_feature("http://jabber.org/protocol/disco#info"); module:add_feature("http://jabber.org/protocol/disco#items"); -- Generate and cache disco result and caps hash local _cached_server_disco_info, _cached_server_caps_feature, _cached_server_caps_hash; local function build_server_disco_info() local query = st.stanza("query", { xmlns = "http://jabber.org/protocol/disco#info" }); local done = {}; for _,identity in ipairs(module:get_host_items("identity")) do local identity_s = identity.category.."\0"..identity.type; if not done[identity_s] then query:tag("identity", identity):up(); done[identity_s] = true; end end for _,feature in ipairs(module:get_host_items("feature")) do if not done[feature] then query:tag("feature", {var=feature}):up(); done[feature] = true; end end _cached_server_disco_info = query; _cached_server_caps_hash = calculate_hash(query); _cached_server_caps_feature = st.stanza("c", { xmlns = "http://jabber.org/protocol/caps"; hash = "sha-1"; node = "http://prosody.im"; ver = _cached_server_caps_hash; }); end local function clear_disco_cache() _cached_server_disco_info, _cached_server_caps_feature, _cached_server_caps_hash = nil, nil, nil; end local function get_server_disco_info() if not _cached_server_disco_info then build_server_disco_info(); end return _cached_server_disco_info; end local function get_server_caps_feature() if not _cached_server_caps_feature then build_server_disco_info(); end return _cached_server_caps_feature; end local function get_server_caps_hash() if not _cached_server_caps_hash then build_server_disco_info(); end return _cached_server_caps_hash; end module:hook("item-added/identity", clear_disco_cache); module:hook("item-added/feature", clear_disco_cache); module:hook("item-removed/identity", clear_disco_cache); module:hook("item-removed/feature", clear_disco_cache); -- Handle disco requests to the server module:hook("iq/host/http://jabber.org/protocol/disco#info:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" and node ~= "http://prosody.im#"..get_server_caps_hash() then return; end -- TODO fire event? local reply_query = get_server_disco_info(); reply_query.node = node; local reply = st.reply(stanza):add_child(reply_query); origin.send(reply); return true; end); module:hook("iq/host/http://jabber.org/protocol/disco#items:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items"); for jid in pairs(get_children(module.host)) do reply:tag("item", {jid = jid}):up(); end for _, item in ipairs(disco_items) do reply:tag("item", {jid=item[1], name=item[2]}):up(); end origin.send(reply); return true; end); -- Handle caps stream feature module:hook("stream-features", function (event) event.features:add_child(get_server_caps_feature()); end); -- Handle disco requests to user accounts module:hook("iq/bare/http://jabber.org/protocol/disco#info:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local username = jid_split(stanza.attr.to) or origin.username; if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then local reply = st.reply(stanza):tag('query', {xmlns='http://jabber.org/protocol/disco#info'}); if not reply.attr.from then reply.attr.from = origin.username.."@"..origin.host; end -- COMPAT To satisfy Psi when querying own account module:fire_event("account-disco-info", { origin = origin, stanza = reply }); origin.send(reply); return true; end end); module:hook("iq/bare/http://jabber.org/protocol/disco#items:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local username = jid_split(stanza.attr.to) or origin.username; if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then local reply = st.reply(stanza):tag('query', {xmlns='http://jabber.org/protocol/disco#items'}); if not reply.attr.from then reply.attr.from = origin.username.."@"..origin.host; end -- COMPAT To satisfy Psi when querying own account module:fire_event("account-disco-items", { origin = origin, stanza = reply }); origin.send(reply); return true; end end);
mod_disco: Fixed: Service discovery features were not being removed on module unload (issue #205).
mod_disco: Fixed: Service discovery features were not being removed on module unload (issue #205).
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
b2c38f9d5f393bb9f2f959cf2f2cb66daf03b698
script/c81907872.lua
script/c81907872.lua
--ゴーストリック・スペクター function c81907872.initial_effect(c) --summon limit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetCondition(c81907872.sumcon) c:RegisterEffect(e1) --turn set local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(81907872,0)) e2:SetCategory(CATEGORY_POSITION) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetTarget(c81907872.postg) e2:SetOperation(c81907872.posop) c:RegisterEffect(e2) --spsummon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(81907872,1)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DRAW) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e3:SetCode(EVENT_TO_GRAVE) e3:SetRange(LOCATION_HAND) e3:SetCondition(c81907872.spcon) e3:SetTarget(c81907872.sptg) e3:SetOperation(c81907872.spop) c:RegisterEffect(e3) end function c81907872.sfilter(c) return c:IsFaceup() and c:IsSetCard(0x8d) end function c81907872.sumcon(e) return not Duel.IsExistingMatchingCard(c81907872.sfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end function c81907872.postg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(81907872)==0 end c:RegisterFlagEffect(81907872,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1) Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0) end function c81907872.posop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.ChangePosition(c,POS_FACEDOWN_DEFENCE) end end function c81907872.cfilter(c,tp) return c:GetPreviousControler()==tp and c:IsSetCard(0x8d) and c:IsReason(REASON_DESTROY) and c:IsType(TYPE_MONSTER) end function c81907872.spcon(e,tp,eg,ep,ev,re,r,rp) return rp~=tp and eg:IsExists(c81907872.cfilter,1,nil,tp) end function c81907872.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN) and Duel.IsPlayerCanDraw(tp,1) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c81907872.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEDOWN_DEFENCE) then Duel.ConfirmCards(1-tp,c) Duel.Draw(tp,1,REASON_EFFECT) end end
--ゴーストリック・スペクター function c81907872.initial_effect(c) --summon limit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetCondition(c81907872.sumcon) c:RegisterEffect(e1) --turn set local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(81907872,0)) e2:SetCategory(CATEGORY_POSITION) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetTarget(c81907872.postg) e2:SetOperation(c81907872.posop) c:RegisterEffect(e2) --spsummon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(81907872,1)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DRAW) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e3:SetCode(EVENT_TO_GRAVE) e3:SetRange(LOCATION_HAND) e3:SetCondition(c81907872.spcon) e3:SetTarget(c81907872.sptg) e3:SetOperation(c81907872.spop) c:RegisterEffect(e3) end function c81907872.sfilter(c) return c:IsFaceup() and c:IsSetCard(0x8d) end function c81907872.sumcon(e) return not Duel.IsExistingMatchingCard(c81907872.sfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end function c81907872.postg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(81907872)==0 end c:RegisterFlagEffect(81907872,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1) Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0) end function c81907872.posop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.ChangePosition(c,POS_FACEDOWN_DEFENCE) end end function c81907872.cfilter(c,tp) return c:GetPreviousControler()==tp and c:IsSetCard(0x8d) and c:IsReason(REASON_DESTROY) and (not c:IsReason(REASON_BATTLE) or c==Duel.GetAttackTarget()) and c:IsType(TYPE_MONSTER) end function c81907872.spcon(e,tp,eg,ep,ev,re,r,rp) return rp~=tp and eg:IsExists(c81907872.cfilter,1,nil,tp) end function c81907872.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN) and Duel.IsPlayerCanDraw(tp,1) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c81907872.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEDOWN_DEFENCE) then Duel.ConfirmCards(1-tp,c) Duel.Draw(tp,1,REASON_EFFECT) end end
fix v2
fix v2
Lua
mit
sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher,SuperAndroid17/DevProLauncher
6512718cd950efb2c386e2aea43103b27fd234b2
vanilla/sys/nginx/handle.lua
vanilla/sys/nginx/handle.lua
local va_conf = require 'vanilla.sys.config' local function create_dirs(necessary_dirs) for _, dir in pairs(necessary_dirs) do os.execute("mkdir -p " .. dir .. " > /dev/null") end end local function create_nginx_conf(nginx_conf_file_path, nginx_conf_content) local fw = io.open(nginx_conf_file_path, "w") fw:write(nginx_conf_content) fw:close() end local function remove_nginx_conf(nginx_conf_file_path) os.remove(nginx_conf_file_path) end local function nginx_command(env, nginx_conf_file_path, nginx_signal) local devnull_logs = "" if V_TRACE == false then devnull_logs = " 2>/dev/null" end local env_cmd = "" local nginx = "" if VANILLA_NGX_PATH ~= nil then nginx = VANILLA_NGX_PATH .. "/sbin/nginx " else nginx = "nginx " end if env ~= nil then env_cmd = "-g \"env VA_ENV=" .. env .. ";\"" end local cmd = nginx .. nginx_signal .. " " .. env_cmd .. " -p `pwd`/ -c " .. nginx_conf_file_path .. devnull_logs if V_TRACE == true then print(cmd) end return os.execute(cmd) end local function start_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '') end local function stop_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '-s stop') end local function reload_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '-s reload') end local NginxHandle = {} NginxHandle.__index = NginxHandle function NginxHandle.new(nginx_conf_content, nginx_conf_file_path) local necessary_dirs = va_conf.app_dirs local instance = { nginx_conf_content = nginx_conf_content, nginx_conf_file_path = nginx_conf_file_path, necessary_dirs = necessary_dirs } setmetatable(instance, NginxHandle) return instance end function NginxHandle:start(env) create_dirs(self.necessary_dirs) create_nginx_conf(self.nginx_conf_file_path, self.nginx_conf_content) return start_nginx(env, self.nginx_conf_file_path) end function NginxHandle:stop(env) result = stop_nginx(env, self.nginx_conf_file_path) remove_nginx_conf(self.nginx_conf_file_path) return result end function NginxHandle:reload(env) remove_nginx_conf(self.nginx_conf_file_path) create_nginx_conf(self.nginx_conf_file_path, self.nginx_conf_content) return reload_nginx(env, self.nginx_conf_file_path) end return NginxHandle
local va_conf = require 'vanilla.sys.config' local function create_dirs(necessary_dirs) for _, dir in pairs(necessary_dirs) do os.execute("mkdir -p " .. dir .. " > /dev/null") end end local function create_nginx_conf(nginx_conf_file_path, nginx_conf_content) local fw = io.open(nginx_conf_file_path, "w") fw:write(nginx_conf_content) fw:close() end local function remove_nginx_conf(nginx_conf_file_path) os.remove(nginx_conf_file_path) end local function nginx_command(env, nginx_conf_file_path, nginx_signal) local devnull_logs = "" if V_TRACE == false then devnull_logs = " 2>/dev/null" end local env_cmd = "" local nginx = "" if VANILLA_NGX_PATH ~= nil then nginx = VANILLA_NGX_PATH .. "/sbin/nginx " else nginx = "nginx " end if env ~= nil then env_cmd = "-g \"env VA_ENV=" .. env .. ";\"" end local cmd = nginx .. nginx_signal .. " " .. env_cmd .. " -p `pwd`/ -c " .. nginx_conf_file_path .. devnull_logs if V_TRACE == true then print(cmd) end return os.execute(cmd) end local function start_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '') end local function stop_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '-s stop') end local function reload_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '-s reload') end local NginxHandle = {} NginxHandle.__index = NginxHandle function NginxHandle.new(nginx_conf_content, nginx_conf_file_path) local necessary_dirs = va_conf.app_dirs local instance = { nginx_conf_content = nginx_conf_content, nginx_conf_file_path = nginx_conf_file_path, necessary_dirs = necessary_dirs } setmetatable(instance, NginxHandle) return instance end function NginxHandle:start(env) create_dirs(self.necessary_dirs) create_nginx_conf(self.nginx_conf_file_path, self.nginx_conf_content) return start_nginx(env, self.nginx_conf_file_path) end function NginxHandle:stop(env) result = stop_nginx(env, self.nginx_conf_file_path) remove_nginx_conf(self.nginx_conf_file_path) return result end function NginxHandle:reload(env) remove_nginx_conf(self.nginx_conf_file_path) create_dirs(self.necessary_dirs) create_nginx_conf(self.nginx_conf_file_path, self.nginx_conf_content) return reload_nginx(env, self.nginx_conf_file_path) end return NginxHandle
fix a reload bug
fix a reload bug
Lua
mit
lhmwzy/vanilla,idevz/vanilla,lhmwzy/vanilla,idevz/vanilla,lhmwzy/vanilla,lhmwzy/vanilla
8d54750efd666756d4afe8a16a544f4285229263
script/c23232295.lua
script/c23232295.lua
--BK 拘束蛮兵リードブロー function c23232295.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,aux.XyzFilterFunctionF(c,aux.FilterBoolFunction(Card.IsSetCard,0x84),4),2) c:EnableReviveLimit() --destroy replace local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EFFECT_DESTROY_REPLACE) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c23232295.reptg) e1:SetValue(c23232295.repval) c:RegisterEffect(e1) --attack up local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(23232295,0)) e2:SetCategory(CATEGORY_ATKCHANGE) e2:SetType(EFFECT_TYPE_TRIGGER_F+EFFECT_TYPE_SINGLE) e2:SetCode(EVENT_DETACH_MATERIAL) e2:SetTarget(c23232295.atktg) e2:SetOperation(c23232295.atkop) c:RegisterEffect(e2) end function c23232295.repfilter(c,tp) return c:IsFaceup() and c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:IsSetCard(0x84) end function c23232295.reptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(c23232295.repfilter,1,nil,tp) end if e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_EFFECT) and Duel.SelectYesNo(tp,aux.Stringid(23232295,1)) then e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_EFFECT) local g=eg:Filter(c23232295.repfilter,nil,tp) if g:GetCount()==1 then e:SetLabelObject(g:GetFirst()) else Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESREPLACE) local cg=g:Select(tp,1,1,nil) e:SetLabelObject(cg:GetFirst()) end return true else return false end end function c23232295.repval(e,c) return c==e:GetLabelObject() end function c23232295.atktg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsRelateToEffect(e) end end function c23232295.atkop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1ff0000) e1:SetValue(800) c:RegisterEffect(e1) end end
--BK 拘束蛮兵リードブロー function c23232295.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,aux.XyzFilterFunctionF(c,aux.FilterBoolFunction(Card.IsSetCard,0x84),4),2) c:EnableReviveLimit() --destroy replace local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(23232295,0)) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EFFECT_DESTROY_REPLACE) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c23232295.reptg) e1:SetValue(c23232295.repval) c:RegisterEffect(e1) --attack up local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_ATKCHANGE) e2:SetType(EFFECT_TYPE_TRIGGER_F+EFFECT_TYPE_SINGLE) e2:SetCode(EVENT_DETACH_MATERIAL) e2:SetTarget(c23232295.atktg) e2:SetOperation(c23232295.atkop) c:RegisterEffect(e2) end function c23232295.repfilter(c,tp) return c:IsFaceup() and c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:IsSetCard(0x84) end function c23232295.reptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(c23232295.repfilter,1,nil,tp) end if e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_EFFECT) and Duel.SelectYesNo(tp,aux.Stringid(23232295,1)) then e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_EFFECT) local g=eg:Filter(c23232295.repfilter,nil,tp) if g:GetCount()==1 then e:SetLabelObject(g:GetFirst()) else Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESREPLACE) local cg=g:Select(tp,1,1,nil) e:SetLabelObject(cg:GetFirst()) end return true else return false end end function c23232295.repval(e,c) return c==e:GetLabelObject() end function c23232295.atktg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsRelateToEffect(e) end end function c23232295.atkop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1ff0000) e1:SetValue(800) c:RegisterEffect(e1) end end
Update c23232295.lua
Update c23232295.lua Yoke, effect string fix
Lua
mit
sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher,SuperAndroid17/DevProLauncher
f60052bf18113f4808d3694bcd4bf8e4a8362c22
script/c80600031.lua
script/c80600031.lua
--@pCAEOCX function c80600031.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetRange(LOCATION_GRAVE) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCondition(c80600031.spcon) e1:SetCost(c80600031.spcost) e1:SetTarget(c80600031.sptg) e1:SetOperation(c80600031.spop) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_TOGRAVE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCost(c80600031.tgtg) e2:SetOperation(c80600031.tgop) c:RegisterEffect(e2) end function c80600031.cfilter(c,tp) return c:IsFaceup() and c:IsControler(tp) and c:IsRace(RACE_ZOMBIE) and c:GetLevel()>4 end function c80600031.spcon(e,tp,eg,ep,ev,re,r,rp) local rc=re:GetHandler() return eg:IsExists(c80600031.cfilter,1,nil,tp) and rc:IsRace(RACE_ZOMBIE) end function c80600031.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetFlagEffect(tp,80600031)==0 and Duel.CheckLPCost(tp,2000) end Duel.PayLPCost(tp,2000) Duel.RegisterFlagEffect(tp,80600031,RESET_PHASE+PHASE_END,0,1) end function c80600031.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c80600031.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end end function c80600031.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(80600031,3)) local op=Duel.SelectOption(tp,aux.Stringid(80600031,0),aux.Stringid(80600031,1),aux.Stringid(80600031,2)) e:SetLabel(op) Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,1-tp,LOCATION_DECK) end function c80600031.tgfilter(c,ty) return c:IsType(ty) and c:IsAbleToGrave() end function c80600031.tgop(e,tp,eg,ep,ev,re,r,rp) local g=nil Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) if e:GetLabel()==0 then g=Duel.SelectMatchingCard(1-tp,c80600031.tgfilter,1-tp,LOCATION_DECK,0,1,1,nil,TYPE_MONSTER) elseif e:GetLabel()==1 then g=Duel.SelectMatchingCard(1-tp,c80600031.tgfilter,1-tp,LOCATION_DECK,0,1,1,nil,TYPE_SPELL) else g=Duel.SelectMatchingCard(1-tp,c80600031.tgfilter,1-tp,LOCATION_DECK,0,1,1,nil,TYPE_TRAP) end Duel.SendtoGrave(g,REASON_EFFECT) end
--���@���p�C�A�E�O���C�X function c80600031.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetRange(LOCATION_GRAVE) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCondition(c80600031.spcon) e1:SetCost(c80600031.spcost) e1:SetTarget(c80600031.sptg) e1:SetOperation(c80600031.spop) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_TOGRAVE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCost(c80600031.tgtg) e2:SetOperation(c80600031.tgop) c:RegisterEffect(e2) end function c80600031.cfilter(c,tp) return c:IsFaceup() and c:IsControler(tp) and c:IsRace(RACE_ZOMBIE) and c:GetLevel()>4 and c:GetReason()==REASON_EFFECT end function c80600031.spcon(e,tp,eg,ep,ev,re,r,rp) local rc=re:GetHandler() return eg:IsExists(c80600031.cfilter,1,nil,tp) and rc:IsRace(RACE_ZOMBIE) end function c80600031.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetFlagEffect(tp,80600031)==0 and Duel.CheckLPCost(tp,2000) end Duel.PayLPCost(tp,2000) Duel.RegisterFlagEffect(tp,80600031,RESET_PHASE+PHASE_END,0,1) end function c80600031.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c80600031.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end end function c80600031.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(80600031,3)) local op=Duel.SelectOption(tp,aux.Stringid(80600031,0),aux.Stringid(80600031,1),aux.Stringid(80600031,2)) e:SetLabel(op) Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,1-tp,LOCATION_DECK) end function c80600031.tgfilter(c,ty) return c:IsType(ty) and c:IsAbleToGrave() end function c80600031.tgop(e,tp,eg,ep,ev,re,r,rp) local g=nil Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) if e:GetLabel()==0 then g=Duel.SelectMatchingCard(1-tp,c80600031.tgfilter,1-tp,LOCATION_DECK,0,1,1,nil,TYPE_MONSTER) elseif e:GetLabel()==1 then g=Duel.SelectMatchingCard(1-tp,c80600031.tgfilter,1-tp,LOCATION_DECK,0,1,1,nil,TYPE_SPELL) else g=Duel.SelectMatchingCard(1-tp,c80600031.tgfilter,1-tp,LOCATION_DECK,0,1,1,nil,TYPE_TRAP) end Duel.SendtoGrave(g,REASON_EFFECT) end
fix
fix fixed triggering on Inherent Summons
Lua
mit
SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher
95772e58134f1fb1e84612b2aa57dd8c0891abbc
scen_edit/meta/meta_model.lua
scen_edit/meta/meta_model.lua
MetaModel = LCS.class{} SCEN_EDIT_META_MODEL_DIR = SCEN_EDIT_DIR .. "meta/" function MetaModel:init() SCEN_EDIT.IncludeDir(SCEN_EDIT_META_MODEL_DIR) self.numericComparisonTypes = {"==", "~=", "<=", ">=", ">", "<"} -- maybe use more user friendly signs self.identityComparisonTypes = {"is", "is not"} -- maybe use more user friendly signs self:SetVariableTypes() --TODO: add array type --local arrayTypes = {} end function MetaModel:SetEventTypes(eventTypes) self.eventTypes = eventTypes self.eventTypes = SCEN_EDIT.CreateNameMapping(self.eventTypes) end function MetaModel:SetFunctionTypes(functionTypes) for i = 1, #functionTypes do local functionType = functionTypes[i] functionType.input = SCEN_EDIT.parseData(functionType.input) end self.functionTypes = SCEN_EDIT.CreateNameMapping(functionTypes) self.functionTypesByInput = SCEN_EDIT.GroupByField(functionTypes, "input") self.functionTypesByOutput = SCEN_EDIT.GroupByField(functionTypes, "output") local coreTypes = SCEN_EDIT.coreTypes() -- fill missing for k, v in pairs(self.functionTypesByInput) do self.functionTypesByInput[k] = SCEN_EDIT.CreateNameMapping(v) end for k, v in pairs(self.functionTypesByOutput) do self.functionTypesByOutput[k] = SCEN_EDIT.CreateNameMapping(v) end --[[ for i = 1, #coreTypes do local coreType = coreTypes[i] if self.functionTypesByInput[coreType.name] then self.functionTypesByInput[coreType.name] = SCEN_EDIT.CreateNameMapping(self.functionTypesByInput[coreType.name]) end if self.functionTypesByOutput[coreType.name] then self.functionTypesByOutput[coreType.name] = SCEN_EDIT.CreateNameMapping(self.functionTypesByOutput[coreType.name]) end end --]] end function MetaModel:SetActionTypes(actionTypes) for i = 1, #actionTypes do local actionType = actionTypes[i] actionType.input = SCEN_EDIT.parseData(actionType.input) end self.actionTypes = SCEN_EDIT.CreateNameMapping(actionTypes) end function MetaModel:SetVariableTypes() --add variables for core types self.variableTypes = {"unit", "unitType", "team", "area", "string", "number", "bool"} for i = 1, #self.variableTypes do local variableType = self.variableTypes[i] local arrayType = variableType .. "_array" table.insert(self.variableTypes, arrayType) end end --TODO: abstract order types out of the meta model function MetaModel:SetOrderTypes(orderTypes) for i = 1, #orderTypes do local orderType = orderTypes[i] orderType.input = SCEN_EDIT.parseData(orderType.input) end self.orderTypes = SCEN_EDIT.CreateNameMapping(orderTypes) end
MetaModel = LCS.class{} SCEN_EDIT_META_MODEL_DIR = SCEN_EDIT_DIR .. "meta/" function MetaModel:init() SCEN_EDIT.IncludeDir(SCEN_EDIT_META_MODEL_DIR) self.numericComparisonTypes = {"==", "~=", "<=", ">=", ">", "<"} -- maybe use more user friendly signs self.identityComparisonTypes = {"is", "is not"} -- maybe use more user friendly signs self:SetVariableTypes() --TODO: add array type --local arrayTypes = {} end function MetaModel:SetEventTypes(eventTypes) self.eventTypes = eventTypes self.eventTypes = SCEN_EDIT.CreateNameMapping(self.eventTypes) end function MetaModel:SetFunctionTypes(functionTypes) for i = 1, #functionTypes do local functionType = functionTypes[i] functionType.input = SCEN_EDIT.parseData(functionType.input) end self.functionTypes = SCEN_EDIT.CreateNameMapping(functionTypes) self.functionTypesByInput = {} for _, functionDef in pairs(self.functionTypes) do for _, input in pairs(functionDef.input) do if self.functionTypesByInput[input.name] then table.insert(self.functionTypesByInput[input.name], v) else self.functionTypesByInput[input.name] = {functionDef} end end end self.functionTypesByOutput = SCEN_EDIT.GroupByField(functionTypes, "output") -- fill missing for k, v in pairs(self.functionTypesByInput) do self.functionTypesByInput[k] = SCEN_EDIT.CreateNameMapping(v) end for k, v in pairs(self.functionTypesByOutput) do self.functionTypesByOutput[k] = SCEN_EDIT.CreateNameMapping(v) end --[[ local coreTypes = SCEN_EDIT.coreTypes() for i = 1, #coreTypes do local coreType = coreTypes[i] if self.functionTypesByInput[coreType.name] then self.functionTypesByInput[coreType.name] = SCEN_EDIT.CreateNameMapping(self.functionTypesByInput[coreType.name]) end if self.functionTypesByOutput[coreType.name] then self.functionTypesByOutput[coreType.name] = SCEN_EDIT.CreateNameMapping(self.functionTypesByOutput[coreType.name]) end end --]] end function MetaModel:SetActionTypes(actionTypes) for i = 1, #actionTypes do local actionType = actionTypes[i] actionType.input = SCEN_EDIT.parseData(actionType.input) end self.actionTypes = SCEN_EDIT.CreateNameMapping(actionTypes) end function MetaModel:SetVariableTypes() --add variables for core types self.variableTypes = {"unit", "unitType", "team", "area", "string", "number", "bool"} for i = 1, #self.variableTypes do local variableType = self.variableTypes[i] local arrayType = variableType .. "_array" table.insert(self.variableTypes, arrayType) end end --TODO: abstract order types out of the meta model function MetaModel:SetOrderTypes(orderTypes) for i = 1, #orderTypes do local orderType = orderTypes[i] orderType.input = SCEN_EDIT.parseData(orderType.input) end self.orderTypes = SCEN_EDIT.CreateNameMapping(orderTypes) end
fixed grouping functions by input (not that it's actually used anywhere atm?)
fixed grouping functions by input (not that it's actually used anywhere atm?)
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
7390a2a9b72316651e089cf97b936179029f9cf7
src/common/github.lua
src/common/github.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Github = newclass "Github" local function _getAssetsVersion(str) local verStr = string.match(str, ".*(%d+%.%d+%.%d+.*)") return zpm.semver(verStr) end function Github:init(loader) self.loader = loader end function Github:get(url) local token = self:_getToken() if token then token = { Authorization = "token " .. token } end return self.loader.http:get(url, token) end function Github:getUrl(prefix, organisation, repository, resource) local url = self.loader.config("github.apiHost") .. prefix .. "/" .. organisation .. "/" .. repository if resource then url = url .. "/" .. resource end return self:get(url) end function Github:getReleases(organisation, repository, pattern, options) pattern = iif(pattern ~= nil, pattern, ".*") local response = json.decode(self:getUrl("repos", organisation, repository, "releases")) local releases = { } table.foreachi(response, function(value) local ok, vers = pcall(_getAssetsVersion, value["tag_name"]) local matches = true table.foreachi(options["match"], function(match) matches = matches and value["tag_name"]:match(match) end) local except = true table.foreachi(options["except"], function(except) except = except and not value["tag_name"]:match(except) end) if ok and (options and matches and except) then local assetTab = { } table.foreachi(value["assets"], function(asset) if asset.name:match(pattern) then table.insert(assetTab, { name = asset["name"], url = asset["browser_download_url"] } ) end end ) table.insert(releases, { version = vers, assets = assetTab } ) end end ) table.sort(releases, function(t1, t2) return t1.version > t2.version end) return releases end function Github:_getToken() local gh = os.getenv("GH_TOKEN") if gh then return gh end gh = _OPTIONS["github-token"] if gh then return gh end local token = self.loader.config("github.token") return iif(token and token:len() > 0, token, nil) end
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Github = newclass "Github" local function _getAssetsVersion(str) local verStr = string.match(str, ".*(%d+%.%d+%.%d+.*)") return zpm.semver(verStr) end function Github:init(loader) self.loader = loader end function Github:get(url) local token = self:_getToken() if token then token = { Authorization = "token " .. token } end return self.loader.http:get(url, token) end function Github:getUrl(prefix, organisation, repository, resource) local url = self.loader.config("github.apiHost") .. prefix .. "/" .. organisation .. "/" .. repository if resource then url = url .. "/" .. resource end return self:get(url) end function Github:getReleases(organisation, repository, pattern, options) pattern = iif(pattern ~= nil, pattern, ".*") options = iif(options ~= nil, options, {}) local response = json.decode(self:getUrl("repos", organisation, repository, "releases")) local releases = { } table.foreachi(response, function(value) local ok, vers = pcall(_getAssetsVersion, value["tag_name"]) local matches = true table.foreachi(options["match"], function(match) matches = matches and value["tag_name"]:match(match) end) local except = true table.foreachi(options["except"], function(except) except = except and not value["tag_name"]:match(except) end) if ok and (options and matches and except) then local assetTab = { } table.foreachi(value["assets"], function(asset) if asset.name:match(pattern) then table.insert(assetTab, { name = asset["name"], url = asset["browser_download_url"] } ) end end ) table.insert(releases, { version = vers, assets = assetTab } ) end end ) table.sort(releases, function(t1, t2) return t1.version > t2.version end) return releases end function Github:_getToken() local gh = os.getenv("GH_TOKEN") if gh then return gh end gh = _OPTIONS["github-token"] if gh then return gh end local token = self.loader.config("github.token") return iif(token and token:len() > 0, token, nil) end
Fix options default argument
Fix options default argument
Lua
mit
Zefiros-Software/ZPM
929046cef4fba399f3bfdca62eba78444a6005ce
applications/luci-minidlna/luasrc/controller/minidlna.lua
applications/luci-minidlna/luasrc/controller/minidlna.lua
--[[ LuCI - Lua Configuration Interface - miniDLNA support Copyright 2012 Gabor Juhos <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.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 <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.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
Lua
apache-2.0
artynet/luci,cshore/luci,lbthomsen/openwrt-luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,daofeng2015/luci,keyidadi/luci,LuttyYang/luci,joaofvieira/luci,NeoRaider/luci,schidler/ionic-luci,urueedi/luci,urueedi/luci,Noltari/luci,tcatm/luci,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,Noltari/luci,cshore/luci,jchuang1977/luci-1,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,thesabbir/luci,fkooman/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,openwrt-es/openwrt-luci,obsy/luci,jlopenwrtluci/luci,nwf/openwrt-luci,lcf258/openwrtcn,NeoRaider/luci,Hostle/luci,marcel-sch/luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,remakeelectric/luci,openwrt/luci,ollie27/openwrt_luci,thess/OpenWrt-luci,Kyklas/luci-proto-hso,981213/luci-1,teslamint/luci,jchuang1977/luci-1,fkooman/luci,mumuqz/luci,joaofvieira/luci,schidler/ionic-luci,artynet/luci,opentechinstitute/luci,RuiChen1113/luci,kuoruan/lede-luci,cshore-firmware/openwrt-luci,oneru/luci,david-xiao/luci,MinFu/luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,Noltari/luci,LuttyYang/luci,openwrt/luci,981213/luci-1,cshore/luci,oyido/luci,lcf258/openwrtcn,mumuqz/luci,mumuqz/luci,urueedi/luci,thess/OpenWrt-luci,cshore/luci,taiha/luci,Sakura-Winkey/LuCI,taiha/luci,dwmw2/luci,oneru/luci,remakeelectric/luci,forward619/luci,lcf258/openwrtcn,Hostle/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,Sakura-Winkey/LuCI,forward619/luci,fkooman/luci,oyido/luci,dismantl/luci-0.12,oneru/luci,tobiaswaldvogel/luci,teslamint/luci,joaofvieira/luci,jchuang1977/luci-1,male-puppies/luci,harveyhu2012/luci,zhaoxx063/luci,cshore/luci,oyido/luci,rogerpueyo/luci,nmav/luci,artynet/luci,marcel-sch/luci,schidler/ionic-luci,RuiChen1113/luci,bright-things/ionic-luci,taiha/luci,teslamint/luci,Hostle/openwrt-luci-multi-user,981213/luci-1,urueedi/luci,shangjiyu/luci-with-extra,daofeng2015/luci,male-puppies/luci,taiha/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,zhaoxx063/luci,RedSnake64/openwrt-luci-packages,wongsyrone/luci-1,maxrio/luci981213,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,dwmw2/luci,marcel-sch/luci,male-puppies/luci,cshore-firmware/openwrt-luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,aircross/OpenWrt-Firefly-LuCI,male-puppies/luci,Hostle/luci,thess/OpenWrt-luci,tcatm/luci,kuoruan/luci,tcatm/luci,Wedmer/luci,LuttyYang/luci,kuoruan/lede-luci,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,jlopenwrtluci/luci,deepak78/new-luci,deepak78/new-luci,forward619/luci,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,sujeet14108/luci,RuiChen1113/luci,joaofvieira/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,fkooman/luci,opentechinstitute/luci,jlopenwrtluci/luci,rogerpueyo/luci,daofeng2015/luci,florian-shellfire/luci,wongsyrone/luci-1,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,nmav/luci,slayerrensky/luci,hnyman/luci,ff94315/luci-1,remakeelectric/luci,LuttyYang/luci,dwmw2/luci,openwrt-es/openwrt-luci,jorgifumi/luci,ollie27/openwrt_luci,daofeng2015/luci,jorgifumi/luci,palmettos/cnLuCI,keyidadi/luci,cappiewu/luci,keyidadi/luci,keyidadi/luci,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,remakeelectric/luci,jorgifumi/luci,openwrt/luci,teslamint/luci,kuoruan/luci,obsy/luci,maxrio/luci981213,thesabbir/luci,981213/luci-1,ff94315/luci-1,deepak78/new-luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,aa65535/luci,Noltari/luci,jchuang1977/luci-1,ff94315/luci-1,obsy/luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,MinFu/luci,jchuang1977/luci-1,remakeelectric/luci,openwrt-es/openwrt-luci,marcel-sch/luci,bright-things/ionic-luci,maxrio/luci981213,dismantl/luci-0.12,cshore-firmware/openwrt-luci,opentechinstitute/luci,kuoruan/luci,kuoruan/luci,artynet/luci,david-xiao/luci,sujeet14108/luci,david-xiao/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,dismantl/luci-0.12,bittorf/luci,openwrt/luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,palmettos/cnLuCI,bittorf/luci,aa65535/luci,kuoruan/lede-luci,david-xiao/luci,urueedi/luci,palmettos/cnLuCI,dwmw2/luci,wongsyrone/luci-1,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,deepak78/new-luci,florian-shellfire/luci,bittorf/luci,cappiewu/luci,nwf/openwrt-luci,ff94315/luci-1,cappiewu/luci,daofeng2015/luci,fkooman/luci,jlopenwrtluci/luci,cappiewu/luci,bittorf/luci,florian-shellfire/luci,tobiaswaldvogel/luci,981213/luci-1,Sakura-Winkey/LuCI,oneru/luci,MinFu/luci,bittorf/luci,maxrio/luci981213,mumuqz/luci,taiha/luci,tobiaswaldvogel/luci,harveyhu2012/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,palmettos/test,schidler/ionic-luci,nwf/openwrt-luci,ollie27/openwrt_luci,thess/OpenWrt-luci,marcel-sch/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,nmav/luci,openwrt/luci,oneru/luci,jorgifumi/luci,fkooman/luci,sujeet14108/luci,sujeet14108/luci,Wedmer/luci,rogerpueyo/luci,nmav/luci,nwf/openwrt-luci,florian-shellfire/luci,LuttyYang/luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,palmettos/cnLuCI,LuttyYang/luci,zhaoxx063/luci,maxrio/luci981213,florian-shellfire/luci,harveyhu2012/luci,harveyhu2012/luci,RedSnake64/openwrt-luci-packages,male-puppies/luci,keyidadi/luci,palmettos/cnLuCI,hnyman/luci,sujeet14108/luci,jorgifumi/luci,ReclaimYourPrivacy/cloak-luci,tobiaswaldvogel/luci,slayerrensky/luci,slayerrensky/luci,opentechinstitute/luci,remakeelectric/luci,Hostle/luci,lcf258/openwrtcn,thess/OpenWrt-luci,ollie27/openwrt_luci,oyido/luci,nmav/luci,dwmw2/luci,palmettos/test,shangjiyu/luci-with-extra,obsy/luci,cshore/luci,nmav/luci,urueedi/luci,obsy/luci,deepak78/new-luci,oyido/luci,maxrio/luci981213,jchuang1977/luci-1,male-puppies/luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,male-puppies/luci,taiha/luci,ollie27/openwrt_luci,dwmw2/luci,schidler/ionic-luci,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,forward619/luci,bright-things/ionic-luci,palmettos/test,Noltari/luci,openwrt/luci,Wedmer/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,palmettos/test,harveyhu2012/luci,mumuqz/luci,NeoRaider/luci,artynet/luci,florian-shellfire/luci,thesabbir/luci,nwf/openwrt-luci,Kyklas/luci-proto-hso,thesabbir/luci,zhaoxx063/luci,david-xiao/luci,lcf258/openwrtcn,lcf258/openwrtcn,aa65535/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,Hostle/luci,joaofvieira/luci,cshore/luci,lbthomsen/openwrt-luci,jorgifumi/luci,Wedmer/luci,zhaoxx063/luci,nmav/luci,mumuqz/luci,joaofvieira/luci,joaofvieira/luci,zhaoxx063/luci,lcf258/openwrtcn,kuoruan/luci,slayerrensky/luci,cshore-firmware/openwrt-luci,bittorf/luci,thesabbir/luci,cappiewu/luci,LuttyYang/luci,palmettos/test,oyido/luci,tobiaswaldvogel/luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,oneru/luci,LuttyYang/luci,Wedmer/luci,openwrt/luci,marcel-sch/luci,david-xiao/luci,aa65535/luci,marcel-sch/luci,cshore/luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,dwmw2/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,thess/OpenWrt-luci,aa65535/luci,dismantl/luci-0.12,zhaoxx063/luci,artynet/luci,MinFu/luci,thesabbir/luci,RuiChen1113/luci,ollie27/openwrt_luci,Kyklas/luci-proto-hso,oyido/luci,chris5560/openwrt-luci,nmav/luci,kuoruan/luci,taiha/luci,opentechinstitute/luci,kuoruan/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,kuoruan/lede-luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,cappiewu/luci,chris5560/openwrt-luci,bittorf/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,chris5560/openwrt-luci,dwmw2/luci,obsy/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,RuiChen1113/luci,palmettos/test,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,chris5560/openwrt-luci,obsy/luci,keyidadi/luci,981213/luci-1,lbthomsen/openwrt-luci,forward619/luci,tcatm/luci,lbthomsen/openwrt-luci,lcf258/openwrtcn,ff94315/luci-1,thess/OpenWrt-luci,mumuqz/luci,daofeng2015/luci,oneru/luci,artynet/luci,ollie27/openwrt_luci,Hostle/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,aa65535/luci,NeoRaider/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,Sakura-Winkey/LuCI,hnyman/luci,Sakura-Winkey/LuCI,daofeng2015/luci,oyido/luci,Noltari/luci,bittorf/luci,slayerrensky/luci,jlopenwrtluci/luci,kuoruan/lede-luci,jlopenwrtluci/luci,aa65535/luci,Noltari/luci,ff94315/luci-1,bright-things/ionic-luci,keyidadi/luci,Wedmer/luci,forward619/luci,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,kuoruan/lede-luci,nwf/openwrt-luci,rogerpueyo/luci,deepak78/new-luci,palmettos/cnLuCI,artynet/luci,chris5560/openwrt-luci,mumuqz/luci,forward619/luci,cappiewu/luci,kuoruan/luci,Kyklas/luci-proto-hso,RuiChen1113/luci,jorgifumi/luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,teslamint/luci,palmettos/cnLuCI,chris5560/openwrt-luci,joaofvieira/luci,hnyman/luci,rogerpueyo/luci,forward619/luci,keyidadi/luci,urueedi/luci,rogerpueyo/luci,florian-shellfire/luci,rogerpueyo/luci,jlopenwrtluci/luci,harveyhu2012/luci,NeoRaider/luci,thesabbir/luci,tcatm/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,slayerrensky/luci,RuiChen1113/luci,981213/luci-1,Wedmer/luci,hnyman/luci,thesabbir/luci,david-xiao/luci,taiha/luci,hnyman/luci,ff94315/luci-1,kuoruan/lede-luci,palmettos/cnLuCI,nwf/openwrt-luci,dismantl/luci-0.12,Noltari/luci,cappiewu/luci,tcatm/luci,remakeelectric/luci,shangjiyu/luci-with-extra,Wedmer/luci,artynet/luci,Noltari/luci,marcel-sch/luci,opentechinstitute/luci,zhaoxx063/luci,palmettos/test,wongsyrone/luci-1,daofeng2015/luci,Sakura-Winkey/LuCI,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,bright-things/ionic-luci,nwf/openwrt-luci,opentechinstitute/luci,obsy/luci,openwrt-es/openwrt-luci,jchuang1977/luci-1,NeoRaider/luci,florian-shellfire/luci,male-puppies/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,aa65535/luci,Hostle/luci,MinFu/luci,palmettos/test,hnyman/luci,MinFu/luci,tobiaswaldvogel/luci,remakeelectric/luci,lbthomsen/openwrt-luci,sujeet14108/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,nmav/luci,fkooman/luci,maxrio/luci981213
2179943363b2b770669147d7c2afe72c8882ad55
src/romdisk/boot.lua
src/romdisk/boot.lua
--[[ --]] -- Make sure xboot table exists. if not xboot then xboot = {} end -- Used for setup: xboot.path = {} --xboot.arg = {} -- Unparsed arguments: --argv = {} -- Replace any \ with /. function xboot.path.normalslashes(p) return string.gsub(p, "\\", "/") end -- Makes sure there is a slash at the end -- of a path. function xboot.path.endslash(p) if string.sub(p, string.len(p)-1) ~= "/" then return p .. "/" else return p end end -- Checks whether a path is absolute or not. function xboot.path.abs(p) local tmp = xboot.path.normalslashes(p) -- Path is absolute if it starts with a "/". if string.find(tmp, "/") == 1 then return true end -- Path is absolute if it starts with a -- letter followed by a colon. if string.find(tmp, "%a:") == 1 then return true end -- Relative. return false end -- Converts any path into a full path. function xboot.path.getfull(p) if xboot.path.abs(p) then return xboot.path.normalslashes(p) end local cwd = "/" --xboot.filesystem.getWorkingDirectory() cwd = xboot.path.normalslashes(cwd) cwd = xboot.path.endslash(cwd) -- Construct a full path. local full = cwd .. xboot.path.normalslashes(p) -- Remove trailing /., if applicable return full:match("(.-)/%.$") or full end -- Returns the leaf of a full path. function xboot.path.leaf(p) local a = 1 local last = p while a do a = string.find(p, "/", a+1) if a then last = string.sub(p, a+1) end end return last end package.path = "/romdisk/system/lib/?.lua;/romdisk/system/lib/?/init.lua;" .. package.path package.cpath = "/romdisk/system/lib/?.so;/romdisk/system/lib/loadall.so;" .. package.path local sample = require "xboot.sample" local framerate = require "xboot.framerate" local logger = require "logger" local dump = require "dump" local test = nil function xboot.boot() -- dump(package.searchers, 3) test = require "test" test.error("ttt") local printr = require "printr" printr(arg) end function xboot.init() end function xboot.run() if xboot.load then xboot.load(arg) end local fr = framerate.new() while true do fr:step() if xboot.update then xboot.update(fr:getdelta()) end if xboot.draw then xboot.draw() end fr:sleep(0.1) --fr.sleep(fr, 0.1) --test.error(fr:getfps()) --logger.error(fr:getfps()) --print(fr:getfps()) break end end local debug = debug local function error_printer(msg, layer) print((debug.traceback("Error: " .. tostring(msg), 1+(layer or 1)):gsub("\n[^\n]+$", ""))) end return function() local result = xpcall(xboot.boot, error_printer) if not result then return 1 end local result = xpcall(xboot.init, error_printer) if not result then return 1 end local result, retval = xpcall(xboot.run, error_printer) if not result then return 1 end return tonumber(retval) or 0 end
-- Make sure xboot table exists if not xboot then xboot = {} end -- Setting package path package.path = "/romdisk/system/lib/?.lua;/romdisk/system/lib/?/init.lua;" .. package.path package.cpath = "/romdisk/system/lib/?.so;/romdisk/system/lib/loadall.so;" .. package.path -- Main function function xboot.main() require("main") end -- Message handler local function handler(msg, layer) print((debug.traceback("ERROR: " .. tostring(msg), 1 + (layer or 1)):gsub("\n[^\n]+$", ""))) end return function() local res, ret = xpcall(xboot.main, handler) if not res then return -1 end return tonumber(ret) or -1 end
fix boot.lua
fix boot.lua
Lua
mit
xboot/xboot,xboot/xboot