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
d7dfb1993eee87f3841a4fb1446d71ba32c62d5a
src_trunk/resources/gate-system/Chinatown_Gate.lua
src_trunk/resources/gate-system/Chinatown_Gate.lua
local objChinaGate = createObject(969, 2562.5, 1822, 10, 0, 0, 0) exports.pool:allocateElement(objChinaGate) local objChinaFence = createObject( 983, 2543.97, 1839.34, 10.5, 0, 0, 0) exports.pool:allocateElement(objChinaFence) open = false -- Gate code function useChinaGate(thePlayer) local team = getPlayerTeam(thePlayer) if (team==getTeamFromName("Yamaguchi-Gumi")) then local x, y, z = getElementPosition(thePlayer) local distance = getDistanceBetweenPoints3D( 2565.1757, 1820.6582, 10.8203, x, y, z ) outputDebugString(tonumber(distance)) if (distance<=10) and (open==false) then open = true outputChatBox("Yakuza gate is now Open!", thePlayer, 0, 255, 0) moveObject(objChinaGate, 3000, 2568, 1822, 10, 0, 0, 0) setTimer(closeChinaGate, 5000, 1, thePlayer) end end end addCommandHandler("gate", useChinaGate) function closeChinaGate(thePlayer) if (getElementType(thePlayer)) then outputChatBox("Yakuza gate is now Closed!", thePlayer, 255, 0, 0) end moveObject(objChinaGate, 3000, 2562.5, 1822, 10, 0, 0, 0) setTimer(resetChinaGateState, 1000, 1) end function resetChinaGateState() open = false end
local objChinaGate = createObject(969, 2562.5, 1822, 10, 0, 0, 0) exports.pool:allocateElement(objChinaGate) local objChinaFence = createObject( 983, 2543.97, 1839.34, 10.5, 0, 0, 0) exports.pool:allocateElement(objChinaFence) open = false -- Gate code function useChinaGate(thePlayer) local team = getPlayerTeam(thePlayer) if (team==getTeamFromName("Yamaguchi-Gumi")) then local x, y, z = getElementPosition(thePlayer) local distance = getDistanceBetweenPoints3D( 2565.1757, 1820.6582, 10.8203, x, y, z ) if (distance<=10) and (open==false) then open = true outputChatBox("Yakuza gate is now Open!", thePlayer, 0, 255, 0) moveObject(objChinaGate, 3000, 2568, 1822, 10, 0, 0, 0) setTimer(closeChinaGate, 5000, 1, thePlayer) end end end addCommandHandler("gate", useChinaGate) function closeChinaGate(thePlayer) if (getElementType(thePlayer)) then outputChatBox("Yakuza gate is now Closed!", thePlayer, 255, 0, 0) end moveObject(objChinaGate, 3000, 2562.5, 1822, 10, 0, 0, 0) setTimer(resetChinaGateState, 1000, 1) end function resetChinaGateState() open = false end
Fixed yakuza gate
Fixed yakuza gate git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@652 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
68a7d0f1875ca680f53ed85db13206be1ecb731f
init.lua
init.lua
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local uv = require('uv') return function (main, ...) -- Inject the global process table _G.process = require('process').globalProcess() -- Seed Lua's RNG do local math = require('math') local os = require('os') math.randomseed(os.clock()) end local args = {...} local success, err = xpcall(function () -- Call the main app main(unpack(args)) -- Start the event loop uv.run() end, debug.traceback) if success then -- Allow actions to run at process exit. require('hooks'):emit('process.exit') uv.run() else _G.process.exitCode = -1 require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n") end -- When the loop exits, close all unclosed uv handles. uv.walk(function (handle) if handle and not handle:is_closing() then handle:close() end end) uv.run() -- Send the exitCode to luvi to return from C's main. return _G.process.exitCode end
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local uv = require('uv') return function (main, ...) -- Inject the global process table _G.process = require('process').globalProcess() -- Seed Lua's RNG do local math = require('math') local os = require('os') math.randomseed(os.clock()) end -- Load Resolver do local jit = require('jit') local dns = require('dns') if jit.os ~= 'Windows' then dns.loadResolver() end end local args = {...} local success, err = xpcall(function () -- Call the main app main(unpack(args)) -- Start the event loop uv.run() end, debug.traceback) if success then -- Allow actions to run at process exit. require('hooks'):emit('process.exit') uv.run() else _G.process.exitCode = -1 require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n") end -- When the loop exits, close all unclosed uv handles. uv.walk(function (handle) if handle and not handle:is_closing() then handle:close() end end) uv.run() -- Send the exitCode to luvi to return from C's main. return _G.process.exitCode end
fix(init): DNS load resolver on non-windows platforms
fix(init): DNS load resolver on non-windows platforms
Lua
apache-2.0
bsn069/luvit,bsn069/luvit,luvit/luvit,kaustavha/luvit,bsn069/luvit,kaustavha/luvit,zhaozg/luvit,luvit/luvit,zhaozg/luvit,kaustavha/luvit
b2b9b4985990bada4ba7c698a30b9082c92826c2
frontend/apps/reader/modules/readeractivityindicator.lua
frontend/apps/reader/modules/readeractivityindicator.lua
-- Start with a empty stub, because 99.9% of users won't actually need this. local ReaderActivityIndicator = {} function ReaderActivityIndicator:isStub() return true end function ReaderActivityIndicator:init() end function ReaderActivityIndicator:onStartActivityIndicator() end function ReaderActivityIndicator:onStopActivityIndicator() end function ReaderActivityIndicator:coda() end -- Now, if we're on Kindle, and we haven't actually murdered Pillow, see what we can do... local Device = require("device") if Device:isKindle() then if os.getenv("PILLOW_HARD_DISABLED") or os.getenv("PILLOW_SOFT_DISABLED") then -- Pillow is dead, bye! return ReaderActivityIndicator end if not Device:isTouchDevice() then -- No lipc, bye! return ReaderActivityIndicator end else -- Not on Kindle, bye! return ReaderActivityIndicator end -- Okay, if we're here, it's basically because we're running on a Kindle on FW 5.x under KPV local EventListener = require("ui/widget/eventlistener") local util = require("ffi/util") -- lipc function ReaderActivityIndicator:isStub() return false end ReaderActivityIndicator = EventListener:new{} function ReaderActivityIndicator:init() if (pcall(require, "liblipclua")) then self.lipc_handle = lipc.init("com.github.koreader.activityindicator") end end function ReaderActivityIndicator:onStartActivityIndicator() if self.lipc_handle then -- check if activity indicator is needed if self.document.configurable.text_wrap == 1 then -- start indicator depends on pillow being enabled self.lipc_handle:set_string_property( "com.lab126.pillow", "activityIndicator", '{"activityIndicator":{ \ "action":"start","timeout":10000, \ "clientId":"com.github.koreader.activityindicator", \ "priority":true}}') self.indicator_started = true end end return true end function ReaderActivityIndicator:onStopActivityIndicator() if self.lipc_handle and self.indicator_started then -- stop indicator depends on pillow being enabled self.lipc_handle:set_string_property( "com.lab126.pillow", "activityIndicator", '{"activityIndicator":{ \ "action":"stop","timeout":10000, \ "clientId":"com.github.koreader.activityindicator", \ "priority":true}}') self.indicator_started = false util.usleep(1000000) end return true end function ReaderActivityIndicator:coda() if self.lipc_handle then self.lipc_handle:close() end end return ReaderActivityIndicator
-- Start with a empty stub, because 99.9% of users won't actually need this. local ReaderActivityIndicator = {} function ReaderActivityIndicator:isStub() return true end function ReaderActivityIndicator:init() end function ReaderActivityIndicator:onStartActivityIndicator() end function ReaderActivityIndicator:onStopActivityIndicator() end function ReaderActivityIndicator:coda() end -- Now, if we're on Kindle, and we haven't actually murdered Pillow, see what we can do... local Device = require("device") if Device:isKindle() then if os.getenv("PILLOW_HARD_DISABLED") or os.getenv("PILLOW_SOFT_DISABLED") then -- Pillow is dead, bye! return ReaderActivityIndicator end if not Device:isTouchDevice() then -- No lipc, bye! return ReaderActivityIndicator end else -- Not on Kindle, bye! return ReaderActivityIndicator end -- Okay, if we're here, it's basically because we're running on a Kindle on FW 5.x under KPV local EventListener = require("ui/widget/eventlistener") local util = require("ffi/util") -- lipc ReaderActivityIndicator = EventListener:new{} function ReaderActivityIndicator:isStub() return false end function ReaderActivityIndicator:init() if (pcall(require, "liblipclua")) then self.lipc_handle = lipc.init("com.github.koreader.activityindicator") end end function ReaderActivityIndicator:onStartActivityIndicator() if self.lipc_handle then -- check if activity indicator is needed if self.document.configurable.text_wrap == 1 then -- start indicator depends on pillow being enabled self.lipc_handle:set_string_property( "com.lab126.pillow", "activityIndicator", '{"activityIndicator":{ \ "action":"start","timeout":10000, \ "clientId":"com.github.koreader.activityindicator", \ "priority":true}}') self.indicator_started = true end end return true end function ReaderActivityIndicator:onStopActivityIndicator() if self.lipc_handle and self.indicator_started then -- stop indicator depends on pillow being enabled self.lipc_handle:set_string_property( "com.lab126.pillow", "activityIndicator", '{"activityIndicator":{ \ "action":"stop","timeout":10000, \ "clientId":"com.github.koreader.activityindicator", \ "priority":true}}') self.indicator_started = false util.usleep(1000000) end return true end function ReaderActivityIndicator:coda() if self.lipc_handle then self.lipc_handle:close() end end return ReaderActivityIndicator
ReaderActivityIndicator: fix isStub()
ReaderActivityIndicator: fix isStub() it was being overridden by the EventListener:new caused by #7002 c.f. https://www.mobileread.com/forums/showthread.php?t=335886
Lua
agpl-3.0
NiLuJe/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,Frenzie/koreader,mwoz123/koreader,poire-z/koreader,pazos/koreader,poire-z/koreader,koreader/koreader,Hzj-jie/koreader,Markismus/koreader
72121a756f5f642933355f4c710163f08f3f346a
tools/rest_translation_server.lua
tools/rest_translation_server.lua
#!/usr/bin/env lua --[[ This requires the restserver-xavante rock to run. run server (this file) th tools/rest_translation_server.lua -model ../Recipes/baseline-1M-enfr/exp/model-baseline-1M-enfr_epoch13_3.44.t7 -gpuid 1 query the server: curl -v -H "Content-Type: application/json" -X POST -d '{ "src" : "international migration" }' http://127.0.0.1:7784/translator/translate ]] require('onmt.init') local separators = require('tools.utils.separators') local tokenizer = require('tools.utils.tokenizer') local BPE = require ('tools.utils.BPE') local restserver = require("restserver") local cmd = onmt.utils.ExtendedCmdLine.new('rest_translation_server.lua') local options = { {'-port', '7784', [[Port to run the server on.]]}, {'-withAttn', false, [[If set returns by default attn vector.]]} } cmd:setCmdLineOptions(options, 'Server') onmt.translate.Translator.declareOpts(cmd) cmd:text("") cmd:text("**Other options**") cmd:text("") onmt.utils.Cuda.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) cmd:option('-mode', 'conservative', [[Define how aggressive should the tokenization be - 'aggressive' only keeps sequences of letters/numbers, 'conservative' allows mix of alphanumeric as in: '2,000', 'E65', 'soft-landing'.]]) cmd:option('-joiner_annotate', false, [[Include joiner annotation using 'joiner' character.]]) cmd:option('-joiner', separators.joiner_marker, [[Character used to annotate joiners.]]) cmd:option('-joiner_new', false, [[in joiner_annotate mode, 'joiner' is an independent token.]]) cmd:option('-case_feature', false, [[Generate case feature.]]) cmd:option('-bpe_model', '', [[Apply Byte Pair Encoding if the BPE model path is given.]]) cmd:option('-batchsize', 1000, [[Size of each parallel batch - you should not change except if low memory.]]) local opt = cmd:parse(arg) local function translateMessage(translator, lines) local batch = {} -- We need to tokenize the input line before translation local bpe local res local err _G.logger:info("Start Tokenization") if opt.bpe_model ~= '' then bpe = BPE.new(opt.bpe_model, opt.joiner_annotate, opt.joiner_new) end for i = 1, #lines do local srcTokenized = {} local tokens local srcTokens = {} res, err = pcall(function() tokens = tokenizer.tokenize(opt, lines[i].src, bpe) end) -- it can generate an exception if there are utf-8 issues in the text if not res then if string.find(err, "interrupted") then error("interrupted") else error("unicode error in line " .. err) end end table.insert(srcTokenized, table.concat(tokens, ' ')) -- Extract from the line. for word in srcTokenized[1]:gmatch'([^%s]+)' do table.insert(srcTokens, word) end -- Currently just a single batch. table.insert(batch, translator:buildInput(srcTokens)) end -- Translate _G.logger:info("Start Translation") local results = translator:translate(batch) _G.logger:info("End Translation") -- Return the nbest translations for each in the batch. local translations = {} for b = 1, #lines do local ret = {} for i = 1, translator.opt.n_best do local srcSent = translator:buildOutput(batch[b]) local predSent = translator:buildOutput(results[b].preds[i]) local oline res, err = pcall(function() oline = tokenizer.detokenize(predSent, opt) end) if not res then if string.find(err,"interrupted") then error("interrupted") else error("unicode error in line ".. err) end end local lineres = { tgt = oline, src = srcSent, n_best = i, pred_score = results[b].preds[i].score } if opt.withAttn or lines[b].withAttn then local attnTable = {} for j = 1, #results[b].preds[i].attention do table.insert(attnTable, results[b].preds[i].attention[j]:totable()) end lineres.attn = attnTable end table.insert(ret, lineres) end table.insert(translations, ret) end return translations end local function init_server(port, translator) local server = restserver:new():port(port) server:add_resource("translator", { { method = "POST", path = "/translate", consumes = "application/json", produces = "application/json", handler = function(req) _G.logger:info("receiving request") local translate = translateMessage(translator, req) _G.logger:info("sending response") return restserver.response():status(200):entity(translate) end, } }) return server end local function main() -- load logger _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) onmt.utils.Cuda.init(opt) -- disable profiling _G.profiler = onmt.utils.Profiler.new(false) _G.logger:info("Loading model") local translator = onmt.translate.Translator.new(opt) _G.logger:info("Launch server") local server = init_server(opt.port, translator) -- This loads the restserver.xavante plugin server:enable("restserver.xavante"):start() end main()
#!/usr/bin/env lua --[[ This requires the restserver-xavante rock to run. run server (this file) th tools/rest_translation_server.lua -model ../Recipes/baseline-1M-enfr/exp/model-baseline-1M-enfr_epoch13_3.44.t7 -gpuid 1 query the server: curl -v -H "Content-Type: application/json" -X POST -d '{ "src" : "international migration" }' http://127.0.0.1:7784/translator/translate ]] require('onmt.init') local separators = require('tools.utils.separators') local tokenizer = require('tools.utils.tokenizer') local BPE = require ('tools.utils.BPE') local restserver = require("restserver") local cmd = onmt.utils.ExtendedCmdLine.new('rest_translation_server.lua') local options = { {'-port', '7784', [[Port to run the server on.]]}, {'-withAttn', false, [[If set returns by default attn vector.]]} } cmd:setCmdLineOptions(options, 'Server') onmt.translate.Translator.declareOpts(cmd) cmd:text("") cmd:text("**Other options**") cmd:text("") onmt.utils.Cuda.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) cmd:option('-mode', 'conservative', [[Define how aggressive should the tokenization be - 'aggressive' only keeps sequences of letters/numbers, 'conservative' allows mix of alphanumeric as in: '2,000', 'E65', 'soft-landing'.]]) cmd:option('-joiner_annotate', false, [[Include joiner annotation using 'joiner' character.]]) cmd:option('-joiner', separators.joiner_marker, [[Character used to annotate joiners.]]) cmd:option('-joiner_new', false, [[in joiner_annotate mode, 'joiner' is an independent token.]]) cmd:option('-case_feature', false, [[Generate case feature.]]) cmd:option('-bpe_model', '', [[Apply Byte Pair Encoding if the BPE model path is given.]]) cmd:option('-batchsize', 1000, [[Size of each parallel batch - you should not change except if low memory.]]) local opt = cmd:parse(arg) local function translateMessage(translator, lines) local batch = {} -- We need to tokenize the input line before translation local bpe local res local err _G.logger:info("Start Tokenization") if opt.bpe_model ~= '' then bpe = BPE.new(opt) end for i = 1, #lines do local srcTokenized = {} local tokens local srcTokens = {} res, err = pcall(function() tokens = tokenizer.tokenize(opt, lines[i].src, bpe) end) -- it can generate an exception if there are utf-8 issues in the text if not res then if string.find(err, "interrupted") then error("interrupted") else error("unicode error in line " .. err) end end table.insert(srcTokenized, table.concat(tokens, ' ')) -- Extract from the line. for word in srcTokenized[1]:gmatch'([^%s]+)' do table.insert(srcTokens, word) end -- Currently just a single batch. table.insert(batch, translator:buildInput(srcTokens)) end -- Translate _G.logger:info("Start Translation") local results = translator:translate(batch) _G.logger:info("End Translation") -- Return the nbest translations for each in the batch. local translations = {} for b = 1, #lines do local ret = {} for i = 1, translator.opt.n_best do local srcSent = translator:buildOutput(batch[b]) local predSent = translator:buildOutput(results[b].preds[i]) local oline res, err = pcall(function() oline = tokenizer.detokenize(predSent, opt) end) if not res then if string.find(err,"interrupted") then error("interrupted") else error("unicode error in line ".. err) end end local lineres = { tgt = oline, src = srcSent, n_best = i, pred_score = results[b].preds[i].score } if opt.withAttn or lines[b].withAttn then local attnTable = {} for j = 1, #results[b].preds[i].attention do table.insert(attnTable, results[b].preds[i].attention[j]:totable()) end lineres.attn = attnTable end table.insert(ret, lineres) end table.insert(translations, ret) end return translations end local function init_server(port, translator) local server = restserver:new():port(port) server:add_resource("translator", { { method = "POST", path = "/translate", consumes = "application/json", produces = "application/json", handler = function(req) _G.logger:info("receiving request") local translate = translateMessage(translator, req) _G.logger:info("sending response") return restserver.response():status(200):entity(translate) end, } }) return server end local function main() -- load logger _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) onmt.utils.Cuda.init(opt) -- disable profiling _G.profiler = onmt.utils.Profiler.new(false) _G.logger:info("Loading model") local translator = onmt.translate.Translator.new(opt) _G.logger:info("Launch server") local server = init_server(opt.port, translator) -- This loads the restserver.xavante plugin server:enable("restserver.xavante"):start() end main()
fix BPE usage from REST server
fix BPE usage from REST server
Lua
mit
da03/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT
73b0c701ce75319d6a7f1b235884d5d7882579ea
frontend/device/android/powerd.lua
frontend/device/android/powerd.lua
local BasePowerD = require("device/generic/powerd") local _, android = pcall(require, "android") local AndroidPowerD = BasePowerD:new{ fl_min = 0, fl_max = 100, } -- Let the footer know of the change local function broadcastLightChanges() if package.loaded["ui/uimanager"] ~= nil then local Event = require("ui/event") local UIManager = require("ui/uimanager") UIManager:broadcastEvent(Event:new("FrontlightStateChanged")) end end function AndroidPowerD:frontlightIntensityHW() return math.floor(android.getScreenBrightness() / self.bright_diff * self.fl_max) end function AndroidPowerD:setIntensityHW(intensity) -- if frontlight switch was toggled of, turn it on android.enableFrontlightSwitch() self.fl_intensity = intensity android.setScreenBrightness(math.floor(intensity * self.bright_diff / self.fl_max)) end function AndroidPowerD:init() local min_bright = android.getScreenMinBrightness() self.bright_diff = android.getScreenMaxBrightness() - min_bright -- if necessary scale fl_min: -- do not use fl_min==0 if getScreenMinBrightness!=0, -- because intenstiy==0 would mean to use system intensity if min_bright ~= self.fl_min then self.fl_min = math.ceil(min_bright * self.bright_diff / self.fl_max) end if self.device:hasNaturalLight() then self.fl_warmth = self:getWarmth() self.fl_warmth_min = android.getScreenMinWarmth() self.fl_warmth_max = android.getScreenMaxWarmth() self.warm_diff = self.fl_warmth_max - self.fl_warmth_min end end function AndroidPowerD:setWarmth(warmth) self.fl_warmth = warmth android.setScreenWarmth(warmth / self.warm_diff) end function AndroidPowerD:getWarmth() return android.getScreenWarmth() * self.warm_diff end function AndroidPowerD:getCapacityHW() return android.getBatteryLevel() end function AndroidPowerD:isChargingHW() return android.isCharging() end function AndroidPowerD:turnOffFrontlightHW() if not self:isFrontlightOnHW() then return end android.setScreenBrightness(self.fl_min) self.is_fl_on = false broadcastLightChanges() end function AndroidPowerD:turnOnFrontlightHW() if self:isFrontlightOn() and self:isFrontlightOnHW() then return end -- on devices with a software frontlight switch (e.g Tolinos), enable it android.enableFrontlightSwitch() android.setScreenBrightness(math.floor(self.fl_intensity * self.bright_diff / self.fl_max)) self.is_fl_on = true broadcastLightChanges() end return AndroidPowerD
local BasePowerD = require("device/generic/powerd") local _, android = pcall(require, "android") local AndroidPowerD = BasePowerD:new{ fl_min = 0, fl_max = 100, } -- Let the footer know of the change local function broadcastLightChanges() if package.loaded["ui/uimanager"] ~= nil then local Event = require("ui/event") local UIManager = require("ui/uimanager") UIManager:broadcastEvent(Event:new("FrontlightStateChanged")) end end function AndroidPowerD:frontlightIntensityHW() return math.floor(android.getScreenBrightness() / self.bright_diff * self.fl_max) end function AndroidPowerD:setIntensityHW(intensity) -- if frontlight switch was toggled of, turn it on android.enableFrontlightSwitch() self.fl_intensity = intensity android.setScreenBrightness(math.floor(intensity * self.bright_diff / self.fl_max)) end function AndroidPowerD:init() local min_bright = android.getScreenMinBrightness() self.bright_diff = android.getScreenMaxBrightness() - min_bright -- if necessary scale fl_min: -- do not use fl_min==0 if getScreenMinBrightness!=0, -- because intenstiy==0 would mean to use system intensity if min_bright ~= self.fl_min then self.fl_min = math.ceil(min_bright * self.bright_diff / self.fl_max) end if self.device:hasNaturalLight() then self.fl_warmth_min = android.getScreenMinWarmth() self.fl_warmth_max = android.getScreenMaxWarmth() self.warm_diff = self.fl_warmth_max - self.fl_warmth_min self.fl_warmth = self:getWarmth() end end function AndroidPowerD:setWarmth(warmth) self.fl_warmth = warmth android.setScreenWarmth(warmth / self.warm_diff) end function AndroidPowerD:getWarmth() return android.getScreenWarmth() * self.warm_diff end function AndroidPowerD:getCapacityHW() return android.getBatteryLevel() end function AndroidPowerD:isChargingHW() return android.isCharging() end function AndroidPowerD:turnOffFrontlightHW() if not self:isFrontlightOnHW() then return end android.setScreenBrightness(self.fl_min) self.is_fl_on = false broadcastLightChanges() end function AndroidPowerD:turnOnFrontlightHW() if self:isFrontlightOn() and self:isFrontlightOnHW() then return end -- on devices with a software frontlight switch (e.g Tolinos), enable it android.enableFrontlightSwitch() android.setScreenBrightness(math.floor(self.fl_intensity * self.bright_diff / self.fl_max)) self.is_fl_on = true broadcastLightChanges() end return AndroidPowerD
correct bug introduced with #6641 (#6665)
correct bug introduced with #6641 (#6665)
Lua
agpl-3.0
poire-z/koreader,Frenzie/koreader,Frenzie/koreader,pazos/koreader,koreader/koreader,Hzj-jie/koreader,koreader/koreader,poire-z/koreader,mwoz123/koreader,NiLuJe/koreader,NiLuJe/koreader,Markismus/koreader
31e95c3ac3f4bad78835282f9c1ea8c5fde0c74b
state/loadgame.lua
state/loadgame.lua
--[[-- LOADGAME STATE ---- Load and construct everything needed to continue a game. --]]-- local st = RunState.new() require 'lib.serialize' local warning, tostring = warning, tostring function st:init() end function st:enter(prevState, world) print('newgame') self._world = world self._loadStep = 0 if self:_chooseFile() then self._doLoadStep = true if Console then Console:print('Loading savegame: %q', self._filename) end else RunState.switch(State.menu) end end function st:leave() if self._file then self._file:close() end self._state = nil self._world = nil self._file = nil self._filename = nil self._loadStep = nil self._doLoadStep = nil end function st:destroy() end function st:_chooseFile() self._filename = 'save/testy.sav' return love.filesystem.exists(self._filename) end function st:_loadFile() local contents = love.filesystem.read(self._filename) local ok, state = pcall(contents) if ok then self._state = state if state.GAMESEED then GAMESEED = state.GAMESEED Random = random.new(GAMESEED) end else warning(state..' (Game not loaded)') end end function st:_setWorldState() if self._state then self._world:setState(self._state) end end function st:_nextLoadStep() if nil ~= self._doLoadStep then self._doLoadStep = true end if nil ~= self._loadStep then self._loadStep = self._loadStep + 1 end end function st:_load() self._doLoadStep = false -- load entities switch(self._loadStep) { [1] = function() self:_loadFile() end, [2] = function() self:_setWorldState() end, [3] = function() RunState.switch(State.construct, self._world) end, default = function() end, } cron.after(LOAD_DELAY, self._nextLoadStep, self) end function st:update(dt) if self._doLoadStep then self:_load() end end function st:draw() if Console then Console:draw() end end function st:keypressed(key, unicode) end return st
--[[-- LOADGAME STATE ---- Load and construct everything needed to continue a game. --]]-- local st = RunState.new() require 'lib.serialize' local warning, tostring = warning, tostring function st:init() end function st:enter(prevState, world) print('newgame') self._world = world self._loadStep = 0 if self:_chooseFile() then self._doLoadStep = true if Console then Console:print('Loading savegame: %q', self._filename) end else RunState.switch(State.menu) end end function st:leave() if self._file then self._file:close() end self._state = nil self._world = nil self._file = nil self._filename = nil self._loadStep = nil self._doLoadStep = nil end function st:destroy() end function st:_chooseFile() self._filename = 'save/testy.sav' return love.filesystem.exists(self._filename) end function st:_loadFile() local contents = love.filesystem.read(self._filename) local ok, err = pcall(loadstring,contents) if ok then ok, err = pcall(err) if ok then self._state = err if self._state.GAMESEED then GAMESEED = self._state.GAMESEED Random = random.new(GAMESEED) end end end if not ok then err = err or '' warning(err..' (Game not loaded)') end end function st:_setWorldState() if self._state then self._world:setState(self._state) end end function st:_nextLoadStep() if nil ~= self._doLoadStep then self._doLoadStep = true end if nil ~= self._loadStep then self._loadStep = self._loadStep + 1 end end function st:_load() self._doLoadStep = false -- load entities switch(self._loadStep) { [1] = function() self:_loadFile() end, [2] = function() self:_setWorldState() end, [3] = function() RunState.switch(State.construct, self._world) end, default = function() end, } cron.after(LOAD_DELAY, self._nextLoadStep, self) end function st:update(dt) if self._doLoadStep then self:_load() end end function st:draw() if Console then Console:draw() end end function st:keypressed(key, unicode) end return st
fix game load from file
fix game load from file
Lua
mit
scottcs/wyx
552090caad52c0c00013d9286a58f1311e7b29f3
src/luarocks/build/cmake.lua
src/luarocks/build/cmake.lua
--- Build back-end for CMake-based modules. --module("luarocks.build.cmake", package.seeall) local cmake = {} local fs = require("luarocks.fs") local util = require("luarocks.util") local cfg = require("luarocks.cfg") --- Driver function for the "cmake" build back-end. -- @param rockspec table: the loaded rockspec. -- @return boolean or (nil, string): true if no errors ocurred, -- nil and an error message otherwise. function cmake.run(rockspec) assert(type(rockspec) == "table") local build = rockspec.build local variables = build.variables or {} -- Pass Env variables variables.CMAKE_MODULE_PATH=os.getenv("CMAKE_MODULE_PATH") variables.CMAKE_LIBRARY_PATH=os.getenv("CMAKE_LIBRARY_PATH") variables.CMAKE_INCLUDE_PATH=os.getenv("CMAKE_INCLUDE_PATH") util.variable_substitutions(variables, rockspec.variables) local ok, err_msg = fs.is_tool_available(rockspec.variables.CMAKE, "CMake") if not ok then return nil, err_msg end -- If inline cmake is present create CMakeLists.txt from it. if type(build.cmake) == "string" then local cmake_handler = assert(io.open(fs.current_dir().."/CMakeLists.txt", "w")) cmake_handler:write(build.cmake) cmake_handler:close() end -- Execute cmake with variables. local args = "" -- Try to pick the best generator. With msvc and x64, CMake does not select it by default so we need to be explicit. if cfg.cmake_generator then args = args .. ' -G"'..cfg.cmake_generator.. '"' elseif cfg.is_platform("windows") and cfg.target_cpu:match("x86_64$") then args = args .. " -DCMAKE_GENERATOR_PLATFORM=x64" end for k,v in pairs(variables) do args = args .. ' -D' ..k.. '="' ..tostring(v).. '"' end if not fs.execute_string(rockspec.variables.CMAKE.." -H. -Bbuild.luarocks "..args) then return nil, "Failed cmake." end if not fs.execute_string(rockspec.variables.CMAKE.." --build build.luarocks --config Release") then return nil, "Failed building." end if not fs.execute_string(rockspec.variables.CMAKE.." --build build.luarocks --target install --config Release") then return nil, "Failed installing." end return true end return cmake
--- Build back-end for CMake-based modules. --module("luarocks.build.cmake", package.seeall) local cmake = {} local fs = require("luarocks.fs") local util = require("luarocks.util") local cfg = require("luarocks.cfg") local deps = require("luarocks.deps") --- Driver function for the "cmake" build back-end. -- @param rockspec table: the loaded rockspec. -- @return boolean or (nil, string): true if no errors ocurred, -- nil and an error message otherwise. function cmake.run(rockspec) assert(type(rockspec) == "table") local build = rockspec.build local variables = build.variables or {} -- Pass Env variables variables.CMAKE_MODULE_PATH=os.getenv("CMAKE_MODULE_PATH") variables.CMAKE_LIBRARY_PATH=os.getenv("CMAKE_LIBRARY_PATH") variables.CMAKE_INCLUDE_PATH=os.getenv("CMAKE_INCLUDE_PATH") util.variable_substitutions(variables, rockspec.variables) local ok, err_msg = fs.is_tool_available(rockspec.variables.CMAKE, "CMake") if not ok then return nil, err_msg end -- If inline cmake is present create CMakeLists.txt from it. if type(build.cmake) == "string" then local cmake_handler = assert(io.open(fs.current_dir().."/CMakeLists.txt", "w")) cmake_handler:write(build.cmake) cmake_handler:close() end -- Execute cmake with variables. local args = "" -- Try to pick the best generator. With msvc and x64, CMake does not select it by default so we need to be explicit. if cfg.cmake_generator then args = args .. ' -G"'..cfg.cmake_generator.. '"' elseif cfg.is_platform("windows") and cfg.target_cpu:match("x86_64$") then args = args .. " -DCMAKE_GENERATOR_PLATFORM=x64" end for k,v in pairs(variables) do args = args .. ' -D' ..k.. '="' ..tostring(v).. '"' end if not fs.execute_string(rockspec.variables.CMAKE.." -H. -Bbuild.luarocks "..args) then return nil, "Failed cmake." end local do_build, do_install if deps.format_is_at_least(rockspec, "3.0") then do_build = (build.build_pass == nil) and true or build.build_pass do_install = (build.install_pass == nil) and true or build.install_pass else do_build = true do_install = true end if do_build then if not fs.execute_string(rockspec.variables.CMAKE.." --build build.luarocks --config Release") then return nil, "Failed building." end end if do_install then if not fs.execute_string(rockspec.variables.CMAKE.." --build build.luarocks --target install --config Release") then return nil, "Failed installing." end end return true end return cmake
Support install_pass in CMake. Fixes #431.
Support install_pass in CMake. Fixes #431.
Lua
mit
keplerproject/luarocks,luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks,tarantool/luarocks,luarocks/luarocks,keplerproject/luarocks,tarantool/luarocks,tarantool/luarocks,luarocks/luarocks
0928c484b2052d4ea1a6bcb7573301fbf7f94f72
src/plugins/lua/multimap.lua
src/plugins/lua/multimap.lua
-- Multimap is rspamd module designed to define and operate with different maps local rules = {} function split(str, delim, maxNb) -- Eliminate bad cases... if string.find(str, delim) == nil then return { str } end if maxNb == nil or maxNb < 1 then maxNb = 0 -- No limit end local result = {} local pat = "(.-)" .. delim .. "()" local nb = 0 local lastPos for part, pos in string.gfind(str, pat) do nb = nb + 1 result[nb] = part lastPos = pos if nb == maxNb then break end end -- Handle the last field if nb ~= maxNb then result[nb + 1] = string.sub(str, lastPos) end return result end function check_multimap(task) for _,rule in ipairs(rules) do if rule['type'] == 'ip' then local ip = task:get_from_ip_num() if rule['ips']:get_key(ip) then task:insert_result(rule['symbol'], 1) end elseif rule['type'] == 'header' then local headers = task:get_message():get_header(rule['header']) if headers then for _,hv in ipairs(headers) do if rule['pattern'] then -- extract a part from header local _,_,ext = string.find(hv, rule['pattern']) if ext then if rule['hash']:get_key(ext) then task:insert_result(rule['symbol'], 1) end end else if rule['hash']:get_key(hv) then task:insert_result(rule['symbol'], 1) end end end end end end end function add_rule(params) local newrule = { type = 'ip', header = nil, pattern = nil, file = nil, symbol = nil } for _,param in ipairs(params) do local _,_,name,value = string.find(param, '(%w+)%s*=%s*(.+)') if not name or not value then rspamd_logger:err('invalid rule: '..param) return 0 end if name == 'type' then if value == 'ip' then newrule['type'] = 'ip' elseif value == 'header' then newrule['type'] = 'header' else rspamd_logger:err('invalid rule type: '.. value) return 0 end elseif name == 'header' then newrule['header'] = value elseif name == 'pattern' then newrule['pattern'] = value elseif name == 'file' then newrule['file'] = value elseif name == 'symbol' then newrule['symbol'] = value else rspamd_logger:err('invalid rule option: '.. name) return 0 end end if not newrule['symbol'] or not newrule['file'] or not newrule['symbol'] then rspamd_logger:err('incomplete rule') return 0 end if newrule['type'] == 'ip' then newrule['ips'] = rspamd_config:add_radix_map (newrule['file']) else newrule['hash'] = rspamd_config:add_hash_map (newrule['file']) end table.insert(rules, newrule) return 1 end local opts = rspamd_config:get_all_opt('multimap') if opts then for opt,value in pairs(opts) do if opt == 'rule' then local params = split(value, ',') if not add_rule (params) then rspamd_logger:err('cannot add rule: "'..value..'"') end end end end if table.maxn(rules) > 0 then -- add fake symbol to check all maps inside a single callback rspamd_config:register_symbol('MULTIMAP', 1.0, 'check_multimap') end
-- Multimap is rspamd module designed to define and operate with different maps local rules = {} function split(str, delim, maxNb) -- Eliminate bad cases... if string.find(str, delim) == nil then return { str } end if maxNb == nil or maxNb < 1 then maxNb = 0 -- No limit end local result = {} local pat = "(.-)" .. delim .. "()" local nb = 0 local lastPos for part, pos in string.gfind(str, pat) do nb = nb + 1 result[nb] = part lastPos = pos if nb == maxNb then break end end -- Handle the last field if nb ~= maxNb then result[nb + 1] = string.sub(str, lastPos) end return result end function check_multimap(task) for _,rule in ipairs(rules) do if rule['type'] == 'ip' then local ip = task:get_from_ip_num() if rule['ips']:get_key(ip) then task:insert_result(rule['symbol'], 1) end elseif rule['type'] == 'header' then local headers = task:get_message():get_header(rule['header']) if headers then for _,hv in ipairs(headers) do if rule['pattern'] then -- extract a part from header local _,_,ext = string.find(hv, rule['pattern']) if ext then if rule['hash']:get_key(ext) then task:insert_result(rule['symbol'], 1) end end else if rule['hash']:get_key(hv) then task:insert_result(rule['symbol'], 1) end end end end end end end function add_rule(params) local newrule = { type = 'ip', header = nil, pattern = nil, map = nil, symbol = nil } for _,param in ipairs(params) do local _,_,name,value = string.find(param, '(%w+)%s*=%s*(.+)') if not name or not value then rspamd_logger:err('invalid rule: '..param) return 0 end if name == 'type' then if value == 'ip' then newrule['type'] = 'ip' elseif value == 'header' then newrule['type'] = 'header' else rspamd_logger:err('invalid rule type: '.. value) return 0 end elseif name == 'header' then newrule['header'] = value elseif name == 'pattern' then newrule['pattern'] = value elseif name == 'map' then newrule['map'] = value elseif name == 'symbol' then newrule['symbol'] = value else rspamd_logger:err('invalid rule option: '.. name) return 0 end end if not newrule['symbol'] or not newrule['map'] or not newrule['symbol'] then rspamd_logger:err('incomplete rule') return 0 end if newrule['type'] == 'ip' then newrule['ips'] = rspamd_config:add_radix_map (newrule['map']) else newrule['hash'] = rspamd_config:add_hash_map (newrule['map']) end table.insert(rules, newrule) return 1 end local opts = rspamd_config:get_all_opt('multimap') if opts then local strrules = opts['rule'] if strrules then for _,value in ipairs(strrules) do local params = split(value, ',') if not add_rule (params) then rspamd_logger:err('cannot add rule: "'..value..'"') end end end end if table.maxn(rules) > 0 then -- add fake symbol to check all maps inside a single callback rspamd_config:register_symbol('MULTIMAP', 1.0, 'check_multimap') end
* Fix some multimap issues
* Fix some multimap issues
Lua
apache-2.0
andrejzverev/rspamd,dark-al/rspamd,andrejzverev/rspamd,minaevmike/rspamd,amohanta/rspamd,dark-al/rspamd,amohanta/rspamd,dark-al/rspamd,amohanta/rspamd,amohanta/rspamd,amohanta/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,awhitesong/rspamd,andrejzverev/rspamd,awhitesong/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,dark-al/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,dark-al/rspamd,minaevmike/rspamd,awhitesong/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,awhitesong/rspamd
f0463c1586c237cb7334ba0b30c668208ecda3ea
src/lounge/lua/shairport.lua
src/lounge/lua/shairport.lua
#!/lounge/bin/janosh -f local util = require("util") function start(key, op, value) Janosh:transaction(function() Janosh:publish("playerPause","W",""); Janosh:system("killall shairport; shairport -a `cat /etc/hostname` &") if Janosh:get("/shairport/active").active == "false" then util:notifyLong("Activating shairport"); Janosh:set_t("/shairport/active", "true") end end) end function stop(key,op,value) Janosh:transaction(function() Janosh:system("killall shairport") if Janosh:get("/shairport/active").active == "true" then util:notifyLong("Deactivating shairport"); Janosh:set_t("/shairport/active", "false") end end) end Janosh:subscribe("shairportStart", start) Janosh:subscribe("shairportStop", stop) while true do Janosh:sleep(1000000) end
#!/lounge/bin/janosh -f local util = require("util") function start(key, op, value) Janosh:transaction(function() Janosh:publish("playerPause","W",""); Janosh:system("killall shairport; shairport -a `cat /etc/hostname` &") if Janosh:get("/shairport/active").active == "false" then util:notifyLong("Activating shairport"); Janosh:set_t("/shairport/active", "true") end end) end function stop(key,op,value) Janosh:transaction(function() Janosh:system("killall shairport") if Janosh:get("/shairport/active").active == "true" then util:notifyLong("Deactivating shairport"); Janosh:set_t("/shairport/active", "false") Janosh:publish("playerPlay","W",""); end end) end Janosh:subscribe("shairportStart", start) Janosh:subscribe("shairportStop", stop) while true do Janosh:sleep(1000000) end
fixed pause/play logic. also there isn't playerStop anymore
fixed pause/play logic. also there isn't playerStop anymore
Lua
agpl-3.0
screeninvader/ScreenInvader,screeninvader/ScreenInvader
58263db25d771f80901bba455b23c3ed988e015b
util/sasl.lua
util/sasl.lua
local base64 = require "base64" local md5 = require "md5" local crypto = require "crypto" local log = require "util.logger".init("sasl"); local tostring = tostring; local st = require "util.stanza"; local generate_uuid = require "util.uuid".generate; local s_match = string.match; local math = require "math" local type = type local error = error local print = print module "sasl" local function new_plain(onAuth, onSuccess, onFail, onWrite) local object = { mechanism = "PLAIN", onAuth = onAuth, onSuccess = onSuccess, onFail = onFail, onWrite = onWrite} local challenge = base64.encode(""); --onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge)) object.feed = function(self, stanza) if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end local response = base64.decode(stanza[1]) local authorization = s_match(response, "([^&%z]+)") local authentication = s_match(response, "%z([^&%z]+)%z") local password = s_match(response, "%z[^&%z]+%z([^&%z]+)") if self.onAuth(authentication, password) == true then self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"})) self.onSuccess(authentication) else self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure")); end end return object end --[[ SERVER: nonce="3145176401",qop="auth",charset=utf-8,algorithm=md5-sess CLIENT: username="tobiasfar",nonce="3145176401",cnonce="pJiW7hzeZLvOSAf7gBzwTzLWe4obYOVDlnNESzQCzGg=",nc=00000001,digest-uri="xmpp/jabber.org",qop=auth,response=99a93ba75235136e6403c3a2ba37089d,charset=utf-8 username="tobias",nonce="4406697386",cnonce="wUnT7vYrOB0V8D/lKd5bhpaNCk+hLJwc8T4CBCqp7WM=",nc=00000001,digest-uri="xmpp/luaetta.ath.cx",qop=auth,response=d202b8a1bdf8204816fb23c5f87b6b63,charset=utf-8 SERVER: rspauth=ab66d28c260e97da577ce3aac46a8991 ]]-- local function new_digest_md5(onAuth, onSuccess, onFail, onWrite) local function H(s) return md5.sum(s) end local function KD(k, s) return H(k..":"..s) end local function HEX(n) return md5.sumhexa(n) end local function HMAC(k, s) return crypto.hmac.digest("md5", s, k, true) end local function serialize(message) local data = "" if type(message) ~= "table" then error("serialize needs an argument of type table.") end -- testing all possible values if message["nonce"] then data = data..[[nonce="]]..message.nonce..[[",]] end if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end if message["charset"] then data = data..[[charset=]]..message.charset.."," end if message["algorithm"] then data = data..[[algorithm=]]..message.algorithm.."," end if message["rspauth"] then data = data..[[rspauth=]]..message.algorith.."," end data = data:gsub(",$", "") return data end local function parse(data) message = {} for k, v in string.gmatch(data, [[([%w%-])="?[%w%-]"?,?]]) do message[k] = v end return message end local object = { mechanism = "DIGEST-MD5", onAuth = onAuth, onSuccess = onSuccess, onFail = onFail, onWrite = onWrite } --TODO: something better than math.random would be nice, maybe OpenSSL's random number generator object.nonce = math.random(0, 9) for i = 1, 9 do object.nonce = object.nonce..math.random(0, 9) end object.step = 1 object.nonce_count = {} local challenge = base64.encode(serialize({ nonce = object.nonce, qop = "auth", charset = "utf-8", algorithm = "md5-sess"} )); object.onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge)) object.feed = function(self, stanza) print(tostring(stanza)) if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end if stanza.name == "auth" then return end self.step = self.step + 1 if (self.step == 2) then log("debug", tostring(stanza[1])) local response = parse(base64.decode(stanza[1])) -- check for replay attack if response["nonce-count"] then if self.nonce_count[response["nonce-count"]] then self.onFail("not-authorized") end end -- check for username, it's REQUIRED by RFC 2831 if not response["username"] then self.onFail("malformed-request") end -- check for nonce, ... if not response["nonce"] then self.onFail("malformed-request") else -- check if it's the right nonce if response["nonce"] ~= self.nonce then self.onFail("malformed-request") end end if not response["cnonce"] then self.onFail("malformed-request") end if not response["qop"] then response["qop"] = "auth" end local hostname = "" if response["digest-uri"] then local uri = response["digest-uri"]:gmatch("^(%w)/(%w)") local protocol = uri[1] log(protocol) local hostname = uri[2] log(hostname) end -- compare response_value with own calculation local A1-- = H(response["username"]..":"..realm-value, ":", passwd } ), -- ":", nonce-value, ":", cnonce-value) local A2 local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2)))) if response["qop"] == "auth" then else end local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2)))) end --[[ local authorization = s_match(response, "([^&%z]+)") local authentication = s_match(response, "%z([^&%z]+)%z") local password = s_match(response, "%z[^&%z]+%z([^&%z]+)") if self.onAuth(authentication, password) == true then self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"})) self.onSuccess(authentication) else self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure")); end]]-- end return object end function new(mechanism, onAuth, onSuccess, onFail, onWrite) local object if mechanism == "PLAIN" then object = new_plain(onAuth, onSuccess, onFail, onWrite) elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(onAuth, onSuccess, onFail, onWrite) else log("debug", "Unsupported SASL mechanism: "..tostring(mechanism)); onFail("unsupported-mechanism") end return object end return _M;
local base64 = require "base64" local md5 = require "md5" local crypto = require "crypto" local log = require "util.logger".init("sasl"); local tostring = tostring; local st = require "util.stanza"; local generate_uuid = require "util.uuid".generate; local s_match = string.match; local gmatch = string.gmatch local math = require "math" local type = type local error = error local print = print module "sasl" local function new_plain(onAuth, onSuccess, onFail, onWrite) local object = { mechanism = "PLAIN", onAuth = onAuth, onSuccess = onSuccess, onFail = onFail, onWrite = onWrite} local challenge = base64.encode(""); --onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge)) object.feed = function(self, stanza) if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end local response = base64.decode(stanza[1]) local authorization = s_match(response, "([^&%z]+)") local authentication = s_match(response, "%z([^&%z]+)%z") local password = s_match(response, "%z[^&%z]+%z([^&%z]+)") if self.onAuth(authentication, password) == true then self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"})) self.onSuccess(authentication) else self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure")); end end return object end --[[ SERVER: nonce="3145176401",qop="auth",charset=utf-8,algorithm=md5-sess CLIENT: username="tobiasfar",nonce="3145176401",cnonce="pJiW7hzeZLvOSAf7gBzwTzLWe4obYOVDlnNESzQCzGg=",nc=00000001,digest-uri="xmpp/jabber.org",qop=auth,response=99a93ba75235136e6403c3a2ba37089d,charset=utf-8 username="tobias",nonce="4406697386",cnonce="wUnT7vYrOB0V8D/lKd5bhpaNCk+hLJwc8T4CBCqp7WM=",nc=00000001,digest-uri="xmpp/luaetta.ath.cx",qop=auth,response=d202b8a1bdf8204816fb23c5f87b6b63,charset=utf-8 SERVER: rspauth=ab66d28c260e97da577ce3aac46a8991 ]]-- local function new_digest_md5(onAuth, onSuccess, onFail, onWrite) local function H(s) return md5.sum(s) end local function KD(k, s) return H(k..":"..s) end local function HEX(n) return md5.sumhexa(n) end local function HMAC(k, s) return crypto.hmac.digest("md5", s, k, true) end local function serialize(message) local data = "" if type(message) ~= "table" then error("serialize needs an argument of type table.") end -- testing all possible values if message["nonce"] then data = data..[[nonce="]]..message.nonce..[[",]] end if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end if message["charset"] then data = data..[[charset=]]..message.charset.."," end if message["algorithm"] then data = data..[[algorithm=]]..message.algorithm.."," end if message["rspauth"] then data = data..[[rspauth=]]..message.algorith.."," end data = data:gsub(",$", "") return data end local function parse(data) message = {} for k, v in gmatch(data, [[([%w%-]+)="?([%w%-%/%.]+)"?,?]]) do message[k] = v end return message end local object = { mechanism = "DIGEST-MD5", onAuth = onAuth, onSuccess = onSuccess, onFail = onFail, onWrite = onWrite } --TODO: something better than math.random would be nice, maybe OpenSSL's random number generator object.nonce = math.random(0, 9) for i = 1, 9 do object.nonce = object.nonce..math.random(0, 9) end object.step = 1 object.nonce_count = {} local challenge = base64.encode(serialize({ nonce = object.nonce, qop = "auth", charset = "utf-8", algorithm = "md5-sess"} )); object.onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge)) object.feed = function(self, stanza) if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end if stanza.name == "auth" then return end self.step = self.step + 1 if (self.step == 2) then local response = parse(base64.decode(stanza[1])) -- check for replay attack if response["nonce-count"] then if self.nonce_count[response["nonce-count"]] then self.onFail("not-authorized") end end -- check for username, it's REQUIRED by RFC 2831 if not response["username"] then self.onFail("malformed-request") end -- check for nonce, ... if not response["nonce"] then self.onFail("malformed-request") else -- check if it's the right nonce if response["nonce"] ~= self.nonce then self.onFail("malformed-request") end end if not response["cnonce"] then self.onFail("malformed-request") end if not response["qop"] then response["qop"] = "auth" end local hostname = "" local protocol = "" if response["digest-uri"] then protocol, hostname = response["digest-uri"]:match("(%w+)/(.*)$") else error("No digest-uri") end -- compare response_value with own calculation local A1-- = H(response["username"]..":"..realm-value, ":", passwd } ), -- ":", nonce-value, ":", cnonce-value) local A2 --local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2)))) if response["qop"] == "auth" then else end --local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2)))) end --[[ local authorization = s_match(response, "([^&%z]+)") local authentication = s_match(response, "%z([^&%z]+)%z") local password = s_match(response, "%z[^&%z]+%z([^&%z]+)") if self.onAuth(authentication, password) == true then self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"})) self.onSuccess(authentication) else self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure")); end]]-- end return object end function new(mechanism, onAuth, onSuccess, onFail, onWrite) local object if mechanism == "PLAIN" then object = new_plain(onAuth, onSuccess, onFail, onWrite) elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(onAuth, onSuccess, onFail, onWrite) else log("debug", "Unsupported SASL mechanism: "..tostring(mechanism)); onFail("unsupported-mechanism") end return object end return _M;
Fixing some parsing and some other stuff.
Fixing some parsing and some other stuff.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
e3422f0c94787a1f5b58b9baac9b90bf50d59aff
agents/monitoring/lua/lib/info.lua
agents/monitoring/lua/lib/info.lua
local Object = require('core').Object local JSON = require('json') --[[ Info ]]-- local Info = Object:extend() function Info:initialize() self._s = sigar:new() self._params = {} end function Info:serialize() return { jsonPayload = JSON.stringify(self._params) } end local NilInfo = Info:extend() --[[ CPUInfo ]]-- local CPUInfo = Info:extend() function CPUInfo:initialize() Info.initialize(self) local cpus = self._s:cpus() self._params = {} for i=1, #cpus do local info = cpus[i]:info() local data = cpus[i]:data() local bucket = 'cpu.' .. i - 1 self._params[bucket] = {} for k, v in pairs(info) do self._params[bucket][k] = v end for k, v in pairs(data) do self._params[bucket][k] = v end end end --[[ DiskInfo ]]-- local DiskInfo = Info:extend() function DiskInfo:initialize() Info.initialize(self) local disks = self._s:disks() local name, usage for i=1, #disks do name = disks[i]:name() usage = disks[i]:usage() if usage then self._params[name] = {} for key, value in pairs(usage) do self._params[name][key] = value end end end end --[[ MemoryInfo ]]-- local MemoryInfo = Info:extend() function MemoryInfo:initialize() Info.initialize(self) local meminfo = self._s:mem() for key, value in pairs(meminfo) do self._params[key] = value end end --[[ NetworkInfo ]]-- local NetworkInfo = Info:extend() function NetworkInfo:initialize() Info.initialize(self) local netifs = self._s:netifs() for i=1,#netifs do self._params.netifs[i] = {} self._params.netifs[i].info = netifs[i]:info() self._params.netifs[i].usage = netifs[i]:usage() end end --[[ Factory ]]-- function create(infoType) if infoType == 'CPU' then return CPUInfo:new() elseif infoType == 'MEMORY' then return MemoryInfo:new() elseif infoType == 'NETWORK' then return NetworkInfo:new() elseif infoType == 'DISK' then return DiskInfo:new() end return NilInfo:new() end --[[ Exports ]]-- local info = {} info.CPUInfo = CPUInfo info.DiskInfo = DiskInfo info.MemoryInfo = MemoryInfo info.NetworkInfo = NetworkInfo info.create = create return info
local Object = require('core').Object local JSON = require('json') --[[ Info ]]-- local Info = Object:extend() function Info:initialize() self._s = sigar:new() self._params = {} end function Info:serialize() return { jsonPayload = JSON.stringify(self._params) } end local NilInfo = Info:extend() --[[ CPUInfo ]]-- local CPUInfo = Info:extend() function CPUInfo:initialize() Info.initialize(self) local cpus = self._s:cpus() self._params = {} for i=1, #cpus do local info = cpus[i]:info() local data = cpus[i]:data() local bucket = 'cpu.' .. i - 1 self._params[bucket] = {} for k, v in pairs(info) do self._params[bucket][k] = v end for k, v in pairs(data) do self._params[bucket][k] = v end end end --[[ DiskInfo ]]-- local DiskInfo = Info:extend() function DiskInfo:initialize() Info.initialize(self) local disks = self._s:disks() local name, usage for i=1, #disks do name = disks[i]:name() usage = disks[i]:usage() if usage then self._params[name] = {} for key, value in pairs(usage) do self._params[name][key] = value end end end end --[[ MemoryInfo ]]-- local MemoryInfo = Info:extend() function MemoryInfo:initialize() Info.initialize(self) local meminfo = self._s:mem() for key, value in pairs(meminfo) do self._params[key] = value end end --[[ NetworkInfo ]]-- local NetworkInfo = Info:extend() function NetworkInfo:initialize() Info.initialize(self) local netifs = self._s:netifs() for i=1,#netifs do local info = netifs[i]:info() local usage = netifs[i]:usage() local name = info.name self._params[name] = {} for k, v in pairs(info) do self._params[name][k] = v end for k, v in pairs(usage) do self._params[name][k] = v end end end --[[ Factory ]]-- function create(infoType) if infoType == 'CPU' then return CPUInfo:new() elseif infoType == 'MEMORY' then return MemoryInfo:new() elseif infoType == 'NETWORK' then return NetworkInfo:new() elseif infoType == 'DISK' then return DiskInfo:new() end return NilInfo:new() end --[[ Exports ]]-- local info = {} info.CPUInfo = CPUInfo info.DiskInfo = DiskInfo info.MemoryInfo = MemoryInfo info.NetworkInfo = NetworkInfo info.create = create return info
fix network info
fix network info
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base
52134f9e576fa4e7a82459b7895a7fce56e02285
lualib/sharedata/corelib.lua
lualib/sharedata/corelib.lua
local core = require "sharedata.core" local type = type local next = next local rawget = rawget local conf = {} conf.host = { new = core.new, delete = core.delete, getref = core.getref, markdirty = core.markdirty, incref = core.incref, decref = core.decref, } local meta = {} local isdirty = core.isdirty local index = core.index local needupdate = core.needupdate local len = core.len local function findroot(self) while self.__parent do self = self.__parent end return self end local function update(root, cobj, gcobj) root.__obj = cobj root.__gcobj = gcobj -- don't use pairs for k,v in next, root do if type(v)=="table" and k~="__parent" then local pointer = index(cobj, k) if type(pointer) == "userdata" then update(v, pointer, gcobj) else root[k] = nil end end end end local function genkey(self) local key = tostring(self.__key) while self.__parent do self = self.__parent key = self.__key .. "." .. key end return key end function meta:__index(key) local obj = self.__obj if isdirty(obj) then local newobj, newtbl = needupdate(self.__gcobj) if newobj then local newgcobj = newtbl.__gcobj local root = findroot(self) update(root, newobj, newgcobj) if obj == self.__obj then error ("The key [" .. genkey(self) .. "] doesn't exist after update") end obj = self.__obj end end local v = index(obj, key) if type(v) == "userdata" then local r = setmetatable({ __obj = v, __gcobj = self.__gcobj, __parent = self, __key = key, }, meta) self[key] = r return r else return v end end function meta:__len() return len(self.__obj) end local function conf_ipairs(self, index) local obj = self.__obj index = index + 1 local value = rawget(self, index) if value then return index, value end local sz = len(obj) if sz < index then return end return index, self[index] end function meta:__ipairs() return conf_ipairs, self, 0 end function meta:__pairs() return conf.next, self, nil end function conf.next(obj, key) local nextkey = core.nextkey(obj.__obj, key) if nextkey then return nextkey, obj[nextkey] end end function conf.box(obj) local gcobj = core.box(obj) return setmetatable({ __parent = false, __obj = obj, __gcobj = gcobj, __key = "", } , meta) end function conf.update(self, pointer) local cobj = self.__obj assert(isdirty(cobj), "Only dirty object can be update") core.update(self.__gcobj, pointer, { __gcobj = core.box(pointer) }) end return conf
local core = require "sharedata.core" local type = type local next = next local rawget = rawget local conf = {} conf.host = { new = core.new, delete = core.delete, getref = core.getref, markdirty = core.markdirty, incref = core.incref, decref = core.decref, } local meta = {} local isdirty = core.isdirty local index = core.index local needupdate = core.needupdate local len = core.len local function findroot(self) while self.__parent do self = self.__parent end return self end local function update(root, cobj, gcobj) root.__obj = cobj root.__gcobj = gcobj -- don't use pairs for k,v in next, root do if type(v)=="table" and k~="__parent" then local pointer = index(cobj, k) if type(pointer) == "userdata" then update(v, pointer, gcobj) else root[k] = nil end end end end local function genkey(self) local key = tostring(self.__key) while self.__parent do self = self.__parent key = self.__key .. "." .. key end return key end local function getcobj(self) local obj = self.__obj if isdirty(obj) then local newobj, newtbl = needupdate(self.__gcobj) if newobj then local newgcobj = newtbl.__gcobj local root = findroot(self) update(root, newobj, newgcobj) if obj == self.__obj then error ("The key [" .. genkey(self) .. "] doesn't exist after update") end obj = self.__obj end end return obj end function meta:__index(key) local obj = getcobj(self) local v = index(obj, key) if type(v) == "userdata" then local r = setmetatable({ __obj = v, __gcobj = self.__gcobj, __parent = self, __key = key, }, meta) self[key] = r return r else return v end end function meta:__len() return len(getcobj(self)) end local function conf_ipairs(self, index) local obj = getcobj(self) index = index + 1 local value = rawget(self, index) if value then return index, value end local sz = len(obj) if sz < index then return end return index, self[index] end function meta:__ipairs() return conf_ipairs, self, 0 end function meta:__pairs() return conf.next, self, nil end function conf.next(obj, key) local cobj = getcobj(obj) local nextkey = core.nextkey(cobj, key) if nextkey then return nextkey, obj[nextkey] end end function conf.box(obj) local gcobj = core.box(obj) return setmetatable({ __parent = false, __obj = obj, __gcobj = gcobj, __key = "", } , meta) end function conf.update(self, pointer) local cobj = self.__obj assert(isdirty(cobj), "Only dirty object can be update") core.update(self.__gcobj, pointer, { __gcobj = core.box(pointer) }) end return conf
check c obj dirty when len, pairs and ipairs. Fix issue #219
check c obj dirty when len, pairs and ipairs. Fix issue #219
Lua
mit
icetoggle/skynet,LuffyPan/skynet,MRunFoss/skynet,letmefly/skynet,javachengwc/skynet,fztcjjl/skynet,dymx101/skynet,cpascal/skynet,puXiaoyi/skynet,hongling0/skynet,dymx101/skynet,fztcjjl/skynet,firedtoad/skynet,LiangMa/skynet,ag6ag/skynet,fztcjjl/skynet,pichina/skynet,kyle-wang/skynet,catinred2/skynet,your-gatsby/skynet,bingo235/skynet,codingabc/skynet,MoZhonghua/skynet,iskygame/skynet,winglsh/skynet,MoZhonghua/skynet,MoZhonghua/skynet,korialuo/skynet,felixdae/skynet,gitfancode/skynet,samael65535/skynet,samael65535/skynet,bttscut/skynet,lc412/skynet,yinjun322/skynet,cdd990/skynet,matinJ/skynet,great90/skynet,zhangshiqian1214/skynet,cloudwu/skynet,plsytj/skynet,wangyi0226/skynet,togolwb/skynet,yinjun322/skynet,puXiaoyi/skynet,cpascal/skynet,nightcj/mmo,wangjunwei01/skynet,ypengju/skynet_comment,vizewang/skynet,nightcj/mmo,bigrpg/skynet,lynx-seu/skynet,winglsh/skynet,sanikoyes/skynet,MetSystem/skynet,zzh442856860/skynet-Note,Markal128/skynet,iskygame/skynet,rainfiel/skynet,cuit-zhaxin/skynet,microcai/skynet,KAndQ/skynet,xjdrew/skynet,cdd990/skynet,xcjmine/skynet,catinred2/skynet,cdd990/skynet,vizewang/skynet,zzh442856860/skynet-Note,liuxuezhan/skynet,ypengju/skynet_comment,wangyi0226/skynet,chfg007/skynet,KittyCookie/skynet,Zirpon/skynet,pigparadise/skynet,microcai/skynet,ludi1991/skynet,bttscut/skynet,JiessieDawn/skynet,javachengwc/skynet,chenjiansnail/skynet,liuxuezhan/skynet,zhangshiqian1214/skynet,wangjunwei01/skynet,matinJ/skynet,korialuo/skynet,KittyCookie/skynet,czlc/skynet,sundream/skynet,letmefly/skynet,zhangshiqian1214/skynet,bigrpg/skynet,KAndQ/skynet,zhouxiaoxiaoxujian/skynet,microcai/skynet,LiangMa/skynet,yunGit/skynet,nightcj/mmo,zzh442856860/skynet,xinjuncoding/skynet,ludi1991/skynet,u20024804/skynet,ilylia/skynet,your-gatsby/skynet,MRunFoss/skynet,ilylia/skynet,ruleless/skynet,cuit-zhaxin/skynet,leezhongshan/skynet,Ding8222/skynet,cmingjian/skynet,dymx101/skynet,sanikoyes/skynet,great90/skynet,enulex/skynet,gitfancode/skynet,harryzeng/skynet,xcjmine/skynet,zhangshiqian1214/skynet,bigrpg/skynet,asanosoyokaze/skynet,winglsh/skynet,pichina/skynet,samael65535/skynet,ludi1991/skynet,firedtoad/skynet,lawnight/skynet,boyuegame/skynet,KittyCookie/skynet,zhaijialong/skynet,zhoukk/skynet,cmingjian/skynet,bingo235/skynet,lawnight/skynet,rainfiel/skynet,QuiQiJingFeng/skynet,fhaoquan/skynet,felixdae/skynet,chfg007/skynet,sdgdsffdsfff/skynet,liuxuezhan/skynet,KAndQ/skynet,fhaoquan/skynet,Ding8222/skynet,chfg007/skynet,iskygame/skynet,wangjunwei01/skynet,zzh442856860/skynet,gitfancode/skynet,pichina/skynet,lc412/skynet,zzh442856860/skynet-Note,sundream/skynet,sdgdsffdsfff/skynet,enulex/skynet,hongling0/skynet,u20024804/skynet,fhaoquan/skynet,longmian/skynet,zhaijialong/skynet,bingo235/skynet,harryzeng/skynet,great90/skynet,lynx-seu/skynet,zhangshiqian1214/skynet,puXiaoyi/skynet,yunGit/skynet,xjdrew/skynet,kyle-wang/skynet,matinJ/skynet,vizewang/skynet,MetSystem/skynet,MetSystem/skynet,codingabc/skynet,jxlczjp77/skynet,javachengwc/skynet,JiessieDawn/skynet,sanikoyes/skynet,leezhongshan/skynet,enulex/skynet,ag6ag/skynet,rainfiel/skynet,kebo/skynet,wangyi0226/skynet,catinred2/skynet,pigparadise/skynet,zzh442856860/skynet,sundream/skynet,xinjuncoding/skynet,cloudwu/skynet,helling34/skynet,lc412/skynet,chuenlungwang/skynet,leezhongshan/skynet,xubigshu/skynet,JiessieDawn/skynet,czlc/skynet,liuxuezhan/skynet,zhouxiaoxiaoxujian/skynet,letmefly/skynet,MRunFoss/skynet,helling34/skynet,kebo/skynet,QuiQiJingFeng/skynet,ilylia/skynet,ruleless/skynet,QuiQiJingFeng/skynet,longmian/skynet,chenjiansnail/skynet,hongling0/skynet,jiuaiwo1314/skynet,jxlczjp77/skynet,xinjuncoding/skynet,cuit-zhaxin/skynet,sdgdsffdsfff/skynet,chenjiansnail/skynet,boyuegame/skynet,togolwb/skynet,plsytj/skynet,helling34/skynet,zhoukk/skynet,bttscut/skynet,Zirpon/skynet,Ding8222/skynet,kyle-wang/skynet,ruleless/skynet,felixdae/skynet,lawnight/skynet,Markal128/skynet,pigparadise/skynet,u20024804/skynet,ag6ag/skynet,zzh442856860/skynet-Note,chuenlungwang/skynet,letmefly/skynet,codingabc/skynet,zhouxiaoxiaoxujian/skynet,cmingjian/skynet,LiangMa/skynet,jiuaiwo1314/skynet,jxlczjp77/skynet,LuffyPan/skynet,czlc/skynet,xubigshu/skynet,firedtoad/skynet,yunGit/skynet,asanosoyokaze/skynet,zhangshiqian1214/skynet,plsytj/skynet,Zirpon/skynet,asanosoyokaze/skynet,ypengju/skynet_comment,icetoggle/skynet,ludi1991/skynet,lawnight/skynet,yinjun322/skynet,jiuaiwo1314/skynet,korialuo/skynet,Markal128/skynet,xjdrew/skynet,harryzeng/skynet,zhaijialong/skynet,longmian/skynet,xcjmine/skynet,boyuegame/skynet,chuenlungwang/skynet,kebo/skynet,cloudwu/skynet,zhoukk/skynet,cpascal/skynet,icetoggle/skynet,LuffyPan/skynet,togolwb/skynet,lynx-seu/skynet,your-gatsby/skynet
d1e5260dd5a6d0317a1f3affdcf0df2dfee0eef6
premake5.lua
premake5.lua
-- A solution contains projects, and defines the available configurations solution "2D Pong" configurations { "Debug", "Release"} flags { "Unicode" , "NoPCH"} projectName = "2d_Pong" projectSourcePath = "src/" projectBuildPath = "bin/" -- A project defines one build target project (projectName) kind "ConsoleApp" location (projectSourcePath) language "C++" targetdir (projectBuildPath) configuration { "windows" } buildoptions "" linkoptions { "/NODEFAULTLIB:msvcrt" } -- https://github.com/yuriks/robotic/blob/master/premake5.lua configuration { "linux" } buildoptions "-std=c++11" --http://industriousone.com/topic/xcode4-c11-build-option toolset "gcc" configuration {} files { path.join(projectSourcePath, "**.h"), path.join(projectSourcePath, "**.cpp") } -- build all .h and .cpp files recursively excludes { "./graphics_dependencies/**" } -- don't build files in graphics_dependencies/ -- where are header files? -- tag::headers[] configuration "windows" includedirs { "./graphics_dependencies/SDL2/include", "./graphics_dependencies/glew/include", "./graphics_dependencies/glm", "./graphics_dependencies/SDL2_image/include", } configuration { "linux" } includedirs { -- should be installed as in ./graphics_dependencies/README.asciidoc } configuration {} -- end::headers[] -- what libraries need linking to -- tag::libraries[] configuration "windows" links { "SDL2", "SDL2main", "opengl32", "glew32", "SDL2_image" } configuration "linux" links { "SDL2", "SDL2main", "GL", "GLEW", "SDL2_image" } configuration {} -- end::libraries[] -- where are libraries? -- tag::librariesDirs[] configuration "windows" libdirs { "./graphics_dependencies/glew/lib/Release/Win32", "./graphics_dependencies/SDL2/lib/win32", "./graphics_dependencies/SDL2_image/lib/x86/", } configuration "linux" -- should be installed as in ./graphics_dependencies/README.asciidoc configuration {} -- end::librariesDirs[] configuration "*Debug" defines { "DEBUG" } flags { "Symbols" } optimize "Off" targetsuffix "-debug" configuration "*Release" defines { "NDEBUG" } optimize "On" targetsuffix "-release" -- tag::copyAssets assetsPaths = { "shaders", "textures"} for i, assetPath in ipairs(assetsPaths) do assetSourcePath = path.join(projectSourcePath, "assets", assetPath) assetBuildPath = path.join(projectBuildPath, "assets", assetPath) os.mkdir(assetBuildPath) os.copyfile(path.join(assetSourcePath, "*") , assetBuildPath) end -- end::copyAssets -- copy dlls on windows -- tag::windowsDLLCopy[] if os.get() == "windows" then os.copyfile("./graphics_dependencies/glew/bin/Release/Win32/glew32.dll", path.join(projectBuildPath, "glew32.dll")) os.copyfile("./graphics_dependencies/SDL2/lib/win32/SDL2.dll", path.join(projectName, "SDL2.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/SDL2_image.dll", path.join(projectBuildPath, "SDL2_image.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libjpeg-9.dll", path.join(projectBuildPath, "libjpeg-9.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libpng16-16.dll", path.join(projectBuildPath, "libpng16-16.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libtiff-5.dll", path.join(projectBuildPath, "libtiff-5.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libwebp-4.dll", path.join(projectBuildPath, "libwebp-4.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/zlib1.dll", path.join(projectBuildPath, "zlib1.dll")) end -- end::windowsDLLCopy[]
-- A solution contains projects, and defines the available configurations solution "2D Pong" configurations { "Debug", "Release"} flags { "Unicode" , "NoPCH"} projectName = "2d_Pong" projectSourcePath = "src/" projectBuildPath = "bin/" -- A project defines one build target project (projectName) kind "ConsoleApp" location (projectSourcePath) language "C++" targetdir (projectBuildPath) configuration { "windows" } buildoptions "" linkoptions { "/NODEFAULTLIB:msvcrt" } -- https://github.com/yuriks/robotic/blob/master/premake5.lua configuration { "linux" } buildoptions "-std=c++11" --http://industriousone.com/topic/xcode4-c11-build-option toolset "gcc" configuration {} files { path.join(projectSourcePath, "**.h"), path.join(projectSourcePath, "**.cpp") } -- build all .h and .cpp files recursively excludes { "./graphics_dependencies/**" } -- don't build files in graphics_dependencies/ -- where are header files? -- tag::headers[] configuration "windows" includedirs { "./graphics_dependencies/SDL2/include", "./graphics_dependencies/SDL2/include/SDL2", "./graphics_dependencies/glew/include", "./graphics_dependencies/glm", "./graphics_dependencies/SDL2_image/include", } configuration { "linux" } includedirs { -- should be installed as in ./graphics_dependencies/README.asciidoc } configuration {} -- end::headers[] -- what libraries need linking to -- tag::libraries[] configuration "windows" links { "SDL2", "SDL2main", "opengl32", "glew32", "SDL2_image" } configuration "linux" links { "SDL2", "SDL2main", "GL", "GLEW", "SDL2_image" } configuration {} -- end::libraries[] -- where are libraries? -- tag::librariesDirs[] configuration "windows" libdirs { "./graphics_dependencies/glew/lib/Release/Win32", "./graphics_dependencies/SDL2/lib/win32", "./graphics_dependencies/SDL2_image/lib/x86/", } configuration "linux" -- should be installed as in ./graphics_dependencies/README.asciidoc configuration {} -- end::librariesDirs[] configuration "*Debug" defines { "DEBUG" } flags { "Symbols" } optimize "Off" targetsuffix "-debug" configuration "*Release" defines { "NDEBUG" } optimize "On" targetsuffix "-release" -- tag::copyAssets assetsPaths = { "shaders", "textures"} for i, assetPath in ipairs(assetsPaths) do assetSourcePath = path.join(projectSourcePath, "assets", assetPath) assetBuildPath = path.join(projectBuildPath, "assets", assetPath) os.mkdir(assetBuildPath) os.copyfile(path.join(assetSourcePath, "*") , assetBuildPath) end -- end::copyAssets -- copy dlls on windows -- tag::windowsDLLCopy[] if os.get() == "windows" then os.copyfile("./graphics_dependencies/glew/bin/Release/Win32/glew32.dll", path.join(projectBuildPath, "glew32.dll")) os.copyfile("./graphics_dependencies/SDL2/lib/win32/SDL2.dll", path.join(projectBuildPath, "SDL2.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/SDL2_image.dll", path.join(projectBuildPath, "SDL2_image.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libjpeg-9.dll", path.join(projectBuildPath, "libjpeg-9.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libpng16-16.dll", path.join(projectBuildPath, "libpng16-16.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libtiff-5.dll", path.join(projectBuildPath, "libtiff-5.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libwebp-4.dll", path.join(projectBuildPath, "libwebp-4.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/zlib1.dll", path.join(projectBuildPath, "zlib1.dll")) end -- end::windowsDLLCopy[]
fix SDL2.dll path for copy, and add SDL2 header location
fix SDL2.dll path for copy, and add SDL2 header location
Lua
mit
shearer12345/2d_pong,shearer12345/2d_pong
2c5e7ce1d8f66b04dfa35727571f1ed2a96ecc1d
premake4.lua
premake4.lua
#!lua -- Install pre-commit hook for linting if not installed yet or outdated if os.execute("test -x .git/hooks/pre-commit") ~= 0 or os.execute("md5 .git/hooks/pre-commit") ~= "cb1e4086756ddacb54ec87f775abd82b" then os.execute("touch .git/hooks/pre-commit") os.execute("echo '#!/bin/sh\necho \"Linting all code, this may take a while...\"\n\nfind src -iname *.cpp -o -iname *.hpp | while read line;\ndo\n if ! python cpplint.py --verbose=0 --extensions=hpp,cpp --counting=detailed --filter=-legal/copyright --linelength=120 $line >/dev/null 2>/dev/null\n then\n echo \"ERROR: Linting error occured. Execute \\\"premake4 lint\\\" for details!\n(What kind of ***** would consider a commit without linting?)\"\n exit 1\n fi\ndone\n\nif [ $? != 0 ]\nthen\n exit 1\nfi\n\necho \"Success, no linting errors found!\"\n\necho \"Testing the Opossum, grrrrr...\"\nmake TestOpossum -j >/dev/null 2>/dev/null\nif ! ./build/TestOpossum >/dev/null 2>/dev/null\nthen\n echo \"ERROR: Testing error occured. Execute \\\"premake4 test\\\" for details!\n(What kind of ***** would consider a commit without testing?)\"\n exit 1\nfi\n\necho \"Success, no testing errors found!\"' > .git/hooks/pre-commit") os.execute("chmod +x .git/hooks/pre-commit") os.execute("echo Successfully installed pre-commit hook.") end -- TODO try LTO/whole program if not _OPTIONS["compiler"] then _OPTIONS["compiler"] = "gcc" end if _OPTIONS["compiler"] == "clang" then toolset = "clang" else if os.execute("gcc-6 -v") == 0 then premake.gcc.cc = 'gcc-6' premake.gcc.cxx = 'g++-6' else error("gcc version 6 required. Aborting.") end end solution "Opossum" configurations { "Debug", "Release" } platforms "x64" flags { "FatalWarnings", "ExtraWarnings" } project "googletest" kind "StaticLib" language "C++" targetdir "build" location "third_party/googletest/googletest" files { "third_party/googletest/googletest/src/gtest-all.cc" } includedirs { "third_party/googletest/googletest", "third_party/googletest/googletest/include" } buildoptions { "-g -Wall -Wextra -pthread" } project "Opossum" kind "StaticLib" language "C++" targetdir "build" buildoptions { "-std=c++1z" } files { "src/lib/**.hpp", "src/lib/**.cpp" } includedirs { "src/lib/", "/usr/local/include" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } prebuildcommands { "find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} sh -c \"clang-format -i -style=file '{}'\"" } configuration "Release" defines { "NDEBUG" } flags { "OptimizeSpeed" } prebuildcommands { "find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} sh -c \"clang-format -i -style=file '{}'\"" } project "BinOpossum" kind "ConsoleApp" language "C++" targetdir "build" location "build" buildoptions { "-std=c++1z" } links { "Opossum" } files { "src/test/test2.cpp" } includedirs { "src/lib/", "/usr/local/include" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } configuration "Release" defines { "NDEBUG" } flags { "OptimizeSpeed" } project "TestOpossum" kind "ConsoleApp" language "C++" targetdir "build" buildoptions { "-std=c++1z" } defines { "DEBUG" } prebuildcommands { "find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} sh -c \"clang-format -i -style=file '{}'\"" } links { "googletest", "Opossum" } files { "src/test/**.hpp", "src/test/**.cpp" } excludes { "src/test/test2.cpp" } includedirs { "src/lib/", "/usr/local/include", "third_party/googletest/googletest/include" } newoption { trigger = "compiler", value = "clang||gcc", description = "Choose a compiler", allowed = { { "gcc", "gcc of version 6 or higher" }, { "clang", "clang llvm frontend" } } } -- Registering linting and formatting as actions for premake is not optimal, make targets would be the preferable option, but impossible to generate or really hacky newaction { trigger = "lint", description = "Lint the code", execute = function () os.execute("find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} python cpplint.py --verbose=0 --extensions=hpp,cpp --counting=detailed --filter=-legal/copyright --linelength=120 {}") end } newaction { trigger = "format", description = "Format the code", execute = function () os.execute("find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} sh -c \"clang-format -i -style=file '{}'\"") end } newaction { trigger = "test", description = "Test the code", execute = function () os.execute("make TestOpossum -j && ./build/TestOpossum") end }
#!lua -- Install pre-commit hook for linting if not installed yet or outdated if os.execute("test -x .git/hooks/pre-commit") ~= 0 or os.execute("md5 .git/hooks/pre-commit") ~= "cb1e4086756ddacb54ec87f775abd82b" then os.execute("touch .git/hooks/pre-commit") os.execute("echo '#!/bin/sh\necho \"Linting all code, this may take a while...\"\n\nfind src -iname *.cpp -o -iname *.hpp | while read line;\ndo\n if ! python cpplint.py --verbose=0 --extensions=hpp,cpp --counting=detailed --filter=-legal/copyright --linelength=120 $line >/dev/null 2>/dev/null\n then\n echo \"ERROR: Linting error occured. Execute \\\"premake4 lint\\\" for details!\n(What kind of ***** would consider a commit without linting?)\"\n exit 1\n fi\ndone\n\nif [ $? != 0 ]\nthen\n exit 1\nfi\n\necho \"Success, no linting errors found!\"\n\necho \"Testing the Opossum, grrrrr...\"\nmake TestOpossum -j >/dev/null 2>/dev/null\nif ! ./build/TestOpossum >/dev/null 2>/dev/null\nthen\n echo \"ERROR: Testing error occured. Execute \\\"premake4 test\\\" for details!\n(What kind of ***** would consider a commit without testing?)\"\n exit 1\nfi\n\necho \"Success, no testing errors found!\"' > .git/hooks/pre-commit") os.execute("chmod +x .git/hooks/pre-commit") os.execute("echo Successfully installed pre-commit hook.") end -- TODO try LTO/whole program if not _OPTIONS["compiler"] then _OPTIONS["compiler"] = "gcc" end if _OPTIONS["compiler"] == "clang" then toolset = "clang" else if os.execute("gcc-6 -v") == 0 then premake.gcc.cc = 'gcc-6' premake.gcc.cxx = 'g++-6' else error("gcc version 6 required. Aborting.") end end solution "Opossum" configurations { "Debug", "Release" } platforms "x64" flags { "FatalWarnings", "ExtraWarnings" } project "googletest" kind "StaticLib" language "C++" targetdir "build" location "build" files { "third_party/googletest/googletest/src/gtest-all.cc" } includedirs { "third_party/googletest/googletest", "third_party/googletest/googletest/include" } buildoptions { "-g -Wall -Wextra -pthread" } project "Opossum" kind "StaticLib" language "C++" targetdir "build" buildoptions { "-std=c++1z" } files { "src/lib/**.hpp", "src/lib/**.cpp" } includedirs { "src/lib/", "/usr/local/include" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } prebuildcommands { "find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} sh -c \"clang-format -i -style=file '{}'\"" } configuration "Release" defines { "NDEBUG" } flags { "OptimizeSpeed" } prebuildcommands { "find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} sh -c \"clang-format -i -style=file '{}'\"" } project "BinOpossum" kind "ConsoleApp" language "C++" targetdir "build" location "build" buildoptions { "-std=c++1z" } links { "Opossum" } files { "src/test/test2.cpp" } includedirs { "src/lib/", "/usr/local/include" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } configuration "Release" defines { "NDEBUG" } flags { "OptimizeSpeed" } project "TestOpossum" kind "ConsoleApp" language "C++" targetdir "build" buildoptions { "-std=c++1z" } defines { "DEBUG" } prebuildcommands { "find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} sh -c \"clang-format -i -style=file '{}'\"" } links { "googletest", "Opossum" } files { "src/test/**.hpp", "src/test/**.cpp" } excludes { "src/test/test2.cpp" } includedirs { "src/lib/", "/usr/local/include", "third_party/googletest/googletest/include" } newoption { trigger = "compiler", value = "clang||gcc", description = "Choose a compiler", allowed = { { "gcc", "gcc of version 6 or higher" }, { "clang", "clang llvm frontend" } } } -- Registering linting and formatting as actions for premake is not optimal, make targets would be the preferable option, but impossible to generate or really hacky newaction { trigger = "lint", description = "Lint the code", execute = function () os.execute("find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} python cpplint.py --verbose=0 --extensions=hpp,cpp --counting=detailed --filter=-legal/copyright --linelength=120 {}") end } newaction { trigger = "format", description = "Format the code", execute = function () os.execute("find src -iname \"*.cpp\" -o -iname \"*.hpp\" | xargs -I{} sh -c \"clang-format -i -style=file '{}'\"") end } newaction { trigger = "test", description = "Test the code", execute = function () os.execute("make TestOpossum -j && ./build/TestOpossum") end }
Minor fix
Minor fix
Lua
mit
hyrise/hyrise,hyrise/hyrise,hyrise/hyrise
3c496c51023b8c910a2665f5bae96e863c40af35
lua/entities/gmod_wire_lamp.lua
lua/entities/gmod_wire_lamp.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Lamp" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Lamp" function ENT:SetupDataTables() self:NetworkVar( "Bool", 0, "On" ) end if CLIENT then local matLight = Material( "sprites/light_ignorez" ) local matBeam = Material( "effects/lamp_beam" ) function ENT:Initialize() self.PixVis = util.GetPixelVisibleHandle() end function ENT:DrawTranslucent() self.BaseClass.DrawTranslucent( self ) -- No glow if we're not switched on! if not self:GetOn() then return end local LightNrm = self:GetAngles():Forward() local ViewNormal = self:GetPos() - EyePos() local Distance = ViewNormal:Length() ViewNormal:Normalize() local ViewDot = ViewNormal:Dot( LightNrm * -1 ) local LightPos = self:GetPos() + LightNrm * 5 -- glow sprite --[[ render.SetMaterial( matBeam ) local BeamDot = BeamDot = 0.25 render.StartBeam( 3 ) render.AddBeam( LightPos + LightNrm * 1, 128, 0.0, Color( r, g, b, 255 * BeamDot) ) render.AddBeam( LightPos - LightNrm * 100, 128, 0.5, Color( r, g, b, 64 * BeamDot) ) render.AddBeam( LightPos - LightNrm * 200, 128, 1, Color( r, g, b, 0) ) render.EndBeam() --]] if ViewDot >= 0 then render.SetMaterial( matLight ) local Visibile = util.PixelVisible( LightPos, 16, self.PixVis ) if (!Visibile) then return end local Size = math.Clamp( Distance * Visibile * ViewDot * 2, 64, 512 ) Distance = math.Clamp( Distance, 32, 800 ) local Alpha = math.Clamp( (1000 - Distance) * Visibile * ViewDot, 0, 100 ) local Col = self:GetColor() Col.a = Alpha render.DrawSprite( LightPos, Size, Size, Col, Visibile * ViewDot ) render.DrawSprite( LightPos, Size*0.4, Size*0.4, Color(255, 255, 255, Alpha), Visibile * ViewDot ) end end return -- No more client end -- Server function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end self.Inputs = WireLib.CreateSpecialInputs(self, {"Red", "Green", "Blue", "RGB", "FOV", "Distance", "Brightness", "On", "Texture"}, {"NORMAL", "NORMAL", "NORMAL", "VECTOR", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING"}) end function ENT:OnTakeDamage( dmginfo ) self:TakePhysicsDamage( dmginfo ) end function ENT:TriggerInput(iname, value) if (iname == "Red") then self.r = value elseif (iname == "Green") then self.g = value elseif (iname == "Blue") then self.b = value elseif (iname == "RGB") then self.r, self.g, self.b = value[1], value[2], value[3] elseif (iname == "FOV") then self.FOV = value elseif (iname == "Distance") then self.Dist = value elseif (iname == "Brightness") then self.Brightness = value elseif (iname == "On") then self:Switch( value ~= 0 ) elseif (iname == "Texture") then if value != "" then self.Texture = value else self.Texture = "effects/flashlight001" end end self:UpdateLight() end function ENT:Switch( on ) if on ~= not self.flashlight then return end self.on = on if not on then SafeRemoveEntity( self.flashlight ) self.flashlight = nil self:SetOn( false ) return end self:SetOn( true ) local angForward = self:GetAngles() self.flashlight = ents.Create( "env_projectedtexture" ) self.flashlight:SetParent( self ) -- The local positions are the offsets from parent.. self.flashlight:SetLocalPos( Vector( 0, 0, 0 ) ) self.flashlight:SetLocalAngles( Angle(0,0,0) ) -- Looks like only one flashlight can have shadows enabled! self.flashlight:SetKeyValue( "enableshadows", 1 ) self.flashlight:SetKeyValue( "farz", self.Dist ) self.flashlight:SetKeyValue( "nearz", 12 ) self.flashlight:SetKeyValue( "lightfov", self.FOV ) local c = self:GetColor() local b = self.Brightness self.flashlight:SetKeyValue( "lightcolor", Format( "%i %i %i 255", c.r * b, c.g * b, c.b * b ) ) self.flashlight:Spawn() self.flashlight:Input( "SpotlightTexture", NULL, NULL, self.Texture ) end function ENT:UpdateLight() self:SetColor( Color( self.r, self.g, self.b, self:GetColor().a ) ) if ( !IsValid( self.flashlight ) ) then return end self.flashlight:Input( "SpotlightTexture", NULL, NULL, self.Texture ) self.flashlight:Input( "FOV", NULL, NULL, tostring( self.FOV ) ) self.flashlight:SetKeyValue( "farz", self.Dist ) local c = self:GetColor() local b = self.Brightness self.flashlight:SetKeyValue( "lightcolor", Format( "%i %i %i 255", c.r*b, c.g*b, c.b*b ) ) self:SetOverlayText( "Red: " .. c.r .. " Green: " .. c.g .. " Blue: " .. c.b .. "\n" .. "FoV: " .. self.FOV .. " Distance: " .. self.Dist .. " Brightness: " .. self.Brightness ) end function ENT:Setup( r, g, b, Texture, fov, dist, brightness, on ) self.r, self.g, self.b = r or 255, g or 255, b or 255 self.Texture = Texture or "effects/flashlight001" self.FOV = fov or 90 self.Dist = dist or 1024 self.Brightness = brightness or 8 self.on = on or false self:Switch( self.on ) self:UpdateLight() end duplicator.RegisterEntityClass( "gmod_wire_lamp", WireLib.MakeWireEnt, "Data", "r", "g", "b", "Texture", "FOV", "Dist", "Brightness", "on" )
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Lamp" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Lamp" function ENT:SetupDataTables() self:NetworkVar( "Bool", 0, "On" ) end if CLIENT then local matLight = Material( "sprites/light_ignorez" ) local matBeam = Material( "effects/lamp_beam" ) function ENT:Initialize() self.PixVis = util.GetPixelVisibleHandle() end function ENT:DrawTranslucent() self.BaseClass.DrawTranslucent( self ) -- No glow if we're not switched on! if not self:GetOn() then return end local LightNrm = self:GetAngles():Forward() local ViewNormal = self:GetPos() - EyePos() local Distance = ViewNormal:Length() ViewNormal:Normalize() local ViewDot = ViewNormal:Dot( LightNrm * -1 ) local LightPos = self:GetPos() + LightNrm * 5 -- glow sprite --[[ render.SetMaterial( matBeam ) local BeamDot = BeamDot = 0.25 render.StartBeam( 3 ) render.AddBeam( LightPos + LightNrm * 1, 128, 0.0, Color( r, g, b, 255 * BeamDot) ) render.AddBeam( LightPos - LightNrm * 100, 128, 0.5, Color( r, g, b, 64 * BeamDot) ) render.AddBeam( LightPos - LightNrm * 200, 128, 1, Color( r, g, b, 0) ) render.EndBeam() --]] if ViewDot >= 0 then render.SetMaterial( matLight ) local Visibile = util.PixelVisible( LightPos, 16, self.PixVis ) if (!Visibile) then return end local Size = math.Clamp( Distance * Visibile * ViewDot * 2, 64, 512 ) Distance = math.Clamp( Distance, 32, 800 ) local Alpha = math.Clamp( (1000 - Distance) * Visibile * ViewDot, 0, 100 ) local Col = self:GetColor() Col.a = Alpha render.DrawSprite( LightPos, Size, Size, Col, Visibile * ViewDot ) render.DrawSprite( LightPos, Size*0.4, Size*0.4, Color(255, 255, 255, Alpha), Visibile * ViewDot ) end end return -- No more client end -- Server function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end self.Inputs = WireLib.CreateSpecialInputs(self, {"Red", "Green", "Blue", "RGB", "FOV", "Distance", "Brightness", "On", "Texture"}, {"NORMAL", "NORMAL", "NORMAL", "VECTOR", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING"}) end function ENT:OnTakeDamage( dmginfo ) self:TakePhysicsDamage( dmginfo ) end function ENT:TriggerInput(iname, value) if (iname == "Red") then self.r = math.Clamp(value,0,255) elseif (iname == "Green") then self.g = math.Clamp(value,0,255) elseif (iname == "Blue") then self.b = math.Clamp(value,0,255) elseif (iname == "RGB") then self.r, self.g, self.b = math.Clamp(value[1],0,255), math.Clamp(value[2],0,255), math.Clamp(value[3],0,255) elseif (iname == "FOV") then self.FOV = value elseif (iname == "Distance") then self.Dist = value elseif (iname == "Brightness") then self.Brightness = math.Clamp(value,0,10) elseif (iname == "On") then self:Switch( value ~= 0 ) elseif (iname == "Texture") then if value != "" then self.Texture = value else self.Texture = "effects/flashlight001" end end self:UpdateLight() end function ENT:Switch( on ) if on ~= not self.flashlight then return end self.on = on if not on then SafeRemoveEntity( self.flashlight ) self.flashlight = nil self:SetOn( false ) return end self:SetOn( true ) local angForward = self:GetAngles() self.flashlight = ents.Create( "env_projectedtexture" ) self.flashlight:SetParent( self ) -- The local positions are the offsets from parent.. self.flashlight:SetLocalPos( Vector( 0, 0, 0 ) ) self.flashlight:SetLocalAngles( Angle(0,0,0) ) -- Looks like only one flashlight can have shadows enabled! self.flashlight:SetKeyValue( "enableshadows", 1 ) self.flashlight:SetKeyValue( "farz", self.Dist ) self.flashlight:SetKeyValue( "nearz", 12 ) self.flashlight:SetKeyValue( "lightfov", self.FOV ) local c = self:GetColor() local b = self.Brightness self.flashlight:SetKeyValue( "lightcolor", Format( "%i %i %i 255", c.r * b, c.g * b, c.b * b ) ) self.flashlight:Spawn() self.flashlight:Input( "SpotlightTexture", NULL, NULL, self.Texture ) end function ENT:UpdateLight() self:SetColor( Color( self.r, self.g, self.b, self:GetColor().a ) ) if ( !IsValid( self.flashlight ) ) then return end self.flashlight:Input( "SpotlightTexture", NULL, NULL, self.Texture ) self.flashlight:Input( "FOV", NULL, NULL, tostring( self.FOV ) ) self.flashlight:SetKeyValue( "farz", self.Dist ) local c = self:GetColor() local b = self.Brightness self.flashlight:SetKeyValue( "lightcolor", Format( "%i %i %i 255", c.r*b, c.g*b, c.b*b ) ) self:SetOverlayText( "Red: " .. c.r .. " Green: " .. c.g .. " Blue: " .. c.b .. "\n" .. "FoV: " .. self.FOV .. " Distance: " .. self.Dist .. " Brightness: " .. self.Brightness ) end function ENT:Setup( r, g, b, Texture, fov, dist, brightness, on ) self.r, self.g, self.b = math.Clamp(r or 255,0,255), math.Clamp(g or 255,0,255), math.Clamp(b or 255,0,255) self.Texture = Texture or "effects/flashlight001" self.FOV = fov or 90 self.Dist = dist or 1024 self.Brightness = math.Clamp(brightness or 8,0,10) self.on = on or false self:Switch( self.on ) self:UpdateLight() end duplicator.RegisterEntityClass( "gmod_wire_lamp", WireLib.MakeWireEnt, "Data", "r", "g", "b", "Texture", "FOV", "Dist", "Brightness", "on" )
fixed color clamping 2
fixed color clamping 2
Lua
apache-2.0
garrysmodlua/wire,dvdvideo1234/wire,CaptainPRICE/wire,thegrb93/wire,notcake/wire,Python1320/wire,bigdogmat/wire,NezzKryptic/Wire,mms92/wire,Grocel/wire,plinkopenguin/wiremod,sammyt291/wire,rafradek/wire,immibis/wiremod,mitterdoo/wire,wiremod/wire
af5c9d4fb4d37b735e37835853da19ab90721d7e
applications/luci-app-openvpn/luasrc/model/cbi/openvpn.lua
applications/luci-app-openvpn/luasrc/model/cbi/openvpn.lua
-- Copyright 2008 Steven Barth <[email protected]> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local testfullps = luci.sys.exec("ps --help 2>&1 | grep BusyBox") --check which ps do we have local psstring = (string.len(testfullps)>0) and "ps w" or "ps axfw" --set command we use to get pid local m = Map("openvpn", translate("OpenVPN")) local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") ) s.template = "cbi/tblsection" s.template_addremove = "openvpn/cbi-select-input-add" s.addremove = true s.add_select_options = { } s.extedit = luci.dispatcher.build_url( "admin", "services", "openvpn", "basic", "%s" ) uci:load("openvpn_recipes") uci:foreach( "openvpn_recipes", "openvpn_recipe", function(section) s.add_select_options[section['.name']] = section['_description'] or section['.name'] end ) function s.parse(self, section) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) if recipe and not s.add_select_options[recipe] then self.invalid_cts = true else TypedSection.parse( self, section ) end end function s.create(self, name) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) name = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".text" ) if string.len(name)>3 and not name:match("[^a-zA-Z0-9_]") then uci:section( "openvpn", "openvpn", name, uci:get_all( "openvpn_recipes", recipe ) ) uci:delete("openvpn", name, "_role") uci:delete("openvpn", name, "_description") uci:save("openvpn") luci.http.redirect( self.extedit:format(name) ) else self.invalid_cts = true end end s:option( Flag, "enabled", translate("Enabled") ) local active = s:option( DummyValue, "_active", translate("Started") ) function active.cfgvalue(self, section) local pid = sys.exec("%s | grep %s | grep openvpn | grep -v grep | awk '{print $1}'" % { psstring,section} ) if pid and #pid > 0 and tonumber(pid) ~= nil then return (sys.process.signal(pid, 0)) and translatef("yes (%i)", pid) or translate("no") end return translate("no") end local updown = s:option( Button, "_updown", translate("Start/Stop") ) updown._state = false updown.redirect = luci.dispatcher.build_url( "admin", "services", "openvpn" ) function updown.cbid(self, section) local pid = sys.exec("%s | grep %s | grep openvpn | grep -v grep | awk '{print $1}'" % { psstring,section} ) self._state = pid and #pid > 0 and sys.process.signal(pid, 0) self.option = self._state and "stop" or "start" return AbstractValue.cbid(self, section) end function updown.cfgvalue(self, section) self.title = self._state and "stop" or "start" self.inputstyle = self._state and "reset" or "reload" end function updown.write(self, section, value) if self.option == "stop" then local pid = sys.exec("%s | grep %s | grep openvpn | grep -v grep | awk '{print $1}'" % { psstring,section} ) sys.process.signal(pid,15) else luci.sys.call("/etc/init.d/openvpn start %s" % section) end luci.http.redirect( self.redirect ) end local port = s:option( DummyValue, "port", translate("Port") ) function port.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) return val or "1194" end local proto = s:option( DummyValue, "proto", translate("Protocol") ) function proto.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) return val or "udp" end return m
-- Copyright 2008 Steven Barth <[email protected]> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local testfullps = luci.sys.exec("ps --help 2>&1 | grep BusyBox") --check which ps do we have local psstring = (string.len(testfullps)>0) and "ps w" or "ps axfw" --set command we use to get pid local m = Map("openvpn", translate("OpenVPN")) local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") ) s.template = "cbi/tblsection" s.template_addremove = "openvpn/cbi-select-input-add" s.addremove = true s.add_select_options = { } s.extedit = luci.dispatcher.build_url( "admin", "services", "openvpn", "basic", "%s" ) uci:load("openvpn_recipes") uci:foreach( "openvpn_recipes", "openvpn_recipe", function(section) s.add_select_options[section['.name']] = section['_description'] or section['.name'] end ) function s.getPID(section) return sys.exec("%s | grep -w %s | grep openvpn | grep -v grep | awk '{print $1}'" % { psstring,section} ) end function s.parse(self, section) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) if recipe and not s.add_select_options[recipe] then self.invalid_cts = true else TypedSection.parse( self, section ) end end function s.create(self, name) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) name = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".text" ) if string.len(name)>3 and not name:match("[^a-zA-Z0-9_]") then uci:section( "openvpn", "openvpn", name, uci:get_all( "openvpn_recipes", recipe ) ) uci:delete("openvpn", name, "_role") uci:delete("openvpn", name, "_description") uci:save("openvpn") luci.http.redirect( self.extedit:format(name) ) else self.invalid_cts = true end end s:option( Flag, "enabled", translate("Enabled") ) local active = s:option( DummyValue, "_active", translate("Started") ) function active.cfgvalue(self, section) local pid = s.getPID(section) if pid and #pid > 0 and tonumber(pid) ~= nil then return (sys.process.signal(pid, 0)) and translatef("yes (%i)", pid) or translate("no") end return translate("no") end local updown = s:option( Button, "_updown", translate("Start/Stop") ) updown._state = false updown.redirect = luci.dispatcher.build_url( "admin", "services", "openvpn" ) function updown.cbid(self, section) local pid = s.getPID(section) self._state = pid and #pid > 0 and sys.process.signal(pid, 0) self.option = self._state and "stop" or "start" return AbstractValue.cbid(self, section) end function updown.cfgvalue(self, section) self.title = self._state and "stop" or "start" self.inputstyle = self._state and "reset" or "reload" end function updown.write(self, section, value) if self.option == "stop" then local pid = s.getPID(section) sys.process.signal(pid,15) else luci.sys.call("/etc/init.d/openvpn start %s" % section) end luci.http.redirect( self.redirect ) end local port = s:option( DummyValue, "port", translate("Port") ) function port.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) return val or "1194" end local proto = s:option( DummyValue, "proto", translate("Protocol") ) function proto.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) return val or "udp" end return m
[luci-app-openvpn] Optimized code and added suggested fix from #650 Signed-off-by: Vladimir Ulrich <[email protected]>
[luci-app-openvpn] Optimized code and added suggested fix from #650 Signed-off-by: Vladimir Ulrich <[email protected]>
Lua
apache-2.0
Wedmer/luci,aa65535/luci,LuttyYang/luci,artynet/luci,wongsyrone/luci-1,bright-things/ionic-luci,cshore/luci,remakeelectric/luci,remakeelectric/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,wongsyrone/luci-1,tobiaswaldvogel/luci,cshore/luci,lbthomsen/openwrt-luci,LuttyYang/luci,ollie27/openwrt_luci,rogerpueyo/luci,tobiaswaldvogel/luci,Noltari/luci,remakeelectric/luci,rogerpueyo/luci,981213/luci-1,cappiewu/luci,openwrt-es/openwrt-luci,Wedmer/luci,mumuqz/luci,hnyman/luci,aa65535/luci,hnyman/luci,981213/luci-1,remakeelectric/luci,nmav/luci,teslamint/luci,taiha/luci,daofeng2015/luci,oneru/luci,kuoruan/luci,bittorf/luci,cshore/luci,hnyman/luci,teslamint/luci,981213/luci-1,teslamint/luci,jlopenwrtluci/luci,openwrt-es/openwrt-luci,981213/luci-1,chris5560/openwrt-luci,nmav/luci,mumuqz/luci,cappiewu/luci,teslamint/luci,LuttyYang/luci,cappiewu/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,ollie27/openwrt_luci,ollie27/openwrt_luci,teslamint/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,bright-things/ionic-luci,hnyman/luci,Wedmer/luci,taiha/luci,hnyman/luci,cappiewu/luci,kuoruan/luci,cappiewu/luci,Wedmer/luci,jlopenwrtluci/luci,openwrt/luci,bright-things/ionic-luci,rogerpueyo/luci,cshore/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,daofeng2015/luci,aa65535/luci,kuoruan/lede-luci,LuttyYang/luci,remakeelectric/luci,cshore-firmware/openwrt-luci,kuoruan/luci,openwrt/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,daofeng2015/luci,ollie27/openwrt_luci,mumuqz/luci,aa65535/luci,Noltari/luci,wongsyrone/luci-1,cshore/luci,rogerpueyo/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,LuttyYang/luci,chris5560/openwrt-luci,kuoruan/lede-luci,aa65535/luci,remakeelectric/luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,bright-things/ionic-luci,shangjiyu/luci-with-extra,remakeelectric/luci,Wedmer/luci,openwrt-es/openwrt-luci,cshore/luci,artynet/luci,oneru/luci,hnyman/luci,kuoruan/lede-luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,kuoruan/luci,oneru/luci,wongsyrone/luci-1,oneru/luci,artynet/luci,openwrt/luci,bittorf/luci,openwrt/luci,openwrt/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,mumuqz/luci,aa65535/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,rogerpueyo/luci,bittorf/luci,mumuqz/luci,kuoruan/luci,cshore/luci,lbthomsen/openwrt-luci,teslamint/luci,artynet/luci,rogerpueyo/luci,artynet/luci,rogerpueyo/luci,Noltari/luci,Noltari/luci,wongsyrone/luci-1,artynet/luci,nmav/luci,bittorf/luci,ollie27/openwrt_luci,mumuqz/luci,Noltari/luci,taiha/luci,Noltari/luci,tobiaswaldvogel/luci,jlopenwrtluci/luci,981213/luci-1,shangjiyu/luci-with-extra,nmav/luci,hnyman/luci,wongsyrone/luci-1,rogerpueyo/luci,daofeng2015/luci,kuoruan/lede-luci,taiha/luci,artynet/luci,nmav/luci,nmav/luci,cappiewu/luci,chris5560/openwrt-luci,taiha/luci,981213/luci-1,bittorf/luci,mumuqz/luci,daofeng2015/luci,cshore/luci,kuoruan/luci,nmav/luci,aa65535/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,LuttyYang/luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,openwrt/luci,bittorf/luci,LuttyYang/luci,oneru/luci,cappiewu/luci,teslamint/luci,teslamint/luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,remakeelectric/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,taiha/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,ollie27/openwrt_luci,LuttyYang/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,Wedmer/luci,wongsyrone/luci-1,cshore-firmware/openwrt-luci,artynet/luci,bittorf/luci,oneru/luci,wongsyrone/luci-1,taiha/luci,openwrt-es/openwrt-luci,oneru/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,chris5560/openwrt-luci,bright-things/ionic-luci,aa65535/luci,jlopenwrtluci/luci,cshore-firmware/openwrt-luci,Noltari/luci,jlopenwrtluci/luci,kuoruan/lede-luci,kuoruan/luci,981213/luci-1,nmav/luci,Noltari/luci,tobiaswaldvogel/luci,nmav/luci,Wedmer/luci,Noltari/luci,hnyman/luci,mumuqz/luci,taiha/luci,cappiewu/luci,kuoruan/luci,kuoruan/lede-luci,chris5560/openwrt-luci,daofeng2015/luci,bittorf/luci,daofeng2015/luci,daofeng2015/luci,openwrt/luci,oneru/luci,Wedmer/luci,artynet/luci
b3a8a78f01d894f8f4d735523e876a89871f313b
tests/gio.lua
tests/gio.lua
--[[-------------------------------------------------------------------------- LGI testsuite, GIo test suite. Copyright (c) 2016 Uli Schlachter Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- local type = type local lgi = require 'lgi' local core = require 'lgi.core' local check = testsuite.check local checkv = testsuite.checkv local gio = testsuite.group.new('gio') function gio.read() local GLib, Gio = lgi.GLib, lgi.Gio -- Prepare the input to read local input input = "line" input = Gio.MemoryInputStream.new_from_data(input) input = Gio.DataInputStream.new(input) local line, length -- Read line line, length = input:read_line() checkv(line, "line", "string") checkv(length, 4, "number") -- Read EOF line, length = input:read_line() checkv(line, nil, "nil") checkv(length, 0, "number") end function gio.async_access() -- Sometimes this hangs with LuaJIT when the JIT is on, no idea why. -- FIXME: Figure out what is going on and fix this. -- See also https://github.com/LuaJIT/LuaJIT/issues/340. if jit then jit.off() end local Gio = lgi.Gio local res res = Gio.DBusProxy.async_new check(res ~= nil) check(type(res) == 'function') res = Gio.DBusProxy.async_call check(res ~= nil) check(type(res) == 'function') res = Gio.async_bus_get check(res ~= nil) check(type(res) == 'function') local file = Gio.File.new_for_path('.') res = Gio.Async.call(function(target) return target:async_query_info('standard::size', 'NONE') end)(file) check(res ~= nil) local b = Gio.Async.call(function() return Gio.async_bus_get('SESSION') end)() check(Gio.DBusConnection:is_type_of(b)) local proxy = Gio.Async.call(function(bus) return Gio.DBusProxy.async_new( bus, 'NONE', nil, 'org.freedesktop.DBus', '/', 'org.freedesktop.DBus') end)(b) check(Gio.DBusProxy:is_type_of(proxy)) if jit then jit.on() end end
--[[-------------------------------------------------------------------------- LGI testsuite, GIo test suite. Copyright (c) 2016 Uli Schlachter Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- local type = type local lgi = require 'lgi' local core = require 'lgi.core' local check = testsuite.check local checkv = testsuite.checkv local gio = testsuite.group.new('gio') function gio.read() local GLib, Gio = lgi.GLib, lgi.Gio -- Prepare the input to read local input input = "line" input = Gio.MemoryInputStream.new_from_data(input) input = Gio.DataInputStream.new(input) local line, length -- Read line line, length = input:read_line() checkv(line, "line", "string") checkv(length, 4, "number") -- Read EOF line, length = input:read_line() checkv(line, nil, "nil") checkv(length, 0, "number") end function gio.async_access() local Gio = lgi.Gio local res res = Gio.DBusProxy.async_new check(res ~= nil) check(type(res) == 'function') res = Gio.DBusProxy.async_call check(res ~= nil) check(type(res) == 'function') res = Gio.async_bus_get check(res ~= nil) check(type(res) == 'function') local file = Gio.File.new_for_path('.') res = Gio.Async.call(function(target) return target:async_query_info('standard::size', 'NONE') end)(file) check(res ~= nil) local b = Gio.Async.call(function() return Gio.async_bus_get('SESSION') end)() check(Gio.DBusConnection:is_type_of(b)) local proxy = Gio.Async.call(function(bus) return Gio.DBusProxy.async_new( bus, 'NONE', nil, 'org.freedesktop.DBus', '/', 'org.freedesktop.DBus') end)(b) check(Gio.DBusProxy:is_type_of(proxy)) end
Revert "Work around a hang on LuaJIT"
Revert "Work around a hang on LuaJIT" This reverts commit 022c2fe4f8ec94d89358ef32466096ec92e53b71. It seems like the previous commit fixed this issue. Yay!
Lua
mit
psychon/lgi,pavouk/lgi
060f1068ac1627361afb76be03e86815e65c52e5
AceEvent-3.0/AceEvent-3.0.lua
AceEvent-3.0/AceEvent-3.0.lua
--- AceEvent-3.0 provides event registration and secure dispatching. -- All dispatching is done using **CallbackHandler-1.0**. AceEvent is a simple wrapper around -- CallbackHandler, and dispatches all game events or addon message to the registrees. -- -- **AceEvent-3.0** can be embeded into your addon, either explicitly by calling AceEvent:Embed(MyAddon) or by -- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object -- and can be accessed directly, without having to explicitly call AceEvent itself.\\ -- It is recommended to embed AceEvent, otherwise you'll have to specify a custom `self` on all calls you -- make into AceEvent. -- @class file -- @name AceEvent-3.0 -- @release $Id$ local MAJOR, MINOR = "AceEvent-3.0", 3 local AceEvent = LibStub:NewLibrary(MAJOR, MINOR) if not AceEvent then return end -- Lua APIs local pairs = pairs local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib -- APIs and registry for blizzard events, using CallbackHandler lib if not AceEvent.events then AceEvent.events = CallbackHandler:New(AceEvent, "RegisterEvent", "UnregisterEvent", "UnregisterAllEvents") end function AceEvent.events:OnUsed(target, eventname) AceEvent.frame:RegisterEvent(eventname) end function AceEvent.events:OnUnused(target, eventname) AceEvent.frame:UnregisterEvent(eventname) end -- APIs and registry for IPC messages, using CallbackHandler lib if not AceEvent.messages then AceEvent.messages = CallbackHandler:New(AceEvent, "RegisterMessage", "UnregisterMessage", "UnregisterAllMessages" ) AceEvent.SendMessage = AceEvent.messages.Fire end --- embedding and embed handling local mixins = { "RegisterEvent", "UnregisterEvent", "RegisterMessage", "UnregisterMessage", "SendMessage", "UnregisterAllEvents", "UnregisterAllMessages", } --- Register for a Blizzard Event. -- The callback will always be called with the event as the first argument, and if supplied, the `arg` as second argument. -- Any arguments to the event will be passed on after that. -- @name AceEvent:RegisterEvent -- @class function -- @paramsig event[, callback [, arg]] -- @param event The event to register for -- @param callback The callback function to call when the event is triggered (funcref or method, defaults to a method with the event name) -- @param arg An optional argument to pass to the callback function --- Unregister an event. -- @name AceEvent:UnregisterEvent -- @class function -- @paramsig event -- @param event The event to unregister --- Register for a custom AceEvent-internal message. -- The callback will always be called with the event as the first argument, and if supplied, the `arg` as second argument. -- Any arguments to the event will be passed on after that. -- @name AceEvent:RegisterMessage -- @class function -- @paramsig message[, callback [, arg]] -- @param message The message to register for -- @param callback The callback function to call when the message is triggered (funcref or method, defaults to a method with the event name) -- @param arg An optional argument to pass to the callback function --- Unregister a message -- @name AceEvent:UnregisterMessage -- @class function -- @paramsig message -- @param message The message to unregister --- Send a message over the AceEvent-3.0 internal message system to other addons registered for this message. -- @name AceEvent:SendMessage -- @class function -- @paramsig message, ... -- @param message The message to send -- @param ... Any arguments to the message -- Embeds AceEvent into the target object making the functions from the mixins list available on target:.. -- @param target target object to embed AceEvent in function AceEvent:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true return target end -- AceEvent:OnEmbedDisable( target ) -- target (object) - target object that is being disabled -- -- Unregister all events messages etc when the target disables. -- this method should be called by the target manually or by an addon framework function AceEvent:OnEmbedDisable(target) target:UnregisterAllEvents() target:UnregisterAllMessages() end -- Script to fire blizzard events into the event listeners local events = AceEvent.events AceEvent.frame:SetScript("OnEvent", function(this, event, ...) events:Fire(event, ...) end) --- Finally: upgrade our old embeds for target, v in pairs(AceEvent.embeds) do AceEvent:Embed(target) end
--- AceEvent-3.0 provides event registration and secure dispatching. -- All dispatching is done using **CallbackHandler-1.0**. AceEvent is a simple wrapper around -- CallbackHandler, and dispatches all game events or addon message to the registrees. -- -- **AceEvent-3.0** can be embeded into your addon, either explicitly by calling AceEvent:Embed(MyAddon) or by -- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object -- and can be accessed directly, without having to explicitly call AceEvent itself.\\ -- It is recommended to embed AceEvent, otherwise you'll have to specify a custom `self` on all calls you -- make into AceEvent. -- @class file -- @name AceEvent-3.0 -- @release $Id$ local MAJOR, MINOR = "AceEvent-3.0", 3 local AceEvent = LibStub:NewLibrary(MAJOR, MINOR) if not AceEvent then return end -- Lua APIs local pairs = pairs local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib -- APIs and registry for blizzard events, using CallbackHandler lib if not AceEvent.events then AceEvent.events = CallbackHandler:New(AceEvent, "RegisterEvent", "UnregisterEvent", "UnregisterAllEvents") end function AceEvent.events:OnUsed(target, eventname) AceEvent.frame:RegisterEvent(eventname) end function AceEvent.events:OnUnused(target, eventname) AceEvent.frame:UnregisterEvent(eventname) end -- APIs and registry for IPC messages, using CallbackHandler lib if not AceEvent.messages then AceEvent.messages = CallbackHandler:New(AceEvent, "RegisterMessage", "UnregisterMessage", "UnregisterAllMessages" ) AceEvent.SendMessage = AceEvent.messages.Fire end --- embedding and embed handling local mixins = { "RegisterEvent", "UnregisterEvent", "RegisterMessage", "UnregisterMessage", "SendMessage", "UnregisterAllEvents", "UnregisterAllMessages", } --- Register for a Blizzard Event. -- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied) -- Any arguments to the event will be passed on after that. -- @name AceEvent:RegisterEvent -- @class function -- @paramsig event[, callback [, arg]] -- @param event The event to register for -- @param callback The callback function to call when the event is triggered (funcref or method, defaults to a method with the event name) -- @param arg An optional argument to pass to the callback function --- Unregister an event. -- @name AceEvent:UnregisterEvent -- @class function -- @paramsig event -- @param event The event to unregister --- Register for a custom AceEvent-internal message. -- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied) -- Any arguments to the event will be passed on after that. -- @name AceEvent:RegisterMessage -- @class function -- @paramsig message[, callback [, arg]] -- @param message The message to register for -- @param callback The callback function to call when the message is triggered (funcref or method, defaults to a method with the event name) -- @param arg An optional argument to pass to the callback function --- Unregister a message -- @name AceEvent:UnregisterMessage -- @class function -- @paramsig message -- @param message The message to unregister --- Send a message over the AceEvent-3.0 internal message system to other addons registered for this message. -- @name AceEvent:SendMessage -- @class function -- @paramsig message, ... -- @param message The message to send -- @param ... Any arguments to the message -- Embeds AceEvent into the target object making the functions from the mixins list available on target:.. -- @param target target object to embed AceEvent in function AceEvent:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true return target end -- AceEvent:OnEmbedDisable( target ) -- target (object) - target object that is being disabled -- -- Unregister all events messages etc when the target disables. -- this method should be called by the target manually or by an addon framework function AceEvent:OnEmbedDisable(target) target:UnregisterAllEvents() target:UnregisterAllMessages() end -- Script to fire blizzard events into the event listeners local events = AceEvent.events AceEvent.frame:SetScript("OnEvent", function(this, event, ...) events:Fire(event, ...) end) --- Finally: upgrade our old embeds for target, v in pairs(AceEvent.embeds) do AceEvent:Embed(target) end
AceEvent-3.0: Fix documentation
AceEvent-3.0: Fix documentation git-svn-id: e768786be8df873dac9515156656ebbdc6d77160@975 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
78c8557abcb9bcfaf84f18a5a61570b7bd8c8fa2
examples/controllers/main.lua
examples/controllers/main.lua
-- Vibrates controllers when their triggers are pressed, draws 3D -- models for each controller, and keeps track of controllers when -- they are connected and disconnected. local controllerModels = {} function lovr.load() print('There are ' .. lovr.headset.getControllerCount() .. ' controllers.') end function lovr.update(dt) local controllers = lovr.headset.getControllers() for i, controller in ipairs(controllers) do if controller:getAxis('trigger') > .5 then controller:vibrate(.0035) end end end function lovr.draw() for controller, model in pairs(controllerModels) do local x, y, z = controller:getPosition() local angle, axisX, axisY, axisZ = controller:getOrientation() model:draw(x, y, z, 1, -angle, axisX, axisY, axisZ) end end function lovr.controlleradded(controller) print('A controller was connected!') controllerModels[controller] = controller:newModel() end function lovr.controllerremoved(controller) print('A controller was disconnected!') controllerModels[controller] = nil end
-- Vibrates controllers when their triggers are pressed, draws 3D -- models for each controller, and keeps track of controllers when -- they are connected and disconnected. local controllerModels = {} function lovr.load() print('There are ' .. lovr.headset.getControllerCount() .. ' controllers.') end function lovr.update(dt) local controllers = lovr.headset.getControllers() for i, controller in ipairs(controllers) do if controller:getAxis('trigger') > .5 then controller:vibrate(.0035) end end end function lovr.draw() for controller, model in pairs(controllerModels) do local x, y, z = controller:getPosition() model:draw(x, y, z, 1, controller:getOrientation()) end end function lovr.controlleradded(controller) print('A controller was connected!') controllerModels[controller] = controller:newModel() end function lovr.controllerremoved(controller) print('A controller was disconnected!') controllerModels[controller] = nil end
Fix controllers example;
Fix controllers example;
Lua
mit
bjornbytes/lovr,bjornbytes/lovr,bjornbytes/lovr,bjornbytes/lovr,bjornbytes/lovr
d634e63c2902a3589c1750c1bddd900f22439941
FabFileConverter/res/drl.lua
FabFileConverter/res/drl.lua
drl_lines = {} drl_tool_colors = {} function addColor(rgb) drl_tool_colors[#drl_tool_colors + 1] = rgb end addColor(RGB(255,0,0)) addColor(RGB(0,255,0)) addColor(RGB(0,0,255)) addColor(RGB(255,255,0)) addColor(RGB(0,255,255)) addColor(RGB(255,0,255)) addColor(RGB(255,255,255)) function drl_g_drawArc(x,y,diameter,rgb) drl_setXY(x,y) drl_setRGB(rgb.r,rgb.g,rgb.b) drl_drawArc(diameter) end function drl_g_drawLine(x1,y1,x2,y2,rgb) drl_setXY(x1,y1) drl_setRGB(rgb.r,rgb.g,rgb.b) drl_drawLine(x2,y2) end drl_d_font = "Arial" function drl_g_placeText(x,y,text,size,fontName,rgb) if b then drl_setRGB(rgb.r,rgb.g,rgb.b) drl_setXY(x,y) drl_placeText(text,size,fontName) else drl_setXY(x,y) drl_setRGB(fontName.r,fontName.r,fontName.g) drl_placeText(text,size,drl_d_font) end end local xyMatch = "^X(.-)Y(.-)$" local xMatch = "^X(.-)$" local yMatch = "^Y(.-)$" local toolMatch = "^T(.-)C(.-)$" local toolSelectMatch = "^T([0-9][0-9])$" local formatMatch = "^(.-),(.-)Z$" local fmatMatch = "^FMAT,(.-)$" local last = {} last.x = 0 last.y = 0 local drl_points = {} local drl_tools = {} local currentTool = nil local currentFormat = "" local drl_fileName = "" local multForMinor = 100 function drl_frame_render() local minX = 0 local minY = 0 local maxX = 0 local maxY = 0 local xoy = 0 for index, point in pairs(drl_points) do if(point.x > maxX) then maxX = point.x elseif (point.x < minX) then minX = point.x end if(point.y > maxY) then maxY = point.y elseif (point.y < minY) then minY = point.Y end end local xScale = drl_frame_width / (maxX + minX); local yScale = drl_frame_height / (maxY + minY); local scale = 0; if (xScale > yScale) then scale = yScale; elseif (yScale > xScale) then scale = xScale; elseif (xScale == yScale) then scale = xScale; end drl_setXY(0,0) drl_setRGB(0,0,0) drl_drawRect(drl_frame_width,drl_frame_height) local lastX = 0 local lastY = 0 local toolSize = 0 for index, point in pairs(drl_points) do toolSize = point.tool.size * (math.pow(10,multForMinor)) * scale if #drl_tool_colors < tonumber(point.tool.index) then drl_g_drawArc((point.x * scale) - (toolSize / 2), (point.y * scale) - (toolSize / 2), toolSize, RGB(255,255,255)) else drl_g_drawArc((point.x * scale) - (toolSize / 2), (point.y * scale) - (toolSize / 2), toolSize, drl_tool_colors[point.tool.index]) end drl_g_drawLine(lastX, lastY, (point.x * scale) - (toolSize / 2) * scale, (point.y * scale) - (toolSize / 2) * scale, RGB(255,255,255)) lastX = (point.x * scale) - (toolSize / 2) * scale lastY = (point.y * scale) - (toolSize / 2) * scale end end function drl_frame_resize(width,height) end function Tool(format, size, index, sSize) if format and size then local tool = Class("Tool") tool.format = format tool.size = size tool.index = tonumber(index) tool.sSize = sSize return tool else error("No format and/or size defined") return nil end end function Point(x,y,t) if x and y and t then local point = Class("Point") point.x = tonumber(x) point.y = tonumber(y) point.tool = t return point else error("No x and/or y and/or t is defined.") return nil end end function drl_convert() print("Converting ...") local currentTool = nil drl_openFile() drl_writeLine("M72\nM48") for index, tool in pairs(drl_tools) do local i = "" if string.len(tostring(tool.index)) < 2 then i = i .. "0" end drl_writeLine("T" .. i .. tool.index .. "C" .. tool.sSize) end drl_writeLine("%") for index, point in pairs(drl_points) do if point.tool == currentTool then else local i = "" if string.len(tostring(point.tool.index)) < 2 then i = i .. "0" end drl_writeLine("T" .. i .. point.tool.index) currentTool = point.tool end drl_writeLine("X" .. point.x .. "Y" .. point.y) end drl_writeLine("M30") drl_closeFile() print("Done.") end function drl_parseLine(line) if(string.match(line, xyMatch)) then local x,y = string.match(line, xyMatch) last.x = tonumber(x) last.y = tonumber(y) drl_points[#drl_points + 1] = Point(last.x,last.y,drl_tools[currentTool]) elseif(string.match(line,xMatch)) then local x = string.match(line, xMatch) last.x = tonumber(x) drl_points[#drl_points + 1] = Point(x,last.y,drl_tools[currentTool]) elseif(string.match(line,yMatch)) then local y = string.match(line, yMatch) last.y = tonumber(y) drl_points[#drl_points + 1] = Point(last.x,y,drl_tools[currentTool]) elseif(string.match(line, toolMatch)) then local tNum, tSize = string.match(line, toolMatch) print(tNum, " ", tSize) drl_tools[tonumber(tNum)] = Tool(currentFormat, tonumber(tSize), tNum, tSize) elseif(string.match(line, formatMatch)) then local formatType, mode = string.match(line, formatMatch) if(formatType == "INCH") then --TODO: add meters as optoin if mode == "T" then else error("File is not correctly exported. Please export with ' Supress Leading Zero's '") end currentFormat = Formats["Inch"] end elseif(string.match(line, fmatMatch)) then multForMinor = tonumber(string.match(line,fmatMatch)) + 1 elseif(string.match(line, toolSelectMatch)) then currentTool = tonumber(string.match(line, toolSelectMatch)) end end function drl_read(content, fileName) drl_fileName = fileName local tbl = split(content, "\n") for _,line in pairs(tbl) do drl_lines[#drl_lines + 1] = line drl_parseLine(line) end end function drl_preview() SYS_clearTextArea() SYS_textAreaAddLine("File: " .. drl_fileName) SYS_textAreaAddLine("") SYS_textAreaAddLine("Found tools: [" .. #drl_tools .. "]: ") SYS_textAreaAddLine("") for index,tool in pairs(drl_tools) do SYS_textAreaAddLine(" [" .. index .."] - Size: " .. tool.size .. tool.format.Major.Ending) end SYS_textAreaAddLine("") SYS_textAreaAddLine("Found drill points [" .. #drl_points .. "]: ") for index,point in pairs(drl_points) do SYS_textAreaAddLine(" X: " .. point.x .. " Y: " .. point.y) end SYS_textAreaScrollTop() end local request = true function drl_show() if request then request = false drl_requestFrame("drl_frame_render", "drl_frame_resize", "Drill preview") drl_frame_setVisible(true) drl_frame_update() end end RegisterConverter("drl", "^[dL][rR][lL]$", "ock")
drl_lines = {} drl_tool_colors = {} function addColor(rgb) drl_tool_colors[#drl_tool_colors + 1] = rgb end addColor(RGB(255,0,0)) addColor(RGB(0,255,0)) addColor(RGB(0,0,255)) addColor(RGB(255,255,0)) addColor(RGB(0,255,255)) addColor(RGB(255,0,255)) addColor(RGB(255,255,255)) function drl_g_drawArc(x,y,diameter,rgb) drl_setXY(x,y) drl_setRGB(rgb.r,rgb.g,rgb.b) drl_drawArc(diameter) end function drl_g_drawLine(x1,y1,x2,y2,rgb) drl_setXY(x1,y1) drl_setRGB(rgb.r,rgb.g,rgb.b) drl_drawLine(x2,y2) end drl_d_font = "Arial" function drl_g_placeText(x,y,text,size,fontName,rgb) if b then drl_setRGB(rgb.r,rgb.g,rgb.b) drl_setXY(x,y) drl_placeText(text,size,fontName) else drl_setXY(x,y) drl_setRGB(fontName.r,fontName.r,fontName.g) drl_placeText(text,size,drl_d_font) end end local xyMatch = "^X(.-)Y(.-)$" local xMatch = "^X(.-)$" local yMatch = "^Y(.-)$" local toolMatch = "^T(.-)C(.-)$" local toolSelectMatch = "^T([0-9][0-9])$" local formatMatch = "^(.-),(.-)Z$" local fmatMatch = "^FMAT,(.-)$" local last = {} last.x = 0 last.y = 0 local drl_points = {} local drl_tools = {} local currentTool = nil local currentFormat = "" local drl_fileName = "" local multForMinor = 100 function drl_frame_render() local minX = 0 local minY = 0 local maxX = 0 local maxY = 0 local xoy = 0 for index, point in pairs(drl_points) do if(point.x > maxX) then maxX = point.x elseif (point.x < minX) then minX = point.x end if(point.y > maxY) then maxY = point.y elseif (point.y < minY) then minY = point.Y end end local xScale = drl_frame_width / (maxX + minX); local yScale = drl_frame_height / (maxY + minY); local scale = 0; if (xScale > yScale) then scale = yScale; elseif (yScale > xScale) then scale = xScale; elseif (xScale == yScale) then scale = xScale; end drl_setXY(0,0) drl_setRGB(0,0,0) drl_drawRect(drl_frame_width,drl_frame_height) local lastX = 0 local lastY = 0 local toolSize = 0 for index, point in pairs(drl_points) do toolSize = point.tool.size * (math.pow(10,multForMinor)) * scale if #drl_tool_colors < tonumber(point.tool.index) then drl_g_drawArc((point.x * scale) - (toolSize / 2), (point.y * scale) - (toolSize / 2), toolSize, RGB(255,255,255)) else drl_g_drawArc((point.x * scale) - (toolSize / 2), (point.y * scale) - (toolSize / 2), toolSize, drl_tool_colors[point.tool.index]) end drl_g_drawLine(lastX, lastY, (point.x * scale) - (toolSize / 2) * scale, (point.y * scale) - (toolSize / 2) * scale, RGB(255,255,255)) lastX = (point.x * scale) - (toolSize / 2) * scale lastY = (point.y * scale) - (toolSize / 2) * scale end end function drl_frame_resize(width,height) end function Tool(format, size, index, sSize) --sSize is the size written in the file so for example: "0.0300" if format and size and index and sSize then local tool = Class("Tool") tool.format = format tool.size = size tool.index = tonumber(index) tool.sSize = sSize return tool else error("No format and/or size and/or index and/or sSize defined") return nil end end function Point(x,y,t) if x and y and t then local point = Class("Point") point.x = tonumber(x) point.y = tonumber(y) point.tool = t return point else error("No x and/or y and/or t is defined.") return nil end end function drl_convert() print("Converting ...") local currentTool = nil drl_openFile() drl_writeLine("M72\nM48") for index, tool in pairs(drl_tools) do local i = "" if string.len(tostring(tool.index)) < 2 then i = i .. "0" end drl_writeLine("T" .. i .. tool.index .. "C" .. tool.sSize) end drl_writeLine("%") for index, point in pairs(drl_points) do if point.tool == currentTool then else local i = "" if string.len(tostring(point.tool.index)) < 2 then i = i .. "0" end drl_writeLine("T" .. i .. point.tool.index) currentTool = point.tool end drl_writeLine("X" .. point.x .. "Y" .. point.y) end drl_writeLine("M30") drl_closeFile() print("Done.") end function drl_parseLine(line) if(string.match(line, xyMatch)) then local x,y = string.match(line, xyMatch) last.x = tonumber(x) last.y = tonumber(y) drl_points[#drl_points + 1] = Point(last.x,last.y,drl_tools[currentTool]) elseif(string.match(line,xMatch)) then local x = string.match(line, xMatch) last.x = tonumber(x) drl_points[#drl_points + 1] = Point(x,last.y,drl_tools[currentTool]) elseif(string.match(line,yMatch)) then local y = string.match(line, yMatch) last.y = tonumber(y) drl_points[#drl_points + 1] = Point(last.x,y,drl_tools[currentTool]) elseif(string.match(line, toolMatch)) then local tNum, tSize = string.match(line, toolMatch) print(tNum, " ", tSize) drl_tools[tonumber(tNum)] = Tool(currentFormat, tonumber(tSize), tNum, tSize) elseif(string.match(line, formatMatch)) then local formatType, mode = string.match(line, formatMatch) if(formatType == "INCH") then --TODO: add meters as optoin if mode == "T" then else error("File is not correctly exported. Please export with ' Supress Leading Zero's '") end currentFormat = Formats["Inch"] end elseif(string.match(line, fmatMatch)) then multForMinor = tonumber(string.match(line,fmatMatch)) + 1 elseif(string.match(line, toolSelectMatch)) then currentTool = tonumber(string.match(line, toolSelectMatch)) end end function drl_read(content, fileName) drl_fileName = fileName local tbl = split(content, "\n") for _,line in pairs(tbl) do drl_lines[#drl_lines + 1] = line drl_parseLine(line) end end function drl_preview() SYS_clearTextArea() SYS_textAreaAddLine("File: " .. drl_fileName) SYS_textAreaAddLine("") SYS_textAreaAddLine("Found tools: [" .. #drl_tools .. "]: ") SYS_textAreaAddLine("") for index,tool in pairs(drl_tools) do SYS_textAreaAddLine(" [" .. index .."] - Size: " .. tool.size .. tool.format.Major.Ending) end SYS_textAreaAddLine("") SYS_textAreaAddLine("Found drill points [" .. #drl_points .. "]: ") for index,point in pairs(drl_points) do SYS_textAreaAddLine(" X: " .. point.x .. " Y: " .. point.y) end SYS_textAreaScrollTop() end local request = true function drl_show() if request then request = false drl_requestFrame("drl_frame_render", "drl_frame_resize", "Drill preview") drl_frame_setVisible(true) drl_frame_update() end end RegisterConverter("drl", "^[dL][rR][lL]$", "ock")
Fixed some potential issues
Fixed some potential issues
Lua
mit
DeltaCore/FabFileConverter
46a3cd2a3f9b18a6f3e8342d2464bf825dba3a3e
plugins/mod_register.lua
plugins/mod_register.lua
-- Prosody IM v0.4 -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local datamanager_store = require "util.datamanager".store; local os_time = os.time; module:add_feature("jabber:iq:register"); module:add_iq_handler("c2s", "jabber:iq:register", function (session, stanza) if stanza.tags[1].name == "query" then local query = stanza.tags[1]; if stanza.attr.type == "get" then local reply = st.reply(stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("registered"):up() :tag("username"):text(session.username):up() :tag("password"):up(); session.send(reply); elseif stanza.attr.type == "set" then if query.tags[1] and query.tags[1].name == "remove" then -- TODO delete user auth data, send iq response, kick all user resources with a <not-authorized/>, delete all user data local username, host = session.username, session.host; --session.send(st.error_reply(stanza, "cancel", "not-allowed")); --return; usermanager_create_user(username, nil, host); -- Disable account -- FIXME the disabling currently allows a different user to recreate the account -- we should add an in-memory account block mode when we have threading session.send(st.reply(stanza)); local roster = session.roster; for _, session in pairs(hosts[host].sessions[username].sessions) do -- disconnect all resources session:close({condition = "not-authorized", text = "Account deleted"}); end -- TODO datamanager should be able to delete all user data itself datamanager.store(username, host, "roster", nil); datamanager.store(username, host, "vcard", nil); datamanager.store(username, host, "private", nil); datamanager.store(username, host, "offline", nil); --local bare = username.."@"..host; for jid, item in pairs(roster) do if jid ~= "pending" then if item.subscription == "both" or item.subscription == "to" then -- TODO unsubscribe end if item.subscription == "both" or item.subscription == "from" then -- TODO unsubscribe end end end datamanager.store(username, host, "accounts", nil); -- delete accounts datastore at the end else local username = query:child_with_name("username"); local password = query:child_with_name("password"); if username and password then -- FIXME shouldn't use table.concat username = table.concat(username); password = table.concat(password); if username == session.username then if usermanager_create_user(username, password, session.host) then -- password change -- TODO is this the right way? session.send(st.reply(stanza)); else -- TODO unable to write file, file may be locked, etc, what's the correct error? session.send(st.error_reply(stanza, "wait", "internal-server-error")); end else session.send(st.error_reply(stanza, "modify", "bad-request")); end else session.send(st.error_reply(stanza, "modify", "bad-request")); end end end else session.send(st.error_reply(stanza, "cancel", "service-unavailable")); end; end); local recent_ips = {}; local min_seconds_between_registrations = config.get(module.host, "core", "min_seconds_between_registrations"); local whitelist_only = config.get(module.host, "core", "whitelist_registration_only"); local whitelisted_ips = config.get(module.host, "core", "registration_whitelist") or { "127.0.0.1" }; local blacklisted_ips = config.get(module.host, "core", "registration_blacklist") or {}; for _, ip in ipairs(whitelisted_ips) do whitelisted_ips[ip] = true; end for _, ip in ipairs(blacklisted_ips) do blacklisted_ips[ip] = true; end module:add_iq_handler("c2s_unauthed", "jabber:iq:register", function (session, stanza) if config.get(module.host, "core", "allow_registration") == false then session.send(st.error_reply(stanza, "cancel", "service-unavailable")); elseif stanza.tags[1].name == "query" then local query = stanza.tags[1]; if stanza.attr.type == "get" then local reply = st.reply(stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("instructions"):text("Choose a username and password for use with this service."):up() :tag("username"):up() :tag("password"):up(); session.send(reply); elseif stanza.attr.type == "set" then if query.tags[1] and query.tags[1].name == "remove" then session.send(st.error_reply(stanza, "auth", "registration-required")); else local username = query:child_with_name("username"); local password = query:child_with_name("password"); if username and password then -- Check that the user is not blacklisted or registering too often if blacklisted_ips[session.ip] or (whitelist_only and not whitelisted_ips[session.ip]) then session.send(st.error_reply(stanza, "cancel", "not-acceptable")); return; elseif min_seconds_between_registrations and not whitelisted_ips[session.ip] then if not recent_ips[session.ip] then recent_ips[session.ip] = { time = os_time(), count = 1 }; else local ip = recent_ips[session.ip]; ip.count = ip.count + 1; if os_time() - ip.time < min_seconds_between_registrations then ip.time = os_time(); session.send(st.error_reply(stanza, "cancel", "not-acceptable")); return; end ip.time = os_time(); end end -- FIXME shouldn't use table.concat username = table.concat(username); password = table.concat(password); if usermanager_user_exists(username, session.host) then session.send(st.error_reply(stanza, "cancel", "conflict")); else if usermanager_create_user(username, password, session.host) then session.send(st.reply(stanza)); -- user created! else -- TODO unable to write file, file may be locked, etc, what's the correct error? session.send(st.error_reply(stanza, "wait", "internal-server-error")); end end else session.send(st.error_reply(stanza, "modify", "not-acceptable")); end end end else session.send(st.error_reply(stanza, "cancel", "service-unavailable")); end; end);
-- Prosody IM v0.4 -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local datamanager_store = require "util.datamanager".store; local os_time = os.time; local nodeprep = require "util.encodings".stringprep.nodeprep; module:add_feature("jabber:iq:register"); module:add_iq_handler("c2s", "jabber:iq:register", function (session, stanza) if stanza.tags[1].name == "query" then local query = stanza.tags[1]; if stanza.attr.type == "get" then local reply = st.reply(stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("registered"):up() :tag("username"):text(session.username):up() :tag("password"):up(); session.send(reply); elseif stanza.attr.type == "set" then if query.tags[1] and query.tags[1].name == "remove" then -- TODO delete user auth data, send iq response, kick all user resources with a <not-authorized/>, delete all user data local username, host = session.username, session.host; --session.send(st.error_reply(stanza, "cancel", "not-allowed")); --return; usermanager_create_user(username, nil, host); -- Disable account -- FIXME the disabling currently allows a different user to recreate the account -- we should add an in-memory account block mode when we have threading session.send(st.reply(stanza)); local roster = session.roster; for _, session in pairs(hosts[host].sessions[username].sessions) do -- disconnect all resources session:close({condition = "not-authorized", text = "Account deleted"}); end -- TODO datamanager should be able to delete all user data itself datamanager.store(username, host, "roster", nil); datamanager.store(username, host, "vcard", nil); datamanager.store(username, host, "private", nil); datamanager.store(username, host, "offline", nil); --local bare = username.."@"..host; for jid, item in pairs(roster) do if jid ~= "pending" then if item.subscription == "both" or item.subscription == "to" then -- TODO unsubscribe end if item.subscription == "both" or item.subscription == "from" then -- TODO unsubscribe end end end datamanager.store(username, host, "accounts", nil); -- delete accounts datastore at the end else local username = query:child_with_name("username"); local password = query:child_with_name("password"); if username and password then -- FIXME shouldn't use table.concat username = nodeprep(table.concat(username)); password = table.concat(password); if username == session.username then if usermanager_create_user(username, password, session.host) then -- password change -- TODO is this the right way? session.send(st.reply(stanza)); else -- TODO unable to write file, file may be locked, etc, what's the correct error? session.send(st.error_reply(stanza, "wait", "internal-server-error")); end else session.send(st.error_reply(stanza, "modify", "bad-request")); end else session.send(st.error_reply(stanza, "modify", "bad-request")); end end end else session.send(st.error_reply(stanza, "cancel", "service-unavailable")); end; end); local recent_ips = {}; local min_seconds_between_registrations = config.get(module.host, "core", "min_seconds_between_registrations"); local whitelist_only = config.get(module.host, "core", "whitelist_registration_only"); local whitelisted_ips = config.get(module.host, "core", "registration_whitelist") or { "127.0.0.1" }; local blacklisted_ips = config.get(module.host, "core", "registration_blacklist") or {}; for _, ip in ipairs(whitelisted_ips) do whitelisted_ips[ip] = true; end for _, ip in ipairs(blacklisted_ips) do blacklisted_ips[ip] = true; end module:add_iq_handler("c2s_unauthed", "jabber:iq:register", function (session, stanza) if config.get(module.host, "core", "allow_registration") == false then session.send(st.error_reply(stanza, "cancel", "service-unavailable")); elseif stanza.tags[1].name == "query" then local query = stanza.tags[1]; if stanza.attr.type == "get" then local reply = st.reply(stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("instructions"):text("Choose a username and password for use with this service."):up() :tag("username"):up() :tag("password"):up(); session.send(reply); elseif stanza.attr.type == "set" then if query.tags[1] and query.tags[1].name == "remove" then session.send(st.error_reply(stanza, "auth", "registration-required")); else local username = query:child_with_name("username"); local password = query:child_with_name("password"); if username and password then -- Check that the user is not blacklisted or registering too often if blacklisted_ips[session.ip] or (whitelist_only and not whitelisted_ips[session.ip]) then session.send(st.error_reply(stanza, "cancel", "not-acceptable")); return; elseif min_seconds_between_registrations and not whitelisted_ips[session.ip] then if not recent_ips[session.ip] then recent_ips[session.ip] = { time = os_time(), count = 1 }; else local ip = recent_ips[session.ip]; ip.count = ip.count + 1; if os_time() - ip.time < min_seconds_between_registrations then ip.time = os_time(); session.send(st.error_reply(stanza, "cancel", "not-acceptable")); return; end ip.time = os_time(); end end -- FIXME shouldn't use table.concat username = nodeprep(table.concat(username)); password = table.concat(password); if usermanager_user_exists(username, session.host) then session.send(st.error_reply(stanza, "cancel", "conflict")); else if usermanager_create_user(username, password, session.host) then session.send(st.reply(stanza)); -- user created! else -- TODO unable to write file, file may be locked, etc, what's the correct error? session.send(st.error_reply(stanza, "wait", "internal-server-error")); end end else session.send(st.error_reply(stanza, "modify", "not-acceptable")); end end end else session.send(st.error_reply(stanza, "cancel", "service-unavailable")); end; end);
Fixed: mod_register: Node prepping was not being applied to usernames (part of issue #57)
Fixed: mod_register: Node prepping was not being applied to usernames (part of issue #57)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
1592986f17e0693bbaea9ec2995b2d2d18aca661
vanilla/v/request.lua
vanilla/v/request.lua
-- perf local error = error local pairs = pairs local setmetatable = setmetatable local Request = {} function Request:new() ngx.req.read_body() local params = ngx.req.get_uri_args() for k,v in pairs(ngx.req.get_post_args()) do params[k] = v end local instance = { uri = ngx.var.uri, req_uri = ngx.var.request_uri, req_args = ngx.var.args, params = params, uri_args = ngx.req.get_uri_args(), method = ngx.req.get_method(), headers = ngx.req.get_headers(), body_raw = ngx.req.get_body_data() } setmetatable(instance, {__index = self}) return instance end function Request:getControllerName() return self.controller_name end function Request:getActionName() return self.action_name end function Request:getHeaders() return self.headers end function Request:getHeader(key) if self.headers[key] ~= nil then return self.headers[key] else return false end end function Request:getParams() return self.params end function Request:getParam(key) return self.params[key] end function Request:setParam(key, value) self.params[key] = value end function Request:getMethod() return self.method end function Request:isGet() if self.method == 'GET' then return true else return false end end return Request
-- perf local error = error local pairs = pairs local setmetatable = setmetatable local sfind = string.find local Request = {} function Request:new() local params = {} -- body params local headers = ngx.req.get_headers() local header = headers['Content-Type'] if header then local is_multipart = sfind(header, "multipart") if is_multipart and is_multipart>0 then -- upload request, should not invoke ngx.req.read_body() else ngx.req.read_body() local post_args = ngx.req.get_post_args() if post_args and type(post_args) == "table" then for k,v in pairs(post_args) do params[k] = v end end end else ngx.req.read_body() local post_args = ngx.req.get_post_args() if post_args and type(post_args) == "table" then for k,v in pairs(post_args) do params[k] = v end end end local instance = { uri = ngx.var.uri, req_uri = ngx.var.request_uri, req_args = ngx.var.args, params = params, uri_args = ngx.req.get_uri_args(), method = ngx.req.get_method(), headers = headers, body_raw = ngx.req.get_body_data() } setmetatable(instance, {__index = self}) return instance end function Request:getControllerName() return self.controller_name end function Request:getActionName() return self.action_name end function Request:getHeaders() return self.headers end function Request:getHeader(key) if self.headers[key] ~= nil then return self.headers[key] else return false end end function Request:getParams() return self.params end function Request:getParam(key) return self.params[key] end function Request:setParam(key, value) self.params[key] = value end function Request:getMethod() return self.method end function Request:isGet() if self.method == 'GET' then return true else return false end end return Request
Fix resty.upload issue
Fix resty.upload issue when use lua-resty-upload , ngx.req.read_body() should not be used
Lua
mit
lhmwzy/vanilla,lhmwzy/vanilla,lhmwzy/vanilla,lhmwzy/vanilla
e6fdff18688ad0250467a27af708734114296fe2
src/soul.lua
src/soul.lua
local soul = {} local conversation = require("conversation") local utils = require("utils") local lfs = require("lfs") commands = {} for file in lfs.dir("commands") do local command = file:match("^(.+).lua") if (command) then local path = "commands." .. command package.loaded[path] = nil local status, ret = pcall(require, path) if (status) then commands[command] = ret logger:info("loaded " .. path) else logger:error(ret) end end end soul.onMessageReceive = function(msg) msg.text = msg.text:gsub("@" .. bot.info.username, "") msg.chat.id = math.floor(msg.chat.id) msg.from.id = math.floor(msg.from.id) if msg.text:find("/(%S+)@(%S+)[Bb][Oo][Tt]") then return true end if os.time() - msg.date > config.ignore then return true end for k, v in pairs(commands) do if msg.text:find("^%s*/" .. k) and not msg.text:find("^%s*/" .. k .. "%S") then if v.limit then if v.limit.disable then return bot.sendMessage{ chat_id = msg.chat.id, text = "Sorry, the command is disabled.", reply_to_message_id = msg.message_id } elseif v.limit.master and msg.from.username ~= config.master then return bot.sendMessage{ chat_id = msg.chat.id, text = "Sorry, permission denied.", reply_to_message_id = msg.message_id } elseif (v.limit.match or v.limit.reply) and not ((v.limit.match and msg.text:find(v.limit.match)) or (v.limit.reply and msg.reply_to_message)) then return commands.help.func(msg, k) end end return v.func(msg) end end for keyword, reply in pairs(conversation) do local match = false if type(keyword) == "string" then match = msg.text:find(keyword) elseif type(keyword) == "table" then for i = 1, #keyword do match = match or msg.text:find(keyword[i]) end if keyword.reply and not msg.reply_to_message then match = false end elseif type(keyword) == "function" then match = keyword(msg.text) end if match then local ans, rep if type(reply) == "string" then ans = reply elseif type(reply) == "table" then ans = utils.rand(table.unpack(reply)) elseif type(reply) == "function" then ans = tostring(reply()) end if reply.reply then rep = msg.message_id elseif reply.reply_to_reply and msg.reply_to_message then rep = msg.reply_to_message.message_id end if ans:find("^sticker#%S-$") then return bot.sendSticker(msg.chat.id, ans:match("^sticker#(%S-)$"), nil, rep) elseif ans:find("^document#%S-$") then return bot.sendDocument(msg.chat.id, ans:match("^document#(%S-)$"), nil, nil, rep) else return bot.sendMessage(msg.chat.id, ans, reply.type or "Markdown", nil, nil, rep) end end end end soul.onEditedMessageReceive = function (msg) -- process end soul.onLeftChatMembersReceive = function (msg) end soul.onNewChatMembersReceive = function (msg) end soul.onPhotoReceive = function(msg) -- process end soul.onAudioReceive = function (msg) -- process end soul.onVideoReceive = function (msg) -- process end soul.onDocumentReceive = function (msg) -- process end soul.onGameReceive = function (msg) -- process end soul.onStickerReceive = function (msg) end soul.onVideoNoteReceive = function (msg) end soul.onContactReceive = function (msg) end soul.onLocationReceive = function (msg) end setmetatable(soul, { __index = function(t, key) logger:warn("called undefined processer " .. key) return (function() return false end) end }) return soul
local soul = {} local conversation = require("conversation") local utils = require("utils") local lfs = require("lfs") commands = {} for file in lfs.dir("commands") do local command = file:match("^(.+).lua") if (command) then local path = "commands." .. command package.loaded[path] = nil local status, ret = pcall(require, path) if (status) then commands[command] = ret logger:info("loaded " .. path) else logger:error(ret) end end end soul.onMessageReceive = function(msg) msg.text = msg.text:gsub("@" .. bot.info.username, "") msg.chat.id = math.floor(msg.chat.id) msg.from.id = math.floor(msg.from.id) if msg.text:find("/(%S+)@(%S+)[Bb][Oo][Tt]") then return true end if os.time() - msg.date > config.ignore then return true end for k, v in pairs(commands) do if msg.text:find("^%s*/" .. k) and not msg.text:find("^%s*/" .. k .. "%S") then if v.limit then if v.limit.disable then return bot.sendMessage{ chat_id = msg.chat.id, text = "Sorry, the command is disabled.", reply_to_message_id = msg.message_id } elseif v.limit.master and msg.from.username ~= config.master then return bot.sendMessage{ chat_id = msg.chat.id, text = "Sorry, permission denied.", reply_to_message_id = msg.message_id } elseif (v.limit.match or v.limit.reply) and not ((v.limit.match and msg.text:find(v.limit.match)) or (v.limit.reply and msg.reply_to_message)) then return commands.help.func(msg, k) end end return v.func(msg) end end for keyword, reply in pairs(conversation) do local match = false if type(keyword) == "string" then match = msg.text:find(keyword) elseif type(keyword) == "table" then for i = 1, #keyword do match = match or msg.text:find(keyword[i]) end if keyword.reply and not msg.reply_to_message then match = false end elseif type(keyword) == "function" then match = keyword(msg.text) end if match then local ans, rep if type(reply) == "string" then ans = reply elseif type(reply) == "table" then ans = utils.rand(table.unpack(reply)) if reply.reply then rep = msg.message_id elseif reply.reply_to_reply and msg.reply_to_message then rep = msg.reply_to_message.message_id end elseif type(reply) == "function" then ans = tostring(reply()) end if ans:find("^sticker#%S-$") then return bot.sendSticker(msg.chat.id, ans:match("^sticker#(%S-)$"), nil, rep) elseif ans:find("^document#%S-$") then return bot.sendDocument(msg.chat.id, ans:match("^document#(%S-)$"), nil, nil, rep) else return bot.sendMessage(msg.chat.id, ans, reply.type or "Markdown", nil, nil, rep) end end end end soul.onEditedMessageReceive = function (msg) -- process end soul.onLeftChatMembersReceive = function (msg) end soul.onNewChatMembersReceive = function (msg) end soul.onPhotoReceive = function(msg) -- process end soul.onAudioReceive = function (msg) -- process end soul.onVideoReceive = function (msg) -- process end soul.onDocumentReceive = function (msg) -- process end soul.onGameReceive = function (msg) -- process end soul.onStickerReceive = function (msg) end soul.onVideoNoteReceive = function (msg) end soul.onContactReceive = function (msg) end soul.onLocationReceive = function (msg) end setmetatable(soul, { __index = function(t, key) logger:warn("called undefined processer " .. key) return (function() return false end) end }) return soul
fix: wrong condition in conversation
fix: wrong condition in conversation
Lua
apache-2.0
SJoshua/Project-Small-R
e4ea99908eea142f544dec2c8e6e8747e3e5a36e
OS/DiskOS/Runtime/Globals/04_GameAPI.lua
OS/DiskOS/Runtime/Globals/04_GameAPI.lua
--Games special API loader local Globals = (...) or {} local sw,sh = screenSize() function Globals.pause() if Globals._DISABLE_PAUSE then return end pushMatrix() pushPalette() pushColor() palt() pal() colorPalette() cam() local oldClip = clip() local bkimg = screenshot():image() local scimg = screenshot(sw/8,sh/8, sw*0.75,sh*0.75) ImageUtils.darken(scimg,2) scimg = scimg:image() palt(0,false) scimg:draw(sw/8,sh/8) rect(sw/8,sh/8,sw*0.75,sh*0.75, true, 0) --Black rect(sw/8+1,sh/8+1,sw*0.75-2,sh*0.75-2, true, 7) --White rect(sw/8+2,sh/8+2,sw*0.75-4,sh*0.75-4, true, 0) --Black color(7) print("GAME IS PAUSED",0,sh*0.4, sw, "center") print("Press escape/return to resume",sw*0.175,sh*0.6, sw*0.65, "center") clearEStack() for event, a,b,c,d,e,f in pullEvent do if event == "keypressed" then if a == "escape" or a == "return" then break end end end bkimg:draw(0,0) if oldClip then clip(unpack(oldClip)) end popColor() popPalette() popMatrix() end local pkeys = {} --Pressed keys local rkeys = {} --Repeated keys local dkeys = {} --Down keys local tbtn = {false,false,false,false,false,false,false} --Touch buttons local gpads = {} --Gamepads local defaultbmap = { {"left","right","up","down","z","x","c"}, --Player 1 {"s","f","e","d","tab","q","w"} --Player 2 } do --So I can hide this part in ZeroBran studio local bmap = ConfigUtils.get("GamesKeymap") if not bmap[1] then bmap[1] = {unpack(defaultbmap[1])} ConfigUtils.saveConfig() end if not bmap[2] then bmap[2] = {unpack(defaultbmap[2])} ConfigUtils.saveConfig() end function Globals.btn(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end local map = bmap[p] local gmap = gpads[p] if not (map or gmap) then return false end --Failed to find a controller return dkeys[map[n]] or (p == 1 and tbtn[n]) or (gmap and gmap[n]) end function Globals.btnp(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end local map = bmap[p] local gmap = gpads[p] if not (map or gmap) then return false end --Failed to find a controller if rkeys[map[n]] or (p == 1 and tbtn[n] and tbtn[n] >= 1) or (gmap and gmap[n] and gmap[n] >= 1) then return true, true else return pkeys[map[n]] or (p == 1 and tbtn[n] and tbtn[n] == 0) or (gmap and gmap[n] and gmap[n] == 0) end end Globals.__BTNUpdate = function(dt) pkeys = {} --Reset the table (easiest way) rkeys = {} --Reset the table (easiest way) for k,v in pairs(dkeys) do if not isKDown(k) then dkeys[k] = nil end end for k,v in ipairs(tbtn) do if v then if tbtn[k] >= 1 then tbtn[k] = 0.9 end tbtn[k] = tbtn[k] + dt end end for id, gpad in pairs(gpads) do for k,v in ipairs(gpad) do if v then if gpad[k] >= 1 then gpad[k] = 0.9 end gpad[k] = gpad[k] + dt end end end end Globals.__BTNKeypressed = function(a,b) pkeys[a] = true rkeys[a] = b dkeys[a] = true end Globals.__BTNTouchControl = function(state,n) if state then tbtn[n] = 0 else tbtn[n] = false end end Globals.__BTNGamepad = function(state,n,id) if not gpads[id] then gpads[id] = {false,false,false,false,false,false} end if state then gpads[id][n] = 0 else gpads[id][n] = false end end end --Persistent data API local GameSaveID local GameSaveData local GameSaveSize = 1024*2 --2KB if not fs.exists("C:/GamesData") then fs.newDirectory("C:/GamesData") end function Globals.SaveID(name) if type(name) ~= "string" then return error("SaveID should be a string, provided: "..type(name)) end if GameSaveID then return error("SaveID could be only set once !") end GameSaveID, GameSaveData = name, "" if fs.exists(string.format("C:/GamesData/%s.bin",GameSaveID)) then GameSaveData = fs.read(string.format("C:/GamesData/%s.bin",GameSaveID), GameSaveSize) end end function Globals.SaveData(data) if type(data) ~= "string" then return error("Save data should be a string, provided: "..type(data)) end if #data > GameSaveSize then return error("Save data can be 2KB maximum !") end if not GameSaveID then return error("Set SaveID inorder to save data !") end --Write the game data fs.write(string.format("C:/GamesData/%s.bin",GameSaveID), data, GameSaveSize) end function Globals.LoadData() if not GameSaveID then return error("Set SaveID inorder to load data !") end return GameSaveData end --Helpers local helpersloader, err = fs.load("C:/Libraries/diskHelpers.lua") if not helpersloader then error(err) end setfenv(helpersloader,Globals) helpersloader() return Globals
--Games special API loader local Globals = (...) or {} local sw,sh = screenSize() function Globals.pause() if Globals._DISABLE_PAUSE then return end pushMatrix() pushPalette() pushColor() palt() pal() colorPalette() cam() local oldClip = clip() local bkimg = screenshot():image() local scimg = screenshot(sw/8,sh/8, sw*0.75,sh*0.75) ImageUtils.darken(scimg,2) scimg = scimg:image() palt(0,false) scimg:draw(sw/8,sh/8) rect(sw/8,sh/8,sw*0.75,sh*0.75, true, 0) --Black rect(sw/8+1,sh/8+1,sw*0.75-2,sh*0.75-2, true, 7) --White rect(sw/8+2,sh/8+2,sw*0.75-4,sh*0.75-4, true, 0) --Black color(7) print("GAME IS PAUSED",0,sh*0.4, sw, "center") print("Press escape/return to resume",sw*0.175,sh*0.6, sw*0.65, "center") clearEStack() for event, a,b,c,d,e,f in pullEvent do if event == "keypressed" then if a == "escape" or a == "return" then break end end end bkimg:draw(0,0) if oldClip then clip(unpack(oldClip)) end popColor() popPalette() popMatrix() end local pkeys = {} --Pressed keys local rkeys = {} --Repeated keys local dkeys = {} --Down keys local tbtn = {false,false,false,false,false,false,false} --Touch buttons local gpads = {} --Gamepads local defaultbmap = { {"left","right","up","down","z","x","c"}, --Player 1 {"s","f","e","d","tab","q","w"} --Player 2 } local mobilebnames = { "Left","Right","Up","Down","Green button","Red button","Blue button" } do --So I can hide this part in ZeroBran studio local bmap = ConfigUtils.get("GamesKeymap") if not bmap[1] then bmap[1] = {unpack(defaultbmap[1])} ConfigUtils.saveConfig() end if not bmap[2] then bmap[2] = {unpack(defaultbmap[2])} ConfigUtils.saveConfig() end function Globals.getBtnName(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end if isMobile() and p == 1 then return mobilebnames[n] else local map = bmap[p] local bname = map[n] return string.upper(string.sub(bname,1,1))..string.sub(bname,2,-1) end end function Globals.btn(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end local map = bmap[p] local gmap = gpads[p] if not (map or gmap) then return false end --Failed to find a controller return dkeys[map[n]] or (p == 1 and tbtn[n]) or (gmap and gmap[n]) end function Globals.btnp(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end local map = bmap[p] local gmap = gpads[p] if not (map or gmap) then return false end --Failed to find a controller if rkeys[map[n]] or (p == 1 and tbtn[n] and tbtn[n] >= 1) or (gmap and gmap[n] and gmap[n] >= 1) then return true, true else return pkeys[map[n]] or (p == 1 and tbtn[n] and tbtn[n] == 0) or (gmap and gmap[n] and gmap[n] == 0) end end Globals.__BTNUpdate = function(dt) pkeys = {} --Reset the table (easiest way) rkeys = {} --Reset the table (easiest way) for k,v in pairs(dkeys) do if not isKDown(k) then dkeys[k] = nil end end for k,v in ipairs(tbtn) do if v then if tbtn[k] >= 1 then tbtn[k] = 0.9 end tbtn[k] = tbtn[k] + dt end end for id, gpad in pairs(gpads) do for k,v in ipairs(gpad) do if v then if gpad[k] >= 1 then gpad[k] = 0.9 end gpad[k] = gpad[k] + dt end end end end Globals.__BTNKeypressed = function(a,b) pkeys[a] = true rkeys[a] = b dkeys[a] = true end Globals.__BTNTouchControl = function(state,n) if state then tbtn[n] = 0 else tbtn[n] = false end end Globals.__BTNGamepad = function(state,n,id) if not gpads[id] then gpads[id] = {false,false,false,false,false,false} end if state then gpads[id][n] = 0 else gpads[id][n] = false end end end --Persistent data API local GameSaveID local GameSaveData local GameSaveSize = 1024*2 --2KB if not fs.exists("C:/GamesData") then fs.newDirectory("C:/GamesData") end function Globals.SaveID(name) if type(name) ~= "string" then return error("SaveID should be a string, provided: "..type(name)) end if GameSaveID then return error("SaveID could be only set once !") end GameSaveID, GameSaveData = name, "" if fs.exists(string.format("C:/GamesData/%s.bin",GameSaveID)) then GameSaveData = fs.read(string.format("C:/GamesData/%s.bin",GameSaveID), GameSaveSize) end end function Globals.SaveData(data) if type(data) ~= "string" then return error("Save data should be a string, provided: "..type(data)) end if #data > GameSaveSize then return error("Save data can be 2KB maximum !") end if not GameSaveID then return error("Set SaveID inorder to save data !") end --Write the game data fs.write(string.format("C:/GamesData/%s.bin",GameSaveID), data, GameSaveSize) end function Globals.LoadData() if not GameSaveID then return error("Set SaveID inorder to load data !") end return GameSaveData end --Helpers local helpersloader, err = fs.load("C:/Libraries/diskHelpers.lua") if not helpersloader then error(err) end setfenv(helpersloader,Globals) helpersloader() return Globals
Fix issue #179 -> New getBtnName function
Fix issue #179 -> New getBtnName function Former-commit-id: da777e2c48c49c5431bef7d91b708eb320285e35
Lua
mit
RamiLego4Game/LIKO-12
b018b10899fac72c8211cc2ebef709f0ed97cfe1
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.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") m = Map("olsrd", translate("olsrd", "OLSR Daemon")) s = m:section(TypedSection, "olsrd", translate("olsrd_general")) s.dynamic = true s.anonymous = true debug = s:option(ListValue, "DebugLevel") for i=0, 9 do debug:value(i) end debug.optional = true ipv = s:option(ListValue, "IpVersion") ipv:value("4", "IPv4") ipv:value("6", "IPv6") noint = s:option(Flag, "AllowNoInt") noint.enabled = "yes" noint.disabled = "no" noint.optional = true s:option(Value, "Pollrate").optional = true tcr = s:option(ListValue, "TcRedundancy") tcr:value("0", translate("olsrd_olsrd_tcredundancy_0")) tcr:value("1", translate("olsrd_olsrd_tcredundancy_1")) tcr:value("2", translate("olsrd_olsrd_tcredundancy_2")) tcr.optional = true s:option(Value, "MprCoverage").optional = true lql = s:option(ListValue, "LinkQualityLevel") lql:value("0", translate("disable")) lql:value("1", translate("olsrd_olsrd_linkqualitylevel_1")) lql:value("2", translate("olsrd_olsrd_linkqualitylevel_2")) lql.optional = true s:option(Value, "LinkQualityAging").optional = true lqa = s:option(ListValue, "LinkQualityAlgorithm") lqa.optional = true lqa:value("etx_fpm", translate("olsrd_etx_fpm")) lqa:value("etx_float", translate("olsrd_etx_float")) lqa:value("etx_ff", translate("olsrd_etx_ff")) lqa.optional = true lqfish = s:option(Flag, "LinkQualityFishEye") lqfish.optional = true s:option(Value, "LinkQualityWinSize").optional = true s:option(Value, "LinkQualityDijkstraLimit").optional = true hyst = s:option(Flag, "UseHysteresis") hyst.enabled = "yes" hyst.disabled = "no" hyst.optional = true fib = s:option(ListValue, "FIBMetric") fib.optional = true fib:value("flat") fib:value("correct") fib:value("approx") fib.optional = true clrscr = s:option(Flag, "ClearScreen") clrscr.enabled = "yes" clrscr.disabled = "no" clrscr.optional = true willingness = s:option(ListValue, "Willingness") for i=0,7 do willingness:value(i) end willingness.optional = true i = m:section(TypedSection, "Interface", translate("interfaces")) i.anonymous = true i.addremove = true i.dynamic = true ign = i:option(Flag, "ignore", "Enable") ign.enabled = "0" ign.disabled = "1" ign.rmempty = false network = i:option(ListValue, "interface", translate("network")) luci.tools.webadmin.cbi_add_networks(network) i:option(Value, "Ip4Broadcast").optional = true ip6t = i:option(ListValue, "Ip6AddrType") ip6t:value("", translate("cbi_select")) ip6t:value("auto") ip6t:value("site-local") ip6t:value("unique-local") ip6t:value("global") ip6t.optional = true i:option(Value, "HelloInterval").optional = true i:option(Value, "HelloValidityTime").optional = true i:option(Value, "TcInterval").optional = true i:option(Value, "TcValidityTime").optional = true i:option(Value, "MidInterval").optional = true i:option(Value, "MidValidityTime").optional = true i:option(Value, "HnaInterval").optional = true i:option(Value, "HnaValidityTime").optional = true adc = i:option(Flag, "AutoDetectChanges") adc.enabled = "yes" adc.disabled = "no" adc.optional = true --[[ ipc = m:section(TypedSection, "IpcConnect") ipc.anonymous = true conns = ipc:option(Value, "MaxConnections") conns.isInteger = true nets = ipc:option(Value, "Net") nets.optional = true hosts = ipc:option(Value, "Host") hosts.optional = true ]] 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") m = Map("olsrd", translate("olsrd", "OLSR Daemon")) s = m:section(TypedSection, "olsrd", translate("olsrd_general")) s.dynamic = true s.anonymous = true debug = s:option(ListValue, "DebugLevel") for i=0, 9 do debug:value(i) end debug.optional = true ipv = s:option(ListValue, "IpVersion") ipv:value("4", "IPv4") ipv:value("6", "IPv6") noint = s:option(Flag, "AllowNoInt") noint.enabled = "yes" noint.disabled = "no" noint.optional = true s:option(Value, "Pollrate").optional = true tcr = s:option(ListValue, "TcRedundancy") tcr:value("0", translate("olsrd_olsrd_tcredundancy_0")) tcr:value("1", translate("olsrd_olsrd_tcredundancy_1")) tcr:value("2", translate("olsrd_olsrd_tcredundancy_2")) tcr.optional = true s:option(Value, "MprCoverage").optional = true lql = s:option(ListValue, "LinkQualityLevel") lql:value("0", translate("disable")) lql:value("1", translate("olsrd_olsrd_linkqualitylevel_1")) lql:value("2", translate("olsrd_olsrd_linkqualitylevel_2")) lql.optional = true s:option(Value, "LinkQualityAging").optional = true lqa = s:option(ListValue, "LinkQualityAlgorithm") lqa.optional = true lqa:value("etx_fpm", translate("olsrd_etx_fpm")) lqa:value("etx_float", translate("olsrd_etx_float")) lqa:value("etx_ff", translate("olsrd_etx_ff")) lqa.optional = true lqfish = s:option(Flag, "LinkQualityFishEye") lqfish.optional = true s:option(Value, "LinkQualityWinSize").optional = true s:option(Value, "LinkQualityDijkstraLimit").optional = true hyst = s:option(Flag, "UseHysteresis") hyst.enabled = "yes" hyst.disabled = "no" hyst.optional = true fib = s:option(ListValue, "FIBMetric") fib.optional = true fib:value("flat") fib:value("correct") fib:value("approx") fib.optional = true clrscr = s:option(Flag, "ClearScreen") clrscr.enabled = "yes" clrscr.disabled = "no" clrscr.optional = true willingness = s:option(ListValue, "Willingness") for i=0,7 do willingness:value(i) end willingness.optional = true i = m:section(TypedSection, "Interface", translate("interfaces")) i.anonymous = true i.addremove = true i.dynamic = true ign = i:option(Flag, "ignore", "Enable") ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:option(ListValue, "interface", translate("network")) luci.tools.webadmin.cbi_add_networks(network) i:option(Value, "Ip4Broadcast").optional = true ip6t = i:option(ListValue, "Ip6AddrType") ip6t:value("", translate("cbi_select")) ip6t:value("auto") ip6t:value("site-local") ip6t:value("unique-local") ip6t:value("global") ip6t.optional = true i:option(Value, "HelloInterval").optional = true i:option(Value, "HelloValidityTime").optional = true i:option(Value, "TcInterval").optional = true i:option(Value, "TcValidityTime").optional = true i:option(Value, "MidInterval").optional = true i:option(Value, "MidValidityTime").optional = true i:option(Value, "HnaInterval").optional = true i:option(Value, "HnaValidityTime").optional = true adc = i:option(Flag, "AutoDetectChanges") adc.enabled = "yes" adc.disabled = "no" adc.optional = true --[[ ipc = m:section(TypedSection, "IpcConnect") ipc.anonymous = true conns = ipc:option(Value, "MaxConnections") conns.isInteger = true nets = ipc:option(Value, "Net") nets.optional = true hosts = ipc:option(Value, "Host") hosts.optional = true ]] return m
[applications] luci-olsr: Fix enable option for interfaces
[applications] luci-olsr: Fix enable option for interfaces git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4740 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
c379d757bb02e2dffaf356a9fa3b9c309ccc3aae
libs/sgi-webuci/root/usr/lib/boa/luci.lua
libs/sgi-webuci/root/usr/lib/boa/luci.lua
module("luci-plugin", package.seeall) function normalize(path) local newpath while newpath ~= path do if (newpath) then path = newpath end newpath = string.gsub(path, "/[^/]+/../", "/") end return newpath end function init(path) -- NB: path points to ROOT/usr/lib/boa, change it to /usr/lib/lua root = normalize(path .. '/../../../') path = normalize(path .. '/../lua/') package.cpath = path..'?.so;'..package.cpath package.path = path..'?.lua;'..package.path require("luci.dispatcher") require("luci.sgi.webuci") require("uci") if (root ~= '/') then -- Entering dummy mode uci.set_savedir(root..'/tmp/.uci') uci.set_confdir(root..'/etc/config') luci.sys.hostname = function() return "" end luci.sys.loadavg = function() return 0,0,0,0,0 end luci.sys.reboot = function() return end luci.sys.sysinfo = function() return "","","" end luci.sys.syslog = function() return "" end luci.sys.net.arptable = function() return {} end luci.sys.net.devices = function() return {} end luci.sys.net.routes = function() return {} end luci.sys.wifi.getiwconfig = function() return {} end luci.sys.wifi.iwscan = function() return {} end luci.sys.user.checkpasswd = function() return true end end end function prepare_req(uri) luci.dispatcher.createindex() env = {} env.REQUEST_URI = uri -- TODO: setting luci-plugin.reload = true allows this function to trigger a context reload end function handle_req(context) env.SERVER_PROTOCOL = context.server_proto env.REMOTE_ADDR = context.remote_addr env.REQUEST_METHOD = context.request_method env.PATH_INFO = context.uri env.REMOTE_PORT = context.remote_port env.SERVER_ADDR = context.server_addr env.SCRIPT_NAME = env.REQUEST_URI:sub(1, #env.REQUEST_URI - #env.PATH_INFO) luci.sgi.webuci.initenv(env, vars) luci.dispatcher.httpdispatch() end
module("luci-plugin", package.seeall) function normalize(path) local newpath while newpath ~= path do if (newpath) then path = newpath end newpath = string.gsub(path, "/[^/]+/../", "/") end return newpath end function init(path) -- NB: path points to ROOT/usr/lib/boa, change it to /usr/lib/lua root = normalize(path .. '/../../../') path = normalize(path .. '/../lua/') package.cpath = path..'?.so;'..package.cpath package.path = path..'?.lua;'..package.path require("luci.dispatcher") require("luci.sgi.webuci") require("uci") if (root ~= '/') then -- Entering dummy mode uci.set_savedir(root..'/tmp/.uci') uci.set_confdir(root..'/etc/config') luci.sys.hostname = function() return "" end luci.sys.loadavg = function() return 0,0,0,0,0 end luci.sys.reboot = function() return end luci.sys.sysinfo = function() return "","","" end luci.sys.syslog = function() return "" end luci.sys.net.arptable = function() return {} end luci.sys.net.devices = function() return {} end luci.sys.net.routes = function() return {} end luci.sys.wifi.getiwconfig = function() return {} end luci.sys.wifi.iwscan = function() return {} end luci.sys.user.checkpasswd = function() return true end luci.http.basic_auth = function() return true end end end function prepare_req(uri) luci.dispatcher.createindex() env = {} env.REQUEST_URI = uri -- TODO: setting luci-plugin.reload = true allows this function to trigger a context reload end function handle_req(context) env.SERVER_PROTOCOL = context.server_proto env.REMOTE_ADDR = context.remote_addr env.REQUEST_METHOD = context.request_method env.PATH_INFO = context.uri env.REMOTE_PORT = context.remote_port env.SERVER_ADDR = context.server_addr env.SCRIPT_NAME = env.REQUEST_URI:sub(1, #env.REQUEST_URI - #env.PATH_INFO) luci.sgi.webuci.initenv(env, vars) luci.dispatcher.httpdispatch() end
* Fixed host builds
* Fixed host builds git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2343 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
Canaan-Creative/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,Canaan-Creative/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,jschmidlapp/luci,alxhh/piratenluci,jschmidlapp/luci,jschmidlapp/luci,alxhh/piratenluci,vhpham80/luci,yeewang/openwrt-luci,gwlim/luci,vhpham80/luci,8devices/carambola2-luci,yeewang/openwrt-luci,alxhh/piratenluci,jschmidlapp/luci,vhpham80/luci,Canaan-Creative/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,vhpham80/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,Flexibity/luci,8devices/carambola2-luci,stephank/luci,alxhh/piratenluci,eugenesan/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,projectbismark/luci-bismark,freifunk-gluon/luci,zwhfly/openwrt-luci,phi-psi/luci,yeewang/openwrt-luci,Flexibity/luci,saraedum/luci-packages-old,stephank/luci,ch3n2k/luci,eugenesan/openwrt-luci,Flexibity/luci,yeewang/openwrt-luci,alxhh/piratenluci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,saraedum/luci-packages-old,vhpham80/luci,Canaan-Creative/luci,phi-psi/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,Canaan-Creative/luci,Flexibity/luci,stephank/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,gwlim/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,Flexibity/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Flexibity/luci,8devices/carambola2-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,ch3n2k/luci,Flexibity/luci,ch3n2k/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,stephank/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,vhpham80/luci,gwlim/luci,gwlim/luci,alxhh/piratenluci,ch3n2k/luci,gwlim/luci,saraedum/luci-packages-old,8devices/carambola2-luci,Canaan-Creative/luci,phi-psi/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,alxhh/piratenluci,saraedum/luci-packages-old,stephank/luci,phi-psi/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,ch3n2k/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,stephank/luci,jschmidlapp/luci,Flexibity/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,eugenesan/openwrt-luci
6d3b1dbf93adad36b90c330a55d7b2e33f374fbc
libs/uci/luasrc/model/uci/bind.lua
libs/uci/luasrc/model/uci/bind.lua
--[[ LuCI - UCI utilities for model classes Copyright 2009 Jo-Philipp Wich <[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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local assert, pairs, type = assert, pairs, type local utl = require "luci.util" module "luci.model.uci.bind" bind = utl.class() function bind.__init__(self, config, cursor) assert(config, "call to bind() without config file") self.cfg = config self.uci = cursor end function bind.init(self, cursor) assert(cursor, "call to init() without uci cursor") self.uci = cursor end function bind.section(self, stype) local x = utl.class(bsection) x.__init__ = function(inst, sid) assert(self.uci:get(self.cfg, sid) == stype, "attempt to instantiate bsection(%q) of wrong type, expected %q" % { sid, stype }) inst.bind = self inst.stype = stype inst.sid = sid end return x end function bind.usection(self, stype) local x = utl.class(bsection) x.__init__ = function(inst) inst.bind = self inst.stype = stype inst.sid = true end return x() end function bind.list(self, list, add, rem) local lookup = { } if type(list) == "string" then local item for item in list:gmatch("%S+") do lookup[item] = true end elseif type(list) == "table" then local item for _, item in pairs(list) do lookup[item] = true end end if add then lookup[add] = true end if rem then lookup[rem] = nil end return utl.keys(lookup) end function bind.bool(self, v) return ( v == "1" or v == "true" or v == "yes" or v == "on" ) end bsection = utl.class() function bsection.uciop(self, op, ...) assert(self.bind and self.bind.uci, "attempt to use unitialized binding") if op then return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...) else return self.bind.uci end end function bsection.get(self, k, c) local v if type(c) == "string" then v = self:uciop("get", c, k) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end if k ~= nil then v = s[k] else v = s end return false end) end return v end function bsection.set(self, k, v, c) local stat if type(c) == "string" then stat = self:uciop("set", c, k, v) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end stat = self:uciop("set", c, k, v) return false end) end return stat or false end function bsection.property(self, k, n) self[n or k] = function(c, val) if val == nil then return c:get(k, c.sid) else return c:set(k, val, c.sid) end end end function bsection.property_bool(self, k, n) self[n or k] = function(c, val) if val == nil then return self.bind:bool(c:get(k, c.sid)) else return c:set(k, self.bind:bool(val) and "1" or "0", c.sid) end end end
--[[ LuCI - UCI utilities for model classes Copyright 2009 Jo-Philipp Wich <[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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local assert, pairs, type = assert, pairs, type local utl = require "luci.util" module "luci.model.uci.bind" bind = utl.class() function bind.__init__(self, config, cursor) assert(config, "call to bind() without config file") self.cfg = config self.uci = cursor end function bind.init(self, cursor) assert(cursor, "call to init() without uci cursor") self.uci = cursor end function bind.section(self, stype) local x = utl.class(bsection) x.__init__ = function(inst, sid) assert(self.uci:get(self.cfg, sid) == stype, "attempt to instantiate bsection(%q) of wrong type, expected %q" % { sid, stype }) inst.bind = self inst.stype = stype inst.sid = sid end return x end function bind.usection(self, stype) local x = utl.class(bsection) x.__init__ = function(inst) inst.bind = self inst.stype = stype inst.sid = true end return x() end function bind.list(self, list, add, rem) local lookup = { } if type(list) == "string" then local item for item in list:gmatch("%S+") do lookup[item] = true end elseif type(list) == "table" then local item for _, item in pairs(list) do lookup[item] = true end end if add then lookup[add] = true end if rem then lookup[rem] = nil end return utl.keys(lookup) end function bind.bool(self, v) return ( v == "1" or v == "true" or v == "yes" or v == "on" ) end bsection = utl.class() function bsection.uciop(self, op, ...) assert(self.bind and self.bind.uci, "attempt to use unitialized binding") if op then return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...) else return self.bind.uci end end function bsection.get(self, k, c) local v if type(c) == "string" then v = self:uciop("get", c, k) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end if k ~= nil then v = s[k] else v = s end return false end) end return v end function bsection.set(self, k, v, c) local stat if type(c) == "string" then if type(v) == "table" and #v == 0 then stat = self:uciop("delete", c, k) else stat = self:uciop("set", c, k, v) end else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end stat = self:uciop("set", c, k, v) return false end) end return stat or false end function bsection.property(self, k, n) self[n or k] = function(c, val) if val == nil then return c:get(k, c.sid) else return c:set(k, val, c.sid) end end end function bsection.property_bool(self, k, n) self[n or k] = function(c, val) if val == nil then return self.bind:bool(c:get(k, c.sid)) else return c:set(k, self.bind:bool(val) and "1" or "0", c.sid) end end end
libs/uci: fix attempt to assign empty tables in uci bind class
libs/uci: fix attempt to assign empty tables in uci bind class
Lua
apache-2.0
deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
819b22c477cab130aec50386702947a3f155a9e8
inkblazers.lua
inkblazers.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local illu_name = os.getenv('illu_name') local illu_number = os.getenv('illu_number') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if string.match(url, "images%.inkblazers%.com") then return verdict elseif item_type == "illustration" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "[^0-9]"..illu_name.."[^0-9]") or string.match(url, "[^0-9]"..illu_number.."[^0-9]") then return verdict elseif html == 0 then return verdict else return false end elseif item_type == "manga" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "/"..illu_number.."/[0-9]+/[0-9]+") then return verdict elseif html == 0 then return verdict else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url) if downloaded[url] ~= true and addedtolist[url] ~= true then table.insert(urls, { url=url }) addedtolist[url] = true end end if item_type == "illustration" then if string.match(url, "https?://illustration%.images%.inkblazers%.com/[0-9]+/[^%?]+%?") then local newurl = string.match(url, "(https?://illustration%.images%.inkblazers%.com/[0-9]+/[^%?]+)%?") check(newurl) end if string.match(url, "inkblazers%.com/illustrations/[^/]+/detail%-page/[0-9]+") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com") then check(newurl) end end local dataurl1 = string.match(html, 'data%-url="([^"]+)"') local dataurl = "http://www.inkblazers.com"..dataurl1 check(dataurl) local datalink = string.match(html, 'data%-link="([^"]+)"') if not string.match(datalink, "load%-as%-page%-by%-profile%-key%.json") then check(datalink) end local datapicture = string.match(html, 'data%-picture="([^"]+)"') check(datapicture) end elseif item_type == "manga" then if string.match(url, "images%.inkblazers%.com/[0-9]+/[^%?]+%?") then local newurl = string.match(url, "(https?://[^/]+/[0-9]+/[^%?]+)%?") check(newurl) end if string.match(url, "inkblazers%.com/api/1%.0/") then html = read_file(file) for newurl in string.gmatch(html, '"https?://[^"]+"') do if string.match(newurl, "images%.inkblazers%.com/") then check(newurl) end end for newurl in string.gmatch(html, '"/read%-manga/[^"]+"') do if string.match(newurl, "/"..illu_number.."/[0-9]+/[0-9]+/") then check(newurl) end end end if string.match(url, "inkblazers%.com/manga%-and%-comics/"..illu_name.."/detail%-page/"..illu_number) or string.match(url, "inkblazers%.com/read%-manga/[^/]+/"..illu_number.."/[0-9]+/[0-9]+") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com") then check(newurl) end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) or status_code == 403 then if string.match(url["url"], "https://") then local newurl = string.gsub(url["url"], "https://", "http://") downloaded[newurl] = true else downloaded[url["url"]] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local illu_name = os.getenv('illu_name') local illu_number = os.getenv('illu_number') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if string.match(url, "images%.inkblazers%.com") then return verdict elseif item_type == "illustration" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "[^0-9]"..illu_name.."[^0-9]") or string.match(url, "[^0-9]"..illu_number.."[^0-9]") then return verdict elseif html == 0 then return verdict else return false end elseif item_type == "manga" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "/"..illu_number.."/[0-9]+/[0-9]+") then return verdict elseif html == 0 then return verdict else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url) if downloaded[url] ~= true and addedtolist[url] ~= true then table.insert(urls, { url=url }) addedtolist[url] = true end end if item_type == "illustration" then if string.match(url, "https?://illustration%.images%.inkblazers%.com/[0-9]+/[^%?]+%?") then local newurl = string.match(url, "(https?://illustration%.images%.inkblazers%.com/[0-9]+/[^%?]+)%?") check(newurl) end if string.match(url, "inkblazers%.com/illustrations/[^/]+/detail%-page/[0-9]+") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com") then check(newurl) end end local dataurl1 = string.match(html, 'data%-url="([^"]+)"') local dataurl = "http://www.inkblazers.com"..dataurl1 check(dataurl) local datalink = string.match(html, 'data%-link="([^"]+)"') if not string.match(datalink, "load%-as%-page%-by%-profile%-key%.json") then check(datalink) end local datapicture = string.match(html, 'data%-picture="([^"]+)"') check(datapicture) end elseif item_type == "manga" then if string.match(url, "images%.inkblazers%.com/[0-9]+/[^%?]+%?") then local newurl = string.match(url, "(https?://[^/]+/[0-9]+/[^%?]+)%?") check(newurl) end if string.match(url, "inkblazers%.com/api/1%.0/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com/") then check(newurl) end end for newurl in string.gmatch(html, '"(/read%-manga/[^"]+)"') do local nurl = "http://www.inkblazers.com"..newurl if string.match(nurl, "/"..illu_number.."/[0-9]+/[0-9]+/") then check(nurl) end end end if string.match(url, "inkblazers%.com/manga%-and%-comics/"..illu_name.."/detail%-page/"..illu_number) or string.match(url, "inkblazers%.com/read%-manga/[^/]+/"..illu_number.."/[0-9]+/[0-9]+") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "images%.inkblazers%.com") then check(newurl) end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) or status_code == 403 then if string.match(url["url"], "https://") then local newurl = string.gsub(url["url"], "https://", "http://") downloaded[newurl] = true else downloaded[url["url"]] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
inkblazers.lua: fix gmatch
inkblazers.lua: fix gmatch
Lua
unlicense
ArchiveTeam/inkblazers-grab,ArchiveTeam/inkblazers-grab
f8af6a1ccac7b2f3407d40eb2c9429b9bd4f274c
practicals/practical2/load_data_mnist.lua
practicals/practical2/load_data_mnist.lua
filepath = 'http://torch7.s3-website-us-east-1.amazonaws.com/data/mnist.t7.tgz' if not paths.dirp('mnist.t7') then print 'MNIST data not found. Downloading...' os.execute('wget ' .. filepath) os.execute('tar xvf ' .. paths.basename('mnist.t7.tgz')) else print 'MNIST data found' end train_file = 'mnist.t7/train_32x32.t7' test_file = 'mnist.t7/test_32x32.t7' ------------------------------------------------------ print 'Loading data' -- Small problem for now if #opt.small > 0 then print '==> using reduced training data, for fast experiments' Ntr = opt.small[1] Nte = opt.small[2] loaded = torch.load(train_file,'ascii') trainData = { data = loaded.X:transpose(3,4)[{ {1, opt.small[1]}, {}, {}, {} }], labels = loaded.y[1][{ {1, opt.small[1]} }], size = function() return Ntr end } -- Torch complains when the line is completely empty (at least in my machine). Add one "empty space" or just delete the line. loaded = torch.load(test_file,'ascii') testData = { data = loaded.X:transpose(3,4)[{ {1, opt.small[2]}, {}, {}, {} }], labels = loaded.y[1][{ {1, opt.small[2]} }], size = function() return Nte end } else loaded = torch.load(train_file,'ascii') Ntr = loaded.data:size()[1] trainData = { data = loaded.data:transpose(3,4), labels = loaded.labels, size = function() return Ntr end } loaded = torch.load(test_file,'ascii') Nte = loaded.data:size()[1] testData = { data = loaded.data:transpose(3,4), labels = loaded.labels, size = function() return Nte end } end classes = {'1','2','3','4','5','6','7','8','9','0'}
filepath = 'http://torch7.s3-website-us-east-1.amazonaws.com/data/mnist.t7.tgz' if not paths.dirp('mnist.t7') then print 'MNIST data not found. Downloading...' os.execute('wget ' .. filepath) os.execute('tar xvf ' .. paths.basename('mnist.t7.tgz')) else print 'MNIST data found' end train_file = 'mnist.t7/train_32x32.t7' test_file = 'mnist.t7/test_32x32.t7' ------------------------------------------------------ print 'Loading data' -- Small problem for now if #opt.small > 0 then print '==> using reduced training data, for fast experiments' Ntr = opt.small[1] Nte = opt.small[2] loaded = torch.load(train_file,'ascii') trainData = { data = loaded.data[{ {1, opt.small[1]}, {}, {}, {} }], labels = loaded.labels[{ {1, opt.small[1]} }], size = function() return Ntr end } -- Torch complains when the line is completely empty (at least in my machine). Add one "empty space" or just delete the line. loaded = torch.load(test_file,'ascii') testData = { data = loaded.data[{ {1, opt.small[2]}, {}, {}, {} }], labels = loaded.labels[{ {1, opt.small[2]} }], size = function() return Nte end } else loaded = torch.load(train_file,'ascii') Ntr = loaded.data:size()[1] trainData = { data = loaded.data, labels = loaded.labels, size = function() return Ntr end } loaded = torch.load(test_file,'ascii') Nte = loaded.data:size()[1] testData = { data = loaded.data, labels = loaded.labels, size = function() return Nte end } end classes = {'0','1','2','3','4','5','6','7','8','9'}
Fixes
Fixes 1) Transpose error which rotated and flipped the images 2) Error which occured for small data set option Please enter the commit message for your changes. Lines starting
Lua
apache-2.0
uvadlc/uvadlc.github.io,uvadlc/uvadlc.github.io,uvadlc/uvadlc.github.io
4862827e7dc64d4158be83377b5c8338d3ffd58a
build/LLVM.lua
build/LLVM.lua
-- Setup the LLVM dependency directories LLVMRootDir = depsdir .. "/llvm/" local LLVMDirPerConfiguration = false local LLVMRootDirDebug = "" local LLVMRootDirRelease = "" require "scripts/LLVM" function SearchLLVM() local basedir = path.getdirectory(_PREMAKE_COMMAND) LLVMRootDirDebug = basedir .. "/scripts/" .. get_llvm_package_name(nil, "Debug") LLVMRootDirRelease = basedir .. "/scripts/" .. get_llvm_package_name() if os.isdir(LLVMRootDirDebug) or os.isdir(LLVMRootDirRelease) then LLVMDirPerConfiguration = true print("Using debug LLVM build: " .. LLVMRootDirDebug) print("Using release LLVM build: " .. LLVMRootDirRelease) elseif os.isdir(LLVMRootDir) then print("Using LLVM build: " .. LLVMRootDir) else error("Error finding an LLVM build") end end function get_llvm_build_dir() local packageDir = path.join(LLVMRootDir, get_llvm_package_name()) local buildDir = path.join(LLVMRootDir, "build") if os.isdir(buildDir) then return buildDir else return packageDir end end function SetupLLVMIncludes() local c = filter() if LLVMDirPerConfiguration then filter { "configurations:Debug" } includedirs { path.join(LLVMRootDirDebug, "include"), path.join(LLVMRootDirDebug, "tools/clang/include"), path.join(LLVMRootDirDebug, "tools/clang/lib"), path.join(LLVMRootDirDebug, "build/include"), path.join(LLVMRootDirDebug, "build/tools/clang/include"), } filter { "configurations:Release" } includedirs { path.join(LLVMRootDirRelease, "include"), path.join(LLVMRootDirRelease, "tools/clang/include"), path.join(LLVMRootDirRelease, "tools/clang/lib"), path.join(LLVMRootDirRelease, "build/include"), path.join(LLVMRootDirRelease, "build/tools/clang/include"), } else local LLVMBuildDir = get_llvm_build_dir() includedirs { path.join(LLVMRootDir, "include"), path.join(LLVMRootDir, "tools/clang/include"), path.join(LLVMRootDir, "tools/clang/lib"), path.join(LLVMBuildDir, "include"), path.join(LLVMBuildDir, "tools/clang/include"), } end filter(c) end function CopyClangIncludes() local clangBuiltinIncludeDir = path.join(LLVMRootDir, "lib") if LLVMDirPerConfiguration then local clangBuiltinDebug = path.join(LLVMRootDirDebug, "lib") local clangBuiltinRelease = path.join(LLVMRootDirRelease, "lib") if os.isdir(path.join(clangBuiltinDebug, "clang")) then clangBuiltinIncludeDir = clangBuiltinDebug end if os.isdir(path.join(clangBuiltinRelease, "clang")) then clangBuiltinIncludeDir = clangBuiltinRelease end end if os.isdir(clangBuiltinIncludeDir) then postbuildcommands { -- Workaround Premake OS-specific behaviour when copying folders: -- See: https://github.com/premake/premake-core/issues/1232 '{MKDIR} "%%{cfg.buildtarget.directory}/lib"', string.format('{COPY} "%s" "%%{cfg.buildtarget.directory}/lib"', clangBuiltinIncludeDir) } end end function SetupLLVMLibs() local c = filter() filter { "action:not vs*" } defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" } filter { "system:macosx" } links { "c++", "curses", "pthread", "z" } filter { "action:vs*" } links { "version" } filter {} if LLVMDirPerConfiguration then filter { "configurations:Debug" } libdirs { path.join(LLVMRootDirDebug, "build/lib") } filter { "configurations:Release" } libdirs { path.join(LLVMRootDirRelease, "build/lib") } else local LLVMBuildDir = get_llvm_build_dir() libdirs { path.join(LLVMBuildDir, "lib") } filter { "configurations:Debug", "action:vs*" } libdirs { path.join(LLVMBuildDir, "Debug/lib") } filter { "configurations:Release", "action:vs*" } libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") } end filter {} links { "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic", "clangIndex", "LLVMLinker", "LLVMipo", "LLVMVectorize", "LLVMBitWriter", "LLVMIRReader", "LLVMAsmParser", "LLVMOption", "LLVMInstrumentation", "LLVMProfileData", "LLVMX86AsmParser", "LLVMX86Desc", "LLVMObject", "LLVMMCParser", "LLVMBitReader", "LLVMX86Info", "LLVMX86Utils", "LLVMX86CodeGen", "LLVMX86Disassembler", "LLVMCodeGen", "LLVMSelectionDAG", "LLVMGlobalISel", "LLVMDebugInfoCodeView", "LLVMScalarOpts", "LLVMInstCombine", "LLVMTransformUtils", "LLVMAnalysis", "LLVMTarget", "LLVMMCDisassembler", "LLVMMC", "LLVMCoverage", "LLVMCore", "LLVMSupport", "LLVMBinaryFormat", "LLVMDemangle", "LLVMRemarks" } filter(c) end
-- Setup the LLVM dependency directories LLVMRootDir = depsdir .. "/llvm/" local LLVMDirPerConfiguration = false local LLVMRootDirDebug = "" local LLVMRootDirRelease = "" require "scripts/LLVM" function SearchLLVM() local basedir = path.getdirectory(_PREMAKE_COMMAND) LLVMRootDirDebug = basedir .. "/scripts/" .. get_llvm_package_name(nil, "Debug") LLVMRootDirRelease = basedir .. "/scripts/" .. get_llvm_package_name() if os.isdir(LLVMRootDirDebug) or os.isdir(LLVMRootDirRelease) then LLVMDirPerConfiguration = true print("Using debug LLVM build: " .. LLVMRootDirDebug) print("Using release LLVM build: " .. LLVMRootDirRelease) elseif os.isdir(LLVMRootDir) then print("Using LLVM build: " .. LLVMRootDir) else error("Error finding an LLVM build") end end function get_llvm_build_dir() local packageDir = path.join(LLVMRootDir, get_llvm_package_name()) local buildDir = path.join(LLVMRootDir, "build") if os.isdir(buildDir) then return buildDir else return packageDir end end function SetupLLVMIncludes() local c = filter() if LLVMDirPerConfiguration then filter { "configurations:Debug" } includedirs { path.join(LLVMRootDirDebug, "include"), path.join(LLVMRootDirDebug, "tools/clang/include"), path.join(LLVMRootDirDebug, "tools/clang/lib"), path.join(LLVMRootDirDebug, "build/include"), path.join(LLVMRootDirDebug, "build/tools/clang/include"), } filter { "configurations:Release" } includedirs { path.join(LLVMRootDirRelease, "include"), path.join(LLVMRootDirRelease, "tools/clang/include"), path.join(LLVMRootDirRelease, "tools/clang/lib"), path.join(LLVMRootDirRelease, "build/include"), path.join(LLVMRootDirRelease, "build/tools/clang/include"), } else local LLVMBuildDir = get_llvm_build_dir() includedirs { path.join(LLVMRootDir, "include"), path.join(LLVMRootDir, "tools/clang/include"), path.join(LLVMRootDir, "tools/clang/lib"), path.join(LLVMBuildDir, "include"), path.join(LLVMBuildDir, "tools/clang/include"), } end filter(c) end function CopyClangIncludes() local clangBuiltinIncludeDir = path.join(LLVMRootDir, "lib") if LLVMDirPerConfiguration then local clangBuiltinDebug = path.join(LLVMRootDirDebug, "lib") local clangBuiltinRelease = path.join(LLVMRootDirRelease, "lib") if os.isdir(path.join(clangBuiltinDebug, "clang")) then clangBuiltinIncludeDir = clangBuiltinDebug end if os.isdir(path.join(clangBuiltinRelease, "clang")) then clangBuiltinIncludeDir = clangBuiltinRelease end end if os.isdir(clangBuiltinIncludeDir) then postbuildcommands { -- Workaround Premake OS-specific behaviour when copying folders: -- See: https://github.com/premake/premake-core/issues/1232 '{RMDIR} "%%{cfg.buildtarget.directory}/lib"', '{MKDIR} "%%{cfg.buildtarget.directory}/lib"', string.format('{COPY} "%s" "%%{cfg.buildtarget.directory}/lib"', clangBuiltinIncludeDir) } end end function SetupLLVMLibs() local c = filter() filter { "action:not vs*" } defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" } filter { "system:macosx" } links { "c++", "curses", "pthread", "z" } filter { "action:vs*" } links { "version" } filter {} if LLVMDirPerConfiguration then filter { "configurations:Debug" } libdirs { path.join(LLVMRootDirDebug, "build/lib") } filter { "configurations:Release" } libdirs { path.join(LLVMRootDirRelease, "build/lib") } else local LLVMBuildDir = get_llvm_build_dir() libdirs { path.join(LLVMBuildDir, "lib") } filter { "configurations:Debug", "action:vs*" } libdirs { path.join(LLVMBuildDir, "Debug/lib") } filter { "configurations:Release", "action:vs*" } libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") } end filter {} links { "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic", "clangIndex", "LLVMLinker", "LLVMipo", "LLVMVectorize", "LLVMBitWriter", "LLVMIRReader", "LLVMAsmParser", "LLVMOption", "LLVMInstrumentation", "LLVMProfileData", "LLVMX86AsmParser", "LLVMX86Desc", "LLVMObject", "LLVMMCParser", "LLVMBitReader", "LLVMX86Info", "LLVMX86Utils", "LLVMX86CodeGen", "LLVMX86Disassembler", "LLVMCodeGen", "LLVMSelectionDAG", "LLVMGlobalISel", "LLVMDebugInfoCodeView", "LLVMScalarOpts", "LLVMInstCombine", "LLVMTransformUtils", "LLVMAnalysis", "LLVMTarget", "LLVMMCDisassembler", "LLVMMC", "LLVMCoverage", "LLVMCore", "LLVMSupport", "LLVMBinaryFormat", "LLVMDemangle", "LLVMRemarks" } filter(c) end
Always re-create the Clang resource directory when building.
Always re-create the Clang resource directory when building. This makes sure that the copy is always done correctly, due to the Premake bug.
Lua
mit
ddobrev/CppSharp,mono/CppSharp,ddobrev/CppSharp,mono/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,mono/CppSharp,mono/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,mono/CppSharp,ddobrev/CppSharp,mono/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp
f705335395987932791b8ddaa0db4b14f68078aa
modules/rroulette.lua
modules/rroulette.lua
local rr = ivar2.persist if(not ivar2.timers) then ivar2.timers = {} end local getBullet = function(n) return n % 10 end local getChamber = function(n) return (n - getBullet(n)) / 10 % 10 end return { PRIVMSG = { ['^%prr$'] = function(self, source, destination) local nick = source.nick if(not rr['rr:'..destination]) then rr['rr:'..destination] = 60 + math.random(1,6) end local bullet = getBullet(rr['rr:'..destination]) local chamber = getChamber(rr['rr:'..destination]) local deathKey = destination .. ':' .. nick .. ':deaths' local attemptKey = destination .. ':' .. nick .. ':attempts' local deaths = rr['rr:'..deathKey] or 0 local attempts = (rr['rr:'..attemptKey] or 0) + 1 local seed = math.random(1, chamber) if(seed == bullet) then bullet = math.random(1, 6) chamber = 6 deaths = deaths + 1 self:Kick(destination, nick, 'BANG!') say('BANG! %s died a gruesome death.', source.nick) else chamber = chamber - 1 if(bullet > chamber) then bullet = chamber end local src = 'Russian Roulette:' .. destination local timer = self:Timer(src, 15*60, function(loop, timer, revents) local n = rr['rr:'..destination] rr['rr:'..destination] = 60 + math.random(1,6) end) say('Click. %d/6', chamber) end rr['rr:'..destination] = (chamber * 10) + bullet rr['rr:'..deathKey] = deaths rr['rr:'..attemptKey] = attempts end, ['^%prrstat$'] = function(self, source, destination) local nicks = {} for n,t in pairs(self.channels[destination].nicks) do nicks[n] = destination..':'..n end local tmp = {} for nick, key in next, nicks do if(not tmp[nick]) then tmp[nick] = {} end type = 'attempts' res = tonumber(rr['rr:'..key..':'..type]) if not res then res = 0 end tmp[nick][type] = res type = 'deaths' res = tonumber(rr['rr:'..key..':'..type]) if not res then res = 0 end tmp[nick][type] = res end local stats = {} for nick, data in next, tmp do if data.deaths > 0 or data.attempts > 0 then local deathRatio = data.deaths / data.attempts table.insert(stats, {nick = nick, deaths = data.deaths, attempts = data.attempts, ratio = deathRatio}) end end table.sort(stats, function(a,b) return a.ratio < b.ratio end) local out = {} for i=1, #stats do table.insert(out, string.format('%s (%.1f%%)', stats[i].nick, (1 - stats[i].ratio) * 100)) end say('Survival rate: %s', ivar2.util.nonickalert(self.channels[destination].nicks, table.concat(out, ', '))) end, } }
local rr = ivar2.persist local getBullet = function(n) return n % 10 end local getChamber = function(n) return (n - getBullet(n)) / 10 % 10 end return { PRIVMSG = { ['^%prr$'] = function(self, source, destination) local nick = source.nick if(not rr['rr:'..destination]) then rr['rr:'..destination] = 60 + math.random(1,6) end local bullet = getBullet(rr['rr:'..destination]) local chamber = getChamber(rr['rr:'..destination]) local deathKey = destination .. ':' .. nick .. ':deaths' local attemptKey = destination .. ':' .. nick .. ':attempts' local deaths = rr['rr:'..deathKey] or 0 local attempts = (rr['rr:'..attemptKey] or 0) + 1 local seed = math.random(1, chamber) if(seed == bullet) then bullet = math.random(1, 6) chamber = 6 deaths = deaths + 1 self:Kick(destination, nick, 'BANG!') say('BANG! %s died a gruesome death.', source.nick) else chamber = chamber - 1 if(bullet > chamber) then bullet = chamber end local src = 'Russian Roulette:' .. destination local timer = self:Timer(src, 15*60, function(loop, timer, revents) local n = rr['rr:'..destination] rr['rr:'..destination] = 60 + math.random(1,6) end) say('Click. %d/6', chamber) end rr['rr:'..destination] = (chamber * 10) + bullet rr['rr:'..deathKey] = deaths rr['rr:'..attemptKey] = attempts end, ['^%prrstat$'] = function(self, source, destination) local nicks = {} for n,t in pairs(self.channels[destination].nicks) do nicks[n] = destination..':'..n end local tmp = {} for nick, key in next, nicks do if(not tmp[nick]) then tmp[nick] = {} end local rtype = 'attempts' local res = tonumber(rr['rr:'..key..':'..rtype]) if not res then res = 0 end tmp[nick][rtype] = res rtype = 'deaths' res = tonumber(rr['rr:'..key..':'..rtype]) if not res then res = 0 end tmp[nick][rtype] = res end local stats = {} for nick, data in next, tmp do if data.deaths > 0 or data.attempts > 0 then local deathRatio = data.deaths / data.attempts table.insert(stats, {nick = nick, deaths = data.deaths, attempts = data.attempts, ratio = deathRatio}) end end table.sort(stats, function(a,b) return a.ratio < b.ratio end) local out = {} for i=1, #stats do table.insert(out, string.format('%s (%.1f%%)', stats[i].nick, (1 - stats[i].ratio) * 100)) end say('Survival rate: %s', ivar2.util.nonickalert(self.channels[destination].nicks, table.concat(out, ', '))) end, } }
rroulette: fix variables usage
rroulette: fix variables usage Former-commit-id: 9d1f86aae043890d95cabb1cc2187dc9c09b3ef6 [formerly e9a99e43548986f1dbe8414395814b3dc9a24d06] Former-commit-id: f9dd5f6aea2a950e324810b061649f3dcfccba46
Lua
mit
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
f34f3a6609314b384a8de3daef3eb62902e99e69
Pointwise.lua
Pointwise.lua
local Pointwise, parent = torch.class('cudnn._Pointwise','nn.Module') local errcheck = cudnn.errcheck function Pointwise:__init(inplace) parent.__init(self) self.inplace = inplace or false end function Pointwise:createIODescriptors(input) assert(self.mode, 'mode is not set. (trying to use base class?)'); assert(input:isContiguous(), 'Non-contiguous inputs not supported yet'); local nElem = input:nElement() self.nElem = self.nElem or nElem -- this goes to the second branch only once if self.iDesc and nElem == self.nElem then return end self.nElem = nElem self.iDesc = cudnn.toDescriptor(input:view(1,1,1,nElem)) if not self.inplace then self.gradInput:resizeAs(input) self.output:resizeAs(input) end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); function Pointwise:updateOutput(input) self:createIODescriptors(input) if self.inplace then self.output = input end errcheck('cudnnActivationForward', cudnn.getHandle(), self.mode, one:data(), self.iDesc[0], input:data(), zero:data(), self.iDesc[0], self.output:data()); return self.output end function Pointwise:updateGradInput(input, gradOutput) if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new():resizeAs(gradOutput) self._gradOutput:copy(gradOutput) gradOutput = self._gradOutput end self:createIODescriptors(input) if self.inplace then self.output = input; self.gradInput = gradOutput end errcheck('cudnnActivationBackward', cudnn.getHandle(), self.mode, one:data(), self.iDesc[0], self.output:data(), self.iDesc[0], gradOutput:data(), self.iDesc[0], input:data(), zero:data(), self.iDesc[0], self.gradInput:data()); return self.gradInput end function Pointwise:write(f) self.iDesc = nil local var = {} for k,v in pairs(self) do var[k] = v end f:writeObject(var) end
local Pointwise, parent = torch.class('cudnn._Pointwise','nn.Module') local errcheck = cudnn.errcheck function Pointwise:__init(inplace) parent.__init(self) self.inplace = inplace or false end function Pointwise:createIODescriptors(input) assert(self.mode, 'mode is not set. (trying to use base class?)'); assert(input:isContiguous(), 'Non-contiguous inputs not supported yet'); if not self.inplace then self.gradInput:resizeAs(input) self.output:resizeAs(input) end local nElem = input:nElement() self.nElem = self.nElem or nElem -- this goes to the second branch only once if self.iDesc and nElem == self.nElem then return end self.nElem = nElem self.iDesc = cudnn.toDescriptor(input:view(1,1,1,nElem)) end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); function Pointwise:updateOutput(input) self:createIODescriptors(input) if self.inplace then self.output = input end errcheck('cudnnActivationForward', cudnn.getHandle(), self.mode, one:data(), self.iDesc[0], input:data(), zero:data(), self.iDesc[0], self.output:data()); return self.output end function Pointwise:updateGradInput(input, gradOutput) if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new():resizeAs(gradOutput) self._gradOutput:copy(gradOutput) gradOutput = self._gradOutput end self:createIODescriptors(input) if self.inplace then self.output = input; self.gradInput = gradOutput end errcheck('cudnnActivationBackward', cudnn.getHandle(), self.mode, one:data(), self.iDesc[0], self.output:data(), self.iDesc[0], gradOutput:data(), self.iDesc[0], input:data(), zero:data(), self.iDesc[0], self.gradInput:data()); return self.gradInput end function Pointwise:write(f) self.iDesc = nil local var = {} for k,v in pairs(self) do var[k] = v end f:writeObject(var) end
fixing small bug where inputs passed in were same number of elements as previous input, but different shape
fixing small bug where inputs passed in were same number of elements as previous input, but different shape
Lua
bsd-3-clause
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
b7408795978c7c8b45a9c8b8c29585bbf82c7b07
xmake/platforms/windows/config.lua
xmake/platforms/windows/config.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file config.lua -- -- imports import("core.project.config") import("core.base.singleton") import("core.platform.environment") import("private.platform.toolchain") import("private.platform.check_arch") import("private.platform.check_vstudio") import("private.platform.check_toolchain") -- get toolchains function _toolchains() -- init cross local cross = "xcrun -sdk macosx " -- init toolchains local cc = toolchain("the c compiler") local cxx = toolchain("the c++ compiler") local mrc = toolchain("the resource compiler") local ld = toolchain("the linker") local sh = toolchain("the shared library linker") local ar = toolchain("the static library archiver") local ex = toolchain("the static library extractor") local as = toolchain("the assember") local gc = toolchain("the golang compiler") local gc_ld = toolchain("the golang linker") local gc_ar = toolchain("the golang static library archiver") local dc = toolchain("the dlang compiler") local dc_ld = toolchain("the dlang linker") local dc_sh = toolchain("the dlang shared library linker") local dc_ar = toolchain("the dlang static library archiver") local rc = toolchain("the rust compiler") local rc_ld = toolchain("the rust linker") local rc_sh = toolchain("the rust shared library linker") local rc_ar = toolchain("the rust static library archiver") local cu = toolchain("the cuda compiler") local cu_ld = toolchain("the cuda linker") local toolchains = {cc = cc, cxx = cxx, mrc = mrc, as = as, ld = ld, sh = sh, ar = ar, ex = ex, gc = gc, ["gc-ld"] = gc_ld, ["gc-ar"] = gc_ar, dc = dc, ["dc-ld"] = dc_ld, ["dc-sh"] = dc_sh, ["dc-ar"] = dc_ar, rc = rc, ["rc-ld"] = rc_ld, ["rc-sh"] = rc_sh, ["rc-ar"] = rc_ar, cu = cu, ["cu-ld"] = cu_ld} -- init the c compiler cc:add("cl.exe") -- init the c++ compiler cxx:add("cl.exe") -- init the resource compiler mrc:add("rc.exe") -- init the assember if config.get("arch"):find("64") then as:add("ml64.exe") else as:add("ml.exe") end -- init the linker ld:add("link.exe") -- init the shared library linker sh:add("link.exe -dll") -- init the static library archiver ar:add("link.exe -lib") -- init the static library extractor ex:add("lib.exe") -- init the golang compiler and linker gc:add("$(env GC)", "go", "gccgo") gc_ld:add("$(env GC)", "go", "gccgo") gc_ar:add("$(env GC)", "go", "gccgo") -- init the dlang compiler and linker dc:add("$(env DC)", "dmd", "ldc2", "gdc") dc_ld:add("$(env DC)", "dmd", "ldc2", "gdc") dc_sh:add("$(env DC)", "dmd", "ldc2", "gdc") dc_ar:add("$(env DC)", "dmd", "ldc2", "gdc") -- init the rust compiler and linker rc:add("$(env RC)", "rustc") rc_ld:add("$(env RC)", "rustc") rc_sh:add("$(env RC)", "rustc") rc_ar:add("$(env RC)", "rustc") -- init the cuda compiler and linker cu:add("nvcc", "clang") cu_ld:add("nvcc") return toolchains end -- check it function main(platform, name) -- only check the given config name? if name then local toolchain = singleton.get("windows.toolchains." .. (config.get("arch") or os.arch()), _toolchains)[name] if toolchain then environment.enter("toolchains") check_toolchain(config, name, toolchain) environment.leave("toolchains") end else -- check arch check_arch(config) -- check vstudio check_vstudio(config) end end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file config.lua -- -- imports import("core.project.config") import("core.base.singleton") import("core.platform.environment") import("private.platform.toolchain") import("private.platform.check_arch") import("private.platform.check_vstudio") import("private.platform.check_toolchain") -- get toolchains function _toolchains() -- init cross local cross = "xcrun -sdk macosx " -- init toolchains local cc = toolchain("the c compiler") local cxx = toolchain("the c++ compiler") local mrc = toolchain("the resource compiler") local ld = toolchain("the linker") local sh = toolchain("the shared library linker") local ar = toolchain("the static library archiver") local ex = toolchain("the static library extractor") local as = toolchain("the assember") local gc = toolchain("the golang compiler") local gc_ld = toolchain("the golang linker") local gc_ar = toolchain("the golang static library archiver") local dc = toolchain("the dlang compiler") local dc_ld = toolchain("the dlang linker") local dc_sh = toolchain("the dlang shared library linker") local dc_ar = toolchain("the dlang static library archiver") local rc = toolchain("the rust compiler") local rc_ld = toolchain("the rust linker") local rc_sh = toolchain("the rust shared library linker") local rc_ar = toolchain("the rust static library archiver") local cu = toolchain("the cuda compiler") local cu_ld = toolchain("the cuda linker") local toolchains = {cc = cc, cxx = cxx, mrc = mrc, as = as, ld = ld, sh = sh, ar = ar, ex = ex, gc = gc, ["gc-ld"] = gc_ld, ["gc-ar"] = gc_ar, dc = dc, ["dc-ld"] = dc_ld, ["dc-sh"] = dc_sh, ["dc-ar"] = dc_ar, rc = rc, ["rc-ld"] = rc_ld, ["rc-sh"] = rc_sh, ["rc-ar"] = rc_ar, cu = cu, ["cu-ld"] = cu_ld} -- init the c compiler cc:add("cl.exe") -- init the c++ compiler cxx:add("cl.exe") -- init the resource compiler mrc:add("rc.exe") -- init the assember local arch = config.get("arch") if arch and arch:find("64") then as:add("ml64.exe") else as:add("ml.exe") end -- init the linker ld:add("link.exe") -- init the shared library linker sh:add("link.exe -dll") -- init the static library archiver ar:add("link.exe -lib") -- init the static library extractor ex:add("lib.exe") -- init the golang compiler and linker gc:add("$(env GC)", "go", "gccgo") gc_ld:add("$(env GC)", "go", "gccgo") gc_ar:add("$(env GC)", "go", "gccgo") -- init the dlang compiler and linker dc:add("$(env DC)", "dmd", "ldc2", "gdc") dc_ld:add("$(env DC)", "dmd", "ldc2", "gdc") dc_sh:add("$(env DC)", "dmd", "ldc2", "gdc") dc_ar:add("$(env DC)", "dmd", "ldc2", "gdc") -- init the rust compiler and linker rc:add("$(env RC)", "rustc") rc_ld:add("$(env RC)", "rustc") rc_sh:add("$(env RC)", "rustc") rc_ar:add("$(env RC)", "rustc") -- init the cuda compiler and linker cu:add("nvcc", "clang") cu_ld:add("nvcc") return toolchains end -- check it function main(platform, name) -- only check the given config name? if name then local toolchain = singleton.get("windows.toolchains." .. (config.get("arch") or os.arch()), _toolchains)[name] if toolchain then environment.enter("toolchains") check_toolchain(config, name, toolchain) environment.leave("toolchains") end else -- check arch check_arch(config) -- check vstudio check_vstudio(config) end end
fix windows config
fix windows config
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
a02964671127ff6b54370be714ab440307c70526
game/scripts/vscripts/heroes/bosses/cursed_zeld/mind_crack.lua
game/scripts/vscripts/heroes/bosses/cursed_zeld/mind_crack.lua
boss_cursed_zeld_mind_crack = {} if IsServer() then function boss_cursed_zeld_mind_crack:OnSpellStart() local caster = self:GetCaster() local health = self:GetSpecialValueFor("clone_health") local modelScale = self:GetSpecialValueFor("clone_model_scale") local armor = caster:GetPhysicalArmorBaseValue() local damageMultiplier = self:GetSpecialValueFor("clone_damage_pct") * 0.01 local damageMin = caster:GetBaseDamageMin() * damageMultiplier local damageMax = caster:GetBaseDamageMax() * damageMultiplier for i = 1, self:GetSpecialValueFor("clone_count") do local clone = CreateUnitByName(caster:GetUnitName(), caster:GetAbsOrigin() + RandomVector(400), true, nil, nil, caster:GetTeamNumber()) clone.isMindCrackClone = true clone:SetBaseMaxHealth(health) clone:SetMaxHealth(health) clone:SetHealth(health) clone:SetPhysicalArmorBaseValue(armor) clone:SetBaseDamageMin(damageMin) clone:SetBaseDamageMax(damageMax) clone:SetModelScale(modelScale) clone:SetDeathXP(0) clone:FindAbilityByName("boss_cursed_zeld_shadows_curse"):SetActivated(false) clone:FindAbilityByName("boss_cursed_zeld_mind_crack"):SetActivated(false) clone:FindAbilityByName("boss_cursed_zeld_mental_influence"):SetActivated(false) end end end
boss_cursed_zeld_mind_crack = {} if IsServer() then function boss_cursed_zeld_mind_crack:OnSpellStart() local caster = self:GetCaster() local health = self:GetSpecialValueFor("clone_health") local modelScale = self:GetSpecialValueFor("clone_model_scale") local armor = caster:GetPhysicalArmorBaseValue() local damageMultiplier = self:GetSpecialValueFor("clone_damage_pct") * 0.01 local damageMin = caster:GetBaseDamageMin() * damageMultiplier local damageMax = caster:GetBaseDamageMax() * damageMultiplier for i = 1, self:GetSpecialValueFor("clone_count") do local clone = CreateUnitByName(caster:GetUnitName(), caster:GetAbsOrigin() + RandomVector(400), true, nil, nil, caster:GetTeamNumber()) clone.isMindCrackClone = true clone:SetBaseMaxHealth(health) clone:SetMaxHealth(health) clone:SetHealth(health) clone:SetPhysicalArmorBaseValue(armor) clone:SetBaseDamageMin(damageMin) clone:SetBaseDamageMax(damageMax) clone:SetModelScale(modelScale) clone:SetDeathXP(0) clone:FindAbilityByName("boss_cursed_zeld_shadows_curse"):SetActivated(false) clone:FindAbilityByName("boss_cursed_zeld_mind_crack"):SetActivated(false) clone:FindAbilityByName("boss_cursed_zeld_mental_influence"):SetActivated(false) Bosses:MakeBossAI(clone, "cursed_zeld", {}) end end end
feat(bosses): make Mind Crack units have the same ai as main boss
feat(bosses): make Mind Crack units have the same ai as main boss Fixes #356.
Lua
mit
ark120202/aabs
53ff282da3ffd23b273f21c0e5d98fa78548c97d
GaborLayer.lua
GaborLayer.lua
-- Clement's old gabor function require 'image' require 'lab' require 'xlua' -- For the similar Gabor code go to -- http://www.mathworks.com/matlabcentral/fileexchange/23253-gabor-filter/content/Gabor%20Filter/gabor_fn.m -- Size should be odd number -- angle (in rad) -- elipse_ratio = aspect ratio(0.5) function gabor(size, sigma, angle, period, ellipse_ratio) -- init matrix local data = lab.zeros(size,size) -- image -> pixel period = period * size sigma = sigma * size -- set params local halfsize = math.floor(size/2) local sigma_x = sigma local sigma_y = sigma/ellipse_ratio for y=-halfsize,halfsize do for x=-halfsize,halfsize do x_angle = x*math.cos(angle) + y*math.sin(angle) y_angle = -x*math.sin(angle) + y*math.cos(angle) data[x+halfsize+1][y+halfsize+1] = math.exp(-0.5*(x_angle^2/sigma_x^2 + y_angle^2/sigma_y^2)) * math.cos(2*math.pi*x_angle/period) end end -- return new tensor return data end
-- Clement's old gabor function require 'image' require 'xlua' -- For the similar Gabor code go to -- http://www.mathworks.com/matlabcentral/fileexchange/23253-gabor-filter/content/Gabor%20Filter/gabor_fn.m -- Size should be odd number -- angle (in rad) -- elipse_ratio = aspect ratio(0.5) -- In order to get some understanding you can run the following test --[[ win = nil sz = 13 s = .125 f = 2 r = .5 for a = 0,180,30 do alpha = a/180*math.pi win=image.display{image=gabor(sz,s,alpha,1/f,r),zoom=20,win=win,legend='alpha = ' .. a .. 'deg'} io.read() end ]] function gabor(size, sigma, angle, period, ellipse_ratio) -- init matrix local data = torch.zeros(size,size) -- image -> pixel period = period * size sigma = sigma * size -- set params local halfsize = math.floor(size/2) local sigma_x = sigma local sigma_y = sigma/ellipse_ratio for y=-halfsize,halfsize do for x=-halfsize,halfsize do x_angle = x*math.cos(angle) + y*math.sin(angle) y_angle = -x*math.sin(angle) + y*math.cos(angle) data[x+halfsize+1][y+halfsize+1] = math.exp(-0.5*(x_angle^2/sigma_x^2 + y_angle^2/sigma_y^2)) * math.cos(2*math.pi*x_angle/period) end end -- return new tensor return data end
Fixed requires and added live example
Fixed requires and added live example
Lua
bsd-3-clause
e-lab/eex
4f1199af09fbcba399f7ecf94e7f21b9edc3622d
busted/outputHandlers/TAP.lua
busted/outputHandlers/TAP.lua
local pretty = require 'pl.pretty' return function(options) local busted = require 'busted' local handler = require 'busted.outputHandlers.base'() local success = 'ok %u - %s' local failure = 'not ' .. success local skip = 'ok %u - # SKIP %s' local counter = 0 handler.suiteReset = function() counter = 0 return nil, true end handler.suiteEnd = function() print('1..' .. counter) return nil, true end local function showFailure(t) local message = t.message local trace = t.trace or {} if message == nil then message = 'Nil error' elseif type(message) ~= 'string' then message = pretty.write(message) end print(failure:format(counter, t.name)) print('# ' .. t.element.trace.short_src .. ' @ ' .. t.element.trace.currentline) if t.randomseed then print('# Random seed: ' .. t.randomseed) end print('# Failure message: ' .. message:gsub('\n', '\n# ')) if options.verbose and trace.traceback then print('# ' .. trace.traceback:gsub('^\n', '', 1):gsub('\n', '\n# ')) end end handler.testStart = function(element, parent) local trace = element.trace if options.verbose and trace and trace.short_src then local fileline = trace.short_src .. ' @ ' .. trace.currentline .. ': ' local testName = fileline .. handler.getFullName(element) print('# ' .. testName) end return nil, true end handler.testEnd = function(element, parent, status, trace) counter = counter + 1 if status == 'success' then local t = handler.successes[#handler.successes] print(success:format(counter, t.name)) elseif status == 'pending' then local t = handler.pendings[#handler.pendings] print(skip:format(counter, (t.message or t.name))) elseif status == 'failure' then showFailure(handler.failures[#handler.failures]) elseif status == 'error' then showFailure(handler.errors[#handler.errors]) end return nil, true end handler.error = function(element, parent, message, debug) if element.descriptor ~= 'it' then counter = counter + 1 showFailure(handler.errors[#handler.errors]) end return nil, true end busted.subscribe({ 'suite', 'reset' }, handler.suiteReset) busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) busted.subscribe({ 'test', 'start' }, handler.testStart) busted.subscribe({ 'test', 'end' }, handler.testEnd) busted.subscribe({ 'error' }, handler.error) return handler end
local pretty = require 'pl.pretty' return function(options) local busted = require 'busted' local handler = require 'busted.outputHandlers.base'() local success = 'ok %u - %s' local failure = 'not ' .. success local skip = 'ok %u - # SKIP %s' local counter = 0 handler.suiteReset = function() counter = 0 return nil, true end handler.suiteEnd = function() print('1..' .. counter) return nil, true end local function showFailure(t) local message = t.message local trace = t.trace or {} if message == nil then message = 'Nil error' elseif type(message) ~= 'string' then message = pretty.write(message) end print(failure:format(counter, t.name)) print('# ' .. t.element.trace.short_src .. ' @ ' .. t.element.trace.currentline) if t.randomseed then print('# Random seed: ' .. t.randomseed) end print('# Failure message: ' .. message:gsub('\n', '\n# ')) if options.verbose and trace.traceback then print('# ' .. trace.traceback:gsub('^\n', '', 1):gsub('\n', '\n# ')) end end handler.testStart = function(element, parent) local trace = element.trace if options.verbose and trace and trace.short_src then local fileline = trace.short_src .. ' @ ' .. trace.currentline .. ': ' local testName = fileline .. handler.getFullName(element) print('# ' .. testName) end return nil, true end handler.testEnd = function(element, parent, status, trace) counter = counter + 1 if status == 'success' then local t = handler.successes[#handler.successes] print(success:format(counter, t.name)) elseif status == 'pending' then local t = handler.pendings[#handler.pendings] print(skip:format(counter, (t.message or t.name))) elseif status == 'failure' then showFailure(handler.failures[#handler.failures]) elseif status == 'error' then showFailure(handler.errors[#handler.errors]) end return nil, true end handler.error = function(element, parent, message, debug) if element.descriptor ~= 'it' then counter = counter + 1 showFailure(handler.errors[#handler.errors]) end return nil, true end busted.subscribe({ 'suite', 'reset' }, handler.suiteReset) busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) busted.subscribe({ 'test', 'start' }, handler.testStart, { predicate = handler.cancelOnPending }) busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending }) busted.subscribe({ 'error' }, handler.error) return handler end
Fix TAP output handler for --suppress-pending option
Fix TAP output handler for --suppress-pending option This fixes a bug in the TAP output handler causing busted to exit with an error when the `--suppress-pending` command-line option is used.
Lua
mit
o-lim/busted,Olivine-Labs/busted
aa0a1e428ca0a7a547d9692bcdb16fa728947379
entity/wave.lua
entity/wave.lua
local Wave = {} Wave.__index = Wave function Wave.create(def, game) local wave = { game = game } setmetatable(wave, Wave) return wave end function Wave:update(dt) end function Wave:draw() love.graphics.setCanvas(self.game.preCanvas) love.graphics.draw(self.game.canvas) love.graphics.setCanvas(self.game.canvas) love.graphics.setShader(pullShader) love.graphics.setColor(255,255,255,255) pullShader:send('timer', love.timer.getTime( )); pullShader:send('startAt',PLAYER_RADIUS); local pullings = {}; local pullingsPosition = {}; local pullingsLength = {}; local pullingsDirection = {}; local pushings = {}; local pushingsLength = {}; local pushingsPosition = {} for k, player in pairs(self.game.players) do if player.pullApplied > 0 then table.insert(pullings, player.pullApplied * (player.active and 1 or player.deathTimer)); local pullx, pully = player:pullPosition() table.insert(pullingsPosition, {pullx, pully}); table.insert(pullingsLength, PULL_LENGTH); table.insert(pullingsDirection, -1); end if player.pushCd > 0 then table.insert(pushings, (PUSH_COOLDOWN - player.pushCd) / PUSH_ANIMATION * (player.active and 1 or player.deathTimer)); table.insert(pushingsPosition, {player.body:getX(), player.body:getY()}); table.insert(pushingsLength, PUSH_LENGTH); end end for k, puller in pairs(self.game.pullers) do table.insert(pullings, 1); table.insert(pullingsPosition, {puller.x, puller.y}); table.insert(pullingsLength, PULLER_RANGE); table.insert(pullingsDirection, -1); end for k, pusher in pairs(self.game.pushers) do table.insert(pullings, 1); table.insert(pullingsPosition, {pusher.x, pusher.y}); table.insert(pullingsLength, PULLER_RANGE); table.insert(pullingsDirection, 1); end for k, bump in pairs(self.game.bumps) do local time = 1 - (bump.timer / BUMP_PUSH_ANIMATION); local startAt = BUMP_PUSH_MIN / BUMP_PUSH_LENGTH; time = time * ( 1 - startAt ) + startAt; local bumpx,bumpy = bump:pushPosition() table.insert(pushings, time); table.insert(pushingsPosition, {bumpx, bumpy}); table.insert(pushingsLength, BUMP_PUSH_LENGTH); end local nbPosition = #pullings; for i = nbPosition + 1, 6 do table.insert(pullings, 0); table.insert(pullingsPosition, {0, 0}); table.insert(pullingsLength, 0); table.insert(pullingsDirection, 0); end pullShader:send('pullings', unpack(pullings)); pullShader:send('pullingsPosition', unpack(pullingsPosition)); pullShader:send('pullingsLength', unpack(pullingsLength)); pullShader:send('pullingsDirection', unpack(pullingsDirection)); nbPosition = #pushings; for i = nbPosition + 1, 8 do table.insert(pushings, 0); table.insert(pushingsPosition, {0, 0}); table.insert(pushingsLength, 0); end pullShader:send('pushings', unpack(pushings)); pullShader:send('pushingsPosition', unpack(pushingsPosition)); pullShader:send('pushingsLength', unpack(pushingsLength)); love.graphics.draw(self.game.preCanvas) love.graphics.reset() love.graphics.setCanvas(self.game.canvas) end return Wave
local Wave = {} Wave.__index = Wave function Wave.create(def, game) local wave = { game = game } setmetatable(wave, Wave) return wave end function Wave:update(dt) end function Wave:draw() love.graphics.setCanvas(self.game.preCanvas) love.graphics.draw(self.game.canvas) love.graphics.setCanvas(self.game.canvas) love.graphics.setShader(pullShader) love.graphics.setColor(255,255,255,255) pullShader:send('timer', love.timer.getTime( )); local pullings = {}; local pullingsPosition = {}; local pullingsLength = {}; local pullingsDirection = {}; local pushings = {}; local pushingsLength = {}; local pushingsPosition = {} for k, player in pairs(self.game.players) do if player.pullApplied > 0 then table.insert(pullings, player.pullApplied * (player.active and 1 or player.deathTimer)); local pullx, pully = player:pullPosition() table.insert(pullingsPosition, {pullx, pully}); table.insert(pullingsLength, PULL_LENGTH); table.insert(pullingsDirection, -1); end if player.pushCd > 0 then table.insert(pushings, (PUSH_COOLDOWN - player.pushCd) / PUSH_ANIMATION * (player.active and 1 or player.deathTimer)); table.insert(pushingsPosition, {player.body:getX(), player.body:getY()}); table.insert(pushingsLength, PUSH_LENGTH); end end for k, puller in pairs(self.game.pullers) do table.insert(pullings, 1); table.insert(pullingsPosition, {puller.x, puller.y}); table.insert(pullingsLength, PULLER_RANGE); table.insert(pullingsDirection, -1); end for k, pusher in pairs(self.game.pushers) do table.insert(pullings, 1); table.insert(pullingsPosition, {pusher.x, pusher.y}); table.insert(pullingsLength, PULLER_RANGE); table.insert(pullingsDirection, 1); end for k, bump in pairs(self.game.bumps) do local time = 1 - (bump.timer / BUMP_PUSH_ANIMATION); local startAt = BUMP_PUSH_MIN / BUMP_PUSH_LENGTH; time = time * ( 1 - startAt ) + startAt; local bumpx,bumpy = bump:pushPosition() table.insert(pushings, time); table.insert(pushingsPosition, {bumpx, bumpy}); table.insert(pushingsLength, BUMP_PUSH_LENGTH); end local nbPosition = #pullings; for i = nbPosition + 1, 6 do table.insert(pullings, 0); table.insert(pullingsPosition, {0, 0}); table.insert(pullingsLength, 0); table.insert(pullingsDirection, 0); end pullShader:send('pullings', unpack(pullings)); pullShader:send('pullingsPosition', unpack(pullingsPosition)); pullShader:send('pullingsLength', unpack(pullingsLength)); pullShader:send('pullingsDirection', unpack(pullingsDirection)); nbPosition = #pushings; for i = nbPosition + 1, 8 do table.insert(pushings, 0); table.insert(pushingsPosition, {0, 0}); table.insert(pushingsLength, 0); end pullShader:send('pushings', unpack(pushings)); pullShader:send('pushingsPosition', unpack(pushingsPosition)); pullShader:send('pushingsLength', unpack(pushingsLength)); love.graphics.draw(self.game.preCanvas) love.graphics.reset() love.graphics.setCanvas(self.game.canvas) end return Wave
Fix "startAt" on shader
Fix "startAt" on shader
Lua
mit
GuiSim/pixel
064c62b8bc757d39065da987a02eaee0c7e3e050
src_trunk/resources/realism-system/c_realism_system.lua
src_trunk/resources/realism-system/c_realism_system.lua
function realisticWeaponSounds(weapon) local x, y, z = getElementPosition(getLocalPlayer()) local tX, tY, tZ = getElementPosition(source) local distance = getDistanceBetweenPoints3D(x, y, z, tX, tY, tZ) if (distance<25) and (weapon>=22 and weapon<=34) then local randSound = math.random(27, 30) playSoundFrontEnd(randSound) end end addEventHandler("onClientPlayerWeaponFire", getRootElement(), realisticWeaponSounds) ------/////////////////////// Pig Pen Strippers ///////////////////////------ -- Stripper Isla View local islaView = createPed (152, 1216.30, -6.45, 1000.32) setElementInterior (islaView, 2) setElementDimension (islaView, 1197) setPedAnimation ( islaView, "STRIP", "STR_C1", -1, true, false, false) local islaDanceNumber = 1 -- Isla Dance Cycle function islaDance() if (islaDanceNumber == 1) then setPedAnimation ( islaView, "STRIP", "STR_Loop_C", -1, true, false, false) islaDanceNumber = islaDanceNumber + 1 elseif (islaDanceNumber == 2) then setPedAnimation ( islaView, "STRIP", "strip_D", -1, true, false, false) islaDanceNumber = islaDanceNumber + 1 elseif (islaDanceNumber == 3) then setPedAnimation ( islaView, "STRIP", "STR_C1", -1, true, false, false) islaDanceNumber = islaDanceNumber - 2 -- reset to 1 end end islaTimer = setTimer ( islaDance, 15000, 0) -- Stripper Angel Rain local angelRain = createPed (257, 1208.12, -6.05, 1000.32) setPedAnimation ( angelRain, "STRIP", "STR_C2", -1, true, false, false) setElementInterior (angelRain, 2) setElementDimension (angelRain, 1197) local angelDanceNumber = 1 -- Angel Dance Cycle function angelDance() if (angelDanceNumber == 1) then setPedAnimation ( angelRain, "STRIP", "Strip_Loop_B", -1, true, false, false) angelDanceNumber = angelDanceNumber + 1 elseif (angelDanceNumber == 2) then setPedAnimation ( angelRain, "STRIP", "STR_Loop_A", -1, true, false, false) angelDanceNumber = angelDanceNumber + 1 elseif (angelDanceNumber == 3) then setPedAnimation ( angelRain, "STRIP", "STR_C2", -1, true, false, false) angelDanceNumber = angelDanceNumber - 1 -- reset to 1 end end angelTimer = setTimer ( angelDance, 12000, 0) ------/////////////////////// Dragon Lady strippers ///////////////////////------ -- Stripper 1 local DrgStrip1 = createPed (140, 1216.30, -6.45, 1000.32) setElementInterior (DrgStrip1, 2) setElementDimension (DrgStrip1, 685) setPedAnimation ( DrgStrip1, "STRIP", "STR_C1", -1, true, false, false) local DrgStrip1DanceNumber = 1 -- Stripper 1 Cycle function DrgStrip1Dance() if (DrgStrip1DanceNumber == 1) then setPedAnimation ( DrgStrip1, "STRIP", "STR_C1", -1, true, false, false) DrgStrip1DanceNumber = DrgStrip1DanceNumber + 1 elseif (DrgStrip1DanceNumber == 2) then setPedAnimation ( DrgStrip1, "STRIP", "strip_D", -1, true, false, false) DrgStrip1DanceNumber = DrgStrip1DanceNumber + 1 elseif (DrgStrip1DanceNumber == 3) then setPedAnimation ( DrgStrip1, "STRIP", "strip_G", -1, true, false, false) DrgStrip1DanceNumber = DrgStrip1DanceNumber - 2 -- reset to 1 end end DrgStrip1Timer = setTimer ( DrgStrip1Dance, 15000, 0) -- Stripper 2 local DrgStrip2 = createPed (257, 1208.12, -6.05, 1000.32) setPedAnimation ( DrgStrip2, "STRIP", "STR_Loop_A", -1, true, false, false) setElementInterior (DrgStrip2, 2) setElementDimension (DrgStrip2, 685) local DrgStrip2DanceNumber = 1 -- Stripper 2 Cycle function DrgStrip2Dance() if (DrgStrip2DanceNumber == 1) then setPedAnimation ( DrgStrip2, "STRIP", "Strip_Loop_B", -1, true, false, false) DrgStrip2DanceNumber = DrgStrip2DanceNumber + 1 elseif (DrgStrip2DanceNumber == 2) then setPedAnimation ( DrgStrip2, "STRIP", "STR_Loop_A", -1, true, false, false) DrgStrip2DanceNumber = DrgStrip2DanceNumber + 1 elseif (DrgStrip2DanceNumber == 3) then setPedAnimation ( DrgStrip2, "STRIP", "STR_C2", -1, true, false, false) DrgStrip2DanceNumber = DrgStrip2DanceNumber - 1 -- reset to 1 end end DrgStrip2Timer = setTimer ( DrgStrip2Dance, 12000, 0)
copCars = { [427] = true, [490] = true, [528] = true, [523] = true, [596] = true, [597] = true, [598] = true, [599] = true, [601] = true } function onCopCarEnter(thePlayer, seat) if (seat < 2) and (thePlayer==getLocalPlayer()) then local model = getElementModel(source) if (copCars[model]) then setRadioChannel(0) end end end addEventHandler("onClientVehicleEnter", getRootElement(), onCopCarEnter) function realisticWeaponSounds(weapon) local x, y, z = getElementPosition(getLocalPlayer()) local tX, tY, tZ = getElementPosition(source) local distance = getDistanceBetweenPoints3D(x, y, z, tX, tY, tZ) if (distance<25) and (weapon>=22 and weapon<=34) then local randSound = math.random(27, 30) playSoundFrontEnd(randSound) end end addEventHandler("onClientPlayerWeaponFire", getRootElement(), realisticWeaponSounds) ------/////////////////////// Pig Pen Strippers ///////////////////////------ -- Stripper Isla View local islaView = createPed (152, 1216.30, -6.45, 1000.32) setElementInterior (islaView, 2) setElementDimension (islaView, 1197) setPedAnimation ( islaView, "STRIP", "STR_C1", -1, true, false, false) local islaDanceNumber = 1 -- Isla Dance Cycle function islaDance() if (islaDanceNumber == 1) then setPedAnimation ( islaView, "STRIP", "STR_Loop_C", -1, true, false, false) islaDanceNumber = islaDanceNumber + 1 elseif (islaDanceNumber == 2) then setPedAnimation ( islaView, "STRIP", "strip_D", -1, true, false, false) islaDanceNumber = islaDanceNumber + 1 elseif (islaDanceNumber == 3) then setPedAnimation ( islaView, "STRIP", "STR_C1", -1, true, false, false) islaDanceNumber = islaDanceNumber - 2 -- reset to 1 end end islaTimer = setTimer ( islaDance, 15000, 0) -- Stripper Angel Rain local angelRain = createPed (257, 1208.12, -6.05, 1000.32) setPedAnimation ( angelRain, "STRIP", "STR_C2", -1, true, false, false) setElementInterior (angelRain, 2) setElementDimension (angelRain, 1197) local angelDanceNumber = 1 -- Angel Dance Cycle function angelDance() if (angelDanceNumber == 1) then setPedAnimation ( angelRain, "STRIP", "Strip_Loop_B", -1, true, false, false) angelDanceNumber = angelDanceNumber + 1 elseif (angelDanceNumber == 2) then setPedAnimation ( angelRain, "STRIP", "STR_Loop_A", -1, true, false, false) angelDanceNumber = angelDanceNumber + 1 elseif (angelDanceNumber == 3) then setPedAnimation ( angelRain, "STRIP", "STR_C2", -1, true, false, false) angelDanceNumber = angelDanceNumber - 1 -- reset to 1 end end angelTimer = setTimer ( angelDance, 12000, 0) ------/////////////////////// Dragon Lady strippers ///////////////////////------ -- Stripper 1 local DrgStrip1 = createPed (140, 1216.30, -6.45, 1000.32) setElementInterior (DrgStrip1, 2) setElementDimension (DrgStrip1, 685) setPedAnimation ( DrgStrip1, "STRIP", "STR_C1", -1, true, false, false) local DrgStrip1DanceNumber = 1 -- Stripper 1 Cycle function DrgStrip1Dance() if (DrgStrip1DanceNumber == 1) then setPedAnimation ( DrgStrip1, "STRIP", "STR_C1", -1, true, false, false) DrgStrip1DanceNumber = DrgStrip1DanceNumber + 1 elseif (DrgStrip1DanceNumber == 2) then setPedAnimation ( DrgStrip1, "STRIP", "strip_D", -1, true, false, false) DrgStrip1DanceNumber = DrgStrip1DanceNumber + 1 elseif (DrgStrip1DanceNumber == 3) then setPedAnimation ( DrgStrip1, "STRIP", "strip_G", -1, true, false, false) DrgStrip1DanceNumber = DrgStrip1DanceNumber - 2 -- reset to 1 end end DrgStrip1Timer = setTimer ( DrgStrip1Dance, 15000, 0) -- Stripper 2 local DrgStrip2 = createPed (257, 1208.12, -6.05, 1000.32) setPedAnimation ( DrgStrip2, "STRIP", "STR_Loop_A", -1, true, false, false) setElementInterior (DrgStrip2, 2) setElementDimension (DrgStrip2, 685) local DrgStrip2DanceNumber = 1 -- Stripper 2 Cycle function DrgStrip2Dance() if (DrgStrip2DanceNumber == 1) then setPedAnimation ( DrgStrip2, "STRIP", "Strip_Loop_B", -1, true, false, false) DrgStrip2DanceNumber = DrgStrip2DanceNumber + 1 elseif (DrgStrip2DanceNumber == 2) then setPedAnimation ( DrgStrip2, "STRIP", "STR_Loop_A", -1, true, false, false) DrgStrip2DanceNumber = DrgStrip2DanceNumber + 1 elseif (DrgStrip2DanceNumber == 3) then setPedAnimation ( DrgStrip2, "STRIP", "STR_C2", -1, true, false, false) DrgStrip2DanceNumber = DrgStrip2DanceNumber - 1 -- reset to 1 end end DrgStrip2Timer = setTimer ( DrgStrip2Dance, 12000, 0)
Small radio fix for cop cars
Small radio fix for cop cars git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@979 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
65ac4d3ae3d4fd2b6d968ce266c6bca6eba816fd
modules/data/scale.lua
modules/data/scale.lua
sptbl["scale"] = { files = { module = "scale.c", header = "scale.h", example = "ex_scale.c", }, func = { create = "sp_scale_create", destroy = "sp_scale_destroy", init = "sp_scale_init", compute = "sp_scale_compute", }, params = { optional = { { name = "inmin", type = "SPFLOAT", description = "Minimum value to scale from.", default = -1 }, { name = "inmax", type = "SPFLOAT", description ="Maximum value to scale from.", default = 1 }, { name = "outmin", type = "SPFLOAT", description = "Minimum value to scale to.", default = 0 }, { name = "outmax", type = "SPFLOAT", description ="Maximum value to scale to.", default = 1 }, } }, modtype = "module", description = [[This module scales an incoming signal (in the range of -1, and 1), and scales it to an arbitrary range. ]], ninputs = 1, noutputs = 1, inputs = { { name = "in", description = "Signal to be scaled, expected to be in the range of +/-1." }, }, outputs = { { name = "out", description = "Signal out" }, } }
sptbl["scale"] = { files = { module = "scale.c", header = "scale.h", example = "ex_scale.c", }, func = { create = "sp_scale_create", destroy = "sp_scale_destroy", init = "sp_scale_init", compute = "sp_scale_compute", }, params = { optional = { { name = "inmin", type = "SPFLOAT", description = "Minimum value to scale from.", default = -1 }, { name = "inmax", type = "SPFLOAT", description ="Maximum value to scale from.", default = 1 }, { name = "outmin", type = "SPFLOAT", description = "Minimum value to scale to.", default = 0 }, { name = "outmax", type = "SPFLOAT", description ="Maximum value to scale to.", default = 1 }, } }, modtype = "module", description = [[This module scales from one range to another defined by a minimum and maximum point in the input and output domain. ]], ninputs = 1, noutputs = 1, inputs = { { name = "in", description = "Signal to be scaled." }, }, outputs = { { name = "out", description = "Scaled signal out" }, } }
Fixed documentation for scale
Fixed documentation for scale
Lua
mit
aure/Soundpipe,narner/Soundpipe,aure/Soundpipe,dan-f/Soundpipe,narner/Soundpipe,dan-f/Soundpipe,dan-f/Soundpipe,aure/Soundpipe,narner/Soundpipe,narner/Soundpipe,aure/Soundpipe
c6add6ad5ab46379a739d413418be77bdb621d1e
src/batcher.lua
src/batcher.lua
Batcher = {} Batcher.__index = Batcher function Batcher:__init(Xf, Yf, batch_size, partial) bat = {} setmetatable(bat, self) bat.Xf = Xf bat.num_seqs = Xf:dataspaceSize()[1] bat.init_depth = Xf:dataspaceSize()[2] bat.seq_len = Xf:dataspaceSize()[4] bat.Yf = Yf if bat.Yf ~= nil then bat.num_targets = Yf:dataspaceSize()[2] end bat.batch_size = batch_size bat.partial = partial or true bat:reset() return bat end function Batcher:next() local X_batch = nil local Y_batch = nil if self.start + self.batch_size <= self.num_seqs or (self.partial and self.start <= self.num_seqs) then -- get data X_batch = self.Xf:partial({self.start,self.stop}, {1,self.init_depth}, {1,1}, {1,self.seq_len}):double() if self.Yf ~= nil then Y_batch = self.Yf:partial({self.start,self.stop}, {1,self.num_targets}):double() end -- update batch indexes for next self.start = self.start + self.batch_size self.stop = math.min(self.stop + self.batch_size, self.num_seqs) end return X_batch, Y_batch end function Batcher:reset() self.start = 1 self.stop = math.min(self.start+self.batch_size-1, self.num_seqs) end
Batcher = {} Batcher.__index = Batcher function Batcher:__init(Xf, Yf, batch_size, partial) bat = {} setmetatable(bat, self) bat.Xf = Xf bat.num_seqs = Xf:dataspaceSize()[1] bat.init_depth = Xf:dataspaceSize()[2] bat.seq_len = Xf:dataspaceSize()[4] bat.Yf = Yf if bat.Yf ~= nil then bat.num_targets = Yf:dataspaceSize()[2] end bat.batch_size = batch_size if partial == nil then bat.partial = true else bat.partial = partial end bat:reset() return bat end function Batcher:next() local X_batch = nil local Y_batch = nil -- print(self.start, self.start+self.batch_size, self.num_seqs, self.partial) if self.start + self.batch_size <= self.num_seqs + 1 or (self.partial and self.start <= self.num_seqs) then -- print("batch provided", self.start, self.stop) -- get data X_batch = self.Xf:partial({self.start,self.stop}, {1,self.init_depth}, {1,1}, {1,self.seq_len}):double() if self.Yf ~= nil then Y_batch = self.Yf:partial({self.start,self.stop}, {1,self.num_targets}):double() end -- update batch indexes for next self.start = self.start + self.batch_size self.stop = math.min(self.stop + self.batch_size, self.num_seqs) -- else -- print("no batch") end return X_batch, Y_batch end function Batcher:reset() self.start = 1 self.stop = math.min(self.start+self.batch_size-1, self.num_seqs) end
partial batch bug
partial batch bug
Lua
mit
davek44/Basset,davek44/Basset
f420ec417ee741248b5d4f473dc9edab8e895a26
lua/autorun/mediaplayer/services/youtube/cl_init.lua
lua/autorun/mediaplayer/services/youtube/cl_init.lua
include "shared.lua" local urllib = url DEFINE_BASECLASS( "mp_service_browser" ) -- https://developers.google.com/youtube/player_parameters -- TODO: add closed caption option according to cvar SERVICE.VideoUrlFormat = "https://www.youtube.com/embed/%s?enablejsapi=1&version=3&playerapiid=ytplayer&autoplay=1&controls=0&modestbranding=1&rel=0&showinfo=0" -- YouTube player API -- https://developers.google.com/youtube/js_api_reference local JS_Init = [[ if (window.MediaPlayer === undefined) { window.MediaPlayer = (function(){ var playerId = '%s', timed = %s; return { init: function () { if (this.player) return; this.player = document.getElementById(playerId); if (!this.player) { console.error('Unable to find YouTube player element!'); return false; } }, isPlayerReady: function () { return ( this.ytReady || (this.player && (this.player.setVolume !== undefined)) ); }, setVolume: function ( volume ) { if (!this.isPlayerReady()) return; this.player.setVolume(volume); }, play: function () { if (!this.isPlayerReady()) return; this.player.playVideo(); }, pause: function () { if (!this.isPlayerReady()) return; this.player.pauseVideo(); }, seek: function ( seekTime ) { if (!this.isPlayerReady()) return; if (!timed) return; var state, curTime, duration, diffTime; state = this.player.getPlayerState(); /*if (state < 0) { this.player.playVideo(); }*/ if (state === 3) return; duration = this.player.getDuration(); if (seekTime > duration) return; curTime = this.player.getCurrentTime(); diffTime = Math.abs(curTime - seekTime); if (diffTime < 5) return; this.player.seekTo(seekTime, true); } }; })(); MediaPlayer.init(); } window.onYouTubePlayerReady = function (playerId) { MediaPlayer.ytReady = true; MediaPlayer.init(); }; ]] local JS_SetVolume = "if(window.MediaPlayer) MediaPlayer.setVolume(%s);" local JS_Seek = "if(window.MediaPlayer) MediaPlayer.seek(%s);" local JS_Play = "if(window.MediaPlayer) MediaPlayer.play();" local JS_Pause = "if(window.MediaPlayer) MediaPlayer.pause();" local function YTSetVolume( self ) -- if not self.playerId then return end local js = JS_SetVolume:format( MediaPlayer.Volume() * 100 ) if self.Browser then self.Browser:RunJavascript(js) end end local function YTSeek( self, seekTime ) -- if not self.playerId then return end local js = JS_Seek:format( seekTime ) if self.Browser then self.Browser:RunJavascript(js) end end function SERVICE:SetVolume( volume ) local js = JS_SetVolume:format( MediaPlayer.Volume() * 100 ) self.Browser:RunJavascript(js) end function SERVICE:OnBrowserReady( browser ) BaseClass.OnBrowserReady( self, browser ) -- Resume paused player if self._YTPaused then self.Browser:RunJavascript( JS_Play ) self._YTPaused = nil return end if not self._setupBrowser then -- This doesn't always get called in time, but it's a nice fallback browser:AddFunction( "window", "onYouTubePlayerReady", function( playerId ) if not playerId then return end self.playerId = string.JavascriptSafe( playerId ) -- Initialize JavaScript MediaPlayer interface local jsinit = JS_Init:format( self.playerId, self:IsTimed() ) browser:RunJavascript( jsinit ) YTSetVolume( self ) end ) self._setupBrowser = true end local videoId = self:GetYouTubeVideoId() local url = self.VideoUrlFormat:format( videoId ) local curTime = self:CurrentTime() -- Add start time to URL if the video didn't just begin if self:IsTimed() and curTime > 3 then url = url .. "&start=" .. math.Round(curTime) end -- Trick the embed page into thinking the referrer is youtube.com; allows -- playing some restricted content due to the block by default behavior -- described here: http://stackoverflow.com/a/13463245/1490006 url = urllib.escape(url) url = "http://www.gmtower.org/apps/mediaplayer/redirect.html#" .. url browser:OpenURL(url) -- Initialize JavaScript MediaPlayer interface local playerId = "player1" local jsinit = JS_Init:format( playerId, self:IsTimed() ) browser:QueueJavascript( jsinit ) end function SERVICE:Pause() BaseClass.Pause( self ) if ValidPanel(self.Browser) then self.Browser:RunJavascript(JS_Pause) self._YTPaused = true end end function SERVICE:Sync() local seekTime = self:CurrentTime() if seekTime > 0 then YTSeek( self, seekTime ) end end
include "shared.lua" local urllib = url DEFINE_BASECLASS( "mp_service_browser" ) -- https://developers.google.com/youtube/player_parameters -- TODO: add closed caption option according to cvar SERVICE.VideoUrlFormat = "https://www.youtube.com/embed/%s?enablejsapi=1&version=3&playerapiid=ytplayer&autoplay=1&controls=0&modestbranding=1&rel=0&showinfo=0" -- YouTube player API -- https://developers.google.com/youtube/js_api_reference local JS_Init = [[ if (window.MediaPlayer === undefined) { window.MediaPlayer = (function(){ var playerId = '%s', timed = %s; return { init: function () { if (this.player) return; var player = document.getElementById(playerId); if (!player) { player = document.querySelector('embed'); } this.player = player; if (!this.player) { console.error('Unable to find YouTube player element!'); return false; } }, isPlayerReady: function () { return ( this.ytReady || (this.player && (this.player.setVolume !== undefined)) ); }, setVolume: function ( volume ) { if (!this.isPlayerReady()) return; this.player.setVolume(volume); }, play: function () { if (!this.isPlayerReady()) return; this.player.playVideo(); }, pause: function () { if (!this.isPlayerReady()) return; this.player.pauseVideo(); }, seek: function ( seekTime ) { if (!this.isPlayerReady()) return; if (!timed) return; var state, curTime, duration, diffTime; state = this.player.getPlayerState(); /*if (state < 0) { this.player.playVideo(); }*/ if (state === 3) return; duration = this.player.getDuration(); if (seekTime > duration) return; curTime = this.player.getCurrentTime(); diffTime = Math.abs(curTime - seekTime); if (diffTime < 5) return; this.player.seekTo(seekTime, true); } }; })(); MediaPlayer.init(); } window.onYouTubePlayerReady = function (playerId) { MediaPlayer.ytReady = true; MediaPlayer.init(); }; ]] local JS_SetVolume = "if(window.MediaPlayer) MediaPlayer.setVolume(%s);" local JS_Seek = "if(window.MediaPlayer) MediaPlayer.seek(%s);" local JS_Play = "if(window.MediaPlayer) MediaPlayer.play();" local JS_Pause = "if(window.MediaPlayer) MediaPlayer.pause();" local function YTSetVolume( self ) -- if not self.playerId then return end local js = JS_SetVolume:format( MediaPlayer.Volume() * 100 ) if self.Browser then self.Browser:RunJavascript(js) end end local function YTSeek( self, seekTime ) -- if not self.playerId then return end local js = JS_Seek:format( seekTime ) if self.Browser then self.Browser:RunJavascript(js) end end function SERVICE:SetVolume( volume ) local js = JS_SetVolume:format( MediaPlayer.Volume() * 100 ) self.Browser:RunJavascript(js) end function SERVICE:OnBrowserReady( browser ) BaseClass.OnBrowserReady( self, browser ) -- Resume paused player if self._YTPaused then self.Browser:RunJavascript( JS_Play ) self._YTPaused = nil return end if not self._setupBrowser then -- This doesn't always get called in time, but it's a nice fallback browser:AddFunction( "window", "onYouTubePlayerReady", function( playerId ) print "YOUTUBE.ONPLAYERREADY" if not playerId then return end self.playerId = string.JavascriptSafe( playerId ) -- Initialize JavaScript MediaPlayer interface local jsinit = JS_Init:format( self.playerId, self:IsTimed() ) browser:RunJavascript( jsinit ) YTSetVolume( self ) end ) self._setupBrowser = true end local videoId = self:GetYouTubeVideoId() local url = self.VideoUrlFormat:format( videoId ) local curTime = self:CurrentTime() -- Add start time to URL if the video didn't just begin if self:IsTimed() and curTime > 3 then url = url .. "&start=" .. math.Round(curTime) end -- Trick the embed page into thinking the referrer is youtube.com; allows -- playing some restricted content due to the block by default behavior -- described here: http://stackoverflow.com/a/13463245/1490006 url = urllib.escape(url) url = "http://www.gmtower.org/apps/mediaplayer/redirect.html#" .. url browser:OpenURL(url) -- Initialize JavaScript MediaPlayer interface local playerId = "player1" local jsinit = JS_Init:format( playerId, self:IsTimed() ) browser:QueueJavascript( jsinit ) end function SERVICE:Pause() BaseClass.Pause( self ) if ValidPanel(self.Browser) then self.Browser:RunJavascript(JS_Pause) self._YTPaused = true end end function SERVICE:Sync() local seekTime = self:CurrentTime() if seekTime > 0 then YTSeek( self, seekTime ) end end
Fixed YouTube service bug due to updated YT API
Fixed YouTube service bug due to updated YT API
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
6cd0c8936e7d847a31cf57b2a4d45866e8bb3542
test_scripts/Polices/build_options/ATF_P_TC_SDL_Build_EXTENDED_POLICY_HTTP.lua
test_scripts/Polices/build_options/ATF_P_TC_SDL_Build_EXTENDED_POLICY_HTTP.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [GENIVI] [Policy] "HTTP" flow: SDL must be build with "-DEXTENDED_POLICY: HTTP" -- -- Description: -- To "switch on" the "HTTP" flow of PolicyTableUpdate feature -- -> SDL should be built with _-DEXTENDED_POLICY: HTTP flag -- 1. Performed steps -- Build SDL with flag above -- -- Expected result: -- SDL is successfully built -- The flag EXTENDED_POLICY is set to HTTP -- PTU passes successfully --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') require('user_modules/AppTypes') config.application2.registerAppInterfaceParams.appName = "Media Application" config.application2.registerAppInterfaceParams.appID = "MyTestApp" --[[ Local Variables ]] local binaryData = "files/jsons/Policies/build_options/ptu_29604.json" local filePTU = "files/ptu.json" --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:SYSTEM_UP_TO_DATE() commonFunctions:check_ptu_sequence_partly(self, filePTU, "ptu.json") end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_OpenNewSession() self.mobileSession2 = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession2:StartService(7) end function Test:TestStep_Trigger_PTU_Check_HTTP_flow() local corId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application2.registerAppInterfaceParams.appName }}) :Do(function() EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "HTTP"}) :Do(function() local CorIdSystemRequest = self.mobileSession:SendRPC ("SystemRequest", { requestType = "HTTP", fileName = "PTU" }, binaryData) EXPECT_RESPONSE(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"}) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate") :ValidIf(function(exp,data) if exp.occurences == 1 and data.params.status == "UPDATE_NEEDED" then return true elseif exp.occurences == 2 and data.params.status == "UPDATING" then return true elseif exp.occurences == 3 and data.params.status == "UP_TO_DATE" then return true end return false end) :Times(3) end) self.mobileSession2:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) self.mobileSession2:ExpectNotification("OnPermissionsChange") end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop_SDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [GENIVI] [Policy] "HTTP" flow: SDL must be build with "-DEXTENDED_POLICY: HTTP" -- -- Description: -- To "switch on" the "HTTP" flow of PolicyTableUpdate feature -- -> SDL should be built with _-DEXTENDED_POLICY: HTTP flag -- 1. Performed steps -- Build SDL with flag above -- -- Expected result: -- SDL is successfully built -- The flag EXTENDED_POLICY is set to HTTP -- PTU passes successfully --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') require('user_modules/AppTypes') config.application2.registerAppInterfaceParams.appName = "Media Application" config.application2.registerAppInterfaceParams.appID = "MyTestApp" --[[ Local Variables ]] local filePTU = "files/ptu.json" --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:SYSTEM_UP_TO_DATE() commonFunctions:check_ptu_sequence_partly(self, filePTU, "ptu.json") end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_OpenNewSession() self.mobileSession2 = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession2:StartService(7) end function Test:TestStep_Trigger_PTU_Check_HTTP_flow() local corId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application2.registerAppInterfaceParams.appName }}) :Do(function() EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "HTTP"}) :Do(function() local CorIdSystemRequest = self.mobileSession:SendRPC ("SystemRequest", { requestType = "HTTP", fileName = "PTU" }, filePTU) EXPECT_RESPONSE(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"}) end) self.mobileSession2:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) self.mobileSession2:ExpectNotification("OnPermissionsChange") end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate") :ValidIf(function(exp,data) if exp.occurences == 1 and data.params.status == "UPDATE_NEEDED" then return true elseif exp.occurences == 2 and data.params.status == "UPDATING" then return true elseif exp.occurences == 3 and data.params.status == "UP_TO_DATE" then return true end return false end) :Times(3) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_SDLStop() StopSDL() end
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
2887b3db118ad06ff39f5abe614f60d49811b091
table.lua
table.lua
-- new functions related to tables -- functions that handle tables-as-lists go in list.lua -- tprint - recursively display the contents of a table -- does not generate something the terp can read; use table.dump() for that function table.tostring(T) local buf = {} assert(T, "bad argument to table.print") local done = {} local function tstr(T, prefix) for k,v in pairs(T) do table.insert(buf, prefix..tostring(k)..'\t=\t'..tostring(v)) if type(v) == 'table' then if not done[v] then done[v] = true tstr(v, prefix.." ") end end end end done[T] = true tstr(T, "") return table.concat(buf, "\n") end function table.print(T) return print(table.tostring(T)) end -- shallow-merge src into dst, with configurable duplicate-key semantics function table.merge(dst, src, dupes) dupes = dupes or "overwrite" for k,v in pairs(src) do if dst[k] == nil or dupes == "overwrite" then dst[k] = v elseif dupes == "ignore" then -- pass elseif dupes == "error" then error("Duplicate key '"..tostring(k).."' while merging tables") else error("Unknown duplicate key resolution mode '"..tostring(dupes).."'") end end return dst end -- dump Lua code which, when loaded and called, returns a copy -- of the table passed to table.dump -- analogous to string.dump() on functions function table.dump(T) dump = "local loadstring = loadstring\nsetfenv(1, {})\n\n" ref = {} local getref local function check_kv(k,v) for _,val in ipairs { k, v } do if type(val) == 'coroutine' or type(val) == 'userdata' then return false end end return true end local function append_table(T) ref[T] = tostring(T):gsub("table: ", "table_") local S = string.format("%s = {\n", ref[T]) for k,v in pairs(T) do if check_kv(k,v) then S = S..string.format("\t[%s] = %s;\n", getref(k), getref(v)) end end dump = dump..S.."}\n\n" end function getref(v) if ref[v] then return ref[v] end local t = type(v) local mt = getmetatable(v) if mt and mt.__repr then return mt.__repr(v) elseif t == 'nil' or t == 'boolean' or t == 'number' then return tostring(v) elseif t == 'string' then return string.format("%q", v) elseif t == 'function' then ref[v] = tostring(v):gsub("function: ", "func_") dump = dump..string.format("%s = assert(loadstring(%q, 'table.dump function serializer'))\n\n", ref[v], string.dump(v)) return ref[v] elseif t == 'table' then append_table(v) return ref[v] else -- error error "Something bad has happened in table.dump()" end end append_table(T) return dump.."return "..getref(T) end -- return a possibly-deep copy of the given table -- metatables are not copied, references are resolved -- appropriately -- depth 0 simply returns the same table, depth 1 is -- a shallow copy, etc -- the default value for depth is infinity function table.copy(from, depth) ref = {} depth = depth or math.huge local function tcopy(from, depth) local function getref(v) if type(v) ~= 'table' then return v elseif not ref[v] then ref[v] = tcopy(v, depth-1) end return ref[v] end if depth <= 0 then return from end local to = {} ref[from] = to for k,v in pairs(from) do to[getref(k)] = getref(v) end return to end return tcopy(from, depth) end -- map over keys -- if multiple calls return the same key the result is undefined function table.mapk(t, f) local tprime = {} for k,v in pairs(t) do tprime[f(k)] = v end return tprime end -- map over values function table.mapv(t, f) local tprime = {} for k,v in pairs(t) do tprime[k] = f(v) end return tprime end -- map over keys and values function table.mapkv(t, f) local tprime = {} for k,v in pairs(t) do k,v = f(k,v) tprime[k] = v end return tprime end -- map over table as list function table.map(t, f) local tprime = {} for i,v in ipairs(t) do tprime[i] = f(v) end return tprime end
-- new functions related to tables -- functions that handle tables-as-lists go in list.lua -- tprint - recursively display the contents of a table -- does not generate something the terp can read; use table.dump() for that function table.tostring(T) local buf = {} assert(T, "bad argument to table.print") local done = {} local function tstr(T, prefix) for k,v in pairs(T) do table.insert(buf, prefix..tostring(k)..'\t=\t'..tostring(v)) if type(v) == 'table' then if not done[v] then done[v] = true tstr(v, prefix.." ") end end end end done[T] = true tstr(T, "") return table.concat(buf, "\n") end function table.print(T) return print(table.tostring(T)) end -- shallow-merge src into dst, with configurable duplicate-key semantics function table.merge(dst, src, dupes) dupes = dupes or "overwrite" for k,v in pairs(src) do if dst[k] == nil or dupes == "overwrite" then dst[k] = v elseif dupes == "ignore" then -- pass elseif dupes == "error" then error("Duplicate key '"..tostring(k).."' while merging tables") else error("Unknown duplicate key resolution mode '"..tostring(dupes).."'") end end return dst end -- dump Lua code which, when loaded and called, returns a copy -- of the table passed to table.dump -- analogous to string.dump() on functions function table.dump(T) local dump = "local loadstring = loadstring\nsetfenv(1, {})\n\n" local ref = {} local ref_n = 0 local getref local function check_kv(k,v) for _,val in ipairs { k, v } do if type(val) == 'coroutine' or type(val) == 'userdata' then return false end end return true end local function append_table(T) ref[T] = "table_ref_"..ref_n ref_n = ref_n + 1 local S = string.format("%s = {\n", ref[T]) for k,v in pairs(T) do if check_kv(k,v) then S = S..string.format("\t[%s] = %s;\n", getref(k), getref(v)) end end dump = dump..S.."}\n\n" end function getref(v) if ref[v] then return ref[v] end local t = type(v) local mt = getmetatable(v) if mt and mt.__repr then return mt.__repr(v) elseif t == 'nil' or t == 'boolean' or t == 'number' then return tostring(v) elseif t == 'string' then return string.format("%q", v) elseif t == 'function' then ref[v] = tostring(v):gsub("function: ", "func_") dump = dump..string.format("%s = assert(loadstring(%q, 'table.dump function serializer'))\n\n", ref[v], string.dump(v)) return ref[v] elseif t == 'table' then append_table(v) return ref[v] else -- error error "Something bad has happened in table.dump()" end end append_table(T) return dump.."return "..getref(T) end -- return a possibly-deep copy of the given table -- metatables are not copied, references are resolved -- appropriately -- depth 0 simply returns the same table, depth 1 is -- a shallow copy, etc -- the default value for depth is infinity function table.copy(from, depth) ref = {} depth = depth or math.huge local function tcopy(from, depth) local function getref(v) if type(v) ~= 'table' then return v elseif not ref[v] then ref[v] = tcopy(v, depth-1) end return ref[v] end if depth <= 0 then return from end local to = {} ref[from] = to for k,v in pairs(from) do to[getref(k)] = getref(v) end return to end return tcopy(from, depth) end -- map over keys -- if multiple calls return the same key the result is undefined function table.mapk(t, f) local tprime = {} for k,v in pairs(t) do tprime[f(k)] = v end return tprime end -- map over values function table.mapv(t, f) local tprime = {} for k,v in pairs(t) do tprime[k] = f(v) end return tprime end -- map over keys and values function table.mapkv(t, f) local tprime = {} for k,v in pairs(t) do k,v = f(k,v) tprime[k] = v end return tprime end -- map over table as list function table.map(t, f) local tprime = {} for i,v in ipairs(t) do tprime[i] = f(v) end return tprime end
Fix bug in table.dump for tables with __tostring set
Fix bug in table.dump for tables with __tostring set
Lua
mit
ToxicFrog/luautil
60ddc5c6cb4ecbb38fe0787ec84cf8bee9a181f5
timeline_0.0.1/htmlsave.lua
timeline_0.0.1/htmlsave.lua
function row(mark) local TICKS_PER_SECOND = 60 local tick = mark.tick local seconds = tick / TICKS_PER_SECOND % 60 local minutes = (seconds / 60) % 60 local hours = seconds / 60 / 60 local timestamp = string.format("%02d:%02d:%02d", hours, minutes, seconds) local name = mark.name local param = mark.param local value = mark.value local tickStr = "<td>" .. tostring(tick) .. "</td>\n" local timestampStr = "<td>" .. timestamp .. "</td>\n" local nameStr = "<td>" .. tostring(name) .. "</td>\n" local paramStr = "<td>" .. tostring(param) .. "</td>\n" local valueStr = "<td>" .. tostring(value) .. "</td>\n" return "<tr>\n" .. tickStr .. timestampStr .. nameStr .. paramStr .. valueStr .. "</tr>\n" end function timelineRows(player) local force = player.force local forceData = global.forces[force.name] local marks = forceData.allMarks html = "" for i, mark in ipairs(marks) do html = html .. row(mark) .. "\n" end return html end function htmlString(player) local html = [[<!DOCTYPE html><html> <head> </head> <body> <table> <thead> <tr> <th>Tick</th> <th>Timestamp</th> <th>Event</th> <th>Parameter</th> <th>Value</th> </tr> </thead> <tbody> ]] html = html .. timelineRows(player) html = html .. [[ </tbody> </table> </body> </html> ]] return html end
function row(mark) local TICKS_PER_SECOND = 60 local tick = mark.tick local seconds = tick / TICKS_PER_SECOND local minutes = seconds / 60 local hours = minutes / 60 local timestamp = string.format("%02d:%02d:%02d", hours, minutes % 60, seconds % 60) local name = mark.name local param = mark.param local value = mark.value local tickStr = "<td>" .. tostring(tick) .. "</td>\n" local timestampStr = "<td>" .. timestamp .. "</td>\n" local nameStr = "<td>" .. tostring(name) .. "</td>\n" local paramStr = "<td>" .. tostring(param) .. "</td>\n" local valueStr = "<td>" .. tostring(value) .. "</td>\n" return "<tr>\n" .. tickStr .. timestampStr .. nameStr .. paramStr .. valueStr .. "</tr>\n" end function timelineRows(player) local force = player.force local forceData = global.forces[force.name] local marks = forceData.allMarks html = "" for i, mark in ipairs(marks) do html = html .. row(mark) .. "\n" end return html end function htmlString(player) local html = [[<!DOCTYPE html><html> <head> </head> <body> <table> <thead> <tr> <th>Tick</th> <th>Timestamp</th> <th>Event</th> <th>Parameter</th> <th>Value</th> </tr> </thead> <tbody> ]] html = html .. timelineRows(player) html = html .. [[ </tbody> </table> </body> </html> ]] return html end
Fix seconds, minutes and hours calculation in Timeline/htmlsave
Fix seconds, minutes and hours calculation in Timeline/htmlsave
Lua
mit
Zomis/FactorioMods
7526b379e0ef675f8dcee7213cbd0aebe559fa68
applications/luci-splash/luasrc/controller/splash/splash.lua
applications/luci-splash/luasrc/controller/splash/splash.lua
module("luci.controller.splash.splash", package.seeall) function index() entry({"admin", "services", "splash"}, cbi("splash/splash"), "Client-Splash") node("splash").target = call("action_dispatch") node("splash", "activate").target = call("action_activate") node("splash", "splash").target = template("splash_splash/splash") end function action_dispatch() local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or "" local status = luci.util.execl("luci-splash status "..mac)[1] if #mac > 0 and ( status == "whitelisted" or status == "lease" ) then luci.http.redirect(luci.dispatcher.build_url()) else luci.http.redirect(luci.dispatcher.build_url("splash", "splash")) end end function action_activate() local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) if mac and luci.http.formvalue("accept") then os.execute("luci-splash add "..mac.." >/dev/null 2>&1") luci.http.redirect(luci.model.uci.cursor():get("freifunk", "community", "homepage")) else luci.http.redirect(luci.dispatcher.build_url()) end end
module("luci.controller.splash.splash", package.seeall) function index() entry({"admin", "services", "splash"}, cbi("splash/splash"), "Client-Splash") node("splash").target = call("action_dispatch") node("splash", "activate").target = call("action_activate") node("splash", "splash").target = template("splash_splash/splash") end function action_dispatch() local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or "" local status = luci.util.execl("luci-splash status "..mac)[1] if #mac > 0 and ( status == "whitelisted" or status == "lease" ) then luci.http.redirect(luci.dispatcher.build_url()) else luci.http.redirect(luci.dispatcher.build_url("splash", "splash")) end end function action_activate() local ip = luci.http.getenv("REMOTE_ADDR") or "127.0.0.1" local mac = luci.sys.net.ip4mac(ip:match("^[\[::ffff:]*(%d+.%d+%.%d+%.%d+)\]*$")) if mac and luci.http.formvalue("accept") then os.execute("luci-splash add "..mac.." >/dev/null 2>&1") luci.http.redirect(luci.model.uci.cursor():get("freifunk", "community", "homepage")) else luci.http.redirect(luci.dispatcher.build_url()) end end
applications/luci-splash: properly fix mac address detection in mixed IPv4/IPv6 environments (thanks stargieg)
applications/luci-splash: properly fix mac address detection in mixed IPv4/IPv6 environments (thanks stargieg) git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4734 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
gwlim/luci,vhpham80/luci,phi-psi/luci,Canaan-Creative/luci,alxhh/piratenluci,stephank/luci,phi-psi/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,Flexibity/luci,phi-psi/luci,8devices/carambola2-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,yeewang/openwrt-luci,freifunk-gluon/luci,stephank/luci,ch3n2k/luci,saraedum/luci-packages-old,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,jschmidlapp/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,projectbismark/luci-bismark,freifunk-gluon/luci,phi-psi/luci,gwlim/luci,freifunk-gluon/luci,saraedum/luci-packages-old,saraedum/luci-packages-old,saraedum/luci-packages-old,gwlim/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,projectbismark/luci-bismark,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,ch3n2k/luci,gwlim/luci,vhpham80/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,eugenesan/openwrt-luci,Canaan-Creative/luci,projectbismark/luci-bismark,vhpham80/luci,dtaht/cerowrt-luci-3.3,stephank/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,phi-psi/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,jschmidlapp/luci,Flexibity/luci,Flexibity/luci,phi-psi/luci,stephank/luci,8devices/carambola2-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,alxhh/piratenluci,Canaan-Creative/luci,gwlim/luci,zwhfly/openwrt-luci,stephank/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,Flexibity/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,projectbismark/luci-bismark,ch3n2k/luci,eugenesan/openwrt-luci,vhpham80/luci,vhpham80/luci,Flexibity/luci,8devices/carambola2-luci,ch3n2k/luci,alxhh/piratenluci,8devices/carambola2-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,jschmidlapp/luci,jschmidlapp/luci,eugenesan/openwrt-luci,stephank/luci,ThingMesh/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,saraedum/luci-packages-old,gwlim/luci,alxhh/piratenluci,projectbismark/luci-bismark,gwlim/luci,saraedum/luci-packages-old,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,jschmidlapp/luci,yeewang/openwrt-luci,alxhh/piratenluci
72eb8afebefab333ad134ec15080e38dd0d3b9e3
openwrt/package/linkmeter/luasrc/controller/linkmeter/lmdata.lua
openwrt/package/linkmeter/luasrc/controller/linkmeter/lmdata.lua
module("luci.controller.linkmeter.lmdata", package.seeall) function index() entry({"lm", "hist"}, call("hist")) entry({"lm", "json"}, call("json")) end function json() -- luci.http.prepare_content("application/json") luci.http.prepare_content("text/plain") local f = io.open("/tmp/json", "rb") luci.ltn12.pump.all(luci.ltn12.source.file(f), luci.http.write) end local function hasData(tbl) -- Returns true if the table has any non-NaN data in it for _,val in ipairs(tbl) do -- If val ~= val then val is a NaN, LUA doesn't have isnan() -- and NaN ~= NaN by C definition (platform-specific) if val == val then return true end end end function hist() local http = require "luci.http" local rrd = require "rrd" local uci = luci.model.uci.cursor() local RRD_FILE = uci:get("linkmeter", "daemon", "rrd_file") local nancnt = tonumber(http.formvalue("nancnt")) local start, step, data, soff if not nixio.fs.access(RRD_FILE) then http.status(503, "Database Unavailable") http.prepare_content("text/plain") http.write("No database: %q" % RRD_FILE) return end if not nancnt then -- scroll through the data and find the first line that has data -- this should indicate the start of data recording on the largest -- step data. Then use that to determine the smallest step that -- includes all the data start, step, _, data = rrd.fetch(RRD_FILE, "AVERAGE") nancnt = 0 for _, dp in ipairs(data) do if hasData(dp) then break end nancnt = nancnt + 1 end end if nancnt >= 460 then step = 10 soff = 3600 elseif nancnt >= 360 then step = 60 soff = 21600 elseif nancnt >= 240 then step = 120 soff = 43200 else step = 180 soff = 86400 end -- Only pull new data if the nancnt probe data isn't what we're lookinf for if step ~= 180 or not data then -- Make sure our end time falls on an exact previous or now time boundary local now = os.time() now = math.floor(now/step) * step start, step, _, data = rrd.fetch(RRD_FILE, "AVERAGE", "--end", now, "--start", now - soff, "-r", step ) end http.prepare_content("text/plain") for _, dp in ipairs(data) do if hasData(dp) then http.write(("%u: %s\n"):format(start, table.concat(dp, " "))) end start = start + step end end
module("luci.controller.linkmeter.lmdata", package.seeall) function index() entry({"lm", "hist"}, call("hist")) entry({"lm", "json"}, call("json")) end function json() -- luci.http.prepare_content("application/json") luci.http.prepare_content("text/plain") local f = io.open("/tmp/json", "rb") luci.ltn12.pump.all(luci.ltn12.source.file(f), luci.http.write) end local function hasData(tbl) -- Returns true if the table has any non-NaN data in it for _,val in ipairs(tbl) do -- If val ~= val then val is a NaN, LUA doesn't have isnan() -- and NaN ~= NaN by C definition (platform-specific) if val == val then return true end end end function hist() local http = require "luci.http" local rrd = require "rrd" local uci = luci.model.uci.cursor() local RRD_FILE = uci:get("linkmeter", "daemon", "rrd_file") local nancnt = tonumber(http.formvalue("nancnt")) local start, step, data, soff if not nixio.fs.access(RRD_FILE) then http.status(503, "Database Unavailable") http.prepare_content("text/plain") http.write("No database: %q" % RRD_FILE) return end local now = os.time() if not nancnt then -- scroll through the data and find the first line that has data -- this should indicate the start of data recording on the largest -- step data. Then use that to determine the smallest step that -- includes all the data start, step, _, data = rrd.fetch(RRD_FILE, "AVERAGE") nancnt = 0 for _, dp in ipairs(data) do if hasData(dp) then break end nancnt = nancnt + 1 end end if nancnt >= 460 then step = 10 soff = 3600 elseif nancnt >= 360 then step = 60 soff = 21600 elseif nancnt >= 240 then step = 120 soff = 43200 else step = 180 soff = 86400 end -- Make sure our end time falls on an exact previous or now time boundary now = math.floor(now/step) * step -- Only pull new data if the nancnt probe data isn't what we're looking for if step ~= 180 or not data then start, step, _, data = rrd.fetch(RRD_FILE, "AVERAGE", "--end", now, "--start", now - soff, "-r", step ) end local seenData http.prepare_content("text/plain") for _, dp in ipairs(data) do -- Skip the first NaN rows until we actually have data and keep -- sending until we get to the 1 or 2 rows at the end that are NaN if (seenData or hasData(dp)) and ((start < now) or (start == now and hasData(dp))) then http.write(("%u: %s\n"):format(start, table.concat(dp, " "))) seenData = true end start = start + step end end
[lm] Fix not sending valid nan data between two real data points and extra code to prevent sending the blank last 1 or 2 rows
[lm] Fix not sending valid nan data between two real data points and extra code to prevent sending the blank last 1 or 2 rows
Lua
mit
kdakers80/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter
faf260af55ea8cebd04cf269c0c7a73e4b47bfd5
kong/plugins/mashape-analytics/handler.lua
kong/plugins/mashape-analytics/handler.lua
-- Analytics plugin handler. -- -- How it works: -- Keep track of calls made to configured APIs on a per-worker basis, using the ALF format -- (alf_serializer.lua). `:access()` and `:body_filter()` are implemented to record some properties -- required for the ALF entry. -- -- When the buffer is full (it reaches the `batch_size` configuration value), send the batch to the server. -- If the server doesn't accept it, don't flush the data and it'll try again at the next call. -- If the server accepted the batch, flush the buffer. -- -- In order to keep Analytics as real-time as possible, we also start a 'delayed timer' running in background. -- If no requests are made during a certain period of time (the `delay` configuration value), the -- delayed timer will fire and send the batch + flush the data, not waiting for the buffer to be full. local http = require "resty_http" local BasePlugin = require "kong.plugins.base_plugin" local ALFSerializer = require "kong.plugins.log_serializers.alf" local ALF_BUFFER = {} local DELAYED_LOCK = false -- careful: this will only work when lua_code_cache is on local LATEST_CALL local ANALYTICS_SOCKET = { host = "socket.analytics.mashape.com", port = 80, path = "/1.0.0/single" } local function send_batch(premature, conf, alf) -- Abort the sending if the entries are empty, maybe it was triggered from the delayed -- timer, but already sent because we reached the limit in a request later. if table.getn(alf.har.log.entries) < 1 then return end local message = alf:to_json_string(conf.service_token, conf.environment) local ok, err local client = http:new() client:set_timeout(50000) -- 5 sec ok, err = client:connect(ANALYTICS_SOCKET.host, ANALYTICS_SOCKET.port) if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to connect to the socket: "..err) return end local res, err = client:request({ path = ANALYTICS_SOCKET.path, body = message }) if not res then ngx.log(ngx.ERR, "[mashape-analytics] failed to send batch: "..err) end -- close connection, or put it into the connection pool if res.headers["connection"] == "close" then ok, err = client:close() if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to close: "..err) end else client:set_keepalive() end if res.status == 200 then alf:flush_entries() ngx.log(ngx.DEBUG, "[mashape-analytics] successfully saved the batch") else ngx.log(ngx.ERR, "[mashape-analytics] socket refused the batch: "..res.body) end end -- A handler for delayed batch sending. When no call have been made for X seconds -- (X being conf.delay), we send the batch to keep analytics as close to real-time -- as possible. local delayed_send_handler delayed_send_handler = function(premature, conf, alf) -- If the latest call was received during the wait delay, abort the delayed send and -- report it for X more seconds. if ngx.now() - LATEST_CALL < conf.delay then local ok, err = ngx.timer.at(conf.delay, delayed_send_handler, conf, alf) if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to create delayed batch sending timer: ", err) end else DELAYED_LOCK = false -- re-enable creation of a delayed-timer send_batch(premature, conf, alf) end end -- -- -- local AnalyticsHandler = BasePlugin:extend() function AnalyticsHandler:new() AnalyticsHandler.super.new(self, "mashape-analytics") end function AnalyticsHandler:access(conf) AnalyticsHandler.super.access(self) -- Retrieve and keep in memory the bodies for this request ngx.ctx.analytics = { req_body = "", res_body = "" } if conf.log_body then ngx.req.read_body() ngx.ctx.analytics.req_body = ngx.req.get_body_data() end end function AnalyticsHandler:body_filter(conf) AnalyticsHandler.super.body_filter(self) local chunk, eof = ngx.arg[1], ngx.arg[2] -- concatenate response chunks for ALF's `response.content.text` if conf.log_body then ngx.ctx.analytics.res_body = ngx.ctx.analytics.res_body..chunk end if eof then -- latest chunk ngx.ctx.analytics.response_received = ngx.now() * 1000 end end function AnalyticsHandler:log(conf) AnalyticsHandler.super.log(self) local api_id = ngx.ctx.api.id -- Create the ALF if not existing for this API if not ALF_BUFFER[api_id] then ALF_BUFFER[api_id] = ALFSerializer:new_alf() end -- Simply adding the entry to the ALF local n_entries = ALF_BUFFER[api_id]:add_entry(ngx) -- Keep track of the latest call for the delayed timer LATEST_CALL = ngx.now() if n_entries >= conf.batch_size then -- Batch size reached, let's send the data local ok, err = ngx.timer.at(0, send_batch, conf, ALF_BUFFER[api_id]) if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to create batch sending timer: ", err) end elseif not DELAYED_LOCK then DELAYED_LOCK = true -- Make sure only one delayed timer is ever pending -- Batch size not yet reached. -- Set a timer sending the data only in case nothing happens for awhile or if the batch_size is taking -- too much time to reach the limit and trigger the flush. local ok, err = ngx.timer.at(conf.delay, delayed_send_handler, conf, ALF_BUFFER[api_id]) if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to create delayed batch sending timer: ", err) end end end return AnalyticsHandler
-- Analytics plugin handler. -- -- How it works: -- Keep track of calls made to configured APIs on a per-worker basis, using the ALF format -- (alf_serializer.lua). `:access()` and `:body_filter()` are implemented to record some properties -- required for the ALF entry. -- -- When the buffer is full (it reaches the `batch_size` configuration value), send the batch to the server. -- If the server doesn't accept it, don't flush the data and it'll try again at the next call. -- If the server accepted the batch, flush the buffer. -- -- In order to keep Analytics as real-time as possible, we also start a 'delayed timer' running in background. -- If no requests are made during a certain period of time (the `delay` configuration value), the -- delayed timer will fire and send the batch + flush the data, not waiting for the buffer to be full. local http = require "resty_http" local BasePlugin = require "kong.plugins.base_plugin" local ALFSerializer = require "kong.plugins.log_serializers.alf" local ALF_BUFFER = {} local DELAYED_LOCK = false -- careful: this will only work when lua_code_cache is on local LATEST_CALL local ANALYTICS_SOCKET = { host = "socket.analytics.mashape.com", port = 80, path = "/1.0.0/single" } local function send_batch(premature, conf, alf) -- Abort the sending if the entries are empty, maybe it was triggered from the delayed -- timer, but already sent because we reached the limit in a request later. if table.getn(alf.har.log.entries) < 1 then return end local message = alf:to_json_string(conf.service_token, conf.environment) local ok, err local client = http:new() client:set_timeout(50000) -- 5 sec ok, err = client:connect(ANALYTICS_SOCKET.host, ANALYTICS_SOCKET.port) if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to connect to the socket server: "..err) return end local res, err = client:request({path = ANALYTICS_SOCKET.path, body = message}) if not res then ngx.log(ngx.ERR, "[mashape-analytics] failed to send batch: "..err) elseif res.status == 200 then alf:flush_entries() ngx.log(ngx.DEBUG, string.format("[mashape-analytics] successfully saved the batch. (%s)", res.body)) else ngx.log(ngx.ERR, string.format("[mashape-analytics] socket server refused the batch. Status: (%s) Error: (%s)", res.status, res.body)) end -- close connection, or put it into the connection pool if not res or res.headers["connection"] == "close" then ok, err = client:close() if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to close socket: "..err) end else client:set_keepalive() end end -- A handler for delayed batch sending. When no call have been made for X seconds -- (X being conf.delay), we send the batch to keep analytics as close to real-time -- as possible. local delayed_send_handler delayed_send_handler = function(premature, conf, alf) -- If the latest call was received during the wait delay, abort the delayed send and -- report it for X more seconds. if ngx.now() - LATEST_CALL < conf.delay then local ok, err = ngx.timer.at(conf.delay, delayed_send_handler, conf, alf) if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to create delayed batch sending timer: ", err) end else DELAYED_LOCK = false -- re-enable creation of a delayed-timer send_batch(premature, conf, alf) end end -- -- -- local AnalyticsHandler = BasePlugin:extend() function AnalyticsHandler:new() AnalyticsHandler.super.new(self, "mashape-analytics") end function AnalyticsHandler:access(conf) AnalyticsHandler.super.access(self) -- Retrieve and keep in memory the bodies for this request ngx.ctx.analytics = { req_body = "", res_body = "" } if conf.log_body then ngx.req.read_body() ngx.ctx.analytics.req_body = ngx.req.get_body_data() end end function AnalyticsHandler:body_filter(conf) AnalyticsHandler.super.body_filter(self) local chunk, eof = ngx.arg[1], ngx.arg[2] -- concatenate response chunks for ALF's `response.content.text` if conf.log_body then ngx.ctx.analytics.res_body = ngx.ctx.analytics.res_body..chunk end if eof then -- latest chunk ngx.ctx.analytics.response_received = ngx.now() * 1000 end end function AnalyticsHandler:log(conf) AnalyticsHandler.super.log(self) local api_id = ngx.ctx.api.id -- Create the ALF if not existing for this API if not ALF_BUFFER[api_id] then ALF_BUFFER[api_id] = ALFSerializer:new_alf() end -- Simply adding the entry to the ALF local n_entries = ALF_BUFFER[api_id]:add_entry(ngx) -- Keep track of the latest call for the delayed timer LATEST_CALL = ngx.now() if n_entries >= conf.batch_size then -- Batch size reached, let's send the data local ok, err = ngx.timer.at(0, send_batch, conf, ALF_BUFFER[api_id]) if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to create batch sending timer: ", err) end elseif not DELAYED_LOCK then DELAYED_LOCK = true -- Make sure only one delayed timer is ever pending -- Batch size not yet reached. -- Set a timer sending the data only in case nothing happens for awhile or if the batch_size is taking -- too much time to reach the limit and trigger the flush. local ok, err = ngx.timer.at(conf.delay, delayed_send_handler, conf, ALF_BUFFER[api_id]) if not ok then ngx.log(ngx.ERR, "[mashape-analytics] failed to create delayed batch sending timer: ", err) end end end return AnalyticsHandler
fix(analytics) more descriptive error logs
fix(analytics) more descriptive error logs Also handle an edgecase where `res` was being accessed while it was nil. Former-commit-id: 894717f5df68bb9461197317567c91c08127a5f3
Lua
apache-2.0
Vermeille/kong,icyxp/kong,ejoncas/kong,streamdataio/kong,isdom/kong,salazar/kong,Mashape/kong,vzaramel/kong,streamdataio/kong,jebenexer/kong,Kong/kong,jerizm/kong,li-wl/kong,ejoncas/kong,Kong/kong,isdom/kong,ind9/kong,smanolache/kong,beauli/kong,ccyphers/kong,xvaara/kong,shiprabehera/kong,vzaramel/kong,ind9/kong,akh00/kong,rafael/kong,kyroskoh/kong,Kong/kong,rafael/kong,kyroskoh/kong,ajayk/kong
60f7bccb3238c98439bbab762128f97256c163c0
src/romdisk/system/lib/org/xboot/event/event_dispatcher.lua
src/romdisk/system/lib/org/xboot/event/event_dispatcher.lua
--- -- All classes that dispatch events inherit from 'event_dispatcher'. The target of -- an event is a listener function and an optional data value. -- -- @module event_dispatcher local M = class() --- -- Creates a new 'event_dispatcher' object. -- -- @function [parent=#event_dispatcher] new -- @return New 'event_dispatcher' object. function M:init() self.event_listeners_map = {} end --- -- Checks if the 'event_dispatcher' object has a event listener registered for the specified type of event. -- -- @function [parent=#event_dispatcher] has_event_listener -- @param self -- @param type (string) The type of event. -- @param listener (optional) The listener function that processes the event. -- @param data (optional) An optional data parameter that is passed to the listener function. -- @return A value of 'true' if a listener of the specified type is registered; 'false' otherwise. function M:has_event_listener(type, listener, data) local els = self.event_listeners_map[type] if not els or #els == 0 then return false end if listener == nil and data == nil then return true end for i, v in ipairs(els) do if v.listener == listener and v.data == data then return true end end return false end --- -- Registers a listener function and an optional data value so that the listener function is called when an event -- of a particular type occurs. -- -- @function [parent=#event_dispatcher] add_event_listener -- @param self -- @param type (string) The type of event. -- @param listener (function) The listener function that processes the event. -- @param data (optional) An optional data parameter that is passed as a first argument to the listener function. -- @return A value of 'true' or 'false'. function M:add_event_listener(type, listener, data) if self:has_event_listener(type, listener, data) then return false end if not self.event_listeners_map[type] then self.event_listeners_map[type] = {} end local els = self.event_listeners_map[type] local el = {type = type, listener = listener, data = data} table.insert(els, el) return true end --- -- Removes a listener from the 'event_dispatcher' object. 'remove_event_listener()' function expects -- the same arguments with 'add_event_listener()' to remove the event. If there is no matching listener -- registered, a call to this function has no effect. -- -- @function [parent=#event_dispatcher] remove_event_listener -- @param self -- @param type (string) The type of event. -- @param listener (function) The listener object to remove. -- @param data The data parameter that is used while registering the event. -- @return A value of 'true' or 'false'. function M:remove_event_listener(type, listener, data) local els = self.event_listeners_map[type] or {} for i, v in ipairs(els) do if v.type == type and v.listener == listener and v.data == data then table.remove(els, i) return true end end return false end --- -- Dispatches an event to this 'event_dispatcher' instance. -- -- @function [parent=#event_dispatcher] dispatch_event -- @param self -- @param event (event) The 'event' object to be dispatched. function M:dispatch_event(event) if event.stoped == true then return end local els = self.event_listeners_map[event.type] if not els or #els == 0 then return end for i, v in ipairs(els) do if v.type == event.type then v.listener(v.data, event) end end end return M
--- -- All classes that dispatch events inherit from 'event_dispatcher'. The target of -- an event is a listener function and an optional data value. -- -- @module event_dispatcher local M = class() --- -- Creates a new 'event_dispatcher' object. -- -- @function [parent=#event_dispatcher] new -- @return New 'event_dispatcher' object. function M:init() self.event_listeners_map = {} end --- -- Checks if the 'event_dispatcher' object has a event listener registered for the specified type of event. -- -- @function [parent=#event_dispatcher] has_event_listener -- @param self -- @param type (string) The type of event. -- @param listener (optional) The listener function that processes the event. -- @param data (optional) An optional data parameter that is passed to the listener function. -- @return A value of 'true' if a listener of the specified type is registered; 'false' otherwise. function M:has_event_listener(type, listener, data) local els = self.event_listeners_map[type] if not els or #els == 0 then return false end if listener == nil and data == nil then return true end for i, v in ipairs(els) do if v.listener == listener and v.data == data then return true end end return false end --- -- Registers a listener function and an optional data value so that the listener function is called when an event -- of a particular type occurs. -- -- @function [parent=#event_dispatcher] add_event_listener -- @param self -- @param type (string) The type of event. -- @param listener (function) The listener function that processes the event. -- @param data (optional) An optional data parameter that is passed as a first argument to the listener function. -- @return A value of 'true' or 'false'. function M:add_event_listener(type, listener, data) assert(type) assert(listener) if self:has_event_listener(type, listener, data) then return false end if not self.event_listeners_map[type] then self.event_listeners_map[type] = {} end local els = self.event_listeners_map[type] local el = {type = type, listener = listener, data = data} table.insert(els, el) return true end --- -- Removes a listener from the 'event_dispatcher' object. 'remove_event_listener()' function expects -- the same arguments with 'add_event_listener()' to remove the event. If there is no matching listener -- registered, a call to this function has no effect. -- -- @function [parent=#event_dispatcher] remove_event_listener -- @param self -- @param type (string) The type of event. -- @param listener (function) The listener object to remove. -- @param data The data parameter that is used while registering the event. -- @return A value of 'true' or 'false'. function M:remove_event_listener(type, listener, data) assert(type) assert(listener) local els = self.event_listeners_map[type] if not els or #els == 0 then return false end for i, v in ipairs(els) do if v.type == type and v.listener == listener and v.data == data then table.remove(els, i) return true end end return false end --- -- Dispatches an event to this 'event_dispatcher' instance. -- -- @function [parent=#event_dispatcher] dispatch_event -- @param self -- @param event (event) The 'event' object to be dispatched. function M:dispatch_event(event) if event.stoped == true then return end local els = self.event_listeners_map[event.type] if not els or #els == 0 then return end for i, v in ipairs(els) do if v.type == event.type then v.listener(v.data, event) end end end return M
fix event_dispatcher.lua
fix event_dispatcher.lua
Lua
mit
xboot/xboot,xboot/xboot
4d48d8292f1e7aa99458ff7384e01fb0a3d99ab9
src_trunk/resources/job-system/photographer/c_photographer_job.lua
src_trunk/resources/job-system/photographer/c_photographer_job.lua
beautifulPeople = { [90]=true, [92]=true, [93]=true, [97]=true, [138]=true, [139]=true, [140]=true, [146]=true, [152]=true } cop = { [280]=true, [281]=true, [282]=true, [283]=true, [84]=true, [286]=true, [288]=true, [287]=true } swat = { [285]=true } flashCar = { [601]=true, [541]=true, [415]=true, [480]=true, [411]=true, [506]=true, [451]=true, [477]=true, [409]=true, [580]=true, [575]=true, [603]=true } emergencyVehicles = { [416]=true, [427]=true, [490]=true, [528]=true, [407]=true, [544]=true, [523]=true, [598]=true, [596]=true, [597]=true, [599]=true, [601]=true } local pictureValue = 0 local collectionValue = 0 -- Ped at submission desk just for the aesthetics. local victoria = createPed(141, 359.7, 173.57419128418, 1008.3893432617) setPedRotation(victoria, 270) setElementDimension(victoria, 787) setElementInterior(victoria, 3) setPedAnimation ( victoria, "INT_OFFICE", "OFF_Sit_Idle_Loop", -1, true, false, false ) function snapPicture(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement ) local logged = getElementData(source, "loggedin") if (logged==1) then local theTeam = getPlayerTeam(source) local factionType = getElementData(theTeam, "type") if (factionType==6) then if (weapon == 43) then pictureValue = 0 local onScreenPlayers = {} local players = getElementsByType( "player" ) for theKey, thePlayer in ipairs(players) do -- thePlayer ~= source if (isElementOnScreen(thePlayer) == true ) then table.insert(onScreenPlayers, thePlayer) -- Identify everyone who is on the screen as the picture is taken. end end for theKey,thePlayer in ipairs(onScreenPlayers) do local Tx,Ty,Tz = getElementPosition(thePlayer) local Px,Py,Pz = getElementPosition(getLocalPlayer()) local isclear = isLineOfSightClear (Px, Py, Pz +1, Tx, Ty, Tz, true, true, false, true, true, false) if (isclear) then ------------------- -- Player Checks -- ------------------- local skin = getElementModel(thePlayer) if(beautifulPeople[skin]) then pictureValue=pictureValue+50 end if(getPedWeapon(thePlayer)~=0)and(getPedTotalAmmo(thePlayer)~=0) then pictureValue=pictureValue+25 if (cop[skin])then pictureValue=pictureValue+5 end end if(swat[skin])then pictureValue=pictureValue+50 end if(getPedControlState(thePlayer, "fire"))then pictureValue=pictureValue+50 end if(isPedChoking(thePlayer))then pictureValue=pictureValue+50 end if(isPedDoingGangDriveby(thePlayer))then pictureValue=pictureValue+100 end if(isPedHeadless(thePlayer))then pictureValue=pictureValue+200 end if(isPedOnFire(thePlayer))then pictureValue=pictureValue+250 end if(isPlayerDead(thePlayer))then pictureValue=pictureValue+150 end if (#onScreenPlayers>3)then pictureValue=pictureValue+10 end -------------------- -- Vehicle checks -- -------------------- local vehicle = getPedOccupiedVehicle(thePlayer) if(vehicle)then if(flashCar[vehicle])then pictureValue=pictureValue+200 end if(emergencyVehicle[vehicle])and(getVehicleSirensOn(vehicle)) then pictureValue=pictureValue+100 end if not (isVehicleOnGround(vehicle))then pictureValue=pictureValue+200 end end end end if(pictureValue==0)then outputChatBox("No one is going to pay for that picture...", 255, 0, 0) else collectionValue = collectionValue + pictureValue outputChatBox("#FF9933That's a keeper! Picture value: $"..pictureValue, 255, 104, 91, true) end outputChatBox("#FF9933Collection value: $"..collectionValue, 255, 104, 91, true) end end end end addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(), snapPicture) -- /totalvalue to see how much your collection of pictures is worth. function showValue() outputChatBox("#FF9933Collection value: $"..collectionValue, 255, 104, 91, true) end addCommandHandler("totalvalue", showValue, false, false) -- /sellpics to sell your collection of pictures to the news company. function sellPhotos(thePlayer, commandName) local theTeam = getPlayerTeam(thePlayer) local factionType = getElementData(theTeam, "type") if (factionType==6) then if not(photoSubmitDeskMarker)then photoSubmitDeskMarker = createMarker( 362, 173, 1007, "cylinder", 1, 0, 100, 255, 170 ) photoSubmitDeskColSphere = createColSphere( 362, 173, 1007, 2 ) setElementInterior(photoSubmitDeskMarker,3) setElementInterior(photoSubmitDeskColSphere,3) setElementDimension(photoSubmitDeskMarker, 787) setElementDimension(photoSubmitDeskColSphere, 787) outputChatBox("#FF9933You can sell your photographs at the #3399FFSan Andreas Network Tower #FF9933((/sellpics at the front desk)).", 255, 255, 255, true) else if (isElementWithinColShape(thePlayer, photoSubmitDeskColSphere))then if(collectionValue==0)then outputChatBox("None of the pictures you have are worth anything.", 255, 0, 0, true) else triggerServerEvent("submitCollection", thePlayer, collectionValue) collectionValue = 0 end else outputChatBox("#FF9933You can sell your photographs at the #3399FFSan Andreas Network Tower #FF9933((/sellpics at the front desk)).", 255, 255, 255, true) end end end end addCommandHandler("sellpics", sellPhotos, false, false)
beautifulPeople = { [90]=true, [92]=true, [93]=true, [97]=true, [138]=true, [139]=true, [140]=true, [146]=true, [152]=true } cop = { [280]=true, [281]=true, [282]=true, [283]=true, [84]=true, [286]=true, [288]=true, [287]=true } swat = { [285]=true } flashCar = { [601]=true, [541]=true, [415]=true, [480]=true, [411]=true, [506]=true, [451]=true, [477]=true, [409]=true, [580]=true, [575]=true, [603]=true } emergencyVehicles = { [416]=true, [427]=true, [490]=true, [528]=true, [407]=true, [544]=true, [523]=true, [598]=true, [596]=true, [597]=true, [599]=true, [601]=true } local pictureValue = 0 local collectionValue = 0 -- Ped at submission desk just for the aesthetics. local victoria = createPed(141, 359.7, 173.57419128418, 1008.3893432617) setPedRotation(victoria, 270) setElementDimension(victoria, 787) setElementInterior(victoria, 3) setPedAnimation ( victoria, "INT_OFFICE", "OFF_Sit_Idle_Loop", -1, true, false, false ) function snapPicture(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement ) local logged = getElementData(source, "loggedin") if (logged==1) then local theTeam = getPlayerTeam(source) local factionType = getElementData(theTeam, "type") if (factionType==6) then if (weapon == 43) then pictureValue = 0 local onScreenPlayers = {} local players = getElementsByType( "player" ) for theKey, thePlayer in ipairs(players) do -- thePlayer ~= source if (isElementOnScreen(thePlayer) == true ) then table.insert(onScreenPlayers, thePlayer) -- Identify everyone who is on the screen as the picture is taken. end end for theKey,thePlayer in ipairs(onScreenPlayers) do local Tx,Ty,Tz = getElementPosition(thePlayer) local Px,Py,Pz = getElementPosition(getLocalPlayer()) local isclear = isLineOfSightClear (Px, Py, Pz +1, Tx, Ty, Tz, true, true, false, true, true, false) if (isclear) then ------------------- -- Player Checks -- ------------------- local skin = getElementModel(thePlayer) if(beautifulPeople[skin]) then pictureValue=pictureValue+50 end if(getPedWeapon(thePlayer)~=0)and(getPedTotalAmmo(thePlayer)~=0) then pictureValue=pictureValue+25 if (cop[skin])then pictureValue=pictureValue+5 end end if(swat[skin])then pictureValue=pictureValue+50 end if(getPedControlState(thePlayer, "fire"))then pictureValue=pictureValue+50 end if(isPedChoking(thePlayer))then pictureValue=pictureValue+50 end if(isPedDoingGangDriveby(thePlayer))then pictureValue=pictureValue+100 end if(isPedHeadless(thePlayer))then pictureValue=pictureValue+200 end if(isPedOnFire(thePlayer))then pictureValue=pictureValue+250 end if(isPlayerDead(thePlayer))then pictureValue=pictureValue+150 end if (#onScreenPlayers>3)then pictureValue=pictureValue+10 end -------------------- -- Vehicle checks -- -------------------- local vehicle = getPedOccupiedVehicle(thePlayer) if(vehicle)then if(flashCar[vehicle])then pictureValue=pictureValue+200 end if(emergencyVehicle[vehicle])and(getVehicleSirensOn(vehicle)) then pictureValue=pictureValue+100 end if not (isVehicleOnGround(vehicle))then pictureValue=pictureValue+200 end end end end if(pictureValue==0)then outputChatBox("No one is going to pay for that picture...", 255, 0, 0) else collectionValue = collectionValue + pictureValue outputChatBox("#FF9933That's a keeper! Picture value: $"..pictureValue, 255, 104, 91, true) end outputChatBox("#FF9933Collection value: $"..collectionValue, 255, 104, 91, true) end end end end addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(), snapPicture) -- /totalvalue to see how much your collection of pictures is worth. function showValue() outputChatBox("#FF9933Collection value: $"..collectionValue, 255, 104, 91, true) end addCommandHandler("totalvalue", showValue, false, false) -- /sellpics to sell your collection of pictures to the news company. function sellPhotos() local theTeam = getPlayerTeam(source) local factionType = getElementData(theTeam, "type") if (factionType==6) then if not(photoSubmitDeskMarker)then photoSubmitDeskMarker = createMarker( 362, 173, 1007, "cylinder", 1, 0, 100, 255, 170 ) photoSubmitDeskColSphere = createColSphere( 362, 173, 1007, 2 ) setElementInterior(photoSubmitDeskMarker,3) setElementInterior(photoSubmitDeskColSphere,3) setElementDimension(photoSubmitDeskMarker, 787) setElementDimension(photoSubmitDeskColSphere, 787) outputChatBox("#FF9933You can sell your photographs at the #3399FFSan Andreas Network Tower #FF9933((/sellpics at the front desk)).", 255, 255, 255, true) else if (isElementWithinColShape(source, photoSubmitDeskColSphere))then if(collectionValue==0)then outputChatBox("None of the pictures you have are worth anything.", 255, 0, 0, true) else triggerServerEvent("submitCollection", source, collectionValue) collectionValue = 0 end else outputChatBox("#FF9933You can sell your photographs at the #3399FFSan Andreas Network Tower #FF9933((/sellpics at the front desk)).", 255, 255, 255, true) end end end end addCommandHandler("sellpics", sellPhotos, false, false)
Photographer job fix
Photographer job fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@780 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
e7d99157a8d2de701cbe5261fd27b8eb2a30971f
src/servicebag/src/Shared/ServiceBag.lua
src/servicebag/src/Shared/ServiceBag.lua
--- -- @classmod ServiceBag -- @author Quenty local require = require(script.Parent.loader).load(script) local Signal = require("Signal") local BaseObject = require("BaseObject") local ServiceBag = setmetatable({}, BaseObject) ServiceBag.ClassName = "ServiceBag" ServiceBag.__index = ServiceBag -- parentProvider is optional function ServiceBag.new(parentProvider) local self = setmetatable(BaseObject.new(), ServiceBag) self._services = {} self._parentProvider = parentProvider self._serviceTypesToInitialize = {} self._initializing = false self._serviceTypesToStart = {} self._destroying = Signal.new() self._maid:GiveTask(self._destroying) return self end function ServiceBag.isServiceBag(serviceBag) return type(serviceBag) == "table" and serviceBag.ClassName == "ServiceBag" end function ServiceBag:GetService(serviceType) if typeof(serviceType) == "Instance" then serviceType = require(serviceType) end local service = self._services[serviceType] if service then -- Ensure initialized if we're during init phase if self._serviceTypesToInitialize and self._initializing then local index = table.find(self._serviceTypesToInitialize, service) if index then local foundServiceType = assert(table.remove(self._serviceTypesToInitialize, index), "No service removed") assert(foundServiceType == service, "foundServiceType ~= service") self:_initService(foundServiceType) end end return self._services[serviceType] end if self._parentProvider then return self._parentProvider:GetService(serviceType) end -- Try to add the service if we're still initializing services self:_addServiceType(serviceType) return self._services[serviceType] end function ServiceBag:Init() assert(not self._initializing, "Already initializing") assert(self._serviceTypesToInitialize, "Already initialized") self._initializing = true while next(self._serviceTypesToInitialize) do local serviceType = table.remove(self._serviceTypesToInitialize) self:_initService(serviceType) end self._serviceTypesToInitialize = nil self._initializing = false end function ServiceBag:Start() assert(self._serviceTypesToStart, "Already started") assert(not self._initializing, "Still initializing") while next(self._serviceTypesToStart) do local serviceType = table.remove(self._serviceTypesToStart) local service = assert(self._services[serviceType], "No service") if service.Start then service:Start() end end self._serviceTypesToStart = nil end --- Adds a service to this provider only function ServiceBag:_addServiceType(serviceType) assert(self._serviceTypesToInitialize, "Already finished initializing, cannot add more services") -- Already added if self._services[serviceType] then return end -- Construct a new version of this service so we're isolated local service = setmetatable({}, { __index = serviceType }) self._services[serviceType] = service if self._initializing then -- let's initialize immediately self:_initService(serviceType) else table.insert(self._serviceTypesToInitialize, serviceType) end end function ServiceBag:_initService(serviceType) local service = assert(self._services[serviceType], "No service") if service.Init then service:Init(self) end table.insert(self._serviceTypesToStart, serviceType) end function ServiceBag:CreateScope() local provider = ServiceBag.new(self) self._services[provider] = provider -- Remove from parent provider self._maid[provider] = provider._destroying:Connect(function() self._maid[provider] = nil self._services[provider] = nil end) return provider end function ServiceBag:Destroy() local super = getmetatable(ServiceBag) self._destroying:Fire() local services = self._services local key, service = next(services) while service ~= nil do services[key] = nil if service.Destroy then service:Destroy() end key, service = next(services) end super.Destroy(self) end return ServiceBag
--- -- @classmod ServiceBag -- @author Quenty local require = require(script.Parent.loader).load(script) local Signal = require("Signal") local BaseObject = require("BaseObject") local ServiceBag = setmetatable({}, BaseObject) ServiceBag.ClassName = "ServiceBag" ServiceBag.__index = ServiceBag -- parentProvider is optional function ServiceBag.new(parentProvider) local self = setmetatable(BaseObject.new(), ServiceBag) self._services = {} self._parentProvider = parentProvider self._serviceTypesToInitializeSet = {} self._initializedServiceTypeSet = {} self._initializing = false self._serviceTypesToStart = {} self._destroying = Signal.new() self._maid:GiveTask(self._destroying) return self end function ServiceBag.isServiceBag(serviceBag) return type(serviceBag) == "table" and serviceBag.ClassName == "ServiceBag" end function ServiceBag:GetService(serviceType) if typeof(serviceType) == "Instance" then serviceType = require(serviceType) end local service = self._services[serviceType] if service then self:_ensureInitialization(serviceType) return self._services[serviceType] else if self._parentProvider then return self._parentProvider:GetService(serviceType) end -- Try to add the service if we're still initializing services self:_addServiceType(serviceType) self:_ensureInitialization(serviceType) return self._services[serviceType] end end function ServiceBag:HasService(serviceType) if self._services[serviceType] then return true else return false end end function ServiceBag:Init() assert(not self._initializing, "Already initializing") assert(self._serviceTypesToInitializeSet, "Already initialized") self._initializing = true while next(self._serviceTypesToInitializeSet) do local serviceType = next(self._serviceTypesToInitializeSet) self._serviceTypesToInitializeSet[serviceType] = nil self:_ensureInitialization(serviceType) end self._serviceTypesToInitializeSet = nil self._initializing = false end function ServiceBag:Start() assert(self._serviceTypesToStart, "Already started") assert(not self._initializing, "Still initializing") while next(self._serviceTypesToStart) do local serviceType = table.remove(self._serviceTypesToStart) local service = assert(self._services[serviceType], "No service") if service.Start then service:Start() end end self._serviceTypesToStart = nil end function ServiceBag:CreateScope() local provider = ServiceBag.new(self) self:_addServiceType(provider) -- Remove from parent provider self._maid[provider] = provider._destroying:Connect(function() self._maid[provider] = nil self._services[provider] = nil end) return provider end --- Adds a service to this provider only function ServiceBag:_addServiceType(serviceType) if not self._serviceTypesToInitializeSet then error(("Already finished initializing, cannot add %q"):format(tostring(serviceType))) return end -- Already added if self._services[serviceType] then return end -- Construct a new version of this service so we're isolated local service = setmetatable({}, { __index = serviceType }) self._services[serviceType] = service self:_ensureInitialization(serviceType) end function ServiceBag:_ensureInitialization(serviceType) if self._initializedServiceTypeSet[serviceType] then return end if self._initializing then self._serviceTypesToInitializeSet[serviceType] = nil self._initializedServiceTypeSet[serviceType] = true self:_initService(serviceType) elseif self._serviceTypesToInitializeSet then self._serviceTypesToInitializeSet[serviceType] = true else error("[ServiceBag._ensureInitialization] - Cannot initialize past initializing phase ") end end function ServiceBag:_initService(serviceType) local service = assert(self._services[serviceType], "No service") if service.Init then service:Init(self) end table.insert(self._serviceTypesToStart, serviceType) end function ServiceBag:Destroy() local super = getmetatable(ServiceBag) self._destroying:Fire() local services = self._services local key, service = next(services) while service ~= nil do services[key] = nil if service.Destroy then service:Destroy() end key, service = next(services) end super.Destroy(self) end return ServiceBag
fix: Prevent double service initialization from occuring when retrieving service that has not yet been added to service bag
fix: Prevent double service initialization from occuring when retrieving service that has not yet been added to service bag
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
83e27dda9c46b21f4a11e3c12be4d927430b989e
test_scripts/Polices/build_options/ATF_P_Transfer_OnSystemRequest_toApp_PROPRIETARY.lua
test_scripts/Polices/build_options/ATF_P_Transfer_OnSystemRequest_toApp_PROPRIETARY.lua
---------------------------------------------------------------------------------------------- -- Requirement summary: -- [PTU-Proprietary] Transfer OnSystemRequest from HMI to mobile app -- -- Description: -- Preconditions: -- 1. SDL is built with "DEXTENDED_POLICY: PRORPIETARY" flag. -- 2. Trigger for PTU occurs -- Steps: -- 1. HMI->SDL: BC.OnSystemRequest(<path to UpdatedPT>, PROPRIETARY, params) -- 2. Verify payload of SDL->MOB: OnSystemRequest() notification -- -- Expected result: -- Payload (Snapshot and Binary Header) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') local testCasesForBuildingSDLPolicyFlag = require('user_modules/shared_testcases/testCasesForBuildingSDLPolicyFlag') local json = require("modules/json") --[[ Local Variables ]] local sequence = { } local f_name = os.tmpname() --[[ Local Functions ]] local function timestamp() local f = io.popen("date +%H:%M:%S.%3N") local o = f:read("*all") f:close() return (o:gsub("\n", "")) end local function log(event, ...) table.insert(sequence, { ts = timestamp(), e = event, p = {...} }) end local function show_log() print("--- Sequence -------------------------------------") for k, v in pairs(sequence) do local s = k .. ": " .. v.ts .. ": " .. v.e for _, val in pairs(v.p) do if val then s = s .. ": " .. val end end print(s) end print("--------------------------------------------------") end local function is_table_equal(t1, t2) local ty1 = type(t1) local ty2 = type(t2) if ty1 ~= ty2 then return false end if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end for k1, v1 in pairs(t1) do local v2 = t2[k1] if v2 == nil or not is_table_equal(v1, v2) then return false end end for k2, v2 in pairs(t2) do local v1 = t1[k2] if v1 == nil or not is_table_equal(v1, v2) then return false end end return true end --[[ General Precondition before ATF start ]] testCasesForBuildingSDLPolicyFlag:CheckPolicyFlagAfterBuild("PROPRIETARY") commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('user_modules/AppTypes') --[[ Specific Notifications ]] EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate") :Do(function(_, d) log("SDL->HMI: SDL.OnStatusUpdate()", d.params.status) end) :Times(AnyNumber()) :Pin() --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:Test() local exp_service_id = 15 local exp_body = '{ "policy_table": { } }' local exp_header = { ["ReadTimeout"] = 60, ["Content-Length"] = string.len(exp_body), ["charset"] = "utf-8", ["UseCaches"] = false, ["ConnectTimeout"] = 60, ["RequestMethod"] = "POST", ["ContentType"] = "application/json", ["InstanceFollowRedirects"] = false, ["DoInput"] = true, ["DoOutput"] = true } local f = io.open(f_name, "w") f:write(exp_body) f:close() self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = f_name, appID = self.applications["Test Application"] }) self.mobileSession:ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }) :ValidIf(function(_, d) if d.serviceType ~= exp_service_id then local msg = table.concat({"Expected service Id: '", exp_service_id, "', actual: '", d.serviceType , "'"}) return false, msg end local binary_data = json.decode(d.binaryData) local actual_header = binary_data["HTTPRequest"]["headers"] local actual_body = binary_data["HTTPRequest"]["body"] if not is_table_equal(exp_header, actual_header) then local msg = table.concat({ "Header Expected:\n", commonFunctions:convertTableToString(exp_header, 1), "\nActual:\n", commonFunctions:convertTableToString(actual_header, 1)}) return false, msg end if exp_body ~= actual_body then local msg = table.concat({"Body Expected:\n", exp_body, "\nActual:\n", actual_body}) return false, msg end return true end) end function Test.Test_ShowSequence() show_log() end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Clean() os.remove(f_name) end function Test.Postconditions_StopSDL() StopSDL() end return Test
---------------------------------------------------------------------------------------------- -- Requirement summary: -- [PTU-Proprietary] Transfer OnSystemRequest from HMI to mobile app -- -- Description: -- Preconditions: -- 1. SDL is built with "DEXTENDED_POLICY: PRORPIETARY" flag. -- 2. Trigger for PTU occurs -- Steps: -- 1. HMI->SDL: BC.OnSystemRequest(<path to UpdatedPT>, PROPRIETARY, params) -- 2. Verify payload of SDL->MOB: OnSystemRequest() notification -- -- Expected result: -- Payload (Snapshot and Binary Header) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') local json = require("modules/json") --[[ Local Variables ]] local sequence = { } local f_name = os.tmpname() --[[ Local Functions ]] local function timestamp() local f = io.popen("date +%H:%M:%S.%3N") local o = f:read("*all") f:close() return (o:gsub("\n", "")) end local function log(event, ...) table.insert(sequence, { ts = timestamp(), e = event, p = {...} }) end local function show_log() print("--- Sequence -------------------------------------") for k, v in pairs(sequence) do local s = k .. ": " .. v.ts .. ": " .. v.e for _, val in pairs(v.p) do if val then s = s .. ": " .. val end end print(s) end print("--------------------------------------------------") end local function is_table_equal(t1, t2) local ty1 = type(t1) local ty2 = type(t2) if ty1 ~= ty2 then return false end if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end for k1, v1 in pairs(t1) do local v2 = t2[k1] if v2 == nil or not is_table_equal(v1, v2) then return false end end for k2, v2 in pairs(t2) do local v1 = t1[k2] if v1 == nil or not is_table_equal(v1, v2) then return false end end return true end --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('user_modules/AppTypes') --[[ Specific Notifications ]] EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate") :Do(function(_, d) log("SDL->HMI: SDL.OnStatusUpdate()", d.params.status) end) :Times(AnyNumber()) :Pin() --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:Test() local exp_service_id = 15 local exp_body = '{ "policy_table": { } }' local exp_header = { ["ReadTimeout"] = 60, ["Content-Length"] = string.len(exp_body), ["charset"] = "utf-8", ["UseCaches"] = false, ["ConnectTimeout"] = 60, ["RequestMethod"] = "POST", ["ContentType"] = "application/json", ["InstanceFollowRedirects"] = false, ["DoInput"] = true, ["DoOutput"] = true } local f = io.open(f_name, "w") f:write(exp_body) f:close() self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = f_name, appID = self.applications["Test Application"] }) self.mobileSession:ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }) :ValidIf(function(_, d) if d.serviceType ~= exp_service_id then local msg = table.concat({"Expected service Id: '", exp_service_id, "', actual: '", d.serviceType , "'"}) return false, msg end local binary_data = json.decode(d.binaryData) local actual_header = binary_data["HTTPRequest"]["headers"] local actual_body = binary_data["HTTPRequest"]["body"] if not is_table_equal(exp_header, actual_header) then local msg = table.concat({ "Header Expected:\n", commonFunctions:convertTableToString(exp_header, 1), "\nActual:\n", commonFunctions:convertTableToString(actual_header, 1)}) return false, msg end if exp_body ~= actual_body then local msg = table.concat({"Body Expected:\n", exp_body, "\nActual:\n", actual_body}) return false, msg end return true end) end function Test.Test_ShowSequence() show_log() end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Clean() os.remove(f_name) end function Test.Postconditions_StopSDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
2c9738857151dfde2f29a8d9ae2c9427a5e4bdba
lua/parse/char/utf8/tools.lua
lua/parse/char/utf8/tools.lua
local strbyte = string.byte local strsub = string.sub local contiguous_byte_ranges = require 'parse.char.utf8.data.contiguous_byte_ranges' local blob_tools = require 'parse.blob.tools' local next_blob = blob_tools.next local previous_blob = blob_tools.previous local special_next = {} local special_previous = {} for i = 2, #contiguous_byte_ranges do local current = contiguous_byte_ranges[i] local previous = contiguous_byte_ranges[i - 1] special_next[previous.max] = current.min special_previous[current.min] = previous.max end local tools = {} local function next_char(v) if v < '\x80' then return next_blob(v) end local last_byte = strbyte(v, -1) if last_byte ~= 0xBF then return next_blob(v) end local special = special_next[v] if special then return special end return next_blob(strsub(v,1,-2)) .. '\x80' end tools.next = next_char local function previous_char(v) if v < '\x80' then return previous_blob(v) end local last_byte = strbyte(v, -1) if last_byte ~= 0x80 then return previous_blob(v) end local special = special_previous[v] if special then return special end return previous_blob(strsub(v,1,-2)) .. '\xBF' end tools.previous = previous_char local function range_aux(final_char, ref_char) local char = next_char(ref_char) if char > final_char then return nil end return char end function tools.range(from_char, to_char) return range_aux, to_char, previous_char(from_char) end return tools
local strbyte, strchar = string.byte, string.char local strsub = string.sub local contiguous_byte_ranges = require 'parse.char.utf8.data.contiguous_byte_ranges' local blob_tools = require 'parse.blob.tools' local next_blob = blob_tools.next local previous_blob = blob_tools.previous local special_next = {} local special_previous = {} for i = 2, #contiguous_byte_ranges do local current = contiguous_byte_ranges[i] local previous = contiguous_byte_ranges[i - 1] special_next[previous.max] = current.min special_previous[current.min] = previous.max end local tools = {} local function next_char(v) if v < '\x80' then return next_blob(v) end local last_byte = strbyte(v, -1) if last_byte ~= 0xBF then return next_blob(v) end local special = special_next[v] if special then return special end return next_blob(strsub(v,1,-2)) .. '\x80' end tools.next = next_char local function previous_80_BF(v) local last_byte = strbyte(v, -1) local rest = strsub(v, 1, -2) if last_byte == 0x80 then return previous_80_BF(rest) .. '\xBF' end return rest .. strchar(last_byte - 1) end local function previous_char(v) if v < '\x80' then return previous_blob(v) end local last_byte = strbyte(v, -1) if last_byte ~= 0x80 then return previous_blob(v) end local special = special_previous[v] if special then return special end return previous_80_BF(strsub(v,1,-2)) .. '\xBF' end tools.previous = previous_char local function range_aux(final_char, ref_char) local char = next_char(ref_char) if char > final_char then return nil end return char end function tools.range(from_char, to_char) return range_aux, to_char, previous_char(from_char) end return tools
Fix previous UTF-8 char method
Fix previous UTF-8 char method
Lua
mit
taxler/radish,taxler/radish,taxler/radish,taxler/radish,taxler/radish,taxler/radish
503991fa19f3417353b292ab7be6fc8acf41ac1d
util/timer.lua
util/timer.lua
-- Prosody IM v0.3 -- 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 ns_addtimer = require "net.server".addtimer; local get_time = os.time; local t_insert = table.insert; local ipairs = ipairs; local type = type; local data = {}; local new_data = {}; module "timer" local function _add_task(delay, func) local current_time = get_time(); delay = delay + current_time; if delay >= current_time then t_insert(new_data, {delay, func}); else func(); end end add_task = _add_task; ns_addtimer(function() local current_time = get_time(); for _, d in ipairs(new_data) do t_insert(data, d); end new_data = {}; for i = #data,1 do local t, func = data[i][1], data[i][2]; if t <= current_time then data[i] = nil; local r = func(); if type(r) == "number" then _add_task(r, func); end end end end); return _M;
-- Prosody IM v0.3 -- 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 ns_addtimer = require "net.server".addtimer; local get_time = os.time; local t_insert = table.insert; local t_remove = table.remove; local ipairs, pairs = ipairs, pairs; local type = type; local data = {}; local new_data = {}; module "timer" local function _add_task(delay, func) local current_time = get_time(); delay = delay + current_time; if delay >= current_time then t_insert(new_data, {delay, func}); else func(); end end add_task = _add_task; ns_addtimer(function() local current_time = get_time(); if #new_data > 0 then for _, d in ipairs(new_data) do t_insert(data, d); end new_data = {}; elseif #data == 0 then return; end for i, d in pairs(data) do local t, func = d[1], d[2]; if t <= current_time then t_remove(data, i); local r = func(); if type(r) == "number" then _add_task(r, func); end end end end); return _M;
util.timer: Fix crash when loaded but no tasks set, fix skipping some tasks when multiple set, and one removed
util.timer: Fix crash when loaded but no tasks set, fix skipping some tasks when multiple set, and one removed
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
93b642a0d7d5b34316a16459bf8bbb0baa170216
frontend/ui/device.lua
frontend/ui/device.lua
Device = { screen_saver_mode = false, charging_mode = false, model = nil, } function Device:getModel() local std_out = io.popen("grep 'MX' /proc/cpuinfo | cut -d':' -f2 | awk {'print $2'}", "r") local cpu_mod = std_out:read() if not cpu_mod then local ret = os.execute("grep 'Hardware : Mario Platform' /proc/cpuinfo", "r") if ret ~= 0 then return nil else return "KindleDXG" end end if cpu_mod == "MX50" then -- for KPW local pw_test_fd = lfs.attributes("/sys/devices/system/fl_tps6116x/fl_tps6116x0/fl_intensity") -- for KT local kt_test_fd = lfs.attributes("/sys/devices/platform/whitney-button") -- another special file for KT is Neonode zForce touchscreen: -- /sys/devices/platform/zforce.0/ if pw_test_fd then return "KindlePaperWhite" elseif kt_test_fd then return "KindleTouch" else return "Kindle4" end elseif cpu_mod == "MX35" then -- check if we are running on Kindle 3 (additional volume input) return "Kindle3" elseif cpu_mod == "MX3" then return "Kindle2" else return nil end end function Device:isKindle4() re_val = os.execute("cat /proc/cpuinfo | grep MX50") if re_val == 0 then return true else return false end end function Device:isKindle3() re_val = os.execute("cat /proc/cpuinfo | grep MX35") if re_val == 0 then return true else return false end end function Device:isKindle2() re_val = os.execute("cat /proc/cpuinfo | grep MX3") if re_val == 0 then return true else return false end end function Device:hasNoKeyboard() if not self.model then self.model = self:getModel() end return self:isTouchDevice() or (self.model == "Kindle4") end function Device:isTouchDevice() if not self.model then self.model = self:getModel() end return (self.model == "KindlePaperWhite") or (self.model == "KindleTouch") or util.isEmulated() end function Device:intoScreenSaver() --os.execute("echo 'screensaver in' >> /mnt/us/event_test.txt") if self.charging_mode == false and self.screen_saver_mode == false then Screen:saveCurrentBB() msg = InfoMessage:new{"Going into screensaver... "} UIManager:show(msg) Screen.kpv_rotation_mode = Screen.cur_rotation_mode Screen.fb:setOrientation(Screen.native_rotation_mode) util.sleep(1) os.execute("killall -cont cvm") self.screen_saver_mode = true UIManager:close(msg) end end function Device:outofScreenSaver() --os.execute("echo 'screensaver out' >> /mnt/us/event_test.txt") if self.screen_saver_mode == true and self.charging_mode == false then util.usleep(1500000) os.execute("killall -stop cvm") Screen.fb:setOrientation(Screen.kpv_rotation_mode) Screen:restoreFromSavedBB() Screen.fb:refresh(0) end self.screen_saver_mode = false end function Device:usbPlugIn() --os.execute("echo 'usb in' >> /mnt/us/event_test.txt") if self.charging_mode == false and self.screen_saver_mode == false then Screen:saveCurrentBB() Screen.kpv_rotation_mode = Screen.cur_rotation_mode Screen.fb:setOrientation(Screen.native_rotation_mode) msg = InfoMessage:new{"Going into USB mode... "} UIManager:show(msg) util.sleep(1) UIManager:close(msg) os.execute("killall -cont cvm") end self.charging_mode = true end function Device:usbPlugOut() --os.execute("echo 'usb out' >> /mnt/us/event_test.txt") if self.charging_mode == true and self.screen_saver_mode == false then util.usleep(1500000) os.execute("killall -stop cvm") Screen.fb:setOrientation(Screen.kpv_rotation_mode) Screen:restoreFromSavedBB() Screen.fb:refresh(0) end --@TODO signal filemanager for file changes 13.06 2012 (houqp) --FileChooser:setPath(FileChooser.path) --FileChooser.pagedirty = true self.charging_mode = false end
Device = { screen_saver_mode = false, charging_mode = false, model = nil, } function Device:getModel() local std_out = io.popen("grep 'MX' /proc/cpuinfo | cut -d':' -f2 | awk {'print $2'}", "r") local cpu_mod = std_out:read() if not cpu_mod then local ret = os.execute("grep 'Hardware : Mario Platform' /proc/cpuinfo", "r") if ret ~= 0 then return nil else return "KindleDXG" end end if cpu_mod == "MX50" then -- for KPW local pw_test_fd = lfs.attributes("/sys/devices/system/fl_tps6116x/fl_tps6116x0/fl_intensity") -- for KT local kt_test_fd = lfs.attributes("/sys/devices/platform/whitney-button") -- another special file for KT is Neonode zForce touchscreen: -- /sys/devices/platform/zforce.0/ if pw_test_fd then return "KindlePaperWhite" elseif kt_test_fd then return "KindleTouch" else return "Kindle4" end elseif cpu_mod == "MX35" then -- check if we are running on Kindle 3 (additional volume input) return "Kindle3" elseif cpu_mod == "MX3" then return "Kindle2" else return nil end end function Device:isKindle4() return (self:getModel() == "Kindle4") end function Device:isKindle3() re_val = os.execute("cat /proc/cpuinfo | grep MX35") if re_val == 0 then return true else return false end end function Device:isKindle2() re_val = os.execute("cat /proc/cpuinfo | grep MX3") if re_val == 0 then return true else return false end end function Device:hasNoKeyboard() if not self.model then self.model = self:getModel() end return self:isTouchDevice() or (self.model == "Kindle4") end function Device:isTouchDevice() if not self.model then self.model = self:getModel() end return (self.model == "KindlePaperWhite") or (self.model == "KindleTouch") or util.isEmulated() end function Device:intoScreenSaver() --os.execute("echo 'screensaver in' >> /mnt/us/event_test.txt") if self.charging_mode == false and self.screen_saver_mode == false then Screen:saveCurrentBB() msg = InfoMessage:new{"Going into screensaver... "} UIManager:show(msg) Screen.kpv_rotation_mode = Screen.cur_rotation_mode Screen.fb:setOrientation(Screen.native_rotation_mode) util.sleep(1) os.execute("killall -cont cvm") self.screen_saver_mode = true UIManager:close(msg) end end function Device:outofScreenSaver() --os.execute("echo 'screensaver out' >> /mnt/us/event_test.txt") if self.screen_saver_mode == true and self.charging_mode == false then util.usleep(1500000) os.execute("killall -stop cvm") Screen.fb:setOrientation(Screen.kpv_rotation_mode) Screen:restoreFromSavedBB() Screen.fb:refresh(0) end self.screen_saver_mode = false end function Device:usbPlugIn() --os.execute("echo 'usb in' >> /mnt/us/event_test.txt") if self.charging_mode == false and self.screen_saver_mode == false then Screen:saveCurrentBB() Screen.kpv_rotation_mode = Screen.cur_rotation_mode Screen.fb:setOrientation(Screen.native_rotation_mode) msg = InfoMessage:new{"Going into USB mode... "} UIManager:show(msg) util.sleep(1) UIManager:close(msg) os.execute("killall -cont cvm") end self.charging_mode = true end function Device:usbPlugOut() --os.execute("echo 'usb out' >> /mnt/us/event_test.txt") if self.charging_mode == true and self.screen_saver_mode == false then util.usleep(1500000) os.execute("killall -stop cvm") Screen.fb:setOrientation(Screen.kpv_rotation_mode) Screen:restoreFromSavedBB() Screen.fb:refresh(0) end --@TODO signal filemanager for file changes 13.06 2012 (houqp) --FileChooser:setPath(FileChooser.path) --FileChooser.pagedirty = true self.charging_mode = false end
fix Device:isKindle4() method
fix Device:isKindle4() method
Lua
agpl-3.0
Frenzie/koreader,apletnev/koreader,frankyifei/koreader-base,houqp/koreader-base,noname007/koreader,robert00s/koreader,ashhher3/koreader,koreader/koreader,koreader/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,apletnev/koreader-base,NickSavage/koreader,Hzj-jie/koreader,pazos/koreader,apletnev/koreader-base,NiLuJe/koreader-base,chrox/koreader,koreader/koreader-base,Frenzie/koreader-base,NiLuJe/koreader,houqp/koreader-base,lgeek/koreader,frankyifei/koreader-base,mihailim/koreader,poire-z/koreader,apletnev/koreader-base,Frenzie/koreader-base,frankyifei/koreader,NiLuJe/koreader-base,koreader/koreader-base,NiLuJe/koreader,NiLuJe/koreader-base,Markismus/koreader,ashang/koreader,mwoz123/koreader,houqp/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,chihyang/koreader,Frenzie/koreader,Frenzie/koreader-base,poire-z/koreader,koreader/koreader,Frenzie/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base
926935f83170e38452a5191d13aa8b04021606ff
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/leds.lua
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/leds.lua
-- Copyright 2008 Steven Barth <[email protected]> -- Licensed to the public under the Apache License 2.0. m = Map("system", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Configuration"), translate("Customizes the behaviour of the device <abbr title=\"Light Emitting Diode\">LED</abbr>s if possible.")) local sysfs_path = "/sys/class/leds/" local leds = {} local fs = require "nixio.fs" local util = require "nixio.util" if fs.access(sysfs_path) then leds = util.consume((fs.dir(sysfs_path))) end if #leds == 0 then return m end s = m:section(TypedSection, "led", "") s.anonymous = true s.addremove = true function s.parse(self, ...) TypedSection.parse(self, ...) os.execute("/etc/init.d/led enable") end s:option(Value, "name", translate("Name")) sysfs = s:option(ListValue, "sysfs", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Name")) for k, v in ipairs(leds) do sysfs:value(v) end s:option(Flag, "default", translate("Default state")).rmempty = false trigger = s:option(ListValue, "trigger", translate("Trigger")) local triggers = fs.readfile(sysfs_path .. leds[1] .. "/trigger") for t in triggers:gmatch("[%w-]+") do trigger:value(t, translate(t:gsub("-", ""))) end delayon = s:option(Value, "delayon", translate ("On-State Delay")) delayon:depends("trigger", "timer") delayoff = s:option(Value, "delayoff", translate ("Off-State Delay")) delayoff:depends("trigger", "timer") dev = s:option(ListValue, "_net_dev", translate("Device")) dev.rmempty = true dev:value("") dev:depends("trigger", "netdev") function dev.cfgvalue(self, section) return m.uci:get("system", section, "dev") end function dev.write(self, section, value) m.uci:set("system", section, "dev", value) end function dev.remove(self, section) local t = trigger:formvalue(section) if t ~= "netdev" and t ~= "usbdev" then m.uci:delete("system", section, "dev") end end for k, v in pairs(luci.sys.net.devices()) do if v ~= "lo" then dev:value(v) end end mode = s:option(MultiValue, "mode", translate("Trigger Mode")) mode.rmempty = true mode:depends("trigger", "netdev") mode:value("link", translate("Link On")) mode:value("tx", translate("Transmit")) mode:value("rx", translate("Receive")) usbdev = s:option(ListValue, "_usb_dev", translate("USB Device")) usbdev:depends("trigger", "usbdev") usbdev.rmempty = true usbdev:value("") function usbdev.cfgvalue(self, section) return m.uci:get("system", section, "dev") end function usbdev.write(self, section, value) m.uci:set("system", section, "dev", value) end function usbdev.remove(self, section) local t = trigger:formvalue(section) if t ~= "netdev" and t ~= "usbdev" then m.uci:delete("system", section, "dev") end end usbport = s:option(MultiValue, "ports", translate("USB Ports")) usbport:depends("trigger", "usbport") usbport.rmempty = true usbport.widget = "checkbox" usbport.size = 1 for p in nixio.fs.glob("/sys/bus/usb/devices/[0-9]*/manufacturer") do local id = p:match("%d+-%d+") local mf = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/manufacturer") or "?" local pr = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/product") or "?" usbdev:value(id, "%s (%s - %s)" %{ id, mf, pr }) end for p in nixio.fs.glob("/sys/bus/usb/devices/[0-9]*") do local bus, port = p:match("(%d+)-(%d+)") if bus and port then usbport:value("usb%u-port%u" %{ tonumber(bus), tonumber(port) }, "Hub %u, Port %u" %{ tonumber(bus), tonumber(port) }) end end return m
-- Copyright 2008 Steven Barth <[email protected]> -- Licensed to the public under the Apache License 2.0. m = Map("system", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Configuration"), translate("Customizes the behaviour of the device <abbr title=\"Light Emitting Diode\">LED</abbr>s if possible.")) local sysfs_path = "/sys/class/leds/" local leds = {} local fs = require "nixio.fs" local nu = require "nixio.util" local util = require "luci.util" if fs.access(sysfs_path) then leds = nu.consume((fs.dir(sysfs_path))) end if #leds == 0 then return m end s = m:section(TypedSection, "led", "") s.anonymous = true s.addremove = true function s.parse(self, ...) TypedSection.parse(self, ...) os.execute("/etc/init.d/led enable") end s:option(Value, "name", translate("Name")) sysfs = s:option(ListValue, "sysfs", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Name")) for k, v in ipairs(leds) do sysfs:value(v) end s:option(Flag, "default", translate("Default state")).rmempty = false trigger = s:option(ListValue, "trigger", translate("Trigger")) local triggers = fs.readfile(sysfs_path .. leds[1] .. "/trigger") for t in triggers:gmatch("[%w-]+") do trigger:value(t, translate(t:gsub("-", ""))) end delayon = s:option(Value, "delayon", translate ("On-State Delay")) delayon:depends("trigger", "timer") delayoff = s:option(Value, "delayoff", translate ("Off-State Delay")) delayoff:depends("trigger", "timer") dev = s:option(ListValue, "_net_dev", translate("Device")) dev.rmempty = true dev:value("") dev:depends("trigger", "netdev") function dev.cfgvalue(self, section) return m.uci:get("system", section, "dev") end function dev.write(self, section, value) m.uci:set("system", section, "dev", value) end function dev.remove(self, section) local t = trigger:formvalue(section) if t ~= "netdev" and t ~= "usbdev" then m.uci:delete("system", section, "dev") end end for k, v in pairs(luci.sys.net.devices()) do if v ~= "lo" then dev:value(v) end end mode = s:option(MultiValue, "mode", translate("Trigger Mode")) mode.rmempty = true mode:depends("trigger", "netdev") mode:value("link", translate("Link On")) mode:value("tx", translate("Transmit")) mode:value("rx", translate("Receive")) usbdev = s:option(ListValue, "_usb_dev", translate("USB Device")) usbdev:depends("trigger", "usbdev") usbdev.rmempty = true usbdev:value("") function usbdev.cfgvalue(self, section) return m.uci:get("system", section, "dev") end function usbdev.write(self, section, value) m.uci:set("system", section, "dev", value) end function usbdev.remove(self, section) local t = trigger:formvalue(section) if t ~= "netdev" and t ~= "usbdev" then m.uci:delete("system", section, "dev") end end usbport = s:option(MultiValue, "port", translate("USB Ports")) usbport:depends("trigger", "usbport") usbport.rmempty = true usbport.widget = "checkbox" usbport.cast = "table" usbport.size = 1 function usbport.valuelist(self, section) local port, ports = nil, {} for port in util.imatch(m.uci:get("system", section, "port")) do local b, n = port:match("^usb(%d+)-port(%d+)$") if not (b and n) then b, n = port:match("^(%d+)-(%d+)$") end if b and n then ports[#ports+1] = "usb%u-port%u" %{ tonumber(b), tonumber(n) } end end return ports end function usbport.validate(self, value) return type(value) == "string" and { value } or value end for p in nixio.fs.glob("/sys/bus/usb/devices/[0-9]*/manufacturer") do local id = p:match("%d+-%d+") local mf = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/manufacturer") or "?" local pr = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/product") or "?" usbdev:value(id, "%s (%s - %s)" %{ id, mf, pr }) end for p in nixio.fs.glob("/sys/bus/usb/devices/*/usb[0-9]*-port[0-9]*") do local bus, port = p:match("usb(%d+)-port(%d+)") if bus and port then usbport:value("usb%u-port%u" %{ tonumber(bus), tonumber(port) }, "Hub %u, Port %u" %{ tonumber(bus), tonumber(port) }) end end return m
luci-mod-admin-full: fixes for usbport LED triggers
luci-mod-admin-full: fixes for usbport LED triggers The previous commit erroneously used "ports" instead of "port" as name for the option widget, causing wrong uci values to be written. Also work around some cbi idiosyncrasies regarding MultiValue widgets which prevented rendering the correct initial selection state. Signed-off-by: Jo-Philipp Wich <[email protected]>
Lua
apache-2.0
Noltari/luci,remakeelectric/luci,wongsyrone/luci-1,taiha/luci,Wedmer/luci,artynet/luci,shangjiyu/luci-with-extra,Noltari/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,oneru/luci,openwrt-es/openwrt-luci,artynet/luci,shangjiyu/luci-with-extra,hnyman/luci,openwrt/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,Wedmer/luci,hnyman/luci,aa65535/luci,taiha/luci,chris5560/openwrt-luci,hnyman/luci,artynet/luci,chris5560/openwrt-luci,remakeelectric/luci,kuoruan/luci,aa65535/luci,wongsyrone/luci-1,kuoruan/luci,taiha/luci,remakeelectric/luci,taiha/luci,hnyman/luci,LuttyYang/luci,shangjiyu/luci-with-extra,kuoruan/luci,981213/luci-1,openwrt/luci,taiha/luci,rogerpueyo/luci,chris5560/openwrt-luci,wongsyrone/luci-1,openwrt/luci,kuoruan/luci,oneru/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,wongsyrone/luci-1,remakeelectric/luci,artynet/luci,nmav/luci,LuttyYang/luci,nmav/luci,wongsyrone/luci-1,taiha/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,openwrt/luci,aa65535/luci,Noltari/luci,nmav/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,artynet/luci,Noltari/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,LuttyYang/luci,hnyman/luci,aa65535/luci,oneru/luci,lbthomsen/openwrt-luci,oneru/luci,LuttyYang/luci,981213/luci-1,wongsyrone/luci-1,aa65535/luci,openwrt/luci,nmav/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,981213/luci-1,lbthomsen/openwrt-luci,artynet/luci,Wedmer/luci,tobiaswaldvogel/luci,hnyman/luci,981213/luci-1,oneru/luci,remakeelectric/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,Wedmer/luci,Wedmer/luci,Noltari/luci,artynet/luci,rogerpueyo/luci,kuoruan/luci,nmav/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,aa65535/luci,remakeelectric/luci,lbthomsen/openwrt-luci,hnyman/luci,artynet/luci,openwrt/luci,kuoruan/luci,artynet/luci,kuoruan/lede-luci,nmav/luci,kuoruan/lede-luci,rogerpueyo/luci,Wedmer/luci,rogerpueyo/luci,rogerpueyo/luci,openwrt/luci,aa65535/luci,aa65535/luci,LuttyYang/luci,wongsyrone/luci-1,remakeelectric/luci,981213/luci-1,kuoruan/luci,LuttyYang/luci,Wedmer/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,kuoruan/luci,taiha/luci,chris5560/openwrt-luci,Noltari/luci,kuoruan/lede-luci,981213/luci-1,oneru/luci,remakeelectric/luci,taiha/luci,chris5560/openwrt-luci,kuoruan/lede-luci,rogerpueyo/luci,nmav/luci,chris5560/openwrt-luci,Noltari/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,Noltari/luci,hnyman/luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,LuttyYang/luci,nmav/luci,nmav/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,oneru/luci,981213/luci-1,openwrt-es/openwrt-luci,openwrt/luci,Noltari/luci,Wedmer/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,LuttyYang/luci,oneru/luci
67072d837eeb32f1070805006baaa6223f8e15d9
examples/l3-tcp-syn-flood.lua
examples/l3-tcp-syn-flood.lua
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" local stats = require "stats" function master(...) local txPorts = tostring((select(1, ...))) local minIP = select(2, ...) local numIPs = tonumber((select(3, ...))) local rate = tonumber(select(4, ...)) if not txPorts or not minIP or not numIPs or not rate then printf("usage: txPort1,txPort2 minIP numIPs rate") return end for currentTxPort in txPorts:gmatch("[0-9+]") do currentTxPort = tonumber(currentTxPort) local rxMempool = memory.createMemPool() local txDev = device.config(currentTxPort, rxMempool, 2, 2) txDev:wait() txDev:getTxQueue(0):setRate(rate) dpdk.launchLua("loadSlave", currentTxPort, 0, minIP, numIPs) end dpdk.waitForSlaves() end function loadSlave(port, queue, minA, numIPs) --- parse and check ip addresses local minIP, ipv4 = parseIPAddress(minA) if minIP then printf("INFO: Detected an %s address.", minIP and "IPv4" or "IPv6") else errorf("ERROR: Invalid minIP: %s", minA) end -- min TCP packet size for IPv6 is 74 bytes (+ CRC) local packetLen = ipv4 and 60 or 74 --continue normally local queue = device.get(port):getTxQueue(queue) local mem = memory.createMemPool(function(buf) buf:getTcpPacket(ipv4):fill{ ethSrc="90:e2:ba:2c:cb:02", ethDst="90:e2:ba:35:b5:81", ip4Dst="192.168.1.1", ip6Dst="fd06::1", tcpSyn=1, tcpSeqNumber=1, tcpWindow=10, pktLength=packetLen } end) local lastPrint = dpdk.getTime() local totalSent = 0 local lastTotal = 0 local lastSent = 0 local bufs = mem:bufArray(128) local counter = 0 local c = 0 local txStats = stats:newDevTxCounter(queue, "plain") while dpdk.running() do -- faill packets and set their size bufs:alloc(packetLen) for i, buf in ipairs(bufs) do local pkt = buf:getTcpPacket(ipv4) --increment IP if ipv4 then pkt.ip4.src:set(minIP) pkt.ip4.src:add(counter) else pkt.ip6.src:set(minIP) pkt.ip6.src:add(counter) end counter = incAndWrap(counter, numIPs) -- dump first 3 packets if c < 3 then buf:dump() c = c + 1 end end --offload checksums to NIC bufs:offloadTcpChecksums(ipv4) totalSent = totalSent + queue:send(bufs) txStats:update() end txStats:finalize() end
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" local stats = require "stats" function master(txPorts, minIp, numIps, rate) if not txPorts then printf("usage: txPort1[,txPort2[,...]] [minIP numIPs rate]") return end minIp = minIp or "10.0.0.1" numIps = numIps or 100 rate = rate or 0 for currentTxPort in txPorts:gmatch("(%d+),?") do currentTxPort = tonumber(currentTxPort) local txDev = device.config({ port = currentTxPort }) txDev:wait() txDev:getTxQueue(0):setRate(rate) dpdk.launchLua("loadSlave", currentTxPort, 0, minIp, numIps) end dpdk.waitForSlaves() end function loadSlave(port, queue, minA, numIPs) --- parse and check ip addresses local minIP, ipv4 = parseIPAddress(minA) if minIP then printf("INFO: Detected an %s address.", minIP and "IPv4" or "IPv6") else errorf("ERROR: Invalid minIP: %s", minA) end -- min TCP packet size for IPv6 is 74 bytes (+ CRC) local packetLen = ipv4 and 60 or 74 --continue normally local queue = device.get(port):getTxQueue(queue) local mem = memory.createMemPool(function(buf) buf:getTcpPacket(ipv4):fill{ ethSrc="90:e2:ba:2c:cb:02", ethDst="90:e2:ba:35:b5:81", ip4Dst="192.168.1.1", ip6Dst="fd06::1", tcpSyn=1, tcpSeqNumber=1, tcpWindow=10, pktLength=packetLen } end) local lastPrint = dpdk.getTime() local totalSent = 0 local lastTotal = 0 local lastSent = 0 local bufs = mem:bufArray(128) local counter = 0 local c = 0 local txStats = stats:newDevTxCounter(queue, "plain") while dpdk.running() do -- faill packets and set their size bufs:alloc(packetLen) for i, buf in ipairs(bufs) do local pkt = buf:getTcpPacket(ipv4) --increment IP if ipv4 then pkt.ip4.src:set(minIP) pkt.ip4.src:add(counter) else pkt.ip6.src:set(minIP) pkt.ip6.src:add(counter) end counter = incAndWrap(counter, numIPs) -- dump first 3 packets if c < 3 then buf:dump() c = c + 1 end end --offload checksums to NIC bufs:offloadTcpChecksums(ipv4) totalSent = totalSent + queue:send(bufs) txStats:update() end txStats:finalize() end
examples/l3-tcp-syn: fix port parsing, modernize
examples/l3-tcp-syn: fix port parsing, modernize obviously needs some more modernization
Lua
mit
gallenmu/MoonGen,slyon/MoonGen,atheurer/MoonGen,dschoeffm/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,slyon/MoonGen,duk3luk3/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen,slyon/MoonGen,wenhuizhang/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,bmichalo/MoonGen,slyon/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,atheurer/MoonGen,duk3luk3/MoonGen,emmericp/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,atheurer/MoonGen,kidaa/MoonGen,duk3luk3/MoonGen,bmichalo/MoonGen
bd82c744722021a0b2555cb8faa71791753b975b
kong/plugins/cors/handler.lua
kong/plugins/cors/handler.lua
local lrucache = require "resty.lrucache" local url = require "socket.url" local kong = kong local re_find = ngx.re.find local find = string.find local concat = table.concat local tostring = tostring local ipairs = ipairs local HTTP_OK = 200 local CorsHandler = {} CorsHandler.PRIORITY = 2000 CorsHandler.VERSION = "2.0.0" -- per-plugin cache of normalized origins for runtime comparison local mt_cache = { __mode = "k" } local config_cache = setmetatable({}, mt_cache) -- per-worker cache of parsed requests origins with 1000 slots local normalized_req_domains = lrucache.new(10e3) local function normalize_origin(domain) local parsed_obj = assert(url.parse(domain)) if not parsed_obj.host then return { domain = domain, host = domain, } end local port = parsed_obj.port if (parsed_obj.scheme == "http" and port == "80") or (parsed_obj.scheme == "https" and port == "443") then port = nil end return { domain = (parsed_obj.scheme and parsed_obj.scheme .. "://" or "") .. parsed_obj.host .. (port and ":" .. port or ""), host = parsed_obj.host, } end local function configure_origin(conf) local n_origins = conf.origins ~= nil and #conf.origins or 0 local set_header = kong.response.set_header if n_origins == 0 then set_header("Access-Control-Allow-Origin", "*") return true end if n_origins == 1 then if conf.origins[1] == "*" then set_header("Access-Control-Allow-Origin", "*") return true end set_header("Vary", "Origin") -- if this doesnt look like a regex, set the ACAO header directly -- otherwise, we'll fall through to an iterative search and -- set the ACAO header based on the client Origin local from, _, err = re_find(conf.origins[1], "^[A-Za-z0-9.:/-]+$", "jo") if err then kong.log.err("could not inspect origin for type: ", err) end if from then set_header("Access-Control-Allow-Origin", conf.origins[1]) return false end end local req_origin = kong.request.get_header("origin") if req_origin then local cached_domains = config_cache[conf] if not cached_domains then cached_domains = {} for _, entry in ipairs(conf.origins) do local domain local maybe_regex, _, err = re_find(entry, "[^A-Za-z0-9.:/-]", "jo") if err then kong.log.err("could not inspect origin for type: ", err) end if maybe_regex then -- Kong 0.x did not anchor regexes: -- Perform adjustments to support regexes -- explicitly anchored by the user. if entry:sub(-1) ~= "$" then entry = entry .. "$" end if entry:sub(1, 1) == "^" then entry = entry:sub(2) end domain = { regex = entry } else domain = normalize_origin(entry) end domain.by_host = not find(entry, ":", 1, true) table.insert(cached_domains, domain) end config_cache[conf] = cached_domains end local normalized_req_origin = normalized_req_domains:get(req_origin) if not normalized_req_origin then normalized_req_origin = normalize_origin(req_origin) normalized_req_domains:set(req_origin, normalized_req_origin) end for _, cached_domain in ipairs(cached_domains) do local found, _, err if cached_domain.regex then local subject = cached_domain.by_host and normalized_req_origin.host or normalized_req_origin.domain found, _, err = re_find(subject, cached_domain.regex, "ajo") if err then kong.log.err("could not search for domain: ", err) end else found = (normalized_req_origin.domain == cached_domain.domain) end if found then set_header("Access-Control-Allow-Origin", normalized_req_origin.domain) set_header("Vary", "Origin") return false end end end return false end local function configure_credentials(conf, allow_all) local set_header = kong.response.set_header if not conf.credentials then return end if not allow_all then set_header("Access-Control-Allow-Credentials", true) return end -- Access-Control-Allow-Origin is '*', must change it because ACAC cannot -- be 'true' if ACAO is '*'. local req_origin = kong.request.get_header("origin") if req_origin then set_header("Access-Control-Allow-Origin", req_origin) set_header("Access-Control-Allow-Credentials", true) set_header("Vary", "Origin") end end function CorsHandler:access(conf) if kong.request.get_method() ~= "OPTIONS" or not kong.request.get_header("Origin") or not kong.request.get_header("Access-Control-Request-Method") then return end -- don't add any response header because we are delegating the preflight to -- the upstream API (conf.preflight_continue=true), or because we already -- added them all kong.ctx.plugin.skip_response_headers = true if conf.preflight_continue then return end local allow_all = configure_origin(conf) configure_credentials(conf, allow_all) local set_header = kong.response.set_header if conf.headers and #conf.headers > 0 then set_header("Access-Control-Allow-Headers", concat(conf.headers, ",")) else local acrh = kong.request.get_header("Access-Control-Request-Headers") if acrh then set_header("Access-Control-Allow-Headers", acrh) else kong.response.clear_header("Access-Control-Allow-Headers") end end local methods = conf.methods and concat(conf.methods, ",") or "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS,TRACE,CONNECT" set_header("Access-Control-Allow-Methods", methods) if conf.max_age then set_header("Access-Control-Max-Age", tostring(conf.max_age)) end return kong.response.exit(HTTP_OK) end function CorsHandler:header_filter(conf) if kong.ctx.plugin.skip_response_headers then return end local allow_all = configure_origin(conf) configure_credentials(conf, allow_all) if conf.exposed_headers and #conf.exposed_headers > 0 then kong.response.set_header("Access-Control-Expose-Headers", concat(conf.exposed_headers, ",")) end end return CorsHandler
local lrucache = require "resty.lrucache" local url = require "socket.url" local kong = kong local re_find = ngx.re.find local find = string.find local concat = table.concat local tostring = tostring local ipairs = ipairs local HTTP_OK = 200 local CorsHandler = {} CorsHandler.PRIORITY = 2000 CorsHandler.VERSION = "2.0.0" -- per-plugin cache of normalized origins for runtime comparison local mt_cache = { __mode = "k" } local config_cache = setmetatable({}, mt_cache) -- per-worker cache of parsed requests origins with 1000 slots local normalized_req_domains = lrucache.new(10e3) local function normalize_origin(domain) local parsed_obj = assert(url.parse(domain)) if not parsed_obj.host then return { domain = domain, host = domain, } end local port = parsed_obj.port if (parsed_obj.scheme == "http" and port == "80") or (parsed_obj.scheme == "https" and port == "443") then port = nil end return { domain = (parsed_obj.scheme and parsed_obj.scheme .. "://" or "") .. parsed_obj.host .. (port and ":" .. port or ""), host = parsed_obj.host, } end local function configure_origin(conf) local n_origins = conf.origins ~= nil and #conf.origins or 0 local set_header = kong.response.set_header if n_origins == 0 then set_header("Access-Control-Allow-Origin", "*") return true end if n_origins == 1 then if conf.origins[1] == "*" then set_header("Access-Control-Allow-Origin", "*") return true end set_header("Vary", "Origin") -- if this doesnt look like a regex, set the ACAO header directly -- otherwise, we'll fall through to an iterative search and -- set the ACAO header based on the client Origin local from, _, err = re_find(conf.origins[1], "^[A-Za-z0-9.:/-]+$", "jo") if err then kong.log.err("could not inspect origin for type: ", err) end if from then set_header("Access-Control-Allow-Origin", conf.origins[1]) return false end end local req_origin = kong.request.get_header("origin") if req_origin then local cached_domains = config_cache[conf] if not cached_domains then cached_domains = {} for _, entry in ipairs(conf.origins) do local domain local maybe_regex, _, err = re_find(entry, "[^A-Za-z0-9.:/-]", "jo") if err then kong.log.err("could not inspect origin for type: ", err) end if maybe_regex then -- Kong 0.x did not anchor regexes: -- Perform adjustments to support regexes -- explicitly anchored by the user. if entry:sub(-1) ~= "$" then entry = entry .. "$" end if entry:sub(1, 1) == "^" then entry = entry:sub(2) end domain = { regex = entry } else domain = normalize_origin(entry) end domain.by_host = not find(entry, ":", 1, true) table.insert(cached_domains, domain) end config_cache[conf] = cached_domains end local normalized_req_origin = normalized_req_domains:get(req_origin) if not normalized_req_origin then normalized_req_origin = normalize_origin(req_origin) normalized_req_domains:set(req_origin, normalized_req_origin) end for _, cached_domain in ipairs(cached_domains) do local found, _, err if cached_domain.regex then local subject = cached_domain.by_host and normalized_req_origin.host or normalized_req_origin.domain found, _, err = re_find(subject, cached_domain.regex, "ajo") if err then kong.log.err("could not search for domain: ", err) end else found = (normalized_req_origin.domain == cached_domain.domain) end if found then set_header("Access-Control-Allow-Origin", normalized_req_origin.domain) set_header("Vary", "Origin") return false end end end kong.response.clear_header("Access-Control-Allow-Origin") return false end local function configure_credentials(conf, allow_all) local set_header = kong.response.set_header if not conf.credentials then return end if not allow_all then set_header("Access-Control-Allow-Credentials", true) return end -- Access-Control-Allow-Origin is '*', must change it because ACAC cannot -- be 'true' if ACAO is '*'. local req_origin = kong.request.get_header("origin") if req_origin then set_header("Access-Control-Allow-Origin", req_origin) set_header("Access-Control-Allow-Credentials", true) set_header("Vary", "Origin") end end function CorsHandler:access(conf) if kong.request.get_method() ~= "OPTIONS" or not kong.request.get_header("Origin") or not kong.request.get_header("Access-Control-Request-Method") then return end -- don't add any response header because we are delegating the preflight to -- the upstream API (conf.preflight_continue=true), or because we already -- added them all kong.ctx.plugin.skip_response_headers = true if conf.preflight_continue then return end local allow_all = configure_origin(conf) configure_credentials(conf, allow_all) local set_header = kong.response.set_header if conf.headers and #conf.headers > 0 then set_header("Access-Control-Allow-Headers", concat(conf.headers, ",")) else local acrh = kong.request.get_header("Access-Control-Request-Headers") if acrh then set_header("Access-Control-Allow-Headers", acrh) else kong.response.clear_header("Access-Control-Allow-Headers") end end local methods = conf.methods and concat(conf.methods, ",") or "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS,TRACE,CONNECT" set_header("Access-Control-Allow-Methods", methods) if conf.max_age then set_header("Access-Control-Max-Age", tostring(conf.max_age)) end return kong.response.exit(HTTP_OK) end function CorsHandler:header_filter(conf) if kong.ctx.plugin.skip_response_headers then return end local allow_all = configure_origin(conf) configure_credentials(conf, allow_all) if conf.exposed_headers and #conf.exposed_headers > 0 then kong.response.set_header("Access-Control-Expose-Headers", concat(conf.exposed_headers, ",")) end end return CorsHandler
fix(cors) remove upstream ACAO header if no match is found (#5511)
fix(cors) remove upstream ACAO header if no match is found (#5511) ### Summary This is a fix for an issue filed as a task/feature at #4886 Upon closer inspection, this behavior is closer to a bug, and probably creates unexpected behavior for all users of the CORS plugin. The plugin logic accounts for all cases where it shuould add an ACAO header to enable CORS. If the plugin is enabled but no allowed domains are defined, ACAO: * If allowed domains = *, ACAO: * If one or more specific domains/regexes is defined and request Origin header matches, ACAO: However, if (and only if) a specific list of domains is defined and the request Origin header FAILS to match, then the upstream header is passed through. If your upstream server returns ACAO: *, there is no way to implement a more restrictive CORS behavior with Kong. This change implements a behavior in which while the CORS plugin is enabled, Kong is always responsible for the content of the ACAO header. This is much more clear and predictable. The only situation that this behavior modification would prevent would be if an admin wants to allow specific CORS URLs in Kong, and also allow a different list of specific URLs at the upstream server, whitelisting both. I think the declarative behavior in the Kong plugin is much more sensible. The precedent for removing upstream headers is already set by the logic for Access-Control-Allow-Headers. ### Full changelog Remove upstream Access-Control-Allow-Origin if Origin doesn't match the list of URLs set in the CORS plugin. ### Issues resolved Fix #4886
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
e454b294cfcf324ccf44c39436766cf8f7988be7
applications/luci-vsftpd/luasrc/model/VsftpdSettingAdapter.lua
applications/luci-vsftpd/luasrc/model/VsftpdSettingAdapter.lua
--[[ Copyright (c) 2011,XRouter GROUP (http://www.xrouter.co.cc) All rights reserved. Name : VsftpdSettingAdapter.lua Description : An adapter between uci config and vsftpd config. Version : 1.0 Author : Xu Guanglin Created on : Jan 3, 2011 --]] module("luci.model.VsftpdSettingAdapter", package.seeall) local util = require "luci.util" local uci = require "luci.model.uci".cursor(); --- VsftpdSettingAdapter Class -- an adapter between uci config and vsftpd config. -- @class table -- @name VsftpdSettingAdapter -- @field vsftpConfigPath -- @field uciConfigFile -- @field homedir -- @field welcomeword -- @field downloadable -- @field uploadable -- @field maxspeed -- @field maxclient VsftpdSettingAdapter = util.class(); VsftpdSettingAdapter.vsftpConfigPath = ""; VsftpdSettingAdapter.uciConfigFile = "vsftpd"; VsftpdSettingAdapter.homedir = "" VsftpdSettingAdapter.welcomeword = "" VsftpdSettingAdapter.downloadable = "" VsftpdSettingAdapter.uploadable = "" VsftpdSettingAdapter.maxspeed = "" VsftpdSettingAdapter.maxclient = "" --- VsftpdSettingAdapter Constructor -- @param balance Initial balance value -- @return Instance object function VsftpdSettingAdapter:__init__(vsftpConfigPath) self.vsftpConfigPath = vsftpConfigPath; end --- Write configurations to vsftpd such as /etc/vsftpd.conf function VsftpdSettingAdapter:writeToVsftpdConfig() io.output("/tmp/luci.write.txt") self:loadOptionsFromUciConfigFile(); self:filterSpecialCharacters(); io.write(string.format("sed -i -e '/anon_root/s/=.*/=%s/g' -e '/local_root/s/=.*/=%s/g' -e '/ftpd_banner/s/=.*/=%s/g' -e '/anonymous_enable/s/=.*/=%s/g' -e '/anon_upload_enable/s/=.*/=%s/g' -e '/anon_max_rate/s/=.*/=%s/g' -e '/local_max_rate/s/=.*/=%s/g' -e '/max_clients/s/=.*/=%s/g' %s", self.homedir, self.homedir, self.welcomeword, self.downloadable, self.uploadable, self.maxspeed, self.maxspeed, self.maxclient, self.vsftpConfigPath)); os.execute(string.format("sed -i -e '/anon_root/s/=.*/=%s/g' -e '/local_root/s/=.*/=%s/g' -e '/ftpd_banner/s/=.*/=%s/g' -e '/anonymous_enable/s/=.*/=%s/g' -e '/anon_upload_enable/s/=.*/=%s/g' -e '/anon_max_rate/s/=.*/=%s/g' -e '/local_max_rate/s/=.*/=%s/g' -e '/max_clients/s/=.*/=%s/g' %s", self.homedir, self.homedir, self.welcomeword, self.downloadable, self.uploadable, self.maxspeed, self.maxspeed, self.maxclient, self.vsftpConfigPath)); end --- Load options from uci config file such as /etc/config/vsftpd function VsftpdSettingAdapter:loadOptionsFromUciConfigFile() self.homedir = uci:get(self.uciConfigFile, "config", "homedir"); self.welcomeword = uci:get(self.uciConfigFile, "config", "welcomeword"); self.downloadable = uci:get(self.uciConfigFile, "security", "downloadable"); self.uploadable = uci:get(self.uciConfigFile, "security", "uploadable"); self.maxspeed = uci:get(self.uciConfigFile, "performance", "maxspeed"); self.maxclient = uci:get(self.uciConfigFile, "performance", "maxclient"); end --- Filter all special characters function VsftpdSettingAdapter:filterSpecialCharacters() self.homedir = self:filterSpecialCharacter(self.homedir); self.welcomeword = self:filterSpecialCharacter(self.welcomeword); self.downloadable = self:convertBoolean(self.downloadable); self.uploadable = self:convertBoolean(self.uploadable); self.maxspeed = self:filterSpecialCharacter(self.maxspeed); self.maxclient = self:filterSpecialCharacter(self.maxclient); end --- Filter some special character which can't be operated by shell script -- @param ins Input value -- @return New value function VsftpdSettingAdapter:filterSpecialCharacter(ins) return string.gsub(ins, "/", "\\/") end --- Convert boolean value from 0, 1 to yes, no -- @param ins Input value -- @return New value function VsftpdSettingAdapter:convertBoolean(ins) return (ins == "1") and "YES" or "NO"; end return VsftpdSettingAdapter
--[[ Copyright (c) 2011,XRouter GROUP (http://www.xrouter.co.cc) All rights reserved. Name : VsftpdSettingAdapter.lua Description : An adapter between uci config and vsftpd config. Version : 1.0 Author : Xu Guanglin Created on : Jan 3, 2011 --]] module("luci.model.VsftpdSettingAdapter", package.seeall) local util = require "luci.util" local uci = require "luci.model.uci".cursor(); --- VsftpdSettingAdapter Class -- an adapter between uci config and vsftpd config. -- @class table -- @name VsftpdSettingAdapter -- @field vsftpConfigPath -- @field uciConfigFile -- @field homedir -- @field welcomeword -- @field downloadable -- @field uploadable -- @field maxspeed -- @field maxclient VsftpdSettingAdapter = util.class(); VsftpdSettingAdapter.vsftpConfigPath = ""; VsftpdSettingAdapter.uciConfigFile = "vsftpd"; VsftpdSettingAdapter.homedir = "" VsftpdSettingAdapter.welcomeword = "" VsftpdSettingAdapter.downloadable = "" VsftpdSettingAdapter.uploadable = "" VsftpdSettingAdapter.maxspeed = "" VsftpdSettingAdapter.maxclient = "" --- VsftpdSettingAdapter Constructor -- @param balance Initial balance value -- @return Instance object function VsftpdSettingAdapter:__init__(vsftpConfigPath) self.vsftpConfigPath = vsftpConfigPath; end --- Write configurations to vsftpd such as /etc/vsftpd.conf function VsftpdSettingAdapter:writeToVsftpdConfig() self:loadOptionsFromUciConfigFile(); self:filterSpecialCharacters(); os.execute(string.format("sed -i -e '/anon_root/s/=.*/=%s/g' -e '/local_root/s/=.*/=%s/g' -e '/ftpd_banner/s/=.*/=%s/g' -e '/anonymous_enable/s/=.*/=%s/g' -e '/anon_upload_enable/s/=.*/=%s/g' -e '/anon_max_rate/s/=.*/=%s/g' -e '/local_max_rate/s/=.*/=%s/g' -e '/max_clients/s/=.*/=%s/g' %s", self.homedir, self.homedir, self.welcomeword, self.downloadable, self.uploadable, self.maxspeed, self.maxspeed, self.maxclient, self.vsftpConfigPath)); end --- Load options from uci config file such as /etc/config/vsftpd function VsftpdSettingAdapter:loadOptionsFromUciConfigFile() self.homedir = uci:get(self.uciConfigFile, "config", "homedir"); self.welcomeword = uci:get(self.uciConfigFile, "config", "welcomeword"); self.downloadable = uci:get(self.uciConfigFile, "security", "downloadable"); self.uploadable = uci:get(self.uciConfigFile, "security", "uploadable"); self.maxspeed = uci:get(self.uciConfigFile, "performance", "maxspeed"); self.maxclient = uci:get(self.uciConfigFile, "performance", "maxclient"); end --- Filter all special characters function VsftpdSettingAdapter:filterSpecialCharacters() self.homedir = self:filterSpecialCharacter(self.homedir); self.welcomeword = self:filterSpecialCharacter(self.welcomeword); self.downloadable = self:convertBoolean(self.downloadable); self.uploadable = self:convertBoolean(self.uploadable); self.maxspeed = self:filterSpecialCharacter(self.maxspeed); self.maxclient = self:filterSpecialCharacter(self.maxclient); end --- Filter some special character which can't be operated by shell script -- @param ins Input value -- @return New value function VsftpdSettingAdapter:filterSpecialCharacter(ins) return string.gsub(ins, "/", "\\/") end --- Convert boolean value from 0, 1 to yes, no -- @param ins Input value -- @return New value function VsftpdSettingAdapter:convertBoolean(ins) return (ins == "1") and "YES" or "NO"; end return VsftpdSettingAdapter
fix unecessary debug stdout info in luci-app-vsftpd
fix unecessary debug stdout info in luci-app-vsftpd
Lua
apache-2.0
mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI
d1f930db9cc5525623b922ce2c59aa0bfa95e9e7
lua/String.lua
lua/String.lua
-- workarounds for IDE bugs local squote = "'" local dquote = '"' local backslash = "\\" local function chartopad(c) return string.format("\\%03d", string.byte(c)) end local pads = { z = "\\z", x = "\\x", ['0'] = '\\0', ['1'] = '\\1', ['2'] = '\\2', ['3'] = '\\3', ['4'] = '\\4', ['5'] = '\\5', ['6'] = '\\6', ['7'] = '\\7', ['8'] = '\\8', ['9'] = '\\9', -- remap escape sequences a = chartopad('\a'), b = chartopad('\b'), f = chartopad('\f'), r = chartopad('\r'), n = chartopad('\n'), t = chartopad('\t'), v = chartopad('\v'), [ dquote ] = chartopad(dquote), [ squote ] = chartopad(squote), [ backslash ] = chartopad(backslash), ['\n'] = chartopad('\n') } local numbers = { ['0'] = true, ['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true, ['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true } local findpairs do local function _findnext(flags, index) -- only branch if index = 0 if index > 0 then -- this should always give a match, -- as we're starting from the same index as the returned match -- TODO: test %f >.> local x,y = string.find(flags[1], flags[2], index, flags[3]) return string.find(flags[1], flags[2], y+1, flags[3]) else return string.find(flags[1], flags[2], index + 1, flags[3]) end end function findpairs(str, pat, raw) return _findnext, {str, pat, raw}, 0 end end local function getline(str, pos) -- remove everything that's not a newline then count the newlines + 1 return #(string.gsub(string.sub(str, 1, pos - 1), "[^\n]", "")) + 1 end -- Parse a string like it's a Lua 5.2 string. local function parseString52(s) -- "validate" string local startChar = string.sub(s,1,1) if startChar~=squote and startChar~=dquote then error("not a string", 0) end if string.sub(s, -1, -1) ~= startChar then error(("[%s]:%d: unfinished string"):format(s, getline(s, -1)), 0) end -- remove quotes local str = string.sub(s, 2, -2) -- replace "normal" escapes with a padded escape str = string.gsub(str, "()\\(.)", function(idx,c) return pads[c] or error(("[%s]:%d: invalid escape sequence near '\\%s'"):format(s, getline(s, idx), c), 0) end) -- check for non-escaped startChar if string.find(str, startChar) then error(("[%s]:%d: unfinished string"):format(s, getline(s, -1)), 0) end -- pad numerical escapes str = string.gsub(str, "\\([0-9])(.?)(.?)", function(a, b, c) local x = a -- swap b and c if #b == 0; this is to avoid UB: -- _in theory_ `c` could match but not `b`, this solves -- that problem. uncomment if you know what you're doing. if #b == 0 then b, c = c, b end if numbers[b] then x, b = x .. b, "" if numbers[c] then x, c = x .. c, "" end end return backslash .. ("0"):rep(3 - #x) .. x .. b .. c end) local t = {} local i = 1 local last = 1 -- split on \z -- we can look for "\z" directly because we already escaped everything else for from, to in findpairs(str, "\\z", true) do t[i] = string.sub(str, last, from - 1) last = to+1 i = i + 1 end t[i] = string.sub(str, last) -- parse results local nt = {} for x,y in ipairs(t) do nt[x] = string.gsub(y, "()\\(([x0-9])((.).))", function(idx,a,b,c,d) if b ~= "x" then local n = tonumber(a) if n >= 256 then error(("[%s]:%d: decimal escape too large near '\\%s'"):format(s,getline(s,idx),a), 0) end return string.char(n) else local n = tonumber(c, 16) if n then return string.char(n) end local o = d:find("[0-9a-fA-F]") and c or d error(("[%s]:%d: hexadecimal digit expected near '\\x%s'"):format(s,getline(s,idx),o), 0) end end) if x > 1 then -- handle \z nt[x] = string.gsub(nt[x], "^[%s]*", "") end end -- merge return table.concat(nt, "") end -- "tests" -- TODO add more -- also add automatic checks if _VERSION == "Lua 5.2" and not ... then -- test string parsing local t = { [=["\""]=], [=["\32"]=], [=["\256"]=], [=["\xnn"]=], '"\\\n"', --[[ -- TODO FIXME [=["\x"]=], -- should error but is never seen [=["\xn"]=], -- same as above --]] } for _, str in ipairs(t) do local s, m = pcall(parseString52, str) io.write(tostring(s and ("[" .. m .. "]") or "nil")) io.write(tostring(s and "" or ("\t" .. m)) .. "\n") s, m = load("return " .. str, "=[" .. str .. "]") io.write(tostring(s and ("[" .. s() .. "]"))) io.write(tostring(m and "\t"..m or "") .. "\n") -- TODO assert that printed status and printed error are -- the same between parse52()/parseString52() vs load() end -- test line stuff local t2 = { {"test\nother", 5, 1}, {"test\nother", 6, 2}, {"\n", 1, 1}, {"\n", 2, 2}, -- there is no char 2 but that's not the point } for _, temp in ipairs(t2) do local got, expect = getline(temp[1], temp[2]), temp[3] assert(got == expect, ("got %d, expected %d"):format(got, expect)) end elseif not ... then print("Tests require Lua 5.2") end return { parse52 = parseString52, findpairs = findpairs, getline = getline, }
-- workarounds for IDE bugs local squote = "'" local dquote = '"' local backslash = "\\" local function chartopad(c) return string.format("\\%03d", string.byte(c)) end local pads = { z = "\\z", x = "\\x", ['0'] = '\\0', ['1'] = '\\1', ['2'] = '\\2', ['3'] = '\\3', ['4'] = '\\4', ['5'] = '\\5', ['6'] = '\\6', ['7'] = '\\7', ['8'] = '\\8', ['9'] = '\\9', -- remap escape sequences a = chartopad('\a'), b = chartopad('\b'), f = chartopad('\f'), r = chartopad('\r'), n = chartopad('\n'), t = chartopad('\t'), v = chartopad('\v'), [ dquote ] = chartopad(dquote), [ squote ] = chartopad(squote), [ backslash ] = chartopad(backslash), ['\n'] = chartopad('\n') } local numbers = { ['0'] = true, ['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true, ['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true } local findpairs do local function _findnext(flags, index) -- only branch if index = 0 if index > 0 then -- this should always give a match, -- as we're starting from the same index as the returned match -- TODO: test %f >.> local x,y = string.find(flags[1], flags[2], index, flags[3]) return string.find(flags[1], flags[2], y+1, flags[3]) else return string.find(flags[1], flags[2], index + 1, flags[3]) end end function findpairs(str, pat, raw) return _findnext, {str, pat, raw}, 0 end end local function getline(str, pos) -- remove everything that's not a newline then count the newlines + 1 return #(string.gsub(string.sub(str, 1, pos - 1), "[^\n]", "")) + 1 end -- Parse a string like it's a Lua 5.2 string. local function parseString52(s) -- "validate" string local startChar = string.sub(s,1,1) if startChar~=squote and startChar~=dquote then error("not a string", 0) end if string.sub(s, -1, -1) ~= startChar then error(("[%s]:%d: unfinished string"):format(s, getline(s, -1)), 0) end -- remove quotes local str = string.sub(s, 2, -2) -- replace "normal" escapes with a padded escape str = string.gsub(str, "()\\(.)", function(idx,c) return pads[c] or error(("[%s]:%d: invalid escape sequence near '\\%s'"):format(s, getline(s, idx), c), 0) end) -- check for non-escaped startChar if string.find(str, startChar) then error(("[%s]:%d: unfinished string"):format(s, getline(s, -1)), 0) end -- pad numerical escapes str = string.gsub(str, "\\([0-9])(.?)(.?)", function(a, b, c) local x = a -- swap b and c if #b == 0; this is to avoid UB: -- _in theory_ `c` could match but not `b`, this solves -- that problem. uncomment if you know what you're doing. if #b == 0 then b, c = c, b end if numbers[b] then x, b = x .. b, "" if numbers[c] then x, c = x .. c, "" end end return backslash .. ("0"):rep(3 - #x) .. x .. b .. c end) local t = {} local i = 1 local last = 1 -- split on \z -- we can look for "\z" directly because we already escaped everything else for from, to in findpairs(str, "\\z", true) do t[i] = string.sub(str, last, from - 1) last = to+1 i = i + 1 end t[i] = string.sub(str, last) -- parse results local nt = {} for x,y in ipairs(t) do -- fix "\x" and "\xn" if y:sub(-3):match("\\x") then -- append 2 startChars, this'll error anyway so it doesn't matter. y = y .. startChar .. startChar end nt[x] = string.gsub(y, "()\\(([x0-9])((.).))", function(idx,a,b,c,d) if b ~= "x" then local n = tonumber(a) if n >= 256 then error(("[%s]:%d: decimal escape too large near '\\%s'"):format(s,getline(s,idx),a), 0) end return string.char(n) else local n = tonumber(c, 16) if n then return string.char(n) end local o = d:find("[0-9a-fA-F]") and c or d error(("[%s]:%d: hexadecimal digit expected near '\\x%s'"):format(s,getline(s,idx),o), 0) end end) if x > 1 then -- handle \z nt[x] = string.gsub(nt[x], "^[%s]*", "") end end -- merge return table.concat(nt, "") end -- "tests" -- TODO add more -- also add automatic checks if _VERSION == "Lua 5.2" and not ... then -- test string parsing local t = { [=["\""]=], [=["\32"]=], [=["\256"]=], [=["\xnn"]=], '"\\\n"', [=["\x"]=], [=["\xn"]=], } for _, str in ipairs(t) do local s, m = pcall(parseString52, str) io.write(tostring(s and ("[" .. m .. "]") or "nil")) io.write(tostring(s and "" or ("\t" .. m)) .. "\n") s, m = load("return " .. str, "=[" .. str .. "]") io.write(tostring(s and ("[" .. s() .. "]"))) io.write(tostring(m and "\t"..m or "") .. "\n") -- TODO assert that printed status and printed error are -- the same between parse52()/parseString52() vs load() end -- test line stuff local t2 = { {"test\nother", 5, 1}, {"test\nother", 6, 2}, {"\n", 1, 1}, {"\n", 2, 2}, -- there is no char 2 but that's not the point } for _, temp in ipairs(t2) do local got, expect = getline(temp[1], temp[2]), temp[3] assert(got == expect, ("got %d, expected %d"):format(got, expect)) end elseif not ... then print("Tests require Lua 5.2") end return { parse52 = parseString52, findpairs = findpairs, getline = getline, }
Fix bug
Fix bug
Lua
mit
SoniEx2/Stuff,SoniEx2/Stuff
714df7776fceaf9c3d6ec06514017bc4d515f4a4
lua/LUA/ak/util/Queue.lua
lua/LUA/ak/util/Queue.lua
if AkDebugLoad then print("Loading ak.road.TrafficLight ...") end local Queue = {} function Queue:new() local o = {first = 0, last = -1, list = {}} self.__index = self setmetatable(o, self) return o end ---Tells if the queue is empty ---@return boolean true if the queue is empty function Queue:isEmpty() return self.last - self.first == -1 end ---Tells if the queue is empty ---@return number number of elements in the queue function Queue:size() return self.last + 1 - self.first end ---Pushes a value to the current queues end ---@param value any @value to be pushed to the end of the queue function Queue:push(value) local last = self.last + 1 self.last = last self.list[last] = value end --- Receives the value at the queues beginning ---@return any function Queue:pop() local first = self.first if first > self.last then error("list is empty") end local value = self.list[first] self.list[first] = nil -- to allow garbage collection self.first = first + 1 return value end function Queue:elements() local elems = {} for i = self.first, self.last, 1 do table.insert(elems, self.list[i]) end return elems end return Queue
if AkDebugLoad then print("Loading ak.road.TrafficLight ...") end local Queue = {} function Queue:new() local o = {first = 0, last = -1, list = {}} self.__index = self setmetatable(o, self) return o end ---Tells if the queue is empty ---@return boolean true if the queue is empty function Queue:isEmpty() return self.last - self.first == -1 end ---Tells the number of elements currently in the queue ---@return number number of elements in the queue function Queue:size() return self.last + 1 - self.first end ---Pushes a value to the current queues end ---@param value any @value to be pushed to the end of the queue function Queue:push(value) local last = self.last + 1 self.last = last self.list[last] = value end --- Receives the value at the queues beginning ---@return any function Queue:pop() local first = self.first if first > self.last then error("list is empty") end local value = self.list[first] self.list[first] = nil -- to allow garbage collection self.first = first + 1 return value end function Queue:elements() local elems = {} for i = self.first, self.last, 1 do table.insert(elems, self.list[i]) end return elems end return Queue
fix queue comment
fix queue comment
Lua
mit
Andreas-Kreuz/ak-lua-skripte-fuer-eep,Andreas-Kreuz/ak-lua-skripte-fuer-eep
a975d5a9abaf4c17272fadecb49018aa71d63b61
mod_pastebin/mod_pastebin.lua
mod_pastebin/mod_pastebin.lua
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local length_threshold = config.get("*", "core", "pastebin_threshold") or 500; local base_url; local pastes = {}; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; local function pastebin_message(text) local uuid = uuid_new(); pastes[uuid] = { text = text, time = os_time() }; return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid].text; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtml then htmlindex = k; end end if not body then return; end body = body:get_text(); module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and #body > length_threshold then local url = pastebin_message(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local length_threshold = config.get("*", "core", "pastebin_threshold") or 500; local base_url = config.get(module.host, "core", "pastebin_url"); local pastes = {}; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; local function pastebin_message(text) local uuid = uuid_new(); pastes[uuid] = { text = text, time = os_time() }; return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid].text; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtml then htmlindex = k; end end if not body then return; end body = body:get_text(); module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and #body > length_threshold then local url = pastebin_message(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
mod_pastebin: Small fix to read the pastebin URL from the config
mod_pastebin: Small fix to read the pastebin URL from the config
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
01d4c6317159ab7998df3d7bf59d8f39faaf7622
item/bottles.lua
item/bottles.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.bottles' WHERE itm_id IN (2500, 2496, 2497, 2501, 2499); local common = require("base.common") local lookat = require("base.lookat") local evilrock = require("triggerfield.evilrock") local M = {} -- nameDE, nameEN, leftover item, { {empty target container, filled target container}, ...} local drinkList = {} drinkList[2500] = { "Weinflasche", "bottle of wine", 2498, {{1858, 1860}, {224, 1857}, {2055, 2057}, {1840, 1842}, {2185, 2187}} } -- Kelch, Goldkelch, Glas, Kupferkelch, Holzbecher drinkList[2496] = { "Wasserflasche", "bottle of water", 2498, { {1858, 1855}, {224, 1854}, {2055, 2058},{1840, 1841}, {2185, 2186} } } drinkList[2497] = { "Metflasche", "bottle of mead", 2498, { {1858, 1853}, {224, 1856}, {2055, 2056},{1840, 1843}, {2185, 2188} } } drinkList[2501] = { "Bierflasche", "bottle of dark beer", 2498, { {1908, 1909} } } -- Krug drinkList[2499] = { "Ciderflasche", "bottle of cider", 2498, { {1858, 1859}, {224, 1861},{2055, 2059},{1840, 1844}, {2185, 2189} } } local BottleQualDe = {"Randvolle ", "Volle ", "Halbvolle ", "Fast leere "} local BottleQualEn = {"Brimfull ", "Full ", "Half full ", "Almost empty "} local BottleQualLm = {8, 6, 3, 1} local function Evilrockentrance(User, SourceItem, ltstate) local checkBucket = world:getItemOnField(position(997,199,2)) if checkBucket.id == 51 and SourceItem.id == 2496 then local foundSource -- check for empty bucket local TargetItem = common.GetItemInArea(User.pos, 51); if (TargetItem ~= nil) then common.TurnTo( User, position(997,199,2) ); -- turn if necessary foundSource=true end if not foundSource then -- nothing found to fill the bucket. common.InformNLS(User,"Du solltest schon einen anderen Eimer zum Umfllen haben.","You should have another container to transfer the water."); return end if ( ltstate == Action.none ) then User:startAction( 20, 21, 5, 10, 25); User:talk(Character.say, "#me beginnt den Eimer zu befllen.", "#me starts to fill bucket.") return end world:swap(checkBucket,52,999) --[[ local checkFullBucket = world:getItemOnField(position(997,199,3)) if checkFullBucket.id == 52 then checkFullBucket.wear=255 world:changeItem(checkFullBucket) end ]] evilrock.RemoveEntranceTrap(User) local notCreated = User:createItem( 2498, 1, 999, nil ); -- create the new produced items if SourceItem.number == 1 then world:erase(SourceItem,1) return end end end function M.UseItem(User, SourceItem) local progress = User:getQuestProgress(1); local food = drinkList[ SourceItem.id ]; if (food ~= nil ) then Evilrockentrance(User, SourceItem, ltstate) local TargetItem = common.GetTargetItem(User, SourceItem); if( TargetItem ) then for i, combo in pairs(food[4]) do if combo[1] == TargetItem.id then -- fill drink if (TargetItem.number > 1) then world:erase( TargetItem, 1 ); User:createItem( combo[2], 1, 333,nil); else TargetItem.id = combo[2]; world:changeItem(TargetItem); end world:makeSound(10,User.pos) -- create leftovers if( SourceItem.quality > 199 ) then -- reduce one portion world:changeQuality( SourceItem, -100 ); else if( math.random( 50 ) <= 1 ) then common.InformNLS( User, "Die leere Flasche ist angeschlagen und unbrauchbar.", "The empty bottle is broken and no longer usable."); else local dataCopy = {descriptionDe=SourceItem:getData("descriptionDe"), descriptionEn=SourceItem:getData("descriptionEn")}; local notCreated = User:createItem( food[3], 1, 333, dataCopy); -- create the remnant item if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId(food[3], notCreated, User.pos, true, 333, dataCopy); common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more."); end end world:erase(SourceItem,1); end -- cancel after one found item break; end -- found item end -- search loop else common.InformNLS( User, "Nimm die Flasche und ein Trinkgef in deine Hnde.", "Take the bottle and a drinking vessel in your hands."); end else --User:inform("unkown bottle item "); end end function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) local food = drinkList[ Item.id ]; if food == nil then return lookAt end -- decode item quality, extract duration local itemDura=math.fmod(Item.quality,100); local itemQual=(Item.quality-itemDura)/100; --User:inform("portions "..itemQual); -- build description local DisplayText=""; -- build quality text for i,qualLimit in pairs(BottleQualLm) do if (itemQual>=qualLimit ) then DisplayText = common.GetNLS( User, BottleQualDe[i], BottleQualEn[i] ); break; end end DisplayText = DisplayText..common.GetNLS( User, food[1], food[2] ); if lookAt.description ~= nil then -- append the label DisplayText = DisplayText..". "..lookAt.description; end lookAt.description = DisplayText return lookAt end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.bottles' WHERE itm_id IN (2500, 2496, 2497, 2501, 2499); local common = require("base.common") local lookat = require("base.lookat") local evilrock = require("triggerfield.evilrock") local M = {} -- nameDE, nameEN, leftover item, { {empty target container, filled target container}, ...} local drinkList = {} drinkList[2500] = { "Weinflasche", "bottle of wine", 2498, {{1858, 1860}, {224, 1857}, {2055, 2057}, {1840, 1842}, {2185, 2187}} } -- Kelch, Goldkelch, Glas, Kupferkelch, Holzbecher drinkList[2496] = { "Wasserflasche", "bottle of water", 2498, { {1858, 1855}, {224, 1854}, {2055, 2058},{1840, 1841}, {2185, 2186} } } drinkList[2497] = { "Metflasche", "bottle of mead", 2498, { {1858, 1853}, {224, 1856}, {2055, 2056},{1840, 1843}, {2185, 2188} } } drinkList[2501] = { "Bierflasche", "bottle of dark beer", 2498, { {1908, 1909} } } -- Krug drinkList[2499] = { "Ciderflasche", "bottle of cider", 2498, { {1858, 1859}, {224, 1861},{2055, 2059},{1840, 1844}, {2185, 2189} } } local BottleQualDe = {"Randvolle ", "Volle ", "Halbvolle ", "Fast leere "} local BottleQualEn = {"Brimfull ", "Full ", "Half full ", "Almost empty "} local BottleQualLm = {8, 6, 3, 1} function M.UseItem(User, SourceItem) local progress = User:getQuestProgress(1); local food = drinkList[ SourceItem.id ]; if (food ~= nil ) then Evilrockentrance(User, SourceItem, ltstate) local TargetItem = common.GetTargetItem(User, SourceItem); if( TargetItem ) then for i, combo in pairs(food[4]) do if combo[1] == TargetItem.id then -- fill drink if (TargetItem.number > 1) then world:erase( TargetItem, 1 ); User:createItem( combo[2], 1, 333,nil); else TargetItem.id = combo[2]; world:changeItem(TargetItem); end world:makeSound(10,User.pos) -- create leftovers if( SourceItem.quality > 199 ) then -- reduce one portion world:changeQuality( SourceItem, -100 ); else if( math.random( 50 ) <= 1 ) then common.InformNLS( User, "Die leere Flasche ist angeschlagen und unbrauchbar.", "The empty bottle is broken and no longer usable."); else local dataCopy = {descriptionDe=SourceItem:getData("descriptionDe"), descriptionEn=SourceItem:getData("descriptionEn")}; local notCreated = User:createItem( food[3], 1, 333, dataCopy); -- create the remnant item if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId(food[3], notCreated, User.pos, true, 333, dataCopy); common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more."); end end world:erase(SourceItem,1); end -- cancel after one found item break; end -- found item end -- search loop else common.InformNLS( User, "Nimm die Flasche und ein Trinkgef in deine Hnde.", "Take the bottle and a drinking vessel in your hands."); end else --User:inform("unkown bottle item "); end end function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) local food = drinkList[ Item.id ]; if food == nil then return lookAt end -- decode item quality, extract duration local itemDura=math.fmod(Item.quality,100); local itemQual=(Item.quality-itemDura)/100; --User:inform("portions "..itemQual); -- build description local DisplayText=""; -- build quality text for i,qualLimit in pairs(BottleQualLm) do if (itemQual>=qualLimit ) then DisplayText = common.GetNLS( User, BottleQualDe[i], BottleQualEn[i] ); break; end end DisplayText = DisplayText..common.GetNLS( User, food[1], food[2] ); if lookAt.description ~= nil then -- append the label DisplayText = DisplayText..". "..lookAt.description; end lookAt.description = DisplayText return lookAt end local function Evilrockentrance(User, SourceItem, ltstate) local checkBucket = world:getItemOnField(position(997,199,2)) if checkBucket.id == 51 and SourceItem.id == 2496 then local foundSource -- check for empty bucket local TargetItem = common.GetItemInArea(User.pos, 51); if (TargetItem ~= nil) then common.TurnTo( User, position(997,199,2) ); -- turn if necessary foundSource=true end if not foundSource then -- nothing found to fill the bucket. common.InformNLS(User,"Du solltest schon einen anderen Eimer zum Umfllen haben.","You should have another container to transfer the water."); return end if ( ltstate == Action.none ) then User:startAction( 20, 21, 5, 10, 25); User:talk(Character.say, "#me beginnt den Eimer zu befllen.", "#me starts to fill bucket.") return end world:swap(checkBucket,52,999) --[[ local checkFullBucket = world:getItemOnField(position(997,199,3)) if checkFullBucket.id == 52 then checkFullBucket.wear=255 world:changeItem(checkFullBucket) end ]] evilrock.RemoveEntranceTrap(User) local notCreated = User:createItem( 2498, 1, 999, nil ); -- create the new produced items if SourceItem.number == 1 then world:erase(SourceItem,1) return end end end return M
#11013 fix error message
#11013 fix error message
Lua
agpl-3.0
Illarion-eV/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content
3540594a4e15b0c3fc7e47ecdd7fe85cb0de45e8
item/gems.lua
item/gems.lua
require("content.lookat.unique") require("base.common") -- UPDATE common SET com_script='item.gems' WHERE com_itemid IN (45, 46, 197, 198, 283, 284, 285); module("item.gems", package.seeall, package.seeall(content.lookat.unique)) function initStones() stoneNumber={}; stoneNumber[285]=1; -- diamant 285 -> 1 stoneNumber[45]=2; -- smaragd 45 -> 2 stoneNumber[46]=3; -- rubin 46 -> 3 stoneNumber[283]=4; -- schwarzstein 283 -> 4 stoneNumber[284]=5; -- blaustein 284 -> 5 stoneNumber[197]=6; -- amethyst 197 -> 6 stoneNumber[198]=7; -- topas 198 -> 7 end function initJewel() jewelNumber={}; jewelNumber[280]=1; -- Diamantring 280 -> 1 jewelNumber[281]=2; -- smaragdring 281 -> 2 jewelNumber[68]=3; -- rubinring 68 -> 3 jewelNumber[278]=4; -- schwarzsteinring 278 -> 4 jewelNumber[279]=5; -- blausteinring 279 -> 5 jewelNumber[277]=6; -- amethystring 277 -> 6 jewelNumber[282]=7; -- topasring 282 -> 7 jewelNumber[235]=8; -- Goldring 235 -> 8 end ------------------------------------------- -- stone2 | str2 - 1 | stone1 | str1 - 1 -- ------------------------------------------- function generateData(gemItem,TargetItem,itemCl,dummy) if initSt==nil then initStones(); initSt=1; end if TargetItem.data==0 then -- first stone inserted --dummy:inform("1"); newData=(gemItem.data-1); newData=newData+10*stoneNumber[gemItem.id] elseif ((TargetItem.data>9) and (TargetItem.data<100) and itemCl~=7) then -- second stone inserted (not for jewels) --dummy:inform("2"); newData=TargetItem.data; newData=newData+100*(gemItem.data-1); newData=newData+1000*stoneNumber[gemItem.id]; else --dummy:inform("3"); return 0; end return newData; end function LookAtItem(User,Item) -- Data 1 -> latent -- Data 2 -> bedingt -- Data 3 -> leicht -- Data 4 -> maessig -- Data 5 -> normal -- Data 6 -> bemerkenswert -- Data 7 -> stark -- Data 8 -> sehr stark -- Data 9 -> unglaublich -- Data 10 -> einzigartig ItemName=world:getItemName( Item.id, User:getPlayerLanguage() ); GEM_DATA_DE= { "latent ", "bedingt ", "leicht ", "m��ig ", "", "bemerkenswert ", "stark ", "sehr stark ", "unglaublich ", "einzigartig " } GEM_DATA_EN= { "latent ", "limited ", "slight ", "moderate ", "", "notable ", "strong ", "very strong ", "unbelievable ", "unique " } if ( (Item.data > 0) and (Item.data < 11) ) then if User:getPlayerLanguage() == 0 then world:itemInform(User,Item,"Du siehst "..GEM_DATA_DE[Item.data].."magischer "..ItemName); else world:itemInform(User,Item,"You see "..GEM_DATA_EN[Item.data].."magical "..ItemName); end; else if User:getPlayerLanguage() == 0 then world:itemInform(User,Item,"Du siehst "..ItemName); else world:itemInform(User,Item,"You see "..ItemName); end; end end function UseItem(User,SourceItem,TargetItem,Counter,Param) -- 1 -> Waffen -- 2 -> B�gen (Fernkampfwaffen) -- 3 -> R�stung -- 4 -> Schilde -- 5 -> Zauberst�be -- 6 -> Werkzeuge -- 7 -> Schmuck itemList(); if ItemClass[TargetItem.id] ~= nil then if checkjewel(SourceItem, TargetItem,ItemClass[TargetItem.id]) then if SourceItem.data >0 and SourceItem.data<11 then dataVal=generateData(SourceItem,TargetItem,ItemClass[TargetItem.id],User); if dataVal>0 then --User:inform("data. "..dataVal); TargetItem.data=dataVal; world:changeItem(TargetItem); world:erase(SourceItem,1); else base.common.InformNLS(User, "Dieser Edelstein kann dort nicht eingef�gt werden.", "The gem cannot be inserted here!"); end end else base.common.InformNLS(User, "Das funktioniert nicht.", "This cannot be done."); end end end function checkjewel(GemItem, TargetItem,ItemClass) if ItemClass==7 then if initSt==nil then initStones(); initSt=1; end if initJw==nil then initJewel(); initJw=1; end if ( (stoneNumber[GemItem.id]==jewelNumber[TargetItem.id]) or jewelNumber[TargetItem.id]==8 ) then return true; else return false; end else return true; end end
require("content.lookat.unique") require("base.common") -- UPDATE common SET com_script='item.gems' WHERE com_itemid IN (45, 46, 197, 198, 283, 284, 285); module("item.gems", package.seeall) function initStones() stoneNumber={}; stoneNumber[285]=1; -- diamant 285 -> 1 stoneNumber[45]=2; -- smaragd 45 -> 2 stoneNumber[46]=3; -- rubin 46 -> 3 stoneNumber[283]=4; -- schwarzstein 283 -> 4 stoneNumber[284]=5; -- blaustein 284 -> 5 stoneNumber[197]=6; -- amethyst 197 -> 6 stoneNumber[198]=7; -- topas 198 -> 7 end function initJewel() jewelNumber={}; jewelNumber[280]=1; -- Diamantring 280 -> 1 jewelNumber[281]=2; -- smaragdring 281 -> 2 jewelNumber[68]=3; -- rubinring 68 -> 3 jewelNumber[278]=4; -- schwarzsteinring 278 -> 4 jewelNumber[279]=5; -- blausteinring 279 -> 5 jewelNumber[277]=6; -- amethystring 277 -> 6 jewelNumber[282]=7; -- topasring 282 -> 7 jewelNumber[235]=8; -- Goldring 235 -> 8 end ------------------------------------------- -- stone2 | str2 - 1 | stone1 | str1 - 1 -- ------------------------------------------- function generateData(gemItem,TargetItem,itemCl,dummy) if initSt==nil then initStones(); initSt=1; end if TargetItem.data==0 then -- first stone inserted --dummy:inform("1"); newData=(gemItem.data-1); newData=newData+10*stoneNumber[gemItem.id] elseif ((TargetItem.data>9) and (TargetItem.data<100) and itemCl~=7) then -- second stone inserted (not for jewels) --dummy:inform("2"); newData=TargetItem.data; newData=newData+100*(gemItem.data-1); newData=newData+1000*stoneNumber[gemItem.id]; else --dummy:inform("3"); return 0; end return newData; end function LookAtItem(User,Item) -- Data 1 -> latent -- Data 2 -> bedingt -- Data 3 -> leicht -- Data 4 -> maessig -- Data 5 -> normal -- Data 6 -> bemerkenswert -- Data 7 -> stark -- Data 8 -> sehr stark -- Data 9 -> unglaublich -- Data 10 -> einzigartig ItemName=world:getItemName( Item.id, User:getPlayerLanguage() ); GEM_DATA_DE= { "latent ", "bedingt ", "leicht ", "m��ig ", "", "bemerkenswert ", "stark ", "sehr stark ", "unglaublich ", "einzigartig " } GEM_DATA_EN= { "latent ", "limited ", "slight ", "moderate ", "", "notable ", "strong ", "very strong ", "unbelievable ", "unique " } if ( (Item.data > 0) and (Item.data < 11) ) then if User:getPlayerLanguage() == 0 then world:itemInform(User,Item,"Du siehst "..GEM_DATA_DE[Item.data].."magischer "..ItemName); else world:itemInform(User,Item,"You see "..GEM_DATA_EN[Item.data].."magical "..ItemName); end; else if User:getPlayerLanguage() == 0 then world:itemInform(User,Item,"Du siehst "..ItemName); else world:itemInform(User,Item,"You see "..ItemName); end; end end function UseItem(User,SourceItem,TargetItem,Counter,Param) -- 1 -> Waffen -- 2 -> B�gen (Fernkampfwaffen) -- 3 -> R�stung -- 4 -> Schilde -- 5 -> Zauberst�be -- 6 -> Werkzeuge -- 7 -> Schmuck content.lookat.unique.itemList(); if ItemClass[TargetItem.id] ~= nil then if checkjewel(SourceItem, TargetItem,ItemClass[TargetItem.id]) then if SourceItem.data >0 and SourceItem.data<11 then dataVal=generateData(SourceItem,TargetItem,ItemClass[TargetItem.id],User); if dataVal>0 then --User:inform("data. "..dataVal); TargetItem.data=dataVal; world:changeItem(TargetItem); world:erase(SourceItem,1); else base.common.InformNLS(User, "Dieser Edelstein kann dort nicht eingef�gt werden.", "The gem cannot be inserted here!"); end end else base.common.InformNLS(User, "Das funktioniert nicht.", "This cannot be done."); end end end function checkjewel(GemItem, TargetItem,ItemClass) if ItemClass==7 then if initSt==nil then initStones(); initSt=1; end if initJw==nil then initJewel(); initJw=1; end if ( (stoneNumber[GemItem.id]==jewelNumber[TargetItem.id]) or jewelNumber[TargetItem.id]==8 ) then return true; else return false; end else return true; end end
Module Bug Fix
Module Bug Fix
Lua
agpl-3.0
LaFamiglia/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
49f0fcb34bfa57e8ec570c24181bfa6fd79128fa
lua/simple-test.lua
lua/simple-test.lua
local luasimplex = require("luasimplex") local rsm = require("luasimplex.rsm") local M = { -- number of variables nvars = 4, -- number of constraints nrows = 2, indexes = luasimplex.iarray(6, 1, 2, 3, 1, 2, 4), elements = luasimplex.darray(6, 1, 2, 1, 2, 1, 1), row_starts = luasimplex.iarray(3, 1, 4, 7), c = luasimplex.darray(4, -1, -1, 0, 0), xl = luasimplex.darray(4, 0, 0, 0, 0), xu = luasimplex.darray(4, math.huge, math.huge, math.huge, math.huge), b = luasimplex.darray(2, 3, 3), } objective, x = rsm.solve(M, {}) io.stderr:write(("Objective: %g\n"):format(objective)) io.stderr:write(" x:") for i = 1, M.nvars do io.stderr:write((" %g"):format(x[i])) end io.stderr:write("\n") -- EOF -------------------------------------------------------------------------
local luasimplex = require("luasimplex") local rsm = require("luasimplex.rsm") local M = { -- number of variables nvars = 4, -- number of constraints nrows = 2, indexes = luasimplex.iarray(6, 1, 2, 3, 1, 2, 4), elements = luasimplex.darray(6, 1, 2, 1, 2, 1, 1), row_starts = luasimplex.iarray(3, 1, 4, 7), c = luasimplex.darray(4, -1, -1, 0, 0), xl = luasimplex.darray(4, 0, 0, 0, 0), xu = luasimplex.darray(4, math.huge, math.huge, math.huge, math.huge), b = luasimplex.darray(2, 3, 3), } local I = luasimplex.new_instance(M.nrows, M.nvars) rsm.initialise(M, I, {}) objective, x = rsm.solve(M, I, {}) io.stderr:write(("Objective: %g\n"):format(objective)) io.stderr:write(" x:") for i = 1, M.nvars do io.stderr:write((" %g"):format(x[i])) end io.stderr:write("\n") -- EOF -------------------------------------------------------------------------
Fixed simple-test.lua
Fixed simple-test.lua
Lua
mit
geoffleyland/luasimplex,geoffleyland/luasimplex,geoffleyland/luasimplex
fc09c47f182136c48e64db089710e4284b0a200d
luasrc/mch/util.lua
luasrc/mch/util.lua
#!/usr/bin/env lua -- -*- lua -*- -- Copyright 2012 Appwill Inc. -- Author : KDr2 -- -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- local json = require("cjson") local math_floor = math.floor local string_char = string.char local string_byte = string.byte local string_rep = string.rep local string_sub = string.sub local debug_getinfo = debug.getinfo local mchvars = require("mch.vars") module('mch.util', package.seeall) function read_all(filename) local file = io.open(filename, "r") local data = ((file and file:read("*a")) or nil) if file then file:close() end return data end function setup_app_env(mch_home, app_name, app_path, global) global['MOOCHINE_HOME']=mch_home global['MOOCHINE_APP']=appname global['MOOCHINE_APP_PATH']=app_path package.path = mch_home .. '/lualibs/?.lua;' .. package.path package.path = app_path .. '/app/?.lua;' .. package.path local request=require("mch.request") local response=require("mch.response") global['MOOCHINE_MODULES']={} global['MOOCHINE_MODULES']['request']=request global['MOOCHINE_MODULES']['response']=response end function loadvars(file) local env = setmetatable({}, {__index=_G}) assert(pcall(setfenv(assert(loadfile(file)), env))) setmetatable(env, nil) return env end function get_config(key, default) if key == nil then return nil end local issub, subname = is_subapp(3) if not issub then -- main app local ret = ngx.var[key] if ret then return ret end local app_conf=mchvars.get(ngx.ctx.MOOCHINE_APP_NAME,"APP_CONFIG") return app_conf[key] or default end -- sub app if not subname then return default end local subapps=mchvars.get(ngx.ctx.MOOCHINE_APP_NAME,"APP_CONFIG").subapps or {} local subconfig=subapps[subname].config or {} return subconfig[key] or default end function _strify(o, tab, act, logged) local v = tostring(o) if logged[o] then return v end if string_sub(v,0,6) == "table:" then logged[o] = true act = "\n" .. string_rep("| ",tab) .. "{ [".. tostring(o) .. ", " act = act .. table_real_length(o) .." item(s)]" for k, v in pairs(o) do act = act .."\n" .. string_rep("| ", tab) act = act .. "| *".. k .. "\t=>\t" .. _strify(v, tab+1, act, logged) end act = act .. "\n" .. string_rep("| ",tab) .. "}" return act else return v end end function strify(o) return _strify(o, 1, "", {}) end function table_print(t) local s1="\n* Table String:" local s2="\n* End Table" return s1 .. strify(t) .. s2 end function table_real_length(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end function is_subapp(__call_frame_level) if not __call_frame_level then __call_frame_level = 2 end local caller = debug_getinfo(__call_frame_level,'S').source local main_app = ngx.var.MOOCHINE_APP_PATH local is_mainapp = (main_app == (string_sub(caller, 2, #main_app+1))) if is_mainapp then return false, nil end -- main app local subapps = mchvars.get(ngx.ctx.MOOCHINE_APP_NAME, "APP_CONFIG").subapps or {} for k, v in pairs(subapps) do local spath = v.path local is_this_subapp = (spath == (string_sub(caller, 2, #spath+1))) if is_this_subapp then return true, k end -- sub app end return false, nil -- not main/sub app, maybe call in moochine! end function parseNetInt(bytes) local a, b, c, d = string_byte(bytes, 1, 4) return a * 256 ^ 3 + b * 256 ^ 2 + c * 256 + d end function toNetInt(n) -- NOTE: for little endian machine only!!! local d = n % 256 n = math_floor(n / 256) local c = n % 256 n = math_floor(n / 256) local b = n % 256 n = math_floor(n / 256) local a = n return string_char(a) .. string_char(b) .. string_char(c) .. string_char(d) end function write_jsonresponse(sock, s) if type(s) == 'table' then s = json.encode(s) end local l = toNetInt(#s) sock:send(l .. s) end function read_jsonresponse(sock) local r, err = sock:receive(4) if not r then logger:warn('Error when receiving from socket: %s', err) return end local len = parseNetInt(r) data, err = sock:receive(len) if not data then logger:error('Error when receiving from socket: %s', err) return end return json.decode(data) end
#!/usr/bin/env lua -- -*- lua -*- -- Copyright 2012 Appwill Inc. -- Author : KDr2 -- -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- local json = require("cjson") local math_floor = math.floor local string_char = string.char local string_byte = string.byte local string_rep = string.rep local string_sub = string.sub local debug_getinfo = debug.getinfo local mchvars = require("mch.vars") module('mch.util', package.seeall) function read_all(filename) local file = io.open(filename, "r") local data = ((file and file:read("*a")) or nil) if file then file:close() end return data end function setup_app_env(mch_home, app_name, app_path, global) global['MOOCHINE_HOME']=mch_home global['MOOCHINE_APP']=appname global['MOOCHINE_APP_PATH']=app_path package.path = mch_home .. '/lualibs/?.lua;' .. package.path package.path = app_path .. '/app/?.lua;' .. package.path local request=require("mch.request") local response=require("mch.response") global['MOOCHINE_MODULES']={} global['MOOCHINE_MODULES']['request']=request global['MOOCHINE_MODULES']['response']=response end function loadvars(file) local env = setmetatable({}, {__index=_G}) assert(pcall(setfenv(assert(loadfile(file)), env))) setmetatable(env, nil) return env end function get_config(key, default) if key == nil then return nil end local issub, subname = is_subapp(3) if not issub then -- main app local ret = ngx.var[key] if ret then return ret end local app_conf=mchvars.get(ngx.ctx.MOOCHINE_APP_NAME,"APP_CONFIG") local v = app_conf[key] if v==nil then v = default end return v end -- sub app if not subname then return default end local subapps=mchvars.get(ngx.ctx.MOOCHINE_APP_NAME,"APP_CONFIG").subapps or {} local subconfig=subapps[subname].config or {} local v = subconfig[key] if v==nil then v = default end return v end function _strify(o, tab, act, logged) local v = tostring(o) if logged[o] then return v end if string_sub(v,0,6) == "table:" then logged[o] = true act = "\n" .. string_rep("| ",tab) .. "{ [".. tostring(o) .. ", " act = act .. table_real_length(o) .." item(s)]" for k, v in pairs(o) do act = act .."\n" .. string_rep("| ", tab) act = act .. "| *".. k .. "\t=>\t" .. _strify(v, tab+1, act, logged) end act = act .. "\n" .. string_rep("| ",tab) .. "}" return act else return v end end function strify(o) return _strify(o, 1, "", {}) end function table_print(t) local s1="\n* Table String:" local s2="\n* End Table" return s1 .. strify(t) .. s2 end function table_real_length(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end function is_subapp(__call_frame_level) if not __call_frame_level then __call_frame_level = 2 end local caller = debug_getinfo(__call_frame_level,'S').source local main_app = ngx.var.MOOCHINE_APP_PATH local is_mainapp = (main_app == (string_sub(caller, 2, #main_app+1))) if is_mainapp then return false, nil end -- main app local subapps = mchvars.get(ngx.ctx.MOOCHINE_APP_NAME, "APP_CONFIG").subapps or {} for k, v in pairs(subapps) do local spath = v.path local is_this_subapp = (spath == (string_sub(caller, 2, #spath+1))) if is_this_subapp then return true, k end -- sub app end return false, nil -- not main/sub app, maybe call in moochine! end function parseNetInt(bytes) local a, b, c, d = string_byte(bytes, 1, 4) return a * 256 ^ 3 + b * 256 ^ 2 + c * 256 + d end function toNetInt(n) -- NOTE: for little endian machine only!!! local d = n % 256 n = math_floor(n / 256) local c = n % 256 n = math_floor(n / 256) local b = n % 256 n = math_floor(n / 256) local a = n return string_char(a) .. string_char(b) .. string_char(c) .. string_char(d) end function write_jsonresponse(sock, s) if type(s) == 'table' then s = json.encode(s) end local l = toNetInt(#s) sock:send(l .. s) end function read_jsonresponse(sock) local r, err = sock:receive(4) if not r then logger:warn('Error when receiving from socket: %s', err) return end local len = parseNetInt(r) data, err = sock:receive(len) if not data then logger:error('Error when receiving from socket: %s', err) return end return json.decode(data) end
fixed get_config
fixed get_config
Lua
apache-2.0
lilien1010/moochine,appwilldev/moochine,lilien1010/moochine,lilien1010/moochine,appwilldev/moochine
56a5664ceb215bd5fbce2e1b1f530391bbdf4d5f
src/cosy/server/middleware/http.lua
src/cosy/server/middleware/http.lua
local url = require "socket.url" local mime = require "mime" local base64 = {} base64.encode = mime.b64 base64.decode = mime.unb64 local Http = {} function Http.request (context) local skt = context.skt local firstline = skt:receive "*l" if firstline == nil then context.continue = false error (true) end -- Extract method: local method, query, protocol = firstline:match "^(%a+)%s+(%S+)%s+(%S+)" if not method or not query or not protocol then error { code = 400, message = "Bad Request", } end local request = context.request local response = context.response request.protocol = protocol request.method = method:upper () request.query = query local parsed = url.parse (query) request.resource = url.parse_path (parsed.path) -- Set default headers depending on protocol: local headers = request.headers response.protocol = request.protocol if protocol == "HTTP/1.0" then headers.connection = "close" elseif protocol == "HTTP/1.1" then headers.connection = "keep-alive" else assert (false) end -- Extract headers: while true do local line = skt:receive "*l" if line == "" then break end local name, value = line:match "([^:]+):%s*(.*)" name = name:trim ():lower ():gsub ("-", "_") value = value:trim () headers [name] = value end -- Extract parameters: local parameters = request.parameters local params = parsed.query or "" for p in params:gmatch "([^;&]+)" do local k, v = p:match "([^=]+)=(.*)" k = url.unescape (k):gsub ("+", " ") v = url.unescape (v):gsub ("+", " ") parameters [k] = v end -- Handle headers: local handled = {} local handlers = {} local nb_handlers = 0 for k in pairs (headers) do local ok, handler = pcall (require, "cosy.server.header." .. k) if not ok then error { code = 412, message = "Precondition Failed", reason = "unknown header: " .. k } end if not handler.request then error ("No request for " .. k) end handlers [k] = handler nb_handlers = nb_handlers + 1 end local count = 0 while count ~= nb_handlers do for k, handler in pairs (handlers) do if not handled [k] then local missing = false for _, k in ipairs (handler.depends or {}) do k = k:lower ():gsub ("-", "_") if headers [k] and not handled [k] then missing = true break end end if not missing then handler.request (context) handled [k] = true count = count + 1 end end end end end function Http.response (context) local skt = context.skt local request = context.request local response = context.response local headers = response.headers local body = response.body assert (response.code) -- Set Content-Length or Transfer-Encoding: if body == nil then response.headers.content_length = 0 elseif type (body) == "string" then response.headers.content_length = #(body) elseif type (body) == "function" then response.headers.transfer_encoding = "chunked" else assert (false) end -- Handle headers: -- FIXME: use the same as in request for k in pairs (headers) do local ok, handler = pcall (require, "cosy.server.header." .. k) if not ok then error { code = 412, message = "Precondition Failed", reason = "unknown header: " .. k } end if not handler.response then error ("No response for " .. k) end handler.response (context) end -- Send response: local to_send = {} to_send [1] = "${protocol} ${code} ${message}" % { protocol = response.protocol, code = response.code, message = response.message, } for k, v in pairs (headers) do to_send [#to_send + 1] = "${name}: ${value}" % { name = k:gsub ("_", "-"), value = v, } end to_send [#to_send + 1] = "" if body == nil then skt:send (table.concat (to_send, "\r\n")) elseif type (body) == "string" then to_send [#to_send + 1] = body skt:send (table.concat (to_send, "\r\n")) elseif type (body) == "function" then skt:send (table.concat (to_send, "\r\n")) for s in body () do local data = tostring (s) skt:send ("${size}\r\n${data}" % { size = #data, data = data, }) end end end function Http.error (context, err) if type (err) == "table" and err.code then context.response = { code = err.code, message = err.message or "", body = err.reason or "", headers = {}, } Http.response (context) else context.continue = false context.response = { code = 500, message = "Internal Server Error", headers = { connection = { ["close"] = true } }, } Http.response (context) error (err) end end return Http
local url = require "socket.url" local mime = require "mime" local base64 = {} base64.encode = mime.b64 base64.decode = mime.unb64 local Http = {} function Http.request (context) local skt = context.skt local firstline = skt:receive "*l" if firstline == nil then context.continue = false error (true) end -- Extract method: local method, query, protocol = firstline:match "^(%a+)%s+(%S+)%s+(%S+)" if not method or not query or not protocol then error { code = 400, message = "Bad Request", } end local request = context.request local response = context.response request.protocol = protocol request.method = method:upper () request.query = query local parsed = url.parse (query) request.resource = url.parse_path (parsed.path) -- Set default headers depending on protocol: local headers = request.headers response.protocol = request.protocol if protocol == "HTTP/1.0" then headers.connection = "close" elseif protocol == "HTTP/1.1" then headers.connection = "keep-alive" else assert (false) end -- Extract headers: while true do local line = skt:receive "*l" if line == "" then break end local name, value = line:match "([^:]+):%s*(.*)" name = name:trim ():lower ():gsub ("-", "_") value = value:trim () headers [name] = value end -- Extract parameters: local parameters = request.parameters local params = parsed.query or "" for p in params:gmatch "([^;&]+)" do local k, v = p:match "([^=]+)=(.*)" k = url.unescape (k):gsub ("+", " ") v = url.unescape (v):gsub ("+", " ") parameters [k] = v end -- Handle headers: local handled = {} local handlers = {} local nb_handlers = 0 for k in pairs (headers) do local ok, handler = pcall (require, "cosy.server.header." .. k) if not ok then error { code = 412, message = "Precondition Failed", reason = "unknown header: " .. k } end if not handler.request then error ("No request for " .. k) end handlers [k] = handler nb_handlers = nb_handlers + 1 end local count = 0 while count ~= nb_handlers do for k, handler in pairs (handlers) do if not handled [k] then local missing = false for _, k in ipairs (handler.depends or {}) do k = k:lower ():gsub ("-", "_") if headers [k] and not handled [k] then missing = true break end end if not missing then handler.request (context) handled [k] = true count = count + 1 end end end end end function Http.response (context) local skt = context.skt local response = context.response local headers = response.headers local body = response.body assert (response.code) -- Set Content-Length or Transfer-Encoding: if body == nil then response.headers.content_length = 0 elseif type (body) == "string" then response.headers.content_length = #(body) elseif type (body) == "function" then response.headers.transfer_encoding = "chunked" else assert (false) end -- Handle headers: -- FIXME: use the same as in request for k in pairs (headers) do local ok, handler = pcall (require, "cosy.server.header." .. k) if not ok then error { code = 412, message = "Precondition Failed", reason = "unknown header: " .. k } end if not handler.response then error ("No response for " .. k) end handler.response (context) end -- Send response: local to_send = {} to_send [1] = "${protocol} ${code} ${message}" % { protocol = response.protocol, code = response.code, message = response.message, } for k, v in pairs (headers) do to_send [#to_send + 1] = "${name}: ${value}" % { name = k:gsub ("_", "-"), value = v, } end to_send [#to_send + 1] = "" if body == nil then skt:send (table.concat (to_send, "\r\n")) elseif type (body) == "string" then to_send [#to_send + 1] = body skt:send (table.concat (to_send, "\r\n")) elseif type (body) == "function" then skt:send (table.concat (to_send, "\r\n")) for s in body () do local data = tostring (s) skt:send ("${size}\r\n${data}" % { size = #data, data = data, }) end end end function Http.error (context, err) if type (err) == "table" and err.code then context.response = { code = err.code, message = err.message or "", body = err.reason or "", headers = {}, } Http.response (context) else context.continue = false context.response = { code = 500, message = "Internal Server Error", headers = { connection = { ["close"] = true } }, } Http.response (context) error (err) end end return Http
Fix warning.
Fix warning.
Lua
mit
CosyVerif/data-server,CosyVerif/data-server
233d40ea3954de14e655d32cc1a5e1b4c9082516
lib/light.lua
lib/light.lua
local _PACKAGE = (...):match("^(.+)[%./][^%./]+") or "" local class = require(_PACKAGE.."/class") local stencils = require(_PACKAGE..'/stencils') local util = require(_PACKAGE..'/util') local light = class() light.shader = love.graphics.newShader(_PACKAGE.."/shaders/poly_shadow.glsl") light.normalShader = love.graphics.newShader(_PACKAGE.."/shaders/normal.glsl") light.normalInvertShader = love.graphics.newShader(_PACKAGE.."/shaders/normal_invert.glsl") function light:init(x, y, r, g, b, range) self.direction = 0 self.angle = math.pi * 2.0 self.range = 0 self.x = x or 0 self.y = y or 0 self.z = 15 self.red = r or 255 self.green = g or 255 self.blue = b or 255 self.range = range or 300 self.smooth = 1.0 self.glowSize = 0.1 self.glowStrength = 0.0 self.visible = true self:refresh() end function light:refresh(w, h) w, h = w or love.window.getWidth(), h or love.window.getHeight() self.shadow = love.graphics.newCanvas(w, h) self.shine = love.graphics.newCanvas(w, h) self.normalInvertShader:send('screenResolution', {w, h}) self.normalShader:send('screenResolution', {w, h}) end -- set position function light:setPosition(x, y, z) if x ~= self.x or y ~= self.y or (z and z ~= self.z) then self.x = x self.y = y if z then self.z = z end end end -- get x function light:getPosition() return self.x, self.y, self.z end -- set color function light:setColor(red, green, blue) self.red = red self.green = green self.blue = blue end -- set range function light:setRange(range) if range ~= self.range then self.range = range end end -- set direction function light:setDirection(direction) if direction ~= self.direction then if direction > math.pi * 2 then self.direction = math.mod(direction, math.pi * 2) elseif direction < 0.0 then self.direction = math.pi * 2 - math.mod(math.abs(direction), math.pi * 2) else self.direction = direction end end end -- set angle function light:setAngle(angle) if angle ~= self.angle then if angle > math.pi then self.angle = math.mod(angle, math.pi) elseif angle < 0.0 then self.angle = math.pi - math.mod(math.abs(angle), math.pi) else self.angle = angle end end end -- set glow size function light:setSmooth(smooth) self.smooth = smooth end -- set glow size function light:setGlowSize(size) self.glowSize = size end -- set glow strength function light:setGlowStrength(strength) self.glowStrength = strength end function light:inRange(l,t,w,h) return self.x + self.range > l and self.x - self.range < (l+w) and self.y + self.range > t and self.y - self.range < (t+h) end function light:drawShadow(l,t,w,h,s,bodies, canvas) if self.visible and self:inRange(l,t,w,h) then -- calculate shadows local shadow_geometry = {} for i = 1, #bodies do local current = bodies[i]:calculateShadow(self) if current ~= nil then shadow_geometry[#shadow_geometry + 1] = current end end -- draw shadow self.shadow:clear() util.drawto(self.shadow, l, t, s, function() self.shader:send("lightPosition", {(self.x + l/s) * s, (h/s - (self.y + t/s)) * s, self.z/255.0}) self.shader:send("lightRange", self.range*s) self.shader:send("lightColor", {self.red / 255.0, self.green / 255.0, self.blue / 255.0}) self.shader:send("lightSmooth", self.smooth) self.shader:send("lightGlow", {1.0 - self.glowSize, self.glowStrength}) self.shader:send("lightAngle", math.pi - self.angle / 2.0) self.shader:send("lightDirection", self.direction) love.graphics.setShader(self.shader) love.graphics.setInvertedStencil(stencils.shadow(shadow_geometry, bodies)) love.graphics.setBlendMode("additive") love.graphics.rectangle("fill", -l/s,-t/s,w/s,h/s) -- draw color shadows love.graphics.setBlendMode("multiplicative") love.graphics.setShader() for k = 1,#shadow_geometry do if shadow_geometry[k].alpha < 1.0 then love.graphics.setColor( shadow_geometry[k].red * (1.0 - shadow_geometry[k].alpha), shadow_geometry[k].green * (1.0 - shadow_geometry[k].alpha), shadow_geometry[k].blue * (1.0 - shadow_geometry[k].alpha) ) love.graphics.polygon("fill", unpack(shadow_geometry[k])) end end for k = 1, #bodies do bodies[k]:drawShadow(self,l,t,w,h,s) end end) love.graphics.setStencil() love.graphics.setShader() util.drawCanvasToCanvas(self.shadow, canvas, {blendmode = "additive"}) end end function light:drawShine(l,t,w,h,s,bodies,canvas) if self.visible then --update shine self.shine:clear(255, 255, 255) util.drawto(self.shine, l, t, s, function() love.graphics.setShader(self.shader) love.graphics.setBlendMode("alpha") love.graphics.setStencil(stencils.shine(bodies)) love.graphics.rectangle("fill", -l/s,-t/s,w/s,h/s) end) love.graphics.setStencil() love.graphics.setShader() util.drawCanvasToCanvas(self.shine, canvas, {blendmode = "additive"}) end end function light:drawPixelShadow(l,t,w,h,s, normalMap, canvas) if self.visible then if self.normalInvert then self.normalInvertShader:send('lightColor', {self.red / 255.0, self.green / 255.0, self.blue / 255.0}) self.normalInvertShader:send("lightPosition", {(self.x + l/s) * s, (h/s - (self.y + t/s)) * s, self.z / 255.0}) self.normalInvertShader:send('lightRange',{self.range}) self.normalInvertShader:send("lightSmooth", self.smooth) self.normalInvertShader:send("lightAngle", math.pi - self.angle / 2.0) self.normalInvertShader:send("lightDirection", self.direction) util.drawCanvasToCanvas(normalMap, canvas, {shader = self.normalInvertShader}) else self.normalShader:send('lightColor', {self.red / 255.0, self.green / 255.0, self.blue / 255.0}) self.normalShader:send("lightPosition", {(self.x + l/s) * s, (h/s - (self.y + t/s)) * s, self.z / 255.0}) self.normalShader:send('lightRange',{self.range}) self.normalShader:send("lightSmooth", self.smooth) self.normalShader:send("lightAngle", math.pi - self.angle / 2.0) self.normalShader:send("lightDirection", self.direction) util.drawCanvasToCanvas(normalMap, canvas, {shader = self.normalShader}) end end end return light
local _PACKAGE = (...):match("^(.+)[%./][^%./]+") or "" local class = require(_PACKAGE.."/class") local stencils = require(_PACKAGE..'/stencils') local util = require(_PACKAGE..'/util') local light = class() light.shader = love.graphics.newShader(_PACKAGE.."/shaders/poly_shadow.glsl") light.normalShader = love.graphics.newShader(_PACKAGE.."/shaders/normal.glsl") light.normalInvertShader = love.graphics.newShader(_PACKAGE.."/shaders/normal_invert.glsl") function light:init(x, y, r, g, b, range) self.direction = 0 self.angle = math.pi * 2.0 self.range = 0 self.x = x or 0 self.y = y or 0 self.z = 15 self.red = r or 255 self.green = g or 255 self.blue = b or 255 self.range = range or 300 self.smooth = 1.0 self.glowSize = 0.1 self.glowStrength = 0.0 self.visible = true self:refresh() end function light:refresh(w, h) w, h = w or love.window.getWidth(), h or love.window.getHeight() self.shadow = love.graphics.newCanvas(w, h) self.shine = love.graphics.newCanvas(w, h) self.normalInvertShader:send('screenResolution', {w, h}) self.normalShader:send('screenResolution', {w, h}) end -- set position function light:setPosition(x, y, z) if x ~= self.x or y ~= self.y or (z and z ~= self.z) then self.x = x self.y = y if z then self.z = z end end end -- get x function light:getPosition() return self.x, self.y, self.z end -- set color function light:setColor(red, green, blue) self.red = red self.green = green self.blue = blue end -- set range function light:setRange(range) if range ~= self.range then self.range = range end end -- set direction function light:setDirection(direction) if direction ~= self.direction then if direction > math.pi * 2 then self.direction = math.mod(direction, math.pi * 2) elseif direction < 0.0 then self.direction = math.pi * 2 - math.mod(math.abs(direction), math.pi * 2) else self.direction = direction end end end -- set angle function light:setAngle(angle) if angle ~= self.angle then if angle > math.pi then self.angle = math.mod(angle, math.pi) elseif angle < 0.0 then self.angle = math.pi - math.mod(math.abs(angle), math.pi) else self.angle = angle end end end -- set glow size function light:setSmooth(smooth) self.smooth = smooth end -- set glow size function light:setGlowSize(size) self.glowSize = size end -- set glow strength function light:setGlowStrength(strength) self.glowStrength = strength end function light:inRange(l,t,w,h,s) local lx, ly, rs = (self.x + l/s) * s, (self.y + t/s) * s, self.range * s return (lx + rs) > 0 and (lx - rs) < w/s and (ly + rs) > 0 and (ly - rs) < h/s end function light:drawShadow(l,t,w,h,s,bodies, canvas) if self.visible and self:inRange(l,t,w,h,s) then -- calculate shadows local shadow_geometry = {} for i = 1, #bodies do local current = bodies[i]:calculateShadow(self) if current ~= nil then shadow_geometry[#shadow_geometry + 1] = current end end -- draw shadow self.shadow:clear() util.drawto(self.shadow, l, t, s, function() self.shader:send("lightPosition", {(self.x + l/s) * s, (h/s - (self.y + t/s)) * s, self.z/255.0}) self.shader:send("lightRange", self.range*s) self.shader:send("lightColor", {self.red / 255.0, self.green / 255.0, self.blue / 255.0}) self.shader:send("lightSmooth", self.smooth) self.shader:send("lightGlow", {1.0 - self.glowSize, self.glowStrength}) self.shader:send("lightAngle", math.pi - self.angle / 2.0) self.shader:send("lightDirection", self.direction) love.graphics.setShader(self.shader) love.graphics.setInvertedStencil(stencils.shadow(shadow_geometry, bodies)) love.graphics.setBlendMode("additive") love.graphics.rectangle("fill", -l/s,-t/s,w/s,h/s) -- draw color shadows love.graphics.setBlendMode("multiplicative") love.graphics.setShader() for k = 1,#shadow_geometry do if shadow_geometry[k].alpha < 1.0 then love.graphics.setColor( shadow_geometry[k].red * (1.0 - shadow_geometry[k].alpha), shadow_geometry[k].green * (1.0 - shadow_geometry[k].alpha), shadow_geometry[k].blue * (1.0 - shadow_geometry[k].alpha) ) love.graphics.polygon("fill", unpack(shadow_geometry[k])) end end for k = 1, #bodies do bodies[k]:drawShadow(self,l,t,w,h,s) end end) love.graphics.setStencil() love.graphics.setShader() util.drawCanvasToCanvas(self.shadow, canvas, {blendmode = "additive"}) end end function light:drawShine(l,t,w,h,s,bodies,canvas) if self.visible and self:inRange(l,t,w,h,s) then --update shine self.shine:clear(255, 255, 255) util.drawto(self.shine, l, t, s, function() love.graphics.setShader(self.shader) love.graphics.setBlendMode("alpha") love.graphics.setStencil(stencils.shine(bodies)) love.graphics.rectangle("fill", -l/s,-t/s,w/s,h/s) end) love.graphics.setStencil() love.graphics.setShader() util.drawCanvasToCanvas(self.shine, canvas, {blendmode = "additive"}) end end function light:drawPixelShadow(l,t,w,h,s, normalMap, canvas) if self.visible and self:inRange(l,t,w,h,s) then if self.normalInvert then self.normalInvertShader:send('lightColor', {self.red / 255.0, self.green / 255.0, self.blue / 255.0}) self.normalInvertShader:send("lightPosition", {(self.x + l/s) * s, (h/s - (self.y + t/s)) * s, self.z / 255.0}) self.normalInvertShader:send('lightRange',{self.range}) self.normalInvertShader:send("lightSmooth", self.smooth) self.normalInvertShader:send("lightAngle", math.pi - self.angle / 2.0) self.normalInvertShader:send("lightDirection", self.direction) util.drawCanvasToCanvas(normalMap, canvas, {shader = self.normalInvertShader}) else self.normalShader:send('lightColor', {self.red / 255.0, self.green / 255.0, self.blue / 255.0}) self.normalShader:send("lightPosition", {(self.x + l/s) * s, (h/s - (self.y + t/s)) * s, self.z / 255.0}) self.normalShader:send('lightRange',{self.range}) self.normalShader:send("lightSmooth", self.smooth) self.normalShader:send("lightAngle", math.pi - self.angle / 2.0) self.normalShader:send("lightDirection", self.direction) util.drawCanvasToCanvas(normalMap, canvas, {shader = self.normalShader}) end end end return light
fixed inaccuracy of the inRange method in Light. also added it to the draw methods in light so that they wont draw if not needed
fixed inaccuracy of the inRange method in Light. also added it to the draw methods in light so that they wont draw if not needed
Lua
mit
willemt/light_world.lua
00eda039cdee6998cca54271cf7d6e634a7c1647
MMOCoreORB/bin/scripts/object/draft_schematic/item/serverobjects.lua
MMOCoreORB/bin/scripts/object/draft_schematic/item/serverobjects.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --Children folder includes includeFile("draft_schematic/item/component/serverobjects.lua") includeFile("draft_schematic/item/quest_item/serverobjects.lua") includeFile("draft_schematic/item/theme_park/serverobjects.lua") -- Server Objects includeFile("draft_schematic/item/craftable_bug_habitat.lua") includeFile("draft_schematic/item/item_agitator_motor.lua") includeFile("draft_schematic/item/item_ballot_box_terminal.lua") includeFile("draft_schematic/item/item_base_tool.lua") includeFile("draft_schematic/item/item_battery_droid.lua") includeFile("draft_schematic/item/item_chance_cube.lua") includeFile("draft_schematic/item/item_clothing_station.lua") includeFile("draft_schematic/item/item_clothing_tool.lua") includeFile("draft_schematic/item/item_configurable_sided_dice.lua") includeFile("draft_schematic/item/item_firework_eighteen.lua") includeFile("draft_schematic/item/item_firework_eleven.lua") includeFile("draft_schematic/item/item_firework_five.lua") includeFile("draft_schematic/item/item_firework_four.lua") includeFile("draft_schematic/item/item_firework_one.lua") includeFile("draft_schematic/item/item_firework_show.lua") includeFile("draft_schematic/item/item_firework_ten.lua") includeFile("draft_schematic/item/item_firework_three.lua") includeFile("draft_schematic/item/item_firework_two.lua") includeFile("draft_schematic/item/item_fishing_pole.lua") includeFile("draft_schematic/item/item_food_station.lua") includeFile("draft_schematic/item/item_food_tool.lua") includeFile("draft_schematic/item/item_generic_tool.lua") includeFile("draft_schematic/item/item_hundred_sided_dice.lua") includeFile("draft_schematic/item/item_jedi_tool.lua") includeFile("draft_schematic/item/item_parrot_cage.lua") includeFile("draft_schematic/item/item_powerup_weapon_melee_generic.lua") includeFile("draft_schematic/item/item_powerup_weapon_melee_lightsaber.lua") includeFile("draft_schematic/item/item_powerup_weapon_mine_explosive.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_five.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_four.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_one.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_six.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_three.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_two.lua") includeFile("draft_schematic/item/item_powerup_weapon_thrown_explosive.lua") includeFile("draft_schematic/item/item_powerup_weapon_thrown_wiring.lua") includeFile("draft_schematic/item/item_public_clothing_station.lua") includeFile("draft_schematic/item/item_public_food_station.lua") includeFile("draft_schematic/item/item_public_structure_station.lua") includeFile("draft_schematic/item/item_public_weapon_station.lua") includeFile("draft_schematic/item/item_recycler_chemical.lua") includeFile("draft_schematic/item/item_recycler_creature.lua") includeFile("draft_schematic/item/item_recycler_flora.lua") includeFile("draft_schematic/item/item_recycler_metal.lua") includeFile("draft_schematic/item/item_recycler_ore.lua") includeFile("draft_schematic/item/item_repairkit_armor.lua") includeFile("draft_schematic/item/item_repairkit_clothing.lua") includeFile("draft_schematic/item/item_repairkit_droid.lua") includeFile("draft_schematic/item/item_repairkit_structure.lua") includeFile("draft_schematic/item/item_repairkit_weapon.lua") includeFile("draft_schematic/item/item_shellfish_harvester.lua") includeFile("draft_schematic/item/item_six_sided_dice.lua") includeFile("draft_schematic/item/item_space_station.lua") includeFile("draft_schematic/item/item_space_tool.lua") includeFile("draft_schematic/item/item_structure_station.lua") includeFile("draft_schematic/item/item_structure_tool.lua") includeFile("draft_schematic/item/item_survey_tool_flora.lua") includeFile("draft_schematic/item/item_survey_tool_gas.lua") includeFile("draft_schematic/item/item_survey_tool_liquid.lua") includeFile("draft_schematic/item/item_survey_tool_mineral.lua") includeFile("draft_schematic/item/item_survey_tool_moisture.lua") includeFile("draft_schematic/item/item_survey_tool_solar.lua") includeFile("draft_schematic/item/item_survey_tool_wind.lua") includeFile("draft_schematic/item/item_ten_sided_dice.lua") includeFile("draft_schematic/item/item_tumble_blender.lua") includeFile("draft_schematic/item/item_twelve_sided_dice.lua") includeFile("draft_schematic/item/item_twenty_sided_dice.lua") includeFile("draft_schematic/item/item_weapon_station.lua") includeFile("draft_schematic/item/item_weapon_tool.lua")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --Children folder includes includeFile("draft_schematic/item/component/serverobjects.lua") includeFile("draft_schematic/item/quest_item/serverobjects.lua") includeFile("draft_schematic/item/theme_park/serverobjects.lua") -- Server Objects includeFile("draft_schematic/item/craftable_bug_habitat.lua") includeFile("draft_schematic/item/item_agitator_motor.lua") includeFile("draft_schematic/item/item_ballot_box_terminal.lua") includeFile("draft_schematic/item/item_base_tool.lua") includeFile("draft_schematic/item/item_battery_droid.lua") includeFile("draft_schematic/item/item_chance_cube.lua") includeFile("draft_schematic/item/item_clothing_station.lua") includeFile("draft_schematic/item/item_clothing_tool.lua") includeFile("draft_schematic/item/item_configurable_sided_dice.lua") includeFile("draft_schematic/item/item_firework_eighteen.lua") includeFile("draft_schematic/item/item_firework_eleven.lua") includeFile("draft_schematic/item/item_firework_five.lua") includeFile("draft_schematic/item/item_firework_four.lua") includeFile("draft_schematic/item/item_firework_one.lua") includeFile("draft_schematic/item/item_firework_show.lua") includeFile("draft_schematic/item/item_firework_ten.lua") includeFile("draft_schematic/item/item_firework_three.lua") includeFile("draft_schematic/item/item_firework_two.lua") includeFile("draft_schematic/item/item_fishing_pole.lua") includeFile("draft_schematic/item/item_food_station.lua") includeFile("draft_schematic/item/item_food_tool.lua") includeFile("draft_schematic/item/item_food_tool2.lua") includeFile("draft_schematic/item/item_generic_tool.lua") includeFile("draft_schematic/item/item_hundred_sided_dice.lua") includeFile("draft_schematic/item/item_jedi_tool.lua") includeFile("draft_schematic/item/item_parrot_cage.lua") includeFile("draft_schematic/item/item_powerup_weapon_melee_generic.lua") includeFile("draft_schematic/item/item_powerup_weapon_melee_lightsaber.lua") includeFile("draft_schematic/item/item_powerup_weapon_mine_explosive.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_five.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_four.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_one.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_six.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_three.lua") includeFile("draft_schematic/item/item_powerup_weapon_ranged_two.lua") includeFile("draft_schematic/item/item_powerup_weapon_thrown_explosive.lua") includeFile("draft_schematic/item/item_powerup_weapon_thrown_wiring.lua") includeFile("draft_schematic/item/item_public_clothing_station.lua") includeFile("draft_schematic/item/item_public_food_station.lua") includeFile("draft_schematic/item/item_public_structure_station.lua") includeFile("draft_schematic/item/item_public_weapon_station.lua") includeFile("draft_schematic/item/item_recycler_chemical.lua") includeFile("draft_schematic/item/item_recycler_creature.lua") includeFile("draft_schematic/item/item_recycler_flora.lua") includeFile("draft_schematic/item/item_recycler_metal.lua") includeFile("draft_schematic/item/item_recycler_ore.lua") includeFile("draft_schematic/item/item_repairkit_armor.lua") includeFile("draft_schematic/item/item_repairkit_clothing.lua") includeFile("draft_schematic/item/item_repairkit_droid.lua") includeFile("draft_schematic/item/item_repairkit_structure.lua") includeFile("draft_schematic/item/item_repairkit_weapon.lua") includeFile("draft_schematic/item/item_shellfish_harvester.lua") includeFile("draft_schematic/item/item_six_sided_dice.lua") includeFile("draft_schematic/item/item_space_station.lua") includeFile("draft_schematic/item/item_space_tool.lua") includeFile("draft_schematic/item/item_structure_station.lua") includeFile("draft_schematic/item/item_structure_tool.lua") includeFile("draft_schematic/item/item_survey_tool_flora.lua") includeFile("draft_schematic/item/item_survey_tool_gas.lua") includeFile("draft_schematic/item/item_survey_tool_liquid.lua") includeFile("draft_schematic/item/item_survey_tool_mineral.lua") includeFile("draft_schematic/item/item_survey_tool_moisture.lua") includeFile("draft_schematic/item/item_survey_tool_solar.lua") includeFile("draft_schematic/item/item_survey_tool_wind.lua") includeFile("draft_schematic/item/item_ten_sided_dice.lua") includeFile("draft_schematic/item/item_tumble_blender.lua") includeFile("draft_schematic/item/item_twelve_sided_dice.lua") includeFile("draft_schematic/item/item_twenty_sided_dice.lua") includeFile("draft_schematic/item/item_weapon_station.lua") includeFile("draft_schematic/item/item_weapon_tool.lua")
[Fixed] Crash on server load
[Fixed] Crash on server load git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@2436 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
99d0442cc9858abd03e24e5ec1c303ef66bc4d65
mods/boats/init.lua
mods/boats/init.lua
-- -- Helper functions -- local function is_water(pos) local nn = minetest.get_node(pos).name return minetest.get_item_group(nn, "water") ~= 0 end local function get_sign(i) if i == 0 then return 0 else return i / math.abs(i) end end local function get_velocity(v, yaw, y) local x = -math.sin(yaw) * v local z = math.cos(yaw) * v return {x = x, y = y, z = z} end local function get_v(v) return math.sqrt(v.x ^ 2 + v.z ^ 2) end -- -- Boat entity -- local boat = { physical = true, collisionbox = {-0.5, -0.4, -0.5, 0.5, 0.3, 0.5}, visual = "mesh", mesh = "boat.obj", textures = {"default_wood.png"}, driver = nil, v = 0, last_v = 0, removed = false } function boat.on_rightclick(self, clicker) if not clicker or not clicker:is_player() then return end local name = clicker:get_player_name() if self.driver and clicker == self.driver then self.driver = nil clicker:set_detach() default.player_attached[name] = false default.player_set_animation(clicker, "stand" , 30) elseif not self.driver then self.driver = clicker clicker:set_attach(self.object, "", {x = 0, y = 11, z = -3}, {x = 0, y = 0, z = 0}) default.player_attached[name] = true minetest.after(0.2, function() default.player_set_animation(clicker, "sit" , 30) end) self.object:setyaw(clicker:get_look_yaw() - math.pi / 2) end end function boat.on_activate(self, staticdata, dtime_s) self.object:set_armor_groups({immortal = 1}) if staticdata then self.v = tonumber(staticdata) end self.last_v = self.v end function boat.get_staticdata(self) return tostring(self.v) end function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction) if not puncher or not puncher:is_player() or self.removed then return end if self.driver and puncher == self.driver then self.driver = nil puncher:set_detach() default.player_attached[puncher:get_player_name()] = false end if not self.driver then self.removed = true -- delay remove to ensure player is detached minetest.after(0.1, function() self.object:remove() end) if not minetest.setting_getbool("creative_mode") then puncher:get_inventory():add_item("main", "boats:boat") end end end function boat.on_step(self, dtime) self.v = get_v(self.object:getvelocity()) * get_sign(self.v) if self.driver then local ctrl = self.driver:get_player_control() local yaw = self.object:getyaw() if ctrl.up then self.v = self.v + 0.1 elseif ctrl.down then self.v = self.v - 0.1 end if ctrl.left then if self.v < 0 then self.object:setyaw(yaw - (1 + dtime) * 0.03) else self.object:setyaw(yaw + (1 + dtime) * 0.03) end elseif ctrl.right then if self.v < 0 then self.object:setyaw(yaw + (1 + dtime) * 0.03) else self.object:setyaw(yaw - (1 + dtime) * 0.03) end end end local velo = self.object:getvelocity() if self.v == 0 and velo.x == 0 and velo.y == 0 and velo.z == 0 then self.object:setpos(self.object:getpos()) return end local s = get_sign(self.v) self.v = self.v - 0.02 * s if s ~= get_sign(self.v) then self.object:setvelocity({x = 0, y = 0, z = 0}) self.v = 0 return end if math.abs(self.v) > 4.5 then self.v = 4.5 * get_sign(self.v) end local p = self.object:getpos() p.y = p.y - 0.5 local new_velo = {x = 0, y = 0, z = 0} local new_acce = {x = 0, y = 0, z = 0} if not is_water(p) then local nodedef = minetest.registered_nodes[minetest.get_node(p).name] if (not nodedef) or nodedef.walkable then self.v = 0 new_acce = {x = 0, y = 1, z = 0} else new_acce = {x = 0, y = -9.8, z = 0} end new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) self.object:setpos(self.object:getpos()) else p.y = p.y + 1 if is_water(p) then local y = self.object:getvelocity().y if y >= 4.5 then y = 4.5 elseif y < 0 then new_acce = {x = 0, y = 20, z = 0} else new_acce = {x = 0, y = 5, z = 0} end new_velo = get_velocity(self.v, self.object:getyaw(), y) self.object:setpos(self.object:getpos()) else new_acce = {x = 0, y = 0, z = 0} if math.abs(self.object:getvelocity().y) < 1 then local pos = self.object:getpos() pos.y = math.floor(pos.y) + 0.5 self.object:setpos(pos) new_velo = get_velocity(self.v, self.object:getyaw(), 0) else new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) self.object:setpos(self.object:getpos()) end end end self.object:setvelocity(new_velo) self.object:setacceleration(new_acce) end minetest.register_entity("boats:boat", boat) minetest.register_craftitem("boats:boat", { description = "Boat", inventory_image = "boat_inventory.png", wield_image = "boat_wield.png", wield_scale = {x = 2, y = 2, z = 1}, liquids_pointable = true, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return end if not is_water(pointed_thing.under) then return end pointed_thing.under.y = pointed_thing.under.y + 0.5 minetest.add_entity(pointed_thing.under, "boats:boat") if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end, }) minetest.register_craft({ output = "boats:boat", recipe = { {"", "", "" }, {"group:wood", "", "group:wood"}, {"group:wood", "group:wood", "group:wood"}, }, })
-- -- Helper functions -- local function is_water(pos) local nn = minetest.get_node(pos).name return minetest.get_item_group(nn, "water") ~= 0 end local function get_sign(i) if i == 0 then return 0 else return i / math.abs(i) end end local function get_velocity(v, yaw, y) local x = -math.sin(yaw) * v local z = math.cos(yaw) * v return {x = x, y = y, z = z} end local function get_v(v) return math.sqrt(v.x ^ 2 + v.z ^ 2) end -- -- Boat entity -- local boat = { physical = true, collisionbox = {-0.5, -0.35, -0.5, 0.5, 0.3, 0.5}, visual = "mesh", mesh = "boat.obj", textures = {"default_wood.png"}, driver = nil, v = 0, last_v = 0, removed = false } function boat.on_rightclick(self, clicker) if not clicker or not clicker:is_player() then return end local name = clicker:get_player_name() if self.driver and clicker == self.driver then self.driver = nil clicker:set_detach() default.player_attached[name] = false default.player_set_animation(clicker, "stand" , 30) local pos = clicker:getpos() pos = {x = pos.x, y = pos.y + 0.2, z = pos.z} minetest.after(0.1, function() clicker:setpos(pos) end) elseif not self.driver then self.driver = clicker clicker:set_attach(self.object, "", {x = 0, y = 11, z = -3}, {x = 0, y = 0, z = 0}) default.player_attached[name] = true minetest.after(0.2, function() default.player_set_animation(clicker, "sit" , 30) end) self.object:setyaw(clicker:get_look_yaw() - math.pi / 2) end end function boat.on_activate(self, staticdata, dtime_s) self.object:set_armor_groups({immortal = 1}) if staticdata then self.v = tonumber(staticdata) end self.last_v = self.v end function boat.get_staticdata(self) return tostring(self.v) end function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction) if not puncher or not puncher:is_player() or self.removed then return end if self.driver and puncher == self.driver then self.driver = nil puncher:set_detach() default.player_attached[puncher:get_player_name()] = false end if not self.driver then self.removed = true -- delay remove to ensure player is detached minetest.after(0.1, function() self.object:remove() end) if not minetest.setting_getbool("creative_mode") then puncher:get_inventory():add_item("main", "boats:boat") end end end function boat.on_step(self, dtime) self.v = get_v(self.object:getvelocity()) * get_sign(self.v) if self.driver then local ctrl = self.driver:get_player_control() local yaw = self.object:getyaw() if ctrl.up then self.v = self.v + 0.1 elseif ctrl.down then self.v = self.v - 0.1 end if ctrl.left then if self.v < 0 then self.object:setyaw(yaw - (1 + dtime) * 0.03) else self.object:setyaw(yaw + (1 + dtime) * 0.03) end elseif ctrl.right then if self.v < 0 then self.object:setyaw(yaw + (1 + dtime) * 0.03) else self.object:setyaw(yaw - (1 + dtime) * 0.03) end end end local velo = self.object:getvelocity() if self.v == 0 and velo.x == 0 and velo.y == 0 and velo.z == 0 then self.object:setpos(self.object:getpos()) return end local s = get_sign(self.v) self.v = self.v - 0.02 * s if s ~= get_sign(self.v) then self.object:setvelocity({x = 0, y = 0, z = 0}) self.v = 0 return end if math.abs(self.v) > 4.5 then self.v = 4.5 * get_sign(self.v) end local p = self.object:getpos() p.y = p.y - 0.5 local new_velo = {x = 0, y = 0, z = 0} local new_acce = {x = 0, y = 0, z = 0} if not is_water(p) then local nodedef = minetest.registered_nodes[minetest.get_node(p).name] if (not nodedef) or nodedef.walkable then self.v = 0 new_acce = {x = 0, y = 1, z = 0} else new_acce = {x = 0, y = -9.8, z = 0} end new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) self.object:setpos(self.object:getpos()) else p.y = p.y + 1 if is_water(p) then local y = self.object:getvelocity().y if y >= 4.5 then y = 4.5 elseif y < 0 then new_acce = {x = 0, y = 20, z = 0} else new_acce = {x = 0, y = 5, z = 0} end new_velo = get_velocity(self.v, self.object:getyaw(), y) self.object:setpos(self.object:getpos()) else new_acce = {x = 0, y = 0, z = 0} if math.abs(self.object:getvelocity().y) < 1 then local pos = self.object:getpos() pos.y = math.floor(pos.y) + 0.5 self.object:setpos(pos) new_velo = get_velocity(self.v, self.object:getyaw(), 0) else new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) self.object:setpos(self.object:getpos()) end end end self.object:setvelocity(new_velo) self.object:setacceleration(new_acce) end minetest.register_entity("boats:boat", boat) minetest.register_craftitem("boats:boat", { description = "Boat", inventory_image = "boat_inventory.png", wield_image = "boat_wield.png", wield_scale = {x = 2, y = 2, z = 1}, liquids_pointable = true, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return end if not is_water(pointed_thing.under) then return end pointed_thing.under.y = pointed_thing.under.y + 0.5 minetest.add_entity(pointed_thing.under, "boats:boat") if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end, }) minetest.register_craft({ output = "boats:boat", recipe = { {"", "", "" }, {"group:wood", "", "group:wood"}, {"group:wood", "group:wood", "group:wood"}, }, })
Boats: Fix sinking through boat when detaching
Boats: Fix sinking through boat when detaching By CProgrammerRU Also, by paramat: Slightly raise base of collision box Improve code style
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
58828a667c49e22c16752e6bd56ce13c3a393641
conky/rings.lua
conky/rings.lua
--[[ Ring Meters by londonali1010 (2009) This script draws percentage meters as rings. It is fully customisable; all options are described in the script. IMPORTANT: if you are using the 'cpu' function, it will cause a segmentation fault if it tries to draw a ring straight away. The if statement on line 145 uses a delay to make sure that this doesn't happen. It calculates the length of the delay by the number of updates since Conky started. Generally, a value of 5s is long enough, so if you update Conky every 1s, use update_num>5 in that if statement (the default). If you only update Conky every 2s, you should change it to update_num>3; conversely if you update Conky every 0.5s, you should use update_num>10. ALSO, if you change your Conky, is it best to use "killall conky; conky" to update it, otherwise the update_num will not be reset and you will get an error. To call this script in Conky, use the following (assuming that you save this script to ~/scripts/rings.lua): lua_load ~/scripts/rings.lua lua_draw_hook_pre ring_stats ]] settings_table = { { -- Edit this table to customise your rings. -- You can create more rings simply by adding more elements to settings_table. -- "name" is the type of stat to display; you can choose from 'cpu', 'memperc', 'fs_used_perc', 'battery_used_perc'. name='time', -- "arg" is the argument to the stat type, e.g. if in Conky you would write ${cpu cpu0}, 'cpu0' would be the argument. If you would not use an argument in the Conky variable, use ''. arg='%I.%M', -- "max" is the maximum value of the ring. If the Conky variable outputs a percentage, use 100. max=12, -- "bg_colour" is the colour of the base ring. bg_colour=0xffffff, -- "bg_alpha" is the alpha value of the base ring. bg_alpha=0.2, -- "fg_colour" is the colour of the indicator part of the ring. fg_colour=0xffffff, -- "fg_alpha" is the alpha value of the indicator part of the ring. fg_alpha=0.4, -- "x" and "y" are the x and y coordinates of the centre of the ring, relative to the top left corner of the Conky window. x=165, y=170, -- "radius" is the radius of the ring. radius=50, -- "thickness" is the thickness of the ring, centred around the radius. thickness=5, -- "start_angle" is the starting angle of the ring, in degrees, clockwise from top. Value can be either positive or negative. start_angle=0, -- "end_angle" is the ending angle of the ring, in degrees, clockwise from top. Value can be either positive or negative, but must be larger (e.g. more clockwise) than start_angle. end_angle=360 }, { name='time', arg='%M.%S', max=60, bg_colour=0xffffff, bg_alpha=0.2, fg_colour=0xffffff, fg_alpha=0.4, x=165, y=170, radius=56, thickness=5, start_angle=0, end_angle=360 }, { name='time', arg='%S', max=60, bg_colour=0xffffff, bg_alpha=0.2, fg_colour=0xffffff, fg_alpha=0.6, x=165, y=170, radius=62, thickness=5, start_angle=0, end_angle=360 }, { name='cpu', arg='cpu1', max=100, bg_colour=0xffffff, bg_alpha=.2, fg_colour=0xffffff, fg_alpha=0.3, x=165, y=170, radius=96, thickness=5, start_angle=-120, end_angle=120 }, { name='cpu', arg='cpu2', max=100, bg_colour=0xffffff, bg_alpha=.2, fg_colour=0xffffff, fg_alpha=0.3, x=165, y=170, radius=91, thickness=5, start_angle=-120, end_angle=120 }, { name='memperc', arg='', max=100, bg_colour=0xffffff, bg_alpha=0.2, fg_colour=0xffffff, fg_alpha=0.3, x=165, y=170, radius=83.5, thickness=8, start_angle=100, end_angle=190 }, { name='cpu', arg='cpu0', max=100, bg_colour=0xffffff, bg_alpha=0.2, fg_colour=0xffffff, fg_alpha=0.5, x=165, y=170, radius=110, thickness=20, start_angle=-120, end_angle=120 }, } require 'cairo' function rgb_to_r_g_b(colour,alpha) return ((colour / 0x10000) % 0x100) / 255., ((colour / 0x100) % 0x100) / 255., (colour % 0x100) / 255., alpha end function draw_ring(cr,t,pt) local w,h=conky_window.width,conky_window.height local xc,yc,ring_r,ring_w,sa,ea=pt['x'],pt['y'],pt['radius'],pt['thickness'],pt['start_angle'],pt['end_angle'] local bgc, bga, fgc, fga=pt['bg_colour'], pt['bg_alpha'], pt['fg_colour'], pt['fg_alpha'] local angle_0=sa*(2*math.pi/360)-math.pi/2 local angle_f=ea*(2*math.pi/360)-math.pi/2 local t_arc=t*(angle_f-angle_0) -- Draw background ring cairo_arc(cr,xc,yc,ring_r,angle_0,angle_f) cairo_set_source_rgba(cr,rgb_to_r_g_b(bgc,bga)) cairo_set_line_width(cr,ring_w) cairo_stroke(cr) -- Draw indicator ring cairo_arc(cr,xc,yc,ring_r,angle_0,angle_0+t_arc) cairo_set_source_rgba(cr,rgb_to_r_g_b(fgc,fga)) cairo_stroke(cr) end function conky_ring_stats() local function setup_rings(cr,pt) local str='' local value=0 str=string.format('${%s %s}',pt['name'],pt['arg']) str=conky_parse(str) value=tonumber(str) pct=value/pt['max'] draw_ring(cr,pct,pt) end if conky_window==nil then return end local cs=cairo_xlib_surface_create(conky_window.display,conky_window.drawable,conky_window.visual, conky_window.width,conky_window.height) local cr=cairo_create(cs) local updates=conky_parse('${updates}') update_num=tonumber(updates) if update_num>3 then for i in pairs(settings_table) do setup_rings(cr,settings_table[i]) end end end
--[[ Ring Meters by londonali1010 (2009) This script draws percentage meters as rings. It is fully customisable; all options are described in the script. IMPORTANT: if you are using the 'cpu' function, it will cause a segmentation fault if it tries to draw a ring straight away. The if statement on line 145 uses a delay to make sure that this doesn't happen. It calculates the length of the delay by the number of updates since Conky started. Generally, a value of 5s is long enough, so if you update Conky every 1s, use update_num>5 in that if statement (the default). If you only update Conky every 2s, you should change it to update_num>3; conversely if you update Conky every 0.5s, you should use update_num>10. ALSO, if you change your Conky, is it best to use "killall conky; conky" to update it, otherwise the update_num will not be reset and you will get an error. To call this script in Conky, use the following (assuming that you save this script to ~/scripts/rings.lua): lua_load ~/scripts/rings.lua lua_draw_hook_pre ring_stats ]] settings_table = { { -- Edit this table to customise your rings. -- You can create more rings simply by adding more elements to settings_table. -- "name" is the type of stat to display; you can choose from 'cpu', 'memperc', 'fs_used_perc', 'battery_used_perc'. name='time', -- "arg" is the argument to the stat type, e.g. if in Conky you would write ${cpu cpu0}, 'cpu0' would be the argument. If you would not use an argument in the Conky variable, use ''. arg='%I.%M', -- "max" is the maximum value of the ring. If the Conky variable outputs a percentage, use 100. max=12, -- "bg_colour" is the colour of the base ring. bg_colour=0xffffff, -- "bg_alpha" is the alpha value of the base ring. bg_alpha=0.2, -- "fg_colour" is the colour of the indicator part of the ring. fg_colour=0xffffff, -- "fg_alpha" is the alpha value of the indicator part of the ring. fg_alpha=0.4, -- "x" and "y" are the x and y coordinates of the centre of the ring, relative to the top left corner of the Conky window. x=165, y=170, -- "radius" is the radius of the ring. radius=50, -- "thickness" is the thickness of the ring, centred around the radius. thickness=5, -- "start_angle" is the starting angle of the ring, in degrees, clockwise from top. Value can be either positive or negative. start_angle=0, -- "end_angle" is the ending angle of the ring, in degrees, clockwise from top. Value can be either positive or negative, but must be larger (e.g. more clockwise) than start_angle. end_angle=360 }, { name='time', arg='%M.%S', max=60, bg_colour=0xffffff, bg_alpha=0.2, fg_colour=0xffffff, fg_alpha=0.4, x=165, y=170, radius=56, thickness=5, start_angle=0, end_angle=360 }, { name='time', arg='%S', max=60, bg_colour=0xffffff, bg_alpha=0.2, fg_colour=0xffffff, fg_alpha=0.6, x=165, y=170, radius=62, thickness=5, start_angle=0, end_angle=360 }, { name='cpu', arg='cpu1', max=100, bg_colour=0xffffff, bg_alpha=.2, fg_colour=0xffffff, fg_alpha=0.3, x=165, y=170, radius=96, thickness=5, start_angle=-120, end_angle=120 }, { name='cpu', arg='cpu2', max=100, bg_colour=0xffffff, bg_alpha=.2, fg_colour=0xffffff, fg_alpha=0.3, x=165, y=170, radius=91, thickness=5, start_angle=-120, end_angle=120 }, { name='memperc', arg='', max=100, bg_colour=0xffffff, bg_alpha=0.2, fg_colour=0xffffff, fg_alpha=0.3, x=165, y=170, radius=83.5, thickness=8, start_angle=100, end_angle=190 }, { name='cpu', arg='cpu0', max=100, bg_colour=0xffffff, bg_alpha=0.2, fg_colour=0xffffff, fg_alpha=0.5, x=165, y=170, radius=110, thickness=20, start_angle=-120, end_angle=120 }, } require 'cairo' function rgb_to_r_g_b(colour,alpha) return ((colour / 0x10000) % 0x100) / 255., ((colour / 0x100) % 0x100) / 255., (colour % 0x100) / 255., alpha end function draw_ring(cr,t,pt) local w,h=conky_window.width,conky_window.height local xc,yc,ring_r,ring_w,sa,ea=pt['x'],pt['y'],pt['radius'],pt['thickness'],pt['start_angle'],pt['end_angle'] local bgc, bga, fgc, fga=pt['bg_colour'], pt['bg_alpha'], pt['fg_colour'], pt['fg_alpha'] local angle_0=sa*(2*math.pi/360)-math.pi/2 local angle_f=ea*(2*math.pi/360)-math.pi/2 local t_arc=t*(angle_f-angle_0) -- Draw background ring cairo_arc(cr,xc,yc,ring_r,angle_0,angle_f) cairo_set_source_rgba(cr,rgb_to_r_g_b(bgc,bga)) cairo_set_line_width(cr,ring_w) cairo_stroke(cr) -- Draw indicator ring cairo_arc(cr,xc,yc,ring_r,angle_0,angle_0+t_arc) cairo_set_source_rgba(cr,rgb_to_r_g_b(fgc,fga)) cairo_stroke(cr) end function conky_ring_stats() local function setup_rings(cr,pt) local str='' local value=0 str=string.format('${%s %s}',pt['name'],pt['arg']) str=conky_parse(str) value=tonumber(str) if not value then value=0 end pct=value/pt['max'] draw_ring(cr,pct,pt) end if conky_window==nil then return end local cs=cairo_xlib_surface_create(conky_window.display,conky_window.drawable,conky_window.visual, conky_window.width,conky_window.height) local cr=cairo_create(cs) local updates=conky_parse('${updates}') update_num=tonumber(updates) if update_num>3 then for i in pairs(settings_table) do setup_rings(cr,settings_table[i]) end end end
conky: fix error in rings.lua
conky: fix error in rings.lua conky_ring_stats execution failed: attempt to call a nil value
Lua
mit
iiey/dotfiles
adadf988b6672fc0cb3671f990611871e627bc05
src/apps/intel/intel_app.lua
src/apps/intel/intel_app.lua
module(...,package.seeall) local basic_apps = require("apps.basic.basic_apps") local lib = require("core.lib") local register = require("lib.hardware.register") local intel10g = require("apps.intel.intel10g") Intel82599 = {} Intel82599.__index = Intel82599 -- table pciaddr => {pf, vflist} local devices = {} local function firsthole(t) for i = 1, #t+1 do if t[i] == nil then return i end end end -- Create an Intel82599 App for the device with 'pciaddress'. function Intel82599:new (args) args = config.parse_app_arg(args) if args.vmdq then if devices[args.pciaddr] == nil then devices[args.pciaddr] = {pf=intel10g.new_pf(args.pciaddr):open(), vflist={}} end local dev = devices[args.pciaddr] local poolnum = firsthole(dev.vflist)-1 local vf = dev.pf:new_vf(poolnum) dev.vflist[poolnum+1] = vf return setmetatable({dev=vf:open(args)}, Intel82599) else local dev = intel10g.new_sf(args.pciaddr) :open() :autonegotiate_sfi() :wait_linkup() return setmetatable({dev=dev}, Intel82599) end end function Intel82599:stop() local close_pf = nil if self.dev.pf and devices[self.dev.pf.pciaddress] then local poolnum = self.dev.poolnum local pciaddress = self.dev.pf.pciaddress local dev = devices[pciaddress] if dev.vflist[poolnum+1] == self.dev then dev.vflist[poolnum+1] = nil end if next(dev.vflist) == nil then close_pf = devices[pciaddress].pf devices[pciaddress] = nil end end self.dev:close() if close_pf then close_pf:close() end end -- Allocate receive buffers from the given freelist. function Intel82599:set_rx_buffer_freelist (fl) self.rx_buffer_freelist = fl end -- Pull in packets from the network and queue them on our 'tx' link. function Intel82599:pull () local l = self.output.tx if l == nil then return end self.dev:sync_receive() while not link.full(l) and self.dev:can_receive() do link.transmit(l, self.dev:receive()) end self:add_receive_buffers() end function Intel82599:add_receive_buffers () if self.rx_buffer_freelist == nil then -- Generic buffers while self.dev:can_add_receive_buffer() do self.dev:add_receive_buffer(buffer.allocate()) end else -- Buffers from a special freelist local fl = self.rx_buffer_freelist while self.dev:can_add_receive_buffer() and freelist.nfree(fl) > 0 do self.dev:add_receive_buffer(freelist.remove(fl)) end end end -- Push packets from our 'rx' link onto the network. function Intel82599:push () local l = self.input.rx if l == nil then return end while not link.empty(l) and self.dev:can_transmit() do local p = link.receive(l) self.dev:transmit(p) packet.deref(p) end self.dev:sync_transmit() end -- Report on relevant status and statistics. function Intel82599:report () print("report on intel device", self.dev.pciaddress or self.dev.pf.pciaddress) --register.dump(self.dev.r) register.dump(self.dev.s, true) if self.dev.rxstats then for name,v in pairs(self.dev:get_rxstats()) do io.write(string.format('%30s: %d\n', 'rx '..name, v)) end end if self.dev.txstats then for name,v in pairs(self.dev:get_txstats()) do io.write(string.format('%30s: %d\n', 'tx '..name, v)) end end register.dump({ self.dev.r.TDH, self.dev.r.TDT, self.dev.r.RDH, self.dev.r.RDT, self.dev.r.AUTOC or self.dev.pf.r.AUTOC, self.dev.r.AUTOC2 or self.dev.pf.r.AUTOC2, self.dev.r.LINKS or self.dev.pf.r.LINKS, self.dev.r.LINKS2 or self.dev.pf.r.LINKS2, }) end function selftest () print("selftest: intel_app") local pcideva = os.getenv("SNABB_TEST_INTEL10G_PCIDEVA") local pcidevb = os.getenv("SNABB_TEST_INTEL10G_PCIDEVB") if not pcideva or not pcidevb then print("SNABB_TEST_INTEL10G_[PCIDEVA | PCIDEVB] was not set\nTest skipped") os.exit(engine.test_skipped_code) end buffer.preallocate(100000) sq_sq(pcideva, pcidevb) engine.main({duration = 1, report={showlinks=true, showapps=false}}) mq_sq(pcideva, pcidevb) engine.main({duration = 1, report={showlinks=true, showapps=false}}) end -- open two singlequeue drivers on both ends of the wire function sq_sq(pcidevA, pcidevB) local c = config.new() config.app(c, 'source1', basic_apps.Source) config.app(c, 'source2', basic_apps.Source) config.app(c, 'nicA', Intel82599, ([[{pciaddr='%s'}]]):format(pcidevA)) config.app(c, 'nicB', Intel82599, ([[{pciaddr='%s'}]]):format(pcidevB)) config.app(c, 'sink', basic_apps.Sink) config.link(c, 'source1.out -> nicA.rx') config.link(c, 'source2.out -> nicB.rx') config.link(c, 'nicA.tx -> sink.in1') config.link(c, 'nicB.tx -> sink.in2') engine.configure(c) end -- one singlequeue driver and a multiqueue at the other end function mq_sq(pcidevA, pcidevB) d1 = lib.hexundump ([[ 52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00 00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8 01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00 00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 ]], 98) -- src: As dst: Bm0 d2 = lib.hexundump ([[ 52:54:00:03:03:03 52:54:00:01:01:01 08 00 45 00 00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8 01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00 00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 ]], 98) -- src: As dst: Bm1 local c = config.new() config.app(c, 'source_ms', basic_apps.Join) config.app(c, 'repeater_ms', basic_apps.Repeater) config.app(c, 'nicAs', Intel82599, ([[{ -- Single App on NIC A pciaddr = '%s', macaddr = '52:54:00:01:01:01', }]]):format(pcidevA)) config.app(c, 'nicBm0', Intel82599, ([[{ -- first VF on NIC B pciaddr = '%s', vmdq = true, macaddr = '52:54:00:02:02:02', }]]):format(pcidevB)) config.app(c, 'nicBm1', Intel82599, ([[{ -- second VF on NIC B pciaddr = '%s', vmdq = true, macaddr = '52:54:00:03:03:03', }]]):format(pcidevB)) print ("Send a bunch of from the SF on NIC A to the VFs on NIC B") print ("half of them go to nicBm0 and nicBm0") config.app(c, 'sink_ms', basic_apps.Sink) config.link(c, 'source_ms.out -> repeater_ms.input') config.link(c, 'repeater_ms.output -> nicAs.rx') config.link(c, 'nicAs.tx -> sink_ms.in1') config.link(c, 'nicBm0.tx -> sink_ms.in2') config.link(c, 'nicBm1.tx -> sink_ms.in3') engine.configure(c) link.transmit(engine.app_table.source_ms.output.out, packet.from_data(d1)) link.transmit(engine.app_table.source_ms.output.out, packet.from_data(d2)) end
module(...,package.seeall) local basic_apps = require("apps.basic.basic_apps") local lib = require("core.lib") local register = require("lib.hardware.register") local intel10g = require("apps.intel.intel10g") local freelist = require("core.freelist") Intel82599 = {} Intel82599.__index = Intel82599 -- table pciaddr => {pf, vflist} local devices = {} local function firsthole(t) for i = 1, #t+1 do if t[i] == nil then return i end end end -- Create an Intel82599 App for the device with 'pciaddress'. function Intel82599:new (args) args = config.parse_app_arg(args) if args.vmdq then if devices[args.pciaddr] == nil then devices[args.pciaddr] = {pf=intel10g.new_pf(args.pciaddr):open(), vflist={}} end local dev = devices[args.pciaddr] local poolnum = firsthole(dev.vflist)-1 local vf = dev.pf:new_vf(poolnum) dev.vflist[poolnum+1] = vf return setmetatable({dev=vf:open(args)}, Intel82599) else local dev = intel10g.new_sf(args.pciaddr) :open() :autonegotiate_sfi() :wait_linkup() return setmetatable({dev=dev}, Intel82599) end end function Intel82599:stop() local close_pf = nil if self.dev.pf and devices[self.dev.pf.pciaddress] then local poolnum = self.dev.poolnum local pciaddress = self.dev.pf.pciaddress local dev = devices[pciaddress] if dev.vflist[poolnum+1] == self.dev then dev.vflist[poolnum+1] = nil end if next(dev.vflist) == nil then close_pf = devices[pciaddress].pf devices[pciaddress] = nil end end self.dev:close() if close_pf then close_pf:close() end end -- Allocate receive buffers from the given freelist. function Intel82599:set_rx_buffer_freelist (fl) self.rx_buffer_freelist = fl end -- Pull in packets from the network and queue them on our 'tx' link. function Intel82599:pull () local l = self.output.tx if l == nil then return end self.dev:sync_receive() while not link.full(l) and self.dev:can_receive() do link.transmit(l, self.dev:receive()) end self:add_receive_buffers() end function Intel82599:add_receive_buffers () if self.rx_buffer_freelist == nil then -- Generic buffers while self.dev:can_add_receive_buffer() do self.dev:add_receive_buffer(buffer.allocate()) end else -- Buffers from a special freelist local fl = self.rx_buffer_freelist while self.dev:can_add_receive_buffer() and freelist.nfree(fl) > 0 do self.dev:add_receive_buffer(freelist.remove(fl)) end end end -- Push packets from our 'rx' link onto the network. function Intel82599:push () local l = self.input.rx if l == nil then return end while not link.empty(l) and self.dev:can_transmit() do local p = link.receive(l) self.dev:transmit(p) packet.deref(p) end self.dev:sync_transmit() end -- Report on relevant status and statistics. function Intel82599:report () print("report on intel device", self.dev.pciaddress or self.dev.pf.pciaddress) --register.dump(self.dev.r) register.dump(self.dev.s, true) if self.dev.rxstats then for name,v in pairs(self.dev:get_rxstats()) do io.write(string.format('%30s: %d\n', 'rx '..name, v)) end end if self.dev.txstats then for name,v in pairs(self.dev:get_txstats()) do io.write(string.format('%30s: %d\n', 'tx '..name, v)) end end register.dump({ self.dev.r.TDH, self.dev.r.TDT, self.dev.r.RDH, self.dev.r.RDT, self.dev.r.AUTOC or self.dev.pf.r.AUTOC, self.dev.r.AUTOC2 or self.dev.pf.r.AUTOC2, self.dev.r.LINKS or self.dev.pf.r.LINKS, self.dev.r.LINKS2 or self.dev.pf.r.LINKS2, }) end function selftest () print("selftest: intel_app") local pcideva = os.getenv("SNABB_TEST_INTEL10G_PCIDEVA") local pcidevb = os.getenv("SNABB_TEST_INTEL10G_PCIDEVB") if not pcideva or not pcidevb then print("SNABB_TEST_INTEL10G_[PCIDEVA | PCIDEVB] was not set\nTest skipped") os.exit(engine.test_skipped_code) end buffer.preallocate(100000) sq_sq(pcideva, pcidevb) engine.main({duration = 1, report={showlinks=true, showapps=false}}) mq_sq(pcideva, pcidevb) engine.main({duration = 1, report={showlinks=true, showapps=false}}) end -- open two singlequeue drivers on both ends of the wire function sq_sq(pcidevA, pcidevB) local c = config.new() config.app(c, 'source1', basic_apps.Source) config.app(c, 'source2', basic_apps.Source) config.app(c, 'nicA', Intel82599, ([[{pciaddr='%s'}]]):format(pcidevA)) config.app(c, 'nicB', Intel82599, ([[{pciaddr='%s'}]]):format(pcidevB)) config.app(c, 'sink', basic_apps.Sink) config.link(c, 'source1.out -> nicA.rx') config.link(c, 'source2.out -> nicB.rx') config.link(c, 'nicA.tx -> sink.in1') config.link(c, 'nicB.tx -> sink.in2') engine.configure(c) end -- one singlequeue driver and a multiqueue at the other end function mq_sq(pcidevA, pcidevB) d1 = lib.hexundump ([[ 52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00 00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8 01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00 00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 ]], 98) -- src: As dst: Bm0 d2 = lib.hexundump ([[ 52:54:00:03:03:03 52:54:00:01:01:01 08 00 45 00 00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8 01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00 00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 ]], 98) -- src: As dst: Bm1 local c = config.new() config.app(c, 'source_ms', basic_apps.Join) config.app(c, 'repeater_ms', basic_apps.Repeater) config.app(c, 'nicAs', Intel82599, ([[{ -- Single App on NIC A pciaddr = '%s', macaddr = '52:54:00:01:01:01', }]]):format(pcidevA)) config.app(c, 'nicBm0', Intel82599, ([[{ -- first VF on NIC B pciaddr = '%s', vmdq = true, macaddr = '52:54:00:02:02:02', }]]):format(pcidevB)) config.app(c, 'nicBm1', Intel82599, ([[{ -- second VF on NIC B pciaddr = '%s', vmdq = true, macaddr = '52:54:00:03:03:03', }]]):format(pcidevB)) print ("Send a bunch of from the SF on NIC A to the VFs on NIC B") print ("half of them go to nicBm0 and nicBm0") config.app(c, 'sink_ms', basic_apps.Sink) config.link(c, 'source_ms.out -> repeater_ms.input') config.link(c, 'repeater_ms.output -> nicAs.rx') config.link(c, 'nicAs.tx -> sink_ms.in1') config.link(c, 'nicBm0.tx -> sink_ms.in2') config.link(c, 'nicBm1.tx -> sink_ms.in3') engine.configure(c) link.transmit(engine.app_table.source_ms.output.out, packet.from_data(d1)) link.transmit(engine.app_table.source_ms.output.out, packet.from_data(d2)) end
[intel_app] fix missing freelist
[intel_app] fix missing freelist Signed-off-by: Nikolay Nikolaev <[email protected]>
Lua
apache-2.0
SnabbCo/snabbswitch,wingo/snabbswitch,mixflowtech/logsensor,pirate/snabbswitch,plajjan/snabbswitch,hb9cwp/snabbswitch,virtualopensystems/snabbswitch,Igalia/snabbswitch,heryii/snabb,lukego/snabbswitch,andywingo/snabbswitch,snabbco/snabb,kbara/snabb,justincormack/snabbswitch,mixflowtech/logsensor,snabbnfv-goodies/snabbswitch,snabbco/snabb,pavel-odintsov/snabbswitch,xdel/snabbswitch,wingo/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,snabbnfv-goodies/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,xdel/snabbswitch,wingo/snabbswitch,aperezdc/snabbswitch,javierguerragiraldez/snabbswitch,lukego/snabb,dpino/snabbswitch,snabbco/snabb,lukego/snabb,lukego/snabbswitch,justincormack/snabbswitch,dpino/snabbswitch,eugeneia/snabb,wingo/snabb,dpino/snabb,mixflowtech/logsensor,SnabbCo/snabbswitch,snabbnfv-goodies/snabbswitch,mixflowtech/logsensor,mixflowtech/logsensor,Igalia/snabb,fhanik/snabbswitch,dpino/snabb,Igalia/snabb,kbara/snabb,wingo/snabb,Igalia/snabb,wingo/snabbswitch,justincormack/snabbswitch,Igalia/snabbswitch,andywingo/snabbswitch,dwdm/snabbswitch,wingo/snabb,eugeneia/snabb,snabbco/snabb,pavel-odintsov/snabbswitch,eugeneia/snabb,snabbco/snabb,plajjan/snabbswitch,heryii/snabb,alexandergall/snabbswitch,virtualopensystems/snabbswitch,heryii/snabb,lukego/snabbswitch,fhanik/snabbswitch,lukego/snabb,plajjan/snabbswitch,pavel-odintsov/snabbswitch,dpino/snabb,lukego/snabbswitch,kellabyte/snabbswitch,javierguerragiraldez/snabbswitch,Igalia/snabbswitch,kbara/snabb,alexandergall/snabbswitch,virtualopensystems/snabbswitch,dpino/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,dwdm/snabbswitch,dpino/snabb,wingo/snabb,eugeneia/snabb,xdel/snabbswitch,Igalia/snabb,kellabyte/snabbswitch,Igalia/snabb,plajjan/snabbswitch,heryii/snabb,pirate/snabbswitch,aperezdc/snabbswitch,andywingo/snabbswitch,eugeneia/snabbswitch,dpino/snabb,kbara/snabb,dpino/snabb,aperezdc/snabbswitch,javierguerragiraldez/snabbswitch,kellabyte/snabbswitch,snabbco/snabb,hb9cwp/snabbswitch,kbara/snabb,snabbco/snabb,eugeneia/snabb,hb9cwp/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,justincormack/snabbswitch,hb9cwp/snabbswitch,dwdm/snabbswitch,wingo/snabbswitch,kbara/snabb,Igalia/snabb,pirate/snabbswitch,fhanik/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,lukego/snabb,eugeneia/snabb,heryii/snabb,snabbnfv-goodies/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,heryii/snabb,alexandergall/snabbswitch,dpino/snabbswitch,andywingo/snabbswitch,aperezdc/snabbswitch,dpino/snabb,wingo/snabb,Igalia/snabbswitch
d032e268a178844599628871bf384ae349f306b6
core/configmanager.lua
core/configmanager.lua
-- Prosody IM v0.3 -- 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 _G = _G; local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile = setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile; module "configmanager" local parsers = {}; local config = { ["*"] = { core = {} } }; local global_config = config["*"]; -- When host not found, use global setmetatable(config, { __index = function () return global_config; end}); local host_mt = { __index = global_config }; -- When key not found in section, check key in global's section function section_mt(section_name) return { __index = function (t, k) local section = rawget(global_config, section_name); if not section then return nil; end return section[k]; end }; end function getconfig() return config; end function get(host, section, key) local sec = config[host][section]; if sec then return sec[key]; end return nil; end function set(host, section, key, value) if host and section and key then local hostconfig = rawget(config, host); if not hostconfig then hostconfig = rawset(config, host, setmetatable({}, host_mt))[host]; end if not rawget(hostconfig, section) then hostconfig[section] = setmetatable({}, section_mt(section)); end hostconfig[section][key] = value; return true; end return false; end function load(filename, format) format = format or filename:match("%w+$"); if parsers[format] and parsers[format].load then local f, err = io.open(filename); if f then local ok, err = parsers[format].load(f:read("*a")); f:close(); return ok, "parser", err; end return f, "file", err; end if not format then return nil, "file", "no parser specified"; else return nil, "file", "no parser for "..(format); end end function save(filename, format) end function addparser(format, parser) if format and parser then parsers[format] = parser; end end -- Built-in Lua parser do local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable; local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring; parsers.lua = {}; function parsers.lua.load(data) local env; -- The ' = true' are needed so as not to set off __newindex when we assign the functions below env = setmetatable({ Host = true; host = true; Component = true, component = true, Include = true, include = true, RunScript = dofile }, { __index = function (t, k) return rawget(_G, k) or function (settings_table) config[__currenthost or "*"][k] = settings_table; end; end, __newindex = function (t, k, v) set(env.__currenthost or "*", "core", k, v); end}); function env.Host(name) rawset(env, "__currenthost", name); -- Needs at least one setting to logically exist :) set(name or "*", "core", "defined", true); end env.host = env.Host; function env.Component(name) return function (module) set(name, "core", "component_module", module); -- Don't load the global modules by default set(name, "core", "modules_enable", false); rawset(env, "__currenthost", name); end end env.component = env.Component; function env.Include(file) local f, err = io.open(file); if f then local data = f:read("*a"); local ok, err = parsers.lua.load(data); if not ok then error(err:gsub("%[string.-%]", file), 0); end end if not f then error("Error loading included "..file..": "..err, 0); end return f, err; end env.include = env.Include; local chunk, err = loadstring(data); if not chunk then return nil, err; end setfenv(chunk, env); local ok, err = pcall(chunk); if not ok then return nil, err; end return true; end end return _M;
-- Prosody IM v0.3 -- 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 _G = _G; local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type = setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type; module "configmanager" local parsers = {}; local config = { ["*"] = { core = {} } }; local global_config = config["*"]; -- When host not found, use global setmetatable(config, { __index = function () return global_config; end}); local host_mt = { __index = global_config }; -- When key not found in section, check key in global's section function section_mt(section_name) return { __index = function (t, k) local section = rawget(global_config, section_name); if not section then return nil; end return section[k]; end }; end function getconfig() return config; end function get(host, section, key) local sec = config[host][section]; if sec then return sec[key]; end return nil; end function set(host, section, key, value) if host and section and key then local hostconfig = rawget(config, host); if not hostconfig then hostconfig = rawset(config, host, setmetatable({}, host_mt))[host]; end if not rawget(hostconfig, section) then hostconfig[section] = setmetatable({}, section_mt(section)); end hostconfig[section][key] = value; return true; end return false; end function load(filename, format) format = format or filename:match("%w+$"); if parsers[format] and parsers[format].load then local f, err = io.open(filename); if f then local ok, err = parsers[format].load(f:read("*a")); f:close(); return ok, "parser", err; end return f, "file", err; end if not format then return nil, "file", "no parser specified"; else return nil, "file", "no parser for "..(format); end end function save(filename, format) end function addparser(format, parser) if format and parser then parsers[format] = parser; end end -- Built-in Lua parser do local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable; local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring; parsers.lua = {}; function parsers.lua.load(data) local env; -- The ' = true' are needed so as not to set off __newindex when we assign the functions below env = setmetatable({ Host = true; host = true; Component = true, component = true, Include = true, include = true, RunScript = dofile }, { __index = function (t, k) return rawget(_G, k) or function (settings_table) config[__currenthost or "*"][k] = settings_table; end; end, __newindex = function (t, k, v) set(env.__currenthost or "*", "core", k, v); end}); function env.Host(name) rawset(env, "__currenthost", name); -- Needs at least one setting to logically exist :) set(name or "*", "core", "defined", true); end env.host = env.Host; function env.Component(name) return function (module) if type(module) == "string" then set(name, "core", "component_module", module); -- Don't load the global modules by default set(name, "core", "modules_enable", false); rawset(env, "__currenthost", name); end end end env.component = env.Component; function env.Include(file) local f, err = io.open(file); if f then local data = f:read("*a"); local ok, err = parsers.lua.load(data); if not ok then error(err:gsub("%[string.-%]", file), 0); end end if not f then error("Error loading included "..file..": "..err, 0); end return f, err; end env.include = env.Include; local chunk, err = loadstring(data); if not chunk then return nil, err; end setfenv(chunk, env); local ok, err = pcall(chunk); if not ok then return nil, err; end return true; end end return _M;
core.configmanager: Small fix to check validity of Component definitions
core.configmanager: Small fix to check validity of Component definitions
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
700d3ae5e58543236606d7da6944b0d582eff98d
spec/03-custom-serve_spec.lua
spec/03-custom-serve_spec.lua
local helpers = require "spec.helpers" describe("Plugin: prometheus (custom server)",function() local proxy_client describe("with custom nginx server block", function() setup(function() local bp = helpers.get_db_utils() local service = bp.services:insert { name = "mock-service", host = helpers.mock_upstream_host, port = helpers.mock_upstream_port, protocol = helpers.mock_upstream_protocol, } bp.routes:insert { protocols = { "http" }, paths = { "/" }, service = service, } bp.plugins:insert { name = "prometheus" } assert(helpers.start_kong({ nginx_conf = "spec/fixtures/prometheus/valid_nginx.template", plugins = "bundled, prometheus", })) proxy_client = helpers.proxy_client() end) teardown(function() if proxy_client then proxy_client:close() end helpers.stop_kong() end) it("metrics can be read from a different port", function() local res = assert(proxy_client:send { method = "GET", path = "/status/200", headers = { host = helpers.mock_upstream_host, } }) assert.res_status(200, res) local client = helpers.http_client("127.0.0.1", 9542) local res = assert(client:send { method = "GET", path = "/metrics", }) local body = assert.res_status(200, res) assert.matches('kong_http_status{code="200",service="mock-service"} 1', body, nil, true) end) end) end)
local helpers = require "spec.helpers" describe("Plugin: prometheus (custom server)",function() local proxy_client describe("with custom nginx server block", function() setup(function() local bp = helpers.get_db_utils() local service = bp.services:insert { name = "mock-service", host = helpers.mock_upstream_host, port = helpers.mock_upstream_port, protocol = helpers.mock_upstream_protocol, } bp.routes:insert { protocols = { "http" }, paths = { "/" }, service = service, } bp.plugins:insert { name = "prometheus" } assert(helpers.start_kong({ nginx_conf = "spec/fixtures/prometheus/valid_nginx.template", plugins = "bundled, prometheus", })) proxy_client = helpers.proxy_client() end) teardown(function() if proxy_client then proxy_client:close() end helpers.stop_kong() end) it("metrics can be read from a different port", function() local res = assert(proxy_client:send { method = "GET", path = "/status/200", headers = { host = helpers.mock_upstream_host, } }) assert.res_status(200, res) local client = helpers.http_client("127.0.0.1", 9542) local res = assert(client:send { method = "GET", path = "/metrics", }) local body = assert.res_status(200, res) assert.matches('kong_http_status{code="200",service="mock-service"} 1', body, nil, true) end) end) end)
chore(prometheus) fix mixed tabs/spaces
chore(prometheus) fix mixed tabs/spaces
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
890e8c17a266ebf27c6d5a10c3c9310f149f0172
src/plugins/lua/emails.lua
src/plugins/lua/emails.lua
-- Emails is module for different checks for emails inside messages -- Rules format: -- symbol = sym, map = file:///path/to/file, domain_only = yes -- symbol = sym2, dnsbl = bl.somehost.com, domain_only = no local rules = {} function split(str, delim, maxNb) -- Eliminate bad cases... if string.find(str, delim) == nil then return { str } end if maxNb == nil or maxNb < 1 then maxNb = 0 -- No limit end local result = {} local pat = "(.-)" .. delim .. "()" local nb = 0 local lastPos for part, pos in string.gmatch(str, pat) do nb = nb + 1 result[nb] = part lastPos = pos if nb == maxNb then break end end -- Handle the last field if nb ~= maxNb then result[nb + 1] = string.sub(str, lastPos) end return result end function emails_dns_cb(task, to_resolve, results, err, symbol) if results then rspamd_logger.info(string.format('<%s> email: [%s] resolved for symbol: %s', task:get_message():get_message_id(), to_resolve, symbol)) task:insert_result(symbol, 1) end end -- Check rule for a single email function check_email_rule(task, rule, addr) if rule['dnsbl'] then local to_resolve = '' if rule['domain_only'] then to_resolve = string.format('%s.%s', addr:get_host(), rule['dnsbl']) else to_resolve = string.format('%s.%s.%s', addr:get_user(), addr:get_host(), rule['dnsbl']) end task:resolve_dns_a(to_resolve, 'emails_dns_cb', rule['symbol']) elseif rule['map'] then if rule['domain_only'] then local key = addr:get_host() if rule['map']:get_key(key) then task:insert_result(rule['symbol'], 1) rspamd_logger.info(string.format('<%s> email: \'%s\' is found in list: %s', task:get_message():get_message_id(), key, rule['symbol'])) end else local key = string.format('%s@%s', addr:get_user(), addr:get_host()) if rule['map']:get_key(key) then task:insert_result(rule['symbol'], 1) rspamd_logger.info(string.format('<%s> email: \'%s\' is found in list: %s', task:get_message():get_message_id(), key, rule['symbol'])) end end end end -- Check email function check_emails(task) local emails = task:get_emails() local checked = {} if emails then for _,addr in ipairs(emails) do local to_check = string.format('%s@%s', addr:get_user(), addr:get_host()) if not checked['to_check'] then for _,rule in ipairs(rules) do check_email_rule(task, rule, addr) end checked[to_check] = true end end end end -- Add rule to ruleset local function add_emails_rule(params) local newrule = { name = nil, dnsbl = nil, map = nil, domain_only = false, symbol = nil } for _,param in ipairs(params) do local _,_,name,value = string.find(param, '([a-zA-Z_0-9]+)%s*=%s*(.+)') if not name or not value then rspamd_logger.err('invalid rule: '..param) return nil end if name == 'dnsbl' then newrule['dnsbl'] = value newrule['name'] = value elseif name == 'map' then newrule['name'] = value newrule['map'] = rspamd_config:add_hash_map (newrule['name']) elseif name == 'symbol' then newrule['symbol'] = value elseif name == 'domain_only' then if value == 'yes' or value == 'true' or value == '1' then newrule['domain_only'] = true end else rspamd_logger.err('invalid rule option: '.. name) return nil end end if not newrule['symbol'] or (not newrule['map'] and not newrule['dnsbl']) then rspamd_logger.err('incomplete rule') return nil end table.insert(rules, newrule) return newrule end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 2 then rspamd_config:register_module_option('emails', 'rule', 'string') else rspamd_logger.err('Invalid rspamd version for this plugin') end end local opts = rspamd_config:get_all_opt('emails') if opts then local strrules = opts['rule'] if strrules then if type(strrules) == 'table' then for _,value in ipairs(strrules) do local params = split(value, ',') local rule = add_emails_rule (params) if not rule then rspamd_logger.err('cannot add rule: "'..value..'"') else if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_virtual_symbol(rule['symbol'], 1.0) end end end elseif type(strrules) == 'string' then local params = split(strrules, ',') local rule = add_emails_rule (params) if not rule then rspamd_logger.err('cannot add rule: "'..strrules..'"') else if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_virtual_symbol(rule['symbol'], 1.0) end end end end end if table.maxn(rules) > 0 then -- add fake symbol to check all maps inside a single callback if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_callback_symbol('EMAILS', 1.0, 'check_emails') else rspamd_config:register_symbol('EMAILS', 1.0, 'check_emails') end end
-- Emails is module for different checks for emails inside messages -- Rules format: -- symbol = sym, map = file:///path/to/file, domain_only = yes -- symbol = sym2, dnsbl = bl.somehost.com, domain_only = no local rules = {} function split(str, delim, maxNb) -- Eliminate bad cases... if string.find(str, delim) == nil then return { str } end if maxNb == nil or maxNb < 1 then maxNb = 0 -- No limit end local result = {} local pat = "(.-)" .. delim .. "()" local nb = 0 local lastPos for part, pos in string.gmatch(str, pat) do nb = nb + 1 result[nb] = part lastPos = pos if nb == maxNb then break end end -- Handle the last field if nb ~= maxNb then result[nb + 1] = string.sub(str, lastPos) end return result end function emails_dns_cb(task, to_resolve, results, err, symbol) if results then rspamd_logger.info(string.format('<%s> email: [%s] resolved for symbol: %s', task:get_message():get_message_id(), to_resolve, symbol)) task:insert_result(symbol, 1) end end -- Check rule for a single email function check_email_rule(task, rule, addr) if rule['dnsbl'] then local to_resolve = '' if rule['domain_only'] then to_resolve = string.format('%s.%s', addr:get_host(), rule['dnsbl']) else to_resolve = string.format('%s.%s.%s', addr:get_user(), addr:get_host(), rule['dnsbl']) end task:resolve_dns_a(to_resolve, 'emails_dns_cb', rule['symbol']) elseif rule['map'] then if rule['domain_only'] then local key = addr:get_host() if rule['map']:get_key(key) then task:insert_result(rule['symbol'], 1) rspamd_logger.info(string.format('<%s> email: \'%s\' is found in list: %s', task:get_message():get_message_id(), key, rule['symbol'])) end else local key = string.format('%s@%s', addr:get_user(), addr:get_host()) if rule['map']:get_key(key) then task:insert_result(rule['symbol'], 1) rspamd_logger.info(string.format('<%s> email: \'%s\' is found in list: %s', task:get_message():get_message_id(), key, rule['symbol'])) end end end end -- Check email function check_emails(task) local emails = task:get_emails() local checked = {} if emails then for _,addr in ipairs(emails) do local to_check = string.format('%s@%s', addr:get_user(), addr:get_host()) if not checked['to_check'] then for _,rule in ipairs(rules) do check_email_rule(task, rule, addr) end checked[to_check] = true end end end end -- Add rule to ruleset local function add_emails_rule(key, obj) local newrule = { name = nil, dnsbl = nil, map = nil, domain_only = false, symbol = k } for name,value in pairs(obj) do if name == 'dnsbl' then newrule['dnsbl'] = value newrule['name'] = value elseif name == 'map' then newrule['name'] = value newrule['map'] = rspamd_config:add_hash_map (newrule['name']) elseif name == 'symbol' then newrule['symbol'] = value elseif name == 'domain_only' then if value == 'yes' or value == 'true' or value == '1' then newrule['domain_only'] = true end else rspamd_logger.err('invalid rule option: '.. name) return nil end end if not newrule['symbol'] or (not newrule['map'] and not newrule['dnsbl']) then rspamd_logger.err('incomplete rule') return nil end table.insert(rules, newrule) return newrule end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 2 then rspamd_config:register_module_option('emails', 'rule', 'string') else rspamd_logger.err('Invalid rspamd version for this plugin') end end local opts = rspamd_config:get_all_opt('emails') if opts then for k,m in pairs(opts) do if type(m) ~= 'table' then rspamd_logger.err('parameter ' .. k .. ' is invalid, must be an object') else local rule = add_emails_rule(k, m) if not rule then rspamd_logger.err('cannot add rule: "'..k..'"') else if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_virtual_symbol(m['symbol'], 1.0) end end end end end if table.maxn(rules) > 0 then -- add fake symbol to check all maps inside a single callback if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_callback_symbol('EMAILS', 1.0, 'check_emails') else rspamd_config:register_symbol('EMAILS', 1.0, 'check_emails') end end
Fix emailbl plugin.
Fix emailbl plugin.
Lua
bsd-2-clause
amohanta/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,awhitesong/rspamd,andrejzverev/rspamd,dark-al/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,dark-al/rspamd,dark-al/rspamd,AlexeySa/rspamd,amohanta/rspamd,minaevmike/rspamd,awhitesong/rspamd,dark-al/rspamd,minaevmike/rspamd,dark-al/rspamd,amohanta/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,amohanta/rspamd,minaevmike/rspamd,minaevmike/rspamd,awhitesong/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,amohanta/rspamd,awhitesong/rspamd
4ce31717cc0b2180c47f27d09b5c9c2b38c3b8fc
samples/gtkbuilder.lua
samples/gtkbuilder.lua
#! /usr/bin/env lua -- Note: demo.ui loaded by this example is copied verbatim from gtk3-demo, and -- is probably covered by its appropriate license. -- Import lgi and get Gtk package. local lgi = require 'lgi' local Gtk = lgi.Gtk -- There are two ways to access Gtk.Builder; using standard Gtk API's -- get_object() and get_objects(), or LGI override shortcuts. Both -- can be used, as demonstrated below. local window if gtk_builder_use_standard_api then -- Instantiate Gtk.Builder and load resources from ui file. local builder = Gtk.Builder() assert(builder:add_from_file('samples/demo.ui')) -- Get top-level window from the builder. window = builder:get_object('window1') -- Connect 'Quit' and 'About' actions. builder:get_object('Quit').on_activate = function(action) window:destroy() end builder:get_object('About').on_activate = function(action) local about_dlg = builder:get_object('aboutdialog1') about_dlg:run() about_dlg:hide() end else -- Instantiate builder and load objects. local builder = Gtk.Builder() assert(builder:add_from_file('samples/demo.ui')) local ui = builder.objects -- Get top-level window from the builder. window = ui.window1 -- Connect 'Quit' and 'About' actions. function ui.Quit:on_activate() window:destroy() end function ui.About:on_activate() ui.aboutdialog1:run() ui.aboutdialog1:hide() end end -- Connect 'destroy' signal of the main window, terminates the main loop. window.on_destroy = Gtk.main_quit -- Make sure that main window is visible. window:show_all() -- Start the loop. Gtk.main()
#! /usr/bin/env lua -- Note: demo.ui loaded by this example is copied verbatim from gtk3-demo, and -- is probably covered by its appropriate license. -- Import lgi and get Gtk package. local lgi = require 'lgi' local Gtk = lgi.Gtk -- There are two ways to access Gtk.Builder; using standard Gtk API's -- get_object() and get_objects(), or LGI override shortcuts. Both -- can be used, as demonstrated below. local window if gtk_builder_use_standard_api then -- Instantiate Gtk.Builder and load resources from ui file. local builder = Gtk.Builder() assert(builder:add_from_file('demo.ui') or builder:add_from_file('samples/demo.ui')) -- Get top-level window from the builder. window = builder:get_object('window1') -- Connect 'Quit' and 'About' actions. builder:get_object('Quit').on_activate = function(action) window:destroy() end builder:get_object('About').on_activate = function(action) local about_dlg = builder:get_object('aboutdialog1') about_dlg:run() about_dlg:hide() end else -- Instantiate builder and load objects. local builder = Gtk.Builder() assert(builder:add_from_file('demo.ui') or builder:add_from_file('samples/demo.ui')) local ui = builder.objects -- Get top-level window from the builder. window = ui.window1 -- Connect 'Quit' and 'About' actions. function ui.Quit:on_activate() window:destroy() end function ui.About:on_activate() ui.aboutdialog1:run() ui.aboutdialog1:hide() end end -- Connect 'destroy' signal of the main window, terminates the main loop. window.on_destroy = Gtk.main_quit -- Make sure that main window is visible. window:show_all() -- Start the loop. Gtk.main()
Fix gtkbuilder sample to run both from lgi root or from samples folder
Fix gtkbuilder sample to run both from lgi root or from samples folder
Lua
mit
psychon/lgi,zevv/lgi,pavouk/lgi
bb4df886b8e95d28a17fb3c8e3aaa6041d5b8e1c
init.lua
init.lua
local JSON = require('json') local timer = require('timer') local http = require('http') local https = require('https') local boundary = require('boundary') local io = require('io') local _url = require('_url') require('_strings') local __pgk = "BOUNDARY NGINX" local _previous = {} local url = "http://127.0.0.1/nginx_status" local pollInterval = 1000 local strictSSL = true local source, username, password if (boundary.param ~= nil) then pollInterval = boundary.param.pollInterval or pollInterval url = boundary.param.url or url username = boundary.param.username password = boundary.param.password strictSSL = boundary.param.strictSSL == true source = (type(boundary.param.source) == 'string' and boundary.param.source:gsub('%s+', '') ~= '' and boundary.param.source) or io.popen("uname -n"):read('*line') end function berror(err) if err then process.stderr:write(string.format("%s ERROR: %s", __pgk, tostring(err))) return err end end --- do a http(s) request local doreq = function(url, cb) local u = _url.parse(url) u.protocol = u.scheme -- reject self signed certs u.rejectUnauthorized = strictSSL if username and password then u.headers = {Authorization = "Basic " .. (string.base64(username..":"..password))} end local output = "" local onSuccess = function(res) res:on("error", function(err) cb("Error while receiving a response: " .. tostring(err), nil) end) res:on("data", function (chunk) output = output .. chunk end) res:on("end", function() if res.statusCode == 401 then return cb("Authentication required, provide user and password", nil) end res:destroy() cb(nil, output) end) end local req = (u.scheme == "https") and https.request(u, onSuccess) or http.request(u, onSuccess) req:on("error", function(err) cb("Error while sending a request: " .. tostring(err), nil) end) req:done() end function split(str, delim) local res = {} local pattern = string.format("([^%s]+)%s()", delim, delim) while (true) do line, pos = str:match(pattern, pos) if line == nil then break end table.insert(res, line) end return res end function parse(str) return tonumber(str) end function diff(a, b) if a == nil or b == nil then return 0 end return math.max(a - b, 0) end function parseStatsText(body) --[[ See http://nginx.org/en/docs/http/ngx_http_stub_status_module.html for body format. Sample response: Active connections: 1 server accepts handled requests 112 112 121 Reading: 0 Writing: 1 Waiting: 0 --]] local stats = {} for i, v in ipairs(split(body, "\n")) do if v:find("Active connections:", 1, true) then local active, connections = v:gmatch('(%w+):%s*(%d+)')() stats[active:lower()] = parse(connections) elseif v:match("%s*(%d+)%s+(%d+)%s+(%d+)%s*$") then accepts, handled, requests = v:gmatch("%s*(%d+)%s+(%d+)%s+(%d+)%s*$")() stats.accepts = parse(accepts) stats.handled = parse(handled) stats.requests = parse(requests) stats.nothandled = stats.accepts - stats.handled elseif v:match("(%w+):%s*(%d+)") then while true do k, va = v:gmatch("(%w+):%s*(%d+)")() if not k then break end stats[k:lower()] = parse(va) v = v:gsub(k, "") end end end return stats end -- accumulate a value and return the difference from the previous value function accumulate(key, newValue) local oldValue = _previous[key] or newValue local difference = diff(newValue, oldValue) _previous[key] = newValue return difference end -- get the natural difference between a and b function diff(a, b) if not a or not b then return 0 end return math.max(a - b, 0) end function parseStatsJson(body) j = nil pcall(function () j = json.parse(body) end) return j end function printEnterpriseStats(stats) local handled = stats['connections']['accepted'] - stats['connections']['dropped'] local requests = stats['requests']['total'] local requestsPerConnection = (requests > 0 and handled) and requests / handled or 0 print(string.format('NGINX_ACTIVE_CONNECTIONS %d %s', stats['connections']['active'] + stats['connections']['idle'], source)) print(string.format('NGINX_WAITING %d %s', stats['connections']['idle'], source)) print(string.format('NGINX_HANDLED %d %s', accumulate('NGINX_HANDLED', handled), source)) print(string.format('NGINX_NOT_HANDLED %d %s', stats['connections']['dropped'], source)) print(string.format('NGINX_REQUESTS %d %s', accumulate('NGINX_REQUESTS', requests), source)) print(string.format('NGINX_REQUESTS_PER_CONNECTION %d %s', requestsPerConnection, source)) -- enterprise customers have 'per zone' statistics for i, zone_name in ipairs(stats.server_zones) do local zone = stats.server_zones[zone_name] local src = source .. zone_name print(string.format('NGINX_REQUESTS %d %s', accumulate('NGINX_REQUESTS_' .. zone_name, zone['requests']), src)) print(string.format('NGINX_RESPONSES %d %s', accumulate('NGINX_RESPONSES_' .. zone_name, zone['responses']['total']), src)) print(string.format('NGINX_TRAFFIC_SENT %d %s', accumulate('NGINX_TRAFFIC_SENT_' .. zone_name, zone['sent']), src)) print(string.format('NGINX_TRAFFIC_RECEIVED %d %s', accumulate('NGINX_TRAFFIC_RECEIVED_' .. zone_name, zone['received']), src)) end end function printStats(stats) local handled = _previous['handled'] and diff(stats.handled, _previous.handled) or 0 local requests = _previous['requests'] and diff(stats.requests, _previous.requests) or 0 local requestsPerConnection = (requests > 0 and handled) and requests / handled or 0 _previous = stats print(string.format('NGINX_ACTIVE_CONNECTIONS %d %s', stats.connections, source)) print(string.format('NGINX_READING %d %s', stats.reading, source)) print(string.format('NGINX_WRITING %d %s', stats.writing, source)) print(string.format('NGINX_WAITING %d %s', stats.waiting, source)) print(string.format('NGINX_HANDLED %d %s', handled, source)) print(string.format('NGINX_NOT_HANDLED %d %s', stats.nothandled, source)) print(string.format('NGINX_REQUESTS %d %s', requests, source)) print(string.format('NGINX_REQUESTS_PER_CONNECTION %d %s', requestsPerConnection, source)) end print("_bevent:NGINX plugin up : version 1.0|t:info|tags:nginx,lua, plugin") timer.setInterval(pollInterval, function () doreq(url, function(err, body) if berror(err) then return end local stats = parseStatsJson(body) if stats then printEnterpriseStats(stats) else stats = parseStatsText(body) printStats(stats) end end) end)
local JSON = require('json') local timer = require('timer') local http = require('http') local https = require('https') local boundary = require('boundary') local io = require('io') local _url = require('_url') local String = require('_strings') local __pgk = "BOUNDARY NGINX" local __ver = "Version 1.0" local _previous = {} local url = "http://127.0.0.1/nginx_status" local pollInterval = 1000 local strictSSL = true local source, username, password if (boundary.param ~= nil) then pollInterval = boundary.param.pollInterval or pollInterval url = boundary.param.url or url username = boundary.param.username password = boundary.param.password strictSSL = boundary.param.strictSSL == true source = (type(boundary.param.source) == 'string' and boundary.param.source:gsub('%s+', '') ~= '' and boundary.param.source) or io.popen("uname -n"):read('*line') end function berror(err) if err then process.stderr:write(string.format("%s ERROR: %s", __pgk, tostring(err))) return err end end --- do a http(s) request local doreq = function(url, cb) local u = _url.parse(url) u.protocol = u.scheme -- reject self signed certs u.rejectUnauthorized = strictSSL if username and password then u.headers = {Authorization = "Basic " .. (string.base64(username..":"..password))} end local output = "" local onSuccess = function(res) res:on("error", function(err) cb("Error while receiving a response: " .. tostring(err), nil) end) res:on("data", function (chunk) output = output .. chunk end) res:on("end", function() if res.statusCode == 401 then return cb("Authentication required, provide user and password", nil) end res:destroy() cb(nil, output) end) end local req = (u.scheme == "https") and https.request(u, onSuccess) or http.request(u, onSuccess) req:on("error", function(err) cb("Error while sending a request: " .. tostring(err), nil) end) req:done() end function split(str, delim) local res = {} local pattern = string.format("([^%s]+)%s()", delim, delim) while (true) do line, pos = str:match(pattern, pos) if line == nil then break end table.insert(res, line) end return res end function parse(str) return tonumber(str) end function diff(a, b) if a == nil or b == nil then return 0 end return math.max(a - b, 0) end function parseStatsText(body) --[[ See http://nginx.org/en/docs/http/ngx_http_stub_status_module.html for body format. Sample response: Active connections: 1 server accepts handled requests 112 112 121 Reading: 0 Writing: 1 Waiting: 0 --]] local stats = {} for i, v in ipairs(split(body, "\n")) do if v:find("Active connections:", 1, true) then local active, connections = v:gmatch('(%w+):%s*(%d+)')() stats[active:lower()] = parse(connections) elseif v:match("%s*(%d+)%s+(%d+)%s+(%d+)%s*$") then accepts, handled, requests = v:gmatch("%s*(%d+)%s+(%d+)%s+(%d+)%s*$")() stats.accepts = parse(accepts) stats.handled = parse(handled) stats.requests = parse(requests) stats.nothandled = stats.accepts - stats.handled elseif v:match("(%w+):%s*(%d+)") then while true do k, va = v:gmatch("(%w+):%s*(%d+)")() if not k then break end stats[k:lower()] = parse(va) v = v:gsub(k, "") end end end return stats end -- accumulate a value and return the difference from the previous value function accumulate(key, newValue) local oldValue = _previous[key] or newValue local difference = diff(newValue, oldValue) _previous[key] = newValue return difference end -- get the natural difference between a and b function diff(a, b) if not a or not b then return 0 end return math.max(a - b, 0) end function parseStatsJson(body) j = nil pcall(function () j = json.parse(body) end) return j end function printEnterpriseStats(stats) local handled = stats['connections']['accepted'] - stats['connections']['dropped'] local requests = stats['requests']['total'] local requestsPerConnection = (requests > 0 and handled) and requests / handled or 0 print(string.format('NGINX_ACTIVE_CONNECTIONS %d %s', stats['connections']['active'] + stats['connections']['idle'], source)) print(string.format('NGINX_WAITING %d %s', stats['connections']['idle'], source)) print(string.format('NGINX_HANDLED %d %s', accumulate('NGINX_HANDLED', handled), source)) print(string.format('NGINX_NOT_HANDLED %d %s', stats['connections']['dropped'], source)) print(string.format('NGINX_REQUESTS %d %s', accumulate('NGINX_REQUESTS', requests), source)) print(string.format('NGINX_REQUESTS_PER_CONNECTION %d %s', requestsPerConnection, source)) -- enterprise customers have 'per zone' statistics for i, zone_name in ipairs(stats.server_zones) do local zone = stats.server_zones[zone_name] local src = source .. zone_name print(string.format('NGINX_REQUESTS %d %s', accumulate('NGINX_REQUESTS_' .. zone_name, zone['requests']), src)) print(string.format('NGINX_RESPONSES %d %s', accumulate('NGINX_RESPONSES_' .. zone_name, zone['responses']['total']), src)) print(string.format('NGINX_TRAFFIC_SENT %d %s', accumulate('NGINX_TRAFFIC_SENT_' .. zone_name, zone['sent']), src)) print(string.format('NGINX_TRAFFIC_RECEIVED %d %s', accumulate('NGINX_TRAFFIC_RECEIVED_' .. zone_name, zone['received']), src)) end end function printStats(stats) local handled = _previous['handled'] and diff(stats.handled, _previous.handled) or 0 local requests = _previous['requests'] and diff(stats.requests, _previous.requests) or 0 local requestsPerConnection = (requests > 0 and handled) and requests / handled or 0 _previous = stats print(string.format('NGINX_ACTIVE_CONNECTIONS %d %s', stats.connections, source)) print(string.format('NGINX_READING %d %s', stats.reading, source)) print(string.format('NGINX_WRITING %d %s', stats.writing, source)) print(string.format('NGINX_WAITING %d %s', stats.waiting, source)) print(string.format('NGINX_HANDLED %d %s', handled, source)) print(string.format('NGINX_NOT_HANDLED %d %s', stats.nothandled, source)) print(string.format('NGINX_REQUESTS %d %s', requests, source)) print(string.format('NGINX_REQUESTS_PER_CONNECTION %d %s', requestsPerConnection, source)) end print(string.format("_bevent:%s : %s UP|t:info|tags:apache, plugin", __pgk, __ver)) timer.setInterval(pollInterval, function () doreq(url, function(err, body) if berror(err) then return end local stats = parseStatsJson(body) if stats then printEnterpriseStats(stats) else stats = parseStatsText(body) printStats(stats) end end) end)
Fixed base64 problem
Fixed base64 problem
Lua
apache-2.0
jdgwartney/boundary-plugin-nginx,boundary/boundary-plugin-nginx,graphdat/plugin-nginx,BigHNF/plugin-nginx,GabrielNicolasAvellaneda/boundary-plugin-nginx
fd752ffeec0c0d400a25765ece12233d44396858
rbm-grads.lua
rbm-grads.lua
grads = {} ProFi = require('ProFi') -- Calculate generative weights -- tcwx is tcwx = torch.mm( x,rbm.W:t() ):add( rbm.c:t() ) function grads.generative(rbm,x,y,tcwx,chx,chy) local visx_rnd, visy_rnd, h0, h0_rnd,ch_idx,drop, vkx, vkx_rnd, vky_rnd,hk h0 = sigm( torch.add(tcwx, torch.mm(y,rbm.U:t() ) ) ) -- UP if rbm.dropout > 0 then drop = 1 h0:cmul(rbm.dropout_mask) -- Apply dropout on p(h|v) end -- Switch between CD and PCD if rbm.traintype == 0 then -- CD -- Use training data as start for negative statistics h0_rnd = sampler(h0,rbm.rand) -- use training data as start else -- use pcd chains as start for negative statistics ch_idx = math.floor( (torch.rand(1) * rbm.npcdchains)[1]) +1 h0_rnd = sampler( rbmup(rbm, chx[ch_idx]:resize(1,x:size(2)), chy[ch_idx]:resize(1,y:size(2)), drop), rbm.rand) end -- If CDn > 1 update chians n-1 times for i = 1, (rbm.cdn - 1) do visx_rnd = sampler( rbmdownx( rbm, h0_rnd ), rbm.rand) visy_rnd = samplevec( rbmdowny( rbm, h0_rnd), rbm.rand) hid_rnd = sampler( rbmup(rbm,visx_rnd, visy_rnd, drop), rbm.rand) end -- Down-Up dont sample hiddens, because it introduces noise vkx = rbmdownx(rbm,h0_rnd) vkx_rnd = sampler(vkx,rbm.rand) vky_rnd = samplevec( rbmdowny(rbm,h0_rnd), rbm.rand) hk = rbmup(rbm,vkx_rnd,vky_rnd,drop) -- If PCD: Update status of selected PCD chains if rbm.traintype == 1 then chx[{ ch_idx,{} }] = vkx_rnd chy[{ ch_idx,{} }] = vky_rnd end -- Calculate generative gradients local dW = torch.mm(h0:t(),x) :add(-torch.mm(hk:t(),vkx_rnd)) local dU = torch.mm(h0:t(),y):add(-torch.mm(hk:t(),vky_rnd)) local db = torch.add(x, -vkx_rnd):t() local dc = torch.add(h0, -hk ):t() local dd = torch.add(y, -vky_rnd):t() return dW, dU, db, dc ,dd, vkx end -- Calculate discriminative weights -- tcwx is tcwx = torch.mm( x,rbm.W:t() ):add( rbm.c:t() ) function grads.discriminative(rbm,x,y,tcwx) local p_y_given_x, F, mask_expanded,F_sigm, F_sigm_prob,F_sigm_prob_sum,F_sigm_dy local dW,dU,dc,dd -- Switch between dropout version and non dropout version of pygivenx if rbm.dropout > 0 then p_y_given_x, F,mask_expanded = grads.pygivenxdropout(rbm,x,tcwx) else p_y_given_x, F = grads.pygivenx(rbm,x,tcwx) end F_sigm = sigm(F) -- Apply dropout mask if rbm.dropout > 0 then F_sigm:cmul(mask_expanded) end F_sigm_prob = torch.cmul( F_sigm, torch.mm( rbm.hidden_by_one,p_y_given_x ) ) F_sigm_prob_sum = F_sigm_prob:sum(2) F_sigm_dy = torch.mm(F_sigm, y:t()) dW = torch.add( torch.mm(F_sigm_dy, x), -torch.mm(F_sigm_prob_sum,x) ) dU = torch.add( -F_sigm_prob, torch.cmul(F_sigm, torch.mm( torch.ones(F_sigm_prob:size(1),1),y ) ) ) dc = torch.add(-F_sigm_prob_sum, F_sigm_dy) dd = torch.add(y, -p_y_given_x):t() return dW, dU, dc, dd,p_y_given_x end function grads.pygivenx(rbm,x,tcwx_pre_calc) local tcwx,F,pyx tcwx_pre_calc = tcwx_pre_calc or torch.mm( x,rbm.W:t() ):add( rbm.c:t() ) F = torch.add( rbm.U, torch.mm(tcwx_pre_calc:t(), rbm.one_by_classes) ) pyx = softplus(F):sum(1) -- p(y|x) logprob pyx:add(-torch.max(pyx)) -- divide by max, log domain pyx:exp() -- convert to real domain pyx:mul( ( 1/pyx:sum() )) -- normalize probabilities return pyx,F end function grads.pygivenxdropout(rbm,x,tcwx_pre_calc) -- Dropout version of pygivenx local tcwx,F,pyx, mask_expanded mask_expanded = torch.mm(rbm.dropout_mask:t(), rbm.one_by_classes) tcwx_pre_calc = tcwx_pre_calc or torch.mm( x,rbm.W:t() ):add( rbm.c:t() ) F = torch.add( rbm.U, torch.mm(tcwx_pre_calc:t(), rbm.one_by_classes) ) F:cmul(mask_expanded) -- Apply dropout mask F_softplus = softplus(F) F_softplus:cmul(mask_expanded) -- Apply dropout mask pyx = F_softplus:sum(1) -- p(y|x) logprob pyx:add(-torch.max(pyx)) -- divide by max, log domain pyx:exp() -- convert to real domain pyx:mul( ( 1/pyx:sum() )) -- normalize probabilities return pyx,F,mask_expanded end function grads.calculategrads(rbm,x_tr,y_tr,x_semi) local dW_gen, dU_gen, db_gen, dc_gen, dd_gen, vkx, tcwx local dW_dis, dU_dis, dc_dis, dd_dis, p_y_given_x local dW_semi, dU_semi,db_semi, dc_semi, dd_semi, y_semi -- reset accumulators rbm.dW:fill(0) rbm.dU:fill(0) rbm.db:fill(0) rbm.dc:fill(0) rbm.dd:fill(0) tcwx = torch.mm( x_tr,rbm.W:t() ):add( rbm.c:t() ) -- precalc tcwx -- GENERATIVE GRADS if rbm.alpha > 0 then dW_gen, dU_gen, db_gen, dc_gen, dd_gen, vkx = grads.generative(rbm,x_tr,y_tr,tcwx,rbm.chx,rbm.chy) rbm.dW:add( dW_gen:mul( rbm.alpha )) rbm.dU:add( dU_gen:mul( rbm.alpha )) rbm.db:add( db_gen:mul( rbm.alpha )) rbm.dc:add( dc_gen:mul( rbm.alpha )) rbm.dd:add( dd_gen:mul( rbm.alpha )) rbm.cur_err:add( torch.sum(torch.add(x_tr,-vkx):pow(2)) ) end -- DISCRIMINATIVE GRADS if rbm.alpha < 1 then dW_dis, dU_dis, dc_dis, dd_dis, p_y_given_x = grads.discriminative(rbm,x_tr,y_tr,tcwx) rbm.dW:add( dW_dis:mul( 1-rbm.alpha )) rbm.dU:add( dU_dis:mul( 1-rbm.alpha )) rbm.dc:add( dc_dis:mul( 1-rbm.alpha )) rbm.dd:add( dd_dis:mul( 1-rbm.alpha )) end -- SEMISUPERVISED GRADS if rbm.beta > 0 then grads.p_y_given_x = p_y_given_x or grads.pygivenx(rbm,x_tr,tcwx) y_semi = samplevec(p_y_given_x,rbm.rand):resize(1,rbm.n_classes) dW_semi, dU_semi,db_semi, dc_semi, dd_semi = grads.generative(rbm,x_semi,y_semi,tcwx,rbm.chx_semisup,rbm.chy_semisup) rbm.dW:add( dW_semi:mul( rbm.beta )) rbm.dU:add( dU_semi:mul( rbm.beta )) rbm.db:add( db_semi:mul( rbm.beta )) rbm.dc:add( dc_semi:mul( rbm.beta )) rbm.dd:add( dd_semi:mul( rbm.beta )) end end
grads = {} ProFi = require('ProFi') -- Calculate generative weights -- tcwx is tcwx = torch.mm( x,rbm.W:t() ):add( rbm.c:t() ) function grads.generative(rbm,x,y,tcwx,chx,chy) local visx_rnd, visy_rnd, h0, h0_rnd,ch_idx,drop, vkx, vkx_rnd, vky_rnd,hk h0 = sigm( torch.add(tcwx, torch.mm(y,rbm.U:t() ) ) ) -- UP if rbm.dropout > 0 then drop = 1 end -- Switch between CD and PCD if rbm.traintype == 0 then -- CD -- Use training data as start for negative statistics h0_rnd = sampler(h0,rbm.rand) -- use training data as start else -- use pcd chains as start for negative statistics ch_idx = math.floor( (torch.rand(1) * rbm.npcdchains)[1]) +1 h0_rnd = sampler( rbmup(rbm, chx[ch_idx]:resize(1,x:size(2)), chy[ch_idx]:resize(1,y:size(2)), drop), rbm.rand) end if rbm.dropout > 0 then h0_rnd:cmul(rbm.dropout_mask) -- Apply dropout on p(h|v) end -- If CDn > 1 update chians n-1 times for i = 1, (rbm.cdn - 1) do visx_rnd = sampler( rbmdownx( rbm, h0_rnd ), rbm.rand) visy_rnd = samplevec( rbmdowny( rbm, h0_rnd), rbm.rand) hid_rnd = sampler( rbmup(rbm,visx_rnd, visy_rnd, drop), rbm.rand) end -- Down-Up dont sample hiddens, because it introduces noise vkx = rbmdownx(rbm,h0_rnd) vkx_rnd = sampler(vkx,rbm.rand) vky_rnd = samplevec( rbmdowny(rbm,h0_rnd), rbm.rand) hk = rbmup(rbm,vkx_rnd,vky_rnd,drop) -- If PCD: Update status of selected PCD chains if rbm.traintype == 1 then chx[{ ch_idx,{} }] = vkx_rnd chy[{ ch_idx,{} }] = vky_rnd end -- Calculate generative gradients local dW = torch.mm(h0:t(),x) :add(-torch.mm(hk:t(),vkx_rnd)) local dU = torch.mm(h0:t(),y):add(-torch.mm(hk:t(),vky_rnd)) local db = torch.add(x, -vkx_rnd):t() local dc = torch.add(h0, -hk ):t() local dd = torch.add(y, -vky_rnd):t() return dW, dU, db, dc ,dd, vkx end -- Calculate discriminative weights -- tcwx is tcwx = torch.mm( x,rbm.W:t() ):add( rbm.c:t() ) function grads.discriminative(rbm,x,y,tcwx) local p_y_given_x, F, mask_expanded,F_sigm, F_sigm_prob,F_sigm_prob_sum,F_sigm_dy local dW,dU,dc,dd -- Switch between dropout version and non dropout version of pygivenx if rbm.dropout > 0 then p_y_given_x, F,mask_expanded = grads.pygivenxdropout(rbm,x,tcwx) else p_y_given_x, F = grads.pygivenx(rbm,x,tcwx) end F_sigm = sigm(F) -- Apply dropout mask if rbm.dropout > 0 then F_sigm:cmul(mask_expanded) end F_sigm_prob = torch.cmul( F_sigm, torch.mm( rbm.hidden_by_one,p_y_given_x ) ) F_sigm_prob_sum = F_sigm_prob:sum(2) F_sigm_dy = torch.mm(F_sigm, y:t()) dW = torch.add( torch.mm(F_sigm_dy, x), -torch.mm(F_sigm_prob_sum,x) ) dU = torch.add( -F_sigm_prob, torch.cmul(F_sigm, torch.mm( torch.ones(F_sigm_prob:size(1),1),y ) ) ) dc = torch.add(-F_sigm_prob_sum, F_sigm_dy) dd = torch.add(y, -p_y_given_x):t() return dW, dU, dc, dd,p_y_given_x end function grads.pygivenx(rbm,x,tcwx_pre_calc) local tcwx,F,pyx tcwx_pre_calc = tcwx_pre_calc or torch.mm( x,rbm.W:t() ):add( rbm.c:t() ) F = torch.add( rbm.U, torch.mm(tcwx_pre_calc:t(), rbm.one_by_classes) ) pyx = softplus(F):sum(1) -- p(y|x) logprob pyx:add(-torch.max(pyx)) -- divide by max, log domain pyx:exp() -- convert to real domain pyx:mul( ( 1/pyx:sum() )) -- normalize probabilities return pyx,F end function grads.pygivenxdropout(rbm,x,tcwx_pre_calc) -- Dropout version of pygivenx local tcwx,F,pyx, mask_expanded mask_expanded = torch.mm(rbm.dropout_mask:t(), rbm.one_by_classes) tcwx_pre_calc = tcwx_pre_calc or torch.mm( x,rbm.W:t() ):add( rbm.c:t() ) F = torch.add( rbm.U, torch.mm(tcwx_pre_calc:t(), rbm.one_by_classes) ) F:cmul(mask_expanded) -- Apply dropout mask F_softplus = softplus(F) F_softplus:cmul(mask_expanded) -- Apply dropout mask pyx = F_softplus:sum(1) -- p(y|x) logprob pyx:add(-torch.max(pyx)) -- divide by max, log domain pyx:exp() -- convert to real domain pyx:mul( ( 1/pyx:sum() )) -- normalize probabilities return pyx,F,mask_expanded end function grads.calculategrads(rbm,x_tr,y_tr,x_semi) local dW_gen, dU_gen, db_gen, dc_gen, dd_gen, vkx, tcwx local dW_dis, dU_dis, dc_dis, dd_dis, p_y_given_x local dW_semi, dU_semi,db_semi, dc_semi, dd_semi, y_semi -- reset accumulators rbm.dW:fill(0) rbm.dU:fill(0) rbm.db:fill(0) rbm.dc:fill(0) rbm.dd:fill(0) tcwx = torch.mm( x_tr,rbm.W:t() ):add( rbm.c:t() ) -- precalc tcwx -- GENERATIVE GRADS if rbm.alpha > 0 then dW_gen, dU_gen, db_gen, dc_gen, dd_gen, vkx = grads.generative(rbm,x_tr,y_tr,tcwx,rbm.chx,rbm.chy) rbm.dW:add( dW_gen:mul( rbm.alpha )) rbm.dU:add( dU_gen:mul( rbm.alpha )) rbm.db:add( db_gen:mul( rbm.alpha )) rbm.dc:add( dc_gen:mul( rbm.alpha )) rbm.dd:add( dd_gen:mul( rbm.alpha )) rbm.cur_err:add( torch.sum(torch.add(x_tr,-vkx):pow(2)) ) end -- DISCRIMINATIVE GRADS if rbm.alpha < 1 then dW_dis, dU_dis, dc_dis, dd_dis, p_y_given_x = grads.discriminative(rbm,x_tr,y_tr,tcwx) rbm.dW:add( dW_dis:mul( 1-rbm.alpha )) rbm.dU:add( dU_dis:mul( 1-rbm.alpha )) rbm.dc:add( dc_dis:mul( 1-rbm.alpha )) rbm.dd:add( dd_dis:mul( 1-rbm.alpha )) end -- SEMISUPERVISED GRADS if rbm.beta > 0 then grads.p_y_given_x = p_y_given_x or grads.pygivenx(rbm,x_tr,tcwx) y_semi = samplevec(p_y_given_x,rbm.rand):resize(1,rbm.n_classes) dW_semi, dU_semi,db_semi, dc_semi, dd_semi = grads.generative(rbm,x_semi,y_semi,tcwx,rbm.chx_semisup,rbm.chy_semisup) rbm.dW:add( dW_semi:mul( rbm.beta )) rbm.dU:add( dU_semi:mul( rbm.beta )) rbm.db:add( db_semi:mul( rbm.beta )) rbm.dc:add( dc_semi:mul( rbm.beta )) rbm.dd:add( dd_semi:mul( rbm.beta )) end end
fix generative dropout
fix generative dropout
Lua
bsd-3-clause
skaae/rbm_toolbox_lua,elezar/rbm_toolbox_lua
5f70d9f4f43a8275a6e960b7cff6f8c140b332ac
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") m = Map("system", translate("system"), translate("a_s_desc")) s = m:section(TypedSection, "system", "") s.anonymous = true local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:option(DummyValue, "_system", translate("system")).value = system s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() s:option(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:option(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") s:option(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end s:option(Value, "log_size", nil, "kiB").optional = true s:option(Value, "log_ip").optional = true s:option(Value, "conloglevel").optional = true s:option(Value, "cronloglevel").optional = true return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") m = Map("system", translate("system"), translate("a_s_desc")) s = m:section(TypedSection, "system", "") s.anonymous = true local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:option(DummyValue, "_system", translate("system")).value = system s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() s:option(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:option(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("mem_cached", "")), 100 * membuffers / memtotal, tostring(translate("mem_buffered", "")), 100 * memfree / memtotal, tostring(translate("mem_free", "")) s:option(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end s:option(Value, "log_size", nil, "kiB").optional = true s:option(Value, "log_ip").optional = true s:option(Value, "conloglevel").optional = true s:option(Value, "cronloglevel").optional = true return m
modules/admin-full: fix udata vs. string in system.lua model
modules/admin-full: fix udata vs. string in system.lua model
Lua
apache-2.0
thess/OpenWrt-luci,Noltari/luci,chris5560/openwrt-luci,lcf258/openwrtcn,thess/OpenWrt-luci,chris5560/openwrt-luci,RedSnake64/openwrt-luci-packages,dwmw2/luci,obsy/luci,shangjiyu/luci-with-extra,taiha/luci,jlopenwrtluci/luci,remakeelectric/luci,LuttyYang/luci,oneru/luci,MinFu/luci,taiha/luci,jorgifumi/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,urueedi/luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,nwf/openwrt-luci,thesabbir/luci,shangjiyu/luci-with-extra,oneru/luci,thesabbir/luci,cshore/luci,ollie27/openwrt_luci,palmettos/test,artynet/luci,deepak78/new-luci,jorgifumi/luci,aa65535/luci,kuoruan/luci,Noltari/luci,keyidadi/luci,nwf/openwrt-luci,tobiaswaldvogel/luci,slayerrensky/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,marcel-sch/luci,joaofvieira/luci,daofeng2015/luci,opentechinstitute/luci,oyido/luci,hnyman/luci,mumuqz/luci,tcatm/luci,obsy/luci,Noltari/luci,nmav/luci,Hostle/openwrt-luci-multi-user,LuttyYang/luci,shangjiyu/luci-with-extra,oyido/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,bright-things/ionic-luci,bittorf/luci,nmav/luci,wongsyrone/luci-1,thesabbir/luci,Noltari/luci,opentechinstitute/luci,urueedi/luci,Kyklas/luci-proto-hso,Wedmer/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,bittorf/luci,openwrt-es/openwrt-luci,981213/luci-1,RedSnake64/openwrt-luci-packages,sujeet14108/luci,palmettos/test,remakeelectric/luci,981213/luci-1,rogerpueyo/luci,LuttyYang/luci,david-xiao/luci,Hostle/luci,981213/luci-1,RuiChen1113/luci,palmettos/cnLuCI,taiha/luci,kuoruan/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,ReclaimYourPrivacy/cloak-luci,remakeelectric/luci,schidler/ionic-luci,david-xiao/luci,Kyklas/luci-proto-hso,zhaoxx063/luci,wongsyrone/luci-1,teslamint/luci,nwf/openwrt-luci,lcf258/openwrtcn,aa65535/luci,lcf258/openwrtcn,ollie27/openwrt_luci,kuoruan/luci,jlopenwrtluci/luci,jorgifumi/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,oyido/luci,rogerpueyo/luci,schidler/ionic-luci,harveyhu2012/luci,RuiChen1113/luci,cshore-firmware/openwrt-luci,florian-shellfire/luci,cappiewu/luci,david-xiao/luci,MinFu/luci,slayerrensky/luci,dismantl/luci-0.12,wongsyrone/luci-1,kuoruan/lede-luci,male-puppies/luci,deepak78/new-luci,Sakura-Winkey/LuCI,palmettos/test,thesabbir/luci,lcf258/openwrtcn,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,slayerrensky/luci,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,deepak78/new-luci,urueedi/luci,shangjiyu/luci-with-extra,artynet/luci,opentechinstitute/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci,Kyklas/luci-proto-hso,cshore/luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,bright-things/ionic-luci,harveyhu2012/luci,nmav/luci,cappiewu/luci,shangjiyu/luci-with-extra,kuoruan/luci,NeoRaider/luci,artynet/luci,dwmw2/luci,teslamint/luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,urueedi/luci,maxrio/luci981213,dismantl/luci-0.12,remakeelectric/luci,jorgifumi/luci,tobiaswaldvogel/luci,mumuqz/luci,tcatm/luci,ff94315/luci-1,NeoRaider/luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,tobiaswaldvogel/luci,cappiewu/luci,openwrt/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,nmav/luci,artynet/luci,zhaoxx063/luci,openwrt-es/openwrt-luci,cappiewu/luci,male-puppies/luci,schidler/ionic-luci,kuoruan/lede-luci,jchuang1977/luci-1,mumuqz/luci,oneru/luci,thess/OpenWrt-luci,artynet/luci,cappiewu/luci,florian-shellfire/luci,wongsyrone/luci-1,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,bright-things/ionic-luci,thess/OpenWrt-luci,bright-things/ionic-luci,RedSnake64/openwrt-luci-packages,LuttyYang/luci,forward619/luci,thess/OpenWrt-luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,openwrt/luci,joaofvieira/luci,jchuang1977/luci-1,nwf/openwrt-luci,david-xiao/luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,thesabbir/luci,tcatm/luci,nwf/openwrt-luci,RuiChen1113/luci,oneru/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,hnyman/luci,urueedi/luci,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,ollie27/openwrt_luci,david-xiao/luci,Sakura-Winkey/LuCI,thesabbir/luci,oneru/luci,deepak78/new-luci,hnyman/luci,teslamint/luci,slayerrensky/luci,marcel-sch/luci,nwf/openwrt-luci,thess/OpenWrt-luci,opentechinstitute/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,ollie27/openwrt_luci,Hostle/luci,kuoruan/luci,cshore/luci,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,Wedmer/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,schidler/ionic-luci,hnyman/luci,forward619/luci,sujeet14108/luci,harveyhu2012/luci,rogerpueyo/luci,palmettos/test,Hostle/luci,RuiChen1113/luci,Kyklas/luci-proto-hso,marcel-sch/luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,obsy/luci,oyido/luci,MinFu/luci,cshore-firmware/openwrt-luci,NeoRaider/luci,taiha/luci,cshore/luci,mumuqz/luci,Noltari/luci,kuoruan/lede-luci,jchuang1977/luci-1,forward619/luci,981213/luci-1,mumuqz/luci,tobiaswaldvogel/luci,cshore/luci,wongsyrone/luci-1,marcel-sch/luci,jorgifumi/luci,chris5560/openwrt-luci,Hostle/luci,daofeng2015/luci,kuoruan/lede-luci,male-puppies/luci,Noltari/luci,Wedmer/luci,ff94315/luci-1,urueedi/luci,bittorf/luci,urueedi/luci,aa65535/luci,urueedi/luci,obsy/luci,Noltari/luci,wongsyrone/luci-1,artynet/luci,fkooman/luci,keyidadi/luci,dismantl/luci-0.12,zhaoxx063/luci,Hostle/luci,RuiChen1113/luci,daofeng2015/luci,aa65535/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,jorgifumi/luci,dwmw2/luci,forward619/luci,openwrt/luci,mumuqz/luci,chris5560/openwrt-luci,jchuang1977/luci-1,taiha/luci,obsy/luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,bittorf/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,florian-shellfire/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,fkooman/luci,palmettos/cnLuCI,dwmw2/luci,oneru/luci,aa65535/luci,ollie27/openwrt_luci,marcel-sch/luci,artynet/luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,kuoruan/lede-luci,jlopenwrtluci/luci,sujeet14108/luci,forward619/luci,fkooman/luci,taiha/luci,Noltari/luci,hnyman/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,openwrt/luci,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,Kyklas/luci-proto-hso,rogerpueyo/luci,LuttyYang/luci,openwrt/luci,fkooman/luci,male-puppies/luci,cshore/luci,male-puppies/luci,cshore/luci,hnyman/luci,jlopenwrtluci/luci,dismantl/luci-0.12,chris5560/openwrt-luci,male-puppies/luci,Wedmer/luci,fkooman/luci,Wedmer/luci,NeoRaider/luci,forward619/luci,nmav/luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,Kyklas/luci-proto-hso,slayerrensky/luci,schidler/ionic-luci,nmav/luci,rogerpueyo/luci,palmettos/test,LuttyYang/luci,tobiaswaldvogel/luci,zhaoxx063/luci,florian-shellfire/luci,sujeet14108/luci,marcel-sch/luci,nmav/luci,dismantl/luci-0.12,tobiaswaldvogel/luci,palmettos/test,maxrio/luci981213,sujeet14108/luci,mumuqz/luci,ollie27/openwrt_luci,slayerrensky/luci,daofeng2015/luci,forward619/luci,openwrt/luci,Noltari/luci,taiha/luci,Kyklas/luci-proto-hso,oneru/luci,zhaoxx063/luci,harveyhu2012/luci,opentechinstitute/luci,Hostle/luci,Wedmer/luci,ollie27/openwrt_luci,schidler/ionic-luci,bittorf/luci,artynet/luci,wongsyrone/luci-1,lcf258/openwrtcn,oyido/luci,jorgifumi/luci,wongsyrone/luci-1,rogerpueyo/luci,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,remakeelectric/luci,joaofvieira/luci,dwmw2/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,nwf/openwrt-luci,cshore-firmware/openwrt-luci,deepak78/new-luci,thesabbir/luci,deepak78/new-luci,deepak78/new-luci,kuoruan/luci,forward619/luci,thess/OpenWrt-luci,kuoruan/luci,remakeelectric/luci,obsy/luci,openwrt/luci,lcf258/openwrtcn,fkooman/luci,thess/OpenWrt-luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,remakeelectric/luci,palmettos/cnLuCI,schidler/ionic-luci,joaofvieira/luci,harveyhu2012/luci,joaofvieira/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,bright-things/ionic-luci,hnyman/luci,LuttyYang/luci,opentechinstitute/luci,teslamint/luci,schidler/ionic-luci,cappiewu/luci,Hostle/luci,cshore/luci,cshore-firmware/openwrt-luci,Wedmer/luci,nwf/openwrt-luci,Hostle/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,opentechinstitute/luci,fkooman/luci,kuoruan/luci,MinFu/luci,db260179/openwrt-bpi-r1-luci,keyidadi/luci,marcel-sch/luci,chris5560/openwrt-luci,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,fkooman/luci,sujeet14108/luci,maxrio/luci981213,obsy/luci,RuiChen1113/luci,ff94315/luci-1,david-xiao/luci,tcatm/luci,aa65535/luci,harveyhu2012/luci,oyido/luci,openwrt-es/openwrt-luci,marcel-sch/luci,kuoruan/lede-luci,lcf258/openwrtcn,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,dismantl/luci-0.12,MinFu/luci,981213/luci-1,981213/luci-1,Hostle/openwrt-luci-multi-user,Sakura-Winkey/LuCI,daofeng2015/luci,jchuang1977/luci-1,dwmw2/luci,david-xiao/luci,MinFu/luci,ollie27/openwrt_luci,keyidadi/luci,kuoruan/lede-luci,maxrio/luci981213,lbthomsen/openwrt-luci,hnyman/luci,aa65535/luci,ff94315/luci-1,dwmw2/luci,NeoRaider/luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,keyidadi/luci,male-puppies/luci,NeoRaider/luci,oyido/luci,keyidadi/luci,zhaoxx063/luci,lcf258/openwrtcn,jorgifumi/luci,RuiChen1113/luci,maxrio/luci981213,jchuang1977/luci-1,thesabbir/luci,cshore-firmware/openwrt-luci,rogerpueyo/luci,shangjiyu/luci-with-extra,ff94315/luci-1,daofeng2015/luci,teslamint/luci,nmav/luci,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,bittorf/luci,slayerrensky/luci,deepak78/new-luci,david-xiao/luci,jchuang1977/luci-1,openwrt-es/openwrt-luci,joaofvieira/luci,sujeet14108/luci,tcatm/luci,joaofvieira/luci,lbthomsen/openwrt-luci,LuttyYang/luci,mumuqz/luci,male-puppies/luci,teslamint/luci,palmettos/cnLuCI,MinFu/luci,bright-things/ionic-luci,remakeelectric/luci,bright-things/ionic-luci,artynet/luci,aa65535/luci,cappiewu/luci,oyido/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,ff94315/luci-1,florian-shellfire/luci,NeoRaider/luci,Wedmer/luci,daofeng2015/luci,cappiewu/luci,Hostle/openwrt-luci-multi-user,981213/luci-1,tcatm/luci,florian-shellfire/luci,sujeet14108/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,dwmw2/luci,taiha/luci,db260179/openwrt-bpi-r1-luci,palmettos/test,obsy/luci,oneru/luci
287482a0f619e5b0ceb33190af04314b363f1d41
aspects/nvim/files/.config/nvim/lua/wincent/ftplugin/lua/includeexpr.lua
aspects/nvim/files/.config/nvim/lua/wincent/ftplugin/lua/includeexpr.lua
local fmt = string.format -- Look at first line of `package.config` for directory separator. -- See: http://www.lua.org/manual/5.2/manual.html#pdf-package.config local separator = string.match(package.config, '^[^\n]') -- Search for lua traditional include paths. -- This mimics how require internally works. local function include_paths(fname) local paths = string.gsub(package.path, "%?", fname) for path in string.gmatch(paths, '[^%;]+') do if vim.fn.filereadable(path) == 1 then return path end end end -- Search for nvim lua include paths local function include_rtpaths(fname, ext) for _, path in ipairs(vim.api.nvim_list_runtime_paths()) do -- Look on runtime path for 'lua/*.lua' files local path1 = table.concat({ path, ext, fmt("%s.%s", fname, ext) }, separator) if vim.fn.filereadable(path1) == 1 then return path1 end -- Look on runtime path for 'lua/*/init.lua' files local path2 = table.concat({ path, ext, fname, fmt("init.%s", ext) }, separator) if vim.fn.filereadable(path2) == 1 then return path2 end end end -- Global function that searches the path for the required file local function find_required_path(module) -- Properly change '.' to separator (probably '/' on *nix and '\' on Windows) local fname = vim.fn.substitute(module, '\\.', separator, 'g') local f ---- First search for lua modules f = include_paths(fname) if f then return f end -- This part is just for nvim modules f = include_rtpaths(fname, "lua") if f then return f end -- This part is just for nvim modules f = include_rtpaths(fname, "fnl") if f then return f end end return find_required_path
local fmt = string.format -- Look at first line of `package.config` for directory separator. -- See: http://www.lua.org/manual/5.2/manual.html#pdf-package.config local separator = string.match(package.config, '^[^\n]') -- Search for lua traditional include paths. -- This mimics how require internally works. local function include_paths(fname) local paths = string.gsub(package.path, "%?", fname) for path in string.gmatch(paths, '[^%;]+') do if vim.fn.filereadable(path) == 1 then return path end end end -- Search for nvim lua include paths local function include_rtpaths(fname, ext) local candidate for _, path in ipairs(vim.api.nvim_list_runtime_paths()) do -- Look for "lua/*.lua". candidate = table.concat({ path, ext, fmt("%s.%s", fname, ext) }, separator) if vim.fn.filereadable(candidate) == 1 then return candidate end -- Look for "lua/*/init.lua". candidate = table.concat({ path, ext, fname, fmt("init.%s", ext) }, separator) if vim.fn.filereadable(candidate) == 1 then return candidate end end end -- Global function that searches the path for the required file local function find_required_path(module) -- Properly change '.' to separator (probably '/' on *nix and '\' on Windows) local fname = vim.fn.substitute(module, '\\.', separator, 'g') local f ---- First search for lua modules f = include_paths(fname) if f then return f end -- This part is just for nvim modules f = include_rtpaths(fname, "lua") if f then return f end -- This part is just for nvim modules f = include_rtpaths(fname, "fnl") if f then return f end end return find_required_path
refactor(nvim): avoid variables with numeric suffixes
refactor(nvim): avoid variables with numeric suffixes These (ie. `path1` and `path2`) are a code smell; it's better to use (and re-use) `candidate`.
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
55282fa0aa4b4a02b714a231e252bd8c5dd32bac
src/select.lua
src/select.lua
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local window = require 'window' local state = Gamestate.new() local Wardrobe = {} Wardrobe.__index = Wardrobe function Wardrobe.create(character) local drobe = {} setmetatable(drobe, Wardrobe) drobe.character = character drobe.count = 1 drobe.image = love.graphics.newImage(character.costumes[1].sheet) drobe.image:setFilter('nearest', 'nearest') drobe.mask = love.graphics.newQuad(0, character.offset, 48, 27, drobe.image:getWidth(), drobe.image:getHeight()) return drobe end function Wardrobe:newCharacter() local sprite = self.character.new(self.image) sprite.ow = self.character.ow return sprite end function Wardrobe:getCostume() return self.character.costumes[self.count] end function Wardrobe:prevCostume() self.count = (self.count - 1) if self.count == 0 then self.count = (# self.character.costumes) end self:loadCostume() end function Wardrobe:nextCostume() self.count = math.max((self.count + 1) % (# self.character.costumes + 1), 1) self:loadCostume() end function Wardrobe:loadCostume() self.image = love.graphics.newImage(self.character.costumes[self.count].sheet) self.mask = love.graphics.newQuad(0, self.character.offset, 48, 27, self.image:getWidth(), self.image:getHeight()) end function Wardrobe:draw(x, y, flipX) love.graphics.drawq(self.image, self.mask, x, y, 0, flipX, 1) end local main_selections = {} main_selections[0] = {} main_selections[1] = {} main_selections[1][0] = Wardrobe.create(require 'characters/troy') main_selections[1][1] = Wardrobe.create(require 'characters/shirley') main_selections[1][2] = Wardrobe.create(require 'characters/pierce') main_selections[0][0] = Wardrobe.create(require 'characters/jeff') main_selections[0][1] = Wardrobe.create(require 'characters/britta') main_selections[0][2] = Wardrobe.create(require 'characters/abed') main_selections[0][3] = Wardrobe.create(require 'characters/annie') local alt_selections = {} alt_selections[0] = {} alt_selections[1] = {} alt_selections[1][0] = Wardrobe.create(require 'characters/fatneil') alt_selections[1][1] = Wardrobe.create(require 'characters/chang') alt_selections[1][2] = Wardrobe.create(require 'characters/vicedean') local main_selected = true local selections = main_selections function state:init() self.side = 0 -- 0 for left, 1 for right self.level = 0 -- 0 through 3 for characters self.screen = love.graphics.newImage("images/selectscreen.png") self.arrow = love.graphics.newImage("images/arrow.png") self.tmp = love.graphics.newImage('images/jeff.png') end function state:enter(previous) self.previous = previous self.music = love.audio.play("audio/opening.ogg", "stream", true) end function state:wardrobe() return selections[self.side][self.level] end function state:keypressed(key) local level = self.level local options = 4 if key == 'left' or key == 'right' or key == 'a' or key == 'd' then self.side = (self.side - 1) % 2 elseif key == 'up' or key == 'w' then level = (self.level - 1) % options elseif key == 'down' or key == 's' then level = (self.level + 1) % options end if key == 'tab' then if self.level == 3 and self.side == 1 then return elseif love.keyboard.isDown("lshift") or love.keyboard.isDown("rshift") then self:wardrobe():prevCostume() else self:wardrobe():nextCostume() end return end self.level = level if key == 'escape' then Gamestate.switch('home') return end if key == 'return' and self.level == 3 and self.side == 1 then if main_selected then selections = alt_selections main_selected = false else selections = main_selections main_selected = true end elseif key == 'return' then local wardrobe = self:wardrobe() if wardrobe then local level = Gamestate.get('overworld') level:reset() Gamestate.switch('overworld', wardrobe:newCharacter()) end end end function state:leave() love.audio.stop(self.music) end function state:draw() love.graphics.draw(self.screen) local x = 17 local r = 0 local offset = 68 if self.side == 1 then x = window.width - 17 r = math.pi offset = 68 + self.arrow:getHeight() end local name = "" if self:wardrobe() then local costume = self:wardrobe():getCostume() name = costume.name end love.graphics.draw(self.arrow, x, offset + 34 * self.level, r) love.graphics.printf("Enter to start", 0, window.height - 55, window.width, 'center') love.graphics.printf("Tab to switch costume", 0, window.height - 35, window.width, 'center') love.graphics.printf(name, 0, 23, window.width, 'center') for i=0,1,1 do for j=0,4,1 do local wardrobe = selections[i][j] if wardrobe then if i == 0 then wardrobe:draw(131 + 48 - 34 * j, 66 + 34 * j, -1) else wardrobe:draw(281 + 34 * j, 66 + 34 * j, 1) end end end end end Gamestate.home = state return state
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local window = require 'window' local state = Gamestate.new() local Wardrobe = {} Wardrobe.__index = Wardrobe function Wardrobe.create(character) local drobe = {} setmetatable(drobe, Wardrobe) drobe.character = character drobe.count = 1 drobe.image = love.graphics.newImage(character.costumes[1].sheet) drobe.image:setFilter('nearest', 'nearest') drobe.mask = love.graphics.newQuad(0, character.offset, 48, 27, drobe.image:getWidth(), drobe.image:getHeight()) return drobe end function Wardrobe:newCharacter() local sprite = self.character.new(self.image) sprite.ow = self.character.ow return sprite end function Wardrobe:getCostume() return self.character.costumes[self.count] end function Wardrobe:prevCostume() self.count = (self.count - 1) if self.count == 0 then self.count = (# self.character.costumes) end self:loadCostume() end function Wardrobe:nextCostume() self.count = math.max((self.count + 1) % (# self.character.costumes + 1), 1) self:loadCostume() end function Wardrobe:loadCostume() self.image = love.graphics.newImage(self.character.costumes[self.count].sheet) self.mask = love.graphics.newQuad(0, self.character.offset, 48, 27, self.image:getWidth(), self.image:getHeight()) end function Wardrobe:draw(x, y, flipX) love.graphics.drawq(self.image, self.mask, x, y, 0, flipX, 1) end local main_selections = {} main_selections[0] = {} main_selections[1] = {} main_selections[1][0] = Wardrobe.create(require 'characters/troy') main_selections[1][1] = Wardrobe.create(require 'characters/shirley') main_selections[1][2] = Wardrobe.create(require 'characters/pierce') main_selections[0][0] = Wardrobe.create(require 'characters/jeff') main_selections[0][1] = Wardrobe.create(require 'characters/britta') main_selections[0][2] = Wardrobe.create(require 'characters/abed') main_selections[0][3] = Wardrobe.create(require 'characters/annie') local alt_selections = {} alt_selections[0] = {} alt_selections[1] = {} alt_selections[1][0] = Wardrobe.create(require 'characters/fatneil') alt_selections[1][1] = Wardrobe.create(require 'characters/chang') alt_selections[1][2] = Wardrobe.create(require 'characters/vicedean') local main_selected = true local selections = main_selections function state:init() self.side = 0 -- 0 for left, 1 for right self.level = 0 -- 0 through 3 for characters self.screen = love.graphics.newImage("images/selectscreen.png") self.arrow = love.graphics.newImage("images/arrow.png") self.tmp = love.graphics.newImage('images/jeff.png') end function state:enter(previous) self.previous = previous self.music = love.audio.play("audio/opening.ogg", "stream", true) end function state:wardrobe() return selections[self.side][self.level] end function state:keypressed(key) local level = self.level local options = 4 if key == 'left' or key == 'right' or key == 'a' or key == 'd' then self.side = (self.side - 1) % 2 elseif key == 'up' or key == 'w' then level = (self.level - 1) % options elseif key == 'down' or key == 's' then level = (self.level + 1) % options end if key == 'tab' then if self.level == 3 and self.side == 1 then return elseif love.keyboard.isDown("lshift") or love.keyboard.isDown("rshift") then local wardrobe = self:wardrobe() if wardrobe then wardrobe:prevCostume() end else local wardrobe = self:wardrobe() if wardrobe then wardrobe:nextCostume() end end return end self.level = level if key == 'escape' then Gamestate.switch('home') return end if key == 'return' and self.level == 3 and self.side == 1 then if main_selected then selections = alt_selections main_selected = false else selections = main_selections main_selected = true end elseif key == 'return' then local wardrobe = self:wardrobe() if wardrobe then local level = Gamestate.get('overworld') level:reset() Gamestate.switch('overworld', wardrobe:newCharacter()) end end end function state:leave() love.audio.stop(self.music) end function state:draw() love.graphics.draw(self.screen) local x = 17 local r = 0 local offset = 68 if self.side == 1 then x = window.width - 17 r = math.pi offset = 68 + self.arrow:getHeight() end local name = "" if self:wardrobe() then local costume = self:wardrobe():getCostume() name = costume.name end love.graphics.draw(self.arrow, x, offset + 34 * self.level, r) love.graphics.printf("Enter to start", 0, window.height - 55, window.width, 'center') love.graphics.printf("Tab to switch costume", 0, window.height - 35, window.width, 'center') love.graphics.printf(name, 0, 23, window.width, 'center') for i=0,1,1 do for j=0,4,1 do local wardrobe = selections[i][j] if wardrobe then if i == 0 then wardrobe:draw(131 + 48 - 34 * j, 66 + 34 * j, -1) else wardrobe:draw(281 + 34 * j, 66 + 34 * j, 1) end end end end end Gamestate.home = state return state
Prevent crashes on selection screen.
Prevent crashes on selection screen. This commit fixes #90
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua
197301bdad8cdb5d17d94f652876dc422ccf86da
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ipaddr, adv_interface, adv_subnet local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network")) adv_interface.widget = "checkbox" adv_interface.exclude = arg[1] adv_interface.default = "lan" adv_interface.template = "cbi/network_netlist" adv_interface.nocreate = true adv_interface.nobridges = true adv_interface.novirtual = true function adv_interface.remove(self, section) self:write(section, " ") end adv_subnet = section:taboption("general", Value, "adv_subnet", translate("Advertised network ID"), translate("Allowed range is 1 to 65535")) adv_subnet.placeholder = "1" adv_subnet.datatype = "range(1,65535)" function adv_subnet.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v and tonumber(v, 16) end function adv_subnet .write(self, section, value) value = tonumber(value) or 1 if value > 65535 then value = 65535 elseif value < 1 then value = 1 end Value.write(self, section, "%X" % value) end adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime", translate("Use valid lifetime"), translate("Specifies the advertised valid prefix lifetime in seconds")) adv_valid_lifetime.placeholder = "300" adv_valid_lifetime.datatype = "uinteger" adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime", translate("Use preferred lifetime"), translate("Specifies the advertised preferred prefix lifetime in seconds")) adv_preferred_lifetime.placeholder = "120" adv_preferred_lifetime.datatype = "uinteger" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(1500)"
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ipaddr, adv_interface, adv_subnet local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network")) adv_interface.widget = "checkbox" adv_interface.exclude = arg[1] adv_interface.default = "lan" adv_interface.template = "cbi/network_netlist" adv_interface.nocreate = true adv_interface.nobridges = true adv_interface.novirtual = true function adv_interface.write(self, section, value) if type(value) == "table" then Value.write(self, section, table.concat(value, " ")) else Value.write(self, section, value) end end function adv_interface.remove(self, section) self:write(section, " ") end adv_subnet = section:taboption("general", Value, "adv_subnet", translate("Advertised network ID"), translate("Allowed range is 1 to 65535")) adv_subnet.placeholder = "1" adv_subnet.datatype = "range(1,65535)" function adv_subnet.cfgvalue(self, section) local v = Value.cfgvalue(self, section) return v and tonumber(v, 16) end function adv_subnet .write(self, section, value) value = tonumber(value) or 1 if value > 65535 then value = 65535 elseif value < 1 then value = 1 end Value.write(self, section, "%X" % value) end adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime", translate("Use valid lifetime"), translate("Specifies the advertised valid prefix lifetime in seconds")) adv_valid_lifetime.placeholder = "300" adv_valid_lifetime.datatype = "uinteger" adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime", translate("Use preferred lifetime"), translate("Specifies the advertised preferred prefix lifetime in seconds")) adv_preferred_lifetime.placeholder = "120" adv_preferred_lifetime.datatype = "uinteger" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(1500)"
proto/6x4: cast 6to4 adv_interface to string when saving to uci, fixes 6in4.sh not picking up the adv interfaces
proto/6x4: cast 6to4 adv_interface to string when saving to uci, fixes 6in4.sh not picking up the adv interfaces git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9009 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
b1217c88c3566c1bd726bce9203da591af564bcf
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/iface_add.lua
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/iface_add.lua
-- Copyright 2009-2010 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. local nw = require "luci.model.network".init() local fw = require "luci.model.firewall".init() local utl = require "luci.util" local uci = require "luci.model.uci".cursor() m = SimpleForm("network", translate("Create Interface")) m.redirect = luci.dispatcher.build_url("admin/network/network") m.reset = false newnet = m:field(Value, "_netname", translate("Name of the new interface"), translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " .. "<code>0-9</code> and <code>_</code>" )) newnet:depends("_attach", "") newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_") newnet.datatype = "uciname" newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface")) netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces")) sifname = m:field(Value, "_ifname", translate("Cover the following interface")) sifname.widget = "radio" sifname.template = "cbi/network_ifacelist" sifname.nobridges = true mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces")) mifname.widget = "checkbox" mifname.template = "cbi/network_ifacelist" mifname.nobridges = true local _, p for _, p in ipairs(nw:get_protocols()) do if p:is_installed() then newproto:value(p:proto(), p:get_i18n()) if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end if not p:is_floating() then sifname:depends({ _bridge = "", _netproto = p:proto()}) mifname:depends({ _bridge = "1", _netproto = p:proto()}) end end end function newproto.validate(self, value, section) local name = newnet:formvalue(section) if not name or #name == 0 then newnet:add_error(section, translate("No network name specified")) elseif m:get(name) then newnet:add_error(section, translate("The given network name is not unique")) end local proto = nw:get_protocol(value) if proto and not proto:is_floating() then local br = (netbridge:formvalue(section) == "1") local ifn = br and mifname:formvalue(section) or sifname:formvalue(section) for ifn in utl.imatch(ifn) do return value end return nil, translate("The selected protocol needs a device assigned") end return value end function newproto.write(self, section, value) local name = newnet:formvalue(section) if name and #name > 0 then local br = (netbridge:formvalue(section) == "1") and "bridge" or nil local net = nw:add_network(name, { proto = value, type = br }) if net then local ifn for ifn in utl.imatch( br and mifname:formvalue(section) or sifname:formvalue(section) ) do net:add_interface(ifn) end nw:save("network") nw:save("wireless") end luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name)) end end return m
-- Copyright 2009-2010 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. local nw = require "luci.model.network".init() local fw = require "luci.model.firewall".init() local utl = require "luci.util" local uci = require "luci.model.uci".cursor() m = SimpleForm("network", translate("Create Interface")) m.redirect = luci.dispatcher.build_url("admin/network/network") m.reset = false newnet = m:field(Value, "_netname", translate("Name of the new interface"), translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " .. "<code>0-9</code> and <code>_</code>" )) newnet:depends("_attach", "") newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_") newnet.datatype = "and(uciname,maxlength(15))" advice = m:field(DummyValue, "d1", translate("Note: interface name length"), translate("Maximum length of the name is 15 characters including " .. "the automatic protocol/bridge prefix (br-, 6in4-, pppoe- etc.)" )) newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface")) netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces")) sifname = m:field(Value, "_ifname", translate("Cover the following interface")) sifname.widget = "radio" sifname.template = "cbi/network_ifacelist" sifname.nobridges = true mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces")) mifname.widget = "checkbox" mifname.template = "cbi/network_ifacelist" mifname.nobridges = true local _, p for _, p in ipairs(nw:get_protocols()) do if p:is_installed() then newproto:value(p:proto(), p:get_i18n()) if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end if not p:is_floating() then sifname:depends({ _bridge = "", _netproto = p:proto()}) mifname:depends({ _bridge = "1", _netproto = p:proto()}) end end end function newproto.validate(self, value, section) local name = newnet:formvalue(section) if not name or #name == 0 then newnet:add_error(section, translate("No network name specified")) elseif m:get(name) then newnet:add_error(section, translate("The given network name is not unique")) end local proto = nw:get_protocol(value) if proto and not proto:is_floating() then local br = (netbridge:formvalue(section) == "1") local ifn = br and mifname:formvalue(section) or sifname:formvalue(section) for ifn in utl.imatch(ifn) do return value end return nil, translate("The selected protocol needs a device assigned") end return value end function newproto.write(self, section, value) local name = newnet:formvalue(section) if name and #name > 0 then local br = (netbridge:formvalue(section) == "1") and "bridge" or nil local net = nw:add_network(name, { proto = value, type = br }) if net then local ifn for ifn in utl.imatch( br and mifname:formvalue(section) or sifname:formvalue(section) ) do net:add_interface(ifn) end nw:save("network") nw:save("wireless") end luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name)) end end return m
luci-mod-admin-full: limit interface name length to 15 chars
luci-mod-admin-full: limit interface name length to 15 chars Limit the name of a new interface to 15 characters. Add a note about the maximum length and the automatic protocol/bridge prefixes (br-, 6in4-, pppoe- etc.). Reference to: https://dev.openwrt.org/ticket/20380 https://github.com/openwrt/luci/issues/507 There is a 15 character limit to the "real" interface name, enforced both in the firewall and dnsmasq. The real interface name includes the possible prefix "br-", "6in4-" etc. Example of an error: interface name `br-lan_protected' must be shorter than IFNAMSIZ (15) Signed-off-by: Hannu Nyman <[email protected]>
Lua
apache-2.0
jlopenwrtluci/luci,openwrt/luci,artynet/luci,981213/luci-1,oneru/luci,maxrio/luci981213,Hostle/luci,mumuqz/luci,Hostle/luci,shangjiyu/luci-with-extra,artynet/luci,openwrt/luci,shangjiyu/luci-with-extra,LuttyYang/luci,artynet/luci,hnyman/luci,openwrt/luci,nmav/luci,urueedi/luci,rogerpueyo/luci,kuoruan/luci,daofeng2015/luci,NeoRaider/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,openwrt/luci,lbthomsen/openwrt-luci,Wedmer/luci,LuttyYang/luci,daofeng2015/luci,teslamint/luci,LuttyYang/luci,rogerpueyo/luci,cshore/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,thess/OpenWrt-luci,cshore/luci,urueedi/luci,remakeelectric/luci,Hostle/luci,daofeng2015/luci,bittorf/luci,taiha/luci,chris5560/openwrt-luci,bright-things/ionic-luci,maxrio/luci981213,cshore/luci,openwrt/luci,Noltari/luci,teslamint/luci,bittorf/luci,Noltari/luci,daofeng2015/luci,taiha/luci,ollie27/openwrt_luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,Wedmer/luci,jlopenwrtluci/luci,LuttyYang/luci,openwrt-es/openwrt-luci,urueedi/luci,nmav/luci,NeoRaider/luci,cappiewu/luci,hnyman/luci,kuoruan/luci,bittorf/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,rogerpueyo/luci,artynet/luci,daofeng2015/luci,remakeelectric/luci,nmav/luci,bright-things/ionic-luci,taiha/luci,kuoruan/lede-luci,chris5560/openwrt-luci,jlopenwrtluci/luci,NeoRaider/luci,bittorf/luci,nmav/luci,mumuqz/luci,bittorf/luci,mumuqz/luci,shangjiyu/luci-with-extra,Noltari/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,kuoruan/luci,cshore/luci,chris5560/openwrt-luci,rogerpueyo/luci,nmav/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,openwrt-es/openwrt-luci,cappiewu/luci,mumuqz/luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt-es/openwrt-luci,cappiewu/luci,mumuqz/luci,Noltari/luci,jlopenwrtluci/luci,artynet/luci,wongsyrone/luci-1,bittorf/luci,wongsyrone/luci-1,maxrio/luci981213,mumuqz/luci,artynet/luci,urueedi/luci,NeoRaider/luci,hnyman/luci,981213/luci-1,remakeelectric/luci,tobiaswaldvogel/luci,teslamint/luci,aa65535/luci,artynet/luci,bright-things/ionic-luci,cappiewu/luci,lbthomsen/openwrt-luci,openwrt/luci,nmav/luci,cshore-firmware/openwrt-luci,Hostle/luci,tobiaswaldvogel/luci,maxrio/luci981213,urueedi/luci,shangjiyu/luci-with-extra,hnyman/luci,Hostle/luci,Wedmer/luci,teslamint/luci,hnyman/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,LuttyYang/luci,Hostle/luci,cshore/luci,Wedmer/luci,aa65535/luci,kuoruan/luci,981213/luci-1,nmav/luci,cshore/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,maxrio/luci981213,Noltari/luci,teslamint/luci,cappiewu/luci,Wedmer/luci,bright-things/ionic-luci,taiha/luci,wongsyrone/luci-1,aa65535/luci,ollie27/openwrt_luci,cappiewu/luci,taiha/luci,daofeng2015/luci,981213/luci-1,ollie27/openwrt_luci,chris5560/openwrt-luci,NeoRaider/luci,jlopenwrtluci/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,oneru/luci,remakeelectric/luci,Hostle/luci,oneru/luci,urueedi/luci,cshore-firmware/openwrt-luci,kuoruan/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,taiha/luci,Hostle/luci,kuoruan/lede-luci,mumuqz/luci,NeoRaider/luci,LuttyYang/luci,aa65535/luci,981213/luci-1,rogerpueyo/luci,kuoruan/luci,remakeelectric/luci,NeoRaider/luci,Noltari/luci,shangjiyu/luci-with-extra,981213/luci-1,chris5560/openwrt-luci,ollie27/openwrt_luci,teslamint/luci,kuoruan/luci,teslamint/luci,mumuqz/luci,Wedmer/luci,jlopenwrtluci/luci,wongsyrone/luci-1,jlopenwrtluci/luci,Wedmer/luci,kuoruan/lede-luci,artynet/luci,Noltari/luci,wongsyrone/luci-1,hnyman/luci,kuoruan/lede-luci,oneru/luci,kuoruan/lede-luci,bright-things/ionic-luci,maxrio/luci981213,Noltari/luci,NeoRaider/luci,kuoruan/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,kuoruan/lede-luci,taiha/luci,hnyman/luci,oneru/luci,taiha/luci,tobiaswaldvogel/luci,oneru/luci,bittorf/luci,LuttyYang/luci,maxrio/luci981213,rogerpueyo/luci,lbthomsen/openwrt-luci,nmav/luci,cshore/luci,artynet/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,chris5560/openwrt-luci,urueedi/luci,hnyman/luci,aa65535/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,oneru/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,ollie27/openwrt_luci,chris5560/openwrt-luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,cshore/luci,kuoruan/lede-luci,981213/luci-1,aa65535/luci,nmav/luci,bittorf/luci,wongsyrone/luci-1,thess/OpenWrt-luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,remakeelectric/luci,Wedmer/luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,remakeelectric/luci,remakeelectric/luci,urueedi/luci,aa65535/luci,oneru/luci,thess/OpenWrt-luci,teslamint/luci,openwrt/luci,bright-things/ionic-luci,aa65535/luci,cappiewu/luci,Noltari/luci,tobiaswaldvogel/luci,LuttyYang/luci,rogerpueyo/luci,thess/OpenWrt-luci,cappiewu/luci
916f498ac102d8194ce7877c87b0e0e104142527
examples/pcap/replay-pcap.lua
examples/pcap/replay-pcap.lua
--- Replay a pcap file. local mg = require "moongen" local device = require "device" local memory = require "memory" local stats = require "stats" local log = require "log" local pcap = require "pcap" local limiter = require "software-ratecontrol" function configure(parser) parser:argument("edev", "Device to use for egress."):args(1):convert(tonumber) parser:argument("idev", "Device to use for ingress."):args(1):convert(tonumber) parser:argument("file", "File to replay."):args(1) parser:option("-s --src-mac", "Overwrite source MAC address of every sent packet"):default(''):target("srcMAC") parser:option("-d --dst-mac", "Overwrite destination MAC address of every sent packet"):default(''):target("dstMAC") parser:option("-f --fix-rate", "Fixed net data rate in Mbit per second (ignore timestamps in pcap)"):default(0):convert(tonumber):target("fixedRate") parser:option("-r --rate-multiplier", "Speed up or slow down replay, 1 = use intervals from file, default = replay as fast as possible"):default(0):convert(tonumber):target("rateMultiplier") parser:option("-p --packets", "Send only the number of packets specified"):default(0):convert(tonumber):target("numberOfPackets") parser:flag("-l --loop", "Repeat pcap file.") local args = parser:parse() return args end function master(args) local edev = device.config{port = args.edev} local idev = device.config{port = args.idev, dropEnable = false} device.waitForLinks() local rateLimiter if args.rateMultiplier > 0 and args.fixedRate > 0 then print("-r and -f option cannot be set at the same time.") return end if args.rateMultiplier > 0 or args.fixedRate > 0 then rateLimiter = limiter:new(edev:getTxQueue(0), "custom") end if args.dstMAC ~= '' then print("Replace dstMAC with " .. args.dstMAC) end if args.srcMAC ~= '' then print("Replace srcMAC with " .. args.srcMAC) end dstmc = parseMacAddress(args.dstMAC, 0) srcmc = parseMacAddress(args.srcMAC, 0) mg.startTask("replay", edev:getTxQueue(0), args.file, args.loop, rateLimiter, args.rateMultiplier, args.fixedRate, args.numberOfPackets, dstmc, srcmc) stats.startStatsTask{txDevices = {edev}, rxDevices = {idev}} mg.waitForTasks() end function replay(queue, file, loop, rateLimiter, multiplier, fixedRate, numberOfPackets, dstMAC, srcMAC) local mempool = memory:createMemPool(4096) local bufs = mempool:bufArray() local pcapFile = pcap:newReader(file) local prev = 0 local linkSpeed = queue.dev:getLinkStatus().speed while mg.running() do local n = pcapFile:read(bufs) if n > 0 and numberOfPackets > 0 then if rateLimiter ~= nil then if prev == 0 then prev = bufs.array[0].udata64 end for i, buf in ipairs(bufs) do if numberOfPackets > 0 then if i > n then break end if dstMAC ~= nil then local pkt = buf:getEthernetPacket() pkt.eth:setDst(dstMAC) end if srcMAC ~= nil then local pkt = buf:getEthernetPacket() pkt.eth:setSrc(srcMAC) end -- ts is in microseconds local ts = buf.udata64 if prev > ts then ts = prev end sz = buf:getSize() local delay = ts - prev delay = tonumber(delay * 10^3) / multiplier -- nanoseconds delay = delay / (8000 / linkSpeed) -- delay in bytes if fixedRate > 0 then delay = (sz + 4) / (fixedRate/10000) end buf:setDelay(delay) prev = ts numberOfPackets = numberOfPackets - 1 else break end end end else if loop then pcapFile:reset() else pcapFile:close() mg.sleepMillis(1500) mg.stop() mg.sleepMillis(1500) os.exit(0) -- ending moongen forcefully return end end if rateLimiter then rateLimiter:sendN(bufs, n) else queue:sendN(bufs, n) end end end
--- Replay a pcap file. local mg = require "moongen" local device = require "device" local memory = require "memory" local stats = require "stats" local log = require "log" local pcap = require "pcap" local limiter = require "software-ratecontrol" function configure(parser) parser:argument("edev", "Device to use for egress."):args(1):convert(tonumber) parser:argument("idev", "Device to use for ingress."):args(1):convert(tonumber) parser:argument("file", "File to replay."):args(1) parser:option("-s --src-mac", "Overwrite source MAC address of every sent packet"):default(''):target("srcMAC") parser:option("-d --dst-mac", "Overwrite destination MAC address of every sent packet"):default(''):target("dstMAC") parser:option("-f --fix-rate", "Fixed net data rate in Mbit per second (ignore timestamps in pcap)"):default(0):convert(tonumber):target("fixedRate") parser:option("-v --fix-packetrate", "Fixed net data rate in packets per second (ignore timestamps in pcap)"):default(0):convert(tonumber):target("fixedPacketRate") parser:option("-r --rate-multiplier", "Speed up or slow down replay, 1 = use intervals from file, default = replay as fast as possible"):default(0):convert(tonumber):target("rateMultiplier") parser:option("-p --packets", "Send only the number of packets specified"):default(0):convert(tonumber):target("numberOfPackets") parser:flag("-l --loop", "Repeat pcap file.") local args = parser:parse() return args end function master(args) local edev = device.config{port = args.edev} local idev = device.config{port = args.idev, dropEnable = false} device.waitForLinks() local rateLimiter if args.rateMultiplier > 0 and args.fixedPacketRate > 0 then print("-r and -v option cannot be set at the same time.") return end if args.rateMultiplier > 0 and args.fixedRate > 0 then print("-r and -f option cannot be set at the same time.") return end if args.rateMultiplier > 0 or args.fixedRate > 0 or args.fixedPacketRate then rateLimiter = limiter:new(edev:getTxQueue(0), "custom") end if args.dstMAC ~= '' then print("Replace dstMAC with " .. args.dstMAC) end if args.srcMAC ~= '' then print("Replace srcMAC with " .. args.srcMAC) end if args.fixedPacketRate ~= 0 then print("Fixed packet rate " .. args.fixedPacketRate .. " pps") end dstmc = parseMacAddress(args.dstMAC, 0) srcmc = parseMacAddress(args.srcMAC, 0) mg.startTask("replay", edev:getTxQueue(0), args.file, args.loop, rateLimiter, args.rateMultiplier, args.fixedRate, args.numberOfPackets, dstmc, srcmc, args.fixedPacketRate) stats.startStatsTask{txDevices = {edev}, rxDevices = {idev}} mg.waitForTasks() end function replay(queue, file, loop, rateLimiter, multiplier, fixedRate, numberOfPackets, dstMAC, srcMAC, fixedPacketRate) local mempool = memory:createMemPool(4096) local bufs = mempool:bufArray() local pcapFile = pcap:newReader(file) local prev = 0 local linkSpeed = queue.dev:getLinkStatus().speed while mg.running() do fixedRateAcc = 0 local n = pcapFile:read(bufs) if n > 0 and numberOfPackets > 0 then if rateLimiter ~= nil then if prev == 0 then prev = bufs.array[0].udata64 end for i, buf in ipairs(bufs) do if numberOfPackets > 0 then if i > n then break end if dstMAC ~= nil then local pkt = buf:getEthernetPacket() pkt.eth:setDst(dstMAC) end if srcMAC ~= nil then local pkt = buf:getEthernetPacket() pkt.eth:setSrc(srcMAC) end -- ts is in microseconds local ts = buf.udata64 if prev > ts then ts = prev end sz = buf:getSize() local delay = ts - prev delay = tonumber(delay * 10^3) / multiplier -- nanoseconds delay = delay / (8000 / linkSpeed) -- delay in bytes if fixedRate > 0 then delay = (sz + 4) / (fixedRate/10000) end if fixedPacketRate > 0 then testdelay = 10000000000 / fixedPacketRate / 8 - (sz + 4) delay = (testdelay > 0) and testdelay or 0 if testdelay < 0 then fixedRateAcc = fixedRateAcc + testdelay + (sz + 4) end end buf:setDelay(delay) prev = ts numberOfPackets = numberOfPackets - 1 else break end end end else if loop then pcapFile:reset() else pcapFile:close() mg.sleepMillis(1500) mg.stop() mg.sleepMillis(1500) os.exit(0) -- ending moongen forcefully return end end if rateLimiter then rateLimiter:sendN(bufs, n) else queue:sendN(bufs, n) end end end
add fixed packet rate to pcap replay
add fixed packet rate to pcap replay
Lua
mit
gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen
a5d39d7158016023a3886dd3a14f6fe817818661
src/test1.lua
src/test1.lua
shape_var_index = 0; function nextShapeVar() shape_var_index = shape_var_index + 1 return "shape" .. shape_var_index end point_var_index = 0; function nextPointVar() point_var_index = point_var_index + 1 return "p" .. point_var_index end function v(x, y) return {x=x,y=y} end function circle(radius) v = nextShapeVar() r = {} r.glsl = function (p) print(" bool " .. v .. " = " .. p .. ".x + " .. p .. ".y < " .. radius .. " * " .. radius .. ";") end r.name = v return r end function box(width) v = nextShapeVar() r = {} r.glsl = function (p) print(" bool " .. v .. " = " .. p .. ".x < " .. width .. " && " .. p .. ".y < " .. width .. ";") end r.name = v return r end Translation = {} function Translate(v, shape) np = nextPointVar() r = {} r.glsl = function(p) print(" vec2 " .. np .. " = " .. p .. " - vec2(" .. v.x .. ", " .. v.y .. ");") shape.glsl(np) end r.name = shape.name return r end Translation.mt = {} Translation.mt.__mul = Translate function translate(x, y) local tr = {x=x,y=y} setmetatable(tr, Translation.mt) return tr end function union(shape1, shape2) v = nextShapeVar() r = {} function glsl(p) shape1.glsl(p) shape2.glsl(p) print(" bool " .. v .. " = " .. shape1.name .. " && " .. shape2.name .. ";") end r.name = v r.glsl = glsl return r end function emit(shape) print("#version 120") print("void main(void) {") shape.glsl("gl_FragCoord") print(" if (" .. shape.name .. ") {") print(" gl_FragColor[0] = 1.0;") print(" gl_FragColor[1] = 0.0; ") print(" gl_FragColor[2] = 0.0; ") print(" } else {") print(" gl_FragColor[0] = 0.0; ") print(" gl_FragColor[1] = 0.0; ") print(" gl_FragColor[2] = 0.0; ") print(" }") print("}") end emit( union( translate(320,320) * box(80), translate(300, 300) * circle(50) ) )
shape_var_index = 0 function nextShapeVar() shape_var_index = shape_var_index + 1 return "shape" .. shape_var_index end point_var_index = 0 function nextPointVar() point_var_index = point_var_index + 1 return "p" .. point_var_index end function v(x, y) return {x=x,y=y} end function circle(radius) local v = nextShapeVar() r = {} r.glsl = function (p) print(" bool " .. v .. " = " .. p .. ".x + " .. p .. ".y < " .. radius .. " * " .. radius .. ";") end r.name = v return r end function box(width) local v = nextShapeVar() r = {} r.glsl = function (p) print(" bool " .. v .. " = " .. p .. ".x < " .. width .. " && " .. p .. ".y < " .. width .. ";") end r.name = v return r end Translation = {} function Translate(v, shape) local np = nextPointVar() r = {} r.glsl = function(p) print(" vec2 " .. np .. " = " .. p .. " - vec2(" .. v.x .. ", " .. v.y .. ");") shape.glsl(np) end r.name = shape.name return r end Translation.mt = {} Translation.mt.__mul = Translate function translate(x, y) local tr = {x=x,y=y} setmetatable(tr, Translation.mt) return tr end function union(shape1, shape2) local v = nextShapeVar() r = {} r.glsl = function (p) shape1.glsl(p) shape2.glsl(p) print(" bool " .. v .. " = " .. shape1.name .. " && " .. shape2.name .. ";") end r.name = v return r end function emit(shape) print("#version 120") print("void main(void) {") shape.glsl("gl_FragCoord") print(" if (" .. shape.name .. ") {") print(" gl_FragColor[0] = 1.0;") print(" gl_FragColor[1] = 0.0; ") print(" gl_FragColor[2] = 0.0; ") print(" } else {") print(" gl_FragColor[0] = 0.0; ") print(" gl_FragColor[1] = 0.0; ") print(" gl_FragColor[2] = 0.0; ") print(" }") print("}") end emit( union( translate(320,320) * box(80), translate(300, 300) * circle(50) ) )
Solve bug of local variables reusing.
Solve bug of local variables reusing.
Lua
mit
loic-fejoz/luacnc
d662b4436c2fe8cfdf72b480b5b159b66878cb1d
tcpdns.lua
tcpdns.lua
local socket = require("socket") local struct = require("struct") ----------------------------------------- -- LRU cache function ----------------------------------------- local function LRU(size) local keys, dict = {}, {} local function get(key) local value = dict[key] if value and keys[1] ~= key then for i, k in ipairs(keys) do if k == key then table.insert(keys, 1, table.remove(keys, i)) break end end end return value end local function add(key, value) if not get(key) then if #keys == size then dict[keys[size]] = nil table.remove(keys) end table.insert(keys, 1, key) end dict[key] = value end return {add = add, get = get} end ----------------------------------------- -- task package ----------------------------------------- do local clock, ipairs, coroutine = os.clock, ipairs, coroutine local pool = {} local clk = setmetatable({}, {__mode = "k"}) local function go(f, ...) local co = coroutine.create(f) coroutine.resume(co, ...) if coroutine.status(co) ~= "dead" then local i = 0 repeat i = i + 1 until not pool[i] pool[i] = co clk[co] = clk[co] or clock() end end local function step() for i, co in ipairs(pool) do coroutine.resume(co) if coroutine.status(co) == "dead" then pool[i] = nil end end return #pool end local function sleep(n) n = n or 0 clk[coroutine.running()] = clock() + n coroutine.yield() end local function loop(n) n = n or 0.001 local sleep = ps.sleep or socket.sleep while step() ~= 0 do sleep(n) end end local mutex = {} local function lock(o, n) while mutex[o] do sleep(n) end mutex[o] = true end local function unlock(o) mutex[o] = nil end task = setmetatable( { go = go, sleep = sleep, step = step, loop = loop, lock = lock, unlock = unlock }, {__len = function() return #pool end} ) end ----------------------------------------- -- TCP DNS proxy ----------------------------------------- local cache = LRU(20) local task = task local hosts = { "8.8.8.8", "8.8.4.4", "208.67.222.222", "208.67.220.220" } local function queryDNS(host, data) local sock = socket.tcp() sock:settimeout(2) local recv = "" if sock:connect(host, 53) then sock:send(struct.pack(">h", #data)..data) sock:settimeout(0) repeat task.sleep(0.01) local s, status, partial = sock:receive(1024) recv = recv..(s or partial) until #recv > 0 or status == "closed" sock:close() end return recv end local function transfer(skt, data, ip, port) local domain = (data:sub(14, -6):gsub("[^%w]", ".")) print("domain: "..domain, "thread: "..#task) task.lock(domain, 0.01) if cache.get(domain) then skt:sendto(data:sub(1, 2)..cache.get(domain), ip, port) else for _, host in ipairs(hosts) do data = queryDNS(host, data) if #data > 0 then break end end if #data > 0 then data = data:sub(3) cache.add(domain, data:sub(3)) skt:sendto(data, ip, port) end end task.unlock(domain) end local function udpserver() local udp = socket.udp() udp:settimeout(0) udp:setsockname('*', 53) while true do local data, ip, port = udp:receivefrom() if data then task.go(transfer, udp, data, ip, port) end task.sleep(0) end end task.go(udpserver) task.loop()
local socket = require("socket") local struct = require("struct") ----------------------------------------- -- LRU cache function ----------------------------------------- local function LRU(size) local keys, dict = {}, {} local function get(key) local value = dict[key] if value and keys[1] ~= key then for i, k in ipairs(keys) do if k == key then table.insert(keys, 1, table.remove(keys, i)) break end end end return value end local function add(key, value) if not get(key) then if #keys == size then dict[keys[size]] = nil table.remove(keys) end table.insert(keys, 1, key) end dict[key] = value end return {add = add, get = get} end ----------------------------------------- -- task package ----------------------------------------- do local pool = {} local mutex = {} local clk = setmetatable({}, {__mode = "k"}) local function go(f, ...) local co = coroutine.create(f) coroutine.resume(co, ...) if coroutine.status(co) ~= "dead" then local i = 0 repeat i = i + 1 until not pool[i] pool[i] = co clk[co] = clk[co] or os.clock() end end local function step() for i, co in ipairs(pool) do if os.clock() >= clk[co] then coroutine.resume(co) if coroutine.status(co) == "dead" then pool[i] = nil end end end return #pool end local function sleep(n) n = n or 0 clk[coroutine.running()] = os.clock() + n coroutine.yield() end local function loop(n) n = n or 0.001 local sleep = ps.sleep or socket.sleep while step() ~= 0 do sleep(n) end end local function lock(o, n) while mutex[o] do sleep(n) end mutex[o] = true end local function unlock(o) mutex[o] = nil end task = setmetatable( { go = go, sleep = sleep, step = step, loop = loop, lock = lock, unlock = unlock }, {__len = function() return #pool end} ) end ----------------------------------------- -- TCP DNS proxy ----------------------------------------- local cache = LRU(20) local task = task local hosts = { "8.8.8.8", "8.8.4.4", "208.67.222.222", "208.67.220.220" } local function queryDNS(host, data) local sock = socket.tcp() sock:settimeout(2) local recv = "" if sock:connect(host, 53) then sock:send(struct.pack(">h", #data)..data) sock:settimeout(0) repeat task.sleep(0.01) local s, status, partial = sock:receive(1024) recv = recv..(s or partial) until #recv > 0 or status == "closed" sock:close() end return recv end local function transfer(skt, data, ip, port) local domain = (data:sub(14, -6):gsub("[^%w]", ".")) print("domain: "..domain, "thread: "..#task) task.lock(domain, 0.01) if cache.get(domain) then skt:sendto(data:sub(1, 2)..cache.get(domain), ip, port) else for _, host in ipairs(hosts) do data = queryDNS(host, data) if #data > 0 then break end end if #data > 0 then data = data:sub(3) cache.add(domain, data:sub(3)) skt:sendto(data, ip, port) end end task.unlock(domain) end local function udpserver() local udp = socket.udp() udp:settimeout(0) udp:setsockname('*', 53) while true do local data, ip, port = udp:receivefrom() if data then task.go(transfer, udp, data, ip, port) end task.sleep(0) end end task.go(udpserver) task.loop()
fix an important issue of task - clock missing
fix an important issue of task - clock missing
Lua
mit
uleelx/dnsforwarder
7af12e759dd5c00a179913237d19ac7ed5ef0412
net/http/parser.lua
net/http/parser.lua
local tonumber = tonumber; local assert = assert; local url_parse = require "socket.url".parse; local urldecode = require "util.http".urldecode; local function preprocess_path(path) path = urldecode((path:gsub("//+", "/"))); if path:sub(1,1) ~= "/" then path = "/"..path; end local level = 0; for component in path:gmatch("([^/]+)/") do if component == ".." then level = level - 1; elseif component ~= "." then level = level + 1; end if level < 0 then return nil; end end return path; end local httpstream = {}; function httpstream.new(success_cb, error_cb, parser_type, options_cb) local client = true; if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end local buf = ""; local chunked; local state = nil; local packet; local len; local have_body; local error; return { feed = function(self, data) if error then return nil, "parse has failed"; end if not data then -- EOF if state and client and not len then -- reading client body until EOF packet.body = buf; success_cb(packet); elseif buf ~= "" then -- unexpected EOF error = true; return error_cb(); end return; end buf = buf..data; while #buf > 0 do if state == nil then -- read request local index = buf:find("\r\n\r\n", nil, true); if not index then return; end -- not enough data local method, path, httpversion, status_code, reason_phrase; local first_line; local headers = {}; for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request if first_line then local key, val = line:match("^([^%s:]+): *(.*)$"); if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers key = key:lower(); headers[key] = headers[key] and headers[key]..","..val or val; else first_line = line; if client then httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$"); status_code = tonumber(status_code); if not status_code then error = true; return error_cb("invalid-status-line"); end have_body = not ( (options_cb and options_cb().method == "HEAD") or (status_code == 204 or status_code == 304 or status_code == 301) or (status_code >= 100 and status_code < 200) ); chunked = have_body and headers["transfer-encoding"] == "chunked"; else method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$"); if not method then error = true; return error_cb("invalid-status-line"); end end end end if not first_line then error = true; return error_cb("invalid-status-line"); end len = tonumber(headers["content-length"]); -- TODO check for invalid len if client then -- FIXME handle '100 Continue' response (by skipping it) if not have_body then len = 0; end packet = { code = status_code; httpversion = httpversion; headers = headers; body = have_body and "" or nil; -- COMPAT the properties below are deprecated responseversion = httpversion; responseheaders = headers; }; else local parsed_url; if path:byte() == 47 then -- starts with / local _path, _query = path:match("([^?]*).?(.*)"); if _query == "" then _query = nil; end parsed_url = { path = _path, query = _query }; else parsed_url = url_parse(path); if not(parsed_url and parsed_url.path) then error = true; return error_cb("invalid-url"); end end path = preprocess_path(parsed_url.path); headers.host = parsed_url.host or headers.host; len = len or 0; packet = { method = method; url = parsed_url; path = path; httpversion = httpversion; headers = headers; body = nil; }; end buf = buf:sub(index + 4); state = true; end if state then -- read body if client then if chunked then local index = buf:find("\r\n", nil, true); if not index then return; end -- not enough data local chunk_size = buf:match("^%x+"); if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end chunk_size = tonumber(chunk_size, 16); index = index + 2; if chunk_size == 0 then state = nil; success_cb(packet); elseif #buf - index + 1 >= chunk_size then -- we have a chunk packet.body = packet.body..buf:sub(index, index + chunk_size - 1); buf = buf:sub(index + chunk_size); end error("trailers"); -- FIXME MUST read trailers elseif len and #buf >= len then packet.body, buf = buf:sub(1, len), buf:sub(len + 1); state = nil; success_cb(packet); else break; end elseif #buf >= len then packet.body, buf = buf:sub(1, len), buf:sub(len + 1); state = nil; success_cb(packet); else break; end end end end; }; end return httpstream;
local tonumber = tonumber; local assert = assert; local url_parse = require "socket.url".parse; local urldecode = require "util.http".urldecode; local function preprocess_path(path) path = urldecode((path:gsub("//+", "/"))); if path:sub(1,1) ~= "/" then path = "/"..path; end local level = 0; for component in path:gmatch("([^/]+)/") do if component == ".." then level = level - 1; elseif component ~= "." then level = level + 1; end if level < 0 then return nil; end end return path; end local httpstream = {}; function httpstream.new(success_cb, error_cb, parser_type, options_cb) local client = true; if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end local buf = ""; local chunked, chunk_size, chunk_start; local state = nil; local packet; local len; local have_body; local error; return { feed = function(self, data) if error then return nil, "parse has failed"; end if not data then -- EOF if state and client and not len then -- reading client body until EOF packet.body = buf; success_cb(packet); elseif buf ~= "" then -- unexpected EOF error = true; return error_cb(); end return; end buf = buf..data; while #buf > 0 do if state == nil then -- read request local index = buf:find("\r\n\r\n", nil, true); if not index then return; end -- not enough data local method, path, httpversion, status_code, reason_phrase; local first_line; local headers = {}; for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request if first_line then local key, val = line:match("^([^%s:]+): *(.*)$"); if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers key = key:lower(); headers[key] = headers[key] and headers[key]..","..val or val; else first_line = line; if client then httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$"); status_code = tonumber(status_code); if not status_code then error = true; return error_cb("invalid-status-line"); end have_body = not ( (options_cb and options_cb().method == "HEAD") or (status_code == 204 or status_code == 304 or status_code == 301) or (status_code >= 100 and status_code < 200) ); else method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$"); if not method then error = true; return error_cb("invalid-status-line"); end end end end if not first_line then error = true; return error_cb("invalid-status-line"); end chunked = have_body and headers["transfer-encoding"] == "chunked"; len = tonumber(headers["content-length"]); -- TODO check for invalid len if client then -- FIXME handle '100 Continue' response (by skipping it) if not have_body then len = 0; end packet = { code = status_code; httpversion = httpversion; headers = headers; body = have_body and "" or nil; -- COMPAT the properties below are deprecated responseversion = httpversion; responseheaders = headers; }; else local parsed_url; if path:byte() == 47 then -- starts with / local _path, _query = path:match("([^?]*).?(.*)"); if _query == "" then _query = nil; end parsed_url = { path = _path, query = _query }; else parsed_url = url_parse(path); if not(parsed_url and parsed_url.path) then error = true; return error_cb("invalid-url"); end end path = preprocess_path(parsed_url.path); headers.host = parsed_url.host or headers.host; len = len or 0; packet = { method = method; url = parsed_url; path = path; httpversion = httpversion; headers = headers; body = nil; }; end buf = buf:sub(index + 4); state = true; end if state then -- read body if client then if chunked then if not buf:find("\r\n", nil, true) then return; end -- not enough data if not chunk_size then chunk_size, chunk_start = buf:match("^(%x+)[^\r\n]*\r\n()"); chunk_size = chunk_size and tonumber(chunk_size, 16); if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end end if chunk_size == 0 and buf:find("\r\n\r\n", chunk_start-2, true) then state, chunk_size = nil, nil; buf = buf:gsub("^.-\r\n\r\n", ""); -- This ensure extensions and trailers are stripped success_cb(packet); elseif #buf - chunk_start + 2 >= chunk_size then -- we have a chunk packet.body = packet.body..buf:sub(chunk_start, chunk_start + chunk_size); buf = buf:sub(chunk_start + chunk_size + 2); chunk_size, chunk_start = nil, nil; else -- Partial chunk remaining break; end elseif len and #buf >= len then packet.body, buf = buf:sub(1, len), buf:sub(len + 1); state = nil; success_cb(packet); else break; end elseif #buf >= len then packet.body, buf = buf:sub(1, len), buf:sub(len + 1); state = nil; success_cb(packet); else break; end end end end; }; end return httpstream;
net.http.parser: Fix chunked encoding response parsing, and make it more robust
net.http.parser: Fix chunked encoding response parsing, and make it more robust
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
38e369defc63b65426927e3c4c5b660749463861
mod_smacks/mod_smacks.lua
mod_smacks/mod_smacks.lua
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; session.handled_stanza_count = 0; -- Overwrite process_stanza() and send() local queue, queue_length = {}, 0; session.outgoing_stanza_queue, session.outgoing_stanza_count = queue, queue_length; local _send = session.send; function session.send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue_length = queue_length + 1; session.outgoing_stanza_count = queue_length; queue[queue_length] = st.reply(stanza); end local ok, err = _send(stanza); if ok and queue_length > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)+1; for i=1,handled_stanza_count do t_remove(origin.outgoing_stanza_queue, 1); end return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = queue[i]; if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, queue[i]); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end end return _destroy_session(session, err); end
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.send; function session.send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.reply(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = queue[i]; if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, queue[i]); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end end return _destroy_session(session, err); end
mod_smacks: Fix the logic for handling outgoing stanzas and ack requests
mod_smacks: Fix the logic for handling outgoing stanzas and ack requests
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
2ee1901f72a6011aa5245329fe4effc42fc0abe2
lua/decoders/json_decoder.lua
lua/decoders/json_decoder.lua
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Parses a payload containing JSON. Does not modify any Heka message attributes, only adds to the `Fields`. Config: - type (string, optional, default json): Sets the message 'Type' header to the specified value - strict (boolean, optional, default true): Should we assume that the entire payload is json parsable. When set to `false` non-json string in the payload are added to `_prefix` and `_postfix` fields respectively. *Example Heka Configuration* .. code-block:: ini [LogInput] type = "LogstreamerInput" log_directory = "/var/log" file_match = 'application\.json' decoder = "JsonDecoder" [JsonDecoder] type = "SandboxDecoder" filename = "lua_decoders/json_decoder.lua" [JsonDecoder.config] type = "json" strict = true --]] require "cjson" require "string" local msg_type = read_config("type") or 'json' local strict_parsing = read_config("strict") if strict_parsing == nil or strict_parsing == '' then strict_parsing = true end function process_message() local payload = read_message("Payload") local ok, json = pcall(cjson.decode, payload) if strict_parsing and not ok then return -1 elseif not ok then -- try parsing once more by stripping extra content on beg and end local json_start = string.find(payload, "{") local json_end = string.match(payload, '^.*()}') if json_start == nil or json_end == nil then return -1 end write_message("Fields[_prefix]", string.sub(payload, 0, json_start-1)) write_message("Fields[_postfix]", string.sub(payload, json_end+1)) ok, json = pcall(cjson.decode, string.sub(payload, json_start, json_end)) end if not ok then return -1 end if type(json) ~= "table" then return -1 end for k, v in pairs(json) do write_message("Fields[" .. k .. "]", v) end write_message("Type", msg_type) return 0 end
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Parses a payload containing JSON. Does not modify any Heka message attributes, only adds to the `Fields`. Config: - type (string, optional, default json): Sets the message 'Type' header to the specified value - strict (boolean, optional, default true): Should we assume that the entire payload is json parsable. When set to `false` non-json string in the payload are added to `_prefix` and `_postfix` fields respectively. *Example Heka Configuration* .. code-block:: ini [LogInput] type = "LogstreamerInput" log_directory = "/var/log" file_match = 'application\.json' decoder = "JsonDecoder" [JsonDecoder] type = "SandboxDecoder" filename = "lua_decoders/json_decoder.lua" [JsonDecoder.config] type = "json" strict = true --]] require "cjson" require "string" local msg_type = read_config("type") or 'json' local strict_parsing = read_config("strict") if strict_parsing == nil or strict_parsing == '' then strict_parsing = true end function process_message() local payload = read_message("Payload") local ok, json = pcall(cjson.decode, payload) local prefix = '' local postfix = '' if strict_parsing and not ok then return -1 elseif not ok then -- try parsing once more by stripping extra content on beg and end local json_start = string.find(payload, "{") local json_end = string.match(payload, '^.*()}') if json_start == nil or json_end == nil then return -1 end prefix = string.sub(payload, 0, json_start-1) postfix = string.sub(payload, json_end+1) ok, json = pcall(cjson.decode, string.sub(payload, json_start, json_end)) end if not ok then return -1 end if type(json) ~= "table" then return -1 end write_message("Fields[_prefix]", prefix) write_message("Fields[_postfix]", postfix) for k, v in pairs(json) do write_message("Fields[" .. k .. "]", v) end write_message("Type", msg_type) return 0 end
json_decoder don't write prefix/postfix unless json
json_decoder don't write prefix/postfix unless json
Lua
apache-2.0
wxdublin/heka-clever-plugins
80b8026094117934ff8b370f475a94e6c3cc6042
lua/lush_theme/jellybeans.lua
lua/lush_theme/jellybeans.lua
local lush = require('lush') local hsl = lush.hsl local jellybeans = require('lush_theme.jellybeans-nvim') local nice_red = "#ff5656" -- A nicer red, also from https://git.io/Jfs2T local spec = lush.extends({jellybeans}).with(function() return { -- Darker background for entire window Normal { fg = "#e8e8d3", bg = "#090909", }, -- Better colors for popup menus Pmenu { bg = "#303030", fg = "#D6D6D6" }, PmenuSel { bg = "#D6D6D6", fg = "#2B2B2B" }, CocErrorSign { fg = nice_red }, -- Treesitter TSMethod { fg = "#b0d0f0" }, TSConstructor { fg = "#fad07a" }, TSType { fg = "#fad07a" }, TSTagAttribute { fg = "#ffb964" }, TSConstBuiltin { jellybeans.Constant }, -- Git Signs GitSignsAdd { fg = "#70b950" }, GitSignsChange { fg = "#8fbfdc" }, GitSignsDelete { fg = nice_red }, } end) return spec
local lush = require('lush') local hsl = lush.hsl local jellybeans = require('lush_theme.jellybeans-nvim') local nice_red = "#ff5656" -- A nicer red, also from https://git.io/Jfs2T local spec = lush.extends({jellybeans}).with(function() return { -- Darker background for entire window Normal { fg = "#e8e8d3", bg = "#090909", }, -- Better colors for popup menus Pmenu { bg = "#202020", fg = "#D6D6D6" }, PmenuSel { bg = "#D6D6D6", fg = "#2B2B2B" }, CocErrorSign { fg = nice_red }, -- Treesitter TSTagAttribute { fg = "#ffb964" }, -- Fixes issue with template strings TSVariable { fg=Normal.fg }, -- Git Signs GitSignsAdd { fg = "#70b950" }, GitSignsChange { fg = "#8fbfdc" }, GitSignsDelete { fg = nice_red }, } end) return spec
fix: jellybeans template string variable highlighting
fix: jellybeans template string variable highlighting
Lua
mit
mutewinter/dot_vim,mutewinter/dot_vim
62db1cbbbd23430d5a6ee7136746e3e72f57f539
tests/proxymenu/proxymenu.lua
tests/proxymenu/proxymenu.lua
require "fmt" stead.proxy_prefix = '   ' local function proxy_wrap(nam, fwd) if not fwd then fwd = nam end return function(s, ...) local t local o = _(s.ref) local act = s.acts or { } act = act[nam] or nam local r, v = std.call(std.game, 'before_'..act, o, ...) t = std.par(std.scene_delim, t or false, r) if v == false then return t or r, true end if nam == 'use' then local oo = {...} oo = oo[1] if oo:type 'proxy' then oo = _(oo.ref) end r, v = std.call(oo, s.acts.used or 'used', o, ...) t = std.par(std.scene_delim, t or false, r) if v == true then oo['__nr_used'] = (oo['__nr_used'] or 0) + 1 return t or r, true end end r, v = std.call(o, act, ...) t = std.par(std.scene_delim, t or false, r) if type(v) == 'boolean' then o['__nr_'..act] = (o['__nr_'..act] or 0) + 1 end if r ~= nil and v == false then -- deny return t or r, true end if v then r, v = std.call(std.game, 'after_'..act, o, ...) t = std.par(std.scene_delim, t or false, r) end if not t then -- game action r, v = std.call(game, act, o, ...) t = std.par(std.scene_delim, t or false, r) end return t or r, true end end std.proxy_obj = std.class ({ __proxy_type = true; new = function(s, v) if type(v) ~= 'table' then std.err ("Wrong argument to std.proxy_obj: "..std.tostr(v), 2) end if not v.ref then std.err ("Wrong argument to std.proxy_obj (no ref attr): "..std.tostr(v), 2) end if v.use_mode then v.__menu_type = false end v = std.obj (v) return v end; disp = function(s) local o = _(s.ref) if have(o) then return stead.proxy_prefix..fmt.em(std.dispof(o)) end return stead.proxy_prefix..std.dispof(o) end; act = proxy_wrap ('act'); inv = proxy_wrap ('inv'); use = proxy_wrap ('use'); menu = proxy_wrap ('menu'); tak = proxy_wrap ('tak'); }, std.menu) local function fill_obj(v, s) if not v:visible() then return nil, false -- do not do it recurse end if not v:type 'menu' and not std.is_system(v) then -- usual objects -- add to proxy local o = { ref = std.nameof(v), use_mode = s.use_mode, sources = s.sources, acts = s.acts, } s.obj:add(new(proxy_obj, o)) end if v:closed() then return nil, false -- do not do it recurse end end std.proxy_menu = std.class ({ __proxy_menu_type = true; new = function(s, v) if type(v) ~= 'table' then std.err ("Wrong argument to std.proxy_obj: "..std.tostr(v), 2) end if v.disp then v.title = v.disp v.disp = nil end return std.menu(v) end; disp = function(s) local d if s.title then d = std.call(s, 'title') else d = std.dispof(s) end -- s:fill() if not s:closed() then return fmt.u(fmt.b(fmt.nb(d))) else return fmt.b(fmt.nb(d)) end end; menu = function(s) -- open/close if not s:closed() then s:close() else std.me().obj:for_each(function (v) if v:type 'proxy_menu' and v ~= s then v:close() end end) s:open() end return false end; fill = function(s) -- fill prox s:for_each(function(v) delete(v) -- delete obj end) s.obj:zap() -- by default -- all obj local src = s.sources or { scene = true } if src.inv then me():inventory():for_each(function(v) fill_obj(v, s) end) end if src.scene then std.here():for_each(function(v) return fill_obj(v, s) end) end if src.ways then std.here().way:for_each(function(v) fill_obj(v, s) end) end end; }, std.menu) std.menu_player = std.class ({ __menu_player_type = true; new = function(self, v) if type(v) ~= 'table' then std.err ("Wrong argument to std.menu_player: "..std.tostr(v), 2) end if not v.nam then v.nam = 'menu_player' end if not v.room then v.room = 'main' end v.invent = std.list {} return std.player(v) end; inventory = function(s) return s.invent end; }, std.player) function proxy_obj(v) local vv = { ref = v.ref; use_mode = v.use_mode; sources = v.sources; acts = v.acts; } return std.proxy_obj(vv) end function proxy_menu(v) local vv = { nam = v.nam; disp = v.disp; use_mode = v.use_mode; sources = v.sources; acts = v.acts; } return std.proxy_menu(vv):close() end std.mod_init(function() -- declarations declare 'proxy_obj' (proxy_obj) declare 'proxy_menu' (proxy_menu) end) std.mod_step(function() me().obj:for_each(function(v) if v:type 'proxy_menu' then v:fill() end end) end)
require "fmt" stead.proxy_prefix = '   ' local function proxy_wrap(nam, fwd) if not fwd then fwd = nam end return function(s, ...) local t local o = _(s.ref) local act = s.acts or { } act = act[nam] or nam local r, v = std.call(std.game, 'before_'..act, o, ...) t = std.par(std.scene_delim, t or false, r) if v == false then return t or r, true end if nam == 'use' then local oo = {...} oo = oo[1] if oo:type 'proxy' then oo = _(oo.ref) end r, v = std.call(oo, s.acts.used or 'used', o) t = std.par(std.scene_delim, t or false, r) if v == true then oo['__nr_used'] = (oo['__nr_used'] or 0) + 1 return t or r, true end r, v = std.call(o, act, oo) else r, v = std.call(o, act, ...) end t = std.par(std.scene_delim, t or false, r) if type(v) == 'boolean' then o['__nr_'..act] = (o['__nr_'..act] or 0) + 1 end if r ~= nil and v == false then -- deny return t or r, true end if v then r, v = std.call(std.game, 'after_'..act, o, ...) t = std.par(std.scene_delim, t or false, r) end if not t then -- game action r, v = std.call(game, act, o, ...) t = std.par(std.scene_delim, t or false, r) end return t or r, true end end std.proxy_obj = std.class ({ __proxy_type = true; new = function(s, v) if type(v) ~= 'table' then std.err ("Wrong argument to std.proxy_obj: "..std.tostr(v), 2) end if not v.ref then std.err ("Wrong argument to std.proxy_obj (no ref attr): "..std.tostr(v), 2) end if v.use_mode then v.__menu_type = false end v = std.obj (v) return v end; disp = function(s) local o = _(s.ref) if have(o) then return stead.proxy_prefix..fmt.em(std.dispof(o)) end return stead.proxy_prefix..std.dispof(o) end; act = proxy_wrap ('act'); inv = proxy_wrap ('inv'); use = proxy_wrap ('use'); menu = proxy_wrap ('menu'); tak = proxy_wrap ('tak'); }, std.menu) local function fill_obj(v, s) if not v:visible() then return nil, false -- do not do it recurse end if not v:type 'menu' and not std.is_system(v) then -- usual objects -- add to proxy local o = { ref = std.nameof(v), use_mode = s.use_mode, sources = s.sources, acts = s.acts, } s.obj:add(new(proxy_obj, o)) end if v:closed() then return nil, false -- do not do it recurse end end std.proxy_menu = std.class ({ __proxy_menu_type = true; new = function(s, v) if type(v) ~= 'table' then std.err ("Wrong argument to std.proxy_obj: "..std.tostr(v), 2) end if v.disp then v.title = v.disp v.disp = nil end return std.menu(v) end; disp = function(s) local d if s.title then d = std.call(s, 'title') else d = std.dispof(s) end -- s:fill() if not s:closed() then return fmt.u(fmt.b(fmt.nb(d))) else return fmt.b(fmt.nb(d)) end end; menu = function(s) -- open/close if not s:closed() then s:close() else std.me().obj:for_each(function (v) if v:type 'proxy_menu' and v ~= s then v:close() end end) s:open() end return false end; fill = function(s) -- fill prox s:for_each(function(v) delete(v) -- delete obj end) s.obj:zap() -- by default -- all obj local src = s.sources or { scene = true } if src.inv then me():inventory():for_each(function(v) fill_obj(v, s) end) end if src.scene then std.here():for_each(function(v) return fill_obj(v, s) end) end if src.ways then std.here().way:for_each(function(v) fill_obj(v, s) end) end end; }, std.menu) std.menu_player = std.class ({ __menu_player_type = true; new = function(self, v) if type(v) ~= 'table' then std.err ("Wrong argument to std.menu_player: "..std.tostr(v), 2) end if not v.nam then v.nam = 'menu_player' end if not v.room then v.room = 'main' end v.invent = std.list {} return std.player(v) end; inventory = function(s) return s.invent end; }, std.player) function proxy_obj(v) local vv = { ref = v.ref; use_mode = v.use_mode; sources = v.sources; acts = v.acts; } return std.proxy_obj(vv) end function proxy_menu(v) local vv = { nam = v.nam; disp = v.disp; use_mode = v.use_mode; sources = v.sources; acts = v.acts; } return std.proxy_menu(vv):close() end std.mod_init(function() -- declarations declare 'proxy_obj' (proxy_obj) declare 'proxy_menu' (proxy_menu) end) std.mod_step(function() me().obj:for_each(function(v) if v:type 'proxy_menu' then v:fill() end end) end)
use/used proxymenu fix
use/used proxymenu fix
Lua
mit
gl00my/stead3
6d5a0d751f218747d78fca7ce686158f7262ea34
plugins/get.lua
plugins/get.lua
local function get_variables_hash(msg, global) if global then if not redis:get(msg.to.id .. ':gvariables') then return 'gvariables' end return false else if msg.to.type == 'channel' then return 'channel:' .. msg.to.id .. ':variables' end if msg.to.type == 'chat' then return 'chat:' .. msg.to.id .. ':variables' end if msg.to.type == 'user' then return 'user:' .. msg.from.id .. ':variables' end return false end end local function get_value(msg, var_name) var_name = var_name:gsub(' ', '_') if not redis:get(msg.to.id .. ':gvariables') then local hash = get_variables_hash(msg, true) if hash then local value = redis:hget(hash, var_name) if value then return value end end end local hash = get_variables_hash(msg, false) if hash then local value = redis:hget(hash, var_name) if value then return value end end end local function list_variables(msg, global) local hash = nil if global then hash = get_variables_hash(msg, true) else hash = get_variables_hash(msg, false) end if hash then local names = redis:hkeys(hash) local text = '' for i = 1, #names do text = text .. names[i]:gsub('_', ' ') .. '\n' end return text end end local function run(msg, matches) if (matches[1]:lower() == 'get' or matches[1]:lower() == 'getlist' or matches[1]:lower() == 'sasha lista') then return list_variables(msg, false) end if (matches[1]:lower() == 'getglobal' or matches[1]:lower() == 'getgloballist' or matches[1]:lower() == 'sasha lista globali') then return list_variables(msg, true) end if matches[1]:lower() == 'enableglobal' then redis:del(msg.to.id .. ':gvariables') return lang_text('globalEnable') end if matches[1]:lower() == 'disableglobal' then redis:set(msg.to.id .. ':gvariables', true) return lang_text('globalDisable') end end local function pre_process(msg, matches) if msg.text then if not string.match(msg.text, "^[#!/][Uu][Nn][Ss][Ee][Tt] ([^%s]+)") and not string.match(msg.text, "^[Uu][Nn][Ss][Ee][Tt][Tt][Aa] ([^%s]+)") and not string.match(msg.text, "^[Ss][Aa][Ss][Hh][Aa] [Uu][Nn][Ss][Ee][Tt][Tt][Aa] ([^%s]+)") and not string.match(msg.text, "^[Uu][Nn][Ss][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll] ([^%s]+)") then local vars = list_variables(msg, true) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local temp = word:lower() if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then local value = get_value(msg, word:lower()) if value then reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false) end end end end local vars = list_variables(msg, false) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local temp = word:lower() if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then local value = get_value(msg, word:lower()) if value then if not string.match(value, "^(.*)user%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)chat%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)channel%.(%d+)%.variables(.*)$") then -- if not media reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false) elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.jpg$") then -- if picture if io.popen('find ' .. value):read("*all") ~= '' then send_photo(get_receiver(msg), value, ok_cb, false) end elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.ogg$") then -- if audio if io.popen('find ' .. value):read("*all") ~= '' then send_audio(get_receiver(msg), value, ok_cb, false) end end end end end end end end return msg end return { description = "GET", patterns = { "^[#!/]([Gg][Ee][Tt][Ll][Ii][Ss][Tt])$", "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll][Ll][Ii][Ss][Tt])$", "^[#!/]([Ee][Nn][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", "^[#!/]([Dd][Ii][Ss][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", -- getlist "^[#!/]([Gg][Ee][Tt])$", "^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa])$", -- getgloballist "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll])$", "^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa] [Gg][Ll][Oo][Bb][Aa][Ll][Ii])$", }, pre_process = pre_process, run = run, min_rank = 0 -- usage -- (#getlist|#get|sasha lista) -- (#getgloballist|#getglobal|sasha lista globali) -- OWNER -- #enableglobal -- #disableglobal }
local function get_variables_hash(msg, global) if global then if not redis:get(msg.to.id .. ':gvariables') then return 'gvariables' end return false else if msg.to.type == 'channel' then return 'channel:' .. msg.to.id .. ':variables' end if msg.to.type == 'chat' then return 'chat:' .. msg.to.id .. ':variables' end if msg.to.type == 'user' then return 'user:' .. msg.from.id .. ':variables' end return false end end local function get_value(msg, var_name) var_name = var_name:gsub(' ', '_') if not redis:get(msg.to.id .. ':gvariables') then local hash = get_variables_hash(msg, true) if hash then local value = redis:hget(hash, var_name) if value then return value end end end local hash = get_variables_hash(msg, false) if hash then local value = redis:hget(hash, var_name) if value then return value end end end local function list_variables(msg, global) local hash = nil if global then hash = get_variables_hash(msg, true) else hash = get_variables_hash(msg, false) end if hash then local names = redis:hkeys(hash) local text = '' for i = 1, #names do text = text .. names[i]:gsub('_', ' ') .. '\n' end return text end end local function run(msg, matches) if (matches[1]:lower() == 'get' or matches[1]:lower() == 'getlist' or matches[1]:lower() == 'sasha lista') then return list_variables(msg, false) end if (matches[1]:lower() == 'getglobal' or matches[1]:lower() == 'getgloballist' or matches[1]:lower() == 'sasha lista globali') then return list_variables(msg, true) end if is_owner(msg) then if matches[1]:lower() == 'enableglobal' then redis:del(msg.to.id .. ':gvariables') return lang_text('globalEnable') end if matches[1]:lower() == 'disableglobal' then redis:set(msg.to.id .. ':gvariables', true) return lang_text('globalDisable') end else return lang_text('require_owner') end end local function pre_process(msg, matches) if msg.text then if not string.match(msg.text, "^[#!/][Uu][Nn][Ss][Ee][Tt] ([^%s]+)") and not string.match(msg.text, "^[Uu][Nn][Ss][Ee][Tt][Tt][Aa] ([^%s]+)") and not string.match(msg.text, "^[Ss][Aa][Ss][Hh][Aa] [Uu][Nn][Ss][Ee][Tt][Tt][Aa] ([^%s]+)") and not string.match(msg.text, "^[Uu][Nn][Ss][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll] ([^%s]+)") then local vars = list_variables(msg, true) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local temp = word:lower() if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then local value = get_value(msg, word:lower()) if value then reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false) end end end end local vars = list_variables(msg, false) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local temp = word:lower() if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then local value = get_value(msg, word:lower()) if value then if not string.match(value, "^(.*)user%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)chat%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)channel%.(%d+)%.variables(.*)$") then -- if not media reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false) elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.jpg$") then -- if picture if io.popen('find ' .. value):read("*all") ~= '' then send_photo(get_receiver(msg), value, ok_cb, false) end elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.ogg$") then -- if audio if io.popen('find ' .. value):read("*all") ~= '' then send_audio(get_receiver(msg), value, ok_cb, false) end end end end end end end end return msg end return { description = "GET", patterns = { "^[#!/]([Gg][Ee][Tt][Ll][Ii][Ss][Tt])$", "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll][Ll][Ii][Ss][Tt])$", "^[#!/]([Ee][Nn][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", "^[#!/]([Dd][Ii][Ss][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", -- getlist "^[#!/]([Gg][Ee][Tt])$", "^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa])$", -- getgloballist "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll])$", "^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa] [Gg][Ll][Oo][Bb][Aa][Ll][Ii])$", }, pre_process = pre_process, run = run, min_rank = 0 -- usage -- (#getlist|#get|sasha lista) -- (#getgloballist|#getglobal|sasha lista globali) -- OWNER -- #enableglobal -- #disableglobal }
fix permissions
fix permissions
Lua
agpl-3.0
xsolinsx/AISasha
124ddbc0aa5e67673763e17c83158734683208ea
nodeMCU/run.lua
nodeMCU/run.lua
local wifiConfig = {} wifiConfig.staticIp = {} local passcode = nil if(file.open("config", "r") ~= nil) then local function read () local buf = file.readline() if(buf ~= nil) then buf = string.gsub(buf, "\n", "") else buf = "" end return buf end wifiConfig.ssid = read().."" wifiConfig.ssidPassword = read().."" wifiConfig.staticIp.ip = read().."" wifiConfig.staticIp.netmask = read().."" wifiConfig.staticIp.gateway = read().."" local tmp = read() if(tmp ~= nil and tmp ~= "") then passcode = tmp end tmp = nil print("-- CONFIGURATION --") print("SSID: " .. wifiConfig.ssid) print("Password: *****") -- .. wifiConfig.ssidPassword) print("IP: " .. wifiConfig.staticIp.ip) print("Netmask: " .. wifiConfig.staticIp.netmask) print("Gateway: " .. wifiConfig.staticIp.gateway) print("-- END CONFIGURATION --") file.close() collectgarbage() else node.restart() end -- Lamp setup local lamp = {} lamp.pin = 4 lamp.status = 1 gpio.mode(lamp.pin, gpio.OUTPUT) gpio.write(lamp.pin, gpio.LOW) local function connect(conn) conn:on ("receive", function (conn, request) local buf = "" local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP") if(method == nil)then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP") end local _GET = {} if (vars ~= nil) then _GET = parsevars(vars) end if(passcode ~= nil and passcode ~= _GET.passcode) then if(_GET.app == "1") then buf = buf.."HTTP/1.1 403\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf.."PASSCODE INCORRECT" else buf = buf.."HTTP/1.1 200\r\nServer: WiFi Relay\r\nContent-Type: text/html\r\n\r\n<html>" buf = buf.."Passcode incorrect, enter one now:<br>" buf = buf.."<form action=\"/\" method=\"get\">" buf = buf.."Passcode:<br><input type=\"text\" name=\"passcode\">" buf = buf.."<input type=\"submit\" value=\"Submit\">" buf = buf.."</form>" end conn:send(buf) conn:close() return end if(_GET.light == "0" or _GET.pin == "OFF") then gpio.write(lamp.pin, gpio.HIGH) lamp.status = 0 elseif(_GET.light == "1" or _GET.pin == "ON") then gpio.write(lamp.pin, gpio.LOW) lamp.status = 1 end if(_GET.factoryreset == "1") then file.remove("config") buf = buf.."HTTP/1.1 200 OK\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf.."1" conn:send(buf) conn:close() tmr.alarm(2, 2000, 0, function() node.restart() end) elseif(_GET.update == "1") then if(_GET.ssid ~= nil) then wifiConfig.ssid = _GET.ssid end if(_GET.pwd ~= nil) then wifiConfig.ssidPassword = _GET.pwd end if(_GET.ip ~= nil) then wifiConfig.staticIp.ip = _GET.ip end if(_GET.netmask ~= nil) then wifiConfig.staticIp.netmask = _GET.netmask end if(_GET.gateway ~= nil) then wifiConfig.staticIp.gateway = _GET.gateway end if(_GET.changePasscode ~= nil) then passcode = _GET.changePasscode end writeConfig(wifiConfig.ssid, wifiConfig.ssidPassword, wifiConfig.staticIp.ip, wifiConfig.staticIp.netmask, wifiConfig.staticIp.gateway, passcode) buf = buf.."HTTP/1.1 200 OK\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf.."1" conn:send(buf) conn:close() tmr.alarm(2, 2000, 0, function() node.restart() end) elseif(_GET.status == "1") then buf = buf.."HTTP/1.1 200 OK\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf..lamp.status conn:send(buf) conn:close() elseif(_GET.ota ~= nil) then if(update(_GET.ota, _GET.otaURL, conn, _GET.restart) == false) then buf = buf.."HTTP/1.1 500\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf.."0" buf = buf.."\nBROKEN URL" conn:send(buf) conn:close() end else buf = buf.."HTTP/1.1 200 OK\r\nServer: WiFi Relay\r\nContent-Type: text/html\r\n\r\n<html>" buf = buf.."<h1> ESP8266 Web Server</h1>" buf = buf.."<p>LAMP <a href=\"?passcode="..passcode.."&pin=ON\"><button>ON</button></a>&nbsp;<a href=\"?passcode="..passcode.."&pin=OFF\"><button>OFF</button></a></p>" buf = buf.."<p>LAMP is <font color=" if(lamp.status == 1) then buf = buf.."\"green\">ON" else buf = buf.."\"red\">OFF" end buf = buf.."</font></p>" buf = buf.."</html>" conn:send(buf) conn:close() end buf = nil collectgarbage() end) end wifi.setmode(wifi.STATION) wifi.sta.config(wifiConfig.ssid, wifiConfig.ssidPassword) wifi.sta.setip(wifiConfig.staticIp) function check_wifi() wifi.sta.connect() local ip = wifi.sta.getip() if(ip==nil) then print("Connecting...") else tmr.stop(1) print("IP: " .. wifi.sta.getip()) local svr = net.createServer(net.TCP) svr:listen(80, connect) gpio.mode(gpio1, gpio.OUTPUT) gpio.write(gpio1, gpio.LOW) end collectgarbage() end tmr.alarm(1,3000,1,check_wifi)
local wifiConfig = {} wifiConfig.staticIp = {} local passcode = nil if(file.open("config", "r") ~= nil) then local function read () local buf = file.readline() if(buf ~= nil) then buf = string.gsub(buf, "\n", "") else buf = "" end return buf end wifiConfig.ssid = read().."" wifiConfig.ssidPassword = read().."" wifiConfig.staticIp.ip = read().."" wifiConfig.staticIp.netmask = read().."" wifiConfig.staticIp.gateway = read().."" local tmp = read() if(tmp ~= nil and tmp ~= "") then passcode = tmp end tmp = nil print("-- CONFIGURATION --") print("SSID: " .. wifiConfig.ssid) print("Password: *****") -- .. wifiConfig.ssidPassword) print("IP: " .. wifiConfig.staticIp.ip) print("Netmask: " .. wifiConfig.staticIp.netmask) print("Gateway: " .. wifiConfig.staticIp.gateway) if(passcode ~= nil and passcode ~= "") then print("Passcode: Yes") else print("Passcode: No") end print("-- END CONFIGURATION --") file.close() collectgarbage() else node.restart() end -- Lamp setup local lamp = {} lamp.pin = 4 lamp.status = 1 gpio.mode(lamp.pin, gpio.OUTPUT) gpio.write(lamp.pin, gpio.LOW) local function connect(conn) conn:on ("receive", function (conn, request) local buf = "" local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP") if(method == nil)then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP") end local _GET = {} if (vars ~= nil) then _GET = parsevars(vars) end if(passcode ~= nil and passcode ~= _GET.passcode) then if(_GET.app == "1") then buf = buf.."HTTP/1.1 403\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf.."PASSCODE INCORRECT" else buf = buf.."HTTP/1.1 200\r\nServer: WiFi Relay\r\nContent-Type: text/html\r\n\r\n<html>" buf = buf.."Passcode incorrect, enter one now:<br>" buf = buf.."<form action=\"/\" method=\"get\">" buf = buf.."Passcode:<br><input type=\"text\" name=\"passcode\">" buf = buf.."<input type=\"submit\" value=\"Submit\">" buf = buf.."</form>" end conn:send(buf) conn:close() return end if(_GET.light == "0" or _GET.pin == "OFF") then gpio.write(lamp.pin, gpio.HIGH) lamp.status = 0 elseif(_GET.light == "1" or _GET.pin == "ON") then gpio.write(lamp.pin, gpio.LOW) lamp.status = 1 end if(_GET.factoryreset == "1") then file.remove("config") buf = buf.."HTTP/1.1 200 OK\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf.."1" conn:send(buf) conn:close() tmr.alarm(2, 2000, 0, function() node.restart() end) elseif(_GET.update == "1") then if(_GET.ssid ~= nil) then wifiConfig.ssid = _GET.ssid end if(_GET.pwd ~= nil) then wifiConfig.ssidPassword = _GET.pwd end if(_GET.ip ~= nil) then wifiConfig.staticIp.ip = _GET.ip end if(_GET.netmask ~= nil) then wifiConfig.staticIp.netmask = _GET.netmask end if(_GET.gateway ~= nil) then wifiConfig.staticIp.gateway = _GET.gateway end if(_GET.changePasscode ~= nil) then if(_GET.changePasscode == "") then passcode = nil else passcode = _GET.changePasscode end end writeConfig(wifiConfig.ssid, wifiConfig.ssidPassword, wifiConfig.staticIp.ip, wifiConfig.staticIp.netmask, wifiConfig.staticIp.gateway, passcode) buf = buf.."HTTP/1.1 200 OK\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf.."1" conn:send(buf) conn:close() tmr.alarm(2, 2000, 0, function() node.restart() end) elseif(_GET.status == "1") then buf = buf.."HTTP/1.1 200 OK\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf..lamp.status conn:send(buf) conn:close() elseif(_GET.ota ~= nil) then if(update(_GET.ota, _GET.otaURL, conn, _GET.restart) == false) then buf = buf.."HTTP/1.1 500\r\nServer: WiFi Relay\r\nContent-Type: text/plain\r\n\r\n" buf = buf.."0" buf = buf.."\nBROKEN URL" conn:send(buf) conn:close() end else buf = buf.."HTTP/1.1 200 OK\r\nServer: WiFi Relay\r\nContent-Type: text/html\r\n\r\n<html>" buf = buf.."<h1> ESP8266 Web Server</h1>" buf = buf.."<p>LAMP <a href=\"?" if(pascode ~= nil) then buf = buf.."passcode="..passcode.."&" end buf = buf.."pin=ON\"><button>ON</button></a>&nbsp;<a href=\"?" if(pascode ~= nil) then buf = buf.."passcode="..passcode.."&" end buf = buf.."pin=OFF\"><button>OFF</button></a></p>" buf = buf.."<p>LAMP is <font color=" if(lamp.status == 1) then buf = buf.."\"green\">ON" else buf = buf.."\"red\">OFF" end buf = buf.."</font></p>" buf = buf.."</html>" conn:send(buf) conn:close() end buf = nil collectgarbage() end) end wifi.setmode(wifi.STATION) wifi.sta.config(wifiConfig.ssid, wifiConfig.ssidPassword) wifi.sta.setip(wifiConfig.staticIp) function check_wifi() wifi.sta.connect() local ip = wifi.sta.getip() if(ip==nil) then print("Connecting...") else tmr.stop(1) print("IP: " .. wifi.sta.getip()) local svr = net.createServer(net.TCP) svr:listen(80, connect) gpio.mode(gpio1, gpio.OUTPUT) gpio.write(gpio1, gpio.LOW) end collectgarbage() end tmr.alarm(1,3000,1,check_wifi)
Fix passcode bug
Fix passcode bug Chip won't crash when there is no passcode set.
Lua
mit
aschmois/WebTimer,aschmois/WebTimer
52e8949932c4913f1744277b8550423037ef9e3f
plugins/set.lua
plugins/set.lua
local function get_variables_hash(msg, global) if global then return 'gvariables' else if msg.to.type == 'channel' then return 'channel:' .. msg.to.id .. ':variables' end if msg.to.type == 'chat' then return 'chat:' .. msg.to.id .. ':variables' end if msg.to.type == 'user' then return 'user:' .. msg.from.id .. ':variables' end return false end end local function set_value(msg, name, value, global) if (not name or not value) then return lang_text('errorTryAgain') end local hash = get_variables_hash(msg, global) if hash then redis:hset(hash, name, value) if global then return name .. lang_text('gSaved') else return name .. lang_text('saved') end end end local function set_media(msg, name) if not name then return lang_text('errorTryAgain') end local hash = get_variables_hash(msg) if hash then redis:hset(hash, 'waiting', name) return lang_text('sendMedia') end end local function callback(extra, success, result) if success and result then local file if extra.media == 'photo' then file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.jpg' elseif extra.media == 'audio' then file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.ogg' end file = file:gsub(':', '.') print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) redis:hset(extra.hash, extra.name, file) redis:hdel(extra.hash, 'waiting') print(file) send_large_msg(extra.receiver, lang_text('mediaSaved')) else send_large_msg(extra.receiver, lang_text('errorDownloading') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver) end end local function run(msg, matches) local hash = get_variables_hash(msg, false) if msg.media then if hash then local name = redis:hget(hash, 'waiting') if name then if is_momod(msg) then if msg.media.type == 'photo' then return load_photo(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type }) elseif msg.media.type == 'audio' then return load_document(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type }) end else return lang_text('require_mod') end end return else return lang_text('nothingToSet') end end if matches[1]:lower() == 'cancel' or matches[1]:lower() == 'sasha annulla' or matches[1]:lower() == 'annulla' then if is_momod(msg) then redis:hdel(hash, 'waiting') return lang_text('cancelled') else return lang_text('require_mod') end elseif matches[1]:lower() == 'setmedia' or matches[1]:lower() == 'sasha setta media' or matches[1]:lower() == 'setta media' then if is_momod(msg) then local name = string.sub(matches[2]:lower(), 1, 50) return set_media(msg, name) else return lang_text('require_mod') end elseif matches[1]:lower() == 'set' or matches[1]:lower() == 'sasha setta' or matches[1]:lower() == 'setta' then if string.match(matches[3], '[Aa][Uu][Tt][Oo][Ee][Xx][Ee][Cc]') then return lang_text('autoexecDenial') end if is_momod(msg) then local name = string.sub(matches[2]:lower(), 1, 50) local value = string.sub(matches[3], 1, 4096) return set_value(msg, name, value, false) else return lang_text('require_mod') end elseif matches[1]:lower() == 'setglobal' then if string.match(matches[3], '[Aa][Uu][Tt][Oo][Ee][Xx][Ee][Cc]') then return lang_text('autoexecDenial') end if is_admin1(msg) then return set_value(msg, name, value, true) else return lang_text('require_admin') end end end return { description = "SET", patterns = { "^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$", "^[#!/]([Ss][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll]) ([^%s]+) (.+)$", "^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", "^[#!/]([Cc][Aa][Nn][Cc][Ee][Ll])$", "%[(photo)%]", "%[(audio)%]", -- set "^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$", "^([Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$", -- setmedia "^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", "^([Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", -- cancel "^([Ss][Aa][Ss][Hh][Aa] [Aa][Nn][Nn][Uu][Ll][Ll][Aa])$", "^([Aa][Nn][Nn][Uu][Ll][Ll][Aa])$", }, run = run, min_rank = 1 -- usage -- MOD -- (#set|[sasha] setta) <var_name> <text> -- (#setmedia|[sasha] setta media) <var_name> -- (#cancel|[sasha] annulla) -- ADMIN -- #setglobal <var_name> <text> }
local function get_variables_hash(msg, global) if global then return 'gvariables' else if msg.to.type == 'channel' then return 'channel:' .. msg.to.id .. ':variables' end if msg.to.type == 'chat' then return 'chat:' .. msg.to.id .. ':variables' end if msg.to.type == 'user' then return 'user:' .. msg.from.id .. ':variables' end return false end end local function set_value(msg, name, value, global) if (not name or not value) then return lang_text('errorTryAgain') end local hash = get_variables_hash(msg, global) if hash then redis:hset(hash, name, value) if global then return name .. lang_text('gSaved') else return name .. lang_text('saved') end end end local function set_media(msg, name) if not name then return lang_text('errorTryAgain') end local hash = get_variables_hash(msg) if hash then redis:hset(hash, 'waiting', name) return lang_text('sendMedia') end end local function callback(extra, success, result) if success and result then local file if extra.media == 'photo' then file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.jpg' elseif extra.media == 'audio' then file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.ogg' end file = file:gsub(':', '.') print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) redis:hset(extra.hash, extra.name, file) redis:hdel(extra.hash, 'waiting') print(file) send_large_msg(extra.receiver, lang_text('mediaSaved')) else send_large_msg(extra.receiver, lang_text('errorDownloading') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver) end end local function run(msg, matches) local hash = get_variables_hash(msg, false) if msg.media then if hash then local name = redis:hget(hash, 'waiting') if name then if is_momod(msg) then if msg.media.type == 'photo' then return load_photo(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type }) elseif msg.media.type == 'audio' then return load_document(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type }) end else return lang_text('require_mod') end end return else return lang_text('nothingToSet') end end if matches[1]:lower() == 'cancel' or matches[1]:lower() == 'sasha annulla' or matches[1]:lower() == 'annulla' then if is_momod(msg) then redis:hdel(hash, 'waiting') return lang_text('cancelled') else return lang_text('require_mod') end elseif matches[1]:lower() == 'setmedia' or matches[1]:lower() == 'sasha setta media' or matches[1]:lower() == 'setta media' then if is_momod(msg) then local name = string.sub(matches[2]:lower(), 1, 50) return set_media(msg, name) else return lang_text('require_mod') end elseif matches[1]:lower() == 'set' or matches[1]:lower() == 'sasha setta' or matches[1]:lower() == 'setta' then if string.match(matches[3], '[Aa][Uu][Tt][Oo][Ee][Xx][Ee][Cc]') then return lang_text('autoexecDenial') end if is_momod(msg) then local name = string.sub(matches[2]:lower(), 1, 50) local value = string.sub(matches[3], 1, 4096) return set_value(msg, name, value, false) else return lang_text('require_mod') end elseif matches[1]:lower() == 'setglobal' then if string.match(matches[3], '[Aa][Uu][Tt][Oo][Ee][Xx][Ee][Cc]') then return lang_text('autoexecDenial') end if is_admin1(msg) then local name = string.sub(matches[2]:lower(), 1, 50) local value = string.sub(matches[3], 1, 4096) return set_value(msg, name, value, true) else return lang_text('require_admin') end end end return { description = "SET", patterns = { "^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$", "^[#!/]([Ss][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll]) ([^%s]+) (.+)$", "^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", "^[#!/]([Cc][Aa][Nn][Cc][Ee][Ll])$", "%[(photo)%]", "%[(audio)%]", -- set "^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$", "^([Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$", -- setmedia "^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", "^([Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", -- cancel "^([Ss][Aa][Ss][Hh][Aa] [Aa][Nn][Nn][Uu][Ll][Ll][Aa])$", "^([Aa][Nn][Nn][Uu][Ll][Ll][Aa])$", }, run = run, min_rank = 1 -- usage -- MOD -- (#set|[sasha] setta) <var_name> <text> -- (#setmedia|[sasha] setta media) <var_name> -- (#cancel|[sasha] annulla) -- ADMIN -- #setglobal <var_name> <text> }
fix setglobal
fix setglobal
Lua
agpl-3.0
xsolinsx/AISasha
2ff1c56d8e13dcc17b55c084c49561f66a6b9153
examples/perf2/thr/remote_thr.lua
examples/perf2/thr/remote_thr.lua
local ZMQ_NAME = "lzmq" local argc = select("#", ...) local argv = {...} if (argc < 3) or (argc > 4)then print("usage: remote_thr <connect-to> <message-size> <message-count> [ffi]"); return 1 end local connect_to = argv [1] local message_size = assert(tonumber(argv [2])) local message_count = assert(tonumber(argv [3])) if argv [4] then assert(argv [4] == 'ffi') ZMQ_NAME = "lzmq.ffi" end local zmq = require(ZMQ_NAME) local zthreads = require(ZMQ_NAME .. ".threads") local zassert = zmq.assert local ctx = zthreads.get_parent_ctx() or zassert(zmq.context()) local s = zassert(ctx:socket{zmq.PUSH, -- Add your socket options here. -- For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. sndhwm = message_count + 1; connect = connect_to; }) local msg = zassert(zmq.msg_init_data( ("0"):rep(message_size) )) local smsg = zassert(zmq.msg_init()) for i = 1, message_count do smsg:copy(msg) zassert(smsg:send(s)) end
local ZMQ_NAME = "lzmq" local argc = select("#", ...) local argv = {...} if (argc < 3) or (argc > 4)then print("usage: remote_thr <connect-to> <message-size> <message-count> [ffi]"); return 1 end local connect_to = argv [1] local message_size = assert(tonumber(argv [2])) local message_count = assert(tonumber(argv [3])) if argv [4] then assert(argv [4] == 'ffi') ZMQ_NAME = "lzmq.ffi" end local zmq = require(ZMQ_NAME) local zthreads = require(ZMQ_NAME .. ".threads") local zassert = zmq.assert local ctx = zthreads.get_parent_ctx() or zassert(zmq.context()) local s = zassert(ctx:socket{zmq.PUSH, -- Add your socket options here. -- For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. sndhwm = message_count + 1; connect = connect_to; }) local function version_1() -- here we create two messages. -- but zmq_msg_copy does not reallocate -- buffer but just copy reference and increment -- couter. So this version is much faseter then -- original version. local msg = zassert(zmq.msg_init_data( ("0"):rep(message_size) )) local smsg = zassert(zmq.msg_init()) for i = 1, message_count do smsg:copy(msg) zassert(smsg:send(s)) end end local function version_2() -- here we create one messages. -- msg:set_size create internal new zmq_msg_t -- each time but does not init memory. -- This is what do original version. -- The main impact for ffi version is callind -- ffi.gc each time we create new zmq_msg_t struct local msg = zmq.msg_init_size(message_size) for i = 1, message_count do zassert(msg:send(s)) msg:set_size(message_size) end end local function version_3() -- this is same as version_2 but we also copy data -- to message local data = ("o"):rep(message_size) local msg = zmq.msg_init_data(data) for i = 1, message_count do zassert(msg:send(s)) msg:set_data(data) end end version_2()
Fix. remote_thr now comparable with origin version.
Fix. remote_thr now comparable with origin version.
Lua
mit
zeromq/lzmq,moteus/lzmq,LuaDist/lzmq-ffi,LuaDist/lzmq-ffi,zeromq/lzmq,LuaDist/lzmq,bsn069/lzmq,zeromq/lzmq,moteus/lzmq,LuaDist/lzmq,bsn069/lzmq,moteus/lzmq
f60d48a3eacb15f1d2802a6a3635017984d46b8d
content/src/replace_txt_chunks.lua
content/src/replace_txt_chunks.lua
#!/usr/bin/env lua5.2 --[[ content/src/replace_txt_chunks.lua * ============================================================================ * Usage: * $ curl -O http://rgolubtsov.github.io/srcs/replace_txt_chunks.lua && \ chmod 700 replace_txt_chunks.lua && \ ./replace_txt_chunks.lua; echo $? * ============================================================================ * This is a demo script. It has to be run in the Lua 5.2 runtime environment. * Tested and known to run exactly the same way on modern versions * of OpenBSD/amd64, Ubuntu Server LTS x86-64, Arch Linux / Arch Linux 32 * operating systems. * * Create a function that will take a String value as the first parameter, * a Number value as the second parameter, and a String value as the third one. * The first parameter should be a sentence or a set of sentences, * the second parameter should be a positional number of a letter in each word * in the given sentence that should be replaced by the third parameter. * That function should return the updated sentence. * ============================================================================ * Copyright (C) 2018 Radislav (Radicchio) Golubtsov * * (See the LICENSE file at the top of the source tree.) --]] -- Helper constants. local EMPTY_STRING = "" local SPACE = " " local COMMA = "," local POINT = "." local NEW_LINE = "\n" local DBG_PREF = "==> " local SPACES = "%S+" local PP1 = "%(" local PP2 = "%)" local PA1 = "(" local PA2 = ")" local AB1 = "<" local AB2 = ">" -- The replace function. function replace(text, pos, subst) local text_ = EMPTY_STRING local text__ = EMPTY_STRING text= text:gsub(PP1, AB1) text= text:gsub(PP2, AB2) local text_ary = {} for i in text:gmatch(SPACES) do table.insert(text_ary, i) end local text_ary_len = #text_ary for i = 1, text_ary_len do local text_ary_i_len = #text_ary[i] -- print(DBG_PREF .. text_ary[i]) if ((pos <= text_ary_i_len) and (text_ary[i]:sub(pos) ~= COMMA) and (text_ary[i]:sub(pos) ~= POINT)) then text__ = text_ary[i] :gsub( text_ary[i]:sub(pos ), subst) .. text_ary[i]:sub(pos + 1) -- print(DBG_PREF .. text__ ) text_ = text_ .. text__ else -- print(DBG_PREF .. text_ary[i]) text_ = text_ .. text_ary[i] end text_ = text_ .. SPACE end text_= text_:gsub(AB1, PA1) return text_:gsub(AB2, PA2) end local text = EMPTY_STRING .. "A guard sequence is either a single guard or a series of guards, " .. "separated by semicolons (';'). The guard sequence 'G1; G2; ...; Gn' " .. "is true if at least one of the guards 'G1', 'G2', ..., 'Gn' " .. "evaluates to 'true'." .. EMPTY_STRING local pos = 3 -- <== Can be set to either from 1 to infinity. --local subst = "callable entity" --local subst = "AAA" --local subst = "+-=" local subst = "|" print(DBG_PREF .. pos ) print(DBG_PREF .. subst .. NEW_LINE) local text_ = replace(text, pos, subst) print(NEW_LINE .. DBG_PREF .. text ) print( DBG_PREF .. text_) -- vim:set nu et ts=4 sw=4:
#!/usr/bin/env lua5.2 --[[ content/src/replace_txt_chunks.lua * ============================================================================ * Usage: * $ curl -O http://rgolubtsov.github.io/srcs/replace_txt_chunks.lua && \ chmod 700 replace_txt_chunks.lua && \ ./replace_txt_chunks.lua; echo $? * ============================================================================ * This is a demo script. It has to be run in the Lua 5.2 runtime environment. * Tested and known to run exactly the same way on modern versions * of OpenBSD/amd64, Ubuntu Server LTS x86-64, Arch Linux / Arch Linux 32 * operating systems. * * Create a function that will take a String value as the first parameter, * a Number value as the second parameter, and a String value as the third one. * The first parameter should be a sentence or a set of sentences, * the second parameter should be a positional number of a letter in each word * in the given sentence that should be replaced by the third parameter. * That function should return the updated sentence. * ============================================================================ * Copyright (C) 2018 Radislav (Radicchio) Golubtsov * * (See the LICENSE file at the top of the source tree.) --]] -- Helper constants. local EMPTY_STRING = "" local SPACE = " " local COMMA = "," local POINT = "." local NEW_LINE = "\n" local DBG_PREF = "==> " local SPACES = "%S+" -- The replace function. function replace(text, pos, subst) local text_ = EMPTY_STRING local text__ = EMPTY_STRING local text_ary = {} for i in text:gmatch(SPACES) do table.insert(text_ary, i) end local text_ary_len = #text_ary for i = 1, text_ary_len do local text_ary_i_len = #text_ary[i] -- print(DBG_PREF .. text_ary[i]) if ((pos <= text_ary_i_len) and (text_ary[i]:sub(pos) ~= COMMA) and (text_ary[i]:sub(pos) ~= POINT)) then text__ = text_ary[i]:sub(1, pos - 1) .. subst .. text_ary[i]:sub( pos + 1) -- print(DBG_PREF .. text__ ) text_ = text_ .. text__ else -- print(DBG_PREF .. text_ary[i]) text_ = text_ .. text_ary[i] end text_ = text_ .. SPACE end return text_ end local text = EMPTY_STRING .. "A guard sequence is either a single guard or a series of guards, " .. "separated by semicolons (';'). The guard sequence 'G1; G2; ...; Gn' " .. "is true if at least one of the guards 'G1', 'G2', ..., 'Gn' " .. "evaluates to 'true'." .. EMPTY_STRING local pos = 3 -- <== Can be set to either from 1 to infinity. --local subst = "callable entity" --local subst = "AAA" --local subst = "+-=" local subst = "|" print(DBG_PREF .. pos ) print(DBG_PREF .. subst .. NEW_LINE) local text_ = replace(text, pos, subst) print(NEW_LINE .. DBG_PREF .. text ) print( DBG_PREF .. text_) -- vim:set nu et ts=4 sw=4:
Bugfix: Make no substitutions. Extract and concatenate substrings instead.
Bugfix: Make no substitutions. Extract and concatenate substrings instead.
Lua
mit
rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io
3cf21db95c31ee7bdc68099afa1ffa910ea941fe
scripts/mcp.lua
scripts/mcp.lua
require "const" local function create_start_points (self) local Distance = 10 local Space = 5 local Offset = math.modf (self.maxCycles / 4) + 1 local Ident = dmz.matrix.new () local HeadingPi = dmz.matrix.new (const.Up, dmz.math.Pi) local oddPos = { -(Space * Offset), 0, Distance } local evenPos = { -(Space * Offset) + (Space / 2), 0, -Distance } for ix = 1, self.maxCycles do local Odd = (1 == math.fmod (ix, 2)) local point = { index = ix, pos = (Odd and oddPos or evenPos), ori = (Odd and Ident or HeadingPi), handle = dmz.object.create (const.StartPointType), } self.startPoints[ix] = point dmz.object.position (point.handle, nil, point.pos) dmz.object.orientation (point.handle, nil, point.ori) dmz.object.activate (point.handle) dmz.object.set_temporary (point.handle) if Odd then oddPos[1] = oddPos[1] + Space else evenPos[1] = evenPos[1] + Space end end end local function assign_points_to_cycles (self) self.playerCount = 0 for object, cycle in pairs (self.cycleList) do if cycle.point then dmz.object.unlink_sub_links (cycle.point.handle, const.StartLinkHandle) cycle.point = nil elseif cycle.wait then end end local count = 1 for object, cycle in pairs (self.cycleList) do if count <= self.maxCycles then cycle.point = self.startPoints[count] dmz.object.link (const.StartLinkHandle, cycle.point.handle, object) self.playerCount = self.playerCount + 1 else end count = count + 1 end end local function get_standby_count (self) local result = 0 for object, cycle in pairs (self.cycleList) do if cycle.standby then result = result + 1 end end return result end local function get_dead_count (self) local result = 0 for object, cycle in pairs (self.cycleList) do if cycle.dead then result = result + 1 end end return result end local function set_game_state (mcp, State) local newState = dmz.object.state (mcp) newState:unset (const.GameStateMask) newState = newState + State dmz.object.state (mcp, nil, newState) end local function update_time_slice (self, time) local State = dmz.object.state (self.mcp) if State then local CTime = dmz.time.frame_time () if State:contains (const.GameWaiting) then if self.assignPoints then assign_points_to_cycles (self) self.assignPoints = false end if (get_standby_count (self) == self.playerCount) and (self.playerCount >= self.minCycles) then self.log:error ("Move to Countdown 5") set_game_state (self.mcp, const.GameCountdown5) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameActive) then if get_dead_count (self) >= (self.playerCount - 1) then set_game_state (self.mcp, const.GameWaiting) end elseif State:contains (const.GameCountdown5) then if CTime >= self.nextStateTime then self.log:error ("Move to Countdown 4") set_game_state (self.mcp, const.GameCountdown4) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameCountdown4) then if CTime >= self.nextStateTime then self.log:error ("Move to Countdown 3") set_game_state (self.mcp, const.GameCountdown3) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameCountdown3) then if CTime >= self.nextStateTime then self.log:error ("Move to Countdown 2") set_game_state (self.mcp, const.GameCountdown2) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameCountdown2) then if CTime >= self.nextStateTime then self.log:error ("Move to Countdown 1") set_game_state (self.mcp, const.GameCountdown1) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameCountdown1) then if CTime >= self.nextStateTime then self.log:error ("Move to Active") set_game_state (self.mcp, const.GameActive) self.nextStateTime = CTime + 1 end else self.log.error ("Game in unknown state. Changing to a waiting state") set_game_state (self.mcp, const.GameWaiting) end end end local function create_object (self, Object, Type) if Type:is_of_type (const.CycleType) then self.cycleList[Object] = {} self.cycleCount = self.cycleCount + 1 self.assignPoints = true end end local function destroy_object (self, Object) local cycle = self.cycleList[Object] if cycle then self.cycleList[Object] = nil self.cycleCount = self.cycleCount - 1 if cycle.point then self.playerCount = self.playerCount - 1 end self.assignPoints = true end end local function update_object_state (self, Object, Attribute, State, PreviousState) local cycle = self.cycleList[Object] if cycle then if not PreviousState then PreviousState = const.EmptyState end if State:contains (const.Dead) and not PreviousState:contains (const.Dead) then cycle.dead = true cycle.standby = false elseif State:contains (const.Standby) and not PreviousState:contains (const.Standby) then cycle.dead = false cycle.standby = true else cycle.dead = false cycle.standby = false end end end local function start (self) self.handle = self.timeSlice:create (update_time_slice, self, self.name) local callbacks = { create_object = create_object, destroy_object = destroy_object, update_object_state = update_object_state, } self.objObs:register (nil, callbacks, self) self.mcp = dmz.object.create (const.MCPType) dmz.object.state (self.mcp, nil, const.GameWaiting) dmz.object.activate (self.mcp) dmz.object.set_temporary (self.mcp) create_start_points (self) end local function stop (self) if self.handle and self.timeSlice then self.timeSlice:destroy (self.handle) end end function new (config, name) local self = { start_plugin = start, stop_plugin = stop, log = dmz.log.new ("lua." .. name), timeSlice = dmz.time_slice.new (), objObs = dmz.object_observer.new (), config = config, name = name, cycleList = {}, cycleCount = 0, startPoints = {}, maxCycles = config:to_number ("cycles.max", 6), minCycles = config:to_number ("cycles.min", 2), } self.log:info ("Creating plugin: " .. name) return self end
require "const" local function create_start_points (self) local Distance = 10 local Space = 5 local Offset = math.modf (self.maxCycles / 4) + 1 local Ident = dmz.matrix.new () local HeadingPi = dmz.matrix.new (const.Up, dmz.math.Pi) local oddPos = { -(Space * Offset), 0, Distance } local evenPos = { -(Space * Offset) + (Space / 2), 0, -Distance } for ix = 1, self.maxCycles do local Odd = (1 == math.fmod (ix, 2)) local point = { index = ix, pos = (Odd and oddPos or evenPos), ori = (Odd and Ident or HeadingPi), handle = dmz.object.create (const.StartPointType), } self.startPoints[ix] = point dmz.object.position (point.handle, nil, point.pos) dmz.object.orientation (point.handle, nil, point.ori) dmz.object.activate (point.handle) dmz.object.set_temporary (point.handle) if Odd then oddPos[1] = oddPos[1] + Space else evenPos[1] = evenPos[1] + Space end end end local function assign_points_to_cycles (self) self.playerCount = 0 for object, cycle in pairs (self.cycleList) do if cycle.point then dmz.object.unlink_sub_links (cycle.point.handle, const.StartLinkHandle) cycle.point = nil elseif cycle.wait then end end local count = 1 for object, cycle in pairs (self.cycleList) do if count <= self.maxCycles then cycle.point = self.startPoints[count] dmz.object.link (const.StartLinkHandle, cycle.point.handle, object) self.playerCount = self.playerCount + 1 else end count = count + 1 end end local function get_standby_count (self) local result = 0 for object, cycle in pairs (self.cycleList) do if cycle.point and cycle.standby then result = result + 1 end end return result end local function get_dead_count (self) local result = 0 for object, cycle in pairs (self.cycleList) do if cycle.point and cycle.dead then result = result + 1 end end return result end local function set_game_state (mcp, State) local newState = dmz.object.state (mcp) newState:unset (const.GameStateMask) newState = newState + State dmz.object.state (mcp, nil, newState) end local function update_time_slice (self, time) local State = dmz.object.state (self.mcp) if State then local CTime = dmz.time.frame_time () if State:contains (const.GameWaiting) then if self.assignPoints then assign_points_to_cycles (self) self.assignPoints = false end if (get_standby_count (self) == self.playerCount) and (self.playerCount >= self.minCycles) then self.log:error ("Move to Countdown 5") set_game_state (self.mcp, const.GameCountdown5) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameActive) then if self.endTime and self.endTime <= CTime then set_game_state (self.mcp, const.GameWaiting) self.endTime = nil elseif not self.endTime and get_dead_count (self) >= (self.playerCount - 1) then self.endTime = CTime + 2 end elseif State:contains (const.GameCountdown5) then if CTime >= self.nextStateTime then self.log:error ("Move to Countdown 4") set_game_state (self.mcp, const.GameCountdown4) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameCountdown4) then if CTime >= self.nextStateTime then self.log:error ("Move to Countdown 3") set_game_state (self.mcp, const.GameCountdown3) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameCountdown3) then if CTime >= self.nextStateTime then self.log:error ("Move to Countdown 2") set_game_state (self.mcp, const.GameCountdown2) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameCountdown2) then if CTime >= self.nextStateTime then self.log:error ("Move to Countdown 1") set_game_state (self.mcp, const.GameCountdown1) self.nextStateTime = CTime + 1 end elseif State:contains (const.GameCountdown1) then if CTime >= self.nextStateTime then self.log:error ("Move to Active") set_game_state (self.mcp, const.GameActive) self.nextStateTime = CTime + 1 end else self.log.error ("Game in unknown state. Changing to a waiting state") set_game_state (self.mcp, const.GameWaiting) end end end local function create_object (self, Object, Type) if Type:is_of_type (const.CycleType) then self.cycleList[Object] = {} self.cycleCount = self.cycleCount + 1 self.assignPoints = true end end local function destroy_object (self, Object) local cycle = self.cycleList[Object] if cycle then self.cycleList[Object] = nil self.cycleCount = self.cycleCount - 1 if cycle.point then self.playerCount = self.playerCount - 1 end self.assignPoints = true end end local function update_object_state (self, Object, Attribute, State, PreviousState) local cycle = self.cycleList[Object] if cycle then if not PreviousState then PreviousState = const.EmptyState end if State:contains (const.Dead) and not PreviousState:contains (const.Dead) then cycle.dead = true cycle.standby = false elseif State:contains (const.Standby) and not PreviousState:contains (const.Standby) then cycle.dead = false cycle.standby = true else cycle.dead = false cycle.standby = false end end end local function start (self) self.handle = self.timeSlice:create (update_time_slice, self, self.name) local callbacks = { create_object = create_object, destroy_object = destroy_object, update_object_state = update_object_state, } self.objObs:register (nil, callbacks, self) self.mcp = dmz.object.create (const.MCPType) dmz.object.state (self.mcp, nil, const.GameWaiting) dmz.object.activate (self.mcp) dmz.object.set_temporary (self.mcp) create_start_points (self) end local function stop (self) if self.handle and self.timeSlice then self.timeSlice:destroy (self.handle) end end function new (config, name) local self = { start_plugin = start, stop_plugin = stop, log = dmz.log.new ("lua." .. name), timeSlice = dmz.time_slice.new (), objObs = dmz.object_observer.new (), config = config, name = name, cycleList = {}, cycleCount = 0, startPoints = {}, maxCycles = config:to_number ("cycles.max", 6), minCycles = config:to_number ("cycles.min", 2), } self.log:info ("Creating plugin: " .. name) return self end
bugfix: game was resetting when new player came up and was not waiting for the current game to end.
bugfix: game was resetting when new player came up and was not waiting for the current game to end.
Lua
mit
shillcock/cycles,shillcock/cycles,dmzgroup/cycles,shillcock/cycles,dmzgroup/cycles,shillcock/cycles,dmzgroup/cycles,dmzgroup/cycles
de39642e9ca7a7c1a325a0f10b76c84d210b6362
build/tiny2.lua
build/tiny2.lua
-- some stubs for tiny-instead -- fake game.gui -- stat, menu -- fake audio -- fake input -- show hints (numbers) game.hinting = true -- fake gui game.gui = { fading = 4; ways_delim = ' | '; inv_delim = ' | '; hinv_delim = ' | '; hideways = false; hideinv = false; hidetitle = false; } -- menu and stat stat = function(v) v.status_type = true v.id = false return obj(v) end function isStatus(v) if stead.type(v) ~= 'table' then return false end if v.status_type then return true end return false end function isMenu(v) if stead.type(v) ~= 'table' then return false end if v.menu_type then return true end return false end stead.menu_save = function(self, name, h, need) local dsc; if need then print ("Warning: menu "..name.." can not be saved!"); return end stead.savemembers(h, self, name, need); end function menu(v) v.menu_type = true if v.inv == nil then v.inv = function(s) local r,v r, v = stead.call(s, 'menu'); if v == nil then v = true end if r == nil then stead.obj_tag(stead.me(), MENU_TAG_ID); -- retag menu field end return r, v end end if v.act == nil then v.act = function(s) local r,v r,v = stead.call(s, 'menu'); if v == nil then v = true end if r == nil then stead.obj_tag(stead.me(), MENU_TAG_ID); -- retag menu field end return r, v end end if v.save == nil then v.save = stead.menu_save; end return obj(v); end -- Audio stead.get_music = function() return game._music, game._music_loop; end stead.get_music_loop = function() return game._music_loop; end stead.save_music = function(s) if s == nil then s = self end s.__old_music__ = stead.get_music(); s.__old_loop__ = stead.get_music_loop(); end stead.restore_music = function(s) if s == nil then s = self end stead.set_music(s.__old_music__, s.__old_loop__); end stead.set_music = function(s, count) game._music = s; if not stead.tonum(count) then game._music_loop = 0; else game._music_loop = stead.tonum(count); end end stead.set_music_fading = function(o, i) end stead.get_music_fading = function() end stead.stop_music = function() stead.set_music(nil, -1); end stead.is_music = function() return game._music ~= nil and game._music_loop ~= -1 end function instead_sound() return true end --пока нет звуков stead.is_sound = function() return false end is_sound = function() return false end stead.get_sound = function() return game._sound, game._sound_channel, game._sound_loop; end stead.get_sound_chan = function() return game._sound_channel end stead.get_sound_loop = function() return game._sound_loop end stead.stop_sound = function(chan, fo) if not stead.tonum(chan) then if stead.tonum(fo) then stead.set_sound('@-1,'..stead.tostr(fo)); else stead.set_sound('@-1'); end return end if stead.tonum(fo) then stead.add_sound('@'..stead.tostr(chan)..','..stead.tostr(fo)); else stead.add_sound('@'..stead.tostr(chan)); end end stead.add_sound = function(s, chan, loop) if stead.type(s) ~= 'string' then return end if stead.type(game._sound) == 'string' then if stead.tonum(chan) then s = s..'@'..stead.tostr(chan); end if stead.tonum(loop) then s = s..','..stead.tostr(loop) end stead.set_sound(game._sound..';'..s, stead.get_sound_chan(), stead.get_sound_loop()); else stead.set_sound(s, chan, loop); end end stead.set_sound = function(s, chan, loop) game._sound = s; if not stead.tonum(loop) then game._sound_loop = 1; else game._sound_loop = stead.tonum(loop); end if not stead.tonum(chan) then game._sound_channel = -1; else game._sound_channel = stead.tonum(chan); end end -- those are sill in global space add_sound = stead.add_sound set_sound = stead.set_sound stop_sound = stead.stop_sound get_sound = stead.get_sound get_sound_loop = stead.get_sound_loop get_sound_chan = stead.get_sound_chan get_music = stead.get_music get_music_fading = stead.get_music_fading get_music_loop = stead.get_music_loop set_music = stead.set_music set_music_fading = stead.set_music_fading stop_music = stead.stop_music save_music = stead.save_music restore_music = stead.restore_music is_music = stead.is_music --Для космический рейнджеров unpack = stead.unpack; stead.set_timer = function() end stead.timer = function() return end instead_theme_name = function() return 'default' end stead.module_init(function(s) timer = obj { nam = 'timer', get = function(s) return 0 end, stop = function(s) end, del = function(s) end, set = function(s, v) return true end, }; end) stead.objects.input = function() return obj { -- input object system_type = true, nam = 'input', }; end; --Место сохранений function instead_savepath() return "../../" --Разрешаем сохранять на 2 уровня выше end --Мой iface iface.xref = function(self, str, obj, ...) local o = stead.ref(stead.here():srch(obj)); if not o then o = stead.ref(ways():srch(obj)); end if not o then o = stead.ref(stead.me():srch(obj)); end o = stead.ref(obj); local a = '' local varg = {...} for i = 1, stead.table.maxn(varg) do a = a..','..varg[i] end if isXaction(o) and not o.id then return stead.cat('[a:'..stead.deref(obj)..a..']',str,'[/a]'); end if not o or not o.id then if isStatus(o) then str = string.gsub(str, "%^", " "); return ("[a]"..(str or '').."#0[/a]"); end return str; end local n = stead.tonum(stead.nameof(o)) -- Новое отображение ссылок, для меню сдвиг на 1000 if (isMenu(o)) then return ("[a]"..(str or '').."#"..stead.tostr((n or o.id)+1000).."[/a]"); end return ("[a]"..(str or '').."#"..stead.tostr(n or o.id).."[/a]"); end; --Форматирование текста stead.fmt = function(...) local res local a = {...} for i = 1, stead.table.maxn(a) do if stead.type(a[i]) == 'string' then local s = stead.string.gsub(a[i],'\t', stead.space_delim):gsub('[\n]+', stead.space_delim); s = stead.string.gsub(s, '\\?[\\^]', { ['^'] = '\n', ['\\^'] = '^', ['\\\\'] = '\\' }); res = stead.par('', res, s); --Убирание информации из тегов res = stead.string.gsub(res,"<u.->(.-)</u>","%1"); res = stead.string.gsub(res,"<b.->(.-)</b>","%1"); res = stead.string.gsub(res,"<l.->(.-)</l>","%1"); res = stead.string.gsub(res,"<i.->(.-)</i>","%1"); res = stead.string.gsub(res,"<w:(.-)>","%1"); res = stead.string.gsub(res,"<c.->(.-)</c>","%1"); end end return res end
-- some stubs for tiny-instead -- fake game.gui -- stat, menu -- fake audio -- fake input -- show hints (numbers) game.hinting = true -- fake gui game.gui = { fading = 4; ways_delim = ' | '; inv_delim = ' | '; hinv_delim = ' | '; hideways = false; hideinv = false; hidetitle = false; } -- menu and stat stat = function(v) v.status_type = true v.id = false return obj(v) end function isStatus(v) if stead.type(v) ~= 'table' then return false end if v.status_type then return true end return false end function isMenu(v) if stead.type(v) ~= 'table' then return false end if v.menu_type then return true end return false end stead.menu_save = function(self, name, h, need) local dsc; if need then print ("Warning: menu "..name.." can not be saved!"); return end stead.savemembers(h, self, name, need); end function menu(v) v.menu_type = true if v.inv == nil then v.inv = function(s) local r,v r, v = stead.call(s, 'menu'); if v == nil then v = true end if r == nil then stead.obj_tag(stead.me(), MENU_TAG_ID); -- retag menu field end return r, v end end if v.act == nil then v.act = function(s) local r,v r,v = stead.call(s, 'menu'); if v == nil then v = true end if r == nil then stead.obj_tag(stead.me(), MENU_TAG_ID); -- retag menu field end return r, v end end if v.save == nil then v.save = stead.menu_save; end return obj(v); end -- Audio stead.get_music = function() return game._music, game._music_loop; end stead.get_music_loop = function() return game._music_loop; end stead.save_music = function(s) if s == nil then s = self end s.__old_music__ = stead.get_music(); s.__old_loop__ = stead.get_music_loop(); end stead.restore_music = function(s) if s == nil then s = self end stead.set_music(s.__old_music__, s.__old_loop__); end stead.set_music = function(s, count) game._music = s; if not stead.tonum(count) then game._music_loop = 0; else game._music_loop = stead.tonum(count); end end stead.set_music_fading = function(o, i) end stead.get_music_fading = function() end stead.stop_music = function() stead.set_music(nil, -1); end stead.is_music = function() return game._music ~= nil and game._music_loop ~= -1 end function instead_sound() return true end --пока нет звуков stead.is_sound = function() return false end is_sound = function() return false end stead.get_sound = function() return game._sound, game._sound_channel, game._sound_loop; end stead.get_sound_chan = function() return game._sound_channel end stead.get_sound_loop = function() return game._sound_loop end stead.stop_sound = function(chan, fo) if not stead.tonum(chan) then if stead.tonum(fo) then stead.set_sound('@-1,'..stead.tostr(fo)); else stead.set_sound('@-1'); end return end if stead.tonum(fo) then stead.add_sound('@'..stead.tostr(chan)..','..stead.tostr(fo)); else stead.add_sound('@'..stead.tostr(chan)); end end stead.add_sound = function(s, chan, loop) if stead.type(s) ~= 'string' then return end if stead.type(game._sound) == 'string' then if stead.tonum(chan) then s = s..'@'..stead.tostr(chan); end if stead.tonum(loop) then s = s..','..stead.tostr(loop) end stead.set_sound(game._sound..';'..s, stead.get_sound_chan(), stead.get_sound_loop()); else stead.set_sound(s, chan, loop); end end stead.set_sound = function(s, chan, loop) game._sound = s; if not stead.tonum(loop) then game._sound_loop = 1; else game._sound_loop = stead.tonum(loop); end if not stead.tonum(chan) then game._sound_channel = -1; else game._sound_channel = stead.tonum(chan); end end -- those are sill in global space add_sound = stead.add_sound set_sound = stead.set_sound stop_sound = stead.stop_sound get_sound = stead.get_sound get_sound_loop = stead.get_sound_loop get_sound_chan = stead.get_sound_chan get_music = stead.get_music get_music_fading = stead.get_music_fading get_music_loop = stead.get_music_loop set_music = stead.set_music set_music_fading = stead.set_music_fading stop_music = stead.stop_music save_music = stead.save_music restore_music = stead.restore_music is_music = stead.is_music --Для космический рейнджеров unpack = stead.unpack; stead.set_timer = function() end stead.timer = function() return end instead_theme_name = function() return 'default' end stead.module_init(function(s) timer = obj { nam = 'timer', get = function(s) return 0 end, stop = function(s) end, del = function(s) end, set = function(s, v) return true end, }; end) stead.objects.input = function() return obj { -- input object system_type = true, nam = 'input', }; end; --Место сохранений function instead_savepath() return "../../" --Разрешаем сохранять на 2 уровня выше end stead.list_search = function(self, n, dis) local i if stead.tonum(n) then i = self:byid(stead.tonum(n), dis); end if not i then i = self:look(n) if not i then i = self:name(n, dis); end if not i then return nil end end if not dis and isDisabled(stead.ref(self[i])) then return nil end return self[i], i end --Мой iface iface.xref = function(self, str, obj, ...) local o = stead.ref(stead.here():srch(obj)) if not o then o = stead.ref(ways():srch(obj)); end if not o then o = stead.ref(stead.me():srch(obj)) end o = stead.ref(obj); local a = '' local varg = {...} for i = 1, stead.table.maxn(varg) do a = a..','..varg[i] end if not isObject(o) or isStatus(o) or (not o.id and not isXaction(o)) then if isStatus(o) then str = string.gsub(str, "%^", " ") return ("[a]"..(str or '').."#0[/a]") end return str end local n = o.id if isMenu(o) then n = n + 1000 -- ??? end if isXaction(o) and not o.id then return stead.cat('[a:'..stead.deref(obj)..a..']',str,'[/a]') end if a == '' then -- why two ways?? return stead.cat('[a]', (str or ''), '#', stead.tostr(n), '[/a]'); end -- this should be same as above: TODO -- objects can have parameters -- for example, 12,bottle is n + a -- so, use 1 + 12,bottle -> use 1,12,bottle return stead.cat('[a:', stead.tostr(n), a, ']',str,'[/a]'); end --Форматирование текста stead.fmt = function(...) local res local a = {...} for i = 1, stead.table.maxn(a) do if stead.type(a[i]) == 'string' then local s = stead.string.gsub(a[i],'\t', stead.space_delim):gsub('[\n]+', stead.space_delim); s = stead.string.gsub(s, '\\?[\\^]', { ['^'] = '\n', ['\\^'] = '^', ['\\\\'] = '\\' }); res = stead.par('', res, s); --Убирание информации из тегов res = stead.string.gsub(res,"<u.->(.-)</u>","%1"); res = stead.string.gsub(res,"<b.->(.-)</b>","%1"); res = stead.string.gsub(res,"<l.->(.-)</l>","%1"); res = stead.string.gsub(res,"<i.->(.-)</i>","%1"); res = stead.string.gsub(res,"<w:(.-)>","%1"); res = stead.string.gsub(res,"<c.->(.-)</c>","%1"); end end return res end
tiny2 fixes
tiny2 fixes
Lua
mit
instead-hub/plainstead,instead-hub/plainstead
400a50152f7999c66bcca981da45f5fc5ed9c7b7
MMOCoreORB/bin/scripts/object/draft_schematic/droid/component/personality_module_slang.lua
MMOCoreORB/bin/scripts/object/draft_schematic/droid/component/personality_module_slang.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_draft_schematic_droid_component_personality_module_slang = object_draft_schematic_droid_component_shared_personality_module_slang:new { templateType = DRAFTSCHEMATIC, customObjectName = "Slang Droid Personality Chip", craftingToolTab = 32, -- (See DraftSchemticImplementation.h) complexity = 22, size = 2, xpType = "crafting_droid_general", xp = 40, assemblySkill = "droid_assembly", experimentingSkill = "droid_experimentation", customizationSkill = "droid_customization", customizationOptions = {}, customizationStringNames = {}, customizationDefaults = {}, ingredientTemplateNames = {"craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n"}, ingredientTitleNames = {"module_frame", "thermal_shielding", "data_smart_indexer", "ancillary_heuristic_processor", "primary_phrase_database", "secondary_phrase_database"}, ingredientSlotType = {0, 0, 1, 1, 1, 1}, resourceTypes = {"copper", "ore_siliclastic", "object/tangible/component/item/shared_electronics_gp_module.iff", "object/tangible/furniture/decorative/shared_corellian_flagpole.iff", "object/tangible/component/item/shared_electronics_memory_module.iff", "object/tangible/component/item/shared_electronics_memory_module.iff"}, resourceQuantities = {13, 6, 1, 1, 1, 1}, contribution = {100, 100, 100, 100, 100, 100}, targetTemplate = "object/tangible/component/droid/personality_module_slang.iff", additionalTemplates = { } } ObjectTemplates:addTemplate(object_draft_schematic_droid_component_personality_module_slang, "object/draft_schematic/droid/component/personality_module_slang.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_draft_schematic_droid_component_personality_module_slang = object_draft_schematic_droid_component_shared_personality_module_slang:new { templateType = DRAFTSCHEMATIC, customObjectName = "Slang Droid Personality Chip", craftingToolTab = 32, -- (See DraftSchemticImplementation.h) complexity = 22, size = 2, xpType = "crafting_droid_general", xp = 40, assemblySkill = "droid_assembly", experimentingSkill = "droid_experimentation", customizationSkill = "droid_customization", customizationOptions = {}, customizationStringNames = {}, customizationDefaults = {}, ingredientTemplateNames = {"craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n"}, ingredientTitleNames = {"module_frame", "thermal_shielding", "data_smart_indexer", "ancillary_heuristic_processor", "primary_phrase_database", "secondary_phrase_database"}, ingredientSlotType = {0, 0, 1, 1, 1, 1}, resourceTypes = {"copper", "ore_siliclastic", "object/tangible/component/item/shared_electronics_gp_module.iff", "object/tangible/component/item/shared_electronics_gp_module.iff", "object/tangible/component/item/shared_electronics_memory_module.iff", "object/tangible/component/item/shared_electronics_memory_module.iff"}, resourceQuantities = {13, 6, 1, 1, 1, 1}, contribution = {100, 100, 100, 100, 100, 100}, targetTemplate = "object/tangible/component/droid/personality_module_slang.iff", additionalTemplates = { } } ObjectTemplates:addTemplate(object_draft_schematic_droid_component_personality_module_slang, "object/draft_schematic/droid/component/personality_module_slang.iff")
[Fixed] Droid Slang Chip resource. Mantis #4648
[Fixed] Droid Slang Chip resource. Mantis #4648 Change-Id: I73189fcfec6f02506c900fbc348787f6abe56cf4
Lua
agpl-3.0
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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
d30637f81d523ceb034bacb8257991cc7f07cb7f
base/gatheringcraft.lua
base/gatheringcraft.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] require("base.common") require("base.treasure") module("base.gatheringcraft", package.seeall) RandomItem = { ID = 0, Quantity = 1, Quality = 333, Data = {}, Probability = 0, MessageDE = nil, MessageEN = nil, }; GatheringCraft = { RandomItems = { }, InterruptMsg = { }, Monsters = { }, LeadSkill = 0, SavedWorkTime = { }, Treasure = 0, TreasureMsg = { }, FoodLevel = 100, FastActionFactor = 1, LearnLimit = 20 }; Monster = { MonsterID = 0, Probability = 100, MessageDE = "", MessageEN = "", Sound = nil, GFX = nil }; function GatheringCraft:new(gc) gc = gc or {}; setmetatable(gc, self); self.__index = self; gc.RandomItems = {}; gc.InterruptMsg = {}; gc.Monsters = {}; gc.TreasureMsg = {}; return gc; end function RandomItem:new(item) item = item or {}; setmetatable(item, self); self.__index = self; return item; end function Monster:new(m) m = m or {}; setmetatable(m, self); self.__index = self; return m; end function GatheringCraft:SetFoodLevel(FoodLevel) self.FoodLevel = FoodLevel; end function GatheringCraft:SetTreasureMap(Probability, MessageDE, MessageEN) self.Treasure = Probability; self.TreasureMsg[1] = MessageDE; self.TreasureMsg[2] = MessageEN; end function GatheringCraft:AddInterruptMessage(MessageDE, MessageEN) table.insert(self.InterruptMsg, { MessageDE, MessageEN }); return; end function GatheringCraft:AddMonster(MonsterID, Probability, MessageDE, MessageEN, Sound, GFX) table.insert(self.Monsters, Monster:new{["MonsterID"] = MonsterID, ["Probability"] = Probability, ["MessageDE"] = MessageDE, ["MessageEN"] = MessageEN, ["Sound"] = Sound, ["GFX"] = GFX}); return; end function GatheringCraft:AddRandomItem(ItemID, Quantity, Quality, Data, Probability, MessageDE, MessageEN) table.insert(self.RandomItems, RandomItem:new{["ID"] = ItemID, ["Quantity"] = Quantity, ["Quality"] = Quality, ["Data"] = Data, ["Probability"] = Probability, ["MessageDE"] = MessageDE, ["MessageEN"] = MessageEN}); return; end -- @return If something was done function GatheringCraft:FindRandomItem(User) --[[Deactivate the call of interrupting messages. if math.random(1,100) == 50 then --why complicated if you can solve it simple... 1% chance for an interruption if(#self.InterruptMsg > 0) then local m = math.random(#self.InterruptMsg); base.common.InformNLS(User, self.InterruptMsg[m][1], self.InterruptMsg[m][2]); return true; end end --]] base.common.GetHungry(User, self.FoodLevel); -- FindRandomItem is called when the User is currently working. If there was -- a reload, the working time will be nil. Check for this case. if (self.SavedWorkTime[User.id] == nil) then -- Just generate the work time again. Does not matter really if this is not -- exactly the original value. self.SavedWorkTime[User.id] = self:GenWorkTime(User,nil); end -- check for Noobia if (base.common.IsOnNoobia(User.pos)) then return false; end if (self.Treasure > 0) then local rand = math.random(); if(rand < self.Treasure*self.FastActionFactor) and base.treasure.createMap(User) then base.common.InformNLS(User, self.TreasureMsg[1], self.TreasureMsg[2]); return true; end end if (#self.Monsters > 0) then local ra = math.random(#self.Monsters); local pa = math.random(); if (pa < self.Monsters[ra].Probability*self.FastActionFactor) then local TargetPos = getSpawnPosition(User) world:createMonster(self.Monsters[ra].MonsterID, TargetPos, 20); if ( self.Monsters[ra].GFX ~= nil ) then world:gfx(self.Monsters[ra].GFX, TargetPos); end if(self.Monsters[ra].Sound ~= nil) then world:makeSound(self.Monsters[ra].Sound, TargetPos); end base.common.InformNLS(User, self.Monsters[ra].MessageDE, self.Monsters[ra].MessageEN); return true; end end if(#self.RandomItems > 0) then -- check all items with same random number and choose any possible item again randomly local itemIndexList = {}; -- list all items that are possible for it = 1, #self.RandomItems, 1 do local rand = math.random(); if (rand <= self.RandomItems[it].Probability*self.FastActionFactor) then table.insert(itemIndexList, it); end end if ( #itemIndexList > 0 ) then -- For the unlikely case that two items were found at once, we just give one to the player local ind = itemIndexList[math.random(1,#itemIndexList)]; base.common.InformNLS(User, self.RandomItems[ind].MessageDE, self.RandomItems[ind].MessageEN); local notCreated = User:createItem(self.RandomItems[ind].ID, self.RandomItems[ind].Quantity, self.RandomItems[ind].Quality, self.RandomItems[ind].Data); if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId( self.RandomItems[ind].ID, notCreated, User.pos, true, self.RandomItems[ind].Quality, self.RandomItems[ind].Data ); base.common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more."); end return true; end end return false; end function getSpawnPosition(User) local TargetPos = base.common.GetFrontPosition(User); local theField = world:getField(TargetPos) if theField:isPassable() == false or world:isCharacterOnField(TargetPos) == true then for i=-1,1 do for j=-1,1 do local checkPosition = position(TargetPos.x+i,TargetPos.y+j,TargetPos.z) local theField = world:getField(checkPosition) if theField:isPassable() == true or world:isCharacterOnField(TargetPos) == false then return checkPosition end end end end return TargetPos end -- Generate working time for gathering actions function GatheringCraft:GenWorkTime(User, toolItem) local minTime = 12; --Minimum time for skill 100 and normal tool local maxTime = 60; --Maximum time for skill 0 and normal tool local skill = base.common.Limit(User:getSkill(self.LeadSkill), 0, 100); local workTime = base.common.Scale(maxTime, minTime, skill); --scaling with the skill -- apply the quality bonus if ( toolItem ~= nil ) then local qual = base.common.Limit(math.floor(toolItem.quality/100), 1, 9); -- quality integer in [1,9] workTime = workTime - workTime*0.20*((qual-5)/4); --+/-20% depending on tool quality end workTime = workTime*self.FastActionFactor; --for fast actions. return math.ceil(workTime); end
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] require("base.common") require("base.treasure") module("base.gatheringcraft", package.seeall) RandomItem = { ID = 0, Quantity = 1, Quality = 333, Data = {}, Probability = 0, MessageDE = nil, MessageEN = nil, }; GatheringCraft = { RandomItems = { }, InterruptMsg = { }, Monsters = { }, LeadSkill = 0, SavedWorkTime = { }, Treasure = 0, TreasureMsg = { }, FoodLevel = 100, FastActionFactor = 1, LearnLimit = 20 }; Monster = { MonsterID = 0, Probability = 100, MessageDE = "", MessageEN = "", Sound = nil, GFX = nil }; function GatheringCraft:new(gc) gc = gc or {}; setmetatable(gc, self); self.__index = self; gc.RandomItems = {}; gc.InterruptMsg = {}; gc.Monsters = {}; gc.TreasureMsg = {}; return gc; end function RandomItem:new(item) item = item or {}; setmetatable(item, self); self.__index = self; return item; end function Monster:new(m) m = m or {}; setmetatable(m, self); self.__index = self; return m; end function GatheringCraft:SetFoodLevel(FoodLevel) self.FoodLevel = FoodLevel; end function GatheringCraft:SetTreasureMap(Probability, MessageDE, MessageEN) self.Treasure = Probability; self.TreasureMsg[1] = MessageDE; self.TreasureMsg[2] = MessageEN; end function GatheringCraft:AddInterruptMessage(MessageDE, MessageEN) table.insert(self.InterruptMsg, { MessageDE, MessageEN }); return; end function GatheringCraft:AddMonster(MonsterID, Probability, MessageDE, MessageEN, Sound, GFX) table.insert(self.Monsters, Monster:new{["MonsterID"] = MonsterID, ["Probability"] = Probability, ["MessageDE"] = MessageDE, ["MessageEN"] = MessageEN, ["Sound"] = Sound, ["GFX"] = GFX}); return; end function GatheringCraft:AddRandomItem(ItemID, Quantity, Quality, Data, Probability, MessageDE, MessageEN) table.insert(self.RandomItems, RandomItem:new{["ID"] = ItemID, ["Quantity"] = Quantity, ["Quality"] = Quality, ["Data"] = Data, ["Probability"] = Probability, ["MessageDE"] = MessageDE, ["MessageEN"] = MessageEN}); return; end -- @return If something was done function GatheringCraft:FindRandomItem(User) --[[Deactivate the call of interrupting messages. if math.random(1,100) == 50 then --why complicated if you can solve it simple... 1% chance for an interruption if(#self.InterruptMsg > 0) then local m = math.random(#self.InterruptMsg); base.common.InformNLS(User, self.InterruptMsg[m][1], self.InterruptMsg[m][2]); return true; end end --]] base.common.GetHungry(User, self.FoodLevel); -- FindRandomItem is called when the User is currently working. If there was -- a reload, the working time will be nil. Check for this case. if (self.SavedWorkTime[User.id] == nil) then -- Just generate the work time again. Does not matter really if this is not -- exactly the original value. self.SavedWorkTime[User.id] = self:GenWorkTime(User,nil); end -- check for Noobia if (base.common.IsOnNoobia(User.pos)) then return false; end if (self.Treasure > 0) then local rand = math.random(); if(rand < self.Treasure*self.FastActionFactor) and base.treasure.createMap(User) then base.common.InformNLS(User, self.TreasureMsg[1], self.TreasureMsg[2]); return true; end end if (#self.Monsters > 0) then local ra = math.random(#self.Monsters); local pa = math.random(); if (pa < self.Monsters[ra].Probability*self.FastActionFactor) then local TargetPos = base.common.getFreePos(User.pos, 1) world:createMonster(self.Monsters[ra].MonsterID, TargetPos, 20); if ( self.Monsters[ra].GFX ~= nil ) then world:gfx(self.Monsters[ra].GFX, TargetPos); end if(self.Monsters[ra].Sound ~= nil) then world:makeSound(self.Monsters[ra].Sound, TargetPos); end base.common.InformNLS(User, self.Monsters[ra].MessageDE, self.Monsters[ra].MessageEN); return true; end end if(#self.RandomItems > 0) then -- check all items with same random number and choose any possible item again randomly local itemIndexList = {}; -- list all items that are possible for it = 1, #self.RandomItems, 1 do local rand = math.random(); if (rand <= self.RandomItems[it].Probability*self.FastActionFactor) then table.insert(itemIndexList, it); end end if ( #itemIndexList > 0 ) then -- For the unlikely case that two items were found at once, we just give one to the player local ind = itemIndexList[math.random(1,#itemIndexList)]; base.common.InformNLS(User, self.RandomItems[ind].MessageDE, self.RandomItems[ind].MessageEN); local notCreated = User:createItem(self.RandomItems[ind].ID, self.RandomItems[ind].Quantity, self.RandomItems[ind].Quality, self.RandomItems[ind].Data); if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId( self.RandomItems[ind].ID, notCreated, User.pos, true, self.RandomItems[ind].Quality, self.RandomItems[ind].Data ); base.common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more."); end return true; end end return false; end -- Generate working time for gathering actions function GatheringCraft:GenWorkTime(User, toolItem) local minTime = 12; --Minimum time for skill 100 and normal tool local maxTime = 60; --Maximum time for skill 0 and normal tool local skill = base.common.Limit(User:getSkill(self.LeadSkill), 0, 100); local workTime = base.common.Scale(maxTime, minTime, skill); --scaling with the skill -- apply the quality bonus if ( toolItem ~= nil ) then local qual = base.common.Limit(math.floor(toolItem.quality/100), 1, 9); -- quality integer in [1,9] workTime = workTime - workTime*0.20*((qual-5)/4); --+/-20% depending on tool quality end workTime = workTime*self.FastActionFactor; --for fast actions. return math.ceil(workTime); end
use a common function to find a free tile to spawn monster.
use a common function to find a free tile to spawn monster. fix #10370
Lua
agpl-3.0
KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
0a1d59ebf62c10cf7cbe2f8b3c921a7baedb7461
spec/expand_rockspec_spec.lua
spec/expand_rockspec_spec.lua
local expand_rockspec = require "luacheck.expand_rockspec" describe("expand_rockspec", function() it("returns sorted array of lua files related to a rock", function() assert.same({ "bar.lua", "baz.lua", "bin.lua", "foo.lua" }, expand_rockspec("spec/folder/rockspec")) end) it("autodetects modules for rockspecs without build table", function() assert.same({ "spec/rock/src/rock.lua", "spec/rock/src/rock/mod.lua", "spec/rock/bin/rock.lua" }, expand_rockspec("spec/rock/rock-dev-1.rockspec")) end) it("autodetects modules for rockspecs without build.modules table", function() assert.same({ "spec/rock2/mod.lua" }, expand_rockspec("spec/rock2/rock2-dev-1.rockspec")) end) it("returns nil, \"I/O\" for non-existent paths", function() local ok, err = expand_rockspec("spec/folder/non-existent") assert.is_nil(ok) assert.equal("I/O", err) end) it("returns nil, \"syntax\" for rockspecs with syntax errors", function() local ok, err = expand_rockspec("spec/folder/bad_config") assert.is_nil(ok) assert.equal("syntax", err) end) it("returns nil, \"runtime\" for rockspecs with run-time errors", function() local ok, err = expand_rockspec("spec/folder/bad_rockspec") assert.is_nil(ok) assert.equal("runtime", err) end) end)
local expand_rockspec = require "luacheck.expand_rockspec" local fs = require "luacheck.fs" local P = fs.normalize describe("expand_rockspec", function() it("returns sorted array of lua files related to a rock", function() assert.same({ "bar.lua", "baz.lua", "bin.lua", "foo.lua" }, expand_rockspec("spec/folder/rockspec")) end) it("autodetects modules for rockspecs without build table", function() assert.same({ P"spec/rock/src/rock.lua", P"spec/rock/src/rock/mod.lua", P"spec/rock/bin/rock.lua" }, expand_rockspec("spec/rock/rock-dev-1.rockspec")) end) it("autodetects modules for rockspecs without build.modules table", function() assert.same({ P"spec/rock2/mod.lua" }, expand_rockspec("spec/rock2/rock2-dev-1.rockspec")) end) it("returns nil, \"I/O\" for non-existent paths", function() local ok, err = expand_rockspec("spec/folder/non-existent") assert.is_nil(ok) assert.equal("I/O", err) end) it("returns nil, \"syntax\" for rockspecs with syntax errors", function() local ok, err = expand_rockspec("spec/folder/bad_config") assert.is_nil(ok) assert.equal("syntax", err) end) it("returns nil, \"runtime\" for rockspecs with run-time errors", function() local ok, err = expand_rockspec("spec/folder/bad_rockspec") assert.is_nil(ok) assert.equal("runtime", err) end) end)
Fix expand_rockspec spec for Windows
Fix expand_rockspec spec for Windows
Lua
mit
mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,xpol/luacheck,xpol/luacheck